@aurodesignsystem-dev/auro-cli 0.0.0-pr289.2 → 0.0.0-pr294.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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/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/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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\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 { 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\nconst auroComponents = [\n \"@aurodesignsystem/auro-accordion\",\n \"@aurodesignsystem/auro-alert\",\n \"@aurodesignsystem/auro-avatar\",\n \"@aurodesignsystem/auro-background\",\n \"@aurodesignsystem/auro-backtotop\",\n \"@aurodesignsystem/auro-button\",\n \"@aurodesignsystem/auro-badge\",\n \"@aurodesignsystem/auro-banner\",\n \"@aurodesignsystem/auro-card\",\n \"@aurodesignsystem/auro-carousel\",\n \"@aurodesignsystem/auro-datetime\",\n \"@aurodesignsystem/auro-dialog\",\n \"@aurodesignsystem/auro-drawer\",\n \"@aurodesignsystem/auro-formkit\",\n \"@aurodesignsystem/auro-flight\",\n \"@aurodesignsystem/auro-flightline\",\n \"@aurodesignsystem/auro-header\",\n \"@aurodesignsystem/auro-hyperlink\",\n \"@aurodesignsystem/auro-icon\",\n \"@aurodesignsystem/auro-loader\",\n \"@aurodesignsystem/auro-lockup\",\n \"@aurodesignsystem/auro-nav\",\n \"@aurodesignsystem/auro-pane\",\n \"@aurodesignsystem/auro-popover\",\n \"@aurodesignsystem/auro-sidenav\",\n \"@aurodesignsystem/auro-skeleton\",\n \"@aurodesignsystem/auro-slideshow\",\n \"@aurodesignsystem/auro-table\",\n \"@aurodesignsystem/auro-tabs\",\n \"@aurodesignsystem/auro-toast\",\n];\n\nconst auroPackages = [\n ...auroComponents,\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: auroComponents.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", "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,EAASC,EAAS,CACrB,QAAQ,IAAI,OACd,QAAQ,IAAI,WAAWA,CAAO,EAAE,CAEpC,CAMe,SAARC,IAAqC,CAC1C,GAAI,CAEF,IAAMC,EAAaJ,GAAc,YAAY,GAAG,EAC1CK,EAAYN,GAAK,QAAQK,CAAU,EACzCH,EAAS,wBAAwBI,CAAS,EAAE,EAG5C,IAAMC,EAAcP,GAAK,QAAQM,EAAW,KAAM,cAAc,EAGhE,OADAJ,EAAS,6BAA6BK,CAAW,EAAE,EAC/CR,GAAG,WAAWQ,CAAW,GAC3BL,EAAS,0BAA0BK,CAAW,EAAE,EAC5B,KAAK,MAAMR,GAAG,aAAaQ,EAAa,MAAM,CAAC,EAChD,UAIrBL,EACE,8FACF,EACO,QACT,OAASM,EAAO,CACd,eAAQ,MAAM,oCAAqCA,CAAK,EACjD,OACT,CACF,CC7CA,OAAS,WAAAC,OAAe,YACxB,OAAOC,OAAS,MCGT,SAASC,EAAiBC,EAAS,CACxC,OAAOA,EACJ,OAAO,gCAAiC,gCAAgC,EACxE,OAAO,cAAe,qB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O,CACvE,OAASY,EAAgB,CACvB,cAAQ,MAAM,0BAA2BA,CAAK,EACxCA,CACR,CACF,CAEA,MAAc,WAAWR,EAAqBe,EAAiC,CAC7E,GAAI,CACF,IAAMD,EAAS,MAAM,KAAK,gBAAgBd,CAAW,EAErD,MAAM,KAAK,QAAQ,KAAK,MAAM,OAAO,CACnC,MAAO,KAAK,SAAS,MACrB,KAAM,KAAK,SAAS,KACpB,YAAae,EACb,KAAMD,CACR,CAAC,EAED,QAAQ,IAAI,4CAA4CC,CAAQ,EAAE,CACpE,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,EvCODC,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", "CONFIG_DIR", "withHomeDir", "OUTPUT_DIR", "auroComponents", "auroPackages", "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", "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/pathUtils.js", "../src/utils/copyReadmeToDemo.js", "../src/utils/shutdown.js", "../src/utils/shell.js", "../src/scripts/build/defaultDocsBuild.js", "../src/scripts/build/devServerUtils.js", "../src/scripts/build/paths.js", "../src/scripts/docs/docs-generator.ts", "../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/commands/docs.ts", "../src/commands/ado.ts", "../src/scripts/ado/index.ts", "../src/commands/rc-workflow.ts", "../src/scripts/rc-workflow/index.ts", "../src/commands/version-scan.ts", "../src/scripts/version-bot/scan.ts", "../src/scripts/version-bot/audit-log.ts", "../src/scripts/version-bot/cache.ts", "../src/scripts/version-bot/evaluate.ts", "../src/scripts/version-bot/aliases.ts", "../src/scripts/version-bot/npm-registry.ts", "../src/scripts/version-bot/policy-catalog.ts", "../src/scripts/version-bot/findings.ts", "../src/scripts/version-bot/manifest-discovery.ts", "../src/commands/version-tickets.ts", "../src/scripts/version-bot/cleanup.ts", "../src/scripts/version-bot/create-tickets.ts", "../src/scripts/ado/wiql.ts", "../src/scripts/version-bot/changelog.ts", "../src/scripts/version-bot/html-preview.ts", "../src/scripts/version-bot/template.ts", "../src/scripts/version-bot/usage-inventory.ts"],
4
+ "sourcesContent": ["// Load .env into process.env before any command file imports \u2014 version-scan\n// reads ECOM_ORG at option-registration time, which fires during import.\nimport \"dotenv/config\";\nimport { 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/docs.ts\";\nimport \"#commands/ado.ts\";\nimport \"#commands/rc-workflow.ts\";\nimport \"#commands/version-scan.ts\";\nimport \"#commands/version-tickets.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 { getDemoConfig, getMainBundleConfig } 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 { 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 { shell } from \"#utils/shell.js\";\nimport { runDefaultDocsBuild } from \"../build/defaultDocsBuild.js\";\nimport { startDevelopmentServer } from \"../build/devServerUtils.js\";\nimport Docs from \"./docs-generator.ts\";\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 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 { 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 { 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 { readFileSync, existsSync } from \"node:fs\";\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(\n config = defaultDocsProcessorConfig,\n skipReadme = false,\n) {\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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\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\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", "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n Attribute,\n ClassMember,\n CustomElementDeclaration,\n Declaration,\n Module,\n Package,\n Parameter,\n} from \"custom-elements-manifest\";\nimport { markdownTable } from \"markdown-table\";\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 = {\n schemaVersion: \"1.0.0\",\n readme: \"\",\n modules: [],\n };\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 // 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 &&\n dec.customElement === true &&\n \"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) =>\n Docs.renderElement(element, true),\n )\n .join(\"\\n\\n\")}`;\n }\n\n /**\n * Render a single element as markdown\n */\n static renderElement(\n element: CustomElementDeclaration,\n includeTitle = true,\n ): string {\n const sections = [];\n const {\n renderTable,\n renderPropertiesAttributesTable,\n renderParameters,\n getType,\n } = 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\" &&\n (\"privacy\" in m ? m.privacy !== \"private\" : true) &&\n m.name[0] !== \"_\",\n )\n .map((m: ClassMember) => ({\n ...m,\n parameters: renderParameters(\n \"parameters\" in m ? (m.parameters as Parameter[]) : undefined,\n ),\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(\n element: CustomElementDeclaration,\n ): string {\n const { getType, escapeMarkdown } = Docs;\n\n const properties =\n 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 =\n \"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:\n (\"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 = [\n \"Properties\",\n \"Attributes\",\n \"Modifiers\",\n \"Type\",\n \"Default\",\n \"Description\",\n ];\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(\n /^\"([^\"]+)\"$/,\n \"$1\",\n );\n const defaultWrapped = defaultDoubleSanitized\n ? defaultDoubleSanitized.startsWith(\"`\") &&\n 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 const { escapeMarkdown, getType } = Docs;\n\n if (!parameters || parameters.length === 0) {\n return \"None\";\n }\n\n return parameters\n .map((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 .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 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.map((p: string | string[]) =>\n capitalize((Array.isArray(p) ? p[0] : p).split(\".\")[0]),\n );\n\n const rows = filteredData.map((item: Record<string, unknown>) =>\n properties.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 (\n 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\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\n .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 })\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\n .map((ref: any) => ref.name || String(ref))\n .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 // 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 { api, cem } from \"#scripts/docs/index.ts\";\n\n/**\n * Analyzes web components and generates API documentation.\n */\nexport async function analyzeComponents() {\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: [\n ...allModulePaths,\n join(process.cwd(), \"src\", \"styles\"),\n join(process.cwd(), \"src\"),\n ],\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 { readFile, writeFile } from \"node:fs/promises\";\nimport process from \"node:process\";\nimport { Logger } from \"@aurodesignsystem/auro-library/scripts/utils/logger.mjs\";\nimport { program } from \"commander\";\nimport { syncDotGithubDir } from \"#scripts/syncDotGithubDir.js\";\n\nexport default program\n .command(\"sync\")\n .option(\n \"-r, --ref <branch/tag/commit>\",\n \"Git reference (branch/tag/commit) to use\",\n \"main\",\n )\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, {\n encoding: \"utf-8\",\n });\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 (\n codeownersFixed.includes(\"\\r\") ||\n codeownersFixed.includes(\"\\n\\n\")\n ) {\n Logger.error(\"CODEOWNERS file still has Windows line endings.\");\n }\n } catch (codeownersError) {\n Logger.error(\n `Error processing CODEOWNERS file: ${codeownersError.message}`,\n );\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\";\n// @ts-expect-error: No types available for this module\n// biome-ignore format: keep this import on a single line so @ts-expect-error covers the from clause\nimport { processContentForFile, templateFiller } from \"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs\";\nimport { Octokit } from \"@octokit/rest\";\nimport ora from \"ora\";\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:\n | string\n | {\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 * 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(\n \"GET /repos/{owner}/{repo}/contents/{path}\",\n {\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\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(\n `Processing directory: ${item.path}`,\n ).start();\n\n const nestedFolderItems = await getFolderItemsFromRelativeRepoPath(\n item.path,\n ref,\n );\n\n directorySpinner.succeed(\n `Found ${nestedFolderItems.length} additional items in ${item.path}`,\n );\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 * 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(\n dirPath: string,\n prefix = \"\",\n isLast = true,\n): 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(\n entryPath,\n newPrefix,\n isLastEntry,\n );\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(\n rootDir: string,\n ref = \"main\",\n template = \"default\",\n) {\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(\n templatesDefaultGithubPath,\n ref,\n );\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 } 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(\n \"-r, --release-notes\",\n \"Generate release notes based on commit messages\",\n )\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 type { Ora } from \"ora\";\nimport 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(\n commitList: CommitInfo[],\n showLog = true,\n): 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(\n chalk.green(\n `\u2713 Generating release notes for ${commitList.length} commits`,\n ),\n );\n }\n\n return releaseNotes;\n}\n\nexport function filterCommitList(\n commitList: CommitInfo[],\n fallbackCommits = true,\n): 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 type { SimpleGit } from \"simple-git\";\nimport { 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 =\n 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 =\n 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<{\n owner: string;\n repo: string;\n } | 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 =\n 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(\n url: string,\n ): { 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 type { Ora } from \"ora\";\nimport 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 { 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\nconst auroComponents = [\n \"@aurodesignsystem/auro-accordion\",\n \"@aurodesignsystem/auro-alert\",\n \"@aurodesignsystem/auro-avatar\",\n \"@aurodesignsystem/auro-background\",\n \"@aurodesignsystem/auro-backtotop\",\n \"@aurodesignsystem/auro-button\",\n \"@aurodesignsystem/auro-badge\",\n \"@aurodesignsystem/auro-banner\",\n \"@aurodesignsystem/auro-card\",\n \"@aurodesignsystem/auro-carousel\",\n \"@aurodesignsystem/auro-datetime\",\n \"@aurodesignsystem/auro-dialog\",\n \"@aurodesignsystem/auro-drawer\",\n \"@aurodesignsystem/auro-formkit\",\n \"@aurodesignsystem/auro-flight\",\n \"@aurodesignsystem/auro-flightline\",\n \"@aurodesignsystem/auro-header\",\n \"@aurodesignsystem/auro-hyperlink\",\n \"@aurodesignsystem/auro-icon\",\n \"@aurodesignsystem/auro-loader\",\n \"@aurodesignsystem/auro-lockup\",\n \"@aurodesignsystem/auro-nav\",\n \"@aurodesignsystem/auro-pane\",\n \"@aurodesignsystem/auro-popover\",\n \"@aurodesignsystem/auro-sidenav\",\n \"@aurodesignsystem/auro-skeleton\",\n \"@aurodesignsystem/auro-slideshow\",\n \"@aurodesignsystem/auro-table\",\n \"@aurodesignsystem/auro-tabs\",\n \"@aurodesignsystem/auro-toast\",\n];\n\nconst auroPackages = [\n ...auroComponents,\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: auroComponents.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", "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\nexport default docsCommand.action(async (options) => {\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 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 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 type { WorkItem } from \"azure-devops-node-api/interfaces/WorkItemTrackingInterfaces.js\";\nimport ora from \"ora\";\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(\n /github\\.com\\/([^/]+)\\/([^/]+)\\/issues\\/(\\d+)/,\n );\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(\n \"Issue must be provided as full URL or in format 'owner/repo#number'\",\n );\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 (\n issue: GitHubIssue,\n): 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) =>\n fieldValue.field?.name?.toLowerCase() === \"ado\" &&\n 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 } 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\nconst ADO_ORG_URL = \"https://dev.azure.com/itsals\";\nconst ADO_PROJECT_NAME = \"E_Retain_Content\";\nconst ADO_AREA_PATH = \"E_Retain_Content\\\\Auro Design System\";\n\nfunction getWorkItemTrackingApi() {\n const adoToken = process.env.ADO_TOKEN;\n if (!adoToken) {\n throw new Error(\"ADO_TOKEN environment variable is required\");\n }\n const authHandler = azdev.getPersonalAccessTokenHandler(adoToken);\n const connection = new azdev.WebApi(ADO_ORG_URL, authHandler);\n return connection.getWorkItemTrackingApi();\n}\n\nexport interface CreateADOWorkItemInput {\n title: string;\n descriptionHtml: string;\n acceptanceCriteriaHtml?: string;\n tags?: string[];\n}\n\n/**\n * Creates a User Story work item in Azure DevOps under the\n * E_Retain_Content\\Auro Design System area path.\n *\n * Generic over input source \u2014 the GitHub-issue path supplies its own\n * title + description, and Phase 5's version-tickets command does the same\n * with its generated upgrade story.\n */\nexport const createADOWorkItem = async (\n input: CreateADOWorkItemInput,\n): Promise<WorkItem> => {\n const workItemTrackingApi = await getWorkItemTrackingApi();\n\n try {\n // Prepare work item data - omitting iteration path to use project default\n const workItemData: Array<{ op: string; path: string; value: string }> = [\n {\n op: \"add\",\n path: \"/fields/System.Title\",\n value: input.title,\n },\n {\n op: \"add\",\n path: \"/fields/System.Description\",\n value: input.descriptionHtml,\n },\n {\n op: \"add\",\n path: \"/fields/System.AreaPath\",\n value: ADO_AREA_PATH,\n },\n ];\n\n if (input.acceptanceCriteriaHtml) {\n workItemData.push({\n op: \"add\",\n path: \"/fields/Microsoft.VSTS.Common.AcceptanceCriteria\",\n value: input.acceptanceCriteriaHtml,\n });\n }\n\n if (input.tags && input.tags.length > 0) {\n workItemData.push({\n op: \"add\",\n path: \"/fields/System.Tags\",\n value: input.tags.join(\"; \"),\n });\n }\n\n return await workItemTrackingApi.createWorkItem(\n null,\n workItemData,\n ADO_PROJECT_NAME,\n \"User Story\",\n );\n } catch (error) {\n throw new Error(`Failed to create ADO work item: ${error}`);\n }\n};\n\nexport interface CloseADOWorkItemInput {\n id: number;\n /** Plain-text comment appended to System.History for audit context. */\n comment?: string;\n /** ADO state to transition to. Defaults to \"Removed\" (soft-delete). */\n state?: string;\n}\n\n/**\n * Soft-deletes (state = \"Removed\") an existing ADO work item and optionally\n * appends a history comment explaining why. Requires the same PAT scope as\n * `createADOWorkItem` (Work Items: Read, write, & manage).\n */\nexport const closeADOWorkItem = async (\n input: CloseADOWorkItemInput,\n): Promise<WorkItem> => {\n const workItemTrackingApi = await getWorkItemTrackingApi();\n const state = input.state ?? \"Removed\";\n\n const patch: Array<{ op: string; path: string; value: string }> = [\n { op: \"add\", path: \"/fields/System.State\", value: state },\n ];\n if (input.comment) {\n patch.push({\n op: \"add\",\n path: \"/fields/System.History\",\n value: input.comment,\n });\n }\n\n try {\n return await workItemTrackingApi.updateWorkItem(\n null,\n patch,\n input.id,\n ADO_PROJECT_NAME,\n );\n } catch (error) {\n throw new Error(`Failed to close ADO work item #${input.id}: ${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({\n title: issue.title,\n descriptionHtml: `GitHub Issue: <a href=\"${issue.html_url}\">${issue.html_url}</a>`,\n });\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(\n \"Adding to GitHub project and updating ADO field...\",\n ).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};\n", "import { program } from \"commander\";\nimport { RCWorkflow } from \"#scripts/rc-workflow/index.ts\";\n\nexport default program\n .command(\"rc-workflow\")\n .description(\"Generate RC issue and pull request\")\n .action(async () => {\n const workflow = await RCWorkflow.create();\n await workflow.createReleaseCandidate();\n });\n", "import { Octokit } from \"@octokit/rest\";\nimport { simpleGit } from \"simple-git\";\nimport {\n filterCommitList,\n generateReleaseNotes,\n} from \"#scripts/check-commits/commit-analyzer.ts\";\nimport { Git } from \"#utils/gitUtils.ts\";\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 = {\n state: \"open\" | \"closed\";\n html_url?: string;\n multipleOpen?: boolean;\n number?: number;\n};\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(\n \"Failed to retrieve repository information. Ensure you're in a valid git repository.\",\n );\n }\n\n const triggerBranch = await RCWorkflow.getTriggerBranchName();\n if (triggerBranch && triggerBranch !== RC_SOURCE_BRANCH) {\n console.log(\n `Switching from ${triggerBranch} to ${RC_SOURCE_BRANCH} branch...`,\n );\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(\n \"No filtered commits found. Continuing to update RC issue/branch/PR.\",\n );\n }\n\n let rcIssue: RcIssue | null = await this.getLatestOpenRcIssue();\n let linkedPr: LinkedPr | null = rcIssue\n ? await this.getLinkedPrByHead(rcIssue.number)\n : null;\n\n if (linkedPr?.multipleOpen) {\n throw new Error(\n \"Multiple open RC PRs found for the same rc/<issueNumber> branch.\",\n );\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(\n `No open Release Candidate issues found in ${this.repoInfo.repo}`,\n );\n return null;\n }\n\n const latestIssue = openIssues[0];\n console.log(\n `Using latest open Release Candidate issue: #${latestIssue.number}`,\n );\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(\n `Created Release Candidate issue: #${data.number} (${data.html_url})`,\n );\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 {\n owner: this.repoInfo.owner,\n repo: this.repoInfo.repo,\n ref: branchRef,\n },\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(\n `Failed to create or update ${branchName} branch: ${error}`,\n );\n }\n }\n\n private async getLinkedPrByHead(\n issueNumber: number,\n ): 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 {\n state: \"open\",\n html_url: openPrs[0].html_url,\n number: openPrs[0].number,\n };\n }\n\n const closedPrs = data.filter((pr) => pr.state === \"closed\");\n if (closedPrs.length > 0) {\n return {\n state: \"closed\",\n html_url: closedPrs[0].html_url,\n number: closedPrs[0].number,\n };\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 (\n error &&\n typeof error === \"object\" &&\n \"status\" in error &&\n (error as { status?: number }).status === 404\n ) {\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(\n `POST /repos/${this.repoInfo.owner}/${this.repoInfo.repo}/pulls`,\n {\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\n console.log(\n `Created Release Candidate pull request: #${data.number} (${data.html_url})`,\n );\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(\n issueNumber: number,\n prNumber: number,\n ): 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", "import chalk from \"chalk\";\nimport { program } from \"commander\";\nimport { runScan } from \"#scripts/version-bot/scan.ts\";\n\ninterface VersionScanOptions {\n org: string;\n force: boolean;\n outputDir?: string;\n}\n\nexport const versionScanCommand = program\n .command(\"version-scan\")\n .description(\n \"Scan a GitHub org for repos using outdated Auro packages and write upgrade candidates JSON.\",\n )\n .option(\n \"--org <name>\",\n \"GitHub org to scan (overrides ECOM_ORG env var)\",\n process.env.ECOM_ORG ?? \"Alaska-ECommerce\",\n )\n .option(\n \"--force\",\n \"Re-scan all repos, ignoring the pushed_at incremental short-circuit\",\n false,\n )\n .option(\n \"--output-dir <dir>\",\n \"Directory to write the cache + candidates JSON files (default: ./.cache/version-bot/)\",\n )\n .action(async (options: VersionScanOptions) => {\n try {\n const summary = await runScan({\n org: options.org,\n force: options.force,\n outputDir: options.outputDir,\n });\n\n console.log(\"\");\n console.log(chalk.bold(\"Version scan complete.\"));\n console.log(\n ` Repos scanned: ${chalk.cyan(summary.reposScanned)} skipped: ${chalk.gray(summary.reposSkipped)} errored: ${chalk.yellow(summary.reposErrored)}`,\n );\n console.log(\n ` Upgrade candidates (>= 1 major behind): ${chalk.cyan(summary.candidatesFound)}`,\n );\n console.log(\n ` Compliance findings (all rows, incl. Current): ${chalk.cyan(summary.findingsCount)}`,\n );\n console.log(` Cache: ${summary.cachePath}`);\n console.log(` Candidates: ${summary.candidatesPath}`);\n console.log(` Findings: ${summary.findingsPath}`);\n } catch (error) {\n console.error(\n chalk.red(\n `version-scan failed: ${error instanceof Error ? error.message : error}`,\n ),\n );\n process.exit(1);\n }\n });\n", "import { Octokit } from \"@octokit/rest\";\nimport ora from \"ora\";\nimport { newRunId } from \"./audit-log.ts\";\nimport {\n complianceFindingsPath,\n displayPath,\n readScanCache,\n scanCachePath,\n upgradeCandidatesPath,\n writeComplianceFindings,\n writeScanCache,\n writeUpgradeCandidates,\n} from \"./cache.ts\";\nimport { buildComplianceFindings, evaluateRepoPackage } from \"./findings.ts\";\nimport { discoverAuroManifests } from \"./manifest-discovery.ts\";\nimport {\n compareSemver,\n type ResolvedLatest,\n resolveLatestAcrossAliases,\n} from \"./npm-registry.ts\";\nimport { findPackagePolicy } from \"./policy-catalog.ts\";\nimport type {\n PackageScan,\n RepoEntry,\n ScanCache,\n UpgradeCandidate,\n} from \"./types.ts\";\n\nconst AURO_ORG = \"AlaskaAirlines\";\n\ninterface ScanOptions {\n org: string;\n force: boolean;\n outputDir?: string;\n}\n\ninterface ScanSummary {\n reposScanned: number;\n reposSkipped: number;\n reposErrored: number;\n candidatesFound: number;\n findingsCount: number;\n cachePath: string;\n candidatesPath: string;\n findingsPath: string;\n}\n\nexport async function runScan(options: ScanOptions): Promise<ScanSummary> {\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({ auth: ghToken });\n const cache = readScanCache(options.outputDir);\n\n const archivedSpinner = ora(\n `Listing archived Auro packages in ${AURO_ORG}...`,\n ).start();\n const archivedPackages = await fetchArchivedAuroPackages(octokit);\n archivedSpinner.succeed(\n `Found ${archivedPackages.size / 2} archived Auro repos (excluded from upgrade candidates).`,\n );\n\n const reposSpinner = ora(`Listing repos in ${options.org}...`).start();\n const repos = await listEcommerceRepos(octokit, options.org);\n reposSpinner.succeed(\n `Found ${repos.length} non-archived, non-fork repos in ${options.org}.`,\n );\n\n const discoverySpinner = ora(\n `Discovering Auro package.json manifests in ${options.org}...`,\n ).start();\n const discovery = await discoverAuroManifests(octokit, options.org);\n discoverySpinner.succeed(\n `Discovered ${discovery.totalMatches} Auro references across ${discovery.byRepo.size} repos.`,\n );\n\n // Map listed repos by name so we can filter discovery hits to non-archived\n // non-fork repos only. Anything in discovery but not in this map is implicitly\n // skipped (archived, fork, or otherwise excluded by listEcommerceRepos).\n const reposByName = new Map(repos.map((r) => [r.name, r]));\n\n let scanned = 0;\n let skipped = 0;\n let errored = 0;\n\n for (const [repoName, manifestPaths] of discovery.byRepo) {\n const repo = reposByName.get(repoName);\n if (!repo) continue; // archived / fork / outside scope\n\n const cached = cache.repos[repoName];\n if (\n !options.force &&\n cached?.scannedAt &&\n cached.pushedAt === repo.pushed_at\n ) {\n skipped++;\n continue;\n }\n\n const repoSpinner = ora(\n `Scanning ${repoName} (${manifestPaths.size} manifest${manifestPaths.size === 1 ? \"\" : \"s\"})...`,\n ).start();\n const entry = await scanRepo(octokit, options.org, repo, manifestPaths);\n cache.repos[repoName] = entry;\n\n if (entry.error) {\n repoSpinner.warn(`${repoName}: ${entry.error}`);\n errored++;\n } else {\n const auroDepCount = countAuroDeps(entry);\n repoSpinner.succeed(\n `${repoName}: ${auroDepCount} Auro deps across ${Object.keys(entry.packages).length} manifest${Object.keys(entry.packages).length === 1 ? \"\" : \"s\"}`,\n );\n }\n scanned++;\n }\n\n // Drop cache entries for repos no longer in discovery. Keeps the cache from\n // accumulating ghosts when a repo drops Auro deps entirely or gets archived.\n for (const cachedName of Object.keys(cache.repos)) {\n if (!discovery.byRepo.has(cachedName)) {\n delete cache.repos[cachedName];\n }\n }\n\n writeScanCache(cache, options.outputDir);\n\n const latestByPackage = await resolveLatestVersions(cache, archivedPackages);\n\n // One scanRunId stamped onto every finding in this run. Forward-compatible\n // with the SQLite migration in the compliance recommendation (rows in a\n // findings table joining to a scan_runs table by this id).\n const scanRunId = newRunId();\n const scannedAt = new Date().toISOString();\n const findings = buildComplianceFindings(\n cache,\n archivedPackages,\n latestByPackage,\n scanRunId,\n scannedAt,\n );\n writeComplianceFindings(findings, options.outputDir);\n\n const candidates = collapseCandidatesByPackage(\n cache,\n archivedPackages,\n latestByPackage,\n options.org,\n );\n writeUpgradeCandidates(candidates, options.outputDir);\n\n return {\n reposScanned: scanned,\n reposSkipped: skipped,\n reposErrored: errored,\n candidatesFound: candidates.length,\n findingsCount: findings.length,\n cachePath: displayPath(scanCachePath(options.outputDir)),\n candidatesPath: displayPath(upgradeCandidatesPath(options.outputDir)),\n findingsPath: displayPath(complianceFindingsPath(options.outputDir)),\n };\n}\n\ninterface RepoSummary {\n name: string;\n default_branch: string;\n pushed_at: string;\n language: string | null;\n}\n\nasync function listEcommerceRepos(\n octokit: Octokit,\n org: string,\n): Promise<RepoSummary[]> {\n const repos: RepoSummary[] = [];\n const iterator = octokit.paginate.iterator(octokit.rest.repos.listForOrg, {\n org,\n per_page: 100,\n type: \"all\",\n });\n\n for await (const { data } of iterator) {\n for (const repo of data) {\n if (repo.archived || repo.fork) continue;\n repos.push({\n name: repo.name,\n default_branch: repo.default_branch ?? \"main\",\n pushed_at: repo.pushed_at ?? \"\",\n language: repo.language ?? null,\n });\n }\n }\n\n return repos;\n}\n\nasync function fetchArchivedAuroPackages(\n octokit: Octokit,\n): Promise<Set<string>> {\n const archived = new Set<string>();\n const iterator = octokit.paginate.iterator(octokit.rest.repos.listForOrg, {\n org: AURO_ORG,\n per_page: 100,\n type: \"all\",\n });\n\n for await (const { data } of iterator) {\n for (const repo of data) {\n if (!repo.archived) continue;\n archived.add(`@aurodesignsystem/${repo.name}`);\n archived.add(`@alaskaairux/${repo.name}`);\n }\n }\n\n return archived;\n}\n\nasync function scanRepo(\n octokit: Octokit,\n org: string,\n repo: RepoSummary,\n manifestPaths: Set<string>,\n): Promise<RepoEntry> {\n const entry: RepoEntry = {\n name: repo.name,\n defaultBranch: repo.default_branch,\n pushedAt: repo.pushed_at,\n archived: false,\n language: repo.language,\n scannedAt: new Date().toISOString(),\n isMonorepo: manifestPaths.size > 1,\n packages: {},\n error: null,\n };\n\n for (const path of manifestPaths) {\n const manifest = await fetchPackageJson(\n octokit,\n org,\n repo.name,\n path,\n repo.default_branch,\n );\n if (!manifest) continue;\n entry.packages[path] = buildPackageScan(manifest, path);\n }\n\n // Code Search said this repo had Auro hits, but every fetch missed (renamed\n // file? deleted between index and fetch?). Record a soft error so the run\n // summary surfaces it without crashing the scan.\n if (Object.keys(entry.packages).length === 0) {\n entry.error = \"no-manifests-fetched\";\n }\n\n return entry;\n}\n\ninterface PackageJsonShape {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\nasync function fetchPackageJson(\n octokit: Octokit,\n owner: string,\n repo: string,\n filePath: string,\n ref: string,\n): Promise<PackageJsonShape | null> {\n try {\n const response = await octokit.rest.repos.getContent({\n owner,\n repo,\n path: filePath,\n ref,\n });\n if (Array.isArray(response.data) || response.data.type !== \"file\") {\n return null;\n }\n if (!(\"content\" in response.data) || !response.data.content) {\n return null;\n }\n const raw = Buffer.from(response.data.content, \"base64\").toString(\"utf8\");\n return JSON.parse(raw) as PackageJsonShape;\n } catch {\n return null;\n }\n}\n\nfunction buildPackageScan(\n pkg: PackageJsonShape,\n filePath: string,\n): PackageScan {\n const all = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n const auroDeps: Record<string, string> = {};\n for (const [name, version] of Object.entries(all)) {\n if (\n name.startsWith(\"@aurodesignsystem/\") ||\n name.startsWith(\"@alaskaairux/\")\n ) {\n auroDeps[name] = version;\n }\n }\n return {\n path: filePath,\n auroDeps,\n totalDeps: Object.keys(all).length,\n };\n}\n\nfunction countAuroDeps(entry: RepoEntry): number {\n let n = 0;\n for (const pkg of Object.values(entry.packages)) {\n n += Object.keys(pkg.auroDeps).length;\n }\n return n;\n}\n\n/**\n * Walks the cache once to collect every Auro package name (plus any\n * catalog `replacedBy` successors) and resolves their npm latest in\n * parallel. Returns a map suitable for both `buildComplianceFindings`\n * and `collapseCandidatesByPackage` \u2014 the npm calls are the slow part\n * of the run, so we make them once and feed both outputs.\n */\nasync function resolveLatestVersions(\n cache: ScanCache,\n archivedPackages: Set<string>,\n): Promise<Map<string, ResolvedLatest>> {\n const distinctPackages = new Set<string>();\n for (const repoEntry of Object.values(cache.repos)) {\n if (repoEntry.error || repoEntry.archived) continue;\n for (const pkgScan of Object.values(repoEntry.packages)) {\n for (const name of Object.keys(pkgScan.auroDeps)) {\n const policy = findPackagePolicy(name);\n // Archived packages with a catalog deprecation pointer (replacedBy)\n // are NOT skipped \u2014 the catalog tells consumers where to migrate, so\n // the ticket is still actionable. Archived without a successor in the\n // catalog stays skipped (we have nothing useful to recommend).\n if (archivedPackages.has(name) && !policy?.replacedBy) continue;\n distinctPackages.add(name);\n // Also resolve the successor's npm latest so deprecation tickets can\n // target it. In practice every successor is already in distinctPackages\n // (consumers declare it directly too), but seeding explicitly removes\n // the dependency on that incidental coverage.\n if (policy?.replacedBy) distinctPackages.add(policy.replacedBy);\n }\n }\n }\n\n const latestSpinner = ora(\n `Resolving latest npm versions for ${distinctPackages.size} Auro packages...`,\n ).start();\n const names = [...distinctPackages];\n const results = await Promise.all(\n names.map((name) => resolveLatestAcrossAliases(name)),\n );\n const latestByPackage = new Map<string, ResolvedLatest>(\n names.map((name, i) => [name, results[i]]),\n );\n latestSpinner.succeed(\n `Resolved ${latestByPackage.size} package versions on npm.`,\n );\n return latestByPackage;\n}\n\n/**\n * Pure helper extracted for testability. Iterates every (repo, manifest,\n * package) tuple in the cache and groups them into one candidate per\n * (repo, package). When the same package appears in multiple manifests\n * within one repo (BFF+Component, monorepos), the lowest pin wins \u2014\n * worst-case-behind drives the ticket urgency \u2014 and every manifest path\n * is recorded so the engineer knows to update them all.\n *\n * Without this, multi-manifest repos would generate duplicate ADO tickets\n * that the WIQL dedupe collapses anyway, producing noisy dry-run output\n * and wasted ticket-creation attempts under `--apply`.\n */\nexport function collapseCandidatesByPackage(\n cache: ScanCache,\n archivedPackages: Set<string>,\n latestByPackage: Map<string, ResolvedLatest>,\n org: string,\n): UpgradeCandidate[] {\n const byKey = new Map<string, UpgradeCandidate>();\n for (const repoEntry of Object.values(cache.repos)) {\n if (repoEntry.error || repoEntry.archived) continue;\n for (const pkgScan of Object.values(repoEntry.packages)) {\n for (const [name, pinned] of Object.entries(pkgScan.auroDeps)) {\n const evaluated = evaluateRepoPackage(\n name,\n pinned,\n archivedPackages,\n latestByPackage,\n );\n if (!evaluated) continue;\n // Candidates are the action subset: drop `Current` rows. Findings\n // keep them so dashboards can show \"you're on the latest.\"\n if (evaluated.status === \"Current\") continue;\n\n const key = `${repoEntry.name}|${name}`;\n const existing = byKey.get(key);\n if (existing) {\n if (!existing.manifestPaths) existing.manifestPaths = [];\n existing.manifestPaths.push(pkgScan.path);\n // Lower pin wins: re-evaluate the worse case so status,\n // majorsBehind, and statusReason reflect the most out-of-date\n // manifest in the repo.\n if ((compareSemver(pinned, existing.pinned) ?? 0) < 0) {\n const reEval = evaluateRepoPackage(\n name,\n pinned,\n archivedPackages,\n latestByPackage,\n );\n if (reEval && reEval.status !== \"Current\") {\n existing.pinned = pinned;\n existing.majorsBehind = reEval.majorsBehind;\n existing.status = reEval.status;\n existing.statusReason = reEval.statusReason;\n }\n }\n } else {\n const candidate: UpgradeCandidate = {\n repo: repoEntry.name,\n package: name,\n pinned,\n latest: evaluated.effectiveLatest,\n majorsBehind: evaluated.majorsBehind,\n repoUrl: `https://github.com/${org}/${repoEntry.name}`,\n manifestPaths: [pkgScan.path],\n status: evaluated.status,\n statusReason: evaluated.statusReason,\n };\n if (evaluated.targetPackage) {\n candidate.targetPackage = evaluated.targetPackage;\n }\n if (evaluated.policy?.notes) {\n candidate.notes = evaluated.policy.notes;\n }\n byKey.set(key, candidate);\n }\n }\n }\n }\n\n return [...byKey.values()];\n}\n", "import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { versionBotDir } from \"./cache.ts\";\nimport type { UpgradeCandidate } from \"./types.ts\";\n\nconst AUDIT_LOG_FILE = \"run-log.jsonl\";\n\nexport type AuditAction = \"created\" | \"closed\";\n\nexport interface AuditEntry {\n runId: string;\n timestamp: string;\n action: AuditAction;\n workItemId: number;\n workItemUrl: string;\n candidate: Pick<\n UpgradeCandidate,\n \"repo\" | \"package\" | \"pinned\" | \"latest\" | \"majorsBehind\"\n >;\n /** When action === \"created\": the work item this one replaces (close-and-recreate path). */\n supersedes?: number;\n /** When action === \"closed\": the new work item replacing this one. */\n replacedBy?: number;\n /** Optional human-readable note (e.g. cleanup reason). */\n note?: string;\n}\n\nexport function auditLogPath(dir?: string): string {\n return path.join(versionBotDir(dir), AUDIT_LOG_FILE);\n}\n\n/**\n * Generates a sortable, human-readable run id like `20260511T143200-a1b2c3`.\n * The timestamp prefix means `ls -1` lists runs chronologically; the hex\n * suffix disambiguates runs started in the same second.\n */\nexport function newRunId(): string {\n const now = new Date();\n const pad = (n: number, w = 2) => n.toString().padStart(w, \"0\");\n const stamp = [\n now.getUTCFullYear(),\n pad(now.getUTCMonth() + 1),\n pad(now.getUTCDate()),\n \"T\",\n pad(now.getUTCHours()),\n pad(now.getUTCMinutes()),\n pad(now.getUTCSeconds()),\n ].join(\"\");\n const suffix = crypto.randomBytes(3).toString(\"hex\");\n return `${stamp}-${suffix}`;\n}\n\nexport function appendAuditEntry(entry: AuditEntry, dir?: string): void {\n const filePath = auditLogPath(dir);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.appendFileSync(filePath, `${JSON.stringify(entry)}\\n`);\n}\n\nexport function readAuditEntries(dir?: string): AuditEntry[] {\n const filePath = auditLogPath(dir);\n if (!fs.existsSync(filePath)) {\n return [];\n }\n const raw = fs.readFileSync(filePath, \"utf8\");\n const entries: AuditEntry[] = [];\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n entries.push(JSON.parse(trimmed) as AuditEntry);\n } catch {\n // Skip malformed lines rather than crashing on a corrupted log.\n }\n }\n return entries;\n}\n\nexport function readAuditEntriesForRun(\n runId: string,\n dir?: string,\n): AuditEntry[] {\n return readAuditEntries(dir).filter((e) => e.runId === runId);\n}\n\nexport function listRunIds(dir?: string): string[] {\n const seen = new Set<string>();\n for (const entry of readAuditEntries(dir)) {\n seen.add(entry.runId);\n }\n return [...seen].sort();\n}\n\nexport function lastRunId(dir?: string): string | null {\n const ids = listRunIds(dir);\n return ids.length > 0 ? ids[ids.length - 1] : null;\n}\n", "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ComplianceFinding,\n ScanCache,\n UpgradeCandidate,\n} from \"./types.ts\";\n\nconst SCAN_CACHE_FILE = \"auro-deps-by-ecommerce-repo.json\";\nconst UPGRADE_CANDIDATES_FILE = \"auro-upgrade-candidates.json\";\nconst COMPLIANCE_FINDINGS_FILE = \"auro-compliance-findings.json\";\n\n/**\n * Default output dir for the version-bot \u2014 project-local under the cwd.\n * Matches the existing `.cache/` convention already in auro-cli's\n * .gitignore. Override at the CLI layer with --output-dir / --candidates.\n */\nconst DEFAULT_OUTPUT_SUBPATH = path.join(\".cache\", \"version-bot\");\n\nexport function defaultOutputDir(): string {\n return path.resolve(process.cwd(), DEFAULT_OUTPUT_SUBPATH);\n}\n\nfunction resolveOutputDir(dir?: string): string {\n return dir ? path.resolve(dir) : defaultOutputDir();\n}\n\nexport function versionBotDir(dir?: string): string {\n return resolveOutputDir(dir);\n}\n\nexport function scanCachePath(dir?: string): string {\n return path.join(resolveOutputDir(dir), SCAN_CACHE_FILE);\n}\n\nexport function upgradeCandidatesPath(dir?: string): string {\n return path.join(resolveOutputDir(dir), UPGRADE_CANDIDATES_FILE);\n}\n\nexport function complianceFindingsPath(dir?: string): string {\n return path.join(resolveOutputDir(dir), COMPLIANCE_FINDINGS_FILE);\n}\n\nfunction ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\nexport function readScanCache(dir?: string): ScanCache {\n const file = scanCachePath(dir);\n if (!fs.existsSync(file)) {\n return { version: 2, lastFullScan: null, repos: {} };\n }\n try {\n const parsed = JSON.parse(fs.readFileSync(file, \"utf8\")) as ScanCache;\n // v1 caches stored only the repo's root package.json. v2 indexes every\n // matching manifest path (including BFF/Component subdirectories). Older\n // caches are discarded rather than migrated \u2014 the next scan rebuilds them.\n if (parsed?.version === 2 && parsed.repos) {\n return parsed;\n }\n } catch {\n // Fall through to a fresh cache on malformed JSON.\n }\n return { version: 2, lastFullScan: null, repos: {} };\n}\n\nexport function writeScanCache(cache: ScanCache, dir?: string): void {\n ensureDir(resolveOutputDir(dir));\n cache.lastFullScan = new Date().toISOString();\n fs.writeFileSync(scanCachePath(dir), JSON.stringify(cache, null, 2));\n}\n\nexport function writeUpgradeCandidates(\n candidates: UpgradeCandidate[],\n dir?: string,\n): void {\n ensureDir(resolveOutputDir(dir));\n fs.writeFileSync(\n upgradeCandidatesPath(dir),\n JSON.stringify(candidates, null, 2),\n );\n}\n\nexport function readUpgradeCandidates(dir?: string): UpgradeCandidate[] {\n const file = upgradeCandidatesPath(dir);\n if (!fs.existsSync(file)) {\n throw new Error(\n `Upgrade candidates file not found at ${file}. Run \\`auro version-scan\\` first.`,\n );\n }\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as UpgradeCandidate[];\n}\n\nexport function writeComplianceFindings(\n findings: ComplianceFinding[],\n dir?: string,\n): void {\n ensureDir(resolveOutputDir(dir));\n fs.writeFileSync(\n complianceFindingsPath(dir),\n JSON.stringify(findings, null, 2),\n );\n}\n\nexport function readComplianceFindings(dir?: string): ComplianceFinding[] {\n const file = complianceFindingsPath(dir);\n if (!fs.existsSync(file)) {\n throw new Error(\n `Compliance findings file not found at ${file}. Run \\`auro version-scan\\` first.`,\n );\n }\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as ComplianceFinding[];\n}\n\n/**\n * Format a path for human display: prefer cwd-relative when the path is\n * inside the project, fall back to absolute otherwise.\n */\nexport function displayPath(filePath: string): string {\n const rel = path.relative(process.cwd(), filePath);\n if (!rel || rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n return filePath;\n }\n return `./${rel}`;\n}\n", "import type { PackagePolicyRecord } from \"./policy-catalog.ts\";\n\nexport type ComplianceStatus =\n | \"Behind\"\n | \"Current\"\n | \"Not used\"\n | \"Review needed\"\n | \"Unknown\"\n | \"Unsupported\";\n\nexport interface EvaluatePackageInput {\n declaredVersion?: string | null;\n detected: boolean;\n hasDeprecatedApiUsage?: boolean;\n packageName: string;\n}\n\nexport interface EvaluatePackageResult {\n packageName: string;\n reason: string;\n status: ComplianceStatus;\n}\n\nconst VERSION_RANGE_PREFIX = /^[\\^~>=<\\s]+/;\n\nconst parseVersion = (raw: string): number[] | null => {\n const cleaned = raw.replace(VERSION_RANGE_PREFIX, \"\").trim();\n const match = cleaned.match(/^(\\d+)\\.(\\d+)(?:\\.(\\d+))?/);\n if (!match) return null;\n return [\n Number.parseInt(match[1], 10),\n Number.parseInt(match[2], 10),\n match[3] !== undefined ? Number.parseInt(match[3], 10) : 0,\n ];\n};\n\nconst compareVersions = (a: number[], b: number[]): number => {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const av = a[i] ?? 0;\n const bv = b[i] ?? 0;\n if (av !== bv) return av > bv ? 1 : -1;\n }\n return 0;\n};\n\n/**\n * Pure-function compliance evaluator. Ported from auro-scan. Returns a\n * status for the (package, declared version, policy) tuple, with a short\n * human-readable reason that the version-bot surfaces in ticket bodies\n * and (eventually) compliance reports.\n *\n * The version-bot wires this in at scan time per (repo, package, manifest)\n * candidate. When no catalog policy exists for a package, the bot falls\n * back to majorsBehind-driven 'Behind' (handled at the call site, not here).\n */\nexport const evaluatePackage = (\n input: EvaluatePackageInput,\n policy: PackagePolicyRecord | undefined,\n): EvaluatePackageResult => {\n const { declaredVersion, detected, hasDeprecatedApiUsage, packageName } =\n input;\n\n if (!detected) {\n return {\n packageName,\n reason: \"No evidence of this package was found in the repository.\",\n status: \"Not used\",\n };\n }\n\n if (!policy) {\n return {\n packageName,\n reason: \"No policy record exists for this package.\",\n status: \"Unknown\",\n };\n }\n\n if (policy.replacedBy) {\n return {\n packageName,\n reason: `This package is deprecated. Migrate to ${policy.replacedBy}.`,\n status: \"Unsupported\",\n };\n }\n\n if (hasDeprecatedApiUsage) {\n return {\n packageName,\n reason:\n \"Deprecated API usage was detected. Review usage and migrate to supported APIs.\",\n status: \"Review needed\",\n };\n }\n\n if (!declaredVersion) {\n return {\n packageName,\n reason: \"Package was detected but no version could be determined.\",\n status: \"Unknown\",\n };\n }\n\n const version = parseVersion(declaredVersion);\n if (!version) {\n return {\n packageName,\n reason: `Could not parse declared version \"${declaredVersion}\".`,\n status: \"Unknown\",\n };\n }\n\n const { minimumVersion, targetVersion } = policy;\n\n if (minimumVersion) {\n const minimum = parseVersion(minimumVersion);\n if (minimum && compareVersions(version, minimum) < 0) {\n return {\n packageName,\n reason: `Version ${declaredVersion} is below the minimum supported version ${minimumVersion}.`,\n status: \"Unsupported\",\n };\n }\n }\n\n if (targetVersion) {\n const target = parseVersion(targetVersion);\n if (target && compareVersions(version, target) < 0) {\n return {\n packageName,\n reason: `Version ${declaredVersion} is behind the target version ${targetVersion}.`,\n status: \"Behind\",\n };\n }\n }\n\n return {\n packageName,\n reason: `Version ${declaredVersion} meets or exceeds the target version${targetVersion ? ` ${targetVersion}` : \"\"}.`,\n status: \"Current\",\n };\n};\n", "/**\n * Maps legacy `@alaskaairux/*` packages to their `@aurodesignsystem/*`\n * successors when the underlying library was republished under the new\n * scope. Used to cross-namespace the \"latest version\" resolution so a\n * consumer pinned on `@alaskaairux/auro-button@4` doesn't appear \"up to\n * date\" at the last `@alaskaairux` version when active development moved\n * to `@aurodesignsystem/auro-button` (currently at 12+).\n *\n * Hand-curated \u2014 not every legacy package migrated, and a couple stayed\n * under the original scope (e.g. `@alaskaairux/icons` is still the\n * canonical name; there's no `@aurodesignsystem/icons` on npm). Add a new\n * entry only after confirming both packages exist on the npm registry\n * AND the `@aurodesignsystem` side is actively published.\n */\nexport const PACKAGE_ALIASES: Readonly<Record<string, string>> = {\n \"@alaskaairux/auro-button\": \"@aurodesignsystem/auro-button\",\n \"@alaskaairux/auro-icon\": \"@aurodesignsystem/auro-icon\",\n \"@alaskaairux/auro-popover\": \"@aurodesignsystem/auro-popover\",\n};\n\n/**\n * Returns the `@aurodesignsystem` successor name for a legacy\n * `@alaskaairux` package if the migration is known, else null.\n */\nexport function aliasFor(pkg: string): string | null {\n return PACKAGE_ALIASES[pkg] ?? null;\n}\n", "import { aliasFor } from \"./aliases.ts\";\nimport type { SemverParts } from \"./types.ts\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org\";\nconst REQUEST_TIMEOUT_MS = 10_000;\n\n/**\n * Fetches the latest published version string for an npm package.\n * Returns null on network failure or unknown package \u2014 callers should treat\n * a null result as \"skip this package this run.\"\n */\nexport async function npmLatest(pkgName: string): Promise<string | null> {\n const url = `${NPM_REGISTRY}/${encodeURIComponent(pkgName)}/latest`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n\n try {\n const response = await fetch(url, { signal: controller.signal });\n if (!response.ok) {\n return null;\n }\n const body = (await response.json()) as { version?: string };\n return body.version ?? null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function parseSemver(\n value: string | null | undefined,\n): SemverParts | null {\n if (!value) {\n return null;\n }\n const stripped = String(value).replace(/^[\\^~>=<\\s]+/, \"\");\n const match = stripped.match(/^(\\d+)\\.(\\d+)\\.(\\d+)/);\n if (!match) {\n return null;\n }\n return {\n major: Number.parseInt(match[1], 10),\n minor: Number.parseInt(match[2], 10),\n patch: Number.parseInt(match[3], 10),\n };\n}\n\nexport function majorsBehind(pinned: string, latest: string | null): number {\n const p = parseSemver(pinned);\n const l = parseSemver(latest);\n if (!p || !l) {\n return 0;\n }\n return Math.max(0, l.major - p.major);\n}\n\nexport interface ResolvedLatest {\n /** The npm package name the returned version actually came from. Equals\n * the input package unless an alias produced a higher version. */\n resolvedPackage: string;\n /** Highest version seen across the input package and its alias (if any),\n * or null when both lookups failed. */\n version: string | null;\n}\n\n/**\n * Like `npmLatest`, but also consults `aliases.ts`. For an\n * `@alaskaairux/*` package with a known `@aurodesignsystem/*` successor,\n * looks up both and returns the higher version. Used by `scan.ts` so a\n * consumer pinned on a legacy-scope package is still cross-checked against\n * its new-scope successor.\n */\nexport async function resolveLatestAcrossAliases(\n pkgName: string,\n): Promise<ResolvedLatest> {\n const alias = aliasFor(pkgName);\n if (!alias) {\n return { resolvedPackage: pkgName, version: await npmLatest(pkgName) };\n }\n const [direct, aliased] = await Promise.all([\n npmLatest(pkgName),\n npmLatest(alias),\n ]);\n if (direct === null && aliased === null) {\n return { resolvedPackage: pkgName, version: null };\n }\n if (direct === null) return { resolvedPackage: alias, version: aliased };\n if (aliased === null) return { resolvedPackage: pkgName, version: direct };\n const cmp = compareSemver(direct, aliased);\n // If either side is unparseable, prefer the aliased (newer scope) version\n // since that's where active development lives.\n if (cmp === null) return { resolvedPackage: alias, version: aliased };\n return cmp < 0\n ? { resolvedPackage: alias, version: aliased }\n : { resolvedPackage: pkgName, version: direct };\n}\n\n/**\n * Compares two semver strings. Returns -1 / 0 / 1 in the standard sort order,\n * or null when either side is unparseable.\n */\nexport function compareSemver(\n a: string | null | undefined,\n b: string | null | undefined,\n): number | null {\n const pa = parseSemver(a);\n const pb = parseSemver(b);\n if (!pa || !pb) return null;\n if (pa.major !== pb.major) return pa.major < pb.major ? -1 : 1;\n if (pa.minor !== pb.minor) return pa.minor < pb.minor ? -1 : 1;\n if (pa.patch !== pb.patch) return pa.patch < pb.patch ? -1 : 1;\n return 0;\n}\n", "/**\n * Per-package policy catalog for the version-bot.\n *\n * Scope note: the catalog is a *policy* surface, not a *discovery* surface.\n * The bot continues to discover packages dynamically via namespace-prefix\n * match in scan.ts. Today the seed list carries 12 standing deprecations\n * (formkit successors + @alaskaairux retirements); all other packages\n * still ticket against npm latest.\n *\n * The `notes` field is the incident knob: an engineer can pin\n * `targetVersion` + add `notes` inline to roll the bot's recommendation\n * off a regressed release, with the notes rendering as a warning callout\n * in every ticket the bot files for that package.\n */\n\nexport interface PolicyException {\n expiresAt?: string;\n reason: string;\n repositoryPattern?: string;\n}\n\nexport interface PackagePolicyRecord {\n packageName: string;\n /** Pinned target version. When set, overrides npm latest in the bot. */\n targetVersion?: string;\n /** Versions below this are flagged Unsupported by evaluatePackage. */\n minimumVersion?: string;\n /** Successor package; presence flags this entry as Unsupported. */\n replacedBy?: string;\n exceptions?: PolicyException[];\n /**\n * Incident / advisory text. Renders as a warning callout above breaking\n * changes in the ticket body. Plain text; HTML-escaped at render time.\n * Example: \"Skip 13.0 \u2014 regression in focus-trap, see #1234.\"\n */\n notes?: string;\n}\n\n/**\n * Standing-deprecation seeds. All entries leave `targetVersion`,\n * `minimumVersion`, and `notes` unset \u2014 the bot still resolves the\n * target from npm latest and files normal upgrade tickets. The\n * `replacedBy` pointer tells `evaluatePackage` to surface these as\n * Unsupported so the ticket carries a `compliance-unsupported` tag.\n *\n * Engineers add `targetVersion`/`notes` inline during an incident; the\n * file is the only commit needed to roll the bot's recommendation off\n * a bad release.\n */\nexport const PACKAGE_POLICY_CATALOG: PackagePolicyRecord[] = [\n // Formkit successors \u2014 standalone packages superseded by @aurodesignsystem/auro-formkit.\n {\n packageName: \"@aurodesignsystem/auro-checkbox\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-combobox\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-datepicker\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-dropdown\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-form\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-input\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-menu\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-radio\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n {\n packageName: \"@aurodesignsystem/auro-select\",\n replacedBy: \"@aurodesignsystem/auro-formkit\",\n },\n\n // Legacy @alaskaairux/* retirements \u2014 scope migrations to @aurodesignsystem/*.\n // Note: @alaskaairux/icons is intentionally omitted (canonical legacy per\n // Decision 11; no successor). @aurodesignsystem/auro-counter is also omitted\n // pending confirmation with Lindsey that a standalone npm publish exists.\n {\n packageName: \"@alaskaairux/auro-button\",\n replacedBy: \"@aurodesignsystem/auro-button\",\n },\n {\n packageName: \"@alaskaairux/auro-icon\",\n replacedBy: \"@aurodesignsystem/auro-icon\",\n },\n {\n packageName: \"@alaskaairux/auro-popover\",\n replacedBy: \"@aurodesignsystem/auro-popover\",\n },\n];\n\nexport const findPackagePolicy = (\n packageName: string,\n): PackagePolicyRecord | undefined =>\n PACKAGE_POLICY_CATALOG.find((record) => record.packageName === packageName);\n", "import { type ComplianceStatus, evaluatePackage } from \"./evaluate.ts\";\nimport {\n compareSemver,\n majorsBehind,\n type ResolvedLatest,\n} from \"./npm-registry.ts\";\nimport {\n findPackagePolicy,\n type PackagePolicyRecord,\n} from \"./policy-catalog.ts\";\nimport type { ComplianceFinding, ScanCache } from \"./types.ts\";\n\n/**\n * Result of evaluating a single (package, pinned) tuple against the\n * catalog + npm resolver. Shared by candidates and findings \u2014 candidates\n * filter out `Current`, findings keep them.\n */\nexport interface EvaluatedTuple {\n policy: PackagePolicyRecord | undefined;\n /** Successor package name when the candidate should point consumers at\n * a different package (catalog.replacedBy OR cross-scope alias). */\n targetPackage: string | undefined;\n /** The version the bot recommends \u2014 successor's npm latest for\n * deprecation cases, `policy.targetVersion ?? npm latest` otherwise. */\n effectiveLatest: string;\n majorsBehind: number;\n status: ComplianceStatus;\n statusReason: string;\n}\n\n/**\n * Pure per-tuple evaluator. Returns null when the tuple should be\n * dropped entirely (archived without a catalog deprecation pointer, or\n * the relevant version couldn't be resolved on npm). Otherwise returns\n * the evaluated state, including `Current` rows \u2014 callers choose whether\n * to surface those.\n *\n * Extracted from scan.ts so candidates and findings share one source of\n * truth for the per-tuple decision: same status logic, same successor\n * pointer, same effectiveLatest computation. Without sharing, the two\n * outputs could drift on, say, the archived-with-replacedBy override or\n * the no-policy fallback to Behind vs Current.\n */\nexport function evaluateRepoPackage(\n name: string,\n pinned: string,\n archivedPackages: Set<string>,\n latestByPackage: Map<string, ResolvedLatest>,\n): EvaluatedTuple | null {\n const policy = findPackagePolicy(name);\n // Defer the archived filter when the catalog points at a successor:\n // the deprecation ticket is the value-add, and the body will direct\n // consumers at policy.replacedBy.\n if (archivedPackages.has(name) && !policy?.replacedBy) return null;\n\n let targetPackage: string | undefined;\n let effectiveLatest: string;\n if (policy?.replacedBy) {\n const successor = latestByPackage.get(policy.replacedBy);\n if (!successor?.version) return null;\n targetPackage = policy.replacedBy;\n effectiveLatest = successor.version;\n } else {\n const resolved = latestByPackage.get(name);\n if (!resolved?.version) return null;\n // The catalog's targetVersion is the incident knob: when an engineer\n // pins it (off a regressed release), the bot files tickets against\n // that pin instead of npm latest. With no catalog override, the\n // effective target is whatever npm currently calls latest.\n effectiveLatest = policy?.targetVersion ?? resolved.version;\n if (resolved.resolvedPackage !== name) {\n targetPackage = resolved.resolvedPackage;\n }\n }\n const mb = majorsBehind(pinned, effectiveLatest);\n\n const evalResult = evaluatePackage(\n { packageName: name, detected: true, declaredVersion: pinned },\n policy,\n );\n let status: ComplianceStatus = evalResult.status;\n let statusReason = evalResult.reason;\n // Uncataloged packages default to npm-latest-driven Behind/Current\n // rather than evaluatePackage's literal 'Unknown'. Without this, the\n // first deploy after wiring evaluatePackage in would flood\n // Unknown-tagged tickets for every uncataloged package the bot\n // currently ships tickets for.\n if (!policy) {\n if (mb >= 1) {\n status = \"Behind\";\n statusReason = `Version ${pinned} is behind npm latest (${effectiveLatest}).`;\n } else {\n status = \"Current\";\n statusReason = `Version ${pinned} matches the latest published major.`;\n }\n }\n\n return {\n policy,\n targetPackage,\n effectiveLatest,\n majorsBehind: mb,\n status,\n statusReason,\n };\n}\n\ninterface FindingInProgress {\n pinned: string;\n paths: string[];\n evaluated: EvaluatedTuple;\n}\n\n/**\n * Walks the cache once, evaluates every (repo, manifest, package) tuple,\n * collapses multi-manifest occurrences to one finding per (repo, package),\n * and returns every row \u2014 including `Current` \u2014 so downstream readers\n * (dashboards, Backstage, compliance reports) see the full picture, not\n * just the bot's action list.\n *\n * The collapse uses the lowest pin across manifests (worst-case-behind),\n * matching how candidates are produced. That choice means a repo with\n * `^11.5.0` in one manifest and `^7.2.0` in another reports the lower\n * pin's status, and `manifestPaths` carries both.\n */\nexport function buildComplianceFindings(\n cache: ScanCache,\n archivedPackages: Set<string>,\n latestByPackage: Map<string, ResolvedLatest>,\n scanRunId: string,\n scannedAt: string,\n): ComplianceFinding[] {\n const byKey = new Map<string, FindingInProgress>();\n for (const repoEntry of Object.values(cache.repos)) {\n if (repoEntry.error || repoEntry.archived) continue;\n for (const pkgScan of Object.values(repoEntry.packages)) {\n for (const [name, pinned] of Object.entries(pkgScan.auroDeps)) {\n const evaluated = evaluateRepoPackage(\n name,\n pinned,\n archivedPackages,\n latestByPackage,\n );\n if (!evaluated) continue;\n\n const key = `${repoEntry.name}|${name}`;\n const existing = byKey.get(key);\n if (existing) {\n existing.paths.push(pkgScan.path);\n // Lower pin wins: re-evaluate with the worse case so status and\n // majorsBehind reflect the most out-of-date manifest.\n if ((compareSemver(pinned, existing.pinned) ?? 0) < 0) {\n const reEval = evaluateRepoPackage(\n name,\n pinned,\n archivedPackages,\n latestByPackage,\n );\n if (reEval) {\n existing.pinned = pinned;\n existing.evaluated = reEval;\n }\n }\n } else {\n byKey.set(key, { pinned, paths: [pkgScan.path], evaluated });\n }\n }\n }\n }\n\n const findings: ComplianceFinding[] = [];\n for (const [key, entry] of byKey) {\n const sepIdx = key.indexOf(\"|\");\n const repository = key.slice(0, sepIdx);\n const packageName = key.slice(sepIdx + 1);\n findings.push({\n scanRunId,\n scannedAt,\n repository,\n packageName,\n declaredVersion: entry.pinned,\n resolvedVersion: null,\n targetVersion: entry.evaluated.policy?.targetVersion ?? null,\n minimumVersion: entry.evaluated.policy?.minimumVersion ?? null,\n status: entry.evaluated.status,\n statusReason: entry.evaluated.statusReason,\n majorsBehind: entry.evaluated.majorsBehind,\n successorPackage: entry.evaluated.targetPackage ?? null,\n notes: entry.evaluated.policy?.notes ?? null,\n manifestPaths: entry.paths,\n });\n }\n return findings;\n}\n", "import type { Octokit } from \"@octokit/rest\";\n\nconst AURO_NAMESPACES = [\"@aurodesignsystem\", \"@alaskaairux\"] as const;\n\nexport interface ManifestDiscoveryResult {\n byRepo: Map<string, Set<string>>;\n totalMatches: number;\n}\n\n/**\n * Discover every package.json in the org that references an Auro namespace.\n *\n * The pre-2026-05-15 scan only read each repo's root `package.json`, so it\n * silently missed BFF+Component patterns (`component/package.json`), microsite\n * subdirectories (`Website/m.alaskaair.com/package.json`), and any monorepo\n * workspace manifest. This function uses GitHub Code Search to find every\n * manifest containing an `@aurodesignsystem` or `@alaskaairux` reference,\n * grouped by repo so the scan can then fetch each one and parse its deps.\n *\n * Notes:\n * - Code Search has a 1000-item hard cap per query. Current org totals are\n * ~250 matches across both namespaces combined, so headroom is large.\n * If a single namespace ever crosses 1000, this function silently\n * undercounts \u2014 a follow-up can split queries by path prefix.\n * - Code Search index is eventually consistent (minutes-to-hours lag).\n * Acceptable for the quarterly scan cadence.\n */\nexport async function discoverAuroManifests(\n octokit: Octokit,\n org: string,\n): Promise<ManifestDiscoveryResult> {\n const byRepo = new Map<string, Set<string>>();\n let totalMatches = 0;\n\n for (const namespace of AURO_NAMESPACES) {\n const q = `${namespace} org:${org} in:file filename:package.json`;\n const iterator = octokit.paginate.iterator(octokit.rest.search.code, {\n q,\n per_page: 100,\n });\n\n for await (const { data } of iterator) {\n for (const item of data) {\n totalMatches++;\n const repoName = item.repository?.name;\n const path = item.path;\n if (!repoName || !path) continue;\n\n const paths = byRepo.get(repoName) ?? new Set<string>();\n paths.add(path);\n byRepo.set(repoName, paths);\n }\n }\n }\n\n return { byRepo, totalMatches };\n}\n", "import chalk from \"chalk\";\nimport { program } from \"commander\";\nimport { runCleanup } from \"#scripts/version-bot/cleanup.ts\";\nimport { runCreateTickets } from \"#scripts/version-bot/create-tickets.ts\";\n\ninterface VersionTicketsOptions {\n minMajors: string;\n apply: boolean;\n limit?: string;\n repo?: string;\n candidates?: string;\n previewDir?: string;\n tags: boolean;\n}\n\nexport const versionTicketsCommand = program\n .command(\"version-tickets\")\n .description(\n \"Create ADO User Stories for Auro upgrade candidates. Defaults to dry-run; pass --apply to actually write to ADO.\",\n )\n .option(\n \"--min-majors <n>\",\n \"Only ticket candidates at or above this majors-behind threshold\",\n \"2\",\n )\n .option(\n \"--apply\",\n \"Actually create tickets in ADO (otherwise dry-run)\",\n false,\n )\n .option(\"--limit <n>\", \"Maximum number of tickets to process this run\")\n .option(\"--repo <name>\", \"Only process candidates from this consumer repo\")\n .option(\n \"--candidates <file>\",\n \"Read candidates from a custom JSON file instead of the default ./.cache/version-bot/auro-upgrade-candidates.json\",\n )\n .option(\n \"--preview-dir <dir>\",\n \"During dry-run, write one styled HTML preview file per candidate to this directory\",\n )\n .option(\"--no-tags\", \"Skip setting System.Tags on created work items\")\n .action(async (options: VersionTicketsOptions) => {\n try {\n const minMajors = Number.parseInt(options.minMajors, 10);\n if (Number.isNaN(minMajors) || minMajors < 1) {\n throw new Error(\"--min-majors must be an integer >= 1\");\n }\n const limit =\n options.limit !== undefined\n ? Number.parseInt(options.limit, 10)\n : undefined;\n if (limit !== undefined && (Number.isNaN(limit) || limit < 1)) {\n throw new Error(\"--limit must be an integer >= 1\");\n }\n\n const summary = await runCreateTickets({\n minMajors,\n apply: options.apply,\n limit,\n repo: options.repo,\n candidatesPath: options.candidates,\n previewDir: options.previewDir,\n noTags: !options.tags,\n });\n\n console.log(\"\");\n console.log(\n chalk.bold(options.apply ? \"Tickets applied.\" : \"Dry run complete.\"),\n );\n console.log(` Total candidates in JSON: ${summary.totalCandidates}`);\n console.log(` After filters: ${summary.afterFilter}`);\n console.log(\n ` Skipped (no usage): ${chalk.dim(summary.notUsedSkipped)}`,\n );\n if (options.apply) {\n console.log(\n ` Applied: ${chalk.green(summary.applied)} failed: ${chalk.red(summary.failed)}`,\n );\n console.log(\n ` Dedupe: ${chalk.yellow(summary.dedupeSkipped)} skipped, ${chalk.magenta(summary.dedupeReplaced)} replaced`,\n );\n console.log(` run-id: ${chalk.dim(summary.runId)}`);\n console.log(\n chalk.dim(\n \"\\n To roll back this run: auro version-tickets cleanup --run-id \" +\n summary.runId,\n ),\n );\n } else {\n console.log(` Dry-run printed: ${chalk.cyan(summary.dryRun)}`);\n console.log(\n chalk.dim(\n \"\\n Re-run with --apply to actually create tickets in ADO.\",\n ),\n );\n }\n } catch (error) {\n console.error(\n chalk.red(\n `version-tickets failed: ${error instanceof Error ? error.message : error}`,\n ),\n );\n process.exit(1);\n }\n });\n\ninterface CleanupCliOptions {\n apply: boolean;\n runId?: string;\n last?: boolean;\n list?: boolean;\n}\n\nversionTicketsCommand\n .command(\"cleanup\")\n .description(\n \"Close (state=Removed) work items created by a prior `version-tickets --apply` run. Dry-run by default.\",\n )\n .option(\"--run-id <id>\", \"Target a specific run id from the audit log\")\n .option(\"--last\", \"Target the most recent run id\", false)\n .option(\"--list\", \"List available run ids and exit (no writes)\", false)\n .option(\"--apply\", \"Actually close tickets in ADO (otherwise dry-run)\", false)\n .action(async (options: CleanupCliOptions) => {\n try {\n const summary = await runCleanup({\n apply: options.apply,\n runId: options.runId,\n last: options.last,\n list: options.list,\n });\n if (options.list) return;\n\n console.log(\"\");\n console.log(\n chalk.bold(options.apply ? \"Cleanup complete.\" : \"Dry run complete.\"),\n );\n console.log(` Eligible: ${summary.candidates}`);\n if (options.apply) {\n console.log(\n ` Closed: ${chalk.green(summary.closed)} failed: ${chalk.red(summary.failed)}`,\n );\n console.log(` run-id: ${chalk.dim(summary.cleanupRunId)}`);\n } else {\n console.log(` Dry-run printed: ${chalk.cyan(summary.skipped)}`);\n console.log(\n chalk.dim(\n \"\\n Re-run with --apply to actually close tickets in ADO.\",\n ),\n );\n }\n } catch (error) {\n console.error(\n chalk.red(\n `cleanup failed: ${error instanceof Error ? error.message : error}`,\n ),\n );\n process.exit(1);\n }\n });\n", "import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { closeADOWorkItem } from \"#scripts/ado/index.ts\";\nimport {\n type AuditEntry,\n appendAuditEntry,\n lastRunId,\n listRunIds,\n newRunId,\n readAuditEntries,\n readAuditEntriesForRun,\n} from \"./audit-log.ts\";\n\nexport interface CleanupOptions {\n /** If true, do real ADO writes. Defaults false (dry-run). */\n apply: boolean;\n /** Specific run id to clean up. Mutually exclusive with `last`. */\n runId?: string;\n /** When true, resolve to the most recent run id from the audit log. */\n last?: boolean;\n /** When true, just list available run ids and exit. */\n list?: boolean;\n}\n\nexport interface CleanupSummary {\n /** The new run id under which cleanup actions are recorded. */\n cleanupRunId: string;\n /** The run id being cleaned up (the original `--apply` run). */\n targetRunId: string | null;\n candidates: number;\n closed: number;\n skipped: number;\n failed: number;\n}\n\n/**\n * Resolves the target run id from the options, surfacing helpful errors\n * when the log is empty or the id isn't found.\n */\nfunction resolveTargetRunId(options: CleanupOptions): string {\n if (options.runId && options.last) {\n throw new Error(\"Pass either --run-id <id> or --last, not both.\");\n }\n if (options.last) {\n const id = lastRunId();\n if (!id) {\n throw new Error(\n \"No prior runs found in the audit log (no `version-tickets --apply` has run yet).\",\n );\n }\n return id;\n }\n if (!options.runId) {\n throw new Error(\n \"Pass --run-id <id> to target a specific run, or --last for the most recent.\",\n );\n }\n const known = new Set(listRunIds());\n if (!known.has(options.runId)) {\n const sample = [...known].slice(-3).join(\", \");\n throw new Error(\n `Unknown run id \"${options.runId}\". Recent run ids: ${sample || \"(none)\"}.`,\n );\n }\n return options.runId;\n}\n\n/**\n * Returns the work items created in `targetRunId` that haven't already been\n * closed (either by an earlier cleanup or by close-and-recreate dedupe).\n */\nfunction selectClosable(targetRunId: string): AuditEntry[] {\n const allEntries = readAuditEntries();\n const closedIds = new Set<number>();\n for (const e of allEntries) {\n if (e.action === \"closed\") closedIds.add(e.workItemId);\n }\n return readAuditEntriesForRun(targetRunId).filter(\n (e) => e.action === \"created\" && !closedIds.has(e.workItemId),\n );\n}\n\nexport async function runCleanup(\n options: CleanupOptions,\n): Promise<CleanupSummary> {\n if (options.list) {\n const ids = listRunIds();\n console.log(chalk.bold(`Run ids in audit log (${ids.length}):`));\n for (const id of ids) {\n const entries = readAuditEntriesForRun(id);\n const created = entries.filter((e) => e.action === \"created\").length;\n console.log(` ${id} (${created} ticket${created === 1 ? \"\" : \"s\"})`);\n }\n return {\n cleanupRunId: \"(none \u2014 list mode)\",\n targetRunId: null,\n candidates: 0,\n closed: 0,\n skipped: 0,\n failed: 0,\n };\n }\n\n const targetRunId = resolveTargetRunId(options);\n const closable = selectClosable(targetRunId);\n const cleanupRunId = newRunId();\n const summary: CleanupSummary = {\n cleanupRunId,\n targetRunId,\n candidates: closable.length,\n closed: 0,\n skipped: 0,\n failed: 0,\n };\n\n console.log(chalk.bold(`Cleanup target: ${targetRunId}`));\n console.log(\n ` ${closable.length} ticket${closable.length === 1 ? \"\" : \"s\"} eligible for removal`,\n );\n\n if (closable.length === 0) {\n console.log(\n chalk.dim(\n \" Nothing to do \u2014 every ticket in this run is already closed.\",\n ),\n );\n return summary;\n }\n\n if (options.apply) {\n console.log(chalk.dim(`run-id: ${cleanupRunId}`));\n }\n\n for (const entry of closable) {\n const label = `#${entry.workItemId} (${entry.candidate.package} in ${entry.candidate.repo})`;\n if (!options.apply) {\n console.log(` ${chalk.cyan(\"[DRY RUN]\")} would close ${label}`);\n summary.skipped++;\n continue;\n }\n const spinner = ora(`Closing ${label}...`).start();\n try {\n await closeADOWorkItem({\n id: entry.workItemId,\n comment: `Removed by \\`auro version-tickets cleanup\\` on ${new Date().toISOString().slice(0, 10)} (cleanup run-id ${cleanupRunId}; original run ${targetRunId}).`,\n });\n spinner.succeed(`Closed ${label}`);\n appendAuditEntry({\n runId: cleanupRunId,\n timestamp: new Date().toISOString(),\n action: \"closed\",\n workItemId: entry.workItemId,\n workItemUrl: entry.workItemUrl,\n candidate: entry.candidate,\n note: `cleanup of run ${targetRunId}`,\n });\n summary.closed++;\n } catch (error) {\n spinner.fail(\n `${label} \u2014 ${error instanceof Error ? error.message : error}`,\n );\n summary.failed++;\n }\n }\n\n return summary;\n}\n", "import fs from \"node:fs\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { closeADOWorkItem, createADOWorkItem } from \"#scripts/ado/index.ts\";\nimport {\n findOpenBotTickets,\n type OpenBotTicket,\n parseLatestFromTitle,\n} from \"#scripts/ado/wiql.ts\";\nimport { appendAuditEntry, newRunId } from \"./audit-log.ts\";\nimport { readUpgradeCandidates } from \"./cache.ts\";\nimport {\n type BreakingChange,\n extractBreakingChanges,\n fetchChangelogStructured,\n} from \"./changelog.ts\";\nimport { writePreviewFile } from \"./html-preview.ts\";\nimport { compareSemver } from \"./npm-registry.ts\";\nimport {\n buildAcceptanceCriteria,\n buildStoryBody,\n buildStoryTitle,\n} from \"./template.ts\";\nimport type { ComplianceStatus, UpgradeCandidate } from \"./types.ts\";\nimport { findUsageInRepo } from \"./usage-inventory.ts\";\n\nexport interface CreateTicketsOptions {\n minMajors: number;\n apply: boolean;\n limit?: number;\n repo?: string;\n candidatesPath?: string;\n previewDir?: string;\n noTags?: boolean;\n}\n\nexport interface CreateTicketsSummary {\n runId: string;\n totalCandidates: number;\n afterFilter: number;\n applied: number;\n dryRun: number;\n failed: number;\n /** Skipped because an open bot ticket already covers the same `latest`. */\n dedupeSkipped: number;\n /** Closed-and-recreated because an open bot ticket was behind the new `latest`. */\n dedupeReplaced: number;\n /**\n * Candidates dropped pre-loop because GitHub Code Search found zero\n * references to the package in the repo \u2014 the dep is declared but dead.\n * `null` usage results (missing GH_TOKEN, search failed) are NOT counted\n * here; they pass through to the ticket-creation path so transient\n * failures don't silently suppress tickets.\n */\n notUsedSkipped: number;\n}\n\nexport async function runCreateTickets(\n options: CreateTicketsOptions,\n): Promise<CreateTicketsSummary> {\n const all = options.candidatesPath\n ? readCandidatesFromPath(options.candidatesPath)\n : readUpgradeCandidates();\n const filtered = all.filter((c) => {\n if (c.majorsBehind < options.minMajors) return false;\n if (options.repo && c.repo !== options.repo) return false;\n return true;\n });\n\n // Not-used filter runs BEFORE `--limit` so the cap reflects post-filter\n // candidates. Skipped candidates won't burn slots, and the filter populates\n // the findUsageInRepo cache so processCandidate's later call is free.\n const { kept, notUsedSkipped } = await applyNotUsedFilter(filtered);\n const selected =\n options.limit !== undefined ? kept.slice(0, options.limit) : kept;\n\n const runId = newRunId();\n const summary: CreateTicketsSummary = {\n runId,\n totalCandidates: all.length,\n afterFilter: kept.length,\n applied: 0,\n dryRun: 0,\n failed: 0,\n dedupeSkipped: 0,\n dedupeReplaced: 0,\n notUsedSkipped,\n };\n\n if (options.apply) {\n console.log(chalk.dim(`run-id: ${runId}`));\n }\n\n for (const candidate of selected) {\n await processCandidate(candidate, options, summary);\n }\n\n return summary;\n}\n\nfunction readCandidatesFromPath(filePath: string): UpgradeCandidate[] {\n if (!fs.existsSync(filePath)) {\n throw new Error(`Candidates file not found: ${filePath}`);\n }\n return JSON.parse(fs.readFileSync(filePath, \"utf8\")) as UpgradeCandidate[];\n}\n\nasync function processCandidate(\n candidate: UpgradeCandidate,\n options: CreateTicketsOptions,\n summary: CreateTicketsSummary,\n): Promise<void> {\n const title = buildStoryTitle(candidate);\n const changelogUrl = buildChangelogUrl(candidate.package);\n const tags = options.noTags ? [] : buildTags(candidate);\n\n const fetchSpinner = ora(\n `Fetching changelog for ${candidate.package}...`,\n ).start();\n const changelogSlice = await fetchChangelogStructured(\n candidate.package,\n candidate.pinned,\n candidate.latest,\n );\n fetchSpinner.stop();\n const breakingChanges: BreakingChange[] = changelogSlice\n ? extractBreakingChanges(changelogSlice)\n : [];\n\n const usage = await fetchUsageInventory(candidate);\n\n // Dry-run: print preview + return. WIQL/ADO writes only happen in --apply.\n if (!options.apply) {\n const { descriptionHtml, usedChangelogSlice } = buildBodyWithinLimit(\n {\n candidate,\n changelogSlice,\n changelogUrl,\n breakingChanges,\n usage,\n },\n title,\n );\n const acceptanceCriteriaHtml = buildAcceptanceCriteria(\n candidate,\n breakingChanges,\n );\n console.log(\"\");\n console.log(chalk.bold.cyan(`[DRY RUN] ${title}`));\n console.log(` ${chalk.dim(\"tags:\")} ${tags.join(\", \")}`);\n console.log(\n ` ${chalk.dim(\"changelog:\")} ${usedChangelogSlice ? chalk.green(\"inlined\") : chalk.yellow(\"link only\")}`,\n );\n console.log(\n ` ${chalk.dim(\"breaking:\")} ${breakingChanges.length} change${breakingChanges.length === 1 ? \"\" : \"s\"} detected`,\n );\n console.log(\n ` ${chalk.dim(\"usage:\")} ${usage ? `${usage.totalCount} file${usage.totalCount === 1 ? \"\" : \"s\"} reference${usage.totalCount === 1 ? \"s\" : \"\"} this package` : \"(not searched)\"}`,\n );\n console.log(` ${chalk.dim(\"body:\")} ${descriptionHtml.length} chars`);\n console.log(\n ` ${chalk.dim(\"AC:\")} ${acceptanceCriteriaHtml.length} chars`,\n );\n if (options.previewDir) {\n const filePath = writePreviewFile(options.previewDir, {\n candidate,\n title,\n bodyHtml: descriptionHtml,\n acceptanceCriteriaHtml,\n tags,\n changelogInlined: usedChangelogSlice,\n });\n console.log(` ${chalk.dim(\"preview:\")} ${filePath}`);\n }\n summary.dryRun++;\n return;\n }\n\n // --apply path: dedupe gate first, then create (or close-and-recreate).\n const dedupe = await resolveDedupeAction(candidate);\n if (dedupe.action === \"skip\") {\n console.log(\n chalk.yellow(\n ` \u21A9 Skipped (dupe of #${dedupe.existing.id}): ${candidate.repo} / ${candidate.package}`,\n ),\n );\n summary.dedupeSkipped++;\n return;\n }\n\n const supersedes =\n dedupe.action === \"replace\" ? dedupe.existing.id : undefined;\n const { descriptionHtml } = buildBodyWithinLimit(\n {\n candidate,\n changelogSlice,\n changelogUrl,\n breakingChanges,\n usage,\n supersedes,\n },\n title,\n );\n const acceptanceCriteriaHtml = buildAcceptanceCriteria(\n candidate,\n breakingChanges,\n );\n\n const spinner = ora(`Creating: ${title}`).start();\n try {\n const workItem = await createADOWorkItem({\n title,\n descriptionHtml,\n acceptanceCriteriaHtml,\n tags,\n });\n const newId = workItem.id;\n const url = workItem._links?.html?.href ?? \"(no URL returned)\";\n if (typeof newId !== \"number\") {\n spinner.fail(`${title} - work item create returned no id`);\n summary.failed++;\n return;\n }\n spinner.succeed(`Created #${newId} -> ${url}`);\n summary.applied++;\n appendAuditEntry({\n runId: summary.runId,\n timestamp: new Date().toISOString(),\n action: \"created\",\n workItemId: newId,\n workItemUrl: url,\n candidate: {\n repo: candidate.repo,\n package: candidate.package,\n pinned: candidate.pinned,\n latest: candidate.latest,\n majorsBehind: candidate.majorsBehind,\n },\n supersedes,\n });\n\n if (dedupe.action === \"replace\") {\n const oldId = dedupe.existing.id;\n const closeSpinner = ora(`Closing superseded #${oldId}...`).start();\n try {\n await closeADOWorkItem({\n id: oldId,\n comment: `Closed because a newer version of ${candidate.package} has shipped (now at ${candidate.latest}). Replaced by #${newId}: ${url}`,\n });\n closeSpinner.succeed(`Closed superseded #${oldId}`);\n summary.dedupeReplaced++;\n appendAuditEntry({\n runId: summary.runId,\n timestamp: new Date().toISOString(),\n action: \"closed\",\n workItemId: oldId,\n workItemUrl: dedupe.existing.url,\n candidate: {\n repo: candidate.repo,\n package: candidate.package,\n pinned: candidate.pinned,\n latest: candidate.latest,\n majorsBehind: candidate.majorsBehind,\n },\n replacedBy: newId,\n note: \"close-and-recreate\",\n });\n } catch (error) {\n closeSpinner.fail(\n `Failed to close superseded #${oldId} \u2014 ${error instanceof Error ? error.message : error}`,\n );\n // Don't fail the candidate: the new ticket was created successfully.\n }\n }\n } catch (error) {\n spinner.fail(\n `${title} - ${error instanceof Error ? error.message : error}`,\n );\n console.log(chalk.dim(` retry candidate: ${JSON.stringify([candidate])}`));\n console.log(\n chalk.dim(\n \" (save that JSON line to a file, then re-run with --candidates <file>)\",\n ),\n );\n summary.failed++;\n }\n}\n\ntype DedupeAction =\n | { action: \"create\" }\n | { action: \"skip\"; existing: OpenBotTicket }\n | { action: \"replace\"; existing: OpenBotTicket };\n\n/**\n * Decides what to do with a candidate given any open bot tickets that\n * already exist for the same (repo, package):\n *\n * - No match \u2192 create\n * - Match in any non-`New` state (Active/Resolved/etc.) \u2192 skip (don't\n * disturb in-progress work)\n * - Match in `New` state with title-latest >= current latest \u2192 skip (dupe)\n * - Match in `New` state with title-latest < current latest \u2192 replace\n * (close old, create new with supersedes link)\n * - Match whose title doesn't parse \u2192 skip (treat as hand-edited, avoid\n * stomping)\n */\nasync function resolveDedupeAction(\n candidate: UpgradeCandidate,\n): Promise<DedupeAction> {\n let existing: OpenBotTicket[];\n try {\n existing = await findOpenBotTickets({\n repo: candidate.repo,\n pkg: candidate.package,\n });\n } catch (error) {\n console.log(\n chalk.yellow(\n ` \u26A0 Dedupe check failed (${error instanceof Error ? error.message : error}). Proceeding with create.`,\n ),\n );\n return { action: \"create\" };\n }\n if (existing.length === 0) return { action: \"create\" };\n\n // If multiple matches, prefer the most recent (highest id) and let the\n // user clean up the older ones manually with `cleanup` if needed.\n const target = existing.reduce((a, b) => (a.id >= b.id ? a : b));\n\n if (target.state !== \"New\") {\n return { action: \"skip\", existing: target };\n }\n const existingLatest = parseLatestFromTitle(target.title);\n if (!existingLatest) {\n // Hand-edited title \u2014 be conservative and skip rather than stomp.\n return { action: \"skip\", existing: target };\n }\n const cmp = compareSemver(existingLatest, candidate.latest);\n if (cmp === null) return { action: \"skip\", existing: target };\n if (cmp >= 0) return { action: \"skip\", existing: target };\n return { action: \"replace\", existing: target };\n}\n\nfunction buildChangelogUrl(pkg: string): string {\n const shortName = pkg.replace(/^@[^/]+\\//, \"\");\n return `https://github.com/AlaskaAirlines/${shortName}/blob/main/CHANGELOG.md`;\n}\n\n/**\n * Base tags plus a `compliance-<status>` tag for any non-`Behind` status.\n * `Behind` is the bot's default \u2014 tagging it would mean every ticket is\n * tagged, which adds no signal. `Unsupported` / `Review needed` / etc.\n * carry real information that the ADO query can filter on.\n */\nfunction buildTags(candidate: UpgradeCandidate): string[] {\n const tags = [\"auro\", \"version-upgrade\"];\n // `majors-behind-N` is meaningful for upgrades within the same package.\n // For deprecation tickets (Unsupported), the old and new packages are\n // different versions of different things \u2014 the number is misleading.\n // The `compliance-unsupported` tag carries the real signal there.\n if (candidate.status !== \"Unsupported\") {\n tags.push(`majors-behind-${candidate.majorsBehind}`);\n }\n if (candidate.status && candidate.status !== \"Behind\") {\n tags.push(`compliance-${complianceTagSlug(candidate.status)}`);\n }\n return tags;\n}\n\nfunction complianceTagSlug(status: ComplianceStatus): string {\n return status.toLowerCase().replace(/ /g, \"-\");\n}\n\n/**\n * Drops candidates whose package has zero GitHub Code Search hits in the\n * consumer repo. The dep is declared in package.json but never imported \u2014\n * filing a ticket would point the engineer at dead code. `null` results\n * (missing GH_TOKEN, search failed) pass through so transient failures\n * don't silently suppress tickets.\n *\n * Side effect: warms findUsageInRepo's per-process cache. The same\n * (org, repo, packages-key) lookup inside processCandidate is then a\n * cache hit, so no API calls are duplicated.\n */\nasync function applyNotUsedFilter(\n candidates: UpgradeCandidate[],\n): Promise<{ kept: UpgradeCandidate[]; notUsedSkipped: number }> {\n const kept: UpgradeCandidate[] = [];\n let notUsedSkipped = 0;\n for (const candidate of candidates) {\n const usage = await fetchUsageInventory(candidate);\n if (usage && usage.totalCount === 0) {\n notUsedSkipped++;\n continue;\n }\n kept.push(candidate);\n }\n return { kept, notUsedSkipped };\n}\n\n/**\n * Pulls org/repo from `candidate.repoUrl` and queries GitHub Code Search.\n * Searches for both the consumer's pinned package name AND the\n * `targetPackage` (when cross-namespace) so usage is counted across the\n * scope swap. Returns null on any failure \u2014 the body just omits the\n * \"Where this package is used\" section.\n */\nasync function fetchUsageInventory(\n candidate: UpgradeCandidate,\n): Promise<Awaited<ReturnType<typeof findUsageInRepo>>> {\n let org: string;\n let repo: string;\n try {\n const url = new URL(candidate.repoUrl);\n const segments = url.pathname.split(\"/\").filter(Boolean);\n if (segments.length < 2) return null;\n [org, repo] = segments;\n } catch {\n return null;\n }\n const packages = candidate.targetPackage\n ? [candidate.package, candidate.targetPackage]\n : [candidate.package];\n return findUsageInRepo({ org, repo, packages });\n}\n\n// ADO accepts up to ~1 MB for System.Description, but rendering performance\n// suffers well before that. When the inlined CHANGELOG slice pushes a body\n// over MAX_BODY_LENGTH, we rebuild without the slice \u2014 the template falls\n// back to a link-only migration section. Breaking-change extraction is\n// unaffected (we already pulled it out of the slice into `breakingChanges`\n// before this guard runs), so the AC bullets remain CHANGELOG-aware.\nconst MAX_BODY_LENGTH = 50_000;\n\nfunction buildBodyWithinLimit(\n input: Parameters<typeof buildStoryBody>[0],\n title: string,\n): { descriptionHtml: string; usedChangelogSlice: boolean } {\n const initial = buildStoryBody(input);\n const hadSlice = input.changelogSlice !== null;\n if (initial.length <= MAX_BODY_LENGTH || !hadSlice) {\n return { descriptionHtml: initial, usedChangelogSlice: hadSlice };\n }\n const fallback = buildStoryBody({ ...input, changelogSlice: null });\n console.log(\n chalk.yellow(\n ` \u26A0 ${title}: body was ${initial.length} chars with the inlined CHANGELOG (> ${MAX_BODY_LENGTH}). Dropped the slice; body is now ${fallback.length} chars with link-only migration section. Breaking-change AC bullets are preserved.`,\n ),\n );\n return { descriptionHtml: fallback, usedChangelogSlice: false };\n}\n", "import * as azdev from \"azure-devops-node-api\";\nimport type { WorkItem } from \"azure-devops-node-api/interfaces/WorkItemTrackingInterfaces.js\";\n\nconst ADO_ORG_URL = \"https://dev.azure.com/itsals\";\nconst ADO_PROJECT_NAME = \"E_Retain_Content\";\nconst ADO_AREA_PATH = \"E_Retain_Content\\\\Auro Design System\";\n\nexport interface OpenBotTicket {\n id: number;\n title: string;\n state: string;\n url: string;\n}\n\n/**\n * Returns open upgrade tickets that match a given (repo, package) pair.\n * \"Open\" means not Removed/Closed/Done. Matching is anchored on the Auro\n * area path plus title substrings for both the repo and package, which is\n * narrow enough that an unrelated ticket would almost never collide.\n *\n * Manual tickets that happen to contain both substrings are also returned;\n * the caller filters them out via `parseLatestFromTitle` (manual titles\n * don't match the bot's `<pinned> -> <latest>` regex, so they're treated\n * as \"skip\" rather than overwritten).\n */\nexport async function findOpenBotTickets({\n repo,\n pkg,\n}: {\n repo: string;\n pkg: string;\n}): Promise<OpenBotTicket[]> {\n const adoToken = process.env.ADO_TOKEN;\n if (!adoToken) {\n throw new Error(\"ADO_TOKEN environment variable is required\");\n }\n\n const authHandler = azdev.getPersonalAccessTokenHandler(adoToken);\n const connection = new azdev.WebApi(ADO_ORG_URL, authHandler);\n const api = await connection.getWorkItemTrackingApi();\n\n // WIQL string-literal escaping: single quotes get doubled. Project/area\n // path are constants we control so they don't need escaping.\n const escape = (s: string) => s.replace(/'/g, \"''\");\n const wiql = {\n query: `\n SELECT [System.Id] FROM WorkItems\n WHERE [System.TeamProject] = '${ADO_PROJECT_NAME}'\n AND [System.AreaPath] UNDER '${ADO_AREA_PATH}'\n AND [System.WorkItemType] = 'User Story'\n AND [System.State] <> 'Removed'\n AND [System.State] <> 'Closed'\n AND [System.State] <> 'Done'\n AND [System.Title] CONTAINS '${escape(pkg)}'\n AND [System.Title] CONTAINS '${escape(repo)}'\n `,\n };\n\n const result = await api.queryByWiql(wiql, { project: ADO_PROJECT_NAME });\n const ids =\n result.workItems\n ?.map((w) => w.id)\n .filter((id): id is number => typeof id === \"number\") ?? [];\n if (ids.length === 0) return [];\n\n const items: WorkItem[] = await api.getWorkItems(\n ids,\n [\"System.Id\", \"System.Title\", \"System.State\"],\n undefined,\n undefined,\n undefined,\n ADO_PROJECT_NAME,\n );\n return items.map((item) => ({\n id: item.id ?? 0,\n title: (item.fields?.[\"System.Title\"] as string) ?? \"\",\n state: (item.fields?.[\"System.State\"] as string) ?? \"\",\n url: item._links?.html?.href ?? \"\",\n }));\n}\n\n/**\n * Parses the `latest` version from a bot-generated title like\n * `Upgrade <pkg> in <repo> (<pinned> -> <latest>, N major(s) behind)`\n * Returns null if the title doesn't match the expected format (e.g. a\n * hand-edited title).\n */\nexport function parseLatestFromTitle(title: string): string | null {\n const m = title.match(/\\(\\s*([\\d.]+)\\s*->\\s*([\\d.]+)\\s*,/);\n return m ? m[2] : null;\n}\n", "import { Octokit } from \"@octokit/rest\";\nimport { parseSemver } from \"./npm-registry.ts\";\nimport type { SemverParts } from \"./types.ts\";\n\nconst REPO_OWNER = \"AlaskaAirlines\";\nconst sliceCache = new Map<string, ChangelogSlice | null>();\n\nexport type ChangelogSectionType =\n | \"features\"\n | \"bugFixes\"\n | \"breakingChanges\"\n | \"other\";\n\nexport interface ChangelogSection {\n type: ChangelogSectionType;\n /** Original heading text from the CHANGELOG (e.g. \"Bug Fixes\"). */\n title: string;\n /** Plain-text bullets with semantic-release PR/commit suffixes stripped. */\n bullets: string[];\n}\n\nexport interface ChangelogVersionSlice {\n version: string;\n dateStr: string | null;\n sections: ChangelogSection[];\n}\n\nexport interface ChangelogSlice {\n versions: ChangelogVersionSlice[];\n /** HTML rendering of the same slice, for direct inclusion in the ticket body. */\n html: string;\n}\n\ninterface ParsedSection {\n version: string;\n dateStr: string | null;\n body: string;\n}\n\n/**\n * Fetches CHANGELOG.md from AlaskaAirlines/<short-pkg-name>, slices the\n * sections that fall in (pinned, latest], and returns both a structured\n * representation (per-version sub-sections by type: features / bug fixes /\n * breaking changes / other) and a rendered HTML string suitable for direct\n * inclusion in a work item description.\n *\n * Returns null on any failure \u2014 missing GH_TOKEN, 404, unparseable structure,\n * empty slice, etc. Callers should fall back to a plain CHANGELOG link.\n *\n * Results are cached in-process by (pkg, pinned, latest) so the same package\n * isn't refetched (or re-parsed) for every consumer repo in one run.\n */\nexport async function fetchChangelogStructured(\n pkg: string,\n pinned: string,\n latest: string,\n): Promise<ChangelogSlice | null> {\n const cacheKey = `${pkg}|${pinned}|${latest}`;\n if (sliceCache.has(cacheKey)) {\n return sliceCache.get(cacheKey) ?? null;\n }\n const result = await fetchAndSlice(pkg, pinned, latest);\n sliceCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Back-compat wrapper for callers that only need the rendered HTML.\n * Prefer `fetchChangelogStructured` for new code.\n */\nexport async function fetchChangelogSlice(\n pkg: string,\n pinned: string,\n latest: string,\n): Promise<string | null> {\n const slice = await fetchChangelogStructured(pkg, pinned, latest);\n return slice ? slice.html : null;\n}\n\nasync function fetchAndSlice(\n pkg: string,\n pinned: string,\n latest: string,\n): Promise<ChangelogSlice | null> {\n const ghToken = process.env.GH_TOKEN;\n if (!ghToken) {\n return null;\n }\n\n const shortName = pkg.replace(/^@[^/]+\\//, \"\");\n const octokit = new Octokit({ auth: ghToken });\n\n let raw: string;\n try {\n const response = await octokit.rest.repos.getContent({\n owner: REPO_OWNER,\n repo: shortName,\n path: \"CHANGELOG.md\",\n });\n if (Array.isArray(response.data) || response.data.type !== \"file\") {\n return null;\n }\n if (!(\"content\" in response.data) || !response.data.content) {\n return null;\n }\n raw = Buffer.from(response.data.content, \"base64\").toString(\"utf8\");\n } catch {\n return null;\n }\n\n const sections = parseSections(raw);\n if (sections.length === 0) {\n return null;\n }\n\n const sliced = sliceSections(sections, pinned, latest);\n if (sliced.length === 0) {\n return null;\n }\n\n const versions = sliced.map(toStructuredVersion);\n const html = versions.map(renderVersion).join(\"\\n\");\n return { versions, html };\n}\n\nfunction parseSections(raw: string): ParsedSection[] {\n // Semantic-release uses `## [x.y.z]` for patch releases and `# [x.y.z]` for\n // minor/major. Both are real version sections and must be captured.\n const headingRegex = /^#{1,2}\\s+\\[([^\\]]+)\\][^\\n]*$/gm;\n const matches = [...raw.matchAll(headingRegex)];\n const sections: ParsedSection[] = [];\n\n for (let i = 0; i < matches.length; i++) {\n const m = matches[i];\n const version = m[1];\n const headingLine = m[0];\n const start = (m.index ?? 0) + headingLine.length;\n const end =\n i + 1 < matches.length\n ? (matches[i + 1].index ?? raw.length)\n : raw.length;\n const body = raw.slice(start, end).trim();\n\n const dateMatch = headingLine.match(/\\((\\d{4}-\\d{2}-\\d{2})\\)/);\n const dateStr = dateMatch ? dateMatch[1] : null;\n\n sections.push({ version, dateStr, body });\n }\n\n return sections;\n}\n\nfunction sliceSections(\n sections: ParsedSection[],\n pinned: string,\n latest: string,\n): ParsedSection[] {\n const pinnedSemver = parseSemver(pinned);\n const latestSemver = parseSemver(latest);\n if (!pinnedSemver || !latestSemver) {\n return [];\n }\n return sections.filter((s) => {\n const semver = parseSemver(s.version);\n if (!semver) {\n return false;\n }\n return (\n compareSemver(semver, pinnedSemver) > 0 &&\n compareSemver(semver, latestSemver) <= 0\n );\n });\n}\n\nfunction compareSemver(a: SemverParts, b: SemverParts): number {\n if (a.major !== b.major) return a.major - b.major;\n if (a.minor !== b.minor) return a.minor - b.minor;\n return a.patch - b.patch;\n}\n\nfunction classifySection(title: string): ChangelogSectionType {\n const normalized = title.trim().toLowerCase();\n if (normalized.includes(\"breaking\")) return \"breakingChanges\";\n if (normalized.startsWith(\"feature\")) return \"features\";\n if (normalized.includes(\"bug fix\") || normalized.startsWith(\"fix\")) {\n return \"bugFixes\";\n }\n return \"other\";\n}\n\nfunction toStructuredVersion(section: ParsedSection): ChangelogVersionSlice {\n const sections: ChangelogSection[] = [];\n let current: ChangelogSection | null = null;\n\n const flush = () => {\n if (current) {\n sections.push(current);\n current = null;\n }\n };\n\n for (const line of section.body.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n const subHeadingMatch = trimmed.match(/^###\\s+(.+)$/);\n if (subHeadingMatch) {\n flush();\n const title = subHeadingMatch[1].trim();\n current = { type: classifySection(title), title, bullets: [] };\n continue;\n }\n\n const bulletMatch = trimmed.match(/^[*-]\\s+(.+)$/);\n if (bulletMatch && current) {\n current.bullets.push(stripBulletSuffix(bulletMatch[1]));\n }\n }\n\n flush();\n return { version: section.version, dateStr: section.dateStr, sections };\n}\n\n/**\n * Strips trailing semantic-release commit/PR references like\n * `text ([#123](url))` or `text ([abc1234](url))`.\n */\nfunction stripBulletSuffix(text: string): string {\n return text.replace(/\\s*\\(\\[[^\\]]+\\]\\([^)]+\\)\\)/g, \"\").trim();\n}\n\nfunction renderVersion(version: ChangelogVersionSlice): string {\n const heading = version.dateStr\n ? `<h4>[${escapeHtml(version.version)}] \u2014 ${escapeHtml(version.dateStr)}</h4>`\n : `<h4>[${escapeHtml(version.version)}]</h4>`;\n const parts: string[] = [heading];\n for (const sec of version.sections) {\n parts.push(`<h5>${escapeHtml(sec.title)}</h5>`);\n if (sec.bullets.length > 0) {\n const bullets = sec.bullets\n .map((b) => `<li>${renderInline(b)}</li>`)\n .join(\"\");\n parts.push(`<ul>${bullets}</ul>`);\n }\n }\n return parts.join(\"\\n\");\n}\n\nfunction renderInline(text: string): string {\n // Already had its semantic-release suffix stripped during parse; just\n // handle inline markdown for `code` and [label](url) links.\n let html = escapeHtml(text);\n html = html.replace(/`([^`]+)`/g, \"<code>$1</code>\");\n html = html.replace(\n /\\[([^\\]]+)\\]\\(([^)]+)\\)/g,\n (_match, label, url) => `<a href=\"${url}\">${label}</a>`,\n );\n return html;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Convenience: flattens all breaking-change bullets across the slice,\n * tagged with the version they came from. Used by the template to render\n * a top-level \"Breaking changes\" section and by AC to emit one bullet\n * per breaking change.\n */\nexport interface BreakingChange {\n version: string;\n text: string;\n}\n\nexport function extractBreakingChanges(\n slice: ChangelogSlice,\n): BreakingChange[] {\n const out: BreakingChange[] = [];\n for (const v of slice.versions) {\n for (const sec of v.sections) {\n if (sec.type !== \"breakingChanges\") continue;\n for (const bullet of sec.bullets) {\n out.push({ version: v.version, text: bullet });\n }\n }\n }\n return out;\n}\n", "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { UpgradeCandidate } from \"./types.ts\";\n\nexport interface PreviewInput {\n candidate: UpgradeCandidate;\n title: string;\n bodyHtml: string;\n acceptanceCriteriaHtml: string;\n tags: string[];\n changelogInlined: boolean;\n}\n\n/**\n * Writes one styled HTML file per candidate to `dir` so a reviewer can open\n * it in a browser and walk the auro-docs \u00A72.4 validation checklist without\n * touching ADO. Filename: `<repo>__<package-flat>.html`.\n */\nexport function writePreviewFile(dir: string, input: PreviewInput): string {\n ensureDir(dir);\n const filename = buildFilename(input.candidate);\n const filePath = path.join(dir, filename);\n fs.writeFileSync(filePath, renderHtml(input));\n return filePath;\n}\n\nfunction ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\nfunction buildFilename(candidate: UpgradeCandidate): string {\n const flatPkg = candidate.package.replace(/^@/, \"\").replace(/\\//g, \"-\");\n return `${sanitize(candidate.repo)}__${sanitize(flatPkg)}.html`;\n}\n\nfunction sanitize(s: string): string {\n return s.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n}\n\nfunction renderHtml(input: PreviewInput): string {\n const {\n candidate,\n title,\n bodyHtml,\n acceptanceCriteriaHtml,\n tags,\n changelogInlined,\n } = input;\n const tagPills = tags\n .map((t) => `<span class=\"tag\">${escapeHtml(t)}</span>`)\n .join(\" \");\n const changelogBadge = changelogInlined\n ? '<span class=\"badge badge-good\">CHANGELOG inlined</span>'\n : '<span class=\"badge badge-warn\">link-only fallback</span>';\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <title>${escapeHtml(title)}</title>\n <style>\n body { font: 14px/1.55 -apple-system, system-ui, \"Segoe UI\", sans-serif; max-width: 760px; margin: 2em auto; padding: 0 1.2em; color: #1f2328; }\n h1 { font-size: 1.35em; padding-bottom: 0.4em; border-bottom: 1px solid #d1d9e0; margin-bottom: 0.6em; }\n h3 { margin-top: 1.6em; font-size: 1.05em; color: #1f2328; }\n h4 { margin-top: 1.2em; font-size: 0.95em; color: #1f2328; }\n h5 { margin: 0.9em 0 0.2em; color: #57606a; font-size: 0.9em; font-weight: 600; }\n p { margin: 0.5em 0; }\n code { background: #eff1f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 90%; font-family: ui-monospace, SFMono-Regular, monospace; }\n a { color: #0969da; text-decoration: none; }\n a:hover { text-decoration: underline; }\n ul { padding-left: 1.5em; }\n li { margin: 0.2em 0; }\n .meta { color: #57606a; font-size: 0.88em; margin-bottom: 1em; }\n .meta strong { color: #1f2328; }\n .tag { display: inline-block; background: #ddf4ff; color: #0550ae; padding: 0.05em 0.55em; margin-right: 0.25em; border-radius: 2em; font-size: 0.82em; }\n .badge { display: inline-block; padding: 0.1em 0.5em; border-radius: 3px; font-size: 0.78em; margin-left: 0.4em; }\n .badge-good { background: #dafbe1; color: #1a7f37; }\n .badge-warn { background: #fff1c2; color: #7d4e00; }\n .preview-banner { background: #fff8c5; border: 1px solid #d4a72c; padding: 0.6em 1em; border-radius: 6px; margin-bottom: 1.5em; font-size: 0.9em; color: #633c01; }\n </style>\n</head>\n<body>\n <div class=\"preview-banner\">\n <strong>Dry-run preview.</strong> No ADO ticket was created. This file shows the HTML body\n that <code>createADOWorkItem</code> would set as <code>System.Description</code>.\n </div>\n <h1>${escapeHtml(title)}</h1>\n <div class=\"meta\">\n <strong>Repo:</strong> <a href=\"${escapeAttr(candidate.repoUrl)}\">${escapeHtml(candidate.repo)}</a> &nbsp;\u00B7&nbsp;\n <strong>Package:</strong> <code>${escapeHtml(candidate.package)}</code> &nbsp;\u00B7&nbsp;\n <strong>Versions:</strong> <code>${escapeHtml(candidate.pinned)}</code> \u2192 <code>${escapeHtml(candidate.latest)}</code> &nbsp;\u00B7&nbsp;\n <strong>Majors behind:</strong> ${candidate.majorsBehind} ${changelogBadge}<br>\n <strong>Tags:</strong> ${tagPills}\n </div>\n <hr>\n ${bodyHtml}\n <h3>Acceptance criteria</h3>\n ${acceptanceCriteriaHtml}\n</body>\n</html>\n`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nfunction escapeAttr(s: string): string {\n return s.replace(/\"/g, \"&quot;\");\n}\n", "import type { BreakingChange, ChangelogSlice } from \"./changelog.ts\";\nimport type { UpgradeCandidate } from \"./types.ts\";\nimport type { UsageInventory } from \"./usage-inventory.ts\";\n\nexport interface StoryBodyInput {\n candidate: UpgradeCandidate;\n changelogSlice: ChangelogSlice | null;\n changelogUrl: string;\n breakingChanges: BreakingChange[];\n /** GitHub Code Search result for the consumer repo \u2014 list of files that\n * reference the package(s). Renders into a \"Where this package is used\"\n * section. Null means the search was skipped or failed; section is\n * omitted. */\n usage?: UsageInventory | null;\n /** When this ticket replaces an earlier bot ticket via close-and-recreate. */\n supersedes?: number;\n}\n\n/**\n * Generic verification bullets that apply to every upgrade. Per-upgrade\n * specifics (e.g. \"verify breaking change X is handled\") are appended\n * downstream by `buildAcceptanceCriteria`.\n */\nfunction genericAcceptanceBullets(c: UpgradeCandidate): string[] {\n const pkg = escapeHtml(c.package);\n const latest = escapeHtml(c.latest);\n const target = c.targetPackage ? escapeHtml(c.targetPackage) : null;\n const manifestPhrase = describeManifestsInline(c.manifestPaths);\n const lockfileWord = `lockfile${c.manifestPaths && c.manifestPaths.length > 1 ? \"s\" : \"\"}`;\n // A migration is a real rewrite when the package short-name changes too\n // (e.g. auro-checkbox \u2192 auro-formkit). When only the scope changes\n // (@alaskaairux/auro-button \u2192 @aurodesignsystem/auro-button), the\n // component is the same and a rename + lockfile update is enough.\n const isRealMigration =\n c.status === \"Unsupported\" &&\n target &&\n !isScopeRename(c.package, c.targetPackage);\n let firstBullet: string;\n if (isRealMigration && target) {\n firstBullet = `Migrate from <code>${pkg}</code> to <code>${target}@${latest}</code> in ${manifestPhrase} (and the matching ${lockfileWord}). <b>This is a code migration, not a drop-in replacement</b> \u2014 the successor exposes different exports and APIs. Review its documentation, update imports and usage, and retest every surface that used <code>${pkg}</code>.`;\n } else if (target) {\n firstBullet = `Replace <code>${pkg}</code> with <code>${target}@${latest}</code> in ${manifestPhrase} (and the matching ${lockfileWord}). Update all import paths from <code>${pkg}</code> to <code>${target}</code>.`;\n } else {\n firstBullet = `Update <code>${pkg}</code> to <code>${latest}</code> in ${manifestPhrase} (and the matching ${lockfileWord}).`;\n }\n const smokeRef = target ?? pkg;\n return [\n firstBullet,\n \"<code>npm ci</code> succeeds with no peer-dep warnings or lockfile drift caused by the upgrade.\",\n \"Build / TypeScript compile passes with no new errors introduced by the upgrade.\",\n \"Lint passes (no new violations).\",\n \"Existing test suite passes.\",\n `Manual smoke check: every UI surface using <code>${smokeRef}</code> renders without new console errors and matches the prior visual baseline.`,\n ];\n}\n\nfunction isScopeRename(\n fromPackage: string,\n toPackage: string | undefined,\n): boolean {\n if (!toPackage) return false;\n const shortName = (p: string) => p.replace(/^@[^/]+\\//, \"\");\n return shortName(fromPackage) === shortName(toPackage);\n}\n\n/**\n * Threshold above which inline comma-separated paths become unreadable.\n * 5 chosen empirically: Borealis's worst-case packages live in 17\u201345\n * manifests, and a 5-item run-on sentence still scans OK; 6+ becomes\n * a wall of text and pushes the AC's action verbs out of view.\n */\nconst INLINE_MANIFEST_LIMIT = 5;\n\n/**\n * Returns a short HTML phrase describing where a dependency lives in the\n * repo, for inline use inside the first AC bullet. Defaults to \"the\n * consumer's <code>package.json</code>\" when manifest paths are unknown or\n * trivial (single root). When the dep lives in a subdirectory manifest, or\n * spans a small number of manifests, names them inline. Above\n * INLINE_MANIFEST_LIMIT, points the engineer at the body's \"Multiple\n * manifests\" callout instead of duplicating a 30+ path list inline \u2014 the\n * AC bullet's job is the action, not a second copy of the list.\n */\nfunction describeManifestsInline(paths: string[] | undefined): string {\n if (!paths || paths.length === 0) {\n return \"the consumer's <code>package.json</code>\";\n }\n if (paths.length === 1 && paths[0] === \"package.json\") {\n return \"the consumer's <code>package.json</code>\";\n }\n if (paths.length === 1) {\n return `<code>${escapeHtml(paths[0])}</code>`;\n }\n if (paths.length > INLINE_MANIFEST_LIMIT) {\n return `each of the ${paths.length} manifests listed in the \"Multiple manifests\" callout in this ticket's description`;\n }\n const items = paths.map((p) => `<code>${escapeHtml(p)}</code>`).join(\", \");\n return `each of the ${paths.length} manifests where it appears (${items})`;\n}\n\n/**\n * Acceptance criteria = the generic verification bullets + at most ONE\n * summary bullet that points back to the body's \"Breaking changes in this\n * upgrade\" section. Long-jump upgrades can carry double-digit breaking\n * changes across many majors; per-item AC bullets become repetitive\n * noise that pushes the meaningful build/lint/test/smoke checkpoints\n * out of view. The body already enumerates each breaking change with\n * version + description; the AC's job is the verification checkpoint,\n * not a second copy of the list.\n */\nexport function buildAcceptanceCriteria(\n c: UpgradeCandidate,\n breakingChanges: BreakingChange[] = [],\n): string {\n const bullets = genericAcceptanceBullets(c).map((b) => ` <li>${b}</li>`);\n if (breakingChanges.length > 0) {\n const count = breakingChanges.length;\n const plural = count === 1 ? \"\" : \"s\";\n bullets.push(\n ` <li>Verify each of the ${count} breaking change${plural} listed in the \"Breaking changes in this upgrade\" section is handled in your codebase.</li>`,\n );\n }\n return [\"<ul>\", ...bullets, \"</ul>\"].join(\"\\n\");\n}\n\nexport function buildStoryTitle(c: UpgradeCandidate): string {\n // Deprecation/replacement tickets get a distinct title: the action is a\n // migration to a different package, not a version bump. \"(deprecated)\" sits\n // flush against the old package@version so it can only modify that one \u2014\n // putting the qualifier at the end of the title (or near the successor)\n // would read as if the new package were unsupported.\n if (c.status === \"Unsupported\" && c.targetPackage) {\n return `Replace ${c.package}@${c.pinned} (deprecated) with ${c.targetPackage}@${c.latest} in ${c.repo}`;\n }\n const plural = c.majorsBehind > 1 ? \"s\" : \"\";\n return `Upgrade ${c.package} in ${c.repo} (${c.pinned} -> ${c.latest}, ${c.majorsBehind} major${plural} behind)`;\n}\n\nexport function buildStoryBody({\n candidate,\n changelogSlice,\n changelogUrl,\n breakingChanges,\n usage,\n supersedes,\n}: StoryBodyInput): string {\n const {\n repo,\n package: pkg,\n pinned,\n latest,\n majorsBehind,\n repoUrl,\n } = candidate;\n const plural = majorsBehind > 1 ? \"s\" : \"\";\n\n const targetPackage = candidate.targetPackage;\n const isRealMigration =\n candidate.status === \"Unsupported\" &&\n !!targetPackage &&\n !isScopeRename(pkg, targetPackage);\n const headlineSentence = isRealMigration\n ? `<p>The repo <a href=\"${repoUrl}\"><b>${escapeHtml(repo)}</b></a> is using <code>${escapeHtml(pkg)}@${escapeHtml(pinned)}</code>, which has been <b>deprecated and replaced</b> by <code>${escapeHtml(targetPackage as string)}@${escapeHtml(latest)}</code>. Migrating off the deprecated package keeps the repo on a supported track for a11y, security patches, and design-system parity.</p>`\n : `<p>The repo <a href=\"${repoUrl}\"><b>${escapeHtml(repo)}</b></a> is using <code>${escapeHtml(pkg)}@${escapeHtml(pinned)}</code> but the latest published version is <code>${escapeHtml(latest)}</code> \u2014 that's <b>${majorsBehind} major version${plural} behind</b>. Staying current keeps a11y, security patches, and design-system parity in step with the rest of the Auro fleet.</p>`;\n const transitionCallout = !targetPackage\n ? \"\"\n : isRealMigration\n ? `<p><b>\u26A0 Package deprecated \u2014 code migration required:</b> <code>${escapeHtml(pkg)}</code> is no longer maintained. The successor <code>${escapeHtml(targetPackage)}</code> is a different package with a different API surface, not a renamed version of the same component. Migration involves removing <code>${escapeHtml(pkg)}</code>, adding <code>${escapeHtml(targetPackage)}</code>, and rewriting source code that referenced the old package. Plan for review time proportional to a real refactor, not a version bump.</p>`\n : `<p><b>\u26A0 Namespace rename:</b> active development of this library moved to <code>${escapeHtml(targetPackage)}</code>. Upgrading requires renaming the dependency in <code>package.json</code> from <code>${escapeHtml(pkg)}</code> to <code>${escapeHtml(targetPackage)}</code> AND updating any matching import paths in source files. The version number bridges both scopes \u2014 <code>${escapeHtml(latest)}</code> is the latest on the new scope.</p>`;\n const contextSection = [\n \"<h3>Context</h3>\",\n headlineSentence,\n transitionCallout,\n buildManifestPathsCallout(candidate.manifestPaths, pinned),\n supersedes !== undefined\n ? `<p><i>This ticket supersedes work item #${supersedes}, which was closed because a newer version of <code>${escapeHtml(pkg)}</code> has shipped since that ticket was created.</i></p>`\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\");\n\n const incidentCallout = buildIncidentCallout(candidate.notes);\n\n const usageSection = buildUsageSection(usage ?? null, pkg, targetPackage);\n\n const breakingSection = buildBreakingChangesSection(\n candidate,\n changelogSlice,\n breakingChanges,\n );\n\n const whatsNewSection = buildWhatsNewSection(\n changelogSlice,\n changelogUrl,\n pkg,\n pinned,\n latest,\n );\n\n return [\n contextSection,\n \"\",\n incidentCallout,\n \"\",\n usageSection,\n \"\",\n breakingSection,\n \"\",\n whatsNewSection,\n \"\",\n \"<p><i>This ticket was auto-generated by the Auro Version Support bot.</i></p>\",\n ]\n .filter((s) => s !== \"\")\n .join(\"\\n\");\n}\n\n/**\n * Renders an inline callout naming the package.json files where this\n * dependency lives. Skipped entirely for the trivial single-root case\n * (one `package.json` at the repo root, which is the assumption a reader\n * already makes). For non-root single manifests OR multi-manifest cases,\n * surfaces the paths explicitly so the engineer knows exactly which files\n * to update \u2014 the original scan bug was missing exactly this signal.\n *\n * The `pinned` parameter is mostly future-proofing \u2014 once we surface\n * per-manifest pins (lockfile parsing, Step 3 in the recommendation),\n * this callout will list each manifest's actual pin rather than the\n * worst-case-behind value that drives the title. For now it's recorded\n * here to flag that the displayed `pinned` is the lowest across manifests.\n */\nfunction buildManifestPathsCallout(\n paths: string[] | undefined,\n _pinned: string,\n): string {\n if (!paths || paths.length === 0) return \"\";\n if (paths.length === 1 && paths[0] === \"package.json\") return \"\";\n\n if (paths.length === 1) {\n return `<p><b>\uD83D\uDCCD Manifest location:</b> this dependency is declared in <code>${escapeHtml(paths[0])}</code>, not the repo's root <code>package.json</code>. Make sure your upgrade edits the right file.</p>`;\n }\n\n // Above the threshold, render as a bulleted block \u2014 a 30+ path\n // comma-separated paragraph is a wall of text. The list itself is the\n // engineer's update checklist; treating it like one makes it scannable\n // and copy-paste-friendly. Below the threshold, inline reads naturally.\n if (paths.length > INLINE_MANIFEST_LIMIT) {\n const items = paths\n .map((p) => ` <li><code>${escapeHtml(p)}</code></li>`)\n .join(\"\\n\");\n return [\n `<p><b>\u26A0 Multiple manifests:</b> this dependency is declared in <b>${paths.length}</b> <code>package.json</code> files \u2014 all must be updated to upgrade the repo consistently:</p>`,\n \"<ul>\",\n items,\n \"</ul>\",\n ].join(\"\\n\");\n }\n\n const items = paths.map((p) => `<code>${escapeHtml(p)}</code>`).join(\", \");\n return `<p><b>\u26A0 Multiple manifests:</b> this dependency is declared in <b>${paths.length}</b> <code>package.json</code> files \u2014 all must be updated to upgrade the repo consistently: ${items}.</p>`;\n}\n\n/**\n * Renders a warning callout carrying the catalog's incident `notes` text.\n * The notes field is the catalog's incident knob: when a release has a\n * known regression, an engineer pins `targetVersion` to the last-known-good\n * version and adds `notes` describing the situation. Every ticket the bot\n * files for that package then surfaces this callout so consumers don't go\n * spelunking through Slack for the context.\n *\n * Empty string when notes is absent \u2014 Stories without an incident render\n * unchanged. Plain text in; HTML-escaped on the way out so a stray `<` in\n * the catalog can't break ADO's renderer.\n */\nfunction buildIncidentCallout(notes: string | undefined): string {\n if (!notes) return \"\";\n return `<p><b>\u26A0 Incident notice:</b> ${escapeHtml(notes)}</p>`;\n}\n\n/**\n * Renders the \"What's new\" section: a deterministic summary of how many\n * Features and Bug Fixes shipped in (pinned, latest], followed by a link\n * to the full CHANGELOG. Replaces the previous \"Migration guide\" section\n * which inlined the entire structured CHANGELOG slice \u2014 bodies for\n * long-jump upgrades routinely cleared the 50KB ADO render budget, and\n * pushed the meaningful per-version migration content out of view.\n *\n * The full CHANGELOG remains one click away. Breaking changes are already\n * extracted into their own section above this one, so removing the inline\n * dump doesn't lose actionable signal. Falls back to a link-only paragraph\n * when the slice was unfetchable.\n */\nfunction buildWhatsNewSection(\n slice: ChangelogSlice | null,\n changelogUrl: string,\n pkg: string,\n pinned: string,\n latest: string,\n): string {\n if (!slice) {\n return [\n \"<h3>What's new</h3>\",\n `<p>See the <a href=\"${changelogUrl}\">CHANGELOG for ${escapeHtml(pkg)}</a> for changes between <code>${escapeHtml(pinned)}</code> and <code>${escapeHtml(latest)}</code>.</p>`,\n ].join(\"\\n\");\n }\n let features = 0;\n let bugFixes = 0;\n for (const version of slice.versions) {\n for (const section of version.sections) {\n if (section.type === \"features\") features += section.bullets.length;\n else if (section.type === \"bugFixes\") bugFixes += section.bullets.length;\n }\n }\n const featuresLine = `Features: <b>${features}</b>`;\n const bugFixesLine = `Bug fixes: <b>${bugFixes}</b>`;\n return [\n \"<h3>What's new</h3>\",\n `<p>Between <code>${escapeHtml(pinned)}</code> and <code>${escapeHtml(latest)}</code>:</p>`,\n \"<ul>\",\n ` <li>${featuresLine}</li>`,\n ` <li>${bugFixesLine}</li>`,\n \"</ul>\",\n `<p>See the <a href=\"${changelogUrl}\">full CHANGELOG for ${escapeHtml(pkg)}</a> for the details.</p>`,\n ].join(\"\\n\");\n}\n\n/**\n * Renders a \"Where this package is used in your codebase\" section from a\n * GitHub Code Search result. Returns an empty string when there's no\n * inventory (search skipped/failed) or when totalCount is 0 \u2014 the body\n * stays clean in those cases instead of carrying a \"we couldn't find\n * usages\" disclaimer that adds no information.\n *\n * The section lives between Context and Breaking changes so it gives the\n * reviewer a sense of scope (how big is the change in *my* repo?) before\n * the migration content.\n */\nfunction buildUsageSection(\n usage: UsageInventory | null,\n pkg: string,\n targetPackage: string | undefined,\n): string {\n if (!usage || usage.totalCount === 0) {\n return \"\";\n }\n const fileWord = usage.totalCount === 1 ? \"file\" : \"files\";\n const sampleSize = Math.min(usage.sampleFiles.length, 10);\n const fileItems = usage.sampleFiles\n .slice(0, sampleSize)\n .map(\n (f) =>\n ` <li><a href=\"${f.htmlUrl}\"><code>${escapeHtml(f.path)}</code></a></li>`,\n )\n .join(\"\\n\");\n const moreNote =\n usage.totalCount > sampleSize\n ? `<p>\u2026 and ${usage.totalCount - sampleSize} more. <a href=\"${usage.searchUrl}\">View all results on GitHub</a>.</p>`\n : \"\";\n const pkgLabel = targetPackage\n ? `<code>${escapeHtml(pkg)}</code> or <code>${escapeHtml(targetPackage)}</code>`\n : `<code>${escapeHtml(pkg)}</code>`;\n return [\n \"<h3>Where this package is used in your codebase</h3>\",\n `<p>GitHub Code Search found ${pkgLabel} referenced in <b>${usage.totalCount}</b> ${fileWord} in this repo:</p>`,\n \"<ul>\",\n fileItems,\n \"</ul>\",\n moreNote,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/**\n * Renders a \"Breaking changes in this upgrade\" section derived from the\n * BREAKING CHANGES subheadings in the CHANGELOG slice. Returns an empty\n * string when the changelog wasn't fetchable (so the section is omitted\n * entirely); returns an explicit \"none detected\" paragraph when the\n * changelog exists but contains no breaking-change entries.\n */\nfunction buildBreakingChangesSection(\n candidate: UpgradeCandidate,\n changelogSlice: ChangelogSlice | null,\n breakingChanges: BreakingChange[],\n): string {\n const { package: pkg, pinned, latest } = candidate;\n if (!changelogSlice) {\n return \"\";\n }\n if (breakingChanges.length === 0) {\n return [\n \"<h3>Breaking changes in this upgrade</h3>\",\n `<p>No breaking changes detected in <code>${escapeHtml(pkg)}</code> between <code>${escapeHtml(pinned)}</code> and <code>${escapeHtml(latest)}</code>.</p>`,\n ].join(\"\\n\");\n }\n const bullets = breakingChanges\n .map((bc) => renderBreakingChangeBullet(bc, candidate))\n .join(\"\\n\");\n return [\n \"<h3>Breaking changes in this upgrade</h3>\",\n \"<ul>\",\n bullets,\n \"</ul>\",\n ].join(\"\\n\");\n}\n\nfunction renderBreakingChangeBullet(\n bc: BreakingChange,\n candidate: UpgradeCandidate,\n): string {\n const baseText = `<b>${escapeHtml(bc.version)}:</b> ${renderInline(bc.text)}`;\n const searchLink = buildBreakingChangeSearchLink(bc.text, candidate);\n if (!searchLink) {\n return ` <li>${baseText}</li>`;\n }\n return ` <li>${baseText} <span class=\"bot-find-link\">${searchLink}</span></li>`;\n}\n\n/**\n * Returns an anchor tag pointing at a GitHub Code Search URL scoped to\n * the consumer repo for any identifier-shaped tokens (alphanumeric +\n * dashes/underscores) the CHANGELOG author wrapped in backticks.\n * Returns null when the breaking-change text has no such tokens \u2014\n * the bullet renders without a search suffix in that case.\n *\n * The URL combines the package's short name AND the identifier(s) so the\n * search returns files that reference both, which is a fair proxy for\n * \"files using this component that mention the changed identifier.\"\n * Pure URL building \u2014 no API call from the bot side; the reviewer\n * clicks if they want to investigate.\n */\nfunction buildBreakingChangeSearchLink(\n rawText: string,\n candidate: UpgradeCandidate,\n): string | null {\n const identifiers = extractIdentifiers(rawText);\n if (identifiers.length === 0) return null;\n\n let org: string;\n let repoName: string;\n try {\n const url = new URL(candidate.repoUrl);\n const segs = url.pathname.split(\"/\").filter(Boolean);\n if (segs.length < 2) return null;\n [org, repoName] = segs;\n } catch {\n return null;\n }\n\n const shortName = (candidate.targetPackage ?? candidate.package).replace(\n /^@[^/]+\\//,\n \"\",\n );\n const idsQuoted = identifiers.map((i) => `\"${i}\"`).join(\" OR \");\n const idsClause = identifiers.length > 1 ? `(${idsQuoted})` : idsQuoted;\n const q = `repo:${org}/${repoName} \"${shortName}\" ${idsClause}`;\n const href = `https://github.com/search?q=${encodeURIComponent(q)}&type=code`;\n const labelTokens = identifiers\n .map((i) => `<code>${escapeHtml(i)}</code>`)\n .join(\", \");\n return `<a href=\"${href}\">\u2192 find ${labelTokens} in this repo</a>`;\n}\n\n/**\n * Pulls identifier-shaped tokens from backticked spans in CHANGELOG text.\n * \"Identifier-shaped\" = starts with a letter, then letters/digits/dashes/\n * underscores only, 2+ chars. This filters out non-searchable spans like\n * sentence fragments, URLs, or quoted snippets.\n */\nfunction extractIdentifiers(text: string): string[] {\n const found = new Set<string>();\n for (const match of text.matchAll(/`([^`]+)`/g)) {\n const ident = match[1].trim();\n if (/^[A-Za-z][\\w-]{1,}$/.test(ident)) {\n found.add(ident);\n }\n }\n return [...found];\n}\n\nfunction renderInline(text: string): string {\n // Inline markdown that survives raw in a CHANGELOG bullet: `code` and\n // [label](url) links. Escape first so URL chars are safe before we\n // re-inject HTML tags.\n let html = escapeHtml(text);\n html = html.replace(/`([^`]+)`/g, \"<code>$1</code>\");\n html = html.replace(\n /\\[([^\\]]+)\\]\\(([^)]+)\\)/g,\n (_match, label, url) => `<a href=\"${url}\">${label}</a>`,\n );\n return html;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n", "import { Octokit } from \"@octokit/rest\";\n\nexport interface UsageFileMatch {\n path: string;\n htmlUrl: string;\n}\n\nexport interface UsageInventory {\n /** Total matching files in the repo (from GitHub's `total_count`). */\n totalCount: number;\n /** First N matches from the search response; surfaced as links in the ticket. */\n sampleFiles: UsageFileMatch[];\n /** Pre-built github.com search URL the reader can click to see all matches. */\n searchUrl: string;\n}\n\nconst inventoryCache = new Map<string, UsageInventory | null>();\n\n/**\n * Queries GitHub Code Search for files in the consumer repo that reference\n * a given package name. For cross-namespace candidates, searches both the\n * legacy and target package names in a single OR query.\n *\n * Returns null on any failure (missing token, 4xx/5xx, network) \u2014 callers\n * should treat null as \"skip the usage section in this ticket.\" A\n * non-null result with totalCount === 0 means the search succeeded but\n * found nothing.\n *\n * Results are cached per (org, repo, packages-key) for the lifetime of\n * the process so multiple candidates for the same (repo, pkg) don't\n * re-hit the API.\n *\n * Rate-limit note: GitHub Code Search authenticated limit is 30\n * requests/min. For a full-org `--apply` (~455 candidates after the\n * 2026-05-13 namespace work) that's ~15 min added to the run. Acceptable\n * for the quarterly cron; negligible for `--apply --limit 1`.\n */\nexport async function findUsageInRepo(input: {\n org: string;\n repo: string;\n packages: string[];\n}): Promise<UsageInventory | null> {\n const { org, repo, packages } = input;\n const packagesKey = packages.slice().sort().join(\"|\");\n const cacheKey = `${org}/${repo}::${packagesKey}`;\n if (inventoryCache.has(cacheKey)) {\n return inventoryCache.get(cacheKey) ?? null;\n }\n\n const token = process.env.GH_TOKEN;\n if (!token) {\n inventoryCache.set(cacheKey, null);\n return null;\n }\n if (packages.length === 0) {\n inventoryCache.set(cacheKey, null);\n return null;\n }\n\n // GitHub Code Search does NOT honor `OR` as a logical operator \u2014\n // an `a OR b` query treats `OR` as a literal token and effectively ANDs\n // everything, which makes cross-namespace queries return zero hits. So\n // we run one search per package and merge the results. Adds a second\n // API call on cross-namespace candidates only (a minority of total).\n try {\n const octokit = new Octokit({ auth: token });\n const merged = new Map<string, UsageFileMatch>();\n let totalCount = 0;\n let primaryQuery = \"\";\n for (const pkg of packages) {\n // GitHub auto-excludes node_modules and binary files. Lockfiles and\n // dist bundles still match, which is noise \u2014 exclude them explicitly.\n // Also exclude package.json itself (root or workspace-nested) \u2014 every\n // candidate by definition has the package in package.json, so listing\n // it adds no information for the reviewer.\n const query =\n `\"${pkg}\" repo:${org}/${repo}` +\n \" -path:package-lock.json -path:yarn.lock -path:pnpm-lock.yaml\" +\n \" -path:dist -path:build -filename:package.json\";\n if (!primaryQuery) primaryQuery = query;\n const result = await octokit.rest.search.code({\n q: query,\n per_page: 10,\n });\n totalCount += result.data.total_count;\n for (const item of result.data.items) {\n if (!merged.has(item.html_url)) {\n merged.set(item.html_url, {\n path: item.path,\n htmlUrl: item.html_url,\n });\n }\n }\n }\n const inventory: UsageInventory = {\n totalCount,\n sampleFiles: [...merged.values()].slice(0, 10),\n searchUrl: `https://github.com/search?q=${encodeURIComponent(primaryQuery)}&type=code`,\n };\n inventoryCache.set(cacheKey, inventory);\n return inventory;\n } catch {\n inventoryCache.set(cacheKey, null);\n return null;\n }\n}\n"],
5
+ "mappings": ";AAEA,MAAO,gBACP,OAAS,WAAAA,OAAe,YCHxB,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,GAAK,Q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AAQ,KAAM,OAElB,QAAQ,IAAI,EAAE,EACd,QAAQ,IACNK,EAAM,KAAKL,EAAQ,MAAQ,oBAAsB,mBAAmB,CACtE,EACA,QAAQ,IAAI,eAAeG,EAAQ,UAAU,EAAE,EAC3CH,EAAQ,OACV,QAAQ,IACN,eAAeK,EAAM,MAAMF,EAAQ,MAAM,CAAC,aAAaE,EAAM,IAAIF,EAAQ,MAAM,CAAC,EAClF,EACA,QAAQ,IAAI,eAAeE,EAAM,IAAIF,EAAQ,YAAY,CAAC,EAAE,IAE5D,QAAQ,IAAI,sBAAsBE,EAAM,KAAKF,EAAQ,OAAO,CAAC,EAAE,EAC/D,QAAQ,IACNE,EAAM,IACJ;AAAA,wDACF,CACF,EAEJ,OAASC,EAAO,CACd,QAAQ,MACND,EAAM,IACJ,mBAAmBC,aAAiB,MAAQA,EAAM,QAAUA,CAAK,EACnE,CACF,EACA,QAAQ,KAAK,CAAC,CAChB,CACF,CAAC,EnDvIHE,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", "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", "spawn", "ora", "shell", "command", "_args", "commandString", "spinner", "finalCommand", "finalArgs", "parts", "isWatchMode", "child", "commandOutput", "data", "output", "resolve", "reject", "code", "fs", "path", "Logger", "generateReadmeUrl", "processContentForFile", "templateFiller", "readFileSync", "existsSync", "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", "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", "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", "readFile", "writeFile", "process", "Logger", "program", "fs", "path", "processContentForFile", "templateFiller", "Octokit", "ora", "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", "CONFIG_DIR", "withHomeDir", "OUTPUT_DIR", "auroComponents", "auroPackages", "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", "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", "ADO_ORG_URL", "ADO_PROJECT_NAME", "ADO_AREA_PATH", "getWorkItemTrackingApi", "adoToken", "authHandler", "createADOWorkItem", "input", "workItemTrackingApi", "workItemData", "closeADOWorkItem", "patch", "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", "simpleGit", "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", "chalk", "program", "Octokit", "ora", "crypto", "fs", "path", "fs", "path", "SCAN_CACHE_FILE", "UPGRADE_CANDIDATES_FILE", "COMPLIANCE_FINDINGS_FILE", "DEFAULT_OUTPUT_SUBPATH", "defaultOutputDir", "resolveOutputDir", "dir", "versionBotDir", "scanCachePath", "upgradeCandidatesPath", "complianceFindingsPath", "ensureDir", "readScanCache", "file", "parsed", "writeScanCache", "cache", "writeUpgradeCandidates", "candidates", "readUpgradeCandidates", "writeComplianceFindings", "findings", "displayPath", "filePath", "rel", "path", "AUDIT_LOG_FILE", "auditLogPath", "dir", "path", "versionBotDir", "newRunId", "now", "pad", "n", "w", "stamp", "suffix", "crypto", "appendAuditEntry", "entry", "filePath", "fs", "readAuditEntries", "raw", "entries", "line", "trimmed", "readAuditEntriesForRun", "runId", "e", "listRunIds", "seen", "lastRunId", "ids", "VERSION_RANGE_PREFIX", "parseVersion", "raw", "match", "compareVersions", "a", "b", "i", "av", "bv", "evaluatePackage", "input", "policy", "declaredVersion", "detected", "hasDeprecatedApiUsage", "packageName", "version", "minimumVersion", "targetVersion", "minimum", "target", "PACKAGE_ALIASES", "aliasFor", "pkg", "NPM_REGISTRY", "REQUEST_TIMEOUT_MS", "npmLatest", "pkgName", "url", "controller", "timer", "response", "parseSemver", "value", "match", "majorsBehind", "pinned", "latest", "p", "l", "resolveLatestAcrossAliases", "alias", "aliasFor", "direct", "aliased", "cmp", "compareSemver", "a", "b", "pa", "pb", "PACKAGE_POLICY_CATALOG", "findPackagePolicy", "packageName", "record", "evaluateRepoPackage", "name", "pinned", "archivedPackages", "latestByPackage", "policy", "findPackagePolicy", "targetPackage", "effectiveLatest", "successor", "resolved", "mb", "majorsBehind", "evalResult", "evaluatePackage", "status", "statusReason", "buildComplianceFindings", "cache", "scanRunId", "scannedAt", "byKey", "repoEntry", "pkgScan", "evaluated", "key", "existing", "compareSemver", "reEval", "findings", "entry", "sepIdx", "repository", "packageName", "AURO_NAMESPACES", "discoverAuroManifests", "octokit", "org", "byRepo", "totalMatches", "namespace", "q", "iterator", "data", "item", "repoName", "path", "paths", "AURO_ORG", "runScan", "options", "ghToken", "octokit", "Octokit", "cache", "readScanCache", "archivedSpinner", "ora", "archivedPackages", "fetchArchivedAuroPackages", "reposSpinner", "repos", "listEcommerceRepos", "discoverySpinner", "discovery", "discoverAuroManifests", "reposByName", "r", "scanned", "skipped", "errored", "repoName", "manifestPaths", "repo", "cached", "repoSpinner", "entry", "scanRepo", "auroDepCount", "countAuroDeps", "cachedName", "writeScanCache", "latestByPackage", "resolveLatestVersions", "scanRunId", "newRunId", "scannedAt", "findings", "buildComplianceFindings", "writeComplianceFindings", "candidates", "collapseCandidatesByPackage", "writeUpgradeCandidates", "displayPath", "scanCachePath", "upgradeCandidatesPath", "complianceFindingsPath", "org", "iterator", "data", "archived", "path", "manifest", "fetchPackageJson", "buildPackageScan", "owner", "filePath", "ref", "response", "raw", "pkg", "all", "auroDeps", "name", "version", "n", "distinctPackages", "repoEntry", "pkgScan", "policy", "findPackagePolicy", "latestSpinner", "names", "results", "resolveLatestAcrossAliases", "i", "byKey", "pinned", "evaluated", "evaluateRepoPackage", "key", "existing", "compareSemver", "reEval", "candidate", "versionScanCommand", "program", "options", "summary", "runScan", "chalk", "error", "chalk", "program", "chalk", "ora", "resolveTargetRunId", "options", "id", "lastRunId", "known", "listRunIds", "sample", "selectClosable", "targetRunId", "allEntries", "readAuditEntries", "closedIds", "e", "readAuditEntriesForRun", "runCleanup", "ids", "chalk", "created", "closable", "cleanupRunId", "newRunId", "summary", "entry", "label", "spinner", "ora", "closeADOWorkItem", "appendAuditEntry", "error", "fs", "chalk", "ora", "azdev", "ADO_ORG_URL", "ADO_PROJECT_NAME", "ADO_AREA_PATH", "findOpenBotTickets", "repo", "pkg", "adoToken", "authHandler", "api", "escape", "s", "wiql", "ids", "w", "id", "item", "parseLatestFromTitle", "title", "m", "Octokit", "REPO_OWNER", "sliceCache", "fetchChangelogStructured", "pkg", "pinned", "latest", "cacheKey", "result", "fetchAndSlice", "fetchAndSlice", "pkg", "pinned", "latest", "ghToken", "shortName", "octokit", "Octokit", "raw", "response", "REPO_OWNER", "sections", "parseSections", "sliced", "sliceSections", "versions", "toStructuredVersion", "html", "renderVersion", "headingRegex", "matches", "i", "m", "version", "headingLine", "start", "end", "body", "dateMatch", "dateStr", "pinnedSemver", "parseSemver", "latestSemver", "semver", "compareSemver", "a", "b", "classifySection", "title", "normalized", "section", "current", "flush", "line", "trimmed", "subHeadingMatch", "bulletMatch", "stripBulletSuffix", "text", "parts", "escapeHtml", "sec", "bullets", "renderInline", "_match", "label", "url", "s", "extractBreakingChanges", "slice", "out", "v", "bullet", "fs", "path", "writePreviewFile", "dir", "input", "ensureDir", "filename", "buildFilename", "filePath", "renderHtml", "candidate", "flatPkg", "sanitize", "s", "title", "bodyHtml", "acceptanceCriteriaHtml", "tags", "changelogInlined", "tagPills", "t", "escapeHtml", "changelogBadge", "escapeAttr", "genericAcceptanceBullets", "c", "pkg", "escapeHtml", "latest", "target", "manifestPhrase", "describeManifestsInline", "lockfileWord", "isRealMigration", "isScopeRename", "firstBullet", "fromPackage", "toPackage", "shortName", "p", "INLINE_MANIFEST_LIMIT", "paths", "items", "buildAcceptanceCriteria", "breakingChanges", "bullets", "b", "count", "plural", "buildStoryTitle", "buildStoryBody", "candidate", "changelogSlice", "changelogUrl", "usage", "supersedes", "repo", "pinned", "majorsBehind", "repoUrl", "targetPackage", "headlineSentence", "transitionCallout", "contextSection", "buildManifestPathsCallout", "incidentCallout", "buildIncidentCallout", "usageSection", "buildUsageSection", "breakingSection", "buildBreakingChangesSection", "whatsNewSection", "buildWhatsNewSection", "s", "_pinned", "notes", "slice", "features", "bugFixes", "version", "section", "featuresLine", "bugFixesLine", "fileWord", "sampleSize", "fileItems", "f", "moreNote", "bc", "renderBreakingChangeBullet", "baseText", "renderInline", "searchLink", "buildBreakingChangeSearchLink", "rawText", "identifiers", "extractIdentifiers", "org", "repoName", "segs", "idsQuoted", "i", "idsClause", "q", "href", "labelTokens", "text", "found", "match", "ident", "html", "_match", "label", "url", "Octokit", "inventoryCache", "findUsageInRepo", "input", "org", "repo", "packages", "packagesKey", "cacheKey", "token", "octokit", "merged", "totalCount", "primaryQuery", "pkg", "query", "result", "item", "inventory", "runCreateTickets", "options", "all", "readCandidatesFromPath", "readUpgradeCandidates", "filtered", "c", "kept", "notUsedSkipped", "applyNotUsedFilter", "selected", "runId", "newRunId", "summary", "chalk", "candidate", "processCandidate", "filePath", "fs", "title", "buildStoryTitle", "changelogUrl", "buildChangelogUrl", "tags", "buildTags", "fetchSpinner", "ora", "changelogSlice", "fetchChangelogStructured", "breakingChanges", "extractBreakingChanges", "usage", "fetchUsageInventory", "descriptionHtml", "usedChangelogSlice", "buildBodyWithinLimit", "acceptanceCriteriaHtml", "buildAcceptanceCriteria", "writePreviewFile", "dedupe", "resolveDedupeAction", "supersedes", "spinner", "workItem", "createADOWorkItem", "newId", "url", "appendAuditEntry", "oldId", "closeSpinner", "closeADOWorkItem", "error", "existing", "findOpenBotTickets", "target", "a", "b", "existingLatest", "parseLatestFromTitle", "cmp", "compareSemver", "pkg", "complianceTagSlug", "status", "candidates", "org", "repo", "segments", "packages", "findUsageInRepo", "MAX_BODY_LENGTH", "input", "initial", "buildStoryBody", "hadSlice", "fallback", "versionTicketsCommand", "program", "options", "minMajors", "limit", "summary", "runCreateTickets", "chalk", "error", "runCleanup", "program", "getPackageVersion", "auroSplash_default"]
7
7
  }