@aurodesignsystem-dev/auro-cli 0.0.0-pr319.4 → 0.0.0-pr319.6
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/auro-cli.js +58 -58
- package/dist/auro-cli.js.map +4 -4
- package/package.json +1 -1
package/dist/auro-cli.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../src/utils/auroSplash.js", "../src/utils/packageVersion.js", "../src/commands/dev.js", "../src/commands/_sharedOptions.js", "../src/scripts/build/index.js", "../src/scripts/build/bundleHandlers.js", "../src/scripts/docs/index.ts", "../src/utils/shell.js", "../src/scripts/docs/docs-generator.ts", "../src/utils/pathUtils.js", "../src/utils/copyReadmeToDemo.js", "../src/utils/shutdown.js", "../src/scripts/build/defaultDocsBuild.js", "../src/scripts/build/devServerUtils.js", "../src/scripts/build/paths.js", "../src/scripts/analyze.js", "../src/scripts/build/configUtils.js", "../src/scripts/build/plugins.js", "../src/scripts/build/watchModeHandlers.js", "../src/commands/build.js", "../src/commands/migrate.js", "../src/commands/sync.js", "../src/scripts/syncDotGithubDir.ts", "../src/commands/wca-setup.js", "../src/scripts/prepWcaCompatibleCode.mjs", "../src/commands/check-commits.ts", "../src/scripts/check-commits/commit-analyzer.ts", "../src/utils/gitUtils.ts", "../src/scripts/check-commits/display-utils.ts", "../src/scripts/check-commits/github-labels.ts", "../src/commands/pr-release.ts", "../src/commands/test.ts", "../src/commands/agent.ts", "../src/scripts/agent/run-migrations/writeMultiGitterConfig.js", "../src/scripts/formatDependencyTree.ts", "../src/static/auroComponents.ts", "../src/commands/cem.ts", "../src/utils/fetchManifest.ts", "../src/utils/mergeManifests.ts", "../src/utils/aggregateManifest.ts", "../src/commands/cem-check.ts", "../src/init/editors/manifest.ts", "../src/
|
|
4
|
-
"sourcesContent": ["import { program } from \"commander\";\nimport auroSplash from \"#utils/auroSplash.js\";\nimport getPackageVersion from \"#utils/packageVersion.js\";\n\n// Register commands (importing them will register them)\nimport \"#commands/dev.js\";\nimport \"#commands/build.js\";\nimport \"#commands/migrate.js\";\nimport \"#commands/sync.js\";\nimport \"#commands/wca-setup.js\";\nimport \"#commands/check-commits.ts\";\nimport \"#commands/pr-release.ts\";\nimport \"#commands/test.js\";\nimport \"#commands/agent.ts\";\nimport \"#commands/cem.ts\";\nimport \"#commands/cem-check.ts\";\nimport \"#commands/context.ts\";\nimport \"#commands/init.ts\";\nimport \"#commands/component.ts\";\nimport \"#commands/docs.ts\";\nimport \"#commands/ado.ts\";\nimport \"#commands/rc-workflow.ts\";\n\nprogram\n .name(\"auro\")\n .version(getPackageVersion())\n .description(\"A cli tool to support the Auro Design System\");\n\nprogram.addHelpText(\"beforeAll\", auroSplash());\n\nprogram.parse();\n", "import figlet from \"figlet\";\nimport { mind } from \"gradient-string\";\n\nexport default () => {\n return mind(figlet.textSync(\"Auro CLI\"));\n};\n", "/* eslint-disable no-underscore-dangle, no-undef */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Simple debug logger that only prints when DEBUG environment variable is set.\n * @param {string} message - The message to log.\n */\nfunction debugLog(message) {\n if (process.env.DEBUG) {\n console.log(`[DEBUG] ${message}`);\n }\n}\n\n/**\n * Retrieves the version from the package.json file.\n * @returns {string} The version from package.json.\n */\nexport default function getPackageVersion() {\n try {\n // Get the directory path of the current module\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n debugLog(`Current module path: ${__dirname}`);\n\n // Standard installed module location - current directory\n const packagePath = path.resolve(__dirname, \"..\", \"package.json\");\n\n debugLog(`Checking package.json at: ${packagePath}`);\n if (fs.existsSync(packagePath)) {\n debugLog(`Found package.json at: ${packagePath}`);\n const packageJson = JSON.parse(fs.readFileSync(packagePath, \"utf8\"));\n return packageJson.version;\n }\n\n // Fallback to a default version if we can't find the package.json\n debugLog(\n \"Could not find package.json in the standard installed module location, using default version\",\n );\n return \"0.0.0\";\n } catch (error) {\n console.error(\"Error retrieving package version:\", error);\n return \"0.0.0\";\n }\n}\n", "import { program } from \"commander\";\nimport ora from \"ora\";\nimport {\n withBuildOptions,\n withServerOptions,\n} from \"#commands/_sharedOptions.js\";\nimport { buildWithRollup } from \"#scripts/build/index.js\";\n\nlet devCommand = program\n .command(\"dev\")\n .description(\"Runs development server for auro components\");\n\ndevCommand = withBuildOptions(devCommand);\ndevCommand = withServerOptions(devCommand);\n\nexport default devCommand.action(async (options) => {\n try {\n const build = ora(\"Initializing...\");\n\n if (options.watch) {\n build.text = \"Waiting for changes...\";\n build.spinner = \"bouncingBar\";\n build.color = \"green\";\n } else {\n build.text =\n options.docs === false\n ? \"Building component (docs disabled)\"\n : \"Building component\";\n }\n\n build.start();\n\n if (!options.watch) {\n build.succeed(\"Build completed!\");\n }\n\n await buildWithRollup({ ...options, dev: true, watch: options.watch });\n } catch (error) {\n // If there's any active spinner, we need to fail it\n ora().fail(`Build failed: ${error.message}`);\n console.error(error);\n process.exit(1);\n }\n});\n", "/**\n * @param {import('commander').Command} command\n * @returns {import('commander').Command}\n */\nexport function withBuildOptions(command) {\n return command\n .option(\"-m, --module-paths [paths...]\", \"Path(s) to node_modules folder\")\n .option(\"-w, --watch\", \"Watches for changes\")\n .option(\"--skip-docs\", \"Skip documentation generation\", false)\n .option(\"-r, --readme-template <url>\", \"URL to the README template file\")\n .option(\n \"--wca-input [files...]\",\n \"Source file(s) to analyze for API documentation\",\n )\n .option(\"--wca-output [files...]\", \"Output file(s) for API documentation\");\n}\n\n/**\n * @param {import('commander').Command} command\n */\nexport function withServerOptions(command) {\n return command\n .option(\"-s, --serve\", \"Starts a server\")\n .option(\"-p, --port <number>\", \"Port for the server\")\n .option(\"-o, --open\", \"Open the browser after starting the server\");\n}\n", "import terser from \"@rollup/plugin-terser\";\nimport { watch } from \"rollup\";\nimport {\n buildCombinedBundle,\n cleanupDist,\n compileDemoScss,\n generateDocs,\n} from \"./bundleHandlers.js\";\nimport {\n getDemoConfig,\n getMainBundleConfig,\n} from \"./configUtils.js\";\nimport { startDevelopmentServer } from \"./devServerUtils.js\";\nimport {\n handleWatcherEvents,\n setupWatchModeListeners,\n} from \"./watchModeHandlers.js\";\n\n/**\n * Run a production build once\n * @param {object} options - Build options\n * @returns {Promise<void>}\n */\nasync function runProductionBuild(options) {\n const mainBundleConfig = getMainBundleConfig(options);\n const demoConfig = getDemoConfig(options);\n\n // Add terser for minification in production\n if (!options.dev) {\n mainBundleConfig.config.plugins.push(terser());\n }\n\n // Generate docs if enabled\n await generateDocs(options);\n\n // Compile demo SCSS to CSS\n await compileDemoScss();\n\n // Build main and demo bundles\n await buildCombinedBundle(mainBundleConfig.config, demoConfig.configs);\n}\n\n/**\n * Set up watch mode for development\n * @param {object} options - Build options\n * @returns {Promise<object>} - Rollup watcher\n */\nasync function setupWatchMode(options) {\n const { dev: isDevMode } = options;\n const mainBundleConfig = getMainBundleConfig({ ...options, watch: true });\n const demoConfig = getDemoConfig({ ...options, watch: true });\n\n // Create and configure the watcher. Each demo entry is its own config so\n // shared imports inline into <name>.min.js rather than emitting a separate\n // <name>2.min.js chunk.\n const watcher = watch([mainBundleConfig.config, ...demoConfig.configs]);\n\n // Set up watcher event handlers\n handleWatcherEvents(\n watcher,\n options,\n isDevMode ? async () => startDevelopmentServer(options) : undefined,\n );\n\n // Watch demo SCSS files separately since they are not part of the rollup bundle\n const chokidar = await import(\"chokidar\");\n let scssCompiling = false;\n let scssPending = false;\n let scssTimer = null;\n\n const scssWatcher = chokidar.watch(\"./demo/**/*.scss\", {\n ignoreInitial: true,\n ignored: [\"**/demo/**/*.min.css\"],\n awaitWriteFinish: {\n stabilityThreshold: 500,\n pollInterval: 100,\n },\n });\n\n scssWatcher.on(\"all\", () => {\n if (scssTimer) clearTimeout(scssTimer);\n\n scssTimer = setTimeout(async () => {\n if (scssCompiling) {\n scssPending = true;\n return;\n }\n\n scssCompiling = true;\n try {\n await compileDemoScss();\n } catch (error) {\n console.error(\"Demo SCSS watch compilation error:\", error);\n } finally {\n scssCompiling = false;\n if (scssPending) {\n scssPending = false;\n scssWatcher.emit(\"all\");\n }\n }\n }, 500);\n });\n\n // Set up clean shutdown\n setupWatchModeListeners(watcher, scssWatcher);\n\n return watcher;\n}\n\n/**\n * Build the component using Rollup with the provided options\n * @param {object} options - Build configuration options\n * @param {boolean} [options.dev=false] - Whether to run in development mode\n * @param {boolean} [options.watch] - Whether to run in watch mode (defaults to value of dev)\n * @param {boolean} [options.docs=true] - Whether to generate documentation\n * @returns {Promise<object|void>} - Rollup watcher if in watch mode\n */\nexport async function buildWithRollup(options = {}) {\n try {\n const { watch } = options;\n\n // Clean output directory\n cleanupDist();\n\n // Run production build once or set up watch mode\n // Only use watch mode if explicitly enabled\n if (watch) {\n return await setupWatchMode(options);\n }\n\n return await runProductionBuild(options);\n } catch (error) {\n throw new Error(`Build failed: ${error.message}`);\n }\n}\n\n// Re-export utilities for backward compatibility\nexport { cleanupDist };\n", "import { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { glob } from \"glob\";\nimport ora from \"ora\";\nimport { rollup } from \"rollup\";\nimport * as sass from \"sass\";\nimport { analyzeComponents } from \"#scripts/analyze.js\";\nimport { runDefaultDocsBuild } from \"#scripts/build/defaultDocsBuild.js\";\nimport { getDemoConfig } from \"#scripts/build/configUtils.js\";\nimport { MODULE_DIRS } from \"#scripts/build/paths.js\";\nimport { copyReadmeToDemo } from \"#utils/copyReadmeToDemo.js\";\n\n/**\n * Clean up the dist folder\n * @returns {boolean} Success status\n */\nexport function cleanupDist() {\n const distPath = join(\"./dist\");\n const spinner = ora(\"Cleaning dist folder...\").start();\n\n try {\n rmSync(distPath, { recursive: true, force: true });\n spinner.succeed(\"All clean! Dist folder wiped.\");\n return true;\n } catch (error) {\n spinner.fail(`Oops! Couldn't clean dist/ folder: ${error.message}`);\n console.error(error);\n return false;\n }\n}\n\n/**\n * Run a build step with spinner feedback\n * @param {string} taskName - Name of the task for spinner text\n * @param {Function} taskFn - Async function to execute the task\n * @param {string} successMsg - Message to show on success\n * @param {string} failMsg - Message to show on failure\n * @returns {Promise<any>} - Result of the task function or throws error\n */\nasync function runBuildStep(taskName, taskFn, successMsg, failMsg) {\n const spinner = ora(taskName).start();\n\n try {\n const result = await taskFn();\n spinner.succeed(successMsg);\n return result;\n } catch (error) {\n spinner.fail(failMsg);\n console.error(`Error: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * Builds the TypeScript definition files\n * @param {object} config - Rollup config for d.ts generation\n * @param {object} outputConfig - Output configuration for d.ts files\n */\nexport async function buildTypeDefinitions(config, outputConfig) {\n return runBuildStep(\n \"Creating type definitions...\",\n async () => {\n const bundle = await rollup(config);\n await bundle.write(outputConfig);\n await bundle.close();\n },\n \"Types files built.\",\n \"Darn! Type definitions failed.\",\n );\n}\n\n/**\n * Builds both the main bundle and demo files in one operation\n * @param {object} mainConfig - Rollup config for the main bundle\n * @param {object[]} demoConfigs - One Rollup config per demo entry file\n */\nexport async function buildCombinedBundle(mainConfig, demoConfigs) {\n return runBuildStep(\n `Bundling ${mainConfig.name || \"main\"} and demo...`,\n async () => {\n // Build main bundle\n const mainBundle = await rollup(mainConfig);\n await mainBundle.write(mainConfig.output);\n await mainBundle.close();\n\n // Build demo entries individually so shared imports inline into each\n // <name>.min.js instead of producing a shared <name>2.min.js chunk.\n for (const cfg of demoConfigs) {\n const bundle = await rollup(cfg);\n await bundle.write(cfg.output);\n await bundle.close();\n }\n },\n `Bundles ready! ${mainConfig.name || \"Main\"} and demo built.`,\n \"Bundle hiccup! Build failed.\",\n );\n}\n\n/**\n * Analyzes web components and generates API documentation.\n * @param {object} options - Options containing wcaInput and wcaOutput\n */\nexport async function generateDocs(options) {\n const { wcaInput: sourceFiles, wcaOutput: outFile, skipDocs } = options;\n\n if (skipDocs) {\n const skipSpinner = ora(\"Skipping docs generation...\").start();\n\n setTimeout(() => {\n skipSpinner.succeed(\"Docs generation skipped.\");\n }, 0);\n return;\n }\n\n return runBuildStep(\n \"Analyzing components and making docs...\",\n async () => {\n await analyzeComponents(sourceFiles, outFile);\n await runDefaultDocsBuild(options);\n copyReadmeToDemo();\n },\n \"Docs ready! Looking good.\",\n \"Doc troubles!\",\n );\n}\n\n\n\n/**\n * Sass FileImporter that resolves bare package imports from node_modules\n * and redirects hoisted dependencies. Returns file: URLs so that\n * within-package relative imports resolve natively on disk. When a\n * relative import fails (e.g. ./../../node_modules/@pkg/foo pointing at\n * a hoisted location that doesn't exist), Sass falls back to findFileUrl,\n * where we redirect to the actual hoisted location.\n */\nfunction createNodeModulesImporter() {\n const cwd = process.cwd();\n\n function tryResolve(filePath) {\n const candidates = [\n filePath,\n `${filePath}.scss`,\n `${filePath}.css`,\n join(dirname(filePath), `_${basename(filePath)}.scss`),\n join(filePath, \"_index.scss\"),\n join(filePath, \"index.scss\"),\n ];\n return candidates.find((c) => existsSync(c));\n }\n\n function findInModuleDirs(pkgPath) {\n for (const dir of MODULE_DIRS) {\n const found = tryResolve(resolve(cwd, dir, pkgPath));\n if (found) return found;\n }\n\n // Try resolving via package.json \"exports\" map\n const exportResolved = resolveViaExports(pkgPath);\n if (exportResolved) return exportResolved;\n\n return null;\n }\n\n /**\n * Resolves a bare specifier using the package.json \"exports\" field.\n * e.g. \"@scope/pkg/demo-styles\" looks up \"./demo-styles\" in the exports map\n * of @scope/pkg/package.json and resolves the mapped path.\n */\n function resolveViaExports(pkgPath) {\n let pkgName;\n let subpath;\n\n if (pkgPath.startsWith(\"@\")) {\n const parts = pkgPath.split(\"/\");\n if (parts.length < 3) return null;\n pkgName = `${parts[0]}/${parts[1]}`;\n subpath = `./${parts.slice(2).join(\"/\")}`;\n } else {\n const slashIdx = pkgPath.indexOf(\"/\");\n if (slashIdx === -1) return null;\n pkgName = pkgPath.slice(0, slashIdx);\n subpath = `./${pkgPath.slice(slashIdx + 1)}`;\n }\n\n for (const dir of MODULE_DIRS) {\n const pkgJsonPath = resolve(cwd, dir, pkgName, \"package.json\");\n if (!existsSync(pkgJsonPath)) continue;\n\n try {\n const pkgJson = JSON.parse(readFileSync(pkgJsonPath, \"utf-8\"));\n const exports = pkgJson.exports;\n if (!exports || typeof exports !== \"object\") continue;\n\n const mapped = exports[subpath];\n if (!mapped) continue;\n\n const target = typeof mapped === \"string\" ? mapped : mapped.default || mapped.import;\n if (!target) continue;\n\n const resolved = tryResolve(resolve(cwd, dir, pkgName, target));\n if (resolved) return resolved;\n } catch {\n continue;\n }\n }\n\n return null;\n }\n\n return {\n findFileUrl(url) {\n // Failed relative import containing a node_modules path that\n // doesn't exist due to hoisting \u2014 redirect to hoisted location\n if (url.includes(\"/node_modules/\")) {\n const lastIdx = url.lastIndexOf(\"/node_modules/\");\n const pkgPath = url.slice(lastIdx + \"/node_modules/\".length);\n const found = findInModuleDirs(pkgPath);\n if (found) return pathToFileURL(found);\n }\n\n // Bare package import (e.g. @aurodesignsystem/webcorestylesheets/...)\n if (!url.startsWith(\".\") && !url.startsWith(\"/\") && !url.startsWith(\"file:\")) {\n const found = findInModuleDirs(url);\n if (found) return pathToFileURL(found);\n }\n\n return null;\n },\n };\n}\n\n/**\n * Compiles all SCSS files in the demo directory to CSS.\n * @param {string} [demoDir=\"./demo\"] - Path to the demo directory\n */\nexport async function compileDemoScss(demoDir = \"./demo\") {\n return runBuildStep(\n \"Compiling demo SCSS...\",\n async () => {\n const scssFiles = glob.sync(join(demoDir, \"**/*.scss\"));\n const importer = createNodeModulesImporter();\n const cwd = process.cwd();\n const loadPaths = MODULE_DIRS.map((dir) => resolve(cwd, dir));\n\n for (const scssFile of scssFiles) {\n const result = sass.compile(scssFile, {\n importers: [importer],\n loadPaths,\n silenceDeprecations: [\"import\"],\n style: \"compressed\",\n });\n\n const cssFile = scssFile.replace(/\\.scss$/, \".min.css\");\n writeFileSync(cssFile, result.css);\n }\n\n return scssFiles.length;\n },\n \"Demo SCSS compiled.\",\n \"SCSS compilation failed.\",\n );\n}\n\n/**\n * Bundles demo JS files to minified ESM output.\n * @param {object} [options={}] - Options passed to getDemoConfig\n */\nexport async function buildDemoBundle(options = {}) {\n const { configs } = getDemoConfig(options);\n\n return runBuildStep(\n \"Bundling demo JS...\",\n async () => {\n for (const cfg of configs) {\n const bundle = await rollup(cfg);\n await bundle.write(cfg.output);\n await bundle.close();\n }\n },\n \"Demo JS bundled.\",\n \"Demo JS bundling failed.\",\n );\n}\n", "import ora from \"ora\";\nimport { shell } from \"#utils/shell.js\";\nimport Docs from \"./docs-generator.ts\";\nimport { configPath } from \"#utils/pathUtils.js\";\nimport { copyReadmeToDemo } from \"#utils/copyReadmeToDemo.js\";\nimport { registerWatcher, installShutdownHandler } from \"#utils/shutdown.js\";\nimport { buildDemoBundle, compileDemoScss } from \"../build/bundleHandlers.js\";\nimport { runDefaultDocsBuild } from \"../build/defaultDocsBuild.js\";\nimport { startDevelopmentServer } from \"../build/devServerUtils.js\";\n\nexport async function cem() {\n const cemSpinner = ora(\"Generating Custom Elements Manifest...\").start();\n\n try {\n // The shell function returns a promise that resolves when the command completes\n await shell(\n `npx --package=@custom-elements-manifest/analyzer -y -- cem analyze --config '${configPath(\"custom-elements-manifest.config.mjs\")}'`,\n );\n cemSpinner.succeed(\"Custom Elements Manifest generated successfully!\");\n } catch (error) {\n // Check if the error is just the plugin issue but the manifest was still created\n const errorMessage = error instanceof Error ? error.message : String(error);\n cemSpinner.warn('CEM analyzer completed with warnings: ' + errorMessage);\n }\n}\n\nexport async function api() {\n const docsSpinner = ora(\"Generating API md file...\").start();\n\n try {\n await Docs.generate();\n docsSpinner.succeed(\"API md file generated successfully!\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n docsSpinner.fail(\"Failed to generate API md file: \" + errorMessage);\n throw error;\n }\n}\n\nexport async function docs(options = {}) {\n const docsSpinner = ora(\"Compiling documentation...\").start();\n\n try {\n await runDefaultDocsBuild(options);\n docsSpinner.succeed(\"Documentation compiled successfully!\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n docsSpinner.fail(\"Failed to compile MD documentation: \" + errorMessage);\n throw error;\n }\n\n copyReadmeToDemo();\n await compileDemoScss();\n await buildDemoBundle(options);\n}\n\nexport async function serve(options = {}) {\n await startDevelopmentServer(options);\n}\n\n/**\n * Watches doc and src files and rebuilds on changes.\n */\nexport async function watchDocs(options = {}) {\n const chokidar = await import(\"chokidar\");\n\n const watchPaths = [\n \"./src/**/*\",\n \"./docs/**/*\",\n \"./docTemplates/**/*\",\n \"./apiExamples/**/*\",\n \"./demo/**/*.scss\",\n ];\n\n const ignored = [\n // Output files that should never trigger a rebuild\n \"**/demo/*.min.js\",\n \"**/demo/*.min.css\",\n \"**/demo/*.md\",\n \"**/demo/readme.md\",\n \"**/docs/api.md\",\n \"**/custom-elements.json\",\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/.git/**\",\n ];\n\n const watcher = chokidar.watch(watchPaths, {\n ignoreInitial: true,\n ignored,\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n });\n\n const watchSpinner = ora(\"Waiting for changes...\");\n watchSpinner.spinner = \"bouncingBar\";\n watchSpinner.color = \"green\";\n watchSpinner.start();\n\n let rebuildTimer: ReturnType<typeof setTimeout> | null = null;\n let rebuilding = false;\n let pendingRebuild = false;\n\n async function rebuild(triggeredBy: string) {\n if (rebuilding) {\n pendingRebuild = true;\n return;\n }\n\n rebuilding = true;\n\n // Pause watcher during rebuild to avoid feedback loops\n watcher.unwatch(watchPaths);\n\n const spinner = ora(`Change detected: ${triggeredBy}`).start();\n try {\n await runDefaultDocsBuild(options);\n copyReadmeToDemo();\n await compileDemoScss();\n await buildDemoBundle(options);\n spinner.succeed(\"Docs rebuilt!\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n spinner.fail(\"Rebuild failed: \" + errorMessage);\n } finally {\n // Re-enable watcher after a short delay for file writes to settle\n setTimeout(() => {\n watcher.add(watchPaths);\n rebuilding = false;\n\n if (pendingRebuild) {\n pendingRebuild = false;\n rebuild(\"queued changes\");\n }\n }, 1000);\n }\n }\n\n watcher.on(\"all\", (_event: string, filePath: string) => {\n if (rebuilding) return;\n\n if (rebuildTimer) {\n clearTimeout(rebuildTimer);\n }\n\n rebuildTimer = setTimeout(() => {\n rebuild(filePath);\n }, 1000);\n });\n\n // Register watcher for clean shutdown\n registerWatcher(watcher);\n installShutdownHandler();\n}\n", "import { spawn } from \"node:child_process\";\nimport ora from \"ora\";\n\nconst shell = (command, _args) => {\n const commandString = `${command} ${_args ? _args.join(\" \") : \"\"}`;\n\n // Initialize the spinner but don't start it - we'll just use it for completion status\n const spinner = ora();\n\n // Parse command string if no args are provided\n let finalCommand = command;\n let finalArgs = _args || [];\n\n if (!_args && typeof command === \"string\") {\n const parts = command.split(\" \");\n finalCommand = parts[0];\n finalArgs = parts.slice(1);\n }\n\n // Simple check for watch mode - if the command contains --watch or -w flags\n const isWatchMode =\n commandString.includes(\"--watch\") || commandString.includes(\" -w\");\n\n // Use different stdio configurations based on watch mode\n const stdio = isWatchMode\n ? \"inherit\" // Full TTY support for watch mode\n : [\"inherit\", \"pipe\", \"pipe\"]; // Capture output but allow input for normal mode\n\n const child = spawn(finalCommand, finalArgs, {\n stdio,\n shell: true,\n });\n\n // Only set up output capture if we're not in watch mode (stdio isn't 'inherit')\n if (!isWatchMode) {\n // Store command output to display after completion\n const commandOutput = [];\n\n child.stdout?.on(\"data\", (data) => {\n // Convert buffer to string\n const output = data.toString();\n\n // Store full output\n commandOutput.push(output);\n\n // Output directly to console\n process.stdout.write(output);\n });\n\n child.stderr?.on(\"data\", (data) => {\n const output = data.toString();\n commandOutput.push(output);\n process.stderr.write(output);\n });\n }\n\n // Set up a promise to track command completion\n return new Promise((resolve, reject) => {\n child.on(\"close\", (code) => {\n if (code !== 0) {\n // In watch mode, don't treat exit codes as errors - these are typically user terminations\n if (isWatchMode) {\n spinner.info(`Watch mode terminated with code ${code}`);\n resolve(); // Resolve without an error for watch mode commands\n } else {\n spinner.fail(`${commandString} failed (code ${code})`);\n reject(new Error(`Command failed with exit code ${code}`));\n }\n } else {\n spinner.succeed(`${commandString} completed successfully`);\n resolve();\n }\n });\n });\n};\n\nexport { shell };\n", "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { markdownTable } from \"markdown-table\";\nimport type {\n Package,\n Module,\n Declaration,\n CustomElementDeclaration,\n ClassMember,\n Parameter,\n Attribute\n} from 'custom-elements-manifest';\n\ninterface GenerateOptions {\n outDir?: string;\n outFile?: string;\n manifestPath?: string;\n}\n\ninterface MergedTableData {\n name: string;\n properties: string;\n attributes: string;\n modifiers: string;\n type: string;\n default: string;\n description: string;\n}\n\nexport default class Docs {\n private static manifest: Package = { schemaVersion: \"1.0.0\", readme: \"\", modules: [] };\n\n /**\n * Generate markdown documentation for all components\n */\n static generate(options: GenerateOptions = {}): void {\n const {\n outDir = \"./docs\",\n outFile = \"api.md\",\n manifestPath = \"./custom-elements.json\",\n } = options;\n\n const { getElements, renderAllElements } = Docs;\n\n // Use provided manifest or fallback to default\n if (manifestPath) {\n try {\n const manifestContent = fs.readFileSync(manifestPath, \"utf8\");\n Docs.manifest = JSON.parse(manifestContent) as Package;\n } catch (error) {\n console.error(`Error reading manifest file at ${manifestPath}:`, error);\n throw error;\n }\n }\n\n const elements = getElements();\n\n // Create docs directory if it doesn't exist\n const docsDir = outDir;\n if (!fs.existsSync(docsDir)) {\n fs.mkdirSync(docsDir, { recursive: true });\n }\n\n // Generate combined API documentation\n const apiMarkdown = renderAllElements(elements);\n const apiFilename = path.join(docsDir, outFile);\n fs.writeFileSync(apiFilename, apiMarkdown);\n console.log(`Generated combined API documentation at ${apiFilename}`);\n }\n\n /**\n * Extract custom elements from the manifest\n */\n static getElements(): CustomElementDeclaration[] {\n\n // if wca exists, use only wca modules\n const wcaModules = Docs.manifest.modules.filter(Docs.isWcaModule);\n\n return Docs.manifest.modules.reduce(\n (els: CustomElementDeclaration[], module: Module) =>\n els.concat(\n module.declarations?.filter(\n (dec: Declaration): dec is CustomElementDeclaration => \n 'customElement' in dec && dec.customElement === true && 'tagName' in dec && \n (wcaModules.length > 0 ? Docs.isWcaModule(module) : true),\n ) ?? [],\n ),\n [],\n );\n }\n\n /**\n * Check if a module has a path that matches the WCA pattern\n */\n static isWcaModule(module: Module): boolean {\n // Check if the module path matches \"scripts/wca/auro-*.js\"\n const { path } = module;\n\n if (!path) {\n return false;\n }\n \n // Match the pattern: starts with \"scripts/wca/auro-\" and ends with \".js\"\n return path.startsWith('scripts/wca/auro-') && path.endsWith('.js');\n }\n\n /**\n * Render all elements into a single markdown document\n */\n static renderAllElements(elements: CustomElementDeclaration[]): string {\n return `${elements\n .sort((a, b) => (a.tagName || '').localeCompare(b.tagName || ''))\n .map((element: CustomElementDeclaration) => Docs.renderElement(element, true))\n .join(\"\\n\\n\")}`;\n }\n\n /**\n * Render a single element as markdown\n */\n static renderElement(element: CustomElementDeclaration, includeTitle = true): string {\n const sections = [];\n const { renderTable, renderPropertiesAttributesTable, renderParameters, getType } = Docs;\n \n // Title and description\n sections.push(includeTitle ? `# ${element.tagName}` : '');\n\n if (element.description) {\n sections.push(element.description);\n }\n \n // Properties & Attributes table\n const propertiesTable = renderPropertiesAttributesTable(element);\n if (propertiesTable) {\n sections.push(propertiesTable.trim());\n }\n \n // Methods table\n const methodsTable = renderTable(\n \"Methods\",\n [\"name\", \"parameters\", \"return\", \"description\"],\n (element.members || [])\n .filter(\n (m: ClassMember) =>\n m.kind === \"method\" && ('privacy' in m ? m.privacy !== \"private\" : true) && m.name[0] !== \"_\",\n )\n .map((m: ClassMember) => ({\n ...m,\n parameters: renderParameters('parameters' in m ? m.parameters as Parameter[] : undefined),\n return: 'return' in m && m.return ? getType(m.return) : \"\",\n })),\n );\n if (methodsTable) {\n sections.push(methodsTable.trim());\n }\n \n // Events table\n const eventsTable = renderTable(\n \"Events\",\n [\"name\", \"description\"],\n element.events as unknown as Record<string, unknown>[],\n );\n if (eventsTable) {\n sections.push(eventsTable.trim());\n }\n \n // Slots table\n const slotsTable = renderTable(\n \"Slots\",\n [[\"name\", \"(default)\"], \"description\"],\n element.slots as unknown as Record<string, unknown>[],\n );\n if (slotsTable) {\n sections.push(slotsTable.trim());\n }\n \n // CSS Shadow Parts table\n const cssPartsTable = renderTable(\n \"CSS Shadow Parts\",\n [\"name\", \"description\"],\n element.cssParts as unknown as Record<string, unknown>[],\n );\n if (cssPartsTable) {\n sections.push(cssPartsTable.trim());\n }\n \n // CSS Custom Properties table\n const cssPropertiesTable = renderTable(\n \"CSS Custom Properties\",\n [\"name\", \"description\"],\n element.cssProperties as unknown as Record<string, unknown>[],\n );\n if (cssPropertiesTable) {\n sections.push(cssPropertiesTable.trim());\n }\n \n return sections.join('\\n\\n');\n }\n\n /**\n * Render combined properties and attributes table\n */\n static renderPropertiesAttributesTable(element: CustomElementDeclaration): string {\n \n const { getType, escapeMarkdown } = Docs;\n \n const properties = element.members?.filter(\n (m: ClassMember) => \n m.kind === \"field\" && \n ('privacy' in m ? m.privacy !== \"private\" : true) && \n m.name[0] !== \"_\"\n ) || [];\n const attributes = element.attributes || [];\n\n // Create a merged dataset\n const mergedData: MergedTableData[] = [];\n const processedNames = new Set<string>();\n\n // Process properties first (only include those with descriptions)\n properties.forEach((prop: ClassMember) => {\n if (prop.description?.trim()) {\n const propType = getType(prop) || \"\";\n const returnType = 'return' in prop && prop.return ? getType(prop.return) : \"\";\n const displayType = returnType || propType;\n \n mergedData.push({\n name: prop.name,\n properties: prop.name,\n attributes: ('attribute' in prop ? prop.attribute as string : '') || \"\",\n modifiers: ('readonly' in prop && prop.readonly ? 'readonly' : ''),\n type: displayType,\n default: ('default' in prop ? prop.default as string : '') || \"\",\n description: prop.description || \"\",\n });\n }\n processedNames.add(prop.name);\n if ('attribute' in prop && prop.attribute) {\n processedNames.add(prop.attribute as string);\n }\n });\n\n // Process attributes that don't have corresponding properties (only include those with descriptions)\n attributes.forEach((attr: Attribute) => {\n if (!processedNames.has(attr.name) && attr.description?.trim()) {\n mergedData.push({\n name: attr.name,\n properties: \"\",\n attributes: attr.name,\n modifiers: \"\",\n type: getType(attr) || \"\",\n default: attr.default || \"\",\n description: attr.description || \"\",\n });\n }\n });\n\n if (mergedData.length === 0) {\n return \"\";\n }\n\n const headers = [\"Properties\", \"Attributes\", \"Modifiers\", \"Type\", \"Default\", \"Description\"];\n const rows = mergedData.map((item: MergedTableData) => {\n const defaultRaw = item.default || \"\";\n const defaultTrimmed = defaultRaw.trim();\n // Remove surrounding single quotes from default values like 'foo'\n const defaultSanitized = defaultTrimmed.replace(/^'([^']+)'$/, \"$1\");\n // Remove surrounding double quotes from default values like \"foo\"\n const defaultDoubleSanitized = defaultSanitized.replace(/^\"([^\"]+)\"$/, \"$1\");\n const defaultWrapped = defaultDoubleSanitized\n ? (defaultDoubleSanitized.startsWith('`') && defaultDoubleSanitized.endsWith('`')\n ? defaultDoubleSanitized\n : `\\`${defaultDoubleSanitized}\\``)\n : \"\";\n return [\n escapeMarkdown(item.properties),\n escapeMarkdown(item.attributes),\n escapeMarkdown(item.modifiers),\n escapeMarkdown(item.type),\n escapeMarkdown(defaultWrapped),\n escapeMarkdown(item.description),\n ];\n });\n\n const table = markdownTable([headers, ...rows]);\n\n return `### Properties & Attributes\n\n${table}\n`;\n }\n\n /**\n * Render method parameters as a formatted string\n */\n static renderParameters(parameters?: Parameter[]): string {\n\n const { escapeMarkdown, getType } = Docs;\n\n if (!parameters || parameters.length === 0) {\n return \"None\";\n }\n\n return parameters\n .map(\n (param: Parameter) => {\n const paramType = getType(param) || \"any\";\n const description = param.description ? ` - ${param.description}` : \"\";\n return `\\`${param.name}\\` (${escapeMarkdown(paramType)})${escapeMarkdown(description)}`;\n }\n )\n .join(\"<br>\");\n }\n\n /**\n * Renders a markdown table of data, plucking the given properties from each item in `data`.\n */\n static renderTable(\n name: string, \n properties: (string | string[])[], \n data?: Array<Record<string, unknown>>\n ): string {\n\n const { escapeMarkdown, get, capitalize } = Docs;\n\n if (data === undefined || data.length === 0) {\n return \"\";\n }\n\n // Filter out items without descriptions\n const filteredData = data.filter((item: Record<string, unknown>) => {\n const { description } = item;\n return typeof description === 'string' && description.trim();\n });\n\n if (filteredData.length === 0) {\n return \"\";\n }\n\n const headers = properties\n .map((p: string | string[]) => capitalize((Array.isArray(p) ? p[0] : p).split(\".\")[0]));\n\n const rows = filteredData\n .map((item: Record<string, unknown>) =>\n properties\n .map((p: string | string[]) => {\n const value = get(item, p);\n // Handle multiline content and escape characters for markdown\n return escapeMarkdown(String(value || \"\"));\n })\n );\n\n const table = markdownTable([headers, ...rows]);\n\n return `### ${name}\n\n${table}\n`;\n }\n\n /**\n * Escape markdown special characters for table content\n */\n static escapeMarkdown(text: string): string {\n return text\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\n/g, \"<br>\")\n .replace(/\\|/g, \"\\\\|\");\n }\n\n /**\n * Extract and format type information from a property or attribute according to custom-elements-manifest schema\n */\n // biome-ignore lint/suspicious/noExplicitAny: utility method needs to work with any object structure\n static getType(obj: any): string {\n if (!obj || !obj.type) {\n return \"\";\n }\n\n const { type } = obj;\n\n // Utility to normalize type text: fix union spacing and replace single quotes with backticks\n const normalizeType = (text: string): string => {\n return text\n // Normalize union separators to have spaces around |\n .replace(/\\s*\\|\\s*/g, ' | ')\n // Replace any single-quoted type segments with backticks\n .replace(/'([^']+)'/g, '`$1`');\n };\n\n // Handle simple string type\n if (typeof type === 'string') {\n return normalizeType(type);\n }\n\n // Handle type with text property\n if (type.text) {\n return normalizeType(type.text);\n }\n\n // Handle union types or arrays of types\n if (Array.isArray(type)) {\n // biome-ignore lint/suspicious/noExplicitAny: handling dynamic type structures from manifest\n return type.map((t: any) => {\n if (typeof t === 'string') return t;\n if (t.text) return t.text;\n if (t.name) return t.name;\n return String(t);\n }).join(' \\\\| ');\n }\n\n // Handle complex type objects\n if (type.name) {\n return normalizeType(type.name);\n }\n\n // Handle references\n if (type.references && Array.isArray(type.references)) {\n // biome-ignore lint/suspicious/noExplicitAny: handling dynamic reference structures from manifest\n return type.references.map((ref: any) => ref.name || String(ref)).join(' \\\\| ');\n }\n\n // Fallback to string representation\n const result = String(type);\n return normalizeType(result);\n }\n\n /**\n * Reads a (possibly deep) path off of an object.\n */\n // biome-ignore lint/suspicious/noExplicitAny: utility method needs to work with any object structure\n static get(obj: any, pathInput: string | string[]): string {\n let fallback = \"\";\n let path: string = pathInput as string;\n if (Array.isArray(pathInput)) {\n [path, fallback] = pathInput;\n }\n const parts = path.split(\".\");\n // biome-ignore lint/suspicious/noExplicitAny: utility method needs to work with any object structure\n let current: any = obj;\n while (current && parts.length) {\n current = current[parts.shift() as string];\n }\n return current == null || current === \"\" ? fallback : String(current);\n }\n\n /**\n * Capitalize the first letter of a string and add spaces before capital letters in camelCase\n */\n static capitalize(s: string): string {\n \n // Add spaces before capital letters and capitalize first letter\n return s\n .replace(/([A-Z])/g, ' $1')\n .replace(/^./, str => str.toUpperCase())\n .trim();\n }\n}\n", "import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nexport function getAuroHomeDir() {\n const homeDir = os.homedir() || process.env.HOME || process.env.USERPROFILE;\n\n if (!homeDir) {\n throw new Error(\"Unable to determine user home directory\");\n }\n\n return path.join(homeDir, \".auro\");\n}\n\nexport function withHomeDir(...args) {\n return path.join(getAuroHomeDir(), ...args);\n}\n\nexport function fromCliRoot(...relativePath) {\n const cliScript = fs.realpathSync(process.argv[1]);\n const dirname = path.dirname(cliScript);\n\n return path.resolve(dirname, ...relativePath);\n}\n \nexport const configPath = (file) => fromCliRoot(\"configs\",file)\n\nexport const migrationPath = (path) => fromCliRoot(\"migrations\",path)\n", "import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/**\n * Copies the processed README.md from the project root into the demo directory as readme.md.\n */\nexport function copyReadmeToDemo() {\n const cwd = process.cwd();\n const readmeSrc = resolve(cwd, \"README.md\");\n const readmeDest = join(resolve(cwd, \"demo\"), \"readme.md\");\n\n if (!existsSync(readmeSrc)) {\n return;\n }\n\n const demoDir = resolve(cwd, \"demo\");\n if (!existsSync(demoDir)) {\n mkdirSync(demoDir, { recursive: true });\n }\n\n copyFileSync(readmeSrc, readmeDest);\n}\n", "import ora from \"ora\";\n\nconst watchers = [];\n\n/**\n * Register a watcher (rollup or chokidar) for clean shutdown on SIGINT.\n * @param {object} watcher - A watcher with a close() method\n */\nexport function registerWatcher(watcher) {\n watchers.push(watcher);\n}\n\n// Single SIGINT handler for all registered watchers\nlet handlerInstalled = false;\n\nexport function installShutdownHandler() {\n if (handlerInstalled) return;\n handlerInstalled = true;\n\n process.on(\"SIGINT\", () => {\n const closeSpinner = ora(\"Wrapping up...\").start();\n for (const watcher of watchers) {\n watcher.close();\n }\n closeSpinner.succeed(\"All done! See you next time. \u2728\");\n process.exit(0);\n });\n}\n", "import { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport {\n generateReadmeUrl,\n processContentForFile,\n templateFiller,\n} from \"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs\";\nimport fs from \"node:fs\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst PAGE_TEMPLATE_PATH = \"/docs/pages\";\n\n/**\n * Processor config object.\n * @typedef {Object} ProcessorConfig\n * @property {boolean} [overwriteLocalCopies=true] - The release version tag to use instead of master.\n * @property {string} [remoteReadmeVersion=\"master\"] - The release version tag to use instead of master.\n * @property {string} [remoteReadmeUrl] - The release version tag to use instead of master.\n * @property {string} [remoteReadmeVariant=\"\"] - The variant string to use for the README source (like \"_esm\" to make README_esm.md).\n * @property {string} [monorepoName] - The name of the monorepo, used as a template variable.\n * @property {Record<string, unknown>} [extraVars] - Additional template variables to pass to the template filler.\n * @param {ProcessorConfig} config - The configuration for this processor.\n */\nexport const defaultDocsProcessorConfig = {\n overwriteLocalCopies: true,\n remoteReadmeVersion: \"master\",\n // eslint-disable-next-line no-warning-comments\n // TODO: remove this variant when all components are updated to use latest auro-library\n // AND the default README.md is updated to use the new paths\n remoteReadmeVariant: \"_updated_paths\",\n monorepoName: undefined,\n extraVars: {},\n};\n\nfunction pathFromCwd(pathLike) {\n const cwd = process.cwd();\n return `${cwd}/${pathLike}`;\n}\n\n/**\n * Walk up the directory tree from the given start directory to find the monorepo\n * root \u2014 identified as the nearest ancestor (or self) whose package.json has a\n * \"workspaces\" field. Falls back to the start directory if none is found.\n * @param {string} [startDir=process.cwd()] - Directory to start searching from.\n * @returns {string} Absolute path to the monorepo root directory.\n */\nfunction findMonorepoRoot(startDir = process.cwd()) {\n let dir = startDir;\n while (true) {\n const pkgPath = path.join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf8\"));\n if (pkg.workspaces) return dir;\n } catch {\n // malformed package.json \u2014 keep walking up\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return startDir;\n}\n\n/**\n * @param {ProcessorConfig} config - The configuration for this processor.\n * @param {boolean} [skipReadme=false] - Whether to skip README.md processing.\n * @returns {import('../utils/sharedFileProcessorUtils').FileProcessorConfig[]}\n */\nexport async function fileConfigs(config, skipReadme = false) {\n const configs = [];\n\n // ---------- README.md ----------\n // Don't need to check for existence of README.md since it's always created\n if (!skipReadme) {\n const inputConfig = config.localReadmePath\n ? config.localReadmePath\n : {\n remoteUrl:\n config.remoteReadmeUrl ||\n generateReadmeUrl(\n config.remoteReadmeVersion,\n config.remoteReadmeVariant,\n ),\n fileName: pathFromCwd(\"/docTemplates/README.md\"),\n overwrite: config.overwriteLocalCopies,\n };\n\n configs.push({\n identifier: \"README.md\",\n input: inputConfig,\n output: pathFromCwd(\"/README.md\"),\n });\n }\n\n // ---------- index.md ----------\n if (fileExists(\"/docs/partials/index.md\")) {\n configs.push({\n identifier: \"index.md\",\n input: pathFromCwd(\"/docs/partials/index.md\"),\n output: pathFromCwd(\"/demo/index.md\"),\n mdMagicConfig: {\n output: {\n directory: pathFromCwd(\"/demo\"),\n },\n },\n });\n }\n\n // ---------- api.md ----------\n if (fileExists(\"/docs/partials/api.md\")) {\n configs.push({\n identifier: \"api.md\",\n input: pathFromCwd(\"/docs/partials/api.md\"),\n output: pathFromCwd(\"/demo/api.md\"),\n preProcessors: [templateFiller.formatApiTable],\n });\n }\n\n // ---------- Page Templates ----------\n const pageTemplateFullPath = pathFromCwd(PAGE_TEMPLATE_PATH);\n\n if (fs.existsSync(pageTemplateFullPath)) {\n const pageFiles = await fs.promises.readdir(pageTemplateFullPath);\n\n const pageObjects = pageFiles.map((file) => ({\n identifier: file,\n input: path.join(pageTemplateFullPath, file),\n output: pathFromCwd(`/demo/${file}`),\n }));\n\n configs.push(...pageObjects);\n }\n\n return configs;\n}\n\n/**\n *\n * @param {ProcessorConfig} config - The configuration for this processor.\n * @param {boolean} [skipReadme=false] - Whether to skip README.md processing.\n * @return {Promise<void>}\n */\nexport async function processDocFiles(config = defaultDocsProcessorConfig, skipReadme = false) {\n // setup\n await templateFiller.extractNames();\n\n const fileConfigsList = await fileConfigs(config, skipReadme);\n\n let monorepoName = config.monorepoName;\n if (!monorepoName) {\n try {\n const rootPkgPath = path.join(findMonorepoRoot(), \"package.json\");\n const pkgJson = JSON.parse(readFileSync(rootPkgPath, \"utf8\"));\n // Strip the npm scope prefix (\"@scope/\") to get the bare package name used in\n // template variables such as {{ monorepoName }} (e.g. \"auro-formkit\").\n monorepoName = pkgJson.name?.replace(/^@[^/]+\\//, '');\n } catch {\n // no root package.json or name field \u2014 leave undefined\n }\n }\n\n const extraVars = {\n ...(monorepoName ? { monorepoName } : {}),\n ...(config.extraVars || {}),\n };\n\n for (const fileConfig of fileConfigsList) {\n try {\n // eslint-disable-next-line no-await-in-loop\n await processContentForFile({ ...fileConfig, extraVars });\n\n // Post-processing for markdown output files\n if (fileConfig.output.endsWith('.md')) {\n await postProcessMarkdownFile(fileConfig.output, extraVars);\n }\n } catch (err) {\n Logger.error(`Error processing ${fileConfig.identifier}: ${err.message}`);\n }\n }\n}\n\n/**\n * Post-process a markdown file to resolve second-pass AURO-GENERATED-CONTENT tags,\n * convert markdown code fences to HTML, and normalize whitespace for marked.js.\n * @param {string} outputPath - The absolute path to the output markdown file.\n * @param {Record<string, unknown>} [extraVars={}] - Additional template variables for second-pass replacement.\n */\nasync function postProcessMarkdownFile(outputPath, extraVars = {}) {\n const outputDir = path.dirname(outputPath);\n\n // --- Second-pass: resolve empty AURO-GENERATED-CONTENT tags ---\n // These tags have empty content (START immediately followed by END) because\n // markdown-magic only runs one pass and doesn't process tags introduced\n // during that same pass.\n let outputContents = await fs.promises.readFile(outputPath, 'utf8');\n const emptyTagPattern = /^[ \\t]*<!-- AURO-GENERATED-CONTENT:START \\((FILE|CODE):src=([^)]+)\\) -->\\n[ \\t]*<!-- AURO-GENERATED-CONTENT:END -->/gm;\n let match;\n let modified = false;\n\n // Fallback directory: paths in shared partials are typically written\n // relative to the demo/ output directory. When the same partial is\n // inlined into a README (output at the project root), the path\n // won't resolve from that shallower directory. Using the demo dir\n // as a fallback ensures nested imports resolve consistently.\n const demoDir = pathFromCwd('demo');\n\n while ((match = emptyTagPattern.exec(outputContents)) !== null) {\n const [fullMatch, type, srcPath] = match;\n const resolvedPath = path.resolve(outputDir, srcPath);\n const fallbackPath = path.resolve(demoDir, srcPath);\n const actualPath = existsSync(resolvedPath) ? resolvedPath : (existsSync(fallbackPath) ? fallbackPath : null);\n\n if (actualPath) {\n const fileContent = readFileSync(actualPath, 'utf8');\n let replacement;\n\n if (type === 'FILE') {\n replacement = `<!-- AURO-GENERATED-CONTENT:START (FILE:src=${srcPath}) -->\\n<!-- The below content is automatically added from ${srcPath} -->\\n${fileContent.trimEnd()}\\n<!-- AURO-GENERATED-CONTENT:END -->`;\n } else {\n // CODE: wrap in a pre/code HTML block with language classes\n const ext = path.extname(srcPath).slice(1) || 'html';\n const escaped = fileContent.trimEnd()\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n replacement = `<!-- AURO-GENERATED-CONTENT:START (CODE:src=${srcPath}) -->\\n<!-- The below code snippet is automatically added from ${srcPath} -->\\n<pre class=\"language-${ext}\"><code class=\"language-${ext}\">${escaped}\\n</code></pre>\\n<!-- AURO-GENERATED-CONTENT:END -->`;\n }\n\n outputContents = outputContents.replace(fullMatch, replacement);\n // Reset lastIndex so the regex rescans from the start of\n // the replacement \u2014 otherwise consecutive tags are skipped\n // because the string length changed.\n emptyTagPattern.lastIndex = 0;\n modified = true;\n }\n }\n\n if (modified) {\n // Replace template variables (e.g. {{ componentName }}) in content\n // introduced by second-pass inlining \u2014 the first pass only\n // replaces variables in the original file, not in nested partials.\n outputContents = templateFiller.replaceTemplateValues(outputContents, extraVars);\n await fs.promises.writeFile(outputPath, outputContents);\n }\n\n // --- Convert markdown code fences to <pre><code> HTML blocks ---\n // marked.js won't parse fences inside HTML block context, so all\n // fenced code blocks need to be converted to raw HTML for consistent rendering.\n outputContents = await fs.promises.readFile(outputPath, 'utf8');\n const fencePattern = /^[ \\t]*```(\\w*)\\n([\\s\\S]*?)^[ \\t]*```[ \\t]*$/gm;\n const convertedContents = outputContents.replace(fencePattern, (_match, lang, code) => {\n const language = lang || 'html';\n const escaped = code.trimEnd()\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n return `<pre class=\"language-${language}\"><code class=\"language-${language}\">${escaped}\\n</code></pre>`;\n });\n\n if (convertedContents !== outputContents) {\n await fs.promises.writeFile(outputPath, convertedContents);\n }\n\n // --- Whitespace normalization for marked.js compatibility ---\n outputContents = await fs.promises.readFile(outputPath, 'utf8');\n\n // Dedent and fix blank lines inside <pre><code>...</code></pre> blocks\n outputContents = outputContents.replace(\n /(<pre[^>]*><code[^>]*>)([\\s\\S]*?)(<\\/code><\\/pre>)/g,\n (_match, open, content, close) => {\n const lines = content.split('\\n');\n // Find minimum indentation across non-empty lines\n const nonEmpty = lines.filter(l => l.trim().length > 0);\n if (nonEmpty.length === 0) return _match;\n const minIndent = Math.min(...nonEmpty.map(l => {\n const m = l.match(/^[ \\t]*/);\n return m ? m[0].length : 0;\n }));\n // Dedent and replace blank lines with zero-width space\n const processed = lines.map(l => {\n if (l === '') return '\\u200B';\n if (l.trim().length === 0) return '\\u200B';\n return minIndent > 0 ? l.substring(minIndent) : l;\n });\n // Strip trailing empty/zwsp lines\n while (processed.length > 0 && (processed[processed.length - 1] === '\\u200B' || processed[processed.length - 1] === '')) {\n processed.pop();\n }\n return open + processed.join('\\n') + close;\n }\n );\n\n // Strip leading whitespace outside <pre> blocks\n const outputLines = outputContents.split('\\n');\n let insidePre = false;\n\n for (let i = 0; i < outputLines.length; i++) {\n if (/<pre[\\s>]/i.test(outputLines[i])) {\n insidePre = true;\n }\n if (!insidePre) {\n // Only strip leading whitespace before HTML tags \u2014 not before markdown\n // content like indented list items, which rely on indentation for structure.\n outputLines[i] = outputLines[i].replace(/^[ \\t]+(?=<)/, '');\n }\n if (/<\\/pre>/i.test(outputLines[i])) {\n insidePre = false;\n }\n }\n\n await fs.promises.writeFile(outputPath, outputLines.join('\\n'));\n}\n\nexport async function runDefaultDocsBuild(options = {}) {\n const readmeTemplate = options.readmeTemplate;\n const isLocalPath = readmeTemplate && !readmeTemplate.startsWith(\"http\");\n\n await processDocFiles({\n ...defaultDocsProcessorConfig,\n ...(isLocalPath\n ? { localReadmePath: path.resolve(process.cwd(), readmeTemplate) }\n : {\n remoteReadmeUrl:\n readmeTemplate ||\n \"https://raw.githubusercontent.com/AlaskaAirlines/auro-templates/main/templates/default/README.md\",\n }),\n }, options.skipReadme);\n}\n\n/**\n * Check if a file exists.\n * @private\n * @param {String} pathToFile - The path to the file to check if it exists.\n * @returns {Boolean}}\n */\nfunction fileExists(pathToFile) {\n return fs.existsSync(pathFromCwd(pathToFile));\n}\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { builtinModules } from \"node:module\";\nimport { resolve } from \"node:path\";\nimport { startDevServer } from \"@web/dev-server\";\nimport { hmrPlugin } from \"@web/dev-server-hmr\";\nimport * as esbuild from \"esbuild\";\nimport ora from \"ora\";\n\nimport { MODULE_DIRS } from \"#scripts/build/paths.js\";\nconst WDS_OUTSIDE_ROOT_RE = /^\\/__wds-outside-root__\\/(\\d+)\\/(.+)$/;\n\n/**\n * Dev-server plugin that serves CSS files from node_modules when the URL\n * looks like a bare package specifier (e.g. /@scope/pkg/dist/file.css).\n * Handles CSS @import rules that reference node_modules packages.\n */\nfunction nodeModulesCssPlugin() {\n return {\n name: \"node-modules-css\",\n\n serve(context) {\n if (!context.path.endsWith(\".css\")) return;\n if (!context.path.startsWith(\"/@\") && !/^\\/[a-z]/i.test(context.path)) return;\n\n const urlPath = context.path.slice(1);\n const cwd = process.cwd();\n\n for (const dir of MODULE_DIRS) {\n const candidate = resolve(cwd, dir, urlPath);\n if (existsSync(candidate)) {\n return { body: readFileSync(candidate, \"utf-8\"), type: \"css\" };\n }\n }\n },\n };\n}\n\nfunction resolveWdsPath(urlPath, rootDir) {\n const match = urlPath.match(WDS_OUTSIDE_ROOT_RE);\n if (match) {\n return resolve(rootDir, \"../\".repeat(Number.parseInt(match[1], 10)), match[2]);\n }\n return resolve(rootDir, `.${urlPath}`);\n}\n\n/**\n * Dev-server plugin that converts CommonJS node_modules to ESM on-the-fly\n * using esbuild. Needed because nodeResolve serves node_modules files\n * directly to the browser, which can't handle require()/module.exports.\n * @returns {object} - A @web/dev-server plugin\n */\nfunction cjsToEsmPlugin() {\n const CJS_PATTERN = /\\b(require\\s*\\(|module\\.exports\\b|exports\\.\\w)/;\n const cache = new Map();\n let resolvedRootDir;\n\n return {\n name: \"cjs-to-esm\",\n\n async serverStart({ config }) {\n resolvedRootDir = resolve(config.rootDir);\n },\n\n async transform(context) {\n if (!context.path.includes(\"node_modules\")) return;\n if (!context.path.endsWith(\".js\") && !context.path.endsWith(\".cjs\")) return;\n if (typeof context.body !== \"string\") return;\n if (!CJS_PATTERN.test(context.body)) return;\n\n const filePath = resolveWdsPath(context.path, resolvedRootDir);\n\n if (cache.has(filePath)) return cache.get(filePath);\n if (!existsSync(filePath)) return;\n\n try {\n const result = await esbuild.build({\n entryPoints: [filePath],\n bundle: true,\n format: \"esm\",\n platform: \"browser\",\n write: false,\n logLevel: \"silent\",\n external: builtinModules,\n });\n\n const output = { body: result.outputFiles[0].text };\n cache.set(filePath, output);\n return output;\n } catch (error) {\n console.error(`CJS-to-ESM bundling failed for ${context.path}:`, error.message);\n }\n },\n };\n}\n\n/**\n * Default server configuration\n */\nconst DEFAULT_CONFIG = {\n watch: true,\n nodeResolve: true,\n basePath: \"/\",\n rootDir: \"./demo\",\n hmrInclude: [\"src/**/*\", \"demo/**/*\", \"apiExamples/**/*\", \"docs/**/*\"],\n};\n\n/**\n * Starts the development server\n * @param {object} options - Server options\n * @param {boolean} [options.serve] - Whether to start the server\n * @param {number} [options.port] - Port number for the server\n * @param {boolean} [options.open] - Whether to open the browser\n * @param {string} [options.rootDir] - Root directory for serving files\n * @param {string[]} [options.hmrInclude] - Patterns to include for HMR\n * @returns {Promise<object>} - The server instance\n */\nexport async function startDevelopmentServer(options = {}) {\n if (!options.serve) return;\n\n const serverSpinner = ora(\"Firing up dev server...\\n\").start();\n\n try {\n const serverConfig = {\n port: Number(options.port) || undefined,\n open: options.open ? \"/\" : undefined,\n watch: options.watch ?? DEFAULT_CONFIG.watch,\n nodeResolve: options.nodeResolve ?? DEFAULT_CONFIG.nodeResolve,\n basePath: options.basePath ?? DEFAULT_CONFIG.basePath,\n rootDir: options.rootDir ?? DEFAULT_CONFIG.rootDir,\n\n middleware: [\n function rewriteIndex(context, next) {\n if (!context.url.endsWith(\"/\") && !context.url.includes(\".\")) {\n context.url += \".html\";\n }\n return next();\n },\n ],\n\n plugins: [\n nodeModulesCssPlugin(),\n cjsToEsmPlugin(),\n hmrPlugin({\n include: options.hmrInclude ?? DEFAULT_CONFIG.hmrInclude,\n }),\n ],\n };\n\n const server = await startDevServer({\n config: serverConfig,\n readCliArgs: false,\n readFileConfig: false,\n });\n\n serverSpinner.stop();\n return server;\n } catch (error) {\n serverSpinner.fail(\"Server snag! Couldn't start dev server.\");\n console.error(\"Error starting development server:\", error);\n throw new Error(`Development server failed to start: ${error.message}`);\n }\n}\n", "/**\n * Common node_modules directory search paths for resolving packages\n * in monorepo and hoisted dependency structures.\n */\nexport const MODULE_DIRS = [\n \"node_modules\",\n \"../node_modules\",\n \"../../node_modules\",\n \"../../../node_modules\",\n];\n", "\nimport { cem, api } from '#scripts/docs/index.ts';\n\n/**\n * Analyzes web components and generates API documentation.\n */\nexport async function analyzeComponents() {\n \n await cem();\n\n await api();\n\n}", "import { basename, join, resolve } from \"node:path\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport { nodeResolve } from \"@rollup/plugin-node-resolve\";\nimport { glob } from \"glob\";\nimport { litScss } from \"rollup-plugin-scss-lit\";\nimport { MODULE_DIRS } from \"./paths.js\";\nimport { watchGlobs } from \"./plugins.js\";\n\n// Default paths used across configurations\nconst DEFAULTS = {\n moduleDirectories: [\"node_modules\"],\n modulePaths: [\"../../node_modules\", \"../node_modules\", \"node_modules\"],\n watchPatterns: [\"./apiExamples/**/*\", \"./docs/**/*\"],\n};\n\n/**\n * Creates Rollup plugins configuration.\n * @param {string[]} modulePaths - Additional paths to include in litScss.\n * @param {object} options - Additional options for plugins\n * @returns {object[]} - Array of Rollup plugins.\n */\nexport function getPluginsConfig(modulePaths = [], options = {}) {\n const {\n watchPatterns = DEFAULTS.watchPatterns,\n dedupe = [\"lit\", \"lit-element\", \"lit-html\"],\n dev = false,\n } = options;\n\n // Combine default paths with any user-provided paths\n const allModulePaths = [...DEFAULTS.modulePaths, ...modulePaths];\n\n // Absolute fallback paths so nodeResolve finds workspace/hoisted packages\n // when the importer's auto-walkup chain doesn't reach the hoist root\n // (e.g. CLI invoked from a sibling repo, symlinked workspaces).\n const cwd = process.cwd();\n const absoluteModulePaths = MODULE_DIRS.map((dir) => resolve(cwd, dir));\n\n return [\n nodeResolve({\n dedupe,\n preferBuiltins: false,\n moduleDirectories: DEFAULTS.moduleDirectories,\n modulePaths: absoluteModulePaths,\n }),\n commonjs(),\n litScss({\n // Disable CSS minification in dev for readability and faster rebuilds\n minify: dev ? false : { fast: true },\n options: {\n loadPaths: [...allModulePaths, join(process.cwd(), \"src\", \"styles\"), join(process.cwd(), \"src\")],\n },\n }),\n watchGlobs(watchPatterns),\n ];\n}\n\n/**\n * Creates Rollup configuration for the main bundle with output options.\n * @param {object} options - Build options.\n * @returns {object} - Complete Rollup configuration object with input and output.\n */\nexport function getMainBundleConfig(options = {}) {\n const {\n modulePaths = [],\n watch = false,\n input = [\"./src/index.js\", \"./src/registered.js\"],\n outputDir = \"./dist\",\n format = \"esm\",\n // When dev is true, avoid randomized filenames for easier debugging\n dev = false,\n } = options;\n\n return {\n name: \"Main\",\n config: {\n input,\n output: {\n format,\n dir: outputDir,\n // Stable names in dev; in production keep stable names for index/registered\n entryFileNames: (chunk) =>\n dev\n ? \"[name].js\"\n : [\"index\", \"registered\"].includes(chunk.name)\n ? \"[name].js\"\n : \"[name]-[hash].js\",\n chunkFileNames: dev ? \"[name].js\" : \"[name]-[hash].js\",\n assetFileNames: dev ? \"[name][extname]\" : \"[name]-[hash][extname]\",\n },\n external: getExternalConfig(),\n plugins: getPluginsConfig(modulePaths, { dev }),\n watch: getWatcherConfig(watch),\n },\n };\n}\n\n/**\n * Creates Rollup configurations for demo files. Each demo entry is built as\n * its own bundle with `inlineDynamicImports` so shared imports get duplicated\n * into each `<name>.min.js` rather than emitted as a separate `<name>2.min.js`\n * chunk. This guarantees demo HTML only needs to load its matching `.min.js`.\n * @param {object} options - Build options.\n * @returns {{name: string, configs: object[]}} - One Rollup config per demo entry.\n */\nexport function getDemoConfig(options = {}) {\n const {\n modulePaths = [],\n watch = false,\n globPattern = \"./demo/*.js\",\n ignorePattern = [\"./demo/*.min.js\"],\n outputDir = \"./demo\",\n dev = false,\n } = options;\n\n const entries = glob.sync(globPattern, { ignore: ignorePattern });\n const plugins = getPluginsConfig(modulePaths, { dev });\n const watcher = getWatcherConfig(watch);\n\n const configs = entries.map((file) => {\n const name = basename(file, \".js\");\n return {\n input: { [name]: file },\n output: {\n format: \"esm\",\n dir: outputDir,\n entryFileNames: \"[name].min.js\",\n chunkFileNames: \"[name].min.js\",\n assetFileNames: dev ? \"[name][extname]\" : \"[name]-[hash][extname]\",\n inlineDynamicImports: true,\n },\n plugins,\n // Fail the build if any import can't be resolved instead of letting\n // Rollup silently externalize it \u2014 a bare specifier in a demo .min.js\n // breaks at runtime in the browser. Most common cause: a workspace\n // dep wasn't built yet (fix the build order, e.g. turbo `^build`).\n onwarn(warning, defaultHandler) {\n if (warning.code === \"UNRESOLVED_IMPORT\") {\n throw new Error(\n `Unresolved import \"${warning.exporter ?? warning.source}\" in ${warning.id ?? file}. ` +\n \"Make sure workspace dependencies are built before bundling demos.\",\n );\n }\n defaultHandler(warning);\n },\n watch: watcher,\n };\n });\n\n return { name: \"Demo\", configs };\n}\n\n/**\n * Creates Rollup configuration for watch mode.\n * @param {boolean|object} watchOptions - Whether to enable watch mode or watch options\n * @returns {object|false} - Watch configuration for Rollup or false if disabled\n */\nexport function getWatcherConfig(watchOptions) {\n // Return false if watch mode is disabled\n if (!watchOptions) {\n return false;\n }\n\n // Allow passing a configuration object or use defaults\n const options = typeof watchOptions === \"object\" ? watchOptions : {};\n\n return {\n clearScreen: options.clearScreen ?? true,\n buildDelay: options.buildDelay ?? 500,\n chokidar: {\n ignoreInitial: true,\n // Ignore common output files that cause feedback loops\n ignored: options.ignored ?? [\n \"**/dist/**/*.d.ts\",\n \"**/custom-elements.json\",\n \"**/demo/*.md\",\n \"**/demo/**/*.min.js\",\n \"**/demo/**/*.min.css\",\n \"**/docs/api.md\",\n \"**/node_modules/**\",\n \"**/.git/**\",\n ],\n // Reduce watcher's sensitivity to prevent loops\n awaitWriteFinish: options.awaitWriteFinish ?? {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n },\n include: options.include ?? [\n \"./src/**/*.scss\",\n \"./src/**/*.js\",\n \"./src/**/*.ts\",\n \"./demo/**/*.js\",\n \"./apiExamples/**/*\",\n \"./docs/**/*.md\",\n ],\n exclude: options.exclude ?? [\"./dist/**/*\", \"./node_modules/**/*\"],\n };\n}\n\n/**\n * Creates external configuration for Rollup.\n * @param {string[]} additional - Additional external patterns\n * @returns {(string|RegExp)[]} - Array of external dependencies.\n */\nexport function getExternalConfig(additional = []) {\n const defaults = [\n // externalize all lit dependencies\n /node_modules\\/lit/,\n /node_modules\\/lit-element/,\n /node_modules\\/lit-html/,\n /node_modules\\/@lit/,\n ];\n\n return [...defaults, ...additional];\n}\n", "import path from \"node:path\";\nimport { glob } from \"glob\";\n\n/**\n * Creates a plugin that watches file globs and adds them to Rollup's watch list.\n * @param {string|string[]} globs - Glob pattern(s) to watch\n * @returns {object} - Rollup plugin\n */\nexport function watchGlobs(globs) {\n return {\n name: \"watch-globs\",\n buildStart() {\n const items = Array.isArray(globs) ? globs : [globs];\n\n for (const item of items) {\n try {\n for (const filename of glob.sync(path.resolve(item))) {\n this.addWatchFile(filename);\n }\n } catch (error) {\n this.error(`Error watching glob pattern \"${item}\": ${error.message}`);\n }\n }\n },\n };\n}\n", "import path from \"node:path\";\nimport ora from \"ora\";\nimport { rollup } from \"rollup\";\nimport { analyzeComponents } from \"#scripts/analyze.js\";\nimport { registerWatcher, installShutdownHandler } from \"#utils/shutdown.js\";\nimport { compileDemoScss, generateDocs } from \"./bundleHandlers.js\";\n\n// Track if any build is in progress to prevent overlapping operations\nlet buildInProgress = false;\n\n// Track build states and times in a single object for cleaner management\nconst builds = {\n analyze: { active: false, lastTime: 0 },\n docs: { active: false, lastTime: 0 },\n scss: { active: false, lastTime: 0 },\n};\n\n// Minimum time between builds of the same type (in ms)\nconst MIN_BUILD_INTERVAL = 5000;\n\n// Track source paths of files that triggered a watch event\nconst sourceEventPaths = new Set();\n\n// Known output files that should never trigger a rebuild\nconst OUTPUT_PATHS = [\n \"/dist/index.d.ts\",\n \"/custom-elements.json\",\n \"/demo/api.md\",\n \"/docs/api.md\",\n \"/demo/index.min.js\",\n];\n\n// Path matching checks - handle any non-string input safely\nfunction isOutputFile(filePath) {\n if (!filePath || typeof filePath !== \"string\") return false;\n\n try {\n const normalizedPath = path.normalize(filePath);\n\n // Check if it's in our known output paths\n return (\n OUTPUT_PATHS.some((outputPath) => normalizedPath.endsWith(outputPath)) ||\n normalizedPath.includes(\"/dist/\") ||\n normalizedPath.endsWith(\".min.js\") ||\n normalizedPath.endsWith(\".min.css\") ||\n normalizedPath.endsWith(\".d.ts\")\n );\n } catch (error) {\n console.error(`Error checking path (${typeof filePath}):`, error.message);\n return false; // If any error occurs, assume it's not an output file\n }\n}\n\n/**\n * Runs a build task with proper tracking of state\n * @param {string} taskName - Type of task (analyze, docs)\n * @param {Function} taskFn - The actual task function to run\n * @returns {Promise<boolean>} - Success status\n */\nasync function runBuildTask(taskName, taskFn) {\n const task = builds[taskName];\n\n // Skip if build is active or within throttle time\n if (task.active || Date.now() - task.lastTime < MIN_BUILD_INTERVAL) {\n return false;\n }\n\n try {\n task.active = true;\n task.lastTime = Date.now();\n return await taskFn();\n } catch (error) {\n console.error(`Error in ${taskName} task:`, error);\n return false;\n } finally {\n task.active = false;\n }\n}\n\n/**\n * Handles the watcher events.\n * @param {object} watcher - Rollup watcher object.\n * @param {object} options - Build options.\n * @param {Function} [onInitialBuildComplete] - Callback to run after initial build completes.\n */\nexport async function handleWatcherEvents(\n watcher,\n options,\n onInitialBuildComplete,\n) {\n // Track if this is the first build\n let isInitialBuild = true;\n // biome-ignore lint/style/useConst: This is an object that is mutated.\n let buildTasksResults = {analyze: false, docs: false, scss: false };\n let scheduledTasksTimer = null;\n let bundleSpinner;\n\n // Create a spinner for watch mode\n const watchSpinner = ora(\"Activating watch mode...\").start();\n\n // The actual task functions\n const buildTasks = {\n // Function to analyze components\n analyze: async () => {\n const { wcaInput: sourceFiles, wcaOutput: outFile, skipDocs } = options;\n if (skipDocs) {\n const skipSpinner = ora(\"Skipping component analysis...\").start();\n setTimeout(() => {\n skipSpinner.succeed(\"Component analysis skipped.\");\n }, 0);\n return true;\n }\n\n const analyzeSpinner = ora(\n \"Detective work: analyzing components...\",\n ).start();\n try {\n await analyzeComponents(sourceFiles, outFile);\n analyzeSpinner.succeed(\"Component analysis complete! API generated.\");\n return true;\n } catch (error) {\n analyzeSpinner.fail(\"Analysis hiccup! Something went wrong.\");\n console.error(\"Component analysis error:\", error);\n return false;\n }\n },\n\n // Function to rebuild documentation\n docs: async () => {\n // Skip if main bundle is still building\n if (buildInProgress) {\n return false;\n }\n\n // Check if docs generation is skipped\n if (options.skipDocs) {\n const skipSpinner = ora(\"Skipping docs generation...\").start();\n setTimeout(() => {\n skipSpinner.succeed(\"Docs generation skipped.\");\n }, 0);\n return true;\n }\n\n const docsSpinner = ora(\"Refreshing docs...\").start();\n try {\n await generateDocs(options);\n docsSpinner.succeed(\"Documentation refreshed!\");\n return true;\n } catch (error) {\n docsSpinner.fail(\"Docs stumble! Couldn't refresh.\");\n console.error(\"Documentation rebuild error:\", error);\n }\n },\n\n // Function to compile demo SCSS\n scss: async () => {\n if (buildInProgress) {\n return false;\n }\n\n try {\n await compileDemoScss();\n return true;\n } catch (error) {\n console.error(\"Demo SCSS compilation error:\", error);\n return false;\n }\n },\n };\n\n // Check if all initial build tasks completed successfully\n const checkInitialBuildComplete = () => {\n if (\n isInitialBuild &&\n buildTasksResults.analyze &&\n buildTasksResults.docs &&\n buildTasksResults.scss &&\n typeof onInitialBuildComplete === \"function\"\n ) {\n isInitialBuild = false;\n onInitialBuildComplete();\n }\n };\n\n // Schedule the post-bundle tasks with proper sequencing\n function schedulePostBundleTasks(delay = 1000) {\n if (scheduledTasksTimer) {\n clearTimeout(scheduledTasksTimer);\n }\n\n scheduledTasksTimer = setTimeout(async () => {\n // Run tasks with delays between them to avoid race conditions\n\n setTimeout(async () => {\n buildTasksResults.analyze = await runBuildTask(\n \"analyze\",\n buildTasks.analyze,\n );\n\n setTimeout(async () => {\n buildTasksResults.docs = await runBuildTask(\"docs\", buildTasks.docs);\n\n setTimeout(async () => {\n buildTasksResults.scss = await runBuildTask(\"scss\", buildTasks.scss);\n checkInitialBuildComplete();\n }, 500);\n }, 1000);\n }, 1000);\n }, delay);\n }\n\n // Set up event handlers for the watcher\n watcher.on(\"event\", async (event) => {\n switch (event.code) {\n case \"START\":\n watchSpinner.succeed(\"Watch mode active! Eyes peeled.\");\n break;\n\n case \"BUNDLE_START\":\n // Clear source paths from the previous bundle operation\n sourceEventPaths.clear();\n\n // Store source file paths that triggered this build\n if (event.input) {\n try {\n // Handle different input formats safely\n const inputs = Array.isArray(event.input)\n ? event.input\n : typeof event.input === \"string\"\n ? [event.input]\n : typeof event.input === \"object\" && event.input !== null\n ? Object.values(event.input)\n : [];\n\n for (const input of inputs) {\n // Only process string inputs and skip non-string values\n if (typeof input === \"string\" && !isOutputFile(input)) {\n sourceEventPaths.add(path.normalize(input));\n }\n }\n } catch (error) {\n console.error(\"Error processing input paths:\", error);\n }\n }\n\n bundleSpinner = ora(\"Weaving bundles...\").start();\n buildInProgress = true;\n break;\n\n case \"BUNDLE_END\":\n if (bundleSpinner) {\n bundleSpinner.succeed(\n `Bundle ${Array.isArray(event.input) ? `of ${event.input.join(\"& \")} ` : \"\"}done in ${event.duration}ms! \uD83D\uDE80`,\n );\n }\n buildInProgress = false;\n\n // Schedule post-bundle tasks if source files triggered this build\n if (sourceEventPaths.size > 0) {\n schedulePostBundleTasks();\n }\n break;\n\n case \"END\":\n // We've already scheduled tasks in BUNDLE_END, nothing to do here\n break;\n\n case \"ERROR\":\n buildInProgress = false;\n if (bundleSpinner) {\n bundleSpinner.fail(`Oops! Bundle hit a snag: ${event.error.message}`);\n } else {\n ora().fail(`Watch mode hiccup: ${event.error.message}`);\n }\n sourceEventPaths.clear();\n break;\n }\n });\n}\n\n/**\n * Setup watch mode for rollup\n * @param {object} watcher - Rollup watcher instance\n * @param {object} [scssWatcher] - Optional chokidar watcher for demo SCSS\n */\nexport function setupWatchModeListeners(watcher, scssWatcher) {\n registerWatcher(watcher);\n if (scssWatcher) registerWatcher(scssWatcher);\n installShutdownHandler();\n\n return watcher;\n}\n", "import { program } from \"commander\";\nimport ora from \"ora\";\nimport { withBuildOptions } from \"#commands/_sharedOptions.js\";\nimport { buildWithRollup } from \"#scripts/build/index.js\";\n\nlet buildCommand = program\n .command(\"build\")\n .description(\"Builds auro components\");\n\nbuildCommand = withBuildOptions(buildCommand);\n\nexport default buildCommand.action(async (options) => {\n try {\n const build = ora(\"Initializing...\");\n\n if (options.watch) {\n build.text = \"Waiting for changes...\";\n build.spinner = \"bouncingBar\";\n build.color = \"green\";\n } else {\n build.text =\n options.docs === false\n ? \"Building component (docs disabled)\"\n : \"Building component\";\n }\n\n build.start();\n\n await buildWithRollup(options);\n\n if (!options.watch) {\n build.succeed(\"Build completed!\");\n }\n } catch (error) {\n // If there's any active spinner, we need to fail it\n ora().fail(`Build failed: ${error.message}`);\n console.error(error);\n process.exit(1);\n }\n});\n", "import { exec } from \"node:child_process\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\nimport util from \"node:util\";\nimport { program } from \"commander\";\nimport inquirer from \"inquirer\";\nimport { shell } from \"#utils/shell.js\";\n\nexport default program\n .command(\"migrate\")\n .description(\"Script runner to perform repetitive code change tasks\")\n .requiredOption(\n \"-i, --id <string>\",\n \"Select the migration you would like to run by id\",\n )\n .option(\n \"-m, --multi-gitter\",\n \"Run the migration on all repositories in the multi-gitter config\",\n )\n .action(async (options) => {\n const filename = fileURLToPath(import.meta.url);\n const dirname = path.dirname(filename);\n const scriptPath = path.resolve(dirname, \"migrations\", options.id);\n\n if (options.multiGitter) {\n // Check if multi-gitter CLI command is available\n const execPromise = util.promisify(exec);\n\n try {\n await execPromise(\"command -v multi-gitter\");\n } catch {\n console.error(\"multi-gitter is not installed.\");\n process.exit(1);\n }\n\n const answers = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"dryRun\",\n message:\n \"Run migration in dry-run mode? (no changes will be committed)\",\n default: true,\n },\n ]);\n\n if (answers.dryRun) {\n shell(\n `multi-gitter run ${scriptPath}/script.sh --config \"${scriptPath}/multi-gitter.yml\" --dry-run`,\n );\n } else {\n shell(\n `multi-gitter run ${scriptPath}/script.sh --config \"${scriptPath}/multi-gitter.yml\"`,\n );\n }\n } else {\n shell(`${scriptPath}/script.sh`);\n }\n });\n", "import process from \"node:process\";\nimport { program } from \"commander\";\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { syncDotGithubDir } from \"#scripts/syncDotGithubDir.js\";\n\nexport default program\n .command(\"sync\")\n .option(\"-r, --ref <branch/tag/commit>\", \"Git reference (branch/tag/commit) to use\", \"main\")\n .option(\"-t, --template <name>\", \"Template based on which to sync\", \"default\")\n .description(\n \"Script runner to synchronize local repository configuration files\",\n )\n .action(async (options) => {\n Logger.info(\"Synchronizing repository configuration files...\");\n\n Logger.warn(\n \"Note: sync does not create a new git branch. Changes are added to the current branch.\",\n );\n\n const cwd = process.cwd();\n\n try {\n await syncDotGithubDir(cwd, options.ref, options.template);\n\n // Cleanup for specific files\n // ------------------------------------------------------\n\n // Some files have specific cleanup tasks that need to be run after syncing\n\n try {\n // CODEOWNERS - has a bizarre issue with line endings. This is a workaround!\n // Maybe it has to do with the file type since there's no ending?\n const codeownersPath = `${cwd}/.github/CODEOWNERS`;\n const codeowners = await readFile(codeownersPath, { encoding: \"utf-8\" });\n\n // Convert line endings to \\n\n const codeownersFixed = codeowners\n .replace(/\\r\\n/gu, \"\\n\")\n .replace(/\\n\\n/gu, \"\\n\");\n await writeFile(codeownersPath, codeownersFixed, { encoding: \"utf-8\" });\n\n if (codeownersFixed.includes(\"\\r\") || codeownersFixed.includes(\"\\n\\n\")) {\n Logger.error(\"CODEOWNERS file still has Windows line endings.\");\n }\n } catch (codeownersError) {\n Logger.error(`Error processing CODEOWNERS file: ${codeownersError.message}`);\n throw codeownersError;\n }\n } catch (error) {\n Logger.error(`Sync operation failed: ${error.message}`);\n process.exit(1);\n }\n });\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Octokit } from \"@octokit/rest\";\nimport ora from \"ora\";\n// @ts-expect-error: No types available currently\nimport { processContentForFile, templateFiller } from \"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs\";\n\n// BELOW TYPES ARE COPIED DIRECTLY FROM THE LIBRARY\n// How can we import JSDoc types from the library?\n\n/**\n * This is the expected object type when passing something other than a string.\n * @typedef {Object} InputFileType\n * @property {string} remoteUrl - The remote template to fetch.\n * @property {string} fileName - Path including file name to store.\n * @property {boolean} [overwrite] - Default is true. Choose to overwrite the file if it exists.\n */\n\ninterface FileProcessorConfig {\n identifier: string;\n input: string | {\n remoteUrl: string;\n fileName: string;\n overwrite?: boolean;\n };\n output: string;\n mdMagicConfig?: Partial<any>;\n preProcessors?: Array<(contents: string) => string>;\n postProcessors?: Array<(contents: string) => string>;\n}\n\n\n/**\n * Get folder items from a repository-relative path.\n * @param path - Repository-relative path (e.g. \".github/workflows\")\n * @returns Promise resolving to an array of GitHub content items.\n */\nasync function getFolderItemsFromRelativeRepoPath(path: string, ref: string) {\n const octokit = new Octokit({\n auth: process.env.GITHUB_TOKEN || ''\n });\n\n try {\n const response = await octokit.request('GET /repos/{owner}/{repo}/contents/{path}', {\n ref,\n owner: 'AlaskaAirlines',\n repo: 'auro-templates',\n path: path,\n headers: {\n 'X-GitHub-Api-Version': '2022-11-28'\n }\n });\n\n const responseData = response.data;\n if (typeof responseData !== 'object' || !Array.isArray(responseData)) {\n const errorMessage = `Unexpected response format: ${JSON.stringify(responseData)}`;\n const errorSpinner = ora().start();\n errorSpinner.fail(errorMessage);\n throw new Error(\"Failed to retrieve folder items\");\n }\n\n return responseData;\n } catch (error: any) {\n const errorSpinner = ora().start();\n if (error.status === 404) {\n errorSpinner.fail(`Template '${path.split('/')[1]}' not found`);\n } else {\n errorSpinner.fail(`Error accessing template: ${error.message}`);\n }\n throw error;\n }\n}\n\ninterface ProcessIntoFileConfigArgs {\n folderItems: Awaited<ReturnType<typeof getFolderItemsFromRelativeRepoPath>>;\n templatePathToReplace: string;\n rootDir: string;\n ref: string;\n}\n\n/**\n * Recursively convert GitHub contents API items into FileProcessorConfig objects.\n */\nasync function processFolderItemsIntoFileConfigs({\n folderItems,\n templatePathToReplace,\n rootDir,\n ref,\n}: ProcessIntoFileConfigArgs): Promise<Array<FileProcessorConfig>> {\n const fileConfigs: Array<FileProcessorConfig> = [];\n\n for (const item of folderItems) {\n if (item.type == 'dir') {\n const directorySpinner = ora(`Processing directory: ${item.path}`).start();\n\n const nestedFolderItems = await getFolderItemsFromRelativeRepoPath(item.path, ref);\n \n directorySpinner.succeed(`Found ${nestedFolderItems.length} additional items in ${item.path}`);\n\n const nestedConfigs = await processFolderItemsIntoFileConfigs({\n folderItems: nestedFolderItems,\n templatePathToReplace,\n rootDir,\n ref,\n })\n\n fileConfigs.push(...nestedConfigs);\n\n continue;\n }\n\n const finalPath = item.path.replace(`${templatePathToReplace}/`, '');\n const outputPath = `${rootDir}/.github/${finalPath}`;\n\n const config = {\n identifier: item.name,\n input: {\n remoteUrl: item.download_url || '',\n fileName: outputPath,\n overwrite: true,\n },\n output: outputPath,\n } satisfies FileProcessorConfig;\n\n fileConfigs.push(config);\n }\n\n return fileConfigs;\n}\n\n\n/**\n * Recursively removes a directory and all its contents.\n * @param {string} dirPath - The path to the directory to remove.\n * @returns {Promise<void>} A promise that resolves when the directory is removed or rejects if an error occurs.\n * @throws {Error} If the directory cannot be removed.\n */\nasync function removeDirectory(dirPath: string) {\n try {\n await fs.rm(dirPath, { recursive: true, force: true });\n const successSpinner = ora().start();\n successSpinner.succeed(`Successfully removed directory: ${dirPath}`);\n } catch (error: any) {\n const errorSpinner = ora().start();\n errorSpinner.fail(`Error removing directory ${dirPath}: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * Generates a tree-like structure representation of a directory.\n * @param {string} dirPath - The path to the directory to analyze.\n * @param {string} [prefix=''] - The prefix for the current level (used for recursion).\n * @param {boolean} [isLast=true] - Whether this is the last item at the current level.\n * @returns {Promise<string>} A promise that resolves to the tree structure as a string.\n */\nasync function generateDirectoryTree(dirPath: string, prefix: string = '', isLast: boolean = true): Promise<string> {\n try {\n const stats = await fs.stat(dirPath);\n const baseName = path.basename(dirPath);\n \n if (!stats.isDirectory()) {\n return `${prefix}${isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '}${baseName}\\n`;\n }\n\n let result = `${prefix}${isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '}${baseName}/\\n`;\n \n try {\n const entries = await fs.readdir(dirPath);\n const sortedEntries = entries.sort();\n \n for (let i = 0; i < sortedEntries.length; i++) {\n const entry = sortedEntries[i];\n const entryPath = path.join(dirPath, entry);\n const isLastEntry = i === sortedEntries.length - 1;\n const newPrefix = prefix + (isLast ? ' ' : '\u2502 ');\n \n result += await generateDirectoryTree(entryPath, newPrefix, isLastEntry);\n }\n } catch (readError) {\n // If we can't read the directory, just show it as a directory\n result += `${prefix}${isLast ? ' ' : '\u2502 '}\u2514\u2500\u2500 [Permission denied or error reading directory]\\n`;\n }\n \n return result;\n } catch (error) {\n return `${prefix}${isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '}[Error: ${error}]\\n`;\n }\n}\n\n/**\n * Sync the .github directory with the remote repository.\n * @param {string} rootDir - The root directory of the local repository.\n * @param {string} ref - The Git reference (branch/tag/commit) to use.\n * @param {string} template - The template based on which to sync.\n * @returns {Promise<void>} A promise that resolves when syncing is complete.\n */\nexport async function syncDotGithubDir(rootDir: string, ref = 'main', template = 'default') {\n if (!rootDir) {\n const errorSpinner = ora().start();\n errorSpinner.fail(\"Root directory must be specified\");\n throw new Error(\"Root directory must be specified\");\n }\n\n // Setup\n await templateFiller.extractNames();\n\n if (!process.env.GITHUB_TOKEN) {\n const tokenErrorSpinner = ora().start();\n tokenErrorSpinner.fail(\"GITHUB_TOKEN environment variable is not set.\");\n throw new Error(\"GITHUB_TOKEN environment variable is not set\");\n }\n\n const templatesDefaultGithubPath = `templates/${template}/.github`;\n \n // Validate template exists BEFORE removing anything\n const folderItems = await getFolderItemsFromRelativeRepoPath(templatesDefaultGithubPath, ref);\n\n // Only remove .github directory after successful template validation\n const githubPath = \".github\";\n const removeSpinner = ora(\"Removing existing .github directory...\").start();\n try {\n await removeDirectory(githubPath);\n removeSpinner.succeed(\".github directory removed successfully\");\n } catch (error: any) {\n removeSpinner.fail(`Error removing .github directory: ${error.message}`);\n throw new Error(`Failed to remove .github directory: ${error.message}`);\n }\n\n const fileConfigs = await processFolderItemsIntoFileConfigs({\n folderItems,\n templatePathToReplace: templatesDefaultGithubPath,\n rootDir,\n ref,\n });\n\n // Process all files\n const processSpinner = ora(\"Processing all files...\").start();\n try {\n await Promise.all(\n fileConfigs.map((config) => processContentForFile(config)),\n );\n processSpinner.succeed(\"All files processed.\");\n\n // Generate and display tree output of the rootDir directory\n const treeSpinner = ora(\"Generating directory tree...\").start();\n try {\n const githubDirPath = path.join(rootDir, '.github');\n const treeOutput = await generateDirectoryTree(githubDirPath);\n treeSpinner.succeed(\"Synced .github directory structure:\");\n console.log(treeOutput);\n } catch (treeError: any) {\n treeSpinner.fail(`Error generating directory tree: ${treeError.message}`);\n // Don't exit here since the main operation succeeded\n }\n\n } catch (error: any) {\n processSpinner.fail(`Error processing files: ${error.message}`);\n throw new Error(`Failed to process files: ${error.message}`);\n }\n}\n", "/* eslint-disable no-await-in-loop, line-comment-position, no-inline-comments, jsdoc/require-jsdoc, no-undef */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport { glob } from \"glob\";\nimport getTemplatedComponentCode from \"#scripts/prepWcaCompatibleCode.mjs\";\n\n// Use glob directly as it's already promised-based in newer versions\n\nconst WAC_DIR = path.resolve(process.cwd(), \"./scripts/wca\");\n\nasync function globPath(sources) {\n try {\n const fileArrays = await Promise.all(sources.map((source) => glob(source)));\n return fileArrays.flat();\n } catch (err) {\n console.error(\"Error processing glob patterns:\", err);\n throw err; // Re-throw to handle failure at caller\n }\n}\n\nasync function createExtendsFile(filePaths) {\n if (!fs.existsSync(WAC_DIR)) {\n await fs.promises.mkdir(WAC_DIR, { recursive: true });\n }\n\n for (const filePath of filePaths) {\n const resolvedPath = path.resolve(process.cwd(), filePath);\n const fileContent = await fs.promises.readFile(resolvedPath, \"utf-8\");\n const newPath = path.resolve(WAC_DIR, `${path.basename(filePath)}`);\n const newCode = getTemplatedComponentCode(\n fileContent,\n path.relative(WAC_DIR, filePath),\n );\n await fs.promises.writeFile(newPath, newCode);\n }\n}\n\nasync function main() {\n // files to analyze\n const filePaths = await globPath([\"./src/auro-*.js\"]);\n await createExtendsFile(filePaths);\n}\n\nexport default program\n .command(\"wca-setup\")\n .description(\"Set up WCA (Web Component Analyzer) for the project\")\n .action(() => {\n main()\n .then(() => {\n Logger.success(\"WCA setup completed successfully.\");\n })\n .catch((error) => {\n Logger.error(`WCA setup failed: ${error.message}`);\n });\n });\n", "/* eslint-disable require-unicode-regexp, prefer-named-capture-group, prefer-destructuring, prettier/prettier */\n\nexport default (code, sourcePath) => {\n const defaultTag = (code.match(/static register\\(name \\= (.+)\\)/) ||\n code.match(/customElements.get\\((.+?)\\)/))[1];\n const className = code.match(/export class (.+) extends/)?.[1];\n const classDesc = code.match(/\\/\\*\\*((.|\\n)*?)(\\*\\n|\\*\\/|[@])/)?.[1] || \"\";\n\n if (!defaultTag || !className) {\n return code;\n }\n return `\nimport { ${className} } from '${sourcePath}';\n\n/**${classDesc}*/\nclass ${className}WCA extends ${className} {}\n\nif (!customElements.get(${defaultTag})) {\n customElements.define(${defaultTag}, ${className}WCA);\n}\n`;\n};\n", "import { program } from \"commander\";\nimport { analyzeCommits } from \"#scripts/check-commits/commit-analyzer.ts\";\n\nexport default program\n .command(\"check-commits\")\n .alias(\"cc\")\n .option(\n \"-l, --set-label\",\n \"Set label on the pull request based on the commit message type\",\n )\n .option(\"-d, --debug\", \"Display detailed commit information for debugging\")\n .option(\"-r, --release-notes\", \"Generate release notes based on commit messages\")\n .description(\n \"Check commits in the local repository for the types of semantic commit messages made and return the results.\",\n )\n .action(async (option) => {\n await analyzeCommits(option.debug, option.setLabel, option.releaseNotes);\n });\n", "import chalk from \"chalk\";\nimport ora from \"ora\";\nimport type { Ora } from \"ora\";\nimport { Git } from \"#utils/gitUtils.ts\";\nimport type { CommitInfo } from \"./display-utils.ts\";\nimport { displayDebugView, getColoredType } from \"./display-utils.ts\";\nimport { applyLabelToPR, getExistingLabels } from \"./github-labels.ts\";\n\nconst RELEASE_COMMIT_TYPES = [\"feat\", \"fix\", \"breaking\", \"perf\"];\n\n/**\n * Generate release notes in the specified format\n * First tries to show only feat, fix, and breaking commits\n * If none found, shows all commits for user selection\n * @param commitList The list of commits to process\n * @param showLog Whether to show the commit count log (default: true)\n */\nexport function generateReleaseNotes(commitList: CommitInfo[], showLog = true): string {\n let releaseNotes = \"### In this release\\n\";\n\n for (const commit of commitList) {\n // Format: - {short commit hash} {commit message}\n releaseNotes += `- ${commit.hash} ${commit.subject}\\n`;\n \n // Add extra commit message content if body exists\n if (commit.body?.trim()) {\n // Split body into meaningful chunks, handling different separators\n const bodyText = commit.body.trim();\n \n // Split by common separators and clean up\n const bodyLines = bodyText\n .split(/\\n+/) // Split on one or more newlines\n .map(line => line.trim())\n .filter(line => line.length > 0);\n \n for (const line of bodyLines) {\n // Handle issue references and add proper spacing\n let formattedLine = line;\n \n // Add spaces before issue references like AlaskaAirlines/auro-cli#108\n formattedLine = formattedLine.replace(\n /([^\\s])(AlaskaAirlines\\/[a-zA-Z0-9-]+#\\d+)/g, \n '$1 $2'\n );\n \n // Add spaces between consecutive issue references\n formattedLine = formattedLine.replace(\n /(AlaskaAirlines\\/[a-zA-Z0-9-]+#\\d+)([^\\s])/g, \n '$1 $2'\n );\n \n releaseNotes += ` - ${formattedLine}`;\n }\n }\n }\n\n // Show helpful info about what was included\n if (commitList.length === 0) {\n return \"\";\n }\n\n if (showLog) {\n console.log(chalk.green(`\u2713 Generating release notes for ${commitList.length} commits`));\n }\n\n return releaseNotes;\n}\n\nexport function filterCommitList(commitList: CommitInfo[], fallbackCommits = true): CommitInfo[] {\n // Filter for preferred commit types first\n const releaseCommits = commitList.filter(commit => \n RELEASE_COMMIT_TYPES.includes(commit.type)\n );\n \n // Use filtered commits if any found, otherwise use all commits\n let commitsToShow;\n\n if (fallbackCommits) {\n commitsToShow = releaseCommits.length > 0 ? releaseCommits : commitList;\n } else {\n commitsToShow = releaseCommits;\n }\n \n if (commitsToShow.length === 0) {\n console.log(\"No commits found to include in release notes.\\n\");\n }\n\n return commitsToShow;\n}\n\n/**\n * Analyze commit messages in the repository\n * @param debug Whether to display detailed debug information\n * @param verbose Whether to display verbose commit messages without truncation\n * @param setLabel Whether to apply a label to the PR based on commit types\n * @returns A promise that resolves when analysis is complete\n */\nexport async function analyzeCommits(\n debug = false,\n setLabel = false,\n releaseNotes = false,\n): Promise<void> {\n const spinner = ora(\"Checking commits...\\n\").start();\n\n try {\n const commitList = await Git.getCommitMessages();\n\n // Generate release notes if requested\n if (releaseNotes) {\n spinner.succeed(`Total commits analyzed: ${commitList.length}`);\n\n const filteredCommits = filterCommitList(commitList);\n\n console.log(generateReleaseNotes(filteredCommits));\n return;\n }\n\n // Only display commit details if debug mode is enabled\n if (debug) {\n displayDebugView(commitList);\n }\n\n spinner.succeed(`Total commits analyzed: ${commitList.length}`);\n\n if (commitList.length !== 0) {\n const commitTypes = commitList.map((commit) => commit.type);\n const uniqueTypes = Array.from(new Set(commitTypes));\n const formattedTypes = uniqueTypes\n .map((type) => getColoredType(type))\n .join(\", \");\n spinner.succeed(`Found commit types: ${formattedTypes}`);\n } else {\n spinner.info(\n \"The list of commits is created by comparing the current branch\\n\" +\n \"with the main branch. If you are on a new branch, please\\n\" +\n \"make sure to commit some changes before running this command.\",\n );\n }\n\n if (setLabel) {\n await handleLabels(commitList, spinner);\n }\n } catch (error) {\n spinner.fail(\"Error getting commit messages\");\n console.error(error);\n }\n}\n\n/**\n * Handle applying labels based on commit types\n * @param commitList The list of commits to analyze\n * @param spinner The ora spinner instance for status updates\n */\nasync function handleLabels(\n commitList: CommitInfo[],\n spinner: Ora,\n): Promise<void> {\n const validCommitTypes = [\n \"breaking\",\n \"feat\",\n \"fix\",\n \"perf\",\n \"docs\",\n \"style\",\n \"refactor\",\n \"test\",\n \"build\",\n \"ci\",\n \"chore\",\n ];\n\n const foundCommitTypes = commitList\n .map((commit) => commit.type)\n .filter((type) => validCommitTypes.includes(type));\n\n let selectedLabel = null;\n let highestPriorityIndex = Number.POSITIVE_INFINITY;\n\n for (const type of foundCommitTypes) {\n const priorityIndex = validCommitTypes.indexOf(type);\n if (priorityIndex < highestPriorityIndex) {\n highestPriorityIndex = priorityIndex;\n selectedLabel = type;\n }\n }\n\n if (selectedLabel) {\n const labelSpinner = ora(\n \"Checking existing labels on pull request...\",\n ).start();\n try {\n const existingLabels = await getExistingLabels();\n\n if (existingLabels.includes(`semantic-status: ${selectedLabel}`)) {\n labelSpinner.info(\n `Label \"semantic-status: ${getColoredType(selectedLabel)}\" already exists on the pull request.`,\n );\n return;\n }\n\n labelSpinner.text = \"Applying label to pull request...\";\n await applyLabelToPR(selectedLabel);\n labelSpinner.succeed(\n `Label \"semantic-status: ${getColoredType(selectedLabel)}\" applied to the pull request.`,\n );\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n labelSpinner.fail(errorMessage);\n }\n } else {\n spinner.warn(\n chalk.yellow(\"No semantic commit type found to apply as label.\"),\n );\n }\n}\n", "import { appendFile, readFile } from \"node:fs/promises\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { simpleGit } from \"simple-git\";\nimport type { SimpleGit } from \"simple-git\";\n\n// Initialize simple-git with proper typing\nlet git: SimpleGit;\ntry {\n git = simpleGit({\n baseDir: process.cwd(),\n binary: \"git\",\n maxConcurrentProcesses: 1,\n });\n} catch (error) {\n Logger.error(`Failed to initialize git: ${error}`);\n // Provide a minimal implementation to prevent runtime errors\n git = {} as SimpleGit;\n}\n\nexport class Git {\n static async checkGitignore(pattern: string) {\n if (pattern === \"\") {\n return false;\n }\n try {\n const fileContent = await readFile(\".gitignore\", \"utf-8\");\n return fileContent.includes(pattern);\n } catch (err) {\n Logger.error(`Error reading file: ${err}`);\n return false;\n }\n }\n\n static async getCommitMessages(sourceBranch = \"\"): Promise<\n Array<{\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n }>\n > {\n try {\n // Use the provided branch parameter, or fall back to current branch if not specified\n let branch = sourceBranch;\n if (!branch) {\n const currentBranch = await git.branchLocal();\n branch = currentBranch.current;\n }\n\n // ---- Get target branch (main) and PR commits ----\n let targetBranch = \"main\";\n let commitRange = \"\";\n\n // Check if we're in a GitHub Actions environment\n const isGitHubAction = !!process.env.GITHUB_ACTIONS;\n\n if (isGitHubAction) {\n // In GitHub Actions, we can use environment variables to determine the PR branch and base\n targetBranch = process.env.GITHUB_BASE_REF || \"main\";\n\n try {\n // Ensure target branch is fetched\n await git.fetch(\"origin\", targetBranch);\n\n // Ensure source branch is available\n if (branch !== \"HEAD\") {\n try {\n await git.raw([\"rev-parse\", \"--verify\", `origin/${branch}`]);\n } catch {\n await git.fetch(\"origin\", branch);\n }\n }\n\n // Use remote refs consistently since we're in CI\n const sourceBranchRef = branch === \"HEAD\" ? \"HEAD\" : `origin/${branch}`;\n\n // Use the merge base between target branch and source branch to get commits\n const mergeBase = await git.raw([\n \"merge-base\",\n `origin/${targetBranch}`,\n sourceBranchRef,\n ]);\n\n // Get commits between merge base and source branch\n commitRange = `${mergeBase.trim()}..${sourceBranchRef}`;\n } catch (error) {\n Logger.warn(`Error setting up commit range in CI: ${error}`);\n // Fall back to simpler approach (just compare with origin/targetBranch)\n const sourceBranchRef = branch === \"HEAD\" ? \"HEAD\" : `origin/${branch}`;\n commitRange = `origin/${targetBranch}..${sourceBranchRef}`;\n }\n } else {\n // Local environment - try to determine commits\n\n try {\n // First check if origin/main exists, fetch it if needed\n try {\n await git.raw([\"rev-parse\", \"--verify\", `origin/${targetBranch}`]);\n } catch {\n Logger.info(`Fetching ${targetBranch} from origin`);\n await git.fetch(\"origin\", targetBranch);\n }\n\n // Ensure source branch is available\n if (branch !== \"HEAD\") {\n try {\n await git.raw([\"rev-parse\", \"--verify\", branch]);\n } catch {\n await git.fetch(\"origin\", branch);\n }\n }\n\n // Find merge base between source branch and target branch\n const mergeBase = await git.raw([\n \"merge-base\",\n `origin/${targetBranch}`,\n branch,\n ]);\n\n commitRange = `${mergeBase.trim()}..${branch}`;\n } catch (error) {\n Logger.warn(`Error determining commits locally: ${error}`);\n\n // Fallback - use last few commits from source branch\n commitRange = `${branch}~10..${branch}`;\n }\n }\n\n // Get and format the PR commits\n return await Git.getFormattedCommits(commitRange);\n } catch (err) {\n Logger.error(`Error getting commit messages: ${err}`);\n return [];\n }\n }\n\n static async getRepoOwnerAndName(): Promise<{ owner: string; repo: string } | null> {\n try {\n // Get remote URLs\n const remotes = await git.getRemotes(true);\n \n if (remotes.length === 0) {\n Logger.warn(\"No remotes found\");\n return null;\n }\n\n // Get the origin remote (or first available)\n const originRemote = remotes.find(remote => remote.name === 'origin') || remotes[0];\n const remoteUrl = originRemote.refs.fetch || originRemote.refs.push;\n\n return Git.parseGitUrl(remoteUrl);\n } catch (err) {\n Logger.error(`Error getting repo owner and name: ${err}`);\n return null;\n }\n }\n\n static async getCurrentBranchName(): Promise<string | null> {\n try {\n const branchInfo = await git.branchLocal();\n return branchInfo.current || null;\n } catch (err) {\n Logger.error(`Error getting current branch name: ${err}`);\n return null;\n }\n }\n\n private static parseGitUrl(url: string): { owner: string; repo: string } | null {\n // Handle different URL formats\n // SSH: git@github.com:owner/repo.git\n // HTTPS: https://github.com/owner/repo.git\n // HTTPS with auth: https://user:token@github.com/owner/repo.git\n\n let match: RegExpMatchArray | null;\n\n // SSH format\n if (url.includes('@') && url.includes(':')) {\n match = url.match(/@([^:]+):([^/]+)\\/(.+?)(?:\\.git)?$/);\n if (match) {\n return { owner: match[2], repo: match[3] };\n }\n }\n\n // HTTPS format\n match = url.match(/https?:\\/\\/(?:[^@]+@)?[^/]+\\/([^/]+)\\/(.+?)(?:\\.git)?$/);\n if (match) {\n return { owner: match[1], repo: match[2] };\n }\n\n Logger.warn(`Could not parse git URL: ${url}`);\n return null;\n }\n\n // Helper function to get formatted commits for a given git range\n static async getFormattedCommits(commitRange: string): Promise<\n Array<{\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n }>\n > {\n interface GitCommitType {\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n type: string;\n }\n\n // Use a format that will let us parse each commit separately\n // %H = hash, %ad = author date, %an = author name, %s = subject, %b = body\n const branchCommitsRaw = await git.raw([\n \"log\",\n \"--pretty=format:COMMIT_START%n%H%n%ad%n%an%n%s%n%b%nCOMMIT_END\",\n \"--date=short\",\n commitRange,\n ]);\n\n // Split by our custom delimiter to get individual commits\n const commitChunks = branchCommitsRaw\n .split(\"COMMIT_START\\n\")\n .filter((chunk: string) => chunk.trim() !== \"\");\n\n const commits: GitCommitType[] = [];\n\n for (const chunk of commitChunks) {\n const parts = chunk.split(\"\\n\");\n if (parts.length >= 4) {\n const hash = parts[0];\n const date = parts[1];\n const author_name = parts[2];\n const subject = parts[3];\n\n // The rest is the body (may contain breaking changes)\n // Filter out the COMMIT_END marker\n const bodyLines = parts\n .slice(4)\n .filter((line: string) => line !== \"COMMIT_END\");\n const body = bodyLines.length > 0 ? bodyLines.join(\"\") : \"\";\n\n // Use a shorter hash format for better readability (7 characters)\n const shortHash = hash.substring(0, 7);\n\n // Determine commit type from subject\n const typeMatch = subject.match(\n /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore)(\\(.+\\))?:/,\n );\n let type = typeMatch ? typeMatch[1] : \"unknown\";\n\n // Check for breaking changes\n if (body.includes(\"BREAKING CHANGE\")) {\n type = \"breaking\";\n }\n\n commits.push({\n type,\n hash: shortHash,\n date,\n subject,\n body,\n message: `${subject}${body ? `\\n\\n${body}` : \"\"}`,\n author_name,\n });\n }\n }\n\n return commits;\n }\n\n // Function to add file to .gitignore\n static async addToGitignore(pattern: string, log = true) {\n await Git.checkGitignore(pattern).then(async (result) => {\n if (result) {\n Logger.warn(`${pattern} already exists`);\n } else {\n try {\n await appendFile(\".gitignore\", `\\n${pattern}`);\n if (log) {\n Logger.success(`${pattern} added to .gitignore`);\n }\n } catch (err) {\n Logger.error(err);\n }\n }\n });\n }\n\n // Function to remove file from git cache\n static async removeFromGitCache(files: string[]) {\n try {\n await git.rmKeepLocal(files);\n Logger.success(`${files.join(\", \")} are removed from git cache`);\n } catch (err) {\n Logger.error(err);\n }\n }\n\n static async createBranch(branchName: string) {\n try {\n await git.checkoutLocalBranch(branchName);\n Logger.success(`Created and switched to ${branchName} branch`);\n } catch (err) {\n Logger.error(err);\n }\n }\n\n static async commitStagedFiles(message: string) {\n try {\n await git.add(\".\");\n await git.commit(message);\n Logger.success(`Committed with message: ${message}`);\n } catch (err) {\n Logger.error(err);\n }\n }\n}\n", "import chalk from \"chalk\";\n\n// Configuration constants for display\nexport const MAX_SUBJECT_LENGTH = 60;\nexport const MAX_BODY_LENGTH = 100;\n\nexport interface CommitInfo {\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n}\n\n// Define valid commit types for better type checking\nexport type CommitType =\n | \"breaking\"\n | \"feat\"\n | \"fix\"\n | \"perf\"\n | \"docs\"\n | \"style\"\n | \"refactor\"\n | \"test\"\n | \"build\"\n | \"ci\"\n | \"chore\"\n | \"unknown\";\n\n/**\n * Get colored text for commit type using a more harmonious color scheme\n */\nexport function getColoredType(type: string): string {\n switch (type) {\n case \"breaking\":\n return chalk.bold.red(type);\n case \"feat\":\n return chalk.bold.green(type);\n case \"fix\":\n return chalk.bold.green(type);\n case \"perf\":\n return chalk.bold.green(type);\n case \"docs\":\n return chalk.bold.cyan(type);\n case \"style\":\n return chalk.bold.cyan(type);\n case \"refactor\":\n return chalk.bold.cyan(type);\n case \"test\":\n return chalk.bold.cyan(type);\n case \"build\":\n return chalk.bold.cyan(type);\n case \"ci\":\n return chalk.bold.cyan(type);\n case \"chore\":\n return chalk.bold.cyan(type);\n default:\n return chalk.bold.white(type);\n }\n}\n\n/**\n * Helper function to wrap long strings to new lines\n */\nexport function wrapString(str: string, maxLength: number): string {\n if (!str) {\n return \"\";\n }\n\n // If the string is shorter than maxLength, return it as is\n if (str.length <= maxLength) {\n return str;\n }\n\n // Split the string into words\n const words = str.split(\" \");\n let result = \"\";\n let currentLine = \"\";\n\n // Build wrapped text with line breaks\n for (const word of words) {\n // If adding this word would exceed maxLength, start a new line\n if ((currentLine + word).length > maxLength && currentLine.length > 0) {\n result += `${currentLine.trim()}\\n`;\n currentLine = \"\";\n }\n currentLine = `${currentLine}${word} `;\n }\n\n // Add the last line\n if (currentLine.length > 0) {\n result += currentLine.trim();\n }\n\n return result;\n}\n\n/**\n * Display commits in a debug format with detailed information\n */\nexport function displayDebugView(commitList: CommitInfo[]): void {\n for (const commit of commitList) {\n console.log(\"\u2500\".repeat(60));\n\n // Use a consistent color theme for metadata\n const subject = wrapString(commit.subject, MAX_SUBJECT_LENGTH);\n const body = wrapString(commit.body, MAX_BODY_LENGTH);\n\n // Display commit info in a more compact format\n console.log(chalk.bold(`${getColoredType(commit.type)}`));\n console.log(\n chalk.dim(`${commit.hash} | ${commit.date} | ${commit.author_name}`),\n );\n console.log(chalk.bold(`${chalk.white(subject)}`));\n\n // Only add body if it exists and keep it more compact\n if (commit.body) {\n console.log(chalk.dim(body));\n }\n }\n console.log(\"\u2500\".repeat(60));\n console.log(\"\\n\");\n}\n", "import * as github from \"@actions/github\";\n\n/**\n * Get existing labels from the current pull request in a GitHub Actions environment\n * @returns Promise that resolves with an array of label names\n */\nexport async function getExistingLabels(): Promise<string[]> {\n try {\n // Get the GitHub token from environment\n const token = process.env.GITHUB_TOKEN;\n\n if (!token) {\n throw new Error(\"GITHUB_TOKEN environment variable is not set\");\n }\n\n // Check if we're in a GitHub Actions environment\n if (!process.env.GITHUB_REPOSITORY || !process.env.GITHUB_EVENT_PATH) {\n throw new Error(\n \"This function can only be used in a GitHub Actions environment\",\n );\n }\n\n const octokit = github.getOctokit(token);\n const { context } = github;\n\n // Make sure we're in a pull request context\n if (!context.payload.pull_request) {\n throw new Error(\"No pull request found in the GitHub context\");\n }\n\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split(\"/\");\n const prNumber = context.payload.pull_request.number;\n\n // Get existing labels\n const { data: existingLabels } =\n await octokit.rest.issues.listLabelsOnIssue({\n owner,\n repo,\n issue_number: prNumber,\n });\n\n // Return array of label names\n return existingLabels.map((label: { name: string }) => label.name);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get existing labels: ${error.message}`);\n }\n throw error;\n }\n}\n\n/**\n * Apply a label to the current pull request in a GitHub Actions environment\n * @param label The label to apply to the pull request\n * @returns Promise that resolves when the label is applied\n */\nexport async function applyLabelToPR(label: string): Promise<void> {\n try {\n // Get the GitHub token from environment\n const token = process.env.GITHUB_TOKEN;\n\n if (!token) {\n throw new Error(\"GITHUB_TOKEN environment variable is not set\");\n }\n\n // Check if we're in a GitHub Actions environment\n if (!process.env.GITHUB_REPOSITORY || !process.env.GITHUB_EVENT_PATH) {\n throw new Error(\n \"This function can only be used in a GitHub Actions environment\",\n );\n }\n\n const octokit = github.getOctokit(token);\n const { context } = github;\n\n // Make sure we're in a pull request context\n if (!context.payload.pull_request) {\n throw new Error(\"No pull request found in the GitHub context\");\n }\n\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split(\"/\");\n const prNumber = context.payload.pull_request.number;\n\n // Add prefix to the label\n const prefixedLabel = `semantic-status: ${label}`;\n\n // Get existing labels\n const existingLabels = await getExistingLabels();\n\n // If the label we want to apply already exists, do nothing\n if (existingLabels.includes(prefixedLabel)) {\n return;\n }\n\n // Find existing semantic status labels that are different from the one we want to apply\n const existingSemanticLabels = existingLabels.filter(\n (existingLabel) =>\n existingLabel.startsWith(\"semantic-status:\") &&\n existingLabel !== prefixedLabel,\n );\n\n // Remove existing semantic status labels that don't match the new one\n for (const existingLabel of existingSemanticLabels) {\n await octokit.rest.issues.removeLabel({\n owner,\n repo,\n issue_number: prNumber,\n name: existingLabel,\n });\n }\n\n // Add the new semantic status label\n await octokit.rest.issues.addLabels({\n owner,\n repo,\n issue_number: prNumber,\n labels: [prefixedLabel],\n });\n\n return;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to apply label: ${error.message}`);\n }\n throw error;\n }\n}\n", "import fs from \"node:fs\";\nimport { get } from \"node:https\"; // Change to https\nimport chalk from \"chalk\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport type { Ora } from \"ora\";\n\nexport default program\n .command(\"pr-release\")\n .option(\n \"-n, --namespace <package-namespace>\",\n \"Set namespace of the package release\",\n \"@aurodesignsystem-dev\",\n )\n .option(\n \"-p, --pr-number <number>\",\n \"Set pull request number for the release\",\n \"0\",\n )\n .description(\n \"Generate the package version based off of PR number then update the package.json file. Note: this does not publish the package.\",\n )\n .action(async (option) => {\n await updatePackageJson(option);\n });\n\ninterface ReleaseOptions {\n namespace: string;\n prNumber: number;\n}\n\nconst updatePackageJson = async (option: ReleaseOptions): Promise<void> => {\n const { namespace, prNumber } = option;\n\n const packageSpinner = ora(\"Updating package.json\").start();\n\n try {\n const packageJsonPath = \"package.json\";\n\n // Read package.json\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n\n // Check if release version is on npmjs already\n packageSpinner.text = \"Checking npm registry for version information...\";\n\n const releaseVersion = `0.0.0-pr${prNumber}`;\n const packageComponent = packageJson.name.split(\"/\")[1];\n const packageName = `${namespace}/${packageComponent}`;\n const incrementVersion = await getIncrementVersion(\n releaseVersion,\n packageName,\n packageSpinner,\n );\n const packageVersion = `${releaseVersion}.${incrementVersion}`;\n\n packageJson.name = packageName;\n packageJson.version = packageVersion;\n\n packageSpinner.text = \"Writing updated package.json...\";\n\n // Write the updated package.json back to the file\n fs.writeFileSync(\n packageJsonPath,\n `${JSON.stringify(packageJson, null, 2)}\\n`,\n \"utf8\",\n );\n\n packageSpinner.succeed(\n `Package.json updated to use ${chalk.green(packageVersion)} and ${chalk.green(packageName)}`,\n );\n\n // Explicitly exit with success code to ensure terminal prompt returns\n process.exit(0);\n } catch (error: unknown) {\n packageSpinner.fail(`Failed to update package.json: ${error}`);\n process.exit(1); // Exit with error code\n }\n};\n\n// checks if version exists on npmjs and returns the next available increment version\nconst getIncrementVersion = (\n releaseVersion: string,\n packageName: string,\n spinner: Ora,\n): Promise<number> => {\n return new Promise((resolve) => {\n try {\n // Use the registry URL to get all versions for the package\n const registryUrl = `https://registry.npmjs.org/${packageName}`;\n\n const req = get(\n registryUrl,\n {\n headers: { Accept: \"application/json\" },\n },\n (res) => {\n // Handle redirects\n if (\n (res.statusCode === 301 || res.statusCode === 302) &&\n res.headers.location\n ) {\n // Persist redirect message\n spinner.info(`Following redirect to ${res.headers.location}...`);\n try {\n get(\n res.headers.location,\n { headers: { Accept: \"application/json\" } },\n handleResponse,\n )\n .on(\"error\", (err) => {\n // On redirect error, default to 0\n spinner.warn(\n `Error following redirect: ${err.message}, defaulting to version 0`,\n );\n resolve(0);\n })\n .end();\n } catch (error) {\n // If redirect request fails, default to 0\n spinner.warn(\n `Redirect request failed: ${error instanceof Error ? error.message : \"Unknown error\"}, defaulting to version 0`,\n );\n resolve(0);\n }\n return;\n }\n\n handleResponse(res);\n },\n );\n\n function handleResponse(res: import(\"http\").IncomingMessage) {\n if (res.statusCode !== 200) {\n // If package not found or other error, we can start with version 0\n spinner.info(\n `Package not found. Status code: ${chalk.red(res.statusCode)}, defaulting to version 0`,\n );\n resolve(0);\n return;\n }\n\n spinner.text = \"Processing version information...\";\n let data = \"\";\n res.on(\"data\", (chunk: Buffer | string) => {\n data += chunk;\n });\n\n res.on(\"end\", () => {\n try {\n const packageData = JSON.parse(data);\n const versions = packageData.versions\n ? Object.keys(packageData.versions)\n : [];\n\n spinner.text = \"Calculating next version number...\";\n\n // Find the highest existing iteration for this release version\n let maxIteration = -1;\n const versionRegex = new RegExp(`^${releaseVersion}\\\\.(\\\\d+)$`);\n\n for (const version of versions) {\n const match = version.match(versionRegex);\n if (match) {\n const iteration = Number.parseInt(match[1], 10);\n maxIteration = Math.max(maxIteration, iteration);\n }\n }\n\n // Return the next iteration number and persist this important info\n if (maxIteration >= 0) {\n spinner.info(\n `Found existing version ${chalk.green(`${releaseVersion}.${maxIteration}`)}. Incrementing to ${chalk.green(`${releaseVersion}.${maxIteration + 1}`)}`,\n );\n } else {\n spinner.info(\n `No existing version found for ${chalk.green(releaseVersion)}. Starting with ${chalk.green(`${releaseVersion}.0`)}`,\n );\n }\n resolve(maxIteration + 1);\n } catch (error) {\n // In case of parsing error, default to 0\n spinner.warn(\n `Failed to parse NPM registry response: ${error instanceof Error ? error.message : \"Unknown error\"}, defaulting to version 0`,\n );\n resolve(0);\n }\n });\n }\n\n req.on(\"error\", (err) => {\n // On request error, default to 0\n spinner.warn(`Request error: ${err.message}, defaulting to version 0`);\n resolve(0);\n });\n\n req.end();\n } catch (error) {\n // Catch any other errors and default to 0\n spinner.warn(\n \"Error checking version in npm registry, defaulting to version 0\",\n );\n resolve(0);\n }\n });\n};\n", "import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { program } from \"commander\";\nimport open from \"open\";\nimport { shell } from \"#utils/shell.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst cliRootDir = path.resolve(path.dirname(__filename), \"..\");\n\nexport default program\n .command(\"test\")\n .option(\"-w, --watch\", \"Set watch number for the test\")\n .option(\"-c, --coverage-report\", \"Generate coverage report\")\n .option(\"-o, --open\", \"Open the coverage report in the browser\")\n .option(\"-f, --files <String|String[]>\", \"Test files glob pattern\")\n .description(\"Run the web test runner to test the component library\")\n .action(async (option) => {\n const configPath = path.join(\n cliRootDir,\n \"dist\",\n \"configs\",\n \"web-test-runner.config.mjs\",\n );\n let command = `npx wtr --config \"${configPath}\"`;\n const coveragePath = `${process.cwd()}/coverage/index.html`;\n\n if (option.coverageReport) {\n command += \" --coverage\";\n }\n\n if (option.watch) {\n command += \" --watch\";\n }\n\n if (option.files) {\n const files = Array.isArray(option.files)\n ? option.files.join(\" \")\n : option.files;\n command += ` --files \"${files}\"`;\n }\n\n shell(command);\n\n if (option.open) {\n await open(coveragePath);\n }\n });\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { program } from \"commander\";\nimport inquirer from \"inquirer\";\nimport ora from \"ora\";\nimport { createMultiGitterDependencyTreeConfig } from \"#scripts/agent/run-migrations/writeMultiGitterConfig.js\";\nimport {\n formatDependencyTree,\n getBatchedUpdateOrder,\n} from \"#scripts/formatDependencyTree.ts\";\nimport { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport { fromCliRoot, withHomeDir } from \"#utils/pathUtils.js\";\nimport { shell } from \"#utils/shell.js\";\n\n// Multi-gitter and other config files live here\nconst CONFIG_DIR = withHomeDir(\"run-migrations\", \"config\");\n// Generated output files live here\nconst OUTPUT_DIR = withHomeDir(\"run-migrations\", \"outputs\");\n\nenum AgentActions {\n RunMigration = \"run-migration\",\n // Add more actions as needed\n}\n\ninterface AgentAnswers {\n agentAction: AgentActions;\n}\n\n// Agent component options\n// =========================================================\n// The canonical component list lives in #static/auroComponents so `auro cem`,\n// `auro component`, and this command can't drift out of sync.\n\nconst auroPackages = [\n ...AURO_COMPONENT_PACKAGES,\n \"@aurodesignsystem/auro-library\",\n \"@aurodesignsystem/WebCoreStyleSheets\",\n \"@aurodesignsystem/AuroDesignTokens\",\n \"@aurodesignsystem/auro-cli\",\n \"@alaskaairux/icons\",\n];\n\n// Agent helpers\n// =========================================================\ninterface DependencyTreeAnswers {\n useExisting: boolean;\n}\n\nasync function getOrCreateDependencyTree(\n relevantPackages: string[],\n): Promise<string> {\n // check if output and config directories exist, if not create them\n try {\n await fs.mkdir(OUTPUT_DIR, { recursive: true });\n await fs.mkdir(CONFIG_DIR, { recursive: true });\n } catch (error) {\n console.error(\"Failed to create output or config directories:\", error);\n process.exit(1);\n }\n\n const spinner = ora(\"Creating dependency tree...\").start();\n\n // Create multi-gitter dependency tree configuration\n spinner.text = \"Creating multi-gitter dependency tree configuration...\";\n await createMultiGitterDependencyTreeConfig(CONFIG_DIR);\n\n spinner.text = \"Scraping dependencies from Auro packages...\";\n\n // Run multi-gitter using the generated config\n const scriptPath = fromCliRoot(\"static\", \"getAuroDeps.js\");\n const multiGitterCommand = `multi-gitter run \"node ${scriptPath}\" --config ${path.join(CONFIG_DIR, \"multi-gitter_DEPENDENCY_TREE.yml\")}`;\n try {\n await shell(multiGitterCommand);\n } catch (error) {\n spinner.fail(\"Failed to generate dependency tree:\");\n console.error(error);\n process.exit(1);\n }\n\n spinner.text = \"Generating dependency tree JSON file using packages...\";\n await formatDependencyTree(OUTPUT_DIR, relevantPackages);\n\n spinner.succeed(\"Dependency tree generated successfully.\");\n\n return path.join(OUTPUT_DIR, \"dependencyTree.json\");\n}\n\nconst getDependencyBatchesFromTree = async (\n dependencyTreePath: string,\n): Promise<string[][]> => {\n const spinner = ora(\"Loading dependency tree...\").start();\n const dependencyTree = JSON.parse(\n await fs.readFile(dependencyTreePath, \"utf-8\"),\n );\n\n spinner.text = \"Processing dependency tree...\";\n const batches = getBatchedUpdateOrder(dependencyTree);\n spinner.succeed(\"Dependency batches created successfully.\");\n\n return batches;\n};\n\n// Agent command\n// =========================================================\nexport default program.command(\"agent\").action(async (option) => {\n const answers = await inquirer.prompt([\n {\n type: \"select\",\n name: \"agentAction\",\n message: \"What agent action do you want to perform?\",\n choices: [\n {\n name: \"Run a migration on auro components\",\n value: AgentActions.RunMigration,\n },\n ],\n default: [AgentActions.RunMigration],\n },\n\n {\n type: \"input\",\n name: \"migrationId\",\n message: \"What migration id do you want to run?\",\n when: (answers) => answers.agentAction === AgentActions.RunMigration,\n validate: (input) =>\n input.trim() !== \"\" || \"Migration id cannot be empty.\",\n },\n\n {\n type: \"confirm\",\n name: \"useExisting\",\n message: \"Would you like to specify starting packages?\",\n default: true,\n transformer: (value) =>\n value ? \"Yes = Packages related to selections\" : \"No = All packages\",\n when: (answers) => answers.agentAction === AgentActions.RunMigration,\n },\n\n {\n type: \"checkbox\",\n name: \"startWithComponents\",\n message:\n \"Enter the components to start with (comma-separated, blank for all):\",\n choices: AURO_COMPONENT_PACKAGES.map((component) => ({\n name: component.replace(\"@aurodesignsystem/\", \"\"),\n value: component,\n })),\n when: (answers) =>\n answers.agentAction === AgentActions.RunMigration &&\n answers.useExisting,\n },\n ]);\n\n switch (answers.agentAction) {\n case AgentActions.RunMigration: {\n // Placeholder for actual migration logic\n const spinner = ora(\"Running migration...\").start();\n const dependencyTreePath = await getOrCreateDependencyTree(\n answers.startWithComponents,\n );\n\n spinner.text = \"Getting dependency batches from tree...\";\n const dependencyBatches =\n await getDependencyBatchesFromTree(dependencyTreePath);\n\n const batchedUpdateOrderText = dependencyBatches\n .map(\n (batch, index) =>\n `Batch ${index + 1}\\n${batch.map((pkg) => ` - ${pkg.replace(\"@aurodesignsystem\", \"AlaskaAirlines\").replace(\"@alaskaairux/icons\", \"AlaskaAirlines/Icons\")}`).join(\"\\n\")}`,\n )\n .join(\"\\n\\n\");\n\n console.log(batchedUpdateOrderText);\n\n spinner.text = \"Running migrations on dependency batches...\";\n // DO STUFF HERE :)\n\n new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate async operation\n spinner.succeed(\"Migration process completed successfully.\");\n\n // spinner.succeed(\"Migration process completed.\");\n break;\n }\n // Add more cases for additional actions as needed\n default:\n console.error(\"Unknown action selected.\");\n // spinner.fail(\"Unknown action selected.\");\n }\n});\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport ora from \"ora\";\n\nconst JsonConfig = {\n \"auth-type\": \"workspace-token\",\n \"author-email\": null,\n \"author-name\": null,\n \"base-branch\": \"main\",\n \"base-url\": null,\n \"clone-dir\": \".gitter-temp\",\n \"code-search\": null,\n concurrent: 4,\n \"conflict-strategy\": \"replace\",\n draft: false,\n \"dry-run\": true,\n \"fetch-depth\": 1,\n fork: false,\n \"fork-owner\": null,\n \"git-type\": \"go\",\n group: null,\n \"include-subgroups\": false,\n insecure: false,\n interactive: false,\n labels: null,\n \"log-file\": \"'-'\",\n \"log-format\": \"'text'\",\n \"log-level\": \"'error'\",\n \"max-reviewers\": 0,\n \"max-team-reviewers\": 0,\n org: null,\n output: \"'-'\",\n \"plain-output\": false,\n platform: \"github\",\n project: null,\n \"push-only\": false,\n repo: [\n \"AlaskaAirlines/auro-accordion\",\n \"AlaskaAirlines/auro-alert\",\n \"AlaskaAirlines/auro-avatar\",\n \"AlaskaAirlines/auro-background\",\n \"AlaskaAirlines/auro-backtotop\",\n \"AlaskaAirlines/auro-button\",\n \"AlaskaAirlines/auro-badge\",\n \"AlaskaAirlines/auro-banner\",\n \"AlaskaAirlines/auro-card\",\n \"AlaskaAirlines/auro-carousel\",\n \"AlaskaAirlines/auro-datetime\",\n \"AlaskaAirlines/auro-dialog\",\n \"AlaskaAirlines/auro-drawer\",\n \"AlaskaAirlines/auro-flight\",\n \"AlaskaAirlines/auro-flightline\",\n \"AlaskaAirlines/auro-header\",\n \"AlaskaAirlines/auro-hyperlink\",\n \"AlaskaAirlines/auro-icon\",\n \"AlaskaAirlines/auro-loader\",\n \"AlaskaAirlines/auro-lockup\",\n \"AlaskaAirlines/auro-nav\",\n \"AlaskaAirlines/auro-pane\",\n \"AlaskaAirlines/auro-popover\",\n \"AlaskaAirlines/auro-sidenav\",\n \"AlaskaAirlines/auro-skeleton\",\n \"AlaskaAirlines/auro-slideshow\",\n \"AlaskaAirlines/auro-table\",\n \"AlaskaAirlines/auro-tabs\",\n \"AlaskaAirlines/auro-toast\",\n // UNCOMMENT BELOW WHEN MAIN/MASTER BRANCHES ARE READY\n // \"AlaskaAirlines/AuroDocsSite\"\n ],\n \"repo-exclude\": null,\n \"repo-include\": null,\n \"repo-search\": null,\n reviewers: null,\n \"skip-forks\": false,\n \"skip-pr\": false,\n \"skip-repo\": null,\n \"ssh-auth\": false,\n \"team-reviewers\": null,\n};\n\nfunction toYaml(config) {\n return Object.entries(config)\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return `${key}:\\n - ${value.join(\"\\n - \")}`;\n }\n if (typeof value === \"object\" && value !== null) {\n return `${key}:\\n${Object.entries(value)\n .map(([k, v]) => ` ${k}: ${v}`)\n .join(\"\\n\")}`;\n }\n return `${key}: ${value}`;\n })\n .join(\"\\n\");\n}\n\nexport async function createMultiGitterDependencyTreeConfig(outputPath) {\n const spinner = ora(\"Writing multi-gitter configuration...\").start();\n const configContent = toYaml(JsonConfig);\n const configPath = path.join(outputPath, \"multi-gitter_DEPENDENCY_TREE.yml\");\n\n try {\n await fs.writeFile(configPath, configContent, \"utf8\");\n spinner.succeed(`Multi-gitter configuration written to ${configPath}`);\n } catch (error) {\n spinner.fail(\"Error writing multi-gitter configuration:\");\n console.error(error);\n }\n}\n", "import fs from \"node:fs\";\nimport path from \"node:path\";\n\ninterface PackageJsonExcerpt {\n name: string;\n peerDependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n dependencies: Record<string, string>;\n}\n\ninterface DependencyNode {\n dependsOn: string[];\n dependentPackages: string[];\n}\n\ntype DependencyTree = Record<string, DependencyNode>;\n\nexport function getBatchedUpdateOrder(\n dependencyTree: DependencyTree,\n): Array<string[]> {\n const inDegree: Record<string, number> = {};\n const batches: Array<string[]> = [];\n let currentBatch: string[] = [];\n const queue: string[] = [];\n\n // Initialize in-degree (count of dependencies for each package)\n for (const pkg in dependencyTree) {\n inDegree[pkg] = dependencyTree[pkg].dependsOn.length;\n }\n\n // Find packages with no dependencies (in-degree = 0)\n for (const pkg in inDegree) {\n if (inDegree[pkg] === 0) {\n queue.push(pkg);\n }\n }\n\n while (queue.length > 0) {\n currentBatch = [];\n // Process the queue (topological sorting)\n const queueLength = queue.length;\n for (let i = 0; i < queueLength; i++) {\n const current = queue.shift()!;\n currentBatch.push(current);\n\n // Reduce the in-degree of dependent packages\n for (const dependent of dependencyTree[current].dependentPackages) {\n inDegree[dependent]--;\n\n // If a package now has no dependencies, add it to the queue\n if (inDegree[dependent] === 0) {\n queue.push(dependent);\n }\n }\n }\n batches.push(currentBatch);\n }\n\n // If we couldn't process all packages, there is a circular dependency\n if (batches.flat().length !== Object.keys(dependencyTree).length) {\n throw new Error(\"Circular dependency detected!\");\n }\n\n return batches;\n}\n\nfunction getJsonFilesFromDirectory(directory: string): string[] {\n return fs.readdirSync(directory).filter((file) => file.endsWith(\".json\"));\n}\n\n/**\n * Formats the dependency tree for the specified target dependencies.\n * @param rawTargetDependencies {string[]} - List of target dependencies to format. Expects package names like \"button\", \"hyperlink\", etc. without the \"@aurodesignsystem/\" prefix.\n * @returns {Promise<DependencyTree>} - A promise that resolves to the formatted dependency tree.\n */\nexport async function formatDependencyTree(\n jsonFileDirectory: string,\n targetDependencies: string[] = [],\n): Promise<DependencyTree> {\n console.log(targetDependencies);\n let dependencyTree: DependencyTree = {};\n\n const files = getJsonFilesFromDirectory(jsonFileDirectory);\n\n for (const file of files) {\n // Skip the dependency tree file itself if it already exists\n if (file === \"dependencyTree.json\") {\n continue;\n }\n\n const contents = fs.readFileSync(`${jsonFileDirectory}/${file}`, \"utf-8\");\n const data: PackageJsonExcerpt = JSON.parse(contents);\n\n const packageName = data.name;\n const peerDependencies = Object.keys(data.peerDependencies);\n const devDependencies = Object.keys(data.devDependencies);\n const dependencies = Object.keys(data.dependencies);\n\n if (!dependencyTree[packageName]) {\n dependencyTree[packageName] = { dependsOn: [], dependentPackages: [] };\n }\n\n const allDependencies = [\n ...peerDependencies,\n ...devDependencies,\n ...dependencies,\n ];\n\n dependencyTree[packageName].dependsOn = [...new Set(allDependencies)];\n\n for (const dependency of allDependencies) {\n if (!dependencyTree[dependency]) {\n dependencyTree[dependency] = { dependsOn: [], dependentPackages: [] };\n }\n\n if (!dependencyTree[dependency].dependentPackages.includes(packageName)) {\n dependencyTree[dependency].dependentPackages.push(packageName);\n }\n }\n }\n\n // If there are no specified target dependencies, use all packages\n if (targetDependencies.length) {\n // If there ARE target dependencies, filter the dependency tree down to just relevant packages\n // A tree will start only include package that the target dependencies depend on, OR packages that depend on the target dependencies\n const relevantPackages = new Set<string>();\n\n // Include any packages that depend on a target dependency\n for (const [pkg, node] of Object.entries(dependencyTree)) {\n if (node.dependsOn.some((dep) => targetDependencies.includes(dep))) {\n relevantPackages.add(pkg);\n }\n }\n\n // Also include the target dependencies themselves\n for (const target of targetDependencies) {\n if (dependencyTree[target]) {\n relevantPackages.add(target);\n }\n }\n\n // Final filtered dependency tree\n const _filteredDependencyTree: DependencyTree = {};\n for (const pkg of relevantPackages) {\n _filteredDependencyTree[pkg] = {\n dependsOn: dependencyTree[pkg].dependsOn.filter((dep) =>\n relevantPackages.has(dep),\n ),\n dependentPackages: dependencyTree[pkg].dependentPackages.filter((dep) =>\n relevantPackages.has(dep),\n ),\n };\n }\n\n dependencyTree = _filteredDependencyTree;\n } else {\n console.log(\"No target dependencies provided - using all packages.\");\n }\n\n // Write the dependency tree to a file\n fs.writeFileSync(\n `${jsonFileDirectory}/dependencyTree.json`,\n JSON.stringify(dependencyTree, null, 2),\n );\n\n return dependencyTree;\n}\n", "/**\n * Candidate Auro component packages to check for a Custom Elements Manifest\n * (`custom-elements.json`) at their package root. Not every component publishes\n * one yet \u2014 the `auro cem` command fetches each and skips those that 404, so\n * this list can safely include components ahead of their CEM adoption.\n *\n * Keep this list in sync with the components published under the\n * `@aurodesignsystem/` npm scope. It intentionally includes the **legacy\n * standalone** form packages (`auro-input`, `auro-select`, `auro-combobox`,\n * `auro-menu`, `auro-checkbox`, `auro-radio`, `auro-datepicker`, `auro-dropdown`,\n * `auro-form`) that `auro-formkit` later absorbed: a consumer may still have a\n * standalone installed alongside `auro-formkit`, and both register the same\n * `auro-*` tag. `resolveComponents` detects that overlap and grounds the tag once\n * (warning which packages collide) \u2014 so the legacy packages must be candidates for\n * the overlap to be seen at all.\n */\nexport const AURO_COMPONENT_PACKAGES = [\n \"@aurodesignsystem/auro-accordion\",\n \"@aurodesignsystem/auro-alert\",\n \"@aurodesignsystem/auro-avatar\",\n \"@aurodesignsystem/auro-background\",\n \"@aurodesignsystem/auro-backtotop\",\n \"@aurodesignsystem/auro-badge\",\n \"@aurodesignsystem/auro-banner\",\n \"@aurodesignsystem/auro-button\",\n \"@aurodesignsystem/auro-card\",\n \"@aurodesignsystem/auro-carousel\",\n \"@aurodesignsystem/auro-checkbox\",\n \"@aurodesignsystem/auro-combobox\",\n \"@aurodesignsystem/auro-datepicker\",\n \"@aurodesignsystem/auro-datetime\",\n \"@aurodesignsystem/auro-dialog\",\n \"@aurodesignsystem/auro-drawer\",\n \"@aurodesignsystem/auro-dropdown\",\n \"@aurodesignsystem/auro-flight\",\n \"@aurodesignsystem/auro-flightline\",\n \"@aurodesignsystem/auro-form\",\n \"@aurodesignsystem/auro-formkit\",\n \"@aurodesignsystem/auro-header\",\n \"@aurodesignsystem/auro-hyperlink\",\n \"@aurodesignsystem/auro-icon\",\n \"@aurodesignsystem/auro-input\",\n \"@aurodesignsystem/auro-loader\",\n \"@aurodesignsystem/auro-lockup\",\n \"@aurodesignsystem/auro-menu\",\n \"@aurodesignsystem/auro-nav\",\n \"@aurodesignsystem/auro-pane\",\n \"@aurodesignsystem/auro-popover\",\n \"@aurodesignsystem/auro-radio\",\n \"@aurodesignsystem/auro-select\",\n \"@aurodesignsystem/auro-sidenav\",\n \"@aurodesignsystem/auro-skeleton\",\n \"@aurodesignsystem/auro-slideshow\",\n \"@aurodesignsystem/auro-table\",\n \"@aurodesignsystem/auro-tabs\",\n \"@aurodesignsystem/auro-tail\",\n \"@aurodesignsystem/auro-toast\",\n \"@aurodesignsystem/auro-tokenlist\",\n];\n", "import { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport { buildAggregateManifest } from \"#utils/aggregateManifest.js\";\n\n/** Options accepted by the `cem` action. */\nexport interface CemOptions {\n output: string;\n}\n\n/**\n * Fetch every published Auro component's canonical manifest, merge them into a\n * single aggregated `custom-elements.json`, and write it to `options.output`.\n * Exits non-zero when nothing could be fetched, the write fails, or any fetch\n * failed transiently (leaving the aggregate incomplete).\n */\nexport async function runCem(options: CemOptions): Promise<void> {\n const spinner = ora(\n `Fetching manifests for ${AURO_COMPONENT_PACKAGES.length} components...`,\n ).start();\n\n // Aggregate the canonical latest published manifests, not whatever happens\n // to be installed locally, so the index doesn't mix versions per machine.\n const {\n manifest: aggregate,\n sources,\n skipped,\n transientFailures,\n } = await buildAggregateManifest(AURO_COMPONENT_PACKAGES, {\n preferLocal: false,\n });\n\n if (sources.length === 0) {\n spinner.fail(\"No component manifests could be fetched.\");\n process.exit(1);\n }\n\n const outputPath = path.resolve(process.cwd(), options.output);\n try {\n await writeFile(\n outputPath,\n `${JSON.stringify(aggregate, null, 2)}\\n`,\n \"utf-8\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(`Failed to write ${options.output}: ${message}`);\n process.exit(1);\n }\n\n spinner.succeed(\n `Aggregated ${sources.length}/${AURO_COMPONENT_PACKAGES.length} component manifests (${aggregate.modules?.length ?? 0} modules) to ${options.output}`,\n );\n\n // Report skips after the spinner so output isn't garbled. Genuine 404s are\n // expected (not every component publishes a CEM yet); transient failures\n // mean the aggregate is incomplete and are treated as an error.\n for (const outcome of skipped) {\n // Transient failures are a subset of `skipped` but are reported as errors\n // below \u2014 don't also log them as deliberate \"Skipped\" (no CEM published).\n if (outcome.transient) continue;\n Logger.info(`Skipped ${outcome.target}: ${outcome.reason}`);\n }\n\n if (transientFailures.length > 0) {\n Logger.error(\n `${transientFailures.length} component(s) failed to fetch transiently; the aggregate may be incomplete. Re-run to retry.`,\n );\n process.exit(1);\n }\n}\n\nexport default program\n .command(\"cem\")\n .description(\n \"Fetch every published Auro component's custom-elements.json and merge them into a single aggregated manifest\",\n )\n .option(\n \"-o, --output <file>\",\n \"Path to write the aggregated manifest\",\n \"custom-elements.aggregate.json\",\n )\n .action(runCem);\n", "import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nconst UNPKG_BASE = \"https://unpkg.com\";\nconst REGISTRY_BASE = \"https://registry.npmjs.org\";\n\n/**\n * Abort a manifest request that stalls. Without this a single connection that\n * is accepted but never answered would hang the CLI indefinitely \u2014 `auro cem`\n * fetches every component concurrently via `Promise.all`, so one stalled\n * request would leave the whole command spinning forever.\n */\nconst REQUEST_TIMEOUT_MS = 10_000;\n\n/** Outcome of resolving a package's Custom Elements Manifest. */\nexport interface ManifestFetchResult {\n /** The npm package (or `package@tag`) that was requested. */\n target: string;\n /** Parsed custom-elements.json, or null when it could not be resolved. */\n manifest: unknown;\n /** Where the manifest was resolved from, when successful. */\n source?: \"local\" | \"unpkg\";\n /** Resolved package version. Currently only known for local reads. */\n version?: string;\n /** Human-readable reason the manifest was unavailable. */\n reason?: string;\n /** True when the failure was transient (network/5xx/parse), not a genuine 404. */\n transient?: boolean;\n}\n\n/** Options controlling how a manifest is resolved. */\nexport interface FetchManifestOptions {\n /**\n * Read an installed copy from the current directory's `node_modules` before\n * falling back to unpkg. Defaults to true. Only applies when `target` has no\n * explicit version/tag \u2014 an explicit ref means \"exactly this version\", which\n * the local install may not match.\n */\n preferLocal?: boolean;\n /**\n * Allow network (unpkg) fetches. Defaults to true. When false, only a local\n * read is attempted and a miss returns a non-transient result.\n */\n allowNetwork?: boolean;\n}\n\n/**\n * Split a target into its package name and optional version/tag. The scope's\n * leading `@` (`@scope/name`) is not a separator \u2014 only a later `@` is:\n * `@aurodesignsystem/auro-button@3.0.0` \u2192 `{ pkg, ref: \"3.0.0\" }`.\n */\nfunction parseTarget(target: string): { pkg: string; ref?: string } {\n const at = target.lastIndexOf(\"@\");\n if (at > 0) {\n return { pkg: target.slice(0, at), ref: target.slice(at + 1) };\n }\n return { pkg: target };\n}\n\n/**\n * Whether `child` resolves to `parent` itself or a path nested inside it \u2014\n * used to keep local reads confined to the intended directory.\n */\nfunction isInside(parent: string, child: string): boolean {\n const rel = path.relative(parent, child);\n return rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel));\n}\n\n/**\n * Attempt to read an installed package's manifest from the current directory's\n * `node_modules`. Returns null when the package isn't installed, or is installed\n * but ships no manifest (so the caller can fall back to unpkg). The manifest\n * path honors the package's `customElements` field, defaulting to\n * `custom-elements.json`.\n */\nasync function readLocalManifest(\n pkg: string,\n): Promise<ManifestFetchResult | null> {\n const modulesRoot = path.join(process.cwd(), \"node_modules\");\n const pkgDir = path.join(modulesRoot, ...pkg.split(\"/\"));\n // Defense-in-depth: package names come from the curated static list or the\n // user's own CLI argument (never untrusted network data), but a name with a\n // `..` segment could still resolve outside node_modules \u2014 refuse it.\n if (!isInside(modulesRoot, pkgDir)) {\n return null;\n }\n\n let version: string | undefined;\n let manifestRelPath = \"custom-elements.json\";\n try {\n const pkgJson = JSON.parse(\n await readFile(path.join(pkgDir, \"package.json\"), \"utf-8\"),\n );\n if (typeof pkgJson.version === \"string\") {\n version = pkgJson.version;\n }\n // The `customElements` field comes from the installed package's own\n // package.json; constrain it to the package directory so a malformed or\n // hostile value can't redirect the read at a file outside the package.\n if (\n typeof pkgJson.customElements === \"string\" &&\n isInside(pkgDir, path.resolve(pkgDir, pkgJson.customElements))\n ) {\n manifestRelPath = pkgJson.customElements;\n }\n } catch {\n // Not installed (or unreadable package.json) \u2014 no local copy.\n return null;\n }\n\n try {\n const manifest = JSON.parse(\n await readFile(path.join(pkgDir, manifestRelPath), \"utf-8\"),\n );\n return { target: pkg, manifest, source: \"local\", version };\n } catch {\n // Installed but ships no manifest \u2014 let the caller fall back to unpkg.\n return null;\n }\n}\n\n/**\n * Resolve a package's Custom Elements Manifest (`custom-elements.json`),\n * preferring a copy installed in the current directory's `node_modules` (so the\n * API shown matches the version the user actually has) and falling back to\n * unpkg for anything not installed. Never throws \u2014 failures are returned as a\n * result so callers can distinguish a genuine absence (404) from a transient\n * error. `target` may be a bare package name (`@aurodesignsystem/auro-button`)\n * or include a dist-tag or version (`@aurodesignsystem/auro-button@latest`).\n */\nexport async function fetchManifest(\n target: string,\n options: FetchManifestOptions = {},\n): Promise<ManifestFetchResult> {\n const { preferLocal = true, allowNetwork = true } = options;\n const { ref } = parseTarget(target);\n\n // Local-first only when no explicit version/tag was requested.\n if (preferLocal && !ref) {\n const local = await readLocalManifest(target);\n if (local) {\n return { ...local, target };\n }\n }\n\n if (!allowNetwork) {\n return {\n target,\n manifest: null,\n reason: \"not installed locally and network fetching is disabled\",\n };\n }\n\n const url = `${UNPKG_BASE}/${target}/custom-elements.json`;\n\n let response: Response;\n try {\n response = await fetch(url, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n const timedOut =\n error instanceof DOMException && error.name === \"TimeoutError\";\n const message = timedOut\n ? `timed out after ${REQUEST_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n return {\n target,\n manifest: null,\n reason: `request failed (${message})`,\n transient: true,\n };\n }\n\n if (response.status === 404) {\n return {\n target,\n manifest: null,\n reason: \"no custom-elements.json published\",\n };\n }\n\n if (!response.ok) {\n return {\n target,\n manifest: null,\n reason: `HTTP ${response.status}`,\n transient: true,\n };\n }\n\n try {\n return { target, manifest: await response.json(), source: \"unpkg\" };\n } catch {\n return {\n target,\n manifest: null,\n reason: \"custom-elements.json is not valid JSON\",\n transient: true,\n };\n }\n}\n\n/** A set of fetch outcomes split by how their failures should be treated. */\nexport interface OutcomePartition {\n /** Every outcome that yielded no manifest \u2014 genuine 404s and transient\n * failures alike (all are absent from the aggregate). */\n skipped: ManifestFetchResult[];\n /** The subset of skips that failed transiently. Their absence means a manifest\n * that *should* be present is missing, so any aggregate built from the\n * remaining sources is incomplete and the run should be treated as failed. */\n transientFailures: ManifestFetchResult[];\n}\n\n/**\n * Partition fetch outcomes into those that produced no manifest and, within\n * those, the ones that failed transiently. A genuine 404 is an expected skip\n * (not every package publishes a CEM), whereas a transient failure (network\n * error, timeout, 5xx, unparseable body) means an expected manifest is missing \u2014\n * distinguishing the two lets a caller skip the former but fail on the latter.\n */\nexport function partitionOutcomes(\n outcomes: ManifestFetchResult[],\n): OutcomePartition {\n const skipped = outcomes.filter((outcome) => !outcome.manifest);\n return {\n skipped,\n transientFailures: skipped.filter((outcome) => outcome.transient),\n };\n}\n\n/**\n * Fetch the latest published version of a package from the npm registry.\n * Returns null on any failure \u2014 staleness reporting is best-effort and must\n * never break the command that calls it.\n */\nexport async function fetchLatestVersion(pkg: string): Promise<string | null> {\n try {\n const response = await fetch(`${REGISTRY_BASE}/${pkg}/latest`, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n if (!response.ok) {\n return null;\n }\n const data = (await response.json()) as { version?: unknown };\n return typeof data.version === \"string\" ? data.version : null;\n } catch {\n return null;\n }\n}\n", "import { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport type { CemModule, Manifest } from \"#utils/cem.js\";\n\n/** A single package's manifest, paired with the package that published it. */\nexport interface ManifestSource {\n pkg: string;\n manifest: Manifest;\n}\n\n/**\n * Recursively namespace every local module reference in a CEM node with the\n * owning package. A reference is local only when it has a `module` string and\n * no `package` sibling (a `package` means it points at an external package, so\n * its `module` must be left untouched). This keeps the merged manifest's\n * internal references (exports' `declaration.module`, `references[].module`,\n * etc.) pointing at the same paths as their now-namespaced modules.\n */\nexport function namespaceReferences(node: unknown, pkg: string): unknown {\n if (Array.isArray(node)) {\n return node.map((item) => namespaceReferences(item, pkg));\n }\n\n if (node && typeof node === \"object\") {\n const source = node as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(source)) {\n if (\n key === \"module\" &&\n typeof value === \"string\" &&\n source.package == null\n ) {\n result[key] = `${pkg}/${value}`;\n } else {\n result[key] = namespaceReferences(value, pkg);\n }\n }\n return result;\n }\n\n return node;\n}\n\n/**\n * Merge per-package manifests into a single Custom Elements Manifest.\n * Every module (and its internal references) is namespaced with its package so\n * paths stay unique and every declaration remains traceable to its component.\n *\n * When the sources declare more than one distinct `schemaVersion`, the merge\n * still proceeds (using the first source's version for the aggregate) but a\n * warning is emitted, since a mixed-schema aggregate may not be internally\n * consistent. The warning sink is injectable so the behavior can be unit-tested\n * without capturing global logger output; it defaults to `Logger.warn`.\n */\nexport function mergeManifests(\n sources: ManifestSource[],\n warn: (message: string) => void = Logger.warn,\n): Manifest {\n const modules: CemModule[] = [];\n\n for (const { pkg, manifest } of sources) {\n for (const module of manifest.modules ?? []) {\n const namespaced = namespaceReferences(module, pkg) as CemModule;\n // Only namespace a real path. A spec-violating module that omits `path`\n // would otherwise be stored as the literal \"@scope/pkg/undefined\"; leave\n // its (absent) path untouched rather than fabricating a bogus one.\n if (typeof module.path === \"string\") {\n namespaced.path = `${pkg}/${module.path}`;\n }\n modules.push(namespaced);\n }\n }\n\n const schemaVersions = new Set(\n sources.map((source) => source.manifest.schemaVersion).filter(Boolean),\n );\n if (schemaVersions.size > 1) {\n warn(\n `Merging mixed CEM schema versions: ${[...schemaVersions].join(\", \")}`,\n );\n }\n\n return {\n schemaVersion: sources[0]?.manifest.schemaVersion ?? \"1.0.0\",\n modules,\n };\n}\n", "import type { Manifest } from \"#utils/cem.js\";\nimport {\n type FetchManifestOptions,\n fetchManifest,\n type ManifestFetchResult,\n partitionOutcomes,\n} from \"#utils/fetchManifest.js\";\nimport { type ManifestSource, mergeManifests } from \"#utils/mergeManifests.js\";\n\n/** The aggregated manifest plus the bookkeeping a caller needs to report on it. */\nexport interface AggregateManifestResult {\n /** The merged, namespaced manifest of every source that resolved. */\n manifest: Manifest;\n /** The per-package manifests that went into the merge. */\n sources: ManifestSource[];\n /** Outcomes that yielded no manifest (genuine 404s and transient alike). */\n skipped: ManifestFetchResult[];\n /** The subset of skips that failed transiently (the aggregate is incomplete). */\n transientFailures: ManifestFetchResult[];\n}\n\n/**\n * Fetch each package's Custom Elements Manifest, merge the ones that resolve into\n * a single aggregated manifest, and report what was skipped. Extracted from the\n * `cem` command so the fetch \u2192 merge \u2192 partition pipeline is reusable (by init's\n * resolver) instead of trapped in the command action. Fetch options pass through\n * to {@link fetchManifest}: `cem` aggregates the canonical published manifests\n * (`preferLocal: false`); init aggregates the installed versions (the default).\n *\n * Never fails on its own \u2014 an empty `sources` array still returns a valid (empty)\n * manifest. The caller decides whether zero sources or a transient failure is an\n * error, since that policy differs per command.\n */\nexport async function buildAggregateManifest(\n packages: readonly string[],\n options: FetchManifestOptions = {},\n): Promise<AggregateManifestResult> {\n const outcomes = await Promise.all(\n packages.map((pkg) => fetchManifest(pkg, options)),\n );\n\n const sources: ManifestSource[] = [];\n for (const outcome of outcomes) {\n if (outcome.manifest) {\n sources.push({\n pkg: outcome.target,\n manifest: outcome.manifest as Manifest,\n });\n }\n }\n\n const { skipped, transientFailures } = partitionOutcomes(outcomes);\n return {\n manifest: mergeManifests(sources),\n sources,\n skipped,\n transientFailures,\n };\n}\n", "/**\n * `auro cem-check <path>` \u2014 the executable CEM contract (layer 1 of the CEM\n * contract-enforcement effort). Validates a `custom-elements.json` two ways:\n *\n * - **Static rules** ([rules.ts](#init/cem-check/rules.ts)) report what auro-cli's\n * defensive prune would otherwise drop in silence \u2014 the missing producer signal.\n * - **Generation smoke** ([smoke.ts](#init/cem-check/smoke.ts)) runs the real\n * editor-type builders + `tsc` against the CEM, the authoritative consumer-path\n * check.\n *\n * Exit contract: `0` when no `error`-severity findings; `1` when any error (or, with\n * `--strict`, any warning). `--json` emits the findings array to stdout for the\n * `/auro` pr/code-review skills to parse; human output goes to stderr so stdout\n * stays machine-parseable.\n *\n * @see docs/cem-contract-enforcement.md\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport { type CemFinding, runContractRules } from \"#init/cem-check/rules.js\";\nimport { runGenerationSmoke } from \"#init/cem-check/smoke.js\";\nimport { resolveComponents } from \"#init/resolver.js\";\nimport type { Manifest } from \"#utils/cem.js\";\nimport type { InstalledComponent } from \"#utils/detectInstalled.js\";\n\n/** Options accepted by the `cem-check` action. */\nexport interface CemCheckOptions {\n /** Emit the findings array as JSON on stdout instead of human text. */\n json?: boolean;\n /** Treat warnings as errors \u2014 any finding then fails the check. */\n strict?: boolean;\n}\n\n/**\n * Derive the package identity for the CEM at `cemPath` from the `package.json`\n * beside it (so import specifiers match what the package publishes). Falls back to\n * a placeholder when the CEM is checked in isolation \u2014 generation-smoke stubs the\n * imports regardless, so the placeholder never blocks the check.\n */\nfunction readSiblingPackageJson(cemPath: string): {\n pkg: string;\n version: string;\n} {\n try {\n const raw = readFileSync(\n join(dirname(resolve(cemPath)), \"package.json\"),\n \"utf-8\",\n );\n const parsed = JSON.parse(raw) as { name?: string; version?: string };\n return {\n pkg: typeof parsed.name === \"string\" ? parsed.name : \"cem-check-subject\",\n version: typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\",\n };\n } catch {\n return { pkg: \"cem-check-subject\", version: \"0.0.0\" };\n }\n}\n\n/** Render one finding as a single stderr line. */\nfunction formatFinding(finding: CemFinding): string {\n const mark = finding.severity === \"error\" ? \"\u2716\" : \"\u26A0\";\n const where = [finding.element, finding.path].filter(Boolean).join(\" \");\n const locator = where ? ` ${where}` : \"\";\n return `${mark} [${finding.rule}]${locator}: ${finding.message}`;\n}\n\n/** The manifest looked for when no path is given \u2014 resolved against the cwd. */\nconst DEFAULT_CEM_PATH = \"custom-elements.json\";\n\n/**\n * Validate the CEM at `cemPath` against the contract and exit per the exit\n * contract. `cemPath` defaults to `custom-elements.json` in the directory the\n * command runs from, so running `auro cem-check` inside a component repo just\n * works; pass an explicit path to check a CEM elsewhere. A read/parse failure\n * exits 1 before any rule runs (an unreadable CEM is itself a failure).\n */\nexport async function runCemCheck(\n cemPath: string = DEFAULT_CEM_PATH,\n options: CemCheckOptions = {},\n): Promise<void> {\n // In `--json` mode nothing may touch stdout but the JSON payload, so the ora\n // spinner (which emits cursor/frame control bytes) is suppressed entirely and\n // progress/errors go to stderr instead.\n const spinner = options.json\n ? null\n : ora(`Checking ${cemPath} against the CEM contract...`).start();\n\n const fail = (message: string): never => {\n if (spinner) {\n spinner.fail(message);\n } else {\n console.error(message);\n }\n process.exit(1);\n };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(resolve(cemPath), \"utf-8\"));\n } catch (error) {\n fail(`Could not read or parse ${cemPath}: ${(error as Error).message}`);\n }\n\n // Valid JSON that is not a CEM object (top-level `null`, an array, or a\n // primitive) parses without throwing but has no `.modules` \u2014 resolving it would\n // throw an uncaught `TypeError` deep in the builders. Reject it here so the\n // failure is a clean exit 1 with a clear message, matching the parse-error path.\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n fail(`Could not read or parse ${cemPath}: not a CEM object.`);\n }\n const manifest = parsed as Manifest;\n\n const { pkg, version } = readSiblingPackageJson(cemPath);\n const installed: InstalledComponent[] = [{ pkg, version, manifest }];\n const { components } = resolveComponents(installed);\n\n const findings: CemFinding[] = [\n ...runContractRules(manifest),\n ...runGenerationSmoke(components),\n ];\n\n const errors = findings.filter((f) => f.severity === \"error\");\n const warnings = findings.filter((f) => f.severity === \"warn\");\n const failed =\n errors.length > 0 || (Boolean(options.strict) && warnings.length > 0);\n\n if (options.json) {\n // No spinner was started in JSON mode, so stdout carries only the payload.\n process.stdout.write(`${JSON.stringify(findings, null, 2)}\\n`);\n if (failed) {\n process.exit(1);\n }\n return;\n }\n\n const summary = `${errors.length} error${errors.length === 1 ? \"\" : \"s\"}, ${warnings.length} warning${warnings.length === 1 ? \"\" : \"s\"}`;\n if (failed) {\n spinner?.fail(`CEM contract failed \u2014 ${summary}.`);\n } else if (warnings.length > 0) {\n spinner?.warn(`CEM contract passed with warnings \u2014 ${summary}.`);\n } else {\n spinner?.succeed(\"CEM contract clean \u2014 no violations.\");\n }\n\n // Errors first, then warnings; each on its own stderr line.\n for (const finding of [...errors, ...warnings]) {\n console.error(formatFinding(finding));\n }\n\n if (failed) {\n process.exit(1);\n }\n}\n\nexport default program\n .command(\"cem-check [path]\")\n .description(\n \"Validate a custom-elements.json against the CEM contract (structural + parseability rules and an end-to-end generation smoke). Defaults to ./custom-elements.json.\",\n )\n .option(\"--json\", \"Output the findings as a JSON array on stdout\", false)\n .option(\"--strict\", \"Treat warnings as errors (any finding fails)\", false)\n .action(runCemCheck);\n", "/**\n * Shared plumbing for the three per-target editor builders\n * (./htmlCustomData.ts, ./jsxTypes.ts, ./svelteTypes.ts). It owns the two seams\n * every builder needs \u2014 the resolved-tag lookup and the synthetic manifest the\n * community tools consume \u2014 plus the temp-dir shim that discards the files those\n * tools insist on writing. The builders stay pure functions of\n * `(components, resolvedTags)`; all the \"turn our model into their input\" glue\n * lives here so it is defined once and cannot drift between targets.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Tag-swap seam /\n * Class-import seam\" and build-order step 2.\n */\n\nimport { mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\nimport type { CemAttribute, CemDeclaration, Manifest } from \"#utils/cem.js\";\n\n/**\n * Blank out string/template-literal contents (replacing each with a space to keep\n * surrounding offsets stable) so a bracket **inside** a quoted string-literal type\n * member \u2014 e.g. the `>` in `'\">\" | \"none\"'`, a perfectly valid union \u2014 isn't\n * mistaken for an unbalanced delimiter. Shared by {@link hasBalancedDelimiters}\n * and the `cem-check` type rules so the *check* and the silent *prune* judge the\n * same text.\n */\nexport function withoutStringLiterals(text: string): string {\n return text.replace(/(['\"`])(?:\\\\.|(?!\\1)[\\s\\S])*\\1/gu, \" \");\n}\n\n/**\n * True when every bracket pair (`()[]{}<>`) in `text` is balanced, treating a\n * `=>` arrow as text rather than a generic close and ignoring brackets that live\n * **inside** string/template literals (a quoted `\">\"` is a valid literal member,\n * not an unbalanced close). The community JSX/Svelte tools splice a CEM\n * `type.text` verbatim into generated TypeScript, so a truncated or garbled type \u2014\n * e.g. auro-formkit's `auroDropdown-idAdded` event ships the type `\"Object<key\"` \u2014\n * yields output no parser (prettier/tsc) can read. A cheap balance check is enough\n * to catch these real-world defects without trying to be a TypeScript parser;\n * anything that fails it is dropped so the generator falls back to its default\n * handler/prop type.\n */\nexport function hasBalancedDelimiters(text: string): boolean {\n const closeToOpen: Record<string, string> = {\n \")\": \"(\",\n \"]\": \"[\",\n \"}\": \"{\",\n \">\": \"<\",\n };\n const stack: string[] = [];\n let prev = \"\";\n for (const ch of withoutStringLiterals(text)) {\n if (ch === \">\" && prev === \"=\") {\n // `=>` arrow \u2014 not a generic close.\n prev = ch;\n continue;\n }\n if (ch === \"(\" || ch === \"[\" || ch === \"{\" || ch === \"<\") {\n stack.push(ch);\n } else if (ch === \")\" || ch === \"]\" || ch === \"}\" || ch === \">\") {\n if (stack.pop() !== closeToOpen[ch]) {\n return false;\n }\n }\n prev = ch;\n }\n return stack.length === 0;\n}\n\n/**\n * Strip an entry's `type` when its `type.text` is present but malformed (see\n * {@link hasBalancedDelimiters}), leaving a well-formed entry the generators can\n * fall back to a default type for. A slightly looser type (`CustomEvent`,\n * `unknown`) beats an artifact no compiler accepts.\n */\nfunction withSafeType<T extends { type?: { text?: string } }>(entry: T): T {\n const text = entry.type?.text;\n if (typeof text === \"string\" && text !== \"\" && !hasBalancedDelimiters(text)) {\n const { type: _dropped, ...rest } = entry;\n return rest as T;\n }\n return entry;\n}\n\n/**\n * True when `attribute` merely reflects an internal (private or omitted) property\n * and carries no documentation of its own \u2014 e.g. auro-button's `data-hover` /\n * `data-active`, reflected from its `@private onHover` / `onActive` members. The\n * CEM analyzer derives an attribute from a property's `attribute:` / `reflect:`\n * options **independently of the property's `privacy`**, so `@private` (or\n * `@ignore`) on the source suppresses the *member* but still emits the\n * *attribute* as a public, description-less entry \u2014 which then leaks into editor\n * autocomplete as something a consumer might set, when it never should.\n *\n * We treat an attribute as such a leak when its backing member (`fieldName`) is\n * private/protected, or absent from the (pruned) member list \u2014 meaning the\n * property was intentionally omitted, e.g. dropped as `@private` \u2014 **and** the\n * attribute has no description. The no-description guard deliberately preserves\n * documented reflections a component *does* expose on purpose (e.g. a11y\n * `role` / `aria-*` attributes carrying real descriptions). An attribute with no\n * `fieldName` has no backing member to judge and is always kept.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 Risks/open questions, \"Private-reflected\n * attributes leak into autocomplete\".\n */\nexport function isPrivateReflection(\n attribute: CemAttribute,\n memberPrivacyByName: ReadonlyMap<string, string | undefined>,\n): boolean {\n const { fieldName, description } = attribute;\n if (typeof fieldName !== \"string\" || fieldName === \"\") {\n return false; // no backing member to judge \u2014 keep it\n }\n if (typeof description === \"string\" && description !== \"\") {\n return false; // deliberately documented \u2014 keep it\n }\n if (!memberPrivacyByName.has(fieldName)) {\n return true; // backing property omitted (e.g. pruned as @private)\n }\n const privacy = memberPrivacyByName.get(fieldName);\n return privacy === \"private\" || privacy === \"protected\";\n}\n\n/**\n * Normalise a CEM declaration into something the community JSX/Svelte/HTML\n * generators reliably accept:\n *\n * 1. Drop entries whose `name` is not a string from every named collection\n * (members, attributes, slots, events, css parts/properties). The schema\n * types these as required, but real manifests ship the odd nameless entry \u2014\n * e.g. auro-formkit's `auro-menu` has a `{ kind: \"field\", type, default }`\n * member with no `name` \u2014 and the tools call `member.name.startsWith(\"#\")`,\n * throwing mid-generation. A nameless member can't become a typed prop anyway.\n * (An empty-string name is kept \u2014 it is the valid default-slot name.)\n * 2. Drop a malformed `type.text` from members/attributes/events (see\n * {@link withSafeType}) so a garbled type can't produce unparseable output.\n * 3. Drop attributes that merely reflect a private/omitted property and carry no\n * description (see {@link isPrivateReflection}) so an internal reflection like\n * `data-hover` never leaks into editor autocomplete as a settable attribute.\n *\n * Everything else on the declaration is preserved verbatim.\n */\nfunction withNamedEntriesPruned(declaration: CemDeclaration): CemDeclaration {\n const hasName = (entry: { name?: unknown }): boolean =>\n typeof entry.name === \"string\";\n const members = declaration.members?.filter(hasName).map(withSafeType);\n // Backing-member privacy for the private-reflection guard, keyed by member\n // name. Built from the pruned members (nameless entries can't be a fieldName\n // target); an attribute whose fieldName is missing here reflects an omitted\n // property.\n const memberPrivacyByName = new Map<string, string | undefined>(\n (members ?? []).map((member) => [member.name, member.privacy]),\n );\n return {\n ...declaration,\n ...(members && { members }),\n ...(declaration.attributes && {\n attributes: declaration.attributes\n .filter(hasName)\n .filter(\n (attribute) => !isPrivateReflection(attribute, memberPrivacyByName),\n )\n .map(withSafeType),\n }),\n ...(declaration.slots && { slots: declaration.slots.filter(hasName) }),\n ...(declaration.events && {\n events: declaration.events.filter(hasName).map(withSafeType),\n }),\n ...(declaration.cssParts && {\n cssParts: declaration.cssParts.filter(hasName),\n }),\n ...(declaration.cssProperties && {\n cssProperties: declaration.cssProperties.filter(hasName),\n }),\n };\n}\n\n/** An editor artifact `auro init` writes: its project-root-relative path + body. */\nexport interface EditorArtifact {\n /**\n * The file to write, relative to the project root, using forward slashes\n * (e.g. `.vscode/auro.html-custom-data.json`). `init` splits on `/` to join it\n * onto the target OS's path separator.\n */\n filename: string;\n /** The complete file contents, newline-terminated. */\n contents: string;\n}\n\n/**\n * The tag a consumer actually registers for a component: its resolved\n * custom/prefixed tag when the registry provided one (keyed by the canonical\n * bare `auro-*` tag), else the canonical tag itself. Mirrors the generator's\n * `displayTag` so every target keys on the same resolved tag \u2014 never the bare\n * `auro-*` tag \u2014 and an absent entry simply means \"no custom registration\".\n */\nexport function resolvedTagFor(\n component: ResolvedComponent,\n resolvedTags: ReadonlyMap<string, string>,\n): string {\n return resolvedTags.get(component.tagName) ?? component.tagName;\n}\n\n/**\n * A map from each component's class name to the module specifier it should be\n * imported from \u2014 the component's `importPath` (package root for a standalone,\n * subpath export for a monorepo component). The JSX and Svelte tools take a\n * `componentTypePath` callback keyed by class name; this feeds it so the emitted\n * `import type { AuroButton } from \"\u2026\"` points at the installed package, not the\n * CEM's internal `src/auro-button.js` path.\n */\nexport function importPathsByClass(\n components: readonly ResolvedComponent[],\n): Map<string, string> {\n return new Map(components.map((c) => [c.declaration.name, c.importPath]));\n}\n\n/**\n * Assemble a Custom Elements Manifest the community tools can consume from our\n * flat `ResolvedComponent[]`: one `javascript-module` per component, its `path`\n * set to the component's `importPath` so any manifest-derived import resolves to\n * the installed package. Each declaration is emitted verbatim EXCEPT its\n * `tagName`, which is set via {@link resolvedTagFor} when `resolvedTags` is\n * given \u2014 the pre-swap seam the HTML and Svelte targets rely on (they have no\n * per-tag formatter hook). The JSX target omits `resolvedTags` (keeping the bare\n * `auro-*` tags) and swaps via the tool's `tagFormatter` instead.\n */\nexport function buildManifest(\n components: readonly ResolvedComponent[],\n resolvedTags?: ReadonlyMap<string, string>,\n): Manifest {\n return {\n schemaVersion: \"1.0.0\",\n modules: components.map((component) => {\n const declaration: CemDeclaration = withNamedEntriesPruned({\n ...component.declaration,\n tagName: resolvedTags\n ? resolvedTagFor(component, resolvedTags)\n : component.tagName,\n });\n return {\n kind: \"javascript-module\",\n path: component.importPath,\n declarations: [declaration],\n exports: [\n {\n kind: \"js\",\n name: declaration.name,\n declaration: {\n name: declaration.name,\n module: component.importPath,\n },\n },\n ],\n };\n }),\n };\n}\n\n/**\n * Run `fn` with a throwaway temp directory, always removing it afterward. The\n * three community tools each insist on writing their output to a file on disk;\n * the builders point them at this scratch dir and either use the string they\n * also return (HTML/JSX) or read the written file back (Svelte), so nothing ever\n * lands in the consumer's project except the artifact `init` writes itself.\n */\nexport function withTempDir<T>(fn: (dir: string) => T): T {\n const dir = mkdtempSync(join(tmpdir(), \"auro-editors-\"));\n try {\n return fn(dir);\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\n/** Guarantee exactly one trailing newline, matching the grounding-file convention. */\nexport function ensureTrailingNewline(contents: string): string {\n return contents.endsWith(\"\\n\") ? contents : `${contents}\\n`;\n}\n\n/**\n * The standard WAI-ARIA state/property attributes plus a `data-*` catch-all \u2014 the\n * accessibility/data global attributes the community JSX/Svelte tools omit from\n * their hardcoded `BaseProps`. Each generated element type\n * (`Partial<Props & BaseProps & BaseEvents>`) *replaces* the tag's intrinsic\n * element type, so any attribute absent here is flagged as unknown \u2014 without this\n * block `<auro-button aria-label=\"Save\" />` errors as an unknown prop.\n *\n * Value types mirror React's `AriaAttributes`; boolean-ish unions are inlined\n * (`boolean | \"true\" | \"false\"`) so the whole block is a single splice needing no\n * extra top-level alias. The `data-*` entry is a **template-literal** index\n * signature (not `[key: string]`), so it constrains only `data-*` keys and does\n * not force the tools' existing `style` / `ref` / `tabIndex` members to conform.\n * Lines are 2-space indented to match the tools' prettier output. `role` and\n * `tabindex` are not here \u2014 the JSX tool already emits them (as `role` / camelCase\n * `tabIndex`); {@link injectGlobalAttributes} prepends the lowercase Svelte forms\n * ({@link SVELTE_GLOBAL_MEMBERS}) for the Svelte target, whose `BaseProps` lacks them.\n */\nconst GLOBAL_ARIA_ATTRS = ` /** Identifies the currently active descendant of a composite widget. */\n \"aria-activedescendant\"?: string;\n /** Whether assistive technologies present all, or only parts of, changed regions. */\n \"aria-atomic\"?: boolean | \"true\" | \"false\";\n /** Whether inputting text triggers display of one or more predictions. */\n \"aria-autocomplete\"?: \"none\" | \"inline\" | \"list\" | \"both\";\n /** Defines a string value that labels the current element (braille). */\n \"aria-braillelabel\"?: string;\n /** Defines a human-readable, author-localized abbreviated role description (braille). */\n \"aria-brailleroledescription\"?: string;\n /** Whether an element is being modified and assistive technologies may wait. */\n \"aria-busy\"?: boolean | \"true\" | \"false\";\n /** The current \"checked\" state of checkboxes, radio buttons, and other widgets. */\n \"aria-checked\"?: boolean | \"false\" | \"mixed\" | \"true\";\n /** Defines the total number of columns in a table, grid, or treegrid. */\n \"aria-colcount\"?: number;\n /** Defines an element's column index or position within a table, grid, or treegrid. */\n \"aria-colindex\"?: number;\n /** A human-readable text alternative of aria-colindex. */\n \"aria-colindextext\"?: string;\n /** Defines the number of columns spanned by a cell or gridcell. */\n \"aria-colspan\"?: number;\n /** Identifies the element(s) whose contents or presence are controlled by this element. */\n \"aria-controls\"?: string;\n /** The element that represents the current item within a container or set. */\n \"aria-current\"?: boolean | \"false\" | \"true\" | \"page\" | \"step\" | \"location\" | \"date\" | \"time\";\n /** Identifies the element(s) that describes the object. */\n \"aria-describedby\"?: string;\n /** Defines a string value that describes or annotates the current element. */\n \"aria-description\"?: string;\n /** Identifies the element that provides a detailed, extended description. */\n \"aria-details\"?: string;\n /** Whether the element is perceivable but disabled, so not editable or operable. */\n \"aria-disabled\"?: boolean | \"true\" | \"false\";\n /** What functions can be performed when a dragged object is released. */\n \"aria-dropeffect\"?: \"none\" | \"copy\" | \"execute\" | \"link\" | \"move\" | \"popup\";\n /** Identifies the element that provides an error message for the object. */\n \"aria-errormessage\"?: string;\n /** Whether the element, or another grouping element it controls, is expanded. */\n \"aria-expanded\"?: boolean | \"true\" | \"false\";\n /** The next element(s) in an alternate reading order of content. */\n \"aria-flowto\"?: string;\n /** Whether an element is in a \"grabbed\" state in a drag-and-drop operation. */\n \"aria-grabbed\"?: boolean | \"true\" | \"false\";\n /** Indicates the availability and type of an interactive popup element. */\n \"aria-haspopup\"?: boolean | \"false\" | \"true\" | \"menu\" | \"listbox\" | \"tree\" | \"grid\" | \"dialog\";\n /** Whether the element is exposed to an accessibility API. */\n \"aria-hidden\"?: boolean | \"true\" | \"false\";\n /** Whether the entered value does not conform to the expected format. */\n \"aria-invalid\"?: boolean | \"false\" | \"true\" | \"grammar\" | \"spelling\";\n /** Keyboard shortcuts an author has implemented to activate or focus an element. */\n \"aria-keyshortcuts\"?: string;\n /** A string value that labels the current element. */\n \"aria-label\"?: string;\n /** Identifies the element(s) that labels the current element. */\n \"aria-labelledby\"?: string;\n /** Defines the hierarchical level of an element within a structure. */\n \"aria-level\"?: number;\n /** Indicates that an element will be updated, and how live updates are described. */\n \"aria-live\"?: \"off\" | \"assertive\" | \"polite\";\n /** Whether an element is modal when displayed. */\n \"aria-modal\"?: boolean | \"true\" | \"false\";\n /** Whether a text box accepts multiple lines of input or only a single line. */\n \"aria-multiline\"?: boolean | \"true\" | \"false\";\n /** Whether the user may select more than one item from the current selectable descendants. */\n \"aria-multiselectable\"?: boolean | \"true\" | \"false\";\n /** Whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */\n \"aria-orientation\"?: \"horizontal\" | \"vertical\";\n /** Identifies an element in order to define a visual, functional, or contextual relationship. */\n \"aria-owns\"?: string;\n /** A short hint intended to aid the user with data entry when the control has no value. */\n \"aria-placeholder\"?: string;\n /** The number or position of an item in the current set of listitems or treeitems. */\n \"aria-posinset\"?: number;\n /** The current \"pressed\" state of toggle buttons. */\n \"aria-pressed\"?: boolean | \"false\" | \"mixed\" | \"true\";\n /** Whether the element is not editable but is otherwise operable. */\n \"aria-readonly\"?: boolean | \"true\" | \"false\";\n /** What notifications the user agent triggers when the accessibility tree is modified. */\n \"aria-relevant\"?: \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text\" | \"text additions\" | \"text removals\";\n /** Whether user input is required on the element before a form may be submitted. */\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /** A human-readable, author-localized description for the role of an element. */\n \"aria-roledescription\"?: string;\n /** Defines the total number of rows in a table, grid, or treegrid. */\n \"aria-rowcount\"?: number;\n /** Defines an element's row index or position within a table, grid, or treegrid. */\n \"aria-rowindex\"?: number;\n /** A human-readable text alternative of aria-rowindex. */\n \"aria-rowindextext\"?: string;\n /** Defines the number of rows spanned by a cell or gridcell. */\n \"aria-rowspan\"?: number;\n /** The current \"selected\" state of various widgets. */\n \"aria-selected\"?: boolean | \"true\" | \"false\";\n /** Defines the number of items in the current set of listitems or treeitems. */\n \"aria-setsize\"?: number;\n /** Indicates if items in a table or grid are sorted in ascending or descending order. */\n \"aria-sort\"?: \"none\" | \"ascending\" | \"descending\" | \"other\";\n /** Defines the maximum allowed value for a range widget. */\n \"aria-valuemax\"?: number;\n /** Defines the minimum allowed value for a range widget. */\n \"aria-valuemin\"?: number;\n /** Defines the current value for a range widget. */\n \"aria-valuenow\"?: number;\n /** Defines the human-readable text alternative of aria-valuenow. */\n \"aria-valuetext\"?: string;\n /** Custom data-* attributes for the element. */\n [key: \\`data-\\${string}\\`]: string | number | boolean | null | undefined;\n`;\n\n/** Matches the opening of the tool-generated `BaseProps` block (JSX form is generic). */\nconst BASE_PROPS_OPEN = /(type BaseProps(?:<[^>]*>)? = \\{\\n)/;\n\n/**\n * Lowercase HTML global attributes the Svelte tool omits or React-cases, prepended\n * for the Svelte target only. Svelte markup uses the native lowercase attribute\n * names (`role`, `tabindex`), but the tool's `BaseProps` lacks `role` entirely and\n * spells tab order as React's camelCase `tabIndex` \u2014 so `<auro-button tabindex=\"0\">`\n * is flagged as an unknown prop. The JSX tool already emits both `role` and\n * `tabIndex`, so these are not prepended there (see {@link injectGlobalAttributes}).\n * `tabindex` is typed `number`, matching the tool's `tabIndex`; svelte2tsx coerces\n * the string literal in `tabindex=\"0\"` to it.\n */\nconst SVELTE_GLOBAL_MEMBERS =\n \" /** Defines the element's semantic role for accessibility APIs. */\\n\" +\n \" role?: string;\\n\" +\n \" /** The position of the element in the sequential keyboard navigation order. */\\n\" +\n \" tabindex?: number;\\n\";\n\n/**\n * Splice the standard ARIA / `data-*` global attributes ({@link GLOBAL_ARIA_ATTRS})\n * into a generated file's `BaseProps` block, immediately after its opening brace \u2014\n * mirroring how `NATIVE_DOM_EVENTS` is folded into `BaseEvents`. Pass\n * `svelteGlobals: true` for the Svelte target, whose `BaseProps` also lacks the\n * lowercase HTML globals ({@link SVELTE_GLOBAL_MEMBERS} \u2014 `role`, `tabindex`); the\n * JSX tool already emits those, so pass `svelteGlobals: false` there to avoid\n * duplicate members.\n *\n * Throws if the `BaseProps` opening is absent (e.g. an upstream reflow of the\n * community tool) rather than returning the string unchanged \u2014 a silent no-op\n * would ship element types that reject `aria-*`, so we surface the drift as a\n * loud, test-caught failure, matching `globalizeSvelteNamespace`'s convention.\n */\nexport function injectGlobalAttributes(\n contents: string,\n { svelteGlobals }: { svelteGlobals: boolean },\n): string {\n if (!BASE_PROPS_OPEN.test(contents)) {\n throw new Error(\n \"the JSX/Svelte generator no longer emits a recognizable `type BaseProps = {` \" +\n \"block; the global-attribute injection in manifest.ts must be updated to match.\",\n );\n }\n const block = `${svelteGlobals ? SVELTE_GLOBAL_MEMBERS : \"\"}${GLOBAL_ARIA_ATTRS}`;\n return contents.replace(BASE_PROPS_OPEN, `$1${block}`);\n}\n", "/**\n * The static half of `auro cem-check`: read the **raw** CEM declarations and\n * *report* what auro-cli's defensive prune ([manifest.ts](../editors/manifest.ts)\n * `buildManifest`) would otherwise drop in silence. The prune is a safety net that\n * keeps generation working but hides the defect from the component team; these\n * rules surface the same conditions as a producer-visible signal.\n *\n * Every rule that mirrors a prune reuses the **exact predicate the prune uses**\n * (`hasBalancedDelimiters`, `isPrivateReflection`), so the check and the silent\n * drop can never disagree \u2014 if the check passes, nothing gets pruned, and vice\n * versa.\n *\n * @see docs/cem-contract-enforcement.md \u2192 \"Build the contract as an executable\n * check\" (the static-validation rule set).\n */\n\nimport {\n hasBalancedDelimiters,\n isPrivateReflection,\n withoutStringLiterals,\n} from \"#init/editors/manifest.js\";\nimport type {\n CemAttribute,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n Deprecated,\n Manifest,\n} from \"#utils/cem.js\";\n\n/** Severity of a contract finding: `error` fails the check, `warn` is advisory. */\nexport type CemSeverity = \"error\" | \"warn\";\n\n/** One contract violation found in a CEM. */\nexport interface CemFinding {\n /** Stable rule id (e.g. `name-required`) for `--json` consumers and docs. */\n rule: string;\n /** `error` blocks the PR; `warn` is advisory unless `--strict`. */\n severity: CemSeverity;\n /** The registered element the finding belongs to (its tag), when applicable. */\n element?: string;\n /** A dotted locator within the declaration (e.g. `attributes[2].type.text`). */\n path?: string;\n /** Human-readable description of what is wrong and why it matters. */\n message: string;\n}\n\n/**\n * Attribute names conventionally backed by a fixed value set. When one is typed as\n * a bare `\"string\"` (no union) every value is accepted and nothing completes \u2014 the\n * `variant`-widening class of bug. Warn-only for now (curated set is deliberately\n * conservative); a future slice may make a core subset fatal once the\n * enumerated-attr scope is settled.\n *\n * @see docs/cem-contract-enforcement.md \u2192 Open questions, \"Union-rule scope\".\n */\nexport const ENUMERATED_ATTRS: ReadonlySet<string> = new Set([\n \"variant\",\n \"shape\",\n \"size\",\n \"type\",\n \"appearance\",\n]);\n\n/**\n * `type.text` spellings that carry no value information \u2014 a curated enumerated\n * attribute typed as any of these accepts every value and completes nothing. Covers\n * the lowercase TS `string`, the capitalized boxed `String` (valid TS, so\n * `type-not-typescript` ignores it \u2014 the shape most auro CEMs actually ship), and\n * `any`. Compared after trimming.\n */\nconst UNINFORMATIVE_STRING_TYPES: ReadonlySet<string> = new Set([\n \"string\",\n \"String\",\n \"any\",\n]);\n\n/**\n * Lowercase JS / JSDoc spellings that are **not** valid TypeScript types \u2014 the\n * `variant` \u2192 `Cannot find name 'array'` class seen across auro-formkit. Inlined\n * verbatim by the JSX/Svelte builders (`useCemTypes`), they make the emitted\n * `.d.ts` fail to compile. Value = the fix to suggest. (`string`/`number`/\n * `boolean`/`object`/`symbol`/`bigint`/`null`/`undefined`/`void`/`any`/`unknown`/\n * `never` are real lowercase TS types and are deliberately absent.)\n */\nconst INVALID_PRIMITIVE_TYPES: ReadonlyMap<string, string> = new Map([\n [\"array\", \"use `unknown[]`, `T[]`, or `Array<T>`\"],\n [\"function\", \"use `Function` or an explicit call signature `(\u2026) => \u2026`\"],\n]);\n\n/**\n * Generic built-ins that require a type argument \u2014 a **bare** `type.text` of one of\n * these (`Array`, not `Array<string>`) fails to compile (`Generic type 'Array<T>'\n * requires 1 type argument(s)`). Value = the shape to suggest.\n */\nconst BARE_GENERIC_TYPES: ReadonlyMap<string, string> = new Map([\n [\"Array\", \"Array<T>\"],\n [\"ReadonlyArray\", \"ReadonlyArray<T>\"],\n [\"Promise\", \"Promise<T>\"],\n [\"Map\", \"Map<K, V>\"],\n [\"WeakMap\", \"WeakMap<K, V>\"],\n [\"Set\", \"Set<T>\"],\n [\"WeakSet\", \"WeakSet<T>\"],\n [\"Record\", \"Record<K, V>\"],\n]);\n\n/**\n * Valid-but-uninformative object types: they compile, but expose no properties so\n * nothing completes in the editor \u2014 an advisory, not a generation break.\n */\nconst VAGUE_OBJECT_TYPES: ReadonlySet<string> = new Set([\"object\", \"Object\"]);\n\n/**\n * A bad token to scan for inside a `type.text`, with its compiled matcher and the\n * fix to suggest. The token is matched as a **whole word** so `myArray`/`ReadonlyArray`\n * never trip the `Array` rule; the trailing lookahead excludes legitimate uses:\n * - primitives (`array`/`function`) skip a following `:` \u2014 a property **key** named\n * `array` (`{ array: string }`) is valid, only a type **position** is not;\n * - generics skip a following `<` (already parameterised, e.g. `Array<string>`) and\n * `:` (a property key).\n */\ninterface BadTypeToken {\n token: string;\n re: RegExp;\n fix: string;\n}\n\nconst INVALID_PRIMITIVE_RULES: readonly BadTypeToken[] = [\n ...INVALID_PRIMITIVE_TYPES,\n].map(([token, fix]) => ({\n token,\n fix,\n re: new RegExp(`\\\\b${token}\\\\b(?!\\\\s*:)`, \"u\"),\n}));\n\nconst BARE_GENERIC_RULES: readonly BadTypeToken[] = [...BARE_GENERIC_TYPES].map(\n ([token, shape]) => ({\n token,\n fix: shape,\n re: new RegExp(`\\\\b${token}\\\\b(?!\\\\s*[<:])`, \"u\"),\n }),\n);\n\n/** Phrase the locator: `is \\`X\\`` when the whole type is the token, else `uses \\`X\\``. */\nfunction describeType(text: string, token: string): string {\n return text === token\n ? `\\`type.text\\` is \\`${token}\\``\n : `\\`type.text\\` (${JSON.stringify(text)}) uses \\`${token}\\``;\n}\n\n/**\n * Prose-level deprecation markers \u2014 a description/summary that *announces* the entry\n * is deprecated. Deliberately narrow: only a **leading** marker, a **bracketed** or\n * **bolded** `deprecated`, or an inline `@deprecated` tag counts. An incidental\n * mention (\"replaces the deprecated `onDark`\") is not at the start and is neither\n * bracketed nor bolded, so it never trips the rule.\n */\nconst DEPRECATION_MARKERS: readonly RegExp[] = [\n /^[\\s>*_~([-]*@?deprecated\\b/iu, // leading: \"DEPRECATED - use \u2026\", \"- @deprecated \u2026\"\n /[([]\\s*deprecated\\b/iu, // bracketed: \"(Deprecated) Notifies \u2026\", \"[deprecated]\"\n /\\*\\*\\s*deprecated\\b/iu, // bolded: \"**deprecated**\"\n /@deprecated\\b/iu, // inline JSDoc tag left in the prose\n];\n\n/** True when any supplied text carries a targeted prose deprecation marker. */\nfunction hasDeprecationMarker(...texts: (string | undefined)[]): boolean {\n return texts.some(\n (text) =>\n typeof text === \"string\" &&\n DEPRECATION_MARKERS.some((re) => re.test(text.trim())),\n );\n}\n\n/** True when a structural `deprecated` field is present (bare `true` or a message). */\nfunction isDeprecationFlagged(deprecated: Deprecated): boolean {\n return deprecated === true || isNonEmptyString(deprecated);\n}\n\n/**\n * Push a `deprecated-prose-unflagged` warning when a real class member (attribute /\n * property / field / method) reads as deprecated in its description or summary but\n * carries no structural `deprecated` field. Author-fixable: the analyzer honors an\n * `@deprecated` JSDoc tag on class members (v0.11.0), so adding the tag makes it emit\n * `deprecated` and clears the finding.\n */\nfunction checkMemberDeprecation(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { description?: string; summary?: string; deprecated?: Deprecated },\n): void {\n if (\n !isDeprecationFlagged(entry.deprecated) &&\n hasDeprecationMarker(entry.description, entry.summary)\n ) {\n findings.push({\n rule: \"deprecated-prose-unflagged\",\n severity: \"warn\",\n element,\n path,\n message:\n \"described as deprecated but missing the `deprecated` field \u2014 add an `@deprecated` JSDoc tag so the generated JSX/Svelte types surface it with a strikethrough. (VS Code HTML custom-data has no deprecation field, so vanilla-HTML editors won't show it.)\",\n });\n }\n}\n\n/**\n * Push a `deprecated-prose-unsupported` warning when an event or slot reads as\n * deprecated in prose but has no `deprecated` field. Unlike class members this is\n * **not** author-fixable with an `@deprecated` tag: the analyzer's inline\n * `@event`/`@fires`/`@slot` handling (v0.11.0) never emits `deprecated`, so editors\n * cannot surface it regardless of JSDoc. Reported under a distinct id so it can be\n * suppressed independently of the member rule.\n */\nfunction checkEventSlotDeprecation(\n findings: CemFinding[],\n element: string,\n kind: \"event\" | \"slot\",\n path: string,\n entry: { description?: string; summary?: string; deprecated?: Deprecated },\n): void {\n if (\n !isDeprecationFlagged(entry.deprecated) &&\n hasDeprecationMarker(entry.description, entry.summary)\n ) {\n findings.push({\n rule: \"deprecated-prose-unsupported\",\n severity: \"warn\",\n element,\n path,\n message: `this ${kind} reads as deprecated in prose, but the analyzer (v0.11.0) does not emit a \\`deprecated\\` field for inline \\`@${kind}\\` tags \u2014 editors cannot surface it. Track upstream or a mapping plugin; suppress this warning if the prose is intentional.`,\n });\n }\n}\n\n/**\n * Push a `deprecated-no-detail` warning when a `deprecated` field is a bare `true`\n * with no message \u2014 editors render a strikethrough but give consumers no migration\n * target. Low priority (a style nudge): prefer `@deprecated <what to use instead>`\n * over a bare `@deprecated`.\n */\nfunction checkDeprecationDetail(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { deprecated?: Deprecated },\n): void {\n if (entry.deprecated === true) {\n findings.push({\n rule: \"deprecated-no-detail\",\n severity: \"warn\",\n element,\n path,\n message:\n \"`deprecated` is set but carries no message \u2014 editors show a strikethrough with no migration target. Prefer `@deprecated <what to use instead>`.\",\n });\n }\n}\n\n/**\n * The registered custom elements in a manifest \u2014 the exact set the builders\n * process (mirrors `registeredElements` in [resolver.ts](../resolver.ts)): a\n * declaration counts only when it is `customElement` with a `tagName`.\n */\nfunction registeredElements(manifest: Manifest): CemDeclaration[] {\n return (manifest.modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName);\n}\n\n/** True when `value` is a usable string identity (name/tag) \u2014 non-empty string. */\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * Push a `name-required` error for every entry in `entries` whose `name` is not a\n * string. Empty-string names are allowed (the valid default-slot name), matching\n * the prune's `hasName = typeof entry.name === \"string\"` guard.\n */\nfunction checkNames(\n findings: CemFinding[],\n element: string,\n collection: string,\n entries: readonly { name?: unknown }[] | undefined,\n): void {\n entries?.forEach((entry, index) => {\n if (typeof entry.name !== \"string\") {\n findings.push({\n rule: \"name-required\",\n severity: \"error\",\n element,\n path: `${collection}[${index}].name`,\n message: `${collection}[${index}] has no string \\`name\\` \u2014 community generators call \\`.name.startsWith(\u2026)\\` and throw mid-generation.`,\n });\n }\n });\n}\n\n/**\n * Push a `type-parseable` error when `type.text` is a non-empty string with\n * unbalanced delimiters \u2014 the exact condition the prune's `withSafeType` strips,\n * which would otherwise splice unparseable TypeScript into the emitted `.d.ts`.\n */\nfunction checkType(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { type?: { text?: string } },\n): void {\n const text = entry.type?.text;\n if (typeof text === \"string\" && text !== \"\" && !hasBalancedDelimiters(text)) {\n findings.push({\n rule: \"type-parseable\",\n severity: \"error\",\n element,\n path: `${path}.type.text`,\n message: `\\`type.text\\` has unbalanced delimiters: ${JSON.stringify(text)} \u2014 the generated \\`.d.ts\\` would not parse.`,\n });\n }\n}\n\n/**\n * Push a finding when `type.text` contains a JS/JSDoc spelling that is not valid\n * TypeScript \u2014 a lowercase primitive (`array`, `function` \u2192 **error**) or a bare\n * generic missing its type argument (`Array`, `Promise`, \u2026 \u2192 **error**) \u2014 or, as a\n * whole, is a valid-but-uninformative object type (`object`/`Object` \u2192 **warn**).\n * These are the same defects the generation smoke catches, but reported with a\n * precise per-entry locator (`attributes[N].type.text`) instead of buried in bundled\n * `tsc` output.\n *\n * The bad-token scan matches whole words **inside** the type (so `\"Array | null\"`\n * and `\"string | array\"` are caught, not just the whole-string forms), after blanking\n * string literals \u2014 a quoted `\"array\"` member or a property key `{ array: string }`\n * is left untouched, keeping the rule free of false positives.\n */\nfunction checkPrimitiveType(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { type?: { text?: string } },\n): void {\n const raw = entry.type?.text;\n if (typeof raw !== \"string\") {\n return;\n }\n const text = raw.trim();\n if (text === \"\") {\n return;\n }\n const scannable = withoutStringLiterals(text);\n\n for (const { token, re, fix } of INVALID_PRIMITIVE_RULES) {\n if (re.test(scannable)) {\n findings.push({\n rule: \"type-not-typescript\",\n severity: \"error\",\n element,\n path: `${path}.type.text`,\n message: `${describeType(text, token)}, which is not a TypeScript type \u2014 ${fix}. The generated \\`.d.ts\\` would not compile.`,\n });\n return;\n }\n }\n\n for (const { token, re, fix } of BARE_GENERIC_RULES) {\n if (re.test(scannable)) {\n findings.push({\n rule: \"type-not-typescript\",\n severity: \"error\",\n element,\n path: `${path}.type.text`,\n message: `${describeType(text, token)}, a generic that requires a type argument \u2014 write \\`${fix}\\`. The generated \\`.d.ts\\` would not compile.`,\n });\n return;\n }\n }\n\n if (VAGUE_OBJECT_TYPES.has(text)) {\n findings.push({\n rule: \"type-imprecise\",\n severity: \"warn\",\n element,\n path: `${path}.type.text`,\n message: `\\`type.text\\` is \\`${text}\\` \u2014 a valid type, but it exposes no properties so nothing completes. Prefer an explicit shape (e.g. \\`{ id: string }\\`).`,\n });\n }\n}\n\n/**\n * True when the character at `index` is escaped \u2014 preceded by an odd number of\n * consecutive backslashes. `\"a\\\\\"` (two backslashes) leaves the following `\"`\n * unescaped; `\"a\\\"` (one backslash) escapes it.\n */\nfunction isEscaped(text: string, index: number): boolean {\n let backslashes = 0;\n for (let j = index - 1; j >= 0 && text[j] === \"\\\\\"; j--) {\n backslashes++;\n }\n return backslashes % 2 === 1;\n}\n\n/**\n * Split a `type.text` on its **top-level** `|` union separators, ignoring any `|`\n * inside quotes or nested `()[]{}<>` (so `\"a|b\" | Array<x | y>` yields two members,\n * not four). Arrow `=>` is not treated as a closing angle. Members are trimmed and\n * empties dropped.\n */\nfunction splitTopLevelUnion(text: string): string[] {\n const members: string[] = [];\n let depth = 0;\n let quote: string | null = null;\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (quote !== null) {\n // A quote closes the literal only when it isn't escaped; an even run of\n // preceding backslashes (incl. zero) means the quote itself is unescaped\n // (`\"a\\\\\"` \u2192 the `\"` closes), an odd run means it's escaped (`\"a\\\"`).\n if (ch === quote && !isEscaped(text, i)) {\n quote = null;\n }\n } else if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n quote = ch;\n } else if (ch === \"(\" || ch === \"[\" || ch === \"{\" || ch === \"<\") {\n depth++;\n } else if (ch === \")\" || ch === \"]\" || ch === \"}\") {\n depth--;\n } else if (ch === \">\") {\n if (text[i - 1] !== \"=\") depth--; // ignore the `>` of an arrow `=>`\n } else if (ch === \"|\" && depth === 0) {\n members.push(text.slice(start, i).trim());\n start = i + 1;\n }\n }\n members.push(text.slice(start).trim());\n return members.filter((member) => member !== \"\");\n}\n\n/** True when a union member is a string literal (`\"x\"` / `'x'` / `` `x` ``). */\nfunction isStringLiteralMember(member: string): boolean {\n return /^(['\"`]).*\\1$/u.test(member);\n}\n\n/**\n * Push a `union-widened-by-string` warning when a `type.text` unions one or more\n * string literals with a bare `string`/`String` \u2014 the bare member widens the whole\n * type back to `string`, so the literals stop validating and completing (the\n * auro-tabs `\"default\" | \"inverse\" | string` class). Warn-only: the emitted `.d.ts`\n * still compiles, it just loses the completion the literals were meant to give.\n */\nfunction checkWidenedUnion(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { type?: { text?: string } },\n): void {\n const text = entry.type?.text?.trim();\n if (typeof text !== \"string\" || !text.includes(\"|\")) {\n return;\n }\n const members = splitTopLevelUnion(text);\n const hasLiteral = members.some(isStringLiteralMember);\n const hasBareString = members.some((m) => m === \"string\" || m === \"String\");\n if (hasLiteral && hasBareString) {\n findings.push({\n rule: \"union-widened-by-string\",\n severity: \"warn\",\n element,\n path: `${path}.type.text`,\n message: `\\`type.text\\` (${JSON.stringify(text)}) unions string literals with a bare \\`string\\`, which widens the whole type back to \\`string\\` \u2014 drop the \\`string\\` member so the literals validate and complete.`,\n });\n }\n}\n\n/** True when a text field is absent or blank (nothing to drive an editor hover). */\nfunction isMissingText(text: string | undefined): boolean {\n return typeof text !== \"string\" || text.trim() === \"\";\n}\n\n/**\n * Push a `missing-description` warning when neither `description` nor `summary`\n * carries text \u2014 editors then show no hover documentation for the entry. Warn-only;\n * applied to the component and its attributes/events (the surfaces the IntelliSense\n * audit measures). `kind` names the surface in the message.\n */\nfunction checkDescription(\n findings: CemFinding[],\n element: string,\n kind: string,\n path: string | undefined,\n entry: { description?: string; summary?: string },\n): void {\n if (isMissingText(entry.description) && isMissingText(entry.summary)) {\n findings.push({\n rule: \"missing-description\",\n severity: \"warn\",\n element,\n ...(path === undefined ? {} : { path }),\n message: `${kind} has no description or summary \u2014 editors show no hover documentation for it. Add a JSDoc description.`,\n });\n }\n}\n\n/** Run every static contract rule over one registered element. */\nfunction checkDeclaration(findings: CemFinding[], decl: CemDeclaration): void {\n const element = isNonEmptyString(decl.tagName) ? decl.tagName : \"<unknown>\";\n\n // The declaration itself must carry a string class `name` (used as the export /\n // import-type identity); a non-string one breaks generation for this element.\n if (typeof decl.name !== \"string\") {\n findings.push({\n rule: \"name-required\",\n severity: \"error\",\n element,\n path: \"name\",\n message:\n \"registered element has no string `name` \u2014 its generated import/export identity is undefined.\",\n });\n }\n\n // Rule: missing-description (warn) \u2014 the component itself carries no hover docs.\n checkDescription(findings, element, \"this component\", undefined, decl);\n\n const members: readonly CemMember[] = decl.members ?? [];\n const attributes: readonly CemAttribute[] = decl.attributes ?? [];\n const events: readonly CemEvent[] = decl.events ?? [];\n const slots: readonly CemSlot[] = decl.slots ?? [];\n\n // Rule: name-required \u2014 every named collection.\n checkNames(findings, element, \"members\", members);\n checkNames(findings, element, \"attributes\", attributes);\n checkNames(findings, element, \"slots\", decl.slots);\n checkNames(findings, element, \"events\", events);\n checkNames(findings, element, \"cssParts\", decl.cssParts);\n checkNames(findings, element, \"cssProperties\", decl.cssProperties);\n\n // Rules: type-parseable (delimiters) + type-not-typescript / type-imprecise\n // (invalid or vague `type.text`) \u2014 members, attributes, events carry a `type.text`.\n members.forEach((m, i) => {\n checkType(findings, element, `members[${i}]`, m);\n checkPrimitiveType(findings, element, `members[${i}]`, m);\n checkMemberDeprecation(findings, element, `members[${i}]`, m);\n checkDeprecationDetail(findings, element, `members[${i}]`, m);\n });\n attributes.forEach((a, i) => {\n checkType(findings, element, `attributes[${i}]`, a);\n checkPrimitiveType(findings, element, `attributes[${i}]`, a);\n checkWidenedUnion(findings, element, `attributes[${i}]`, a);\n checkDescription(findings, element, \"attribute\", `attributes[${i}]`, a);\n checkMemberDeprecation(findings, element, `attributes[${i}]`, a);\n checkDeprecationDetail(findings, element, `attributes[${i}]`, a);\n });\n events.forEach((e, i) => {\n checkType(findings, element, `events[${i}]`, e);\n checkPrimitiveType(findings, element, `events[${i}]`, e);\n checkDescription(findings, element, \"event\", `events[${i}]`, e);\n checkEventSlotDeprecation(findings, element, \"event\", `events[${i}]`, e);\n checkDeprecationDetail(findings, element, `events[${i}]`, e);\n });\n slots.forEach((s, i) => {\n checkEventSlotDeprecation(findings, element, \"slot\", `slots[${i}]`, s);\n checkDeprecationDetail(findings, element, `slots[${i}]`, s);\n });\n\n // Backing-member privacy, keyed by name (built from raw members with a string\n // name \u2014 a nameless member can't be a `fieldName` target). Feeds both the\n // private-reflection warn below and mirrors the prune's own map.\n const memberPrivacyByName = new Map<string, string | undefined>(\n members\n .filter((m): m is CemMember => typeof m.name === \"string\")\n .map((m) => [m.name, m.privacy]),\n );\n\n attributes.forEach((attribute, index) => {\n // Rule: attribute-name-not-lowercase (warn) \u2014 the browser lowercases HTML\n // attribute names, so a camelCase `name` (e.g. `buttonHref`) never binds as\n // written. The JS property name lives in `fieldName`/the backing member; only\n // the reflected attribute `name` must be lowercase.\n if (isNonEmptyString(attribute.name) && /[A-Z]/u.test(attribute.name)) {\n findings.push({\n rule: \"attribute-name-not-lowercase\",\n severity: \"warn\",\n element,\n path: `attributes[${index}].name`,\n message: `attribute \\`${attribute.name}\\` has uppercase letters \u2014 HTML lowercases attribute names, so it never binds as written. Use \\`${attribute.name.toLowerCase()}\\` (the camelCase property name belongs in \\`fieldName\\`).`,\n });\n }\n\n // Rule: enumerated-union (warn) \u2014 a conventionally-enumerated attribute typed as\n // a bare uninformative string (`string`/`String`/`any`) accepts every value and\n // completes nothing.\n if (\n isNonEmptyString(attribute.name) &&\n ENUMERATED_ATTRS.has(attribute.name) &&\n UNINFORMATIVE_STRING_TYPES.has(attribute.type?.text?.trim() ?? \"\")\n ) {\n findings.push({\n rule: \"enumerated-union\",\n severity: \"warn\",\n element,\n path: `attributes[${index}].type.text`,\n message: `\\`${attribute.name}\\` is typed as bare \\`${JSON.stringify(attribute.type?.text ?? \"\")}\\` \u2014 an enumerated attribute should carry a string-literal union (e.g. \\`\"primary\" | \"secondary\"\\`) so values validate and complete.`,\n });\n }\n\n // Rule: private-reflection (warn) \u2014 an undescribed attribute reflected from a\n // private/omitted member leaks internal state into editor autocomplete.\n if (isPrivateReflection(attribute, memberPrivacyByName)) {\n findings.push({\n rule: \"private-reflection\",\n severity: \"warn\",\n element,\n path: `attributes[${index}]`,\n message: `\\`${attribute.name ?? \"<unnamed>\"}\\` reflects a private/omitted member and has no description \u2014 it leaks into editor autocomplete as a settable attribute (add a description if it is genuinely public).`,\n });\n }\n });\n}\n\n/**\n * Run the static contract rules over a parsed CEM, returning every finding (errors\n * and warnings). Pure and side-effect-free \u2014 the caller decides how findings map to\n * an exit code (see the `cem-check` command's exit contract).\n */\nexport function runContractRules(manifest: Manifest): CemFinding[] {\n const findings: CemFinding[] = [];\n\n // Rule: schema-version (warn) \u2014 a missing version means the generators can't\n // know which CEM shape they're reading.\n if (!isNonEmptyString(manifest.schemaVersion)) {\n findings.push({\n rule: \"schema-version\",\n severity: \"warn\",\n message:\n \"manifest has no `schemaVersion` \u2014 declare the CEM schema version it targets.\",\n });\n }\n\n for (const decl of registeredElements(manifest)) {\n checkDeclaration(findings, decl);\n }\n\n return findings;\n}\n", "/**\n * The authoritative half of `auro cem-check`: run auro-cli's **real** editor-type\n * builders against the candidate CEM and `tsc --noEmit` their output. Because it\n * exercises the exact consumer path (`buildJsxTypes` / `buildSvelteTypes` \u2192 the\n * emitted `.d.ts` \u2192 the pinned TypeScript compiler), a CEM change that breaks\n * generation surfaces here as a non-zero result \u2014 even when the static rules pass.\n *\n * The mechanism (temp project + stubs + `execFileSync(tsc)`) is the runtime\n * counterpart of the test smokes\n * ([init.editors.tsc-smoke.test.ts](../../../test/init.editors.tsc-smoke.test.ts),\n * [init.editors.svelte-event-collision.test.ts](../../../test/init.editors.svelte-event-collision.test.ts));\n * JSX and Svelte compile in separate throwaway projects, exactly as those tests do,\n * so neither artifact's global augmentations contaminate the other.\n *\n * @see docs/cem-contract-enforcement.md \u2192 \"End-to-end generation smoke\".\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport type { CemFinding } from \"#init/cem-check/rules.js\";\nimport { buildJsxTypes } from \"#init/editors/jsxTypes.js\";\nimport type { EditorArtifact } from \"#init/editors/manifest.js\";\nimport { withTempDir } from \"#init/editors/manifest.js\";\nimport { buildSvelteTypes } from \"#init/editors/svelteTypes.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\nconst require = createRequire(import.meta.url);\n/** The project's own pinned `tsc` \u2014 versioned with the CLI, no PATH dependency. */\nconst TSC = require.resolve(\"typescript/bin/tsc\");\n\n/** The global-JSX shim svelte2tsx output references (its only external symbol). */\nconst JSX_SHIM =\n \"declare namespace JSX {\\n\" +\n \" type Element = unknown;\\n\" +\n \" interface CSSProperties {}\\n\" +\n \"}\\n\";\n\n/** Turn an import specifier into a safe stub filename. */\nfunction stubFileFor(importPath: string): string {\n return `${importPath.replace(/[^a-zA-Z0-9]+/gu, \"_\")}.d.ts`;\n}\n\n/**\n * Parse the `import type { A, B as C } from \"path\"` statements the JSX artifact\n * emits into `path \u2192 {exported names}`. Driving the stubs off the artifact's real\n * imports (rather than only the component classes) means a cross-package type\n * reference the CEM points at another subpath \u2014 common in a monorepo like\n * auro-formkit \u2014 gets a matching stub too, instead of a false `no exported member`\n * failure. Only import statements at the start of a line are matched, so the\n * `import type { ScopedElements } \u2026` example inside the tool's doc comment is\n * ignored. Each name is stubbed as a real class (usable both as a value and, as the\n * artifact does with `BaseProps<AuroButton>`, as a type).\n */\nfunction importedNamesByPath(source: string): Map<string, Set<string>> {\n const byPath = new Map<string, Set<string>>();\n const re =\n /^[ \\t]*import\\s+(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*[\"']([^\"']+)[\"']/gmu;\n for (const match of source.matchAll(re)) {\n const names = match[1]\n .split(\",\")\n .map((entry) =>\n entry\n .trim()\n .split(/\\s+as\\s+/u)[0]\n .trim(),\n )\n .filter(Boolean);\n if (names.length === 0) {\n continue;\n }\n const set = byPath.get(match[2]) ?? new Set<string>();\n for (const name of names) {\n set.add(name);\n }\n byPath.set(match[2], set);\n }\n return byPath;\n}\n\n/** Write `tsconfig.json` into `cwd` with the shared smoke compiler options. */\nfunction writeTsconfig(\n cwd: string,\n include: string[],\n paths?: Record<string, string[]>,\n): void {\n writeFileSync(\n join(cwd, \"tsconfig.json\"),\n JSON.stringify(\n {\n compilerOptions: {\n noEmit: true,\n // The artifacts are themselves `.d.ts`, so only an un-skipped lib check\n // actually type-checks them.\n skipLibCheck: false,\n strict: false,\n // The condition under which the native-vs-CEM event collision surfaces\n // as a real error (handler params checked contravariantly).\n strictFunctionTypes: true,\n target: \"ES2020\",\n module: \"ESNext\",\n moduleResolution: \"bundler\",\n ...(paths && { baseUrl: \".\", paths }),\n lib: [\"ES2020\", \"DOM\"],\n types: [],\n },\n include,\n },\n null,\n 2,\n ),\n \"utf-8\",\n );\n}\n\n/** Write an artifact into `cwd`, creating its parent directory. */\nfunction writeArtifact(cwd: string, artifact: EditorArtifact): void {\n const dest = join(cwd, artifact.filename);\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, artifact.contents, \"utf-8\");\n}\n\n/**\n * Compile `artifact` under a throwaway `tsc` project. Returns `null` on success, or\n * one `error` finding carrying the compiler diagnostics on failure.\n */\nfunction compile(\n label: string,\n artifact: EditorArtifact,\n setup: (cwd: string) => void,\n): CemFinding | null {\n return withTempDir((cwd) => {\n writeArtifact(cwd, artifact);\n setup(cwd);\n try {\n execFileSync(process.execPath, [TSC, \"-p\", \"tsconfig.json\"], {\n cwd,\n stdio: \"pipe\",\n });\n return null;\n } catch (error) {\n const e = error as { stdout?: Buffer; stderr?: Buffer };\n const output = `${e.stdout?.toString() ?? \"\"}${e.stderr?.toString() ?? \"\"}`;\n return {\n rule: \"generation-smoke\",\n severity: \"error\" as const,\n element: label,\n message: `the generated ${label} \\`.d.ts\\` does not type-check \u2014 this CEM breaks the editor tooling:\\n${output.trim()}`,\n };\n }\n });\n}\n\n/**\n * Build the JSX and Svelte artifacts from `components` and type-check each. A build\n * throw or a `tsc` rejection becomes an `error` finding; a clean run returns `[]`.\n * Tags are passed through unchanged (identity map) \u2014 `cem-check` validates the CEM\n * as authored, without a consumer's tag overrides.\n */\nexport function runGenerationSmoke(\n components: readonly ResolvedComponent[],\n): CemFinding[] {\n if (components.length === 0) {\n return [];\n }\n const identityTags = new Map(components.map((c) => [c.tagName, c.tagName]));\n const findings: CemFinding[] = [];\n\n // JSX \u2014 the artifact emits `import type { <Class> } from \"<importPath>\"` (and, in a\n // monorepo, cross-package type references). Stub every imported name as a real class\n // via a `paths` mapping (deterministic, offline, independent of node_modules layout).\n // The names come from the artifact itself, so a cross-package reference resolves too\n // \u2014 the smoke validates the generated structure and inlined `type.text`, not whether\n // the real package happens to export that symbol (the shipped Auro packages ship\n // unresolvable class types anyway; the class import is unused under `useCemTypes`).\n try {\n const jsx = buildJsxTypes(components, identityTags);\n const importsByPath = importedNamesByPath(jsx.contents);\n const jsxFinding = compile(\"JSX\", jsx, (cwd) => {\n mkdirSync(join(cwd, \"stubs\"), { recursive: true });\n const paths: Record<string, string[]> = {};\n const include = [jsx.filename];\n for (const [importPath, names] of importsByPath) {\n const file = stubFileFor(importPath);\n writeFileSync(\n join(cwd, \"stubs\", file),\n `${[...names]\n .map(\n (name) => `export declare class ${name} extends HTMLElement {}`,\n )\n .join(\"\\n\")}\\n`,\n \"utf-8\",\n );\n paths[importPath] = [`./stubs/${file}`];\n include.push(`stubs/${file}`);\n }\n writeTsconfig(cwd, include, paths);\n });\n if (jsxFinding) {\n findings.push(jsxFinding);\n }\n } catch (error) {\n findings.push({\n rule: \"generation-build\",\n severity: \"error\",\n element: \"JSX\",\n message: `JSX type generation threw for this CEM: ${(error as Error).message}`,\n });\n }\n\n // Svelte \u2014 inlines CEM `type.text`, so it imports no package class; its only\n // external reference is svelte2tsx's global JSX namespace, satisfied by the shim.\n try {\n const svelte = buildSvelteTypes(components, identityTags);\n const svelteFinding = compile(\"Svelte\", svelte, (cwd) => {\n mkdirSync(join(cwd, \"stubs\"), { recursive: true });\n writeFileSync(join(cwd, \"stubs\", \"jsx-shim.d.ts\"), JSX_SHIM, \"utf-8\");\n writeTsconfig(cwd, [svelte.filename, \"stubs/jsx-shim.d.ts\"]);\n });\n if (svelteFinding) {\n findings.push(svelteFinding);\n }\n } catch (error) {\n findings.push({\n rule: \"generation-build\",\n severity: \"error\",\n element: \"Svelte\",\n message: `Svelte type generation threw for this CEM: ${(error as Error).message}`,\n });\n }\n\n return findings;\n}\n", "/**\n * Build the JSX / React type declarations (`auro-types/auro-jsx.d.ts`) that give\n * `.tsx` files tag + prop IntelliSense through the TypeScript language service.\n * Pure: `(components, resolvedTags) \u2192 EditorArtifact`.\n *\n * Two seams, both via the tool's own hooks (so the manifest keeps its canonical\n * `auro-*` tags here, unlike the HTML/Svelte pre-swap path):\n * - `tagFormatter` renames each canonical tag to the tag the consumer registers,\n * so the augmented `JSX.IntrinsicElements` / `react/jsx-runtime` keys match.\n * - `componentTypePath` routes the emitted class/event/reference `import type`\n * specifiers at the component's installed `importPath` (package root or monorepo\n * subpath), not the CEM's internal source path.\n *\n * Prop types come from `useCemTypes: true`, which inlines each attribute's CEM\n * `type.text` (real string-literal unions like `variant` \u2192\n * `\"primary\" | \"secondary\" | \u2026`). Without it the tool would type props as\n * `Component['prop']`, which resolves to `any` because the shipped Auro packages\n * ship unresolvable class declarations \u2014 so values would never complete/validate.\n * The class import the tool still emits is then unused but harmless.\n *\n * `includeDefaultDOMEvents: true` folds the tool's built-in native DOM event\n * handlers (`onClick`, `onFocus`, `onKeyDown`, \u2026 \u2014 all lib.dom event types) into\n * the shared `BaseEvents` type every element intersects. A CEM only declares a\n * component's *own* events, so without this native handlers are absent and\n * `<auro-button onFocus={\u2026} />` is flagged as an unknown prop. No collision with\n * a CEM `click` event: React camelCase `onClick` never clashes with the custom\n * event's `onclick`.\n *\n * The tool's `BaseProps` covers `role` and camelCase `tabIndex` but no `aria-*` or\n * `data-*` attributes, and the generated element type *replaces* the tag's intrinsic\n * type \u2014 so {@link injectGlobalAttributes} splices the standard ARIA / `data-*` set\n * into `BaseProps` (no tool option exposes it; `allowUnknownProps` would disable all\n * prop validation). `svelteGlobals: false` here \u2014 the tool already emits `role` and\n * `tabIndex`; the lowercase `role` / `tabindex` forms are Svelte-only.\n *\n * `generateJsxTypes` both writes a file to `outdir` and returns the source; we\n * discard the write (scratch dir) and keep the returned string.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 build-order step 2.\n */\n\nimport { generateJsxTypes } from \"@wc-toolkit/jsx-types\";\nimport { JSX_TYPES_FILENAME, JSX_TYPES_PATH } from \"#init/editors/layout.js\";\nimport {\n buildManifest,\n type EditorArtifact,\n ensureTrailingNewline,\n importPathsByClass,\n injectGlobalAttributes,\n withTempDir,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/**\n * Render the JSX `.d.ts` for the resolved component set. Returns the artifact's\n * project-root-relative path plus its contents; writing is the caller's job.\n */\nexport function buildJsxTypes(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact {\n // Canonical tags \u2014 the swap happens through `tagFormatter`, not the manifest.\n const manifest = buildManifest(components);\n const importPaths = importPathsByClass(components);\n\n const contents = withTempDir((outdir) =>\n // The tool types its manifest param as the strict `custom-elements-manifest`\n // Package; our loose Manifest is structurally compatible at runtime, so cast\n // to the tool's own parameter type rather than reshaping our model.\n generateJsxTypes(\n manifest as unknown as Parameters<typeof generateJsxTypes>[0],\n {\n outdir,\n fileName: JSX_TYPES_FILENAME,\n tagFormatter: (tagName) => resolvedTags.get(tagName) ?? tagName,\n componentTypePath: (name) => importPaths.get(name) ?? name,\n // Inline CEM `type.text` for props instead of `Component['prop']`, which\n // resolves to `any` against the packages' unresolvable class .d.ts.\n useCemTypes: true,\n // Fold native DOM event handlers (onClick/onFocus/\u2026) into BaseEvents; a\n // CEM only declares a component's own events, so without this they are\n // absent and native handlers flag as unknown props.\n includeDefaultDOMEvents: true,\n },\n ),\n );\n\n if (typeof contents !== \"string\") {\n throw new Error(\n \"JSX type generation returned no output for the resolved components.\",\n );\n }\n\n return {\n filename: JSX_TYPES_PATH,\n // The tool already emits `role` / `tabIndex`, so inject ARIA / data-* only.\n contents: ensureTrailingNewline(\n injectGlobalAttributes(contents, { svelteGlobals: false }),\n ),\n };\n}\n", "/**\n * Frozen locations and editor-wiring keys for the IntelliSense artifacts\n * `auro init` emits (PT-M2). This is the editor-target analogue of\n * ../layout.ts: it owns the input-INDEPENDENT shape only \u2014 the artifact\n * filenames, the directories they live in, and the settings/tsconfig keys the\n * command merges into \u2014 not the generated contents (the per-target builders in\n * ./htmlCustomData.ts, ./jsxTypes.ts, ./svelteTypes.ts fill those around these\n * constants, and must not re-derive them).\n *\n * FROZEN per docs/pt-m2-completion-plan.md \u2192 build-order step 1 (\"Freeze the\n * filenames/paths/wiring-key shapes\") and \"Frozen decisions \u2192 Artifact locations\n * + editor wiring\". Composite paths are DERIVED from their parts below so a single\n * edit can never leave the artifact path and its wiring entry disagreeing.\n *\n * @see test/fixtures/init/editors/ for the golden artifacts these pin.\n */\n\n// ---------------------------------------------------------------------------\n// VS Code HTML custom-data (HTML Language Server target)\n// ---------------------------------------------------------------------------\n\n/** Project-root directory VS Code reads editor data and settings from. */\nexport const VSCODE_DIR = \".vscode\";\n\n/** The VS Code settings file merged non-destructively for the HTML target. */\nexport const VSCODE_SETTINGS_FILENAME = \"settings.json\";\n\n/**\n * Auro-namespaced HTML custom-data artifact. The `auro.` prefix keeps it from\n * colliding with a team's own or another tool's custom-data file.\n */\nexport const HTML_CUSTOM_DATA_FILENAME = \"auro.html-custom-data.json\";\n\n/** The `settings.json` key that loads HTML custom-data files. */\nexport const HTML_CUSTOM_DATA_SETTINGS_KEY = \"html.customData\";\n\n/**\n * Path recorded in `settings.json` under {@link HTML_CUSTOM_DATA_SETTINGS_KEY}.\n * Per VS Code's rule this is **relative to the project root**, not to the settings\n * file, and always uses forward slashes (JSON + VS Code, every OS). Derived from\n * the dir + filename so it cannot drift from the file we actually write.\n */\nexport const HTML_CUSTOM_DATA_SETTINGS_ENTRY = `./${VSCODE_DIR}/${HTML_CUSTOM_DATA_FILENAME}`;\n\n/**\n * The HTML custom-data artifact's path **relative to the project root** \u2014 the\n * `filename` a builder returns and `init` writes. Same target as\n * {@link HTML_CUSTOM_DATA_SETTINGS_ENTRY} without the leading `./` (a path to\n * write vs. a settings-file entry). Forward slashes; `init` splits on `/` to join.\n */\nexport const HTML_CUSTOM_DATA_PATH = `${VSCODE_DIR}/${HTML_CUSTOM_DATA_FILENAME}`;\n\n// ---------------------------------------------------------------------------\n// VS Code CSS `::part()` snippets (CSS language-service target)\n// ---------------------------------------------------------------------------\n\n/**\n * Auro-namespaced VS Code snippets artifact. The `.code-snippets` extension is\n * what makes VS Code **auto-discover** it under {@link VSCODE_DIR} \u2014 unlike the\n * HTML custom-data file, no `settings.json` entry registers it, so this target\n * has no `_SETTINGS_KEY`/`_ENTRY` sibling. The `auro.` prefix keeps it from\n * colliding with a team's own project snippets.\n */\nexport const CSS_SNIPPETS_FILENAME = \"auro.code-snippets\";\n\n/**\n * The CSS snippets artifact's path **relative to the project root** \u2014 the\n * `filename` its builder returns and `init` writes. Derived from the dir +\n * filename (forward slashes) so it always lands in the auto-discovered\n * {@link VSCODE_DIR}. There is deliberately no settings entry to keep in sync.\n */\nexport const CSS_SNIPPETS_PATH = `${VSCODE_DIR}/${CSS_SNIPPETS_FILENAME}`;\n\n// ---------------------------------------------------------------------------\n// Framework TypeScript types (TS + Svelte language-server targets)\n// ---------------------------------------------------------------------------\n\n/**\n * Directory holding the generated framework `.d.ts` bundles, at the project root.\n *\n * The **non-dotted** name is deliberate and evidence-driven: TypeScript's default\n * `include` glob (`**` + `/*`, used when a project sets neither `include` nor\n * `files`) skips dot-prefixed directories, so a `.auro/` dir would be silently\n * invisible to default-include projects \u2014 whereas `auro-types/` is auto-picked-up\n * with zero tsconfig edits. See docs/pt-m2-completion-plan.md \u2192 resolved Risk\n * \"Consumer tsconfig variance\".\n */\nexport const FRAMEWORK_TYPES_DIR = \"auro-types\";\n\n/** JSX / React type declarations (augments `JSX.IntrinsicElements`). */\nexport const JSX_TYPES_FILENAME = \"auro-jsx.d.ts\";\n\n/** Svelte type declarations (augments Svelte element types). */\nexport const SVELTE_TYPES_FILENAME = \"auro-svelte.d.ts\";\n\n/**\n * The JSX `.d.ts` bundle's path **relative to the project root** \u2014 the `filename`\n * its builder returns and `init` writes. Derived from the types dir + filename so\n * it always lands where {@link TSCONFIG_INCLUDE_ENTRY} points. Forward slashes.\n */\nexport const JSX_TYPES_PATH = `${FRAMEWORK_TYPES_DIR}/${JSX_TYPES_FILENAME}`;\n\n/**\n * The Svelte `.d.ts` bundle's path **relative to the project root** \u2014 the\n * `filename` its builder returns and `init` writes. Derived from the types dir +\n * filename so it always lands where {@link TSCONFIG_INCLUDE_ENTRY} points.\n */\nexport const SVELTE_TYPES_PATH = `${FRAMEWORK_TYPES_DIR}/${SVELTE_TYPES_FILENAME}`;\n\n/** The `tsconfig.json` key that puts declaration files on the TypeScript program. */\nexport const TSCONFIG_INCLUDE_KEY = \"include\";\n\n/**\n * Entry appended to `tsconfig.json` `include` to pull in the framework types.\n * Equal to {@link FRAMEWORK_TYPES_DIR} by construction so the wiring can never\n * point somewhere other than where the files are written.\n */\nexport const TSCONFIG_INCLUDE_ENTRY = FRAMEWORK_TYPES_DIR;\n", "/**\n * Build the Svelte type declarations (`auro-types/auro-svelte.d.ts`) that give\n * Svelte markup tag + prop IntelliSense through the Svelte language server.\n * Pure: `(components, resolvedTags) \u2192 EditorArtifact`.\n *\n * The Svelte tool has no per-tag rename hook (no `tagFormatter`), so \u2014 like the\n * HTML target \u2014 the resolved tags are baked in by pre-swapping the manifest\n * ({@link buildManifest} with `resolvedTags`). We deliberately do NOT pass\n * `componentTypePath`: the tool types each attribute as `Component['field']` only\n * when that hook is set, else it inlines the CEM's own `type.text` \u2014 and the\n * class-indexed form resolves to `any` because the shipped Auro packages ship\n * unresolvable class declarations (auro-button's `dist/index.d.ts` imports from a\n * non-published `src/`; auro-formkit subpaths carry no `types` condition). Inlining\n * the CEM type keeps real string-literal unions (`variant` \u2192\n * `\"primary\" | \"secondary\" | \u2026`) so values actually complete/validate. Unlike the\n * other two tools this one returns `void` and only writes a file, so we point it\n * at a scratch dir and read the result back.\n *\n * A CEM only declares a component's *own* events, so native DOM event handlers\n * (`on:click`, `on:focus`, \u2026) would otherwise be absent from every element type.\n * Unlike the JSX tool there is no `includeDefaultDOMEvents` flag here \u2014 its only\n * lever is `globalEvents`, a string spliced verbatim into the shared\n * `type BaseEvents = { \u2026 }`. We pass {@link NATIVE_DOM_EVENTS} (the same 38-event\n * set the JSX tool injects, in Svelte-4 `on:` directive form, lib.dom types only)\n * so those handlers type-check on every element.\n *\n * The tool's `BaseProps` omits `role`, `tabindex`, `aria-*`, and `data-*` (it spells\n * tab order as React's camelCase `tabIndex`), and the generated element type\n * *replaces* the tag's intrinsic type \u2014 so `<auro-button aria-label=\"Save\" />` and\n * `<auro-button tabindex=\"0\" />` are flagged as unknown props.\n * {@link injectGlobalAttributes} (`svelteGlobals: true`, since Svelte's `BaseProps`\n * lacks even the lowercase `role` / `tabindex` HTML globals) splices those plus the\n * standard ARIA / `data-*` set into `BaseProps`; the tool exposes no option for it.\n *\n * Post-processing passes fix what the community tool can't express on its own:\n * {@link labelComponentMembers} (mark component-owned members so IntelliSense\n * distinguishes them from inherited global HTML attributes),\n * {@link addSvelte5EventHandlers} (Svelte 4 *and* 5 event syntax \u2014 this also\n * derives the Svelte-5 property form of the native events above),\n * {@link injectGlobalAttributes} (ARIA / `data-*` into `BaseProps`), and\n * {@link globalizeSvelteNamespace} (global vs module-scoped augmentation).\n *\n * @see docs/pt-m2-completion-plan.md \u2192 build-order step 2.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { generateSvelteTypes } from \"custom-element-svelte-integration\";\nimport {\n SVELTE_TYPES_FILENAME,\n SVELTE_TYPES_PATH,\n} from \"#init/editors/layout.js\";\nimport {\n buildManifest,\n type EditorArtifact,\n ensureTrailingNewline,\n injectGlobalAttributes,\n withTempDir,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/**\n * The exact module-scoped `svelteHTML` augmentation the community tool emits\n * (prettier-formatted, so this matches the bytes it writes). Because the\n * generated file has top-level `import`/`export`, it is a *module* \u2014 a plain\n * `declare namespace svelteHTML` inside it is module-scoped and never merges\n * into the global `svelteHTML` the Svelte language server actually reads, so\n * element completion silently does nothing. See {@link globalizeSvelteNamespace}.\n */\nconst MODULE_SCOPED_SVELTE_NAMESPACE = `declare namespace svelteHTML {\n // eslint-disable-next-line @typescript-eslint/no-empty-interface\n interface IntrinsicElements extends CustomElements {}\n}`;\n\n/** The global-scoped replacement that merges into the language server's `svelteHTML`. */\nconst GLOBAL_SVELTE_NAMESPACE = `declare global {\n namespace svelteHTML {\n // eslint-disable-next-line @typescript-eslint/no-empty-interface\n interface IntrinsicElements extends CustomElements {}\n }\n}`;\n\n/**\n * Native DOM event handlers to fold into the shared `BaseEvents` type via the\n * tool's `globalEvents` option (spliced verbatim inside `type BaseEvents = {\u2026}`).\n * Mirrors the 38 events `@wc-toolkit/jsx-types` injects with\n * `includeDefaultDOMEvents`, translated to real DOM event names in Svelte-4\n * `\"on:<name>\"` directive form; {@link addSvelte5EventHandlers} then derives the\n * Svelte-5 `\"on<name>\"` property sibling for each. All handler types are lib.dom\n * globals, so the artifact stays self-contained (no `svelte/elements` import).\n *\n * Ends with a trailing newline and 2-space indentation so it slots cleanly\n * between the tool's `type BaseEvents = {` and `};`.\n */\nconst NATIVE_DOM_EVENTS = `\n // Mouse events\n \"on:click\"?: (e: MouseEvent) => void;\n \"on:contextmenu\"?: (e: MouseEvent) => void;\n \"on:dblclick\"?: (e: MouseEvent) => void;\n \"on:mousedown\"?: (e: MouseEvent) => void;\n \"on:mouseenter\"?: (e: MouseEvent) => void;\n \"on:mouseleave\"?: (e: MouseEvent) => void;\n \"on:mousemove\"?: (e: MouseEvent) => void;\n \"on:mouseout\"?: (e: MouseEvent) => void;\n \"on:mouseover\"?: (e: MouseEvent) => void;\n \"on:mouseup\"?: (e: MouseEvent) => void;\n // Drag events\n \"on:drag\"?: (e: DragEvent) => void;\n \"on:dragend\"?: (e: DragEvent) => void;\n \"on:dragenter\"?: (e: DragEvent) => void;\n \"on:dragexit\"?: (e: DragEvent) => void;\n \"on:dragleave\"?: (e: DragEvent) => void;\n \"on:dragover\"?: (e: DragEvent) => void;\n \"on:dragstart\"?: (e: DragEvent) => void;\n \"on:drop\"?: (e: DragEvent) => void;\n // Keyboard events\n \"on:keydown\"?: (e: KeyboardEvent) => void;\n \"on:keyup\"?: (e: KeyboardEvent) => void;\n \"on:keypress\"?: (e: KeyboardEvent) => void;\n // Focus events\n \"on:focus\"?: (e: FocusEvent) => void;\n \"on:blur\"?: (e: FocusEvent) => void;\n // Form events\n \"on:change\"?: (e: Event) => void;\n \"on:input\"?: (e: Event) => void;\n \"on:submit\"?: (e: Event) => void;\n \"on:reset\"?: (e: Event) => void;\n // Scroll / wheel events\n \"on:scroll\"?: (e: UIEvent) => void;\n \"on:wheel\"?: (e: WheelEvent) => void;\n // Animation / transition events\n \"on:animationstart\"?: (e: AnimationEvent) => void;\n \"on:animationend\"?: (e: AnimationEvent) => void;\n \"on:animationiteration\"?: (e: AnimationEvent) => void;\n \"on:transitionend\"?: (e: TransitionEvent) => void;\n // Resource events\n \"on:load\"?: (e: Event) => void;\n \"on:error\"?: (e: Event) => void;\n // Clipboard events\n \"on:copy\"?: (e: ClipboardEvent) => void;\n \"on:cut\"?: (e: ClipboardEvent) => void;\n \"on:paste\"?: (e: ClipboardEvent) => void;\n`;\n\n/**\n * The community tool emits every event handler in Svelte 4 *directive* form only\n * \u2014 `\"on:${event.name}\"?: (e: CustomEvent<\u2026>) => void;` (its index.js:295). Svelte\n * 5 replaced the `on:event` directive with plain event-handler **properties**\n * (`<el onclick={\u2026}>`), so a Svelte 5 component that writes `onclick={\u2026}` finds no\n * matching member on the element type and the language server flags it.\n *\n * For each emitted `\"on:NAME\"?: <handler>;` line, emit an additional sibling\n * `\"onNAME\"?: <handler>;` carrying the identical `CustomEvent` signature, so both\n * the Svelte 4 directive and the Svelte 5 property form resolve against the same\n * event type. The `on` + verbatim-name convention matches what the JSX tool\n * already emits. Components with no events produce no matches and pass through\n * unchanged, so this is a safe no-op when there is nothing to augment.\n */\nconst SVELTE4_EVENT_HANDLER = /^([ \\t]*)\"on:([^\"]+)\"(\\?:.*=> void;)$/gmu;\n\nfunction addSvelte5EventHandlers(contents: string): string {\n return contents.replace(\n SVELTE4_EVENT_HANDLER,\n (_match, indent, name, handler) =>\n `${indent}\"on:${name}\"${handler}\\n${indent}\"on${name}\"${handler}`,\n );\n}\n\n/**\n * Resolve name collisions between a component's CEM members and the shared\n * `BaseProps`/`BaseEvents` blocks \u2014 ASYMMETRICALLY, because the right winner\n * differs for events vs global attributes.\n *\n * Every element is mapped as `Partial<<Name>Props & BaseProps & BaseEvents>`.\n * `BaseProps` carries the inherited global HTML attributes (`tabindex`, `id`,\n * `role`, \u2026) and {@link NATIVE_DOM_EVENTS} folds 38 native handlers into\n * `BaseEvents`. A TypeScript intersection of object types intersects SAME-NAMED\n * members, so any name a component redeclares collides with the base copy \u2014 and a\n * bare intersection breaks a legitimate value two different ways:\n *\n * \u2022 Events \u2014 a CEM event named like a native one (`input`, `click`, `change`,\n * `submit`, `load`, `error`, `scroll`, \u2026) is in both `<Name>Props` (typed\n * `(e: CustomEvent<\u2026>) => void`) and `BaseEvents` (typed `(e: Event | \u2026) =>\n * void`). The member becomes `((e: CustomEvent) => void) & ((e: Event) =>\n * void)`; a handler must satisfy BOTH, and the intended CustomEvent handler is\n * rejected by the native half (parameter contravariance).\n * \u2022 Attributes \u2014 a CEM attribute whose type differs from the injected global\n * (auro-button documents `tabindex` as a `string` for its `.tabindex` property\n * form, while the global `tabindex` is deliberately `number` \u2014 svelte2tsx\n * coerces the literal in `tabindex=\"0\"` to a number; see {@link\n * injectGlobalAttributes}). The member becomes `string & number` = `never`,\n * which under `Partial<>` is `undefined`, so even a valid `tabindex=\"0\"` is\n * rejected.\n *\n * The winner differs by kind:\n *\n * \u2022 For EVENTS the component wins \u2014 its CEM `CustomEvent` signature is strictly\n * more precise than the generic native handler, so `BaseEvents` yields the\n * colliding name: `Omit<BaseEvents, keyof <Name>Props>`.\n * \u2022 For global ATTRIBUTES the base wins \u2014 the global carries the framework's\n * coercion-aware typing (`tabindex: number`), which a CEM restating the\n * attribute as a raw `string` would only degrade, so the component's props\n * yield the colliding global names: `Omit<<Name>Props, keyof BaseProps>`.\n *\n * Net mapping:\n * `Partial<Omit<<Name>Props, keyof BaseProps> & BaseProps & Omit<BaseEvents, keyof <Name>Props>>`.\n * A component-only attribute (`variant`, `shape`, \u2026) is in neither base block, so\n * it is untouched; a component that redeclares nothing collides on nothing.\n */\nconst CUSTOM_ELEMENT_MAPPING =\n /^(\\s*\"[^\"]+\": Partial<)(\\w+)Props & BaseProps & BaseEvents(>;)$/gm;\n\nfunction overrideCollidingBaseMembers(contents: string): string {\n return contents.replace(\n CUSTOM_ELEMENT_MAPPING,\n (_match, head, name, tail) =>\n `${head}Omit<${name}Props, keyof BaseProps> & BaseProps &` +\n ` Omit<BaseEvents, keyof ${name}Props>${tail}`,\n );\n}\n\n/**\n * Matches one generated per-component props block \u2014\n * `type <ClassName>Props = {\\n \u2026members\u2026 \\n};` \u2014 capturing the class-name stem\n * (group 1, e.g. `AuroButton` from `AuroButtonProps`) and the block body (group\n * 2). The trailing `\\n};` at column 0 bounds the block; member lines are indented\n * so the non-greedy body stops at the first closing brace. This also matches the\n * fixed `BaseProps` block, which {@link labelComponentMembers} filters out by\n * class name (`BaseEvents` has no `Props` suffix, so it never matches).\n */\nconst PROPS_BLOCK = /^type (\\w+)Props = \\{\\n([\\s\\S]*?)\\n\\};$/gm;\n\n/** Start of every single-line JSDoc the tool emits for a component member. */\nconst MEMBER_JSDOC_OPEN = /\\/\\*\\* /g;\n\n/**\n * The Svelte language server flattens each element's type\n * (`Partial<<Name>Props & BaseProps & BaseEvents>`) into one alphabetized\n * completion list with identical icons, so a component's own members (`variant`,\n * `shape`) are visually indistinguishable from the inherited global HTML\n * attributes (`id`, `class`, `title`). We can't change the icon or grouping (the\n * language server owns those), but we *can* prefix a marker into the JSDoc that\n * shows in the hover/completion docs pane.\n *\n * For every member inside a per-component `type <Name>Props` block, prefix\n * `\u3010<label>\u3011 ` onto its JSDoc. `<label>` is the tag the consumer actually\n * writes in markup \u2014 the registered tag when the project renamed it, falling back\n * to the component class name when it kept the default `auro-*` tag (so the marker\n * never just echoes the obvious default). `markerByClass` is keyed by class name\n * (`declaration.name`), which is exactly the `<Name>` stem of each props block.\n * Blocks whose stem is not a known component \u2014 `BaseProps` \u2014 are returned\n * untouched, so inherited attributes stay unmarked and remain the visual \"other\"\n * group. Members without JSDoc (e.g. the Svelte 5 `\"onNAME\"` handler sibling) have\n * nothing to prefix and pass through unchanged.\n */\nfunction labelComponentMembers(\n contents: string,\n markerByClass: ReadonlyMap<string, string>,\n): string {\n return contents.replace(PROPS_BLOCK, (whole, className, body) => {\n const label = markerByClass.get(className);\n if (label === undefined) {\n return whole;\n }\n const marked = body.replace(MEMBER_JSDOC_OPEN, `/** \u3010${label}\u3011 `);\n return `type ${className}Props = {\\n${marked}\\n};`;\n });\n}\n\n/**\n * Build the class-name \u2192 marker-label map {@link labelComponentMembers} consumes.\n * The label is the registered tag (what the consumer writes in markup); when the\n * project kept the component's default `auro-*` tag we fall back to the class name\n * rather than repeat the obvious default. Keyed by `declaration.name` to match the\n * `<Name>Props` block stems the tool emits.\n */\nfunction markerLabelsByClass(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): Map<string, string> {\n return new Map(\n components.map((component) => {\n const defaultTag = component.tagName;\n const resolvedTag = resolvedTags.get(defaultTag) ?? defaultTag;\n const label =\n resolvedTag === defaultTag ? component.declaration.name : resolvedTag;\n return [component.declaration.name, label];\n }),\n );\n}\n\n/**\n * Wrap the tool's module-scoped `declare namespace svelteHTML` in `declare\n * global { \u2026 }` so it augments the global `svelteHTML` namespace the Svelte\n * language server reads \u2014 the same pattern auro-cli's own per-component\n * `addDtsExportsPlugin` already emits. Without this the augmentation is inert in\n * a module file and Svelte element completion never appears.\n *\n * Throws if the expected block is absent (e.g. an upstream reflow of\n * `custom-element-svelte-integration`) rather than returning the string\n * unchanged \u2014 a silent no-op would ship the broken module-scoped form, so we\n * surface the drift as a loud, test-caught failure instead.\n */\nfunction globalizeSvelteNamespace(contents: string): string {\n if (!contents.includes(MODULE_SCOPED_SVELTE_NAMESPACE)) {\n throw new Error(\n \"custom-element-svelte-integration no longer emits the expected \" +\n \"`declare namespace svelteHTML` block; the global-augmentation rewrite \" +\n \"in svelteTypes.ts must be updated to match the new output.\",\n );\n }\n return contents.replace(\n MODULE_SCOPED_SVELTE_NAMESPACE,\n GLOBAL_SVELTE_NAMESPACE,\n );\n}\n\n/**\n * Render the Svelte `.d.ts` for the resolved component set. Returns the\n * artifact's project-root-relative path plus its contents; writing is the\n * caller's job.\n */\nexport function buildSvelteTypes(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact {\n const manifest = buildManifest(components, resolvedTags);\n const markerByClass = markerLabelsByClass(components, resolvedTags);\n\n const contents = withTempDir((outdir) => {\n generateSvelteTypes(manifest, {\n outdir,\n fileName: SVELTE_TYPES_FILENAME,\n hideLogs: true,\n // Fold native DOM event handlers into the shared BaseEvents type; a CEM\n // only declares a component's own events, so without this native handlers\n // are absent. addSvelte5EventHandlers derives the Svelte-5 property form.\n globalEvents: NATIVE_DOM_EVENTS,\n // No `componentTypePath`: inline the CEM's `type.text` (real unions) instead\n // of `Component['field']`, which resolves to `any` against the packages'\n // unresolvable class .d.ts. See the module header for the full rationale.\n });\n return readFileSync(join(outdir, SVELTE_TYPES_FILENAME), \"utf-8\");\n });\n\n return {\n filename: SVELTE_TYPES_PATH,\n contents: ensureTrailingNewline(\n globalizeSvelteNamespace(\n overrideCollidingBaseMembers(\n injectGlobalAttributes(\n addSvelte5EventHandlers(\n labelComponentMembers(contents, markerByClass),\n ),\n // Svelte's BaseProps lacks the lowercase `role` / `tabindex` HTML\n // globals too, so add them alongside the ARIA set.\n { svelteGlobals: true },\n ),\n ),\n ),\n ),\n };\n}\n", "import { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport type { Manifest } from \"#utils/cem.js\";\nimport {\n fetchManifest,\n type ManifestFetchResult,\n} from \"#utils/fetchManifest.js\";\n\n/** A component package resolved from the current project's `node_modules`. */\nexport interface InstalledComponent {\n /** The installed npm package, e.g. `@aurodesignsystem/auro-button`. */\n pkg: string;\n /** The installed version, read from the package's own `package.json`. */\n version: string;\n /** The package's parsed `custom-elements.json`. */\n manifest: Manifest;\n}\n\n/**\n * Pick the locally installed components out of a set of manifest fetch outcomes.\n * Pure and side-effect-free: an outcome counts as installed only when it was\n * resolved from local `node_modules` (`source: \"local\"`) and carries both a\n * parsed manifest and a version. Shared by {@link detectInstalled} and the\n * `context` command so the \"scan node_modules + capture the installed version\"\n * rule lives in exactly one place.\n */\nexport function installedFromOutcomes(\n outcomes: readonly ManifestFetchResult[],\n): InstalledComponent[] {\n const installed: InstalledComponent[] = [];\n for (const outcome of outcomes) {\n if (outcome.source === \"local\" && outcome.manifest && outcome.version) {\n installed.push({\n pkg: outcome.target,\n version: outcome.version,\n manifest: outcome.manifest as Manifest,\n });\n }\n }\n return installed;\n}\n\n/**\n * Detect which Auro component packages are installed in the current directory's\n * `node_modules`, capturing each one's installed version and manifest. Local\n * reads only \u2014 never hits the network \u2014 so the result reflects exactly what the\n * project has installed (the version-pinned set `auro init` grounds against).\n * Defaults to the curated candidate list; pass an explicit set to scope the scan.\n */\nexport async function detectInstalled(\n packages: readonly string[] = AURO_COMPONENT_PACKAGES,\n): Promise<InstalledComponent[]> {\n const outcomes = await Promise.all(\n packages.map((pkg) => fetchManifest(pkg, { allowNetwork: false })),\n );\n return installedFromOutcomes(outcomes);\n}\n", "/**\n * The single data module PT-M1 isolates behind one seam (per the ticket): detect\n * the installed Auro packages, resolve each at its installed version, and\n * normalise both single-component and aggregated multi-component (monorepo) CEMs\n * into one flat `ResolvedComponent[]`. Everything downstream \u2014 tag resolution\n * (`registry.ts`) and generation (`generator.ts`) \u2014 consumes that flat list, so a\n * Phase-2 shared core can replace this module without touching the generator.\n */\n\nimport type { CemDeclaration, Manifest } from \"#utils/cem.js\";\nimport {\n detectInstalled,\n type InstalledComponent,\n} from \"#utils/detectInstalled.js\";\n\n/** One installed Auro custom element, normalised for grounding-file generation. */\nexport interface ResolvedComponent {\n /** The npm package that ships this component. */\n pkg: string;\n /**\n * The installed version of {@link pkg}. A multi-component package shares one\n * version across every component it ships.\n */\n version: string;\n /**\n * The component's canonical, bare `auro-*` tag as declared in the manifest \u2014\n * the stable identity used as the `auro.config.json` key and the subpath\n * segment. Any custom/prefixed tag is applied later by the generator using\n * `registry.ts` output; the resolver never renames a component.\n */\n tagName: string;\n /** The element's Custom Elements Manifest declaration (its full API surface). */\n declaration: CemDeclaration;\n /**\n * The module specifier to import this component from: the package root for a\n * standalone package (`@aurodesignsystem/auro-button`), or the per-component\n * subpath export for a multi-component package\n * (`@aurodesignsystem/auro-formkit/auro-input`).\n */\n importPath: string;\n /** True when {@link pkg} ships more than one registered element. */\n isMonorepo: boolean;\n}\n\n/** A tag registered by more than one installed package (a dedupe conflict). */\nexport interface DuplicateTag {\n /** The canonical bare `auro-*` tag registered by multiple packages. */\n tagName: string;\n /** The installed packages that all register {@link tagName}, in resolve order. */\n packages: string[];\n}\n\n/** The normalised component set plus any cross-package tag conflicts. */\nexport interface ResolveResult {\n /**\n * Every installed component, flattened across single- and multi-component\n * packages, in package-detection order then manifest-declaration order.\n */\n components: ResolvedComponent[];\n /**\n * Tags registered by more than one installed package \u2014 the legacy-standalone\n * vs monorepo overlap the generator warns on (never silently drops).\n */\n duplicates: DuplicateTag[];\n}\n\n/**\n * Pull every registered custom element out of a single package's manifest. A\n * declaration counts only when it is a real registered element \u2014 `customElement`\n * with a `tagName` \u2014 since an internal base class can be `customElement: true`\n * yet carry no tag. Module and declaration order is preserved for deterministic\n * output.\n */\nfunction registeredElements(manifest: Manifest): CemDeclaration[] {\n return (manifest.modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName);\n}\n\n/**\n * Normalise the installed packages into a flat component list, deriving each\n * component's import specifier and flagging any tag registered by more than one\n * package. Pure and side-effect-free \u2014 the network/fs work is done upstream by\n * {@link detectInstalled} \u2014 so it can be unit-tested against synthetic manifests.\n *\n * A package is treated as multi-component (\"monorepo\") when its manifest registers\n * more than one element; each of those components imports via its subpath export\n * (`<pkg>/<tag>`, e.g. `@aurodesignsystem/auro-formkit/auro-input`), while a\n * standalone package imports from its root. The subpath segment is the component's\n * canonical bare `auro-*` tag, which matches Auro's per-component export names.\n *\n * A tag registered by more than one installed package (the legacy standalone vs\n * `auro-formkit` monorepo overlap) is **grounded once** \u2014 the first-detected\n * package wins \u2014 and every colliding package is recorded in `duplicates` so the\n * command warns which packages the tag came from. Detection order follows the\n * installed order, so the winner is deterministic.\n */\nexport function resolveComponents(\n installed: readonly InstalledComponent[],\n): ResolveResult {\n const components: ResolvedComponent[] = [];\n // tag -> the packages that register it, insertion-ordered, for duplicate\n // detection. A package appears at most once per tag.\n const owningPackages = new Map<string, string[]>();\n // Tags already emitted to `components`, so a duplicate tag is grounded once.\n const grounded = new Set<string>();\n\n for (const { pkg, version, manifest } of installed) {\n const elements = registeredElements(manifest);\n // The import shape is per-package: >1 registered element means the package\n // ships per-component subpath exports (an aggregated monorepo CEM).\n const isMonorepo = elements.length > 1;\n for (const declaration of elements) {\n const tagName = declaration.tagName as string;\n\n // Record every package that registers this tag (for the dedupe warning),\n // before deciding whether to ground it.\n const owners = owningPackages.get(tagName);\n if (owners) {\n if (!owners.includes(pkg)) {\n owners.push(pkg);\n }\n } else {\n owningPackages.set(tagName, [pkg]);\n }\n\n // Ground each canonical tag exactly once: the first package to register it\n // wins. A later package's registration is flagged as a duplicate (above),\n // never grounded a second time.\n if (grounded.has(tagName)) {\n continue;\n }\n grounded.add(tagName);\n components.push({\n pkg,\n version,\n tagName,\n declaration,\n importPath: isMonorepo ? `${pkg}/${tagName}` : pkg,\n isMonorepo,\n });\n }\n }\n\n const duplicates: DuplicateTag[] = [];\n for (const [tagName, packages] of owningPackages) {\n if (packages.length > 1) {\n duplicates.push({ tagName, packages });\n }\n }\n\n return { components, duplicates };\n}\n\n/**\n * Detect the installed Auro packages in the current project and normalise them\n * into a {@link ResolveResult}. Delegates detection to {@link detectInstalled}\n * (local-only, version-pinned) and normalisation to {@link resolveComponents}.\n * Pass an explicit package set to scope the scan; defaults to the curated\n * candidate list.\n */\nexport async function resolveInstalled(\n packages?: readonly string[],\n): Promise<ResolveResult> {\n const installed = await detectInstalled(packages);\n return resolveComponents(installed);\n}\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport {\n type AuroComponent,\n buildAuroContext,\n renderComponentRows,\n STATIC_COMPONENTS,\n} from \"#static/auroContext.js\";\nimport { clean, type Manifest } from \"#utils/cem.js\";\nimport { installedFromOutcomes } from \"#utils/detectInstalled.js\";\nimport { fetchManifest } from \"#utils/fetchManifest.js\";\nimport { checkOutdated, renderOutdatedBanner } from \"#utils/outdated.js\";\n\n/**\n * Build the Component Reference body, starting from the curated component set\n * and overriding each component's package and description with Custom Elements\n * Manifest data \u2014 preferring a locally installed copy, falling back to unpkg.\n * Seeding from the curated set guarantees every component is listed even before\n * it publishes a CEM, while live data keeps the descriptions of those that do\n * current. Returns the assembled table body, how many components were enriched,\n * and the installed version of every package resolved from local node_modules.\n */\nasync function buildComponentTable(allowNetwork: boolean): Promise<{\n rows: string;\n resolved: number;\n enriched: number;\n local: Map<string, string>;\n}> {\n // Curated set is the base \u2014 keyed by tag, insertion order preserved so the\n // reference stays stable and no component is ever dropped.\n const byTag = new Map<string, AuroComponent>();\n for (const component of STATIC_COMPONENTS) {\n byTag.set(component.tag, { ...component });\n }\n\n const outcomes = await Promise.all(\n AURO_COMPONENT_PACKAGES.map((pkg) => fetchManifest(pkg, { allowNetwork })),\n );\n\n // The installed-version map is the shared \"detect installed\" concern \u2014 derive\n // it from the same outcomes so the rule lives in one place (detectInstalled).\n const local = new Map<string, string>(\n installedFromOutcomes(outcomes).map((component) => [\n component.pkg,\n component.version,\n ]),\n );\n let resolved = 0;\n let enriched = 0;\n for (const outcome of outcomes) {\n if (!outcome.manifest) {\n continue;\n }\n // A manifest was fetched (local or unpkg) regardless of whether any of its\n // declarations document a description \u2014 this is what distinguishes \"found\n // nothing\" from \"found manifests that happen to be undocumented\".\n resolved += 1;\n // Only real registered elements \u2014 a declaration can be customElement: true\n // yet be an internal base class with no tagName.\n const declarations = ((outcome.manifest as Manifest).modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName);\n for (const decl of declarations) {\n const tag = decl.tagName as string;\n const liveDescription = clean(decl.summary || decl.description);\n const existing = byTag.get(tag);\n byTag.set(tag, {\n tag,\n pkg: outcome.target,\n description: liveDescription || existing?.description || \"\",\n });\n if (liveDescription) {\n enriched += 1;\n }\n }\n }\n\n return {\n rows: renderComponentRows([...byTag.values()]),\n resolved,\n enriched,\n local,\n };\n}\n\n/**\n * Compare each locally installed package against the latest published release\n * and report any that are behind. Best-effort and network-dependent \u2014 advisory\n * output goes to stderr so it never pollutes the context document on stdout.\n */\nasync function reportOutdated(local: Map<string, string>): Promise<void> {\n const spinner = ora(\"Checking for newer component releases...\").start();\n const outdated = await checkOutdated(local);\n\n if (outdated.length === 0) {\n spinner.succeed(\"All installed Auro components are on the latest release.\");\n return;\n }\n\n // Stop the spinner without its own icon/line \u2014 the banner below carries the\n // warning, and a leftover spinner line would dilute it.\n spinner.stop();\n // stderr \u2014 keep the generated document (stdout) clean. A bordered, bold banner\n // so the notice stands out from the streamed markdown context on stdout rather\n // than scrolling past unnoticed.\n console.error(renderOutdatedBanner(outdated));\n}\n\n/** Options accepted by the `context` action. */\nexport interface ContextOptions {\n output?: string;\n offline?: boolean;\n}\n\n/**\n * Generate the Auro AI-assistant context document and either write it to\n * `options.output` or stream it to stdout. With `--offline`, only locally\n * installed manifests (and the built-in table) are used; online, manifests are\n * enriched from local node_modules or unpkg and outdated installs are flagged on\n * stderr. Exits non-zero only when writing the output file fails.\n */\nexport async function runContext(options: ContextOptions): Promise<void> {\n const online = !options.offline;\n\n const spinner = ora(\n online\n ? \"Resolving component manifests...\"\n : \"Reading installed component manifests...\",\n ).start();\n const { rows, resolved, enriched, local } = await buildComponentTable(online);\n const context = buildAuroContext(rows);\n\n if (online) {\n // Online success is measured by descriptions enriched from any source\n // (local or unpkg); a run that resolves nothing falls back to the table.\n if (enriched > 0) {\n // `enriched` counts component descriptions (one package can export many),\n // while `local.size` counts packages \u2014 label each so the two aren't\n // conflated (e.g. a single package exporting 6 components reads as \"6\").\n // With nothing installed, enrichment came entirely from unpkg; saying\n // \"0 package(s) from local node_modules\" would read as a contradiction.\n spinner.succeed(\n local.size > 0\n ? `Enriched ${enriched} component description(s); ${local.size} package(s) resolved from local node_modules.`\n : `Enriched ${enriched} component description(s) from unpkg.`,\n );\n } else if (resolved > 0) {\n // Manifests were fetched but none documented an element description \u2014 the\n // table is complete, just not enriched. Gate this on `resolved`, not\n // `enriched`, so we don't claim \"No manifests available\" when some were.\n spinner.succeed(\n `Resolved ${resolved} component manifest(s); none documented a description, using the built-in table.`,\n );\n } else {\n spinner.warn(\n \"No manifests available; using the built-in component table.\",\n );\n }\n } else {\n // Offline success is measured by manifests *found* in node_modules, not by\n // descriptions enriched \u2014 an installed manifest can document no element\n // description (e.g. auro-button@12.3.0) yet is still a valid local read.\n if (local.size > 0) {\n spinner.succeed(\n enriched > 0\n ? `Read ${local.size} installed component manifest(s) from local node_modules; enriched ${enriched} description(s).`\n : `Read ${local.size} installed component manifest(s) from local node_modules; none documented a description, using the built-in table.`,\n );\n } else {\n spinner.warn(\n \"No installed component manifests found; using the built-in component table.\",\n );\n }\n }\n\n if (options.output) {\n const writeSpinner = ora(`Writing context to ${options.output}...`).start();\n try {\n const outputPath = path.resolve(process.cwd(), options.output);\n await fs.writeFile(outputPath, context, \"utf-8\");\n writeSpinner.succeed(`Auro context written to ${options.output}`);\n // Advisory only \u2014 keep it on stderr so `--output FILE` callers that capture\n // stdout don't get this line mixed into their capture.\n console.error(\n \"\\nPaste this file into your AI coding tool (Claude, Cursor, Copilot, etc.) to prime it on Auro components.\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n writeSpinner.fail(`Failed to write context: ${message}`);\n process.exit(1);\n }\n } else {\n process.stdout.write(context);\n }\n\n // Advisory only, and needs the network \u2014 skip in offline mode.\n if (online && local.size > 0) {\n await reportOutdated(local);\n }\n}\n\nexport default program\n .command(\"context\")\n .description(\n \"Generate an AI assistant context document for the Auro Design System\",\n )\n .option(\n \"-o, --output <path>\",\n \"Write context to a file instead of stdout (e.g. AURO_CONTEXT.md)\",\n )\n .option(\n \"--offline\",\n \"Skip network fetches; use locally installed manifests and the built-in table\",\n false,\n )\n .action(runContext);\n", "const AURO_CONTEXT_HEADER = `# Auro Design System \u2014 AI Assistant Context\nAlaska Airlines open-source design system | https://auro.alaskaair.com\n\n## What is Auro?\nAuro is Alaska Airlines' design system built on Web Components (Custom Elements v1) using the Lit library.\n- npm scope: \\`@aurodesignsystem/\\` (current), \\`@alaskaairux/\\` (legacy)\n- Framework-agnostic: works with React, Angular, Vue, Svelte, or plain HTML\n- Each component is a separate npm package\n- All components use the \\`<auro-*>\\` custom element tag\n\n## Rules for Writing Auro Code\n\n1. **Use \\`<auro-*>\\` custom element tags \u2014 never plain HTML equivalents**\n - \u2717 \\`<button>\\` \u2192 \u2713 \\`<auro-button>\\`\n - \u2717 \\`<a href=\"...\">\\` \u2192 \u2713 \\`<auro-hyperlink href=\"...\">\\`\n - \u2717 \\`<input>\\` \u2192 \u2713 \\`<auro-input>\\` (from auro-formkit)\n\n2. **Install and register each component before use**\n \\`\\`\\`bash\n npm install @aurodesignsystem/auro-button\n \\`\\`\\`\n \\`\\`\\`js\n import \"@aurodesignsystem/auro-button\"; // registers <auro-button> globally\n \\`\\`\\`\n\n3. **Props are HTML attributes in templates; camelCase properties in JS**\n \\`\\`\\`html\n <auro-button disabled loading>Save</auro-button>\n \\`\\`\\`\n \\`\\`\\`js\n document.querySelector('auro-button').loading = true;\n \\`\\`\\`\n\n4. **Content goes in named slots, not innerHTML**\n \\`\\`\\`html\n <auro-dialog>\n <span slot=\"header\">Title</span>\n <div slot=\"content\">Body content here</div>\n </auro-dialog>\n \\`\\`\\`\n\n5. **Design tokens are CSS custom properties**\n \\`\\`\\`bash\n npm install @aurodesignsystem/design-tokens\n \\`\\`\\`\n \\`\\`\\`css\n @import \"@aurodesignsystem/design-tokens/dist/themes/CSSCustomProperties--bundled.css\";\n \\`\\`\\`\n Token naming: \\`--ds-basic-*\\` and \\`--ds-advanced-*\\` (e.g. \\`--ds-advanced-color-*\\`, \\`--ds-basic-color-*\\`)\n\n## Component Reference\n\n`;\n\n/** The Markdown table header rows the component-reference body sits under. */\nconst COMPONENT_TABLE_HEADER = `| Element Tag | Package | Description |\n|---|---|---|`;\n\n/** A single component's entry in the curated Component Reference. */\nexport interface AuroComponent {\n /** The custom element tag, without angle brackets \u2014 e.g. \\`auro-button\\`. */\n tag: string;\n /** The npm package that publishes the component. */\n pkg: string;\n /** One-line description shown in the Component Reference table. */\n description: string;\n}\n\n/**\n * Curated component data, used as the offline fallback and as the base set the\n * \\`auro context\\` command enriches with live Custom Elements Manifest data.\n * Descriptions here are hand-written and may lag the published manifests \u2014\n * \\`auro context\\` overrides them with live manifest data where available, but\n * always keeps every component listed so nothing is dropped before a component\n * publishes a CEM.\n */\nexport const STATIC_COMPONENTS: AuroComponent[] = [\n {\n tag: \"auro-accordion\",\n pkg: \"@aurodesignsystem/auro-accordion\",\n description: \"Expandable content sections\",\n },\n {\n tag: \"auro-alert\",\n pkg: \"@aurodesignsystem/auro-alert\",\n description: \"Inline status messages: error, warning, success, information\",\n },\n {\n tag: \"auro-avatar\",\n pkg: \"@aurodesignsystem/auro-avatar\",\n description: \"User or entity avatar\",\n },\n {\n tag: \"auro-background\",\n pkg: \"@aurodesignsystem/auro-background\",\n description: \"Themed background wrapper\",\n },\n {\n tag: \"auro-backtotop\",\n pkg: \"@aurodesignsystem/auro-backtotop\",\n description: \"Scroll-to-top button\",\n },\n {\n tag: \"auro-badge\",\n pkg: \"@aurodesignsystem/auro-badge\",\n description: \"Status or count badge\",\n },\n {\n tag: \"auro-banner\",\n pkg: \"@aurodesignsystem/auro-banner\",\n description: \"Full-width promotional banner\",\n },\n {\n tag: \"auro-button\",\n pkg: \"@aurodesignsystem/auro-button\",\n description: \"Interactive button; supports `loading`, `disabled`, `shape`\",\n },\n {\n tag: \"auro-card\",\n pkg: \"@aurodesignsystem/auro-card\",\n description: \"Content card container\",\n },\n {\n tag: \"auro-carousel\",\n pkg: \"@aurodesignsystem/auro-carousel\",\n description: \"Horizontally scrollable carousel\",\n },\n {\n tag: \"auro-datetime\",\n pkg: \"@aurodesignsystem/auro-datetime\",\n description: \"Localized date and time formatting\",\n },\n {\n tag: \"auro-dialog\",\n pkg: \"@aurodesignsystem/auro-dialog\",\n description: \"Modal dialog; slots: header, content, footer\",\n },\n {\n tag: \"auro-drawer\",\n pkg: \"@aurodesignsystem/auro-drawer\",\n description: \"Slide-in panel; slots: header, content, footer\",\n },\n {\n tag: \"auro-flight\",\n pkg: \"@aurodesignsystem/auro-flight\",\n description: \"Flight segment display (origin, destination, stops)\",\n },\n {\n tag: \"auro-flightline\",\n pkg: \"@aurodesignsystem/auro-flightline\",\n description: \"Visual flight path/stop indicator\",\n },\n {\n tag: \"auro-input\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Text input field\",\n },\n {\n tag: \"auro-select\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Select/dropdown\",\n },\n {\n tag: \"auro-datepicker\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Date picker input\",\n },\n {\n tag: \"auro-combobox\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Combobox with search\",\n },\n {\n tag: \"auro-checkbox\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Checkbox input\",\n },\n {\n tag: \"auro-radio\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Radio button input\",\n },\n {\n tag: \"auro-header\",\n pkg: \"@aurodesignsystem/auro-header\",\n description: \"Page/section heading\",\n },\n {\n tag: \"auro-hyperlink\",\n pkg: \"@aurodesignsystem/auro-hyperlink\",\n description: \"Accessible anchor link\",\n },\n {\n tag: \"auro-icon\",\n pkg: \"@aurodesignsystem/auro-icon\",\n description: \"Alaska Airlines icon: `category` + `name` attributes\",\n },\n {\n tag: \"auro-loader\",\n pkg: \"@aurodesignsystem/auro-loader\",\n description: \"Loading spinner\",\n },\n {\n tag: \"auro-lockup\",\n pkg: \"@aurodesignsystem/auro-lockup\",\n description: \"Image + text layout lockup\",\n },\n {\n tag: \"auro-nav\",\n pkg: \"@aurodesignsystem/auro-nav\",\n description: \"Secondary navigation aid (relation to higher-level pages)\",\n },\n {\n tag: \"auro-pane\",\n pkg: \"@aurodesignsystem/auro-pane\",\n description: \"Selectable shoulder dates with associated prices\",\n },\n {\n tag: \"auro-popover\",\n pkg: \"@aurodesignsystem/auro-popover\",\n description: \"Tooltip-style popover\",\n },\n {\n tag: \"auro-sidenav\",\n pkg: \"@aurodesignsystem/auro-sidenav\",\n description: \"Vertical side navigation\",\n },\n {\n tag: \"auro-skeleton\",\n pkg: \"@aurodesignsystem/auro-skeleton\",\n description: \"Loading placeholder skeleton\",\n },\n {\n tag: \"auro-slideshow\",\n pkg: \"@aurodesignsystem/auro-slideshow\",\n description: \"Image/content slideshow\",\n },\n {\n tag: \"auro-table\",\n pkg: \"@aurodesignsystem/auro-table\",\n description: \"Accessible data table\",\n },\n {\n tag: \"auro-tabs\",\n pkg: \"@aurodesignsystem/auro-tabs\",\n description: \"Tabbed content panels\",\n },\n {\n tag: \"auro-tail\",\n pkg: \"@aurodesignsystem/auro-tail\",\n description: \"Alaska, Hawaiian, and partner airline tail graphics\",\n },\n {\n tag: \"auro-toast\",\n pkg: \"@aurodesignsystem/auro-toast\",\n description: \"Transient notification toast\",\n },\n {\n tag: \"auro-tokenlist\",\n pkg: \"@aurodesignsystem/auro-tokenlist\",\n description: \"Design token display utilities\",\n },\n];\n\n/**\n * Render a set of components as the Markdown Component Reference body (the\n * \\`| tag | package | description |\\` rows, without the header). Pipes in\n * descriptions are escaped so they don't break the table.\n */\nexport function renderComponentRows(\n components: readonly AuroComponent[],\n): string {\n return components\n .map(\n (component) =>\n `| \\`<${component.tag}>\\` | \\`${component.pkg}\\` | ${component.description.replace(/\\|/gu, \"\\\\|\")} |`,\n )\n .join(\"\\n\");\n}\n\n/**\n * Hand-written component-reference table body, used as the offline fallback\n * when the live Custom Elements Manifests can't be fetched.\n */\nexport const STATIC_COMPONENT_TABLE = renderComponentRows(STATIC_COMPONENTS);\n\nconst AURO_CONTEXT_FOOTER = `## Common Patterns\n\n### Button (default, secondary, tertiary)\n\\`\\`\\`html\n<auro-button>Primary</auro-button>\n<auro-button variant=\"secondary\">Secondary</auro-button>\n<auro-button variant=\"tertiary\">Tertiary</auro-button>\n<auro-button loading>Saving...</auro-button>\n\\`\\`\\`\n\n### Alert\n\\`\\`\\`html\n<auro-alert type=\"success\">Changes saved.</auro-alert>\n<auro-alert type=\"error\">Something went wrong.</auro-alert>\n<auro-alert type=\"warning\">Please review before continuing.</auro-alert>\n<auro-alert type=\"information\">Your flight departs at 9am.</auro-alert>\n\\`\\`\\`\n\n### Form inputs (auro-formkit)\nauro-formkit has no root export \u2014 always import the specific sub-component.\nThe field label is a **slot**, not an attribute.\n\\`\\`\\`js\nimport \"@aurodesignsystem/auro-formkit/auro-input\";\nimport \"@aurodesignsystem/auro-formkit/auro-select\";\n\\`\\`\\`\n\\`\\`\\`html\n<auro-input required>\n <span slot=\"label\">First name</span>\n</auro-input>\n<auro-select>\n <span slot=\"label\">Seat preference</span>\n <auro-menu>\n <auro-menuoption value=\"window\">Window</auro-menuoption>\n <auro-menuoption value=\"aisle\">Aisle</auro-menuoption>\n </auro-menu>\n</auro-select>\n\\`\\`\\`\n\n### Icon\nSet \\`category\\` and \\`name\\`. Icon names are exact \u2014 check the icon library for the correct name.\n\\`\\`\\`html\n<auro-icon category=\"interface\" name=\"arrow-right\"></auro-icon>\n<auro-icon category=\"terminal\" name=\"plane-side-fill\"></auro-icon>\n\\`\\`\\`\n\n### Hyperlink\n\\`\\`\\`html\n<auro-hyperlink href=\"/flights\">View flights</auro-hyperlink>\n<auro-hyperlink href=\"https://example.com\" target=\"_blank\">External link</auro-hyperlink>\n\\`\\`\\`\n\n### Dialog (modal)\n\\`\\`\\`js\ndocument.querySelector('#confirmDialog').show();\n\\`\\`\\`\n\\`\\`\\`html\n<auro-dialog id=\"confirmDialog\">\n <span slot=\"header\">Confirm booking</span>\n <div slot=\"content\">Are you sure you want to book this flight?</div>\n <div slot=\"footer\">\n <auro-button>Confirm</auro-button>\n <auro-button variant=\"secondary\">Cancel</auro-button>\n </div>\n</auro-dialog>\n\\`\\`\\`\n\n## Accessibility Notes\n- Use the \\`ariaLabel\\` slot on \\`<auro-button>\\` for icon-only buttons\n- \\`<auro-hyperlink>\\` adds rel=\"noopener noreferrer\" automatically for external links\n- All \\`auro-formkit\\` components handle aria-invalid and error messaging built-in\n- All components meet WCAG 2.1 AA\n\n## Documentation\n- Component docs: https://auro.alaskaair.com\n- Component status: https://auro.alaskaair.com/component-status\n- Design tokens: https://auro.alaskaair.com/getting-started/developers/token-usage\n- Contributing: https://auro.alaskaair.com/getting-started/developers/contributing\n- GitHub: https://github.com/AlaskaAirlines\n`;\n\n/**\n * Assemble the full AI-assistant context document from a Component Reference\n * table body (the \\`| tag | package | description |\\` rows, without the header).\n * The surrounding prose \u2014 rules, patterns, accessibility notes \u2014 is static; only\n * the component table varies between the live-manifest and fallback versions.\n */\nexport function buildAuroContext(componentTable: string): string {\n return `${AURO_CONTEXT_HEADER}${COMPONENT_TABLE_HEADER}\\n${componentTable}\\n\\n${AURO_CONTEXT_FOOTER}`;\n}\n\n/**\n * Fully static context document using the hand-written component table. Used as\n * the offline fallback when live manifests can't be fetched.\n */\nexport const AURO_CONTEXT = buildAuroContext(STATIC_COMPONENT_TABLE);\n", "/**\n * Shared Custom Elements Manifest (CEM) types and helpers used by the commands\n * that read `custom-elements.json` (cem, component, context). Keeping one copy\n * here avoids the shapes drifting across commands.\n */\n\nexport interface CemType {\n text?: string;\n}\n\nexport type Deprecated = boolean | string | undefined;\n\nexport interface CemAttribute {\n name: string;\n fieldName?: string;\n type?: CemType;\n default?: string;\n description?: string;\n summary?: string;\n deprecated?: Deprecated;\n}\n\nexport interface CemMember {\n kind: string;\n name: string;\n privacy?: string;\n static?: boolean;\n type?: CemType;\n default?: string;\n description?: string;\n summary?: string;\n deprecated?: Deprecated;\n return?: { type?: CemType };\n}\n\nexport interface CemSlot {\n name: string;\n description?: string;\n summary?: string;\n // The analyzer does not emit this for inline `@slot` tags (v0.11.0); optional so\n // a custom plugin that maps `@deprecated` onto slots stays type-compatible.\n deprecated?: Deprecated;\n}\n\nexport interface CemEvent {\n name: string;\n type?: CemType;\n description?: string;\n summary?: string;\n // The analyzer does not emit this for inline `@event`/`@fires` tags (v0.11.0);\n // optional so a custom plugin mapping `@deprecated` onto events stays compatible.\n deprecated?: Deprecated;\n}\n\nexport interface CemNamed {\n name: string;\n description?: string;\n}\n\nexport interface CemDeclaration {\n kind?: string;\n name: string;\n tagName?: string;\n customElement?: boolean;\n description?: string;\n summary?: string;\n superclass?: { name?: string };\n attributes?: CemAttribute[];\n members?: CemMember[];\n slots?: CemSlot[];\n events?: CemEvent[];\n cssParts?: CemNamed[];\n cssProperties?: CemNamed[];\n}\n\nexport interface CemModule {\n path?: string;\n declarations?: CemDeclaration[];\n [key: string]: unknown;\n}\n\nexport interface Manifest {\n schemaVersion?: string;\n modules?: CemModule[];\n [key: string]: unknown;\n}\n\n/**\n * Collapse whitespace (including embedded newlines from JSDoc descriptions) to a\n * single space so descriptions render on one line.\n */\nexport function clean(text: string | undefined): string {\n return (text ?? \"\").replace(/\\s+/gu, \" \").trim();\n}\n", "import chalk from \"chalk\";\nimport {\n formkitSubpathFor,\n isLegacyFormkitPackage,\n} from \"#static/formkitMigration.js\";\nimport { fetchLatestVersion } from \"#utils/fetchManifest.js\";\n\n/** A component whose installed version is behind its latest published release. */\nexport interface OutdatedComponent {\n pkg: string;\n installed: string;\n latest: string;\n}\n\nconst SEMVER =\n /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/u;\n\nfunction parseSemver(\n version: string,\n): { main: [number, number, number]; pre: string[] } | null {\n const match = SEMVER.exec(version.trim());\n if (!match) {\n return null;\n }\n return {\n main: [Number(match[1]), Number(match[2]), Number(match[3])],\n // Build metadata (after `+`) is ignored for precedence; only the prerelease\n // identifiers (after `-`) matter.\n pre: match[4] ? match[4].split(\".\") : [],\n };\n}\n\n/**\n * Compare two version strings by semver precedence. Returns a negative number\n * when `a` is older than `b`, a positive number when newer, and 0 when equal.\n * Numeric main segments compare numerically, and a version carrying a\n * prerelease tag (`13.0.0-beta.1`) ranks *below* the same version without one,\n * per the semver spec. Returns null when either side isn't valid semver, so a\n * caller can decline to guess rather than compare non-comparable strings.\n */\nexport function compareVersions(a: string, b: string): number | null {\n const pa = parseSemver(a);\n const pb = parseSemver(b);\n if (!pa || !pb) {\n return null;\n }\n\n for (let i = 0; i < 3; i += 1) {\n if (pa.main[i] !== pb.main[i]) {\n return pa.main[i] < pb.main[i] ? -1 : 1;\n }\n }\n\n // Equal main version: a release outranks any prerelease of the same version.\n if (pa.pre.length === 0 && pb.pre.length === 0) {\n return 0;\n }\n if (pa.pre.length === 0) {\n return 1;\n }\n if (pb.pre.length === 0) {\n return -1;\n }\n\n // Both prereleases: compare identifier by identifier (numeric < alphanumeric,\n // and a shorter set of identifiers has lower precedence when all else ties).\n const len = Math.max(pa.pre.length, pb.pre.length);\n for (let i = 0; i < len; i += 1) {\n const ai = pa.pre[i];\n const bi = pb.pre[i];\n if (ai === undefined) {\n return -1;\n }\n if (bi === undefined) {\n return 1;\n }\n const aNum = /^\\d+$/u.test(ai);\n const bNum = /^\\d+$/u.test(bi);\n if (aNum && bNum) {\n const diff = Number(ai) - Number(bi);\n if (diff !== 0) {\n return diff < 0 ? -1 : 1;\n }\n } else if (aNum !== bNum) {\n return aNum ? -1 : 1;\n } else if (ai !== bi) {\n return ai < bi ? -1 : 1;\n }\n }\n return 0;\n}\n\n/**\n * Compare each installed package against its latest published release and return\n * the ones that are behind. Best-effort and network-dependent \u2014 a package whose\n * latest version cannot be resolved is treated as current (never reported).\n */\nexport async function checkOutdated(\n installed: Map<string, string>,\n): Promise<OutdatedComponent[]> {\n const entries = [...installed.entries()];\n const latest = await Promise.all(\n entries.map(([pkg]) => fetchLatestVersion(pkg)),\n );\n\n const outdated: OutdatedComponent[] = [];\n entries.forEach(([pkg, version], index) => {\n const newest = latest[index];\n if (!newest) {\n return;\n }\n // Report only when the installed version is *strictly older* than latest.\n // A version that is equal, ahead (a prerelease / `@next` / linked workspace\n // copy such as 13.0.0-beta vs a 12.3.0 latest), or non-comparable is treated\n // as current, so the banner never advises `install @latest` as a downgrade.\n const cmp = compareVersions(version, newest);\n if (cmp !== null && cmp < 0) {\n outdated.push({ pkg, installed: version, latest: newest });\n }\n });\n return outdated;\n}\n\n// The visible annotation appended to a legacy-standalone row (color codes have\n// zero display width, so only this bare text counts toward the border math).\nconst FORMKIT_MARK = \" \u21E2 auro-formkit\";\n\n/**\n * Render the \"components behind latest\" notice as a bold, bordered banner with\n * an aligned version table and ready-to-run guidance. Colors degrade\n * automatically (chalk disables them when the stream is not a TTY, e.g.\n * redirected to a file), while the border and heading keep it prominent\n * regardless. Meant for stderr so it never pollutes command output on stdout.\n *\n * A **legacy standalone** form package (one `auro-formkit` now ships) is not advised\n * to update to `@latest` \u2014 that pushes the consumer deeper into the deprecated\n * package. Its row is marked `\u21E2 auro-formkit` and it appears under a distinct\n * \"Migrate to auro-formkit\" block instead of the `npm install @latest` command.\n */\nexport function renderOutdatedBanner(outdated: OutdatedComponent[]): string {\n // Self-guard: with no components the width math (`Math.max(...[])`) would\n // yield -Infinity and garble the banner. Callers already skip the empty case,\n // but returning \"\" keeps this safe for any future caller.\n if (outdated.length === 0) {\n return \"\";\n }\n\n const legacy = outdated.filter((o) => isLegacyFormkitPackage(o.pkg));\n const normal = outdated.filter((o) => !isLegacyFormkitPackage(o.pkg));\n\n const heading = `\u26A0 ${outdated.length} Auro component(s) are NOT on the latest release`;\n const pkgWidth = Math.max(...outdated.map((o) => o.pkg.length));\n const installedWidth = Math.max(...outdated.map((o) => o.installed.length));\n\n const isLegacy = (o: OutdatedComponent): boolean =>\n isLegacyFormkitPackage(o.pkg);\n const rows = outdated.map((o) => {\n const row = ` ${chalk.bold(o.pkg.padEnd(pkgWidth))} ${chalk.dim(\n o.installed.padStart(installedWidth),\n )} ${chalk.dim(\"\u2192\")} ${chalk.green.bold(o.latest)}`;\n return isLegacy(o) ? `${row}${chalk.yellow(FORMKIT_MARK)}` : row;\n });\n\n // Guidance: standard packages update to @latest; legacy standalones migrate to\n // the formkit subpath instead. Either block is omitted when it has no members.\n const guidance: string[] = [];\n if (normal.length > 0) {\n const updateCmd = `npm install ${normal\n .map((o) => `${o.pkg}@latest`)\n .join(\" \")}`;\n guidance.push(\n \"\",\n chalk.dim(\" Update to latest with:\"),\n ` ${chalk.cyan(updateCmd)}`,\n );\n }\n if (legacy.length > 0) {\n guidance.push(\n \"\",\n chalk.dim(\" Migrate to auro-formkit (run `auro init`):\"),\n );\n for (const o of legacy) {\n guidance.push(\n ` ${chalk.dim(o.pkg)} ${chalk.dim(\"\u2192\")} ${chalk.cyan(formkitSubpathFor(o.pkg))}`,\n );\n }\n }\n\n // Border width tracks the widest visible line (ignoring color codes), capped\n // so a long update command doesn't blow out the terminal.\n const visibleWidths = [\n // `\u26A0` (U+26A0) renders as two terminal columns but `.length` counts it as\n // one, so add 1 or the border falls a column short of the heading.\n heading.length + 1,\n ...outdated.map((o) => {\n const base = 2 + pkgWidth + 2 + installedWidth + 3 + o.latest.length;\n return isLegacy(o) ? base + FORMKIT_MARK.length : base;\n }),\n ];\n const width = Math.min(Math.max(...visibleWidths), 78);\n const border = \"\u2500\".repeat(width);\n\n return [\n \"\",\n chalk.yellow.bold(`\u250C${border}\u2510`),\n chalk.yellow.bold(heading),\n chalk.yellow.bold(`\u2514${border}\u2518`),\n ...rows,\n ...guidance,\n \"\",\n ].join(\"\\n\");\n}\n", "/**\n * The legacy-standalone \u2192 `auro-formkit` relationship, in one place.\n *\n * Nine Auro form components were first published as **standalone** packages\n * (`@aurodesignsystem/auro-input`, `-select`, \u2026) and were later absorbed into the\n * `@aurodesignsystem/auro-formkit` monorepo, which re-exports each under a\n * per-component subpath (`@aurodesignsystem/auro-formkit/auro-<x>`). A project on a\n * standalone is on the *legacy* form of that component and should migrate to\n * formkit \u2014 the standalone import path (`@aurodesignsystem/auro-<x>`) maps 1:1 to a\n * formkit subpath.\n *\n * `auro-button` is a genuine standalone that was **never** part of formkit, so it is\n * deliberately absent from {@link LEGACY_FORMKIT_PACKAGES}. This is the same overlap\n * documented in [auroComponents.ts](./auroComponents.ts); keep the two lists in sync.\n */\n\n/** The monorepo that absorbed the legacy standalone form components. */\nexport const FORMKIT_PACKAGE = \"@aurodesignsystem/auro-formkit\";\n\n/**\n * The legacy standalone form packages that now live inside {@link FORMKIT_PACKAGE}.\n * A project depending on any of these should migrate to the formkit subpath.\n * Excludes `@aurodesignsystem/auro-button` (a true standalone, not in formkit).\n */\nexport const LEGACY_FORMKIT_PACKAGES: readonly string[] = [\n \"@aurodesignsystem/auro-input\",\n \"@aurodesignsystem/auro-select\",\n \"@aurodesignsystem/auro-combobox\",\n \"@aurodesignsystem/auro-menu\",\n \"@aurodesignsystem/auro-checkbox\",\n \"@aurodesignsystem/auro-radio\",\n \"@aurodesignsystem/auro-datepicker\",\n \"@aurodesignsystem/auro-dropdown\",\n \"@aurodesignsystem/auro-form\",\n];\n\nconst LEGACY_SET = new Set(LEGACY_FORMKIT_PACKAGES);\n\n/** True when `pkg` is a legacy standalone that formkit now ships. */\nexport function isLegacyFormkitPackage(pkg: string): boolean {\n return LEGACY_SET.has(pkg);\n}\n\n/**\n * The bare `auro-*` element name a legacy standalone contributes to formkit:\n * `@aurodesignsystem/auro-input` \u2192 `auro-input`. Assumes {@link isLegacyFormkitPackage}\n * \u2014 the standalone's package basename *is* its canonical tag.\n */\nexport function formkitTagFor(pkg: string): string {\n return pkg.slice(\"@aurodesignsystem/\".length);\n}\n\n/**\n * The formkit subpath import specifier that replaces a legacy standalone import:\n * `@aurodesignsystem/auro-input` \u2192 `@aurodesignsystem/auro-formkit/auro-input`.\n */\nexport function formkitSubpathFor(pkg: string): string {\n return `${FORMKIT_PACKAGE}/${formkitTagFor(pkg)}`;\n}\n", "/**\n * `auro init` \u2014 generate the AI grounding files (`AGENTS.md` + the thin\n * `CLAUDE.md`) for the Auro components a project actually has installed, plus the\n * CLI-owned `auro.config.json` that records how each component's tag is resolved.\n *\n * This command is the orchestration seam that wires the PT-M1 data modules\n * together: detect + resolve installed components (`resolver.ts`), plan each\n * component's custom tag under the frozen **config \u2192 AST scan \u2192 default prefix**\n * precedence (`registry.ts`), render the grounding files (`generator.ts`), then\n * write them and persist the config. It owns the two policy concerns the pure\n * planner deliberately excludes: the interactive prefix prompt/confirm and the\n * non-interactive TTY/CI guard.\n *\n * Its generated files are committed artifacts \u2014 `auro.config.json` and the rest\n * are meant to be checked in so regeneration is deterministic across a team and in\n * CI. To protect that, a post-write check asks git whether any file it wrote is\n * ignored and, with consent, appends the `.gitignore` negations that keep it\n * tracked (it never *adds* ignore rules). See `reconcileGitignore`/`gitignore.ts`.\n *\n * After writing, `init` runs the same best-effort **outdated-release check** as\n * `auro context`/`auro component` (a bordered banner on stderr for any installed\n * package behind its latest release). This is the one network touch in an otherwise\n * offline command; `--offline` skips it and keeps the run fully network-free.\n *\n * **One opt-in codemod exception.** `init` otherwise documents, never rewrites,\n * consumer source. The sole exception is the legacy-standalone \u2192 `auro-formkit`\n * migration: when a project depends on a deprecated standalone form package, an\n * interactive run offers to migrate it (edit `package.json`, rewrite import\n * specifiers). This is gated behind an explicit TTY confirm and fully skipped in a\n * non-interactive/CI run (which only advises). See `migrateFormkit.ts`.\n */\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { program } from \"commander\";\nimport inquirer from \"inquirer\";\nimport ora from \"ora\";\nimport { type AuroConfig, CONFIG_FILENAME } from \"#init/config.js\";\nimport {\n detectEditorSignals,\n EDITOR_TARGETS,\n type EditorSelection,\n type EditorTarget,\n} from \"#init/editors/detect.js\";\nimport { verifyEditorWiring } from \"#init/editors/verify.js\";\nimport {\n type EditorWriteReport,\n writeEditorArtifacts,\n} from \"#init/editors/write.js\";\nimport { groundingFiles } from \"#init/generator.js\";\nimport { findIgnored, unignore } from \"#init/gitignore.js\";\nimport { AGENTS_FILENAME, CLAUDE_FILENAME } from \"#init/layout.js\";\nimport {\n detectLegacyFormkit,\n type LegacyDependency,\n migrateToFormkit,\n} from \"#init/migrateFormkit.js\";\nimport {\n emptyConfig,\n loadConfig,\n planTagResolution,\n RegistryError,\n saveConfig,\n scanProject,\n type TagResolutionPlan,\n} from \"#init/registry.js\";\nimport { applyReset, planReset, type ResetPlan } from \"#init/reset.js\";\nimport { type ResolvedComponent, resolveInstalled } from \"#init/resolver.js\";\nimport { renderWarningBanner } from \"#utils/banner.js\";\nimport { checkOutdated, renderOutdatedBanner } from \"#utils/outdated.js\";\n\n/** Options accepted by the `init` action. */\nexport interface InitOptions {\n /** Default tag prefix (e.g. `myapp-`) for components without an existing registration. */\n prefix?: string;\n /** Never prompt; take the prefix from `--prefix` or fail cleanly. */\n nonInteractive?: boolean;\n /** Alias for {@link nonInteractive}. */\n yes?: boolean;\n /**\n * Editor-target opt-ins. Each is **tri-state**: `true` (`--vscode`) forces the\n * target on, `false` (`--no-vscode`) forces it off, and `undefined` (neither\n * flag) leaves it to the persisted config \u2192 detection \u2192 prompt precedence. An\n * explicit flag always wins and is persisted for later runs.\n */\n vscode?: boolean;\n jsx?: boolean;\n svelte?: boolean;\n cssSnippets?: boolean;\n /**\n * Skip the best-effort network check for newer component releases. `init` is\n * otherwise offline; the release-check is its one network touch, so `--offline`\n * keeps the whole run network-free (useful in CI or air-gapped environments).\n */\n offline?: boolean;\n /**\n * Teardown mode: remove every file and config entry a previous `auro init` run\n * produced instead of generating. A pure reverse operation \u2014 needs no installed\n * components, prefix resolution, or network. See {@link runReset}.\n */\n reset?: boolean;\n}\n\n/**\n * Is this run non-interactive? True when stdin is not a TTY, when `CI` is set, or\n * when the user passed `--non-interactive`/`--yes`. A non-interactive run never\n * calls `inquirer` (which would throw on a closed stdin) \u2014 it takes the prefix\n * from `--prefix` or fails cleanly.\n */\nfunction isNonInteractive(options: InitOptions): boolean {\n return (\n !process.stdin.isTTY ||\n Boolean(process.env.CI) ||\n Boolean(options.nonInteractive) ||\n Boolean(options.yes)\n );\n}\n\n/**\n * Interactively resolve the default prefix for components that have no config or\n * scan-detected tag. Offers the majority `suggestedDefault` (when one was\n * inferred from existing registrations) as a `confirm`, falling back to a free\n * `input` \u2014 a blank answer keeps the bare `auro-*` tags (the planner warns).\n * Only called on an interactive TTY.\n */\nasync function promptDefaultPrefix(plan: TagResolutionPlan): Promise<string> {\n if (plan.suggestedDefault) {\n const { accept } = await inquirer.prompt<{ accept: boolean }>([\n {\n type: \"confirm\",\n name: \"accept\",\n message: plan.mixedPrefixes\n ? `Existing registrations use more than one prefix. Use the most common, '${plan.suggestedDefault}', as the default for the remaining components?`\n : `Use the detected prefix '${plan.suggestedDefault}' as the default for the remaining components?`,\n default: true,\n },\n ]);\n if (accept) {\n return plan.suggestedDefault;\n }\n }\n\n const { prefix } = await inquirer.prompt<{ prefix: string }>([\n {\n type: \"input\",\n name: \"prefix\",\n message:\n \"Prefix for Auro custom-element tags (e.g. myapp-; blank keeps the bare auro-* tags):\",\n default: plan.suggestedDefault ?? \"\",\n },\n ]);\n return String(prefix).trim();\n}\n\n/**\n * Validate a user-entered custom-element tag (inquirer `validate` contract:\n * `true` when acceptable, else the error string to show). A conservative subset\n * of the HTML custom-element name grammar \u2014 lowercase, must start with an ASCII\n * letter and contain at least one hyphen \u2014 enough to reject typos like\n * `MyButton` or a bare `button` that would generate IntelliSense keyed on a tag\n * the markup never uses.\n */\nexport function isValidCustomTag(tag: string): true | string {\n const trimmed = tag.trim();\n if (!/^[a-z][a-z0-9-]*$/.test(trimmed)) {\n return \"Use a lowercase tag starting with a letter (letters, digits, and hyphens only).\";\n }\n if (!trimmed.includes(\"-\")) {\n return \"A custom-element tag must contain a hyphen (e.g. nav-menu).\";\n }\n return true;\n}\n\n/**\n * Optionally let the user name any installed component's tag explicitly. Gated\n * behind one confirm (default no); on yes, prompts once per component with the\n * prefix-calculated tag as the editable default \u2014 Enter keeps it, a typed value\n * replaces it. Returns only the entries the user actually changed (canonical\n * `auro-*` tag \u2192 typed custom tag), so an unchanged component stays driven by the\n * prefix machinery (a later `--prefix` still propagates to it) rather than being\n * pinned as an override. Interactive TTY only \u2014 the caller guards on that.\n */\nasync function promptCustomTags(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): Promise<Record<string, string>> {\n const { customize } = await inquirer.prompt<{ customize: boolean }>([\n {\n type: \"confirm\",\n name: \"customize\",\n message:\n \"Define a custom tag name for any installed component? (you'll be prompted per component; Enter keeps the calculated name)\",\n default: false,\n },\n ]);\n if (!customize) {\n return {};\n }\n\n const overrides: Record<string, string> = {};\n for (const component of components) {\n const canonical = component.tagName;\n const calculated = resolvedTags.get(canonical) ?? canonical;\n const { tag } = await inquirer.prompt<{ tag: string }>([\n {\n type: \"input\",\n name: \"tag\",\n message: `Tag for ${component.declaration.name} (<${canonical}>):`,\n default: calculated,\n validate: isValidCustomTag,\n },\n ]);\n const entered = String(tag).trim();\n if (entered !== calculated) {\n overrides[canonical] = entered;\n }\n }\n return overrides;\n}\n\n/**\n * Build the config to re-plan against after the per-component prompt: the loaded\n * config's default + overrides, merged with the user's typed customs (which win).\n * Falls back to an empty config when the project had none. Pure \u2014 the returned\n * config feeds {@link planTagResolution}, which re-derives resolved tags and\n * warnings and yields the authoritative config to persist.\n */\nfunction withUserOverrides(\n config: AuroConfig | null,\n overrides: Record<string, string>,\n): AuroConfig {\n const base = config ?? emptyConfig();\n return {\n ...base,\n init: {\n ...base.init,\n prefix: {\n default: base.init.prefix.default,\n overrides: { ...base.init.prefix.overrides, ...overrides },\n },\n },\n };\n}\n\n/** Human-facing label + artifact path for each editor target's confirm prompt. */\nconst EDITOR_TARGET_META: Record<\n EditorTarget,\n { label: string; artifact: string }\n> = {\n vscode: {\n label: \"VS Code HTML custom-data\",\n artifact: \".vscode/auro.html-custom-data.json\",\n },\n jsx: {\n label: \"JSX/React type declarations\",\n artifact: \"auro-types/auro-jsx.d.ts\",\n },\n svelte: {\n label: \"Svelte type declarations\",\n artifact: \"auro-types/auro-svelte.d.ts\",\n },\n cssSnippets: {\n label: \"CSS ::part() snippets\",\n artifact: \".vscode/auro.code-snippets\",\n },\n};\n\n/**\n * Settle each editor target on/off under the frozen precedence\n * flag \u2192 persisted config \u2192 detection \u2192 interactive prompt. An explicit\n * `--vscode`/`--no-vscode` flag wins outright; else a settled `init.editors.*`\n * choice from a prior run is honored (no re-detect/re-prompt); else the target is\n * unsettled and its detected default is either offered as a confirm (interactive)\n * or taken as-is (non-interactive/CI \u2014 an editor target has a safe default, so\n * `init` never prompts or fails over it here). Every target is returned as a\n * concrete boolean so the caller can persist all three and later runs stay\n * deterministic.\n */\nasync function resolveEditorTargets(\n cwd: string,\n options: InitOptions,\n config: Awaited<ReturnType<typeof loadConfig>>,\n): Promise<EditorSelection> {\n const persisted = config?.init.editors;\n const signals = detectEditorSignals(cwd);\n const interactive = !isNonInteractive(options);\n\n const selection: EditorSelection = {\n vscode: false,\n jsx: false,\n svelte: false,\n cssSnippets: false,\n };\n const pending: Array<{\n type: \"confirm\";\n name: EditorTarget;\n message: string;\n default: boolean;\n }> = [];\n\n for (const target of EDITOR_TARGETS) {\n const flag = options[target];\n if (flag !== undefined) {\n selection[target] = flag; // explicit flag \u2014 highest precedence, persisted.\n continue;\n }\n const saved = persisted?.[target];\n if (saved !== undefined) {\n selection[target] = saved; // settled last run \u2014 honored as-is.\n continue;\n }\n // Unsettled: prompt on an interactive TTY, else take the detected default.\n if (interactive) {\n const { label, artifact } = EDITOR_TARGET_META[target];\n pending.push({\n type: \"confirm\",\n name: target,\n message: `Generate ${label} (${artifact})?`,\n default: signals[target],\n });\n } else {\n selection[target] = signals[target];\n }\n }\n\n if (pending.length > 0) {\n const answers =\n await inquirer.prompt<Record<EditorTarget, boolean>>(pending);\n for (const { name } of pending) {\n selection[name] = Boolean(answers[name]);\n }\n }\n\n return selection;\n}\n\n/**\n * Offer to migrate legacy standalone form packages (now shipped by `auro-formkit`)\n * to formkit. Returns `true` when a migration was applied \u2014 the caller then stops\n * this run, because the standalone is still in `node_modules` and grounding it now\n * would document the very imports the codemod just rewrote; the user reinstalls and\n * re-runs to ground formkit. Returns `false` when there is nothing to migrate, the\n * user declines, or the run is non-interactive (which only advises), so the caller\n * continues with normal grounding.\n */\nasync function offerFormkitMigration(\n cwd: string,\n options: InitOptions,\n): Promise<boolean> {\n let legacy: LegacyDependency[];\n try {\n legacy = detectLegacyFormkit(cwd);\n } catch (error) {\n // A malformed package.json is surfaced but must not abort grounding.\n const message = error instanceof Error ? error.message : String(error);\n console.error(`\u26A0 Skipping formkit migration check: ${message}`);\n return false;\n }\n if (legacy.length === 0) {\n return false;\n }\n\n const names = legacy.map((l) => l.pkg).join(\", \");\n if (isNonInteractive(options)) {\n console.error(\n `\u26A0 ${legacy.length} legacy standalone package(s) can be migrated to @aurodesignsystem/auro-formkit: ${names}. Run \\`auro init\\` interactively to apply the migration.`,\n );\n return false;\n }\n\n const { migrate } = await inquirer.prompt<{ migrate: boolean }>([\n {\n type: \"confirm\",\n name: \"migrate\",\n message: `${legacy.length} legacy standalone package(s) now live in auro-formkit (${names}). Migrate to auro-formkit now? This edits package.json and rewrites import specifiers.`,\n default: false,\n },\n ]);\n if (!migrate) {\n return false;\n }\n\n const spinner = ora(\"Migrating to auro-formkit...\").start();\n const report = migrateToFormkit(cwd, legacy);\n spinner.succeed(\n `Migrated ${report.packagesMigrated.length} package(s) to auro-formkit; rewrote ${report.rewriteCount} import(s) across ${report.filesChanged.length} file(s).`,\n );\n\n // Deep imports can't be remapped 1:1 to a formkit subpath \u2014 flag for follow-up.\n for (const { file, specifier } of report.deepImports) {\n console.error(\n `\u26A0 ${file}: left deep import '${specifier}' unchanged \u2014 update it to an @aurodesignsystem/auro-formkit subpath by hand.`,\n );\n }\n console.error(\n \"Next: run `npm install`, then re-run `auro init` to regenerate grounding for auro-formkit.\",\n );\n return true;\n}\n\n/**\n * Compare each resolved component's installed version against the latest published\n * release and, for any that are behind, print the shared outdated banner on stderr\n * (advisory \u2014 stdout stays clean). Best-effort and network-dependent: a package\n * whose latest can't be resolved is treated as current (`checkOutdated`), so a flaky\n * or absent network simply yields no banner and never fails `init`. Mirrors\n * `auro context`'s `reportOutdated`; the pkg\u2192version map is derived from the\n * components init already resolved (a monorepo pkg repeats with one shared version,\n * de-duped by the Map).\n */\nasync function reportOutdated(components: ResolvedComponent[]): Promise<void> {\n const installed = new Map(components.map((c) => [c.pkg, c.version]));\n const spinner = ora(\"Checking for newer component releases...\").start();\n const outdated = await checkOutdated(installed);\n\n if (outdated.length === 0) {\n spinner.succeed(\"All installed Auro components are on the latest release.\");\n return;\n }\n\n // Stop the spinner without its own icon/line \u2014 the banner below carries the\n // warning, and a leftover spinner line would dilute it.\n spinner.stop();\n console.error(renderOutdatedBanner(outdated));\n}\n\n/**\n * Generate and write the grounding files for the installed Auro components. See\n * the module header for the detect \u2192 plan \u2192 generate \u2192 write pipeline. Exits\n * non-zero on a malformed config, an unresolvable prefix in a non-interactive\n * run, or a write failure; warns (never guesses) on unresolvable registrations,\n * bare `auro-*` fallbacks, and cross-package duplicate tags.\n */\nexport async function runInit(options: InitOptions): Promise<void> {\n const cwd = process.cwd();\n\n // Teardown short-circuit: reset is a pure reverse operation, so it runs before\n // any detection/resolution/network \u2014 it must work even when no components are\n // installed or the config is gone.\n if (options.reset) {\n await runReset(cwd, options);\n return;\n }\n\n const spinner = ora(\"Detecting installed Auro components...\").start();\n const { components, duplicates } = await resolveInstalled();\n\n if (components.length === 0) {\n spinner.warn(\n \"No installed Auro components found; nothing to ground. Install an Auro component package and re-run `auro init`.\",\n );\n return;\n }\n spinner.succeed(\n `Detected ${components.length} installed component(s) to ground.`,\n );\n\n // Before grounding, offer to migrate any legacy standalone form package onto\n // auro-formkit. When a migration is applied, stop: the project must be\n // reinstalled and re-run so grounding reflects the formkit imports (see helper).\n if (await offerFormkitMigration(cwd, options)) {\n return;\n }\n\n // The persisted config is the source of truth for how tags were resolved last\n // run; a malformed or newer-version file is an explicit, actionable failure.\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = loadConfig(cwd);\n } catch (error) {\n const message =\n error instanceof RegistryError\n ? error.message\n : error instanceof Error\n ? error.message\n : String(error);\n console.error(`Cannot read ${CONFIG_FILENAME}: ${message}`);\n process.exit(1);\n }\n\n // Read-only scan of the project's own sources for existing register('<tag>')\n // calls \u2014 heuristic input to the config \u2192 scan \u2192 default-prefix precedence.\n const scan = scanProject(cwd);\n\n let plan = planTagResolution(components, {\n config,\n scan,\n prefix: options.prefix,\n });\n\n // Two-phase resolution: when some components still need a default prefix, or\n // existing registrations imply conflicting prefixes, resolve one and re-plan.\n //\n // The decision (confirm majority / prompt / CI-fail) is only needed while the\n // default is UNSETTLED \u2014 no --prefix and no persisted config default. A settled\n // default already governs unregistered components, so mixed per-component\n // overrides are simply honored and regeneration stays deterministic (no\n // re-prompt, no CI-fail on every run of a committed mixed-prefix project).\n const defaultSettled =\n options.prefix !== undefined || config?.init.prefix.default !== undefined;\n const needsDecision =\n !defaultSettled && (plan.needsDefaultPrefix || plan.mixedPrefixes);\n // The effective default prefix, tracked so a later re-plan (custom tags, below)\n // reuses the same one the user just settled instead of re-deriving it.\n let resolvedPrefix = options.prefix;\n if (needsDecision) {\n if (isNonInteractive(options)) {\n const reason = plan.needsDefaultPrefix\n ? `${plan.needingDefault.length} component(s) have no resolvable tag and no default prefix`\n : \"existing registrations use inconsistent prefixes\";\n console.error(\n `Cannot resolve component tags non-interactively: ${reason}. Re-run with --prefix <prefix> (e.g. --prefix myapp-).`,\n );\n process.exit(1);\n }\n resolvedPrefix = await promptDefaultPrefix(plan);\n plan = planTagResolution(components, {\n config,\n scan,\n prefix: resolvedPrefix,\n });\n }\n\n // Defensive: a resolved prefix must clear needsDefaultPrefix before we persist.\n if (plan.needsDefaultPrefix) {\n console.error(\n \"Unable to resolve a default prefix for every component. Re-run with --prefix <prefix>.\",\n );\n process.exit(1);\n }\n\n // Per-component custom tags (interactive only). Every component now has a\n // prefix-calculated tag; offer to override any of them with an explicit name.\n // Typed customs become `overrides` \u2014 the highest-precedence input \u2014 so a re-plan\n // re-derives resolved tags, reconciliation/no-prefix warnings, and the config to\n // persist. Non-interactive/CI runs skip this, keeping regeneration deterministic.\n if (!isNonInteractive(options)) {\n const customTags = await promptCustomTags(components, plan.resolvedTags);\n if (Object.keys(customTags).length > 0) {\n plan = planTagResolution(components, {\n config: withUserOverrides(config, customTags),\n scan,\n prefix: resolvedPrefix,\n });\n }\n }\n\n // Settle the editor targets (may prompt) before the spinner so the confirm UI\n // and the spinner never fight for the terminal, then record all three in the\n // config we are about to persist so later runs honor them without re-detecting.\n const editorSelection = await resolveEditorTargets(cwd, options, config);\n plan.config.init.editors = editorSelection;\n\n const writeSpinner = ora(\"Writing generated files...\").start();\n let editorReport: EditorWriteReport = { written: [], warnings: [] };\n try {\n for (const file of groundingFiles(components, plan.resolvedTags)) {\n await fs.writeFile(path.join(cwd, file.filename), file.contents, \"utf-8\");\n }\n // Write + wire the enabled editor artifacts (no-op when all targets are off).\n editorReport = await writeEditorArtifacts(\n cwd,\n components,\n plan.resolvedTags,\n editorSelection,\n );\n // Persist the authoritative config so regeneration is idempotent.\n saveConfig(cwd, plan.config);\n const editorNote =\n editorReport.written.length > 0\n ? ` Editor IntelliSense: ${editorReport.written.join(\", \")}.`\n : \"\";\n writeSpinner.succeed(\n `Wrote ${AGENTS_FILENAME}, ${CLAUDE_FILENAME}, and ${CONFIG_FILENAME} for ${components.length} component(s).${editorNote}`,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n writeSpinner.fail(`Failed to write generated files: ${message}`);\n process.exit(1);\n }\n\n // Advisory only \u2014 keep warnings on stderr so a caller capturing stdout gets a\n // clean run. Warn, never guess: unresolvable registrations and bare fallbacks.\n // Editor-wiring merges that were skipped (malformed target file) warn too, with\n // the manual one-liner already baked in.\n for (const warning of editorReport.warnings) {\n console.error(`\u26A0 ${warning}`);\n }\n for (const warning of plan.warnings) {\n console.error(`\u26A0 ${warning}`);\n }\n // A tag registered by more than one installed package (legacy standalone vs\n // monorepo overlap) is grounded once; surface it so the user picks intentionally.\n for (const duplicate of duplicates) {\n console.error(\n `\u26A0 Tag <${duplicate.tagName}> is registered by multiple installed packages: ${duplicate.packages.join(\", \")}. Grounded once \u2014 verify which package you intend to use.`,\n );\n }\n\n // Tag-reconciliation advisories (a grounded tag that may not match what the app\n // registers at runtime) silently break IntelliSense and are easy to miss among\n // the plain warnings above \u2014 surface them in a prominent red bordered banner,\n // the cousin of the outdated-release banner below.\n if (plan.reconciliationWarnings.length > 0) {\n console.error(\n renderWarningBanner(\n `\u26A0 ${plan.reconciliationWarnings.length} component tag(s) may not match your app's registered tags`,\n plan.reconciliationWarnings,\n \"red\",\n ),\n );\n }\n\n // Bare `auro-*` groundings \u2014 self-consistent but collision-prone. Less severe\n // than a reconciliation mismatch, so a yellow banner rather than red, but still\n // promoted above the plain-line noise so a missing prefix is hard to overlook.\n if (plan.noPrefixWarnings.length > 0) {\n console.error(\n renderWarningBanner(\n `\u26A0 ${plan.noPrefixWarnings.length} component(s) grounded under bare 'auro-*' tags \u2014 pass a prefix to avoid collisions`,\n plan.noPrefixWarnings,\n \"yellow\",\n ),\n );\n }\n\n // IntelliSense health check. `writeEditorArtifacts` above already wrote every\n // enabled target, but a merge can no-op against stale wiring whose artifact was\n // externally removed \u2014 leaving a settings pointer to a missing file. Read back\n // what actually landed; on a gap, re-run the idempotent writer once to self-heal,\n // then re-verify. A surviving gap is a red banner; a disabled markup target is a\n // yellow one, so absent `<auro-*>` completions are never a silent surprise.\n let verdict = verifyEditorWiring(cwd, editorSelection);\n if (verdict.inconsistencies.length > 0) {\n const healReport = await writeEditorArtifacts(\n cwd,\n components,\n plan.resolvedTags,\n editorSelection,\n );\n // The self-heal pass can raise warnings the first write didn't (e.g. a target\n // file that turned malformed since). Surface the new ones instead of dropping\n // its report; the first pass already printed the shared ones.\n const alreadyWarned = new Set(editorReport.warnings);\n for (const warning of healReport.warnings) {\n if (!alreadyWarned.has(warning)) {\n console.error(`\u26A0 ${warning}`);\n }\n }\n verdict = verifyEditorWiring(cwd, editorSelection);\n }\n if (verdict.inconsistencies.length > 0) {\n console.error(\n renderWarningBanner(\n \"\u26A0 Editor IntelliSense wiring is incomplete after writing\",\n verdict.inconsistencies,\n \"red\",\n ),\n );\n }\n if (verdict.markupDisabled) {\n console.error(\n renderWarningBanner(\n \"\u26A0 VS Code markup IntelliSense is off \u2014 no <auro-*> completions or hover docs\",\n [\n \"Type-checking may still work, but tag/attribute completions will not.\",\n \"Re-run `auro init --vscode` to generate them.\",\n ],\n \"yellow\",\n ),\n );\n }\n\n // Git-ignore reconciliation. Every file above is meant to be committed so a team\n // and CI share one deterministic set; a `.gitignore` rule (commonly `.vscode/`)\n // silently drops one from version control. Detect any ignored path and \u2014 with\n // consent \u2014 append the negations that keep it tracked. Advisory: never fails.\n const touched = [\n ...new Set([\n AGENTS_FILENAME,\n CLAUDE_FILENAME,\n CONFIG_FILENAME,\n ...editorReport.written,\n ]),\n ];\n await reconcileGitignore(cwd, touched, options);\n\n // Advisory, network-dependent \u2014 mirror `auro context`. Warn last so it's the\n // final thing on screen, not scrolled off by the write summary and warnings.\n // `--offline` skips it, keeping the run fully network-free.\n if (!options.offline) {\n await reportOutdated(components);\n }\n}\n\n/**\n * Detect files `auro init` wrote that git would ignore (so they'd never be\n * committed) and, with consent, append `.gitignore` negations to re-include them.\n * A prominent red banner surfaces the problem; the fix is offered interactively\n * (confirm, default yes) or applied straight away under `--yes`. A pure\n * non-interactive/CI run without `--yes` only warns \u2014 it never edits `.gitignore`\n * unprompted. Advisory throughout: never throws, never exits. See `gitignore.ts`.\n */\nasync function reconcileGitignore(\n cwd: string,\n touched: string[],\n options: InitOptions,\n): Promise<void> {\n const ignored = await findIgnored(cwd, touched);\n if (ignored.length === 0) {\n return;\n }\n\n console.error(\n renderWarningBanner(\n `\u26A0 ${ignored.length} file(s) auro init wrote are git-ignored and won't be committed`,\n [\n ...ignored,\n \"These are meant to be committed so your team and CI share the same grounding/IntelliSense.\",\n ],\n \"red\",\n ),\n );\n\n // Pure CI/non-interactive without --yes: warn only, never edit .gitignore unasked.\n if (isNonInteractive(options) && !options.yes) {\n console.error(\n \"\u26A0 Un-ignore them in .gitignore (or re-run with --yes) so they get committed.\",\n );\n return;\n }\n\n // Interactive without --yes: confirm before touching .gitignore. --yes: proceed.\n if (!options.yes) {\n const { fix } = await inquirer.prompt<{ fix: boolean }>([\n {\n type: \"confirm\",\n name: \"fix\",\n message:\n \"Add entries to .gitignore so these files stay tracked (committed)?\",\n default: true,\n },\n ]);\n if (!fix) {\n return;\n }\n }\n\n const { fixed, unfixable } = await unignore(cwd, ignored);\n if (fixed.length > 0) {\n console.error(\n `\u2714 Un-ignored ${fixed.length} file(s) in .gitignore so they will be committed.`,\n );\n }\n if (unfixable.length > 0) {\n console.error(\n renderWarningBanner(\n `\u26A0 ${unfixable.length} file(s) are still git-ignored \u2014 un-ignore them by hand`,\n [\n ...unfixable,\n \"A parent directory is ignored by a rule auro init won't rewrite; edit .gitignore to re-include these paths.\",\n ],\n \"red\",\n ),\n );\n }\n}\n\n/** True when a plan would remove or un-merge nothing (a no-op reset). */\nfunction isEmptyResetPlan(plan: ResetPlan): boolean {\n return plan.filesToRemove.length === 0 && plan.unmerges.length === 0;\n}\n\n/**\n * Teardown for `auro init --reset`: reverse a previous `auro init` run. Plans the\n * removals read-only, shows them for an interactive confirm (skippable with\n * `--yes`/`--non-interactive`/CI), then applies and summarizes. Signature-guarded\n * files that could not be confirmed as ours are reported, not deleted; the one-way\n * formkit migration is never reversed (a note says so). See `reset.ts`.\n */\nasync function runReset(cwd: string, options: InitOptions): Promise<void> {\n const plan = planReset(cwd);\n\n if (isEmptyResetPlan(plan)) {\n // Nothing of ours on disk. Still surface skips (e.g. a hand-edited AGENTS.md)\n // so the user understands why an expected file was left alone.\n console.log(\"Nothing to reset \u2014 no `auro init` output found.\");\n for (const skip of plan.filesToSkip) {\n console.error(`\u26A0 Left ${skip.path} in place: ${skip.reason}.`);\n }\n return;\n }\n\n // Show the exact teardown before touching disk.\n console.log(\"`auro init --reset` will:\");\n for (const file of plan.filesToRemove) {\n console.log(` \u2022 remove ${file}`);\n }\n for (const unmerge of plan.unmerges) {\n console.log(` \u2022 remove the Auro entry from ${unmerge.path}`);\n }\n for (const dir of plan.dirsToPrune) {\n console.log(` \u2022 remove ${dir}/ if it is left empty`);\n }\n for (const skip of plan.filesToSkip) {\n console.log(` \u2022 keep ${skip.path} (${skip.reason})`);\n }\n\n if (!isNonInteractive(options)) {\n const { confirm } = await inquirer.prompt<{ confirm: boolean }>([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Remove these files and config entries?\",\n default: false,\n },\n ]);\n if (!confirm) {\n console.log(\"Reset aborted \u2014 nothing was changed.\");\n return;\n }\n }\n\n const resetSpinner = ora(\"Removing `auro init` output...\").start();\n let report: ReturnType<typeof applyReset>;\n try {\n report = applyReset(cwd, plan);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n resetSpinner.fail(`Failed to reset: ${message}`);\n process.exit(1);\n }\n\n const removedNote =\n report.removed.length > 0\n ? `Removed ${report.removed.length} file(s)`\n : \"Removed no files\";\n const unmergedNote =\n report.unmerged.length > 0\n ? `, un-merged ${report.unmerged.join(\", \")}`\n : \"\";\n const prunedNote =\n report.prunedDirs.length > 0\n ? `, pruned ${report.prunedDirs.map((d) => `${d}/`).join(\", \")}`\n : \"\";\n resetSpinner.succeed(`${removedNote}${unmergedNote}${prunedNote}.`);\n\n for (const warning of report.warnings) {\n console.error(`\u26A0 ${warning}`);\n }\n for (const skip of report.skipped) {\n console.error(`\u26A0 Left ${skip.path} in place: ${skip.reason}.`);\n }\n\n // `--reset` never reverses the one-way formkit migration (package.json edits +\n // import rewrites) \u2014 say so rather than leave the user assuming a clean slate.\n console.error(\n \"\u2139 Reset does not undo an `auro-formkit` migration. If you migrated a legacy standalone form package, revert those package.json and import changes with git.\",\n );\n}\n\nexport default program\n .command(\"init\")\n .description(\n \"Generate AI grounding files (AGENTS.md + CLAUDE.md) for the installed Auro components\",\n )\n .option(\n \"--prefix <prefix>\",\n \"Default custom-element tag prefix (e.g. myapp-) for components without an existing registration\",\n )\n .option(\n \"--non-interactive\",\n \"Never prompt; take the prefix from --prefix or fail cleanly (implied by a non-TTY stdin or CI)\",\n false,\n )\n .option(\"--yes\", \"Alias for --non-interactive\", false)\n .option(\n \"--offline\",\n \"Skip the network check for newer component releases\",\n false,\n )\n .option(\n \"--vscode\",\n \"Generate VS Code HTML custom-data IntelliSense (use --no-vscode to skip; default: auto-detect)\",\n )\n .option(\"--no-vscode\", \"Skip the VS Code HTML custom-data artifact\")\n .option(\n \"--jsx\",\n \"Generate JSX/React type declarations (use --no-jsx to skip; default: auto-detect)\",\n )\n .option(\"--no-jsx\", \"Skip the JSX/React type declarations\")\n .option(\n \"--svelte\",\n \"Generate Svelte type declarations (use --no-svelte to skip; default: auto-detect)\",\n )\n .option(\"--no-svelte\", \"Skip the Svelte type declarations\")\n .option(\n \"--css-snippets\",\n \"Generate VS Code CSS ::part() snippets (use --no-css-snippets to skip; default: auto-detect)\",\n )\n .option(\"--no-css-snippets\", \"Skip the VS Code CSS ::part() snippets\")\n .option(\n \"--reset\",\n \"Remove every file and config entry a previous `auro init` run created (does not undo an auro-formkit migration)\",\n false,\n )\n .action(runInit);\n", "/**\n * Frozen schema for the CLI-owned `auro.config.json` file that `auro init` reads\n * and rewrites on every regeneration.\n *\n * See docs/pt-m1-completion-plan.md \u2192 \"Frozen decisions \u2192 CLI-owned config\n * location/shape\". This shape is FROZEN: do not change it without bumping\n * {@link CONFIG_VERSION} and shipping a migration. The top-level `version` field\n * exists from v1 precisely so any future change is an explicit migration rather\n * than a guess (the ticket's \"freeze the format early / bus-factor\" requirement).\n *\n * The one sanctioned exception is adding an **optional** field: a v1 reader treats\n * its absence as \"unresolved\", so a v1 file written before the field existed stays\n * valid without migration. {@link EditorsConfig} (PT-M2) is such a field \u2014 see\n * docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Config schema extension is\n * additive \u2014 no version bump\". A *breaking* change still requires the bump above.\n */\n\n/** Current on-disk config format version. Bump only alongside a migration. */\nexport const CONFIG_VERSION = 1 as const;\n\n/** The dedicated project-root file `auro init` reads and writes. */\nexport const CONFIG_FILENAME = \"auro.config.json\";\n\n/**\n * Custom-element registration prefixing.\n * - `default` applies to every installed component that has no override.\n * - `overrides` map a bare `auro-*` tag (the stable component identity, and the\n * resolver's canonical `tagName`) to the resolved custom tag.\n */\nexport interface PrefixConfig {\n /** Prefix applied to unregistered components, e.g. `\"myapp-\"`. */\n default: string;\n /** Per-component custom tags, keyed by the bare `auro-*` tag. */\n overrides: Record<string, string>;\n}\n\n/**\n * Per-editor-target opt-in for the IntelliSense artifacts `auro init` can\n * additionally emit (PT-M2). Each key is **optional and tri-state**: `true` /\n * `false` is a settled choice that later runs (including CI) honor without\n * re-detecting or re-prompting; **absence means \"unresolved\"** \u2014 the target is\n * auto-detected/prompted on the next interactive run. The whole block is optional\n * so a PT-M1 v1 file that predates it stays valid (see {@link AuroConfig} doc).\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Detection / prompt / flags\".\n */\nexport interface EditorsConfig {\n /** VS Code HTML custom-data (`.vscode/auro.html-custom-data.json`). */\n vscode?: boolean;\n /** JSX/React type declarations (`auro-types/auro-jsx.d.ts`). */\n jsx?: boolean;\n /** Svelte type declarations (`auro-types/auro-svelte.d.ts`). */\n svelte?: boolean;\n /** VS Code CSS `::part()` snippets (`.vscode/auro.code-snippets`). */\n cssSnippets?: boolean;\n}\n\n/** The `init`-namespaced settings block. Future commands get sibling keys. */\nexport interface InitConfig {\n prefix: PrefixConfig;\n /**\n * Optional per-editor opt-in (PT-M2). Additive; absence is valid and means\n * \"no editor target settled yet\". See {@link EditorsConfig}.\n */\n editors?: EditorsConfig;\n}\n\n/** Top-level shape of `auro.config.json`, namespaced per command. */\nexport interface AuroConfig {\n /** Format version; equals {@link CONFIG_VERSION} for files this CLI writes. */\n version: typeof CONFIG_VERSION;\n init: InitConfig;\n}\n", "/**\n * Read-only detection heuristics that pick a sensible **default** for each\n * editor-IntelliSense target when the consumer hasn't settled it via a flag or a\n * persisted `auro.config.json` choice. Every probe is a cheap, offline filesystem\n * look \u2014 never a network call, never a write \u2014 so it is safe to run on every\n * `auro init`, interactive or CI.\n *\n * These signals are only ever a *default*: the frozen precedence is\n * flag \u2192 persisted config \u2192 **detection** \u2192 interactive prompt. On an interactive\n * TTY the detected value seeds the confirm prompt; on a non-interactive/CI run\n * with no flag and no persisted choice it is taken as-is and recorded (an editor\n * target has a safe default, so \u2014 unlike the prefix \u2014 `init` never CI-fails over\n * it). See docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Detection / prompt\n * / flags\".\n */\n\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse as parseJsonc } from \"jsonc-parser\";\nimport { VSCODE_DIR } from \"#init/editors/layout.js\";\n\n/** Per-target on/off selection \u2014 the shape persisted under `init.editors`. */\nexport interface EditorSelection {\n /** VS Code HTML custom-data (`.vscode/auro.html-custom-data.json`). */\n vscode: boolean;\n /** JSX/React type declarations (`auro-types/auro-jsx.d.ts`). */\n jsx: boolean;\n /** Svelte type declarations (`auro-types/auro-svelte.d.ts`). */\n svelte: boolean;\n /** VS Code CSS `::part()` snippets (`.vscode/auro.code-snippets`). */\n cssSnippets: boolean;\n}\n\n/** The editor targets, in the order `init` resolves and reports them. */\nexport const EDITOR_TARGETS = [\n \"vscode\",\n \"jsx\",\n \"svelte\",\n \"cssSnippets\",\n] as const;\n\n/** One editor target key (`\"vscode\" | \"jsx\" | \"svelte\" | \"cssSnippets\"`). */\nexport type EditorTarget = (typeof EDITOR_TARGETS)[number];\n\n/** True when `<cwd>/<rel>` exists and is a directory. */\nfunction isDir(cwd: string, rel: string): boolean {\n try {\n return statSync(path.join(cwd, rel)).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * The union of `dependencies` + `devDependencies` names from `<cwd>/package.json`,\n * or an empty set when the file is absent or unreadable/malformed (detection never\n * throws \u2014 a bad manifest just yields no dependency signal).\n */\nfunction dependencyNames(cwd: string): Set<string> {\n try {\n const raw = readFileSync(path.join(cwd, \"package.json\"), \"utf-8\");\n const pkg = parseJsonc(raw, [], { allowTrailingComma: true }) as\n | {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n }\n | undefined;\n if (typeof pkg !== \"object\" || pkg === null) {\n return new Set();\n }\n return new Set([\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.devDependencies ?? {}),\n ]);\n } catch {\n return new Set();\n }\n}\n\n/**\n * VS Code target signal: the project already keeps a `.vscode/` directory (it\n * uses VS Code workspace settings), so wiring HTML custom-data into it is apt.\n */\nexport function detectVsCode(cwd: string): boolean {\n return isDir(cwd, VSCODE_DIR);\n}\n\n/**\n * CSS `::part()` snippets target signal: the project keeps a `.vscode/`\n * directory, so it uses VS Code, which auto-discovers the `.code-snippets` file\n * we write there. Same signal as {@link detectVsCode} \u2014 the snippets are a VS\n * Code feature \u2014 kept as its own named probe so the target reads independently.\n */\nexport function detectCssSnippets(cwd: string): boolean {\n return isDir(cwd, VSCODE_DIR);\n}\n\n/**\n * JSX/React target signal: the TypeScript config turns on JSX\n * (`compilerOptions.jsx` is set) **or** `react` is a (dev)dependency. Either means\n * the project authors `.tsx`/`.jsx` and would benefit from the JSX `.d.ts`.\n */\nexport function detectJsx(cwd: string): boolean {\n const tsconfigPath = path.join(cwd, \"tsconfig.json\");\n if (existsSync(tsconfigPath)) {\n try {\n const raw = readFileSync(tsconfigPath, \"utf-8\");\n const tsconfig = parseJsonc(raw, [], { allowTrailingComma: true }) as\n | { compilerOptions?: { jsx?: unknown } }\n | undefined;\n if (\n typeof tsconfig === \"object\" &&\n tsconfig !== null &&\n tsconfig.compilerOptions?.jsx !== undefined\n ) {\n return true;\n }\n } catch {\n // Unparseable tsconfig \u2014 fall through to the dependency signal.\n }\n }\n return dependencyNames(cwd).has(\"react\");\n}\n\n/**\n * Svelte target signal: `svelte` is a (dev)dependency **or** a `svelte.config.*`\n * lives at the project root \u2014 either means a Svelte project whose language server\n * consumes the Svelte `.d.ts`.\n */\nexport function detectSvelte(cwd: string): boolean {\n if (dependencyNames(cwd).has(\"svelte\")) {\n return true;\n }\n return [\"js\", \"ts\", \"mjs\", \"cjs\"].some((ext) =>\n existsSync(path.join(cwd, `svelte.config.${ext}`)),\n );\n}\n\n/** Run every target probe against `cwd` and return the detected defaults. */\nexport function detectEditorSignals(cwd: string): EditorSelection {\n return {\n vscode: detectVsCode(cwd),\n jsx: detectJsx(cwd),\n svelte: detectSvelte(cwd),\n cssSnippets: detectCssSnippets(cwd),\n };\n}\n", "/**\n * Post-write health check for the editor-IntelliSense targets. `auro init` writes\n * the artifacts and merges their wiring (./write.ts), then calls this to confirm\n * what actually landed on disk \u2014 so the command can **self-heal** a target whose\n * artifact or wiring went missing, and **loudly warn** when the markup-completion\n * (VS Code) target is off, instead of finishing \"successfully\" with silently-broken\n * IntelliSense.\n *\n * Read-only (mirrors reset.ts's `readOrNull`): it never writes. Two failure kinds:\n * - {@link EditorWiringVerdict.inconsistencies} \u2014 an *enabled* target whose file or\n * config wiring is absent/incomplete on disk. The caller re-runs the idempotent\n * writer once to repair, then re-verifies.\n * - {@link EditorWiringVerdict.markupDisabled} \u2014 the VS Code target resolved off, so\n * `<auro-*>` tag/attribute completions and hover docs are not generated at all.\n * The Svelte/JSX `.d.ts` type-checking layer can still be on, which masks this \u2014\n * the caller surfaces it so a missing markup layer is never a silent surprise.\n *\n * @see src/commands/init.ts (the caller), ./write.ts (the writer this guards),\n * ./settings.ts (the merge whose result this reads back).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse as parseJsonc } from \"jsonc-parser\";\nimport type { EditorSelection } from \"#init/editors/detect.js\";\nimport {\n HTML_CUSTOM_DATA_PATH,\n HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n JSX_TYPES_PATH,\n SVELTE_TYPES_PATH,\n TSCONFIG_INCLUDE_ENTRY,\n TSCONFIG_INCLUDE_KEY,\n VSCODE_DIR,\n VSCODE_SETTINGS_FILENAME,\n} from \"#init/editors/layout.js\";\n\n/** Outcome of a {@link verifyEditorWiring} pass. */\nexport interface EditorWiringVerdict {\n /**\n * One message per **enabled** target whose artifact or wiring is missing or\n * incomplete on disk. Empty when every enabled target is fully wired. The caller\n * treats a non-empty list as \"re-run the writer to repair, then re-check\".\n */\n inconsistencies: string[];\n /**\n * True when the VS Code (markup-completion) target is off. With Auro components\n * installed this means no `<auro-*>` completions/hover are generated \u2014 the caller\n * warns and points at `--vscode`.\n */\n markupDisabled: boolean;\n}\n\n/** Absolute path for a forward-slash, root-relative artifact path. */\nfunction toAbsolute(cwd: string, rel: string): string {\n return path.join(cwd, ...rel.split(\"/\"));\n}\n\n/** Read a file as UTF-8, or `null` when it does not exist / cannot be read. */\nfunction readOrNull(absolute: string): string | null {\n try {\n return readFileSync(absolute, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * True when `.vscode/settings.json` registers the HTML custom-data entry under\n * `html.customData` (as a bare string or inside the array). A missing/unparseable\n * file, or the key holding some other type, counts as \"not registered\".\n */\nfunction settingsHasPointer(cwd: string): boolean {\n const contents = readOrNull(\n toAbsolute(cwd, `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME}`),\n );\n if (contents === null) {\n return false;\n }\n const data = parseJsonc(contents, [], { allowTrailingComma: true }) as\n | Record<string, unknown>\n | undefined;\n const value = data?.[HTML_CUSTOM_DATA_SETTINGS_KEY];\n if (typeof value === \"string\") {\n return value === HTML_CUSTOM_DATA_SETTINGS_ENTRY;\n }\n if (Array.isArray(value)) {\n return value.includes(HTML_CUSTOM_DATA_SETTINGS_ENTRY);\n }\n return false;\n}\n\n/**\n * True when the framework-types dir is on the TypeScript program: either no\n * `tsconfig.json`/`jsconfig.json` exists (the default glob already covers the\n * non-dotted `auro-types/`), or the first one that exists lists the entry in its\n * `include` array. A `files`-only or wrong-typed `include` config counts as \"not\n * wired\" \u2014 the writer would have had to add it, so its absence is a real gap.\n */\nfunction tsProgramIncludesTypes(cwd: string): boolean {\n for (const configRel of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const contents = readOrNull(path.join(cwd, configRel));\n if (contents === null) {\n continue;\n }\n const data = parseJsonc(contents, [], { allowTrailingComma: true }) as\n | Record<string, unknown>\n | undefined;\n // Only the first existing config is authoritative (matches the writer's\n // branch selection in `mergeTsconfigInclude`).\n const include = data?.[TSCONFIG_INCLUDE_KEY];\n if (Array.isArray(include)) {\n // Branch 1: include array \u2014 wired iff it lists the entry.\n return include.includes(TSCONFIG_INCLUDE_ENTRY);\n }\n if (include !== undefined) {\n // Branch 4a: wrong-typed include \u2014 the writer refuses, so it's not wired.\n return false;\n }\n if (\"files\" in (data ?? {})) {\n // Branch 2: `files` suppresses the default glob, so an include is\n // required; its absence here is a real gap.\n return false;\n }\n // Branch 3: neither key \u2014 the default glob already covers `auro-types/`.\n return true;\n }\n // Neither config exists \u2014 the default include glob picks up `auro-types/`.\n return true;\n}\n\n/**\n * Check that every **enabled** editor target's artifact and wiring is present on\n * disk, and report whether the markup-completion target is off. Pure reads \u2014 safe\n * to call after {@link writeEditorArtifacts} on any run.\n */\nexport function verifyEditorWiring(\n cwd: string,\n selection: EditorSelection,\n): EditorWiringVerdict {\n const inconsistencies: string[] = [];\n\n if (selection.vscode) {\n if (!existsSync(toAbsolute(cwd, HTML_CUSTOM_DATA_PATH))) {\n inconsistencies.push(\n `${HTML_CUSTOM_DATA_PATH} is missing \u2014 VS Code markup completions will not work.`,\n );\n }\n if (!settingsHasPointer(cwd)) {\n inconsistencies.push(\n `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME} does not register \"${HTML_CUSTOM_DATA_SETTINGS_ENTRY}\" under \"${HTML_CUSTOM_DATA_SETTINGS_KEY}\".`,\n );\n }\n }\n\n if (selection.svelte && !existsSync(toAbsolute(cwd, SVELTE_TYPES_PATH))) {\n inconsistencies.push(`${SVELTE_TYPES_PATH} is missing.`);\n }\n if (selection.jsx && !existsSync(toAbsolute(cwd, JSX_TYPES_PATH))) {\n inconsistencies.push(`${JSX_TYPES_PATH} is missing.`);\n }\n // A single include wires both TS targets \u2014 check it once when either is on.\n if ((selection.svelte || selection.jsx) && !tsProgramIncludesTypes(cwd)) {\n inconsistencies.push(\n `${TSCONFIG_INCLUDE_ENTRY} is not on the TypeScript program (missing from \"${TSCONFIG_INCLUDE_KEY}\").`,\n );\n }\n\n return { inconsistencies, markupDisabled: !selection.vscode };\n}\n", "/**\n * Orchestration seam for the editor-IntelliSense targets: given the resolved\n * component set, the tag map, and the settled per-target selection, build the\n * enabled artifacts, write them under the project root, and merge their wiring\n * into `.vscode/settings.json` / `tsconfig.json`. Returns a report the command\n * turns into its success summary and stderr warnings.\n *\n * This is the \"impure\" bookend to the pure per-target builders\n * (./htmlCustomData.ts, ./jsxTypes.ts, ./svelteTypes.ts) and the pure config\n * merges (./settings.ts): those decide *what* the files should contain; this\n * module decides *where* they land and *whether* a merge is safe, doing the actual\n * `mkdir`/`writeFile`/`readFile`. Every merge is non-destructive and idempotent\n * (see ./settings.ts); a merge that can't be applied cleanly degrades to a warning\n * carrying the manual one-liner, and the artifact is still written regardless.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Artifact locations +\n * editor wiring / settings.json merge / tsconfig four-branch tree\" and\n * build-order step 3.\n */\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { buildCssSnippets } from \"#init/editors/cssSnippets.js\";\nimport type { EditorSelection } from \"#init/editors/detect.js\";\nimport { buildHtmlCustomData } from \"#init/editors/htmlCustomData.js\";\nimport { buildJsxTypes } from \"#init/editors/jsxTypes.js\";\nimport {\n HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n TSCONFIG_INCLUDE_ENTRY,\n TSCONFIG_INCLUDE_KEY,\n VSCODE_DIR,\n VSCODE_SETTINGS_FILENAME,\n} from \"#init/editors/layout.js\";\nimport type { EditorArtifact } from \"#init/editors/manifest.js\";\nimport {\n mergeTsconfigInclude,\n mergeVsCodeSettings,\n} from \"#init/editors/settings.js\";\nimport { buildSvelteTypes } from \"#init/editors/svelteTypes.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/** Outcome of writing the enabled editor artifacts and wiring. */\nexport interface EditorWriteReport {\n /**\n * Project-root-relative paths of the files created or updated (artifacts plus\n * any settings/tsconfig files a merge actually changed), in write order \u2014 the\n * command lists these in its success message.\n */\n written: string[];\n /**\n * Advisory warnings for merges that were skipped (unparseable file, or the\n * target key held an unexpected type). Each already includes the manual wiring\n * one-liner; the command prints them on stderr. The artifact itself is still\n * written, so IntelliSense works once the consumer adds the line by hand.\n */\n warnings: string[];\n}\n\n/** Absolute path for an artifact's forward-slash, root-relative `filename`. */\nfunction toAbsolute(cwd: string, filename: string): string {\n return path.join(cwd, ...filename.split(\"/\"));\n}\n\n/** Write one artifact, creating its parent directory if needed. */\nasync function writeArtifact(\n cwd: string,\n artifact: EditorArtifact,\n): Promise<string> {\n const absolute = toAbsolute(cwd, artifact.filename);\n await fs.mkdir(path.dirname(absolute), { recursive: true });\n await fs.writeFile(absolute, artifact.contents, \"utf-8\");\n return artifact.filename;\n}\n\n/** Read a file, or `\"\"` when it does not exist (any other error propagates). */\nasync function readOrEmpty(absolute: string): Promise<string> {\n try {\n return await fs.readFile(absolute, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return \"\";\n }\n throw error;\n }\n}\n\n/**\n * Build, write, and wire every **enabled** editor target. Disabled targets are\n * skipped entirely \u2014 no artifact, no directory, no merge (so `init` never creates\n * `.vscode/` or `auro-types/` for a target the consumer turned off). The tsconfig\n * merge runs once when either the JSX or Svelte target is on, and only when a\n * `tsconfig.json` (or its JS-project `jsconfig.json` variant) already exists\n * (absent \u2192 the default program glob already picks up the non-dotted\n * `auro-types/`, so there is nothing to wire).\n */\nexport async function writeEditorArtifacts(\n cwd: string,\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n selection: EditorSelection,\n): Promise<EditorWriteReport> {\n const written: string[] = [];\n const warnings: string[] = [];\n\n if (selection.vscode) {\n written.push(\n await writeArtifact(cwd, buildHtmlCustomData(components, resolvedTags)),\n );\n\n // Register the custom-data file in .vscode/settings.json (created if absent).\n const settingsRel = `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME}`;\n const settingsAbs = toAbsolute(cwd, settingsRel);\n const merged = mergeVsCodeSettings(await readOrEmpty(settingsAbs));\n if (merged.warning) {\n warnings.push(\n `${merged.warning} Add \"${HTML_CUSTOM_DATA_SETTINGS_ENTRY}\" to \"${HTML_CUSTOM_DATA_SETTINGS_KEY}\" in ${settingsRel} by hand.`,\n );\n } else if (merged.changed) {\n await fs.mkdir(path.dirname(settingsAbs), { recursive: true });\n await fs.writeFile(settingsAbs, merged.contents, \"utf-8\");\n written.push(settingsRel);\n }\n }\n\n if (selection.jsx) {\n written.push(\n await writeArtifact(cwd, buildJsxTypes(components, resolvedTags)),\n );\n }\n\n if (selection.svelte) {\n written.push(\n await writeArtifact(cwd, buildSvelteTypes(components, resolvedTags)),\n );\n }\n\n // CSS `::part()` snippets are write-only: VS Code auto-discovers the\n // `.code-snippets` file, so there is no settings/tsconfig merge. The builder\n // returns null when no installed component exposes any cssParts \u2014 nothing to\n // write then, so the artifact (and `.vscode/`) is never created for it.\n if (selection.cssSnippets) {\n const artifact = buildCssSnippets(components, resolvedTags);\n if (artifact) {\n written.push(await writeArtifact(cwd, artifact));\n }\n }\n\n // A single config wiring covers both TS-consuming targets. Prefer tsconfig.json;\n // a JS-based Svelte/JSX project uses jsconfig.json instead (TypeScript ignores\n // jsconfig.json when a tsconfig.json is present, so tsconfig wins when both\n // exist). Only touch an existing config \u2014 neither present is the \"default glob\n // covers the non-dotted auro-types/\" branch, so there is nothing to wire.\n if (selection.jsx || selection.svelte) {\n for (const configRel of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const configAbs = path.join(cwd, configRel);\n const existing = await readOrEmpty(configAbs);\n if (existing === \"\") {\n continue;\n }\n const merged = mergeTsconfigInclude(\n existing,\n TSCONFIG_INCLUDE_ENTRY,\n configRel,\n );\n if (merged.warning) {\n warnings.push(\n `${merged.warning} Add \"${TSCONFIG_INCLUDE_ENTRY}\" to \"${TSCONFIG_INCLUDE_KEY}\" in ${configRel} by hand.`,\n );\n } else if (merged.changed) {\n await fs.writeFile(configAbs, merged.contents, \"utf-8\");\n written.push(configRel);\n }\n // Only the first existing config is authoritative; stop after it.\n break;\n }\n }\n\n return { written, warnings };\n}\n", "/**\n * Build the VS Code CSS snippets artifact (`.vscode/auro.code-snippets`) that\n * gives editor-assisted `::part()` completion for the installed components'\n * shadow parts. Pure: `(components, resolvedTags) \u2192 EditorArtifact | null`.\n *\n * This is the ONLY target that assists shadow-part styling. The other artifacts\n * can't: VS Code CSS custom-data (`css.customData`) has no field to enumerate an\n * element's `::part()` argument names, and the JSX/Svelte `.d.ts` describe\n * attributes, not the CSS the language service resolves `::part()` against. The\n * source data \u2014 each component's CEM `cssParts` (`{ name, description? }`) \u2014 is\n * already installed, so we emit one snippet per component whose body is a\n * `${1|\u2026|}` choice placeholder of that component's part names, keyed and prefixed\n * on the **resolved tag** the consumer actually writes in a stylesheet.\n *\n * VS Code auto-discovers any `.vscode/*.code-snippets` file, so \u2014 unlike the HTML\n * custom-data target \u2014 nothing registers this in `settings.json`; writing the\n * file is the whole wiring. `scope: \"css,scss,less\"` fires it across plain CSS\n * and the SCSS/LESS preprocessors (and Svelte `<style>`, which is CSS-language \u2014\n * a part there needs a `:global(...)` wrapper because of Svelte's style scoping).\n *\n * Returns `null` when no installed component exposes any `cssParts`, so `init`\n * writes nothing rather than an empty `{}` snippets file.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 the CSS `::part()` snippets decision.\n */\n\nimport { CSS_SNIPPETS_PATH } from \"#init/editors/layout.js\";\nimport {\n type EditorArtifact,\n ensureTrailingNewline,\n resolvedTagFor,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/** One VS Code snippet entry (the value side of a `.code-snippets` map). */\ninterface CodeSnippet {\n scope: string;\n prefix: string;\n body: string[];\n description: string;\n}\n\n/**\n * The stylesheet languages the snippet fires in. Plain CSS plus the two\n * preprocessors that share `::part()` selector syntax; Svelte `<style>` is\n * CSS-language and picks it up too (with a documented `:global(...)` caveat).\n */\nconst SNIPPET_SCOPE = \"css,scss,less\";\n\n/**\n * A part name is dropped when it contains a character that would corrupt the\n * `${1|a,b,c|}` choice placeholder (`,` and `|` are its delimiters, `}` closes\n * it). Real CSS part names are identifiers, so this only guards against a\n * malformed CEM \u2014 it never trims a legitimate name.\n */\nfunction isChoiceSafe(name: string): boolean {\n return !/[,|}]/u.test(name);\n}\n\n/**\n * Part names for one component: its declared `cssParts`, each pruned to a\n * non-empty, choice-safe string name (mirrors the manifest's `hasName` guard).\n * Order is preserved so the choice list reads in the component's declared order.\n */\nfunction partNames(component: ResolvedComponent): string[] {\n return (component.declaration.cssParts ?? [])\n .map((part) => part.name)\n .filter((name): name is string => typeof name === \"string\" && name !== \"\")\n .filter(isChoiceSafe);\n}\n\n/** Build the `${1|\u2026|}` choice-placeholder snippet for one tag + its part names. */\nfunction snippetFor(tag: string, parts: string[]): CodeSnippet {\n const choice = `\\${1|${parts.join(\",\")}|}`;\n return {\n scope: SNIPPET_SCOPE,\n prefix: `${tag}::part`,\n body: [`${tag}::part(${choice}) {`, \"\\t$0\", \"}\"],\n description: `Style a shadow part of <${tag}> (${parts.join(\", \")})`,\n };\n}\n\n/**\n * Render the CSS `::part()` snippets for the resolved component set. Each\n * component with at least one usable part contributes one snippet keyed\n * `Auro <tag> ::part`; components with no parts are omitted. Returns the\n * artifact's project-root-relative path plus its contents, or `null` when no\n * component exposes any parts (so the caller writes nothing). Writing is the\n * caller's job.\n */\nexport function buildCssSnippets(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact | null {\n const snippets: Record<string, CodeSnippet> = {};\n\n for (const component of components) {\n const parts = partNames(component);\n if (parts.length === 0) {\n continue;\n }\n const tag = resolvedTagFor(component, resolvedTags);\n snippets[`Auro <${tag}> ::part`] = snippetFor(tag, parts);\n }\n\n if (Object.keys(snippets).length === 0) {\n return null;\n }\n\n return {\n filename: CSS_SNIPPETS_PATH,\n contents: ensureTrailingNewline(JSON.stringify(snippets, null, 2)),\n };\n}\n", "/**\n * Build the VS Code HTML custom-data artifact (`.vscode/auro.html-custom-data.json`)\n * that drives tag/attribute IntelliSense in `.html` files via VS Code's HTML\n * Language Server. Pure: `(components, resolvedTags) \u2192 EditorArtifact`.\n *\n * The HTML tool has no per-tag rename hook, so the resolved tags are baked in by\n * pre-swapping the manifest ({@link buildManifest} with `resolvedTags`) \u2014 the\n * emitted custom-data is keyed on the tags a consumer actually registers\n * (`<myapp-button>`), never the bare `auro-*` tags. The tool insists on writing\n * its output to disk as well as returning it; we point it at a scratch dir and\n * keep only the returned string.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 build-order step 2.\n */\n\nimport { getVsCodeHtmlCustomData } from \"custom-element-vs-code-integration\";\nimport { HTML_CUSTOM_DATA_PATH } from \"#init/editors/layout.js\";\nimport {\n buildManifest,\n type EditorArtifact,\n ensureTrailingNewline,\n withTempDir,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/**\n * Render the HTML custom-data JSON for the resolved component set. Returns the\n * artifact's project-root-relative path plus its contents; writing is the\n * caller's job (`init`).\n */\nexport function buildHtmlCustomData(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact {\n const manifest = buildManifest(components, resolvedTags);\n const contents = withTempDir((outdir) =>\n // The tool types its manifest param as the strict `custom-elements-manifest`\n // CEM; our loose Manifest is compatible at runtime, so cast to the tool's own\n // parameter type rather than reshaping our model.\n getVsCodeHtmlCustomData(\n manifest as unknown as Parameters<typeof getVsCodeHtmlCustomData>[0],\n {\n outdir,\n htmlFileName: \"auro.html-custom-data.json\",\n hideLogs: true,\n },\n ),\n );\n return {\n filename: HTML_CUSTOM_DATA_PATH,\n contents: ensureTrailingNewline(contents),\n };\n}\n", "/**\n * Non-destructive, idempotent merges of the two consumer config files `auro init`\n * wires the editor artifacts into: `.vscode/settings.json` (registers the HTML\n * custom-data file) and `tsconfig.json` (puts the framework `.d.ts` bundles on\n * the TypeScript program). Both are pure `(existing, entry) \u2192 MergeResult`\n * string transforms \u2014 reading and writing are the caller's job.\n *\n * Comment- and formatting-preserving via `jsonc-parser`'s surgical `modify` /\n * `applyEdits` (never a parse-then-stringify round-trip, which would strip a\n * consumer's comments and reorder their keys). Every merge:\n * - creates the key/file when absent, appends when present, and is a no-op when\n * the Auro entry is already there (idempotent \u2014 re-running `init` never\n * duplicates or reorders);\n * - refuses to touch a file it cannot cleanly parse, returning a `warning`\n * instead of throwing so the command can still write the artifact and print\n * the manual one-liner.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 settings.json merge\"\n * and the tsconfig four-branch decision tree.\n */\n\nimport {\n applyEdits,\n modify,\n type ParseError,\n parse as parseJsonc,\n parseTree,\n} from \"jsonc-parser\";\nimport {\n HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n TSCONFIG_INCLUDE_ENTRY,\n TSCONFIG_INCLUDE_KEY,\n} from \"#init/editors/layout.js\";\n\n/** The outcome of a config-file merge. */\nexport interface MergeResult {\n /**\n * The file contents to write. When {@link changed} is false this is the input\n * verbatim (the caller may skip the write entirely).\n */\n contents: string;\n /** True when the merge produced an edit the caller should write. */\n changed: boolean;\n /**\n * Set when the merge was skipped because the file could not be safely edited\n * (unparseable, or the target key holds an unexpected type). The caller surfaces\n * it as a warning and falls back to printing the manual wiring line.\n */\n warning?: string;\n}\n\n/** 2-space, spaces-not-tabs \u2014 the prevailing style for these config files. */\nconst FORMATTING = { tabSize: 2, insertSpaces: true } as const;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Parse `source` as JSONC, returning the object or a reason it can't be edited.\n * An empty/whitespace-only file is treated as an empty object (the merge will\n * create it). Any syntax error, or a root that isn't an object, is refused \u2014\n * we never guess at a malformed file's intent.\n */\nfunction parseObject(\n source: string,\n label: string,\n): { data: Record<string, unknown> } | { warning: string } {\n if (source.trim() === \"\") {\n return { data: {} };\n }\n const errors: ParseError[] = [];\n const data = parseJsonc(source, errors, { allowTrailingComma: true });\n if (errors.length > 0) {\n return { warning: `${label} is not valid JSON \u2014 leaving it untouched.` };\n }\n if (!isPlainObject(data)) {\n return { warning: `${label} is not a JSON object \u2014 leaving it untouched.` };\n }\n return { data };\n}\n\n/**\n * Apply a single value edit at `path` to `source` (an empty file becomes `{}`\n * first so `modify` has an object to edit into), preserving surrounding comments\n * and formatting.\n */\nfunction applyValueEdit(\n source: string,\n path: string[],\n value: unknown,\n): string {\n const base = source.trim() === \"\" ? \"{}\" : source;\n const edits = modify(base, path, value, { formattingOptions: FORMATTING });\n return applyEdits(base, edits);\n}\n\n/**\n * Splice out `key` when it is the object's **only** top-level property, returning\n * `null` in every other case (not an object, more than one property, or a\n * different sole key). `jsonc-parser`'s `modify` reformats an object to `{}` when\n * its last property is deleted, which discards any interior comment\n * (`{ // note\\n \"k\": v }` \u2192 `{}`); removing just the property node preserves that\n * comment. Only the last-property case needs this \u2014 with siblings remaining,\n * `modify` already keeps comments.\n */\nfunction deleteLoneTopLevelKey(source: string, key: string): string | null {\n const root = parseTree(source);\n if (!root || root.type !== \"object\" || root.children?.length !== 1) {\n return null;\n }\n const prop = root.children[0];\n if (prop.children?.[0]?.value !== key) {\n return null;\n }\n let end = prop.offset + prop.length;\n while (end < source.length && source[end] === \",\") {\n end++; // swallow a trailing comma so no stray `{ , }` is left behind\n }\n return source.slice(0, prop.offset) + source.slice(end);\n}\n\n/**\n * Surgically remove the property at `path` from `source`, preserving surrounding\n * comments and formatting. `modify(..., undefined, ...)` emits the delete edit;\n * `applyEdits` splices it in without a parse-then-stringify round-trip. The\n * inverse of {@link applyValueEdit}, used by the un-merge helpers below.\n *\n * For a lone top-level key we splice the property node ourselves so a user's\n * interior comment survives, since `modify` would drop it when emptying the object.\n */\nfunction applyKeyDeletion(source: string, path: string[]): string {\n if (path.length === 1) {\n const surgical = deleteLoneTopLevelKey(source, path[0]);\n if (surgical !== null) {\n return surgical;\n }\n }\n const edits = modify(source, path, undefined, {\n formattingOptions: FORMATTING,\n });\n return applyEdits(source, edits);\n}\n\n/**\n * Register the HTML custom-data file in `.vscode/settings.json` under\n * `html.customData`, appending non-destructively:\n * - absent \u2192 create the key as a one-element array;\n * - a string (VS Code allows a bare string) \u2192 normalise to `[existing, entry]`;\n * - an array \u2192 append the entry if missing;\n * - already present (string or array) \u2192 no-op;\n * - any other type \u2192 refuse and warn.\n */\nexport function mergeVsCodeSettings(\n existing: string,\n entry: string = HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n): MergeResult {\n const parsed = parseObject(existing, \".vscode/settings.json\");\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const current = parsed.data[HTML_CUSTOM_DATA_SETTINGS_KEY];\n\n let nextValue: string[];\n if (current === undefined) {\n nextValue = [entry];\n } else if (typeof current === \"string\") {\n if (current === entry) {\n return { contents: existing, changed: false };\n }\n nextValue = [current, entry];\n } else if (Array.isArray(current)) {\n if (current.includes(entry)) {\n return { contents: existing, changed: false };\n }\n nextValue = [...(current as string[]), entry];\n } else {\n return {\n contents: existing,\n changed: false,\n warning: `.vscode/settings.json \"${HTML_CUSTOM_DATA_SETTINGS_KEY}\" is not a string or array \u2014 leaving it untouched.`,\n };\n }\n\n const contents = applyValueEdit(\n existing,\n [HTML_CUSTOM_DATA_SETTINGS_KEY],\n nextValue,\n );\n return { contents, changed: true };\n}\n\n/**\n * Put the framework types dir on the TypeScript program via a `tsconfig.json` or\n * `jsconfig.json` (identical `include`/`files` schema \u2014 a JS Svelte/JSX project\n * uses the `jsconfig.json` variant), following the four-branch decision tree that\n * keeps the default `**` + `/*` include working:\n * 1. `include` present (array) \u2192 append the entry if missing.\n * 2. `files` present, no `include` \u2192 specifying `files` suppresses the default\n * glob, so add `include: [entry]` to bring the types back in.\n * 3. neither `files` nor `include` \u2192 the default glob already picks up the\n * non-dotted types dir; **do not edit** (no-op, no warning).\n * 4. `include` present but not an array, or the file is unparseable \u2192 refuse\n * and warn.\n *\n * `configName` is used only for the parse/refusal messages so they name the file\n * actually being merged. Idempotent: an entry already in `include` is a no-op.\n */\nexport function mergeTsconfigInclude(\n existing: string,\n entry: string = TSCONFIG_INCLUDE_ENTRY,\n configName = \"tsconfig.json\",\n): MergeResult {\n const parsed = parseObject(existing, configName);\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const { data } = parsed;\n const include = data[TSCONFIG_INCLUDE_KEY];\n\n // Branch 1: an existing include array \u2014 append if the entry isn't there.\n if (Array.isArray(include)) {\n if (include.includes(entry)) {\n return { contents: existing, changed: false };\n }\n const contents = applyValueEdit(\n existing,\n [TSCONFIG_INCLUDE_KEY],\n [...(include as string[]), entry],\n );\n return { contents, changed: true };\n }\n\n // Branch 4a: include present but the wrong type \u2014 don't guess at it.\n if (include !== undefined) {\n return {\n contents: existing,\n changed: false,\n warning: `${configName} \"${TSCONFIG_INCLUDE_KEY}\" is not an array \u2014 leaving it untouched.`,\n };\n }\n\n // Branch 2: `files` suppresses the default glob, so an include is required.\n if (\"files\" in data) {\n const contents = applyValueEdit(existing, [TSCONFIG_INCLUDE_KEY], [entry]);\n return { contents, changed: true };\n }\n\n // Branch 3: neither key \u2014 the default glob already covers the non-dotted dir.\n return { contents: existing, changed: false };\n}\n\n/**\n * Reverse {@link mergeVsCodeSettings}: remove the HTML custom-data entry from\n * `.vscode/settings.json` `html.customData`, the un-merge `auro init --reset`\n * applies. Non-destructive and idempotent \u2014 only our own entry is touched:\n * - an array containing `entry` \u2192 drop it; if that empties the array, delete\n * the whole key (so no dangling `\"html.customData\": []` is left behind);\n * - a bare string equal to `entry` \u2192 delete the key;\n * - `entry` absent, key absent, or the value is some other type \u2192 no-op (there\n * is nothing of ours to remove);\n * - unparseable file \u2192 refuse and warn, same contract as the merge.\n */\nexport function unmergeVsCodeSettings(\n existing: string,\n entry: string = HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n): MergeResult {\n const parsed = parseObject(existing, \".vscode/settings.json\");\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const current = parsed.data[HTML_CUSTOM_DATA_SETTINGS_KEY];\n\n if (typeof current === \"string\") {\n if (current !== entry) {\n return { contents: existing, changed: false };\n }\n const contents = applyKeyDeletion(existing, [\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n ]);\n return { contents, changed: true };\n }\n\n if (Array.isArray(current)) {\n if (!current.includes(entry)) {\n return { contents: existing, changed: false };\n }\n const remaining = (current as string[]).filter((v) => v !== entry);\n const contents =\n remaining.length === 0\n ? applyKeyDeletion(existing, [HTML_CUSTOM_DATA_SETTINGS_KEY])\n : applyValueEdit(existing, [HTML_CUSTOM_DATA_SETTINGS_KEY], remaining);\n return { contents, changed: true };\n }\n\n // Absent or an unexpected type \u2014 nothing of ours to remove.\n return { contents: existing, changed: false };\n}\n\n/**\n * Reverse {@link mergeTsconfigInclude}: remove the framework-types entry from a\n * `tsconfig.json`/`jsconfig.json` `include` array, the un-merge\n * `auro init --reset` applies. Non-destructive and idempotent:\n * - an `include` array containing `entry` \u2192 drop it; if that empties the array,\n * delete the `include` key entirely (restoring the default-glob branch the\n * merge relied on when it created a single-entry include);\n * - `include` not an array, absent, or without `entry` \u2192 no-op;\n * - unparseable file \u2192 refuse and warn.\n */\nexport function unmergeTsconfigInclude(\n existing: string,\n entry: string = TSCONFIG_INCLUDE_ENTRY,\n configName = \"tsconfig.json\",\n): MergeResult {\n const parsed = parseObject(existing, configName);\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const include = parsed.data[TSCONFIG_INCLUDE_KEY];\n if (!Array.isArray(include) || !include.includes(entry)) {\n return { contents: existing, changed: false };\n }\n\n const remaining = (include as string[]).filter((v) => v !== entry);\n const contents =\n remaining.length === 0\n ? applyKeyDeletion(existing, [TSCONFIG_INCLUDE_KEY])\n : applyValueEdit(existing, [TSCONFIG_INCLUDE_KEY], remaining);\n return { contents, changed: true };\n}\n", "/**\n * Frozen layout for the files `auro init` writes: the canonical `AGENTS.md`\n * grounding file and the thin `CLAUDE.md` that imports it.\n *\n * FROZEN per docs/pt-m1-completion-plan.md \u2192 build-order step 1 (\"freeze the file\n * format\") and \"Frozen decisions \u2192 `AGENTS.md` vs data files\". This module owns\n * the input-INDEPENDENT scaffolding only: the header/intro, the frozen top-level\n * section order, the regeneration note, and the `CLAUDE.md` body. The generator\n * (build-order step 4) fills the per-component API bodies and the resolved\n * tag/import/registration lines around this scaffolding; it must not re-derive\n * these constants.\n *\n * @see {@link AURO_CODING_RULES} in ./rules.ts for the \"Auro Coding Rules\" body.\n * @see test/fixtures/init/ for the golden assembled documents this pins.\n */\n\n/**\n * Canonical name of the grounding file. `CLAUDE.md` imports this by name, so the\n * two must agree.\n */\nexport const AGENTS_FILENAME = \"AGENTS.md\";\n\n/** The thin per-assistant import file name. */\nexport const CLAUDE_FILENAME = \"CLAUDE.md\";\n\n/**\n * Frozen top-level section order of `AGENTS.md`. The generator emits these H2\n * sections in exactly this order; the per-component subsections (H3) live under\n * \"Installed Components\". Changing this order is a format change (see module\n * doc) \u2014 bump behavior deliberately, don't reorder ad hoc.\n */\nexport const SECTION_HEADINGS = [\n \"What is Auro?\",\n \"Auro Coding Rules\",\n \"Installed Components\",\n \"Regeneration\",\n] as const;\n\n/**\n * The stable marker string baked into every generated `AGENTS.md` (inside the\n * \"do not edit\" HTML comment below). `auro init --reset` uses this as the\n * signature that a file is Auro-generated and therefore safe to delete \u2014 sharing\n * one source of truth with {@link GROUNDING_HEADER} so the guard can never drift\n * from the header it checks for.\n */\nexport const GROUNDING_MARKER = \"Generated by `auro init`\";\n\n/**\n * The document header + intro + \"What is Auro?\" section \u2014 everything above the\n * coding rules. Input-independent, so it lives here as a frozen constant.\n */\nexport const GROUNDING_HEADER = `# Auro Design System \u2014 AI Assistant Grounding\n\n<!-- ${GROUNDING_MARKER}. Do not edit by hand \u2014 re-run \\`auro init\\` to\nregenerate. Custom element tags are governed by \\`auro.config.json\\`. -->\n\nAlaska Airlines open-source design system | https://auro.alaskaair.com\n\nThis file grounds AI assistants in the Auro components **installed in this\nproject**. It lists only installed packages, their exact registered tags, and the\nfull API for the installed version of each component. Treat it as authoritative\nfor this project.\n\n## What is Auro?\n\nAuro is Alaska Airlines' design system, built on Web Components (Custom Elements\nv1) using the Lit library.\n- npm scope: \\`@aurodesignsystem/\\` (current), \\`@alaskaairux/\\` (legacy)\n- Framework-agnostic: works with React, Angular, Vue, Svelte, or plain HTML\n- Each component is a separate npm package and registers a custom element tag\n`;\n\n/**\n * Column header for the \"Installed Components\" summary table. The generator\n * emits one row per resolved component beneath it.\n */\nexport const INSTALLED_TABLE_HEADER = `| Tag | Package | Version | Import |\n|---|---|---|---|`;\n\n/**\n * The closing \"Regeneration\" section. Input-independent, so it's frozen here.\n */\nexport const REGENERATION_NOTE = `## Regeneration\n\nThis file is generated by \\`auro init\\`. Re-run it after adding or removing an Auro\ndependency to update the component list and APIs. Custom element tags are governed\nby \\`auro.config.json\\` (committed by default) \u2014 change prefixes there, not in this\nfile, then re-run \\`auro init\\`.\n`;\n\n/**\n * The entire body of the generated \\`CLAUDE.md\\`: a thin import of \\`AGENTS.md\\` so a\n * single canonical grounding file serves every assistant target (task #5). This\n * is the ONLY justified indirection (see \"Frozen decisions \u2192 \\`AGENTS.md\\` vs data\n * files\").\n */\nexport const CLAUDE_MD = `@${AGENTS_FILENAME}\n`;\n", "/**\n * The static \"Auro coding rules\" block embedded in every generated `AGENTS.md`.\n *\n * FROZEN per docs/pt-m1-completion-plan.md \u2192 \"Frozen decisions\" (the ticket's\n * bus-factor note: freeze the file format early). This is input-independent\n * prose; the per-component API bodies and the resolved tag/import lines are\n * assembled around it by the generator (build-order step 4). Edit here \u2014 never\n * inline in the generator \u2014 so the rules stay in one place.\n *\n * The block owns its own `## Auro Coding Rules` heading so it can be dropped into\n * the document (or reused for future targets) as a self-contained unit.\n */\nexport const AURO_CODING_RULES = `## Auro Coding Rules\n\nThese rules apply to every Auro component in this project. Use the exact\nregistered tags listed under **Installed Components** below: this project uses\ncustom registration, so a component's tag may differ from its default \\`auro-*\\`\nname.\n\n1. **Use Auro custom-element tags, never plain HTML equivalents.**\n - \u2717 \\`<button>\\` \u2192 \u2713 the registered Auro button tag\n - \u2717 \\`<input>\\` \u2192 \u2713 the registered Auro input tag (from \\`auro-formkit\\`)\n\n Only use components listed under **Installed Components**. Do not invent tags\n or reference components this project has not installed.\n\n2. **Import and register each component before use.** Each component ships its\n own import, and this project registers components under custom tags. The exact\n \\`import\\` + \\`register(...)\\` snippet for each component is shown in its section\n below. \\`auro-formkit\\` has no root export \u2014 always import the specific\n sub-component via its subpath export (e.g.\n \\`@aurodesignsystem/auro-formkit/auro-input\\`).\n\n3. **Attributes in markup, camelCase properties in JS.** The same field is a\n kebab-case attribute in HTML and a camelCase property in JavaScript.\n \\`\\`\\`html\n <!-- attribute -->\n <auro-button disabled>Save</auro-button>\n \\`\\`\\`\n \\`\\`\\`js\n element.loading = true; // property\n \\`\\`\\`\n\n4. **Put content in named slots, not \\`innerHTML\\`.** Each component's slot names\n are listed in its API section below.\n\n5. **Use design tokens for color, spacing, and type.** Install\n \\`@aurodesignsystem/design-tokens\\` and use the \\`--ds-basic-*\\` /\n \\`--ds-advanced-*\\` CSS custom properties rather than hard-coded values.\n\n6. **Accessibility is built in \u2014 don't override it.** Auro components ship WCAG\n 2.1 AA behavior (focus management, ARIA, error messaging). Prefer the provided\n slots and attributes over custom ARIA.\n`;\n", "/**\n * Pure formatting/naming helpers for the `auro component` command. Kept separate\n * from the command wiring so they can be unit-tested without importing commander,\n * ora, or triggering the command's side effects.\n */\n\nimport { type CemDeclaration, clean, type Deprecated } from \"#utils/cem.js\";\n\nconst SCOPE = \"@aurodesignsystem\";\n\n/**\n * Normalize a user-supplied component name into a full npm package name.\n * Accepts \"button\", \"auro-button\", or \"@aurodesignsystem/auro-button\" (and\n * tolerates surrounding whitespace / casing). An explicit scope is respected.\n */\nexport function toPackageName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.startsWith(\"@\")) {\n return trimmed;\n }\n const lower = trimmed.toLowerCase();\n if (lower.startsWith(\"auro-\")) {\n return `${SCOPE}/${lower}`;\n }\n return `${SCOPE}/auro-${lower}`;\n}\n\n/**\n * Convert a kebab-case attribute name to its camelCase property form\n * (`no-validate` \u2192 `noValidate`), matching how Lit maps attributes to fields.\n */\nexport function kebabToCamel(name: string): string {\n return name.replace(/-([a-z])/gu, (_, char: string) => char.toUpperCase());\n}\n\n/**\n * Render a `[deprecated]` (optionally with a reason) marker.\n */\nexport function deprecatedTag(deprecated: Deprecated): string {\n if (!deprecated) {\n return \"\";\n }\n return typeof deprecated === \"string\"\n ? ` [deprecated: ${clean(deprecated)}]`\n : \" [deprecated]\";\n}\n\n/**\n * Render a two-column list (name \u2192 description) with aligned padding.\n */\nexport function renderList(rows: Array<[string, string]>): string {\n if (rows.length === 0) {\n return \" (none)\";\n }\n // Coerce label/description defensively: published manifests occasionally ship\n // an entry missing its `name` (the types promise a string but the data can\n // violate it), and one bad row must not crash the whole lookup.\n const width = Math.max(...rows.map(([label]) => (label ?? \"\").length));\n return rows\n .map(([label, desc]) =>\n ` ${(label ?? \"\").padEnd(width)} ${desc ?? \"\"}`.trimEnd(),\n )\n .join(\"\\n\");\n}\n\n/** Overrides for the `Install:` lines when the import differs from the header package. */\nexport interface FormatDeclarationOptions {\n /** Package to `npm i` (defaults to the header `pkg`). */\n installPkg?: string;\n /** Module specifier to `import` (defaults to the header `pkg`). */\n importSpecifier?: string;\n}\n\n/**\n * Format one custom-element declaration into a readable summary. `pkg` heads the\n * declaration and drives the `Install:` lines by default; when the element is\n * fetched from a monorepo that re-exports it under a subpath (e.g. a legacy form\n * component now served by `@aurodesignsystem/auro-formkit`), pass `installPkg` /\n * `importSpecifier` so the install snippet points at the package to install and the\n * exact subpath to import.\n */\nexport function formatDeclaration(\n pkg: string,\n decl: CemDeclaration,\n options: FormatDeclarationOptions = {},\n): string {\n const { installPkg = pkg, importSpecifier = pkg } = options;\n const lines: string[] = [];\n\n lines.push(`${decl.tagName} (${pkg})`);\n const description = decl.summary || decl.description;\n if (description) {\n lines.push(clean(description));\n }\n const heritage = decl.superclass?.name\n ? `${decl.name} extends ${decl.superclass.name}`\n : decl.name;\n lines.push(`Class: ${heritage}`);\n\n lines.push(\"\");\n lines.push(\"Install:\");\n lines.push(` npm i ${installPkg}`);\n lines.push(` import \"${importSpecifier}\";`);\n\n lines.push(...apiBodyLines(decl));\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render the API sections of a declaration \u2014 Attributes, Properties & Methods,\n * Slots, Events, and (when present) CSS Parts / CSS Custom Properties \u2014 as a list\n * of lines, led by a blank separator. Shared by {@link formatDeclaration} (the\n * `component` command's full render) and `auro init`'s per-component grounding\n * sections, which wrap this same body under their own resolved-tag header and\n * prefix/subpath-aware install lines. Returns lines (not a joined string) so a\n * caller can splice them into a larger `lines` array.\n */\nexport function apiBodyLines(decl: CemDeclaration): string[] {\n const lines: string[] = [];\n\n const attributes = decl.attributes ?? [];\n lines.push(\"\");\n lines.push(`Attributes (${attributes.length}):`);\n lines.push(\n renderList(\n attributes.map((a) => {\n const type = a.type?.text ? ` {${clean(a.type.text)}}` : \"\";\n const def = a.default ? ` = ${clean(a.default)}` : \"\";\n return [\n a.name,\n `${clean(a.description)}${type}${def}${deprecatedTag(a.deprecated)}`.trim(),\n ];\n }),\n ),\n );\n\n // Public properties/methods not already covered by an attribute. An\n // attribute's backing field is named by `fieldName`; when a manifest omits it\n // we fall back to the attribute `name` and its camelCase form (attribute\n // names are kebab-case, fields camelCase) so the field isn't listed a second\n // time under Properties & Methods.\n const attrFields = new Set(\n attributes.flatMap((a) =>\n a.fieldName ? [a.fieldName] : [a.name, kebabToCamel(a.name)],\n ),\n );\n const members = (decl.members ?? []).filter(\n (m) =>\n // A member with no name is malformed CEM data \u2014 it can't be referenced,\n // so drop it rather than list an unnamed row.\n m.name &&\n (m.privacy === undefined || m.privacy === \"public\") &&\n !m.static &&\n !(m.kind === \"field\" && attrFields.has(m.name)),\n );\n lines.push(\"\");\n lines.push(`Properties & Methods (${members.length}):`);\n lines.push(\n renderList(\n members.map((m) => {\n const isMethod = m.kind === \"method\";\n const label = isMethod ? `${m.name}()` : m.name;\n const typeText = isMethod ? m.return?.type?.text : m.type?.text;\n const type = typeText ? ` {${clean(typeText)}}` : \"\";\n const def = !isMethod && m.default ? ` = ${clean(m.default)}` : \"\";\n return [\n label,\n `${clean(m.description)}${type}${def}${deprecatedTag(m.deprecated)}`.trim(),\n ];\n }),\n ),\n );\n\n const slots = decl.slots ?? [];\n lines.push(\"\");\n lines.push(`Slots (${slots.length}):`);\n lines.push(\n renderList(slots.map((s) => [s.name || \"(default)\", clean(s.description)])),\n );\n\n const events = decl.events ?? [];\n lines.push(\"\");\n lines.push(`Events (${events.length}):`);\n lines.push(\n renderList(\n events.map((e) => {\n const type = e.type?.text ? ` {${clean(e.type.text)}}` : \"\";\n return [e.name, `${clean(e.description)}${type}`.trim()];\n }),\n ),\n );\n\n const cssParts = decl.cssParts ?? [];\n if (cssParts.length > 0) {\n lines.push(\"\");\n lines.push(`CSS Parts (${cssParts.length}):`);\n lines.push(renderList(cssParts.map((p) => [p.name, clean(p.description)])));\n }\n\n const cssProps = decl.cssProperties ?? [];\n if (cssProps.length > 0) {\n lines.push(\"\");\n lines.push(`CSS Custom Properties (${cssProps.length}):`);\n lines.push(renderList(cssProps.map((p) => [p.name, clean(p.description)])));\n }\n\n return lines;\n}\n", "/**\n * Render the grounding files `auro init` writes \u2014 the canonical `AGENTS.md` and\n * the thin `CLAUDE.md` \u2014 from a resolved component set plus the resolved custom\n * tags. Pure, side-effect-free string builders: detection, resolution, and tag\n * resolution happen upstream (`resolver.ts` / `registry.ts`); this module only\n * assembles the frozen scaffolding (`layout.ts` / `rules.ts`) around each\n * component's resolved tag, prefix/subpath-aware install lines, and API body.\n *\n * The generator takes resolved tags as an INPUT \u2014 it never computes prefixes\n * itself (that is `registry.ts`). Structured as a set of per-target renderers so\n * future targets (e.g. `copilot-instructions.md`) are additive over the same\n * `ResolvedComponent[]` model, per build-order step 4 / task #11.\n */\n\nimport {\n AGENTS_FILENAME,\n CLAUDE_FILENAME,\n CLAUDE_MD,\n GROUNDING_HEADER,\n INSTALLED_TABLE_HEADER,\n REGENERATION_NOTE,\n} from \"#init/layout.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\nimport { AURO_CODING_RULES } from \"#init/rules.js\";\nimport { clean } from \"#utils/cem.js\";\nimport { apiBodyLines } from \"#utils/formatComponent.js\";\n\n/** A file `auro init` writes: its name and full contents. */\nexport interface GroundingFile {\n /** The file to write, relative to the project root (e.g. `AGENTS.md`). */\n filename: string;\n /** The complete file contents. */\n contents: string;\n}\n\n/**\n * The tag to display for a component: its resolved custom/prefixed tag when the\n * registry provided one (keyed by the canonical bare `auro-*` tag), else the\n * canonical tag itself. The generator never derives prefixes \u2014 an absent entry\n * simply means \"no custom registration\", so the bare tag stands.\n */\nfunction displayTag(\n component: ResolvedComponent,\n resolvedTags: ReadonlyMap<string, string>,\n): string {\n return resolvedTags.get(component.tagName) ?? component.tagName;\n}\n\n/**\n * Render one component's fenced grounding block: a resolved-tag header, the\n * prefix/subpath-aware install + register snippet, and the shared API body. The\n * import line uses the component's `importPath` (package root for a standalone,\n * subpath export for a monorepo component); the register line uses the resolved\n * tag so an assistant copies the exact call this project expects.\n */\nfunction componentBlock(component: ResolvedComponent, tag: string): string {\n const { pkg, importPath, declaration: decl } = component;\n const lines: string[] = [`${tag} (${pkg})`];\n\n const description = decl.summary || decl.description;\n if (description) {\n lines.push(clean(description));\n }\n\n const heritage = decl.superclass?.name\n ? `${decl.name} extends ${decl.superclass.name}`\n : decl.name;\n lines.push(`Class: ${heritage}`);\n\n lines.push(\"\");\n lines.push(\"Install:\");\n lines.push(` npm i ${pkg}`);\n lines.push(` import \"${importPath}\";`);\n lines.push(` ${decl.name}.register('${tag}');`);\n\n lines.push(...apiBodyLines(decl));\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render the canonical `AGENTS.md`: the frozen header + coding rules, an\n * Installed Components table with one row per component, a fenced API section per\n * component (with its resolved tag + install/register snippet), and the frozen\n * Regeneration note. Components are emitted in the order given, so a caller\n * controls listing order by ordering the input. Passing an empty list yields a\n * valid document with just the table header and no component rows/sections.\n */\nexport function generateAgentsMd(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string> = new Map(),\n): string {\n const rows = components.map((component) => {\n const tag = displayTag(component, resolvedTags);\n return `| \\`<${tag}>\\` | \\`${component.pkg}\\` | ${component.version} | \\`${component.importPath}\\` |`;\n });\n\n const sections = components.map((component) => {\n const tag = displayTag(component, resolvedTags);\n return `### \\`<${tag}>\\`\\n\\n\\`\\`\\`\\n${componentBlock(component, tag)}\\n\\`\\`\\``;\n });\n\n const installedLines = [\n \"## Installed Components\",\n \"\",\n INSTALLED_TABLE_HEADER,\n ...rows,\n ];\n if (sections.length > 0) {\n installedLines.push(\"\", sections.join(\"\\n\\n\"));\n }\n const installedSection = installedLines.join(\"\\n\");\n\n // Join the frozen sections with a single blank line between each, then one\n // trailing newline. Each constant's own trailing whitespace is trimmed so the\n // spacing is governed here, not by the constants.\n return `${[\n GROUNDING_HEADER.trimEnd(),\n AURO_CODING_RULES.trimEnd(),\n installedSection,\n REGENERATION_NOTE.trimEnd(),\n ].join(\"\\n\\n\")}\\n`;\n}\n\n/** Render the thin `CLAUDE.md` \u2014 the frozen `@AGENTS.md` import. */\nexport function generateClaudeMd(): string {\n return CLAUDE_MD;\n}\n\n/**\n * Render every grounding file `auro init` writes for v1: the canonical\n * `AGENTS.md` and the thin `CLAUDE.md` that imports it. Returned as a list so the\n * command writes them uniformly and future targets are additive here.\n */\nexport function groundingFiles(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string> = new Map(),\n): GroundingFile[] {\n return [\n {\n filename: AGENTS_FILENAME,\n contents: generateAgentsMd(components, resolvedTags),\n },\n { filename: CLAUDE_FILENAME, contents: generateClaudeMd() },\n ];\n}\n", "/**\n * Git-ignore reconciliation for the files `auro init` writes. Everything the\n * command emits \u2014 the grounding files, `auro.config.json`, and the editor\n * IntelliSense artifacts plus their wiring \u2014 is meant to be **committed** so a\n * team and CI share one deterministic set. A project `.gitignore` can silently\n * defeat that: `.vscode/` is very commonly ignored, so a `--vscode` run writes\n * `.vscode/auro.html-custom-data.json`, the local editor works, and the file is\n * never committed. This module lets the command detect that and, with consent,\n * repair it.\n *\n * Two functions, both **advisory and non-throwing** (a git hiccup must never\n * break a write that already succeeded):\n * - {@link findIgnored} \u2014 ask git which of the given paths are ignored.\n * - {@link unignore} \u2014 append the minimal `.gitignore` negations to re-include\n * them, verifying with git that the fix actually took.\n *\n * We defer to `git check-ignore` (via the `simple-git` dependency already used in\n * ../utils/gitUtils.ts) rather than parse `.gitignore` ourselves: it honors nested\n * ignore files, `.git/info/exclude`, global excludes, negations, and the rule that\n * a *tracked* file is never ignored \u2014 none of which naive string matching gets\n * right.\n */\n\nimport { appendFileSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { simpleGit } from \"simple-git\";\n\n/** Header marking the block of entries `auro init` appends to `.gitignore`. */\nconst GITIGNORE_HEADER =\n \"# Added by auro init \u2014 keep generated grounding/IntelliSense files tracked\";\n\n/**\n * The subset of `paths` (project-root-relative, forward-slash) that git would\n * ignore \u2014 i.e. that a plain `git add` would not stage. Returns `[]` when `cwd`\n * is not a git repository, git is unavailable, or `paths` is empty, so callers\n * can treat \"no git\" as \"nothing to warn about\". Never throws.\n */\nexport async function findIgnored(\n cwd: string,\n paths: string[],\n): Promise<string[]> {\n if (paths.length === 0) {\n return [];\n }\n try {\n return await simpleGit({ baseDir: cwd }).checkIgnore(paths);\n } catch {\n // Not a git repo / git missing \u2192 ignoring is not in play here.\n return [];\n }\n}\n\n/** POSIX dirname of a forward-slash path, or \"\" for a root-level file. */\nfunction parentDir(rel: string): string {\n const dir = path.posix.dirname(rel);\n return dir === \".\" ? \"\" : dir;\n}\n\n/** Trimmed set of the current `<cwd>/.gitignore` lines (empty when absent). */\nfunction readGitignoreLines(cwd: string): Set<string> {\n try {\n const current = readFileSync(path.join(cwd, \".gitignore\"), \"utf-8\");\n return new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n } catch {\n return new Set();\n }\n}\n\n/**\n * Append `lines` to `<cwd>/.gitignore` (created if absent), preserving a trailing\n * newline. With `dedupe` (the default) any line already present is skipped so\n * re-runs stay idempotent; pass `dedupe: false` for order-sensitive negation\n * blocks whose entries must land in sequence even if an equal line exists earlier\n * (a later match wins in git's last-match-wins rule).\n */\nfunction appendGitignore(cwd: string, lines: string[], dedupe = true): void {\n const gitignoreAbs = path.join(cwd, \".gitignore\");\n let current = \"\";\n try {\n current = readFileSync(gitignoreAbs, \"utf-8\");\n } catch {\n // Absent \u2192 we create it below.\n }\n const existing = new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n const toAdd = dedupe\n ? lines.filter((line) => !existing.has(line.trim()))\n : lines;\n if (toAdd.length === 0) {\n return;\n }\n // Separate the appended block from prior content when the file lacks a final \\n.\n const prefix = current === \"\" || current.endsWith(\"\\n\") ? \"\" : \"\\n\";\n try {\n appendFileSync(gitignoreAbs, `${prefix}${toAdd.join(\"\\n\")}\\n`, \"utf-8\");\n } catch {\n // Advisory and non-throwing (see the module doc): a failed .gitignore write\n // must never break an `init` whose main artifacts already landed. The path\n // simply stays ignored and surfaces to the caller as `unfixable` via the git\n // re-check in `unignore`, rather than crashing the command.\n }\n}\n\n/**\n * Un-ignore `ignoredPaths` by appending the minimal negations to `.gitignore`,\n * verifying each step with git so the returned result is never optimistic.\n *\n * Two rounds, because a bare `!<file>` cannot re-include a file whose parent\n * *directory* is excluded (a documented git limitation):\n * 1. Append `!<path>` for each ignored path; re-check.\n * 2. For anything still ignored (a parent dir is the culprit), append the\n * git-documented re-include trio per parent dir \u2014 `!<dir>/`, `<dir>/*`,\n * `!<path>` \u2014 where `<dir>/*` preserves the ignore for the dir's other files;\n * re-check.\n *\n * @returns `fixed` (now tracked) and `unfixable` (git still reports ignored after\n * both rounds \u2014 surfaced to the caller for manual handling, never silently\n * dropped).\n */\nexport async function unignore(\n cwd: string,\n ignoredPaths: string[],\n): Promise<{ fixed: string[]; unfixable: string[] }> {\n if (ignoredPaths.length === 0) {\n return { fixed: [], unfixable: [] };\n }\n\n // Round 1 \u2014 a simple negation clears a file/glob ignore (`*.json`, a bare name).\n appendGitignore(cwd, [\n GITIGNORE_HEADER,\n ...ignoredPaths.map((rel) => `!${rel}`),\n ]);\n let stillIgnored = await findIgnored(cwd, ignoredPaths);\n\n // Round 2 \u2014 a still-ignored path has an excluded ancestor dir; re-include it,\n // re-exclude its contents (to keep siblings ignored), then re-include the file.\n // Force-append (no dedupe): the `!<path>` must land AFTER `<dir>/*`, but Round 1\n // already wrote `!<path>` earlier \u2014 a deduping append would skip it and leave\n // `<dir>/*` as the last match, re-ignoring the file.\n //\n // A path that stays ignored after Round 2 is unfixable, so it re-enters this\n // block on every re-run. To avoid stacking duplicate trios, skip a path whose\n // trio is already present: `<dir>/*` is only ever written here alongside its\n // `!<path>` entries, so if both lines exist the trio ran on a prior invocation.\n if (stillIgnored.length > 0) {\n const present = readGitignoreLines(cwd);\n const trio: string[] = [];\n const seenDirs = new Set<string>();\n for (const rel of stillIgnored) {\n const dir = parentDir(rel);\n const dirBlockPresent = dir === \"\" || present.has(`${dir}/*`);\n if (dirBlockPresent && present.has(`!${rel}`)) {\n continue; // trio already written on an earlier run \u2014 don't restack it.\n }\n if (dir !== \"\" && !seenDirs.has(dir) && !present.has(`${dir}/*`)) {\n seenDirs.add(dir);\n trio.push(`!${dir}/`, `${dir}/*`);\n }\n trio.push(`!${rel}`);\n }\n if (trio.length > 0) {\n appendGitignore(cwd, trio, false);\n stillIgnored = await findIgnored(cwd, ignoredPaths);\n }\n }\n\n const unfixable = new Set(stillIgnored);\n return {\n fixed: ignoredPaths.filter((rel) => !unfixable.has(rel)),\n unfixable: [...unfixable],\n };\n}\n", "/**\n * The legacy-standalone \u2192 `auro-formkit` migration codemod.\n *\n * A consumer on a legacy standalone form package (`@aurodesignsystem/auro-input`,\n * \u2026) is on the deprecated form of a component that now lives in the\n * `auro-formkit` monorepo. This module detects those dependencies and, on request,\n * rewrites the project onto formkit: it swaps the `package.json` dependency and\n * rewrites the bare import specifiers to the formkit subpath\n * (`@aurodesignsystem/auro-formkit/auro-<x>`).\n *\n * It is intentionally file-in / file-out \u2014 no prompting, no network \u2014 so the `init`\n * command owns the interactive confirm and the non-interactive/CI guard, and so the\n * codemod is unit-testable against a temp fixture. It is **conservative**: only an\n * exact bare specifier is rewritten; a deep import (`\u2026/auro-input/dist/x.js`) is left\n * untouched and reported, since formkit's deep layout is not a 1:1 remap.\n */\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { globSync } from \"glob\";\nimport { SOURCE_GLOB, SOURCE_GLOB_IGNORE } from \"#init/registry.js\";\nimport {\n FORMKIT_PACKAGE,\n formkitSubpathFor,\n isLegacyFormkitPackage,\n LEGACY_FORMKIT_PACKAGES,\n} from \"#static/formkitMigration.js\";\n\n/** A legacy standalone package declared in the consumer's `package.json`. */\nexport interface LegacyDependency {\n /** The standalone package name, e.g. `@aurodesignsystem/auro-input`. */\n pkg: string;\n /** Its declared version range (from `dependencies` or `devDependencies`). */\n version: string;\n /** Which manifest field it was declared in. */\n field: \"dependencies\" | \"devDependencies\";\n}\n\n/** A deep import the codemod deliberately left in place for manual follow-up. */\nexport interface SkippedDeepImport {\n /** The source file (relative to `cwd`) containing the import. */\n file: string;\n /** The full deep specifier, e.g. `@aurodesignsystem/auro-input/dist/index.js`. */\n specifier: string;\n}\n\n/** What {@link migrateToFormkit} changed, for the caller to report and tests to assert. */\nexport interface MigrationReport {\n /** Legacy packages removed from `package.json`. */\n packagesMigrated: string[];\n /** Whether `auro-formkit` was newly added or already a dependency. */\n formkit: \"added\" | \"present\";\n /** Source files (relative to `cwd`) whose import specifiers were rewritten. */\n filesChanged: string[];\n /** Total bare specifiers rewritten across all files. */\n rewriteCount: number;\n /** Deep imports left untouched \u2014 a formkit deep path can't be guessed 1:1. */\n deepImports: SkippedDeepImport[];\n}\n\ntype PackageJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n};\n\nconst PACKAGE_JSON = \"package.json\";\n\n/** Read and parse `<cwd>/package.json`, or `null` when it is absent. */\nfunction readPackageJson(cwd: string): PackageJson | null {\n let raw: string;\n try {\n raw = readFileSync(path.join(cwd, PACKAGE_JSON), \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n try {\n return JSON.parse(raw) as PackageJson;\n } catch {\n throw new Error(`${PACKAGE_JSON}: invalid JSON.`);\n }\n}\n\n/**\n * Detect the legacy standalone form packages declared in the consumer's\n * `package.json` (`dependencies` + `devDependencies`). This is authoritative for\n * \"installed\" \u2014 it is exactly what the migration edits \u2014 and version-independent:\n * any declared legacy standalone qualifies, regardless of how current it is.\n * Returns `[]` when there is no `package.json`; throws on malformed JSON.\n */\nexport function detectLegacyFormkit(cwd: string): LegacyDependency[] {\n const pkgJson = readPackageJson(cwd);\n if (!pkgJson) {\n return [];\n }\n\n const found: LegacyDependency[] = [];\n const fields: LegacyDependency[\"field\"][] = [\n \"dependencies\",\n \"devDependencies\",\n ];\n // Iterate the curated legacy list (stable, deterministic order) rather than the\n // manifest's key order, so the report reads the same across projects.\n for (const pkg of LEGACY_FORMKIT_PACKAGES) {\n for (const field of fields) {\n const version = pkgJson[field]?.[pkg];\n if (typeof version === \"string\") {\n found.push({ pkg, version, field });\n break; // a package in both fields is reported once (dependencies wins)\n }\n }\n }\n return found;\n}\n\n/** Escape a string for literal use inside a `RegExp`. */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Rewrite one source file's legacy specifiers to formkit subpaths. An exact bare\n * specifier (`\"@aurodesignsystem/auro-input\"`, any quote style) is rewritten; a deep\n * specifier (`\"@aurodesignsystem/auro-input/\u2026\"`) is left in place and returned as a\n * skip. Returns the (possibly unchanged) source, the number of rewrites, and any\n * deep imports seen.\n */\nfunction rewriteSource(\n source: string,\n legacyPkgs: readonly string[],\n): { next: string; rewrites: number; deep: string[] } {\n let next = source;\n let rewrites = 0;\n const deep: string[] = [];\n\n for (const pkg of legacyPkgs) {\n const escaped = escapeRegExp(pkg);\n // Exact bare specifier: quote, package, same quote \u2014 the trailing quote rules\n // out any deep `\u2026/dist` path (which has a `/` before the quote).\n const bare = new RegExp(`(['\"\\`])${escaped}\\\\1`, \"g\");\n next = next.replace(bare, (_match, quote: string) => {\n rewrites += 1;\n return `${quote}${formkitSubpathFor(pkg)}${quote}`;\n });\n\n // Deep specifier: quote, package, `/`, anything but the quote, same quote.\n const deepRe = new RegExp(`(['\"\\`])(${escaped}/[^'\"\\`]*)\\\\1`, \"g\");\n let deepMatch: RegExpExecArray | null = deepRe.exec(next);\n while (deepMatch !== null) {\n deep.push(deepMatch[2]);\n deepMatch = deepRe.exec(next);\n }\n }\n\n return { next, rewrites, deep };\n}\n\n/**\n * Migrate the project at `cwd` off the given legacy standalone packages and onto\n * `auro-formkit`: remove each from `package.json`, ensure `auro-formkit` is a\n * dependency (added as `\"latest\"` when absent \u2014 the exact version resolves on the\n * user's next `npm install`; an existing formkit version is kept), and rewrite bare\n * legacy import specifiers across the project's source to the formkit subpath.\n *\n * `legacy` is normally {@link detectLegacyFormkit}'s output; only entries that are\n * genuine legacy packages are acted on. Returns a {@link MigrationReport}.\n */\nexport function migrateToFormkit(\n cwd: string,\n legacy: readonly LegacyDependency[],\n): MigrationReport {\n const legacyPkgs = [\n ...new Set(legacy.map((l) => l.pkg).filter(isLegacyFormkitPackage)),\n ];\n\n const report: MigrationReport = {\n packagesMigrated: [],\n formkit: \"present\",\n filesChanged: [],\n rewriteCount: 0,\n deepImports: [],\n };\n if (legacyPkgs.length === 0) {\n return report;\n }\n\n // 1. package.json \u2014 swap the legacy deps for auro-formkit.\n const pkgJson = readPackageJson(cwd);\n if (pkgJson) {\n for (const field of [\"dependencies\", \"devDependencies\"] as const) {\n const block = pkgJson[field];\n if (!block) {\n continue;\n }\n for (const pkg of legacyPkgs) {\n if (pkg in block) {\n delete block[pkg];\n if (!report.packagesMigrated.includes(pkg)) {\n report.packagesMigrated.push(pkg);\n }\n }\n }\n }\n\n const alreadyHasFormkit =\n Boolean(pkgJson.dependencies?.[FORMKIT_PACKAGE]) ||\n Boolean(pkgJson.devDependencies?.[FORMKIT_PACKAGE]);\n if (alreadyHasFormkit) {\n report.formkit = \"present\";\n } else {\n pkgJson.dependencies ??= {};\n pkgJson.dependencies[FORMKIT_PACKAGE] = \"latest\";\n report.formkit = \"added\";\n }\n\n writeFileSync(\n path.join(cwd, PACKAGE_JSON),\n `${JSON.stringify(pkgJson, null, 2)}\\n`,\n \"utf-8\",\n );\n }\n\n // 2. Source \u2014 rewrite bare legacy specifiers to formkit subpaths.\n const files = globSync(SOURCE_GLOB, {\n cwd,\n absolute: true,\n nodir: true,\n ignore: SOURCE_GLOB_IGNORE,\n });\n for (const file of files) {\n let source: string;\n try {\n source = readFileSync(file, \"utf-8\");\n } catch {\n continue; // unreadable file \u2014 skip, mirrors the scanner's tolerance\n }\n const { next, rewrites, deep } = rewriteSource(source, legacyPkgs);\n const rel = path.relative(cwd, file);\n for (const specifier of deep) {\n report.deepImports.push({ file: rel, specifier });\n }\n if (rewrites > 0 && next !== source) {\n writeFileSync(file, next, \"utf-8\");\n report.filesChanged.push(rel);\n report.rewriteCount += rewrites;\n }\n }\n\n return report;\n}\n", "/**\n * Resolve each installed component's canonical `auro-*` tag to the tag the\n * consumer project actually registers, producing the `resolvedTags`\n * `Map<canonical-tag, custom-tag>` the generator (`generator.ts`) consumes.\n *\n * Resolution precedence is **config \u2192 AST scan \u2192 default prefix** (the frozen\n * decision): an explicit `auro.config.json` override wins; else a\n * statically-detected `register('<tag>')` in consumer source; else the default\n * prefix is applied. Anything unresolvable is **warned, never guessed**.\n *\n * This module is a PURE PLANNER plus two thin IO wrappers (`loadConfig`/\n * `saveConfig`, `scanProject`). It performs no prompting: the interactive prefix\n * prompt, the majority-confirm, and the non-interactive TTY/CI guard live in the\n * `init` command (build-order step 6), which consumes {@link planTagResolution}.\n *\n * **Two-phase caller contract.** Call {@link planTagResolution} once. If the plan\n * reports `needsDefaultPrefix`, obtain a prefix (prompt/confirm `suggestedDefault`,\n * take `--prefix`, or fail cleanly in CI) and **re-call** with that `prefix` to get\n * the authoritative `resolvedTags` + `config`. Only persist (`saveConfig`) a plan\n * whose `needsDefaultPrefix` is `false`.\n */\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { globSync } from \"glob\";\nimport ts from \"typescript\";\nimport {\n type AuroConfig,\n CONFIG_FILENAME,\n CONFIG_VERSION,\n} from \"#init/config.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\nconst AURO_PREFIX = \"auro-\";\n\n/**\n * The consumer source files both the AST scan and the formkit migration walk: JS/TS\n * in every common extension plus Svelte single-file components. Shared so the two\n * stay in lockstep \u2014 anything the scanner reads is a file the migration may rewrite.\n */\nexport const SOURCE_GLOB = \"**/*.{js,jsx,ts,tsx,mjs,cjs,svelte}\";\n\n/**\n * Directories excluded from {@link SOURCE_GLOB} \u2014 dependencies and build output,\n * whose Auro `static register` defaults would be false positives (scan) and are not\n * the consumer's own source to rewrite (migration).\n */\nexport const SOURCE_GLOB_IGNORE = [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/coverage/**\",\n];\n\n/** A registry-layer failure with a caller-presentable message. */\nexport class RegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RegistryError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Config IO\n// ---------------------------------------------------------------------------\n\n/** A fresh, empty config with the given default prefix (`\"\"` = bare/no prefix). */\nexport function emptyConfig(defaultPrefix = \"\"): AuroConfig {\n return {\n version: CONFIG_VERSION,\n init: { prefix: { default: defaultPrefix, overrides: {} } },\n };\n}\n\n/**\n * Structurally validate a parsed value against the frozen {@link AuroConfig}\n * shape. Returns the narrowed config or throws {@link RegistryError} \u2014 a newer\n * `version` is an explicit, actionable failure (the format-freeze contract), not\n * a silent best-effort read.\n */\nfunction assertConfig(value: unknown, source: string): AuroConfig {\n const obj = value as Partial<AuroConfig> | null;\n if (!obj || typeof obj !== \"object\") {\n throw new RegistryError(`${source}: not a JSON object.`);\n }\n if (obj.version !== CONFIG_VERSION) {\n throw new RegistryError(\n `${source}: unsupported config version ${String(obj.version)} (expected ${CONFIG_VERSION}). Upgrade the CLI or remove the file.`,\n );\n }\n const prefix = obj.init?.prefix;\n if (\n !prefix ||\n typeof prefix.default !== \"string\" ||\n typeof prefix.overrides !== \"object\" ||\n prefix.overrides === null\n ) {\n throw new RegistryError(`${source}: malformed init.prefix block.`);\n }\n return obj as AuroConfig;\n}\n\n/**\n * Read `<cwd>/auro.config.json`. Returns `null` when the file is absent (a\n * first-run project), or the validated {@link AuroConfig}. Throws\n * {@link RegistryError} on malformed or unsupported-version JSON.\n */\nexport function loadConfig(cwd: string): AuroConfig | null {\n const file = path.join(cwd, CONFIG_FILENAME);\n let raw: string;\n try {\n raw = readFileSync(file, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new RegistryError(`${CONFIG_FILENAME}: invalid JSON.`);\n }\n return assertConfig(parsed, CONFIG_FILENAME);\n}\n\n/** Write `<cwd>/auro.config.json` as pretty JSON with a trailing newline. */\nexport function saveConfig(cwd: string, config: AuroConfig): void {\n const file = path.join(cwd, CONFIG_FILENAME);\n writeFileSync(file, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// AST scan \u2014 read-only detection of existing register('<tag>') calls\n// ---------------------------------------------------------------------------\n\n/** A statically-resolvable `<Class>.register('<tag>')` found in consumer source. */\nexport interface RegistrationMatch {\n /** The callee object identifier (e.g. `AuroInput`), when it is a plain name. */\n className?: string;\n /** The literal tag passed to `register(...)`. */\n tag: string;\n}\n\n/** The result of scanning source: resolvable matches plus skip/parse warnings. */\nexport interface RegistrationScan {\n matches: RegistrationMatch[];\n /**\n * Callee class names that called `register()` with **no argument** \u2014 the\n * canonical default-tag registration (e.g. `AuroButton.register()` registers\n * `<auro-button>`). Optional so callers may omit it; the planner reads it to\n * warn when a default registration is grounded under a custom prefix.\n */\n defaultRegistrations?: string[];\n warnings: string[];\n}\n\nfunction scriptKindFor(filePath: string): ts.ScriptKind {\n switch (path.extname(filePath).toLowerCase()) {\n case \".tsx\":\n return ts.ScriptKind.TSX;\n case \".jsx\":\n return ts.ScriptKind.JSX;\n case \".ts\":\n case \".mts\":\n case \".cts\":\n return ts.ScriptKind.TS;\n default:\n return ts.ScriptKind.JS;\n }\n}\n\n/**\n * A statically-resolvable tag argument is a plain string literal or a backtick\n * string with no `${}` substitutions (a `NoSubstitutionTemplateLiteral`).\n */\nfunction staticTag(arg: ts.Expression | undefined): string | null {\n if (!arg) {\n return null;\n }\n if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {\n return arg.text;\n }\n return null;\n}\n\n/**\n * Scan one source string for `<Class>.register('<tag>')` calls. Purely syntactic\n * (`ts.createSourceFile`, no type-checker): captures every call whose first\n * argument is a static tag. A `register()` with **no argument** is the canonical\n * default-tag registration \u2014 recorded (by callee class name) in\n * `defaultRegistrations`, never warned, since the tag is known (the component's\n * `auro-*` tag). Any `.register(...)` whose tag is a template with substitutions,\n * an identifier, a call, or a spread is warned and skipped \u2014 the scan never\n * guesses a computed tag. A parse failure warns and yields no matches for that\n * file rather than throwing.\n *\n * `scriptKind` defaults to the one inferred from `filePath`'s extension; callers\n * that feed extracted source under a different-looking path (e.g. a Svelte\n * `<script lang=\"ts\">` block scanned under its `.svelte` path) pass it explicitly.\n */\nexport function scanSource(\n filePath: string,\n source: string,\n scriptKind: ts.ScriptKind = scriptKindFor(filePath),\n): RegistrationScan {\n const matches: RegistrationMatch[] = [];\n const defaultRegistrations: string[] = [];\n const warnings: string[] = [];\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.ES2022,\n /* setParentNodes */ true,\n scriptKind,\n );\n } catch {\n return {\n matches,\n defaultRegistrations,\n warnings: [`${filePath}: could not be parsed; skipped.`],\n };\n }\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === \"register\"\n ) {\n const object = node.expression.expression;\n const className = ts.isIdentifier(object) ? object.text : undefined;\n\n if (node.arguments.length === 0) {\n // A no-arg register() uses the component's canonical default tag. Record\n // it (when the callee is a plain class name) so the planner can flag an\n // app-vs-grounding mismatch under a custom prefix; a callee we cannot name\n // is not actionable, so drop it silently.\n if (className) {\n defaultRegistrations.push(className);\n }\n } else {\n const tag = staticTag(node.arguments[0]);\n if (tag === null) {\n warnings.push(\n `${filePath}: register() with a non-literal tag could not be resolved; skipped.`,\n );\n } else {\n matches.push({ className, tag });\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n\n return { matches, defaultRegistrations, warnings };\n}\n\n/** One extracted Svelte `<script>` block: its inner source and its language. */\ninterface SvelteScript {\n content: string;\n scriptKind: ts.ScriptKind;\n}\n\n// A Svelte `<script ...>...</script>` block. Non-greedy body so it stops at the\n// first closing tag; `gi` walks every block (an instance block plus an optional\n// `context=\"module\"` / Svelte-5 `module` block).\nconst SVELTE_SCRIPT = /<script\\b([^>]*)>([\\s\\S]*?)<\\/script>/gi;\n// A `lang=\"ts\"` / `lang='typescript'` (quotes optional) attribute \u2192 TypeScript.\nconst SVELTE_LANG_TS = /\\blang\\s*=\\s*[\"']?(?:ts|typescript)[\"']?/i;\n\n/**\n * Pull the JS/TS out of a Svelte single-file component. A `.svelte` file's logic\n * lives in one or more `<script>` blocks (an instance block plus an optional\n * `context=\"module\"`/`module` block); the surrounding template markup and\n * `<style>` are not parseable as a module, so only the script bodies are\n * returned \u2014 each tagged TS or JS from its `lang` attribute. Returns `[]` when\n * the component has no `<script>` block. Purely lexical (no Svelte compiler): a\n * literal `</script>` inside a string would end a block early, an accepted v1\n * limitation.\n */\nexport function extractSvelteScripts(source: string): SvelteScript[] {\n const scripts: SvelteScript[] = [];\n // A shared regex with the `g` flag carries lastIndex across calls, so reset it\n // before each scan to stay reentrant.\n SVELTE_SCRIPT.lastIndex = 0;\n let match: RegExpExecArray | null = SVELTE_SCRIPT.exec(source);\n while (match !== null) {\n const [, attributes, content] = match;\n scripts.push({\n content,\n scriptKind: SVELTE_LANG_TS.test(attributes)\n ? ts.ScriptKind.TS\n : ts.ScriptKind.JS,\n });\n match = SVELTE_SCRIPT.exec(source);\n }\n return scripts;\n}\n\n/**\n * Scan the project's own sources under `cwd` for existing registrations. Globs\n * `**\\/*.{js,jsx,ts,tsx,mjs,cjs,svelte}` (excluding `node_modules`/`dist`/`build`/\n * `coverage` \u2014 Auro's own `static register` defaults would be false positives),\n * reads each file, and aggregates {@link scanSource}. A `.svelte` file is scanned\n * per extracted `<script>` block ({@link extractSvelteScripts}) so its template\n * markup never reaches the parser. A read failure on one file warns and continues.\n */\nexport function scanProject(cwd: string): RegistrationScan {\n const files = globSync(SOURCE_GLOB, {\n cwd,\n absolute: true,\n nodir: true,\n ignore: SOURCE_GLOB_IGNORE,\n });\n\n const matches: RegistrationMatch[] = [];\n const defaultRegistrations: string[] = [];\n const warnings: string[] = [];\n const collect = (scan: RegistrationScan): void => {\n matches.push(...scan.matches);\n defaultRegistrations.push(...(scan.defaultRegistrations ?? []));\n warnings.push(...scan.warnings);\n };\n\n for (const file of files) {\n let source: string;\n try {\n source = readFileSync(file, \"utf-8\");\n } catch {\n warnings.push(`${file}: could not be read; skipped.`);\n continue;\n }\n if (path.extname(file).toLowerCase() === \".svelte\") {\n for (const { content, scriptKind } of extractSvelteScripts(source)) {\n collect(scanSource(file, content, scriptKind));\n }\n } else {\n collect(scanSource(file, source));\n }\n }\n return { matches, defaultRegistrations, warnings };\n}\n\n// ---------------------------------------------------------------------------\n// Prefix inference\n// ---------------------------------------------------------------------------\n\n/** The bare component base of a canonical tag: `auro-input` \u2192 `input`. */\nfunction baseOf(canonicalTag: string): string {\n return canonicalTag.startsWith(AURO_PREFIX)\n ? canonicalTag.slice(AURO_PREFIX.length)\n : canonicalTag;\n}\n\n/**\n * Infer the prefix that turns a canonical tag into a custom tag: for\n * `auro-input` \u2192 `legacy-input` the prefix is `legacy-`. Returns `null` when the\n * custom tag is a full rename (does not end with the component base), and so\n * carries no reusable prefix.\n */\nexport function inferPrefixFromTag(\n canonicalTag: string,\n customTag: string,\n): string | null {\n const base = baseOf(canonicalTag);\n if (!customTag.endsWith(base)) {\n return null;\n }\n return customTag.slice(0, customTag.length - base.length);\n}\n\n/** The most common default prefix suggested by existing registrations. */\nexport interface PrefixSuggestion {\n /** The majority real prefix, or `undefined` when none is inferable. */\n suggestion?: string;\n /** True when two or more distinct real prefixes were seen (a conflict). */\n mixed: boolean;\n}\n\n/**\n * Suggest a default prefix from a set of inferred prefixes. Empty and bare\n * (`auro-`) prefixes are not real custom registrations and are ignored. Returns\n * the most frequent remaining prefix and whether the real prefixes disagree.\n */\nexport function suggestDefaultPrefix(\n prefixes: readonly (string | null)[],\n): PrefixSuggestion {\n const counts = new Map<string, number>();\n for (const prefix of prefixes) {\n if (!prefix || prefix === AURO_PREFIX) {\n continue;\n }\n counts.set(prefix, (counts.get(prefix) ?? 0) + 1);\n }\n if (counts.size === 0) {\n return { mixed: false };\n }\n let suggestion: string | undefined;\n let best = -1;\n for (const [prefix, count] of counts) {\n if (count > best) {\n best = count;\n suggestion = prefix;\n }\n }\n return { suggestion, mixed: counts.size > 1 };\n}\n\n// ---------------------------------------------------------------------------\n// Tag-resolution planner\n// ---------------------------------------------------------------------------\n\n/** Existing registrations reconciled to their component's canonical tag. */\ninterface Reconciled {\n /** canonical `auro-*` tag \u2192 the custom tag detected for it. */\n overrides: Map<string, string>;\n /** canonical `auro-*` tag \u2192 callee class name that registered its default tag. */\n defaultRegistered: Map<string, string>;\n warnings: string[];\n}\n\n/**\n * Tie each scanned registration to an installed component by matching the\n * callee class name against the component's declaration `name`. A static-tag\n * match whose class name is missing or unknown among the components is warned (a\n * `register()` we cannot attribute to an installed component) and dropped. No-arg\n * default registrations are tied the same way, but an untieable one is dropped\n * silently \u2014 a bare `register()` on an unknown class is not actionable.\n */\nfunction reconcileRegistrations(\n components: readonly ResolvedComponent[],\n matches: readonly RegistrationMatch[],\n defaultRegistrations: readonly string[] = [],\n): Reconciled {\n const byClassName = new Map<string, string>();\n for (const component of components) {\n byClassName.set(component.declaration.name, component.tagName);\n }\n\n const overrides = new Map<string, string>();\n const warnings: string[] = [];\n for (const match of matches) {\n const canonical = match.className\n ? byClassName.get(match.className)\n : undefined;\n if (!canonical) {\n warnings.push(\n `Found register('${match.tag}')${match.className ? ` on ${match.className}` : \"\"} but could not tie it to an installed Auro component; ignored.`,\n );\n continue;\n }\n overrides.set(canonical, match.tag);\n }\n\n const defaultRegistered = new Map<string, string>();\n for (const className of defaultRegistrations) {\n const canonical = byClassName.get(className);\n if (canonical) {\n defaultRegistered.set(canonical, className);\n }\n }\n return { overrides, defaultRegistered, warnings };\n}\n\n/** Options controlling {@link planTagResolution}. */\nexport interface PlanOptions {\n /** The loaded `auro.config.json`, if the project has one. */\n config?: AuroConfig | null;\n /** The result of scanning consumer source for existing registrations. */\n scan?: RegistrationScan;\n /** An explicit default prefix (from `--prefix`), overriding the config default. */\n prefix?: string;\n}\n\n/** The outcome of planning tag resolution for an installed component set. */\nexport interface TagResolutionPlan {\n /** canonical `auro-*` tag \u2192 resolved custom tag, for every resolvable component. */\n resolvedTags: Map<string, string>;\n /** The config to persist once `needsDefaultPrefix` is `false`. */\n config: AuroConfig;\n /** Canonical tags with no override/scan match, awaiting a default prefix. */\n needingDefault: string[];\n /** True when components await a default prefix but none is known yet. */\n needsDefaultPrefix: boolean;\n /** Majority prefix suggested from existing registrations, when any. */\n suggestedDefault?: string;\n /** True when existing registrations imply two or more distinct prefixes. */\n mixedPrefixes: boolean;\n /**\n * Non-fatal warnings (unresolvable registrations, scan parse skips). Advisory\n * only \u2014 the caller prints these as plain `\u26A0` lines.\n */\n warnings: string[];\n /**\n * The subset of advisories where a resolved/grounded tag may **not match the\n * tag the app registers at runtime** \u2014 a prefix grounded a custom tag with no\n * corroborating `register()` in source, or a detected default `register()` was\n * grounded under a custom prefix. These silently break IntelliSense (the\n * generated artifacts key on a tag the markup never uses), so the caller\n * surfaces them in a prominent bordered banner rather than a plain line. See\n * {@link renderWarningBanner}.\n */\n reconciliationWarnings: string[];\n /**\n * Components grounded under their bare `auro-*` tag because no custom prefix\n * was given. Less severe than a reconciliation mismatch (the grounding is\n * self-consistent), but still worth surfacing prominently since a bare tag\n * risks registration collisions \u2014 the caller renders these in a yellow\n * bordered banner. See {@link renderWarningBanner}.\n */\n noPrefixWarnings: string[];\n}\n\n/**\n * Apply a default prefix to a canonical tag. A missing or bare (`auro-`) prefix\n * yields the canonical tag unchanged (the component keeps its `auro-*` tag);\n * otherwise the `auro-` prefix is replaced, e.g. `myapp-` + `auro-button` \u2192\n * `myapp-button`.\n */\nfunction applyPrefix(prefix: string, canonicalTag: string): string {\n if (!prefix || prefix === AURO_PREFIX) {\n return canonicalTag;\n }\n return prefix + baseOf(canonicalTag);\n}\n\n/**\n * Plan the resolved custom tag for every installed component, following the\n * frozen **config \u2192 scan \u2192 default prefix** precedence. Pure: performs no IO and\n * no prompting. When some components still need the default prefix and none is\n * known (`needsDefaultPrefix`), the caller resolves a prefix (prompt/`--prefix`/\n * CI-fail) and re-calls with it; the returned `config` is authoritative only once\n * `needsDefaultPrefix` is `false`.\n */\nexport function planTagResolution(\n components: readonly ResolvedComponent[],\n options: PlanOptions = {},\n): TagResolutionPlan {\n const { config, scan, prefix } = options;\n const configOverrides = config?.init.prefix.overrides ?? {};\n const reconciled = reconcileRegistrations(\n components,\n scan?.matches ?? [],\n scan?.defaultRegistrations ?? [],\n );\n\n // The effective default: an explicit --prefix wins over a persisted config\n // default. `undefined` means \"not yet known\" (distinct from a bare \"\").\n const configDefault = config?.init.prefix.default;\n const effectiveDefault = prefix ?? configDefault;\n\n const resolvedTags = new Map<string, string>();\n const persistOverrides: Record<string, string> = { ...configOverrides };\n const needingDefault: string[] = [];\n const warnings = [...(scan?.warnings ?? []), ...reconciled.warnings];\n // App-vs-grounding tag mismatches \u2014 surfaced prominently, not inline (see the\n // TagResolutionPlan.reconciliationWarnings doc).\n const reconciliationWarnings: string[] = [];\n // Bare `auro-*` groundings \u2014 surfaced in a yellow banner (see the\n // TagResolutionPlan.noPrefixWarnings doc).\n const noPrefixWarnings: string[] = [];\n\n for (const component of components) {\n const tag = component.tagName;\n\n const fromConfig = configOverrides[tag];\n if (fromConfig !== undefined) {\n resolvedTags.set(tag, fromConfig);\n continue;\n }\n\n const fromScan = reconciled.overrides.get(tag);\n if (fromScan !== undefined) {\n resolvedTags.set(tag, fromScan);\n persistOverrides[tag] = fromScan; // detected registrations are persisted\n continue;\n }\n\n if (effectiveDefault === undefined) {\n needingDefault.push(tag);\n continue;\n }\n\n const resolved = applyPrefix(effectiveDefault, tag);\n resolvedTags.set(tag, resolved);\n if (resolved === tag) {\n noPrefixWarnings.push(\n `${tag}: no custom prefix \u2014 grounding it under its bare 'auro-*' tag. Pass a prefix to avoid registration collisions.`,\n );\n } else if (!reconciled.defaultRegistered.has(tag)) {\n // The prefix produced a custom tag, but nothing in the consumer's source\n // corroborates it \u2014 no scan match (those `continue` above) and no detected\n // no-arg default register() (that case is warned specifically below). Auro\n // components self-register their default `auro-*` tag on import, so a\n // project that never calls register('<resolved>') runs `<auro-*>` at\n // runtime while every generated artifact is keyed on `<resolved>` \u2014 the\n // IntelliSense silently matches nothing. We cannot see auto-registration\n // statically, so advise (never guess): name the exact call that makes the\n // app agree with the grounding.\n reconciliationWarnings.push(\n `${tag}: grounded as '<${resolved}>' from the '${effectiveDefault}' prefix, but no register('${resolved}') was found in your source. If ${component.declaration.name} is registered under a different tag (e.g. the default '<${tag}>' from a side-effect import), IntelliSense will not match your markup \u2014 call ${component.declaration.name}.register('${resolved}') so your app matches the generated tags.`,\n );\n }\n }\n\n // A component the consumer registers with the default no-arg register() keeps\n // its canonical `auro-*` tag at runtime. If we grounded it under a custom tag\n // (a prefix or a config/scan override), the app and AGENTS.md diverge \u2014 warn so\n // the user updates their register() call. Never rewrite their source (v1 docs).\n for (const [canonical, className] of reconciled.defaultRegistered) {\n const resolved = resolvedTags.get(canonical);\n if (resolved !== undefined && resolved !== canonical) {\n reconciliationWarnings.push(\n `${className}.register() uses the default '<${canonical}>' tag, but this project grounds it as '<${resolved}>'. Update the register() call to '${resolved}' so your app matches AGENTS.md.`,\n );\n }\n }\n\n // Suggest a default from every real (config + scanned) custom registration.\n const inferred = [\n ...Object.entries(configOverrides),\n ...reconciled.overrides,\n ].map(([canonical, custom]) => inferPrefixFromTag(canonical, custom));\n const { suggestion, mixed } = suggestDefaultPrefix(inferred);\n\n const needsDefaultPrefix =\n needingDefault.length > 0 && effectiveDefault === undefined;\n\n const persistedDefault = effectiveDefault ?? suggestion ?? \"\";\n const persistConfig: AuroConfig = {\n version: CONFIG_VERSION,\n init: {\n prefix: { default: persistedDefault, overrides: persistOverrides },\n },\n };\n\n return {\n resolvedTags,\n config: persistConfig,\n needingDefault,\n needsDefaultPrefix,\n suggestedDefault: suggestion,\n mixedPrefixes: mixed,\n warnings,\n reconciliationWarnings,\n noPrefixWarnings,\n };\n}\n", "/**\n * Teardown for `auro init --reset`: reverse everything a previous `auro init`\n * run produced. Two phases so the command can show an accurate confirm list\n * before touching disk (mirroring registry.ts's plan/apply split):\n *\n * - {@link planReset} \u2014 READ-ONLY. Stats each known artifact path, signature-\n * guards the grounding files (`AGENTS.md`/`CLAUDE.md`) and the CLI config so an\n * unrelated or hand-authored file is never deleted, and computes the two\n * config un-merges (`.vscode/settings.json`, `tsconfig.json`/`jsconfig.json`).\n * - {@link applyReset} \u2014 the only mutating step: delete the guarded files, write\n * the un-merged configs, prune the now-empty `auro-types/` and `.vscode/` dirs.\n *\n * Sweeps the frozen artifact paths directly (layout constants) rather than\n * trusting `auro.config.json`, so a reset still works when that file was deleted\n * or corrupted. Deliberately does NOT reverse the one-way `auro-formkit`\n * migration codemod \u2014 that edits package.json + import specifiers and is not\n * safely reversible; the command notes this rather than guessing.\n *\n * @see docs/pt-m2-completion-plan.md and the `auro init` inventory in the\n * `--reset` plan.\n */\n\nimport {\n existsSync,\n readdirSync,\n readFileSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { parse as parseJsonc } from \"jsonc-parser\";\nimport { CONFIG_FILENAME } from \"#init/config.js\";\nimport {\n CSS_SNIPPETS_PATH,\n FRAMEWORK_TYPES_DIR,\n HTML_CUSTOM_DATA_PATH,\n JSX_TYPES_PATH,\n SVELTE_TYPES_PATH,\n VSCODE_DIR,\n VSCODE_SETTINGS_FILENAME,\n} from \"#init/editors/layout.js\";\nimport {\n type MergeResult,\n unmergeTsconfigInclude,\n unmergeVsCodeSettings,\n} from \"#init/editors/settings.js\";\nimport {\n AGENTS_FILENAME,\n CLAUDE_FILENAME,\n CLAUDE_MD,\n GROUNDING_MARKER,\n} from \"#init/layout.js\";\nimport { loadConfig, RegistryError } from \"#init/registry.js\";\n\n/** A generated file that exists but did not pass its signature guard. */\nexport interface SkippedFile {\n /** Project-root-relative path (forward slashes). */\n path: string;\n /** Why it was left in place (shown to the user). */\n reason: string;\n}\n\n/** An un-merge to apply to one existing config file. */\ninterface ConfigUnmerge {\n /** Project-root-relative path (forward slashes). */\n path: string;\n /** The un-merge result (contents to write when `changed`). */\n result: MergeResult;\n}\n\n/** The read-only plan of what a reset will remove and un-merge. */\nexport interface ResetPlan {\n /** Root-relative paths that exist and passed their guard \u2014 safe to delete. */\n filesToRemove: string[];\n /** Files that exist but were left in place (failed a signature/parse guard). */\n filesToSkip: SkippedFile[];\n /** Config un-merges that actually change a file (only `changed` results). */\n unmerges: ConfigUnmerge[];\n /** Warnings from an un-merge that had to be skipped (unparseable config). */\n warnings: string[];\n /** Dirs to remove if empty after file removal, most-nested first. */\n dirsToPrune: string[];\n}\n\n/** What {@link applyReset} actually did. */\nexport interface ResetReport {\n /** Root-relative paths removed. */\n removed: string[];\n /** Root-relative config paths whose Auro entry was un-merged. */\n unmerged: string[];\n /** Root-relative dirs pruned because they were left empty. */\n prunedDirs: string[];\n /** Files left in place (carried through from the plan). */\n skipped: SkippedFile[];\n /** Advisory warnings (carried from the plan). */\n warnings: string[];\n}\n\n/** Absolute path for a forward-slash, root-relative artifact path. */\nfunction toAbsolute(cwd: string, rel: string): string {\n return path.join(cwd, ...rel.split(\"/\"));\n}\n\n/** True when `source` is JSONC for an object with no keys (`{}`, comments aside). */\nfunction isEmptyObject(source: string): boolean {\n const data = parseJsonc(source, [], { allowTrailingComma: true }) as unknown;\n return (\n typeof data === \"object\" &&\n data !== null &&\n !Array.isArray(data) &&\n Object.keys(data).length === 0\n );\n}\n\n/**\n * True when `source` contains a JSONC comment. Only used on content already known\n * to parse to an empty object \u2014 with no string values left, a bare `//` or `/*`\n * can only start a comment, so this needs no string-aware scan.\n */\nfunction hasComments(source: string): boolean {\n return source.includes(\"//\") || source.includes(\"/*\");\n}\n\n/** Read a file as UTF-8, or `null` when it does not exist. */\nfunction readOrNull(absolute: string): string | null {\n try {\n return readFileSync(absolute, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n}\n\n/**\n * Editor artifacts carry unambiguous Auro-namespaced names, so their mere\n * presence is enough to remove them \u2014 no content signature needed.\n */\nconst UNCONDITIONAL_ARTIFACTS = [\n HTML_CUSTOM_DATA_PATH,\n CSS_SNIPPETS_PATH,\n JSX_TYPES_PATH,\n SVELTE_TYPES_PATH,\n] as const;\n\n/**\n * Classify a grounding file: `\"remove\"` when it carries the Auro signature,\n * `\"skip\"` with a reason when it exists but looks hand-authored/unrelated, or\n * `null` when it is absent. `AGENTS.md` is matched by the generated marker\n * comment; `CLAUDE.md` by exact equality with the thin generated body.\n */\nfunction classifyGroundingFile(\n contents: string | null,\n kind: \"agents\" | \"claude\",\n): \"remove\" | SkippedFile[\"reason\"] | null {\n if (contents === null) {\n return null;\n }\n if (kind === \"agents\") {\n return contents.includes(GROUNDING_MARKER)\n ? \"remove\"\n : `not recognized as an \\`auro init\\` file (missing the \"${GROUNDING_MARKER}\" marker)`;\n }\n return contents.trim() === CLAUDE_MD.trim()\n ? \"remove\"\n : \"contains content beyond the generated `@AGENTS.md` import\";\n}\n\n/**\n * Plan a reset for `cwd` without touching disk. Sweeps every known artifact\n * path, signature-guards the grounding files and the CLI config, and computes\n * the two config un-merges against their current contents.\n */\nexport function planReset(cwd: string): ResetPlan {\n const filesToRemove: string[] = [];\n const filesToSkip: SkippedFile[] = [];\n const warnings: string[] = [];\n\n // Grounding files \u2014 signature-guarded so we never delete a file we cannot\n // confirm we authored.\n for (const [rel, kind] of [\n [AGENTS_FILENAME, \"agents\"],\n [CLAUDE_FILENAME, \"claude\"],\n ] as const) {\n const verdict = classifyGroundingFile(\n readOrNull(toAbsolute(cwd, rel)),\n kind,\n );\n if (verdict === \"remove\") {\n filesToRemove.push(rel);\n } else if (verdict !== null) {\n filesToSkip.push({ path: rel, reason: verdict });\n }\n }\n\n // auro.config.json \u2014 remove only when it parses as our config; a malformed or\n // unsupported-version file is surfaced, not nuked (it may not be ours).\n if (existsSync(toAbsolute(cwd, CONFIG_FILENAME))) {\n try {\n if (loadConfig(cwd)) {\n filesToRemove.push(CONFIG_FILENAME);\n }\n } catch (error) {\n const reason =\n error instanceof RegistryError ? error.message : String(error);\n filesToSkip.push({ path: CONFIG_FILENAME, reason });\n }\n }\n\n // Editor artifacts \u2014 unambiguous names, remove when present.\n for (const rel of UNCONDITIONAL_ARTIFACTS) {\n if (existsSync(toAbsolute(cwd, rel))) {\n filesToRemove.push(rel);\n }\n }\n\n // Config un-merges. settings.json is standalone; the TS include lives in the\n // first of tsconfig.json/jsconfig.json that exists (matches the write-side\n // \"first existing wins\" rule).\n const unmerges: ConfigUnmerge[] = [];\n const settingsRel = `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME}`;\n const settingsContents = readOrNull(toAbsolute(cwd, settingsRel));\n if (settingsContents !== null) {\n const result = unmergeVsCodeSettings(settingsContents);\n if (result.warning) {\n warnings.push(result.warning);\n } else if (result.changed) {\n // Removing our entry emptied the object \u2192 the file held only our entry, so\n // `auro init` created it. Delete it (a faithful teardown, and so the\n // `.vscode/` prune below can reclaim a now-empty dir) rather than leaving a\n // stray `{}` that a later run only survives on by accident \u2014 UNLESS the file\n // still carries user comments, which deletion would silently discard. In\n // that case keep the file and just write back the emptied object.\n if (isEmptyObject(result.contents) && !hasComments(result.contents)) {\n filesToRemove.push(settingsRel);\n } else {\n unmerges.push({ path: settingsRel, result });\n }\n }\n }\n for (const configRel of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const contents = readOrNull(toAbsolute(cwd, configRel));\n if (contents === null) {\n continue;\n }\n const result = unmergeTsconfigInclude(contents, undefined, configRel);\n if (result.warning) {\n warnings.push(result.warning);\n } else if (result.changed) {\n unmerges.push({ path: configRel, result });\n }\n // Only the first existing config is authoritative; stop after it.\n break;\n }\n\n return {\n filesToRemove,\n filesToSkip,\n unmerges,\n warnings,\n dirsToPrune: [FRAMEWORK_TYPES_DIR, VSCODE_DIR],\n };\n}\n\n/** True when the directory exists and holds no entries. */\nfunction isEmptyDir(absolute: string): boolean {\n try {\n return readdirSync(absolute).length === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Execute a {@link planReset} result: delete the guarded files, write the\n * un-merged configs, and prune the artifact dirs left empty. Idempotent \u2014 a\n * second run over an already-clean project removes nothing.\n */\nexport function applyReset(cwd: string, plan: ResetPlan): ResetReport {\n const removed: string[] = [];\n for (const rel of plan.filesToRemove) {\n rmSync(toAbsolute(cwd, rel), { force: true });\n removed.push(rel);\n }\n\n const unmerged: string[] = [];\n for (const { path: rel, result } of plan.unmerges) {\n writeFileSync(toAbsolute(cwd, rel), result.contents, \"utf-8\");\n unmerged.push(rel);\n }\n\n const prunedDirs: string[] = [];\n for (const rel of plan.dirsToPrune) {\n const absolute = toAbsolute(cwd, rel);\n if (isEmptyDir(absolute)) {\n rmdirSync(absolute);\n prunedDirs.push(rel);\n }\n }\n\n return {\n removed,\n unmerged,\n prunedDirs,\n skipped: plan.filesToSkip,\n warnings: plan.warnings,\n };\n}\n", "/**\n * Bordered, colored terminal banners for advisories that must not scroll past\n * unnoticed. The prominent cousin of a plain `\u26A0 ...` stderr line: a boxed heading\n * plus word-wrapped bullet messages, mirroring the box/heading treatment of\n * {@link renderOutdatedBanner} in ./outdated.ts so the two read as a family.\n *\n * Presentation only \u2014 no IO. Callers pass already-composed message strings and\n * print the result (typically to stderr, keeping stdout clean for piped output).\n * Colors degrade automatically: chalk disables them when the stream is not a TTY\n * (redirected to a file, captured in a test), while the border and heading keep\n * the banner legible without them.\n */\n\nimport chalk from \"chalk\";\n\n/** Banner accent, applied to the border, heading, and message text. */\nexport type BannerColor = \"red\" | \"yellow\";\n\n/** The box never grows past this many columns, so it fits a standard terminal. */\nconst MAX_WIDTH = 78;\n\n/** Content column budget for wrapped message text (leaves a small margin). */\nconst CONTENT_WIDTH = 74;\n\nconst BULLET = \" \u2022 \";\nconst CONTINUATION_INDENT = \" \";\n\n/**\n * Word-wrap `text` to at most `width` columns, breaking on whitespace only. A\n * single word longer than `width` is left intact on its own line (overflow)\n * rather than hard-split, so tokens like `Class.register('my-tag')` stay\n * copy-pasteable. Never returns an empty array \u2014 a blank input yields `[\"\"]`.\n */\nfunction wrapText(text: string, width: number): string[] {\n const words = text.split(/\\s+/u).filter(Boolean);\n if (words.length === 0) {\n return [\"\"];\n }\n const lines: string[] = [];\n let current = words[0];\n for (const word of words.slice(1)) {\n if (current.length + 1 + word.length <= width) {\n current += ` ${word}`;\n } else {\n lines.push(current);\n current = word;\n }\n }\n lines.push(current);\n return lines;\n}\n\n/**\n * Render `messages` as a bordered banner under `heading`, accented in `color`.\n * Each message becomes a wrapped bullet; long messages continue on indented\n * lines. Returns `\"\"` for an empty `messages` list so a caller can emit\n * unconditionally (`console.error(renderWarningBanner(...))`).\n *\n * The border width tracks the heading (never past {@link MAX_WIDTH}); a `\u26A0`\n * (U+26A0) in the heading renders as two columns but counts as one char, so its\n * width is nudged by one to keep the border from falling a column short \u2014 the\n * same correction {@link renderOutdatedBanner} applies.\n */\nexport function renderWarningBanner(\n heading: string,\n messages: string[],\n color: BannerColor = \"red\",\n): string {\n if (messages.length === 0) {\n return \"\";\n }\n\n const accent = chalk[color].bold;\n\n const body: string[] = [];\n messages.forEach((message, index) => {\n const wrapped = wrapText(message, CONTENT_WIDTH - BULLET.length);\n wrapped.forEach((line, lineIndex) => {\n const prefix = lineIndex === 0 ? BULLET : CONTINUATION_INDENT;\n body.push(chalk[color](prefix + line));\n });\n // Blank spacer between messages for readability (never after the last).\n if (index < messages.length - 1) {\n body.push(\"\");\n }\n });\n\n const headingWidth = heading.length + (heading.includes(\"\u26A0\") ? 1 : 0);\n const width = Math.min(Math.max(headingWidth, CONTENT_WIDTH), MAX_WIDTH);\n const border = \"\u2500\".repeat(width);\n\n return [\n \"\",\n accent(`\u250C${border}\u2510`),\n accent(heading),\n accent(`\u2514${border}\u2518`),\n ...body,\n \"\",\n ].join(\"\\n\");\n}\n", "import process from \"node:process\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport {\n FORMKIT_PACKAGE,\n formkitSubpathFor,\n formkitTagFor,\n isLegacyFormkitPackage,\n} from \"#static/formkitMigration.js\";\nimport type { Manifest } from \"#utils/cem.js\";\nimport {\n fetchManifest,\n type ManifestFetchResult,\n} from \"#utils/fetchManifest.js\";\nimport { formatDeclaration, toPackageName } from \"#utils/formatComponent.js\";\nimport { checkOutdated, renderOutdatedBanner } from \"#utils/outdated.js\";\n\n/** Options accepted by the `component` action. */\nexport interface ComponentOptions {\n tag?: string;\n json?: boolean;\n}\n\n/** How a component name resolved to a manifest source and its display metadata. */\ninterface ResolvedSource {\n /** Package to show in the `(pkg)` header and use for the outdated check. */\n headerPkg: string;\n /** Package the `Install:` snippet tells the user to `npm i`. */\n installPkg: string;\n /** Module specifier the `Install:` snippet tells the user to `import`. */\n importSpecifier: string;\n /** When set, keep only the declaration with this tag (monorepo aggregate CEM). */\n tagFilter?: string;\n /** True when a legacy standalone was redirected to the auro-formkit monorepo. */\n redirectedToFormkit: boolean;\n /** The resolved manifest fetch outcome. */\n result: ManifestFetchResult;\n}\n\n/**\n * Decide where a component's manifest comes from and how to present it.\n *\n * A legacy standalone form package (one `auro-formkit` now ships) is fetched from\n * the **monorepo** unless that standalone is *actually installed* in the current\n * project \u2014 matching what the user has, and steering everyone else onto formkit\n * rather than the deprecated standalone. An explicit `--tag` always pins the\n * standalone package (formkit versions its own line), so it bypasses the redirect.\n */\nasync function resolveSource(\n pkg: string,\n options: ComponentOptions,\n): Promise<ResolvedSource> {\n const plain = (result: ManifestFetchResult): ResolvedSource => ({\n headerPkg: pkg,\n installPkg: pkg,\n importSpecifier: pkg,\n redirectedToFormkit: false,\n result,\n });\n\n if (options.tag) {\n return plain(await fetchManifest(`${pkg}@${options.tag}`));\n }\n\n if (isLegacyFormkitPackage(pkg)) {\n // Prefer the legacy standalone only when it's actually installed here.\n const localLegacy = await fetchManifest(pkg, { allowNetwork: false });\n if (localLegacy.manifest) {\n return plain(localLegacy);\n }\n // Otherwise show the monorepo copy (local formkit first, then unpkg).\n return {\n headerPkg: FORMKIT_PACKAGE,\n installPkg: FORMKIT_PACKAGE,\n importSpecifier: formkitSubpathFor(pkg),\n tagFilter: formkitTagFor(pkg),\n redirectedToFormkit: true,\n result: await fetchManifest(FORMKIT_PACKAGE),\n };\n }\n\n return plain(await fetchManifest(pkg));\n}\n\n/**\n * Look up a single component's API from its Custom Elements Manifest and print\n * it (formatted, or raw JSON with `--json`). Exits non-zero when the manifest\n * can't be resolved or documents no registered element.\n */\nexport async function runComponent(\n name: string,\n options: ComponentOptions,\n): Promise<void> {\n const pkg = toPackageName(name);\n const spinner = ora(`Fetching ${pkg}...`).start();\n\n const source = await resolveSource(pkg, options);\n const { result } = source;\n const target = result.target;\n if (!result.manifest) {\n spinner.fail(\n result.transient\n ? `Failed to fetch ${target}: ${result.reason}.`\n : `No custom-elements.json published for ${target}. It may not exist or may not publish a manifest yet.`,\n );\n process.exit(1);\n }\n const manifest = result.manifest as Manifest;\n\n // Only real registered elements \u2014 a declaration can be customElement: true\n // yet be an internal base class with no tagName. When the source is the\n // monorepo aggregate CEM, narrow to the one requested tag so a lookup for\n // `input` shows `auro-input` alone, not every formkit element.\n const declarations = (manifest.modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName)\n .filter((decl) => !source.tagFilter || decl.tagName === source.tagFilter);\n\n if (declarations.length === 0) {\n spinner.fail(\n source.tagFilter\n ? `No <${source.tagFilter}> element found in ${target}.`\n : `No registered custom elements found for ${target}.`,\n );\n process.exit(1);\n }\n\n const origin =\n result.source === \"local\"\n ? ` (local${result.version ? ` v${result.version}` : \"\"})`\n : \" (unpkg)\";\n spinner.succeed(\n `${target} \u2014 ${declarations.length} custom element${declarations.length === 1 ? \"\" : \"s\"}${origin}`,\n );\n\n // A legacy standalone the user hasn't installed was redirected to the monorepo;\n // tell them why the package/import shown differs from what they typed. On stderr\n // (not Logger, which prints to stdout) so `--json` output stays machine-parseable.\n if (source.redirectedToFormkit) {\n console.error(\n `\u2139 ${source.tagFilter} now ships in ${FORMKIT_PACKAGE} \u2014 showing the monorepo version (the legacy standalone isn't installed).`,\n );\n }\n\n // When the manifest came from a local install, check whether that install is\n // behind the latest published release and warn \u2014 mirroring `auro context`.\n // Only meaningful for a local read (unpkg already serves latest, and an\n // explicit --tag forces a network fetch, so source is never \"local\" then).\n let outdatedBanner: string | null = null;\n if (result.source === \"local\" && result.version) {\n const check = ora(\"Checking for a newer release...\").start();\n const outdated = await checkOutdated(\n new Map([[source.headerPkg, result.version]]),\n );\n check.stop();\n if (outdated.length > 0) {\n outdatedBanner = renderOutdatedBanner(outdated);\n }\n }\n\n if (options.json) {\n process.stdout.write(`${JSON.stringify(declarations, null, 2)}\\n`);\n // stderr \u2014 keep JSON on stdout machine-parseable.\n if (outdatedBanner) {\n console.error(outdatedBanner);\n }\n return;\n }\n\n process.stdout.write(\n `\\n${declarations\n .map((decl) =>\n formatDeclaration(source.headerPkg, decl, {\n installPkg: source.installPkg,\n importSpecifier: source.importSpecifier,\n }),\n )\n .join(\"\\n\\n---\\n\\n\")}\\n`,\n );\n Logger.info(\"\\nFull docs: https://auro.alaskaair.com\");\n // Warn last so it's the final thing on screen, not scrolled off by the API dump.\n if (outdatedBanner) {\n console.error(outdatedBanner);\n }\n}\n\nexport default program\n .command(\"component <name>\")\n .description(\n \"Look up an Auro component's API (attributes, properties, slots, events, CSS parts) from its published Custom Elements Manifest\",\n )\n .option(\n \"-t, --tag <version>\",\n \"npm dist-tag or version to look up (default: latest); pins the standalone package for a legacy form component\",\n )\n .option(\"--json\", \"Output the raw manifest declaration(s) as JSON\", false)\n .action(runComponent);\n", "import { program } from \"commander\";\nimport { api, cem, docs, serve, watchDocs } from \"#scripts/docs/index.ts\";\nimport { withServerOptions } from \"#commands/_sharedOptions.js\";\n\nlet docsCommand = program\n .command(\"docs\")\n .description(\"Generate API documentation\")\n .option(\"-c, --cem\", \"Generate Custom Elements Manifest (CEM) file\", false)\n .option(\"-a, --api\", \"Creates api md file from CEM\", false)\n .option(\"-w, --watch\", \"Watch for changes and rebuild docs\", false)\n .option(\"-r, --readme-template <url>\", \"URL to the README template file\")\n .option(\"--skip-readme\", \"Skip README.md processing\", false)\n \n docsCommand = withServerOptions(docsCommand);\n\n export default docsCommand.action(async (options) => {\n\n if (options.cem) {\n await cem();\n }\n\n if (options.api) {\n await api();\n }\n\n await docs(options);\n\n if( options.serve ) {\n await serve(options);\n }\n\n if (options.watch) {\n await watchDocs(options);\n }\n\n });\n", "import { program } from \"commander\";\nimport { createADOItem } from \"#scripts/ado/index.ts\";\n\nexport const adoCommand = program\n .command(\"ado\")\n .description(\"Generate ADO item from GitHub issue\")\n .option(\"-g, --gh-issue <issue>\", \"What GitHub issue to use\")\n .action(async (options) => {\n\n if (options.ghIssue) {\n await createADOItem(options.ghIssue);\n }\n });\n", "import { Octokit } from \"@octokit/rest\";\nimport * as azdev from \"azure-devops-node-api\";\nimport ora from \"ora\";\nimport type { WorkItem } from \"azure-devops-node-api/interfaces/WorkItemTrackingInterfaces.js\";\n\ninterface GitHubIssue {\n title: string;\n body: string | null;\n html_url: string;\n number: number;\n repository: {\n owner: { login: string };\n name: string;\n };\n}\n\n/**\n * Fetches GitHub issue details\n * @param issueUrl - Full GitHub issue URL or in format \"owner/repo#number\"\n * @returns GitHub issue details\n */\nconst fetchGitHubIssue = async (issueUrl: string): Promise<GitHubIssue> => {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n throw new Error(\"GH_TOKEN environment variable is required\");\n }\n\n const octokit = new Octokit({\n auth: ghToken,\n });\n\n let owner: string;\n let repo: string;\n let issueNumberStr: string;\n\n // Parse the issue URL or reference\n if (issueUrl.includes('github.com')) {\n // Full URL format: https://github.com/owner/repo/issues/123\n const urlMatch = issueUrl.match(/github\\.com\\/([^\\/]+)\\/([^\\/]+)\\/issues\\/(\\d+)/);\n if (!urlMatch) {\n throw new Error(\"Invalid GitHub issue URL format\");\n }\n [, owner, repo, issueNumberStr] = urlMatch;\n } else if (issueUrl.includes('#')) {\n // Short format: owner/repo#123\n const shortMatch = issueUrl.match(/([^\\/]+)\\/([^#]+)#(\\d+)/);\n if (!shortMatch) {\n throw new Error(\"Invalid GitHub issue reference format\");\n }\n [, owner, repo, issueNumberStr] = shortMatch;\n } else {\n throw new Error(\"Issue must be provided as full URL or in format 'owner/repo#number'\");\n }\n\n const issueNumber = Number.parseInt(issueNumberStr, 10);\n\n try {\n const { data: issue } = await octokit.rest.issues.get({\n owner,\n repo,\n issue_number: issueNumber,\n });\n\n return {\n title: issue.title,\n body: issue.body ?? null,\n html_url: issue.html_url,\n number: issue.number,\n repository: {\n owner: { login: owner },\n name: repo,\n },\n };\n } catch (error) {\n throw new Error(`Failed to fetch GitHub issue: ${error}`);\n }\n};\n\n/**\n * Checks if GitHub issue already has an ADO work item linked\n * @param issue - GitHub issue details\n * @returns ADO URL if found, null otherwise\n */\nconst getExistingADOLink = async (issue: GitHubIssue): Promise<string | null> => {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n return null;\n }\n\n const octokit = new Octokit({\n auth: ghToken,\n });\n\n try {\n // Get the ADO field value from the GitHub project\n const query = `\n query($owner: String!, $repo: String!, $issueNumber: Int!) {\n repository(owner: $owner, name: $repo) {\n issue(number: $issueNumber) {\n projectItems(first: 10) {\n nodes {\n project {\n number\n }\n fieldValues(first: 20) {\n nodes {\n ... on ProjectV2ItemFieldTextValue {\n text\n field {\n ... on ProjectV2Field {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n `;\n\n const variables = {\n owner: issue.repository.owner.login,\n repo: issue.repository.name,\n issueNumber: issue.number,\n };\n\n const response = await octokit.graphql(query, variables) as {\n repository: {\n issue: {\n projectItems: {\n nodes: Array<{\n project: { number: number };\n fieldValues: {\n nodes: Array<{\n text?: string;\n field?: { name?: string };\n }>;\n };\n }>;\n };\n };\n };\n };\n\n // Look for project #19 with ado field\n const project19Item = response.repository.issue.projectItems.nodes.find(\n item => item.project.number === 19\n );\n\n if (project19Item) {\n const adoFieldValue = project19Item.fieldValues.nodes.find(\n fieldValue => fieldValue.field?.name?.toLowerCase() === 'ado' && fieldValue.text?.trim()\n );\n\n if (adoFieldValue?.text?.trim()) {\n return adoFieldValue.text.trim();\n }\n }\n\n return null;\n } catch (error) {\n console.error(`Failed to check existing ADO link: ${error}`);\n return null;\n }\n};\n\n/**\n * Adds GitHub issue to project #19 and updates the \"ado\" field\n * @param issue - GitHub issue details\n * @param adoWorkItemUrl - ADO work item URL\n */\nconst updateGitHubProject = async (\n issue: GitHubIssue,\n adoWorkItemUrl: string\n): Promise<void> => {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n throw new Error(\"GH_TOKEN environment variable is required\");\n }\n\n const octokit = new Octokit({\n auth: ghToken,\n });\n\n const projectNumber = 19; // Alaska Airlines project #19\n\n try {\n // Get project and issue info in one query\n const query = `\n query($org: String!, $projectNumber: Int!, $owner: String!, $repo: String!, $issueNumber: Int!) {\n organization(login: $org) {\n projectV2(number: $projectNumber) {\n id\n fields(first: 20) {\n nodes {\n ... on ProjectV2Field {\n id\n name\n }\n ... on ProjectV2SingleSelectField {\n id\n name\n }\n ... on ProjectV2IterationField {\n id\n name\n }\n }\n }\n }\n }\n repository(owner: $owner, name: $repo) {\n issue(number: $issueNumber) {\n id\n projectItems(first: 10) {\n nodes {\n id\n project {\n number\n }\n }\n }\n }\n }\n }\n `;\n\n const variables = {\n org: \"AlaskaAirlines\",\n projectNumber,\n owner: issue.repository.owner.login,\n repo: issue.repository.name,\n issueNumber: issue.number,\n };\n\n const response = await octokit.graphql(query, variables) as {\n organization: {\n projectV2: {\n id: string;\n fields: {\n nodes: Array<{ id: string; name: string }>;\n };\n };\n };\n repository: {\n issue: {\n id: string;\n projectItems: {\n nodes: Array<{\n id: string;\n project: { number: number };\n }>;\n };\n };\n };\n };\n\n const projectId = response.organization.projectV2.id;\n const issueId = response.repository.issue.id;\n const adoField = response.organization.projectV2.fields.nodes.find(\n field => field.name?.toLowerCase() === 'ado'\n );\n\n // Check if issue is already in the project\n let projectItemId = response.repository.issue.projectItems.nodes.find(\n item => item.project.number === projectNumber\n )?.id;\n\n // Add to project if not already there\n if (!projectItemId) {\n const addMutation = `\n mutation($projectId: ID!, $contentId: ID!) {\n addProjectV2ItemById(\n input: {\n projectId: $projectId\n contentId: $contentId\n }\n ) {\n item {\n id\n }\n }\n }\n `;\n\n const addResponse = await octokit.graphql(addMutation, {\n projectId,\n contentId: issueId,\n }) as {\n addProjectV2ItemById: {\n item: { id: string };\n };\n };\n\n projectItemId = addResponse.addProjectV2ItemById.item.id;\n // Issue added to project (handled by spinner in main function)\n }\n\n // Update the ado field if it exists\n if (adoField && projectItemId) {\n const updateMutation = `\n mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $value: String!) {\n updateProjectV2ItemFieldValue(\n input: {\n projectId: $projectId\n itemId: $itemId\n fieldId: $fieldId\n value: {\n text: $value\n }\n }\n ) {\n projectV2Item {\n id\n }\n }\n }\n `;\n\n await octokit.graphql(updateMutation, {\n projectId,\n itemId: projectItemId,\n fieldId: adoField.id,\n value: adoWorkItemUrl,\n });\n\n // Field updated (handled by spinner in main function)\n } else if (!adoField) {\n throw new Error(\"No 'ado' field found in GitHub project\");\n }\n\n } catch (error) {\n console.error(`Failed to update GitHub project: ${error}`);\n // Don't throw - we don't want to fail the entire process\n }\n};\n\n/**\n * Creates a user story work item in Azure DevOps\n * @param issue - GitHub issue details\n * @returns Created work item\n */\nconst createADOWorkItem = async (issue: GitHubIssue): Promise<WorkItem> => {\n const adoToken = process.env.ADO_TOKEN;\n if (!adoToken) {\n throw new Error(\"ADO_TOKEN environment variable is required\");\n }\n\n // ADO organization and project details\n const orgUrl = \"https://dev.azure.com/itsals\";\n const projectName = \"E_Retain_Content\";\n const areaPath = \"E_Retain_Content\\\\Auro Design System\";\n\n // Create connection to Azure DevOps\n const authHandler = azdev.getPersonalAccessTokenHandler(adoToken);\n const connection = new azdev.WebApi(orgUrl, authHandler);\n const workItemTrackingApi = await connection.getWorkItemTrackingApi();\n\n try {\n // Prepare work item data - omitting iteration path to use project default\n const workItemData = [\n {\n op: \"add\",\n path: \"/fields/System.Title\",\n value: issue.title,\n },\n {\n op: \"add\",\n path: \"/fields/System.Description\",\n value: `GitHub Issue: <a href=\"${issue.html_url}\">${issue.html_url}</a>`,\n },\n {\n op: \"add\",\n path: \"/fields/System.AreaPath\",\n value: areaPath,\n },\n ];\n\n return await workItemTrackingApi.createWorkItem(\n null,\n workItemData,\n projectName,\n \"User Story\"\n );\n } catch (error) {\n throw new Error(`Failed to create ADO work item: ${error}`);\n }\n};\n\nexport const createADOItem = async (ghIssue: string) => {\n const spinner = ora(`Processing GitHub issue: ${ghIssue}`).start();\n \n try {\n // Validate environment variables\n if (!process.env.GH_TOKEN) {\n throw new Error(\"GH_TOKEN environment variable is required\");\n }\n if (!process.env.ADO_TOKEN) {\n throw new Error(\"ADO_TOKEN environment variable is required\");\n }\n\n spinner.text = \"Fetching GitHub issue details...\";\n const issue = await fetchGitHubIssue(ghIssue);\n spinner.succeed(`Found issue: \"${issue.title}\"`);\n\n // Check if issue already has an ADO work item linked in the project\n const checkSpinner = ora(\"Checking for existing ADO work item...\").start();\n const existingADOLink = await getExistingADOLink(issue);\n \n if (existingADOLink) {\n checkSpinner.succeed(\"ADO work item already exists for this issue!\");\n console.log(`${existingADOLink}`);\n return; // Exit early - no need to create a new work item\n }\n \n checkSpinner.succeed(\"No existing ADO work item found\");\n\n const createSpinner = ora(\"Creating new ADO work item...\").start();\n const workItem = await createADOWorkItem(issue);\n createSpinner.succeed(`Successfully created ADO work item #${workItem.id}`);\n \n console.log(`Work item: ${workItem._links?.html?.href || 'N/A'}`);\n\n // Add to GitHub project and update the ado field with the new work item\n if (workItem._links?.html?.href) {\n const projectSpinner = ora(\"Adding to GitHub project and updating ADO field...\").start();\n await updateGitHubProject(issue, workItem._links.html.href);\n projectSpinner.succeed(\"Updated GitHub project with ADO link\");\n } \n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n}", "import { program } from \"commander\";\nimport { RCWorkflow } from \"#scripts/rc-workflow/index.ts\";\n\n\nexport default program\n .command(\"rc-workflow\")\n .description(\"Generate RC issue and pull request\")\n .action(async () => {\n\n const workflow = await RCWorkflow.create();\n await workflow.createReleaseCandidate();\n});\n\n", "import { Git } from \"#utils/gitUtils.ts\";\nimport { Octokit } from \"@octokit/rest\";\nimport { generateReleaseNotes, filterCommitList } from \"#scripts/check-commits/commit-analyzer.ts\";\nimport { simpleGit } from \"simple-git\";\n\n// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo\nconst LABEL = \"Release Candidate\";\nconst RC_SOURCE_BRANCH = \"dev\";\nconst RC_BASE_BRANCH = \"main\";\n\ntype RcIssue = { number: number; title?: string; html_url?: string };\ntype LinkedPr = { state: \"open\" | \"closed\"; html_url?: string; multipleOpen?: boolean; number?: number };\n\nexport class RCWorkflow {\n private repoInfo: { owner: string; repo: string };\n private octokit: Octokit;\n private filteredCommits: Array<{\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n }> | null = null;\n\n constructor(owner: string, repo: string, octokit: Octokit) {\n this.repoInfo = { owner, repo };\n this.octokit = octokit;\n }\n\n /**\n * Static factory method to create an instance of RCWorkflow\n * @returns {Promise<RCWorkflow>} A promise that resolves to an instance of RCWorkflow\n */\n static async create(): Promise<RCWorkflow> {\n const token = process.env.GITHUB_TOKEN;\n if (!token) {\n throw new Error(\"GITHUB_TOKEN is required to run RC workflow.\");\n }\n\n const info = await Git.getRepoOwnerAndName();\n const octokit = new Octokit({ auth: token });\n \n if (!info) {\n throw new Error(\"Failed to retrieve repository information. Ensure you're in a valid git repository.\");\n }\n\n const triggerBranch = await RCWorkflow.getTriggerBranchName();\n if (triggerBranch && triggerBranch !== RC_SOURCE_BRANCH) {\n console.log(`Switching from ${triggerBranch} to ${RC_SOURCE_BRANCH} branch...`);\n const git = simpleGit();\n await git.checkout(RC_SOURCE_BRANCH);\n }\n \n return new RCWorkflow(info.owner, info.repo, octokit);\n }\n\n // Getter for owner\n get owner(): string {\n return this.repoInfo.owner;\n }\n\n // Getter for repo name \n get repo(): string {\n return this.repoInfo.repo;\n }\n\n // Getter for full repo info\n get repoData(): { owner: string; repo: string } {\n return { ...this.repoInfo };\n }\n\n async createReleaseCandidate(): Promise<void> {\n const hasCommitsReady = await this.hasCommitsReadyInDev();\n if (!hasCommitsReady) {\n console.log(\"No filtered commits found. Continuing to update RC issue/branch/PR.\");\n }\n\n let rcIssue: RcIssue | null = await this.getLatestOpenRcIssue();\n let linkedPr: LinkedPr | null = rcIssue ? await this.getLinkedPrByHead(rcIssue.number) : null;\n\n if (linkedPr?.multipleOpen) {\n throw new Error(\"Multiple open RC PRs found for the same rc/<issueNumber> branch.\");\n }\n\n if (linkedPr?.state === \"closed\") {\n console.log(\"Linked RC PR is closed. Creating a new RC issue and PR.\");\n rcIssue = await this.createRcIssue();\n linkedPr = null;\n }\n\n if (!rcIssue) {\n rcIssue = await this.createRcIssue();\n } else {\n await this.updateRcIssue(rcIssue.number);\n }\n\n if (!rcIssue) {\n throw new Error(\"Failed to resolve RC issue.\");\n }\n\n await this.createOrUpdateRcBranch(rcIssue.number);\n\n if (!linkedPr) {\n linkedPr = await this.createRcPr(rcIssue.number);\n } else {\n await this.updateRcPr(rcIssue.number, linkedPr.number!);\n }\n }\n\n private async getFilteredCommits() {\n if (this.filteredCommits === null) {\n const commitList = await Git.getCommitMessages(RC_SOURCE_BRANCH);\n this.filteredCommits = filterCommitList(commitList);\n }\n return this.filteredCommits;\n }\n\n async hasCommitsReadyInDev(): Promise<boolean> {\n const filteredCommits = await this.getFilteredCommits();\n return filteredCommits.length > 0;\n }\n\n private async getLatestOpenRcIssue(): Promise<RcIssue | null> {\n const { data } = await this.octokit.rest.issues.listForRepo({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n labels: LABEL,\n state: \"open\",\n sort: \"updated\",\n direction: \"desc\",\n per_page: 30,\n });\n\n const openIssues = data.filter(issue => !issue.pull_request);\n\n if (openIssues.length === 0) {\n console.log(`No open Release Candidate issues found in ${this.repoInfo.repo}`);\n return null;\n }\n\n const latestIssue = openIssues[0];\n console.log(`Using latest open Release Candidate issue: #${latestIssue.number}`);\n return { number: latestIssue.number, title: latestIssue.title || \"\" };\n }\n\n private async updateRcIssue(issueNumber: number): Promise<void> {\n const releaseNotes = await this.getReleaseNotes();\n const title = `RC ${this.getCurrentDate()}`;\n\n await this.octokit.rest.issues.update({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n issue_number: issueNumber,\n title,\n body: releaseNotes,\n });\n }\n\n private async createRcIssue(): Promise<RcIssue> {\n const releaseNotes = await this.getReleaseNotes();\n\n const { data } = await this.octokit.rest.issues.create({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n title: `RC ${this.getCurrentDate()}`,\n labels: [LABEL],\n body: releaseNotes,\n });\n\n console.log(`Created Release Candidate issue: #${data.number} (${data.html_url})`);\n return { number: data.number, html_url: data.html_url };\n }\n\n private async createOrUpdateRcBranch(issueNumber: number): Promise<void> {\n const branchRef = `heads/rc/${issueNumber}`;\n const branchName = `rc/${issueNumber}`;\n\n const { data: devBranch } = await this.octokit.rest.repos.getBranch({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n branch: RC_SOURCE_BRANCH,\n });\n\n // Check if branch exists by listing matching refs\n const { data: matchingRefs } = await this.octokit.rest.git.listMatchingRefs({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: branchRef,\n });\n\n const branchExists = matchingRefs.length > 0;\n\n try {\n if (branchExists) {\n console.log(`Updating existing RC branch: ${branchName}`);\n await this.octokit.rest.git.updateRef({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: branchRef,\n sha: devBranch.commit.sha,\n force: true,\n });\n } else {\n console.log(`Creating new RC branch: ${branchName}`);\n await this.octokit.rest.git.createRef({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: `refs/${branchRef}`,\n sha: devBranch.commit.sha,\n });\n }\n } catch (error: unknown) {\n throw new Error(`Failed to create or update ${branchName} branch: ${error}`);\n }\n }\n\n private async getLinkedPrByHead(issueNumber: number): Promise<LinkedPr | null> {\n const head = `${this.repoInfo.owner}:rc/${issueNumber}`;\n const { data } = await this.octokit.rest.pulls.list({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n state: \"all\",\n head,\n per_page: 30,\n });\n\n const openPrs = data.filter(pr => pr.state === \"open\");\n if (openPrs.length > 1) {\n return { state: \"open\", multipleOpen: true };\n }\n\n if (openPrs.length === 1) {\n return { state: \"open\", html_url: openPrs[0].html_url, number: openPrs[0].number };\n }\n\n const closedPrs = data.filter(pr => pr.state === \"closed\");\n if (closedPrs.length > 0) {\n return { state: \"closed\", html_url: closedPrs[0].html_url, number: closedPrs[0].number };\n }\n\n return null;\n }\n\n private async fetchPrTemplate(issueNumber: number): Promise<string> {\n try {\n // Try to fetch the PR template from the current repo\n const { data } = await this.octokit.rest.repos.getContent({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n path: \".github/PULL_REQUEST_TEMPLATE.md\",\n });\n \n // Check if data is a file (not a directory or submodule)\n if (\"content\" in data && data.type === \"file\") {\n // Decode the base64 content\n let template = Buffer.from(data.content, \"base64\").toString(\"utf-8\");\n \n // Replace the summary placeholder with RC-specific text\n template = template.replace(\n \"Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.\",\n `Release candidate pull request. See issue #${issueNumber} for details.`\n );\n \n // Replace all <details> with <details open>\n template = template.replace(/<details>/g, \"<details open>\");\n \n return template;\n }\n } catch (error: unknown) {\n // Template doesn't exist or couldn't be fetched, use fallback\n if (error && typeof error === \"object\" && \"status\" in error && (error as { status?: number }).status === 404) {\n console.log(\"No PR template found in repo, using default message.\");\n } else {\n console.warn(\"Failed to fetch PR template:\", error);\n }\n }\n \n // Fallback if template doesn't exist or fetch fails\n return `Release candidate pull request. See issue #${issueNumber} for details.`;\n }\n\n private async createRcPr(issueNumber: number): Promise<LinkedPr> {\n try {\n const prBody = await this.fetchPrTemplate(issueNumber);\n\n const { data } = await this.octokit.request(`POST /repos/${this.repoInfo.owner}/${this.repoInfo.repo}/pulls`, {\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n title: `RC #${issueNumber}`,\n body: prBody,\n head: `rc/${issueNumber}`,\n base: RC_BASE_BRANCH,\n headers: {\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n\n console.log(`Created Release Candidate pull request: #${data.number} (${data.html_url})`);\n return { state: \"open\", html_url: data.html_url, number: data.number };\n } catch (error: unknown) {\n console.error(\"Failed to create RC PR:\", error);\n throw error;\n }\n }\n\n private async updateRcPr(issueNumber: number, prNumber: number): Promise<void> {\n try {\n const prBody = await this.fetchPrTemplate(issueNumber);\n\n await this.octokit.rest.pulls.update({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n pull_number: prNumber,\n body: prBody,\n });\n\n console.log(`Updated Release Candidate pull request: #${prNumber}`);\n } catch (error: unknown) {\n console.error(\"Failed to update RC PR:\", error);\n throw error;\n }\n }\n\n async getReleaseNotes(): Promise<string> {\n const filteredCommits = await this.getFilteredCommits();\n return generateReleaseNotes(filteredCommits, false);\n }\n\n private static async getTriggerBranchName(): Promise<string | null> {\n if (process.env.GITHUB_REF_NAME) {\n return process.env.GITHUB_REF_NAME;\n }\n\n if (process.env.GITHUB_REF?.startsWith(\"refs/heads/\")) {\n return process.env.GITHUB_REF.replace(\"refs/heads/\", \"\");\n }\n\n return Git.getCurrentBranchName();\n }\n\n private getCurrentDate(): string {\n return new Date().toISOString().split(\"T\")[0];\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,OAAS,WAAAA,OAAe,YCAxB,OAAOC,OAAY,SACnB,OAAS,QAAAC,OAAY,kBAErB,IAAOC,GAAQ,IACND,GAAKD,GAAO,SAAS,UAAU,CAAC,ECHzC,OAAOG,OAAQ,UACf,OA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DAAiD,EAAK,EACvE,OAAO,WAAY,+CAAgD,EAAK,EACxE,OAAOvB,EAAW,ESrKrB,OAAOwB,OAAQ,mBACf,OAAOC,OAAU,YACjB,OAAS,WAAAC,OAAe,YACxB,OAAOC,OAAS,MCHhB,IAAMC,GAAsB,syDAuDtBC,GAAyB;AAAA,eAqBlBC,GAAqC,CAChD,CACE,IAAK,iBACL,IAAK,mCACL,YAAa,6BACf,EACA,CACE,IAAK,aACL,IAAK,+BACL,YAAa,8DACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,uBACf,EACA,CACE,IAAK,kBACL,IAAK,oCACL,YAAa,2BACf,EACA,CACE,IAAK,iBACL,IAAK,mCACL,YAAa,sBACf,EACA,CACE,IAAK,aACL,IAAK,+BACL,YAAa,uBACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,+BACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,6DACf,EACA,CACE,IAAK,YACL,IAAK,8BACL,YAAa,wBACf,EACA,CACE,IAAK,gBACL,IAAK,kCACL,YAAa,kCACf,EACA,CACE,IAAK,gBACL,IAAK,kCACL,YAAa,oCACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,8CACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,gDACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,qDACf,EACA,CACE,IAAK,kBACL,IAAK,oCACL,YAAa,mCACf,EACA,CACE,IAAK,aACL,IAAK,iCACL,YAAa,kBACf,EACA,CACE,IAAK,cACL,IAAK,iCACL,YAAa,iBACf,EACA,CACE,IAAK,kBACL,IAAK,iCACL,YAAa,mBACf,EACA,CACE,IAAK,gBACL,IAAK,iCACL,YAAa,sBACf,EACA,CACE,IAAK,gBACL,IAAK,iCACL,YAAa,gBACf,EACA,CACE,IAAK,aACL,IAAK,iCACL,YAAa,oBACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,sBACf,EACA,CACE,IAAK,iBACL,IA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mBAAmB,EACtD,OAAOC,GAAqBD,EAAiB,EAAK,CACpD,CAEA,aAAqB,sBAA+C,CAClE,OAAI,QAAQ,IAAI,gBACP,QAAQ,IAAI,gBAGjB,QAAQ,IAAI,YAAY,WAAW,aAAa,EAC3C,QAAQ,IAAI,WAAW,QAAQ,cAAe,EAAE,EAGlD3B,EAAI,qBAAqB,CAClC,CAEQ,gBAAyB,CAC/B,OAAO,IAAI,KAAK,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC,CAC9C,CACF,EDrVA,IAAO6B,GAAQC,GACZ,QAAQ,aAAa,EACrB,YAAY,oCAAoC,EAChD,OAAO,SAAY,CAGpB,MADiB,MAAMC,GAAW,OAAO,GAC1B,uBAAuB,CACxC,CAAC,E5EYDC,GACG,KAAK,MAAM,EACX,QAAQC,GAAkB,CAAC,EAC3B,YAAY,8CAA8C,EAE7DD,GAAQ,YAAY,YAAaE,GAAW,CAAC,EAE7CF,GAAQ,MAAM",
|
|
6
|
-
"names": ["program", "figlet", "mind", "auroSplash_default", "fs", "path", "fileURLToPath", "debugLog", "message", "getPackageVersion", "__filename", "__dirname", "packagePath", "error", "program", "ora", "withBuildOptions", "command", "withServerOptions", "terser", "watch", "existsSync", "readFileSync", "rmSync", "writeFileSync", "basename", "dirname", "join", "resolve", "pathToFileURL", "glob", "ora", "rollup", "sass", "ora", "spawn", "ora", "shell", "command", "_args", "commandString", "spinner", "finalCommand", "finalArgs", "parts", "isWatchMode", "child", "commandOutput", "data", "output", "resolve", "reject", "code", "fs", "path", "markdownTable", "Docs", "_Docs", "options", "outDir", "outFile", "manifestPath", "getElements", "renderAllElements", "manifestContent", "error", "elements", "docsDir", "apiMarkdown", "apiFilename", "wcaModules", "els", "module", "dec", "a", "b", "element", "includeTitle", "sections", "renderTable", "renderPropertiesAttributesTable", "renderParameters", "getType", "propertiesTable", "methodsTable", "m", "eventsTable", "slotsTable", "cssPartsTable", "cssPropertiesTable", "escapeMarkdown", "properties", "attributes", "mergedData", "processedNames", "prop", "propType", "displayType", "attr", "headers", "rows", "item", "defaultDoubleSanitized", "defaultWrapped", "parameters", "param", "paramType", "description", "name", "data", "get", "capitalize", "filteredData", "p", "value", "table", "text", "obj", "type", "normalizeType", "t", "ref", "result", "pathInput", "fallback", "parts", "current", "s", "str", "fs", "os", "path", "process", "getAuroHomeDir", "homeDir", "withHomeDir", "args", "fromCliRoot", "relativePath", "cliScript", "dirname", "configPath", "file", "copyFileSync", "existsSync", "mkdirSync", "join", "resolve", "copyReadmeToDemo", "cwd", "readmeSrc", "readmeDest", "demoDir", "ora", "watchers", "registerWatcher", "watcher", "handlerInstalled", "installShutdownHandler", "closeSpinner", "Logger", "generateReadmeUrl", "processContentForFile", "templateFiller", "fs", "readFileSync", "existsSync", "path", "PAGE_TEMPLATE_PATH", "defaultDocsProcessorConfig", "pathFromCwd", "pathLike", "findMonorepoRoot", "startDir", "dir", "pkgPath", "parent", "fileConfigs", "config", "skipReadme", "configs", "inputConfig", "fileExists", "pageTemplateFullPath", "pageObjects", "file", "processDocFiles", "fileConfigsList", "monorepoName", "rootPkgPath", "extraVars", "fileConfig", "postProcessMarkdownFile", "err", "outputPath", "outputDir", "outputContents", "emptyTagPattern", "match", "modified", "demoDir", "fullMatch", "type", "srcPath", "resolvedPath", "fallbackPath", "actualPath", "fileContent", "replacement", "ext", "escaped", "fencePattern", "convertedContents", "_match", "lang", "code", "language", "open", "content", "close", "lines", "nonEmpty", "l", "minIndent", "m", "processed", "outputLines", "insidePre", "i", "runDefaultDocsBuild", "options", "readmeTemplate", "isLocalPath", "pathToFile", "existsSync", "readFileSync", "builtinModules", "resolve", "startDevServer", "hmrPlugin", "esbuild", "ora", "MODULE_DIRS", "WDS_OUTSIDE_ROOT_RE", "nodeModulesCssPlugin", "context", "urlPath", "cwd", "dir", "MODULE_DIRS", "candidate", "resolve", "existsSync", "readFileSync", "resolveWdsPath", "rootDir", "match", "cjsToEsmPlugin", "CJS_PATTERN", "cache", "resolvedRootDir", "config", "filePath", "output", "builtinModules", "error", "DEFAULT_CONFIG", "startDevelopmentServer", "options", "serverSpinner", "ora", "serverConfig", "next", "hmrPlugin", "server", "startDevServer", "cem", "cemSpinner", "ora", "shell", "configPath", "error", "errorMessage", "api", "docsSpinner", "Docs", "docs", "options", "runDefaultDocsBuild", "copyReadmeToDemo", "compileDemoScss", "buildDemoBundle", "serve", "startDevelopmentServer", "watchDocs", "chokidar", "watchPaths", "ignored", "watcher", "watchSpinner", "rebuildTimer", "rebuilding", "pendingRebuild", "rebuild", "triggeredBy", "spinner", "_event", "filePath", "registerWatcher", "installShutdownHandler", "analyzeComponents", "cem", "api", "basename", "join", "resolve", "commonjs", "nodeResolve", "glob", "litScss", "path", "glob", "watchGlobs", "globs", "items", "item", "filename", "error", "DEFAULTS", "getPluginsConfig", "modulePaths", "options", "watchPatterns", "dedupe", "dev", "allModulePaths", "cwd", "absoluteModulePaths", "MODULE_DIRS", "dir", "resolve", "nodeResolve", "commonjs", "litScss", "join", "watchGlobs", "getMainBundleConfig", "watch", "input", "outputDir", "format", "chunk", "getExternalConfig", "getWatcherConfig", "getDemoConfig", "globPattern", "ignorePattern", "entries", "glob", "plugins", "watcher", "file", "basename", "warning", "defaultHandler", "watchOptions", "additional", "cleanupDist", "distPath", "join", "spinner", "ora", "rmSync", "error", "runBuildStep", "taskName", "taskFn", "successMsg", "failMsg", "result", "buildCombinedBundle", "mainConfig", "demoConfigs", "runBuildStep", "mainBundle", "rollup", "cfg", "bundle", "generateDocs", "options", "sourceFiles", "outFile", "skipDocs", "skipSpinner", "ora", "analyzeComponents", "runDefaultDocsBuild", "copyReadmeToDemo", "createNodeModulesImporter", "cwd", "tryResolve", "filePath", "join", "dirname", "basename", "c", "existsSync", "findInModuleDirs", "pkgPath", "dir", "MODULE_DIRS", "found", "resolve", "exportResolved", "resolveViaExports", "pkgName", "subpath", "parts", "slashIdx", "pkgJsonPath", "exports", "readFileSync", "mapped", "target", "resolved", "url", "lastIdx", "pathToFileURL", "compileDemoScss", "demoDir", "scssFiles", "glob", "importer", "loadPaths", "scssFile", "result", "cssFile", "writeFileSync", "buildDemoBundle", "configs", "getDemoConfig", "path", "ora", "buildInProgress", "builds", "MIN_BUILD_INTERVAL", "sourceEventPaths", "OUTPUT_PATHS", "isOutputFile", "filePath", "normalizedPath", "path", "outputPath", "error", "runBuildTask", "taskName", "taskFn", "task", "handleWatcherEvents", "watcher", "options", "onInitialBuildComplete", "isInitialBuild", "buildTasksResults", "scheduledTasksTimer", "bundleSpinner", "watchSpinner", "ora", "buildTasks", "sourceFiles", "outFile", "skipDocs", "skipSpinner", "analyzeSpinner", "analyzeComponents", "docsSpinner", "generateDocs", "compileDemoScss", "checkInitialBuildComplete", "schedulePostBundleTasks", "delay", "event", "inputs", "input", "setupWatchModeListeners", "scssWatcher", "registerWatcher", "installShutdownHandler", "runProductionBuild", "options", "mainBundleConfig", "getMainBundleConfig", "demoConfig", "getDemoConfig", "terser", "generateDocs", "compileDemoScss", "buildCombinedBundle", "setupWatchMode", "isDevMode", "watcher", "watch", "handleWatcherEvents", "startDevelopmentServer", "chokidar", "scssCompiling", "scssPending", "scssTimer", "scssWatcher", "error", "setupWatchModeListeners", "buildWithRollup", "cleanupDist", "devCommand", "program", "withBuildOptions", "withServerOptions", "dev_default", "options", "build", "ora", "buildWithRollup", "error", "program", "ora", "buildCommand", "program", "withBuildOptions", "build_default", "options", "build", "ora", "buildWithRollup", "error", "exec", "path", "process", "fileURLToPath", "util", "program", "inquirer", "migrate_default", "program", "options", "filename", "fileURLToPath", "dirname", "path", "scriptPath", "execPromise", "util", "exec", "process", "inquirer", "shell", "process", "program", "readFile", "writeFile", "Logger", "fs", "path", "Octokit", "ora", "processContentForFile", "templateFiller", "getFolderItemsFromRelativeRepoPath", "ref", "octokit", "responseData", "errorMessage", "error", "errorSpinner", "processFolderItemsIntoFileConfigs", "folderItems", "templatePathToReplace", "rootDir", "fileConfigs", "item", "directorySpinner", "nestedFolderItems", "nestedConfigs", "finalPath", "outputPath", "config", "removeDirectory", "dirPath", "generateDirectoryTree", "prefix", "isLast", "stats", "baseName", "result", "sortedEntries", "i", "entry", "entryPath", "isLastEntry", "newPrefix", "syncDotGithubDir", "template", "templatesDefaultGithubPath", "githubPath", "removeSpinner", "processSpinner", "treeSpinner", "githubDirPath", "treeOutput", "treeError", "sync_default", "program", "options", "Logger", "cwd", "process", "syncDotGithubDir", "codeownersPath", "codeownersFixed", "readFile", "writeFile", "codeownersError", "error", "fs", "path", "Logger", "program", "glob", "prepWcaCompatibleCode_default", "code", "sourcePath", "defaultTag", "className", "classDesc", "WAC_DIR", "path", "globPath", "sources", "source", "glob", "err", "createExtendsFile", "filePaths", "fs", "filePath", "resolvedPath", "fileContent", "newPath", "newCode", "prepWcaCompatibleCode_default", "main", "wca_setup_default", "program", "Logger", "error", "program", "chalk", "ora", "appendFile", "readFile", "Logger", "simpleGit", "git", "error", "Git", "_Git", "pattern", "err", "sourceBranch", "branch", "targetBranch", "commitRange", "sourceBranchRef", "remotes", "originRemote", "remote", "remoteUrl", "url", "match", "commitChunks", "chunk", "commits", "parts", "hash", "date", "author_name", "subject", "bodyLines", "line", "body", "shortHash", "typeMatch", "type", "log", "result", "files", "branchName", "message", "chalk", "MAX_SUBJECT_LENGTH", "MAX_BODY_LENGTH", "getColoredType", "type", "wrapString", "str", "maxLength", "words", "result", "currentLine", "word", "displayDebugView", "commitList", "commit", "subject", "body", "github", "getExistingLabels", "token", "octokit", "context", "owner", "repo", "prNumber", "existingLabels", "label", "error", "applyLabelToPR", "prefixedLabel", "existingSemanticLabels", "existingLabel", "RELEASE_COMMIT_TYPES", "generateReleaseNotes", "commitList", "showLog", "releaseNotes", "commit", "bodyLines", "line", "formattedLine", "chalk", "filterCommitList", "fallbackCommits", "releaseCommits", "commitsToShow", "analyzeCommits", "debug", "setLabel", "spinner", "ora", "Git", "filteredCommits", "displayDebugView", "commitTypes", "formattedTypes", "type", "getColoredType", "handleLabels", "error", "validCommitTypes", "foundCommitTypes", "selectedLabel", "highestPriorityIndex", "priorityIndex", "labelSpinner", "getExistingLabels", "applyLabelToPR", "errorMessage", "check_commits_default", "program", "option", "analyzeCommits", "fs", "get", "chalk", "program", "ora", "pr_release_default", "option", "updatePackageJson", "namespace", "prNumber", "packageSpinner", "packageJsonPath", "packageJson", "releaseVersion", "packageComponent", "packageName", "incrementVersion", "getIncrementVersion", "packageVersion", "error", "spinner", "resolve", "handleResponse", "res", "data", "chunk", "packageData", "versions", "maxIteration", "versionRegex", "version", "match", "iteration", "registryUrl", "req", "err", "path", "fileURLToPath", "program", "open", "__filename", "fileURLToPath", "cliRootDir", "path", "test_default", "program", "option", "command", "coveragePath", "files", "shell", "open", "fs", "path", "program", "inquirer", "ora", "fs", "path", "ora", "JsonConfig", "toYaml", "config", "key", "value", "k", "v", "createMultiGitterDependencyTreeConfig", "outputPath", "spinner", "configContent", "configPath", "error", "fs", "getBatchedUpdateOrder", "dependencyTree", "inDegree", "batches", "currentBatch", "queue", "pkg", "queueLength", "current", "dependent", "getJsonFilesFromDirectory", "directory", "file", "formatDependencyTree", "jsonFileDirectory", "targetDependencies", "files", "contents", "data", "packageName", "peerDependencies", "devDependencies", "dependencies", "allDependencies", "dependency", "relevantPackages", "node", "dep", "target", "_filteredDependencyTree", "AURO_COMPONENT_PACKAGES", "CONFIG_DIR", "withHomeDir", "OUTPUT_DIR", "auroPackages", "AURO_COMPONENT_PACKAGES", "getOrCreateDependencyTree", "relevantPackages", "fs", "OUTPUT_DIR", "CONFIG_DIR", "error", "spinner", "ora", "createMultiGitterDependencyTreeConfig", "multiGitterCommand", "fromCliRoot", "path", "shell", "formatDependencyTree", "getDependencyBatchesFromTree", "dependencyTreePath", "dependencyTree", "batches", "getBatchedUpdateOrder", "agent_default", "program", "option", "answers", "inquirer", "input", "value", "component", "batchedUpdateOrderText", "batch", "index", "pkg", "resolve", "writeFile", "path", "process", "Logger", "program", "ora", "readFile", "path", "process", "UNPKG_BASE", "REGISTRY_BASE", "REQUEST_TIMEOUT_MS", "parseTarget", "target", "at", "isInside", "parent", "child", "rel", "readLocalManifest", "pkg", "modulesRoot", "pkgDir", "version", "manifestRelPath", "pkgJson", "manifest", "fetchManifest", "options", "preferLocal", "allowNetwork", "ref", "local", "url", "response", "error", "message", "partitionOutcomes", "outcomes", "skipped", "outcome", "fetchLatestVersion", "data", "Logger", "namespaceReferences", "node", "pkg", "item", "source", "result", "key", "value", "mergeManifests", "sources", "warn", "modules", "manifest", "module", "namespaced", "schemaVersions", "buildAggregateManifest", "packages", "options", "outcomes", "pkg", "fetchManifest", "sources", "outcome", "skipped", "transientFailures", "partitionOutcomes", "mergeManifests", "runCem", "options", "spinner", "ora", "AURO_COMPONENT_PACKAGES", "aggregate", "sources", "skipped", "transientFailures", "buildAggregateManifest", "process", "outputPath", "path", "writeFile", "error", "message", "outcome", "Logger", "cem_default", "program", "readFileSync", "dirname", "join", "resolve", "process", "program", "ora", "mkdtempSync", "rmSync", "tmpdir", "join", "withoutStringLiterals", "text", "hasBalancedDelimiters", "closeToOpen", "stack", "prev", "ch", "withSafeType", "entry", "_dropped", "rest", "isPrivateReflection", "attribute", "memberPrivacyByName", "fieldName", "description", "privacy", "withNamedEntriesPruned", "declaration", "hasName", "members", "member", "resolvedTagFor", "component", "resolvedTags", "importPathsByClass", "components", "c", "buildManifest", "withTempDir", "fn", "dir", "ensureTrailingNewline", "contents", "GLOBAL_ARIA_ATTRS", "BASE_PROPS_OPEN", "SVELTE_GLOBAL_MEMBERS", "injectGlobalAttributes", "svelteGlobals", "block", "ENUMERATED_ATTRS", "UNINFORMATIVE_STRING_TYPES", "INVALID_PRIMITIVE_TYPES", "BARE_GENERIC_TYPES", "VAGUE_OBJECT_TYPES", "INVALID_PRIMITIVE_RULES", "token", "fix", "BARE_GENERIC_RULES", "shape", "describeType", "text", "DEPRECATION_MARKERS", "hasDeprecationMarker", "texts", "re", "isDeprecationFlagged", "deprecated", "isNonEmptyString", "checkMemberDeprecation", "findings", "element", "path", "entry", "checkEventSlotDeprecation", "kind", "checkDeprecationDetail", "registeredElements", "manifest", "module", "decl", "value", "checkNames", "collection", "entries", "index", "checkType", "hasBalancedDelimiters", "checkPrimitiveType", "raw", "scannable", "withoutStringLiterals", "isEscaped", "backslashes", "j", "splitTopLevelUnion", "members", "depth", "quote", "start", "i", "ch", "member", "isStringLiteralMember", "checkWidenedUnion", "hasLiteral", "hasBareString", "m", "isMissingText", "checkDescription", "checkDeclaration", "attributes", "events", "slots", "a", "e", "s", "memberPrivacyByName", "attribute", "isPrivateReflection", "runContractRules", "execFileSync", "mkdirSync", "writeFileSync", "createRequire", "dirname", "join", "generateJsxTypes", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "HTML_CUSTOM_DATA_FILENAME", "HTML_CUSTOM_DATA_SETTINGS_KEY", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "HTML_CUSTOM_DATA_PATH", "CSS_SNIPPETS_FILENAME", "CSS_SNIPPETS_PATH", "FRAMEWORK_TYPES_DIR", "JSX_TYPES_FILENAME", "SVELTE_TYPES_FILENAME", "JSX_TYPES_PATH", "SVELTE_TYPES_PATH", "TSCONFIG_INCLUDE_KEY", "TSCONFIG_INCLUDE_ENTRY", "buildJsxTypes", "components", "resolvedTags", "manifest", "buildManifest", "importPaths", "importPathsByClass", "contents", "withTempDir", "outdir", "generateJsxTypes", "JSX_TYPES_FILENAME", "tagName", "name", "JSX_TYPES_PATH", "ensureTrailingNewline", "injectGlobalAttributes", "readFileSync", "join", "generateSvelteTypes", "MODULE_SCOPED_SVELTE_NAMESPACE", "GLOBAL_SVELTE_NAMESPACE", "NATIVE_DOM_EVENTS", "SVELTE4_EVENT_HANDLER", "addSvelte5EventHandlers", "contents", "_match", "indent", "name", "handler", "CUSTOM_ELEMENT_MAPPING", "overrideCollidingBaseMembers", "head", "tail", "PROPS_BLOCK", "MEMBER_JSDOC_OPEN", "labelComponentMembers", "markerByClass", "whole", "className", "body", "label", "marked", "markerLabelsByClass", "components", "resolvedTags", "component", "defaultTag", "resolvedTag", "globalizeSvelteNamespace", "buildSvelteTypes", "manifest", "buildManifest", "withTempDir", "outdir", "generateSvelteTypes", "SVELTE_TYPES_FILENAME", "readFileSync", "join", "SVELTE_TYPES_PATH", "ensureTrailingNewline", "injectGlobalAttributes", "require", "createRequire", "TSC", "JSX_SHIM", "stubFileFor", "importPath", "importedNamesByPath", "source", "byPath", "re", "match", "names", "entry", "set", "name", "writeTsconfig", "cwd", "include", "paths", "writeFileSync", "join", "writeArtifact", "artifact", "dest", "mkdirSync", "dirname", "compile", "label", "setup", "withTempDir", "execFileSync", "error", "e", "output", "runGenerationSmoke", "components", "identityTags", "c", "findings", "jsx", "buildJsxTypes", "importsByPath", "jsxFinding", "file", "svelte", "buildSvelteTypes", "svelteFinding", "installedFromOutcomes", "outcomes", "installed", "outcome", "detectInstalled", "packages", "AURO_COMPONENT_PACKAGES", "pkg", "fetchManifest", "registeredElements", "manifest", "module", "decl", "resolveComponents", "installed", "components", "owningPackages", "grounded", "pkg", "version", "elements", "isMonorepo", "declaration", "tagName", "owners", "duplicates", "packages", "resolveInstalled", "detectInstalled", "readSiblingPackageJson", "cemPath", "raw", "readFileSync", "join", "dirname", "resolve", "parsed", "formatFinding", "finding", "mark", "where", "locator", "DEFAULT_CEM_PATH", "runCemCheck", "options", "spinner", "ora", "fail", "message", "process", "error", "manifest", "pkg", "version", "installed", "components", "resolveComponents", "findings", "runContractRules", "runGenerationSmoke", "errors", "f", "warnings", "failed", "summary", "cem_check_default", "program", "fs", "path", "program", "ora", "AURO_CONTEXT_HEADER", "COMPONENT_TABLE_HEADER", "STATIC_COMPONENTS", "renderComponentRows", "components", "component", "STATIC_COMPONENT_TABLE", "AURO_CONTEXT_FOOTER", "buildAuroContext", "componentTable", "AURO_CONTEXT", "clean", "text", "chalk", "FORMKIT_PACKAGE", "LEGACY_FORMKIT_PACKAGES", "LEGACY_SET", "isLegacyFormkitPackage", "pkg", "formkitTagFor", "formkitSubpathFor", "SEMVER", "parseSemver", "version", "match", "compareVersions", "a", "b", "pa", "pb", "i", "len", "ai", "bi", "aNum", "bNum", "diff", "checkOutdated", "installed", "entries", "latest", "pkg", "fetchLatestVersion", "outdated", "index", "newest", "cmp", "FORMKIT_MARK", "renderOutdatedBanner", "legacy", "o", "isLegacyFormkitPackage", "normal", "heading", "pkgWidth", "installedWidth", "isLegacy", "rows", "row", "chalk", "guidance", "updateCmd", "formkitSubpathFor", "visibleWidths", "base", "width", "border", "buildComponentTable", "allowNetwork", "byTag", "component", "STATIC_COMPONENTS", "outcomes", "AURO_COMPONENT_PACKAGES", "pkg", "fetchManifest", "local", "installedFromOutcomes", "resolved", "enriched", "outcome", "declarations", "module", "decl", "tag", "liveDescription", "clean", "existing", "renderComponentRows", "reportOutdated", "spinner", "ora", "outdated", "checkOutdated", "renderOutdatedBanner", "runContext", "options", "online", "rows", "context", "buildAuroContext", "writeSpinner", "outputPath", "path", "fs", "error", "message", "context_default", "program", "fs", "path", "process", "program", "inquirer", "ora", "CONFIG_FILENAME", "existsSync", "readFileSync", "statSync", "path", "parseJsonc", "EDITOR_TARGETS", "isDir", "cwd", "rel", "statSync", "path", "dependencyNames", "raw", "readFileSync", "pkg", "parseJsonc", "detectVsCode", "VSCODE_DIR", "detectCssSnippets", "detectJsx", "tsconfigPath", "existsSync", "tsconfig", "detectSvelte", "ext", "detectEditorSignals", "existsSync", "readFileSync", "path", "parseJsonc", "toAbsolute", "cwd", "rel", "path", "readOrNull", "absolute", "readFileSync", "settingsHasPointer", "contents", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "value", "parseJsonc", "HTML_CUSTOM_DATA_SETTINGS_KEY", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "tsProgramIncludesTypes", "configRel", "data", "include", "TSCONFIG_INCLUDE_KEY", "TSCONFIG_INCLUDE_ENTRY", "verifyEditorWiring", "selection", "inconsistencies", "existsSync", "HTML_CUSTOM_DATA_PATH", "SVELTE_TYPES_PATH", "JSX_TYPES_PATH", "fs", "path", "SNIPPET_SCOPE", "isChoiceSafe", "name", "partNames", "component", "part", "snippetFor", "tag", "parts", "choice", "buildCssSnippets", "components", "resolvedTags", "snippets", "resolvedTagFor", "CSS_SNIPPETS_PATH", "ensureTrailingNewline", "getVsCodeHtmlCustomData", "buildHtmlCustomData", "components", "resolvedTags", "manifest", "buildManifest", "contents", "withTempDir", "outdir", "getVsCodeHtmlCustomData", "HTML_CUSTOM_DATA_PATH", "ensureTrailingNewline", "applyEdits", "modify", "parseJsonc", "parseTree", "FORMATTING", "isPlainObject", "value", "parseObject", "source", "label", "errors", "data", "parseJsonc", "applyValueEdit", "path", "base", "edits", "modify", "applyEdits", "deleteLoneTopLevelKey", "key", "root", "parseTree", "prop", "end", "applyKeyDeletion", "surgical", "mergeVsCodeSettings", "existing", "entry", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "parsed", "current", "HTML_CUSTOM_DATA_SETTINGS_KEY", "nextValue", "mergeTsconfigInclude", "TSCONFIG_INCLUDE_ENTRY", "configName", "include", "TSCONFIG_INCLUDE_KEY", "unmergeVsCodeSettings", "remaining", "v", "unmergeTsconfigInclude", "toAbsolute", "cwd", "filename", "path", "writeArtifact", "artifact", "absolute", "fs", "readOrEmpty", "error", "writeEditorArtifacts", "components", "resolvedTags", "selection", "written", "warnings", "buildHtmlCustomData", "settingsRel", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "settingsAbs", "merged", "mergeVsCodeSettings", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "HTML_CUSTOM_DATA_SETTINGS_KEY", "buildJsxTypes", "buildSvelteTypes", "buildCssSnippets", "configRel", "configAbs", "existing", "mergeTsconfigInclude", "TSCONFIG_INCLUDE_ENTRY", "TSCONFIG_INCLUDE_KEY", "AGENTS_FILENAME", "CLAUDE_FILENAME", "GROUNDING_MARKER", "GROUNDING_HEADER", "INSTALLED_TABLE_HEADER", "REGENERATION_NOTE", "CLAUDE_MD", "AGENTS_FILENAME", "AURO_CODING_RULES", "SCOPE", "toPackageName", "name", "trimmed", "lower", "kebabToCamel", "_", "char", "deprecatedTag", "deprecated", "clean", "renderList", "rows", "width", "label", "desc", "formatDeclaration", "pkg", "decl", "options", "installPkg", "importSpecifier", "lines", "description", "heritage", "apiBodyLines", "attributes", "a", "type", "def", "attrFields", "members", "m", "isMethod", "typeText", "slots", "s", "events", "e", "cssParts", "p", "cssProps", "displayTag", "component", "resolvedTags", "componentBlock", "tag", "pkg", "importPath", "decl", "lines", "description", "clean", "heritage", "apiBodyLines", "generateAgentsMd", "components", "rows", "sections", "installedLines", "INSTALLED_TABLE_HEADER", "installedSection", "GROUNDING_HEADER", "AURO_CODING_RULES", "REGENERATION_NOTE", "generateClaudeMd", "CLAUDE_MD", "groundingFiles", "AGENTS_FILENAME", "CLAUDE_FILENAME", "appendFileSync", "readFileSync", "path", "simpleGit", "GITIGNORE_HEADER", "findIgnored", "cwd", "paths", "parentDir", "rel", "dir", "readGitignoreLines", "current", "line", "appendGitignore", "lines", "dedupe", "gitignoreAbs", "existing", "toAdd", "prefix", "unignore", "ignoredPaths", "stillIgnored", "present", "trio", "seenDirs", "unfixable", "readFileSync", "writeFileSync", "path", "globSync", "readFileSync", "writeFileSync", "path", "globSync", "ts", "AURO_PREFIX", "SOURCE_GLOB", "SOURCE_GLOB_IGNORE", "RegistryError", "message", "emptyConfig", "defaultPrefix", "assertConfig", "value", "source", "obj", "prefix", "loadConfig", "cwd", "file", "path", "CONFIG_FILENAME", "raw", "readFileSync", "error", "parsed", "saveConfig", "config", "writeFileSync", "scriptKindFor", "filePath", "ts", "staticTag", "arg", "scanSource", "scriptKind", "matches", "defaultRegistrations", "warnings", "sourceFile", "visit", "node", "object", "className", "tag", "SVELTE_SCRIPT", "SVELTE_LANG_TS", "extractSvelteScripts", "scripts", "match", "attributes", "content", "scanProject", "files", "globSync", "collect", "scan", "baseOf", "canonicalTag", "inferPrefixFromTag", "customTag", "base", "suggestDefaultPrefix", "prefixes", "counts", "suggestion", "best", "count", "reconcileRegistrations", "components", "byClassName", "component", "overrides", "canonical", "defaultRegistered", "applyPrefix", "planTagResolution", "options", "configOverrides", "reconciled", "configDefault", "effectiveDefault", "resolvedTags", "persistOverrides", "needingDefault", "reconciliationWarnings", "noPrefixWarnings", "fromConfig", "fromScan", "resolved", "inferred", "custom", "mixed", "needsDefaultPrefix", "PACKAGE_JSON", "readPackageJson", "cwd", "raw", "readFileSync", "path", "error", "detectLegacyFormkit", "pkgJson", "found", "fields", "pkg", "LEGACY_FORMKIT_PACKAGES", "field", "version", "escapeRegExp", "value", "rewriteSource", "source", "legacyPkgs", "next", "rewrites", "deep", "escaped", "bare", "_match", "quote", "formkitSubpathFor", "deepRe", "deepMatch", "migrateToFormkit", "legacy", "l", "isLegacyFormkitPackage", "report", "block", "FORMKIT_PACKAGE", "writeFileSync", "files", "globSync", "SOURCE_GLOB", "SOURCE_GLOB_IGNORE", "file", "rel", "specifier", "existsSync", "readdirSync", "readFileSync", "rmdirSync", "rmSync", "writeFileSync", "path", "parseJsonc", "toAbsolute", "cwd", "rel", "path", "isEmptyObject", "source", "data", "parseJsonc", "hasComments", "readOrNull", "absolute", "readFileSync", "error", "UNCONDITIONAL_ARTIFACTS", "HTML_CUSTOM_DATA_PATH", "CSS_SNIPPETS_PATH", "JSX_TYPES_PATH", "SVELTE_TYPES_PATH", "classifyGroundingFile", "contents", "kind", "GROUNDING_MARKER", "CLAUDE_MD", "planReset", "filesToRemove", "filesToSkip", "warnings", "AGENTS_FILENAME", "CLAUDE_FILENAME", "verdict", "existsSync", "CONFIG_FILENAME", "loadConfig", "reason", "RegistryError", "unmerges", "settingsRel", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "settingsContents", "result", "unmergeVsCodeSettings", "configRel", "unmergeTsconfigInclude", "FRAMEWORK_TYPES_DIR", "isEmptyDir", "readdirSync", "applyReset", "plan", "removed", "rmSync", "unmerged", "writeFileSync", "prunedDirs", "rmdirSync", "chalk", "MAX_WIDTH", "CONTENT_WIDTH", "BULLET", "CONTINUATION_INDENT", "wrapText", "text", "width", "words", "lines", "current", "word", "renderWarningBanner", "heading", "messages", "color", "accent", "body", "message", "index", "line", "lineIndex", "prefix", "headingWidth", "border", "isNonInteractive", "options", "process", "promptDefaultPrefix", "plan", "accept", "inquirer", "prefix", "isValidCustomTag", "tag", "trimmed", "promptCustomTags", "components", "resolvedTags", "customize", "overrides", "component", "canonical", "calculated", "entered", "withUserOverrides", "config", "base", "emptyConfig", "EDITOR_TARGET_META", "resolveEditorTargets", "cwd", "persisted", "signals", "detectEditorSignals", "interactive", "selection", "pending", "target", "EDITOR_TARGETS", "flag", "saved", "label", "artifact", "answers", "name", "offerFormkitMigration", "legacy", "detectLegacyFormkit", "error", "message", "names", "l", "migrate", "spinner", "ora", "report", "migrateToFormkit", "file", "specifier", "reportOutdated", "installed", "c", "outdated", "checkOutdated", "renderOutdatedBanner", "runInit", "runReset", "duplicates", "resolveInstalled", "loadConfig", "RegistryError", "CONFIG_FILENAME", "scan", "scanProject", "planTagResolution", "needsDecision", "resolvedPrefix", "reason", "customTags", "editorSelection", "writeSpinner", "editorReport", "groundingFiles", "fs", "path", "writeEditorArtifacts", "saveConfig", "editorNote", "AGENTS_FILENAME", "CLAUDE_FILENAME", "warning", "duplicate", "renderWarningBanner", "verdict", "verifyEditorWiring", "healReport", "alreadyWarned", "touched", "reconcileGitignore", "ignored", "findIgnored", "fix", "fixed", "unfixable", "unignore", "isEmptyResetPlan", "planReset", "skip", "unmerge", "dir", "confirm", "resetSpinner", "applyReset", "removedNote", "unmergedNote", "prunedNote", "d", "init_default", "program", "process", "Logger", "program", "ora", "resolveSource", "pkg", "options", "plain", "result", "fetchManifest", "isLegacyFormkitPackage", "localLegacy", "FORMKIT_PACKAGE", "formkitSubpathFor", "formkitTagFor", "runComponent", "name", "toPackageName", "spinner", "ora", "source", "target", "process", "declarations", "module", "decl", "origin", "outdatedBanner", "check", "outdated", "checkOutdated", "renderOutdatedBanner", "formatDeclaration", "Logger", "component_default", "program", "program", "docsCommand", "program", "withServerOptions", "docs_default", "options", "cem", "api", "docs", "serve", "watchDocs", "program", "Octokit", "azdev", "ora", "fetchGitHubIssue", "issueUrl", "ghToken", "octokit", "owner", "repo", "issueNumberStr", "urlMatch", "shortMatch", "issueNumber", "issue", "error", "getExistingADOLink", "query", "variables", "project19Item", "item", "adoFieldValue", "fieldValue", "updateGitHubProject", "adoWorkItemUrl", "projectNumber", "response", "projectId", "issueId", "adoField", "field", "projectItemId", "createADOWorkItem", "adoToken", "orgUrl", "projectName", "areaPath", "authHandler", "workItemTrackingApi", "workItemData", "createADOItem", "ghIssue", "spinner", "checkSpinner", "existingADOLink", "createSpinner", "workItem", "projectSpinner", "adoCommand", "program", "options", "createADOItem", "program", "Octokit", "simpleGit", "LABEL", "RC_SOURCE_BRANCH", "RC_BASE_BRANCH", "RCWorkflow", "_RCWorkflow", "owner", "repo", "octokit", "token", "info", "Git", "Octokit", "triggerBranch", "rcIssue", "linkedPr", "commitList", "filterCommitList", "data", "openIssues", "issue", "latestIssue", "issueNumber", "releaseNotes", "title", "branchRef", "branchName", "devBranch", "matchingRefs", "branchExists", "error", "head", "openPrs", "pr", "closedPrs", "template", "prBody", "prNumber", "filteredCommits", "generateReleaseNotes", "rc_workflow_default", "program", "RCWorkflow", "program", "getPackageVersion", "auroSplash_default"]
|
|
3
|
+
"sources": ["../src/index.ts", "../src/utils/auroSplash.js", "../src/utils/packageVersion.js", "../src/commands/dev.js", "../src/commands/_sharedOptions.js", "../src/scripts/build/index.js", "../src/scripts/build/bundleHandlers.js", "../src/scripts/docs/index.ts", "../src/utils/shell.js", "../src/scripts/docs/docs-generator.ts", "../src/utils/pathUtils.js", "../src/utils/copyReadmeToDemo.js", "../src/utils/shutdown.js", "../src/scripts/build/defaultDocsBuild.js", "../src/scripts/build/devServerUtils.js", "../src/scripts/build/paths.js", "../src/scripts/analyze.js", "../src/scripts/build/configUtils.js", "../src/scripts/build/plugins.js", "../src/scripts/build/watchModeHandlers.js", "../src/commands/build.js", "../src/commands/migrate.js", "../src/commands/sync.js", "../src/scripts/syncDotGithubDir.ts", "../src/commands/wca-setup.js", "../src/scripts/prepWcaCompatibleCode.mjs", "../src/commands/check-commits.ts", "../src/scripts/check-commits/commit-analyzer.ts", "../src/utils/gitUtils.ts", "../src/scripts/check-commits/display-utils.ts", "../src/scripts/check-commits/github-labels.ts", "../src/commands/pr-release.ts", "../src/commands/test.ts", "../src/commands/agent.ts", "../src/scripts/agent/run-migrations/writeMultiGitterConfig.js", "../src/scripts/formatDependencyTree.ts", "../src/static/auroComponents.ts", "../src/commands/cem.ts", "../src/utils/fetchManifest.ts", "../src/utils/mergeManifests.ts", "../src/utils/aggregateManifest.ts", "../src/commands/cem-check.ts", "../src/init/editors/manifest.ts", "../src/utils/detectInstalled.ts", "../src/init/resolver.ts", "../src/init/cem-check/rules.ts", "../src/init/cem-check/smoke.ts", "../src/init/editors/jsxTypes.ts", "../src/init/editors/layout.ts", "../src/init/editors/svelteTypes.ts", "../src/commands/context.ts", "../src/static/auroContext.ts", "../src/utils/cem.ts", "../src/utils/outdated.ts", "../src/static/formkitMigration.ts", "../src/commands/init.ts", "../src/init/config.ts", "../src/init/editors/detect.ts", "../src/init/editors/verify.ts", "../src/init/editors/write.ts", "../src/init/editors/cssSnippets.ts", "../src/init/editors/htmlCustomData.ts", "../src/init/editors/settings.ts", "../src/init/layout.ts", "../src/init/rules.ts", "../src/utils/formatComponent.ts", "../src/init/generator.ts", "../src/init/gitignore.ts", "../src/init/migrateFormkit.ts", "../src/init/registry.ts", "../src/init/reset.ts", "../src/utils/banner.ts", "../src/commands/component.ts", "../src/commands/docs.ts", "../src/commands/ado.ts", "../src/scripts/ado/index.ts", "../src/commands/rc-workflow.ts", "../src/scripts/rc-workflow/index.ts"],
|
|
4
|
+
"sourcesContent": ["import { program } from \"commander\";\nimport auroSplash from \"#utils/auroSplash.js\";\nimport getPackageVersion from \"#utils/packageVersion.js\";\n\n// Register commands (importing them will register them)\nimport \"#commands/dev.js\";\nimport \"#commands/build.js\";\nimport \"#commands/migrate.js\";\nimport \"#commands/sync.js\";\nimport \"#commands/wca-setup.js\";\nimport \"#commands/check-commits.ts\";\nimport \"#commands/pr-release.ts\";\nimport \"#commands/test.js\";\nimport \"#commands/agent.ts\";\nimport \"#commands/cem.ts\";\nimport \"#commands/cem-check.ts\";\nimport \"#commands/context.ts\";\nimport \"#commands/init.ts\";\nimport \"#commands/component.ts\";\nimport \"#commands/docs.ts\";\nimport \"#commands/ado.ts\";\nimport \"#commands/rc-workflow.ts\";\n\nprogram\n .name(\"auro\")\n .version(getPackageVersion())\n .description(\"A cli tool to support the Auro Design System\");\n\nprogram.addHelpText(\"beforeAll\", auroSplash());\n\nprogram.parse();\n", "import figlet from \"figlet\";\nimport { mind } from \"gradient-string\";\n\nexport default () => {\n return mind(figlet.textSync(\"Auro CLI\"));\n};\n", "/* eslint-disable no-underscore-dangle, no-undef */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Simple debug logger that only prints when DEBUG environment variable is set.\n * @param {string} message - The message to log.\n */\nfunction debugLog(message) {\n if (process.env.DEBUG) {\n console.log(`[DEBUG] ${message}`);\n }\n}\n\n/**\n * Retrieves the version from the package.json file.\n * @returns {string} The version from package.json.\n */\nexport default function getPackageVersion() {\n try {\n // Get the directory path of the current module\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n debugLog(`Current module path: ${__dirname}`);\n\n // Standard installed module location - current directory\n const packagePath = path.resolve(__dirname, \"..\", \"package.json\");\n\n debugLog(`Checking package.json at: ${packagePath}`);\n if (fs.existsSync(packagePath)) {\n debugLog(`Found package.json at: ${packagePath}`);\n const packageJson = JSON.parse(fs.readFileSync(packagePath, \"utf8\"));\n return packageJson.version;\n }\n\n // Fallback to a default version if we can't find the package.json\n debugLog(\n \"Could not find package.json in the standard installed module location, using default version\",\n );\n return \"0.0.0\";\n } catch (error) {\n console.error(\"Error retrieving package version:\", error);\n return \"0.0.0\";\n }\n}\n", "import { program } from \"commander\";\nimport ora from \"ora\";\nimport {\n withBuildOptions,\n withServerOptions,\n} from \"#commands/_sharedOptions.js\";\nimport { buildWithRollup } from \"#scripts/build/index.js\";\n\nlet devCommand = program\n .command(\"dev\")\n .description(\"Runs development server for auro components\");\n\ndevCommand = withBuildOptions(devCommand);\ndevCommand = withServerOptions(devCommand);\n\nexport default devCommand.action(async (options) => {\n try {\n const build = ora(\"Initializing...\");\n\n if (options.watch) {\n build.text = \"Waiting for changes...\";\n build.spinner = \"bouncingBar\";\n build.color = \"green\";\n } else {\n build.text =\n options.docs === false\n ? \"Building component (docs disabled)\"\n : \"Building component\";\n }\n\n build.start();\n\n if (!options.watch) {\n build.succeed(\"Build completed!\");\n }\n\n await buildWithRollup({ ...options, dev: true, watch: options.watch });\n } catch (error) {\n // If there's any active spinner, we need to fail it\n ora().fail(`Build failed: ${error.message}`);\n console.error(error);\n process.exit(1);\n }\n});\n", "/**\n * @param {import('commander').Command} command\n * @returns {import('commander').Command}\n */\nexport function withBuildOptions(command) {\n return command\n .option(\"-m, --module-paths [paths...]\", \"Path(s) to node_modules folder\")\n .option(\"-w, --watch\", \"Watches for changes\")\n .option(\"--skip-docs\", \"Skip documentation generation\", false)\n .option(\"-r, --readme-template <url>\", \"URL to the README template file\")\n .option(\n \"--wca-input [files...]\",\n \"Source file(s) to analyze for API documentation\",\n )\n .option(\"--wca-output [files...]\", \"Output file(s) for API documentation\");\n}\n\n/**\n * @param {import('commander').Command} command\n */\nexport function withServerOptions(command) {\n return command\n .option(\"-s, --serve\", \"Starts a server\")\n .option(\"-p, --port <number>\", \"Port for the server\")\n .option(\"-o, --open\", \"Open the browser after starting the server\");\n}\n", "import terser from \"@rollup/plugin-terser\";\nimport { watch } from \"rollup\";\nimport {\n buildCombinedBundle,\n cleanupDist,\n compileDemoScss,\n generateDocs,\n} from \"./bundleHandlers.js\";\nimport {\n getDemoConfig,\n getMainBundleConfig,\n} from \"./configUtils.js\";\nimport { startDevelopmentServer } from \"./devServerUtils.js\";\nimport {\n handleWatcherEvents,\n setupWatchModeListeners,\n} from \"./watchModeHandlers.js\";\n\n/**\n * Run a production build once\n * @param {object} options - Build options\n * @returns {Promise<void>}\n */\nasync function runProductionBuild(options) {\n const mainBundleConfig = getMainBundleConfig(options);\n const demoConfig = getDemoConfig(options);\n\n // Add terser for minification in production\n if (!options.dev) {\n mainBundleConfig.config.plugins.push(terser());\n }\n\n // Generate docs if enabled\n await generateDocs(options);\n\n // Compile demo SCSS to CSS\n await compileDemoScss();\n\n // Build main and demo bundles\n await buildCombinedBundle(mainBundleConfig.config, demoConfig.configs);\n}\n\n/**\n * Set up watch mode for development\n * @param {object} options - Build options\n * @returns {Promise<object>} - Rollup watcher\n */\nasync function setupWatchMode(options) {\n const { dev: isDevMode } = options;\n const mainBundleConfig = getMainBundleConfig({ ...options, watch: true });\n const demoConfig = getDemoConfig({ ...options, watch: true });\n\n // Create and configure the watcher. Each demo entry is its own config so\n // shared imports inline into <name>.min.js rather than emitting a separate\n // <name>2.min.js chunk.\n const watcher = watch([mainBundleConfig.config, ...demoConfig.configs]);\n\n // Set up watcher event handlers\n handleWatcherEvents(\n watcher,\n options,\n isDevMode ? async () => startDevelopmentServer(options) : undefined,\n );\n\n // Watch demo SCSS files separately since they are not part of the rollup bundle\n const chokidar = await import(\"chokidar\");\n let scssCompiling = false;\n let scssPending = false;\n let scssTimer = null;\n\n const scssWatcher = chokidar.watch(\"./demo/**/*.scss\", {\n ignoreInitial: true,\n ignored: [\"**/demo/**/*.min.css\"],\n awaitWriteFinish: {\n stabilityThreshold: 500,\n pollInterval: 100,\n },\n });\n\n scssWatcher.on(\"all\", () => {\n if (scssTimer) clearTimeout(scssTimer);\n\n scssTimer = setTimeout(async () => {\n if (scssCompiling) {\n scssPending = true;\n return;\n }\n\n scssCompiling = true;\n try {\n await compileDemoScss();\n } catch (error) {\n console.error(\"Demo SCSS watch compilation error:\", error);\n } finally {\n scssCompiling = false;\n if (scssPending) {\n scssPending = false;\n scssWatcher.emit(\"all\");\n }\n }\n }, 500);\n });\n\n // Set up clean shutdown\n setupWatchModeListeners(watcher, scssWatcher);\n\n return watcher;\n}\n\n/**\n * Build the component using Rollup with the provided options\n * @param {object} options - Build configuration options\n * @param {boolean} [options.dev=false] - Whether to run in development mode\n * @param {boolean} [options.watch] - Whether to run in watch mode (defaults to value of dev)\n * @param {boolean} [options.docs=true] - Whether to generate documentation\n * @returns {Promise<object|void>} - Rollup watcher if in watch mode\n */\nexport async function buildWithRollup(options = {}) {\n try {\n const { watch } = options;\n\n // Clean output directory\n cleanupDist();\n\n // Run production build once or set up watch mode\n // Only use watch mode if explicitly enabled\n if (watch) {\n return await setupWatchMode(options);\n }\n\n return await runProductionBuild(options);\n } catch (error) {\n throw new Error(`Build failed: ${error.message}`);\n }\n}\n\n// Re-export utilities for backward compatibility\nexport { cleanupDist };\n", "import { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { glob } from \"glob\";\nimport ora from \"ora\";\nimport { rollup } from \"rollup\";\nimport * as sass from \"sass\";\nimport { analyzeComponents } from \"#scripts/analyze.js\";\nimport { runDefaultDocsBuild } from \"#scripts/build/defaultDocsBuild.js\";\nimport { getDemoConfig } from \"#scripts/build/configUtils.js\";\nimport { MODULE_DIRS } from \"#scripts/build/paths.js\";\nimport { copyReadmeToDemo } from \"#utils/copyReadmeToDemo.js\";\n\n/**\n * Clean up the dist folder\n * @returns {boolean} Success status\n */\nexport function cleanupDist() {\n const distPath = join(\"./dist\");\n const spinner = ora(\"Cleaning dist folder...\").start();\n\n try {\n rmSync(distPath, { recursive: true, force: true });\n spinner.succeed(\"All clean! Dist folder wiped.\");\n return true;\n } catch (error) {\n spinner.fail(`Oops! Couldn't clean dist/ folder: ${error.message}`);\n console.error(error);\n return false;\n }\n}\n\n/**\n * Run a build step with spinner feedback\n * @param {string} taskName - Name of the task for spinner text\n * @param {Function} taskFn - Async function to execute the task\n * @param {string} successMsg - Message to show on success\n * @param {string} failMsg - Message to show on failure\n * @returns {Promise<any>} - Result of the task function or throws error\n */\nasync function runBuildStep(taskName, taskFn, successMsg, failMsg) {\n const spinner = ora(taskName).start();\n\n try {\n const result = await taskFn();\n spinner.succeed(successMsg);\n return result;\n } catch (error) {\n spinner.fail(failMsg);\n console.error(`Error: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * Builds the TypeScript definition files\n * @param {object} config - Rollup config for d.ts generation\n * @param {object} outputConfig - Output configuration for d.ts files\n */\nexport async function buildTypeDefinitions(config, outputConfig) {\n return runBuildStep(\n \"Creating type definitions...\",\n async () => {\n const bundle = await rollup(config);\n await bundle.write(outputConfig);\n await bundle.close();\n },\n \"Types files built.\",\n \"Darn! Type definitions failed.\",\n );\n}\n\n/**\n * Builds both the main bundle and demo files in one operation\n * @param {object} mainConfig - Rollup config for the main bundle\n * @param {object[]} demoConfigs - One Rollup config per demo entry file\n */\nexport async function buildCombinedBundle(mainConfig, demoConfigs) {\n return runBuildStep(\n `Bundling ${mainConfig.name || \"main\"} and demo...`,\n async () => {\n // Build main bundle\n const mainBundle = await rollup(mainConfig);\n await mainBundle.write(mainConfig.output);\n await mainBundle.close();\n\n // Build demo entries individually so shared imports inline into each\n // <name>.min.js instead of producing a shared <name>2.min.js chunk.\n for (const cfg of demoConfigs) {\n const bundle = await rollup(cfg);\n await bundle.write(cfg.output);\n await bundle.close();\n }\n },\n `Bundles ready! ${mainConfig.name || \"Main\"} and demo built.`,\n \"Bundle hiccup! Build failed.\",\n );\n}\n\n/**\n * Analyzes web components and generates API documentation.\n * @param {object} options - Options containing wcaInput and wcaOutput\n */\nexport async function generateDocs(options) {\n const { wcaInput: sourceFiles, wcaOutput: outFile, skipDocs } = options;\n\n if (skipDocs) {\n const skipSpinner = ora(\"Skipping docs generation...\").start();\n\n setTimeout(() => {\n skipSpinner.succeed(\"Docs generation skipped.\");\n }, 0);\n return;\n }\n\n return runBuildStep(\n \"Analyzing components and making docs...\",\n async () => {\n await analyzeComponents(sourceFiles, outFile);\n await runDefaultDocsBuild(options);\n copyReadmeToDemo();\n },\n \"Docs ready! Looking good.\",\n \"Doc troubles!\",\n );\n}\n\n\n\n/**\n * Sass FileImporter that resolves bare package imports from node_modules\n * and redirects hoisted dependencies. Returns file: URLs so that\n * within-package relative imports resolve natively on disk. When a\n * relative import fails (e.g. ./../../node_modules/@pkg/foo pointing at\n * a hoisted location that doesn't exist), Sass falls back to findFileUrl,\n * where we redirect to the actual hoisted location.\n */\nfunction createNodeModulesImporter() {\n const cwd = process.cwd();\n\n function tryResolve(filePath) {\n const candidates = [\n filePath,\n `${filePath}.scss`,\n `${filePath}.css`,\n join(dirname(filePath), `_${basename(filePath)}.scss`),\n join(filePath, \"_index.scss\"),\n join(filePath, \"index.scss\"),\n ];\n return candidates.find((c) => existsSync(c));\n }\n\n function findInModuleDirs(pkgPath) {\n for (const dir of MODULE_DIRS) {\n const found = tryResolve(resolve(cwd, dir, pkgPath));\n if (found) return found;\n }\n\n // Try resolving via package.json \"exports\" map\n const exportResolved = resolveViaExports(pkgPath);\n if (exportResolved) return exportResolved;\n\n return null;\n }\n\n /**\n * Resolves a bare specifier using the package.json \"exports\" field.\n * e.g. \"@scope/pkg/demo-styles\" looks up \"./demo-styles\" in the exports map\n * of @scope/pkg/package.json and resolves the mapped path.\n */\n function resolveViaExports(pkgPath) {\n let pkgName;\n let subpath;\n\n if (pkgPath.startsWith(\"@\")) {\n const parts = pkgPath.split(\"/\");\n if (parts.length < 3) return null;\n pkgName = `${parts[0]}/${parts[1]}`;\n subpath = `./${parts.slice(2).join(\"/\")}`;\n } else {\n const slashIdx = pkgPath.indexOf(\"/\");\n if (slashIdx === -1) return null;\n pkgName = pkgPath.slice(0, slashIdx);\n subpath = `./${pkgPath.slice(slashIdx + 1)}`;\n }\n\n for (const dir of MODULE_DIRS) {\n const pkgJsonPath = resolve(cwd, dir, pkgName, \"package.json\");\n if (!existsSync(pkgJsonPath)) continue;\n\n try {\n const pkgJson = JSON.parse(readFileSync(pkgJsonPath, \"utf-8\"));\n const exports = pkgJson.exports;\n if (!exports || typeof exports !== \"object\") continue;\n\n const mapped = exports[subpath];\n if (!mapped) continue;\n\n const target = typeof mapped === \"string\" ? mapped : mapped.default || mapped.import;\n if (!target) continue;\n\n const resolved = tryResolve(resolve(cwd, dir, pkgName, target));\n if (resolved) return resolved;\n } catch {\n continue;\n }\n }\n\n return null;\n }\n\n return {\n findFileUrl(url) {\n // Failed relative import containing a node_modules path that\n // doesn't exist due to hoisting \u2014 redirect to hoisted location\n if (url.includes(\"/node_modules/\")) {\n const lastIdx = url.lastIndexOf(\"/node_modules/\");\n const pkgPath = url.slice(lastIdx + \"/node_modules/\".length);\n const found = findInModuleDirs(pkgPath);\n if (found) return pathToFileURL(found);\n }\n\n // Bare package import (e.g. @aurodesignsystem/webcorestylesheets/...)\n if (!url.startsWith(\".\") && !url.startsWith(\"/\") && !url.startsWith(\"file:\")) {\n const found = findInModuleDirs(url);\n if (found) return pathToFileURL(found);\n }\n\n return null;\n },\n };\n}\n\n/**\n * Compiles all SCSS files in the demo directory to CSS.\n * @param {string} [demoDir=\"./demo\"] - Path to the demo directory\n */\nexport async function compileDemoScss(demoDir = \"./demo\") {\n return runBuildStep(\n \"Compiling demo SCSS...\",\n async () => {\n const scssFiles = glob.sync(join(demoDir, \"**/*.scss\"));\n const importer = createNodeModulesImporter();\n const cwd = process.cwd();\n const loadPaths = MODULE_DIRS.map((dir) => resolve(cwd, dir));\n\n for (const scssFile of scssFiles) {\n const result = sass.compile(scssFile, {\n importers: [importer],\n loadPaths,\n silenceDeprecations: [\"import\"],\n style: \"compressed\",\n });\n\n const cssFile = scssFile.replace(/\\.scss$/, \".min.css\");\n writeFileSync(cssFile, result.css);\n }\n\n return scssFiles.length;\n },\n \"Demo SCSS compiled.\",\n \"SCSS compilation failed.\",\n );\n}\n\n/**\n * Bundles demo JS files to minified ESM output.\n * @param {object} [options={}] - Options passed to getDemoConfig\n */\nexport async function buildDemoBundle(options = {}) {\n const { configs } = getDemoConfig(options);\n\n return runBuildStep(\n \"Bundling demo JS...\",\n async () => {\n for (const cfg of configs) {\n const bundle = await rollup(cfg);\n await bundle.write(cfg.output);\n await bundle.close();\n }\n },\n \"Demo JS bundled.\",\n \"Demo JS bundling failed.\",\n );\n}\n", "import ora from \"ora\";\nimport { shell } from \"#utils/shell.js\";\nimport Docs from \"./docs-generator.ts\";\nimport { configPath } from \"#utils/pathUtils.js\";\nimport { copyReadmeToDemo } from \"#utils/copyReadmeToDemo.js\";\nimport { registerWatcher, installShutdownHandler } from \"#utils/shutdown.js\";\nimport { buildDemoBundle, compileDemoScss } from \"../build/bundleHandlers.js\";\nimport { runDefaultDocsBuild } from \"../build/defaultDocsBuild.js\";\nimport { startDevelopmentServer } from \"../build/devServerUtils.js\";\n\nexport async function cem() {\n const cemSpinner = ora(\"Generating Custom Elements Manifest...\").start();\n\n try {\n // The shell function returns a promise that resolves when the command completes\n await shell(\n `npx --package=@custom-elements-manifest/analyzer -y -- cem analyze --config '${configPath(\"custom-elements-manifest.config.mjs\")}'`,\n );\n cemSpinner.succeed(\"Custom Elements Manifest generated successfully!\");\n } catch (error) {\n // Check if the error is just the plugin issue but the manifest was still created\n const errorMessage = error instanceof Error ? error.message : String(error);\n cemSpinner.warn('CEM analyzer completed with warnings: ' + errorMessage);\n }\n}\n\nexport async function api() {\n const docsSpinner = ora(\"Generating API md file...\").start();\n\n try {\n await Docs.generate();\n docsSpinner.succeed(\"API md file generated successfully!\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n docsSpinner.fail(\"Failed to generate API md file: \" + errorMessage);\n throw error;\n }\n}\n\nexport async function docs(options = {}) {\n const docsSpinner = ora(\"Compiling documentation...\").start();\n\n try {\n await runDefaultDocsBuild(options);\n docsSpinner.succeed(\"Documentation compiled successfully!\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n docsSpinner.fail(\"Failed to compile MD documentation: \" + errorMessage);\n throw error;\n }\n\n copyReadmeToDemo();\n await compileDemoScss();\n await buildDemoBundle(options);\n}\n\nexport async function serve(options = {}) {\n await startDevelopmentServer(options);\n}\n\n/**\n * Watches doc and src files and rebuilds on changes.\n */\nexport async function watchDocs(options = {}) {\n const chokidar = await import(\"chokidar\");\n\n const watchPaths = [\n \"./src/**/*\",\n \"./docs/**/*\",\n \"./docTemplates/**/*\",\n \"./apiExamples/**/*\",\n \"./demo/**/*.scss\",\n ];\n\n const ignored = [\n // Output files that should never trigger a rebuild\n \"**/demo/*.min.js\",\n \"**/demo/*.min.css\",\n \"**/demo/*.md\",\n \"**/demo/readme.md\",\n \"**/docs/api.md\",\n \"**/custom-elements.json\",\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/.git/**\",\n ];\n\n const watcher = chokidar.watch(watchPaths, {\n ignoreInitial: true,\n ignored,\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n });\n\n const watchSpinner = ora(\"Waiting for changes...\");\n watchSpinner.spinner = \"bouncingBar\";\n watchSpinner.color = \"green\";\n watchSpinner.start();\n\n let rebuildTimer: ReturnType<typeof setTimeout> | null = null;\n let rebuilding = false;\n let pendingRebuild = false;\n\n async function rebuild(triggeredBy: string) {\n if (rebuilding) {\n pendingRebuild = true;\n return;\n }\n\n rebuilding = true;\n\n // Pause watcher during rebuild to avoid feedback loops\n watcher.unwatch(watchPaths);\n\n const spinner = ora(`Change detected: ${triggeredBy}`).start();\n try {\n await runDefaultDocsBuild(options);\n copyReadmeToDemo();\n await compileDemoScss();\n await buildDemoBundle(options);\n spinner.succeed(\"Docs rebuilt!\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n spinner.fail(\"Rebuild failed: \" + errorMessage);\n } finally {\n // Re-enable watcher after a short delay for file writes to settle\n setTimeout(() => {\n watcher.add(watchPaths);\n rebuilding = false;\n\n if (pendingRebuild) {\n pendingRebuild = false;\n rebuild(\"queued changes\");\n }\n }, 1000);\n }\n }\n\n watcher.on(\"all\", (_event: string, filePath: string) => {\n if (rebuilding) return;\n\n if (rebuildTimer) {\n clearTimeout(rebuildTimer);\n }\n\n rebuildTimer = setTimeout(() => {\n rebuild(filePath);\n }, 1000);\n });\n\n // Register watcher for clean shutdown\n registerWatcher(watcher);\n installShutdownHandler();\n}\n", "import { spawn } from \"node:child_process\";\nimport ora from \"ora\";\n\nconst shell = (command, _args) => {\n const commandString = `${command} ${_args ? _args.join(\" \") : \"\"}`;\n\n // Initialize the spinner but don't start it - we'll just use it for completion status\n const spinner = ora();\n\n // Parse command string if no args are provided\n let finalCommand = command;\n let finalArgs = _args || [];\n\n if (!_args && typeof command === \"string\") {\n const parts = command.split(\" \");\n finalCommand = parts[0];\n finalArgs = parts.slice(1);\n }\n\n // Simple check for watch mode - if the command contains --watch or -w flags\n const isWatchMode =\n commandString.includes(\"--watch\") || commandString.includes(\" -w\");\n\n // Use different stdio configurations based on watch mode\n const stdio = isWatchMode\n ? \"inherit\" // Full TTY support for watch mode\n : [\"inherit\", \"pipe\", \"pipe\"]; // Capture output but allow input for normal mode\n\n const child = spawn(finalCommand, finalArgs, {\n stdio,\n shell: true,\n });\n\n // Only set up output capture if we're not in watch mode (stdio isn't 'inherit')\n if (!isWatchMode) {\n // Store command output to display after completion\n const commandOutput = [];\n\n child.stdout?.on(\"data\", (data) => {\n // Convert buffer to string\n const output = data.toString();\n\n // Store full output\n commandOutput.push(output);\n\n // Output directly to console\n process.stdout.write(output);\n });\n\n child.stderr?.on(\"data\", (data) => {\n const output = data.toString();\n commandOutput.push(output);\n process.stderr.write(output);\n });\n }\n\n // Set up a promise to track command completion\n return new Promise((resolve, reject) => {\n child.on(\"close\", (code) => {\n if (code !== 0) {\n // In watch mode, don't treat exit codes as errors - these are typically user terminations\n if (isWatchMode) {\n spinner.info(`Watch mode terminated with code ${code}`);\n resolve(); // Resolve without an error for watch mode commands\n } else {\n spinner.fail(`${commandString} failed (code ${code})`);\n reject(new Error(`Command failed with exit code ${code}`));\n }\n } else {\n spinner.succeed(`${commandString} completed successfully`);\n resolve();\n }\n });\n });\n};\n\nexport { shell };\n", "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { markdownTable } from \"markdown-table\";\nimport type {\n Package,\n Module,\n Declaration,\n CustomElementDeclaration,\n ClassMember,\n Parameter,\n Attribute\n} from 'custom-elements-manifest';\n\ninterface GenerateOptions {\n outDir?: string;\n outFile?: string;\n manifestPath?: string;\n}\n\ninterface MergedTableData {\n name: string;\n properties: string;\n attributes: string;\n modifiers: string;\n type: string;\n default: string;\n description: string;\n}\n\nexport default class Docs {\n private static manifest: Package = { schemaVersion: \"1.0.0\", readme: \"\", modules: [] };\n\n /**\n * Generate markdown documentation for all components\n */\n static generate(options: GenerateOptions = {}): void {\n const {\n outDir = \"./docs\",\n outFile = \"api.md\",\n manifestPath = \"./custom-elements.json\",\n } = options;\n\n const { getElements, renderAllElements } = Docs;\n\n // Use provided manifest or fallback to default\n if (manifestPath) {\n try {\n const manifestContent = fs.readFileSync(manifestPath, \"utf8\");\n Docs.manifest = JSON.parse(manifestContent) as Package;\n } catch (error) {\n console.error(`Error reading manifest file at ${manifestPath}:`, error);\n throw error;\n }\n }\n\n const elements = getElements();\n\n // Create docs directory if it doesn't exist\n const docsDir = outDir;\n if (!fs.existsSync(docsDir)) {\n fs.mkdirSync(docsDir, { recursive: true });\n }\n\n // Generate combined API documentation\n const apiMarkdown = renderAllElements(elements);\n const apiFilename = path.join(docsDir, outFile);\n fs.writeFileSync(apiFilename, apiMarkdown);\n console.log(`Generated combined API documentation at ${apiFilename}`);\n }\n\n /**\n * Extract custom elements from the manifest\n */\n static getElements(): CustomElementDeclaration[] {\n\n // if wca exists, use only wca modules\n const wcaModules = Docs.manifest.modules.filter(Docs.isWcaModule);\n\n return Docs.manifest.modules.reduce(\n (els: CustomElementDeclaration[], module: Module) =>\n els.concat(\n module.declarations?.filter(\n (dec: Declaration): dec is CustomElementDeclaration => \n 'customElement' in dec && dec.customElement === true && 'tagName' in dec && \n (wcaModules.length > 0 ? Docs.isWcaModule(module) : true),\n ) ?? [],\n ),\n [],\n );\n }\n\n /**\n * Check if a module has a path that matches the WCA pattern\n */\n static isWcaModule(module: Module): boolean {\n // Check if the module path matches \"scripts/wca/auro-*.js\"\n const { path } = module;\n\n if (!path) {\n return false;\n }\n \n // Match the pattern: starts with \"scripts/wca/auro-\" and ends with \".js\"\n return path.startsWith('scripts/wca/auro-') && path.endsWith('.js');\n }\n\n /**\n * Render all elements into a single markdown document\n */\n static renderAllElements(elements: CustomElementDeclaration[]): string {\n return `${elements\n .sort((a, b) => (a.tagName || '').localeCompare(b.tagName || ''))\n .map((element: CustomElementDeclaration) => Docs.renderElement(element, true))\n .join(\"\\n\\n\")}`;\n }\n\n /**\n * Render a single element as markdown\n */\n static renderElement(element: CustomElementDeclaration, includeTitle = true): string {\n const sections = [];\n const { renderTable, renderPropertiesAttributesTable, renderParameters, getType } = Docs;\n \n // Title and description\n sections.push(includeTitle ? `# ${element.tagName}` : '');\n\n if (element.description) {\n sections.push(element.description);\n }\n \n // Properties & Attributes table\n const propertiesTable = renderPropertiesAttributesTable(element);\n if (propertiesTable) {\n sections.push(propertiesTable.trim());\n }\n \n // Methods table\n const methodsTable = renderTable(\n \"Methods\",\n [\"name\", \"parameters\", \"return\", \"description\"],\n (element.members || [])\n .filter(\n (m: ClassMember) =>\n m.kind === \"method\" && ('privacy' in m ? m.privacy !== \"private\" : true) && m.name[0] !== \"_\",\n )\n .map((m: ClassMember) => ({\n ...m,\n parameters: renderParameters('parameters' in m ? m.parameters as Parameter[] : undefined),\n return: 'return' in m && m.return ? getType(m.return) : \"\",\n })),\n );\n if (methodsTable) {\n sections.push(methodsTable.trim());\n }\n \n // Events table\n const eventsTable = renderTable(\n \"Events\",\n [\"name\", \"description\"],\n element.events as unknown as Record<string, unknown>[],\n );\n if (eventsTable) {\n sections.push(eventsTable.trim());\n }\n \n // Slots table\n const slotsTable = renderTable(\n \"Slots\",\n [[\"name\", \"(default)\"], \"description\"],\n element.slots as unknown as Record<string, unknown>[],\n );\n if (slotsTable) {\n sections.push(slotsTable.trim());\n }\n \n // CSS Shadow Parts table\n const cssPartsTable = renderTable(\n \"CSS Shadow Parts\",\n [\"name\", \"description\"],\n element.cssParts as unknown as Record<string, unknown>[],\n );\n if (cssPartsTable) {\n sections.push(cssPartsTable.trim());\n }\n \n // CSS Custom Properties table\n const cssPropertiesTable = renderTable(\n \"CSS Custom Properties\",\n [\"name\", \"description\"],\n element.cssProperties as unknown as Record<string, unknown>[],\n );\n if (cssPropertiesTable) {\n sections.push(cssPropertiesTable.trim());\n }\n \n return sections.join('\\n\\n');\n }\n\n /**\n * Render combined properties and attributes table\n */\n static renderPropertiesAttributesTable(element: CustomElementDeclaration): string {\n \n const { getType, escapeMarkdown } = Docs;\n \n const properties = element.members?.filter(\n (m: ClassMember) => \n m.kind === \"field\" && \n ('privacy' in m ? m.privacy !== \"private\" : true) && \n m.name[0] !== \"_\"\n ) || [];\n const attributes = element.attributes || [];\n\n // Create a merged dataset\n const mergedData: MergedTableData[] = [];\n const processedNames = new Set<string>();\n\n // Process properties first (only include those with descriptions)\n properties.forEach((prop: ClassMember) => {\n if (prop.description?.trim()) {\n const propType = getType(prop) || \"\";\n const returnType = 'return' in prop && prop.return ? getType(prop.return) : \"\";\n const displayType = returnType || propType;\n \n mergedData.push({\n name: prop.name,\n properties: prop.name,\n attributes: ('attribute' in prop ? prop.attribute as string : '') || \"\",\n modifiers: ('readonly' in prop && prop.readonly ? 'readonly' : ''),\n type: displayType,\n default: ('default' in prop ? prop.default as string : '') || \"\",\n description: prop.description || \"\",\n });\n }\n processedNames.add(prop.name);\n if ('attribute' in prop && prop.attribute) {\n processedNames.add(prop.attribute as string);\n }\n });\n\n // Process attributes that don't have corresponding properties (only include those with descriptions)\n attributes.forEach((attr: Attribute) => {\n if (!processedNames.has(attr.name) && attr.description?.trim()) {\n mergedData.push({\n name: attr.name,\n properties: \"\",\n attributes: attr.name,\n modifiers: \"\",\n type: getType(attr) || \"\",\n default: attr.default || \"\",\n description: attr.description || \"\",\n });\n }\n });\n\n if (mergedData.length === 0) {\n return \"\";\n }\n\n const headers = [\"Properties\", \"Attributes\", \"Modifiers\", \"Type\", \"Default\", \"Description\"];\n const rows = mergedData.map((item: MergedTableData) => {\n const defaultRaw = item.default || \"\";\n const defaultTrimmed = defaultRaw.trim();\n // Remove surrounding single quotes from default values like 'foo'\n const defaultSanitized = defaultTrimmed.replace(/^'([^']+)'$/, \"$1\");\n // Remove surrounding double quotes from default values like \"foo\"\n const defaultDoubleSanitized = defaultSanitized.replace(/^\"([^\"]+)\"$/, \"$1\");\n const defaultWrapped = defaultDoubleSanitized\n ? (defaultDoubleSanitized.startsWith('`') && defaultDoubleSanitized.endsWith('`')\n ? defaultDoubleSanitized\n : `\\`${defaultDoubleSanitized}\\``)\n : \"\";\n return [\n escapeMarkdown(item.properties),\n escapeMarkdown(item.attributes),\n escapeMarkdown(item.modifiers),\n escapeMarkdown(item.type),\n escapeMarkdown(defaultWrapped),\n escapeMarkdown(item.description),\n ];\n });\n\n const table = markdownTable([headers, ...rows]);\n\n return `### Properties & Attributes\n\n${table}\n`;\n }\n\n /**\n * Render method parameters as a formatted string\n */\n static renderParameters(parameters?: Parameter[]): string {\n\n const { escapeMarkdown, getType } = Docs;\n\n if (!parameters || parameters.length === 0) {\n return \"None\";\n }\n\n return parameters\n .map(\n (param: Parameter) => {\n const paramType = getType(param) || \"any\";\n const description = param.description ? ` - ${param.description}` : \"\";\n return `\\`${param.name}\\` (${escapeMarkdown(paramType)})${escapeMarkdown(description)}`;\n }\n )\n .join(\"<br>\");\n }\n\n /**\n * Renders a markdown table of data, plucking the given properties from each item in `data`.\n */\n static renderTable(\n name: string, \n properties: (string | string[])[], \n data?: Array<Record<string, unknown>>\n ): string {\n\n const { escapeMarkdown, get, capitalize } = Docs;\n\n if (data === undefined || data.length === 0) {\n return \"\";\n }\n\n // Filter out items without descriptions\n const filteredData = data.filter((item: Record<string, unknown>) => {\n const { description } = item;\n return typeof description === 'string' && description.trim();\n });\n\n if (filteredData.length === 0) {\n return \"\";\n }\n\n const headers = properties\n .map((p: string | string[]) => capitalize((Array.isArray(p) ? p[0] : p).split(\".\")[0]));\n\n const rows = filteredData\n .map((item: Record<string, unknown>) =>\n properties\n .map((p: string | string[]) => {\n const value = get(item, p);\n // Handle multiline content and escape characters for markdown\n return escapeMarkdown(String(value || \"\"));\n })\n );\n\n const table = markdownTable([headers, ...rows]);\n\n return `### ${name}\n\n${table}\n`;\n }\n\n /**\n * Escape markdown special characters for table content\n */\n static escapeMarkdown(text: string): string {\n return text\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\n/g, \"<br>\")\n .replace(/\\|/g, \"\\\\|\");\n }\n\n /**\n * Extract and format type information from a property or attribute according to custom-elements-manifest schema\n */\n // biome-ignore lint/suspicious/noExplicitAny: utility method needs to work with any object structure\n static getType(obj: any): string {\n if (!obj || !obj.type) {\n return \"\";\n }\n\n const { type } = obj;\n\n // Utility to normalize type text: fix union spacing and replace single quotes with backticks\n const normalizeType = (text: string): string => {\n return text\n // Normalize union separators to have spaces around |\n .replace(/\\s*\\|\\s*/g, ' | ')\n // Replace any single-quoted type segments with backticks\n .replace(/'([^']+)'/g, '`$1`');\n };\n\n // Handle simple string type\n if (typeof type === 'string') {\n return normalizeType(type);\n }\n\n // Handle type with text property\n if (type.text) {\n return normalizeType(type.text);\n }\n\n // Handle union types or arrays of types\n if (Array.isArray(type)) {\n // biome-ignore lint/suspicious/noExplicitAny: handling dynamic type structures from manifest\n return type.map((t: any) => {\n if (typeof t === 'string') return t;\n if (t.text) return t.text;\n if (t.name) return t.name;\n return String(t);\n }).join(' \\\\| ');\n }\n\n // Handle complex type objects\n if (type.name) {\n return normalizeType(type.name);\n }\n\n // Handle references\n if (type.references && Array.isArray(type.references)) {\n // biome-ignore lint/suspicious/noExplicitAny: handling dynamic reference structures from manifest\n return type.references.map((ref: any) => ref.name || String(ref)).join(' \\\\| ');\n }\n\n // Fallback to string representation\n const result = String(type);\n return normalizeType(result);\n }\n\n /**\n * Reads a (possibly deep) path off of an object.\n */\n // biome-ignore lint/suspicious/noExplicitAny: utility method needs to work with any object structure\n static get(obj: any, pathInput: string | string[]): string {\n let fallback = \"\";\n let path: string = pathInput as string;\n if (Array.isArray(pathInput)) {\n [path, fallback] = pathInput;\n }\n const parts = path.split(\".\");\n // biome-ignore lint/suspicious/noExplicitAny: utility method needs to work with any object structure\n let current: any = obj;\n while (current && parts.length) {\n current = current[parts.shift() as string];\n }\n return current == null || current === \"\" ? fallback : String(current);\n }\n\n /**\n * Capitalize the first letter of a string and add spaces before capital letters in camelCase\n */\n static capitalize(s: string): string {\n \n // Add spaces before capital letters and capitalize first letter\n return s\n .replace(/([A-Z])/g, ' $1')\n .replace(/^./, str => str.toUpperCase())\n .trim();\n }\n}\n", "import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nexport function getAuroHomeDir() {\n const homeDir = os.homedir() || process.env.HOME || process.env.USERPROFILE;\n\n if (!homeDir) {\n throw new Error(\"Unable to determine user home directory\");\n }\n\n return path.join(homeDir, \".auro\");\n}\n\nexport function withHomeDir(...args) {\n return path.join(getAuroHomeDir(), ...args);\n}\n\nexport function fromCliRoot(...relativePath) {\n const cliScript = fs.realpathSync(process.argv[1]);\n const dirname = path.dirname(cliScript);\n\n return path.resolve(dirname, ...relativePath);\n}\n \nexport const configPath = (file) => fromCliRoot(\"configs\",file)\n\nexport const migrationPath = (path) => fromCliRoot(\"migrations\",path)\n", "import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/**\n * Copies the processed README.md from the project root into the demo directory as readme.md.\n */\nexport function copyReadmeToDemo() {\n const cwd = process.cwd();\n const readmeSrc = resolve(cwd, \"README.md\");\n const readmeDest = join(resolve(cwd, \"demo\"), \"readme.md\");\n\n if (!existsSync(readmeSrc)) {\n return;\n }\n\n const demoDir = resolve(cwd, \"demo\");\n if (!existsSync(demoDir)) {\n mkdirSync(demoDir, { recursive: true });\n }\n\n copyFileSync(readmeSrc, readmeDest);\n}\n", "import ora from \"ora\";\n\nconst watchers = [];\n\n/**\n * Register a watcher (rollup or chokidar) for clean shutdown on SIGINT.\n * @param {object} watcher - A watcher with a close() method\n */\nexport function registerWatcher(watcher) {\n watchers.push(watcher);\n}\n\n// Single SIGINT handler for all registered watchers\nlet handlerInstalled = false;\n\nexport function installShutdownHandler() {\n if (handlerInstalled) return;\n handlerInstalled = true;\n\n process.on(\"SIGINT\", () => {\n const closeSpinner = ora(\"Wrapping up...\").start();\n for (const watcher of watchers) {\n watcher.close();\n }\n closeSpinner.succeed(\"All done! See you next time. \u2728\");\n process.exit(0);\n });\n}\n", "import { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport {\n generateReadmeUrl,\n processContentForFile,\n templateFiller,\n} from \"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs\";\nimport fs from \"node:fs\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst PAGE_TEMPLATE_PATH = \"/docs/pages\";\n\n/**\n * Processor config object.\n * @typedef {Object} ProcessorConfig\n * @property {boolean} [overwriteLocalCopies=true] - The release version tag to use instead of master.\n * @property {string} [remoteReadmeVersion=\"master\"] - The release version tag to use instead of master.\n * @property {string} [remoteReadmeUrl] - The release version tag to use instead of master.\n * @property {string} [remoteReadmeVariant=\"\"] - The variant string to use for the README source (like \"_esm\" to make README_esm.md).\n * @property {string} [monorepoName] - The name of the monorepo, used as a template variable.\n * @property {Record<string, unknown>} [extraVars] - Additional template variables to pass to the template filler.\n * @param {ProcessorConfig} config - The configuration for this processor.\n */\nexport const defaultDocsProcessorConfig = {\n overwriteLocalCopies: true,\n remoteReadmeVersion: \"master\",\n // eslint-disable-next-line no-warning-comments\n // TODO: remove this variant when all components are updated to use latest auro-library\n // AND the default README.md is updated to use the new paths\n remoteReadmeVariant: \"_updated_paths\",\n monorepoName: undefined,\n extraVars: {},\n};\n\nfunction pathFromCwd(pathLike) {\n const cwd = process.cwd();\n return `${cwd}/${pathLike}`;\n}\n\n/**\n * Walk up the directory tree from the given start directory to find the monorepo\n * root \u2014 identified as the nearest ancestor (or self) whose package.json has a\n * \"workspaces\" field. Falls back to the start directory if none is found.\n * @param {string} [startDir=process.cwd()] - Directory to start searching from.\n * @returns {string} Absolute path to the monorepo root directory.\n */\nfunction findMonorepoRoot(startDir = process.cwd()) {\n let dir = startDir;\n while (true) {\n const pkgPath = path.join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf8\"));\n if (pkg.workspaces) return dir;\n } catch {\n // malformed package.json \u2014 keep walking up\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return startDir;\n}\n\n/**\n * @param {ProcessorConfig} config - The configuration for this processor.\n * @param {boolean} [skipReadme=false] - Whether to skip README.md processing.\n * @returns {import('../utils/sharedFileProcessorUtils').FileProcessorConfig[]}\n */\nexport async function fileConfigs(config, skipReadme = false) {\n const configs = [];\n\n // ---------- README.md ----------\n // Don't need to check for existence of README.md since it's always created\n if (!skipReadme) {\n const inputConfig = config.localReadmePath\n ? config.localReadmePath\n : {\n remoteUrl:\n config.remoteReadmeUrl ||\n generateReadmeUrl(\n config.remoteReadmeVersion,\n config.remoteReadmeVariant,\n ),\n fileName: pathFromCwd(\"/docTemplates/README.md\"),\n overwrite: config.overwriteLocalCopies,\n };\n\n configs.push({\n identifier: \"README.md\",\n input: inputConfig,\n output: pathFromCwd(\"/README.md\"),\n });\n }\n\n // ---------- index.md ----------\n if (fileExists(\"/docs/partials/index.md\")) {\n configs.push({\n identifier: \"index.md\",\n input: pathFromCwd(\"/docs/partials/index.md\"),\n output: pathFromCwd(\"/demo/index.md\"),\n mdMagicConfig: {\n output: {\n directory: pathFromCwd(\"/demo\"),\n },\n },\n });\n }\n\n // ---------- api.md ----------\n if (fileExists(\"/docs/partials/api.md\")) {\n configs.push({\n identifier: \"api.md\",\n input: pathFromCwd(\"/docs/partials/api.md\"),\n output: pathFromCwd(\"/demo/api.md\"),\n preProcessors: [templateFiller.formatApiTable],\n });\n }\n\n // ---------- Page Templates ----------\n const pageTemplateFullPath = pathFromCwd(PAGE_TEMPLATE_PATH);\n\n if (fs.existsSync(pageTemplateFullPath)) {\n const pageFiles = await fs.promises.readdir(pageTemplateFullPath);\n\n const pageObjects = pageFiles.map((file) => ({\n identifier: file,\n input: path.join(pageTemplateFullPath, file),\n output: pathFromCwd(`/demo/${file}`),\n }));\n\n configs.push(...pageObjects);\n }\n\n return configs;\n}\n\n/**\n *\n * @param {ProcessorConfig} config - The configuration for this processor.\n * @param {boolean} [skipReadme=false] - Whether to skip README.md processing.\n * @return {Promise<void>}\n */\nexport async function processDocFiles(config = defaultDocsProcessorConfig, skipReadme = false) {\n // setup\n await templateFiller.extractNames();\n\n const fileConfigsList = await fileConfigs(config, skipReadme);\n\n let monorepoName = config.monorepoName;\n if (!monorepoName) {\n try {\n const rootPkgPath = path.join(findMonorepoRoot(), \"package.json\");\n const pkgJson = JSON.parse(readFileSync(rootPkgPath, \"utf8\"));\n // Strip the npm scope prefix (\"@scope/\") to get the bare package name used in\n // template variables such as {{ monorepoName }} (e.g. \"auro-formkit\").\n monorepoName = pkgJson.name?.replace(/^@[^/]+\\//, '');\n } catch {\n // no root package.json or name field \u2014 leave undefined\n }\n }\n\n const extraVars = {\n ...(monorepoName ? { monorepoName } : {}),\n ...(config.extraVars || {}),\n };\n\n for (const fileConfig of fileConfigsList) {\n try {\n // eslint-disable-next-line no-await-in-loop\n await processContentForFile({ ...fileConfig, extraVars });\n\n // Post-processing for markdown output files\n if (fileConfig.output.endsWith('.md')) {\n await postProcessMarkdownFile(fileConfig.output, extraVars);\n }\n } catch (err) {\n Logger.error(`Error processing ${fileConfig.identifier}: ${err.message}`);\n }\n }\n}\n\n/**\n * Post-process a markdown file to resolve second-pass AURO-GENERATED-CONTENT tags,\n * convert markdown code fences to HTML, and normalize whitespace for marked.js.\n * @param {string} outputPath - The absolute path to the output markdown file.\n * @param {Record<string, unknown>} [extraVars={}] - Additional template variables for second-pass replacement.\n */\nasync function postProcessMarkdownFile(outputPath, extraVars = {}) {\n const outputDir = path.dirname(outputPath);\n\n // --- Second-pass: resolve empty AURO-GENERATED-CONTENT tags ---\n // These tags have empty content (START immediately followed by END) because\n // markdown-magic only runs one pass and doesn't process tags introduced\n // during that same pass.\n let outputContents = await fs.promises.readFile(outputPath, 'utf8');\n const emptyTagPattern = /^[ \\t]*<!-- AURO-GENERATED-CONTENT:START \\((FILE|CODE):src=([^)]+)\\) -->\\n[ \\t]*<!-- AURO-GENERATED-CONTENT:END -->/gm;\n let match;\n let modified = false;\n\n // Fallback directory: paths in shared partials are typically written\n // relative to the demo/ output directory. When the same partial is\n // inlined into a README (output at the project root), the path\n // won't resolve from that shallower directory. Using the demo dir\n // as a fallback ensures nested imports resolve consistently.\n const demoDir = pathFromCwd('demo');\n\n while ((match = emptyTagPattern.exec(outputContents)) !== null) {\n const [fullMatch, type, srcPath] = match;\n const resolvedPath = path.resolve(outputDir, srcPath);\n const fallbackPath = path.resolve(demoDir, srcPath);\n const actualPath = existsSync(resolvedPath) ? resolvedPath : (existsSync(fallbackPath) ? fallbackPath : null);\n\n if (actualPath) {\n const fileContent = readFileSync(actualPath, 'utf8');\n let replacement;\n\n if (type === 'FILE') {\n replacement = `<!-- AURO-GENERATED-CONTENT:START (FILE:src=${srcPath}) -->\\n<!-- The below content is automatically added from ${srcPath} -->\\n${fileContent.trimEnd()}\\n<!-- AURO-GENERATED-CONTENT:END -->`;\n } else {\n // CODE: wrap in a pre/code HTML block with language classes\n const ext = path.extname(srcPath).slice(1) || 'html';\n const escaped = fileContent.trimEnd()\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n replacement = `<!-- AURO-GENERATED-CONTENT:START (CODE:src=${srcPath}) -->\\n<!-- The below code snippet is automatically added from ${srcPath} -->\\n<pre class=\"language-${ext}\"><code class=\"language-${ext}\">${escaped}\\n</code></pre>\\n<!-- AURO-GENERATED-CONTENT:END -->`;\n }\n\n outputContents = outputContents.replace(fullMatch, replacement);\n // Reset lastIndex so the regex rescans from the start of\n // the replacement \u2014 otherwise consecutive tags are skipped\n // because the string length changed.\n emptyTagPattern.lastIndex = 0;\n modified = true;\n }\n }\n\n if (modified) {\n // Replace template variables (e.g. {{ componentName }}) in content\n // introduced by second-pass inlining \u2014 the first pass only\n // replaces variables in the original file, not in nested partials.\n outputContents = templateFiller.replaceTemplateValues(outputContents, extraVars);\n await fs.promises.writeFile(outputPath, outputContents);\n }\n\n // --- Convert markdown code fences to <pre><code> HTML blocks ---\n // marked.js won't parse fences inside HTML block context, so all\n // fenced code blocks need to be converted to raw HTML for consistent rendering.\n outputContents = await fs.promises.readFile(outputPath, 'utf8');\n const fencePattern = /^[ \\t]*```(\\w*)\\n([\\s\\S]*?)^[ \\t]*```[ \\t]*$/gm;\n const convertedContents = outputContents.replace(fencePattern, (_match, lang, code) => {\n const language = lang || 'html';\n const escaped = code.trimEnd()\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n return `<pre class=\"language-${language}\"><code class=\"language-${language}\">${escaped}\\n</code></pre>`;\n });\n\n if (convertedContents !== outputContents) {\n await fs.promises.writeFile(outputPath, convertedContents);\n }\n\n // --- Whitespace normalization for marked.js compatibility ---\n outputContents = await fs.promises.readFile(outputPath, 'utf8');\n\n // Dedent and fix blank lines inside <pre><code>...</code></pre> blocks\n outputContents = outputContents.replace(\n /(<pre[^>]*><code[^>]*>)([\\s\\S]*?)(<\\/code><\\/pre>)/g,\n (_match, open, content, close) => {\n const lines = content.split('\\n');\n // Find minimum indentation across non-empty lines\n const nonEmpty = lines.filter(l => l.trim().length > 0);\n if (nonEmpty.length === 0) return _match;\n const minIndent = Math.min(...nonEmpty.map(l => {\n const m = l.match(/^[ \\t]*/);\n return m ? m[0].length : 0;\n }));\n // Dedent and replace blank lines with zero-width space\n const processed = lines.map(l => {\n if (l === '') return '\\u200B';\n if (l.trim().length === 0) return '\\u200B';\n return minIndent > 0 ? l.substring(minIndent) : l;\n });\n // Strip trailing empty/zwsp lines\n while (processed.length > 0 && (processed[processed.length - 1] === '\\u200B' || processed[processed.length - 1] === '')) {\n processed.pop();\n }\n return open + processed.join('\\n') + close;\n }\n );\n\n // Strip leading whitespace outside <pre> blocks\n const outputLines = outputContents.split('\\n');\n let insidePre = false;\n\n for (let i = 0; i < outputLines.length; i++) {\n if (/<pre[\\s>]/i.test(outputLines[i])) {\n insidePre = true;\n }\n if (!insidePre) {\n // Only strip leading whitespace before HTML tags \u2014 not before markdown\n // content like indented list items, which rely on indentation for structure.\n outputLines[i] = outputLines[i].replace(/^[ \\t]+(?=<)/, '');\n }\n if (/<\\/pre>/i.test(outputLines[i])) {\n insidePre = false;\n }\n }\n\n await fs.promises.writeFile(outputPath, outputLines.join('\\n'));\n}\n\nexport async function runDefaultDocsBuild(options = {}) {\n const readmeTemplate = options.readmeTemplate;\n const isLocalPath = readmeTemplate && !readmeTemplate.startsWith(\"http\");\n\n await processDocFiles({\n ...defaultDocsProcessorConfig,\n ...(isLocalPath\n ? { localReadmePath: path.resolve(process.cwd(), readmeTemplate) }\n : {\n remoteReadmeUrl:\n readmeTemplate ||\n \"https://raw.githubusercontent.com/AlaskaAirlines/auro-templates/main/templates/default/README.md\",\n }),\n }, options.skipReadme);\n}\n\n/**\n * Check if a file exists.\n * @private\n * @param {String} pathToFile - The path to the file to check if it exists.\n * @returns {Boolean}}\n */\nfunction fileExists(pathToFile) {\n return fs.existsSync(pathFromCwd(pathToFile));\n}\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { builtinModules } from \"node:module\";\nimport { resolve } from \"node:path\";\nimport { startDevServer } from \"@web/dev-server\";\nimport { hmrPlugin } from \"@web/dev-server-hmr\";\nimport * as esbuild from \"esbuild\";\nimport ora from \"ora\";\n\nimport { MODULE_DIRS } from \"#scripts/build/paths.js\";\nconst WDS_OUTSIDE_ROOT_RE = /^\\/__wds-outside-root__\\/(\\d+)\\/(.+)$/;\n\n/**\n * Dev-server plugin that serves CSS files from node_modules when the URL\n * looks like a bare package specifier (e.g. /@scope/pkg/dist/file.css).\n * Handles CSS @import rules that reference node_modules packages.\n */\nfunction nodeModulesCssPlugin() {\n return {\n name: \"node-modules-css\",\n\n serve(context) {\n if (!context.path.endsWith(\".css\")) return;\n if (!context.path.startsWith(\"/@\") && !/^\\/[a-z]/i.test(context.path)) return;\n\n const urlPath = context.path.slice(1);\n const cwd = process.cwd();\n\n for (const dir of MODULE_DIRS) {\n const candidate = resolve(cwd, dir, urlPath);\n if (existsSync(candidate)) {\n return { body: readFileSync(candidate, \"utf-8\"), type: \"css\" };\n }\n }\n },\n };\n}\n\nfunction resolveWdsPath(urlPath, rootDir) {\n const match = urlPath.match(WDS_OUTSIDE_ROOT_RE);\n if (match) {\n return resolve(rootDir, \"../\".repeat(Number.parseInt(match[1], 10)), match[2]);\n }\n return resolve(rootDir, `.${urlPath}`);\n}\n\n/**\n * Dev-server plugin that converts CommonJS node_modules to ESM on-the-fly\n * using esbuild. Needed because nodeResolve serves node_modules files\n * directly to the browser, which can't handle require()/module.exports.\n * @returns {object} - A @web/dev-server plugin\n */\nfunction cjsToEsmPlugin() {\n const CJS_PATTERN = /\\b(require\\s*\\(|module\\.exports\\b|exports\\.\\w)/;\n const cache = new Map();\n let resolvedRootDir;\n\n return {\n name: \"cjs-to-esm\",\n\n async serverStart({ config }) {\n resolvedRootDir = resolve(config.rootDir);\n },\n\n async transform(context) {\n if (!context.path.includes(\"node_modules\")) return;\n if (!context.path.endsWith(\".js\") && !context.path.endsWith(\".cjs\")) return;\n if (typeof context.body !== \"string\") return;\n if (!CJS_PATTERN.test(context.body)) return;\n\n const filePath = resolveWdsPath(context.path, resolvedRootDir);\n\n if (cache.has(filePath)) return cache.get(filePath);\n if (!existsSync(filePath)) return;\n\n try {\n const result = await esbuild.build({\n entryPoints: [filePath],\n bundle: true,\n format: \"esm\",\n platform: \"browser\",\n write: false,\n logLevel: \"silent\",\n external: builtinModules,\n });\n\n const output = { body: result.outputFiles[0].text };\n cache.set(filePath, output);\n return output;\n } catch (error) {\n console.error(`CJS-to-ESM bundling failed for ${context.path}:`, error.message);\n }\n },\n };\n}\n\n/**\n * Default server configuration\n */\nconst DEFAULT_CONFIG = {\n watch: true,\n nodeResolve: true,\n basePath: \"/\",\n rootDir: \"./demo\",\n hmrInclude: [\"src/**/*\", \"demo/**/*\", \"apiExamples/**/*\", \"docs/**/*\"],\n};\n\n/**\n * Starts the development server\n * @param {object} options - Server options\n * @param {boolean} [options.serve] - Whether to start the server\n * @param {number} [options.port] - Port number for the server\n * @param {boolean} [options.open] - Whether to open the browser\n * @param {string} [options.rootDir] - Root directory for serving files\n * @param {string[]} [options.hmrInclude] - Patterns to include for HMR\n * @returns {Promise<object>} - The server instance\n */\nexport async function startDevelopmentServer(options = {}) {\n if (!options.serve) return;\n\n const serverSpinner = ora(\"Firing up dev server...\\n\").start();\n\n try {\n const serverConfig = {\n port: Number(options.port) || undefined,\n open: options.open ? \"/\" : undefined,\n watch: options.watch ?? DEFAULT_CONFIG.watch,\n nodeResolve: options.nodeResolve ?? DEFAULT_CONFIG.nodeResolve,\n basePath: options.basePath ?? DEFAULT_CONFIG.basePath,\n rootDir: options.rootDir ?? DEFAULT_CONFIG.rootDir,\n\n middleware: [\n function rewriteIndex(context, next) {\n if (!context.url.endsWith(\"/\") && !context.url.includes(\".\")) {\n context.url += \".html\";\n }\n return next();\n },\n ],\n\n plugins: [\n nodeModulesCssPlugin(),\n cjsToEsmPlugin(),\n hmrPlugin({\n include: options.hmrInclude ?? DEFAULT_CONFIG.hmrInclude,\n }),\n ],\n };\n\n const server = await startDevServer({\n config: serverConfig,\n readCliArgs: false,\n readFileConfig: false,\n });\n\n serverSpinner.stop();\n return server;\n } catch (error) {\n serverSpinner.fail(\"Server snag! Couldn't start dev server.\");\n console.error(\"Error starting development server:\", error);\n throw new Error(`Development server failed to start: ${error.message}`);\n }\n}\n", "/**\n * Common node_modules directory search paths for resolving packages\n * in monorepo and hoisted dependency structures.\n */\nexport const MODULE_DIRS = [\n \"node_modules\",\n \"../node_modules\",\n \"../../node_modules\",\n \"../../../node_modules\",\n];\n", "\nimport { cem, api } from '#scripts/docs/index.ts';\n\n/**\n * Analyzes web components and generates API documentation.\n */\nexport async function analyzeComponents() {\n \n await cem();\n\n await api();\n\n}", "import { basename, join, resolve } from \"node:path\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport { nodeResolve } from \"@rollup/plugin-node-resolve\";\nimport { glob } from \"glob\";\nimport { litScss } from \"rollup-plugin-scss-lit\";\nimport { MODULE_DIRS } from \"./paths.js\";\nimport { watchGlobs } from \"./plugins.js\";\n\n// Default paths used across configurations\nconst DEFAULTS = {\n moduleDirectories: [\"node_modules\"],\n modulePaths: [\"../../node_modules\", \"../node_modules\", \"node_modules\"],\n watchPatterns: [\"./apiExamples/**/*\", \"./docs/**/*\"],\n};\n\n/**\n * Creates Rollup plugins configuration.\n * @param {string[]} modulePaths - Additional paths to include in litScss.\n * @param {object} options - Additional options for plugins\n * @returns {object[]} - Array of Rollup plugins.\n */\nexport function getPluginsConfig(modulePaths = [], options = {}) {\n const {\n watchPatterns = DEFAULTS.watchPatterns,\n dedupe = [\"lit\", \"lit-element\", \"lit-html\"],\n dev = false,\n } = options;\n\n // Combine default paths with any user-provided paths\n const allModulePaths = [...DEFAULTS.modulePaths, ...modulePaths];\n\n // Absolute fallback paths so nodeResolve finds workspace/hoisted packages\n // when the importer's auto-walkup chain doesn't reach the hoist root\n // (e.g. CLI invoked from a sibling repo, symlinked workspaces).\n const cwd = process.cwd();\n const absoluteModulePaths = MODULE_DIRS.map((dir) => resolve(cwd, dir));\n\n return [\n nodeResolve({\n dedupe,\n preferBuiltins: false,\n moduleDirectories: DEFAULTS.moduleDirectories,\n modulePaths: absoluteModulePaths,\n }),\n commonjs(),\n litScss({\n // Disable CSS minification in dev for readability and faster rebuilds\n minify: dev ? false : { fast: true },\n options: {\n loadPaths: [...allModulePaths, join(process.cwd(), \"src\", \"styles\"), join(process.cwd(), \"src\")],\n },\n }),\n watchGlobs(watchPatterns),\n ];\n}\n\n/**\n * Creates Rollup configuration for the main bundle with output options.\n * @param {object} options - Build options.\n * @returns {object} - Complete Rollup configuration object with input and output.\n */\nexport function getMainBundleConfig(options = {}) {\n const {\n modulePaths = [],\n watch = false,\n input = [\"./src/index.js\", \"./src/registered.js\"],\n outputDir = \"./dist\",\n format = \"esm\",\n // When dev is true, avoid randomized filenames for easier debugging\n dev = false,\n } = options;\n\n return {\n name: \"Main\",\n config: {\n input,\n output: {\n format,\n dir: outputDir,\n // Stable names in dev; in production keep stable names for index/registered\n entryFileNames: (chunk) =>\n dev\n ? \"[name].js\"\n : [\"index\", \"registered\"].includes(chunk.name)\n ? \"[name].js\"\n : \"[name]-[hash].js\",\n chunkFileNames: dev ? \"[name].js\" : \"[name]-[hash].js\",\n assetFileNames: dev ? \"[name][extname]\" : \"[name]-[hash][extname]\",\n },\n external: getExternalConfig(),\n plugins: getPluginsConfig(modulePaths, { dev }),\n watch: getWatcherConfig(watch),\n },\n };\n}\n\n/**\n * Creates Rollup configurations for demo files. Each demo entry is built as\n * its own bundle with `inlineDynamicImports` so shared imports get duplicated\n * into each `<name>.min.js` rather than emitted as a separate `<name>2.min.js`\n * chunk. This guarantees demo HTML only needs to load its matching `.min.js`.\n * @param {object} options - Build options.\n * @returns {{name: string, configs: object[]}} - One Rollup config per demo entry.\n */\nexport function getDemoConfig(options = {}) {\n const {\n modulePaths = [],\n watch = false,\n globPattern = \"./demo/*.js\",\n ignorePattern = [\"./demo/*.min.js\"],\n outputDir = \"./demo\",\n dev = false,\n } = options;\n\n const entries = glob.sync(globPattern, { ignore: ignorePattern });\n const plugins = getPluginsConfig(modulePaths, { dev });\n const watcher = getWatcherConfig(watch);\n\n const configs = entries.map((file) => {\n const name = basename(file, \".js\");\n return {\n input: { [name]: file },\n output: {\n format: \"esm\",\n dir: outputDir,\n entryFileNames: \"[name].min.js\",\n chunkFileNames: \"[name].min.js\",\n assetFileNames: dev ? \"[name][extname]\" : \"[name]-[hash][extname]\",\n inlineDynamicImports: true,\n },\n plugins,\n // Fail the build if any import can't be resolved instead of letting\n // Rollup silently externalize it \u2014 a bare specifier in a demo .min.js\n // breaks at runtime in the browser. Most common cause: a workspace\n // dep wasn't built yet (fix the build order, e.g. turbo `^build`).\n onwarn(warning, defaultHandler) {\n if (warning.code === \"UNRESOLVED_IMPORT\") {\n throw new Error(\n `Unresolved import \"${warning.exporter ?? warning.source}\" in ${warning.id ?? file}. ` +\n \"Make sure workspace dependencies are built before bundling demos.\",\n );\n }\n defaultHandler(warning);\n },\n watch: watcher,\n };\n });\n\n return { name: \"Demo\", configs };\n}\n\n/**\n * Creates Rollup configuration for watch mode.\n * @param {boolean|object} watchOptions - Whether to enable watch mode or watch options\n * @returns {object|false} - Watch configuration for Rollup or false if disabled\n */\nexport function getWatcherConfig(watchOptions) {\n // Return false if watch mode is disabled\n if (!watchOptions) {\n return false;\n }\n\n // Allow passing a configuration object or use defaults\n const options = typeof watchOptions === \"object\" ? watchOptions : {};\n\n return {\n clearScreen: options.clearScreen ?? true,\n buildDelay: options.buildDelay ?? 500,\n chokidar: {\n ignoreInitial: true,\n // Ignore common output files that cause feedback loops\n ignored: options.ignored ?? [\n \"**/dist/**/*.d.ts\",\n \"**/custom-elements.json\",\n \"**/demo/*.md\",\n \"**/demo/**/*.min.js\",\n \"**/demo/**/*.min.css\",\n \"**/docs/api.md\",\n \"**/node_modules/**\",\n \"**/.git/**\",\n ],\n // Reduce watcher's sensitivity to prevent loops\n awaitWriteFinish: options.awaitWriteFinish ?? {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n },\n include: options.include ?? [\n \"./src/**/*.scss\",\n \"./src/**/*.js\",\n \"./src/**/*.ts\",\n \"./demo/**/*.js\",\n \"./apiExamples/**/*\",\n \"./docs/**/*.md\",\n ],\n exclude: options.exclude ?? [\"./dist/**/*\", \"./node_modules/**/*\"],\n };\n}\n\n/**\n * Creates external configuration for Rollup.\n * @param {string[]} additional - Additional external patterns\n * @returns {(string|RegExp)[]} - Array of external dependencies.\n */\nexport function getExternalConfig(additional = []) {\n const defaults = [\n // externalize all lit dependencies\n /node_modules\\/lit/,\n /node_modules\\/lit-element/,\n /node_modules\\/lit-html/,\n /node_modules\\/@lit/,\n ];\n\n return [...defaults, ...additional];\n}\n", "import path from \"node:path\";\nimport { glob } from \"glob\";\n\n/**\n * Creates a plugin that watches file globs and adds them to Rollup's watch list.\n * @param {string|string[]} globs - Glob pattern(s) to watch\n * @returns {object} - Rollup plugin\n */\nexport function watchGlobs(globs) {\n return {\n name: \"watch-globs\",\n buildStart() {\n const items = Array.isArray(globs) ? globs : [globs];\n\n for (const item of items) {\n try {\n for (const filename of glob.sync(path.resolve(item))) {\n this.addWatchFile(filename);\n }\n } catch (error) {\n this.error(`Error watching glob pattern \"${item}\": ${error.message}`);\n }\n }\n },\n };\n}\n", "import path from \"node:path\";\nimport ora from \"ora\";\nimport { rollup } from \"rollup\";\nimport { analyzeComponents } from \"#scripts/analyze.js\";\nimport { registerWatcher, installShutdownHandler } from \"#utils/shutdown.js\";\nimport { compileDemoScss, generateDocs } from \"./bundleHandlers.js\";\n\n// Track if any build is in progress to prevent overlapping operations\nlet buildInProgress = false;\n\n// Track build states and times in a single object for cleaner management\nconst builds = {\n analyze: { active: false, lastTime: 0 },\n docs: { active: false, lastTime: 0 },\n scss: { active: false, lastTime: 0 },\n};\n\n// Minimum time between builds of the same type (in ms)\nconst MIN_BUILD_INTERVAL = 5000;\n\n// Track source paths of files that triggered a watch event\nconst sourceEventPaths = new Set();\n\n// Known output files that should never trigger a rebuild\nconst OUTPUT_PATHS = [\n \"/dist/index.d.ts\",\n \"/custom-elements.json\",\n \"/demo/api.md\",\n \"/docs/api.md\",\n \"/demo/index.min.js\",\n];\n\n// Path matching checks - handle any non-string input safely\nfunction isOutputFile(filePath) {\n if (!filePath || typeof filePath !== \"string\") return false;\n\n try {\n const normalizedPath = path.normalize(filePath);\n\n // Check if it's in our known output paths\n return (\n OUTPUT_PATHS.some((outputPath) => normalizedPath.endsWith(outputPath)) ||\n normalizedPath.includes(\"/dist/\") ||\n normalizedPath.endsWith(\".min.js\") ||\n normalizedPath.endsWith(\".min.css\") ||\n normalizedPath.endsWith(\".d.ts\")\n );\n } catch (error) {\n console.error(`Error checking path (${typeof filePath}):`, error.message);\n return false; // If any error occurs, assume it's not an output file\n }\n}\n\n/**\n * Runs a build task with proper tracking of state\n * @param {string} taskName - Type of task (analyze, docs)\n * @param {Function} taskFn - The actual task function to run\n * @returns {Promise<boolean>} - Success status\n */\nasync function runBuildTask(taskName, taskFn) {\n const task = builds[taskName];\n\n // Skip if build is active or within throttle time\n if (task.active || Date.now() - task.lastTime < MIN_BUILD_INTERVAL) {\n return false;\n }\n\n try {\n task.active = true;\n task.lastTime = Date.now();\n return await taskFn();\n } catch (error) {\n console.error(`Error in ${taskName} task:`, error);\n return false;\n } finally {\n task.active = false;\n }\n}\n\n/**\n * Handles the watcher events.\n * @param {object} watcher - Rollup watcher object.\n * @param {object} options - Build options.\n * @param {Function} [onInitialBuildComplete] - Callback to run after initial build completes.\n */\nexport async function handleWatcherEvents(\n watcher,\n options,\n onInitialBuildComplete,\n) {\n // Track if this is the first build\n let isInitialBuild = true;\n // biome-ignore lint/style/useConst: This is an object that is mutated.\n let buildTasksResults = {analyze: false, docs: false, scss: false };\n let scheduledTasksTimer = null;\n let bundleSpinner;\n\n // Create a spinner for watch mode\n const watchSpinner = ora(\"Activating watch mode...\").start();\n\n // The actual task functions\n const buildTasks = {\n // Function to analyze components\n analyze: async () => {\n const { wcaInput: sourceFiles, wcaOutput: outFile, skipDocs } = options;\n if (skipDocs) {\n const skipSpinner = ora(\"Skipping component analysis...\").start();\n setTimeout(() => {\n skipSpinner.succeed(\"Component analysis skipped.\");\n }, 0);\n return true;\n }\n\n const analyzeSpinner = ora(\n \"Detective work: analyzing components...\",\n ).start();\n try {\n await analyzeComponents(sourceFiles, outFile);\n analyzeSpinner.succeed(\"Component analysis complete! API generated.\");\n return true;\n } catch (error) {\n analyzeSpinner.fail(\"Analysis hiccup! Something went wrong.\");\n console.error(\"Component analysis error:\", error);\n return false;\n }\n },\n\n // Function to rebuild documentation\n docs: async () => {\n // Skip if main bundle is still building\n if (buildInProgress) {\n return false;\n }\n\n // Check if docs generation is skipped\n if (options.skipDocs) {\n const skipSpinner = ora(\"Skipping docs generation...\").start();\n setTimeout(() => {\n skipSpinner.succeed(\"Docs generation skipped.\");\n }, 0);\n return true;\n }\n\n const docsSpinner = ora(\"Refreshing docs...\").start();\n try {\n await generateDocs(options);\n docsSpinner.succeed(\"Documentation refreshed!\");\n return true;\n } catch (error) {\n docsSpinner.fail(\"Docs stumble! Couldn't refresh.\");\n console.error(\"Documentation rebuild error:\", error);\n }\n },\n\n // Function to compile demo SCSS\n scss: async () => {\n if (buildInProgress) {\n return false;\n }\n\n try {\n await compileDemoScss();\n return true;\n } catch (error) {\n console.error(\"Demo SCSS compilation error:\", error);\n return false;\n }\n },\n };\n\n // Check if all initial build tasks completed successfully\n const checkInitialBuildComplete = () => {\n if (\n isInitialBuild &&\n buildTasksResults.analyze &&\n buildTasksResults.docs &&\n buildTasksResults.scss &&\n typeof onInitialBuildComplete === \"function\"\n ) {\n isInitialBuild = false;\n onInitialBuildComplete();\n }\n };\n\n // Schedule the post-bundle tasks with proper sequencing\n function schedulePostBundleTasks(delay = 1000) {\n if (scheduledTasksTimer) {\n clearTimeout(scheduledTasksTimer);\n }\n\n scheduledTasksTimer = setTimeout(async () => {\n // Run tasks with delays between them to avoid race conditions\n\n setTimeout(async () => {\n buildTasksResults.analyze = await runBuildTask(\n \"analyze\",\n buildTasks.analyze,\n );\n\n setTimeout(async () => {\n buildTasksResults.docs = await runBuildTask(\"docs\", buildTasks.docs);\n\n setTimeout(async () => {\n buildTasksResults.scss = await runBuildTask(\"scss\", buildTasks.scss);\n checkInitialBuildComplete();\n }, 500);\n }, 1000);\n }, 1000);\n }, delay);\n }\n\n // Set up event handlers for the watcher\n watcher.on(\"event\", async (event) => {\n switch (event.code) {\n case \"START\":\n watchSpinner.succeed(\"Watch mode active! Eyes peeled.\");\n break;\n\n case \"BUNDLE_START\":\n // Clear source paths from the previous bundle operation\n sourceEventPaths.clear();\n\n // Store source file paths that triggered this build\n if (event.input) {\n try {\n // Handle different input formats safely\n const inputs = Array.isArray(event.input)\n ? event.input\n : typeof event.input === \"string\"\n ? [event.input]\n : typeof event.input === \"object\" && event.input !== null\n ? Object.values(event.input)\n : [];\n\n for (const input of inputs) {\n // Only process string inputs and skip non-string values\n if (typeof input === \"string\" && !isOutputFile(input)) {\n sourceEventPaths.add(path.normalize(input));\n }\n }\n } catch (error) {\n console.error(\"Error processing input paths:\", error);\n }\n }\n\n bundleSpinner = ora(\"Weaving bundles...\").start();\n buildInProgress = true;\n break;\n\n case \"BUNDLE_END\":\n if (bundleSpinner) {\n bundleSpinner.succeed(\n `Bundle ${Array.isArray(event.input) ? `of ${event.input.join(\"& \")} ` : \"\"}done in ${event.duration}ms! \uD83D\uDE80`,\n );\n }\n buildInProgress = false;\n\n // Schedule post-bundle tasks if source files triggered this build\n if (sourceEventPaths.size > 0) {\n schedulePostBundleTasks();\n }\n break;\n\n case \"END\":\n // We've already scheduled tasks in BUNDLE_END, nothing to do here\n break;\n\n case \"ERROR\":\n buildInProgress = false;\n if (bundleSpinner) {\n bundleSpinner.fail(`Oops! Bundle hit a snag: ${event.error.message}`);\n } else {\n ora().fail(`Watch mode hiccup: ${event.error.message}`);\n }\n sourceEventPaths.clear();\n break;\n }\n });\n}\n\n/**\n * Setup watch mode for rollup\n * @param {object} watcher - Rollup watcher instance\n * @param {object} [scssWatcher] - Optional chokidar watcher for demo SCSS\n */\nexport function setupWatchModeListeners(watcher, scssWatcher) {\n registerWatcher(watcher);\n if (scssWatcher) registerWatcher(scssWatcher);\n installShutdownHandler();\n\n return watcher;\n}\n", "import { program } from \"commander\";\nimport ora from \"ora\";\nimport { withBuildOptions } from \"#commands/_sharedOptions.js\";\nimport { buildWithRollup } from \"#scripts/build/index.js\";\n\nlet buildCommand = program\n .command(\"build\")\n .description(\"Builds auro components\");\n\nbuildCommand = withBuildOptions(buildCommand);\n\nexport default buildCommand.action(async (options) => {\n try {\n const build = ora(\"Initializing...\");\n\n if (options.watch) {\n build.text = \"Waiting for changes...\";\n build.spinner = \"bouncingBar\";\n build.color = \"green\";\n } else {\n build.text =\n options.docs === false\n ? \"Building component (docs disabled)\"\n : \"Building component\";\n }\n\n build.start();\n\n await buildWithRollup(options);\n\n if (!options.watch) {\n build.succeed(\"Build completed!\");\n }\n } catch (error) {\n // If there's any active spinner, we need to fail it\n ora().fail(`Build failed: ${error.message}`);\n console.error(error);\n process.exit(1);\n }\n});\n", "import { exec } from \"node:child_process\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\nimport util from \"node:util\";\nimport { program } from \"commander\";\nimport inquirer from \"inquirer\";\nimport { shell } from \"#utils/shell.js\";\n\nexport default program\n .command(\"migrate\")\n .description(\"Script runner to perform repetitive code change tasks\")\n .requiredOption(\n \"-i, --id <string>\",\n \"Select the migration you would like to run by id\",\n )\n .option(\n \"-m, --multi-gitter\",\n \"Run the migration on all repositories in the multi-gitter config\",\n )\n .action(async (options) => {\n const filename = fileURLToPath(import.meta.url);\n const dirname = path.dirname(filename);\n const scriptPath = path.resolve(dirname, \"migrations\", options.id);\n\n if (options.multiGitter) {\n // Check if multi-gitter CLI command is available\n const execPromise = util.promisify(exec);\n\n try {\n await execPromise(\"command -v multi-gitter\");\n } catch {\n console.error(\"multi-gitter is not installed.\");\n process.exit(1);\n }\n\n const answers = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"dryRun\",\n message:\n \"Run migration in dry-run mode? (no changes will be committed)\",\n default: true,\n },\n ]);\n\n if (answers.dryRun) {\n shell(\n `multi-gitter run ${scriptPath}/script.sh --config \"${scriptPath}/multi-gitter.yml\" --dry-run`,\n );\n } else {\n shell(\n `multi-gitter run ${scriptPath}/script.sh --config \"${scriptPath}/multi-gitter.yml\"`,\n );\n }\n } else {\n shell(`${scriptPath}/script.sh`);\n }\n });\n", "import process from \"node:process\";\nimport { program } from \"commander\";\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { syncDotGithubDir } from \"#scripts/syncDotGithubDir.js\";\n\nexport default program\n .command(\"sync\")\n .option(\"-r, --ref <branch/tag/commit>\", \"Git reference (branch/tag/commit) to use\", \"main\")\n .option(\"-t, --template <name>\", \"Template based on which to sync\", \"default\")\n .description(\n \"Script runner to synchronize local repository configuration files\",\n )\n .action(async (options) => {\n Logger.info(\"Synchronizing repository configuration files...\");\n\n Logger.warn(\n \"Note: sync does not create a new git branch. Changes are added to the current branch.\",\n );\n\n const cwd = process.cwd();\n\n try {\n await syncDotGithubDir(cwd, options.ref, options.template);\n\n // Cleanup for specific files\n // ------------------------------------------------------\n\n // Some files have specific cleanup tasks that need to be run after syncing\n\n try {\n // CODEOWNERS - has a bizarre issue with line endings. This is a workaround!\n // Maybe it has to do with the file type since there's no ending?\n const codeownersPath = `${cwd}/.github/CODEOWNERS`;\n const codeowners = await readFile(codeownersPath, { encoding: \"utf-8\" });\n\n // Convert line endings to \\n\n const codeownersFixed = codeowners\n .replace(/\\r\\n/gu, \"\\n\")\n .replace(/\\n\\n/gu, \"\\n\");\n await writeFile(codeownersPath, codeownersFixed, { encoding: \"utf-8\" });\n\n if (codeownersFixed.includes(\"\\r\") || codeownersFixed.includes(\"\\n\\n\")) {\n Logger.error(\"CODEOWNERS file still has Windows line endings.\");\n }\n } catch (codeownersError) {\n Logger.error(`Error processing CODEOWNERS file: ${codeownersError.message}`);\n throw codeownersError;\n }\n } catch (error) {\n Logger.error(`Sync operation failed: ${error.message}`);\n process.exit(1);\n }\n });\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Octokit } from \"@octokit/rest\";\nimport ora from \"ora\";\n// @ts-expect-error: No types available currently\nimport { processContentForFile, templateFiller } from \"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs\";\n\n// BELOW TYPES ARE COPIED DIRECTLY FROM THE LIBRARY\n// How can we import JSDoc types from the library?\n\n/**\n * This is the expected object type when passing something other than a string.\n * @typedef {Object} InputFileType\n * @property {string} remoteUrl - The remote template to fetch.\n * @property {string} fileName - Path including file name to store.\n * @property {boolean} [overwrite] - Default is true. Choose to overwrite the file if it exists.\n */\n\ninterface FileProcessorConfig {\n identifier: string;\n input: string | {\n remoteUrl: string;\n fileName: string;\n overwrite?: boolean;\n };\n output: string;\n mdMagicConfig?: Partial<any>;\n preProcessors?: Array<(contents: string) => string>;\n postProcessors?: Array<(contents: string) => string>;\n}\n\n\n/**\n * Get folder items from a repository-relative path.\n * @param path - Repository-relative path (e.g. \".github/workflows\")\n * @returns Promise resolving to an array of GitHub content items.\n */\nasync function getFolderItemsFromRelativeRepoPath(path: string, ref: string) {\n const octokit = new Octokit({\n auth: process.env.GITHUB_TOKEN || ''\n });\n\n try {\n const response = await octokit.request('GET /repos/{owner}/{repo}/contents/{path}', {\n ref,\n owner: 'AlaskaAirlines',\n repo: 'auro-templates',\n path: path,\n headers: {\n 'X-GitHub-Api-Version': '2022-11-28'\n }\n });\n\n const responseData = response.data;\n if (typeof responseData !== 'object' || !Array.isArray(responseData)) {\n const errorMessage = `Unexpected response format: ${JSON.stringify(responseData)}`;\n const errorSpinner = ora().start();\n errorSpinner.fail(errorMessage);\n throw new Error(\"Failed to retrieve folder items\");\n }\n\n return responseData;\n } catch (error: any) {\n const errorSpinner = ora().start();\n if (error.status === 404) {\n errorSpinner.fail(`Template '${path.split('/')[1]}' not found`);\n } else {\n errorSpinner.fail(`Error accessing template: ${error.message}`);\n }\n throw error;\n }\n}\n\ninterface ProcessIntoFileConfigArgs {\n folderItems: Awaited<ReturnType<typeof getFolderItemsFromRelativeRepoPath>>;\n templatePathToReplace: string;\n rootDir: string;\n ref: string;\n}\n\n/**\n * Recursively convert GitHub contents API items into FileProcessorConfig objects.\n */\nasync function processFolderItemsIntoFileConfigs({\n folderItems,\n templatePathToReplace,\n rootDir,\n ref,\n}: ProcessIntoFileConfigArgs): Promise<Array<FileProcessorConfig>> {\n const fileConfigs: Array<FileProcessorConfig> = [];\n\n for (const item of folderItems) {\n if (item.type == 'dir') {\n const directorySpinner = ora(`Processing directory: ${item.path}`).start();\n\n const nestedFolderItems = await getFolderItemsFromRelativeRepoPath(item.path, ref);\n \n directorySpinner.succeed(`Found ${nestedFolderItems.length} additional items in ${item.path}`);\n\n const nestedConfigs = await processFolderItemsIntoFileConfigs({\n folderItems: nestedFolderItems,\n templatePathToReplace,\n rootDir,\n ref,\n })\n\n fileConfigs.push(...nestedConfigs);\n\n continue;\n }\n\n const finalPath = item.path.replace(`${templatePathToReplace}/`, '');\n const outputPath = `${rootDir}/.github/${finalPath}`;\n\n const config = {\n identifier: item.name,\n input: {\n remoteUrl: item.download_url || '',\n fileName: outputPath,\n overwrite: true,\n },\n output: outputPath,\n } satisfies FileProcessorConfig;\n\n fileConfigs.push(config);\n }\n\n return fileConfigs;\n}\n\n\n/**\n * Recursively removes a directory and all its contents.\n * @param {string} dirPath - The path to the directory to remove.\n * @returns {Promise<void>} A promise that resolves when the directory is removed or rejects if an error occurs.\n * @throws {Error} If the directory cannot be removed.\n */\nasync function removeDirectory(dirPath: string) {\n try {\n await fs.rm(dirPath, { recursive: true, force: true });\n const successSpinner = ora().start();\n successSpinner.succeed(`Successfully removed directory: ${dirPath}`);\n } catch (error: any) {\n const errorSpinner = ora().start();\n errorSpinner.fail(`Error removing directory ${dirPath}: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * Generates a tree-like structure representation of a directory.\n * @param {string} dirPath - The path to the directory to analyze.\n * @param {string} [prefix=''] - The prefix for the current level (used for recursion).\n * @param {boolean} [isLast=true] - Whether this is the last item at the current level.\n * @returns {Promise<string>} A promise that resolves to the tree structure as a string.\n */\nasync function generateDirectoryTree(dirPath: string, prefix: string = '', isLast: boolean = true): Promise<string> {\n try {\n const stats = await fs.stat(dirPath);\n const baseName = path.basename(dirPath);\n \n if (!stats.isDirectory()) {\n return `${prefix}${isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '}${baseName}\\n`;\n }\n\n let result = `${prefix}${isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '}${baseName}/\\n`;\n \n try {\n const entries = await fs.readdir(dirPath);\n const sortedEntries = entries.sort();\n \n for (let i = 0; i < sortedEntries.length; i++) {\n const entry = sortedEntries[i];\n const entryPath = path.join(dirPath, entry);\n const isLastEntry = i === sortedEntries.length - 1;\n const newPrefix = prefix + (isLast ? ' ' : '\u2502 ');\n \n result += await generateDirectoryTree(entryPath, newPrefix, isLastEntry);\n }\n } catch (readError) {\n // If we can't read the directory, just show it as a directory\n result += `${prefix}${isLast ? ' ' : '\u2502 '}\u2514\u2500\u2500 [Permission denied or error reading directory]\\n`;\n }\n \n return result;\n } catch (error) {\n return `${prefix}${isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '}[Error: ${error}]\\n`;\n }\n}\n\n/**\n * Sync the .github directory with the remote repository.\n * @param {string} rootDir - The root directory of the local repository.\n * @param {string} ref - The Git reference (branch/tag/commit) to use.\n * @param {string} template - The template based on which to sync.\n * @returns {Promise<void>} A promise that resolves when syncing is complete.\n */\nexport async function syncDotGithubDir(rootDir: string, ref = 'main', template = 'default') {\n if (!rootDir) {\n const errorSpinner = ora().start();\n errorSpinner.fail(\"Root directory must be specified\");\n throw new Error(\"Root directory must be specified\");\n }\n\n // Setup\n await templateFiller.extractNames();\n\n if (!process.env.GITHUB_TOKEN) {\n const tokenErrorSpinner = ora().start();\n tokenErrorSpinner.fail(\"GITHUB_TOKEN environment variable is not set.\");\n throw new Error(\"GITHUB_TOKEN environment variable is not set\");\n }\n\n const templatesDefaultGithubPath = `templates/${template}/.github`;\n \n // Validate template exists BEFORE removing anything\n const folderItems = await getFolderItemsFromRelativeRepoPath(templatesDefaultGithubPath, ref);\n\n // Only remove .github directory after successful template validation\n const githubPath = \".github\";\n const removeSpinner = ora(\"Removing existing .github directory...\").start();\n try {\n await removeDirectory(githubPath);\n removeSpinner.succeed(\".github directory removed successfully\");\n } catch (error: any) {\n removeSpinner.fail(`Error removing .github directory: ${error.message}`);\n throw new Error(`Failed to remove .github directory: ${error.message}`);\n }\n\n const fileConfigs = await processFolderItemsIntoFileConfigs({\n folderItems,\n templatePathToReplace: templatesDefaultGithubPath,\n rootDir,\n ref,\n });\n\n // Process all files\n const processSpinner = ora(\"Processing all files...\").start();\n try {\n await Promise.all(\n fileConfigs.map((config) => processContentForFile(config)),\n );\n processSpinner.succeed(\"All files processed.\");\n\n // Generate and display tree output of the rootDir directory\n const treeSpinner = ora(\"Generating directory tree...\").start();\n try {\n const githubDirPath = path.join(rootDir, '.github');\n const treeOutput = await generateDirectoryTree(githubDirPath);\n treeSpinner.succeed(\"Synced .github directory structure:\");\n console.log(treeOutput);\n } catch (treeError: any) {\n treeSpinner.fail(`Error generating directory tree: ${treeError.message}`);\n // Don't exit here since the main operation succeeded\n }\n\n } catch (error: any) {\n processSpinner.fail(`Error processing files: ${error.message}`);\n throw new Error(`Failed to process files: ${error.message}`);\n }\n}\n", "/* eslint-disable no-await-in-loop, line-comment-position, no-inline-comments, jsdoc/require-jsdoc, no-undef */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport { glob } from \"glob\";\nimport getTemplatedComponentCode from \"#scripts/prepWcaCompatibleCode.mjs\";\n\n// Use glob directly as it's already promised-based in newer versions\n\nconst WAC_DIR = path.resolve(process.cwd(), \"./scripts/wca\");\n\nasync function globPath(sources) {\n try {\n const fileArrays = await Promise.all(sources.map((source) => glob(source)));\n return fileArrays.flat();\n } catch (err) {\n console.error(\"Error processing glob patterns:\", err);\n throw err; // Re-throw to handle failure at caller\n }\n}\n\nasync function createExtendsFile(filePaths) {\n if (!fs.existsSync(WAC_DIR)) {\n await fs.promises.mkdir(WAC_DIR, { recursive: true });\n }\n\n for (const filePath of filePaths) {\n const resolvedPath = path.resolve(process.cwd(), filePath);\n const fileContent = await fs.promises.readFile(resolvedPath, \"utf-8\");\n const newPath = path.resolve(WAC_DIR, `${path.basename(filePath)}`);\n const newCode = getTemplatedComponentCode(\n fileContent,\n path.relative(WAC_DIR, filePath),\n );\n await fs.promises.writeFile(newPath, newCode);\n }\n}\n\nasync function main() {\n // files to analyze\n const filePaths = await globPath([\"./src/auro-*.js\"]);\n await createExtendsFile(filePaths);\n}\n\nexport default program\n .command(\"wca-setup\")\n .description(\"Set up WCA (Web Component Analyzer) for the project\")\n .action(() => {\n main()\n .then(() => {\n Logger.success(\"WCA setup completed successfully.\");\n })\n .catch((error) => {\n Logger.error(`WCA setup failed: ${error.message}`);\n });\n });\n", "/* eslint-disable require-unicode-regexp, prefer-named-capture-group, prefer-destructuring, prettier/prettier */\n\nexport default (code, sourcePath) => {\n const defaultTag = (code.match(/static register\\(name \\= (.+)\\)/) ||\n code.match(/customElements.get\\((.+?)\\)/))[1];\n const className = code.match(/export class (.+) extends/)?.[1];\n const classDesc = code.match(/\\/\\*\\*((.|\\n)*?)(\\*\\n|\\*\\/|[@])/)?.[1] || \"\";\n\n if (!defaultTag || !className) {\n return code;\n }\n return `\nimport { ${className} } from '${sourcePath}';\n\n/**${classDesc}*/\nclass ${className}WCA extends ${className} {}\n\nif (!customElements.get(${defaultTag})) {\n customElements.define(${defaultTag}, ${className}WCA);\n}\n`;\n};\n", "import { program } from \"commander\";\nimport { analyzeCommits } from \"#scripts/check-commits/commit-analyzer.ts\";\n\nexport default program\n .command(\"check-commits\")\n .alias(\"cc\")\n .option(\n \"-l, --set-label\",\n \"Set label on the pull request based on the commit message type\",\n )\n .option(\"-d, --debug\", \"Display detailed commit information for debugging\")\n .option(\"-r, --release-notes\", \"Generate release notes based on commit messages\")\n .description(\n \"Check commits in the local repository for the types of semantic commit messages made and return the results.\",\n )\n .action(async (option) => {\n await analyzeCommits(option.debug, option.setLabel, option.releaseNotes);\n });\n", "import chalk from \"chalk\";\nimport ora from \"ora\";\nimport type { Ora } from \"ora\";\nimport { Git } from \"#utils/gitUtils.ts\";\nimport type { CommitInfo } from \"./display-utils.ts\";\nimport { displayDebugView, getColoredType } from \"./display-utils.ts\";\nimport { applyLabelToPR, getExistingLabels } from \"./github-labels.ts\";\n\nconst RELEASE_COMMIT_TYPES = [\"feat\", \"fix\", \"breaking\", \"perf\"];\n\n/**\n * Generate release notes in the specified format\n * First tries to show only feat, fix, and breaking commits\n * If none found, shows all commits for user selection\n * @param commitList The list of commits to process\n * @param showLog Whether to show the commit count log (default: true)\n */\nexport function generateReleaseNotes(commitList: CommitInfo[], showLog = true): string {\n let releaseNotes = \"### In this release\\n\";\n\n for (const commit of commitList) {\n // Format: - {short commit hash} {commit message}\n releaseNotes += `- ${commit.hash} ${commit.subject}\\n`;\n \n // Add extra commit message content if body exists\n if (commit.body?.trim()) {\n // Split body into meaningful chunks, handling different separators\n const bodyText = commit.body.trim();\n \n // Split by common separators and clean up\n const bodyLines = bodyText\n .split(/\\n+/) // Split on one or more newlines\n .map(line => line.trim())\n .filter(line => line.length > 0);\n \n for (const line of bodyLines) {\n // Handle issue references and add proper spacing\n let formattedLine = line;\n \n // Add spaces before issue references like AlaskaAirlines/auro-cli#108\n formattedLine = formattedLine.replace(\n /([^\\s])(AlaskaAirlines\\/[a-zA-Z0-9-]+#\\d+)/g, \n '$1 $2'\n );\n \n // Add spaces between consecutive issue references\n formattedLine = formattedLine.replace(\n /(AlaskaAirlines\\/[a-zA-Z0-9-]+#\\d+)([^\\s])/g, \n '$1 $2'\n );\n \n releaseNotes += ` - ${formattedLine}`;\n }\n }\n }\n\n // Show helpful info about what was included\n if (commitList.length === 0) {\n return \"\";\n }\n\n if (showLog) {\n console.log(chalk.green(`\u2713 Generating release notes for ${commitList.length} commits`));\n }\n\n return releaseNotes;\n}\n\nexport function filterCommitList(commitList: CommitInfo[], fallbackCommits = true): CommitInfo[] {\n // Filter for preferred commit types first\n const releaseCommits = commitList.filter(commit => \n RELEASE_COMMIT_TYPES.includes(commit.type)\n );\n \n // Use filtered commits if any found, otherwise use all commits\n let commitsToShow;\n\n if (fallbackCommits) {\n commitsToShow = releaseCommits.length > 0 ? releaseCommits : commitList;\n } else {\n commitsToShow = releaseCommits;\n }\n \n if (commitsToShow.length === 0) {\n console.log(\"No commits found to include in release notes.\\n\");\n }\n\n return commitsToShow;\n}\n\n/**\n * Analyze commit messages in the repository\n * @param debug Whether to display detailed debug information\n * @param verbose Whether to display verbose commit messages without truncation\n * @param setLabel Whether to apply a label to the PR based on commit types\n * @returns A promise that resolves when analysis is complete\n */\nexport async function analyzeCommits(\n debug = false,\n setLabel = false,\n releaseNotes = false,\n): Promise<void> {\n const spinner = ora(\"Checking commits...\\n\").start();\n\n try {\n const commitList = await Git.getCommitMessages();\n\n // Generate release notes if requested\n if (releaseNotes) {\n spinner.succeed(`Total commits analyzed: ${commitList.length}`);\n\n const filteredCommits = filterCommitList(commitList);\n\n console.log(generateReleaseNotes(filteredCommits));\n return;\n }\n\n // Only display commit details if debug mode is enabled\n if (debug) {\n displayDebugView(commitList);\n }\n\n spinner.succeed(`Total commits analyzed: ${commitList.length}`);\n\n if (commitList.length !== 0) {\n const commitTypes = commitList.map((commit) => commit.type);\n const uniqueTypes = Array.from(new Set(commitTypes));\n const formattedTypes = uniqueTypes\n .map((type) => getColoredType(type))\n .join(\", \");\n spinner.succeed(`Found commit types: ${formattedTypes}`);\n } else {\n spinner.info(\n \"The list of commits is created by comparing the current branch\\n\" +\n \"with the main branch. If you are on a new branch, please\\n\" +\n \"make sure to commit some changes before running this command.\",\n );\n }\n\n if (setLabel) {\n await handleLabels(commitList, spinner);\n }\n } catch (error) {\n spinner.fail(\"Error getting commit messages\");\n console.error(error);\n }\n}\n\n/**\n * Handle applying labels based on commit types\n * @param commitList The list of commits to analyze\n * @param spinner The ora spinner instance for status updates\n */\nasync function handleLabels(\n commitList: CommitInfo[],\n spinner: Ora,\n): Promise<void> {\n const validCommitTypes = [\n \"breaking\",\n \"feat\",\n \"fix\",\n \"perf\",\n \"docs\",\n \"style\",\n \"refactor\",\n \"test\",\n \"build\",\n \"ci\",\n \"chore\",\n ];\n\n const foundCommitTypes = commitList\n .map((commit) => commit.type)\n .filter((type) => validCommitTypes.includes(type));\n\n let selectedLabel = null;\n let highestPriorityIndex = Number.POSITIVE_INFINITY;\n\n for (const type of foundCommitTypes) {\n const priorityIndex = validCommitTypes.indexOf(type);\n if (priorityIndex < highestPriorityIndex) {\n highestPriorityIndex = priorityIndex;\n selectedLabel = type;\n }\n }\n\n if (selectedLabel) {\n const labelSpinner = ora(\n \"Checking existing labels on pull request...\",\n ).start();\n try {\n const existingLabels = await getExistingLabels();\n\n if (existingLabels.includes(`semantic-status: ${selectedLabel}`)) {\n labelSpinner.info(\n `Label \"semantic-status: ${getColoredType(selectedLabel)}\" already exists on the pull request.`,\n );\n return;\n }\n\n labelSpinner.text = \"Applying label to pull request...\";\n await applyLabelToPR(selectedLabel);\n labelSpinner.succeed(\n `Label \"semantic-status: ${getColoredType(selectedLabel)}\" applied to the pull request.`,\n );\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n labelSpinner.fail(errorMessage);\n }\n } else {\n spinner.warn(\n chalk.yellow(\"No semantic commit type found to apply as label.\"),\n );\n }\n}\n", "import { appendFile, readFile } from \"node:fs/promises\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { simpleGit } from \"simple-git\";\nimport type { SimpleGit } from \"simple-git\";\n\n// Initialize simple-git with proper typing\nlet git: SimpleGit;\ntry {\n git = simpleGit({\n baseDir: process.cwd(),\n binary: \"git\",\n maxConcurrentProcesses: 1,\n });\n} catch (error) {\n Logger.error(`Failed to initialize git: ${error}`);\n // Provide a minimal implementation to prevent runtime errors\n git = {} as SimpleGit;\n}\n\nexport class Git {\n static async checkGitignore(pattern: string) {\n if (pattern === \"\") {\n return false;\n }\n try {\n const fileContent = await readFile(\".gitignore\", \"utf-8\");\n return fileContent.includes(pattern);\n } catch (err) {\n Logger.error(`Error reading file: ${err}`);\n return false;\n }\n }\n\n static async getCommitMessages(sourceBranch = \"\"): Promise<\n Array<{\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n }>\n > {\n try {\n // Use the provided branch parameter, or fall back to current branch if not specified\n let branch = sourceBranch;\n if (!branch) {\n const currentBranch = await git.branchLocal();\n branch = currentBranch.current;\n }\n\n // ---- Get target branch (main) and PR commits ----\n let targetBranch = \"main\";\n let commitRange = \"\";\n\n // Check if we're in a GitHub Actions environment\n const isGitHubAction = !!process.env.GITHUB_ACTIONS;\n\n if (isGitHubAction) {\n // In GitHub Actions, we can use environment variables to determine the PR branch and base\n targetBranch = process.env.GITHUB_BASE_REF || \"main\";\n\n try {\n // Ensure target branch is fetched\n await git.fetch(\"origin\", targetBranch);\n\n // Ensure source branch is available\n if (branch !== \"HEAD\") {\n try {\n await git.raw([\"rev-parse\", \"--verify\", `origin/${branch}`]);\n } catch {\n await git.fetch(\"origin\", branch);\n }\n }\n\n // Use remote refs consistently since we're in CI\n const sourceBranchRef = branch === \"HEAD\" ? \"HEAD\" : `origin/${branch}`;\n\n // Use the merge base between target branch and source branch to get commits\n const mergeBase = await git.raw([\n \"merge-base\",\n `origin/${targetBranch}`,\n sourceBranchRef,\n ]);\n\n // Get commits between merge base and source branch\n commitRange = `${mergeBase.trim()}..${sourceBranchRef}`;\n } catch (error) {\n Logger.warn(`Error setting up commit range in CI: ${error}`);\n // Fall back to simpler approach (just compare with origin/targetBranch)\n const sourceBranchRef = branch === \"HEAD\" ? \"HEAD\" : `origin/${branch}`;\n commitRange = `origin/${targetBranch}..${sourceBranchRef}`;\n }\n } else {\n // Local environment - try to determine commits\n\n try {\n // First check if origin/main exists, fetch it if needed\n try {\n await git.raw([\"rev-parse\", \"--verify\", `origin/${targetBranch}`]);\n } catch {\n Logger.info(`Fetching ${targetBranch} from origin`);\n await git.fetch(\"origin\", targetBranch);\n }\n\n // Ensure source branch is available\n if (branch !== \"HEAD\") {\n try {\n await git.raw([\"rev-parse\", \"--verify\", branch]);\n } catch {\n await git.fetch(\"origin\", branch);\n }\n }\n\n // Find merge base between source branch and target branch\n const mergeBase = await git.raw([\n \"merge-base\",\n `origin/${targetBranch}`,\n branch,\n ]);\n\n commitRange = `${mergeBase.trim()}..${branch}`;\n } catch (error) {\n Logger.warn(`Error determining commits locally: ${error}`);\n\n // Fallback - use last few commits from source branch\n commitRange = `${branch}~10..${branch}`;\n }\n }\n\n // Get and format the PR commits\n return await Git.getFormattedCommits(commitRange);\n } catch (err) {\n Logger.error(`Error getting commit messages: ${err}`);\n return [];\n }\n }\n\n static async getRepoOwnerAndName(): Promise<{ owner: string; repo: string } | null> {\n try {\n // Get remote URLs\n const remotes = await git.getRemotes(true);\n \n if (remotes.length === 0) {\n Logger.warn(\"No remotes found\");\n return null;\n }\n\n // Get the origin remote (or first available)\n const originRemote = remotes.find(remote => remote.name === 'origin') || remotes[0];\n const remoteUrl = originRemote.refs.fetch || originRemote.refs.push;\n\n return Git.parseGitUrl(remoteUrl);\n } catch (err) {\n Logger.error(`Error getting repo owner and name: ${err}`);\n return null;\n }\n }\n\n static async getCurrentBranchName(): Promise<string | null> {\n try {\n const branchInfo = await git.branchLocal();\n return branchInfo.current || null;\n } catch (err) {\n Logger.error(`Error getting current branch name: ${err}`);\n return null;\n }\n }\n\n private static parseGitUrl(url: string): { owner: string; repo: string } | null {\n // Handle different URL formats\n // SSH: git@github.com:owner/repo.git\n // HTTPS: https://github.com/owner/repo.git\n // HTTPS with auth: https://user:token@github.com/owner/repo.git\n\n let match: RegExpMatchArray | null;\n\n // SSH format\n if (url.includes('@') && url.includes(':')) {\n match = url.match(/@([^:]+):([^/]+)\\/(.+?)(?:\\.git)?$/);\n if (match) {\n return { owner: match[2], repo: match[3] };\n }\n }\n\n // HTTPS format\n match = url.match(/https?:\\/\\/(?:[^@]+@)?[^/]+\\/([^/]+)\\/(.+?)(?:\\.git)?$/);\n if (match) {\n return { owner: match[1], repo: match[2] };\n }\n\n Logger.warn(`Could not parse git URL: ${url}`);\n return null;\n }\n\n // Helper function to get formatted commits for a given git range\n static async getFormattedCommits(commitRange: string): Promise<\n Array<{\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n }>\n > {\n interface GitCommitType {\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n type: string;\n }\n\n // Use a format that will let us parse each commit separately\n // %H = hash, %ad = author date, %an = author name, %s = subject, %b = body\n const branchCommitsRaw = await git.raw([\n \"log\",\n \"--pretty=format:COMMIT_START%n%H%n%ad%n%an%n%s%n%b%nCOMMIT_END\",\n \"--date=short\",\n commitRange,\n ]);\n\n // Split by our custom delimiter to get individual commits\n const commitChunks = branchCommitsRaw\n .split(\"COMMIT_START\\n\")\n .filter((chunk: string) => chunk.trim() !== \"\");\n\n const commits: GitCommitType[] = [];\n\n for (const chunk of commitChunks) {\n const parts = chunk.split(\"\\n\");\n if (parts.length >= 4) {\n const hash = parts[0];\n const date = parts[1];\n const author_name = parts[2];\n const subject = parts[3];\n\n // The rest is the body (may contain breaking changes)\n // Filter out the COMMIT_END marker\n const bodyLines = parts\n .slice(4)\n .filter((line: string) => line !== \"COMMIT_END\");\n const body = bodyLines.length > 0 ? bodyLines.join(\"\") : \"\";\n\n // Use a shorter hash format for better readability (7 characters)\n const shortHash = hash.substring(0, 7);\n\n // Determine commit type from subject\n const typeMatch = subject.match(\n /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore)(\\(.+\\))?:/,\n );\n let type = typeMatch ? typeMatch[1] : \"unknown\";\n\n // Check for breaking changes\n if (body.includes(\"BREAKING CHANGE\")) {\n type = \"breaking\";\n }\n\n commits.push({\n type,\n hash: shortHash,\n date,\n subject,\n body,\n message: `${subject}${body ? `\\n\\n${body}` : \"\"}`,\n author_name,\n });\n }\n }\n\n return commits;\n }\n\n // Function to add file to .gitignore\n static async addToGitignore(pattern: string, log = true) {\n await Git.checkGitignore(pattern).then(async (result) => {\n if (result) {\n Logger.warn(`${pattern} already exists`);\n } else {\n try {\n await appendFile(\".gitignore\", `\\n${pattern}`);\n if (log) {\n Logger.success(`${pattern} added to .gitignore`);\n }\n } catch (err) {\n Logger.error(err);\n }\n }\n });\n }\n\n // Function to remove file from git cache\n static async removeFromGitCache(files: string[]) {\n try {\n await git.rmKeepLocal(files);\n Logger.success(`${files.join(\", \")} are removed from git cache`);\n } catch (err) {\n Logger.error(err);\n }\n }\n\n static async createBranch(branchName: string) {\n try {\n await git.checkoutLocalBranch(branchName);\n Logger.success(`Created and switched to ${branchName} branch`);\n } catch (err) {\n Logger.error(err);\n }\n }\n\n static async commitStagedFiles(message: string) {\n try {\n await git.add(\".\");\n await git.commit(message);\n Logger.success(`Committed with message: ${message}`);\n } catch (err) {\n Logger.error(err);\n }\n }\n}\n", "import chalk from \"chalk\";\n\n// Configuration constants for display\nexport const MAX_SUBJECT_LENGTH = 60;\nexport const MAX_BODY_LENGTH = 100;\n\nexport interface CommitInfo {\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n}\n\n// Define valid commit types for better type checking\nexport type CommitType =\n | \"breaking\"\n | \"feat\"\n | \"fix\"\n | \"perf\"\n | \"docs\"\n | \"style\"\n | \"refactor\"\n | \"test\"\n | \"build\"\n | \"ci\"\n | \"chore\"\n | \"unknown\";\n\n/**\n * Get colored text for commit type using a more harmonious color scheme\n */\nexport function getColoredType(type: string): string {\n switch (type) {\n case \"breaking\":\n return chalk.bold.red(type);\n case \"feat\":\n return chalk.bold.green(type);\n case \"fix\":\n return chalk.bold.green(type);\n case \"perf\":\n return chalk.bold.green(type);\n case \"docs\":\n return chalk.bold.cyan(type);\n case \"style\":\n return chalk.bold.cyan(type);\n case \"refactor\":\n return chalk.bold.cyan(type);\n case \"test\":\n return chalk.bold.cyan(type);\n case \"build\":\n return chalk.bold.cyan(type);\n case \"ci\":\n return chalk.bold.cyan(type);\n case \"chore\":\n return chalk.bold.cyan(type);\n default:\n return chalk.bold.white(type);\n }\n}\n\n/**\n * Helper function to wrap long strings to new lines\n */\nexport function wrapString(str: string, maxLength: number): string {\n if (!str) {\n return \"\";\n }\n\n // If the string is shorter than maxLength, return it as is\n if (str.length <= maxLength) {\n return str;\n }\n\n // Split the string into words\n const words = str.split(\" \");\n let result = \"\";\n let currentLine = \"\";\n\n // Build wrapped text with line breaks\n for (const word of words) {\n // If adding this word would exceed maxLength, start a new line\n if ((currentLine + word).length > maxLength && currentLine.length > 0) {\n result += `${currentLine.trim()}\\n`;\n currentLine = \"\";\n }\n currentLine = `${currentLine}${word} `;\n }\n\n // Add the last line\n if (currentLine.length > 0) {\n result += currentLine.trim();\n }\n\n return result;\n}\n\n/**\n * Display commits in a debug format with detailed information\n */\nexport function displayDebugView(commitList: CommitInfo[]): void {\n for (const commit of commitList) {\n console.log(\"\u2500\".repeat(60));\n\n // Use a consistent color theme for metadata\n const subject = wrapString(commit.subject, MAX_SUBJECT_LENGTH);\n const body = wrapString(commit.body, MAX_BODY_LENGTH);\n\n // Display commit info in a more compact format\n console.log(chalk.bold(`${getColoredType(commit.type)}`));\n console.log(\n chalk.dim(`${commit.hash} | ${commit.date} | ${commit.author_name}`),\n );\n console.log(chalk.bold(`${chalk.white(subject)}`));\n\n // Only add body if it exists and keep it more compact\n if (commit.body) {\n console.log(chalk.dim(body));\n }\n }\n console.log(\"\u2500\".repeat(60));\n console.log(\"\\n\");\n}\n", "import * as github from \"@actions/github\";\n\n/**\n * Get existing labels from the current pull request in a GitHub Actions environment\n * @returns Promise that resolves with an array of label names\n */\nexport async function getExistingLabels(): Promise<string[]> {\n try {\n // Get the GitHub token from environment\n const token = process.env.GITHUB_TOKEN;\n\n if (!token) {\n throw new Error(\"GITHUB_TOKEN environment variable is not set\");\n }\n\n // Check if we're in a GitHub Actions environment\n if (!process.env.GITHUB_REPOSITORY || !process.env.GITHUB_EVENT_PATH) {\n throw new Error(\n \"This function can only be used in a GitHub Actions environment\",\n );\n }\n\n const octokit = github.getOctokit(token);\n const { context } = github;\n\n // Make sure we're in a pull request context\n if (!context.payload.pull_request) {\n throw new Error(\"No pull request found in the GitHub context\");\n }\n\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split(\"/\");\n const prNumber = context.payload.pull_request.number;\n\n // Get existing labels\n const { data: existingLabels } =\n await octokit.rest.issues.listLabelsOnIssue({\n owner,\n repo,\n issue_number: prNumber,\n });\n\n // Return array of label names\n return existingLabels.map((label: { name: string }) => label.name);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get existing labels: ${error.message}`);\n }\n throw error;\n }\n}\n\n/**\n * Apply a label to the current pull request in a GitHub Actions environment\n * @param label The label to apply to the pull request\n * @returns Promise that resolves when the label is applied\n */\nexport async function applyLabelToPR(label: string): Promise<void> {\n try {\n // Get the GitHub token from environment\n const token = process.env.GITHUB_TOKEN;\n\n if (!token) {\n throw new Error(\"GITHUB_TOKEN environment variable is not set\");\n }\n\n // Check if we're in a GitHub Actions environment\n if (!process.env.GITHUB_REPOSITORY || !process.env.GITHUB_EVENT_PATH) {\n throw new Error(\n \"This function can only be used in a GitHub Actions environment\",\n );\n }\n\n const octokit = github.getOctokit(token);\n const { context } = github;\n\n // Make sure we're in a pull request context\n if (!context.payload.pull_request) {\n throw new Error(\"No pull request found in the GitHub context\");\n }\n\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split(\"/\");\n const prNumber = context.payload.pull_request.number;\n\n // Add prefix to the label\n const prefixedLabel = `semantic-status: ${label}`;\n\n // Get existing labels\n const existingLabels = await getExistingLabels();\n\n // If the label we want to apply already exists, do nothing\n if (existingLabels.includes(prefixedLabel)) {\n return;\n }\n\n // Find existing semantic status labels that are different from the one we want to apply\n const existingSemanticLabels = existingLabels.filter(\n (existingLabel) =>\n existingLabel.startsWith(\"semantic-status:\") &&\n existingLabel !== prefixedLabel,\n );\n\n // Remove existing semantic status labels that don't match the new one\n for (const existingLabel of existingSemanticLabels) {\n await octokit.rest.issues.removeLabel({\n owner,\n repo,\n issue_number: prNumber,\n name: existingLabel,\n });\n }\n\n // Add the new semantic status label\n await octokit.rest.issues.addLabels({\n owner,\n repo,\n issue_number: prNumber,\n labels: [prefixedLabel],\n });\n\n return;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to apply label: ${error.message}`);\n }\n throw error;\n }\n}\n", "import fs from \"node:fs\";\nimport { get } from \"node:https\"; // Change to https\nimport chalk from \"chalk\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport type { Ora } from \"ora\";\n\nexport default program\n .command(\"pr-release\")\n .option(\n \"-n, --namespace <package-namespace>\",\n \"Set namespace of the package release\",\n \"@aurodesignsystem-dev\",\n )\n .option(\n \"-p, --pr-number <number>\",\n \"Set pull request number for the release\",\n \"0\",\n )\n .description(\n \"Generate the package version based off of PR number then update the package.json file. Note: this does not publish the package.\",\n )\n .action(async (option) => {\n await updatePackageJson(option);\n });\n\ninterface ReleaseOptions {\n namespace: string;\n prNumber: number;\n}\n\nconst updatePackageJson = async (option: ReleaseOptions): Promise<void> => {\n const { namespace, prNumber } = option;\n\n const packageSpinner = ora(\"Updating package.json\").start();\n\n try {\n const packageJsonPath = \"package.json\";\n\n // Read package.json\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n\n // Check if release version is on npmjs already\n packageSpinner.text = \"Checking npm registry for version information...\";\n\n const releaseVersion = `0.0.0-pr${prNumber}`;\n const packageComponent = packageJson.name.split(\"/\")[1];\n const packageName = `${namespace}/${packageComponent}`;\n const incrementVersion = await getIncrementVersion(\n releaseVersion,\n packageName,\n packageSpinner,\n );\n const packageVersion = `${releaseVersion}.${incrementVersion}`;\n\n packageJson.name = packageName;\n packageJson.version = packageVersion;\n\n packageSpinner.text = \"Writing updated package.json...\";\n\n // Write the updated package.json back to the file\n fs.writeFileSync(\n packageJsonPath,\n `${JSON.stringify(packageJson, null, 2)}\\n`,\n \"utf8\",\n );\n\n packageSpinner.succeed(\n `Package.json updated to use ${chalk.green(packageVersion)} and ${chalk.green(packageName)}`,\n );\n\n // Explicitly exit with success code to ensure terminal prompt returns\n process.exit(0);\n } catch (error: unknown) {\n packageSpinner.fail(`Failed to update package.json: ${error}`);\n process.exit(1); // Exit with error code\n }\n};\n\n// checks if version exists on npmjs and returns the next available increment version\nconst getIncrementVersion = (\n releaseVersion: string,\n packageName: string,\n spinner: Ora,\n): Promise<number> => {\n return new Promise((resolve) => {\n try {\n // Use the registry URL to get all versions for the package\n const registryUrl = `https://registry.npmjs.org/${packageName}`;\n\n const req = get(\n registryUrl,\n {\n headers: { Accept: \"application/json\" },\n },\n (res) => {\n // Handle redirects\n if (\n (res.statusCode === 301 || res.statusCode === 302) &&\n res.headers.location\n ) {\n // Persist redirect message\n spinner.info(`Following redirect to ${res.headers.location}...`);\n try {\n get(\n res.headers.location,\n { headers: { Accept: \"application/json\" } },\n handleResponse,\n )\n .on(\"error\", (err) => {\n // On redirect error, default to 0\n spinner.warn(\n `Error following redirect: ${err.message}, defaulting to version 0`,\n );\n resolve(0);\n })\n .end();\n } catch (error) {\n // If redirect request fails, default to 0\n spinner.warn(\n `Redirect request failed: ${error instanceof Error ? error.message : \"Unknown error\"}, defaulting to version 0`,\n );\n resolve(0);\n }\n return;\n }\n\n handleResponse(res);\n },\n );\n\n function handleResponse(res: import(\"http\").IncomingMessage) {\n if (res.statusCode !== 200) {\n // If package not found or other error, we can start with version 0\n spinner.info(\n `Package not found. Status code: ${chalk.red(res.statusCode)}, defaulting to version 0`,\n );\n resolve(0);\n return;\n }\n\n spinner.text = \"Processing version information...\";\n let data = \"\";\n res.on(\"data\", (chunk: Buffer | string) => {\n data += chunk;\n });\n\n res.on(\"end\", () => {\n try {\n const packageData = JSON.parse(data);\n const versions = packageData.versions\n ? Object.keys(packageData.versions)\n : [];\n\n spinner.text = \"Calculating next version number...\";\n\n // Find the highest existing iteration for this release version\n let maxIteration = -1;\n const versionRegex = new RegExp(`^${releaseVersion}\\\\.(\\\\d+)$`);\n\n for (const version of versions) {\n const match = version.match(versionRegex);\n if (match) {\n const iteration = Number.parseInt(match[1], 10);\n maxIteration = Math.max(maxIteration, iteration);\n }\n }\n\n // Return the next iteration number and persist this important info\n if (maxIteration >= 0) {\n spinner.info(\n `Found existing version ${chalk.green(`${releaseVersion}.${maxIteration}`)}. Incrementing to ${chalk.green(`${releaseVersion}.${maxIteration + 1}`)}`,\n );\n } else {\n spinner.info(\n `No existing version found for ${chalk.green(releaseVersion)}. Starting with ${chalk.green(`${releaseVersion}.0`)}`,\n );\n }\n resolve(maxIteration + 1);\n } catch (error) {\n // In case of parsing error, default to 0\n spinner.warn(\n `Failed to parse NPM registry response: ${error instanceof Error ? error.message : \"Unknown error\"}, defaulting to version 0`,\n );\n resolve(0);\n }\n });\n }\n\n req.on(\"error\", (err) => {\n // On request error, default to 0\n spinner.warn(`Request error: ${err.message}, defaulting to version 0`);\n resolve(0);\n });\n\n req.end();\n } catch (error) {\n // Catch any other errors and default to 0\n spinner.warn(\n \"Error checking version in npm registry, defaulting to version 0\",\n );\n resolve(0);\n }\n });\n};\n", "import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { program } from \"commander\";\nimport open from \"open\";\nimport { shell } from \"#utils/shell.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst cliRootDir = path.resolve(path.dirname(__filename), \"..\");\n\nexport default program\n .command(\"test\")\n .option(\"-w, --watch\", \"Set watch number for the test\")\n .option(\"-c, --coverage-report\", \"Generate coverage report\")\n .option(\"-o, --open\", \"Open the coverage report in the browser\")\n .option(\"-f, --files <String|String[]>\", \"Test files glob pattern\")\n .description(\"Run the web test runner to test the component library\")\n .action(async (option) => {\n const configPath = path.join(\n cliRootDir,\n \"dist\",\n \"configs\",\n \"web-test-runner.config.mjs\",\n );\n let command = `npx wtr --config \"${configPath}\"`;\n const coveragePath = `${process.cwd()}/coverage/index.html`;\n\n if (option.coverageReport) {\n command += \" --coverage\";\n }\n\n if (option.watch) {\n command += \" --watch\";\n }\n\n if (option.files) {\n const files = Array.isArray(option.files)\n ? option.files.join(\" \")\n : option.files;\n command += ` --files \"${files}\"`;\n }\n\n shell(command);\n\n if (option.open) {\n await open(coveragePath);\n }\n });\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { program } from \"commander\";\nimport inquirer from \"inquirer\";\nimport ora from \"ora\";\nimport { createMultiGitterDependencyTreeConfig } from \"#scripts/agent/run-migrations/writeMultiGitterConfig.js\";\nimport {\n formatDependencyTree,\n getBatchedUpdateOrder,\n} from \"#scripts/formatDependencyTree.ts\";\nimport { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport { fromCliRoot, withHomeDir } from \"#utils/pathUtils.js\";\nimport { shell } from \"#utils/shell.js\";\n\n// Multi-gitter and other config files live here\nconst CONFIG_DIR = withHomeDir(\"run-migrations\", \"config\");\n// Generated output files live here\nconst OUTPUT_DIR = withHomeDir(\"run-migrations\", \"outputs\");\n\nenum AgentActions {\n RunMigration = \"run-migration\",\n // Add more actions as needed\n}\n\ninterface AgentAnswers {\n agentAction: AgentActions;\n}\n\n// Agent component options\n// =========================================================\n// The canonical component list lives in #static/auroComponents so `auro cem`,\n// `auro component`, and this command can't drift out of sync.\n\nconst auroPackages = [\n ...AURO_COMPONENT_PACKAGES,\n \"@aurodesignsystem/auro-library\",\n \"@aurodesignsystem/WebCoreStyleSheets\",\n \"@aurodesignsystem/AuroDesignTokens\",\n \"@aurodesignsystem/auro-cli\",\n \"@alaskaairux/icons\",\n];\n\n// Agent helpers\n// =========================================================\ninterface DependencyTreeAnswers {\n useExisting: boolean;\n}\n\nasync function getOrCreateDependencyTree(\n relevantPackages: string[],\n): Promise<string> {\n // check if output and config directories exist, if not create them\n try {\n await fs.mkdir(OUTPUT_DIR, { recursive: true });\n await fs.mkdir(CONFIG_DIR, { recursive: true });\n } catch (error) {\n console.error(\"Failed to create output or config directories:\", error);\n process.exit(1);\n }\n\n const spinner = ora(\"Creating dependency tree...\").start();\n\n // Create multi-gitter dependency tree configuration\n spinner.text = \"Creating multi-gitter dependency tree configuration...\";\n await createMultiGitterDependencyTreeConfig(CONFIG_DIR);\n\n spinner.text = \"Scraping dependencies from Auro packages...\";\n\n // Run multi-gitter using the generated config\n const scriptPath = fromCliRoot(\"static\", \"getAuroDeps.js\");\n const multiGitterCommand = `multi-gitter run \"node ${scriptPath}\" --config ${path.join(CONFIG_DIR, \"multi-gitter_DEPENDENCY_TREE.yml\")}`;\n try {\n await shell(multiGitterCommand);\n } catch (error) {\n spinner.fail(\"Failed to generate dependency tree:\");\n console.error(error);\n process.exit(1);\n }\n\n spinner.text = \"Generating dependency tree JSON file using packages...\";\n await formatDependencyTree(OUTPUT_DIR, relevantPackages);\n\n spinner.succeed(\"Dependency tree generated successfully.\");\n\n return path.join(OUTPUT_DIR, \"dependencyTree.json\");\n}\n\nconst getDependencyBatchesFromTree = async (\n dependencyTreePath: string,\n): Promise<string[][]> => {\n const spinner = ora(\"Loading dependency tree...\").start();\n const dependencyTree = JSON.parse(\n await fs.readFile(dependencyTreePath, \"utf-8\"),\n );\n\n spinner.text = \"Processing dependency tree...\";\n const batches = getBatchedUpdateOrder(dependencyTree);\n spinner.succeed(\"Dependency batches created successfully.\");\n\n return batches;\n};\n\n// Agent command\n// =========================================================\nexport default program.command(\"agent\").action(async (option) => {\n const answers = await inquirer.prompt([\n {\n type: \"select\",\n name: \"agentAction\",\n message: \"What agent action do you want to perform?\",\n choices: [\n {\n name: \"Run a migration on auro components\",\n value: AgentActions.RunMigration,\n },\n ],\n default: [AgentActions.RunMigration],\n },\n\n {\n type: \"input\",\n name: \"migrationId\",\n message: \"What migration id do you want to run?\",\n when: (answers) => answers.agentAction === AgentActions.RunMigration,\n validate: (input) =>\n input.trim() !== \"\" || \"Migration id cannot be empty.\",\n },\n\n {\n type: \"confirm\",\n name: \"useExisting\",\n message: \"Would you like to specify starting packages?\",\n default: true,\n transformer: (value) =>\n value ? \"Yes = Packages related to selections\" : \"No = All packages\",\n when: (answers) => answers.agentAction === AgentActions.RunMigration,\n },\n\n {\n type: \"checkbox\",\n name: \"startWithComponents\",\n message:\n \"Enter the components to start with (comma-separated, blank for all):\",\n choices: AURO_COMPONENT_PACKAGES.map((component) => ({\n name: component.replace(\"@aurodesignsystem/\", \"\"),\n value: component,\n })),\n when: (answers) =>\n answers.agentAction === AgentActions.RunMigration &&\n answers.useExisting,\n },\n ]);\n\n switch (answers.agentAction) {\n case AgentActions.RunMigration: {\n // Placeholder for actual migration logic\n const spinner = ora(\"Running migration...\").start();\n const dependencyTreePath = await getOrCreateDependencyTree(\n answers.startWithComponents,\n );\n\n spinner.text = \"Getting dependency batches from tree...\";\n const dependencyBatches =\n await getDependencyBatchesFromTree(dependencyTreePath);\n\n const batchedUpdateOrderText = dependencyBatches\n .map(\n (batch, index) =>\n `Batch ${index + 1}\\n${batch.map((pkg) => ` - ${pkg.replace(\"@aurodesignsystem\", \"AlaskaAirlines\").replace(\"@alaskaairux/icons\", \"AlaskaAirlines/Icons\")}`).join(\"\\n\")}`,\n )\n .join(\"\\n\\n\");\n\n console.log(batchedUpdateOrderText);\n\n spinner.text = \"Running migrations on dependency batches...\";\n // DO STUFF HERE :)\n\n new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate async operation\n spinner.succeed(\"Migration process completed successfully.\");\n\n // spinner.succeed(\"Migration process completed.\");\n break;\n }\n // Add more cases for additional actions as needed\n default:\n console.error(\"Unknown action selected.\");\n // spinner.fail(\"Unknown action selected.\");\n }\n});\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport ora from \"ora\";\n\nconst JsonConfig = {\n \"auth-type\": \"workspace-token\",\n \"author-email\": null,\n \"author-name\": null,\n \"base-branch\": \"main\",\n \"base-url\": null,\n \"clone-dir\": \".gitter-temp\",\n \"code-search\": null,\n concurrent: 4,\n \"conflict-strategy\": \"replace\",\n draft: false,\n \"dry-run\": true,\n \"fetch-depth\": 1,\n fork: false,\n \"fork-owner\": null,\n \"git-type\": \"go\",\n group: null,\n \"include-subgroups\": false,\n insecure: false,\n interactive: false,\n labels: null,\n \"log-file\": \"'-'\",\n \"log-format\": \"'text'\",\n \"log-level\": \"'error'\",\n \"max-reviewers\": 0,\n \"max-team-reviewers\": 0,\n org: null,\n output: \"'-'\",\n \"plain-output\": false,\n platform: \"github\",\n project: null,\n \"push-only\": false,\n repo: [\n \"AlaskaAirlines/auro-accordion\",\n \"AlaskaAirlines/auro-alert\",\n \"AlaskaAirlines/auro-avatar\",\n \"AlaskaAirlines/auro-background\",\n \"AlaskaAirlines/auro-backtotop\",\n \"AlaskaAirlines/auro-button\",\n \"AlaskaAirlines/auro-badge\",\n \"AlaskaAirlines/auro-banner\",\n \"AlaskaAirlines/auro-card\",\n \"AlaskaAirlines/auro-carousel\",\n \"AlaskaAirlines/auro-datetime\",\n \"AlaskaAirlines/auro-dialog\",\n \"AlaskaAirlines/auro-drawer\",\n \"AlaskaAirlines/auro-flight\",\n \"AlaskaAirlines/auro-flightline\",\n \"AlaskaAirlines/auro-header\",\n \"AlaskaAirlines/auro-hyperlink\",\n \"AlaskaAirlines/auro-icon\",\n \"AlaskaAirlines/auro-loader\",\n \"AlaskaAirlines/auro-lockup\",\n \"AlaskaAirlines/auro-nav\",\n \"AlaskaAirlines/auro-pane\",\n \"AlaskaAirlines/auro-popover\",\n \"AlaskaAirlines/auro-sidenav\",\n \"AlaskaAirlines/auro-skeleton\",\n \"AlaskaAirlines/auro-slideshow\",\n \"AlaskaAirlines/auro-table\",\n \"AlaskaAirlines/auro-tabs\",\n \"AlaskaAirlines/auro-toast\",\n // UNCOMMENT BELOW WHEN MAIN/MASTER BRANCHES ARE READY\n // \"AlaskaAirlines/AuroDocsSite\"\n ],\n \"repo-exclude\": null,\n \"repo-include\": null,\n \"repo-search\": null,\n reviewers: null,\n \"skip-forks\": false,\n \"skip-pr\": false,\n \"skip-repo\": null,\n \"ssh-auth\": false,\n \"team-reviewers\": null,\n};\n\nfunction toYaml(config) {\n return Object.entries(config)\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return `${key}:\\n - ${value.join(\"\\n - \")}`;\n }\n if (typeof value === \"object\" && value !== null) {\n return `${key}:\\n${Object.entries(value)\n .map(([k, v]) => ` ${k}: ${v}`)\n .join(\"\\n\")}`;\n }\n return `${key}: ${value}`;\n })\n .join(\"\\n\");\n}\n\nexport async function createMultiGitterDependencyTreeConfig(outputPath) {\n const spinner = ora(\"Writing multi-gitter configuration...\").start();\n const configContent = toYaml(JsonConfig);\n const configPath = path.join(outputPath, \"multi-gitter_DEPENDENCY_TREE.yml\");\n\n try {\n await fs.writeFile(configPath, configContent, \"utf8\");\n spinner.succeed(`Multi-gitter configuration written to ${configPath}`);\n } catch (error) {\n spinner.fail(\"Error writing multi-gitter configuration:\");\n console.error(error);\n }\n}\n", "import fs from \"node:fs\";\nimport path from \"node:path\";\n\ninterface PackageJsonExcerpt {\n name: string;\n peerDependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n dependencies: Record<string, string>;\n}\n\ninterface DependencyNode {\n dependsOn: string[];\n dependentPackages: string[];\n}\n\ntype DependencyTree = Record<string, DependencyNode>;\n\nexport function getBatchedUpdateOrder(\n dependencyTree: DependencyTree,\n): Array<string[]> {\n const inDegree: Record<string, number> = {};\n const batches: Array<string[]> = [];\n let currentBatch: string[] = [];\n const queue: string[] = [];\n\n // Initialize in-degree (count of dependencies for each package)\n for (const pkg in dependencyTree) {\n inDegree[pkg] = dependencyTree[pkg].dependsOn.length;\n }\n\n // Find packages with no dependencies (in-degree = 0)\n for (const pkg in inDegree) {\n if (inDegree[pkg] === 0) {\n queue.push(pkg);\n }\n }\n\n while (queue.length > 0) {\n currentBatch = [];\n // Process the queue (topological sorting)\n const queueLength = queue.length;\n for (let i = 0; i < queueLength; i++) {\n const current = queue.shift()!;\n currentBatch.push(current);\n\n // Reduce the in-degree of dependent packages\n for (const dependent of dependencyTree[current].dependentPackages) {\n inDegree[dependent]--;\n\n // If a package now has no dependencies, add it to the queue\n if (inDegree[dependent] === 0) {\n queue.push(dependent);\n }\n }\n }\n batches.push(currentBatch);\n }\n\n // If we couldn't process all packages, there is a circular dependency\n if (batches.flat().length !== Object.keys(dependencyTree).length) {\n throw new Error(\"Circular dependency detected!\");\n }\n\n return batches;\n}\n\nfunction getJsonFilesFromDirectory(directory: string): string[] {\n return fs.readdirSync(directory).filter((file) => file.endsWith(\".json\"));\n}\n\n/**\n * Formats the dependency tree for the specified target dependencies.\n * @param rawTargetDependencies {string[]} - List of target dependencies to format. Expects package names like \"button\", \"hyperlink\", etc. without the \"@aurodesignsystem/\" prefix.\n * @returns {Promise<DependencyTree>} - A promise that resolves to the formatted dependency tree.\n */\nexport async function formatDependencyTree(\n jsonFileDirectory: string,\n targetDependencies: string[] = [],\n): Promise<DependencyTree> {\n console.log(targetDependencies);\n let dependencyTree: DependencyTree = {};\n\n const files = getJsonFilesFromDirectory(jsonFileDirectory);\n\n for (const file of files) {\n // Skip the dependency tree file itself if it already exists\n if (file === \"dependencyTree.json\") {\n continue;\n }\n\n const contents = fs.readFileSync(`${jsonFileDirectory}/${file}`, \"utf-8\");\n const data: PackageJsonExcerpt = JSON.parse(contents);\n\n const packageName = data.name;\n const peerDependencies = Object.keys(data.peerDependencies);\n const devDependencies = Object.keys(data.devDependencies);\n const dependencies = Object.keys(data.dependencies);\n\n if (!dependencyTree[packageName]) {\n dependencyTree[packageName] = { dependsOn: [], dependentPackages: [] };\n }\n\n const allDependencies = [\n ...peerDependencies,\n ...devDependencies,\n ...dependencies,\n ];\n\n dependencyTree[packageName].dependsOn = [...new Set(allDependencies)];\n\n for (const dependency of allDependencies) {\n if (!dependencyTree[dependency]) {\n dependencyTree[dependency] = { dependsOn: [], dependentPackages: [] };\n }\n\n if (!dependencyTree[dependency].dependentPackages.includes(packageName)) {\n dependencyTree[dependency].dependentPackages.push(packageName);\n }\n }\n }\n\n // If there are no specified target dependencies, use all packages\n if (targetDependencies.length) {\n // If there ARE target dependencies, filter the dependency tree down to just relevant packages\n // A tree will start only include package that the target dependencies depend on, OR packages that depend on the target dependencies\n const relevantPackages = new Set<string>();\n\n // Include any packages that depend on a target dependency\n for (const [pkg, node] of Object.entries(dependencyTree)) {\n if (node.dependsOn.some((dep) => targetDependencies.includes(dep))) {\n relevantPackages.add(pkg);\n }\n }\n\n // Also include the target dependencies themselves\n for (const target of targetDependencies) {\n if (dependencyTree[target]) {\n relevantPackages.add(target);\n }\n }\n\n // Final filtered dependency tree\n const _filteredDependencyTree: DependencyTree = {};\n for (const pkg of relevantPackages) {\n _filteredDependencyTree[pkg] = {\n dependsOn: dependencyTree[pkg].dependsOn.filter((dep) =>\n relevantPackages.has(dep),\n ),\n dependentPackages: dependencyTree[pkg].dependentPackages.filter((dep) =>\n relevantPackages.has(dep),\n ),\n };\n }\n\n dependencyTree = _filteredDependencyTree;\n } else {\n console.log(\"No target dependencies provided - using all packages.\");\n }\n\n // Write the dependency tree to a file\n fs.writeFileSync(\n `${jsonFileDirectory}/dependencyTree.json`,\n JSON.stringify(dependencyTree, null, 2),\n );\n\n return dependencyTree;\n}\n", "/**\n * Candidate Auro component packages to check for a Custom Elements Manifest\n * (`custom-elements.json`) at their package root. Not every component publishes\n * one yet \u2014 the `auro cem` command fetches each and skips those that 404, so\n * this list can safely include components ahead of their CEM adoption.\n *\n * Keep this list in sync with the components published under the\n * `@aurodesignsystem/` npm scope. It intentionally includes the **legacy\n * standalone** form packages (`auro-input`, `auro-select`, `auro-combobox`,\n * `auro-menu`, `auro-checkbox`, `auro-radio`, `auro-datepicker`, `auro-dropdown`,\n * `auro-form`) that `auro-formkit` later absorbed: a consumer may still have a\n * standalone installed alongside `auro-formkit`, and both register the same\n * `auro-*` tag. `resolveComponents` detects that overlap and grounds the tag once\n * (warning which packages collide) \u2014 so the legacy packages must be candidates for\n * the overlap to be seen at all.\n */\nexport const AURO_COMPONENT_PACKAGES = [\n \"@aurodesignsystem/auro-accordion\",\n \"@aurodesignsystem/auro-alert\",\n \"@aurodesignsystem/auro-avatar\",\n \"@aurodesignsystem/auro-background\",\n \"@aurodesignsystem/auro-backtotop\",\n \"@aurodesignsystem/auro-badge\",\n \"@aurodesignsystem/auro-banner\",\n \"@aurodesignsystem/auro-button\",\n \"@aurodesignsystem/auro-card\",\n \"@aurodesignsystem/auro-carousel\",\n \"@aurodesignsystem/auro-checkbox\",\n \"@aurodesignsystem/auro-combobox\",\n \"@aurodesignsystem/auro-datepicker\",\n \"@aurodesignsystem/auro-datetime\",\n \"@aurodesignsystem/auro-dialog\",\n \"@aurodesignsystem/auro-drawer\",\n \"@aurodesignsystem/auro-dropdown\",\n \"@aurodesignsystem/auro-flight\",\n \"@aurodesignsystem/auro-flightline\",\n \"@aurodesignsystem/auro-form\",\n \"@aurodesignsystem/auro-formkit\",\n \"@aurodesignsystem/auro-header\",\n \"@aurodesignsystem/auro-hyperlink\",\n \"@aurodesignsystem/auro-icon\",\n \"@aurodesignsystem/auro-input\",\n \"@aurodesignsystem/auro-loader\",\n \"@aurodesignsystem/auro-lockup\",\n \"@aurodesignsystem/auro-menu\",\n \"@aurodesignsystem/auro-nav\",\n \"@aurodesignsystem/auro-pane\",\n \"@aurodesignsystem/auro-popover\",\n \"@aurodesignsystem/auro-radio\",\n \"@aurodesignsystem/auro-select\",\n \"@aurodesignsystem/auro-sidenav\",\n \"@aurodesignsystem/auro-skeleton\",\n \"@aurodesignsystem/auro-slideshow\",\n \"@aurodesignsystem/auro-table\",\n \"@aurodesignsystem/auro-tabs\",\n \"@aurodesignsystem/auro-tail\",\n \"@aurodesignsystem/auro-toast\",\n \"@aurodesignsystem/auro-tokenlist\",\n];\n", "import { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport { buildAggregateManifest } from \"#utils/aggregateManifest.js\";\n\n/** Options accepted by the `cem` action. */\nexport interface CemOptions {\n output: string;\n}\n\n/**\n * Fetch every published Auro component's canonical manifest, merge them into a\n * single aggregated `custom-elements.json`, and write it to `options.output`.\n * Exits non-zero when nothing could be fetched, the write fails, or any fetch\n * failed transiently (leaving the aggregate incomplete).\n */\nexport async function runCem(options: CemOptions): Promise<void> {\n const spinner = ora(\n `Fetching manifests for ${AURO_COMPONENT_PACKAGES.length} components...`,\n ).start();\n\n // Aggregate the canonical latest published manifests, not whatever happens\n // to be installed locally, so the index doesn't mix versions per machine.\n const {\n manifest: aggregate,\n sources,\n skipped,\n transientFailures,\n } = await buildAggregateManifest(AURO_COMPONENT_PACKAGES, {\n preferLocal: false,\n });\n\n if (sources.length === 0) {\n spinner.fail(\"No component manifests could be fetched.\");\n process.exit(1);\n }\n\n const outputPath = path.resolve(process.cwd(), options.output);\n try {\n await writeFile(\n outputPath,\n `${JSON.stringify(aggregate, null, 2)}\\n`,\n \"utf-8\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(`Failed to write ${options.output}: ${message}`);\n process.exit(1);\n }\n\n spinner.succeed(\n `Aggregated ${sources.length}/${AURO_COMPONENT_PACKAGES.length} component manifests (${aggregate.modules?.length ?? 0} modules) to ${options.output}`,\n );\n\n // Report skips after the spinner so output isn't garbled. Genuine 404s are\n // expected (not every component publishes a CEM yet); transient failures\n // mean the aggregate is incomplete and are treated as an error.\n for (const outcome of skipped) {\n // Transient failures are a subset of `skipped` but are reported as errors\n // below \u2014 don't also log them as deliberate \"Skipped\" (no CEM published).\n if (outcome.transient) continue;\n Logger.info(`Skipped ${outcome.target}: ${outcome.reason}`);\n }\n\n if (transientFailures.length > 0) {\n Logger.error(\n `${transientFailures.length} component(s) failed to fetch transiently; the aggregate may be incomplete. Re-run to retry.`,\n );\n process.exit(1);\n }\n}\n\nexport default program\n .command(\"cem\")\n .description(\n \"Fetch every published Auro component's custom-elements.json and merge them into a single aggregated manifest\",\n )\n .option(\n \"-o, --output <file>\",\n \"Path to write the aggregated manifest\",\n \"custom-elements.aggregate.json\",\n )\n .action(runCem);\n", "import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nconst UNPKG_BASE = \"https://unpkg.com\";\nconst REGISTRY_BASE = \"https://registry.npmjs.org\";\n\n/**\n * Abort a manifest request that stalls. Without this a single connection that\n * is accepted but never answered would hang the CLI indefinitely \u2014 `auro cem`\n * fetches every component concurrently via `Promise.all`, so one stalled\n * request would leave the whole command spinning forever.\n */\nconst REQUEST_TIMEOUT_MS = 10_000;\n\n/** Outcome of resolving a package's Custom Elements Manifest. */\nexport interface ManifestFetchResult {\n /** The npm package (or `package@tag`) that was requested. */\n target: string;\n /** Parsed custom-elements.json, or null when it could not be resolved. */\n manifest: unknown;\n /** Where the manifest was resolved from, when successful. */\n source?: \"local\" | \"unpkg\";\n /** Resolved package version. Currently only known for local reads. */\n version?: string;\n /** Human-readable reason the manifest was unavailable. */\n reason?: string;\n /** True when the failure was transient (network/5xx/parse), not a genuine 404. */\n transient?: boolean;\n}\n\n/** Options controlling how a manifest is resolved. */\nexport interface FetchManifestOptions {\n /**\n * Read an installed copy from the current directory's `node_modules` before\n * falling back to unpkg. Defaults to true. Only applies when `target` has no\n * explicit version/tag \u2014 an explicit ref means \"exactly this version\", which\n * the local install may not match.\n */\n preferLocal?: boolean;\n /**\n * Allow network (unpkg) fetches. Defaults to true. When false, only a local\n * read is attempted and a miss returns a non-transient result.\n */\n allowNetwork?: boolean;\n}\n\n/**\n * Split a target into its package name and optional version/tag. The scope's\n * leading `@` (`@scope/name`) is not a separator \u2014 only a later `@` is:\n * `@aurodesignsystem/auro-button@3.0.0` \u2192 `{ pkg, ref: \"3.0.0\" }`.\n */\nfunction parseTarget(target: string): { pkg: string; ref?: string } {\n const at = target.lastIndexOf(\"@\");\n if (at > 0) {\n return { pkg: target.slice(0, at), ref: target.slice(at + 1) };\n }\n return { pkg: target };\n}\n\n/**\n * Whether `child` resolves to `parent` itself or a path nested inside it \u2014\n * used to keep local reads confined to the intended directory.\n */\nfunction isInside(parent: string, child: string): boolean {\n const rel = path.relative(parent, child);\n return rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel));\n}\n\n/**\n * Attempt to read an installed package's manifest from the current directory's\n * `node_modules`. Returns null when the package isn't installed, or is installed\n * but ships no manifest (so the caller can fall back to unpkg). The manifest\n * path honors the package's `customElements` field, defaulting to\n * `custom-elements.json`.\n */\nasync function readLocalManifest(\n pkg: string,\n): Promise<ManifestFetchResult | null> {\n const modulesRoot = path.join(process.cwd(), \"node_modules\");\n const pkgDir = path.join(modulesRoot, ...pkg.split(\"/\"));\n // Defense-in-depth: package names come from the curated static list or the\n // user's own CLI argument (never untrusted network data), but a name with a\n // `..` segment could still resolve outside node_modules \u2014 refuse it.\n if (!isInside(modulesRoot, pkgDir)) {\n return null;\n }\n\n let version: string | undefined;\n let manifestRelPath = \"custom-elements.json\";\n try {\n const pkgJson = JSON.parse(\n await readFile(path.join(pkgDir, \"package.json\"), \"utf-8\"),\n );\n if (typeof pkgJson.version === \"string\") {\n version = pkgJson.version;\n }\n // The `customElements` field comes from the installed package's own\n // package.json; constrain it to the package directory so a malformed or\n // hostile value can't redirect the read at a file outside the package.\n if (\n typeof pkgJson.customElements === \"string\" &&\n isInside(pkgDir, path.resolve(pkgDir, pkgJson.customElements))\n ) {\n manifestRelPath = pkgJson.customElements;\n }\n } catch {\n // Not installed (or unreadable package.json) \u2014 no local copy.\n return null;\n }\n\n try {\n const manifest = JSON.parse(\n await readFile(path.join(pkgDir, manifestRelPath), \"utf-8\"),\n );\n return { target: pkg, manifest, source: \"local\", version };\n } catch {\n // Installed but ships no manifest \u2014 let the caller fall back to unpkg.\n return null;\n }\n}\n\n/**\n * Resolve a package's Custom Elements Manifest (`custom-elements.json`),\n * preferring a copy installed in the current directory's `node_modules` (so the\n * API shown matches the version the user actually has) and falling back to\n * unpkg for anything not installed. Never throws \u2014 failures are returned as a\n * result so callers can distinguish a genuine absence (404) from a transient\n * error. `target` may be a bare package name (`@aurodesignsystem/auro-button`)\n * or include a dist-tag or version (`@aurodesignsystem/auro-button@latest`).\n */\nexport async function fetchManifest(\n target: string,\n options: FetchManifestOptions = {},\n): Promise<ManifestFetchResult> {\n const { preferLocal = true, allowNetwork = true } = options;\n const { ref } = parseTarget(target);\n\n // Local-first only when no explicit version/tag was requested.\n if (preferLocal && !ref) {\n const local = await readLocalManifest(target);\n if (local) {\n return { ...local, target };\n }\n }\n\n if (!allowNetwork) {\n return {\n target,\n manifest: null,\n reason: \"not installed locally and network fetching is disabled\",\n };\n }\n\n const url = `${UNPKG_BASE}/${target}/custom-elements.json`;\n\n let response: Response;\n try {\n response = await fetch(url, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n const timedOut =\n error instanceof DOMException && error.name === \"TimeoutError\";\n const message = timedOut\n ? `timed out after ${REQUEST_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n return {\n target,\n manifest: null,\n reason: `request failed (${message})`,\n transient: true,\n };\n }\n\n if (response.status === 404) {\n return {\n target,\n manifest: null,\n reason: \"no custom-elements.json published\",\n };\n }\n\n if (!response.ok) {\n return {\n target,\n manifest: null,\n reason: `HTTP ${response.status}`,\n transient: true,\n };\n }\n\n try {\n return { target, manifest: await response.json(), source: \"unpkg\" };\n } catch {\n return {\n target,\n manifest: null,\n reason: \"custom-elements.json is not valid JSON\",\n transient: true,\n };\n }\n}\n\n/** A set of fetch outcomes split by how their failures should be treated. */\nexport interface OutcomePartition {\n /** Every outcome that yielded no manifest \u2014 genuine 404s and transient\n * failures alike (all are absent from the aggregate). */\n skipped: ManifestFetchResult[];\n /** The subset of skips that failed transiently. Their absence means a manifest\n * that *should* be present is missing, so any aggregate built from the\n * remaining sources is incomplete and the run should be treated as failed. */\n transientFailures: ManifestFetchResult[];\n}\n\n/**\n * Partition fetch outcomes into those that produced no manifest and, within\n * those, the ones that failed transiently. A genuine 404 is an expected skip\n * (not every package publishes a CEM), whereas a transient failure (network\n * error, timeout, 5xx, unparseable body) means an expected manifest is missing \u2014\n * distinguishing the two lets a caller skip the former but fail on the latter.\n */\nexport function partitionOutcomes(\n outcomes: ManifestFetchResult[],\n): OutcomePartition {\n const skipped = outcomes.filter((outcome) => !outcome.manifest);\n return {\n skipped,\n transientFailures: skipped.filter((outcome) => outcome.transient),\n };\n}\n\n/**\n * Fetch the latest published version of a package from the npm registry.\n * Returns null on any failure \u2014 staleness reporting is best-effort and must\n * never break the command that calls it.\n */\nexport async function fetchLatestVersion(pkg: string): Promise<string | null> {\n try {\n const response = await fetch(`${REGISTRY_BASE}/${pkg}/latest`, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n if (!response.ok) {\n return null;\n }\n const data = (await response.json()) as { version?: unknown };\n return typeof data.version === \"string\" ? data.version : null;\n } catch {\n return null;\n }\n}\n", "import { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport type { CemModule, Manifest } from \"#utils/cem.js\";\n\n/** A single package's manifest, paired with the package that published it. */\nexport interface ManifestSource {\n pkg: string;\n manifest: Manifest;\n}\n\n/**\n * Recursively namespace every local module reference in a CEM node with the\n * owning package. A reference is local only when it has a `module` string and\n * no `package` sibling (a `package` means it points at an external package, so\n * its `module` must be left untouched). This keeps the merged manifest's\n * internal references (exports' `declaration.module`, `references[].module`,\n * etc.) pointing at the same paths as their now-namespaced modules.\n */\nexport function namespaceReferences(node: unknown, pkg: string): unknown {\n if (Array.isArray(node)) {\n return node.map((item) => namespaceReferences(item, pkg));\n }\n\n if (node && typeof node === \"object\") {\n const source = node as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(source)) {\n if (\n key === \"module\" &&\n typeof value === \"string\" &&\n source.package == null\n ) {\n result[key] = `${pkg}/${value}`;\n } else {\n result[key] = namespaceReferences(value, pkg);\n }\n }\n return result;\n }\n\n return node;\n}\n\n/**\n * Merge per-package manifests into a single Custom Elements Manifest.\n * Every module (and its internal references) is namespaced with its package so\n * paths stay unique and every declaration remains traceable to its component.\n *\n * When the sources declare more than one distinct `schemaVersion`, the merge\n * still proceeds (using the first source's version for the aggregate) but a\n * warning is emitted, since a mixed-schema aggregate may not be internally\n * consistent. The warning sink is injectable so the behavior can be unit-tested\n * without capturing global logger output; it defaults to `Logger.warn`.\n */\nexport function mergeManifests(\n sources: ManifestSource[],\n warn: (message: string) => void = Logger.warn,\n): Manifest {\n const modules: CemModule[] = [];\n\n for (const { pkg, manifest } of sources) {\n for (const module of manifest.modules ?? []) {\n const namespaced = namespaceReferences(module, pkg) as CemModule;\n // Only namespace a real path. A spec-violating module that omits `path`\n // would otherwise be stored as the literal \"@scope/pkg/undefined\"; leave\n // its (absent) path untouched rather than fabricating a bogus one.\n if (typeof module.path === \"string\") {\n namespaced.path = `${pkg}/${module.path}`;\n }\n modules.push(namespaced);\n }\n }\n\n const schemaVersions = new Set(\n sources.map((source) => source.manifest.schemaVersion).filter(Boolean),\n );\n if (schemaVersions.size > 1) {\n warn(\n `Merging mixed CEM schema versions: ${[...schemaVersions].join(\", \")}`,\n );\n }\n\n return {\n schemaVersion: sources[0]?.manifest.schemaVersion ?? \"1.0.0\",\n modules,\n };\n}\n", "import type { Manifest } from \"#utils/cem.js\";\nimport {\n type FetchManifestOptions,\n fetchManifest,\n type ManifestFetchResult,\n partitionOutcomes,\n} from \"#utils/fetchManifest.js\";\nimport { type ManifestSource, mergeManifests } from \"#utils/mergeManifests.js\";\n\n/** The aggregated manifest plus the bookkeeping a caller needs to report on it. */\nexport interface AggregateManifestResult {\n /** The merged, namespaced manifest of every source that resolved. */\n manifest: Manifest;\n /** The per-package manifests that went into the merge. */\n sources: ManifestSource[];\n /** Outcomes that yielded no manifest (genuine 404s and transient alike). */\n skipped: ManifestFetchResult[];\n /** The subset of skips that failed transiently (the aggregate is incomplete). */\n transientFailures: ManifestFetchResult[];\n}\n\n/**\n * Fetch each package's Custom Elements Manifest, merge the ones that resolve into\n * a single aggregated manifest, and report what was skipped. Extracted from the\n * `cem` command so the fetch \u2192 merge \u2192 partition pipeline is reusable (by init's\n * resolver) instead of trapped in the command action. Fetch options pass through\n * to {@link fetchManifest}: `cem` aggregates the canonical published manifests\n * (`preferLocal: false`); init aggregates the installed versions (the default).\n *\n * Never fails on its own \u2014 an empty `sources` array still returns a valid (empty)\n * manifest. The caller decides whether zero sources or a transient failure is an\n * error, since that policy differs per command.\n */\nexport async function buildAggregateManifest(\n packages: readonly string[],\n options: FetchManifestOptions = {},\n): Promise<AggregateManifestResult> {\n const outcomes = await Promise.all(\n packages.map((pkg) => fetchManifest(pkg, options)),\n );\n\n const sources: ManifestSource[] = [];\n for (const outcome of outcomes) {\n if (outcome.manifest) {\n sources.push({\n pkg: outcome.target,\n manifest: outcome.manifest as Manifest,\n });\n }\n }\n\n const { skipped, transientFailures } = partitionOutcomes(outcomes);\n return {\n manifest: mergeManifests(sources),\n sources,\n skipped,\n transientFailures,\n };\n}\n", "/**\n * `auro cem-check <path>` \u2014 the executable CEM contract (layer 1 of the CEM\n * contract-enforcement effort). Validates a `custom-elements.json` two ways:\n *\n * - **Static rules** ([rules.ts](#init/cem-check/rules.ts)) report what auro-cli's\n * defensive prune would otherwise drop in silence \u2014 the missing producer signal.\n * - **Generation smoke** ([smoke.ts](#init/cem-check/smoke.ts)) runs the real\n * editor-type builders + `tsc` against the CEM, the authoritative consumer-path\n * check.\n *\n * Exit contract: `0` when no `error`-severity findings; `1` when any error (or, with\n * `--strict`, any warning). `--json` emits the findings array to stdout for the\n * `/auro` pr/code-review skills to parse; human output goes to stderr so stdout\n * stays machine-parseable.\n *\n * @see docs/cem-contract-enforcement.md\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport { type CemFinding, runContractRules } from \"#init/cem-check/rules.js\";\nimport { runGenerationSmoke } from \"#init/cem-check/smoke.js\";\nimport { resolveComponents } from \"#init/resolver.js\";\nimport type { Manifest } from \"#utils/cem.js\";\nimport type { InstalledComponent } from \"#utils/detectInstalled.js\";\n\n/** Options accepted by the `cem-check` action. */\nexport interface CemCheckOptions {\n /** Emit the findings array as JSON on stdout instead of human text. */\n json?: boolean;\n /** Treat warnings as errors \u2014 any finding then fails the check. */\n strict?: boolean;\n}\n\n/**\n * Derive the package identity for the CEM at `cemPath` from the `package.json`\n * beside it (so import specifiers match what the package publishes). Falls back to\n * a placeholder when the CEM is checked in isolation \u2014 generation-smoke stubs the\n * imports regardless, so the placeholder never blocks the check.\n */\nfunction readSiblingPackageJson(cemPath: string): {\n pkg: string;\n version: string;\n} {\n try {\n const raw = readFileSync(\n join(dirname(resolve(cemPath)), \"package.json\"),\n \"utf-8\",\n );\n const parsed = JSON.parse(raw) as { name?: string; version?: string };\n return {\n pkg: typeof parsed.name === \"string\" ? parsed.name : \"cem-check-subject\",\n version: typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\",\n };\n } catch {\n return { pkg: \"cem-check-subject\", version: \"0.0.0\" };\n }\n}\n\n/** Render one finding as a single stderr line. */\nfunction formatFinding(finding: CemFinding): string {\n const mark = finding.severity === \"error\" ? \"\u2716\" : \"\u26A0\";\n const where = [finding.element, finding.path].filter(Boolean).join(\" \");\n const locator = where ? ` ${where}` : \"\";\n return `${mark} [${finding.rule}]${locator}: ${finding.message}`;\n}\n\n/** The manifest looked for when no path is given \u2014 resolved against the cwd. */\nconst DEFAULT_CEM_PATH = \"custom-elements.json\";\n\n/**\n * Validate the CEM at `cemPath` against the contract and exit per the exit\n * contract. `cemPath` defaults to `custom-elements.json` in the directory the\n * command runs from, so running `auro cem-check` inside a component repo just\n * works; pass an explicit path to check a CEM elsewhere. A read/parse failure\n * exits 1 before any rule runs (an unreadable CEM is itself a failure).\n */\nexport async function runCemCheck(\n cemPath: string = DEFAULT_CEM_PATH,\n options: CemCheckOptions = {},\n): Promise<void> {\n // In `--json` mode nothing may touch stdout but the JSON payload, so the ora\n // spinner (which emits cursor/frame control bytes) is suppressed entirely and\n // progress/errors go to stderr instead.\n const spinner = options.json\n ? null\n : ora(`Checking ${cemPath} against the CEM contract...`).start();\n\n const fail = (message: string): never => {\n if (spinner) {\n spinner.fail(message);\n } else {\n console.error(message);\n }\n process.exit(1);\n };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(resolve(cemPath), \"utf-8\"));\n } catch (error) {\n fail(`Could not read or parse ${cemPath}: ${(error as Error).message}`);\n }\n\n // Valid JSON that is not a CEM object (top-level `null`, an array, or a\n // primitive) parses without throwing but has no `.modules` \u2014 resolving it would\n // throw an uncaught `TypeError` deep in the builders. Reject it here so the\n // failure is a clean exit 1 with a clear message, matching the parse-error path.\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n fail(`Could not read or parse ${cemPath}: not a CEM object.`);\n }\n const manifest = parsed as Manifest;\n\n const { pkg, version } = readSiblingPackageJson(cemPath);\n const installed: InstalledComponent[] = [{ pkg, version, manifest }];\n const { components } = resolveComponents(installed);\n\n const findings: CemFinding[] = [\n ...runContractRules(manifest),\n ...runGenerationSmoke(components),\n ];\n\n const errors = findings.filter((f) => f.severity === \"error\");\n const warnings = findings.filter((f) => f.severity === \"warn\");\n const failed =\n errors.length > 0 || (Boolean(options.strict) && warnings.length > 0);\n\n if (options.json) {\n // No spinner was started in JSON mode, so stdout carries only the payload.\n process.stdout.write(`${JSON.stringify(findings, null, 2)}\\n`);\n if (failed) {\n process.exit(1);\n }\n return;\n }\n\n const summary = `${errors.length} error${errors.length === 1 ? \"\" : \"s\"}, ${warnings.length} warning${warnings.length === 1 ? \"\" : \"s\"}`;\n if (failed) {\n spinner?.fail(`CEM contract failed \u2014 ${summary}.`);\n } else if (warnings.length > 0) {\n spinner?.warn(`CEM contract passed with warnings \u2014 ${summary}.`);\n } else {\n spinner?.succeed(\"CEM contract clean \u2014 no violations.\");\n }\n\n // Errors first, then warnings; each on its own stderr line.\n for (const finding of [...errors, ...warnings]) {\n console.error(formatFinding(finding));\n }\n\n if (failed) {\n process.exit(1);\n }\n}\n\nexport default program\n .command(\"cem-check [path]\")\n .description(\n \"Validate a custom-elements.json against the CEM contract (structural + parseability rules and an end-to-end generation smoke). Defaults to ./custom-elements.json.\",\n )\n .option(\"--json\", \"Output the findings as a JSON array on stdout\", false)\n .option(\"--strict\", \"Treat warnings as errors (any finding fails)\", false)\n .action(runCemCheck);\n", "/**\n * Shared plumbing for the three per-target editor builders\n * (./htmlCustomData.ts, ./jsxTypes.ts, ./svelteTypes.ts). It owns the two seams\n * every builder needs \u2014 the resolved-tag lookup and the synthetic manifest the\n * community tools consume \u2014 plus the temp-dir shim that discards the files those\n * tools insist on writing. The builders stay pure functions of\n * `(components, resolvedTags)`; all the \"turn our model into their input\" glue\n * lives here so it is defined once and cannot drift between targets.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Tag-swap seam /\n * Class-import seam\" and build-order step 2.\n */\n\nimport { mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\nimport type { CemAttribute, CemDeclaration, Manifest } from \"#utils/cem.js\";\n\n/**\n * Blank out string/template-literal contents (replacing each with a space to keep\n * surrounding offsets stable) so a bracket **inside** a quoted string-literal type\n * member \u2014 e.g. the `>` in `'\">\" | \"none\"'`, a perfectly valid union \u2014 isn't\n * mistaken for an unbalanced delimiter. Shared by {@link hasBalancedDelimiters}\n * and the `cem-check` type rules so the *check* and the silent *prune* judge the\n * same text.\n */\nexport function withoutStringLiterals(text: string): string {\n return text.replace(/(['\"`])(?:\\\\.|(?!\\1)[\\s\\S])*\\1/gu, \" \");\n}\n\n/**\n * True when every bracket pair (`()[]{}<>`) in `text` is balanced, treating a\n * `=>` arrow as text rather than a generic close and ignoring brackets that live\n * **inside** string/template literals (a quoted `\">\"` is a valid literal member,\n * not an unbalanced close). The community JSX/Svelte tools splice a CEM\n * `type.text` verbatim into generated TypeScript, so a truncated or garbled type \u2014\n * e.g. auro-formkit's `auroDropdown-idAdded` event ships the type `\"Object<key\"` \u2014\n * yields output no parser (prettier/tsc) can read. A cheap balance check is enough\n * to catch these real-world defects without trying to be a TypeScript parser;\n * anything that fails it is dropped so the generator falls back to its default\n * handler/prop type.\n */\nexport function hasBalancedDelimiters(text: string): boolean {\n const closeToOpen: Record<string, string> = {\n \")\": \"(\",\n \"]\": \"[\",\n \"}\": \"{\",\n \">\": \"<\",\n };\n const stack: string[] = [];\n let prev = \"\";\n for (const ch of withoutStringLiterals(text)) {\n if (ch === \">\" && prev === \"=\") {\n // `=>` arrow \u2014 not a generic close.\n prev = ch;\n continue;\n }\n if (ch === \"(\" || ch === \"[\" || ch === \"{\" || ch === \"<\") {\n stack.push(ch);\n } else if (ch === \")\" || ch === \"]\" || ch === \"}\" || ch === \">\") {\n if (stack.pop() !== closeToOpen[ch]) {\n return false;\n }\n }\n prev = ch;\n }\n return stack.length === 0;\n}\n\n/**\n * Strip an entry's `type` when its `type.text` is present but malformed (see\n * {@link hasBalancedDelimiters}), leaving a well-formed entry the generators can\n * fall back to a default type for. A slightly looser type (`CustomEvent`,\n * `unknown`) beats an artifact no compiler accepts.\n */\nfunction withSafeType<T extends { type?: { text?: string } }>(entry: T): T {\n const text = entry.type?.text;\n if (typeof text === \"string\" && text !== \"\" && !hasBalancedDelimiters(text)) {\n const { type: _dropped, ...rest } = entry;\n return rest as T;\n }\n return entry;\n}\n\n/**\n * True when `attribute` merely reflects an internal (private or omitted) property\n * and carries no documentation of its own \u2014 e.g. auro-button's `data-hover` /\n * `data-active`, reflected from its `@private onHover` / `onActive` members. The\n * CEM analyzer derives an attribute from a property's `attribute:` / `reflect:`\n * options **independently of the property's `privacy`**, so `@private` (or\n * `@ignore`) on the source suppresses the *member* but still emits the\n * *attribute* as a public, description-less entry \u2014 which then leaks into editor\n * autocomplete as something a consumer might set, when it never should.\n *\n * We treat an attribute as such a leak when its backing member (`fieldName`) is\n * private/protected, or absent from the (pruned) member list \u2014 meaning the\n * property was intentionally omitted, e.g. dropped as `@private` \u2014 **and** the\n * attribute has no description. The no-description guard deliberately preserves\n * documented reflections a component *does* expose on purpose (e.g. a11y\n * `role` / `aria-*` attributes carrying real descriptions). An attribute with no\n * `fieldName` has no backing member to judge and is always kept.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 Risks/open questions, \"Private-reflected\n * attributes leak into autocomplete\".\n */\nexport function isPrivateReflection(\n attribute: CemAttribute,\n memberPrivacyByName: ReadonlyMap<string, string | undefined>,\n): boolean {\n const { fieldName, description } = attribute;\n if (typeof fieldName !== \"string\" || fieldName === \"\") {\n return false; // no backing member to judge \u2014 keep it\n }\n if (typeof description === \"string\" && description !== \"\") {\n return false; // deliberately documented \u2014 keep it\n }\n if (!memberPrivacyByName.has(fieldName)) {\n return true; // backing property omitted (e.g. pruned as @private)\n }\n const privacy = memberPrivacyByName.get(fieldName);\n return privacy === \"private\" || privacy === \"protected\";\n}\n\n/**\n * Normalise a CEM declaration into something the community JSX/Svelte/HTML\n * generators reliably accept:\n *\n * 1. Drop entries whose `name` is not a string from every named collection\n * (members, attributes, slots, events, css parts/properties). The schema\n * types these as required, but real manifests ship the odd nameless entry \u2014\n * e.g. auro-formkit's `auro-menu` has a `{ kind: \"field\", type, default }`\n * member with no `name` \u2014 and the tools call `member.name.startsWith(\"#\")`,\n * throwing mid-generation. A nameless member can't become a typed prop anyway.\n * (An empty-string name is kept \u2014 it is the valid default-slot name.)\n * 2. Drop a malformed `type.text` from members/attributes/events (see\n * {@link withSafeType}) so a garbled type can't produce unparseable output.\n * 3. Drop attributes that merely reflect a private/omitted property and carry no\n * description (see {@link isPrivateReflection}) so an internal reflection like\n * `data-hover` never leaks into editor autocomplete as a settable attribute.\n *\n * Everything else on the declaration is preserved verbatim.\n */\nfunction withNamedEntriesPruned(declaration: CemDeclaration): CemDeclaration {\n const hasName = (entry: { name?: unknown }): boolean =>\n typeof entry.name === \"string\";\n const members = declaration.members?.filter(hasName).map(withSafeType);\n // Backing-member privacy for the private-reflection guard, keyed by member\n // name. Built from the pruned members (nameless entries can't be a fieldName\n // target); an attribute whose fieldName is missing here reflects an omitted\n // property.\n const memberPrivacyByName = new Map<string, string | undefined>(\n (members ?? []).map((member) => [member.name, member.privacy]),\n );\n return {\n ...declaration,\n ...(members && { members }),\n ...(declaration.attributes && {\n attributes: declaration.attributes\n .filter(hasName)\n .filter(\n (attribute) => !isPrivateReflection(attribute, memberPrivacyByName),\n )\n .map(withSafeType),\n }),\n ...(declaration.slots && { slots: declaration.slots.filter(hasName) }),\n ...(declaration.events && {\n events: declaration.events.filter(hasName).map(withSafeType),\n }),\n ...(declaration.cssParts && {\n cssParts: declaration.cssParts.filter(hasName),\n }),\n ...(declaration.cssProperties && {\n cssProperties: declaration.cssProperties.filter(hasName),\n }),\n };\n}\n\n/** An editor artifact `auro init` writes: its project-root-relative path + body. */\nexport interface EditorArtifact {\n /**\n * The file to write, relative to the project root, using forward slashes\n * (e.g. `.vscode/auro.html-custom-data.json`). `init` splits on `/` to join it\n * onto the target OS's path separator.\n */\n filename: string;\n /** The complete file contents, newline-terminated. */\n contents: string;\n}\n\n/**\n * The tag a consumer actually registers for a component: its resolved\n * custom/prefixed tag when the registry provided one (keyed by the canonical\n * bare `auro-*` tag), else the canonical tag itself. Mirrors the generator's\n * `displayTag` so every target keys on the same resolved tag \u2014 never the bare\n * `auro-*` tag \u2014 and an absent entry simply means \"no custom registration\".\n */\nexport function resolvedTagFor(\n component: ResolvedComponent,\n resolvedTags: ReadonlyMap<string, string>,\n): string {\n return resolvedTags.get(component.tagName) ?? component.tagName;\n}\n\n/**\n * A map from each component's class name to the module specifier it should be\n * imported from \u2014 the component's `importPath` (package root for a standalone,\n * subpath export for a monorepo component). The JSX and Svelte tools take a\n * `componentTypePath` callback keyed by class name; this feeds it so the emitted\n * `import type { AuroButton } from \"\u2026\"` points at the installed package, not the\n * CEM's internal `src/auro-button.js` path.\n */\nexport function importPathsByClass(\n components: readonly ResolvedComponent[],\n): Map<string, string> {\n return new Map(components.map((c) => [c.declaration.name, c.importPath]));\n}\n\n/**\n * Assemble a Custom Elements Manifest the community tools can consume from our\n * flat `ResolvedComponent[]`: one `javascript-module` per component, its `path`\n * set to the component's `importPath` so any manifest-derived import resolves to\n * the installed package. Each declaration is emitted verbatim EXCEPT its\n * `tagName`, which is set via {@link resolvedTagFor} when `resolvedTags` is\n * given \u2014 the pre-swap seam the HTML and Svelte targets rely on (they have no\n * per-tag formatter hook). The JSX target omits `resolvedTags` (keeping the bare\n * `auro-*` tags) and swaps via the tool's `tagFormatter` instead.\n */\nexport function buildManifest(\n components: readonly ResolvedComponent[],\n resolvedTags?: ReadonlyMap<string, string>,\n): Manifest {\n return {\n schemaVersion: \"1.0.0\",\n modules: components.map((component) => {\n const declaration: CemDeclaration = withNamedEntriesPruned({\n ...component.declaration,\n tagName: resolvedTags\n ? resolvedTagFor(component, resolvedTags)\n : component.tagName,\n });\n return {\n kind: \"javascript-module\",\n path: component.importPath,\n declarations: [declaration],\n exports: [\n {\n kind: \"js\",\n name: declaration.name,\n declaration: {\n name: declaration.name,\n module: component.importPath,\n },\n },\n ],\n };\n }),\n };\n}\n\n/**\n * Run `fn` with a throwaway temp directory, always removing it afterward. The\n * three community tools each insist on writing their output to a file on disk;\n * the builders point them at this scratch dir and either use the string they\n * also return (HTML/JSX) or read the written file back (Svelte), so nothing ever\n * lands in the consumer's project except the artifact `init` writes itself.\n */\nexport function withTempDir<T>(fn: (dir: string) => T): T {\n const dir = mkdtempSync(join(tmpdir(), \"auro-editors-\"));\n try {\n return fn(dir);\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\n/** Guarantee exactly one trailing newline, matching the grounding-file convention. */\nexport function ensureTrailingNewline(contents: string): string {\n return contents.endsWith(\"\\n\") ? contents : `${contents}\\n`;\n}\n\n/**\n * The standard WAI-ARIA state/property attributes plus a `data-*` catch-all \u2014 the\n * accessibility/data global attributes the community JSX/Svelte tools omit from\n * their hardcoded `BaseProps`. Each generated element type\n * (`Partial<Props & BaseProps & BaseEvents>`) *replaces* the tag's intrinsic\n * element type, so any attribute absent here is flagged as unknown \u2014 without this\n * block `<auro-button aria-label=\"Save\" />` errors as an unknown prop.\n *\n * Value types mirror React's `AriaAttributes`; boolean-ish unions are inlined\n * (`boolean | \"true\" | \"false\"`) so the whole block is a single splice needing no\n * extra top-level alias. The `data-*` entry is a **template-literal** index\n * signature (not `[key: string]`), so it constrains only `data-*` keys and does\n * not force the tools' existing `style` / `ref` / `tabIndex` members to conform.\n * Lines are 2-space indented to match the tools' prettier output. `role` and\n * `tabindex` are not here \u2014 the JSX tool already emits them (as `role` / camelCase\n * `tabIndex`); {@link injectGlobalAttributes} prepends the lowercase Svelte forms\n * ({@link SVELTE_GLOBAL_MEMBERS}) for the Svelte target, whose `BaseProps` lacks them.\n */\nconst GLOBAL_ARIA_ATTRS = ` /** Identifies the currently active descendant of a composite widget. */\n \"aria-activedescendant\"?: string;\n /** Whether assistive technologies present all, or only parts of, changed regions. */\n \"aria-atomic\"?: boolean | \"true\" | \"false\";\n /** Whether inputting text triggers display of one or more predictions. */\n \"aria-autocomplete\"?: \"none\" | \"inline\" | \"list\" | \"both\";\n /** Defines a string value that labels the current element (braille). */\n \"aria-braillelabel\"?: string;\n /** Defines a human-readable, author-localized abbreviated role description (braille). */\n \"aria-brailleroledescription\"?: string;\n /** Whether an element is being modified and assistive technologies may wait. */\n \"aria-busy\"?: boolean | \"true\" | \"false\";\n /** The current \"checked\" state of checkboxes, radio buttons, and other widgets. */\n \"aria-checked\"?: boolean | \"false\" | \"mixed\" | \"true\";\n /** Defines the total number of columns in a table, grid, or treegrid. */\n \"aria-colcount\"?: number;\n /** Defines an element's column index or position within a table, grid, or treegrid. */\n \"aria-colindex\"?: number;\n /** A human-readable text alternative of aria-colindex. */\n \"aria-colindextext\"?: string;\n /** Defines the number of columns spanned by a cell or gridcell. */\n \"aria-colspan\"?: number;\n /** Identifies the element(s) whose contents or presence are controlled by this element. */\n \"aria-controls\"?: string;\n /** The element that represents the current item within a container or set. */\n \"aria-current\"?: boolean | \"false\" | \"true\" | \"page\" | \"step\" | \"location\" | \"date\" | \"time\";\n /** Identifies the element(s) that describes the object. */\n \"aria-describedby\"?: string;\n /** Defines a string value that describes or annotates the current element. */\n \"aria-description\"?: string;\n /** Identifies the element that provides a detailed, extended description. */\n \"aria-details\"?: string;\n /** Whether the element is perceivable but disabled, so not editable or operable. */\n \"aria-disabled\"?: boolean | \"true\" | \"false\";\n /** What functions can be performed when a dragged object is released. */\n \"aria-dropeffect\"?: \"none\" | \"copy\" | \"execute\" | \"link\" | \"move\" | \"popup\";\n /** Identifies the element that provides an error message for the object. */\n \"aria-errormessage\"?: string;\n /** Whether the element, or another grouping element it controls, is expanded. */\n \"aria-expanded\"?: boolean | \"true\" | \"false\";\n /** The next element(s) in an alternate reading order of content. */\n \"aria-flowto\"?: string;\n /** Whether an element is in a \"grabbed\" state in a drag-and-drop operation. */\n \"aria-grabbed\"?: boolean | \"true\" | \"false\";\n /** Indicates the availability and type of an interactive popup element. */\n \"aria-haspopup\"?: boolean | \"false\" | \"true\" | \"menu\" | \"listbox\" | \"tree\" | \"grid\" | \"dialog\";\n /** Whether the element is exposed to an accessibility API. */\n \"aria-hidden\"?: boolean | \"true\" | \"false\";\n /** Whether the entered value does not conform to the expected format. */\n \"aria-invalid\"?: boolean | \"false\" | \"true\" | \"grammar\" | \"spelling\";\n /** Keyboard shortcuts an author has implemented to activate or focus an element. */\n \"aria-keyshortcuts\"?: string;\n /** A string value that labels the current element. */\n \"aria-label\"?: string;\n /** Identifies the element(s) that labels the current element. */\n \"aria-labelledby\"?: string;\n /** Defines the hierarchical level of an element within a structure. */\n \"aria-level\"?: number;\n /** Indicates that an element will be updated, and how live updates are described. */\n \"aria-live\"?: \"off\" | \"assertive\" | \"polite\";\n /** Whether an element is modal when displayed. */\n \"aria-modal\"?: boolean | \"true\" | \"false\";\n /** Whether a text box accepts multiple lines of input or only a single line. */\n \"aria-multiline\"?: boolean | \"true\" | \"false\";\n /** Whether the user may select more than one item from the current selectable descendants. */\n \"aria-multiselectable\"?: boolean | \"true\" | \"false\";\n /** Whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */\n \"aria-orientation\"?: \"horizontal\" | \"vertical\";\n /** Identifies an element in order to define a visual, functional, or contextual relationship. */\n \"aria-owns\"?: string;\n /** A short hint intended to aid the user with data entry when the control has no value. */\n \"aria-placeholder\"?: string;\n /** The number or position of an item in the current set of listitems or treeitems. */\n \"aria-posinset\"?: number;\n /** The current \"pressed\" state of toggle buttons. */\n \"aria-pressed\"?: boolean | \"false\" | \"mixed\" | \"true\";\n /** Whether the element is not editable but is otherwise operable. */\n \"aria-readonly\"?: boolean | \"true\" | \"false\";\n /** What notifications the user agent triggers when the accessibility tree is modified. */\n \"aria-relevant\"?: \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text\" | \"text additions\" | \"text removals\";\n /** Whether user input is required on the element before a form may be submitted. */\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /** A human-readable, author-localized description for the role of an element. */\n \"aria-roledescription\"?: string;\n /** Defines the total number of rows in a table, grid, or treegrid. */\n \"aria-rowcount\"?: number;\n /** Defines an element's row index or position within a table, grid, or treegrid. */\n \"aria-rowindex\"?: number;\n /** A human-readable text alternative of aria-rowindex. */\n \"aria-rowindextext\"?: string;\n /** Defines the number of rows spanned by a cell or gridcell. */\n \"aria-rowspan\"?: number;\n /** The current \"selected\" state of various widgets. */\n \"aria-selected\"?: boolean | \"true\" | \"false\";\n /** Defines the number of items in the current set of listitems or treeitems. */\n \"aria-setsize\"?: number;\n /** Indicates if items in a table or grid are sorted in ascending or descending order. */\n \"aria-sort\"?: \"none\" | \"ascending\" | \"descending\" | \"other\";\n /** Defines the maximum allowed value for a range widget. */\n \"aria-valuemax\"?: number;\n /** Defines the minimum allowed value for a range widget. */\n \"aria-valuemin\"?: number;\n /** Defines the current value for a range widget. */\n \"aria-valuenow\"?: number;\n /** Defines the human-readable text alternative of aria-valuenow. */\n \"aria-valuetext\"?: string;\n /** Custom data-* attributes for the element. */\n [key: \\`data-\\${string}\\`]: string | number | boolean | null | undefined;\n`;\n\n/** Matches the opening of the tool-generated `BaseProps` block (JSX form is generic). */\nconst BASE_PROPS_OPEN = /(type BaseProps(?:<[^>]*>)? = \\{\\n)/;\n\n/**\n * Lowercase HTML global attributes the Svelte tool omits or React-cases, prepended\n * for the Svelte target only. Svelte markup uses the native lowercase attribute\n * names (`role`, `tabindex`), but the tool's `BaseProps` lacks `role` entirely and\n * spells tab order as React's camelCase `tabIndex` \u2014 so `<auro-button tabindex=\"0\">`\n * is flagged as an unknown prop. The JSX tool already emits both `role` and\n * `tabIndex`, so these are not prepended there (see {@link injectGlobalAttributes}).\n * `tabindex` is typed `number`, matching the tool's `tabIndex`; svelte2tsx coerces\n * the string literal in `tabindex=\"0\"` to it.\n */\nconst SVELTE_GLOBAL_MEMBERS =\n \" /** Defines the element's semantic role for accessibility APIs. */\\n\" +\n \" role?: string;\\n\" +\n \" /** The position of the element in the sequential keyboard navigation order. */\\n\" +\n \" tabindex?: number;\\n\";\n\n/**\n * Splice the standard ARIA / `data-*` global attributes ({@link GLOBAL_ARIA_ATTRS})\n * into a generated file's `BaseProps` block, immediately after its opening brace \u2014\n * mirroring how `NATIVE_DOM_EVENTS` is folded into `BaseEvents`. Pass\n * `svelteGlobals: true` for the Svelte target, whose `BaseProps` also lacks the\n * lowercase HTML globals ({@link SVELTE_GLOBAL_MEMBERS} \u2014 `role`, `tabindex`); the\n * JSX tool already emits those, so pass `svelteGlobals: false` there to avoid\n * duplicate members.\n *\n * Throws if the `BaseProps` opening is absent (e.g. an upstream reflow of the\n * community tool) rather than returning the string unchanged \u2014 a silent no-op\n * would ship element types that reject `aria-*`, so we surface the drift as a\n * loud, test-caught failure, matching `globalizeSvelteNamespace`'s convention.\n */\nexport function injectGlobalAttributes(\n contents: string,\n { svelteGlobals }: { svelteGlobals: boolean },\n): string {\n if (!BASE_PROPS_OPEN.test(contents)) {\n throw new Error(\n \"the JSX/Svelte generator no longer emits a recognizable `type BaseProps = {` \" +\n \"block; the global-attribute injection in manifest.ts must be updated to match.\",\n );\n }\n const block = `${svelteGlobals ? SVELTE_GLOBAL_MEMBERS : \"\"}${GLOBAL_ARIA_ATTRS}`;\n return contents.replace(BASE_PROPS_OPEN, `$1${block}`);\n}\n", "import { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport type { Manifest } from \"#utils/cem.js\";\nimport {\n fetchManifest,\n type ManifestFetchResult,\n} from \"#utils/fetchManifest.js\";\n\n/** A component package resolved from the current project's `node_modules`. */\nexport interface InstalledComponent {\n /** The installed npm package, e.g. `@aurodesignsystem/auro-button`. */\n pkg: string;\n /** The installed version, read from the package's own `package.json`. */\n version: string;\n /** The package's parsed `custom-elements.json`. */\n manifest: Manifest;\n}\n\n/**\n * Pick the locally installed components out of a set of manifest fetch outcomes.\n * Pure and side-effect-free: an outcome counts as installed only when it was\n * resolved from local `node_modules` (`source: \"local\"`) and carries both a\n * parsed manifest and a version. Shared by {@link detectInstalled} and the\n * `context` command so the \"scan node_modules + capture the installed version\"\n * rule lives in exactly one place.\n */\nexport function installedFromOutcomes(\n outcomes: readonly ManifestFetchResult[],\n): InstalledComponent[] {\n const installed: InstalledComponent[] = [];\n for (const outcome of outcomes) {\n if (outcome.source === \"local\" && outcome.manifest && outcome.version) {\n installed.push({\n pkg: outcome.target,\n version: outcome.version,\n manifest: outcome.manifest as Manifest,\n });\n }\n }\n return installed;\n}\n\n/**\n * Detect which Auro component packages are installed in the current directory's\n * `node_modules`, capturing each one's installed version and manifest. Local\n * reads only \u2014 never hits the network \u2014 so the result reflects exactly what the\n * project has installed (the version-pinned set `auro init` grounds against).\n * Defaults to the curated candidate list; pass an explicit set to scope the scan.\n */\nexport async function detectInstalled(\n packages: readonly string[] = AURO_COMPONENT_PACKAGES,\n): Promise<InstalledComponent[]> {\n const outcomes = await Promise.all(\n packages.map((pkg) => fetchManifest(pkg, { allowNetwork: false })),\n );\n return installedFromOutcomes(outcomes);\n}\n", "/**\n * The single data module PT-M1 isolates behind one seam (per the ticket): detect\n * the installed Auro packages, resolve each at its installed version, and\n * normalise both single-component and aggregated multi-component (monorepo) CEMs\n * into one flat `ResolvedComponent[]`. Everything downstream \u2014 tag resolution\n * (`registry.ts`) and generation (`generator.ts`) \u2014 consumes that flat list, so a\n * Phase-2 shared core can replace this module without touching the generator.\n */\n\nimport type { CemDeclaration, Manifest } from \"#utils/cem.js\";\nimport {\n detectInstalled,\n type InstalledComponent,\n} from \"#utils/detectInstalled.js\";\n\n/** One installed Auro custom element, normalised for grounding-file generation. */\nexport interface ResolvedComponent {\n /** The npm package that ships this component. */\n pkg: string;\n /**\n * The installed version of {@link pkg}. A multi-component package shares one\n * version across every component it ships.\n */\n version: string;\n /**\n * The component's canonical, bare `auro-*` tag as declared in the manifest \u2014\n * the stable identity used as the `auro.config.json` key and the subpath\n * segment. Any custom/prefixed tag is applied later by the generator using\n * `registry.ts` output; the resolver never renames a component.\n */\n tagName: string;\n /** The element's Custom Elements Manifest declaration (its full API surface). */\n declaration: CemDeclaration;\n /**\n * The module specifier to import this component from: the package root for a\n * standalone package (`@aurodesignsystem/auro-button`), or the per-component\n * subpath export for a multi-component package\n * (`@aurodesignsystem/auro-formkit/auro-input`).\n */\n importPath: string;\n /** True when {@link pkg} ships more than one registered element. */\n isMonorepo: boolean;\n}\n\n/** A tag registered by more than one installed package (a dedupe conflict). */\nexport interface DuplicateTag {\n /** The canonical bare `auro-*` tag registered by multiple packages. */\n tagName: string;\n /** The installed packages that all register {@link tagName}, in resolve order. */\n packages: string[];\n}\n\n/** The normalised component set plus any cross-package tag conflicts. */\nexport interface ResolveResult {\n /**\n * Every installed component, flattened across single- and multi-component\n * packages, in package-detection order then manifest-declaration order.\n */\n components: ResolvedComponent[];\n /**\n * Tags registered by more than one installed package \u2014 the legacy-standalone\n * vs monorepo overlap the generator warns on (never silently drops).\n */\n duplicates: DuplicateTag[];\n}\n\n/**\n * Pull every registered custom element out of a single package's manifest. A\n * declaration counts only when it is a real registered element \u2014 `customElement`\n * with a `tagName` \u2014 since an internal base class can be `customElement: true`\n * yet carry no tag. Module and declaration order is preserved for deterministic\n * output.\n */\nexport function registeredElements(manifest: Manifest): CemDeclaration[] {\n return (manifest.modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName);\n}\n\n/**\n * Normalise the installed packages into a flat component list, deriving each\n * component's import specifier and flagging any tag registered by more than one\n * package. Pure and side-effect-free \u2014 the network/fs work is done upstream by\n * {@link detectInstalled} \u2014 so it can be unit-tested against synthetic manifests.\n *\n * A package is treated as multi-component (\"monorepo\") when its manifest registers\n * more than one element; each of those components imports via its subpath export\n * (`<pkg>/<tag>`, e.g. `@aurodesignsystem/auro-formkit/auro-input`), while a\n * standalone package imports from its root. The subpath segment is the component's\n * canonical bare `auro-*` tag, which matches Auro's per-component export names.\n *\n * A tag registered by more than one installed package (the legacy standalone vs\n * `auro-formkit` monorepo overlap) is **grounded once** \u2014 the first-detected\n * package wins \u2014 and every colliding package is recorded in `duplicates` so the\n * command warns which packages the tag came from. Detection order follows the\n * installed order, so the winner is deterministic.\n */\nexport function resolveComponents(\n installed: readonly InstalledComponent[],\n): ResolveResult {\n const components: ResolvedComponent[] = [];\n // tag -> the packages that register it, insertion-ordered, for duplicate\n // detection. A package appears at most once per tag.\n const owningPackages = new Map<string, string[]>();\n // Tags already emitted to `components`, so a duplicate tag is grounded once.\n const grounded = new Set<string>();\n\n for (const { pkg, version, manifest } of installed) {\n const elements = registeredElements(manifest);\n // The import shape is per-package: >1 registered element means the package\n // ships per-component subpath exports (an aggregated monorepo CEM).\n const isMonorepo = elements.length > 1;\n for (const declaration of elements) {\n const tagName = declaration.tagName as string;\n\n // Record every package that registers this tag (for the dedupe warning),\n // before deciding whether to ground it.\n const owners = owningPackages.get(tagName);\n if (owners) {\n if (!owners.includes(pkg)) {\n owners.push(pkg);\n }\n } else {\n owningPackages.set(tagName, [pkg]);\n }\n\n // Ground each canonical tag exactly once: the first package to register it\n // wins. A later package's registration is flagged as a duplicate (above),\n // never grounded a second time.\n if (grounded.has(tagName)) {\n continue;\n }\n grounded.add(tagName);\n components.push({\n pkg,\n version,\n tagName,\n declaration,\n importPath: isMonorepo ? `${pkg}/${tagName}` : pkg,\n isMonorepo,\n });\n }\n }\n\n const duplicates: DuplicateTag[] = [];\n for (const [tagName, packages] of owningPackages) {\n if (packages.length > 1) {\n duplicates.push({ tagName, packages });\n }\n }\n\n return { components, duplicates };\n}\n\n/**\n * Detect the installed Auro packages in the current project and normalise them\n * into a {@link ResolveResult}. Delegates detection to {@link detectInstalled}\n * (local-only, version-pinned) and normalisation to {@link resolveComponents}.\n * Pass an explicit package set to scope the scan; defaults to the curated\n * candidate list.\n */\nexport async function resolveInstalled(\n packages?: readonly string[],\n): Promise<ResolveResult> {\n const installed = await detectInstalled(packages);\n return resolveComponents(installed);\n}\n", "/**\n * The static half of `auro cem-check`: read the **raw** CEM declarations and\n * *report* what auro-cli's defensive prune ([manifest.ts](../editors/manifest.ts)\n * `buildManifest`) would otherwise drop in silence. The prune is a safety net that\n * keeps generation working but hides the defect from the component team; these\n * rules surface the same conditions as a producer-visible signal.\n *\n * Every rule that mirrors a prune reuses the **exact predicate the prune uses**\n * (`hasBalancedDelimiters`, `isPrivateReflection`), so the check and the silent\n * drop can never disagree \u2014 if the check passes, nothing gets pruned, and vice\n * versa.\n *\n * @see docs/cem-contract-enforcement.md \u2192 \"Build the contract as an executable\n * check\" (the static-validation rule set).\n */\n\nimport {\n hasBalancedDelimiters,\n isPrivateReflection,\n withoutStringLiterals,\n} from \"#init/editors/manifest.js\";\n// Reuse the resolver's element filter so the check and the resolver can never\n// disagree on which declarations count as registered elements.\nimport { registeredElements } from \"#init/resolver.js\";\nimport type {\n CemAttribute,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n Deprecated,\n Manifest,\n} from \"#utils/cem.js\";\n\n/** Severity of a contract finding: `error` fails the check, `warn` is advisory. */\nexport type CemSeverity = \"error\" | \"warn\";\n\n/** One contract violation found in a CEM. */\nexport interface CemFinding {\n /** Stable rule id (e.g. `name-required`) for `--json` consumers and docs. */\n rule: string;\n /** `error` blocks the PR; `warn` is advisory unless `--strict`. */\n severity: CemSeverity;\n /** The registered element the finding belongs to (its tag), when applicable. */\n element?: string;\n /** A dotted locator within the declaration (e.g. `attributes[2].type.text`). */\n path?: string;\n /** Human-readable description of what is wrong and why it matters. */\n message: string;\n}\n\n/**\n * Attribute names conventionally backed by a fixed value set. When one is typed as\n * a bare `\"string\"` (no union) every value is accepted and nothing completes \u2014 the\n * `variant`-widening class of bug. Warn-only for now (curated set is deliberately\n * conservative); a future slice may make a core subset fatal once the\n * enumerated-attr scope is settled.\n *\n * @see docs/cem-contract-enforcement.md \u2192 Open questions, \"Union-rule scope\".\n */\nexport const ENUMERATED_ATTRS: ReadonlySet<string> = new Set([\n \"variant\",\n \"shape\",\n \"size\",\n \"type\",\n \"appearance\",\n]);\n\n/**\n * `type.text` spellings that carry no value information \u2014 a curated enumerated\n * attribute typed as any of these accepts every value and completes nothing. Covers\n * the lowercase TS `string`, the capitalized boxed `String` (valid TS, so\n * `type-not-typescript` ignores it \u2014 the shape most auro CEMs actually ship), and\n * `any`. Compared after trimming.\n */\nconst UNINFORMATIVE_STRING_TYPES: ReadonlySet<string> = new Set([\n \"string\",\n \"String\",\n \"any\",\n]);\n\n/**\n * Lowercase JS / JSDoc spellings that are **not** valid TypeScript types \u2014 the\n * `variant` \u2192 `Cannot find name 'array'` class seen across auro-formkit. Inlined\n * verbatim by the JSX/Svelte builders (`useCemTypes`), they make the emitted\n * `.d.ts` fail to compile. Value = the fix to suggest. (`string`/`number`/\n * `boolean`/`object`/`symbol`/`bigint`/`null`/`undefined`/`void`/`any`/`unknown`/\n * `never` are real lowercase TS types and are deliberately absent.)\n */\nconst INVALID_PRIMITIVE_TYPES: ReadonlyMap<string, string> = new Map([\n [\"array\", \"use `unknown[]`, `T[]`, or `Array<T>`\"],\n [\"function\", \"use `Function` or an explicit call signature `(\u2026) => \u2026`\"],\n]);\n\n/**\n * Generic built-ins that require a type argument \u2014 a **bare** `type.text` of one of\n * these (`Array`, not `Array<string>`) fails to compile (`Generic type 'Array<T>'\n * requires 1 type argument(s)`). Value = the shape to suggest.\n */\nconst BARE_GENERIC_TYPES: ReadonlyMap<string, string> = new Map([\n [\"Array\", \"Array<T>\"],\n [\"ReadonlyArray\", \"ReadonlyArray<T>\"],\n [\"Promise\", \"Promise<T>\"],\n [\"Map\", \"Map<K, V>\"],\n [\"WeakMap\", \"WeakMap<K, V>\"],\n [\"Set\", \"Set<T>\"],\n [\"WeakSet\", \"WeakSet<T>\"],\n [\"Record\", \"Record<K, V>\"],\n]);\n\n/**\n * Valid-but-uninformative object types: they compile, but expose no properties so\n * nothing completes in the editor \u2014 an advisory, not a generation break.\n */\nconst VAGUE_OBJECT_TYPES: ReadonlySet<string> = new Set([\"object\", \"Object\"]);\n\n/**\n * A bad token to scan for inside a `type.text`, with its compiled matcher and the\n * fix to suggest. The token is matched as a **whole word** so `myArray`/`ReadonlyArray`\n * never trip the `Array` rule; the trailing lookahead excludes legitimate uses:\n * - primitives (`array`/`function`) skip a following `:` \u2014 a property **key** named\n * `array` (`{ array: string }`) is valid, only a type **position** is not;\n * - generics skip a following `<` (already parameterised, e.g. `Array<string>`) and\n * `:` (a property key).\n */\ninterface BadTypeToken {\n token: string;\n re: RegExp;\n fix: string;\n}\n\nconst INVALID_PRIMITIVE_RULES: readonly BadTypeToken[] = [\n ...INVALID_PRIMITIVE_TYPES,\n].map(([token, fix]) => ({\n token,\n fix,\n re: new RegExp(`\\\\b${token}\\\\b(?!\\\\s*:)`, \"u\"),\n}));\n\nconst BARE_GENERIC_RULES: readonly BadTypeToken[] = [...BARE_GENERIC_TYPES].map(\n ([token, shape]) => ({\n token,\n fix: shape,\n re: new RegExp(`\\\\b${token}\\\\b(?!\\\\s*[<:])`, \"u\"),\n }),\n);\n\n/** Phrase the locator: `is \\`X\\`` when the whole type is the token, else `uses \\`X\\``. */\nfunction describeType(text: string, token: string): string {\n return text === token\n ? `\\`type.text\\` is \\`${token}\\``\n : `\\`type.text\\` (${JSON.stringify(text)}) uses \\`${token}\\``;\n}\n\n/**\n * Prose-level deprecation markers \u2014 a description/summary that *announces* the entry\n * is deprecated. Deliberately narrow: only a **leading** marker, a **bracketed** or\n * **bolded** `deprecated`, or an inline `@deprecated` tag counts. An incidental\n * mention (\"replaces the deprecated `onDark`\") is not at the start and is neither\n * bracketed nor bolded, so it never trips the rule.\n */\nconst DEPRECATION_MARKERS: readonly RegExp[] = [\n /^[\\s>*_~([-]*@?deprecated\\b/iu, // leading: \"DEPRECATED - use \u2026\", \"- @deprecated \u2026\"\n /[([]\\s*deprecated\\b/iu, // bracketed: \"(Deprecated) Notifies \u2026\", \"[deprecated]\"\n /\\*\\*\\s*deprecated\\b/iu, // bolded: \"**deprecated**\"\n /@deprecated\\b/iu, // inline JSDoc tag left in the prose\n];\n\n/** True when any supplied text carries a targeted prose deprecation marker. */\nfunction hasDeprecationMarker(...texts: (string | undefined)[]): boolean {\n return texts.some(\n (text) =>\n typeof text === \"string\" &&\n DEPRECATION_MARKERS.some((re) => re.test(text.trim())),\n );\n}\n\n/** True when a structural `deprecated` field is present (bare `true` or a message). */\nfunction isDeprecationFlagged(deprecated: Deprecated): boolean {\n return deprecated === true || isNonEmptyString(deprecated);\n}\n\n/**\n * Push a `deprecated-prose-unflagged` warning when a real class member (attribute /\n * property / field / method) reads as deprecated in its description or summary but\n * carries no structural `deprecated` field. Author-fixable: the analyzer honors an\n * `@deprecated` JSDoc tag on class members (v0.11.0), so adding the tag makes it emit\n * `deprecated` and clears the finding.\n */\nfunction checkMemberDeprecation(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { description?: string; summary?: string; deprecated?: Deprecated },\n): void {\n if (\n !isDeprecationFlagged(entry.deprecated) &&\n hasDeprecationMarker(entry.description, entry.summary)\n ) {\n findings.push({\n rule: \"deprecated-prose-unflagged\",\n severity: \"warn\",\n element,\n path,\n message:\n \"described as deprecated but missing the `deprecated` field \u2014 add an `@deprecated` JSDoc tag so the generated JSX/Svelte types surface it with a strikethrough. (VS Code HTML custom-data has no deprecation field, so vanilla-HTML editors won't show it.)\",\n });\n }\n}\n\n/**\n * Push a `deprecated-prose-unsupported` warning when an event or slot reads as\n * deprecated in prose but has no `deprecated` field. Unlike class members this is\n * **not** author-fixable with an `@deprecated` tag: the analyzer's inline\n * `@event`/`@fires`/`@slot` handling (v0.11.0) never emits `deprecated`, so editors\n * cannot surface it regardless of JSDoc. Reported under a distinct id so it can be\n * suppressed independently of the member rule.\n */\nfunction checkEventSlotDeprecation(\n findings: CemFinding[],\n element: string,\n kind: \"event\" | \"slot\",\n path: string,\n entry: { description?: string; summary?: string; deprecated?: Deprecated },\n): void {\n if (\n !isDeprecationFlagged(entry.deprecated) &&\n hasDeprecationMarker(entry.description, entry.summary)\n ) {\n findings.push({\n rule: \"deprecated-prose-unsupported\",\n severity: \"warn\",\n element,\n path,\n message: `this ${kind} reads as deprecated in prose, but the analyzer (v0.11.0) does not emit a \\`deprecated\\` field for inline \\`@${kind}\\` tags \u2014 editors cannot surface it. Track upstream or a mapping plugin; suppress this warning if the prose is intentional.`,\n });\n }\n}\n\n/**\n * Push a `deprecated-no-detail` warning when a `deprecated` field is a bare `true`\n * with no message \u2014 editors render a strikethrough but give consumers no migration\n * target. Low priority (a style nudge): prefer `@deprecated <what to use instead>`\n * over a bare `@deprecated`.\n */\nfunction checkDeprecationDetail(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { deprecated?: Deprecated },\n): void {\n if (entry.deprecated === true) {\n findings.push({\n rule: \"deprecated-no-detail\",\n severity: \"warn\",\n element,\n path,\n message:\n \"`deprecated` is set but carries no message \u2014 editors show a strikethrough with no migration target. Prefer `@deprecated <what to use instead>`.\",\n });\n }\n}\n\n/** True when `value` is a usable string identity (name/tag) \u2014 non-empty string. */\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * Push a `name-required` error for every entry in `entries` whose `name` is not a\n * string. Empty-string names are allowed (the valid default-slot name), matching\n * the prune's `hasName = typeof entry.name === \"string\"` guard.\n */\nfunction checkNames(\n findings: CemFinding[],\n element: string,\n collection: string,\n entries: readonly { name?: unknown }[] | undefined,\n): void {\n entries?.forEach((entry, index) => {\n if (typeof entry.name !== \"string\") {\n findings.push({\n rule: \"name-required\",\n severity: \"error\",\n element,\n path: `${collection}[${index}].name`,\n message: `${collection}[${index}] has no string \\`name\\` \u2014 community generators call \\`.name.startsWith(\u2026)\\` and throw mid-generation.`,\n });\n }\n });\n}\n\n/**\n * Push a `type-parseable` error when `type.text` is a non-empty string with\n * unbalanced delimiters \u2014 the exact condition the prune's `withSafeType` strips,\n * which would otherwise splice unparseable TypeScript into the emitted `.d.ts`.\n */\nfunction checkType(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { type?: { text?: string } },\n): void {\n const text = entry.type?.text;\n if (typeof text === \"string\" && text !== \"\" && !hasBalancedDelimiters(text)) {\n findings.push({\n rule: \"type-parseable\",\n severity: \"error\",\n element,\n path: `${path}.type.text`,\n message: `\\`type.text\\` has unbalanced delimiters: ${JSON.stringify(text)} \u2014 the generated \\`.d.ts\\` would not parse.`,\n });\n }\n}\n\n/**\n * Push a finding when `type.text` contains a JS/JSDoc spelling that is not valid\n * TypeScript \u2014 a lowercase primitive (`array`, `function` \u2192 **error**) or a bare\n * generic missing its type argument (`Array`, `Promise`, \u2026 \u2192 **error**) \u2014 or, as a\n * whole, is a valid-but-uninformative object type (`object`/`Object` \u2192 **warn**).\n * These are the same defects the generation smoke catches, but reported with a\n * precise per-entry locator (`attributes[N].type.text`) instead of buried in bundled\n * `tsc` output.\n *\n * The bad-token scan matches whole words **inside** the type (so `\"Array | null\"`\n * and `\"string | array\"` are caught, not just the whole-string forms), after blanking\n * string literals \u2014 a quoted `\"array\"` member or a property key `{ array: string }`\n * is left untouched, keeping the rule free of false positives.\n */\nfunction checkPrimitiveType(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { type?: { text?: string } },\n): void {\n const raw = entry.type?.text;\n if (typeof raw !== \"string\") {\n return;\n }\n const text = raw.trim();\n if (text === \"\") {\n return;\n }\n const scannable = withoutStringLiterals(text);\n\n for (const { token, re, fix } of INVALID_PRIMITIVE_RULES) {\n if (re.test(scannable)) {\n findings.push({\n rule: \"type-not-typescript\",\n severity: \"error\",\n element,\n path: `${path}.type.text`,\n message: `${describeType(text, token)}, which is not a TypeScript type \u2014 ${fix}. The generated \\`.d.ts\\` would not compile.`,\n });\n return;\n }\n }\n\n for (const { token, re, fix } of BARE_GENERIC_RULES) {\n if (re.test(scannable)) {\n findings.push({\n rule: \"type-not-typescript\",\n severity: \"error\",\n element,\n path: `${path}.type.text`,\n message: `${describeType(text, token)}, a generic that requires a type argument \u2014 write \\`${fix}\\`. The generated \\`.d.ts\\` would not compile.`,\n });\n return;\n }\n }\n\n if (VAGUE_OBJECT_TYPES.has(text)) {\n findings.push({\n rule: \"type-imprecise\",\n severity: \"warn\",\n element,\n path: `${path}.type.text`,\n message: `\\`type.text\\` is \\`${text}\\` \u2014 a valid type, but it exposes no properties so nothing completes. Prefer an explicit shape (e.g. \\`{ id: string }\\`).`,\n });\n }\n}\n\n/**\n * True when the character at `index` is escaped \u2014 preceded by an odd number of\n * consecutive backslashes. `\"a\\\\\"` (two backslashes) leaves the following `\"`\n * unescaped; `\"a\\\"` (one backslash) escapes it.\n */\nfunction isEscaped(text: string, index: number): boolean {\n let backslashes = 0;\n for (let j = index - 1; j >= 0 && text[j] === \"\\\\\"; j--) {\n backslashes++;\n }\n return backslashes % 2 === 1;\n}\n\n/**\n * Split a `type.text` on its **top-level** `|` union separators, ignoring any `|`\n * inside quotes or nested `()[]{}<>` (so `\"a|b\" | Array<x | y>` yields two members,\n * not four). Arrow `=>` is not treated as a closing angle. Members are trimmed and\n * empties dropped.\n */\nfunction splitTopLevelUnion(text: string): string[] {\n const members: string[] = [];\n let depth = 0;\n let quote: string | null = null;\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (quote !== null) {\n // A quote closes the literal only when it isn't escaped; an even run of\n // preceding backslashes (incl. zero) means the quote itself is unescaped\n // (`\"a\\\\\"` \u2192 the `\"` closes), an odd run means it's escaped (`\"a\\\"`).\n if (ch === quote && !isEscaped(text, i)) {\n quote = null;\n }\n } else if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n quote = ch;\n } else if (ch === \"(\" || ch === \"[\" || ch === \"{\" || ch === \"<\") {\n depth++;\n } else if (ch === \")\" || ch === \"]\" || ch === \"}\") {\n depth--;\n } else if (ch === \">\") {\n if (i > 0 && text[i - 1] !== \"=\") depth--; // ignore the `>` of an arrow `=>`\n } else if (ch === \"|\" && depth === 0) {\n members.push(text.slice(start, i).trim());\n start = i + 1;\n }\n }\n members.push(text.slice(start).trim());\n return members.filter((member) => member !== \"\");\n}\n\n/** True when a union member is a string literal (`\"x\"` / `'x'` / `` `x` ``). */\nfunction isStringLiteralMember(member: string): boolean {\n return /^(['\"`]).*\\1$/u.test(member);\n}\n\n/**\n * Push a `union-widened-by-string` warning when a `type.text` unions one or more\n * string literals with a bare `string`/`String` \u2014 the bare member widens the whole\n * type back to `string`, so the literals stop validating and completing (the\n * auro-tabs `\"default\" | \"inverse\" | string` class). Warn-only: the emitted `.d.ts`\n * still compiles, it just loses the completion the literals were meant to give.\n */\nfunction checkWidenedUnion(\n findings: CemFinding[],\n element: string,\n path: string,\n entry: { type?: { text?: string } },\n): void {\n const text = entry.type?.text?.trim();\n if (typeof text !== \"string\" || !text.includes(\"|\")) {\n return;\n }\n const members = splitTopLevelUnion(text);\n const hasLiteral = members.some(isStringLiteralMember);\n const hasBareString = members.some((m) => m === \"string\" || m === \"String\");\n if (hasLiteral && hasBareString) {\n findings.push({\n rule: \"union-widened-by-string\",\n severity: \"warn\",\n element,\n path: `${path}.type.text`,\n message: `\\`type.text\\` (${JSON.stringify(text)}) unions string literals with a bare \\`string\\`, which widens the whole type back to \\`string\\` \u2014 drop the \\`string\\` member so the literals validate and complete.`,\n });\n }\n}\n\n/** True when a text field is absent or blank (nothing to drive an editor hover). */\nfunction isMissingText(text: string | undefined): boolean {\n return typeof text !== \"string\" || text.trim() === \"\";\n}\n\n/**\n * Push a `missing-description` warning when neither `description` nor `summary`\n * carries text \u2014 editors then show no hover documentation for the entry. Warn-only;\n * applied to the component and its attributes/events (the surfaces the IntelliSense\n * audit measures). `kind` names the surface in the message.\n */\nfunction checkDescription(\n findings: CemFinding[],\n element: string,\n kind: string,\n path: string | undefined,\n entry: { description?: string; summary?: string },\n): void {\n if (isMissingText(entry.description) && isMissingText(entry.summary)) {\n findings.push({\n rule: \"missing-description\",\n severity: \"warn\",\n element,\n ...(path === undefined ? {} : { path }),\n message: `${kind} has no description or summary \u2014 editors show no hover documentation for it. Add a JSDoc description.`,\n });\n }\n}\n\n/** Run every static contract rule over one registered element. */\nfunction checkDeclaration(findings: CemFinding[], decl: CemDeclaration): void {\n const element = isNonEmptyString(decl.tagName) ? decl.tagName : \"<unknown>\";\n\n // The declaration itself must carry a string class `name` (used as the export /\n // import-type identity); a non-string one breaks generation for this element.\n if (typeof decl.name !== \"string\") {\n findings.push({\n rule: \"name-required\",\n severity: \"error\",\n element,\n path: \"name\",\n message:\n \"registered element has no string `name` \u2014 its generated import/export identity is undefined.\",\n });\n }\n\n // Rule: missing-description (warn) \u2014 the component itself carries no hover docs.\n checkDescription(findings, element, \"this component\", undefined, decl);\n\n const members: readonly CemMember[] = decl.members ?? [];\n const attributes: readonly CemAttribute[] = decl.attributes ?? [];\n const events: readonly CemEvent[] = decl.events ?? [];\n const slots: readonly CemSlot[] = decl.slots ?? [];\n\n // Rule: name-required \u2014 every named collection.\n checkNames(findings, element, \"members\", members);\n checkNames(findings, element, \"attributes\", attributes);\n checkNames(findings, element, \"slots\", decl.slots);\n checkNames(findings, element, \"events\", events);\n checkNames(findings, element, \"cssParts\", decl.cssParts);\n checkNames(findings, element, \"cssProperties\", decl.cssProperties);\n\n // Rules: type-parseable (delimiters) + type-not-typescript / type-imprecise\n // (invalid or vague `type.text`) \u2014 members, attributes, events carry a `type.text`.\n members.forEach((m, i) => {\n checkType(findings, element, `members[${i}]`, m);\n checkPrimitiveType(findings, element, `members[${i}]`, m);\n checkMemberDeprecation(findings, element, `members[${i}]`, m);\n checkDeprecationDetail(findings, element, `members[${i}]`, m);\n });\n attributes.forEach((a, i) => {\n checkType(findings, element, `attributes[${i}]`, a);\n checkPrimitiveType(findings, element, `attributes[${i}]`, a);\n checkWidenedUnion(findings, element, `attributes[${i}]`, a);\n checkDescription(findings, element, \"attribute\", `attributes[${i}]`, a);\n checkMemberDeprecation(findings, element, `attributes[${i}]`, a);\n checkDeprecationDetail(findings, element, `attributes[${i}]`, a);\n });\n events.forEach((e, i) => {\n checkType(findings, element, `events[${i}]`, e);\n checkPrimitiveType(findings, element, `events[${i}]`, e);\n checkDescription(findings, element, \"event\", `events[${i}]`, e);\n checkEventSlotDeprecation(findings, element, \"event\", `events[${i}]`, e);\n checkDeprecationDetail(findings, element, `events[${i}]`, e);\n });\n slots.forEach((s, i) => {\n checkEventSlotDeprecation(findings, element, \"slot\", `slots[${i}]`, s);\n checkDeprecationDetail(findings, element, `slots[${i}]`, s);\n });\n\n // Backing-member privacy, keyed by name (built from raw members with a string\n // name \u2014 a nameless member can't be a `fieldName` target). Feeds both the\n // private-reflection warn below and mirrors the prune's own map.\n const memberPrivacyByName = new Map<string, string | undefined>(\n members\n .filter((m): m is CemMember => typeof m.name === \"string\")\n .map((m) => [m.name, m.privacy]),\n );\n\n attributes.forEach((attribute, index) => {\n // Rule: attribute-name-not-lowercase (warn) \u2014 the browser lowercases HTML\n // attribute names, so a camelCase `name` (e.g. `buttonHref`) never binds as\n // written. The JS property name lives in `fieldName`/the backing member; only\n // the reflected attribute `name` must be lowercase.\n if (isNonEmptyString(attribute.name) && /[A-Z]/u.test(attribute.name)) {\n findings.push({\n rule: \"attribute-name-not-lowercase\",\n severity: \"warn\",\n element,\n path: `attributes[${index}].name`,\n message: `attribute \\`${attribute.name}\\` has uppercase letters \u2014 HTML lowercases attribute names, so it never binds as written. Use \\`${attribute.name.toLowerCase()}\\` (the camelCase property name belongs in \\`fieldName\\`).`,\n });\n }\n\n // Rule: enumerated-union (warn) \u2014 a conventionally-enumerated attribute typed as\n // a bare uninformative string (`string`/`String`/`any`) accepts every value and\n // completes nothing.\n if (\n isNonEmptyString(attribute.name) &&\n ENUMERATED_ATTRS.has(attribute.name) &&\n UNINFORMATIVE_STRING_TYPES.has(attribute.type?.text?.trim() ?? \"\")\n ) {\n findings.push({\n rule: \"enumerated-union\",\n severity: \"warn\",\n element,\n path: `attributes[${index}].type.text`,\n message: `\\`${attribute.name}\\` is typed as bare \\`${JSON.stringify(attribute.type?.text ?? \"\")}\\` \u2014 an enumerated attribute should carry a string-literal union (e.g. \\`\"primary\" | \"secondary\"\\`) so values validate and complete.`,\n });\n }\n\n // Rule: private-reflection (warn) \u2014 an undescribed attribute reflected from a\n // private/omitted member leaks internal state into editor autocomplete.\n if (isPrivateReflection(attribute, memberPrivacyByName)) {\n findings.push({\n rule: \"private-reflection\",\n severity: \"warn\",\n element,\n path: `attributes[${index}]`,\n message: `\\`${attribute.name ?? \"<unnamed>\"}\\` reflects a private/omitted member and has no description \u2014 it leaks into editor autocomplete as a settable attribute (add a description if it is genuinely public).`,\n });\n }\n });\n}\n\n/**\n * Run the static contract rules over a parsed CEM, returning every finding (errors\n * and warnings). Pure and side-effect-free \u2014 the caller decides how findings map to\n * an exit code (see the `cem-check` command's exit contract).\n */\nexport function runContractRules(manifest: Manifest): CemFinding[] {\n const findings: CemFinding[] = [];\n\n // Rule: schema-version (warn) \u2014 a missing version means the generators can't\n // know which CEM shape they're reading.\n if (!isNonEmptyString(manifest.schemaVersion)) {\n findings.push({\n rule: \"schema-version\",\n severity: \"warn\",\n message:\n \"manifest has no `schemaVersion` \u2014 declare the CEM schema version it targets.\",\n });\n }\n\n for (const decl of registeredElements(manifest)) {\n checkDeclaration(findings, decl);\n }\n\n return findings;\n}\n", "/**\n * The authoritative half of `auro cem-check`: run auro-cli's **real** editor-type\n * builders against the candidate CEM and `tsc --noEmit` their output. Because it\n * exercises the exact consumer path (`buildJsxTypes` / `buildSvelteTypes` \u2192 the\n * emitted `.d.ts` \u2192 the pinned TypeScript compiler), a CEM change that breaks\n * generation surfaces here as a non-zero result \u2014 even when the static rules pass.\n *\n * The mechanism (temp project + stubs + `execFileSync(tsc)`) is the runtime\n * counterpart of the test smokes\n * ([init.editors.tsc-smoke.test.ts](../../../test/init.editors.tsc-smoke.test.ts),\n * [init.editors.svelte-event-collision.test.ts](../../../test/init.editors.svelte-event-collision.test.ts));\n * JSX and Svelte compile in separate throwaway projects, exactly as those tests do,\n * so neither artifact's global augmentations contaminate the other.\n *\n * @see docs/cem-contract-enforcement.md \u2192 \"End-to-end generation smoke\".\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport process from \"node:process\";\nimport type { CemFinding } from \"#init/cem-check/rules.js\";\nimport { buildJsxTypes } from \"#init/editors/jsxTypes.js\";\nimport type { EditorArtifact } from \"#init/editors/manifest.js\";\nimport { withTempDir } from \"#init/editors/manifest.js\";\nimport { buildSvelteTypes } from \"#init/editors/svelteTypes.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\nconst require = createRequire(import.meta.url);\n/** The project's own pinned `tsc` \u2014 versioned with the CLI, no PATH dependency. */\nconst TSC = require.resolve(\"typescript/bin/tsc\");\n\n/** The global-JSX shim svelte2tsx output references (its only external symbol). */\nconst JSX_SHIM =\n \"declare namespace JSX {\\n\" +\n \" type Element = unknown;\\n\" +\n \" interface CSSProperties {}\\n\" +\n \"}\\n\";\n\n/** Turn an import specifier into a safe stub filename. */\nfunction stubFileFor(importPath: string): string {\n return `${importPath.replace(/[^a-zA-Z0-9]+/gu, \"_\")}.d.ts`;\n}\n\n/**\n * Parse the `import type { A, B as C } from \"path\"` statements the JSX artifact\n * emits into `path \u2192 {exported names}`. Driving the stubs off the artifact's real\n * imports (rather than only the component classes) means a cross-package type\n * reference the CEM points at another subpath \u2014 common in a monorepo like\n * auro-formkit \u2014 gets a matching stub too, instead of a false `no exported member`\n * failure. Only import statements at the start of a line are matched, so the\n * `import type { ScopedElements } \u2026` example inside the tool's doc comment is\n * ignored. Each name is stubbed as a real class (usable both as a value and, as the\n * artifact does with `BaseProps<AuroButton>`, as a type).\n */\nfunction importedNamesByPath(source: string): Map<string, Set<string>> {\n const byPath = new Map<string, Set<string>>();\n const re =\n /^[ \\t]*import\\s+(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*[\"']([^\"']+)[\"']/gmu;\n for (const match of source.matchAll(re)) {\n const names = match[1]\n .split(\",\")\n .map((entry) =>\n entry\n .trim()\n .split(/\\s+as\\s+/u)[0]\n .trim(),\n )\n .filter(Boolean);\n if (names.length === 0) {\n continue;\n }\n const set = byPath.get(match[2]) ?? new Set<string>();\n for (const name of names) {\n set.add(name);\n }\n byPath.set(match[2], set);\n }\n return byPath;\n}\n\n/** Write `tsconfig.json` into `cwd` with the shared smoke compiler options. */\nfunction writeTsconfig(\n cwd: string,\n include: string[],\n paths?: Record<string, string[]>,\n): void {\n writeFileSync(\n join(cwd, \"tsconfig.json\"),\n JSON.stringify(\n {\n compilerOptions: {\n noEmit: true,\n // The artifacts are themselves `.d.ts`, so only an un-skipped lib check\n // actually type-checks them.\n skipLibCheck: false,\n strict: false,\n // The condition under which the native-vs-CEM event collision surfaces\n // as a real error (handler params checked contravariantly).\n strictFunctionTypes: true,\n target: \"ES2020\",\n module: \"ESNext\",\n moduleResolution: \"bundler\",\n ...(paths && { baseUrl: \".\", paths }),\n lib: [\"ES2020\", \"DOM\"],\n types: [],\n },\n include,\n },\n null,\n 2,\n ),\n \"utf-8\",\n );\n}\n\n/** Write an artifact into `cwd`, creating its parent directory. */\nfunction writeArtifact(cwd: string, artifact: EditorArtifact): void {\n const dest = join(cwd, artifact.filename);\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, artifact.contents, \"utf-8\");\n}\n\n/**\n * Compile `artifact` under a throwaway `tsc` project. Returns `null` on success, or\n * one `error` finding carrying the compiler diagnostics on failure.\n */\nfunction compile(\n label: string,\n artifact: EditorArtifact,\n setup: (cwd: string) => void,\n): CemFinding | null {\n return withTempDir((cwd) => {\n writeArtifact(cwd, artifact);\n setup(cwd);\n try {\n execFileSync(process.execPath, [TSC, \"-p\", \"tsconfig.json\"], {\n cwd,\n stdio: \"pipe\",\n });\n return null;\n } catch (error) {\n const e = error as { stdout?: Buffer; stderr?: Buffer };\n const output = `${e.stdout?.toString() ?? \"\"}${e.stderr?.toString() ?? \"\"}`;\n return {\n rule: \"generation-smoke\",\n severity: \"error\" as const,\n element: label,\n message: `the generated ${label} \\`.d.ts\\` does not type-check \u2014 this CEM breaks the editor tooling:\\n${output.trim()}`,\n };\n }\n });\n}\n\n/**\n * Build the JSX and Svelte artifacts from `components` and type-check each. A build\n * throw or a `tsc` rejection becomes an `error` finding; a clean run returns `[]`.\n * Tags are passed through unchanged (identity map) \u2014 `cem-check` validates the CEM\n * as authored, without a consumer's tag overrides.\n */\nexport function runGenerationSmoke(\n components: readonly ResolvedComponent[],\n): CemFinding[] {\n if (components.length === 0) {\n return [];\n }\n const identityTags = new Map(components.map((c) => [c.tagName, c.tagName]));\n const findings: CemFinding[] = [];\n\n // JSX \u2014 the artifact emits `import type { <Class> } from \"<importPath>\"` (and, in a\n // monorepo, cross-package type references). Stub every imported name as a real class\n // via a `paths` mapping (deterministic, offline, independent of node_modules layout).\n // The names come from the artifact itself, so a cross-package reference resolves too\n // \u2014 the smoke validates the generated structure and inlined `type.text`, not whether\n // the real package happens to export that symbol (the shipped Auro packages ship\n // unresolvable class types anyway; the class import is unused under `useCemTypes`).\n try {\n const jsx = buildJsxTypes(components, identityTags);\n const importsByPath = importedNamesByPath(jsx.contents);\n const jsxFinding = compile(\"JSX\", jsx, (cwd) => {\n mkdirSync(join(cwd, \"stubs\"), { recursive: true });\n const paths: Record<string, string[]> = {};\n const include = [jsx.filename];\n for (const [importPath, names] of importsByPath) {\n const file = stubFileFor(importPath);\n writeFileSync(\n join(cwd, \"stubs\", file),\n `${[...names]\n .map(\n (name) => `export declare class ${name} extends HTMLElement {}`,\n )\n .join(\"\\n\")}\\n`,\n \"utf-8\",\n );\n paths[importPath] = [`./stubs/${file}`];\n include.push(`stubs/${file}`);\n }\n writeTsconfig(cwd, include, paths);\n });\n if (jsxFinding) {\n findings.push(jsxFinding);\n }\n } catch (error) {\n findings.push({\n rule: \"generation-build\",\n severity: \"error\",\n element: \"JSX\",\n message: `JSX type generation threw for this CEM: ${(error as Error).message}`,\n });\n }\n\n // Svelte \u2014 inlines CEM `type.text`, so it imports no package class; its only\n // external reference is svelte2tsx's global JSX namespace, satisfied by the shim.\n try {\n const svelte = buildSvelteTypes(components, identityTags);\n const svelteFinding = compile(\"Svelte\", svelte, (cwd) => {\n mkdirSync(join(cwd, \"stubs\"), { recursive: true });\n writeFileSync(join(cwd, \"stubs\", \"jsx-shim.d.ts\"), JSX_SHIM, \"utf-8\");\n writeTsconfig(cwd, [svelte.filename, \"stubs/jsx-shim.d.ts\"]);\n });\n if (svelteFinding) {\n findings.push(svelteFinding);\n }\n } catch (error) {\n findings.push({\n rule: \"generation-build\",\n severity: \"error\",\n element: \"Svelte\",\n message: `Svelte type generation threw for this CEM: ${(error as Error).message}`,\n });\n }\n\n return findings;\n}\n", "/**\n * Build the JSX / React type declarations (`auro-types/auro-jsx.d.ts`) that give\n * `.tsx` files tag + prop IntelliSense through the TypeScript language service.\n * Pure: `(components, resolvedTags) \u2192 EditorArtifact`.\n *\n * Two seams, both via the tool's own hooks (so the manifest keeps its canonical\n * `auro-*` tags here, unlike the HTML/Svelte pre-swap path):\n * - `tagFormatter` renames each canonical tag to the tag the consumer registers,\n * so the augmented `JSX.IntrinsicElements` / `react/jsx-runtime` keys match.\n * - `componentTypePath` routes the emitted class/event/reference `import type`\n * specifiers at the component's installed `importPath` (package root or monorepo\n * subpath), not the CEM's internal source path.\n *\n * Prop types come from `useCemTypes: true`, which inlines each attribute's CEM\n * `type.text` (real string-literal unions like `variant` \u2192\n * `\"primary\" | \"secondary\" | \u2026`). Without it the tool would type props as\n * `Component['prop']`, which resolves to `any` because the shipped Auro packages\n * ship unresolvable class declarations \u2014 so values would never complete/validate.\n * The class import the tool still emits is then unused but harmless.\n *\n * `includeDefaultDOMEvents: true` folds the tool's built-in native DOM event\n * handlers (`onClick`, `onFocus`, `onKeyDown`, \u2026 \u2014 all lib.dom event types) into\n * the shared `BaseEvents` type every element intersects. A CEM only declares a\n * component's *own* events, so without this native handlers are absent and\n * `<auro-button onFocus={\u2026} />` is flagged as an unknown prop. No collision with\n * a CEM `click` event: React camelCase `onClick` never clashes with the custom\n * event's `onclick`.\n *\n * The tool's `BaseProps` covers `role` and camelCase `tabIndex` but no `aria-*` or\n * `data-*` attributes, and the generated element type *replaces* the tag's intrinsic\n * type \u2014 so {@link injectGlobalAttributes} splices the standard ARIA / `data-*` set\n * into `BaseProps` (no tool option exposes it; `allowUnknownProps` would disable all\n * prop validation). `svelteGlobals: false` here \u2014 the tool already emits `role` and\n * `tabIndex`; the lowercase `role` / `tabindex` forms are Svelte-only.\n *\n * `generateJsxTypes` both writes a file to `outdir` and returns the source; we\n * discard the write (scratch dir) and keep the returned string.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 build-order step 2.\n */\n\nimport { generateJsxTypes } from \"@wc-toolkit/jsx-types\";\nimport { JSX_TYPES_FILENAME, JSX_TYPES_PATH } from \"#init/editors/layout.js\";\nimport {\n buildManifest,\n type EditorArtifact,\n ensureTrailingNewline,\n importPathsByClass,\n injectGlobalAttributes,\n withTempDir,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/**\n * Render the JSX `.d.ts` for the resolved component set. Returns the artifact's\n * project-root-relative path plus its contents; writing is the caller's job.\n */\nexport function buildJsxTypes(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact {\n // Canonical tags \u2014 the swap happens through `tagFormatter`, not the manifest.\n const manifest = buildManifest(components);\n const importPaths = importPathsByClass(components);\n\n const contents = withTempDir((outdir) =>\n // The tool types its manifest param as the strict `custom-elements-manifest`\n // Package; our loose Manifest is structurally compatible at runtime, so cast\n // to the tool's own parameter type rather than reshaping our model.\n generateJsxTypes(\n manifest as unknown as Parameters<typeof generateJsxTypes>[0],\n {\n outdir,\n fileName: JSX_TYPES_FILENAME,\n tagFormatter: (tagName) => resolvedTags.get(tagName) ?? tagName,\n componentTypePath: (name) => importPaths.get(name) ?? name,\n // Inline CEM `type.text` for props instead of `Component['prop']`, which\n // resolves to `any` against the packages' unresolvable class .d.ts.\n useCemTypes: true,\n // Fold native DOM event handlers (onClick/onFocus/\u2026) into BaseEvents; a\n // CEM only declares a component's own events, so without this they are\n // absent and native handlers flag as unknown props.\n includeDefaultDOMEvents: true,\n },\n ),\n );\n\n if (typeof contents !== \"string\") {\n throw new Error(\n \"JSX type generation returned no output for the resolved components.\",\n );\n }\n\n return {\n filename: JSX_TYPES_PATH,\n // The tool already emits `role` / `tabIndex`, so inject ARIA / data-* only.\n contents: ensureTrailingNewline(\n injectGlobalAttributes(contents, { svelteGlobals: false }),\n ),\n };\n}\n", "/**\n * Frozen locations and editor-wiring keys for the IntelliSense artifacts\n * `auro init` emits (PT-M2). This is the editor-target analogue of\n * ../layout.ts: it owns the input-INDEPENDENT shape only \u2014 the artifact\n * filenames, the directories they live in, and the settings/tsconfig keys the\n * command merges into \u2014 not the generated contents (the per-target builders in\n * ./htmlCustomData.ts, ./jsxTypes.ts, ./svelteTypes.ts fill those around these\n * constants, and must not re-derive them).\n *\n * FROZEN per docs/pt-m2-completion-plan.md \u2192 build-order step 1 (\"Freeze the\n * filenames/paths/wiring-key shapes\") and \"Frozen decisions \u2192 Artifact locations\n * + editor wiring\". Composite paths are DERIVED from their parts below so a single\n * edit can never leave the artifact path and its wiring entry disagreeing.\n *\n * @see test/fixtures/init/editors/ for the golden artifacts these pin.\n */\n\n// ---------------------------------------------------------------------------\n// VS Code HTML custom-data (HTML Language Server target)\n// ---------------------------------------------------------------------------\n\n/** Project-root directory VS Code reads editor data and settings from. */\nexport const VSCODE_DIR = \".vscode\";\n\n/** The VS Code settings file merged non-destructively for the HTML target. */\nexport const VSCODE_SETTINGS_FILENAME = \"settings.json\";\n\n/**\n * Auro-namespaced HTML custom-data artifact. The `auro.` prefix keeps it from\n * colliding with a team's own or another tool's custom-data file.\n */\nexport const HTML_CUSTOM_DATA_FILENAME = \"auro.html-custom-data.json\";\n\n/** The `settings.json` key that loads HTML custom-data files. */\nexport const HTML_CUSTOM_DATA_SETTINGS_KEY = \"html.customData\";\n\n/**\n * Path recorded in `settings.json` under {@link HTML_CUSTOM_DATA_SETTINGS_KEY}.\n * Per VS Code's rule this is **relative to the project root**, not to the settings\n * file, and always uses forward slashes (JSON + VS Code, every OS). Derived from\n * the dir + filename so it cannot drift from the file we actually write.\n */\nexport const HTML_CUSTOM_DATA_SETTINGS_ENTRY = `./${VSCODE_DIR}/${HTML_CUSTOM_DATA_FILENAME}`;\n\n/**\n * The HTML custom-data artifact's path **relative to the project root** \u2014 the\n * `filename` a builder returns and `init` writes. Same target as\n * {@link HTML_CUSTOM_DATA_SETTINGS_ENTRY} without the leading `./` (a path to\n * write vs. a settings-file entry). Forward slashes; `init` splits on `/` to join.\n */\nexport const HTML_CUSTOM_DATA_PATH = `${VSCODE_DIR}/${HTML_CUSTOM_DATA_FILENAME}`;\n\n// ---------------------------------------------------------------------------\n// VS Code CSS `::part()` snippets (CSS language-service target)\n// ---------------------------------------------------------------------------\n\n/**\n * Auro-namespaced VS Code snippets artifact. The `.code-snippets` extension is\n * what makes VS Code **auto-discover** it under {@link VSCODE_DIR} \u2014 unlike the\n * HTML custom-data file, no `settings.json` entry registers it, so this target\n * has no `_SETTINGS_KEY`/`_ENTRY` sibling. The `auro.` prefix keeps it from\n * colliding with a team's own project snippets.\n */\nexport const CSS_SNIPPETS_FILENAME = \"auro.code-snippets\";\n\n/**\n * The CSS snippets artifact's path **relative to the project root** \u2014 the\n * `filename` its builder returns and `init` writes. Derived from the dir +\n * filename (forward slashes) so it always lands in the auto-discovered\n * {@link VSCODE_DIR}. There is deliberately no settings entry to keep in sync.\n */\nexport const CSS_SNIPPETS_PATH = `${VSCODE_DIR}/${CSS_SNIPPETS_FILENAME}`;\n\n// ---------------------------------------------------------------------------\n// Framework TypeScript types (TS + Svelte language-server targets)\n// ---------------------------------------------------------------------------\n\n/**\n * Directory holding the generated framework `.d.ts` bundles, at the project root.\n *\n * The **non-dotted** name is deliberate and evidence-driven: TypeScript's default\n * `include` glob (`**` + `/*`, used when a project sets neither `include` nor\n * `files`) skips dot-prefixed directories, so a `.auro/` dir would be silently\n * invisible to default-include projects \u2014 whereas `auro-types/` is auto-picked-up\n * with zero tsconfig edits. See docs/pt-m2-completion-plan.md \u2192 resolved Risk\n * \"Consumer tsconfig variance\".\n */\nexport const FRAMEWORK_TYPES_DIR = \"auro-types\";\n\n/** JSX / React type declarations (augments `JSX.IntrinsicElements`). */\nexport const JSX_TYPES_FILENAME = \"auro-jsx.d.ts\";\n\n/** Svelte type declarations (augments Svelte element types). */\nexport const SVELTE_TYPES_FILENAME = \"auro-svelte.d.ts\";\n\n/**\n * The JSX `.d.ts` bundle's path **relative to the project root** \u2014 the `filename`\n * its builder returns and `init` writes. Derived from the types dir + filename so\n * it always lands where {@link TSCONFIG_INCLUDE_ENTRY} points. Forward slashes.\n */\nexport const JSX_TYPES_PATH = `${FRAMEWORK_TYPES_DIR}/${JSX_TYPES_FILENAME}`;\n\n/**\n * The Svelte `.d.ts` bundle's path **relative to the project root** \u2014 the\n * `filename` its builder returns and `init` writes. Derived from the types dir +\n * filename so it always lands where {@link TSCONFIG_INCLUDE_ENTRY} points.\n */\nexport const SVELTE_TYPES_PATH = `${FRAMEWORK_TYPES_DIR}/${SVELTE_TYPES_FILENAME}`;\n\n/** The `tsconfig.json` key that puts declaration files on the TypeScript program. */\nexport const TSCONFIG_INCLUDE_KEY = \"include\";\n\n/**\n * Entry appended to `tsconfig.json` `include` to pull in the framework types.\n * Equal to {@link FRAMEWORK_TYPES_DIR} by construction so the wiring can never\n * point somewhere other than where the files are written.\n */\nexport const TSCONFIG_INCLUDE_ENTRY = FRAMEWORK_TYPES_DIR;\n", "/**\n * Build the Svelte type declarations (`auro-types/auro-svelte.d.ts`) that give\n * Svelte markup tag + prop IntelliSense through the Svelte language server.\n * Pure: `(components, resolvedTags) \u2192 EditorArtifact`.\n *\n * The Svelte tool has no per-tag rename hook (no `tagFormatter`), so \u2014 like the\n * HTML target \u2014 the resolved tags are baked in by pre-swapping the manifest\n * ({@link buildManifest} with `resolvedTags`). We deliberately do NOT pass\n * `componentTypePath`: the tool types each attribute as `Component['field']` only\n * when that hook is set, else it inlines the CEM's own `type.text` \u2014 and the\n * class-indexed form resolves to `any` because the shipped Auro packages ship\n * unresolvable class declarations (auro-button's `dist/index.d.ts` imports from a\n * non-published `src/`; auro-formkit subpaths carry no `types` condition). Inlining\n * the CEM type keeps real string-literal unions (`variant` \u2192\n * `\"primary\" | \"secondary\" | \u2026`) so values actually complete/validate. Unlike the\n * other two tools this one returns `void` and only writes a file, so we point it\n * at a scratch dir and read the result back.\n *\n * A CEM only declares a component's *own* events, so native DOM event handlers\n * (`on:click`, `on:focus`, \u2026) would otherwise be absent from every element type.\n * Unlike the JSX tool there is no `includeDefaultDOMEvents` flag here \u2014 its only\n * lever is `globalEvents`, a string spliced verbatim into the shared\n * `type BaseEvents = { \u2026 }`. We pass {@link NATIVE_DOM_EVENTS} (the same 38-event\n * set the JSX tool injects, in Svelte-4 `on:` directive form, lib.dom types only)\n * so those handlers type-check on every element.\n *\n * The tool's `BaseProps` omits `role`, `tabindex`, `aria-*`, and `data-*` (it spells\n * tab order as React's camelCase `tabIndex`), and the generated element type\n * *replaces* the tag's intrinsic type \u2014 so `<auro-button aria-label=\"Save\" />` and\n * `<auro-button tabindex=\"0\" />` are flagged as unknown props.\n * {@link injectGlobalAttributes} (`svelteGlobals: true`, since Svelte's `BaseProps`\n * lacks even the lowercase `role` / `tabindex` HTML globals) splices those plus the\n * standard ARIA / `data-*` set into `BaseProps`; the tool exposes no option for it.\n *\n * Post-processing passes fix what the community tool can't express on its own:\n * {@link labelComponentMembers} (mark component-owned members so IntelliSense\n * distinguishes them from inherited global HTML attributes),\n * {@link addSvelte5EventHandlers} (Svelte 4 *and* 5 event syntax \u2014 this also\n * derives the Svelte-5 property form of the native events above),\n * {@link injectGlobalAttributes} (ARIA / `data-*` into `BaseProps`), and\n * {@link globalizeSvelteNamespace} (global vs module-scoped augmentation).\n *\n * @see docs/pt-m2-completion-plan.md \u2192 build-order step 2.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { generateSvelteTypes } from \"custom-element-svelte-integration\";\nimport {\n SVELTE_TYPES_FILENAME,\n SVELTE_TYPES_PATH,\n} from \"#init/editors/layout.js\";\nimport {\n buildManifest,\n type EditorArtifact,\n ensureTrailingNewline,\n injectGlobalAttributes,\n withTempDir,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/**\n * The exact module-scoped `svelteHTML` augmentation the community tool emits\n * (prettier-formatted, so this matches the bytes it writes). Because the\n * generated file has top-level `import`/`export`, it is a *module* \u2014 a plain\n * `declare namespace svelteHTML` inside it is module-scoped and never merges\n * into the global `svelteHTML` the Svelte language server actually reads, so\n * element completion silently does nothing. See {@link globalizeSvelteNamespace}.\n */\nconst MODULE_SCOPED_SVELTE_NAMESPACE = `declare namespace svelteHTML {\n // eslint-disable-next-line @typescript-eslint/no-empty-interface\n interface IntrinsicElements extends CustomElements {}\n}`;\n\n/** The global-scoped replacement that merges into the language server's `svelteHTML`. */\nconst GLOBAL_SVELTE_NAMESPACE = `declare global {\n namespace svelteHTML {\n // eslint-disable-next-line @typescript-eslint/no-empty-interface\n interface IntrinsicElements extends CustomElements {}\n }\n}`;\n\n/**\n * Native DOM event handlers to fold into the shared `BaseEvents` type via the\n * tool's `globalEvents` option (spliced verbatim inside `type BaseEvents = {\u2026}`).\n * Mirrors the 38 events `@wc-toolkit/jsx-types` injects with\n * `includeDefaultDOMEvents`, translated to real DOM event names in Svelte-4\n * `\"on:<name>\"` directive form; {@link addSvelte5EventHandlers} then derives the\n * Svelte-5 `\"on<name>\"` property sibling for each. All handler types are lib.dom\n * globals, so the artifact stays self-contained (no `svelte/elements` import).\n *\n * Ends with a trailing newline and 2-space indentation so it slots cleanly\n * between the tool's `type BaseEvents = {` and `};`.\n */\nconst NATIVE_DOM_EVENTS = `\n // Mouse events\n \"on:click\"?: (e: MouseEvent) => void;\n \"on:contextmenu\"?: (e: MouseEvent) => void;\n \"on:dblclick\"?: (e: MouseEvent) => void;\n \"on:mousedown\"?: (e: MouseEvent) => void;\n \"on:mouseenter\"?: (e: MouseEvent) => void;\n \"on:mouseleave\"?: (e: MouseEvent) => void;\n \"on:mousemove\"?: (e: MouseEvent) => void;\n \"on:mouseout\"?: (e: MouseEvent) => void;\n \"on:mouseover\"?: (e: MouseEvent) => void;\n \"on:mouseup\"?: (e: MouseEvent) => void;\n // Drag events\n \"on:drag\"?: (e: DragEvent) => void;\n \"on:dragend\"?: (e: DragEvent) => void;\n \"on:dragenter\"?: (e: DragEvent) => void;\n \"on:dragexit\"?: (e: DragEvent) => void;\n \"on:dragleave\"?: (e: DragEvent) => void;\n \"on:dragover\"?: (e: DragEvent) => void;\n \"on:dragstart\"?: (e: DragEvent) => void;\n \"on:drop\"?: (e: DragEvent) => void;\n // Keyboard events\n \"on:keydown\"?: (e: KeyboardEvent) => void;\n \"on:keyup\"?: (e: KeyboardEvent) => void;\n \"on:keypress\"?: (e: KeyboardEvent) => void;\n // Focus events\n \"on:focus\"?: (e: FocusEvent) => void;\n \"on:blur\"?: (e: FocusEvent) => void;\n // Form events\n \"on:change\"?: (e: Event) => void;\n \"on:input\"?: (e: Event) => void;\n \"on:submit\"?: (e: Event) => void;\n \"on:reset\"?: (e: Event) => void;\n // Scroll / wheel events\n \"on:scroll\"?: (e: UIEvent) => void;\n \"on:wheel\"?: (e: WheelEvent) => void;\n // Animation / transition events\n \"on:animationstart\"?: (e: AnimationEvent) => void;\n \"on:animationend\"?: (e: AnimationEvent) => void;\n \"on:animationiteration\"?: (e: AnimationEvent) => void;\n \"on:transitionend\"?: (e: TransitionEvent) => void;\n // Resource events\n \"on:load\"?: (e: Event) => void;\n \"on:error\"?: (e: Event) => void;\n // Clipboard events\n \"on:copy\"?: (e: ClipboardEvent) => void;\n \"on:cut\"?: (e: ClipboardEvent) => void;\n \"on:paste\"?: (e: ClipboardEvent) => void;\n`;\n\n/**\n * The community tool emits every event handler in Svelte 4 *directive* form only\n * \u2014 `\"on:${event.name}\"?: (e: CustomEvent<\u2026>) => void;` (its index.js:295). Svelte\n * 5 replaced the `on:event` directive with plain event-handler **properties**\n * (`<el onclick={\u2026}>`), so a Svelte 5 component that writes `onclick={\u2026}` finds no\n * matching member on the element type and the language server flags it.\n *\n * For each emitted `\"on:NAME\"?: <handler>;` line, emit an additional sibling\n * `\"onNAME\"?: <handler>;` carrying the identical `CustomEvent` signature, so both\n * the Svelte 4 directive and the Svelte 5 property form resolve against the same\n * event type. The `on` + verbatim-name convention matches what the JSX tool\n * already emits. Components with no events produce no matches and pass through\n * unchanged, so this is a safe no-op when there is nothing to augment.\n */\nconst SVELTE4_EVENT_HANDLER = /^([ \\t]*)\"on:([^\"]+)\"(\\?:.*=> void;)$/gmu;\n\nfunction addSvelte5EventHandlers(contents: string): string {\n return contents.replace(\n SVELTE4_EVENT_HANDLER,\n (_match, indent, name, handler) =>\n `${indent}\"on:${name}\"${handler}\\n${indent}\"on${name}\"${handler}`,\n );\n}\n\n/**\n * Resolve name collisions between a component's CEM members and the shared\n * `BaseProps`/`BaseEvents` blocks \u2014 ASYMMETRICALLY, because the right winner\n * differs for events vs global attributes.\n *\n * Every element is mapped as `Partial<<Name>Props & BaseProps & BaseEvents>`.\n * `BaseProps` carries the inherited global HTML attributes (`tabindex`, `id`,\n * `role`, \u2026) and {@link NATIVE_DOM_EVENTS} folds 38 native handlers into\n * `BaseEvents`. A TypeScript intersection of object types intersects SAME-NAMED\n * members, so any name a component redeclares collides with the base copy \u2014 and a\n * bare intersection breaks a legitimate value two different ways:\n *\n * \u2022 Events \u2014 a CEM event named like a native one (`input`, `click`, `change`,\n * `submit`, `load`, `error`, `scroll`, \u2026) is in both `<Name>Props` (typed\n * `(e: CustomEvent<\u2026>) => void`) and `BaseEvents` (typed `(e: Event | \u2026) =>\n * void`). The member becomes `((e: CustomEvent) => void) & ((e: Event) =>\n * void)`; a handler must satisfy BOTH, and the intended CustomEvent handler is\n * rejected by the native half (parameter contravariance).\n * \u2022 Attributes \u2014 a CEM attribute whose type differs from the injected global\n * (auro-button documents `tabindex` as a `string` for its `.tabindex` property\n * form, while the global `tabindex` is deliberately `number` \u2014 svelte2tsx\n * coerces the literal in `tabindex=\"0\"` to a number; see {@link\n * injectGlobalAttributes}). The member becomes `string & number` = `never`,\n * which under `Partial<>` is `undefined`, so even a valid `tabindex=\"0\"` is\n * rejected.\n *\n * The winner differs by kind:\n *\n * \u2022 For EVENTS the component wins \u2014 its CEM `CustomEvent` signature is strictly\n * more precise than the generic native handler, so `BaseEvents` yields the\n * colliding name: `Omit<BaseEvents, keyof <Name>Props>`.\n * \u2022 For global ATTRIBUTES the base wins \u2014 the global carries the framework's\n * coercion-aware typing (`tabindex: number`), which a CEM restating the\n * attribute as a raw `string` would only degrade, so the component's props\n * yield the colliding global names: `Omit<<Name>Props, keyof BaseProps>`.\n *\n * Net mapping:\n * `Partial<Omit<<Name>Props, keyof BaseProps> & BaseProps & Omit<BaseEvents, keyof <Name>Props>>`.\n * A component-only attribute (`variant`, `shape`, \u2026) is in neither base block, so\n * it is untouched; a component that redeclares nothing collides on nothing.\n */\nconst CUSTOM_ELEMENT_MAPPING =\n /^(\\s*\"[^\"]+\": Partial<)(\\w+)Props & BaseProps & BaseEvents(>;)$/gm;\n\nfunction overrideCollidingBaseMembers(contents: string): string {\n let matched = false;\n const next = contents.replace(\n CUSTOM_ELEMENT_MAPPING,\n (_match, head, name, tail) => {\n matched = true;\n return (\n `${head}Omit<${name}Props, keyof BaseProps> & BaseProps &` +\n ` Omit<BaseEvents, keyof ${name}Props>${tail}`\n );\n },\n );\n // A silent no-op would ship the un-rewritten `Partial<<Name>Props & BaseProps &\n // BaseEvents>` form, whose same-named members collapse (a native-named CEM event\n // to an unsatisfiable intersection, a restated global attribute to `never`) \u2014\n // invisibly, until a consumer hits it. Mirror globalizeSvelteNamespace: if the\n // expected element mapping isn't present, the upstream format drifted, so fail\n // loudly here rather than downstream in the tsc smoke.\n if (!matched) {\n throw new Error(\n \"custom-element-svelte-integration no longer emits the expected \" +\n \"`Partial<<Name>Props & BaseProps & BaseEvents>` element mapping; the \" +\n \"base-member collision rewrite in svelteTypes.ts must be updated to \" +\n \"match the new output.\",\n );\n }\n return next;\n}\n\n/**\n * Matches one generated per-component props block \u2014\n * `type <ClassName>Props = {\\n \u2026members\u2026 \\n};` \u2014 capturing the class-name stem\n * (group 1, e.g. `AuroButton` from `AuroButtonProps`) and the block body (group\n * 2). The trailing `\\n};` at column 0 bounds the block; member lines are indented\n * so the non-greedy body stops at the first closing brace. This also matches the\n * fixed `BaseProps` block, which {@link labelComponentMembers} filters out by\n * class name (`BaseEvents` has no `Props` suffix, so it never matches).\n */\nconst PROPS_BLOCK = /^type (\\w+)Props = \\{\\n([\\s\\S]*?)\\n\\};$/gm;\n\n/** Start of every single-line JSDoc the tool emits for a component member. */\nconst MEMBER_JSDOC_OPEN = /\\/\\*\\* /g;\n\n/**\n * The Svelte language server flattens each element's type\n * (`Partial<<Name>Props & BaseProps & BaseEvents>`) into one alphabetized\n * completion list with identical icons, so a component's own members (`variant`,\n * `shape`) are visually indistinguishable from the inherited global HTML\n * attributes (`id`, `class`, `title`). We can't change the icon or grouping (the\n * language server owns those), but we *can* prefix a marker into the JSDoc that\n * shows in the hover/completion docs pane.\n *\n * For every member inside a per-component `type <Name>Props` block, prefix\n * `\u3010<label>\u3011 ` onto its JSDoc. `<label>` is the tag the consumer actually\n * writes in markup \u2014 the registered tag when the project renamed it, falling back\n * to the component class name when it kept the default `auro-*` tag (so the marker\n * never just echoes the obvious default). `markerByClass` is keyed by class name\n * (`declaration.name`), which is exactly the `<Name>` stem of each props block.\n * Blocks whose stem is not a known component \u2014 `BaseProps` \u2014 are returned\n * untouched, so inherited attributes stay unmarked and remain the visual \"other\"\n * group. Members without JSDoc (e.g. the Svelte 5 `\"onNAME\"` handler sibling) have\n * nothing to prefix and pass through unchanged.\n */\nfunction labelComponentMembers(\n contents: string,\n markerByClass: ReadonlyMap<string, string>,\n): string {\n return contents.replace(PROPS_BLOCK, (whole, className, body) => {\n const label = markerByClass.get(className);\n if (label === undefined) {\n return whole;\n }\n const marked = body.replace(MEMBER_JSDOC_OPEN, `/** \u3010${label}\u3011 `);\n return `type ${className}Props = {\\n${marked}\\n};`;\n });\n}\n\n/**\n * Build the class-name \u2192 marker-label map {@link labelComponentMembers} consumes.\n * The label is the registered tag (what the consumer writes in markup); when the\n * project kept the component's default `auro-*` tag we fall back to the class name\n * rather than repeat the obvious default. Keyed by `declaration.name` to match the\n * `<Name>Props` block stems the tool emits.\n */\nfunction markerLabelsByClass(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): Map<string, string> {\n return new Map(\n components.map((component) => {\n const defaultTag = component.tagName;\n const resolvedTag = resolvedTags.get(defaultTag) ?? defaultTag;\n const label =\n resolvedTag === defaultTag ? component.declaration.name : resolvedTag;\n return [component.declaration.name, label];\n }),\n );\n}\n\n/**\n * Wrap the tool's module-scoped `declare namespace svelteHTML` in `declare\n * global { \u2026 }` so it augments the global `svelteHTML` namespace the Svelte\n * language server reads \u2014 the same pattern auro-cli's own per-component\n * `addDtsExportsPlugin` already emits. Without this the augmentation is inert in\n * a module file and Svelte element completion never appears.\n *\n * Throws if the expected block is absent (e.g. an upstream reflow of\n * `custom-element-svelte-integration`) rather than returning the string\n * unchanged \u2014 a silent no-op would ship the broken module-scoped form, so we\n * surface the drift as a loud, test-caught failure instead.\n */\nfunction globalizeSvelteNamespace(contents: string): string {\n if (!contents.includes(MODULE_SCOPED_SVELTE_NAMESPACE)) {\n throw new Error(\n \"custom-element-svelte-integration no longer emits the expected \" +\n \"`declare namespace svelteHTML` block; the global-augmentation rewrite \" +\n \"in svelteTypes.ts must be updated to match the new output.\",\n );\n }\n return contents.replace(\n MODULE_SCOPED_SVELTE_NAMESPACE,\n GLOBAL_SVELTE_NAMESPACE,\n );\n}\n\n/**\n * Render the Svelte `.d.ts` for the resolved component set. Returns the\n * artifact's project-root-relative path plus its contents; writing is the\n * caller's job.\n */\nexport function buildSvelteTypes(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact {\n const manifest = buildManifest(components, resolvedTags);\n const markerByClass = markerLabelsByClass(components, resolvedTags);\n\n const contents = withTempDir((outdir) => {\n generateSvelteTypes(manifest, {\n outdir,\n fileName: SVELTE_TYPES_FILENAME,\n hideLogs: true,\n // Fold native DOM event handlers into the shared BaseEvents type; a CEM\n // only declares a component's own events, so without this native handlers\n // are absent. addSvelte5EventHandlers derives the Svelte-5 property form.\n globalEvents: NATIVE_DOM_EVENTS,\n // No `componentTypePath`: inline the CEM's `type.text` (real unions) instead\n // of `Component['field']`, which resolves to `any` against the packages'\n // unresolvable class .d.ts. See the module header for the full rationale.\n });\n return readFileSync(join(outdir, SVELTE_TYPES_FILENAME), \"utf-8\");\n });\n\n return {\n filename: SVELTE_TYPES_PATH,\n contents: ensureTrailingNewline(\n globalizeSvelteNamespace(\n overrideCollidingBaseMembers(\n injectGlobalAttributes(\n addSvelte5EventHandlers(\n labelComponentMembers(contents, markerByClass),\n ),\n // Svelte's BaseProps lacks the lowercase `role` / `tabindex` HTML\n // globals too, so add them alongside the ARIA set.\n { svelteGlobals: true },\n ),\n ),\n ),\n ),\n };\n}\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport { AURO_COMPONENT_PACKAGES } from \"#static/auroComponents.js\";\nimport {\n type AuroComponent,\n buildAuroContext,\n renderComponentRows,\n STATIC_COMPONENTS,\n} from \"#static/auroContext.js\";\nimport { clean, type Manifest } from \"#utils/cem.js\";\nimport { installedFromOutcomes } from \"#utils/detectInstalled.js\";\nimport { fetchManifest } from \"#utils/fetchManifest.js\";\nimport { checkOutdated, renderOutdatedBanner } from \"#utils/outdated.js\";\n\n/**\n * Build the Component Reference body, starting from the curated component set\n * and overriding each component's package and description with Custom Elements\n * Manifest data \u2014 preferring a locally installed copy, falling back to unpkg.\n * Seeding from the curated set guarantees every component is listed even before\n * it publishes a CEM, while live data keeps the descriptions of those that do\n * current. Returns the assembled table body, how many components were enriched,\n * and the installed version of every package resolved from local node_modules.\n */\nasync function buildComponentTable(allowNetwork: boolean): Promise<{\n rows: string;\n resolved: number;\n enriched: number;\n local: Map<string, string>;\n}> {\n // Curated set is the base \u2014 keyed by tag, insertion order preserved so the\n // reference stays stable and no component is ever dropped.\n const byTag = new Map<string, AuroComponent>();\n for (const component of STATIC_COMPONENTS) {\n byTag.set(component.tag, { ...component });\n }\n\n const outcomes = await Promise.all(\n AURO_COMPONENT_PACKAGES.map((pkg) => fetchManifest(pkg, { allowNetwork })),\n );\n\n // The installed-version map is the shared \"detect installed\" concern \u2014 derive\n // it from the same outcomes so the rule lives in one place (detectInstalled).\n const local = new Map<string, string>(\n installedFromOutcomes(outcomes).map((component) => [\n component.pkg,\n component.version,\n ]),\n );\n let resolved = 0;\n let enriched = 0;\n for (const outcome of outcomes) {\n if (!outcome.manifest) {\n continue;\n }\n // A manifest was fetched (local or unpkg) regardless of whether any of its\n // declarations document a description \u2014 this is what distinguishes \"found\n // nothing\" from \"found manifests that happen to be undocumented\".\n resolved += 1;\n // Only real registered elements \u2014 a declaration can be customElement: true\n // yet be an internal base class with no tagName.\n const declarations = ((outcome.manifest as Manifest).modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName);\n for (const decl of declarations) {\n const tag = decl.tagName as string;\n const liveDescription = clean(decl.summary || decl.description);\n const existing = byTag.get(tag);\n byTag.set(tag, {\n tag,\n pkg: outcome.target,\n description: liveDescription || existing?.description || \"\",\n });\n if (liveDescription) {\n enriched += 1;\n }\n }\n }\n\n return {\n rows: renderComponentRows([...byTag.values()]),\n resolved,\n enriched,\n local,\n };\n}\n\n/**\n * Compare each locally installed package against the latest published release\n * and report any that are behind. Best-effort and network-dependent \u2014 advisory\n * output goes to stderr so it never pollutes the context document on stdout.\n */\nasync function reportOutdated(local: Map<string, string>): Promise<void> {\n const spinner = ora(\"Checking for newer component releases...\").start();\n const outdated = await checkOutdated(local);\n\n if (outdated.length === 0) {\n spinner.succeed(\"All installed Auro components are on the latest release.\");\n return;\n }\n\n // Stop the spinner without its own icon/line \u2014 the banner below carries the\n // warning, and a leftover spinner line would dilute it.\n spinner.stop();\n // stderr \u2014 keep the generated document (stdout) clean. A bordered, bold banner\n // so the notice stands out from the streamed markdown context on stdout rather\n // than scrolling past unnoticed.\n console.error(renderOutdatedBanner(outdated));\n}\n\n/** Options accepted by the `context` action. */\nexport interface ContextOptions {\n output?: string;\n offline?: boolean;\n}\n\n/**\n * Generate the Auro AI-assistant context document and either write it to\n * `options.output` or stream it to stdout. With `--offline`, only locally\n * installed manifests (and the built-in table) are used; online, manifests are\n * enriched from local node_modules or unpkg and outdated installs are flagged on\n * stderr. Exits non-zero only when writing the output file fails.\n */\nexport async function runContext(options: ContextOptions): Promise<void> {\n const online = !options.offline;\n\n const spinner = ora(\n online\n ? \"Resolving component manifests...\"\n : \"Reading installed component manifests...\",\n ).start();\n const { rows, resolved, enriched, local } = await buildComponentTable(online);\n const context = buildAuroContext(rows);\n\n if (online) {\n // Online success is measured by descriptions enriched from any source\n // (local or unpkg); a run that resolves nothing falls back to the table.\n if (enriched > 0) {\n // `enriched` counts component descriptions (one package can export many),\n // while `local.size` counts packages \u2014 label each so the two aren't\n // conflated (e.g. a single package exporting 6 components reads as \"6\").\n // With nothing installed, enrichment came entirely from unpkg; saying\n // \"0 package(s) from local node_modules\" would read as a contradiction.\n spinner.succeed(\n local.size > 0\n ? `Enriched ${enriched} component description(s); ${local.size} package(s) resolved from local node_modules.`\n : `Enriched ${enriched} component description(s) from unpkg.`,\n );\n } else if (resolved > 0) {\n // Manifests were fetched but none documented an element description \u2014 the\n // table is complete, just not enriched. Gate this on `resolved`, not\n // `enriched`, so we don't claim \"No manifests available\" when some were.\n spinner.succeed(\n `Resolved ${resolved} component manifest(s); none documented a description, using the built-in table.`,\n );\n } else {\n spinner.warn(\n \"No manifests available; using the built-in component table.\",\n );\n }\n } else {\n // Offline success is measured by manifests *found* in node_modules, not by\n // descriptions enriched \u2014 an installed manifest can document no element\n // description (e.g. auro-button@12.3.0) yet is still a valid local read.\n if (local.size > 0) {\n spinner.succeed(\n enriched > 0\n ? `Read ${local.size} installed component manifest(s) from local node_modules; enriched ${enriched} description(s).`\n : `Read ${local.size} installed component manifest(s) from local node_modules; none documented a description, using the built-in table.`,\n );\n } else {\n spinner.warn(\n \"No installed component manifests found; using the built-in component table.\",\n );\n }\n }\n\n if (options.output) {\n const writeSpinner = ora(`Writing context to ${options.output}...`).start();\n try {\n const outputPath = path.resolve(process.cwd(), options.output);\n await fs.writeFile(outputPath, context, \"utf-8\");\n writeSpinner.succeed(`Auro context written to ${options.output}`);\n // Advisory only \u2014 keep it on stderr so `--output FILE` callers that capture\n // stdout don't get this line mixed into their capture.\n console.error(\n \"\\nPaste this file into your AI coding tool (Claude, Cursor, Copilot, etc.) to prime it on Auro components.\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n writeSpinner.fail(`Failed to write context: ${message}`);\n process.exit(1);\n }\n } else {\n process.stdout.write(context);\n }\n\n // Advisory only, and needs the network \u2014 skip in offline mode.\n if (online && local.size > 0) {\n await reportOutdated(local);\n }\n}\n\nexport default program\n .command(\"context\")\n .description(\n \"Generate an AI assistant context document for the Auro Design System\",\n )\n .option(\n \"-o, --output <path>\",\n \"Write context to a file instead of stdout (e.g. AURO_CONTEXT.md)\",\n )\n .option(\n \"--offline\",\n \"Skip network fetches; use locally installed manifests and the built-in table\",\n false,\n )\n .action(runContext);\n", "const AURO_CONTEXT_HEADER = `# Auro Design System \u2014 AI Assistant Context\nAlaska Airlines open-source design system | https://auro.alaskaair.com\n\n## What is Auro?\nAuro is Alaska Airlines' design system built on Web Components (Custom Elements v1) using the Lit library.\n- npm scope: \\`@aurodesignsystem/\\` (current), \\`@alaskaairux/\\` (legacy)\n- Framework-agnostic: works with React, Angular, Vue, Svelte, or plain HTML\n- Each component is a separate npm package\n- All components use the \\`<auro-*>\\` custom element tag\n\n## Rules for Writing Auro Code\n\n1. **Use \\`<auro-*>\\` custom element tags \u2014 never plain HTML equivalents**\n - \u2717 \\`<button>\\` \u2192 \u2713 \\`<auro-button>\\`\n - \u2717 \\`<a href=\"...\">\\` \u2192 \u2713 \\`<auro-hyperlink href=\"...\">\\`\n - \u2717 \\`<input>\\` \u2192 \u2713 \\`<auro-input>\\` (from auro-formkit)\n\n2. **Install and register each component before use**\n \\`\\`\\`bash\n npm install @aurodesignsystem/auro-button\n \\`\\`\\`\n \\`\\`\\`js\n import \"@aurodesignsystem/auro-button\"; // registers <auro-button> globally\n \\`\\`\\`\n\n3. **Props are HTML attributes in templates; camelCase properties in JS**\n \\`\\`\\`html\n <auro-button disabled loading>Save</auro-button>\n \\`\\`\\`\n \\`\\`\\`js\n document.querySelector('auro-button').loading = true;\n \\`\\`\\`\n\n4. **Content goes in named slots, not innerHTML**\n \\`\\`\\`html\n <auro-dialog>\n <span slot=\"header\">Title</span>\n <div slot=\"content\">Body content here</div>\n </auro-dialog>\n \\`\\`\\`\n\n5. **Design tokens are CSS custom properties**\n \\`\\`\\`bash\n npm install @aurodesignsystem/design-tokens\n \\`\\`\\`\n \\`\\`\\`css\n @import \"@aurodesignsystem/design-tokens/dist/themes/CSSCustomProperties--bundled.css\";\n \\`\\`\\`\n Token naming: \\`--ds-basic-*\\` and \\`--ds-advanced-*\\` (e.g. \\`--ds-advanced-color-*\\`, \\`--ds-basic-color-*\\`)\n\n## Component Reference\n\n`;\n\n/** The Markdown table header rows the component-reference body sits under. */\nconst COMPONENT_TABLE_HEADER = `| Element Tag | Package | Description |\n|---|---|---|`;\n\n/** A single component's entry in the curated Component Reference. */\nexport interface AuroComponent {\n /** The custom element tag, without angle brackets \u2014 e.g. \\`auro-button\\`. */\n tag: string;\n /** The npm package that publishes the component. */\n pkg: string;\n /** One-line description shown in the Component Reference table. */\n description: string;\n}\n\n/**\n * Curated component data, used as the offline fallback and as the base set the\n * \\`auro context\\` command enriches with live Custom Elements Manifest data.\n * Descriptions here are hand-written and may lag the published manifests \u2014\n * \\`auro context\\` overrides them with live manifest data where available, but\n * always keeps every component listed so nothing is dropped before a component\n * publishes a CEM.\n */\nexport const STATIC_COMPONENTS: AuroComponent[] = [\n {\n tag: \"auro-accordion\",\n pkg: \"@aurodesignsystem/auro-accordion\",\n description: \"Expandable content sections\",\n },\n {\n tag: \"auro-alert\",\n pkg: \"@aurodesignsystem/auro-alert\",\n description: \"Inline status messages: error, warning, success, information\",\n },\n {\n tag: \"auro-avatar\",\n pkg: \"@aurodesignsystem/auro-avatar\",\n description: \"User or entity avatar\",\n },\n {\n tag: \"auro-background\",\n pkg: \"@aurodesignsystem/auro-background\",\n description: \"Themed background wrapper\",\n },\n {\n tag: \"auro-backtotop\",\n pkg: \"@aurodesignsystem/auro-backtotop\",\n description: \"Scroll-to-top button\",\n },\n {\n tag: \"auro-badge\",\n pkg: \"@aurodesignsystem/auro-badge\",\n description: \"Status or count badge\",\n },\n {\n tag: \"auro-banner\",\n pkg: \"@aurodesignsystem/auro-banner\",\n description: \"Full-width promotional banner\",\n },\n {\n tag: \"auro-button\",\n pkg: \"@aurodesignsystem/auro-button\",\n description: \"Interactive button; supports `loading`, `disabled`, `shape`\",\n },\n {\n tag: \"auro-card\",\n pkg: \"@aurodesignsystem/auro-card\",\n description: \"Content card container\",\n },\n {\n tag: \"auro-carousel\",\n pkg: \"@aurodesignsystem/auro-carousel\",\n description: \"Horizontally scrollable carousel\",\n },\n {\n tag: \"auro-datetime\",\n pkg: \"@aurodesignsystem/auro-datetime\",\n description: \"Localized date and time formatting\",\n },\n {\n tag: \"auro-dialog\",\n pkg: \"@aurodesignsystem/auro-dialog\",\n description: \"Modal dialog; slots: header, content, footer\",\n },\n {\n tag: \"auro-drawer\",\n pkg: \"@aurodesignsystem/auro-drawer\",\n description: \"Slide-in panel; slots: header, content, footer\",\n },\n {\n tag: \"auro-flight\",\n pkg: \"@aurodesignsystem/auro-flight\",\n description: \"Flight segment display (origin, destination, stops)\",\n },\n {\n tag: \"auro-flightline\",\n pkg: \"@aurodesignsystem/auro-flightline\",\n description: \"Visual flight path/stop indicator\",\n },\n {\n tag: \"auro-input\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Text input field\",\n },\n {\n tag: \"auro-select\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Select/dropdown\",\n },\n {\n tag: \"auro-datepicker\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Date picker input\",\n },\n {\n tag: \"auro-combobox\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Combobox with search\",\n },\n {\n tag: \"auro-checkbox\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Checkbox input\",\n },\n {\n tag: \"auro-radio\",\n pkg: \"@aurodesignsystem/auro-formkit\",\n description: \"Radio button input\",\n },\n {\n tag: \"auro-header\",\n pkg: \"@aurodesignsystem/auro-header\",\n description: \"Page/section heading\",\n },\n {\n tag: \"auro-hyperlink\",\n pkg: \"@aurodesignsystem/auro-hyperlink\",\n description: \"Accessible anchor link\",\n },\n {\n tag: \"auro-icon\",\n pkg: \"@aurodesignsystem/auro-icon\",\n description: \"Alaska Airlines icon: `category` + `name` attributes\",\n },\n {\n tag: \"auro-loader\",\n pkg: \"@aurodesignsystem/auro-loader\",\n description: \"Loading spinner\",\n },\n {\n tag: \"auro-lockup\",\n pkg: \"@aurodesignsystem/auro-lockup\",\n description: \"Image + text layout lockup\",\n },\n {\n tag: \"auro-nav\",\n pkg: \"@aurodesignsystem/auro-nav\",\n description: \"Secondary navigation aid (relation to higher-level pages)\",\n },\n {\n tag: \"auro-pane\",\n pkg: \"@aurodesignsystem/auro-pane\",\n description: \"Selectable shoulder dates with associated prices\",\n },\n {\n tag: \"auro-popover\",\n pkg: \"@aurodesignsystem/auro-popover\",\n description: \"Tooltip-style popover\",\n },\n {\n tag: \"auro-sidenav\",\n pkg: \"@aurodesignsystem/auro-sidenav\",\n description: \"Vertical side navigation\",\n },\n {\n tag: \"auro-skeleton\",\n pkg: \"@aurodesignsystem/auro-skeleton\",\n description: \"Loading placeholder skeleton\",\n },\n {\n tag: \"auro-slideshow\",\n pkg: \"@aurodesignsystem/auro-slideshow\",\n description: \"Image/content slideshow\",\n },\n {\n tag: \"auro-table\",\n pkg: \"@aurodesignsystem/auro-table\",\n description: \"Accessible data table\",\n },\n {\n tag: \"auro-tabs\",\n pkg: \"@aurodesignsystem/auro-tabs\",\n description: \"Tabbed content panels\",\n },\n {\n tag: \"auro-tail\",\n pkg: \"@aurodesignsystem/auro-tail\",\n description: \"Alaska, Hawaiian, and partner airline tail graphics\",\n },\n {\n tag: \"auro-toast\",\n pkg: \"@aurodesignsystem/auro-toast\",\n description: \"Transient notification toast\",\n },\n {\n tag: \"auro-tokenlist\",\n pkg: \"@aurodesignsystem/auro-tokenlist\",\n description: \"Design token display utilities\",\n },\n];\n\n/**\n * Render a set of components as the Markdown Component Reference body (the\n * \\`| tag | package | description |\\` rows, without the header). Pipes in\n * descriptions are escaped so they don't break the table.\n */\nexport function renderComponentRows(\n components: readonly AuroComponent[],\n): string {\n return components\n .map(\n (component) =>\n `| \\`<${component.tag}>\\` | \\`${component.pkg}\\` | ${component.description.replace(/\\|/gu, \"\\\\|\")} |`,\n )\n .join(\"\\n\");\n}\n\n/**\n * Hand-written component-reference table body, used as the offline fallback\n * when the live Custom Elements Manifests can't be fetched.\n */\nexport const STATIC_COMPONENT_TABLE = renderComponentRows(STATIC_COMPONENTS);\n\nconst AURO_CONTEXT_FOOTER = `## Common Patterns\n\n### Button (default, secondary, tertiary)\n\\`\\`\\`html\n<auro-button>Primary</auro-button>\n<auro-button variant=\"secondary\">Secondary</auro-button>\n<auro-button variant=\"tertiary\">Tertiary</auro-button>\n<auro-button loading>Saving...</auro-button>\n\\`\\`\\`\n\n### Alert\n\\`\\`\\`html\n<auro-alert type=\"success\">Changes saved.</auro-alert>\n<auro-alert type=\"error\">Something went wrong.</auro-alert>\n<auro-alert type=\"warning\">Please review before continuing.</auro-alert>\n<auro-alert type=\"information\">Your flight departs at 9am.</auro-alert>\n\\`\\`\\`\n\n### Form inputs (auro-formkit)\nauro-formkit has no root export \u2014 always import the specific sub-component.\nThe field label is a **slot**, not an attribute.\n\\`\\`\\`js\nimport \"@aurodesignsystem/auro-formkit/auro-input\";\nimport \"@aurodesignsystem/auro-formkit/auro-select\";\n\\`\\`\\`\n\\`\\`\\`html\n<auro-input required>\n <span slot=\"label\">First name</span>\n</auro-input>\n<auro-select>\n <span slot=\"label\">Seat preference</span>\n <auro-menu>\n <auro-menuoption value=\"window\">Window</auro-menuoption>\n <auro-menuoption value=\"aisle\">Aisle</auro-menuoption>\n </auro-menu>\n</auro-select>\n\\`\\`\\`\n\n### Icon\nSet \\`category\\` and \\`name\\`. Icon names are exact \u2014 check the icon library for the correct name.\n\\`\\`\\`html\n<auro-icon category=\"interface\" name=\"arrow-right\"></auro-icon>\n<auro-icon category=\"terminal\" name=\"plane-side-fill\"></auro-icon>\n\\`\\`\\`\n\n### Hyperlink\n\\`\\`\\`html\n<auro-hyperlink href=\"/flights\">View flights</auro-hyperlink>\n<auro-hyperlink href=\"https://example.com\" target=\"_blank\">External link</auro-hyperlink>\n\\`\\`\\`\n\n### Dialog (modal)\n\\`\\`\\`js\ndocument.querySelector('#confirmDialog').show();\n\\`\\`\\`\n\\`\\`\\`html\n<auro-dialog id=\"confirmDialog\">\n <span slot=\"header\">Confirm booking</span>\n <div slot=\"content\">Are you sure you want to book this flight?</div>\n <div slot=\"footer\">\n <auro-button>Confirm</auro-button>\n <auro-button variant=\"secondary\">Cancel</auro-button>\n </div>\n</auro-dialog>\n\\`\\`\\`\n\n## Accessibility Notes\n- Use the \\`ariaLabel\\` slot on \\`<auro-button>\\` for icon-only buttons\n- \\`<auro-hyperlink>\\` adds rel=\"noopener noreferrer\" automatically for external links\n- All \\`auro-formkit\\` components handle aria-invalid and error messaging built-in\n- All components meet WCAG 2.1 AA\n\n## Documentation\n- Component docs: https://auro.alaskaair.com\n- Component status: https://auro.alaskaair.com/component-status\n- Design tokens: https://auro.alaskaair.com/getting-started/developers/token-usage\n- Contributing: https://auro.alaskaair.com/getting-started/developers/contributing\n- GitHub: https://github.com/AlaskaAirlines\n`;\n\n/**\n * Assemble the full AI-assistant context document from a Component Reference\n * table body (the \\`| tag | package | description |\\` rows, without the header).\n * The surrounding prose \u2014 rules, patterns, accessibility notes \u2014 is static; only\n * the component table varies between the live-manifest and fallback versions.\n */\nexport function buildAuroContext(componentTable: string): string {\n return `${AURO_CONTEXT_HEADER}${COMPONENT_TABLE_HEADER}\\n${componentTable}\\n\\n${AURO_CONTEXT_FOOTER}`;\n}\n\n/**\n * Fully static context document using the hand-written component table. Used as\n * the offline fallback when live manifests can't be fetched.\n */\nexport const AURO_CONTEXT = buildAuroContext(STATIC_COMPONENT_TABLE);\n", "/**\n * Shared Custom Elements Manifest (CEM) types and helpers used by the commands\n * that read `custom-elements.json` (cem, component, context). Keeping one copy\n * here avoids the shapes drifting across commands.\n */\n\nexport interface CemType {\n text?: string;\n}\n\nexport type Deprecated = boolean | string | undefined;\n\nexport interface CemAttribute {\n name: string;\n fieldName?: string;\n type?: CemType;\n default?: string;\n description?: string;\n summary?: string;\n deprecated?: Deprecated;\n}\n\nexport interface CemMember {\n kind: string;\n name: string;\n privacy?: string;\n static?: boolean;\n type?: CemType;\n default?: string;\n description?: string;\n summary?: string;\n deprecated?: Deprecated;\n return?: { type?: CemType };\n}\n\nexport interface CemSlot {\n name: string;\n description?: string;\n summary?: string;\n // The analyzer does not emit this for inline `@slot` tags (v0.11.0); optional so\n // a custom plugin that maps `@deprecated` onto slots stays type-compatible.\n deprecated?: Deprecated;\n}\n\nexport interface CemEvent {\n name: string;\n type?: CemType;\n description?: string;\n summary?: string;\n // The analyzer does not emit this for inline `@event`/`@fires` tags (v0.11.0);\n // optional so a custom plugin mapping `@deprecated` onto events stays compatible.\n deprecated?: Deprecated;\n}\n\nexport interface CemNamed {\n name: string;\n description?: string;\n}\n\nexport interface CemDeclaration {\n kind?: string;\n name: string;\n tagName?: string;\n customElement?: boolean;\n description?: string;\n summary?: string;\n superclass?: { name?: string };\n attributes?: CemAttribute[];\n members?: CemMember[];\n slots?: CemSlot[];\n events?: CemEvent[];\n cssParts?: CemNamed[];\n cssProperties?: CemNamed[];\n}\n\nexport interface CemModule {\n path?: string;\n declarations?: CemDeclaration[];\n [key: string]: unknown;\n}\n\nexport interface Manifest {\n schemaVersion?: string;\n modules?: CemModule[];\n [key: string]: unknown;\n}\n\n/**\n * Collapse whitespace (including embedded newlines from JSDoc descriptions) to a\n * single space so descriptions render on one line.\n */\nexport function clean(text: string | undefined): string {\n return (text ?? \"\").replace(/\\s+/gu, \" \").trim();\n}\n", "import chalk from \"chalk\";\nimport {\n formkitSubpathFor,\n isLegacyFormkitPackage,\n} from \"#static/formkitMigration.js\";\nimport { fetchLatestVersion } from \"#utils/fetchManifest.js\";\n\n/** A component whose installed version is behind its latest published release. */\nexport interface OutdatedComponent {\n pkg: string;\n installed: string;\n latest: string;\n}\n\nconst SEMVER =\n /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/u;\n\nfunction parseSemver(\n version: string,\n): { main: [number, number, number]; pre: string[] } | null {\n const match = SEMVER.exec(version.trim());\n if (!match) {\n return null;\n }\n return {\n main: [Number(match[1]), Number(match[2]), Number(match[3])],\n // Build metadata (after `+`) is ignored for precedence; only the prerelease\n // identifiers (after `-`) matter.\n pre: match[4] ? match[4].split(\".\") : [],\n };\n}\n\n/**\n * Compare two version strings by semver precedence. Returns a negative number\n * when `a` is older than `b`, a positive number when newer, and 0 when equal.\n * Numeric main segments compare numerically, and a version carrying a\n * prerelease tag (`13.0.0-beta.1`) ranks *below* the same version without one,\n * per the semver spec. Returns null when either side isn't valid semver, so a\n * caller can decline to guess rather than compare non-comparable strings.\n */\nexport function compareVersions(a: string, b: string): number | null {\n const pa = parseSemver(a);\n const pb = parseSemver(b);\n if (!pa || !pb) {\n return null;\n }\n\n for (let i = 0; i < 3; i += 1) {\n if (pa.main[i] !== pb.main[i]) {\n return pa.main[i] < pb.main[i] ? -1 : 1;\n }\n }\n\n // Equal main version: a release outranks any prerelease of the same version.\n if (pa.pre.length === 0 && pb.pre.length === 0) {\n return 0;\n }\n if (pa.pre.length === 0) {\n return 1;\n }\n if (pb.pre.length === 0) {\n return -1;\n }\n\n // Both prereleases: compare identifier by identifier (numeric < alphanumeric,\n // and a shorter set of identifiers has lower precedence when all else ties).\n const len = Math.max(pa.pre.length, pb.pre.length);\n for (let i = 0; i < len; i += 1) {\n const ai = pa.pre[i];\n const bi = pb.pre[i];\n if (ai === undefined) {\n return -1;\n }\n if (bi === undefined) {\n return 1;\n }\n const aNum = /^\\d+$/u.test(ai);\n const bNum = /^\\d+$/u.test(bi);\n if (aNum && bNum) {\n const diff = Number(ai) - Number(bi);\n if (diff !== 0) {\n return diff < 0 ? -1 : 1;\n }\n } else if (aNum !== bNum) {\n return aNum ? -1 : 1;\n } else if (ai !== bi) {\n return ai < bi ? -1 : 1;\n }\n }\n return 0;\n}\n\n/**\n * Compare each installed package against its latest published release and return\n * the ones that are behind. Best-effort and network-dependent \u2014 a package whose\n * latest version cannot be resolved is treated as current (never reported).\n */\nexport async function checkOutdated(\n installed: Map<string, string>,\n): Promise<OutdatedComponent[]> {\n const entries = [...installed.entries()];\n const latest = await Promise.all(\n entries.map(([pkg]) => fetchLatestVersion(pkg)),\n );\n\n const outdated: OutdatedComponent[] = [];\n entries.forEach(([pkg, version], index) => {\n const newest = latest[index];\n if (!newest) {\n return;\n }\n // Report only when the installed version is *strictly older* than latest.\n // A version that is equal, ahead (a prerelease / `@next` / linked workspace\n // copy such as 13.0.0-beta vs a 12.3.0 latest), or non-comparable is treated\n // as current, so the banner never advises `install @latest` as a downgrade.\n const cmp = compareVersions(version, newest);\n if (cmp !== null && cmp < 0) {\n outdated.push({ pkg, installed: version, latest: newest });\n }\n });\n return outdated;\n}\n\n// The visible annotation appended to a legacy-standalone row (color codes have\n// zero display width, so only this bare text counts toward the border math).\nconst FORMKIT_MARK = \" \u21E2 auro-formkit\";\n\n/**\n * Render the \"components behind latest\" notice as a bold, bordered banner with\n * an aligned version table and ready-to-run guidance. Colors degrade\n * automatically (chalk disables them when the stream is not a TTY, e.g.\n * redirected to a file), while the border and heading keep it prominent\n * regardless. Meant for stderr so it never pollutes command output on stdout.\n *\n * A **legacy standalone** form package (one `auro-formkit` now ships) is not advised\n * to update to `@latest` \u2014 that pushes the consumer deeper into the deprecated\n * package. Its row is marked `\u21E2 auro-formkit` and it appears under a distinct\n * \"Migrate to auro-formkit\" block instead of the `npm install @latest` command.\n */\nexport function renderOutdatedBanner(outdated: OutdatedComponent[]): string {\n // Self-guard: with no components the width math (`Math.max(...[])`) would\n // yield -Infinity and garble the banner. Callers already skip the empty case,\n // but returning \"\" keeps this safe for any future caller.\n if (outdated.length === 0) {\n return \"\";\n }\n\n const legacy = outdated.filter((o) => isLegacyFormkitPackage(o.pkg));\n const normal = outdated.filter((o) => !isLegacyFormkitPackage(o.pkg));\n\n const heading = `\u26A0 ${outdated.length} Auro component(s) are NOT on the latest release`;\n const pkgWidth = Math.max(...outdated.map((o) => o.pkg.length));\n const installedWidth = Math.max(...outdated.map((o) => o.installed.length));\n\n const isLegacy = (o: OutdatedComponent): boolean =>\n isLegacyFormkitPackage(o.pkg);\n const rows = outdated.map((o) => {\n const row = ` ${chalk.bold(o.pkg.padEnd(pkgWidth))} ${chalk.dim(\n o.installed.padStart(installedWidth),\n )} ${chalk.dim(\"\u2192\")} ${chalk.green.bold(o.latest)}`;\n return isLegacy(o) ? `${row}${chalk.yellow(FORMKIT_MARK)}` : row;\n });\n\n // Guidance: standard packages update to @latest; legacy standalones migrate to\n // the formkit subpath instead. Either block is omitted when it has no members.\n const guidance: string[] = [];\n if (normal.length > 0) {\n const updateCmd = `npm install ${normal\n .map((o) => `${o.pkg}@latest`)\n .join(\" \")}`;\n guidance.push(\n \"\",\n chalk.dim(\" Update to latest with:\"),\n ` ${chalk.cyan(updateCmd)}`,\n );\n }\n if (legacy.length > 0) {\n guidance.push(\n \"\",\n chalk.dim(\" Migrate to auro-formkit (run `auro init`):\"),\n );\n for (const o of legacy) {\n guidance.push(\n ` ${chalk.dim(o.pkg)} ${chalk.dim(\"\u2192\")} ${chalk.cyan(formkitSubpathFor(o.pkg))}`,\n );\n }\n }\n\n // Border width tracks the widest visible line (ignoring color codes), capped\n // so a long update command doesn't blow out the terminal.\n const visibleWidths = [\n // `\u26A0` (U+26A0) renders as two terminal columns but `.length` counts it as\n // one, so add 1 or the border falls a column short of the heading.\n heading.length + 1,\n ...outdated.map((o) => {\n const base = 2 + pkgWidth + 2 + installedWidth + 3 + o.latest.length;\n return isLegacy(o) ? base + FORMKIT_MARK.length : base;\n }),\n ];\n const width = Math.min(Math.max(...visibleWidths), 78);\n const border = \"\u2500\".repeat(width);\n\n return [\n \"\",\n chalk.yellow.bold(`\u250C${border}\u2510`),\n chalk.yellow.bold(heading),\n chalk.yellow.bold(`\u2514${border}\u2518`),\n ...rows,\n ...guidance,\n \"\",\n ].join(\"\\n\");\n}\n", "/**\n * The legacy-standalone \u2192 `auro-formkit` relationship, in one place.\n *\n * Nine Auro form components were first published as **standalone** packages\n * (`@aurodesignsystem/auro-input`, `-select`, \u2026) and were later absorbed into the\n * `@aurodesignsystem/auro-formkit` monorepo, which re-exports each under a\n * per-component subpath (`@aurodesignsystem/auro-formkit/auro-<x>`). A project on a\n * standalone is on the *legacy* form of that component and should migrate to\n * formkit \u2014 the standalone import path (`@aurodesignsystem/auro-<x>`) maps 1:1 to a\n * formkit subpath.\n *\n * `auro-button` is a genuine standalone that was **never** part of formkit, so it is\n * deliberately absent from {@link LEGACY_FORMKIT_PACKAGES}. This is the same overlap\n * documented in [auroComponents.ts](./auroComponents.ts); keep the two lists in sync.\n */\n\n/** The monorepo that absorbed the legacy standalone form components. */\nexport const FORMKIT_PACKAGE = \"@aurodesignsystem/auro-formkit\";\n\n/**\n * The legacy standalone form packages that now live inside {@link FORMKIT_PACKAGE}.\n * A project depending on any of these should migrate to the formkit subpath.\n * Excludes `@aurodesignsystem/auro-button` (a true standalone, not in formkit).\n */\nexport const LEGACY_FORMKIT_PACKAGES: readonly string[] = [\n \"@aurodesignsystem/auro-input\",\n \"@aurodesignsystem/auro-select\",\n \"@aurodesignsystem/auro-combobox\",\n \"@aurodesignsystem/auro-menu\",\n \"@aurodesignsystem/auro-checkbox\",\n \"@aurodesignsystem/auro-radio\",\n \"@aurodesignsystem/auro-datepicker\",\n \"@aurodesignsystem/auro-dropdown\",\n \"@aurodesignsystem/auro-form\",\n];\n\nconst LEGACY_SET = new Set(LEGACY_FORMKIT_PACKAGES);\n\n/** True when `pkg` is a legacy standalone that formkit now ships. */\nexport function isLegacyFormkitPackage(pkg: string): boolean {\n return LEGACY_SET.has(pkg);\n}\n\n/**\n * The bare `auro-*` element name a legacy standalone contributes to formkit:\n * `@aurodesignsystem/auro-input` \u2192 `auro-input`. Assumes {@link isLegacyFormkitPackage}\n * \u2014 the standalone's package basename *is* its canonical tag.\n */\nexport function formkitTagFor(pkg: string): string {\n return pkg.slice(\"@aurodesignsystem/\".length);\n}\n\n/**\n * The formkit subpath import specifier that replaces a legacy standalone import:\n * `@aurodesignsystem/auro-input` \u2192 `@aurodesignsystem/auro-formkit/auro-input`.\n */\nexport function formkitSubpathFor(pkg: string): string {\n return `${FORMKIT_PACKAGE}/${formkitTagFor(pkg)}`;\n}\n", "/**\n * `auro init` \u2014 generate the AI grounding files (`AGENTS.md` + the thin\n * `CLAUDE.md`) for the Auro components a project actually has installed, plus the\n * CLI-owned `auro.config.json` that records how each component's tag is resolved.\n *\n * This command is the orchestration seam that wires the PT-M1 data modules\n * together: detect + resolve installed components (`resolver.ts`), plan each\n * component's custom tag under the frozen **config \u2192 AST scan \u2192 default prefix**\n * precedence (`registry.ts`), render the grounding files (`generator.ts`), then\n * write them and persist the config. It owns the two policy concerns the pure\n * planner deliberately excludes: the interactive prefix prompt/confirm and the\n * non-interactive TTY/CI guard.\n *\n * Its generated files are committed artifacts \u2014 `auro.config.json` and the rest\n * are meant to be checked in so regeneration is deterministic across a team and in\n * CI. To protect that, a post-write check asks git whether any file it wrote is\n * ignored and, with consent, appends the `.gitignore` negations that keep it\n * tracked (it never *adds* ignore rules). See `reconcileGitignore`/`gitignore.ts`.\n *\n * After writing, `init` runs the same best-effort **outdated-release check** as\n * `auro context`/`auro component` (a bordered banner on stderr for any installed\n * package behind its latest release). This is the one network touch in an otherwise\n * offline command; `--offline` skips it and keeps the run fully network-free.\n *\n * **One opt-in codemod exception.** `init` otherwise documents, never rewrites,\n * consumer source. The sole exception is the legacy-standalone \u2192 `auro-formkit`\n * migration: when a project depends on a deprecated standalone form package, an\n * interactive run offers to migrate it (edit `package.json`, rewrite import\n * specifiers). This is gated behind an explicit TTY confirm and fully skipped in a\n * non-interactive/CI run (which only advises). See `migrateFormkit.ts`.\n */\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { program } from \"commander\";\nimport inquirer from \"inquirer\";\nimport ora from \"ora\";\nimport { type AuroConfig, CONFIG_FILENAME } from \"#init/config.js\";\nimport {\n detectEditorSignals,\n EDITOR_TARGETS,\n type EditorSelection,\n type EditorTarget,\n} from \"#init/editors/detect.js\";\nimport { verifyEditorWiring } from \"#init/editors/verify.js\";\nimport {\n type EditorWriteReport,\n writeEditorArtifacts,\n} from \"#init/editors/write.js\";\nimport { groundingFiles } from \"#init/generator.js\";\nimport { findIgnored, unignore } from \"#init/gitignore.js\";\nimport { AGENTS_FILENAME, CLAUDE_FILENAME } from \"#init/layout.js\";\nimport {\n detectLegacyFormkit,\n type LegacyDependency,\n migrateToFormkit,\n} from \"#init/migrateFormkit.js\";\nimport {\n emptyConfig,\n loadConfig,\n planTagResolution,\n RegistryError,\n saveConfig,\n scanProject,\n type TagResolutionPlan,\n} from \"#init/registry.js\";\nimport { applyReset, planReset, type ResetPlan } from \"#init/reset.js\";\nimport { type ResolvedComponent, resolveInstalled } from \"#init/resolver.js\";\nimport { renderWarningBanner } from \"#utils/banner.js\";\nimport { checkOutdated, renderOutdatedBanner } from \"#utils/outdated.js\";\n\n/** Options accepted by the `init` action. */\nexport interface InitOptions {\n /** Default tag prefix (e.g. `myapp-`) for components without an existing registration. */\n prefix?: string;\n /** Never prompt; take the prefix from `--prefix` or fail cleanly. */\n nonInteractive?: boolean;\n /** Alias for {@link nonInteractive}. */\n yes?: boolean;\n /**\n * Editor-target opt-ins. Each is **tri-state**: `true` (`--vscode`) forces the\n * target on, `false` (`--no-vscode`) forces it off, and `undefined` (neither\n * flag) leaves it to the persisted config \u2192 detection \u2192 prompt precedence. An\n * explicit flag always wins and is persisted for later runs.\n */\n vscode?: boolean;\n jsx?: boolean;\n svelte?: boolean;\n cssSnippets?: boolean;\n /**\n * Skip the best-effort network check for newer component releases. `init` is\n * otherwise offline; the release-check is its one network touch, so `--offline`\n * keeps the whole run network-free (useful in CI or air-gapped environments).\n */\n offline?: boolean;\n /**\n * Teardown mode: remove every file and config entry a previous `auro init` run\n * produced instead of generating. A pure reverse operation \u2014 needs no installed\n * components, prefix resolution, or network. See {@link runReset}.\n */\n reset?: boolean;\n}\n\n/**\n * Is this run non-interactive? True when stdin is not a TTY, when `CI` is set, or\n * when the user passed `--non-interactive`/`--yes`. A non-interactive run never\n * calls `inquirer` (which would throw on a closed stdin) \u2014 it takes the prefix\n * from `--prefix` or fails cleanly.\n */\nfunction isNonInteractive(options: InitOptions): boolean {\n return (\n !process.stdin.isTTY ||\n Boolean(process.env.CI) ||\n Boolean(options.nonInteractive) ||\n Boolean(options.yes)\n );\n}\n\n/**\n * Interactively resolve the default prefix for components that have no config or\n * scan-detected tag. Offers the majority `suggestedDefault` (when one was\n * inferred from existing registrations) as a `confirm`, falling back to a free\n * `input` \u2014 a blank answer keeps the bare `auro-*` tags (the planner warns).\n * Only called on an interactive TTY.\n */\nasync function promptDefaultPrefix(plan: TagResolutionPlan): Promise<string> {\n if (plan.suggestedDefault) {\n const { accept } = await inquirer.prompt<{ accept: boolean }>([\n {\n type: \"confirm\",\n name: \"accept\",\n message: plan.mixedPrefixes\n ? `Existing registrations use more than one prefix. Use the most common, '${plan.suggestedDefault}', as the default for the remaining components?`\n : `Use the detected prefix '${plan.suggestedDefault}' as the default for the remaining components?`,\n default: true,\n },\n ]);\n if (accept) {\n return plan.suggestedDefault;\n }\n }\n\n const { prefix } = await inquirer.prompt<{ prefix: string }>([\n {\n type: \"input\",\n name: \"prefix\",\n message:\n \"Prefix for Auro custom-element tags (e.g. myapp-; blank keeps the bare auro-* tags):\",\n default: plan.suggestedDefault ?? \"\",\n },\n ]);\n return String(prefix).trim();\n}\n\n/**\n * Validate a user-entered custom-element tag (inquirer `validate` contract:\n * `true` when acceptable, else the error string to show). A conservative subset\n * of the HTML custom-element name grammar \u2014 lowercase, must start with an ASCII\n * letter and contain at least one hyphen \u2014 enough to reject typos like\n * `MyButton` or a bare `button` that would generate IntelliSense keyed on a tag\n * the markup never uses.\n */\nexport function isValidCustomTag(tag: string): true | string {\n const trimmed = tag.trim();\n if (!/^[a-z][a-z0-9-]*$/.test(trimmed)) {\n return \"Use a lowercase tag starting with a letter (letters, digits, and hyphens only).\";\n }\n if (!trimmed.includes(\"-\")) {\n return \"A custom-element tag must contain a hyphen (e.g. nav-menu).\";\n }\n return true;\n}\n\n/**\n * Optionally let the user name any installed component's tag explicitly. Gated\n * behind one confirm (default no); on yes, prompts once per component with the\n * prefix-calculated tag as the editable default \u2014 Enter keeps it, a typed value\n * replaces it. Returns only the entries the user actually changed (canonical\n * `auro-*` tag \u2192 typed custom tag), so an unchanged component stays driven by the\n * prefix machinery (a later `--prefix` still propagates to it) rather than being\n * pinned as an override. Interactive TTY only \u2014 the caller guards on that.\n */\nasync function promptCustomTags(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): Promise<Record<string, string>> {\n const { customize } = await inquirer.prompt<{ customize: boolean }>([\n {\n type: \"confirm\",\n name: \"customize\",\n message:\n \"Define a custom tag name for any installed component? (you'll be prompted per component; Enter keeps the calculated name)\",\n default: false,\n },\n ]);\n if (!customize) {\n return {};\n }\n\n const overrides: Record<string, string> = {};\n for (const component of components) {\n const canonical = component.tagName;\n const calculated = resolvedTags.get(canonical) ?? canonical;\n const { tag } = await inquirer.prompt<{ tag: string }>([\n {\n type: \"input\",\n name: \"tag\",\n message: `Tag for ${component.declaration.name} (<${canonical}>):`,\n default: calculated,\n validate: isValidCustomTag,\n },\n ]);\n const entered = String(tag).trim();\n if (entered !== calculated) {\n overrides[canonical] = entered;\n }\n }\n return overrides;\n}\n\n/**\n * Build the config to re-plan against after the per-component prompt: the loaded\n * config's default + overrides, merged with the user's typed customs (which win).\n * Falls back to an empty config when the project had none. Pure \u2014 the returned\n * config feeds {@link planTagResolution}, which re-derives resolved tags and\n * warnings and yields the authoritative config to persist.\n */\nfunction withUserOverrides(\n config: AuroConfig | null,\n overrides: Record<string, string>,\n): AuroConfig {\n const base = config ?? emptyConfig();\n return {\n ...base,\n init: {\n ...base.init,\n prefix: {\n default: base.init.prefix.default,\n overrides: { ...base.init.prefix.overrides, ...overrides },\n },\n },\n };\n}\n\n/** Human-facing label + artifact path for each editor target's confirm prompt. */\nconst EDITOR_TARGET_META: Record<\n EditorTarget,\n { label: string; artifact: string }\n> = {\n vscode: {\n label: \"VS Code HTML custom-data\",\n artifact: \".vscode/auro.html-custom-data.json\",\n },\n jsx: {\n label: \"JSX/React type declarations\",\n artifact: \"auro-types/auro-jsx.d.ts\",\n },\n svelte: {\n label: \"Svelte type declarations\",\n artifact: \"auro-types/auro-svelte.d.ts\",\n },\n cssSnippets: {\n label: \"CSS ::part() snippets\",\n artifact: \".vscode/auro.code-snippets\",\n },\n};\n\n/**\n * Settle each editor target on/off under the frozen precedence\n * flag \u2192 persisted config \u2192 detection \u2192 interactive prompt. An explicit\n * `--vscode`/`--no-vscode` flag wins outright; else a settled `init.editors.*`\n * choice from a prior run is honored (no re-detect/re-prompt); else the target is\n * unsettled and its detected default is either offered as a confirm (interactive)\n * or taken as-is (non-interactive/CI \u2014 an editor target has a safe default, so\n * `init` never prompts or fails over it here). Every target is returned as a\n * concrete boolean so the caller can persist all three and later runs stay\n * deterministic.\n */\nasync function resolveEditorTargets(\n cwd: string,\n options: InitOptions,\n config: Awaited<ReturnType<typeof loadConfig>>,\n): Promise<EditorSelection> {\n const persisted = config?.init.editors;\n const signals = detectEditorSignals(cwd);\n const interactive = !isNonInteractive(options);\n\n const selection: EditorSelection = {\n vscode: false,\n jsx: false,\n svelte: false,\n cssSnippets: false,\n };\n const pending: Array<{\n type: \"confirm\";\n name: EditorTarget;\n message: string;\n default: boolean;\n }> = [];\n\n for (const target of EDITOR_TARGETS) {\n const flag = options[target];\n if (flag !== undefined) {\n selection[target] = flag; // explicit flag \u2014 highest precedence, persisted.\n continue;\n }\n const saved = persisted?.[target];\n if (saved !== undefined) {\n selection[target] = saved; // settled last run \u2014 honored as-is.\n continue;\n }\n // Unsettled: prompt on an interactive TTY, else take the detected default.\n if (interactive) {\n const { label, artifact } = EDITOR_TARGET_META[target];\n pending.push({\n type: \"confirm\",\n name: target,\n message: `Generate ${label} (${artifact})?`,\n default: signals[target],\n });\n } else {\n selection[target] = signals[target];\n }\n }\n\n if (pending.length > 0) {\n const answers =\n await inquirer.prompt<Record<EditorTarget, boolean>>(pending);\n for (const { name } of pending) {\n selection[name] = Boolean(answers[name]);\n }\n }\n\n return selection;\n}\n\n/**\n * Offer to migrate legacy standalone form packages (now shipped by `auro-formkit`)\n * to formkit. Returns `true` when a migration was applied \u2014 the caller then stops\n * this run, because the standalone is still in `node_modules` and grounding it now\n * would document the very imports the codemod just rewrote; the user reinstalls and\n * re-runs to ground formkit. Returns `false` when there is nothing to migrate, the\n * user declines, or the run is non-interactive (which only advises), so the caller\n * continues with normal grounding.\n */\nasync function offerFormkitMigration(\n cwd: string,\n options: InitOptions,\n): Promise<boolean> {\n let legacy: LegacyDependency[];\n try {\n legacy = detectLegacyFormkit(cwd);\n } catch (error) {\n // A malformed package.json is surfaced but must not abort grounding.\n const message = error instanceof Error ? error.message : String(error);\n console.error(`\u26A0 Skipping formkit migration check: ${message}`);\n return false;\n }\n if (legacy.length === 0) {\n return false;\n }\n\n const names = legacy.map((l) => l.pkg).join(\", \");\n if (isNonInteractive(options)) {\n console.error(\n `\u26A0 ${legacy.length} legacy standalone package(s) can be migrated to @aurodesignsystem/auro-formkit: ${names}. Run \\`auro init\\` interactively to apply the migration.`,\n );\n return false;\n }\n\n const { migrate } = await inquirer.prompt<{ migrate: boolean }>([\n {\n type: \"confirm\",\n name: \"migrate\",\n message: `${legacy.length} legacy standalone package(s) now live in auro-formkit (${names}). Migrate to auro-formkit now? This edits package.json and rewrites import specifiers.`,\n default: false,\n },\n ]);\n if (!migrate) {\n return false;\n }\n\n const spinner = ora(\"Migrating to auro-formkit...\").start();\n const report = migrateToFormkit(cwd, legacy);\n spinner.succeed(\n `Migrated ${report.packagesMigrated.length} package(s) to auro-formkit; rewrote ${report.rewriteCount} import(s) across ${report.filesChanged.length} file(s).`,\n );\n\n // Deep imports can't be remapped 1:1 to a formkit subpath \u2014 flag for follow-up.\n for (const { file, specifier } of report.deepImports) {\n console.error(\n `\u26A0 ${file}: left deep import '${specifier}' unchanged \u2014 update it to an @aurodesignsystem/auro-formkit subpath by hand.`,\n );\n }\n console.error(\n \"Next: run `npm install`, then re-run `auro init` to regenerate grounding for auro-formkit.\",\n );\n return true;\n}\n\n/**\n * Compare each resolved component's installed version against the latest published\n * release and, for any that are behind, print the shared outdated banner on stderr\n * (advisory \u2014 stdout stays clean). Best-effort and network-dependent: a package\n * whose latest can't be resolved is treated as current (`checkOutdated`), so a flaky\n * or absent network simply yields no banner and never fails `init`. Mirrors\n * `auro context`'s `reportOutdated`; the pkg\u2192version map is derived from the\n * components init already resolved (a monorepo pkg repeats with one shared version,\n * de-duped by the Map).\n */\nasync function reportOutdated(components: ResolvedComponent[]): Promise<void> {\n const installed = new Map(components.map((c) => [c.pkg, c.version]));\n const spinner = ora(\"Checking for newer component releases...\").start();\n const outdated = await checkOutdated(installed);\n\n if (outdated.length === 0) {\n spinner.succeed(\"All installed Auro components are on the latest release.\");\n return;\n }\n\n // Stop the spinner without its own icon/line \u2014 the banner below carries the\n // warning, and a leftover spinner line would dilute it.\n spinner.stop();\n console.error(renderOutdatedBanner(outdated));\n}\n\n/**\n * Generate and write the grounding files for the installed Auro components. See\n * the module header for the detect \u2192 plan \u2192 generate \u2192 write pipeline. Exits\n * non-zero on a malformed config, an unresolvable prefix in a non-interactive\n * run, or a write failure; warns (never guesses) on unresolvable registrations,\n * bare `auro-*` fallbacks, and cross-package duplicate tags.\n */\nexport async function runInit(options: InitOptions): Promise<void> {\n const cwd = process.cwd();\n\n // Teardown short-circuit: reset is a pure reverse operation, so it runs before\n // any detection/resolution/network \u2014 it must work even when no components are\n // installed or the config is gone.\n if (options.reset) {\n await runReset(cwd, options);\n return;\n }\n\n const spinner = ora(\"Detecting installed Auro components...\").start();\n const { components, duplicates } = await resolveInstalled();\n\n if (components.length === 0) {\n spinner.warn(\n \"No installed Auro components found; nothing to ground. Install an Auro component package and re-run `auro init`.\",\n );\n return;\n }\n spinner.succeed(\n `Detected ${components.length} installed component(s) to ground.`,\n );\n\n // Before grounding, offer to migrate any legacy standalone form package onto\n // auro-formkit. When a migration is applied, stop: the project must be\n // reinstalled and re-run so grounding reflects the formkit imports (see helper).\n if (await offerFormkitMigration(cwd, options)) {\n return;\n }\n\n // The persisted config is the source of truth for how tags were resolved last\n // run; a malformed or newer-version file is an explicit, actionable failure.\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = loadConfig(cwd);\n } catch (error) {\n const message =\n error instanceof RegistryError\n ? error.message\n : error instanceof Error\n ? error.message\n : String(error);\n console.error(`Cannot read ${CONFIG_FILENAME}: ${message}`);\n process.exit(1);\n }\n\n // Read-only scan of the project's own sources for existing register('<tag>')\n // calls \u2014 heuristic input to the config \u2192 scan \u2192 default-prefix precedence.\n const scan = scanProject(cwd);\n\n let plan = planTagResolution(components, {\n config,\n scan,\n prefix: options.prefix,\n });\n\n // Two-phase resolution: when some components still need a default prefix, or\n // existing registrations imply conflicting prefixes, resolve one and re-plan.\n //\n // The decision (confirm majority / prompt / CI-fail) is only needed while the\n // default is UNSETTLED \u2014 no --prefix and no persisted config default. A settled\n // default already governs unregistered components, so mixed per-component\n // overrides are simply honored and regeneration stays deterministic (no\n // re-prompt, no CI-fail on every run of a committed mixed-prefix project).\n const defaultSettled =\n options.prefix !== undefined || config?.init.prefix.default !== undefined;\n const needsDecision =\n !defaultSettled && (plan.needsDefaultPrefix || plan.mixedPrefixes);\n // The effective default prefix, tracked so a later re-plan (custom tags, below)\n // reuses the same one the user just settled instead of re-deriving it.\n let resolvedPrefix = options.prefix;\n if (needsDecision) {\n if (isNonInteractive(options)) {\n const reason = plan.needsDefaultPrefix\n ? `${plan.needingDefault.length} component(s) have no resolvable tag and no default prefix`\n : \"existing registrations use inconsistent prefixes\";\n console.error(\n `Cannot resolve component tags non-interactively: ${reason}. Re-run with --prefix <prefix> (e.g. --prefix myapp-).`,\n );\n process.exit(1);\n }\n resolvedPrefix = await promptDefaultPrefix(plan);\n plan = planTagResolution(components, {\n config,\n scan,\n prefix: resolvedPrefix,\n });\n }\n\n // Defensive: a resolved prefix must clear needsDefaultPrefix before we persist.\n if (plan.needsDefaultPrefix) {\n console.error(\n \"Unable to resolve a default prefix for every component. Re-run with --prefix <prefix>.\",\n );\n process.exit(1);\n }\n\n // Per-component custom tags (interactive only). Every component now has a\n // prefix-calculated tag; offer to override any of them with an explicit name.\n // Typed customs become `overrides` \u2014 the highest-precedence input \u2014 so a re-plan\n // re-derives resolved tags, reconciliation/no-prefix warnings, and the config to\n // persist. Non-interactive/CI runs skip this, keeping regeneration deterministic.\n if (!isNonInteractive(options)) {\n const customTags = await promptCustomTags(components, plan.resolvedTags);\n if (Object.keys(customTags).length > 0) {\n plan = planTagResolution(components, {\n config: withUserOverrides(config, customTags),\n scan,\n prefix: resolvedPrefix,\n });\n }\n }\n\n // Settle the editor targets (may prompt) before the spinner so the confirm UI\n // and the spinner never fight for the terminal, then record all three in the\n // config we are about to persist so later runs honor them without re-detecting.\n const editorSelection = await resolveEditorTargets(cwd, options, config);\n plan.config.init.editors = editorSelection;\n\n const writeSpinner = ora(\"Writing generated files...\").start();\n let editorReport: EditorWriteReport = { written: [], warnings: [] };\n try {\n for (const file of groundingFiles(components, plan.resolvedTags)) {\n await fs.writeFile(path.join(cwd, file.filename), file.contents, \"utf-8\");\n }\n // Write + wire the enabled editor artifacts (no-op when all targets are off).\n editorReport = await writeEditorArtifacts(\n cwd,\n components,\n plan.resolvedTags,\n editorSelection,\n );\n // Persist the authoritative config so regeneration is idempotent.\n saveConfig(cwd, plan.config);\n const editorNote =\n editorReport.written.length > 0\n ? ` Editor IntelliSense: ${editorReport.written.join(\", \")}.`\n : \"\";\n writeSpinner.succeed(\n `Wrote ${AGENTS_FILENAME}, ${CLAUDE_FILENAME}, and ${CONFIG_FILENAME} for ${components.length} component(s).${editorNote}`,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n writeSpinner.fail(`Failed to write generated files: ${message}`);\n process.exit(1);\n }\n\n // Advisory only \u2014 keep warnings on stderr so a caller capturing stdout gets a\n // clean run. Warn, never guess: unresolvable registrations and bare fallbacks.\n // Editor-wiring merges that were skipped (malformed target file) warn too, with\n // the manual one-liner already baked in.\n for (const warning of editorReport.warnings) {\n console.error(`\u26A0 ${warning}`);\n }\n for (const warning of plan.warnings) {\n console.error(`\u26A0 ${warning}`);\n }\n // A tag registered by more than one installed package (legacy standalone vs\n // monorepo overlap) is grounded once; surface it so the user picks intentionally.\n for (const duplicate of duplicates) {\n console.error(\n `\u26A0 Tag <${duplicate.tagName}> is registered by multiple installed packages: ${duplicate.packages.join(\", \")}. Grounded once \u2014 verify which package you intend to use.`,\n );\n }\n\n // Tag-reconciliation advisories (a grounded tag that may not match what the app\n // registers at runtime) silently break IntelliSense and are easy to miss among\n // the plain warnings above \u2014 surface them in a prominent red bordered banner,\n // the cousin of the outdated-release banner below.\n if (plan.reconciliationWarnings.length > 0) {\n console.error(\n renderWarningBanner(\n `\u26A0 ${plan.reconciliationWarnings.length} component tag(s) may not match your app's registered tags`,\n plan.reconciliationWarnings,\n \"red\",\n ),\n );\n }\n\n // Bare `auro-*` groundings \u2014 self-consistent but collision-prone. Less severe\n // than a reconciliation mismatch, so a yellow banner rather than red, but still\n // promoted above the plain-line noise so a missing prefix is hard to overlook.\n if (plan.noPrefixWarnings.length > 0) {\n console.error(\n renderWarningBanner(\n `\u26A0 ${plan.noPrefixWarnings.length} component(s) grounded under bare 'auro-*' tags \u2014 pass a prefix to avoid collisions`,\n plan.noPrefixWarnings,\n \"yellow\",\n ),\n );\n }\n\n // IntelliSense health check. `writeEditorArtifacts` above already wrote every\n // enabled target, but a merge can no-op against stale wiring whose artifact was\n // externally removed \u2014 leaving a settings pointer to a missing file. Read back\n // what actually landed; on a gap, re-run the idempotent writer once to self-heal,\n // then re-verify. A surviving gap is a red banner; a disabled markup target is a\n // yellow one, so absent `<auro-*>` completions are never a silent surprise.\n let verdict = verifyEditorWiring(cwd, editorSelection);\n if (verdict.inconsistencies.length > 0) {\n // The primary write above already succeeded (the spinner reported success), so\n // a failed self-heal must not crash the command \u2014 unlike the first write, this\n // pass is best-effort remediation, not the main artifact write. Guard it: a\n // reject here (e.g. a disk-full or permission race) would otherwise become an\n // unhandled rejection under the synchronous `program.parse()` and print a raw\n // stack trace. On failure, warn and fall through to the incomplete-wiring\n // banner below, which then reflects the un-healed verdict.\n try {\n const healReport = await writeEditorArtifacts(\n cwd,\n components,\n plan.resolvedTags,\n editorSelection,\n );\n // The self-heal pass can raise warnings the first write didn't (e.g. a target\n // file that turned malformed since). Surface the new ones instead of dropping\n // its report; the first pass already printed the shared ones.\n const alreadyWarned = new Set(editorReport.warnings);\n for (const warning of healReport.warnings) {\n if (!alreadyWarned.has(warning)) {\n console.error(`\u26A0 ${warning}`);\n }\n }\n verdict = verifyEditorWiring(cwd, editorSelection);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\n `\u26A0 Could not re-write editor artifacts to self-heal wiring: ${message}`,\n );\n }\n }\n if (verdict.inconsistencies.length > 0) {\n console.error(\n renderWarningBanner(\n \"\u26A0 Editor IntelliSense wiring is incomplete after writing\",\n verdict.inconsistencies,\n \"red\",\n ),\n );\n }\n if (verdict.markupDisabled) {\n console.error(\n renderWarningBanner(\n \"\u26A0 VS Code markup IntelliSense is off \u2014 no <auro-*> completions or hover docs\",\n [\n \"Type-checking may still work, but tag/attribute completions will not.\",\n \"Re-run `auro init --vscode` to generate them.\",\n ],\n \"yellow\",\n ),\n );\n }\n\n // Git-ignore reconciliation. Every file above is meant to be committed so a team\n // and CI share one deterministic set; a `.gitignore` rule (commonly `.vscode/`)\n // silently drops one from version control. Detect any ignored path and \u2014 with\n // consent \u2014 append the negations that keep it tracked. Advisory: never fails.\n const touched = [\n ...new Set([\n AGENTS_FILENAME,\n CLAUDE_FILENAME,\n CONFIG_FILENAME,\n ...editorReport.written,\n ]),\n ];\n await reconcileGitignore(cwd, touched, options);\n\n // Advisory, network-dependent \u2014 mirror `auro context`. Warn last so it's the\n // final thing on screen, not scrolled off by the write summary and warnings.\n // `--offline` skips it, keeping the run fully network-free.\n if (!options.offline) {\n await reportOutdated(components);\n }\n}\n\n/**\n * Detect files `auro init` wrote that git would ignore (so they'd never be\n * committed) and, with consent, append `.gitignore` negations to re-include them.\n * A prominent red banner surfaces the problem; the fix is offered interactively\n * (confirm, default yes) or applied straight away under `--yes`. A pure\n * non-interactive/CI run without `--yes` only warns \u2014 it never edits `.gitignore`\n * unprompted. Advisory throughout: never throws, never exits. See `gitignore.ts`.\n */\nasync function reconcileGitignore(\n cwd: string,\n touched: string[],\n options: InitOptions,\n): Promise<void> {\n const ignored = await findIgnored(cwd, touched);\n if (ignored.length === 0) {\n return;\n }\n\n console.error(\n renderWarningBanner(\n `\u26A0 ${ignored.length} file(s) auro init wrote are git-ignored and won't be committed`,\n [\n ...ignored,\n \"These are meant to be committed so your team and CI share the same grounding/IntelliSense.\",\n ],\n \"red\",\n ),\n );\n\n // Pure CI/non-interactive without --yes: warn only, never edit .gitignore unasked.\n if (isNonInteractive(options) && !options.yes) {\n console.error(\n \"\u26A0 Un-ignore them in .gitignore (or re-run with --yes) so they get committed.\",\n );\n return;\n }\n\n // Interactive without --yes: confirm before touching .gitignore. --yes: proceed.\n if (!options.yes) {\n const { fix } = await inquirer.prompt<{ fix: boolean }>([\n {\n type: \"confirm\",\n name: \"fix\",\n message:\n \"Add entries to .gitignore so these files stay tracked (committed)?\",\n default: true,\n },\n ]);\n if (!fix) {\n return;\n }\n }\n\n const { fixed, unfixable } = await unignore(cwd, ignored);\n if (fixed.length > 0) {\n console.error(\n `\u2714 Un-ignored ${fixed.length} file(s) in .gitignore so they will be committed.`,\n );\n }\n if (unfixable.length > 0) {\n console.error(\n renderWarningBanner(\n `\u26A0 ${unfixable.length} file(s) are still git-ignored \u2014 un-ignore them by hand`,\n [\n ...unfixable,\n \"A parent directory is ignored by a rule auro init won't rewrite; edit .gitignore to re-include these paths.\",\n ],\n \"red\",\n ),\n );\n }\n}\n\n/** True when a plan would remove or un-merge nothing (a no-op reset). */\nfunction isEmptyResetPlan(plan: ResetPlan): boolean {\n return plan.filesToRemove.length === 0 && plan.unmerges.length === 0;\n}\n\n/**\n * Teardown for `auro init --reset`: reverse a previous `auro init` run. Plans the\n * removals read-only, shows them for an interactive confirm (skippable with\n * `--yes`/`--non-interactive`/CI), then applies and summarizes. Signature-guarded\n * files that could not be confirmed as ours are reported, not deleted; the one-way\n * formkit migration is never reversed (a note says so). See `reset.ts`.\n */\nasync function runReset(cwd: string, options: InitOptions): Promise<void> {\n const plan = planReset(cwd);\n\n if (isEmptyResetPlan(plan)) {\n // Nothing of ours on disk. Still surface skips (e.g. a hand-edited AGENTS.md)\n // so the user understands why an expected file was left alone.\n console.log(\"Nothing to reset \u2014 no `auro init` output found.\");\n for (const skip of plan.filesToSkip) {\n console.error(`\u26A0 Left ${skip.path} in place: ${skip.reason}.`);\n }\n return;\n }\n\n // Show the exact teardown before touching disk.\n console.log(\"`auro init --reset` will:\");\n for (const file of plan.filesToRemove) {\n console.log(` \u2022 remove ${file}`);\n }\n for (const unmerge of plan.unmerges) {\n console.log(` \u2022 remove the Auro entry from ${unmerge.path}`);\n }\n for (const dir of plan.dirsToPrune) {\n console.log(` \u2022 remove ${dir}/ if it is left empty`);\n }\n for (const skip of plan.filesToSkip) {\n console.log(` \u2022 keep ${skip.path} (${skip.reason})`);\n }\n\n if (!isNonInteractive(options)) {\n const { confirm } = await inquirer.prompt<{ confirm: boolean }>([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Remove these files and config entries?\",\n default: false,\n },\n ]);\n if (!confirm) {\n console.log(\"Reset aborted \u2014 nothing was changed.\");\n return;\n }\n }\n\n const resetSpinner = ora(\"Removing `auro init` output...\").start();\n let report: ReturnType<typeof applyReset>;\n try {\n report = applyReset(cwd, plan);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n resetSpinner.fail(`Failed to reset: ${message}`);\n process.exit(1);\n }\n\n const removedNote =\n report.removed.length > 0\n ? `Removed ${report.removed.length} file(s)`\n : \"Removed no files\";\n const unmergedNote =\n report.unmerged.length > 0\n ? `, un-merged ${report.unmerged.join(\", \")}`\n : \"\";\n const prunedNote =\n report.prunedDirs.length > 0\n ? `, pruned ${report.prunedDirs.map((d) => `${d}/`).join(\", \")}`\n : \"\";\n resetSpinner.succeed(`${removedNote}${unmergedNote}${prunedNote}.`);\n\n for (const warning of report.warnings) {\n console.error(`\u26A0 ${warning}`);\n }\n for (const skip of report.skipped) {\n console.error(`\u26A0 Left ${skip.path} in place: ${skip.reason}.`);\n }\n\n // `--reset` never reverses the one-way formkit migration (package.json edits +\n // import rewrites) \u2014 say so rather than leave the user assuming a clean slate.\n console.error(\n \"\u2139 Reset does not undo an `auro-formkit` migration. If you migrated a legacy standalone form package, revert those package.json and import changes with git.\",\n );\n}\n\nexport default program\n .command(\"init\")\n .description(\n \"Generate AI grounding files (AGENTS.md + CLAUDE.md) for the installed Auro components\",\n )\n .option(\n \"--prefix <prefix>\",\n \"Default custom-element tag prefix (e.g. myapp-) for components without an existing registration\",\n )\n .option(\n \"--non-interactive\",\n \"Never prompt; take the prefix from --prefix or fail cleanly (implied by a non-TTY stdin or CI)\",\n false,\n )\n .option(\"--yes\", \"Alias for --non-interactive\", false)\n .option(\n \"--offline\",\n \"Skip the network check for newer component releases\",\n false,\n )\n .option(\n \"--vscode\",\n \"Generate VS Code HTML custom-data IntelliSense (use --no-vscode to skip; default: auto-detect)\",\n )\n .option(\"--no-vscode\", \"Skip the VS Code HTML custom-data artifact\")\n .option(\n \"--jsx\",\n \"Generate JSX/React type declarations (use --no-jsx to skip; default: auto-detect)\",\n )\n .option(\"--no-jsx\", \"Skip the JSX/React type declarations\")\n .option(\n \"--svelte\",\n \"Generate Svelte type declarations (use --no-svelte to skip; default: auto-detect)\",\n )\n .option(\"--no-svelte\", \"Skip the Svelte type declarations\")\n .option(\n \"--css-snippets\",\n \"Generate VS Code CSS ::part() snippets (use --no-css-snippets to skip; default: auto-detect)\",\n )\n .option(\"--no-css-snippets\", \"Skip the VS Code CSS ::part() snippets\")\n .option(\n \"--reset\",\n \"Remove every file and config entry a previous `auro init` run created (does not undo an auro-formkit migration)\",\n false,\n )\n .action(runInit);\n", "/**\n * Frozen schema for the CLI-owned `auro.config.json` file that `auro init` reads\n * and rewrites on every regeneration.\n *\n * See docs/pt-m1-completion-plan.md \u2192 \"Frozen decisions \u2192 CLI-owned config\n * location/shape\". This shape is FROZEN: do not change it without bumping\n * {@link CONFIG_VERSION} and shipping a migration. The top-level `version` field\n * exists from v1 precisely so any future change is an explicit migration rather\n * than a guess (the ticket's \"freeze the format early / bus-factor\" requirement).\n *\n * The one sanctioned exception is adding an **optional** field: a v1 reader treats\n * its absence as \"unresolved\", so a v1 file written before the field existed stays\n * valid without migration. {@link EditorsConfig} (PT-M2) is such a field \u2014 see\n * docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Config schema extension is\n * additive \u2014 no version bump\". A *breaking* change still requires the bump above.\n */\n\n/** Current on-disk config format version. Bump only alongside a migration. */\nexport const CONFIG_VERSION = 1 as const;\n\n/** The dedicated project-root file `auro init` reads and writes. */\nexport const CONFIG_FILENAME = \"auro.config.json\";\n\n/**\n * Custom-element registration prefixing.\n * - `default` applies to every installed component that has no override.\n * - `overrides` map a bare `auro-*` tag (the stable component identity, and the\n * resolver's canonical `tagName`) to the resolved custom tag.\n */\nexport interface PrefixConfig {\n /** Prefix applied to unregistered components, e.g. `\"myapp-\"`. */\n default: string;\n /** Per-component custom tags, keyed by the bare `auro-*` tag. */\n overrides: Record<string, string>;\n}\n\n/**\n * Per-editor-target opt-in for the IntelliSense artifacts `auro init` can\n * additionally emit (PT-M2). Each key is **optional and tri-state**: `true` /\n * `false` is a settled choice that later runs (including CI) honor without\n * re-detecting or re-prompting; **absence means \"unresolved\"** \u2014 the target is\n * auto-detected/prompted on the next interactive run. The whole block is optional\n * so a PT-M1 v1 file that predates it stays valid (see {@link AuroConfig} doc).\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Detection / prompt / flags\".\n */\nexport interface EditorsConfig {\n /** VS Code HTML custom-data (`.vscode/auro.html-custom-data.json`). */\n vscode?: boolean;\n /** JSX/React type declarations (`auro-types/auro-jsx.d.ts`). */\n jsx?: boolean;\n /** Svelte type declarations (`auro-types/auro-svelte.d.ts`). */\n svelte?: boolean;\n /** VS Code CSS `::part()` snippets (`.vscode/auro.code-snippets`). */\n cssSnippets?: boolean;\n}\n\n/** The `init`-namespaced settings block. Future commands get sibling keys. */\nexport interface InitConfig {\n prefix: PrefixConfig;\n /**\n * Optional per-editor opt-in (PT-M2). Additive; absence is valid and means\n * \"no editor target settled yet\". See {@link EditorsConfig}.\n */\n editors?: EditorsConfig;\n}\n\n/** Top-level shape of `auro.config.json`, namespaced per command. */\nexport interface AuroConfig {\n /** Format version; equals {@link CONFIG_VERSION} for files this CLI writes. */\n version: typeof CONFIG_VERSION;\n init: InitConfig;\n}\n", "/**\n * Read-only detection heuristics that pick a sensible **default** for each\n * editor-IntelliSense target when the consumer hasn't settled it via a flag or a\n * persisted `auro.config.json` choice. Every probe is a cheap, offline filesystem\n * look \u2014 never a network call, never a write \u2014 so it is safe to run on every\n * `auro init`, interactive or CI.\n *\n * These signals are only ever a *default*: the frozen precedence is\n * flag \u2192 persisted config \u2192 **detection** \u2192 interactive prompt. On an interactive\n * TTY the detected value seeds the confirm prompt; on a non-interactive/CI run\n * with no flag and no persisted choice it is taken as-is and recorded (an editor\n * target has a safe default, so \u2014 unlike the prefix \u2014 `init` never CI-fails over\n * it). See docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Detection / prompt\n * / flags\".\n */\n\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse as parseJsonc } from \"jsonc-parser\";\nimport { VSCODE_DIR } from \"#init/editors/layout.js\";\n\n/** Per-target on/off selection \u2014 the shape persisted under `init.editors`. */\nexport interface EditorSelection {\n /** VS Code HTML custom-data (`.vscode/auro.html-custom-data.json`). */\n vscode: boolean;\n /** JSX/React type declarations (`auro-types/auro-jsx.d.ts`). */\n jsx: boolean;\n /** Svelte type declarations (`auro-types/auro-svelte.d.ts`). */\n svelte: boolean;\n /** VS Code CSS `::part()` snippets (`.vscode/auro.code-snippets`). */\n cssSnippets: boolean;\n}\n\n/** The editor targets, in the order `init` resolves and reports them. */\nexport const EDITOR_TARGETS = [\n \"vscode\",\n \"jsx\",\n \"svelte\",\n \"cssSnippets\",\n] as const;\n\n/** One editor target key (`\"vscode\" | \"jsx\" | \"svelte\" | \"cssSnippets\"`). */\nexport type EditorTarget = (typeof EDITOR_TARGETS)[number];\n\n/** True when `<cwd>/<rel>` exists and is a directory. */\nfunction isDir(cwd: string, rel: string): boolean {\n try {\n return statSync(path.join(cwd, rel)).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * The union of `dependencies` + `devDependencies` names from `<cwd>/package.json`,\n * or an empty set when the file is absent or unreadable/malformed (detection never\n * throws \u2014 a bad manifest just yields no dependency signal).\n */\nfunction dependencyNames(cwd: string): Set<string> {\n try {\n const raw = readFileSync(path.join(cwd, \"package.json\"), \"utf-8\");\n const pkg = parseJsonc(raw, [], { allowTrailingComma: true }) as\n | {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n }\n | undefined;\n if (typeof pkg !== \"object\" || pkg === null) {\n return new Set();\n }\n return new Set([\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.devDependencies ?? {}),\n ]);\n } catch {\n return new Set();\n }\n}\n\n/**\n * VS Code target signal: the project already keeps a `.vscode/` directory (it\n * uses VS Code workspace settings), so wiring HTML custom-data into it is apt.\n */\nexport function detectVsCode(cwd: string): boolean {\n return isDir(cwd, VSCODE_DIR);\n}\n\n/**\n * CSS `::part()` snippets target signal: the project keeps a `.vscode/`\n * directory, so it uses VS Code, which auto-discovers the `.code-snippets` file\n * we write there. Same signal as {@link detectVsCode} \u2014 the snippets are a VS\n * Code feature \u2014 kept as its own named probe so the target reads independently.\n */\nexport function detectCssSnippets(cwd: string): boolean {\n return isDir(cwd, VSCODE_DIR);\n}\n\n/**\n * JSX/React target signal: the TypeScript config turns on JSX\n * (`compilerOptions.jsx` is set) **or** `react` is a (dev)dependency. Either means\n * the project authors `.tsx`/`.jsx` and would benefit from the JSX `.d.ts`.\n */\nexport function detectJsx(cwd: string): boolean {\n const tsconfigPath = path.join(cwd, \"tsconfig.json\");\n if (existsSync(tsconfigPath)) {\n try {\n const raw = readFileSync(tsconfigPath, \"utf-8\");\n const tsconfig = parseJsonc(raw, [], { allowTrailingComma: true }) as\n | { compilerOptions?: { jsx?: unknown } }\n | undefined;\n if (\n typeof tsconfig === \"object\" &&\n tsconfig !== null &&\n tsconfig.compilerOptions?.jsx !== undefined\n ) {\n return true;\n }\n } catch {\n // Unparseable tsconfig \u2014 fall through to the dependency signal.\n }\n }\n return dependencyNames(cwd).has(\"react\");\n}\n\n/**\n * Svelte target signal: `svelte` is a (dev)dependency **or** a `svelte.config.*`\n * lives at the project root \u2014 either means a Svelte project whose language server\n * consumes the Svelte `.d.ts`.\n */\nexport function detectSvelte(cwd: string): boolean {\n if (dependencyNames(cwd).has(\"svelte\")) {\n return true;\n }\n return [\"js\", \"ts\", \"mjs\", \"cjs\"].some((ext) =>\n existsSync(path.join(cwd, `svelte.config.${ext}`)),\n );\n}\n\n/** Run every target probe against `cwd` and return the detected defaults. */\nexport function detectEditorSignals(cwd: string): EditorSelection {\n return {\n vscode: detectVsCode(cwd),\n jsx: detectJsx(cwd),\n svelte: detectSvelte(cwd),\n cssSnippets: detectCssSnippets(cwd),\n };\n}\n", "/**\n * Post-write health check for the editor-IntelliSense targets. `auro init` writes\n * the artifacts and merges their wiring (./write.ts), then calls this to confirm\n * what actually landed on disk \u2014 so the command can **self-heal** a target whose\n * artifact or wiring went missing, and **loudly warn** when the markup-completion\n * (VS Code) target is off, instead of finishing \"successfully\" with silently-broken\n * IntelliSense.\n *\n * Read-only (mirrors reset.ts's `readOrNull`): it never writes. Two failure kinds:\n * - {@link EditorWiringVerdict.inconsistencies} \u2014 an *enabled* target whose file or\n * config wiring is absent/incomplete on disk. The caller re-runs the idempotent\n * writer once to repair, then re-verifies.\n * - {@link EditorWiringVerdict.markupDisabled} \u2014 the VS Code target resolved off, so\n * `<auro-*>` tag/attribute completions and hover docs are not generated at all.\n * The Svelte/JSX `.d.ts` type-checking layer can still be on, which masks this \u2014\n * the caller surfaces it so a missing markup layer is never a silent surprise.\n *\n * @see src/commands/init.ts (the caller), ./write.ts (the writer this guards),\n * ./settings.ts (the merge whose result this reads back).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse as parseJsonc } from \"jsonc-parser\";\nimport type { EditorSelection } from \"#init/editors/detect.js\";\nimport {\n HTML_CUSTOM_DATA_PATH,\n HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n JSX_TYPES_PATH,\n SVELTE_TYPES_PATH,\n TSCONFIG_INCLUDE_ENTRY,\n TSCONFIG_INCLUDE_KEY,\n VSCODE_DIR,\n VSCODE_SETTINGS_FILENAME,\n} from \"#init/editors/layout.js\";\n\n/** Outcome of a {@link verifyEditorWiring} pass. */\nexport interface EditorWiringVerdict {\n /**\n * One message per **enabled** target whose artifact or wiring is missing or\n * incomplete on disk. Empty when every enabled target is fully wired. The caller\n * treats a non-empty list as \"re-run the writer to repair, then re-check\".\n */\n inconsistencies: string[];\n /**\n * True when the VS Code (markup-completion) target is off. With Auro components\n * installed this means no `<auro-*>` completions/hover are generated \u2014 the caller\n * warns and points at `--vscode`.\n */\n markupDisabled: boolean;\n}\n\n/** Absolute path for a forward-slash, root-relative artifact path. */\nfunction toAbsolute(cwd: string, rel: string): string {\n return path.join(cwd, ...rel.split(\"/\"));\n}\n\n/** Read a file as UTF-8, or `null` when it does not exist / cannot be read. */\nfunction readOrNull(absolute: string): string | null {\n try {\n return readFileSync(absolute, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * True when `.vscode/settings.json` registers the HTML custom-data entry under\n * `html.customData` (as a bare string or inside the array). A missing/unparseable\n * file, or the key holding some other type, counts as \"not registered\".\n */\nfunction settingsHasPointer(cwd: string): boolean {\n const contents = readOrNull(\n toAbsolute(cwd, `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME}`),\n );\n if (contents === null) {\n return false;\n }\n const data = parseJsonc(contents, [], { allowTrailingComma: true }) as\n | Record<string, unknown>\n | undefined;\n const value = data?.[HTML_CUSTOM_DATA_SETTINGS_KEY];\n if (typeof value === \"string\") {\n return value === HTML_CUSTOM_DATA_SETTINGS_ENTRY;\n }\n if (Array.isArray(value)) {\n return value.includes(HTML_CUSTOM_DATA_SETTINGS_ENTRY);\n }\n return false;\n}\n\n/**\n * True when the framework-types dir is on the TypeScript program: either no\n * `tsconfig.json`/`jsconfig.json` exists (the default glob already covers the\n * non-dotted `auro-types/`), or the first one that exists lists the entry in its\n * `include` array. A `files`-only or wrong-typed `include` config counts as \"not\n * wired\" \u2014 the writer would have had to add it, so its absence is a real gap.\n */\nfunction tsProgramIncludesTypes(cwd: string): boolean {\n for (const configRel of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const contents = readOrNull(path.join(cwd, configRel));\n if (contents === null) {\n continue;\n }\n const data = parseJsonc(contents, [], { allowTrailingComma: true }) as\n | Record<string, unknown>\n | undefined;\n // Only the first existing config is authoritative (matches the writer's\n // branch selection in `mergeTsconfigInclude`).\n const include = data?.[TSCONFIG_INCLUDE_KEY];\n if (Array.isArray(include)) {\n // Branch 1: include array \u2014 wired iff it lists the entry.\n return include.includes(TSCONFIG_INCLUDE_ENTRY);\n }\n if (include !== undefined) {\n // Branch 4a: wrong-typed include \u2014 the writer refuses, so it's not wired.\n return false;\n }\n if (\"files\" in (data ?? {})) {\n // Branch 2: `files` suppresses the default glob, so an include is\n // required; its absence here is a real gap.\n return false;\n }\n // Branch 3: neither key \u2014 the default glob already covers `auro-types/`.\n return true;\n }\n // Neither config exists \u2014 the default include glob picks up `auro-types/`.\n return true;\n}\n\n/**\n * Check that every **enabled** editor target's artifact and wiring is present on\n * disk, and report whether the markup-completion target is off. Pure reads \u2014 safe\n * to call after {@link writeEditorArtifacts} on any run.\n */\nexport function verifyEditorWiring(\n cwd: string,\n selection: EditorSelection,\n): EditorWiringVerdict {\n const inconsistencies: string[] = [];\n\n if (selection.vscode) {\n if (!existsSync(toAbsolute(cwd, HTML_CUSTOM_DATA_PATH))) {\n inconsistencies.push(\n `${HTML_CUSTOM_DATA_PATH} is missing \u2014 VS Code markup completions will not work.`,\n );\n }\n if (!settingsHasPointer(cwd)) {\n inconsistencies.push(\n `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME} does not register \"${HTML_CUSTOM_DATA_SETTINGS_ENTRY}\" under \"${HTML_CUSTOM_DATA_SETTINGS_KEY}\".`,\n );\n }\n }\n\n if (selection.svelte && !existsSync(toAbsolute(cwd, SVELTE_TYPES_PATH))) {\n inconsistencies.push(`${SVELTE_TYPES_PATH} is missing.`);\n }\n if (selection.jsx && !existsSync(toAbsolute(cwd, JSX_TYPES_PATH))) {\n inconsistencies.push(`${JSX_TYPES_PATH} is missing.`);\n }\n // A single include wires both TS targets \u2014 check it once when either is on.\n if ((selection.svelte || selection.jsx) && !tsProgramIncludesTypes(cwd)) {\n inconsistencies.push(\n `${TSCONFIG_INCLUDE_ENTRY} is not on the TypeScript program (missing from \"${TSCONFIG_INCLUDE_KEY}\").`,\n );\n }\n\n return { inconsistencies, markupDisabled: !selection.vscode };\n}\n", "/**\n * Orchestration seam for the editor-IntelliSense targets: given the resolved\n * component set, the tag map, and the settled per-target selection, build the\n * enabled artifacts, write them under the project root, and merge their wiring\n * into `.vscode/settings.json` / `tsconfig.json`. Returns a report the command\n * turns into its success summary and stderr warnings.\n *\n * This is the \"impure\" bookend to the pure per-target builders\n * (./htmlCustomData.ts, ./jsxTypes.ts, ./svelteTypes.ts) and the pure config\n * merges (./settings.ts): those decide *what* the files should contain; this\n * module decides *where* they land and *whether* a merge is safe, doing the actual\n * `mkdir`/`writeFile`/`readFile`. Every merge is non-destructive and idempotent\n * (see ./settings.ts); a merge that can't be applied cleanly degrades to a warning\n * carrying the manual one-liner, and the artifact is still written regardless.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 Artifact locations +\n * editor wiring / settings.json merge / tsconfig four-branch tree\" and\n * build-order step 3.\n */\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { buildCssSnippets } from \"#init/editors/cssSnippets.js\";\nimport type { EditorSelection } from \"#init/editors/detect.js\";\nimport { buildHtmlCustomData } from \"#init/editors/htmlCustomData.js\";\nimport { buildJsxTypes } from \"#init/editors/jsxTypes.js\";\nimport {\n HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n TSCONFIG_INCLUDE_ENTRY,\n TSCONFIG_INCLUDE_KEY,\n VSCODE_DIR,\n VSCODE_SETTINGS_FILENAME,\n} from \"#init/editors/layout.js\";\nimport type { EditorArtifact } from \"#init/editors/manifest.js\";\nimport {\n mergeTsconfigInclude,\n mergeVsCodeSettings,\n} from \"#init/editors/settings.js\";\nimport { buildSvelteTypes } from \"#init/editors/svelteTypes.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/** Outcome of writing the enabled editor artifacts and wiring. */\nexport interface EditorWriteReport {\n /**\n * Project-root-relative paths of the files created or updated (artifacts plus\n * any settings/tsconfig files a merge actually changed), in write order \u2014 the\n * command lists these in its success message.\n */\n written: string[];\n /**\n * Advisory warnings for merges that were skipped (unparseable file, or the\n * target key held an unexpected type). Each already includes the manual wiring\n * one-liner; the command prints them on stderr. The artifact itself is still\n * written, so IntelliSense works once the consumer adds the line by hand.\n */\n warnings: string[];\n}\n\n/** Absolute path for an artifact's forward-slash, root-relative `filename`. */\nfunction toAbsolute(cwd: string, filename: string): string {\n return path.join(cwd, ...filename.split(\"/\"));\n}\n\n/** Write one artifact, creating its parent directory if needed. */\nasync function writeArtifact(\n cwd: string,\n artifact: EditorArtifact,\n): Promise<string> {\n const absolute = toAbsolute(cwd, artifact.filename);\n await fs.mkdir(path.dirname(absolute), { recursive: true });\n await fs.writeFile(absolute, artifact.contents, \"utf-8\");\n return artifact.filename;\n}\n\n/** Read a file, or `\"\"` when it does not exist (any other error propagates). */\nasync function readOrEmpty(absolute: string): Promise<string> {\n try {\n return await fs.readFile(absolute, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return \"\";\n }\n throw error;\n }\n}\n\n/**\n * Build, write, and wire every **enabled** editor target. Disabled targets are\n * skipped entirely \u2014 no artifact, no directory, no merge (so `init` never creates\n * `.vscode/` or `auro-types/` for a target the consumer turned off). The tsconfig\n * merge runs once when either the JSX or Svelte target is on, and only when a\n * `tsconfig.json` (or its JS-project `jsconfig.json` variant) already exists\n * (absent \u2192 the default program glob already picks up the non-dotted\n * `auro-types/`, so there is nothing to wire).\n */\nexport async function writeEditorArtifacts(\n cwd: string,\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n selection: EditorSelection,\n): Promise<EditorWriteReport> {\n const written: string[] = [];\n const warnings: string[] = [];\n\n if (selection.vscode) {\n written.push(\n await writeArtifact(cwd, buildHtmlCustomData(components, resolvedTags)),\n );\n\n // Register the custom-data file in .vscode/settings.json (created if absent).\n const settingsRel = `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME}`;\n const settingsAbs = toAbsolute(cwd, settingsRel);\n const merged = mergeVsCodeSettings(await readOrEmpty(settingsAbs));\n if (merged.warning) {\n warnings.push(\n `${merged.warning} Add \"${HTML_CUSTOM_DATA_SETTINGS_ENTRY}\" to \"${HTML_CUSTOM_DATA_SETTINGS_KEY}\" in ${settingsRel} by hand.`,\n );\n } else if (merged.changed) {\n await fs.mkdir(path.dirname(settingsAbs), { recursive: true });\n await fs.writeFile(settingsAbs, merged.contents, \"utf-8\");\n written.push(settingsRel);\n }\n }\n\n if (selection.jsx) {\n written.push(\n await writeArtifact(cwd, buildJsxTypes(components, resolvedTags)),\n );\n }\n\n if (selection.svelte) {\n written.push(\n await writeArtifact(cwd, buildSvelteTypes(components, resolvedTags)),\n );\n }\n\n // CSS `::part()` snippets are write-only: VS Code auto-discovers the\n // `.code-snippets` file, so there is no settings/tsconfig merge. The builder\n // returns null when no installed component exposes any cssParts \u2014 nothing to\n // write then, so the artifact (and `.vscode/`) is never created for it.\n if (selection.cssSnippets) {\n const artifact = buildCssSnippets(components, resolvedTags);\n if (artifact) {\n written.push(await writeArtifact(cwd, artifact));\n }\n }\n\n // A single config wiring covers both TS-consuming targets. Prefer tsconfig.json;\n // a JS-based Svelte/JSX project uses jsconfig.json instead (TypeScript ignores\n // jsconfig.json when a tsconfig.json is present, so tsconfig wins when both\n // exist). Only touch an existing config \u2014 neither present is the \"default glob\n // covers the non-dotted auro-types/\" branch, so there is nothing to wire.\n if (selection.jsx || selection.svelte) {\n for (const configRel of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const configAbs = path.join(cwd, configRel);\n const existing = await readOrEmpty(configAbs);\n if (existing === \"\") {\n continue;\n }\n const merged = mergeTsconfigInclude(\n existing,\n TSCONFIG_INCLUDE_ENTRY,\n configRel,\n );\n if (merged.warning) {\n warnings.push(\n `${merged.warning} Add \"${TSCONFIG_INCLUDE_ENTRY}\" to \"${TSCONFIG_INCLUDE_KEY}\" in ${configRel} by hand.`,\n );\n } else if (merged.changed) {\n await fs.writeFile(configAbs, merged.contents, \"utf-8\");\n written.push(configRel);\n }\n // Only the first existing config is authoritative; stop after it.\n break;\n }\n }\n\n return { written, warnings };\n}\n", "/**\n * Build the VS Code CSS snippets artifact (`.vscode/auro.code-snippets`) that\n * gives editor-assisted `::part()` completion for the installed components'\n * shadow parts. Pure: `(components, resolvedTags) \u2192 EditorArtifact | null`.\n *\n * This is the ONLY target that assists shadow-part styling. The other artifacts\n * can't: VS Code CSS custom-data (`css.customData`) has no field to enumerate an\n * element's `::part()` argument names, and the JSX/Svelte `.d.ts` describe\n * attributes, not the CSS the language service resolves `::part()` against. The\n * source data \u2014 each component's CEM `cssParts` (`{ name, description? }`) \u2014 is\n * already installed, so we emit one snippet per component whose body is a\n * `${1|\u2026|}` choice placeholder of that component's part names, keyed and prefixed\n * on the **resolved tag** the consumer actually writes in a stylesheet.\n *\n * VS Code auto-discovers any `.vscode/*.code-snippets` file, so \u2014 unlike the HTML\n * custom-data target \u2014 nothing registers this in `settings.json`; writing the\n * file is the whole wiring. `scope: \"css,scss,less\"` fires it across plain CSS\n * and the SCSS/LESS preprocessors (and Svelte `<style>`, which is CSS-language \u2014\n * a part there needs a `:global(...)` wrapper because of Svelte's style scoping).\n *\n * Returns `null` when no installed component exposes any `cssParts`, so `init`\n * writes nothing rather than an empty `{}` snippets file.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 the CSS `::part()` snippets decision.\n */\n\nimport { CSS_SNIPPETS_PATH } from \"#init/editors/layout.js\";\nimport {\n type EditorArtifact,\n ensureTrailingNewline,\n resolvedTagFor,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/** One VS Code snippet entry (the value side of a `.code-snippets` map). */\ninterface CodeSnippet {\n scope: string;\n prefix: string;\n body: string[];\n description: string;\n}\n\n/**\n * The stylesheet languages the snippet fires in. Plain CSS plus the two\n * preprocessors that share `::part()` selector syntax; Svelte `<style>` is\n * CSS-language and picks it up too (with a documented `:global(...)` caveat).\n */\nconst SNIPPET_SCOPE = \"css,scss,less\";\n\n/**\n * A part name is dropped when it contains a character that would corrupt the\n * `${1|a,b,c|}` choice placeholder (`,` and `|` are its delimiters, `}` closes\n * it). Real CSS part names are identifiers, so this only guards against a\n * malformed CEM \u2014 it never trims a legitimate name.\n */\nfunction isChoiceSafe(name: string): boolean {\n return !/[,|}]/u.test(name);\n}\n\n/**\n * Part names for one component: its declared `cssParts`, each pruned to a\n * non-empty, choice-safe string name (mirrors the manifest's `hasName` guard).\n * Order is preserved so the choice list reads in the component's declared order.\n */\nfunction partNames(component: ResolvedComponent): string[] {\n return (component.declaration.cssParts ?? [])\n .map((part) => part.name)\n .filter((name): name is string => typeof name === \"string\" && name !== \"\")\n .filter(isChoiceSafe);\n}\n\n/** Build the `${1|\u2026|}` choice-placeholder snippet for one tag + its part names. */\nfunction snippetFor(tag: string, parts: string[]): CodeSnippet {\n const choice = `\\${1|${parts.join(\",\")}|}`;\n return {\n scope: SNIPPET_SCOPE,\n prefix: `${tag}::part`,\n body: [`${tag}::part(${choice}) {`, \"\\t$0\", \"}\"],\n description: `Style a shadow part of <${tag}> (${parts.join(\", \")})`,\n };\n}\n\n/**\n * Render the CSS `::part()` snippets for the resolved component set. Each\n * component with at least one usable part contributes one snippet keyed\n * `Auro <tag> ::part`; components with no parts are omitted. Returns the\n * artifact's project-root-relative path plus its contents, or `null` when no\n * component exposes any parts (so the caller writes nothing). Writing is the\n * caller's job.\n */\nexport function buildCssSnippets(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact | null {\n const snippets: Record<string, CodeSnippet> = {};\n\n for (const component of components) {\n const parts = partNames(component);\n if (parts.length === 0) {\n continue;\n }\n const tag = resolvedTagFor(component, resolvedTags);\n snippets[`Auro <${tag}> ::part`] = snippetFor(tag, parts);\n }\n\n if (Object.keys(snippets).length === 0) {\n return null;\n }\n\n return {\n filename: CSS_SNIPPETS_PATH,\n contents: ensureTrailingNewline(JSON.stringify(snippets, null, 2)),\n };\n}\n", "/**\n * Build the VS Code HTML custom-data artifact (`.vscode/auro.html-custom-data.json`)\n * that drives tag/attribute IntelliSense in `.html` files via VS Code's HTML\n * Language Server. Pure: `(components, resolvedTags) \u2192 EditorArtifact`.\n *\n * The HTML tool has no per-tag rename hook, so the resolved tags are baked in by\n * pre-swapping the manifest ({@link buildManifest} with `resolvedTags`) \u2014 the\n * emitted custom-data is keyed on the tags a consumer actually registers\n * (`<myapp-button>`), never the bare `auro-*` tags. The tool insists on writing\n * its output to disk as well as returning it; we point it at a scratch dir and\n * keep only the returned string.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 build-order step 2.\n */\n\nimport { getVsCodeHtmlCustomData } from \"custom-element-vs-code-integration\";\nimport { HTML_CUSTOM_DATA_PATH } from \"#init/editors/layout.js\";\nimport {\n buildManifest,\n type EditorArtifact,\n ensureTrailingNewline,\n withTempDir,\n} from \"#init/editors/manifest.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\n/**\n * Render the HTML custom-data JSON for the resolved component set. Returns the\n * artifact's project-root-relative path plus its contents; writing is the\n * caller's job (`init`).\n */\nexport function buildHtmlCustomData(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string>,\n): EditorArtifact {\n const manifest = buildManifest(components, resolvedTags);\n const contents = withTempDir((outdir) =>\n // The tool types its manifest param as the strict `custom-elements-manifest`\n // CEM; our loose Manifest is compatible at runtime, so cast to the tool's own\n // parameter type rather than reshaping our model.\n getVsCodeHtmlCustomData(\n manifest as unknown as Parameters<typeof getVsCodeHtmlCustomData>[0],\n {\n outdir,\n htmlFileName: \"auro.html-custom-data.json\",\n hideLogs: true,\n },\n ),\n );\n return {\n filename: HTML_CUSTOM_DATA_PATH,\n contents: ensureTrailingNewline(contents),\n };\n}\n", "/**\n * Non-destructive, idempotent merges of the two consumer config files `auro init`\n * wires the editor artifacts into: `.vscode/settings.json` (registers the HTML\n * custom-data file) and `tsconfig.json` (puts the framework `.d.ts` bundles on\n * the TypeScript program). Both are pure `(existing, entry) \u2192 MergeResult`\n * string transforms \u2014 reading and writing are the caller's job.\n *\n * Comment- and formatting-preserving via `jsonc-parser`'s surgical `modify` /\n * `applyEdits` (never a parse-then-stringify round-trip, which would strip a\n * consumer's comments and reorder their keys). Every merge:\n * - creates the key/file when absent, appends when present, and is a no-op when\n * the Auro entry is already there (idempotent \u2014 re-running `init` never\n * duplicates or reorders);\n * - refuses to touch a file it cannot cleanly parse, returning a `warning`\n * instead of throwing so the command can still write the artifact and print\n * the manual one-liner.\n *\n * @see docs/pt-m2-completion-plan.md \u2192 \"Frozen decisions \u2192 settings.json merge\"\n * and the tsconfig four-branch decision tree.\n */\n\nimport {\n applyEdits,\n modify,\n type ParseError,\n parse as parseJsonc,\n parseTree,\n} from \"jsonc-parser\";\nimport {\n HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n TSCONFIG_INCLUDE_ENTRY,\n TSCONFIG_INCLUDE_KEY,\n} from \"#init/editors/layout.js\";\n\n/** The outcome of a config-file merge. */\nexport interface MergeResult {\n /**\n * The file contents to write. When {@link changed} is false this is the input\n * verbatim (the caller may skip the write entirely).\n */\n contents: string;\n /** True when the merge produced an edit the caller should write. */\n changed: boolean;\n /**\n * Set when the merge was skipped because the file could not be safely edited\n * (unparseable, or the target key holds an unexpected type). The caller surfaces\n * it as a warning and falls back to printing the manual wiring line.\n */\n warning?: string;\n}\n\n/** 2-space, spaces-not-tabs \u2014 the prevailing style for these config files. */\nconst FORMATTING = { tabSize: 2, insertSpaces: true } as const;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Parse `source` as JSONC, returning the object or a reason it can't be edited.\n * An empty/whitespace-only file is treated as an empty object (the merge will\n * create it). Any syntax error, or a root that isn't an object, is refused \u2014\n * we never guess at a malformed file's intent.\n */\nfunction parseObject(\n source: string,\n label: string,\n): { data: Record<string, unknown> } | { warning: string } {\n if (source.trim() === \"\") {\n return { data: {} };\n }\n const errors: ParseError[] = [];\n const data = parseJsonc(source, errors, { allowTrailingComma: true });\n if (errors.length > 0) {\n return { warning: `${label} is not valid JSON \u2014 leaving it untouched.` };\n }\n if (!isPlainObject(data)) {\n return { warning: `${label} is not a JSON object \u2014 leaving it untouched.` };\n }\n return { data };\n}\n\n/**\n * Apply a single value edit at `path` to `source` (an empty file becomes `{}`\n * first so `modify` has an object to edit into), preserving surrounding comments\n * and formatting.\n */\nfunction applyValueEdit(\n source: string,\n path: string[],\n value: unknown,\n): string {\n const base = source.trim() === \"\" ? \"{}\" : source;\n const edits = modify(base, path, value, { formattingOptions: FORMATTING });\n return applyEdits(base, edits);\n}\n\n/**\n * Splice out `key` when it is the object's **only** top-level property, returning\n * `null` in every other case (not an object, more than one property, or a\n * different sole key). `jsonc-parser`'s `modify` reformats an object to `{}` when\n * its last property is deleted, which discards any interior comment\n * (`{ // note\\n \"k\": v }` \u2192 `{}`); removing just the property node preserves that\n * comment. Only the last-property case needs this \u2014 with siblings remaining,\n * `modify` already keeps comments.\n */\nfunction deleteLoneTopLevelKey(source: string, key: string): string | null {\n const root = parseTree(source);\n if (!root || root.type !== \"object\" || root.children?.length !== 1) {\n return null;\n }\n const prop = root.children[0];\n if (prop.children?.[0]?.value !== key) {\n return null;\n }\n let end = prop.offset + prop.length;\n while (end < source.length && source[end] === \",\") {\n end++; // swallow a trailing comma so no stray `{ , }` is left behind\n }\n return source.slice(0, prop.offset) + source.slice(end);\n}\n\n/**\n * Surgically remove the property at `path` from `source`, preserving surrounding\n * comments and formatting. `modify(..., undefined, ...)` emits the delete edit;\n * `applyEdits` splices it in without a parse-then-stringify round-trip. The\n * inverse of {@link applyValueEdit}, used by the un-merge helpers below.\n *\n * For a lone top-level key we splice the property node ourselves so a user's\n * interior comment survives, since `modify` would drop it when emptying the object.\n */\nfunction applyKeyDeletion(source: string, path: string[]): string {\n if (path.length === 1) {\n const surgical = deleteLoneTopLevelKey(source, path[0]);\n if (surgical !== null) {\n return surgical;\n }\n }\n const edits = modify(source, path, undefined, {\n formattingOptions: FORMATTING,\n });\n return applyEdits(source, edits);\n}\n\n/**\n * Register the HTML custom-data file in `.vscode/settings.json` under\n * `html.customData`, appending non-destructively:\n * - absent \u2192 create the key as a one-element array;\n * - a string (VS Code allows a bare string) \u2192 normalise to `[existing, entry]`;\n * - an array \u2192 append the entry if missing;\n * - already present (string or array) \u2192 no-op;\n * - any other type \u2192 refuse and warn.\n */\nexport function mergeVsCodeSettings(\n existing: string,\n entry: string = HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n): MergeResult {\n const parsed = parseObject(existing, \".vscode/settings.json\");\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const current = parsed.data[HTML_CUSTOM_DATA_SETTINGS_KEY];\n\n let nextValue: string[];\n if (current === undefined) {\n nextValue = [entry];\n } else if (typeof current === \"string\") {\n if (current === entry) {\n return { contents: existing, changed: false };\n }\n nextValue = [current, entry];\n } else if (Array.isArray(current)) {\n if (current.includes(entry)) {\n return { contents: existing, changed: false };\n }\n nextValue = [...(current as string[]), entry];\n } else {\n return {\n contents: existing,\n changed: false,\n warning: `.vscode/settings.json \"${HTML_CUSTOM_DATA_SETTINGS_KEY}\" is not a string or array \u2014 leaving it untouched.`,\n };\n }\n\n const contents = applyValueEdit(\n existing,\n [HTML_CUSTOM_DATA_SETTINGS_KEY],\n nextValue,\n );\n return { contents, changed: true };\n}\n\n/**\n * Put the framework types dir on the TypeScript program via a `tsconfig.json` or\n * `jsconfig.json` (identical `include`/`files` schema \u2014 a JS Svelte/JSX project\n * uses the `jsconfig.json` variant), following the four-branch decision tree that\n * keeps the default `**` + `/*` include working:\n * 1. `include` present (array) \u2192 append the entry if missing.\n * 2. `files` present, no `include` \u2192 specifying `files` suppresses the default\n * glob, so add `include: [entry]` to bring the types back in.\n * 3. neither `files` nor `include` \u2192 the default glob already picks up the\n * non-dotted types dir; **do not edit** (no-op, no warning).\n * 4. `include` present but not an array, or the file is unparseable \u2192 refuse\n * and warn.\n *\n * `configName` is used only for the parse/refusal messages so they name the file\n * actually being merged. Idempotent: an entry already in `include` is a no-op.\n */\nexport function mergeTsconfigInclude(\n existing: string,\n entry: string = TSCONFIG_INCLUDE_ENTRY,\n configName = \"tsconfig.json\",\n): MergeResult {\n const parsed = parseObject(existing, configName);\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const { data } = parsed;\n const include = data[TSCONFIG_INCLUDE_KEY];\n\n // Branch 1: an existing include array \u2014 append if the entry isn't there.\n if (Array.isArray(include)) {\n if (include.includes(entry)) {\n return { contents: existing, changed: false };\n }\n const contents = applyValueEdit(\n existing,\n [TSCONFIG_INCLUDE_KEY],\n [...(include as string[]), entry],\n );\n return { contents, changed: true };\n }\n\n // Branch 4a: include present but the wrong type \u2014 don't guess at it.\n if (include !== undefined) {\n return {\n contents: existing,\n changed: false,\n warning: `${configName} \"${TSCONFIG_INCLUDE_KEY}\" is not an array \u2014 leaving it untouched.`,\n };\n }\n\n // Branch 2: `files` suppresses the default glob, so an include is required.\n if (\"files\" in data) {\n const contents = applyValueEdit(existing, [TSCONFIG_INCLUDE_KEY], [entry]);\n return { contents, changed: true };\n }\n\n // Branch 3: neither key \u2014 the default glob already covers the non-dotted dir.\n return { contents: existing, changed: false };\n}\n\n/**\n * Reverse {@link mergeVsCodeSettings}: remove the HTML custom-data entry from\n * `.vscode/settings.json` `html.customData`, the un-merge `auro init --reset`\n * applies. Non-destructive and idempotent \u2014 only our own entry is touched:\n * - an array containing `entry` \u2192 drop it; if that empties the array, delete\n * the whole key (so no dangling `\"html.customData\": []` is left behind);\n * - a bare string equal to `entry` \u2192 delete the key;\n * - `entry` absent, key absent, or the value is some other type \u2192 no-op (there\n * is nothing of ours to remove);\n * - unparseable file \u2192 refuse and warn, same contract as the merge.\n */\nexport function unmergeVsCodeSettings(\n existing: string,\n entry: string = HTML_CUSTOM_DATA_SETTINGS_ENTRY,\n): MergeResult {\n const parsed = parseObject(existing, \".vscode/settings.json\");\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const current = parsed.data[HTML_CUSTOM_DATA_SETTINGS_KEY];\n\n if (typeof current === \"string\") {\n if (current !== entry) {\n return { contents: existing, changed: false };\n }\n const contents = applyKeyDeletion(existing, [\n HTML_CUSTOM_DATA_SETTINGS_KEY,\n ]);\n return { contents, changed: true };\n }\n\n if (Array.isArray(current)) {\n if (!current.includes(entry)) {\n return { contents: existing, changed: false };\n }\n const remaining = (current as string[]).filter((v) => v !== entry);\n const contents =\n remaining.length === 0\n ? applyKeyDeletion(existing, [HTML_CUSTOM_DATA_SETTINGS_KEY])\n : applyValueEdit(existing, [HTML_CUSTOM_DATA_SETTINGS_KEY], remaining);\n return { contents, changed: true };\n }\n\n // Absent or an unexpected type \u2014 nothing of ours to remove.\n return { contents: existing, changed: false };\n}\n\n/**\n * Reverse {@link mergeTsconfigInclude}: remove the framework-types entry from a\n * `tsconfig.json`/`jsconfig.json` `include` array, the un-merge\n * `auro init --reset` applies. Non-destructive and idempotent:\n * - an `include` array containing `entry` \u2192 drop it; if that empties the array,\n * delete the `include` key entirely (restoring the default-glob branch the\n * merge relied on when it created a single-entry include);\n * - `include` not an array, absent, or without `entry` \u2192 no-op;\n * - unparseable file \u2192 refuse and warn.\n */\nexport function unmergeTsconfigInclude(\n existing: string,\n entry: string = TSCONFIG_INCLUDE_ENTRY,\n configName = \"tsconfig.json\",\n): MergeResult {\n const parsed = parseObject(existing, configName);\n if (\"warning\" in parsed) {\n return { contents: existing, changed: false, warning: parsed.warning };\n }\n\n const include = parsed.data[TSCONFIG_INCLUDE_KEY];\n if (!Array.isArray(include) || !include.includes(entry)) {\n return { contents: existing, changed: false };\n }\n\n const remaining = (include as string[]).filter((v) => v !== entry);\n const contents =\n remaining.length === 0\n ? applyKeyDeletion(existing, [TSCONFIG_INCLUDE_KEY])\n : applyValueEdit(existing, [TSCONFIG_INCLUDE_KEY], remaining);\n return { contents, changed: true };\n}\n", "/**\n * Frozen layout for the files `auro init` writes: the canonical `AGENTS.md`\n * grounding file and the thin `CLAUDE.md` that imports it.\n *\n * FROZEN per docs/pt-m1-completion-plan.md \u2192 build-order step 1 (\"freeze the file\n * format\") and \"Frozen decisions \u2192 `AGENTS.md` vs data files\". This module owns\n * the input-INDEPENDENT scaffolding only: the header/intro, the frozen top-level\n * section order, the regeneration note, and the `CLAUDE.md` body. The generator\n * (build-order step 4) fills the per-component API bodies and the resolved\n * tag/import/registration lines around this scaffolding; it must not re-derive\n * these constants.\n *\n * @see {@link AURO_CODING_RULES} in ./rules.ts for the \"Auro Coding Rules\" body.\n * @see test/fixtures/init/ for the golden assembled documents this pins.\n */\n\n/**\n * Canonical name of the grounding file. `CLAUDE.md` imports this by name, so the\n * two must agree.\n */\nexport const AGENTS_FILENAME = \"AGENTS.md\";\n\n/** The thin per-assistant import file name. */\nexport const CLAUDE_FILENAME = \"CLAUDE.md\";\n\n/**\n * Frozen top-level section order of `AGENTS.md`. The generator emits these H2\n * sections in exactly this order; the per-component subsections (H3) live under\n * \"Installed Components\". Changing this order is a format change (see module\n * doc) \u2014 bump behavior deliberately, don't reorder ad hoc.\n */\nexport const SECTION_HEADINGS = [\n \"What is Auro?\",\n \"Auro Coding Rules\",\n \"Installed Components\",\n \"Regeneration\",\n] as const;\n\n/**\n * The stable marker string baked into every generated `AGENTS.md` (inside the\n * \"do not edit\" HTML comment below). `auro init --reset` uses this as the\n * signature that a file is Auro-generated and therefore safe to delete \u2014 sharing\n * one source of truth with {@link GROUNDING_HEADER} so the guard can never drift\n * from the header it checks for.\n */\nexport const GROUNDING_MARKER = \"Generated by `auro init`\";\n\n/**\n * The document header + intro + \"What is Auro?\" section \u2014 everything above the\n * coding rules. Input-independent, so it lives here as a frozen constant.\n */\nexport const GROUNDING_HEADER = `# Auro Design System \u2014 AI Assistant Grounding\n\n<!-- ${GROUNDING_MARKER}. Do not edit by hand \u2014 re-run \\`auro init\\` to\nregenerate. Custom element tags are governed by \\`auro.config.json\\`. -->\n\nAlaska Airlines open-source design system | https://auro.alaskaair.com\n\nThis file grounds AI assistants in the Auro components **installed in this\nproject**. It lists only installed packages, their exact registered tags, and the\nfull API for the installed version of each component. Treat it as authoritative\nfor this project.\n\n## What is Auro?\n\nAuro is Alaska Airlines' design system, built on Web Components (Custom Elements\nv1) using the Lit library.\n- npm scope: \\`@aurodesignsystem/\\` (current), \\`@alaskaairux/\\` (legacy)\n- Framework-agnostic: works with React, Angular, Vue, Svelte, or plain HTML\n- Each component is a separate npm package and registers a custom element tag\n`;\n\n/**\n * Column header for the \"Installed Components\" summary table. The generator\n * emits one row per resolved component beneath it.\n */\nexport const INSTALLED_TABLE_HEADER = `| Tag | Package | Version | Import |\n|---|---|---|---|`;\n\n/**\n * The closing \"Regeneration\" section. Input-independent, so it's frozen here.\n */\nexport const REGENERATION_NOTE = `## Regeneration\n\nThis file is generated by \\`auro init\\`. Re-run it after adding or removing an Auro\ndependency to update the component list and APIs. Custom element tags are governed\nby \\`auro.config.json\\` (committed by default) \u2014 change prefixes there, not in this\nfile, then re-run \\`auro init\\`.\n`;\n\n/**\n * The entire body of the generated \\`CLAUDE.md\\`: a thin import of \\`AGENTS.md\\` so a\n * single canonical grounding file serves every assistant target (task #5). This\n * is the ONLY justified indirection (see \"Frozen decisions \u2192 \\`AGENTS.md\\` vs data\n * files\").\n */\nexport const CLAUDE_MD = `@${AGENTS_FILENAME}\n`;\n", "/**\n * The static \"Auro coding rules\" block embedded in every generated `AGENTS.md`.\n *\n * FROZEN per docs/pt-m1-completion-plan.md \u2192 \"Frozen decisions\" (the ticket's\n * bus-factor note: freeze the file format early). This is input-independent\n * prose; the per-component API bodies and the resolved tag/import lines are\n * assembled around it by the generator (build-order step 4). Edit here \u2014 never\n * inline in the generator \u2014 so the rules stay in one place.\n *\n * The block owns its own `## Auro Coding Rules` heading so it can be dropped into\n * the document (or reused for future targets) as a self-contained unit.\n */\nexport const AURO_CODING_RULES = `## Auro Coding Rules\n\nThese rules apply to every Auro component in this project. Use the exact\nregistered tags listed under **Installed Components** below: this project uses\ncustom registration, so a component's tag may differ from its default \\`auro-*\\`\nname.\n\n1. **Use Auro custom-element tags, never plain HTML equivalents.**\n - \u2717 \\`<button>\\` \u2192 \u2713 the registered Auro button tag\n - \u2717 \\`<input>\\` \u2192 \u2713 the registered Auro input tag (from \\`auro-formkit\\`)\n\n Only use components listed under **Installed Components**. Do not invent tags\n or reference components this project has not installed.\n\n2. **Import and register each component before use.** Each component ships its\n own import, and this project registers components under custom tags. The exact\n \\`import\\` + \\`register(...)\\` snippet for each component is shown in its section\n below. \\`auro-formkit\\` has no root export \u2014 always import the specific\n sub-component via its subpath export (e.g.\n \\`@aurodesignsystem/auro-formkit/auro-input\\`).\n\n3. **Attributes in markup, camelCase properties in JS.** The same field is a\n kebab-case attribute in HTML and a camelCase property in JavaScript.\n \\`\\`\\`html\n <!-- attribute -->\n <auro-button disabled>Save</auro-button>\n \\`\\`\\`\n \\`\\`\\`js\n element.loading = true; // property\n \\`\\`\\`\n\n4. **Put content in named slots, not \\`innerHTML\\`.** Each component's slot names\n are listed in its API section below.\n\n5. **Use design tokens for color, spacing, and type.** Install\n \\`@aurodesignsystem/design-tokens\\` and use the \\`--ds-basic-*\\` /\n \\`--ds-advanced-*\\` CSS custom properties rather than hard-coded values.\n\n6. **Accessibility is built in \u2014 don't override it.** Auro components ship WCAG\n 2.1 AA behavior (focus management, ARIA, error messaging). Prefer the provided\n slots and attributes over custom ARIA.\n`;\n", "/**\n * Pure formatting/naming helpers for the `auro component` command. Kept separate\n * from the command wiring so they can be unit-tested without importing commander,\n * ora, or triggering the command's side effects.\n */\n\nimport { type CemDeclaration, clean, type Deprecated } from \"#utils/cem.js\";\n\nconst SCOPE = \"@aurodesignsystem\";\n\n/**\n * Normalize a user-supplied component name into a full npm package name.\n * Accepts \"button\", \"auro-button\", or \"@aurodesignsystem/auro-button\" (and\n * tolerates surrounding whitespace / casing). An explicit scope is respected.\n */\nexport function toPackageName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.startsWith(\"@\")) {\n return trimmed;\n }\n const lower = trimmed.toLowerCase();\n if (lower.startsWith(\"auro-\")) {\n return `${SCOPE}/${lower}`;\n }\n return `${SCOPE}/auro-${lower}`;\n}\n\n/**\n * Convert a kebab-case attribute name to its camelCase property form\n * (`no-validate` \u2192 `noValidate`), matching how Lit maps attributes to fields.\n */\nexport function kebabToCamel(name: string): string {\n return name.replace(/-([a-z])/gu, (_, char: string) => char.toUpperCase());\n}\n\n/**\n * Render a `[deprecated]` (optionally with a reason) marker.\n */\nexport function deprecatedTag(deprecated: Deprecated): string {\n if (!deprecated) {\n return \"\";\n }\n return typeof deprecated === \"string\"\n ? ` [deprecated: ${clean(deprecated)}]`\n : \" [deprecated]\";\n}\n\n/**\n * Render a two-column list (name \u2192 description) with aligned padding.\n */\nexport function renderList(rows: Array<[string, string]>): string {\n if (rows.length === 0) {\n return \" (none)\";\n }\n // Coerce label/description defensively: published manifests occasionally ship\n // an entry missing its `name` (the types promise a string but the data can\n // violate it), and one bad row must not crash the whole lookup.\n const width = Math.max(...rows.map(([label]) => (label ?? \"\").length));\n return rows\n .map(([label, desc]) =>\n ` ${(label ?? \"\").padEnd(width)} ${desc ?? \"\"}`.trimEnd(),\n )\n .join(\"\\n\");\n}\n\n/** Overrides for the `Install:` lines when the import differs from the header package. */\nexport interface FormatDeclarationOptions {\n /** Package to `npm i` (defaults to the header `pkg`). */\n installPkg?: string;\n /** Module specifier to `import` (defaults to the header `pkg`). */\n importSpecifier?: string;\n}\n\n/**\n * Format one custom-element declaration into a readable summary. `pkg` heads the\n * declaration and drives the `Install:` lines by default; when the element is\n * fetched from a monorepo that re-exports it under a subpath (e.g. a legacy form\n * component now served by `@aurodesignsystem/auro-formkit`), pass `installPkg` /\n * `importSpecifier` so the install snippet points at the package to install and the\n * exact subpath to import.\n */\nexport function formatDeclaration(\n pkg: string,\n decl: CemDeclaration,\n options: FormatDeclarationOptions = {},\n): string {\n const { installPkg = pkg, importSpecifier = pkg } = options;\n const lines: string[] = [];\n\n lines.push(`${decl.tagName} (${pkg})`);\n const description = decl.summary || decl.description;\n if (description) {\n lines.push(clean(description));\n }\n const heritage = decl.superclass?.name\n ? `${decl.name} extends ${decl.superclass.name}`\n : decl.name;\n lines.push(`Class: ${heritage}`);\n\n lines.push(\"\");\n lines.push(\"Install:\");\n lines.push(` npm i ${installPkg}`);\n lines.push(` import \"${importSpecifier}\";`);\n\n lines.push(...apiBodyLines(decl));\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render the API sections of a declaration \u2014 Attributes, Properties & Methods,\n * Slots, Events, and (when present) CSS Parts / CSS Custom Properties \u2014 as a list\n * of lines, led by a blank separator. Shared by {@link formatDeclaration} (the\n * `component` command's full render) and `auro init`'s per-component grounding\n * sections, which wrap this same body under their own resolved-tag header and\n * prefix/subpath-aware install lines. Returns lines (not a joined string) so a\n * caller can splice them into a larger `lines` array.\n */\nexport function apiBodyLines(decl: CemDeclaration): string[] {\n const lines: string[] = [];\n\n const attributes = decl.attributes ?? [];\n lines.push(\"\");\n lines.push(`Attributes (${attributes.length}):`);\n lines.push(\n renderList(\n attributes.map((a) => {\n const type = a.type?.text ? ` {${clean(a.type.text)}}` : \"\";\n const def = a.default ? ` = ${clean(a.default)}` : \"\";\n return [\n a.name,\n `${clean(a.description)}${type}${def}${deprecatedTag(a.deprecated)}`.trim(),\n ];\n }),\n ),\n );\n\n // Public properties/methods not already covered by an attribute. An\n // attribute's backing field is named by `fieldName`; when a manifest omits it\n // we fall back to the attribute `name` and its camelCase form (attribute\n // names are kebab-case, fields camelCase) so the field isn't listed a second\n // time under Properties & Methods.\n const attrFields = new Set(\n attributes.flatMap((a) =>\n a.fieldName ? [a.fieldName] : [a.name, kebabToCamel(a.name)],\n ),\n );\n const members = (decl.members ?? []).filter(\n (m) =>\n // A member with no name is malformed CEM data \u2014 it can't be referenced,\n // so drop it rather than list an unnamed row.\n m.name &&\n (m.privacy === undefined || m.privacy === \"public\") &&\n !m.static &&\n !(m.kind === \"field\" && attrFields.has(m.name)),\n );\n lines.push(\"\");\n lines.push(`Properties & Methods (${members.length}):`);\n lines.push(\n renderList(\n members.map((m) => {\n const isMethod = m.kind === \"method\";\n const label = isMethod ? `${m.name}()` : m.name;\n const typeText = isMethod ? m.return?.type?.text : m.type?.text;\n const type = typeText ? ` {${clean(typeText)}}` : \"\";\n const def = !isMethod && m.default ? ` = ${clean(m.default)}` : \"\";\n return [\n label,\n `${clean(m.description)}${type}${def}${deprecatedTag(m.deprecated)}`.trim(),\n ];\n }),\n ),\n );\n\n const slots = decl.slots ?? [];\n lines.push(\"\");\n lines.push(`Slots (${slots.length}):`);\n lines.push(\n renderList(slots.map((s) => [s.name || \"(default)\", clean(s.description)])),\n );\n\n const events = decl.events ?? [];\n lines.push(\"\");\n lines.push(`Events (${events.length}):`);\n lines.push(\n renderList(\n events.map((e) => {\n const type = e.type?.text ? ` {${clean(e.type.text)}}` : \"\";\n return [e.name, `${clean(e.description)}${type}`.trim()];\n }),\n ),\n );\n\n const cssParts = decl.cssParts ?? [];\n if (cssParts.length > 0) {\n lines.push(\"\");\n lines.push(`CSS Parts (${cssParts.length}):`);\n lines.push(renderList(cssParts.map((p) => [p.name, clean(p.description)])));\n }\n\n const cssProps = decl.cssProperties ?? [];\n if (cssProps.length > 0) {\n lines.push(\"\");\n lines.push(`CSS Custom Properties (${cssProps.length}):`);\n lines.push(renderList(cssProps.map((p) => [p.name, clean(p.description)])));\n }\n\n return lines;\n}\n", "/**\n * Render the grounding files `auro init` writes \u2014 the canonical `AGENTS.md` and\n * the thin `CLAUDE.md` \u2014 from a resolved component set plus the resolved custom\n * tags. Pure, side-effect-free string builders: detection, resolution, and tag\n * resolution happen upstream (`resolver.ts` / `registry.ts`); this module only\n * assembles the frozen scaffolding (`layout.ts` / `rules.ts`) around each\n * component's resolved tag, prefix/subpath-aware install lines, and API body.\n *\n * The generator takes resolved tags as an INPUT \u2014 it never computes prefixes\n * itself (that is `registry.ts`). Structured as a set of per-target renderers so\n * future targets (e.g. `copilot-instructions.md`) are additive over the same\n * `ResolvedComponent[]` model, per build-order step 4 / task #11.\n */\n\nimport {\n AGENTS_FILENAME,\n CLAUDE_FILENAME,\n CLAUDE_MD,\n GROUNDING_HEADER,\n INSTALLED_TABLE_HEADER,\n REGENERATION_NOTE,\n} from \"#init/layout.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\nimport { AURO_CODING_RULES } from \"#init/rules.js\";\nimport { clean } from \"#utils/cem.js\";\nimport { apiBodyLines } from \"#utils/formatComponent.js\";\n\n/** A file `auro init` writes: its name and full contents. */\nexport interface GroundingFile {\n /** The file to write, relative to the project root (e.g. `AGENTS.md`). */\n filename: string;\n /** The complete file contents. */\n contents: string;\n}\n\n/**\n * The tag to display for a component: its resolved custom/prefixed tag when the\n * registry provided one (keyed by the canonical bare `auro-*` tag), else the\n * canonical tag itself. The generator never derives prefixes \u2014 an absent entry\n * simply means \"no custom registration\", so the bare tag stands.\n */\nfunction displayTag(\n component: ResolvedComponent,\n resolvedTags: ReadonlyMap<string, string>,\n): string {\n return resolvedTags.get(component.tagName) ?? component.tagName;\n}\n\n/**\n * Render one component's fenced grounding block: a resolved-tag header, the\n * prefix/subpath-aware install + register snippet, and the shared API body. The\n * import line uses the component's `importPath` (package root for a standalone,\n * subpath export for a monorepo component); the register line uses the resolved\n * tag so an assistant copies the exact call this project expects.\n */\nfunction componentBlock(component: ResolvedComponent, tag: string): string {\n const { pkg, importPath, declaration: decl } = component;\n const lines: string[] = [`${tag} (${pkg})`];\n\n const description = decl.summary || decl.description;\n if (description) {\n lines.push(clean(description));\n }\n\n const heritage = decl.superclass?.name\n ? `${decl.name} extends ${decl.superclass.name}`\n : decl.name;\n lines.push(`Class: ${heritage}`);\n\n lines.push(\"\");\n lines.push(\"Install:\");\n lines.push(` npm i ${pkg}`);\n lines.push(` import \"${importPath}\";`);\n lines.push(` ${decl.name}.register('${tag}');`);\n\n lines.push(...apiBodyLines(decl));\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render the canonical `AGENTS.md`: the frozen header + coding rules, an\n * Installed Components table with one row per component, a fenced API section per\n * component (with its resolved tag + install/register snippet), and the frozen\n * Regeneration note. Components are emitted in the order given, so a caller\n * controls listing order by ordering the input. Passing an empty list yields a\n * valid document with just the table header and no component rows/sections.\n */\nexport function generateAgentsMd(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string> = new Map(),\n): string {\n const rows = components.map((component) => {\n const tag = displayTag(component, resolvedTags);\n return `| \\`<${tag}>\\` | \\`${component.pkg}\\` | ${component.version} | \\`${component.importPath}\\` |`;\n });\n\n const sections = components.map((component) => {\n const tag = displayTag(component, resolvedTags);\n return `### \\`<${tag}>\\`\\n\\n\\`\\`\\`\\n${componentBlock(component, tag)}\\n\\`\\`\\``;\n });\n\n const installedLines = [\n \"## Installed Components\",\n \"\",\n INSTALLED_TABLE_HEADER,\n ...rows,\n ];\n if (sections.length > 0) {\n installedLines.push(\"\", sections.join(\"\\n\\n\"));\n }\n const installedSection = installedLines.join(\"\\n\");\n\n // Join the frozen sections with a single blank line between each, then one\n // trailing newline. Each constant's own trailing whitespace is trimmed so the\n // spacing is governed here, not by the constants.\n return `${[\n GROUNDING_HEADER.trimEnd(),\n AURO_CODING_RULES.trimEnd(),\n installedSection,\n REGENERATION_NOTE.trimEnd(),\n ].join(\"\\n\\n\")}\\n`;\n}\n\n/** Render the thin `CLAUDE.md` \u2014 the frozen `@AGENTS.md` import. */\nexport function generateClaudeMd(): string {\n return CLAUDE_MD;\n}\n\n/**\n * Render every grounding file `auro init` writes for v1: the canonical\n * `AGENTS.md` and the thin `CLAUDE.md` that imports it. Returned as a list so the\n * command writes them uniformly and future targets are additive here.\n */\nexport function groundingFiles(\n components: readonly ResolvedComponent[],\n resolvedTags: ReadonlyMap<string, string> = new Map(),\n): GroundingFile[] {\n return [\n {\n filename: AGENTS_FILENAME,\n contents: generateAgentsMd(components, resolvedTags),\n },\n { filename: CLAUDE_FILENAME, contents: generateClaudeMd() },\n ];\n}\n", "/**\n * Git-ignore reconciliation for the files `auro init` writes. Everything the\n * command emits \u2014 the grounding files, `auro.config.json`, and the editor\n * IntelliSense artifacts plus their wiring \u2014 is meant to be **committed** so a\n * team and CI share one deterministic set. A project `.gitignore` can silently\n * defeat that: `.vscode/` is very commonly ignored, so a `--vscode` run writes\n * `.vscode/auro.html-custom-data.json`, the local editor works, and the file is\n * never committed. This module lets the command detect that and, with consent,\n * repair it.\n *\n * Two functions, both **advisory and non-throwing** (a git hiccup must never\n * break a write that already succeeded):\n * - {@link findIgnored} \u2014 ask git which of the given paths are ignored.\n * - {@link unignore} \u2014 append the minimal `.gitignore` negations to re-include\n * them, verifying with git that the fix actually took.\n *\n * We defer to `git check-ignore` (via the `simple-git` dependency already used in\n * ../utils/gitUtils.ts) rather than parse `.gitignore` ourselves: it honors nested\n * ignore files, `.git/info/exclude`, global excludes, negations, and the rule that\n * a *tracked* file is never ignored \u2014 none of which naive string matching gets\n * right.\n */\n\nimport { appendFileSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { simpleGit } from \"simple-git\";\n\n/** Header marking the block of entries `auro init` appends to `.gitignore`. */\nconst GITIGNORE_HEADER =\n \"# Added by auro init \u2014 keep generated grounding/IntelliSense files tracked\";\n\n/**\n * The subset of `paths` (project-root-relative, forward-slash) that git would\n * ignore \u2014 i.e. that a plain `git add` would not stage. Returns `[]` when `cwd`\n * is not a git repository, git is unavailable, or `paths` is empty, so callers\n * can treat \"no git\" as \"nothing to warn about\". Never throws.\n */\nexport async function findIgnored(\n cwd: string,\n paths: string[],\n): Promise<string[]> {\n if (paths.length === 0) {\n return [];\n }\n try {\n return await simpleGit({ baseDir: cwd }).checkIgnore(paths);\n } catch {\n // Not a git repo / git missing \u2192 ignoring is not in play here.\n return [];\n }\n}\n\n/** POSIX dirname of a forward-slash path, or \"\" for a root-level file. */\nfunction parentDir(rel: string): string {\n const dir = path.posix.dirname(rel);\n return dir === \".\" ? \"\" : dir;\n}\n\n/** Trimmed set of the current `<cwd>/.gitignore` lines (empty when absent). */\nfunction readGitignoreLines(cwd: string): Set<string> {\n try {\n const current = readFileSync(path.join(cwd, \".gitignore\"), \"utf-8\");\n return new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n } catch {\n return new Set();\n }\n}\n\n/**\n * Append `lines` to `<cwd>/.gitignore` (created if absent), preserving a trailing\n * newline. With `dedupe` (the default) any line already present is skipped so\n * re-runs stay idempotent; pass `dedupe: false` for order-sensitive negation\n * blocks whose entries must land in sequence even if an equal line exists earlier\n * (a later match wins in git's last-match-wins rule).\n */\nfunction appendGitignore(cwd: string, lines: string[], dedupe = true): void {\n const gitignoreAbs = path.join(cwd, \".gitignore\");\n let current = \"\";\n try {\n current = readFileSync(gitignoreAbs, \"utf-8\");\n } catch {\n // Absent \u2192 we create it below.\n }\n const existing = new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n const toAdd = dedupe\n ? lines.filter((line) => !existing.has(line.trim()))\n : lines;\n if (toAdd.length === 0) {\n return;\n }\n // Separate the appended block from prior content when the file lacks a final \\n.\n const prefix = current === \"\" || current.endsWith(\"\\n\") ? \"\" : \"\\n\";\n try {\n appendFileSync(gitignoreAbs, `${prefix}${toAdd.join(\"\\n\")}\\n`, \"utf-8\");\n } catch {\n // Advisory and non-throwing (see the module doc): a failed .gitignore write\n // must never break an `init` whose main artifacts already landed. The path\n // simply stays ignored and surfaces to the caller as `unfixable` via the git\n // re-check in `unignore`, rather than crashing the command.\n }\n}\n\n/**\n * Un-ignore `ignoredPaths` by appending the minimal negations to `.gitignore`,\n * verifying each step with git so the returned result is never optimistic.\n *\n * Two rounds, because a bare `!<file>` cannot re-include a file whose parent\n * *directory* is excluded (a documented git limitation):\n * 1. Append `!<path>` for each ignored path; re-check.\n * 2. For anything still ignored (a parent dir is the culprit), append the\n * git-documented re-include trio per parent dir \u2014 `!<dir>/`, `<dir>/*`,\n * `!<path>` \u2014 where `<dir>/*` preserves the ignore for the dir's other files;\n * re-check.\n *\n * @returns `fixed` (now tracked) and `unfixable` (git still reports ignored after\n * both rounds \u2014 surfaced to the caller for manual handling, never silently\n * dropped).\n */\nexport async function unignore(\n cwd: string,\n ignoredPaths: string[],\n): Promise<{ fixed: string[]; unfixable: string[] }> {\n if (ignoredPaths.length === 0) {\n return { fixed: [], unfixable: [] };\n }\n\n // Round 1 \u2014 a simple negation clears a file/glob ignore (`*.json`, a bare name).\n appendGitignore(cwd, [\n GITIGNORE_HEADER,\n ...ignoredPaths.map((rel) => `!${rel}`),\n ]);\n let stillIgnored = await findIgnored(cwd, ignoredPaths);\n\n // Round 2 \u2014 a still-ignored path has an excluded ancestor dir; re-include it,\n // re-exclude its contents (to keep siblings ignored), then re-include the file.\n // Force-append (no dedupe): the `!<path>` must land AFTER `<dir>/*`, but Round 1\n // already wrote `!<path>` earlier \u2014 a deduping append would skip it and leave\n // `<dir>/*` as the last match, re-ignoring the file.\n //\n // A path that stays ignored after Round 2 is unfixable, so it re-enters this\n // block on every re-run. To avoid stacking duplicate trios, skip a path whose\n // trio is already present: `<dir>/*` is only ever written here alongside its\n // `!<path>` entries, so if both lines exist the trio ran on a prior invocation.\n if (stillIgnored.length > 0) {\n const present = readGitignoreLines(cwd);\n const trio: string[] = [];\n const seenDirs = new Set<string>();\n for (const rel of stillIgnored) {\n const dir = parentDir(rel);\n const dirBlockPresent = dir === \"\" || present.has(`${dir}/*`);\n if (dirBlockPresent && present.has(`!${rel}`)) {\n continue; // trio already written on an earlier run \u2014 don't restack it.\n }\n if (dir !== \"\" && !seenDirs.has(dir) && !present.has(`${dir}/*`)) {\n seenDirs.add(dir);\n trio.push(`!${dir}/`, `${dir}/*`);\n }\n trio.push(`!${rel}`);\n }\n if (trio.length > 0) {\n appendGitignore(cwd, trio, false);\n stillIgnored = await findIgnored(cwd, ignoredPaths);\n }\n }\n\n const unfixable = new Set(stillIgnored);\n return {\n fixed: ignoredPaths.filter((rel) => !unfixable.has(rel)),\n unfixable: [...unfixable],\n };\n}\n", "/**\n * The legacy-standalone \u2192 `auro-formkit` migration codemod.\n *\n * A consumer on a legacy standalone form package (`@aurodesignsystem/auro-input`,\n * \u2026) is on the deprecated form of a component that now lives in the\n * `auro-formkit` monorepo. This module detects those dependencies and, on request,\n * rewrites the project onto formkit: it swaps the `package.json` dependency and\n * rewrites the bare import specifiers to the formkit subpath\n * (`@aurodesignsystem/auro-formkit/auro-<x>`).\n *\n * It is intentionally file-in / file-out \u2014 no prompting, no network \u2014 so the `init`\n * command owns the interactive confirm and the non-interactive/CI guard, and so the\n * codemod is unit-testable against a temp fixture. It is **conservative**: only an\n * exact bare specifier is rewritten; a deep import (`\u2026/auro-input/dist/x.js`) is left\n * untouched and reported, since formkit's deep layout is not a 1:1 remap.\n */\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { globSync } from \"glob\";\nimport { SOURCE_GLOB, SOURCE_GLOB_IGNORE } from \"#init/registry.js\";\nimport {\n FORMKIT_PACKAGE,\n formkitSubpathFor,\n isLegacyFormkitPackage,\n LEGACY_FORMKIT_PACKAGES,\n} from \"#static/formkitMigration.js\";\n\n/** A legacy standalone package declared in the consumer's `package.json`. */\nexport interface LegacyDependency {\n /** The standalone package name, e.g. `@aurodesignsystem/auro-input`. */\n pkg: string;\n /** Its declared version range (from `dependencies` or `devDependencies`). */\n version: string;\n /** Which manifest field it was declared in. */\n field: \"dependencies\" | \"devDependencies\";\n}\n\n/** A deep import the codemod deliberately left in place for manual follow-up. */\nexport interface SkippedDeepImport {\n /** The source file (relative to `cwd`) containing the import. */\n file: string;\n /** The full deep specifier, e.g. `@aurodesignsystem/auro-input/dist/index.js`. */\n specifier: string;\n}\n\n/** What {@link migrateToFormkit} changed, for the caller to report and tests to assert. */\nexport interface MigrationReport {\n /** Legacy packages removed from `package.json`. */\n packagesMigrated: string[];\n /** Whether `auro-formkit` was newly added or already a dependency. */\n formkit: \"added\" | \"present\";\n /** Source files (relative to `cwd`) whose import specifiers were rewritten. */\n filesChanged: string[];\n /** Total bare specifiers rewritten across all files. */\n rewriteCount: number;\n /** Deep imports left untouched \u2014 a formkit deep path can't be guessed 1:1. */\n deepImports: SkippedDeepImport[];\n}\n\ntype PackageJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n};\n\nconst PACKAGE_JSON = \"package.json\";\n\n/** Read and parse `<cwd>/package.json`, or `null` when it is absent. */\n/**\n * The indentation of `raw`'s first indented line, as a `JSON.stringify` spec\n * (the indent string \u2014 `\" \"`, `\" \"`, `\"\\t\"`), or `2` when none is discernible\n * (a single-line or empty object). Lets a rewrite match the consumer's own style.\n */\nfunction detectJsonIndent(raw: string): string | number {\n const match = raw.match(/\\n([ \\t]+)\\S/u);\n return match ? match[1] : 2;\n}\n\n/**\n * Read and parse `<cwd>/package.json`, returning the parsed object alongside the\n * file's detected indentation so a rewrite preserves the consumer's style\n * (2-space, 4-space, tabs) rather than normalising it \u2014 keeping the migration's\n * `git diff` to the dependency changes alone. Returns `null` when the file is\n * absent; throws on malformed JSON.\n */\nfunction readPackageJson(\n cwd: string,\n): { pkgJson: PackageJson; indent: string | number } | null {\n let raw: string;\n try {\n raw = readFileSync(path.join(cwd, PACKAGE_JSON), \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n try {\n return {\n pkgJson: JSON.parse(raw) as PackageJson,\n indent: detectJsonIndent(raw),\n };\n } catch {\n throw new Error(`${PACKAGE_JSON}: invalid JSON.`);\n }\n}\n\n/**\n * Detect the legacy standalone form packages declared in the consumer's\n * `package.json` (`dependencies` + `devDependencies`). This is authoritative for\n * \"installed\" \u2014 it is exactly what the migration edits \u2014 and version-independent:\n * any declared legacy standalone qualifies, regardless of how current it is.\n * Returns `[]` when there is no `package.json`; throws on malformed JSON.\n */\nexport function detectLegacyFormkit(cwd: string): LegacyDependency[] {\n const parsed = readPackageJson(cwd);\n if (!parsed) {\n return [];\n }\n const { pkgJson } = parsed;\n\n const found: LegacyDependency[] = [];\n const fields: LegacyDependency[\"field\"][] = [\n \"dependencies\",\n \"devDependencies\",\n ];\n // Iterate the curated legacy list (stable, deterministic order) rather than the\n // manifest's key order, so the report reads the same across projects.\n for (const pkg of LEGACY_FORMKIT_PACKAGES) {\n for (const field of fields) {\n const version = pkgJson[field]?.[pkg];\n if (typeof version === \"string\") {\n found.push({ pkg, version, field });\n break; // a package in both fields is reported once (dependencies wins)\n }\n }\n }\n return found;\n}\n\n/** Escape a string for literal use inside a `RegExp`. */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Rewrite one source file's legacy specifiers to formkit subpaths. An exact bare\n * specifier (`\"@aurodesignsystem/auro-input\"`, any quote style) is rewritten; a deep\n * specifier (`\"@aurodesignsystem/auro-input/\u2026\"`) is left in place and returned as a\n * skip. Returns the (possibly unchanged) source, the number of rewrites, and any\n * deep imports seen.\n */\nfunction rewriteSource(\n source: string,\n legacyPkgs: readonly string[],\n): { next: string; rewrites: number; deep: string[] } {\n let next = source;\n let rewrites = 0;\n const deep: string[] = [];\n\n for (const pkg of legacyPkgs) {\n const escaped = escapeRegExp(pkg);\n // Exact bare specifier: quote, package, same quote \u2014 the trailing quote rules\n // out any deep `\u2026/dist` path (which has a `/` before the quote).\n const bare = new RegExp(`(['\"\\`])${escaped}\\\\1`, \"g\");\n next = next.replace(bare, (_match, quote: string) => {\n rewrites += 1;\n return `${quote}${formkitSubpathFor(pkg)}${quote}`;\n });\n\n // Deep specifier: quote, package, `/`, anything but the quote, same quote.\n const deepRe = new RegExp(`(['\"\\`])(${escaped}/[^'\"\\`]*)\\\\1`, \"g\");\n let deepMatch: RegExpExecArray | null = deepRe.exec(next);\n while (deepMatch !== null) {\n deep.push(deepMatch[2]);\n deepMatch = deepRe.exec(next);\n }\n }\n\n return { next, rewrites, deep };\n}\n\n/**\n * Migrate the project at `cwd` off the given legacy standalone packages and onto\n * `auro-formkit`: remove each from `package.json`, ensure `auro-formkit` is a\n * dependency (added as `\"latest\"` when absent \u2014 the exact version resolves on the\n * user's next `npm install`; an existing formkit version is kept), and rewrite bare\n * legacy import specifiers across the project's source to the formkit subpath.\n *\n * `legacy` is normally {@link detectLegacyFormkit}'s output; only entries that are\n * genuine legacy packages are acted on. Returns a {@link MigrationReport}.\n */\nexport function migrateToFormkit(\n cwd: string,\n legacy: readonly LegacyDependency[],\n): MigrationReport {\n const legacyPkgs = [\n ...new Set(legacy.map((l) => l.pkg).filter(isLegacyFormkitPackage)),\n ];\n\n const report: MigrationReport = {\n packagesMigrated: [],\n formkit: \"present\",\n filesChanged: [],\n rewriteCount: 0,\n deepImports: [],\n };\n if (legacyPkgs.length === 0) {\n return report;\n }\n\n // 1. package.json \u2014 swap the legacy deps for auro-formkit.\n const parsed = readPackageJson(cwd);\n if (parsed) {\n const { pkgJson, indent } = parsed;\n for (const field of [\"dependencies\", \"devDependencies\"] as const) {\n const block = pkgJson[field];\n if (!block) {\n continue;\n }\n for (const pkg of legacyPkgs) {\n if (pkg in block) {\n delete block[pkg];\n if (!report.packagesMigrated.includes(pkg)) {\n report.packagesMigrated.push(pkg);\n }\n }\n }\n }\n\n const alreadyHasFormkit =\n Boolean(pkgJson.dependencies?.[FORMKIT_PACKAGE]) ||\n Boolean(pkgJson.devDependencies?.[FORMKIT_PACKAGE]);\n if (alreadyHasFormkit) {\n report.formkit = \"present\";\n } else {\n pkgJson.dependencies ??= {};\n pkgJson.dependencies[FORMKIT_PACKAGE] = \"latest\";\n report.formkit = \"added\";\n }\n\n writeFileSync(\n path.join(cwd, PACKAGE_JSON),\n `${JSON.stringify(pkgJson, null, indent)}\\n`,\n \"utf-8\",\n );\n }\n\n // 2. Source \u2014 rewrite bare legacy specifiers to formkit subpaths.\n const files = globSync(SOURCE_GLOB, {\n cwd,\n absolute: true,\n nodir: true,\n ignore: SOURCE_GLOB_IGNORE,\n });\n for (const file of files) {\n let source: string;\n try {\n source = readFileSync(file, \"utf-8\");\n } catch {\n continue; // unreadable file \u2014 skip, mirrors the scanner's tolerance\n }\n const { next, rewrites, deep } = rewriteSource(source, legacyPkgs);\n const rel = path.relative(cwd, file);\n for (const specifier of deep) {\n report.deepImports.push({ file: rel, specifier });\n }\n if (rewrites > 0 && next !== source) {\n writeFileSync(file, next, \"utf-8\");\n report.filesChanged.push(rel);\n report.rewriteCount += rewrites;\n }\n }\n\n return report;\n}\n", "/**\n * Resolve each installed component's canonical `auro-*` tag to the tag the\n * consumer project actually registers, producing the `resolvedTags`\n * `Map<canonical-tag, custom-tag>` the generator (`generator.ts`) consumes.\n *\n * Resolution precedence is **config \u2192 AST scan \u2192 default prefix** (the frozen\n * decision): an explicit `auro.config.json` override wins; else a\n * statically-detected `register('<tag>')` in consumer source; else the default\n * prefix is applied. Anything unresolvable is **warned, never guessed**.\n *\n * This module is a PURE PLANNER plus two thin IO wrappers (`loadConfig`/\n * `saveConfig`, `scanProject`). It performs no prompting: the interactive prefix\n * prompt, the majority-confirm, and the non-interactive TTY/CI guard live in the\n * `init` command (build-order step 6), which consumes {@link planTagResolution}.\n *\n * **Two-phase caller contract.** Call {@link planTagResolution} once. If the plan\n * reports `needsDefaultPrefix`, obtain a prefix (prompt/confirm `suggestedDefault`,\n * take `--prefix`, or fail cleanly in CI) and **re-call** with that `prefix` to get\n * the authoritative `resolvedTags` + `config`. Only persist (`saveConfig`) a plan\n * whose `needsDefaultPrefix` is `false`.\n */\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { globSync } from \"glob\";\nimport ts from \"typescript\";\nimport {\n type AuroConfig,\n CONFIG_FILENAME,\n CONFIG_VERSION,\n} from \"#init/config.js\";\nimport type { ResolvedComponent } from \"#init/resolver.js\";\n\nconst AURO_PREFIX = \"auro-\";\n\n/**\n * The consumer source files both the AST scan and the formkit migration walk: JS/TS\n * in every common extension plus Svelte single-file components. Shared so the two\n * stay in lockstep \u2014 anything the scanner reads is a file the migration may rewrite.\n */\nexport const SOURCE_GLOB = \"**/*.{js,jsx,ts,tsx,mjs,cjs,svelte}\";\n\n/**\n * Directories excluded from {@link SOURCE_GLOB} \u2014 dependencies and build output,\n * whose Auro `static register` defaults would be false positives (scan) and are not\n * the consumer's own source to rewrite (migration).\n */\nexport const SOURCE_GLOB_IGNORE = [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/coverage/**\",\n];\n\n/** A registry-layer failure with a caller-presentable message. */\nexport class RegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RegistryError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Config IO\n// ---------------------------------------------------------------------------\n\n/** A fresh, empty config with the given default prefix (`\"\"` = bare/no prefix). */\nexport function emptyConfig(defaultPrefix = \"\"): AuroConfig {\n return {\n version: CONFIG_VERSION,\n init: { prefix: { default: defaultPrefix, overrides: {} } },\n };\n}\n\n/**\n * Structurally validate a parsed value against the frozen {@link AuroConfig}\n * shape. Returns the narrowed config or throws {@link RegistryError} \u2014 a newer\n * `version` is an explicit, actionable failure (the format-freeze contract), not\n * a silent best-effort read.\n */\nfunction assertConfig(value: unknown, source: string): AuroConfig {\n const obj = value as Partial<AuroConfig> | null;\n if (!obj || typeof obj !== \"object\") {\n throw new RegistryError(`${source}: not a JSON object.`);\n }\n if (obj.version !== CONFIG_VERSION) {\n throw new RegistryError(\n `${source}: unsupported config version ${String(obj.version)} (expected ${CONFIG_VERSION}). Upgrade the CLI or remove the file.`,\n );\n }\n const prefix = obj.init?.prefix;\n if (\n !prefix ||\n typeof prefix.default !== \"string\" ||\n typeof prefix.overrides !== \"object\" ||\n prefix.overrides === null\n ) {\n throw new RegistryError(`${source}: malformed init.prefix block.`);\n }\n return obj as AuroConfig;\n}\n\n/**\n * Read `<cwd>/auro.config.json`. Returns `null` when the file is absent (a\n * first-run project), or the validated {@link AuroConfig}. Throws\n * {@link RegistryError} on malformed or unsupported-version JSON.\n */\nexport function loadConfig(cwd: string): AuroConfig | null {\n const file = path.join(cwd, CONFIG_FILENAME);\n let raw: string;\n try {\n raw = readFileSync(file, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new RegistryError(`${CONFIG_FILENAME}: invalid JSON.`);\n }\n return assertConfig(parsed, CONFIG_FILENAME);\n}\n\n/** Write `<cwd>/auro.config.json` as pretty JSON with a trailing newline. */\nexport function saveConfig(cwd: string, config: AuroConfig): void {\n const file = path.join(cwd, CONFIG_FILENAME);\n writeFileSync(file, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// AST scan \u2014 read-only detection of existing register('<tag>') calls\n// ---------------------------------------------------------------------------\n\n/** A statically-resolvable `<Class>.register('<tag>')` found in consumer source. */\nexport interface RegistrationMatch {\n /** The callee object identifier (e.g. `AuroInput`), when it is a plain name. */\n className?: string;\n /** The literal tag passed to `register(...)`. */\n tag: string;\n}\n\n/** The result of scanning source: resolvable matches plus skip/parse warnings. */\nexport interface RegistrationScan {\n matches: RegistrationMatch[];\n /**\n * Callee class names that called `register()` with **no argument** \u2014 the\n * canonical default-tag registration (e.g. `AuroButton.register()` registers\n * `<auro-button>`). Optional so callers may omit it; the planner reads it to\n * warn when a default registration is grounded under a custom prefix.\n */\n defaultRegistrations?: string[];\n warnings: string[];\n}\n\nfunction scriptKindFor(filePath: string): ts.ScriptKind {\n switch (path.extname(filePath).toLowerCase()) {\n case \".tsx\":\n return ts.ScriptKind.TSX;\n case \".jsx\":\n return ts.ScriptKind.JSX;\n case \".ts\":\n case \".mts\":\n case \".cts\":\n return ts.ScriptKind.TS;\n default:\n return ts.ScriptKind.JS;\n }\n}\n\n/**\n * A statically-resolvable tag argument is a plain string literal or a backtick\n * string with no `${}` substitutions (a `NoSubstitutionTemplateLiteral`).\n */\nfunction staticTag(arg: ts.Expression | undefined): string | null {\n if (!arg) {\n return null;\n }\n if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {\n return arg.text;\n }\n return null;\n}\n\n/**\n * Scan one source string for `<Class>.register('<tag>')` calls. Purely syntactic\n * (`ts.createSourceFile`, no type-checker): captures every call whose first\n * argument is a static tag. A `register()` with **no argument** is the canonical\n * default-tag registration \u2014 recorded (by callee class name) in\n * `defaultRegistrations`, never warned, since the tag is known (the component's\n * `auro-*` tag). Any `.register(...)` whose tag is a template with substitutions,\n * an identifier, a call, or a spread is warned and skipped \u2014 the scan never\n * guesses a computed tag. A parse failure warns and yields no matches for that\n * file rather than throwing.\n *\n * `scriptKind` defaults to the one inferred from `filePath`'s extension; callers\n * that feed extracted source under a different-looking path (e.g. a Svelte\n * `<script lang=\"ts\">` block scanned under its `.svelte` path) pass it explicitly.\n */\nexport function scanSource(\n filePath: string,\n source: string,\n scriptKind: ts.ScriptKind = scriptKindFor(filePath),\n): RegistrationScan {\n const matches: RegistrationMatch[] = [];\n const defaultRegistrations: string[] = [];\n const warnings: string[] = [];\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.ES2022,\n /* setParentNodes */ true,\n scriptKind,\n );\n } catch {\n return {\n matches,\n defaultRegistrations,\n warnings: [`${filePath}: could not be parsed; skipped.`],\n };\n }\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === \"register\"\n ) {\n const object = node.expression.expression;\n const className = ts.isIdentifier(object) ? object.text : undefined;\n\n if (node.arguments.length === 0) {\n // A no-arg register() uses the component's canonical default tag. Record\n // it (when the callee is a plain class name) so the planner can flag an\n // app-vs-grounding mismatch under a custom prefix; a callee we cannot name\n // is not actionable, so drop it silently.\n if (className) {\n defaultRegistrations.push(className);\n }\n } else {\n const tag = staticTag(node.arguments[0]);\n if (tag === null) {\n warnings.push(\n `${filePath}: register() with a non-literal tag could not be resolved; skipped.`,\n );\n } else {\n matches.push({ className, tag });\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n\n return { matches, defaultRegistrations, warnings };\n}\n\n/** One extracted Svelte `<script>` block: its inner source and its language. */\ninterface SvelteScript {\n content: string;\n scriptKind: ts.ScriptKind;\n}\n\n// A Svelte `<script ...>...</script>` block. Non-greedy body so it stops at the\n// first closing tag; `gi` walks every block (an instance block plus an optional\n// `context=\"module\"` / Svelte-5 `module` block).\nconst SVELTE_SCRIPT = /<script\\b([^>]*)>([\\s\\S]*?)<\\/script>/gi;\n// A `lang=\"ts\"` / `lang='typescript'` (quotes optional) attribute \u2192 TypeScript.\nconst SVELTE_LANG_TS = /\\blang\\s*=\\s*[\"']?(?:ts|typescript)[\"']?/i;\n\n/**\n * Pull the JS/TS out of a Svelte single-file component. A `.svelte` file's logic\n * lives in one or more `<script>` blocks (an instance block plus an optional\n * `context=\"module\"`/`module` block); the surrounding template markup and\n * `<style>` are not parseable as a module, so only the script bodies are\n * returned \u2014 each tagged TS or JS from its `lang` attribute. Returns `[]` when\n * the component has no `<script>` block. Purely lexical (no Svelte compiler): a\n * literal `</script>` inside a string would end a block early, an accepted v1\n * limitation.\n */\nexport function extractSvelteScripts(source: string): SvelteScript[] {\n const scripts: SvelteScript[] = [];\n // A shared regex with the `g` flag carries lastIndex across calls, so reset it\n // before each scan to stay reentrant.\n SVELTE_SCRIPT.lastIndex = 0;\n let match: RegExpExecArray | null = SVELTE_SCRIPT.exec(source);\n while (match !== null) {\n const [, attributes, content] = match;\n scripts.push({\n content,\n scriptKind: SVELTE_LANG_TS.test(attributes)\n ? ts.ScriptKind.TS\n : ts.ScriptKind.JS,\n });\n match = SVELTE_SCRIPT.exec(source);\n }\n return scripts;\n}\n\n/**\n * Scan the project's own sources under `cwd` for existing registrations. Globs\n * `**\\/*.{js,jsx,ts,tsx,mjs,cjs,svelte}` (excluding `node_modules`/`dist`/`build`/\n * `coverage` \u2014 Auro's own `static register` defaults would be false positives),\n * reads each file, and aggregates {@link scanSource}. A `.svelte` file is scanned\n * per extracted `<script>` block ({@link extractSvelteScripts}) so its template\n * markup never reaches the parser. A read failure on one file warns and continues.\n */\nexport function scanProject(cwd: string): RegistrationScan {\n const files = globSync(SOURCE_GLOB, {\n cwd,\n absolute: true,\n nodir: true,\n ignore: SOURCE_GLOB_IGNORE,\n });\n\n const matches: RegistrationMatch[] = [];\n const defaultRegistrations: string[] = [];\n const warnings: string[] = [];\n const collect = (scan: RegistrationScan): void => {\n matches.push(...scan.matches);\n defaultRegistrations.push(...(scan.defaultRegistrations ?? []));\n warnings.push(...scan.warnings);\n };\n\n for (const file of files) {\n let source: string;\n try {\n source = readFileSync(file, \"utf-8\");\n } catch {\n warnings.push(`${file}: could not be read; skipped.`);\n continue;\n }\n if (path.extname(file).toLowerCase() === \".svelte\") {\n for (const { content, scriptKind } of extractSvelteScripts(source)) {\n collect(scanSource(file, content, scriptKind));\n }\n } else {\n collect(scanSource(file, source));\n }\n }\n return { matches, defaultRegistrations, warnings };\n}\n\n// ---------------------------------------------------------------------------\n// Prefix inference\n// ---------------------------------------------------------------------------\n\n/** The bare component base of a canonical tag: `auro-input` \u2192 `input`. */\nfunction baseOf(canonicalTag: string): string {\n return canonicalTag.startsWith(AURO_PREFIX)\n ? canonicalTag.slice(AURO_PREFIX.length)\n : canonicalTag;\n}\n\n/**\n * Infer the prefix that turns a canonical tag into a custom tag: for\n * `auro-input` \u2192 `legacy-input` the prefix is `legacy-`. Returns `null` when the\n * custom tag is a full rename (does not end with the component base), and so\n * carries no reusable prefix.\n */\nexport function inferPrefixFromTag(\n canonicalTag: string,\n customTag: string,\n): string | null {\n const base = baseOf(canonicalTag);\n if (!customTag.endsWith(base)) {\n return null;\n }\n return customTag.slice(0, customTag.length - base.length);\n}\n\n/** The most common default prefix suggested by existing registrations. */\nexport interface PrefixSuggestion {\n /** The majority real prefix, or `undefined` when none is inferable. */\n suggestion?: string;\n /** True when two or more distinct real prefixes were seen (a conflict). */\n mixed: boolean;\n}\n\n/**\n * Suggest a default prefix from a set of inferred prefixes. Empty and bare\n * (`auro-`) prefixes are not real custom registrations and are ignored. Returns\n * the most frequent remaining prefix and whether the real prefixes disagree.\n */\nexport function suggestDefaultPrefix(\n prefixes: readonly (string | null)[],\n): PrefixSuggestion {\n const counts = new Map<string, number>();\n for (const prefix of prefixes) {\n if (!prefix || prefix === AURO_PREFIX) {\n continue;\n }\n counts.set(prefix, (counts.get(prefix) ?? 0) + 1);\n }\n if (counts.size === 0) {\n return { mixed: false };\n }\n let suggestion: string | undefined;\n let best = -1;\n for (const [prefix, count] of counts) {\n if (count > best) {\n best = count;\n suggestion = prefix;\n }\n }\n return { suggestion, mixed: counts.size > 1 };\n}\n\n// ---------------------------------------------------------------------------\n// Tag-resolution planner\n// ---------------------------------------------------------------------------\n\n/** Existing registrations reconciled to their component's canonical tag. */\ninterface Reconciled {\n /** canonical `auro-*` tag \u2192 the custom tag detected for it. */\n overrides: Map<string, string>;\n /** canonical `auro-*` tag \u2192 callee class name that registered its default tag. */\n defaultRegistered: Map<string, string>;\n warnings: string[];\n}\n\n/**\n * Tie each scanned registration to an installed component by matching the\n * callee class name against the component's declaration `name`. A static-tag\n * match whose class name is missing or unknown among the components is warned (a\n * `register()` we cannot attribute to an installed component) and dropped. No-arg\n * default registrations are tied the same way, but an untieable one is dropped\n * silently \u2014 a bare `register()` on an unknown class is not actionable.\n */\nfunction reconcileRegistrations(\n components: readonly ResolvedComponent[],\n matches: readonly RegistrationMatch[],\n defaultRegistrations: readonly string[] = [],\n): Reconciled {\n const byClassName = new Map<string, string>();\n for (const component of components) {\n byClassName.set(component.declaration.name, component.tagName);\n }\n\n const overrides = new Map<string, string>();\n const warnings: string[] = [];\n for (const match of matches) {\n const canonical = match.className\n ? byClassName.get(match.className)\n : undefined;\n if (!canonical) {\n warnings.push(\n `Found register('${match.tag}')${match.className ? ` on ${match.className}` : \"\"} but could not tie it to an installed Auro component; ignored.`,\n );\n continue;\n }\n overrides.set(canonical, match.tag);\n }\n\n const defaultRegistered = new Map<string, string>();\n for (const className of defaultRegistrations) {\n const canonical = byClassName.get(className);\n if (canonical) {\n defaultRegistered.set(canonical, className);\n }\n }\n return { overrides, defaultRegistered, warnings };\n}\n\n/** Options controlling {@link planTagResolution}. */\nexport interface PlanOptions {\n /** The loaded `auro.config.json`, if the project has one. */\n config?: AuroConfig | null;\n /** The result of scanning consumer source for existing registrations. */\n scan?: RegistrationScan;\n /** An explicit default prefix (from `--prefix`), overriding the config default. */\n prefix?: string;\n}\n\n/** The outcome of planning tag resolution for an installed component set. */\nexport interface TagResolutionPlan {\n /** canonical `auro-*` tag \u2192 resolved custom tag, for every resolvable component. */\n resolvedTags: Map<string, string>;\n /** The config to persist once `needsDefaultPrefix` is `false`. */\n config: AuroConfig;\n /** Canonical tags with no override/scan match, awaiting a default prefix. */\n needingDefault: string[];\n /** True when components await a default prefix but none is known yet. */\n needsDefaultPrefix: boolean;\n /** Majority prefix suggested from existing registrations, when any. */\n suggestedDefault?: string;\n /** True when existing registrations imply two or more distinct prefixes. */\n mixedPrefixes: boolean;\n /**\n * Non-fatal warnings (unresolvable registrations, scan parse skips). Advisory\n * only \u2014 the caller prints these as plain `\u26A0` lines.\n */\n warnings: string[];\n /**\n * The subset of advisories where a resolved/grounded tag may **not match the\n * tag the app registers at runtime** \u2014 a prefix grounded a custom tag with no\n * corroborating `register()` in source, or a detected default `register()` was\n * grounded under a custom prefix. These silently break IntelliSense (the\n * generated artifacts key on a tag the markup never uses), so the caller\n * surfaces them in a prominent bordered banner rather than a plain line. See\n * {@link renderWarningBanner}.\n */\n reconciliationWarnings: string[];\n /**\n * Components grounded under their bare `auro-*` tag because no custom prefix\n * was given. Less severe than a reconciliation mismatch (the grounding is\n * self-consistent), but still worth surfacing prominently since a bare tag\n * risks registration collisions \u2014 the caller renders these in a yellow\n * bordered banner. See {@link renderWarningBanner}.\n */\n noPrefixWarnings: string[];\n}\n\n/**\n * Apply a default prefix to a canonical tag. A missing or bare (`auro-`) prefix\n * yields the canonical tag unchanged (the component keeps its `auro-*` tag);\n * otherwise the `auro-` prefix is replaced, e.g. `myapp-` + `auro-button` \u2192\n * `myapp-button`.\n */\nfunction applyPrefix(prefix: string, canonicalTag: string): string {\n if (!prefix || prefix === AURO_PREFIX) {\n return canonicalTag;\n }\n return prefix + baseOf(canonicalTag);\n}\n\n/**\n * Plan the resolved custom tag for every installed component, following the\n * frozen **config \u2192 scan \u2192 default prefix** precedence. Pure: performs no IO and\n * no prompting. When some components still need the default prefix and none is\n * known (`needsDefaultPrefix`), the caller resolves a prefix (prompt/`--prefix`/\n * CI-fail) and re-calls with it; the returned `config` is authoritative only once\n * `needsDefaultPrefix` is `false`.\n */\nexport function planTagResolution(\n components: readonly ResolvedComponent[],\n options: PlanOptions = {},\n): TagResolutionPlan {\n const { config, scan, prefix } = options;\n const configOverrides = config?.init.prefix.overrides ?? {};\n const reconciled = reconcileRegistrations(\n components,\n scan?.matches ?? [],\n scan?.defaultRegistrations ?? [],\n );\n\n // The effective default: an explicit --prefix wins over a persisted config\n // default. `undefined` means \"not yet known\" (distinct from a bare \"\").\n const configDefault = config?.init.prefix.default;\n const effectiveDefault = prefix ?? configDefault;\n\n const resolvedTags = new Map<string, string>();\n const persistOverrides: Record<string, string> = { ...configOverrides };\n const needingDefault: string[] = [];\n const warnings = [...(scan?.warnings ?? []), ...reconciled.warnings];\n // App-vs-grounding tag mismatches \u2014 surfaced prominently, not inline (see the\n // TagResolutionPlan.reconciliationWarnings doc).\n const reconciliationWarnings: string[] = [];\n // Bare `auro-*` groundings \u2014 surfaced in a yellow banner (see the\n // TagResolutionPlan.noPrefixWarnings doc).\n const noPrefixWarnings: string[] = [];\n\n for (const component of components) {\n const tag = component.tagName;\n\n const fromConfig = configOverrides[tag];\n if (fromConfig !== undefined) {\n resolvedTags.set(tag, fromConfig);\n continue;\n }\n\n const fromScan = reconciled.overrides.get(tag);\n if (fromScan !== undefined) {\n resolvedTags.set(tag, fromScan);\n persistOverrides[tag] = fromScan; // detected registrations are persisted\n continue;\n }\n\n if (effectiveDefault === undefined) {\n needingDefault.push(tag);\n continue;\n }\n\n const resolved = applyPrefix(effectiveDefault, tag);\n resolvedTags.set(tag, resolved);\n if (resolved === tag) {\n noPrefixWarnings.push(\n `${tag}: no custom prefix \u2014 grounding it under its bare 'auro-*' tag. Pass a prefix to avoid registration collisions.`,\n );\n } else if (!reconciled.defaultRegistered.has(tag)) {\n // The prefix produced a custom tag, but nothing in the consumer's source\n // corroborates it \u2014 no scan match (those `continue` above) and no detected\n // no-arg default register() (that case is warned specifically below). Auro\n // components self-register their default `auro-*` tag on import, so a\n // project that never calls register('<resolved>') runs `<auro-*>` at\n // runtime while every generated artifact is keyed on `<resolved>` \u2014 the\n // IntelliSense silently matches nothing. We cannot see auto-registration\n // statically, so advise (never guess): name the exact call that makes the\n // app agree with the grounding.\n reconciliationWarnings.push(\n `${tag}: grounded as '<${resolved}>' from the '${effectiveDefault}' prefix, but no register('${resolved}') was found in your source. If ${component.declaration.name} is registered under a different tag (e.g. the default '<${tag}>' from a side-effect import), IntelliSense will not match your markup \u2014 call ${component.declaration.name}.register('${resolved}') so your app matches the generated tags.`,\n );\n }\n }\n\n // A component the consumer registers with the default no-arg register() keeps\n // its canonical `auro-*` tag at runtime. If we grounded it under a custom tag\n // (a prefix or a config/scan override), the app and AGENTS.md diverge \u2014 warn so\n // the user updates their register() call. Never rewrite their source (v1 docs).\n for (const [canonical, className] of reconciled.defaultRegistered) {\n const resolved = resolvedTags.get(canonical);\n if (resolved !== undefined && resolved !== canonical) {\n reconciliationWarnings.push(\n `${className}.register() uses the default '<${canonical}>' tag, but this project grounds it as '<${resolved}>'. Update the register() call to '${resolved}' so your app matches AGENTS.md.`,\n );\n }\n }\n\n // Suggest a default from every real (config + scanned) custom registration.\n const inferred = [\n ...Object.entries(configOverrides),\n ...reconciled.overrides,\n ].map(([canonical, custom]) => inferPrefixFromTag(canonical, custom));\n const { suggestion, mixed } = suggestDefaultPrefix(inferred);\n\n const needsDefaultPrefix =\n needingDefault.length > 0 && effectiveDefault === undefined;\n\n const persistedDefault = effectiveDefault ?? suggestion ?? \"\";\n const persistConfig: AuroConfig = {\n version: CONFIG_VERSION,\n init: {\n prefix: { default: persistedDefault, overrides: persistOverrides },\n },\n };\n\n return {\n resolvedTags,\n config: persistConfig,\n needingDefault,\n needsDefaultPrefix,\n suggestedDefault: suggestion,\n mixedPrefixes: mixed,\n warnings,\n reconciliationWarnings,\n noPrefixWarnings,\n };\n}\n", "/**\n * Teardown for `auro init --reset`: reverse everything a previous `auro init`\n * run produced. Two phases so the command can show an accurate confirm list\n * before touching disk (mirroring registry.ts's plan/apply split):\n *\n * - {@link planReset} \u2014 READ-ONLY. Stats each known artifact path, signature-\n * guards the grounding files (`AGENTS.md`/`CLAUDE.md`) and the CLI config so an\n * unrelated or hand-authored file is never deleted, and computes the two\n * config un-merges (`.vscode/settings.json`, `tsconfig.json`/`jsconfig.json`).\n * - {@link applyReset} \u2014 the only mutating step: delete the guarded files, write\n * the un-merged configs, prune the now-empty `auro-types/` and `.vscode/` dirs.\n *\n * Sweeps the frozen artifact paths directly (layout constants) rather than\n * trusting `auro.config.json`, so a reset still works when that file was deleted\n * or corrupted. Deliberately does NOT reverse the one-way `auro-formkit`\n * migration codemod \u2014 that edits package.json + import specifiers and is not\n * safely reversible; the command notes this rather than guessing.\n *\n * @see docs/pt-m2-completion-plan.md and the `auro init` inventory in the\n * `--reset` plan.\n */\n\nimport {\n existsSync,\n readdirSync,\n readFileSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { parse as parseJsonc } from \"jsonc-parser\";\nimport { CONFIG_FILENAME } from \"#init/config.js\";\nimport {\n CSS_SNIPPETS_PATH,\n FRAMEWORK_TYPES_DIR,\n HTML_CUSTOM_DATA_PATH,\n JSX_TYPES_PATH,\n SVELTE_TYPES_PATH,\n VSCODE_DIR,\n VSCODE_SETTINGS_FILENAME,\n} from \"#init/editors/layout.js\";\nimport {\n type MergeResult,\n unmergeTsconfigInclude,\n unmergeVsCodeSettings,\n} from \"#init/editors/settings.js\";\nimport {\n AGENTS_FILENAME,\n CLAUDE_FILENAME,\n CLAUDE_MD,\n GROUNDING_MARKER,\n} from \"#init/layout.js\";\nimport { loadConfig, RegistryError } from \"#init/registry.js\";\n\n/** A generated file that exists but did not pass its signature guard. */\nexport interface SkippedFile {\n /** Project-root-relative path (forward slashes). */\n path: string;\n /** Why it was left in place (shown to the user). */\n reason: string;\n}\n\n/** An un-merge to apply to one existing config file. */\ninterface ConfigUnmerge {\n /** Project-root-relative path (forward slashes). */\n path: string;\n /** The un-merge result (contents to write when `changed`). */\n result: MergeResult;\n}\n\n/** The read-only plan of what a reset will remove and un-merge. */\nexport interface ResetPlan {\n /** Root-relative paths that exist and passed their guard \u2014 safe to delete. */\n filesToRemove: string[];\n /** Files that exist but were left in place (failed a signature/parse guard). */\n filesToSkip: SkippedFile[];\n /** Config un-merges that actually change a file (only `changed` results). */\n unmerges: ConfigUnmerge[];\n /** Warnings from an un-merge that had to be skipped (unparseable config). */\n warnings: string[];\n /** Dirs to remove if empty after file removal, most-nested first. */\n dirsToPrune: string[];\n}\n\n/** What {@link applyReset} actually did. */\nexport interface ResetReport {\n /** Root-relative paths removed. */\n removed: string[];\n /** Root-relative config paths whose Auro entry was un-merged. */\n unmerged: string[];\n /** Root-relative dirs pruned because they were left empty. */\n prunedDirs: string[];\n /** Files left in place (carried through from the plan). */\n skipped: SkippedFile[];\n /** Advisory warnings (carried from the plan). */\n warnings: string[];\n}\n\n/** Absolute path for a forward-slash, root-relative artifact path. */\nfunction toAbsolute(cwd: string, rel: string): string {\n return path.join(cwd, ...rel.split(\"/\"));\n}\n\n/** True when `source` is JSONC for an object with no keys (`{}`, comments aside). */\nfunction isEmptyObject(source: string): boolean {\n const data = parseJsonc(source, [], { allowTrailingComma: true }) as unknown;\n return (\n typeof data === \"object\" &&\n data !== null &&\n !Array.isArray(data) &&\n Object.keys(data).length === 0\n );\n}\n\n/**\n * True when `source` contains a JSONC comment. Only used on content already known\n * to parse to an empty object \u2014 with no string values left, a bare `//` or `/*`\n * can only start a comment, so this needs no string-aware scan.\n */\nfunction hasComments(source: string): boolean {\n return source.includes(\"//\") || source.includes(\"/*\");\n}\n\n/** Read a file as UTF-8, or `null` when it does not exist. */\nfunction readOrNull(absolute: string): string | null {\n try {\n return readFileSync(absolute, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n}\n\n/**\n * Editor artifacts carry unambiguous Auro-namespaced names, so their mere\n * presence is enough to remove them \u2014 no content signature needed.\n */\nconst UNCONDITIONAL_ARTIFACTS = [\n HTML_CUSTOM_DATA_PATH,\n CSS_SNIPPETS_PATH,\n JSX_TYPES_PATH,\n SVELTE_TYPES_PATH,\n] as const;\n\n/**\n * Classify a grounding file: `\"remove\"` when it carries the Auro signature,\n * `\"skip\"` with a reason when it exists but looks hand-authored/unrelated, or\n * `null` when it is absent. `AGENTS.md` is matched by the generated marker\n * comment; `CLAUDE.md` by exact equality with the thin generated body.\n */\nfunction classifyGroundingFile(\n contents: string | null,\n kind: \"agents\" | \"claude\",\n): \"remove\" | SkippedFile[\"reason\"] | null {\n if (contents === null) {\n return null;\n }\n if (kind === \"agents\") {\n return contents.includes(GROUNDING_MARKER)\n ? \"remove\"\n : `not recognized as an \\`auro init\\` file (missing the \"${GROUNDING_MARKER}\" marker)`;\n }\n return contents.trim() === CLAUDE_MD.trim()\n ? \"remove\"\n : \"contains content beyond the generated `@AGENTS.md` import\";\n}\n\n/**\n * Plan a reset for `cwd` without touching disk. Sweeps every known artifact\n * path, signature-guards the grounding files and the CLI config, and computes\n * the two config un-merges against their current contents.\n */\nexport function planReset(cwd: string): ResetPlan {\n const filesToRemove: string[] = [];\n const filesToSkip: SkippedFile[] = [];\n const warnings: string[] = [];\n\n // Grounding files \u2014 signature-guarded so we never delete a file we cannot\n // confirm we authored.\n for (const [rel, kind] of [\n [AGENTS_FILENAME, \"agents\"],\n [CLAUDE_FILENAME, \"claude\"],\n ] as const) {\n const verdict = classifyGroundingFile(\n readOrNull(toAbsolute(cwd, rel)),\n kind,\n );\n if (verdict === \"remove\") {\n filesToRemove.push(rel);\n } else if (verdict !== null) {\n filesToSkip.push({ path: rel, reason: verdict });\n }\n }\n\n // auro.config.json \u2014 remove only when it parses as our config; a malformed or\n // unsupported-version file is surfaced, not nuked (it may not be ours).\n if (existsSync(toAbsolute(cwd, CONFIG_FILENAME))) {\n try {\n if (loadConfig(cwd)) {\n filesToRemove.push(CONFIG_FILENAME);\n }\n } catch (error) {\n const reason =\n error instanceof RegistryError ? error.message : String(error);\n filesToSkip.push({ path: CONFIG_FILENAME, reason });\n }\n }\n\n // Editor artifacts \u2014 unambiguous names, remove when present.\n for (const rel of UNCONDITIONAL_ARTIFACTS) {\n if (existsSync(toAbsolute(cwd, rel))) {\n filesToRemove.push(rel);\n }\n }\n\n // Config un-merges. settings.json is standalone; the TS include lives in the\n // first of tsconfig.json/jsconfig.json that exists (matches the write-side\n // \"first existing wins\" rule).\n const unmerges: ConfigUnmerge[] = [];\n const settingsRel = `${VSCODE_DIR}/${VSCODE_SETTINGS_FILENAME}`;\n const settingsContents = readOrNull(toAbsolute(cwd, settingsRel));\n if (settingsContents !== null) {\n const result = unmergeVsCodeSettings(settingsContents);\n if (result.warning) {\n warnings.push(result.warning);\n } else if (result.changed) {\n // Removing our entry emptied the object \u2192 the file held only our entry, so\n // `auro init` created it. Delete it (a faithful teardown, and so the\n // `.vscode/` prune below can reclaim a now-empty dir) rather than leaving a\n // stray `{}` that a later run only survives on by accident \u2014 UNLESS the file\n // still carries user comments, which deletion would silently discard. In\n // that case keep the file and just write back the emptied object.\n if (isEmptyObject(result.contents) && !hasComments(result.contents)) {\n filesToRemove.push(settingsRel);\n } else {\n unmerges.push({ path: settingsRel, result });\n }\n }\n }\n for (const configRel of [\"tsconfig.json\", \"jsconfig.json\"]) {\n const contents = readOrNull(toAbsolute(cwd, configRel));\n if (contents === null) {\n continue;\n }\n const result = unmergeTsconfigInclude(contents, undefined, configRel);\n if (result.warning) {\n warnings.push(result.warning);\n } else if (result.changed) {\n unmerges.push({ path: configRel, result });\n }\n // Only the first existing config is authoritative; stop after it.\n break;\n }\n\n return {\n filesToRemove,\n filesToSkip,\n unmerges,\n warnings,\n dirsToPrune: [FRAMEWORK_TYPES_DIR, VSCODE_DIR],\n };\n}\n\n/** True when the directory exists and holds no entries. */\nfunction isEmptyDir(absolute: string): boolean {\n try {\n return readdirSync(absolute).length === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Execute a {@link planReset} result: delete the guarded files, write the\n * un-merged configs, and prune the artifact dirs left empty. Idempotent \u2014 a\n * second run over an already-clean project removes nothing.\n */\nexport function applyReset(cwd: string, plan: ResetPlan): ResetReport {\n const removed: string[] = [];\n for (const rel of plan.filesToRemove) {\n rmSync(toAbsolute(cwd, rel), { force: true });\n removed.push(rel);\n }\n\n const unmerged: string[] = [];\n for (const { path: rel, result } of plan.unmerges) {\n writeFileSync(toAbsolute(cwd, rel), result.contents, \"utf-8\");\n unmerged.push(rel);\n }\n\n const prunedDirs: string[] = [];\n for (const rel of plan.dirsToPrune) {\n const absolute = toAbsolute(cwd, rel);\n if (isEmptyDir(absolute)) {\n rmdirSync(absolute);\n prunedDirs.push(rel);\n }\n }\n\n return {\n removed,\n unmerged,\n prunedDirs,\n skipped: plan.filesToSkip,\n warnings: plan.warnings,\n };\n}\n", "/**\n * Bordered, colored terminal banners for advisories that must not scroll past\n * unnoticed. The prominent cousin of a plain `\u26A0 ...` stderr line: a boxed heading\n * plus word-wrapped bullet messages, mirroring the box/heading treatment of\n * {@link renderOutdatedBanner} in ./outdated.ts so the two read as a family.\n *\n * Presentation only \u2014 no IO. Callers pass already-composed message strings and\n * print the result (typically to stderr, keeping stdout clean for piped output).\n * Colors degrade automatically: chalk disables them when the stream is not a TTY\n * (redirected to a file, captured in a test), while the border and heading keep\n * the banner legible without them.\n */\n\nimport chalk from \"chalk\";\n\n/** Banner accent, applied to the border, heading, and message text. */\nexport type BannerColor = \"red\" | \"yellow\";\n\n/** The box never grows past this many columns, so it fits a standard terminal. */\nconst MAX_WIDTH = 78;\n\n/** Content column budget for wrapped message text (leaves a small margin). */\nconst CONTENT_WIDTH = 74;\n\nconst BULLET = \" \u2022 \";\nconst CONTINUATION_INDENT = \" \";\n\n/**\n * Word-wrap `text` to at most `width` columns, breaking on whitespace only. A\n * single word longer than `width` is left intact on its own line (overflow)\n * rather than hard-split, so tokens like `Class.register('my-tag')` stay\n * copy-pasteable. Never returns an empty array \u2014 a blank input yields `[\"\"]`.\n */\nfunction wrapText(text: string, width: number): string[] {\n const words = text.split(/\\s+/u).filter(Boolean);\n if (words.length === 0) {\n return [\"\"];\n }\n const lines: string[] = [];\n let current = words[0];\n for (const word of words.slice(1)) {\n if (current.length + 1 + word.length <= width) {\n current += ` ${word}`;\n } else {\n lines.push(current);\n current = word;\n }\n }\n lines.push(current);\n return lines;\n}\n\n/**\n * Render `messages` as a bordered banner under `heading`, accented in `color`.\n * Each message becomes a wrapped bullet; long messages continue on indented\n * lines. Returns `\"\"` for an empty `messages` list so a caller can emit\n * unconditionally (`console.error(renderWarningBanner(...))`).\n *\n * The border width tracks the heading (never past {@link MAX_WIDTH}); a `\u26A0`\n * (U+26A0) in the heading renders as two columns but counts as one char, so its\n * width is nudged by one to keep the border from falling a column short \u2014 the\n * same correction {@link renderOutdatedBanner} applies.\n */\nexport function renderWarningBanner(\n heading: string,\n messages: string[],\n color: BannerColor = \"red\",\n): string {\n if (messages.length === 0) {\n return \"\";\n }\n\n const accent = chalk[color].bold;\n\n const body: string[] = [];\n messages.forEach((message, index) => {\n const wrapped = wrapText(message, CONTENT_WIDTH - BULLET.length);\n wrapped.forEach((line, lineIndex) => {\n const prefix = lineIndex === 0 ? BULLET : CONTINUATION_INDENT;\n body.push(chalk[color](prefix + line));\n });\n // Blank spacer between messages for readability (never after the last).\n if (index < messages.length - 1) {\n body.push(\"\");\n }\n });\n\n const headingWidth = heading.length + (heading.includes(\"\u26A0\") ? 1 : 0);\n const width = Math.min(Math.max(headingWidth, CONTENT_WIDTH), MAX_WIDTH);\n const border = \"\u2500\".repeat(width);\n\n return [\n \"\",\n accent(`\u250C${border}\u2510`),\n accent(heading),\n accent(`\u2514${border}\u2518`),\n ...body,\n \"\",\n ].join(\"\\n\");\n}\n", "import process from \"node:process\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport ora from \"ora\";\nimport {\n FORMKIT_PACKAGE,\n formkitSubpathFor,\n formkitTagFor,\n isLegacyFormkitPackage,\n} from \"#static/formkitMigration.js\";\nimport type { Manifest } from \"#utils/cem.js\";\nimport {\n fetchManifest,\n type ManifestFetchResult,\n} from \"#utils/fetchManifest.js\";\nimport { formatDeclaration, toPackageName } from \"#utils/formatComponent.js\";\nimport { checkOutdated, renderOutdatedBanner } from \"#utils/outdated.js\";\n\n/** Options accepted by the `component` action. */\nexport interface ComponentOptions {\n tag?: string;\n json?: boolean;\n}\n\n/** How a component name resolved to a manifest source and its display metadata. */\ninterface ResolvedSource {\n /** Package to show in the `(pkg)` header and use for the outdated check. */\n headerPkg: string;\n /** Package the `Install:` snippet tells the user to `npm i`. */\n installPkg: string;\n /** Module specifier the `Install:` snippet tells the user to `import`. */\n importSpecifier: string;\n /** When set, keep only the declaration with this tag (monorepo aggregate CEM). */\n tagFilter?: string;\n /** True when a legacy standalone was redirected to the auro-formkit monorepo. */\n redirectedToFormkit: boolean;\n /** The resolved manifest fetch outcome. */\n result: ManifestFetchResult;\n}\n\n/**\n * Decide where a component's manifest comes from and how to present it.\n *\n * A legacy standalone form package (one `auro-formkit` now ships) is fetched from\n * the **monorepo** unless that standalone is *actually installed* in the current\n * project \u2014 matching what the user has, and steering everyone else onto formkit\n * rather than the deprecated standalone. An explicit `--tag` always pins the\n * standalone package (formkit versions its own line), so it bypasses the redirect.\n */\nasync function resolveSource(\n pkg: string,\n options: ComponentOptions,\n): Promise<ResolvedSource> {\n const plain = (result: ManifestFetchResult): ResolvedSource => ({\n headerPkg: pkg,\n installPkg: pkg,\n importSpecifier: pkg,\n redirectedToFormkit: false,\n result,\n });\n\n if (options.tag) {\n return plain(await fetchManifest(`${pkg}@${options.tag}`));\n }\n\n if (isLegacyFormkitPackage(pkg)) {\n // Prefer the legacy standalone only when it's actually installed here.\n const localLegacy = await fetchManifest(pkg, { allowNetwork: false });\n if (localLegacy.manifest) {\n return plain(localLegacy);\n }\n // Otherwise show the monorepo copy (local formkit first, then unpkg).\n return {\n headerPkg: FORMKIT_PACKAGE,\n installPkg: FORMKIT_PACKAGE,\n importSpecifier: formkitSubpathFor(pkg),\n tagFilter: formkitTagFor(pkg),\n redirectedToFormkit: true,\n result: await fetchManifest(FORMKIT_PACKAGE),\n };\n }\n\n return plain(await fetchManifest(pkg));\n}\n\n/**\n * Look up a single component's API from its Custom Elements Manifest and print\n * it (formatted, or raw JSON with `--json`). Exits non-zero when the manifest\n * can't be resolved or documents no registered element.\n */\nexport async function runComponent(\n name: string,\n options: ComponentOptions,\n): Promise<void> {\n const pkg = toPackageName(name);\n const spinner = ora(`Fetching ${pkg}...`).start();\n\n const source = await resolveSource(pkg, options);\n const { result } = source;\n const target = result.target;\n if (!result.manifest) {\n spinner.fail(\n result.transient\n ? `Failed to fetch ${target}: ${result.reason}.`\n : `No custom-elements.json published for ${target}. It may not exist or may not publish a manifest yet.`,\n );\n process.exit(1);\n }\n const manifest = result.manifest as Manifest;\n\n // Only real registered elements \u2014 a declaration can be customElement: true\n // yet be an internal base class with no tagName. When the source is the\n // monorepo aggregate CEM, narrow to the one requested tag so a lookup for\n // `input` shows `auro-input` alone, not every formkit element.\n const declarations = (manifest.modules ?? [])\n .flatMap((module) => module.declarations ?? [])\n .filter((decl) => decl.customElement && decl.tagName)\n .filter((decl) => !source.tagFilter || decl.tagName === source.tagFilter);\n\n if (declarations.length === 0) {\n spinner.fail(\n source.tagFilter\n ? `No <${source.tagFilter}> element found in ${target}.`\n : `No registered custom elements found for ${target}.`,\n );\n process.exit(1);\n }\n\n const origin =\n result.source === \"local\"\n ? ` (local${result.version ? ` v${result.version}` : \"\"})`\n : \" (unpkg)\";\n spinner.succeed(\n `${target} \u2014 ${declarations.length} custom element${declarations.length === 1 ? \"\" : \"s\"}${origin}`,\n );\n\n // A legacy standalone the user hasn't installed was redirected to the monorepo;\n // tell them why the package/import shown differs from what they typed. On stderr\n // (not Logger, which prints to stdout) so `--json` output stays machine-parseable.\n if (source.redirectedToFormkit) {\n console.error(\n `\u2139 ${source.tagFilter} now ships in ${FORMKIT_PACKAGE} \u2014 showing the monorepo version (the legacy standalone isn't installed).`,\n );\n }\n\n // When the manifest came from a local install, check whether that install is\n // behind the latest published release and warn \u2014 mirroring `auro context`.\n // Only meaningful for a local read (unpkg already serves latest, and an\n // explicit --tag forces a network fetch, so source is never \"local\" then).\n let outdatedBanner: string | null = null;\n if (result.source === \"local\" && result.version) {\n const check = ora(\"Checking for a newer release...\").start();\n const outdated = await checkOutdated(\n new Map([[source.headerPkg, result.version]]),\n );\n check.stop();\n if (outdated.length > 0) {\n outdatedBanner = renderOutdatedBanner(outdated);\n }\n }\n\n if (options.json) {\n process.stdout.write(`${JSON.stringify(declarations, null, 2)}\\n`);\n // stderr \u2014 keep JSON on stdout machine-parseable.\n if (outdatedBanner) {\n console.error(outdatedBanner);\n }\n return;\n }\n\n process.stdout.write(\n `\\n${declarations\n .map((decl) =>\n formatDeclaration(source.headerPkg, decl, {\n installPkg: source.installPkg,\n importSpecifier: source.importSpecifier,\n }),\n )\n .join(\"\\n\\n---\\n\\n\")}\\n`,\n );\n Logger.info(\"\\nFull docs: https://auro.alaskaair.com\");\n // Warn last so it's the final thing on screen, not scrolled off by the API dump.\n if (outdatedBanner) {\n console.error(outdatedBanner);\n }\n}\n\nexport default program\n .command(\"component <name>\")\n .description(\n \"Look up an Auro component's API (attributes, properties, slots, events, CSS parts) from its published Custom Elements Manifest\",\n )\n .option(\n \"-t, --tag <version>\",\n \"npm dist-tag or version to look up (default: latest); pins the standalone package for a legacy form component\",\n )\n .option(\"--json\", \"Output the raw manifest declaration(s) as JSON\", false)\n .action(runComponent);\n", "import { program } from \"commander\";\nimport { api, cem, docs, serve, watchDocs } from \"#scripts/docs/index.ts\";\nimport { withServerOptions } from \"#commands/_sharedOptions.js\";\n\nlet docsCommand = program\n .command(\"docs\")\n .description(\"Generate API documentation\")\n .option(\"-c, --cem\", \"Generate Custom Elements Manifest (CEM) file\", false)\n .option(\"-a, --api\", \"Creates api md file from CEM\", false)\n .option(\"-w, --watch\", \"Watch for changes and rebuild docs\", false)\n .option(\"-r, --readme-template <url>\", \"URL to the README template file\")\n .option(\"--skip-readme\", \"Skip README.md processing\", false)\n \n docsCommand = withServerOptions(docsCommand);\n\n export default docsCommand.action(async (options) => {\n\n if (options.cem) {\n await cem();\n }\n\n if (options.api) {\n await api();\n }\n\n await docs(options);\n\n if( options.serve ) {\n await serve(options);\n }\n\n if (options.watch) {\n await watchDocs(options);\n }\n\n });\n", "import { program } from \"commander\";\nimport { createADOItem } from \"#scripts/ado/index.ts\";\n\nexport const adoCommand = program\n .command(\"ado\")\n .description(\"Generate ADO item from GitHub issue\")\n .option(\"-g, --gh-issue <issue>\", \"What GitHub issue to use\")\n .action(async (options) => {\n\n if (options.ghIssue) {\n await createADOItem(options.ghIssue);\n }\n });\n", "import { Octokit } from \"@octokit/rest\";\nimport * as azdev from \"azure-devops-node-api\";\nimport ora from \"ora\";\nimport type { WorkItem } from \"azure-devops-node-api/interfaces/WorkItemTrackingInterfaces.js\";\n\ninterface GitHubIssue {\n title: string;\n body: string | null;\n html_url: string;\n number: number;\n repository: {\n owner: { login: string };\n name: string;\n };\n}\n\n/**\n * Fetches GitHub issue details\n * @param issueUrl - Full GitHub issue URL or in format \"owner/repo#number\"\n * @returns GitHub issue details\n */\nconst fetchGitHubIssue = async (issueUrl: string): Promise<GitHubIssue> => {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n throw new Error(\"GH_TOKEN environment variable is required\");\n }\n\n const octokit = new Octokit({\n auth: ghToken,\n });\n\n let owner: string;\n let repo: string;\n let issueNumberStr: string;\n\n // Parse the issue URL or reference\n if (issueUrl.includes('github.com')) {\n // Full URL format: https://github.com/owner/repo/issues/123\n const urlMatch = issueUrl.match(/github\\.com\\/([^\\/]+)\\/([^\\/]+)\\/issues\\/(\\d+)/);\n if (!urlMatch) {\n throw new Error(\"Invalid GitHub issue URL format\");\n }\n [, owner, repo, issueNumberStr] = urlMatch;\n } else if (issueUrl.includes('#')) {\n // Short format: owner/repo#123\n const shortMatch = issueUrl.match(/([^\\/]+)\\/([^#]+)#(\\d+)/);\n if (!shortMatch) {\n throw new Error(\"Invalid GitHub issue reference format\");\n }\n [, owner, repo, issueNumberStr] = shortMatch;\n } else {\n throw new Error(\"Issue must be provided as full URL or in format 'owner/repo#number'\");\n }\n\n const issueNumber = Number.parseInt(issueNumberStr, 10);\n\n try {\n const { data: issue } = await octokit.rest.issues.get({\n owner,\n repo,\n issue_number: issueNumber,\n });\n\n return {\n title: issue.title,\n body: issue.body ?? null,\n html_url: issue.html_url,\n number: issue.number,\n repository: {\n owner: { login: owner },\n name: repo,\n },\n };\n } catch (error) {\n throw new Error(`Failed to fetch GitHub issue: ${error}`);\n }\n};\n\n/**\n * Checks if GitHub issue already has an ADO work item linked\n * @param issue - GitHub issue details\n * @returns ADO URL if found, null otherwise\n */\nconst getExistingADOLink = async (issue: GitHubIssue): Promise<string | null> => {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n return null;\n }\n\n const octokit = new Octokit({\n auth: ghToken,\n });\n\n try {\n // Get the ADO field value from the GitHub project\n const query = `\n query($owner: String!, $repo: String!, $issueNumber: Int!) {\n repository(owner: $owner, name: $repo) {\n issue(number: $issueNumber) {\n projectItems(first: 10) {\n nodes {\n project {\n number\n }\n fieldValues(first: 20) {\n nodes {\n ... on ProjectV2ItemFieldTextValue {\n text\n field {\n ... on ProjectV2Field {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n `;\n\n const variables = {\n owner: issue.repository.owner.login,\n repo: issue.repository.name,\n issueNumber: issue.number,\n };\n\n const response = await octokit.graphql(query, variables) as {\n repository: {\n issue: {\n projectItems: {\n nodes: Array<{\n project: { number: number };\n fieldValues: {\n nodes: Array<{\n text?: string;\n field?: { name?: string };\n }>;\n };\n }>;\n };\n };\n };\n };\n\n // Look for project #19 with ado field\n const project19Item = response.repository.issue.projectItems.nodes.find(\n item => item.project.number === 19\n );\n\n if (project19Item) {\n const adoFieldValue = project19Item.fieldValues.nodes.find(\n fieldValue => fieldValue.field?.name?.toLowerCase() === 'ado' && fieldValue.text?.trim()\n );\n\n if (adoFieldValue?.text?.trim()) {\n return adoFieldValue.text.trim();\n }\n }\n\n return null;\n } catch (error) {\n console.error(`Failed to check existing ADO link: ${error}`);\n return null;\n }\n};\n\n/**\n * Adds GitHub issue to project #19 and updates the \"ado\" field\n * @param issue - GitHub issue details\n * @param adoWorkItemUrl - ADO work item URL\n */\nconst updateGitHubProject = async (\n issue: GitHubIssue,\n adoWorkItemUrl: string\n): Promise<void> => {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n throw new Error(\"GH_TOKEN environment variable is required\");\n }\n\n const octokit = new Octokit({\n auth: ghToken,\n });\n\n const projectNumber = 19; // Alaska Airlines project #19\n\n try {\n // Get project and issue info in one query\n const query = `\n query($org: String!, $projectNumber: Int!, $owner: String!, $repo: String!, $issueNumber: Int!) {\n organization(login: $org) {\n projectV2(number: $projectNumber) {\n id\n fields(first: 20) {\n nodes {\n ... on ProjectV2Field {\n id\n name\n }\n ... on ProjectV2SingleSelectField {\n id\n name\n }\n ... on ProjectV2IterationField {\n id\n name\n }\n }\n }\n }\n }\n repository(owner: $owner, name: $repo) {\n issue(number: $issueNumber) {\n id\n projectItems(first: 10) {\n nodes {\n id\n project {\n number\n }\n }\n }\n }\n }\n }\n `;\n\n const variables = {\n org: \"AlaskaAirlines\",\n projectNumber,\n owner: issue.repository.owner.login,\n repo: issue.repository.name,\n issueNumber: issue.number,\n };\n\n const response = await octokit.graphql(query, variables) as {\n organization: {\n projectV2: {\n id: string;\n fields: {\n nodes: Array<{ id: string; name: string }>;\n };\n };\n };\n repository: {\n issue: {\n id: string;\n projectItems: {\n nodes: Array<{\n id: string;\n project: { number: number };\n }>;\n };\n };\n };\n };\n\n const projectId = response.organization.projectV2.id;\n const issueId = response.repository.issue.id;\n const adoField = response.organization.projectV2.fields.nodes.find(\n field => field.name?.toLowerCase() === 'ado'\n );\n\n // Check if issue is already in the project\n let projectItemId = response.repository.issue.projectItems.nodes.find(\n item => item.project.number === projectNumber\n )?.id;\n\n // Add to project if not already there\n if (!projectItemId) {\n const addMutation = `\n mutation($projectId: ID!, $contentId: ID!) {\n addProjectV2ItemById(\n input: {\n projectId: $projectId\n contentId: $contentId\n }\n ) {\n item {\n id\n }\n }\n }\n `;\n\n const addResponse = await octokit.graphql(addMutation, {\n projectId,\n contentId: issueId,\n }) as {\n addProjectV2ItemById: {\n item: { id: string };\n };\n };\n\n projectItemId = addResponse.addProjectV2ItemById.item.id;\n // Issue added to project (handled by spinner in main function)\n }\n\n // Update the ado field if it exists\n if (adoField && projectItemId) {\n const updateMutation = `\n mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $value: String!) {\n updateProjectV2ItemFieldValue(\n input: {\n projectId: $projectId\n itemId: $itemId\n fieldId: $fieldId\n value: {\n text: $value\n }\n }\n ) {\n projectV2Item {\n id\n }\n }\n }\n `;\n\n await octokit.graphql(updateMutation, {\n projectId,\n itemId: projectItemId,\n fieldId: adoField.id,\n value: adoWorkItemUrl,\n });\n\n // Field updated (handled by spinner in main function)\n } else if (!adoField) {\n throw new Error(\"No 'ado' field found in GitHub project\");\n }\n\n } catch (error) {\n console.error(`Failed to update GitHub project: ${error}`);\n // Don't throw - we don't want to fail the entire process\n }\n};\n\n/**\n * Creates a user story work item in Azure DevOps\n * @param issue - GitHub issue details\n * @returns Created work item\n */\nconst createADOWorkItem = async (issue: GitHubIssue): Promise<WorkItem> => {\n const adoToken = process.env.ADO_TOKEN;\n if (!adoToken) {\n throw new Error(\"ADO_TOKEN environment variable is required\");\n }\n\n // ADO organization and project details\n const orgUrl = \"https://dev.azure.com/itsals\";\n const projectName = \"E_Retain_Content\";\n const areaPath = \"E_Retain_Content\\\\Auro Design System\";\n\n // Create connection to Azure DevOps\n const authHandler = azdev.getPersonalAccessTokenHandler(adoToken);\n const connection = new azdev.WebApi(orgUrl, authHandler);\n const workItemTrackingApi = await connection.getWorkItemTrackingApi();\n\n try {\n // Prepare work item data - omitting iteration path to use project default\n const workItemData = [\n {\n op: \"add\",\n path: \"/fields/System.Title\",\n value: issue.title,\n },\n {\n op: \"add\",\n path: \"/fields/System.Description\",\n value: `GitHub Issue: <a href=\"${issue.html_url}\">${issue.html_url}</a>`,\n },\n {\n op: \"add\",\n path: \"/fields/System.AreaPath\",\n value: areaPath,\n },\n ];\n\n return await workItemTrackingApi.createWorkItem(\n null,\n workItemData,\n projectName,\n \"User Story\"\n );\n } catch (error) {\n throw new Error(`Failed to create ADO work item: ${error}`);\n }\n};\n\nexport const createADOItem = async (ghIssue: string) => {\n const spinner = ora(`Processing GitHub issue: ${ghIssue}`).start();\n \n try {\n // Validate environment variables\n if (!process.env.GH_TOKEN) {\n throw new Error(\"GH_TOKEN environment variable is required\");\n }\n if (!process.env.ADO_TOKEN) {\n throw new Error(\"ADO_TOKEN environment variable is required\");\n }\n\n spinner.text = \"Fetching GitHub issue details...\";\n const issue = await fetchGitHubIssue(ghIssue);\n spinner.succeed(`Found issue: \"${issue.title}\"`);\n\n // Check if issue already has an ADO work item linked in the project\n const checkSpinner = ora(\"Checking for existing ADO work item...\").start();\n const existingADOLink = await getExistingADOLink(issue);\n \n if (existingADOLink) {\n checkSpinner.succeed(\"ADO work item already exists for this issue!\");\n console.log(`${existingADOLink}`);\n return; // Exit early - no need to create a new work item\n }\n \n checkSpinner.succeed(\"No existing ADO work item found\");\n\n const createSpinner = ora(\"Creating new ADO work item...\").start();\n const workItem = await createADOWorkItem(issue);\n createSpinner.succeed(`Successfully created ADO work item #${workItem.id}`);\n \n console.log(`Work item: ${workItem._links?.html?.href || 'N/A'}`);\n\n // Add to GitHub project and update the ado field with the new work item\n if (workItem._links?.html?.href) {\n const projectSpinner = ora(\"Adding to GitHub project and updating ADO field...\").start();\n await updateGitHubProject(issue, workItem._links.html.href);\n projectSpinner.succeed(\"Updated GitHub project with ADO link\");\n } \n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : error}`);\n process.exit(1);\n }\n}", "import { program } from \"commander\";\nimport { RCWorkflow } from \"#scripts/rc-workflow/index.ts\";\n\n\nexport default program\n .command(\"rc-workflow\")\n .description(\"Generate RC issue and pull request\")\n .action(async () => {\n\n const workflow = await RCWorkflow.create();\n await workflow.createReleaseCandidate();\n});\n\n", "import { Git } from \"#utils/gitUtils.ts\";\nimport { Octokit } from \"@octokit/rest\";\nimport { generateReleaseNotes, filterCommitList } from \"#scripts/check-commits/commit-analyzer.ts\";\nimport { simpleGit } from \"simple-git\";\n\n// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo\nconst LABEL = \"Release Candidate\";\nconst RC_SOURCE_BRANCH = \"dev\";\nconst RC_BASE_BRANCH = \"main\";\n\ntype RcIssue = { number: number; title?: string; html_url?: string };\ntype LinkedPr = { state: \"open\" | \"closed\"; html_url?: string; multipleOpen?: boolean; number?: number };\n\nexport class RCWorkflow {\n private repoInfo: { owner: string; repo: string };\n private octokit: Octokit;\n private filteredCommits: Array<{\n type: string;\n hash: string;\n date: string;\n subject: string;\n body: string;\n message: string;\n author_name: string;\n }> | null = null;\n\n constructor(owner: string, repo: string, octokit: Octokit) {\n this.repoInfo = { owner, repo };\n this.octokit = octokit;\n }\n\n /**\n * Static factory method to create an instance of RCWorkflow\n * @returns {Promise<RCWorkflow>} A promise that resolves to an instance of RCWorkflow\n */\n static async create(): Promise<RCWorkflow> {\n const token = process.env.GITHUB_TOKEN;\n if (!token) {\n throw new Error(\"GITHUB_TOKEN is required to run RC workflow.\");\n }\n\n const info = await Git.getRepoOwnerAndName();\n const octokit = new Octokit({ auth: token });\n \n if (!info) {\n throw new Error(\"Failed to retrieve repository information. Ensure you're in a valid git repository.\");\n }\n\n const triggerBranch = await RCWorkflow.getTriggerBranchName();\n if (triggerBranch && triggerBranch !== RC_SOURCE_BRANCH) {\n console.log(`Switching from ${triggerBranch} to ${RC_SOURCE_BRANCH} branch...`);\n const git = simpleGit();\n await git.checkout(RC_SOURCE_BRANCH);\n }\n \n return new RCWorkflow(info.owner, info.repo, octokit);\n }\n\n // Getter for owner\n get owner(): string {\n return this.repoInfo.owner;\n }\n\n // Getter for repo name \n get repo(): string {\n return this.repoInfo.repo;\n }\n\n // Getter for full repo info\n get repoData(): { owner: string; repo: string } {\n return { ...this.repoInfo };\n }\n\n async createReleaseCandidate(): Promise<void> {\n const hasCommitsReady = await this.hasCommitsReadyInDev();\n if (!hasCommitsReady) {\n console.log(\"No filtered commits found. Continuing to update RC issue/branch/PR.\");\n }\n\n let rcIssue: RcIssue | null = await this.getLatestOpenRcIssue();\n let linkedPr: LinkedPr | null = rcIssue ? await this.getLinkedPrByHead(rcIssue.number) : null;\n\n if (linkedPr?.multipleOpen) {\n throw new Error(\"Multiple open RC PRs found for the same rc/<issueNumber> branch.\");\n }\n\n if (linkedPr?.state === \"closed\") {\n console.log(\"Linked RC PR is closed. Creating a new RC issue and PR.\");\n rcIssue = await this.createRcIssue();\n linkedPr = null;\n }\n\n if (!rcIssue) {\n rcIssue = await this.createRcIssue();\n } else {\n await this.updateRcIssue(rcIssue.number);\n }\n\n if (!rcIssue) {\n throw new Error(\"Failed to resolve RC issue.\");\n }\n\n await this.createOrUpdateRcBranch(rcIssue.number);\n\n if (!linkedPr) {\n linkedPr = await this.createRcPr(rcIssue.number);\n } else {\n await this.updateRcPr(rcIssue.number, linkedPr.number!);\n }\n }\n\n private async getFilteredCommits() {\n if (this.filteredCommits === null) {\n const commitList = await Git.getCommitMessages(RC_SOURCE_BRANCH);\n this.filteredCommits = filterCommitList(commitList);\n }\n return this.filteredCommits;\n }\n\n async hasCommitsReadyInDev(): Promise<boolean> {\n const filteredCommits = await this.getFilteredCommits();\n return filteredCommits.length > 0;\n }\n\n private async getLatestOpenRcIssue(): Promise<RcIssue | null> {\n const { data } = await this.octokit.rest.issues.listForRepo({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n labels: LABEL,\n state: \"open\",\n sort: \"updated\",\n direction: \"desc\",\n per_page: 30,\n });\n\n const openIssues = data.filter(issue => !issue.pull_request);\n\n if (openIssues.length === 0) {\n console.log(`No open Release Candidate issues found in ${this.repoInfo.repo}`);\n return null;\n }\n\n const latestIssue = openIssues[0];\n console.log(`Using latest open Release Candidate issue: #${latestIssue.number}`);\n return { number: latestIssue.number, title: latestIssue.title || \"\" };\n }\n\n private async updateRcIssue(issueNumber: number): Promise<void> {\n const releaseNotes = await this.getReleaseNotes();\n const title = `RC ${this.getCurrentDate()}`;\n\n await this.octokit.rest.issues.update({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n issue_number: issueNumber,\n title,\n body: releaseNotes,\n });\n }\n\n private async createRcIssue(): Promise<RcIssue> {\n const releaseNotes = await this.getReleaseNotes();\n\n const { data } = await this.octokit.rest.issues.create({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n title: `RC ${this.getCurrentDate()}`,\n labels: [LABEL],\n body: releaseNotes,\n });\n\n console.log(`Created Release Candidate issue: #${data.number} (${data.html_url})`);\n return { number: data.number, html_url: data.html_url };\n }\n\n private async createOrUpdateRcBranch(issueNumber: number): Promise<void> {\n const branchRef = `heads/rc/${issueNumber}`;\n const branchName = `rc/${issueNumber}`;\n\n const { data: devBranch } = await this.octokit.rest.repos.getBranch({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n branch: RC_SOURCE_BRANCH,\n });\n\n // Check if branch exists by listing matching refs\n const { data: matchingRefs } = await this.octokit.rest.git.listMatchingRefs({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: branchRef,\n });\n\n const branchExists = matchingRefs.length > 0;\n\n try {\n if (branchExists) {\n console.log(`Updating existing RC branch: ${branchName}`);\n await this.octokit.rest.git.updateRef({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: branchRef,\n sha: devBranch.commit.sha,\n force: true,\n });\n } else {\n console.log(`Creating new RC branch: ${branchName}`);\n await this.octokit.rest.git.createRef({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: `refs/${branchRef}`,\n sha: devBranch.commit.sha,\n });\n }\n } catch (error: unknown) {\n throw new Error(`Failed to create or update ${branchName} branch: ${error}`);\n }\n }\n\n private async getLinkedPrByHead(issueNumber: number): Promise<LinkedPr | null> {\n const head = `${this.repoInfo.owner}:rc/${issueNumber}`;\n const { data } = await this.octokit.rest.pulls.list({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n state: \"all\",\n head,\n per_page: 30,\n });\n\n const openPrs = data.filter(pr => pr.state === \"open\");\n if (openPrs.length > 1) {\n return { state: \"open\", multipleOpen: true };\n }\n\n if (openPrs.length === 1) {\n return { state: \"open\", html_url: openPrs[0].html_url, number: openPrs[0].number };\n }\n\n const closedPrs = data.filter(pr => pr.state === \"closed\");\n if (closedPrs.length > 0) {\n return { state: \"closed\", html_url: closedPrs[0].html_url, number: closedPrs[0].number };\n }\n\n return null;\n }\n\n private async fetchPrTemplate(issueNumber: number): Promise<string> {\n try {\n // Try to fetch the PR template from the current repo\n const { data } = await this.octokit.rest.repos.getContent({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n path: \".github/PULL_REQUEST_TEMPLATE.md\",\n });\n \n // Check if data is a file (not a directory or submodule)\n if (\"content\" in data && data.type === \"file\") {\n // Decode the base64 content\n let template = Buffer.from(data.content, \"base64\").toString(\"utf-8\");\n \n // Replace the summary placeholder with RC-specific text\n template = template.replace(\n \"Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.\",\n `Release candidate pull request. See issue #${issueNumber} for details.`\n );\n \n // Replace all <details> with <details open>\n template = template.replace(/<details>/g, \"<details open>\");\n \n return template;\n }\n } catch (error: unknown) {\n // Template doesn't exist or couldn't be fetched, use fallback\n if (error && typeof error === \"object\" && \"status\" in error && (error as { status?: number }).status === 404) {\n console.log(\"No PR template found in repo, using default message.\");\n } else {\n console.warn(\"Failed to fetch PR template:\", error);\n }\n }\n \n // Fallback if template doesn't exist or fetch fails\n return `Release candidate pull request. See issue #${issueNumber} for details.`;\n }\n\n private async createRcPr(issueNumber: number): Promise<LinkedPr> {\n try {\n const prBody = await this.fetchPrTemplate(issueNumber);\n\n const { data } = await this.octokit.request(`POST /repos/${this.repoInfo.owner}/${this.repoInfo.repo}/pulls`, {\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n title: `RC #${issueNumber}`,\n body: prBody,\n head: `rc/${issueNumber}`,\n base: RC_BASE_BRANCH,\n headers: {\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n\n console.log(`Created Release Candidate pull request: #${data.number} (${data.html_url})`);\n return { state: \"open\", html_url: data.html_url, number: data.number };\n } catch (error: unknown) {\n console.error(\"Failed to create RC PR:\", error);\n throw error;\n }\n }\n\n private async updateRcPr(issueNumber: number, prNumber: number): Promise<void> {\n try {\n const prBody = await this.fetchPrTemplate(issueNumber);\n\n await this.octokit.rest.pulls.update({\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n pull_number: prNumber,\n body: prBody,\n });\n\n console.log(`Updated Release Candidate pull request: #${prNumber}`);\n } catch (error: unknown) {\n console.error(\"Failed to update RC PR:\", error);\n throw error;\n }\n }\n\n async getReleaseNotes(): Promise<string> {\n const filteredCommits = await this.getFilteredCommits();\n return generateReleaseNotes(filteredCommits, false);\n }\n\n private static async getTriggerBranchName(): Promise<string | null> {\n if (process.env.GITHUB_REF_NAME) {\n return process.env.GITHUB_REF_NAME;\n }\n\n if (process.env.GITHUB_REF?.startsWith(\"refs/heads/\")) {\n return process.env.GITHUB_REF.replace(\"refs/heads/\", \"\");\n }\n\n return Git.getCurrentBranchName();\n }\n\n private getCurrentDate(): string {\n return new Date().toISOString().split(\"T\")[0];\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,OAAS,WAAAA,OAAe,YCAxB,OAAOC,OAAY,SACnB,OAAS,QAAAC,OAAY,kBAErB,IAAOC,GAAQ,IACND,GAAKD,GAAO,SAAS,UAAU,CAAC,ECHzC,OAAOG,OAAQ,UACf,OAAOC,OAAU,YACjB,OAAS,iBAAAC,OAAqB,WAM9B,SAASC,GAASC,EAAS,CACrB,QAAQ,IAAI,OACd,QAAQ,IAAI,WAAWA,CAAO,EAAE,CAEpC,CAMe,SAARC,IAAqC,CAC1C,GAAI,CAEF,IAAMC,EAAaJ,GAAc,YAAY,GAAG,EAC1CK,EAAYN,G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CACL,YAAa,6BACf,EACA,CACE,IAAK,aACL,IAAK,+BACL,YAAa,8DACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,uBACf,EACA,CACE,IAAK,kBACL,IAAK,oCACL,YAAa,2BACf,EACA,CACE,IAAK,iBACL,IAAK,mCACL,YAAa,sBACf,EACA,CACE,IAAK,aACL,IAAK,+BACL,YAAa,uBACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,+BACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,6DACf,EACA,CACE,IAAK,YACL,IAAK,8BACL,YAAa,wBACf,EACA,CACE,IAAK,gBACL,IAAK,kCACL,YAAa,kCACf,EACA,CACE,IAAK,gBACL,IAAK,kCACL,YAAa,oCACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,8CACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,gDACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,qDACf,EACA,CACE,IAAK,kBACL,IAAK,oCACL,YAAa,mCACf,EACA,CACE,IAAK,aACL,IAAK,iCACL,YAAa,kBACf,EACA,CACE,IAAK,cACL,IAAK,iCACL,YAAa,iBACf,EACA,CACE,IAAK,kBACL,IAAK,iCACL,YAAa,mBACf,EACA,CACE,IAAK,gBACL,IAAK,iCACL,YAAa,sBACf,EACA,CACE,IAAK,gBACL,IAAK,iCACL,YAAa,gBACf,EACA,CACE,IAAK,aACL,IAAK,iCACL,YAAa,oBACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,sBACf,EACA,CACE,IAAK,iBACL,IAAK,mCACL,YAAa,wBACf,EACA,CACE,IAAK,YACL,IAAK,8BACL,YAAa,sDACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,iBACf,EACA,CACE,IAAK,cACL,IAAK,gCACL,YAAa,4BACf,EACA,CACE,IAAK,WACL,IAAK,6BACL,YAAa,2DACf,EACA,CACE,IAAK,YACL,IAAK,8BACL,YAAa,kDACf,EAC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pE,OAASP,EAAgB,CACvB,cAAQ,MAAM,0BAA2BA,CAAK,EACxCA,CACR,CACF,CAEA,MAAM,iBAAmC,CACvC,IAAMQ,EAAkB,MAAM,KAAK,mBAAmB,EACtD,OAAOC,GAAqBD,EAAiB,EAAK,CACpD,CAEA,aAAqB,sBAA+C,CAClE,OAAI,QAAQ,IAAI,gBACP,QAAQ,IAAI,gBAGjB,QAAQ,IAAI,YAAY,WAAW,aAAa,EAC3C,QAAQ,IAAI,WAAW,QAAQ,cAAe,EAAE,EAGlD3B,EAAI,qBAAqB,CAClC,CAEQ,gBAAyB,CAC/B,OAAO,IAAI,KAAK,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC,CAC9C,CACF,EDrVA,IAAO6B,GAAQC,GACZ,QAAQ,aAAa,EACrB,YAAY,oCAAoC,EAChD,OAAO,SAAY,CAGpB,MADiB,MAAMC,GAAW,OAAO,GAC1B,uBAAuB,CACxC,CAAC,E5EYDC,GACG,KAAK,MAAM,EACX,QAAQC,GAAkB,CAAC,EAC3B,YAAY,8CAA8C,EAE7DD,GAAQ,YAAY,YAAaE,GAAW,CAAC,EAE7CF,GAAQ,MAAM",
|
|
6
|
+
"names": ["program", "figlet", "mind", "auroSplash_default", "fs", "path", "fileURLToPath", "debugLog", "message", "getPackageVersion", "__filename", "__dirname", "packagePath", "error", "program", "ora", "withBuildOptions", "command", "withServerOptions", "terser", "watch", "existsSync", "readFileSync", "rmSync", "writeFileSync", "basename", "dirname", "join", "resolve", "pathToFileURL", "glob", "ora", "rollup", "sass", "ora", "spawn", "ora", "shell", "command", "_args", "commandString", "spinner", "finalCommand", "finalArgs", "parts", "isWatchMode", "child", "commandOutput", "data", "output", "resolve", "reject", "code", "fs", "path", "markdownTable", "Docs", "_Docs", "options", "outDir", "outFile", "manifestPath", "getElements", "renderAllElements", "manifestContent", "error", "elements", "docsDir", "apiMarkdown", "apiFilename", "wcaModules", "els", "module", "dec", "a", "b", "element", "includeTitle", "sections", "renderTable", "renderPropertiesAttributesTable", "renderParameters", "getType", "propertiesTable", "methodsTable", "m", "eventsTable", "slotsTable", "cssPartsTable", "cssPropertiesTable", "escapeMarkdown", "properties", "attributes", "mergedData", "processedNames", "prop", "propType", "displayType", "attr", "headers", "rows", "item", "defaultDoubleSanitized", "defaultWrapped", "parameters", "param", "paramType", "description", "name", "data", "get", "capitalize", "filteredData", "p", "value", "table", "text", "obj", "type", "normalizeType", "t", "ref", "result", "pathInput", "fallback", "parts", "current", "s", "str", "os", "path", "process", "getAuroHomeDir", "homeDir", "withHomeDir", "args", "fromCliRoot", "relativePath", "cliScript", "dirname", "configPath", "file", "copyFileSync", "existsSync", "mkdirSync", "join", "resolve", "copyReadmeToDemo", "cwd", "readmeSrc", "readmeDest", "demoDir", "ora", "watchers", "registerWatcher", "watcher", "handlerInstalled", "installShutdownHandler", "closeSpinner", "Logger", "generateReadmeUrl", "processContentForFile", "templateFiller", "fs", "readFileSync", "existsSync", "path", "PAGE_TEMPLATE_PATH", "defaultDocsProcessorConfig", "pathFromCwd", "pathLike", "findMonorepoRoot", "startDir", "dir", "pkgPath", "parent", "fileConfigs", "config", "skipReadme", "configs", "inputConfig", "fileExists", "pageTemplateFullPath", "pageObjects", "file", "processDocFiles", "fileConfigsList", "monorepoName", "rootPkgPath", "extraVars", "fileConfig", "postProcessMarkdownFile", "err", "outputPath", "outputDir", "outputContents", "emptyTagPattern", "match", "modified", "demoDir", "fullMatch", "type", "srcPath", "resolvedPath", "fallbackPath", "actualPath", "fileContent", "replacement", "ext", "escaped", "fencePattern", "convertedContents", "_match", "lang", "code", "language", "open", "content", "close", "lines", "nonEmpty", "l", "minIndent", "m", "processed", "outputLines", "insidePre", "i", "runDefaultDocsBuild", "options", "readmeTemplate", "isLocalPath", "pathToFile", "existsSync", "readFileSync", "builtinModules", "resolve", "startDevServer", "hmrPlugin", "esbuild", "ora", "MODULE_DIRS", "WDS_OUTSIDE_ROOT_RE", "nodeModulesCssPlugin", "context", "urlPath", "cwd", "dir", "MODULE_DIRS", "candidate", "resolve", "existsSync", "readFileSync", "resolveWdsPath", "rootDir", "match", "cjsToEsmPlugin", "CJS_PATTERN", "cache", "resolvedRootDir", "config", "filePath", "output", "builtinModules", "error", "DEFAULT_CONFIG", "startDevelopmentServer", "options", "serverSpinner", "ora", "serverConfig", "next", "hmrPlugin", "server", "startDevServer", "cem", "cemSpinner", "ora", "shell", "configPath", "error", "errorMessage", "api", "docsSpinner", "Docs", "docs", "options", "runDefaultDocsBuild", "copyReadmeToDemo", "compileDemoScss", "buildDemoBundle", "serve", "startDevelopmentServer", "watchDocs", "chokidar", "watchPaths", "ignored", "watcher", "watchSpinner", "rebuildTimer", "rebuilding", "pendingRebuild", "rebuild", "triggeredBy", "spinner", "_event", "filePath", "registerWatcher", "installShutdownHandler", "analyzeComponents", "cem", "api", "basename", "join", "resolve", "commonjs", "nodeResolve", "glob", "litScss", "path", "glob", "watchGlobs", "globs", "items", "item", "filename", "error", "DEFAULTS", "getPluginsConfig", "modulePaths", "options", "watchPatterns", "dedupe", "dev", "allModulePaths", "cwd", "absoluteModulePaths", "MODULE_DIRS", "dir", "resolve", "nodeResolve", "commonjs", "litScss", "join", "watchGlobs", "getMainBundleConfig", "watch", "input", "outputDir", "format", "chunk", "getExternalConfig", "getWatcherConfig", "getDemoConfig", "globPattern", "ignorePattern", "entries", "glob", "plugins", "watcher", "file", "basename", "warning", "defaultHandler", "watchOptions", "additional", "cleanupDist", "distPath", "join", "spinner", "ora", "rmSync", "error", "runBuildStep", "taskName", "taskFn", "successMsg", "failMsg", "result", "buildCombinedBundle", "mainConfig", "demoConfigs", "runBuildStep", "mainBundle", "rollup", "cfg", "bundle", "generateDocs", "options", "sourceFiles", "outFile", "skipDocs", "skipSpinner", "ora", "analyzeComponents", "runDefaultDocsBuild", "copyReadmeToDemo", "createNodeModulesImporter", "cwd", "tryResolve", "filePath", "join", "dirname", "basename", "c", "existsSync", "findInModuleDirs", "pkgPath", "dir", "MODULE_DIRS", "found", "resolve", "exportResolved", "resolveViaExports", "pkgName", "subpath", "parts", "slashIdx", "pkgJsonPath", "exports", "readFileSync", "mapped", "target", "resolved", "url", "lastIdx", "pathToFileURL", "compileDemoScss", "demoDir", "scssFiles", "glob", "importer", "loadPaths", "scssFile", "result", "cssFile", "writeFileSync", "buildDemoBundle", "configs", "getDemoConfig", "path", "ora", "buildInProgress", "builds", "MIN_BUILD_INTERVAL", "sourceEventPaths", "OUTPUT_PATHS", "isOutputFile", "filePath", "normalizedPath", "path", "outputPath", "error", "runBuildTask", "taskName", "taskFn", "task", "handleWatcherEvents", "watcher", "options", "onInitialBuildComplete", "isInitialBuild", "buildTasksResults", "scheduledTasksTimer", "bundleSpinner", "watchSpinner", "ora", "buildTasks", "sourceFiles", "outFile", "skipDocs", "skipSpinner", "analyzeSpinner", "analyzeComponents", "docsSpinner", "generateDocs", "compileDemoScss", "checkInitialBuildComplete", "schedulePostBundleTasks", "delay", "event", "inputs", "input", "setupWatchModeListeners", "scssWatcher", "registerWatcher", "installShutdownHandler", "runProductionBuild", "options", "mainBundleConfig", "getMainBundleConfig", "demoConfig", "getDemoConfig", "terser", "generateDocs", "compileDemoScss", "buildCombinedBundle", "setupWatchMode", "isDevMode", "watcher", "watch", "handleWatcherEvents", "startDevelopmentServer", "chokidar", "scssCompiling", "scssPending", "scssTimer", "scssWatcher", "error", "setupWatchModeListeners", "buildWithRollup", "cleanupDist", "devCommand", "program", "withBuildOptions", "withServerOptions", "dev_default", "options", "build", "ora", "buildWithRollup", "error", "program", "ora", "buildCommand", "program", "withBuildOptions", "build_default", "options", "build", "ora", "buildWithRollup", "error", "exec", "path", "process", "fileURLToPath", "util", "program", "inquirer", "migrate_default", "program", "options", "filename", "fileURLToPath", "dirname", "path", "scriptPath", "execPromise", "util", "exec", "process", "inquirer", "shell", "process", "program", "readFile", "writeFile", "Logger", "fs", "path", "Octokit", "ora", "processContentForFile", "templateFiller", "getFolderItemsFromRelativeRepoPath", "ref", "octokit", "responseData", "errorMessage", "error", "errorSpinner", "processFolderItemsIntoFileConfigs", "folderItems", "templatePathToReplace", "rootDir", "fileConfigs", "item", "directorySpinner", "nestedFolderItems", "nestedConfigs", "finalPath", "outputPath", "config", "removeDirectory", "dirPath", "generateDirectoryTree", "prefix", "isLast", "stats", "baseName", "result", "sortedEntries", "i", "entry", "entryPath", "isLastEntry", "newPrefix", "syncDotGithubDir", "template", "templatesDefaultGithubPath", "githubPath", "removeSpinner", "processSpinner", "treeSpinner", "githubDirPath", "treeOutput", "treeError", "sync_default", "program", "options", "Logger", "cwd", "process", "syncDotGithubDir", "codeownersPath", "codeownersFixed", "readFile", "writeFile", "codeownersError", "error", "fs", "path", "Logger", "program", "glob", "prepWcaCompatibleCode_default", "code", "sourcePath", "defaultTag", "className", "classDesc", "WAC_DIR", "path", "globPath", "sources", "source", "glob", "err", "createExtendsFile", "filePaths", "fs", "filePath", "resolvedPath", "fileContent", "newPath", "newCode", "prepWcaCompatibleCode_default", "main", "wca_setup_default", "program", "Logger", "error", "program", "chalk", "ora", "appendFile", "readFile", "Logger", "simpleGit", "git", "error", "Git", "_Git", "pattern", "err", "sourceBranch", "branch", "targetBranch", "commitRange", "sourceBranchRef", "remotes", "originRemote", "remote", "remoteUrl", "url", "match", "commitChunks", "chunk", "commits", "parts", "hash", "date", "author_name", "subject", "bodyLines", "line", "body", "shortHash", "typeMatch", "type", "log", "result", "files", "branchName", "message", "chalk", "MAX_SUBJECT_LENGTH", "MAX_BODY_LENGTH", "getColoredType", "type", "wrapString", "str", "maxLength", "words", "result", "currentLine", "word", "displayDebugView", "commitList", "commit", "subject", "body", "github", "getExistingLabels", "token", "octokit", "context", "owner", "repo", "prNumber", "existingLabels", "label", "error", "applyLabelToPR", "prefixedLabel", "existingSemanticLabels", "existingLabel", "RELEASE_COMMIT_TYPES", "generateReleaseNotes", "commitList", "showLog", "releaseNotes", "commit", "bodyLines", "line", "formattedLine", "chalk", "filterCommitList", "fallbackCommits", "releaseCommits", "commitsToShow", "analyzeCommits", "debug", "setLabel", "spinner", "ora", "Git", "filteredCommits", "displayDebugView", "commitTypes", "formattedTypes", "type", "getColoredType", "handleLabels", "error", "validCommitTypes", "foundCommitTypes", "selectedLabel", "highestPriorityIndex", "priorityIndex", "labelSpinner", "getExistingLabels", "applyLabelToPR", "errorMessage", "check_commits_default", "program", "option", "analyzeCommits", "fs", "get", "chalk", "program", "ora", "pr_release_default", "option", "updatePackageJson", "namespace", "prNumber", "packageSpinner", "packageJsonPath", "packageJson", "releaseVersion", "packageComponent", "packageName", "incrementVersion", "getIncrementVersion", "packageVersion", "error", "spinner", "resolve", "handleResponse", "res", "data", "chunk", "packageData", "versions", "maxIteration", "versionRegex", "version", "match", "iteration", "registryUrl", "req", "err", "path", "fileURLToPath", "program", "open", "__filename", "fileURLToPath", "cliRootDir", "path", "test_default", "program", "option", "command", "coveragePath", "files", "shell", "open", "fs", "path", "program", "inquirer", "ora", "fs", "path", "ora", "JsonConfig", "toYaml", "config", "key", "value", "k", "v", "createMultiGitterDependencyTreeConfig", "outputPath", "spinner", "configContent", "configPath", "error", "fs", "getBatchedUpdateOrder", "dependencyTree", "inDegree", "batches", "currentBatch", "queue", "pkg", "queueLength", "current", "dependent", "getJsonFilesFromDirectory", "directory", "file", "formatDependencyTree", "jsonFileDirectory", "targetDependencies", "files", "contents", "data", "packageName", "peerDependencies", "devDependencies", "dependencies", "allDependencies", "dependency", "relevantPackages", "node", "dep", "target", "_filteredDependencyTree", "AURO_COMPONENT_PACKAGES", "CONFIG_DIR", "withHomeDir", "OUTPUT_DIR", "auroPackages", "AURO_COMPONENT_PACKAGES", "getOrCreateDependencyTree", "relevantPackages", "fs", "OUTPUT_DIR", "CONFIG_DIR", "error", "spinner", "ora", "createMultiGitterDependencyTreeConfig", "multiGitterCommand", "fromCliRoot", "path", "shell", "formatDependencyTree", "getDependencyBatchesFromTree", "dependencyTreePath", "dependencyTree", "batches", "getBatchedUpdateOrder", "agent_default", "program", "option", "answers", "inquirer", "input", "value", "component", "batchedUpdateOrderText", "batch", "index", "pkg", "resolve", "writeFile", "path", "process", "Logger", "program", "ora", "readFile", "path", "process", "UNPKG_BASE", "REGISTRY_BASE", "REQUEST_TIMEOUT_MS", "parseTarget", "target", "at", "isInside", "parent", "child", "rel", "readLocalManifest", "pkg", "modulesRoot", "pkgDir", "version", "manifestRelPath", "pkgJson", "manifest", "fetchManifest", "options", "preferLocal", "allowNetwork", "ref", "local", "url", "response", "error", "message", "partitionOutcomes", "outcomes", "skipped", "outcome", "fetchLatestVersion", "data", "Logger", "namespaceReferences", "node", "pkg", "item", "source", "result", "key", "value", "mergeManifests", "sources", "warn", "modules", "manifest", "module", "namespaced", "schemaVersions", "buildAggregateManifest", "packages", "options", "outcomes", "pkg", "fetchManifest", "sources", "outcome", "skipped", "transientFailures", "partitionOutcomes", "mergeManifests", "runCem", "options", "spinner", "ora", "AURO_COMPONENT_PACKAGES", "aggregate", "sources", "skipped", "transientFailures", "buildAggregateManifest", "process", "outputPath", "path", "writeFile", "error", "message", "outcome", "Logger", "cem_default", "program", "readFileSync", "dirname", "join", "resolve", "process", "program", "ora", "mkdtempSync", "rmSync", "tmpdir", "join", "withoutStringLiterals", "text", "hasBalancedDelimiters", "closeToOpen", "stack", "prev", "ch", "withSafeType", "entry", "_dropped", "rest", "isPrivateReflection", "attribute", "memberPrivacyByName", "fieldName", "description", "privacy", "withNamedEntriesPruned", "declaration", "hasName", "members", "member", "resolvedTagFor", "component", "resolvedTags", "importPathsByClass", "components", "c", "buildManifest", "withTempDir", "fn", "dir", "ensureTrailingNewline", "contents", "GLOBAL_ARIA_ATTRS", "BASE_PROPS_OPEN", "SVELTE_GLOBAL_MEMBERS", "injectGlobalAttributes", "svelteGlobals", "block", "installedFromOutcomes", "outcomes", "installed", "outcome", "detectInstalled", "packages", "AURO_COMPONENT_PACKAGES", "pkg", "fetchManifest", "registeredElements", "manifest", "module", "decl", "resolveComponents", "installed", "components", "owningPackages", "grounded", "pkg", "version", "elements", "isMonorepo", "declaration", "tagName", "owners", "duplicates", "packages", "resolveInstalled", "detectInstalled", "ENUMERATED_ATTRS", "UNINFORMATIVE_STRING_TYPES", "INVALID_PRIMITIVE_TYPES", "BARE_GENERIC_TYPES", "VAGUE_OBJECT_TYPES", "INVALID_PRIMITIVE_RULES", "token", "fix", "BARE_GENERIC_RULES", "shape", "describeType", "text", "DEPRECATION_MARKERS", "hasDeprecationMarker", "texts", "re", "isDeprecationFlagged", "deprecated", "isNonEmptyString", "checkMemberDeprecation", "findings", "element", "path", "entry", "checkEventSlotDeprecation", "kind", "checkDeprecationDetail", "value", "checkNames", "collection", "entries", "index", "checkType", "hasBalancedDelimiters", "checkPrimitiveType", "raw", "scannable", "withoutStringLiterals", "isEscaped", "backslashes", "j", "splitTopLevelUnion", "members", "depth", "quote", "start", "i", "ch", "member", "isStringLiteralMember", "checkWidenedUnion", "hasLiteral", "hasBareString", "m", "isMissingText", "checkDescription", "checkDeclaration", "decl", "attributes", "events", "slots", "a", "e", "s", "memberPrivacyByName", "attribute", "isPrivateReflection", "runContractRules", "manifest", "registeredElements", "execFileSync", "mkdirSync", "writeFileSync", "createRequire", "dirname", "join", "process", "generateJsxTypes", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "HTML_CUSTOM_DATA_FILENAME", "HTML_CUSTOM_DATA_SETTINGS_KEY", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "HTML_CUSTOM_DATA_PATH", "CSS_SNIPPETS_FILENAME", "CSS_SNIPPETS_PATH", "FRAMEWORK_TYPES_DIR", "JSX_TYPES_FILENAME", "SVELTE_TYPES_FILENAME", "JSX_TYPES_PATH", "SVELTE_TYPES_PATH", "TSCONFIG_INCLUDE_KEY", "TSCONFIG_INCLUDE_ENTRY", "buildJsxTypes", "components", "resolvedTags", "manifest", "buildManifest", "importPaths", "importPathsByClass", "contents", "withTempDir", "outdir", "generateJsxTypes", "JSX_TYPES_FILENAME", "tagName", "name", "JSX_TYPES_PATH", "ensureTrailingNewline", "injectGlobalAttributes", "readFileSync", "join", "generateSvelteTypes", "MODULE_SCOPED_SVELTE_NAMESPACE", "GLOBAL_SVELTE_NAMESPACE", "NATIVE_DOM_EVENTS", "SVELTE4_EVENT_HANDLER", "addSvelte5EventHandlers", "contents", "_match", "indent", "name", "handler", "CUSTOM_ELEMENT_MAPPING", "overrideCollidingBaseMembers", "matched", "next", "head", "tail", "PROPS_BLOCK", "MEMBER_JSDOC_OPEN", "labelComponentMembers", "markerByClass", "whole", "className", "body", "label", "marked", "markerLabelsByClass", "components", "resolvedTags", "component", "defaultTag", "resolvedTag", "globalizeSvelteNamespace", "buildSvelteTypes", "manifest", "buildManifest", "withTempDir", "outdir", "generateSvelteTypes", "SVELTE_TYPES_FILENAME", "readFileSync", "join", "SVELTE_TYPES_PATH", "ensureTrailingNewline", "injectGlobalAttributes", "require", "createRequire", "TSC", "JSX_SHIM", "stubFileFor", "importPath", "importedNamesByPath", "source", "byPath", "re", "match", "names", "entry", "set", "name", "writeTsconfig", "cwd", "include", "paths", "writeFileSync", "join", "writeArtifact", "artifact", "dest", "mkdirSync", "dirname", "compile", "label", "setup", "withTempDir", "execFileSync", "process", "error", "e", "output", "runGenerationSmoke", "components", "identityTags", "c", "findings", "jsx", "buildJsxTypes", "importsByPath", "jsxFinding", "file", "svelte", "buildSvelteTypes", "svelteFinding", "readSiblingPackageJson", "cemPath", "raw", "readFileSync", "join", "dirname", "resolve", "parsed", "formatFinding", "finding", "mark", "where", "locator", "DEFAULT_CEM_PATH", "runCemCheck", "options", "spinner", "ora", "fail", "message", "process", "error", "manifest", "pkg", "version", "installed", "components", "resolveComponents", "findings", "runContractRules", "runGenerationSmoke", "errors", "f", "warnings", "failed", "summary", "cem_check_default", "program", "fs", "path", "program", "ora", "AURO_CONTEXT_HEADER", "COMPONENT_TABLE_HEADER", "STATIC_COMPONENTS", "renderComponentRows", "components", "component", "STATIC_COMPONENT_TABLE", "AURO_CONTEXT_FOOTER", "buildAuroContext", "componentTable", "AURO_CONTEXT", "clean", "text", "chalk", "FORMKIT_PACKAGE", "LEGACY_FORMKIT_PACKAGES", "LEGACY_SET", "isLegacyFormkitPackage", "pkg", "formkitTagFor", "formkitSubpathFor", "SEMVER", "parseSemver", "version", "match", "compareVersions", "a", "b", "pa", "pb", "i", "len", "ai", "bi", "aNum", "bNum", "diff", "checkOutdated", "installed", "entries", "latest", "pkg", "fetchLatestVersion", "outdated", "index", "newest", "cmp", "FORMKIT_MARK", "renderOutdatedBanner", "legacy", "o", "isLegacyFormkitPackage", "normal", "heading", "pkgWidth", "installedWidth", "isLegacy", "rows", "row", "chalk", "guidance", "updateCmd", "formkitSubpathFor", "visibleWidths", "base", "width", "border", "buildComponentTable", "allowNetwork", "byTag", "component", "STATIC_COMPONENTS", "outcomes", "AURO_COMPONENT_PACKAGES", "pkg", "fetchManifest", "local", "installedFromOutcomes", "resolved", "enriched", "outcome", "declarations", "module", "decl", "tag", "liveDescription", "clean", "existing", "renderComponentRows", "reportOutdated", "spinner", "ora", "outdated", "checkOutdated", "renderOutdatedBanner", "runContext", "options", "online", "rows", "context", "buildAuroContext", "writeSpinner", "outputPath", "path", "fs", "error", "message", "context_default", "program", "fs", "path", "process", "program", "inquirer", "ora", "CONFIG_FILENAME", "existsSync", "readFileSync", "statSync", "path", "parseJsonc", "EDITOR_TARGETS", "isDir", "cwd", "rel", "statSync", "path", "dependencyNames", "raw", "readFileSync", "pkg", "parseJsonc", "detectVsCode", "VSCODE_DIR", "detectCssSnippets", "detectJsx", "tsconfigPath", "existsSync", "tsconfig", "detectSvelte", "ext", "detectEditorSignals", "existsSync", "readFileSync", "path", "parseJsonc", "toAbsolute", "cwd", "rel", "path", "readOrNull", "absolute", "readFileSync", "settingsHasPointer", "contents", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "value", "parseJsonc", "HTML_CUSTOM_DATA_SETTINGS_KEY", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "tsProgramIncludesTypes", "configRel", "data", "include", "TSCONFIG_INCLUDE_KEY", "TSCONFIG_INCLUDE_ENTRY", "verifyEditorWiring", "selection", "inconsistencies", "existsSync", "HTML_CUSTOM_DATA_PATH", "SVELTE_TYPES_PATH", "JSX_TYPES_PATH", "fs", "path", "SNIPPET_SCOPE", "isChoiceSafe", "name", "partNames", "component", "part", "snippetFor", "tag", "parts", "choice", "buildCssSnippets", "components", "resolvedTags", "snippets", "resolvedTagFor", "CSS_SNIPPETS_PATH", "ensureTrailingNewline", "getVsCodeHtmlCustomData", "buildHtmlCustomData", "components", "resolvedTags", "manifest", "buildManifest", "contents", "withTempDir", "outdir", "getVsCodeHtmlCustomData", "HTML_CUSTOM_DATA_PATH", "ensureTrailingNewline", "applyEdits", "modify", "parseJsonc", "parseTree", "FORMATTING", "isPlainObject", "value", "parseObject", "source", "label", "errors", "data", "parseJsonc", "applyValueEdit", "path", "base", "edits", "modify", "applyEdits", "deleteLoneTopLevelKey", "key", "root", "parseTree", "prop", "end", "applyKeyDeletion", "surgical", "mergeVsCodeSettings", "existing", "entry", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "parsed", "current", "HTML_CUSTOM_DATA_SETTINGS_KEY", "nextValue", "mergeTsconfigInclude", "TSCONFIG_INCLUDE_ENTRY", "configName", "include", "TSCONFIG_INCLUDE_KEY", "unmergeVsCodeSettings", "remaining", "v", "unmergeTsconfigInclude", "toAbsolute", "cwd", "filename", "path", "writeArtifact", "artifact", "absolute", "fs", "readOrEmpty", "error", "writeEditorArtifacts", "components", "resolvedTags", "selection", "written", "warnings", "buildHtmlCustomData", "settingsRel", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "settingsAbs", "merged", "mergeVsCodeSettings", "HTML_CUSTOM_DATA_SETTINGS_ENTRY", "HTML_CUSTOM_DATA_SETTINGS_KEY", "buildJsxTypes", "buildSvelteTypes", "buildCssSnippets", "configRel", "configAbs", "existing", "mergeTsconfigInclude", "TSCONFIG_INCLUDE_ENTRY", "TSCONFIG_INCLUDE_KEY", "AGENTS_FILENAME", "CLAUDE_FILENAME", "GROUNDING_MARKER", "GROUNDING_HEADER", "INSTALLED_TABLE_HEADER", "REGENERATION_NOTE", "CLAUDE_MD", "AGENTS_FILENAME", "AURO_CODING_RULES", "SCOPE", "toPackageName", "name", "trimmed", "lower", "kebabToCamel", "_", "char", "deprecatedTag", "deprecated", "clean", "renderList", "rows", "width", "label", "desc", "formatDeclaration", "pkg", "decl", "options", "installPkg", "importSpecifier", "lines", "description", "heritage", "apiBodyLines", "attributes", "a", "type", "def", "attrFields", "members", "m", "isMethod", "typeText", "slots", "s", "events", "e", "cssParts", "p", "cssProps", "displayTag", "component", "resolvedTags", "componentBlock", "tag", "pkg", "importPath", "decl", "lines", "description", "clean", "heritage", "apiBodyLines", "generateAgentsMd", "components", "rows", "sections", "installedLines", "INSTALLED_TABLE_HEADER", "installedSection", "GROUNDING_HEADER", "AURO_CODING_RULES", "REGENERATION_NOTE", "generateClaudeMd", "CLAUDE_MD", "groundingFiles", "AGENTS_FILENAME", "CLAUDE_FILENAME", "appendFileSync", "readFileSync", "path", "simpleGit", "GITIGNORE_HEADER", "findIgnored", "cwd", "paths", "parentDir", "rel", "dir", "readGitignoreLines", "current", "line", "appendGitignore", "lines", "dedupe", "gitignoreAbs", "existing", "toAdd", "prefix", "unignore", "ignoredPaths", "stillIgnored", "present", "trio", "seenDirs", "unfixable", "readFileSync", "writeFileSync", "path", "globSync", "readFileSync", "writeFileSync", "path", "globSync", "ts", "AURO_PREFIX", "SOURCE_GLOB", "SOURCE_GLOB_IGNORE", "RegistryError", "message", "emptyConfig", "defaultPrefix", "assertConfig", "value", "source", "obj", "prefix", "loadConfig", "cwd", "file", "path", "CONFIG_FILENAME", "raw", "readFileSync", "error", "parsed", "saveConfig", "config", "writeFileSync", "scriptKindFor", "filePath", "ts", "staticTag", "arg", "scanSource", "scriptKind", "matches", "defaultRegistrations", "warnings", "sourceFile", "visit", "node", "object", "className", "tag", "SVELTE_SCRIPT", "SVELTE_LANG_TS", "extractSvelteScripts", "scripts", "match", "attributes", "content", "scanProject", "files", "globSync", "collect", "scan", "baseOf", "canonicalTag", "inferPrefixFromTag", "customTag", "base", "suggestDefaultPrefix", "prefixes", "counts", "suggestion", "best", "count", "reconcileRegistrations", "components", "byClassName", "component", "overrides", "canonical", "defaultRegistered", "applyPrefix", "planTagResolution", "options", "configOverrides", "reconciled", "configDefault", "effectiveDefault", "resolvedTags", "persistOverrides", "needingDefault", "reconciliationWarnings", "noPrefixWarnings", "fromConfig", "fromScan", "resolved", "inferred", "custom", "mixed", "needsDefaultPrefix", "PACKAGE_JSON", "detectJsonIndent", "raw", "match", "readPackageJson", "cwd", "readFileSync", "path", "error", "detectLegacyFormkit", "parsed", "pkgJson", "found", "fields", "pkg", "LEGACY_FORMKIT_PACKAGES", "field", "version", "escapeRegExp", "value", "rewriteSource", "source", "legacyPkgs", "next", "rewrites", "deep", "escaped", "bare", "_match", "quote", "formkitSubpathFor", "deepRe", "deepMatch", "migrateToFormkit", "legacy", "l", "isLegacyFormkitPackage", "report", "indent", "block", "FORMKIT_PACKAGE", "writeFileSync", "files", "globSync", "SOURCE_GLOB", "SOURCE_GLOB_IGNORE", "file", "rel", "specifier", "existsSync", "readdirSync", "readFileSync", "rmdirSync", "rmSync", "writeFileSync", "path", "parseJsonc", "toAbsolute", "cwd", "rel", "path", "isEmptyObject", "source", "data", "parseJsonc", "hasComments", "readOrNull", "absolute", "readFileSync", "error", "UNCONDITIONAL_ARTIFACTS", "HTML_CUSTOM_DATA_PATH", "CSS_SNIPPETS_PATH", "JSX_TYPES_PATH", "SVELTE_TYPES_PATH", "classifyGroundingFile", "contents", "kind", "GROUNDING_MARKER", "CLAUDE_MD", "planReset", "filesToRemove", "filesToSkip", "warnings", "AGENTS_FILENAME", "CLAUDE_FILENAME", "verdict", "existsSync", "CONFIG_FILENAME", "loadConfig", "reason", "RegistryError", "unmerges", "settingsRel", "VSCODE_DIR", "VSCODE_SETTINGS_FILENAME", "settingsContents", "result", "unmergeVsCodeSettings", "configRel", "unmergeTsconfigInclude", "FRAMEWORK_TYPES_DIR", "isEmptyDir", "readdirSync", "applyReset", "plan", "removed", "rmSync", "unmerged", "writeFileSync", "prunedDirs", "rmdirSync", "chalk", "MAX_WIDTH", "CONTENT_WIDTH", "BULLET", "CONTINUATION_INDENT", "wrapText", "text", "width", "words", "lines", "current", "word", "renderWarningBanner", "heading", "messages", "color", "accent", "body", "message", "index", "line", "lineIndex", "prefix", "headingWidth", "border", "isNonInteractive", "options", "process", "promptDefaultPrefix", "plan", "accept", "inquirer", "prefix", "isValidCustomTag", "tag", "trimmed", "promptCustomTags", "components", "resolvedTags", "customize", "overrides", "component", "canonical", "calculated", "entered", "withUserOverrides", "config", "base", "emptyConfig", "EDITOR_TARGET_META", "resolveEditorTargets", "cwd", "persisted", "signals", "detectEditorSignals", "interactive", "selection", "pending", "target", "EDITOR_TARGETS", "flag", "saved", "label", "artifact", "answers", "name", "offerFormkitMigration", "legacy", "detectLegacyFormkit", "error", "message", "names", "l", "migrate", "spinner", "ora", "report", "migrateToFormkit", "file", "specifier", "reportOutdated", "installed", "c", "outdated", "checkOutdated", "renderOutdatedBanner", "runInit", "runReset", "duplicates", "resolveInstalled", "loadConfig", "RegistryError", "CONFIG_FILENAME", "scan", "scanProject", "planTagResolution", "needsDecision", "resolvedPrefix", "reason", "customTags", "editorSelection", "writeSpinner", "editorReport", "groundingFiles", "fs", "path", "writeEditorArtifacts", "saveConfig", "editorNote", "AGENTS_FILENAME", "CLAUDE_FILENAME", "warning", "duplicate", "renderWarningBanner", "verdict", "verifyEditorWiring", "healReport", "alreadyWarned", "touched", "reconcileGitignore", "ignored", "findIgnored", "fix", "fixed", "unfixable", "unignore", "isEmptyResetPlan", "planReset", "skip", "unmerge", "dir", "confirm", "resetSpinner", "applyReset", "removedNote", "unmergedNote", "prunedNote", "d", "init_default", "program", "process", "Logger", "program", "ora", "resolveSource", "pkg", "options", "plain", "result", "fetchManifest", "isLegacyFormkitPackage", "localLegacy", "FORMKIT_PACKAGE", "formkitSubpathFor", "formkitTagFor", "runComponent", "name", "toPackageName", "spinner", "ora", "source", "target", "process", "declarations", "module", "decl", "origin", "outdatedBanner", "check", "outdated", "checkOutdated", "renderOutdatedBanner", "formatDeclaration", "Logger", "component_default", "program", "program", "docsCommand", "program", "withServerOptions", "docs_default", "options", "cem", "api", "docs", "serve", "watchDocs", "program", "Octokit", "azdev", "ora", "fetchGitHubIssue", "issueUrl", "ghToken", "octokit", "owner", "repo", "issueNumberStr", "urlMatch", "shortMatch", "issueNumber", "issue", "error", "getExistingADOLink", "query", "variables", "project19Item", "item", "adoFieldValue", "fieldValue", "updateGitHubProject", "adoWorkItemUrl", "projectNumber", "response", "projectId", "issueId", "adoField", "field", "projectItemId", "createADOWorkItem", "adoToken", "orgUrl", "projectName", "areaPath", "authHandler", "workItemTrackingApi", "workItemData", "createADOItem", "ghIssue", "spinner", "checkSpinner", "existingADOLink", "createSpinner", "workItem", "projectSpinner", "adoCommand", "program", "options", "createADOItem", "program", "Octokit", "simpleGit", "LABEL", "RC_SOURCE_BRANCH", "RC_BASE_BRANCH", "RCWorkflow", "_RCWorkflow", "owner", "repo", "octokit", "token", "info", "Git", "Octokit", "triggerBranch", "rcIssue", "linkedPr", "commitList", "filterCommitList", "data", "openIssues", "issue", "latestIssue", "issueNumber", "releaseNotes", "title", "branchRef", "branchName", "devBranch", "matchingRefs", "branchExists", "error", "head", "openPrs", "pr", "closedPrs", "template", "prBody", "prNumber", "filteredCommits", "generateReleaseNotes", "rc_workflow_default", "program", "RCWorkflow", "program", "getPackageVersion", "auroSplash_default"]
|
|
7
7
|
}
|