@salesforce/storefront-next-dev 1.3.1 → 1.4.0-alpha.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 +1 @@
1
- {"version":3,"file":"index.js","names":["LEVEL_PRIORITY: Record<LogLevel, number>","overrideLevel: LogLevel | undefined","isCliAvailable: boolean | null","result: Array<{ id: string; path: string; file: string; index?: boolean }>","fullPath: string","join","VALID_ATTRIBUTE_TYPES: readonly AttributeType[]","TYPE_MAPPING: Record<string, string>","mapped: Record<string, unknown>","result: Record<string, unknown>","result: unknown[]","attributes: Record<string, unknown>[]","attribute: Record<string, unknown>","regionDefinitions: Record<string, unknown>[]","regionDefinition: Record<string, unknown>","components: unknown[]","componentMetadata: Record<string, unknown>","pageTypes: unknown[]","aspects: unknown[]","cartridgeData: Record<string, unknown>","files: string[]","allComponents: unknown[]","allPageTypes: unknown[]","allAspects: unknown[]"],"sources":["../../src/utils/logger.ts","../../src/cartridge-services/react-router-config.ts","../../src/utils/format-with-project-biome.ts","../../src/cartridge-services/generate-cartridge.ts"],"sourcesContent":["/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* oxlint-disable no-console */\nimport os from 'os';\nimport chalk from 'chalk';\nimport { createRequire } from 'module';\nimport type { ServerMode } from '../server/modes';\nimport pkg from '../../package.json' with { type: 'json' };\n\n/**\n * Get the local network IPv4 address\n */\nexport function getNetworkAddress(): string | undefined {\n const interfaces = os.networkInterfaces();\n for (const name of Object.keys(interfaces)) {\n const iface = interfaces[name];\n if (!iface) continue;\n for (const alias of iface) {\n if (alias.family === 'IPv4' && !alias.internal) {\n return alias.address;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Get the version of a package from the project's package.json\n */\nexport function getPackageVersion(packageName: string, projectDir: string): string {\n try {\n const require = createRequire(import.meta.url);\n const pkgPath = require.resolve(`${packageName}/package.json`, { paths: [projectDir] });\n const pkgJson = require(pkgPath) as { version: string };\n return pkgJson.version;\n } catch {\n return 'unknown';\n }\n}\n\n/**\n * Centralized, level-gated logger for the SDK.\n *\n * Log level is controlled by `SFCC_LOG_LEVEL` env var (`error` | `warn` | `info` | `debug`).\n * Falls back to: `DEBUG` targeting sfnext -> `debug`, `NODE_ENV=production` -> `warn`, otherwise `info`.\n */\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug';\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nlet overrideLevel: LogLevel | undefined;\n\n/**\n * Returns true when the `DEBUG` env var targets sfnext or is a general enable flag.\n * Avoids accidentally enabling debug mode when DEBUG is set for unrelated libraries\n * (e.g. `DEBUG=express:*`).\n */\nfunction debugEnablesSfnext(): boolean {\n const raw = process.env.DEBUG?.trim();\n if (!raw) return false;\n const normalized = raw.toLowerCase();\n if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;\n return raw.split(',').some((token) => {\n const value = token.trim();\n return value === '*' || value === 'sfnext' || value === 'sfnext:*';\n });\n}\n\nfunction resolveLevel(): LogLevel {\n if (overrideLevel) return overrideLevel;\n const envLevel = process.env.MRT_LOG_LEVEL ?? process.env.SFCC_LOG_LEVEL;\n if (envLevel && envLevel in LEVEL_PRIORITY) return envLevel as LogLevel;\n if (debugEnablesSfnext()) return 'debug';\n if (process.env.NODE_ENV === 'production') return 'warn';\n return 'info';\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LEVEL_PRIORITY[level] <= LEVEL_PRIORITY[resolveLevel()];\n}\n\nexport const logger = {\n error(msg: string, ...args: unknown[]): void {\n if (!shouldLog('error')) return;\n console.error(chalk.red('[sfnext:error]'), msg, ...args);\n },\n warn(msg: string, ...args: unknown[]): void {\n if (!shouldLog('warn')) return;\n console.warn(chalk.yellow('[sfnext:warn]'), msg, ...args);\n },\n info(msg: string, ...args: unknown[]): void {\n if (!shouldLog('info')) return;\n console.log(chalk.cyan('[sfnext:info]'), msg, ...args);\n },\n debug(msg: string, ...args: unknown[]): void {\n if (!shouldLog('debug')) return;\n console.log(chalk.gray('[sfnext:debug]'), msg, ...args);\n },\n setLevel(level: LogLevel | undefined): void {\n overrideLevel = level;\n },\n getLevel(): LogLevel {\n return resolveLevel();\n },\n};\n\n/**\n * Print the server information banner with URLs and versions\n */\nexport function printServerInfo(mode: ServerMode, port: number, startTime: number, projectDir: string): void {\n const elapsed = Date.now() - startTime;\n const sfnextVersion = pkg.version;\n const reactVersion = getPackageVersion('react', projectDir);\n const reactRouterVersion = getPackageVersion('react-router', projectDir);\n const viteVersion = getPackageVersion('vite', projectDir);\n\n const modeLabel = mode === 'development' ? 'Development Mode' : 'Preview Mode';\n\n console.log();\n console.log(` ${chalk.cyan.bold('⚡ SFCC Storefront Next')} ${chalk.dim(`v${sfnextVersion}`)}`);\n console.log(` ${chalk.green.bold(modeLabel)}`);\n console.log();\n const logLevel = resolveLevel();\n const logLevelColors: Record<LogLevel, (s: string) => string> = {\n error: chalk.red,\n warn: chalk.yellow,\n info: chalk.cyan,\n debug: chalk.gray,\n };\n\n console.log(\n ` ${chalk.dim('react')} ${chalk.green(`v${reactVersion}`)} ${chalk.dim('|')} ` +\n `${chalk.dim('react-router')} ${chalk.green(`v${reactRouterVersion}`)} ${chalk.dim('|')} ` +\n `${chalk.dim('vite')} ${chalk.green(`v${viteVersion}`)}`\n );\n console.log(\n ` ${chalk.dim('log level')} ${logLevelColors[logLevel](logLevel)} ${chalk.dim('|')} ` +\n `${chalk.green(`ready in ${elapsed}ms`)}`\n );\n console.log();\n}\n\n/**\n * Print server configuration details (proxy, static, etc.)\n */\nexport function printServerConfig(config: {\n mode: ServerMode;\n port: number;\n enableProxy?: boolean;\n enableStaticServing?: boolean;\n enableCompression?: boolean;\n proxyPath?: string;\n proxyHost?: string;\n shortCode?: string;\n organizationId?: string;\n clientId?: string;\n}): void {\n const {\n port,\n enableProxy,\n enableStaticServing,\n enableCompression,\n proxyPath,\n proxyHost,\n shortCode,\n organizationId,\n clientId,\n } = config;\n\n console.log(` ${chalk.bold('Environment Configuration:')}`);\n\n if (enableProxy && proxyPath && proxyHost && shortCode) {\n console.log(\n ` ${chalk.green('✓')} ${chalk.bold('Proxy:')} ${chalk.cyan(`localhost:${port}${proxyPath}`)} ${chalk.dim('→')} ${chalk.cyan(proxyHost)}`\n );\n console.log(` ${chalk.dim('Short Code: ')}${chalk.dim(shortCode)}`);\n if (organizationId) {\n console.log(` ${chalk.dim('Organization ID: ')}${chalk.dim(organizationId)}`);\n }\n if (clientId) {\n console.log(` ${chalk.dim('Client ID: ')}${chalk.dim(clientId)}`);\n }\n } else {\n console.log(` ${chalk.bold('Proxy: ')} ${chalk.dim('disabled')}`);\n }\n\n if (enableStaticServing) {\n console.log(` ${chalk.bold('Static: ')} ${chalk.dim('enabled')}`);\n }\n\n if (enableCompression) {\n console.log(` ${chalk.bold('Compression: ')} ${chalk.dim('enabled')}`);\n }\n\n // URLs\n const localUrl = `http://localhost:${port}`;\n const showNetwork = process.env.SHOW_NETWORK === 'true';\n const networkAddress = showNetwork ? getNetworkAddress() : undefined;\n const networkUrl = networkAddress ? `http://${networkAddress}:${port}` : undefined;\n\n console.log();\n console.log(` ${chalk.bold('Local: ')} ${chalk.cyan(localUrl)}`);\n if (networkUrl) {\n console.log(` ${chalk.bold('Network:')} ${chalk.cyan(networkUrl)}`);\n }\n\n console.log();\n console.log(` ${chalk.dim('Press')} ${chalk.bold('Ctrl+C')} ${chalk.dim('to stop the server')}`);\n console.log();\n}\n\n/**\n * Print shutdown message\n */\nexport function printShutdownMessage(): void {\n console.log(`\\n ${chalk.yellow('⚡')} ${chalk.dim('Server shutting down...')}\\n`);\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { join } from 'node:path';\nimport { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { execSync } from 'node:child_process';\nimport { tmpdir } from 'node:os';\nimport { randomUUID } from 'node:crypto';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { RouteConfigEntry } from '@react-router/dev/routes';\nimport { logger } from '../logger';\n\nlet isCliAvailable: boolean | null = null;\n\nfunction checkReactRouterCli(projectDirectory: string): boolean {\n if (isCliAvailable !== null) {\n return isCliAvailable;\n }\n\n try {\n execSync('react-router --version', {\n cwd: projectDirectory,\n env: npmRunPathEnv(),\n stdio: 'pipe',\n });\n isCliAvailable = true;\n } catch {\n isCliAvailable = false;\n }\n return isCliAvailable;\n}\n\n/**\n * Get the fully resolved routes from React Router by invoking its CLI.\n * This ensures we get the exact same route resolution as React Router uses internally,\n * including all presets, file-system routes, and custom route configurations.\n * @param projectDirectory - The project root directory\n * @returns Array of resolved route config entries\n * @example\n * const routes = getReactRouterRoutes('/path/to/project');\n * // Returns the same structure as `react-router routes --json`\n */\nfunction getReactRouterRoutes(projectDirectory: string): RouteConfigEntry[] {\n if (!checkReactRouterCli(projectDirectory)) {\n throw new Error(\n 'React Router CLI is not available. Please make sure @react-router/dev is installed and accessible.'\n );\n }\n\n // Use a temp file to avoid Node.js buffer limits (8KB default)\n const tempFile = join(tmpdir(), `react-router-routes-${randomUUID()}.json`);\n\n try {\n // Redirect output to temp file to avoid buffer truncation\n execSync(`react-router routes --json > \"${tempFile}\"`, {\n cwd: projectDirectory,\n env: npmRunPathEnv(),\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n const output = readFileSync(tempFile, 'utf-8');\n return JSON.parse(output) as RouteConfigEntry[];\n } catch (error) {\n throw new Error(`Failed to get routes from React Router CLI: ${(error as Error).message}`);\n } finally {\n // Clean up temp file\n try {\n if (existsSync(tempFile)) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n }\n}\n\n/**\n * Convert a file path to its corresponding route path using React Router's CLI.\n * This ensures we get the exact same route resolution as React Router uses internally.\n * @param filePath - Absolute path to the route file\n * @param projectRoot - The project root directory\n * @returns The route path (e.g., '/cart', '/product/:productId')\n * @example\n * const route = filePathToRoute('/path/to/project/src/routes/_app.cart.tsx', '/path/to/project');\n * // Returns: '/cart'\n */\nexport function filePathToRoute(filePath: string, projectRoot: string): string {\n // Normalize paths to POSIX-style\n const filePathPosix = filePath.replace(/\\\\/g, '/');\n\n // Get all routes from React Router CLI\n const routes = getReactRouterRoutes(projectRoot);\n const flatRoutes = flattenRoutes(routes);\n\n // Skip root-duplicate routes — these are convenience clones created by applyUrlConfig\n // so the bare \"/\" URL still works. The canonical route (under the site-context prefix)\n // is the one that should appear in cartridge metadata.\n const canonicalRoutes = flatRoutes.filter((route) => !route.id.endsWith('--root-duplicate'));\n\n // Find the route that matches this file\n for (const route of canonicalRoutes) {\n // Normalize the route file path for comparison\n const routeFilePosix = route.file.replace(/\\\\/g, '/');\n const routeFileNormalized = routeFilePosix.replace(/^\\.\\//, '');\n\n // Check if the file path ends with the route file (handles relative vs. absolute paths)\n if (\n filePathPosix.endsWith(routeFilePosix) ||\n filePathPosix.endsWith(`/${routeFilePosix}`) ||\n filePathPosix.endsWith(routeFileNormalized) ||\n filePathPosix.endsWith(`/${routeFileNormalized}`)\n ) {\n return route.path;\n }\n }\n\n // Fallback: if no match found, return a warning path\n logger.warn(`Could not find route for file: ${filePath}`);\n return '/unknown';\n}\n\n/**\n * Flatten a nested route tree into a flat array with computed paths.\n * Each route will have its full path computed from parent paths.\n * @param routes - The nested route config entries\n * @param parentPath - The parent path prefix (used internally for recursion)\n * @returns Flat array of routes with their full paths\n */\nfunction flattenRoutes(\n routes: RouteConfigEntry[],\n parentPath = ''\n): Array<{ id: string; path: string; file: string; index?: boolean }> {\n const result: Array<{ id: string; path: string; file: string; index?: boolean }> = [];\n\n for (const route of routes) {\n // Compute the full path\n let fullPath: string;\n if (route.index) {\n fullPath = parentPath || '/';\n } else if (route.path) {\n // Handle paths that already start with / (absolute paths from extensions)\n const pathSegment = route.path.startsWith('/') ? route.path : `/${route.path}`;\n fullPath = parentPath ? `${parentPath}${pathSegment}`.replace(/\\/+/g, '/') : pathSegment;\n } else {\n // Layout route without path - use parent path\n fullPath = parentPath || '/';\n }\n\n // Add this route if it has an id\n if (route.id) {\n result.push({\n id: route.id,\n path: fullPath,\n file: route.file,\n index: route.index,\n });\n }\n\n // Recursively process children\n if (route.children && route.children.length > 0) {\n const childPath = route.path ? fullPath : parentPath;\n result.push(...flattenRoutes(route.children, childPath));\n }\n }\n\n return result;\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { spawnSync } from 'child_process';\nimport { createRequire } from 'module';\nimport { basename, dirname, join, relative } from 'path';\nimport { fileURLToPath } from 'url';\nimport { logger } from '../logger';\n\n/** This module's own path — the resolution root for the SDK-bundled Biome fallback. */\nconst HERE = fileURLToPath(import.meta.url);\n\n/**\n * Format generated file content with the *consuming project's* Biome so the written file\n * matches what the project's own `biome format` / `pnpm lint:fix` would produce.\n *\n * The SDK generates two kinds of files into a customer project — the extension `config.json`\n * (`trim-extensions.ts`) and the static component registry (`staticRegistry.ts`). Both must\n * be emitted in the exact byte shape the project's formatter produces, or the generated file\n * fails `pnpm lint` on a fresh project / churns on every `biome format --write` (W-23074938).\n *\n * Biome is preferred from the target file's own location — i.e. the consuming project's\n * `node_modules` — so it's the project's Biome version whose output is matched. When that\n * isn't installed yet (e.g. `create-storefront` runs `trim-extensions` BEFORE the generated\n * project's first `pnpm install`), we fall back to the SDK-bundled `@biomejs/biome` (a hard\n * dependency of this package, pinned to the template's version). Either way the file's\n * committed `biome.json` governs the output: Biome discovers its config by walking up from\n * the working directory, so we spawn it with `cwd` set to the file's directory and pass the\n * file's basename via `--stdin-file-path` (which drives both parser selection and formatting).\n *\n * Returns the content unchanged when no Biome can be resolved at all or the format fails, so\n * generation never breaks over formatting. A genuine format error is logged but non-fatal —\n * an unformatted-but-valid file is recoverable by the customer running `biome format --write`.\n *\n * @param content - The serialized file content to format.\n * @param filePath - The file's path (drives parser selection + config resolution + cwd).\n * @returns The Biome-formatted content, or the original content if Biome is unavailable.\n */\nexport function formatWithProjectBiome(content: string, filePath: string): string {\n const biomeBin = resolveBiomeBin(filePath);\n if (!biomeBin) {\n logger.warn(`⚠️ Biome could not be resolved; ${basename(filePath)} will be written unformatted.`);\n return content;\n }\n\n // Biome resolves biome.json by walking up from cwd, so run it from the file's directory\n // and identify the file by basename for parser selection.\n const result = spawnSync(process.execPath, [biomeBin, 'format', `--stdin-file-path=${basename(filePath)}`], {\n cwd: dirname(filePath),\n input: content,\n encoding: 'utf8',\n });\n\n if (result.status !== 0 || typeof result.stdout !== 'string') {\n const detail = result.stderr?.trim() || `exit code ${result.status}`;\n logger.warn(`⚠️ Skipping Biome formatting for ${basename(filePath)}: ${detail}`);\n return content;\n }\n\n return result.stdout;\n}\n\n/**\n * Format every file Biome recognizes under `directory` in place with the consuming project's\n * Biome, so generated files (e.g. cartridge metadata JSON) match `biome format` / `pnpm lint:fix`.\n *\n * Unlike {@link formatWithProjectBiome} (single file via stdin), this runs `biome format --write`\n * against the directory so Biome discovers the project's `biome.json` by walking up from it and\n * applies the project's formatting to the written files directly.\n *\n * Fail-safe: when Biome can't be resolved or the run fails, the files are left as written (valid,\n * just unformatted) and a warning is logged — generation never breaks over formatting.\n *\n * @param directory - Directory whose Biome-recognized files should be formatted in place.\n */\nexport function formatDirectoryWithProjectBiome(directory: string): void {\n // Resolve Biome as if from a file inside the directory, so a node_modules directly under\n // `directory` is on the resolution path (createRequire resolves relative to the file's dir).\n const biomeBin = resolveBiomeBin(join(directory, 'biome-resolution-root.js'));\n if (!biomeBin) {\n logger.warn(`⚠️ Biome could not be resolved; generated files in ${directory} were left unformatted.`);\n return;\n }\n\n // `--write` formats in place; Biome resolves biome.json by walking up from cwd, so run it\n // from the target directory. It exits non-zero if a file can't be fixed, which we treat as\n // non-fatal — the files are still valid, just not reformatted.\n const result = spawnSync(process.execPath, [biomeBin, 'format', '--write', '.'], {\n cwd: directory,\n encoding: 'utf8',\n });\n\n if (result.status !== 0) {\n const detail = result.stderr?.trim() || `exit code ${result.status}`;\n logger.warn(`⚠️ Some generated files in ${directory} could not be formatted by Biome: ${detail}`);\n return;\n }\n\n logger.debug(`✅ Formatted generated files in ${directory} with Biome`);\n}\n\n/**\n * Format only files changed by generation with the SDK-bundled Biome.\n *\n * Extension trimming can touch customer-owned source files, so formatting the project root would\n * rewrite unrelated files. The SDK's pinned Biome keeps this automatic path independent of any\n * target-project executable while the target project's biome.json still determines formatting.\n *\n * @param directory - Project root containing the Biome configuration.\n * @param filePaths - Absolute paths of files changed by generation.\n */\nexport function formatFilesWithBundledBiome(directory: string, filePaths: string[]): void {\n if (filePaths.length === 0) {\n return;\n }\n\n const biomeBin = resolveBiomeBin(HERE);\n if (!biomeBin) {\n logger.warn(`⚠️ Biome could not be resolved; generated files in ${directory} were left unformatted.`);\n return;\n }\n\n const result = spawnSync(\n process.execPath,\n [biomeBin, 'format', '--write', ...filePaths.map((filePath) => relative(directory, filePath))],\n {\n cwd: directory,\n encoding: 'utf8',\n }\n );\n\n if (result.status !== 0) {\n const detail = result.stderr?.trim() || `exit code ${result.status}`;\n logger.warn(`⚠️ Some generated files in ${directory} could not be formatted by Biome: ${detail}`);\n return;\n }\n\n logger.debug(`✅ Formatted ${filePaths.length} generated files in ${directory} with Biome`);\n}\n\n/**\n * Resolve a Biome CLI binary path, preferring the consuming project's install and falling back\n * to the SDK-bundled copy (available pre-install). Returns null when neither resolves.\n */\nfunction resolveBiomeBin(filePath: string): string | null {\n // Prefer the project's own @biomejs/biome (resolved from the target file's location);\n // fall back to this SDK package's bundled copy when the project isn't installed yet.\n for (const fromPath of [filePath, HERE]) {\n try {\n const req = createRequire(fromPath);\n const biomePkgJson = req.resolve('@biomejs/biome/package.json');\n const { bin } = req(biomePkgJson) as { bin: { biome: string } };\n return join(dirname(biomePkgJson), bin.biome);\n } catch {\n // Try the next resolution root.\n }\n }\n return null;\n}\n","#!/usr/bin/env node\n/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { readdir, readFile, writeFile, mkdir, access, rm } from 'node:fs/promises';\nimport { join, extname, resolve, basename } from 'node:path';\nimport { Project, Node, type SourceFile, type PropertyDeclaration, type Decorator, type Expression } from 'ts-morph';\nimport { filePathToRoute } from './react-router-config.js';\nimport { logger } from '../logger';\nimport { formatDirectoryWithProjectBiome } from '../utils/format-with-project-biome';\n\n// Re-export `filePathToRoute`\nexport { filePathToRoute };\n\nconst SKIP_DIRECTORIES = ['build', 'dist', 'node_modules', '.git', '.next', 'coverage', 'verticals'];\n\nconst DEFAULT_COMPONENT_GROUP = 'storefrontnext_base';\nconst ARCH_TYPE_HEADLESS = 'headless';\n\ntype AttributeType =\n | 'string'\n | 'text'\n | 'markup'\n | 'integer'\n | 'boolean'\n | 'product'\n | 'category'\n | 'file'\n | 'page'\n | 'image'\n | 'url'\n | 'enum'\n | 'custom'\n | 'cms_record';\n\nconst VALID_ATTRIBUTE_TYPES: readonly AttributeType[] = [\n 'string',\n 'text',\n 'markup',\n 'integer',\n 'boolean',\n 'product',\n 'category',\n 'file',\n 'page',\n 'image',\n 'url',\n 'enum',\n 'custom',\n 'cms_record',\n] as const;\n\n// Type mapping for TypeScript types to B2C Commerce attribute types\n// Based on official schema: https://salesforcecommercecloud.github.io/b2c-dev-doc/docs/current/content/attributedefinition.json\nconst TYPE_MAPPING: Record<string, string> = {\n String: 'string',\n string: 'string',\n Number: 'integer',\n number: 'integer',\n Boolean: 'boolean',\n boolean: 'boolean',\n Date: 'string', // B2C Commerce doesn't have a native date type, use string\n URL: 'url',\n CMSRecord: 'cms_record',\n};\n\n// Resolve attribute type in order: decorator type -> ts-morph type inference -> fallback to string\nfunction resolveAttributeType(decoratorType?: string, tsMorphType?: string, fieldName?: string): string {\n // 1) If the type is set on the decorator, use that (with validation)\n if (decoratorType) {\n if (!VALID_ATTRIBUTE_TYPES.includes(decoratorType as AttributeType)) {\n logger.error(\n `Invalid attribute type '${decoratorType}' for field '${fieldName || 'unknown'}'. Valid types are: ${VALID_ATTRIBUTE_TYPES.join(', ')}`\n );\n process.exit(1);\n }\n return decoratorType;\n }\n\n // 2) Use the type from ts-morph type inference\n if (tsMorphType && TYPE_MAPPING[tsMorphType]) {\n return TYPE_MAPPING[tsMorphType];\n }\n\n // 3) Fall back to string\n return 'string';\n}\n\n// Attribute types for which the Page Designer metadefinition schema forbids `searching`.\nconst SEARCHING_FORBIDDEN_TYPES = new Set(['integer', 'boolean', 'file', 'page', 'image', 'url', 'enum']);\n\n/**\n * Validate an authored `searching` config against the resolved attribute type and map it to the\n * snake_case schema shape. The metadefinition schema gates `searching` by type; an invalid\n * combination fails cartridge generation (matching the strict behavior of `resolveAttributeType`).\n *\n * Rules (from attributedefinition.json):\n * - Forbidden entirely on integer/boolean/file/page/image/url/enum.\n * - `markup`: `sortable` must be false.\n * - `custom`/`cms_record`: `refinable` must be false; `boost_factor`/`sortable` not allowed.\n * - `string`/`text`/`product`/`category`: all fields allowed.\n */\nfunction mapAttributeSearching(\n searching: Record<string, unknown>,\n resolvedType: string,\n fieldName: string\n): Record<string, unknown> {\n const fail = (reason: string): never => {\n logger.error(`Invalid 'searching' config for attribute '${fieldName}' (type '${resolvedType}'): ${reason}`);\n process.exit(1);\n };\n\n if (SEARCHING_FORBIDDEN_TYPES.has(resolvedType)) {\n fail(`the '${resolvedType}' attribute type does not support searching.`);\n }\n\n const { searchable, refinable, boostFactor, sortable } = searching as {\n searchable?: unknown;\n refinable?: unknown;\n boostFactor?: unknown;\n sortable?: unknown;\n };\n\n if (typeof searchable !== 'boolean' || typeof refinable !== 'boolean') {\n fail(`'searchable' and 'refinable' are required booleans.`);\n }\n\n if (resolvedType === 'markup' && sortable === true) {\n fail(`'sortable' must be false for markup attributes.`);\n }\n\n if (resolvedType === 'custom' || resolvedType === 'cms_record') {\n if (refinable === true) {\n fail(`'refinable' must be false for ${resolvedType} attributes.`);\n }\n if (boostFactor !== undefined) {\n fail(`'boostFactor' is not supported for ${resolvedType} attributes.`);\n }\n if (sortable === true) {\n fail(`'sortable' must be false for ${resolvedType} attributes.`);\n }\n }\n\n const mapped: Record<string, unknown> = { searchable, refinable };\n if (boostFactor !== undefined) {\n mapped.boost_factor = boostFactor;\n }\n if (sortable !== undefined) {\n mapped.sortable = sortable;\n }\n return mapped;\n}\n\n/**\n * Validate an authored `dynamicLookup` config and map it to the snake_case schema shape.\n * The metadefinition schema allows `dynamic_lookup` on all attribute types but requires a\n * single `aspect_attribute_alias` field (`additionalProperties: false`); a missing alias fails\n * cartridge generation (matching the strict behavior of `resolveAttributeType`).\n */\nfunction mapAttributeDynamicLookup(dynamicLookup: Record<string, unknown>, fieldName: string): Record<string, unknown> {\n const { aspectAttributeAlias } = dynamicLookup as { aspectAttributeAlias?: unknown };\n\n if (typeof aspectAttributeAlias !== 'string' || aspectAttributeAlias.length === 0) {\n logger.error(\n `Invalid 'dynamicLookup' config for attribute '${fieldName}': 'aspectAttributeAlias' is required and must be a non-empty string.`\n );\n process.exit(1);\n }\n\n return { aspect_attribute_alias: aspectAttributeAlias };\n}\n\n// Convert field name to human-readable name\nfunction toHumanReadableName(fieldName: string): string {\n return fieldName\n .replace(/([A-Z])/g, ' $1') // Add space before capital letters\n .replace(/^./, (str) => str.toUpperCase()) // Capitalize first letter\n .trim();\n}\n\n// Convert name to camelCase filename (handles spaces and hyphens, preserves existing camelCase)\nfunction toCamelCaseFileName(name: string): string {\n // If the name is already camelCase (no spaces or hyphens), return as-is\n if (!/[\\s-]/.test(name)) {\n return name;\n }\n\n return name\n .split(/[\\s-]+/) // Split by whitespace and hyphens\n .map((word, index) => {\n if (index === 0) {\n return word.toLowerCase(); // First word is all lowercase\n }\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); // Subsequent words are capitalized\n })\n .join(''); // Join without spaces or hyphens\n}\n\nfunction getTypeFromTsMorph(property: PropertyDeclaration, _sourceFile: SourceFile): string {\n try {\n const typeNode = property.getTypeNode();\n if (typeNode) {\n const typeText = typeNode.getText();\n // Extract the base type name from complex types\n const baseType = typeText.split('|')[0].split('&')[0].trim();\n return baseType;\n }\n } catch {\n // If type extraction fails, return string\n }\n\n return 'string';\n}\n\n/**\n * Resolve a variable's initializer expression from the same source file,\n * unwrapping `as const` type assertions.\n */\nfunction resolveVariableInitializer(sourceFile: SourceFile, name: string): Expression | undefined {\n const varDecl = sourceFile.getVariableDeclaration(name);\n if (!varDecl) return undefined;\n let initializer = varDecl.getInitializer();\n if (initializer && Node.isAsExpression(initializer)) {\n initializer = initializer.getExpression();\n }\n return initializer;\n}\n\n/**\n * Check whether an AST node is a type that `parseExpression` can resolve to a\n * concrete JS value (as opposed to falling through to `getText()`).\n */\nfunction isResolvableLiteral(node: Expression): boolean {\n return (\n Node.isStringLiteral(node) ||\n Node.isNumericLiteral(node) ||\n Node.isTrueLiteral(node) ||\n Node.isFalseLiteral(node) ||\n Node.isObjectLiteralExpression(node) ||\n Node.isArrayLiteralExpression(node)\n );\n}\n\nclass UnresolvedConstantReferenceError extends Error {\n constructor(reference: string) {\n super(\n `Cannot resolve constant reference '${reference}'. ` +\n `Ensure the variable is declared in the same file as a literal value.`\n );\n this.name = 'UnresolvedConstantReferenceError';\n }\n}\n\n// Helper function to parse any TypeScript expression into a JavaScript value\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseExpression(expression: any): unknown {\n if (Node.isStringLiteral(expression)) {\n return expression.getLiteralValue();\n } else if (Node.isNumericLiteral(expression)) {\n return expression.getLiteralValue();\n } else if (Node.isTrueLiteral(expression)) {\n return true;\n } else if (Node.isFalseLiteral(expression)) {\n return false;\n } else if (Node.isObjectLiteralExpression(expression)) {\n return parseNestedObject(expression);\n } else if (Node.isArrayLiteralExpression(expression)) {\n return parseArrayLiteral(expression);\n } else if (Node.isPropertyAccessExpression(expression)) {\n const obj = expression.getExpression();\n const propName = expression.getName();\n if (Node.isIdentifier(obj)) {\n const resolved = resolveVariableInitializer(expression.getSourceFile(), obj.getText());\n if (resolved && Node.isObjectLiteralExpression(resolved)) {\n const prop = resolved.getProperty(propName);\n if (prop && Node.isPropertyAssignment(prop)) {\n const propInit = prop.getInitializer();\n if (propInit) return parseExpression(propInit);\n }\n }\n throw new UnresolvedConstantReferenceError(expression.getText());\n }\n return expression.getText();\n } else if (Node.isIdentifier(expression)) {\n const resolved = resolveVariableInitializer(expression.getSourceFile(), expression.getText());\n if (resolved && isResolvableLiteral(resolved)) {\n return parseExpression(resolved);\n }\n return expression.getText();\n } else {\n return expression.getText();\n }\n}\n\n// Helper function to parse deeply nested object literals\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseNestedObject(objectLiteral: any): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n try {\n const properties = objectLiteral.getProperties();\n\n for (const property of properties) {\n if (Node.isPropertyAssignment(property)) {\n const name = property.getName();\n const initializer = property.getInitializer();\n\n if (initializer) {\n result[name] = parseExpression(initializer);\n }\n }\n }\n } catch (error) {\n logger.warn(`Could not parse nested object: ${(error as Error).message}`);\n return result; // Return the result even if there was an error\n }\n\n return result;\n}\n\n// Helper function to parse array literals\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseArrayLiteral(arrayLiteral: any): unknown[] {\n const result: unknown[] = [];\n\n try {\n const elements = arrayLiteral.getElements();\n\n for (const element of elements) {\n result.push(parseExpression(element));\n }\n } catch (error) {\n logger.warn(`Could not parse array literal: ${(error as Error).message}`);\n }\n\n return result;\n}\n\n// Parse decorator arguments using ts-morph\nfunction parseDecoratorArgs(decorator: Decorator): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n try {\n const args = decorator.getArguments();\n\n if (args.length === 0) {\n return result;\n }\n\n // Handle the first argument\n const firstArg = args[0];\n\n if (Node.isObjectLiteralExpression(firstArg)) {\n // First argument is an object literal - parse all its properties\n const properties = firstArg.getProperties();\n\n for (const property of properties) {\n if (Node.isPropertyAssignment(property)) {\n const name = property.getName();\n const initializer = property.getInitializer();\n\n if (initializer) {\n result[name] = parseExpression(initializer);\n }\n }\n }\n } else if (Node.isStringLiteral(firstArg)) {\n // First argument is a string literal - use it as the id\n result.id = parseExpression(firstArg);\n\n // Check if there's a second argument (options object)\n if (args.length > 1) {\n const secondArg = args[1];\n if (Node.isObjectLiteralExpression(secondArg)) {\n const properties = secondArg.getProperties();\n\n for (const property of properties) {\n if (Node.isPropertyAssignment(property)) {\n const name = property.getName();\n const initializer = property.getInitializer();\n\n if (initializer) {\n result[name] = parseExpression(initializer);\n }\n }\n }\n }\n }\n }\n\n return result;\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not parse decorator arguments: ${(error as Error).message}`);\n return result;\n }\n}\n\nfunction extractAttributesFromSource(sourceFile: SourceFile, className: string): Record<string, unknown>[] {\n const attributes: Record<string, unknown>[] = [];\n\n try {\n // Find the class declaration\n const classDeclaration = sourceFile.getClass(className);\n if (!classDeclaration) {\n return attributes;\n }\n\n // Get all properties in the class\n const properties = classDeclaration.getProperties();\n\n for (const property of properties) {\n // Check if the property has an @AttributeDefinition decorator\n const attributeDecorator = property.getDecorator('AttributeDefinition');\n if (!attributeDecorator) {\n continue;\n }\n\n const fieldName = property.getName();\n const config = parseDecoratorArgs(attributeDecorator);\n\n const isRequired = !property.hasQuestionToken();\n\n const inferredType = (config.type as string) || getTypeFromTsMorph(property, sourceFile);\n\n const attribute: Record<string, unknown> = {\n id: config.id || fieldName,\n name: config.name || toHumanReadableName(fieldName),\n type: resolveAttributeType(config.type as string, inferredType, fieldName),\n required: config.required !== undefined ? config.required : isRequired,\n description: config.description || `Field: ${fieldName}`,\n };\n\n if (config.values) {\n attribute.values = config.values;\n }\n\n if (config.defaultValue !== undefined) {\n attribute.default_value = config.defaultValue;\n }\n\n if (config.editorDefinition !== undefined) {\n attribute.editor_definition = config.editorDefinition;\n }\n\n if (config.searching !== undefined) {\n attribute.searching = mapAttributeSearching(\n config.searching as Record<string, unknown>,\n attribute.type as string,\n String(attribute.id)\n );\n }\n\n if (config.dynamicLookup !== undefined) {\n attribute.dynamic_lookup = mapAttributeDynamicLookup(\n config.dynamicLookup as Record<string, unknown>,\n String(attribute.id)\n );\n }\n\n attributes.push(attribute);\n }\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not extract attributes from class ${className}: ${(error as Error).message}`);\n }\n\n return attributes;\n}\n\nfunction normalizeComponentTypeId(typeId: string, defaultGroup: string): string {\n return typeId.includes('.') ? typeId : `${defaultGroup}.${typeId}`;\n}\n\nfunction extractRegionDefinitionsFromSource(\n sourceFile: SourceFile,\n className: string,\n defaultComponentGroup = DEFAULT_COMPONENT_GROUP\n): Record<string, unknown>[] {\n const regionDefinitions: Record<string, unknown>[] = [];\n\n try {\n // Find the class declaration\n const classDeclaration = sourceFile.getClass(className);\n if (!classDeclaration) {\n return regionDefinitions;\n }\n\n // Check for class-level @RegionDefinition decorator\n const classRegionDecorator = classDeclaration.getDecorator('RegionDefinition');\n if (classRegionDecorator) {\n const args = classRegionDecorator.getArguments();\n if (args.length > 0) {\n const firstArg = args[0];\n\n // Handle array literal argument (most common case)\n if (Node.isArrayLiteralExpression(firstArg)) {\n const elements = firstArg.getElements();\n for (const element of elements) {\n if (Node.isObjectLiteralExpression(element)) {\n const regionConfig = parseDecoratorArgs({\n getArguments: () => [element],\n } as unknown as Decorator);\n\n const regionDefinition: Record<string, unknown> = {\n id: regionConfig.id || 'region',\n name: regionConfig.name || 'Region',\n };\n\n // Add optional properties if they exist in the decorator\n if (regionConfig.description !== undefined) {\n regionDefinition.description = regionConfig.description;\n }\n\n if (regionConfig.componentTypes) {\n regionDefinition.component_types = regionConfig.componentTypes;\n }\n\n if (Array.isArray(regionConfig.componentTypeInclusions)) {\n regionDefinition.component_type_inclusions = regionConfig.componentTypeInclusions.map(\n (incl) => ({\n type_id: normalizeComponentTypeId(String(incl), defaultComponentGroup),\n })\n );\n }\n\n if (Array.isArray(regionConfig.componentTypeExclusions)) {\n regionDefinition.component_type_exclusions = regionConfig.componentTypeExclusions.map(\n (excl) => ({\n type_id: normalizeComponentTypeId(String(excl), defaultComponentGroup),\n })\n );\n }\n\n if (regionConfig.maxComponents !== undefined) {\n regionDefinition.max_components = regionConfig.maxComponents;\n }\n\n if (regionConfig.minComponents !== undefined) {\n regionDefinition.min_components = regionConfig.minComponents;\n }\n\n if (regionConfig.allowMultiple !== undefined) {\n regionDefinition.allow_multiple = regionConfig.allowMultiple;\n }\n\n if (Array.isArray(regionConfig.defaultComponentConstructors)) {\n // Map the decorator's authoring shape ({ id, typeId, data }) onto the\n // Page Designer componentconstructor schema, which only permits\n // `type_id` (required), `name`, and nested `region_component_constructors`.\n // The decorator's `id`/`data` fields have no place in the metadefinition\n // format (`additionalProperties: false`), so they are intentionally dropped.\n regionDefinition.default_component_constructors =\n regionConfig.defaultComponentConstructors.map((constructor) => {\n const { typeId, name } = constructor as {\n typeId?: unknown;\n name?: unknown;\n };\n const mapped: Record<string, unknown> = {\n type_id: normalizeComponentTypeId(String(typeId), defaultComponentGroup),\n };\n if (name !== undefined) {\n mapped.name = name;\n }\n return mapped;\n });\n }\n\n regionDefinitions.push(regionDefinition);\n }\n }\n }\n }\n }\n } catch (error) {\n logger.warn(\n `Warning: Could not extract region definitions from class ${className}: ${(error as Error).message}`\n );\n }\n\n return regionDefinitions;\n}\n\nasync function processComponentFile(filePath: string, _projectRoot: string): Promise<unknown[]> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const components: unknown[] = [];\n\n // Check if file contains @Component decorator\n if (!content.includes('@Component')) {\n return components;\n }\n\n // Convert file path to module path (currently unused but may be needed in future)\n // const relativePath = relative(join(projectRoot, 'src'), filePath);\n // const modulePath = relativePath.replace(/\\.tsx?$/, '').replace(/\\\\/g, '/');\n\n try {\n // Create a ts-morph project and add the source file\n const project = new Project({\n useInMemoryFileSystem: true,\n skipAddingFilesFromTsConfig: true,\n });\n\n const sourceFile = project.createSourceFile(filePath, content);\n\n const classes = sourceFile.getClasses();\n\n for (const classDeclaration of classes) {\n const componentDecorator = classDeclaration.getDecorator('Component');\n if (!componentDecorator) {\n continue;\n }\n\n const className = classDeclaration.getName();\n if (!className) {\n continue;\n }\n\n const componentConfig = parseDecoratorArgs(componentDecorator);\n const componentGroup = String(componentConfig.group || DEFAULT_COMPONENT_GROUP);\n\n const attributes = extractAttributesFromSource(sourceFile, className);\n const regionDefinitions = extractRegionDefinitionsFromSource(sourceFile, className, componentGroup);\n\n const componentMetadata: Record<string, unknown> = {\n typeId: componentConfig.id || className.toLowerCase(),\n name: componentConfig.name || toHumanReadableName(className),\n group: componentGroup,\n description: componentConfig.description || `Custom component: ${className}`,\n regionDefinitions,\n attributes,\n };\n\n if (typeof componentConfig.embedded === 'boolean') {\n componentMetadata.embedded = componentConfig.embedded;\n }\n if (componentConfig.component_id !== undefined) {\n componentMetadata.component_id = String(componentConfig.component_id);\n }\n\n components.push(componentMetadata);\n }\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not process file ${filePath}:`, (error as Error).message);\n }\n\n return components;\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not read file ${filePath}:`, (error as Error).message);\n return [];\n }\n}\n\nasync function processPageTypeFile(filePath: string, projectRoot: string): Promise<unknown[]> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const pageTypes: unknown[] = [];\n\n // Check if file contains @PageType decorator\n if (!content.includes('@PageType')) {\n return pageTypes;\n }\n\n try {\n // Create a ts-morph project and add the source file\n const project = new Project({\n useInMemoryFileSystem: true,\n skipAddingFilesFromTsConfig: true,\n });\n\n const sourceFile = project.createSourceFile(filePath, content);\n\n const classes = sourceFile.getClasses();\n\n for (const classDeclaration of classes) {\n const pageTypeDecorator = classDeclaration.getDecorator('PageType');\n if (!pageTypeDecorator) {\n continue;\n }\n\n const className = classDeclaration.getName();\n if (!className) {\n continue;\n }\n\n const pageTypeConfig = parseDecoratorArgs(pageTypeDecorator);\n\n const attributes = extractAttributesFromSource(sourceFile, className);\n const regionDefinitions = extractRegionDefinitionsFromSource(sourceFile, className);\n const route = filePathToRoute(filePath, projectRoot);\n\n const pageTypeMetadata = {\n typeId: pageTypeConfig.id || className.toLowerCase(),\n name: pageTypeConfig.name || toHumanReadableName(className),\n description: pageTypeConfig.description || `Custom page type: ${className}`,\n regionDefinitions,\n supportedAspectTypes: pageTypeConfig.supportedAspectTypes || [],\n attributes,\n route,\n // Only carry `preview` when the decorator declared it, so undeclared page types\n // stay clean and the emitted JSON omits the field entirely.\n ...(pageTypeConfig.preview !== undefined && { preview: pageTypeConfig.preview }),\n };\n\n pageTypes.push(pageTypeMetadata);\n }\n } catch (error) {\n logger.warn(`Could not process file ${filePath}:`, (error as Error).message);\n }\n\n return pageTypes;\n } catch (error) {\n logger.warn(`Could not read file ${filePath}:`, (error as Error).message);\n return [];\n }\n}\n\nasync function processAspectFile(filePath: string, _projectRoot: string): Promise<unknown[]> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const aspects: unknown[] = [];\n\n // Check if file is a JSON aspect file\n if (!filePath.endsWith('.json') || !content.trim().startsWith('{')) {\n return aspects;\n }\n\n // Check if file is in the aspects directory\n if (!filePath.includes('/aspects/') && !filePath.includes('\\\\aspects\\\\')) {\n return aspects;\n }\n\n try {\n // Parse the JSON content\n const aspectData = JSON.parse(content);\n\n // Extract filename without extension as the aspect ID\n const fileName = basename(filePath, '.json');\n\n // Validate that it looks like an aspect file\n if (!aspectData.name || !aspectData.attribute_definitions) {\n return aspects;\n }\n\n const aspectMetadata = {\n id: fileName,\n name: aspectData.name,\n description: aspectData.description || `Aspect type: ${aspectData.name}`,\n attributeDefinitions: aspectData.attribute_definitions || [],\n supportedObjectTypes: aspectData.supported_object_types || [],\n };\n\n aspects.push(aspectMetadata);\n } catch (parseError) {\n logger.warn(`Could not parse JSON in file ${filePath}:`, (parseError as Error).message);\n }\n\n return aspects;\n } catch (error) {\n logger.warn(`Could not read file ${filePath}:`, (error as Error).message);\n return [];\n }\n}\n\nasync function generateComponentCartridge(\n component: Record<string, unknown>,\n outputDir: string,\n dryRun = false\n): Promise<void> {\n const fileName = toCamelCaseFileName(component.typeId as string);\n const groupDir = join(outputDir, component.group as string);\n const outputPath = join(groupDir, `${fileName}.json`);\n\n if (!dryRun) {\n // Ensure the group directory exists\n try {\n await mkdir(groupDir, { recursive: true });\n } catch {\n // Directory might already exist, which is fine\n }\n\n const attributeDefinitionGroups = [\n {\n id: component.typeId,\n name: component.name,\n description: component.description,\n attribute_definitions: component.attributes,\n },\n ];\n\n const cartridgeData: Record<string, unknown> = {\n name: component.name,\n description: component.description,\n group: component.group,\n arch_type: ARCH_TYPE_HEADLESS,\n ...(typeof component.embedded === 'boolean' && { embedded: component.embedded }),\n component_id: component.component_id,\n region_definitions: component.regionDefinitions || [],\n attribute_definition_groups: attributeDefinitionGroups,\n };\n\n await writeFile(outputPath, JSON.stringify(cartridgeData, null, 2));\n }\n\n const prefix = dryRun ? ' - [DRY RUN]' : ' -';\n logger.debug(\n `${prefix} ${String(component.typeId)}: ${String(component.name)} (${String((component.attributes as unknown[]).length)} attributes) → ${fileName}.json`\n );\n}\n\nasync function generatePageTypeCartridge(\n pageType: Record<string, unknown>,\n outputDir: string,\n dryRun = false\n): Promise<void> {\n const fileName = toCamelCaseFileName(pageType.name as string);\n const outputPath = join(outputDir, `${fileName}.json`);\n\n if (!dryRun) {\n const cartridgeData: Record<string, unknown> = {\n name: pageType.name,\n description: pageType.description,\n arch_type: ARCH_TYPE_HEADLESS,\n region_definitions: pageType.regionDefinitions || [],\n };\n\n // Add attribute_definition_groups if there are attributes\n if (pageType.attributes && (pageType.attributes as unknown[]).length > 0) {\n const attributeDefinitionGroups = [\n {\n id: pageType.typeId || fileName,\n name: pageType.name,\n description: pageType.description,\n attribute_definitions: pageType.attributes,\n },\n ];\n cartridgeData.attribute_definition_groups = attributeDefinitionGroups;\n }\n\n // Add supported_aspect_types if specified\n if (pageType.supportedAspectTypes) {\n cartridgeData.supported_aspect_types = pageType.supportedAspectTypes;\n }\n\n if (pageType.route) {\n cartridgeData.route = pageType.route;\n }\n\n // Add preview only when the page type declared it (omitted otherwise to keep existing\n // page-type JSON byte-stable). Use the same presence check as processPageTypeFile so the\n // \"declared\" gate is identical on both sides.\n if (pageType.preview !== undefined) {\n cartridgeData.preview = pageType.preview;\n }\n\n await writeFile(outputPath, JSON.stringify(cartridgeData, null, 2));\n }\n\n const prefix = dryRun ? ' - [DRY RUN]' : ' -';\n logger.debug(\n `${prefix} ${String(pageType.name)}: ${String(pageType.description)} (${String((pageType.attributes as unknown[]).length)} attributes) → ${fileName}.json`\n );\n}\n\nasync function generateAspectCartridge(\n aspect: Record<string, unknown>,\n outputDir: string,\n dryRun = false\n): Promise<void> {\n const fileName = toCamelCaseFileName(aspect.id as string);\n const outputPath = join(outputDir, `${fileName}.json`);\n\n if (!dryRun) {\n const cartridgeData: Record<string, unknown> = {\n name: aspect.name,\n description: aspect.description,\n arch_type: ARCH_TYPE_HEADLESS,\n attribute_definitions: aspect.attributeDefinitions || [],\n };\n\n // Add supported_object_types if specified\n if (aspect.supportedObjectTypes) {\n cartridgeData.supported_object_types = aspect.supportedObjectTypes;\n }\n\n await writeFile(outputPath, JSON.stringify(cartridgeData, null, 2));\n }\n\n const prefix = dryRun ? ' - [DRY RUN]' : ' -';\n logger.debug(\n `${prefix} ${String(aspect.name)}: ${String(aspect.description)} (${String((aspect.attributeDefinitions as unknown[]).length)} attributes) → ${fileName}.json`\n );\n}\n\n/**\n * Options for generateMetadata function\n */\nexport interface GenerateMetadataOptions {\n /**\n * Optional array of specific file paths to process.\n * If provided, only these files will be processed and existing cartridge files will NOT be deleted.\n * If omitted, the entire src/ directory will be scanned and all existing cartridge files will be deleted first.\n */\n filePaths?: string[];\n\n /**\n * Whether to format generated JSON files with Biome so they match the project's formatting.\n * Defaults to true.\n */\n lintFix?: boolean;\n\n /**\n * If true, scans files and reports what would be generated without actually writing any files or deleting directories.\n * Defaults to false.\n */\n dryRun?: boolean;\n}\n\n/**\n * Result returned by generateMetadata function\n */\nexport interface GenerateMetadataResult {\n componentsGenerated: number;\n pageTypesGenerated: number;\n aspectsGenerated: number;\n totalFiles: number;\n}\n\n/**\n * Formats the generated JSON files in place so they match the project's `biome format` output\n * (and therefore pass `pnpm lint` out of the box). Delegates to the shared Biome helper, which\n * prefers the consuming project's Biome and is fail-safe (logs and leaves files valid-but-\n * unformatted rather than throwing) when Biome can't run.\n */\nfunction lintGeneratedFiles(metadataDir: string): void {\n logger.debug('🔧 Formatting generated JSON files with Biome...');\n formatDirectoryWithProjectBiome(metadataDir);\n}\n\n// Main function\nexport async function generateMetadata(\n projectDirectory: string,\n metadataDirectory: string,\n options?: GenerateMetadataOptions\n): Promise<GenerateMetadataResult> {\n try {\n const filePaths = options?.filePaths;\n const isIncrementalMode = filePaths && filePaths.length > 0;\n const dryRun = options?.dryRun || false;\n\n if (dryRun) {\n logger.debug('🔍 [DRY RUN] Scanning for decorated components and page types...');\n } else if (isIncrementalMode) {\n logger.debug(`🔍 Generating metadata for ${filePaths.length} specified file(s)...`);\n } else {\n logger.debug('🔍 Generating metadata for decorated components and page types...');\n }\n\n const projectRoot = resolve(projectDirectory);\n const srcDir = join(projectRoot, 'src');\n const metadataDir = resolve(metadataDirectory);\n const componentsOutputDir = join(metadataDir, 'components');\n const pagesOutputDir = join(metadataDir, 'pages');\n const aspectsOutputDir = join(metadataDir, 'aspects');\n\n // Skip directory operations in dry run mode\n if (!dryRun) {\n // Only delete existing directories in full scan mode (not incremental)\n if (!isIncrementalMode) {\n logger.debug('🗑️ Cleaning existing output directories...');\n for (const outputDir of [componentsOutputDir, pagesOutputDir, aspectsOutputDir]) {\n try {\n await rm(outputDir, { recursive: true, force: true });\n logger.debug(` - Deleted: ${outputDir}`);\n } catch {\n // Directory might not exist, which is fine\n logger.debug(` - Directory not found (skipping): ${outputDir}`);\n }\n }\n } else {\n logger.debug('📝 Incremental mode: existing cartridge files will be preserved/overwritten');\n }\n\n // Create output directories if they don't exist\n logger.debug('Creating output directories...');\n for (const outputDir of [componentsOutputDir, pagesOutputDir, aspectsOutputDir]) {\n try {\n await mkdir(outputDir, { recursive: true });\n } catch (error) {\n try {\n await access(outputDir);\n // Directory exists, that's fine\n } catch {\n const err = error as Error;\n logger.error(`❌ Failed to create output directory ${outputDir}: ${err.message}`);\n process.exit(1);\n throw err;\n }\n }\n }\n } else if (isIncrementalMode) {\n logger.debug(`📝 [DRY RUN] Would process ${filePaths.length} specific file(s)`);\n } else {\n logger.debug('📝 [DRY RUN] Would clean and regenerate all metadata files');\n }\n\n let files: string[] = [];\n\n if (isIncrementalMode && filePaths) {\n // Use the specified file paths (resolve them relative to project root)\n files = filePaths.map((fp) => resolve(projectRoot, fp));\n logger.debug(`📂 Processing ${files.length} specified file(s)...`);\n } else {\n // Full scan mode: scan entire src directory\n const scanDirectory = async (dir: string): Promise<void> => {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n\n if (entry.isDirectory()) {\n if (!SKIP_DIRECTORIES.includes(entry.name)) {\n await scanDirectory(fullPath);\n }\n } else if (\n entry.isFile() &&\n (extname(entry.name) === '.ts' ||\n extname(entry.name) === '.tsx' ||\n extname(entry.name) === '.json')\n ) {\n files.push(fullPath);\n }\n }\n };\n\n await scanDirectory(srcDir);\n\n const configMetadataDir = join(projectRoot, 'config-metadata');\n try {\n await access(configMetadataDir);\n await scanDirectory(configMetadataDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n logger.debug(` - Directory not found (skipping): ${configMetadataDir}`);\n } else {\n logger.warn(` - Unable to access ${configMetadataDir}:`, (error as Error).message);\n }\n }\n }\n\n // Process each file for both components and page types\n const allComponents: unknown[] = [];\n const allPageTypes: unknown[] = [];\n const allAspects: unknown[] = [];\n\n for (const file of files) {\n const components = await processComponentFile(file, projectRoot);\n allComponents.push(...components);\n\n const pageTypes = await processPageTypeFile(file, projectRoot);\n allPageTypes.push(...pageTypes);\n\n const aspects = await processAspectFile(file, projectRoot);\n allAspects.push(...aspects);\n }\n\n if (allComponents.length === 0 && allPageTypes.length === 0 && allAspects.length === 0) {\n logger.info('⚠️ No decorated components, page types, or aspect files found.');\n return {\n componentsGenerated: 0,\n pageTypesGenerated: 0,\n aspectsGenerated: 0,\n totalFiles: 0,\n };\n }\n\n // Generate component cartridge files\n if (allComponents.length > 0) {\n logger.debug(`✅ Found ${allComponents.length} decorated component(s)`);\n for (const component of allComponents) {\n await generateComponentCartridge(component as Record<string, unknown>, componentsOutputDir, dryRun);\n }\n if (dryRun) {\n logger.info(`[DRY RUN] Would generate ${allComponents.length} component metadata file(s)`);\n } else {\n logger.info(`Generated ${allComponents.length} component metadata file(s)`);\n }\n }\n\n // Generate page type cartridge files\n if (allPageTypes.length > 0) {\n logger.debug(`✅ Found ${allPageTypes.length} decorated page type(s)`);\n for (const pageType of allPageTypes) {\n await generatePageTypeCartridge(pageType as Record<string, unknown>, pagesOutputDir, dryRun);\n }\n if (dryRun) {\n logger.info(`[DRY RUN] Would generate ${allPageTypes.length} page type metadata file(s)`);\n } else {\n logger.info(`Generated ${allPageTypes.length} page type metadata file(s)`);\n }\n }\n\n if (allAspects.length > 0) {\n logger.debug(`✅ Found ${allAspects.length} decorated aspect(s)`);\n for (const aspect of allAspects) {\n await generateAspectCartridge(aspect as Record<string, unknown>, aspectsOutputDir, dryRun);\n }\n if (dryRun) {\n logger.info(`[DRY RUN] Would generate ${allAspects.length} aspect metadata file(s)`);\n } else {\n logger.info(`Generated ${allAspects.length} aspect metadata file(s)`);\n }\n }\n\n // Format generated JSON files with Biome so they match the project's formatting.\n const shouldLintFix = options?.lintFix !== false; // Default to true\n if (\n !dryRun &&\n shouldLintFix &&\n (allComponents.length > 0 || allPageTypes.length > 0 || allAspects.length > 0)\n ) {\n lintGeneratedFiles(metadataDir);\n }\n\n // Return statistics\n return {\n componentsGenerated: allComponents.length,\n pageTypesGenerated: allPageTypes.length,\n aspectsGenerated: allAspects.length,\n totalFiles: allComponents.length + allPageTypes.length + allAspects.length,\n };\n } catch (error) {\n const err = error as Error;\n logger.error('❌ Error:', err.message);\n process.exit(1);\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8DA,MAAMA,iBAA2C;CAC7C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACV;AAED,IAAIC;;;;;;AAOJ,SAAS,qBAA8B;CACnC,MAAM,MAAM,QAAQ,IAAI,OAAO,MAAM;AACrC,KAAI,CAAC,IAAK,Q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AM,2BAA2B,WAAsC,qBAAqB,OAAO;AAEvG,OAAI,OACA,QAAO,KAAK,4BAA4B,cAAc,OAAO,6BAA6B;OAE1F,QAAO,KAAK,aAAa,cAAc,OAAO,6BAA6B;;AAKnF,MAAI,aAAa,SAAS,GAAG;AACzB,UAAO,MAAM,WAAW,aAAa,OAAO,yBAAyB;AACrE,QAAK,MAAM,YAAY,aACnB,OAAM,0BAA0B,UAAqC,gBAAgB,OAAO;AAEhG,OAAI,OACA,QAAO,KAAK,4BAA4B,aAAa,OAAO,6BAA6B;OAEzF,QAAO,KAAK,aAAa,aAAa,OAAO,6BAA6B;;AAIlF,MAAI,WAAW,SAAS,GAAG;AACvB,UAAO,MAAM,WAAW,WAAW,OAAO,sBAAsB;AAChE,QAAK,MAAM,UAAU,WACjB,OAAM,wBAAwB,QAAmC,kBAAkB,OAAO;AAE9F,OAAI,OACA,QAAO,KAAK,4BAA4B,WAAW,OAAO,0BAA0B;OAEpF,QAAO,KAAK,aAAa,WAAW,OAAO,0BAA0B;;EAK7E,MAAM,gBAAgB,SAAS,YAAY;AAC3C,MACI,CAAC,UACD,kBACC,cAAc,SAAS,KAAK,aAAa,SAAS,KAAK,WAAW,SAAS,GAE5E,oBAAmB,YAAY;AAInC,SAAO;GACH,qBAAqB,cAAc;GACnC,oBAAoB,aAAa;GACjC,kBAAkB,WAAW;GAC7B,YAAY,cAAc,SAAS,aAAa,SAAS,WAAW;GACvE;UACI,OAAO;EACZ,MAAM,MAAM;AACZ,SAAO,MAAM,YAAY,IAAI,QAAQ;AACrC,UAAQ,KAAK,EAAE;AACf,QAAM"}
1
+ {"version":3,"file":"index.js","names":["LEVEL_PRIORITY: Record<LogLevel, number>","MRT_NUMERIC_TO_LEVEL: Record<string, LogLevel>","overrideLevel: LogLevel | undefined","isCliAvailable: boolean | null","result: Array<{ id: string; path: string; file: string; index?: boolean }>","fullPath: string","join","VALID_ATTRIBUTE_TYPES: readonly AttributeType[]","TYPE_MAPPING: Record<string, string>","mapped: Record<string, unknown>","result: Record<string, unknown>","result: unknown[]","attributes: Record<string, unknown>[]","attribute: Record<string, unknown>","regionDefinitions: Record<string, unknown>[]","regionDefinition: Record<string, unknown>","components: unknown[]","componentMetadata: Record<string, unknown>","pageTypes: unknown[]","aspects: unknown[]","cartridgeData: Record<string, unknown>","files: string[]","allComponents: unknown[]","allPageTypes: unknown[]","allAspects: unknown[]"],"sources":["../../src/utils/logger.ts","../../src/cartridge-services/react-router-config.ts","../../src/utils/format-with-project-biome.ts","../../src/cartridge-services/generate-cartridge.ts"],"sourcesContent":["/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* oxlint-disable no-console */\nimport os from 'os';\nimport chalk from 'chalk';\nimport { createRequire } from 'module';\nimport type { ServerMode } from '../server/modes';\nimport pkg from '../../package.json' with { type: 'json' };\n\n/**\n * Get the local network IPv4 address\n */\nexport function getNetworkAddress(): string | undefined {\n const interfaces = os.networkInterfaces();\n for (const name of Object.keys(interfaces)) {\n const iface = interfaces[name];\n if (!iface) continue;\n for (const alias of iface) {\n if (alias.family === 'IPv4' && !alias.internal) {\n return alias.address;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Get the version of a package from the project's package.json\n */\nexport function getPackageVersion(packageName: string, projectDir: string): string {\n try {\n const require = createRequire(import.meta.url);\n const pkgPath = require.resolve(`${packageName}/package.json`, { paths: [projectDir] });\n const pkgJson = require(pkgPath) as { version: string };\n return pkgJson.version;\n } catch {\n return 'unknown';\n }\n}\n\n/**\n * Centralized, level-gated logger for the SDK.\n *\n * Log level is controlled by `SFCC_LOG_LEVEL` env var (`error` | `warn` | `info` | `debug`),\n * or on Managed Runtime by the numeric `MRT_LOG_LEVEL` (see {@link MRT_NUMERIC_TO_LEVEL}).\n * Falls back to: `DEBUG` targeting sfnext -> `debug`, `NODE_ENV=production` -> `warn`, otherwise `info`.\n */\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug';\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\n/**\n * Type guard for a {@link LogLevel} name. Uses `Object.hasOwn` (not `in`) so\n * inherited properties like `toString` don't falsely validate an env value.\n */\nfunction isLogLevel(value: string): value is LogLevel {\n return Object.hasOwn(LEVEL_PRIORITY, value);\n}\n\n/**\n * Managed Runtime injects `MRT_LOG_LEVEL` as a numeric string from its own\n * `LogLevel` enum (`0=TRACE, 1=DEBUG, 2=INFO, 3=WARN, 4=ERROR, 5=FATAL`), not a\n * level name — so it must be mapped, not matched against {@link LEVEL_PRIORITY}'s\n * keys. `TRACE` and `FATAL` clamp to the closest level this logger supports.\n */\nconst MRT_NUMERIC_TO_LEVEL: Record<string, LogLevel> = {\n '0': 'debug', // TRACE\n '1': 'debug', // DEBUG\n '2': 'info', // INFO\n '3': 'warn', // WARN\n '4': 'error', // ERROR\n '5': 'error', // FATAL\n};\n\nlet overrideLevel: LogLevel | undefined;\n\n/**\n * Returns true when the `DEBUG` env var targets sfnext or is a general enable flag.\n * Avoids accidentally enabling debug mode when DEBUG is set for unrelated libraries\n * (e.g. `DEBUG=express:*`).\n */\nfunction debugEnablesSfnext(): boolean {\n const raw = process.env.DEBUG?.trim();\n if (!raw) return false;\n const normalized = raw.toLowerCase();\n if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;\n return raw.split(',').some((token) => {\n const value = token.trim();\n return value === '*' || value === 'sfnext' || value === 'sfnext:*';\n });\n}\n\nfunction resolveLevel(): LogLevel {\n if (overrideLevel) return overrideLevel;\n\n // MRT sets MRT_LOG_LEVEL as a number; resolve it via the numeric map first.\n const mrtLevel = process.env.MRT_LOG_LEVEL;\n if (mrtLevel && mrtLevel in MRT_NUMERIC_TO_LEVEL) return MRT_NUMERIC_TO_LEVEL[mrtLevel];\n\n // SFCC_LOG_LEVEL is a level name set by the developer.\n const sfccLevel = process.env.SFCC_LOG_LEVEL;\n if (sfccLevel && isLogLevel(sfccLevel)) return sfccLevel;\n\n if (debugEnablesSfnext()) return 'debug';\n if (process.env.NODE_ENV === 'production') return 'warn';\n return 'info';\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LEVEL_PRIORITY[level] <= LEVEL_PRIORITY[resolveLevel()];\n}\n\nexport const logger = {\n error(msg: string, ...args: unknown[]): void {\n if (!shouldLog('error')) return;\n console.error(chalk.red('[sfnext:error]'), msg, ...args);\n },\n warn(msg: string, ...args: unknown[]): void {\n if (!shouldLog('warn')) return;\n console.warn(chalk.yellow('[sfnext:warn]'), msg, ...args);\n },\n info(msg: string, ...args: unknown[]): void {\n if (!shouldLog('info')) return;\n console.log(chalk.cyan('[sfnext:info]'), msg, ...args);\n },\n debug(msg: string, ...args: unknown[]): void {\n if (!shouldLog('debug')) return;\n console.log(chalk.gray('[sfnext:debug]'), msg, ...args);\n },\n setLevel(level: LogLevel | undefined): void {\n overrideLevel = level;\n },\n getLevel(): LogLevel {\n return resolveLevel();\n },\n};\n\n/**\n * Print the server information banner with URLs and versions\n */\nexport function printServerInfo(mode: ServerMode, port: number, startTime: number, projectDir: string): void {\n const elapsed = Date.now() - startTime;\n const sfnextVersion = pkg.version;\n const reactVersion = getPackageVersion('react', projectDir);\n const reactRouterVersion = getPackageVersion('react-router', projectDir);\n const viteVersion = getPackageVersion('vite', projectDir);\n\n const modeLabel = mode === 'development' ? 'Development Mode' : 'Preview Mode';\n\n console.log();\n console.log(` ${chalk.cyan.bold('⚡ SFCC Storefront Next')} ${chalk.dim(`v${sfnextVersion}`)}`);\n console.log(` ${chalk.green.bold(modeLabel)}`);\n console.log();\n const logLevel = resolveLevel();\n const logLevelColors: Record<LogLevel, (s: string) => string> = {\n error: chalk.red,\n warn: chalk.yellow,\n info: chalk.cyan,\n debug: chalk.gray,\n };\n\n console.log(\n ` ${chalk.dim('react')} ${chalk.green(`v${reactVersion}`)} ${chalk.dim('|')} ` +\n `${chalk.dim('react-router')} ${chalk.green(`v${reactRouterVersion}`)} ${chalk.dim('|')} ` +\n `${chalk.dim('vite')} ${chalk.green(`v${viteVersion}`)}`\n );\n console.log(\n ` ${chalk.dim('log level')} ${logLevelColors[logLevel](logLevel)} ${chalk.dim('|')} ` +\n `${chalk.green(`ready in ${elapsed}ms`)}`\n );\n console.log();\n}\n\n/**\n * Print server configuration details (proxy, static, etc.)\n */\nexport function printServerConfig(config: {\n mode: ServerMode;\n port: number;\n enableProxy?: boolean;\n enableStaticServing?: boolean;\n enableCompression?: boolean;\n proxyPath?: string;\n proxyHost?: string;\n shortCode?: string;\n organizationId?: string;\n clientId?: string;\n}): void {\n const {\n port,\n enableProxy,\n enableStaticServing,\n enableCompression,\n proxyPath,\n proxyHost,\n shortCode,\n organizationId,\n clientId,\n } = config;\n\n console.log(` ${chalk.bold('Environment Configuration:')}`);\n\n if (enableProxy && proxyPath && proxyHost && shortCode) {\n console.log(\n ` ${chalk.green('✓')} ${chalk.bold('Proxy:')} ${chalk.cyan(`localhost:${port}${proxyPath}`)} ${chalk.dim('→')} ${chalk.cyan(proxyHost)}`\n );\n console.log(` ${chalk.dim('Short Code: ')}${chalk.dim(shortCode)}`);\n if (organizationId) {\n console.log(` ${chalk.dim('Organization ID: ')}${chalk.dim(organizationId)}`);\n }\n if (clientId) {\n console.log(` ${chalk.dim('Client ID: ')}${chalk.dim(clientId)}`);\n }\n } else {\n console.log(` ${chalk.bold('Proxy: ')} ${chalk.dim('disabled')}`);\n }\n\n if (enableStaticServing) {\n console.log(` ${chalk.bold('Static: ')} ${chalk.dim('enabled')}`);\n }\n\n if (enableCompression) {\n console.log(` ${chalk.bold('Compression: ')} ${chalk.dim('enabled')}`);\n }\n\n // URLs\n const localUrl = `http://localhost:${port}`;\n const showNetwork = process.env.SHOW_NETWORK === 'true';\n const networkAddress = showNetwork ? getNetworkAddress() : undefined;\n const networkUrl = networkAddress ? `http://${networkAddress}:${port}` : undefined;\n\n console.log();\n console.log(` ${chalk.bold('Local: ')} ${chalk.cyan(localUrl)}`);\n if (networkUrl) {\n console.log(` ${chalk.bold('Network:')} ${chalk.cyan(networkUrl)}`);\n }\n\n console.log();\n console.log(` ${chalk.dim('Press')} ${chalk.bold('Ctrl+C')} ${chalk.dim('to stop the server')}`);\n console.log();\n}\n\n/**\n * Print shutdown message\n */\nexport function printShutdownMessage(): void {\n console.log(`\\n ${chalk.yellow('⚡')} ${chalk.dim('Server shutting down...')}\\n`);\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { join } from 'node:path';\nimport { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { execSync } from 'node:child_process';\nimport { tmpdir } from 'node:os';\nimport { randomUUID } from 'node:crypto';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { RouteConfigEntry } from '@react-router/dev/routes';\nimport { logger } from '../logger';\n\nlet isCliAvailable: boolean | null = null;\n\nfunction filePathEndsWithRoute(filePath: string, routeFile: string): boolean {\n const routeFileNormalized = routeFile.replace(/^\\.\\//, '');\n return filePath === routeFileNormalized || filePath.endsWith(`/${routeFileNormalized}`);\n}\n\n/**\n * Match the selected vertical route shadow to its canonical route module.\n *\n * `VERTICAL` is optional and selects the overlay directory reported by React Router,\n * for example `furniture` for `verticals/furniture/routes/_app._index.tsx`.\n */\nfunction routeFileMatches(filePath: string, routeFile: string): boolean {\n if (filePathEndsWithRoute(filePath, routeFile)) {\n return true;\n }\n\n const vertical = process.env.VERTICAL;\n const verticalRoutePrefix = vertical ? `verticals/${vertical}/routes/` : undefined;\n if (!verticalRoutePrefix || !routeFile.startsWith(verticalRoutePrefix)) {\n return false;\n }\n\n const canonicalRouteFile = `routes/${routeFile.slice(verticalRoutePrefix.length)}`;\n return filePathEndsWithRoute(filePath, canonicalRouteFile);\n}\n\nfunction checkReactRouterCli(projectDirectory: string): boolean {\n if (isCliAvailable !== null) {\n return isCliAvailable;\n }\n\n try {\n execSync('react-router --version', {\n cwd: projectDirectory,\n env: npmRunPathEnv(),\n stdio: 'pipe',\n });\n isCliAvailable = true;\n } catch {\n isCliAvailable = false;\n }\n return isCliAvailable;\n}\n\n/**\n * Get the fully resolved routes from React Router by invoking its CLI.\n * This ensures we get the exact same route resolution as React Router uses internally,\n * including all presets, file-system routes, and custom route configurations.\n * @param projectDirectory - The project root directory\n * @returns Array of resolved route config entries\n * @example\n * const routes = getReactRouterRoutes('/path/to/project');\n * // Returns the same structure as `react-router routes --json`\n */\nfunction getReactRouterRoutes(projectDirectory: string): RouteConfigEntry[] {\n if (!checkReactRouterCli(projectDirectory)) {\n throw new Error(\n 'React Router CLI is not available. Please make sure @react-router/dev is installed and accessible.'\n );\n }\n\n // Use a temp file to avoid Node.js buffer limits (8KB default)\n const tempFile = join(tmpdir(), `react-router-routes-${randomUUID()}.json`);\n\n try {\n // Redirect output to temp file to avoid buffer truncation\n execSync(`react-router routes --json > \"${tempFile}\"`, {\n cwd: projectDirectory,\n env: npmRunPathEnv(),\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n const output = readFileSync(tempFile, 'utf-8');\n return JSON.parse(output) as RouteConfigEntry[];\n } catch (error) {\n throw new Error(`Failed to get routes from React Router CLI: ${(error as Error).message}`);\n } finally {\n // Clean up temp file\n try {\n if (existsSync(tempFile)) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n }\n}\n\n/**\n * Convert a file path to its corresponding route path using React Router's CLI.\n * This ensures we get the exact same route resolution as React Router uses internally.\n * @param filePath - Absolute path to the route file\n * @param projectRoot - The project root directory\n * @returns The route path (e.g., '/cart', '/p/*')\n * @example\n * const route = filePathToRoute('/path/to/project/src/routes/_app.cart.tsx', '/path/to/project');\n * // Returns: '/cart'\n */\nexport function filePathToRoute(filePath: string, projectRoot: string): string {\n // Normalize paths to POSIX-style\n const filePathPosix = filePath.replace(/\\\\/g, '/');\n\n // Get all routes from React Router CLI\n const routes = getReactRouterRoutes(projectRoot);\n const flatRoutes = flattenRoutes(routes);\n\n // Skip root-duplicate routes — these are convenience clones created by applyUrlConfig\n // so the bare \"/\" URL still works. The canonical route (under the site-context prefix)\n // is the one that should appear in cartridge metadata.\n const canonicalRoutes = flatRoutes.filter((route) => !route.id.endsWith('--root-duplicate'));\n\n // Find the route that matches this file\n for (const route of canonicalRoutes) {\n // Normalize the route file path for comparison\n const routeFilePosix = route.file.replace(/\\\\/g, '/');\n\n if (routeFileMatches(filePathPosix, routeFilePosix)) {\n const seoAliases = canonicalRoutes\n .filter((candidate) => candidate.id.startsWith(`${route.id}--seo-alias--`))\n .sort((left, right) => left.path.localeCompare(right.path));\n\n if (seoAliases.length > 0) {\n if (seoAliases.length > 1) {\n logger.warn(\n `Multiple SEO route aliases match ${filePath}; using ${seoAliases[0].path} for Page Designer metadata.`\n );\n }\n return seoAliases[0].path;\n }\n\n return route.path;\n }\n }\n\n // Fallback: if no match found, return a warning path\n logger.warn(`Could not find route for file: ${filePath}`);\n return '/unknown';\n}\n\n/**\n * Flatten a nested route tree into a flat array with computed paths.\n * Each route will have its full path computed from parent paths.\n * @param routes - The nested route config entries\n * @param parentPath - The parent path prefix (used internally for recursion)\n * @returns Flat array of routes with their full paths\n */\nfunction flattenRoutes(\n routes: RouteConfigEntry[],\n parentPath = ''\n): Array<{ id: string; path: string; file: string; index?: boolean }> {\n const result: Array<{ id: string; path: string; file: string; index?: boolean }> = [];\n\n for (const route of routes) {\n // Compute the full path\n let fullPath: string;\n if (route.index) {\n fullPath = parentPath || '/';\n } else if (route.path) {\n // Handle paths that already start with / (absolute paths from extensions)\n const pathSegment = route.path.startsWith('/') ? route.path : `/${route.path}`;\n fullPath = parentPath ? `${parentPath}${pathSegment}`.replace(/\\/+/g, '/') : pathSegment;\n } else {\n // Layout route without path - use parent path\n fullPath = parentPath || '/';\n }\n\n // Add this route if it has an id\n if (route.id) {\n result.push({\n id: route.id,\n path: fullPath,\n file: route.file,\n index: route.index,\n });\n }\n\n // Recursively process children\n if (route.children && route.children.length > 0) {\n const childPath = route.path ? fullPath : parentPath;\n result.push(...flattenRoutes(route.children, childPath));\n }\n }\n\n return result;\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { spawnSync } from 'child_process';\nimport { createRequire } from 'module';\nimport { basename, dirname, join, relative } from 'path';\nimport { fileURLToPath } from 'url';\nimport { logger } from '../logger';\n\n/** This module's own path — the resolution root for the SDK-bundled Biome fallback. */\nconst HERE = fileURLToPath(import.meta.url);\n\n/**\n * Format generated file content with the *consuming project's* Biome so the written file\n * matches what the project's own `biome format` / `pnpm lint:fix` would produce.\n *\n * The SDK generates two kinds of files into a customer project — the extension `config.json`\n * (`trim-extensions.ts`) and the static component registry (`staticRegistry.ts`). Both must\n * be emitted in the exact byte shape the project's formatter produces, or the generated file\n * fails `pnpm lint` on a fresh project / churns on every `biome format --write` (W-23074938).\n *\n * Biome is preferred from the target file's own location — i.e. the consuming project's\n * `node_modules` — so it's the project's Biome version whose output is matched. When that\n * isn't installed yet (e.g. `create-storefront` runs `trim-extensions` BEFORE the generated\n * project's first `pnpm install`), we fall back to the SDK-bundled `@biomejs/biome` (a hard\n * dependency of this package, pinned to the template's version). Either way the file's\n * committed `biome.json` governs the output: Biome discovers its config by walking up from\n * the working directory, so we spawn it with `cwd` set to the file's directory and pass the\n * file's basename via `--stdin-file-path` (which drives both parser selection and formatting).\n *\n * Returns the content unchanged when no Biome can be resolved at all or the format fails, so\n * generation never breaks over formatting. A genuine format error is logged but non-fatal —\n * an unformatted-but-valid file is recoverable by the customer running `biome format --write`.\n *\n * @param content - The serialized file content to format.\n * @param filePath - The file's path (drives parser selection + config resolution + cwd).\n * @returns The Biome-formatted content, or the original content if Biome is unavailable.\n */\nexport function formatWithProjectBiome(content: string, filePath: string): string {\n const biomeBin = resolveBiomeBin(filePath);\n if (!biomeBin) {\n logger.warn(`⚠️ Biome could not be resolved; ${basename(filePath)} will be written unformatted.`);\n return content;\n }\n\n // Biome resolves biome.json by walking up from cwd, so run it from the file's directory\n // and identify the file by basename for parser selection.\n const result = spawnSync(process.execPath, [biomeBin, 'format', `--stdin-file-path=${basename(filePath)}`], {\n cwd: dirname(filePath),\n input: content,\n encoding: 'utf8',\n });\n\n if (result.status !== 0 || typeof result.stdout !== 'string') {\n const detail = result.stderr?.trim() || `exit code ${result.status}`;\n logger.warn(`⚠️ Skipping Biome formatting for ${basename(filePath)}: ${detail}`);\n return content;\n }\n\n return result.stdout;\n}\n\n/**\n * Format every file Biome recognizes under `directory` in place with the consuming project's\n * Biome, so generated files (e.g. cartridge metadata JSON) match `biome format` / `pnpm lint:fix`.\n *\n * Unlike {@link formatWithProjectBiome} (single file via stdin), this runs `biome format --write`\n * against the directory so Biome discovers the project's `biome.json` by walking up from it and\n * applies the project's formatting to the written files directly.\n *\n * Fail-safe: when Biome can't be resolved or the run fails, the files are left as written (valid,\n * just unformatted) and a warning is logged — generation never breaks over formatting.\n *\n * @param directory - Directory whose Biome-recognized files should be formatted in place.\n */\nexport function formatDirectoryWithProjectBiome(directory: string): void {\n // Resolve Biome as if from a file inside the directory, so a node_modules directly under\n // `directory` is on the resolution path (createRequire resolves relative to the file's dir).\n const biomeBin = resolveBiomeBin(join(directory, 'biome-resolution-root.js'));\n if (!biomeBin) {\n logger.warn(`⚠️ Biome could not be resolved; generated files in ${directory} were left unformatted.`);\n return;\n }\n\n // `--write` formats in place; Biome resolves biome.json by walking up from cwd, so run it\n // from the target directory. It exits non-zero if a file can't be fixed, which we treat as\n // non-fatal — the files are still valid, just not reformatted.\n const result = spawnSync(process.execPath, [biomeBin, 'format', '--write', '.'], {\n cwd: directory,\n encoding: 'utf8',\n });\n\n if (result.status !== 0) {\n const detail = result.stderr?.trim() || `exit code ${result.status}`;\n logger.warn(`⚠️ Some generated files in ${directory} could not be formatted by Biome: ${detail}`);\n return;\n }\n\n logger.debug(`✅ Formatted generated files in ${directory} with Biome`);\n}\n\n/**\n * Format only files changed by generation with the SDK-bundled Biome.\n *\n * Extension trimming can touch customer-owned source files, so formatting the project root would\n * rewrite unrelated files. The SDK's pinned Biome keeps this automatic path independent of any\n * target-project executable while the target project's biome.json still determines formatting.\n *\n * @param directory - Project root containing the Biome configuration.\n * @param filePaths - Absolute paths of files changed by generation.\n */\nexport function formatFilesWithBundledBiome(directory: string, filePaths: string[]): void {\n if (filePaths.length === 0) {\n return;\n }\n\n const biomeBin = resolveBiomeBin(HERE);\n if (!biomeBin) {\n logger.warn(`⚠️ Biome could not be resolved; generated files in ${directory} were left unformatted.`);\n return;\n }\n\n const result = spawnSync(\n process.execPath,\n [biomeBin, 'format', '--write', ...filePaths.map((filePath) => relative(directory, filePath))],\n {\n cwd: directory,\n encoding: 'utf8',\n }\n );\n\n if (result.status !== 0) {\n const detail = result.stderr?.trim() || `exit code ${result.status}`;\n logger.warn(`⚠️ Some generated files in ${directory} could not be formatted by Biome: ${detail}`);\n return;\n }\n\n logger.debug(`✅ Formatted ${filePaths.length} generated files in ${directory} with Biome`);\n}\n\n/**\n * Resolve a Biome CLI binary path, preferring the consuming project's install and falling back\n * to the SDK-bundled copy (available pre-install). Returns null when neither resolves.\n */\nfunction resolveBiomeBin(filePath: string): string | null {\n // Prefer the project's own @biomejs/biome (resolved from the target file's location);\n // fall back to this SDK package's bundled copy when the project isn't installed yet.\n for (const fromPath of [filePath, HERE]) {\n try {\n const req = createRequire(fromPath);\n const biomePkgJson = req.resolve('@biomejs/biome/package.json');\n const { bin } = req(biomePkgJson) as { bin: { biome: string } };\n return join(dirname(biomePkgJson), bin.biome);\n } catch {\n // Try the next resolution root.\n }\n }\n return null;\n}\n","#!/usr/bin/env node\n/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { readdir, readFile, writeFile, mkdir, access, rm } from 'node:fs/promises';\nimport { join, extname, resolve, basename } from 'node:path';\nimport { Project, Node, type SourceFile, type PropertyDeclaration, type Decorator, type Expression } from 'ts-morph';\nimport { filePathToRoute } from './react-router-config.js';\nimport { logger } from '../logger';\nimport { formatDirectoryWithProjectBiome } from '../utils/format-with-project-biome';\n\n// Re-export `filePathToRoute`\nexport { filePathToRoute };\n\nconst SKIP_DIRECTORIES = ['build', 'dist', 'node_modules', '.git', '.next', 'coverage', 'verticals'];\n\nconst DEFAULT_COMPONENT_GROUP = 'storefrontnext_base';\nconst ARCH_TYPE_HEADLESS = 'headless';\n\ntype AttributeType =\n | 'string'\n | 'text'\n | 'markup'\n | 'integer'\n | 'boolean'\n | 'product'\n | 'category'\n | 'file'\n | 'page'\n | 'image'\n | 'url'\n | 'enum'\n | 'custom'\n | 'cms_record';\n\nconst VALID_ATTRIBUTE_TYPES: readonly AttributeType[] = [\n 'string',\n 'text',\n 'markup',\n 'integer',\n 'boolean',\n 'product',\n 'category',\n 'file',\n 'page',\n 'image',\n 'url',\n 'enum',\n 'custom',\n 'cms_record',\n] as const;\n\n// Type mapping for TypeScript types to B2C Commerce attribute types\n// Based on official schema: https://salesforcecommercecloud.github.io/b2c-dev-doc/docs/current/content/attributedefinition.json\nconst TYPE_MAPPING: Record<string, string> = {\n String: 'string',\n string: 'string',\n Number: 'integer',\n number: 'integer',\n Boolean: 'boolean',\n boolean: 'boolean',\n Date: 'string', // B2C Commerce doesn't have a native date type, use string\n URL: 'url',\n CMSRecord: 'cms_record',\n};\n\n// Resolve attribute type in order: decorator type -> ts-morph type inference -> fallback to string\nfunction resolveAttributeType(decoratorType?: string, tsMorphType?: string, fieldName?: string): string {\n // 1) If the type is set on the decorator, use that (with validation)\n if (decoratorType) {\n if (!VALID_ATTRIBUTE_TYPES.includes(decoratorType as AttributeType)) {\n logger.error(\n `Invalid attribute type '${decoratorType}' for field '${fieldName || 'unknown'}'. Valid types are: ${VALID_ATTRIBUTE_TYPES.join(', ')}`\n );\n process.exit(1);\n }\n return decoratorType;\n }\n\n // 2) Use the type from ts-morph type inference\n if (tsMorphType && TYPE_MAPPING[tsMorphType]) {\n return TYPE_MAPPING[tsMorphType];\n }\n\n // 3) Fall back to string\n return 'string';\n}\n\n// Attribute types for which the Page Designer metadefinition schema forbids `searching`.\nconst SEARCHING_FORBIDDEN_TYPES = new Set(['integer', 'boolean', 'file', 'page', 'image', 'url', 'enum']);\n\n/**\n * Validate an authored `searching` config against the resolved attribute type and map it to the\n * snake_case schema shape. The metadefinition schema gates `searching` by type; an invalid\n * combination fails cartridge generation (matching the strict behavior of `resolveAttributeType`).\n *\n * Rules (from attributedefinition.json):\n * - Forbidden entirely on integer/boolean/file/page/image/url/enum.\n * - `markup`: `sortable` must be false.\n * - `custom`/`cms_record`: `refinable` must be false; `boost_factor`/`sortable` not allowed.\n * - `string`/`text`/`product`/`category`: all fields allowed.\n */\nfunction mapAttributeSearching(\n searching: Record<string, unknown>,\n resolvedType: string,\n fieldName: string\n): Record<string, unknown> {\n const fail = (reason: string): never => {\n logger.error(`Invalid 'searching' config for attribute '${fieldName}' (type '${resolvedType}'): ${reason}`);\n process.exit(1);\n };\n\n if (SEARCHING_FORBIDDEN_TYPES.has(resolvedType)) {\n fail(`the '${resolvedType}' attribute type does not support searching.`);\n }\n\n const { searchable, refinable, boostFactor, sortable } = searching as {\n searchable?: unknown;\n refinable?: unknown;\n boostFactor?: unknown;\n sortable?: unknown;\n };\n\n if (typeof searchable !== 'boolean' || typeof refinable !== 'boolean') {\n fail(`'searchable' and 'refinable' are required booleans.`);\n }\n\n if (resolvedType === 'markup' && sortable === true) {\n fail(`'sortable' must be false for markup attributes.`);\n }\n\n if (resolvedType === 'custom' || resolvedType === 'cms_record') {\n if (refinable === true) {\n fail(`'refinable' must be false for ${resolvedType} attributes.`);\n }\n if (boostFactor !== undefined) {\n fail(`'boostFactor' is not supported for ${resolvedType} attributes.`);\n }\n if (sortable === true) {\n fail(`'sortable' must be false for ${resolvedType} attributes.`);\n }\n }\n\n const mapped: Record<string, unknown> = { searchable, refinable };\n if (boostFactor !== undefined) {\n mapped.boost_factor = boostFactor;\n }\n if (sortable !== undefined) {\n mapped.sortable = sortable;\n }\n return mapped;\n}\n\n/**\n * Validate an authored `dynamicLookup` config and map it to the snake_case schema shape.\n * The metadefinition schema allows `dynamic_lookup` on all attribute types but requires a\n * single `aspect_attribute_alias` field (`additionalProperties: false`); a missing alias fails\n * cartridge generation (matching the strict behavior of `resolveAttributeType`).\n */\nfunction mapAttributeDynamicLookup(dynamicLookup: Record<string, unknown>, fieldName: string): Record<string, unknown> {\n const { aspectAttributeAlias } = dynamicLookup as { aspectAttributeAlias?: unknown };\n\n if (typeof aspectAttributeAlias !== 'string' || aspectAttributeAlias.length === 0) {\n logger.error(\n `Invalid 'dynamicLookup' config for attribute '${fieldName}': 'aspectAttributeAlias' is required and must be a non-empty string.`\n );\n process.exit(1);\n }\n\n return { aspect_attribute_alias: aspectAttributeAlias };\n}\n\n// Convert field name to human-readable name\nfunction toHumanReadableName(fieldName: string): string {\n return fieldName\n .replace(/([A-Z])/g, ' $1') // Add space before capital letters\n .replace(/^./, (str) => str.toUpperCase()) // Capitalize first letter\n .trim();\n}\n\n// Convert name to camelCase filename (handles spaces and hyphens, preserves existing camelCase)\nfunction toCamelCaseFileName(name: string): string {\n // If the name is already camelCase (no spaces or hyphens), return as-is\n if (!/[\\s-]/.test(name)) {\n return name;\n }\n\n return name\n .split(/[\\s-]+/) // Split by whitespace and hyphens\n .map((word, index) => {\n if (index === 0) {\n return word.toLowerCase(); // First word is all lowercase\n }\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); // Subsequent words are capitalized\n })\n .join(''); // Join without spaces or hyphens\n}\n\nfunction getTypeFromTsMorph(property: PropertyDeclaration, _sourceFile: SourceFile): string {\n try {\n const typeNode = property.getTypeNode();\n if (typeNode) {\n const typeText = typeNode.getText();\n // Extract the base type name from complex types\n const baseType = typeText.split('|')[0].split('&')[0].trim();\n return baseType;\n }\n } catch {\n // If type extraction fails, return string\n }\n\n return 'string';\n}\n\n/**\n * Resolve a variable's initializer expression from the same source file,\n * unwrapping `as const` type assertions.\n */\nfunction resolveVariableInitializer(sourceFile: SourceFile, name: string): Expression | undefined {\n const varDecl = sourceFile.getVariableDeclaration(name);\n if (!varDecl) return undefined;\n let initializer = varDecl.getInitializer();\n if (initializer && Node.isAsExpression(initializer)) {\n initializer = initializer.getExpression();\n }\n return initializer;\n}\n\n/**\n * Check whether an AST node is a type that `parseExpression` can resolve to a\n * concrete JS value (as opposed to falling through to `getText()`).\n */\nfunction isResolvableLiteral(node: Expression): boolean {\n return (\n Node.isStringLiteral(node) ||\n Node.isNumericLiteral(node) ||\n Node.isTrueLiteral(node) ||\n Node.isFalseLiteral(node) ||\n Node.isObjectLiteralExpression(node) ||\n Node.isArrayLiteralExpression(node)\n );\n}\n\nclass UnresolvedConstantReferenceError extends Error {\n constructor(reference: string) {\n super(\n `Cannot resolve constant reference '${reference}'. ` +\n `Ensure the variable is declared in the same file as a literal value.`\n );\n this.name = 'UnresolvedConstantReferenceError';\n }\n}\n\n// Helper function to parse any TypeScript expression into a JavaScript value\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseExpression(expression: any): unknown {\n if (Node.isStringLiteral(expression)) {\n return expression.getLiteralValue();\n } else if (Node.isNumericLiteral(expression)) {\n return expression.getLiteralValue();\n } else if (Node.isTrueLiteral(expression)) {\n return true;\n } else if (Node.isFalseLiteral(expression)) {\n return false;\n } else if (Node.isObjectLiteralExpression(expression)) {\n return parseNestedObject(expression);\n } else if (Node.isArrayLiteralExpression(expression)) {\n return parseArrayLiteral(expression);\n } else if (Node.isPropertyAccessExpression(expression)) {\n const obj = expression.getExpression();\n const propName = expression.getName();\n if (Node.isIdentifier(obj)) {\n const resolved = resolveVariableInitializer(expression.getSourceFile(), obj.getText());\n if (resolved && Node.isObjectLiteralExpression(resolved)) {\n const prop = resolved.getProperty(propName);\n if (prop && Node.isPropertyAssignment(prop)) {\n const propInit = prop.getInitializer();\n if (propInit) return parseExpression(propInit);\n }\n }\n throw new UnresolvedConstantReferenceError(expression.getText());\n }\n return expression.getText();\n } else if (Node.isIdentifier(expression)) {\n const resolved = resolveVariableInitializer(expression.getSourceFile(), expression.getText());\n if (resolved && isResolvableLiteral(resolved)) {\n return parseExpression(resolved);\n }\n return expression.getText();\n } else {\n return expression.getText();\n }\n}\n\n// Helper function to parse deeply nested object literals\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseNestedObject(objectLiteral: any): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n try {\n const properties = objectLiteral.getProperties();\n\n for (const property of properties) {\n if (Node.isPropertyAssignment(property)) {\n const name = property.getName();\n const initializer = property.getInitializer();\n\n if (initializer) {\n result[name] = parseExpression(initializer);\n }\n }\n }\n } catch (error) {\n logger.warn(`Could not parse nested object: ${(error as Error).message}`);\n return result; // Return the result even if there was an error\n }\n\n return result;\n}\n\n// Helper function to parse array literals\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseArrayLiteral(arrayLiteral: any): unknown[] {\n const result: unknown[] = [];\n\n try {\n const elements = arrayLiteral.getElements();\n\n for (const element of elements) {\n result.push(parseExpression(element));\n }\n } catch (error) {\n logger.warn(`Could not parse array literal: ${(error as Error).message}`);\n }\n\n return result;\n}\n\n// Parse decorator arguments using ts-morph\nfunction parseDecoratorArgs(decorator: Decorator): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n try {\n const args = decorator.getArguments();\n\n if (args.length === 0) {\n return result;\n }\n\n // Handle the first argument\n const firstArg = args[0];\n\n if (Node.isObjectLiteralExpression(firstArg)) {\n // First argument is an object literal - parse all its properties\n const properties = firstArg.getProperties();\n\n for (const property of properties) {\n if (Node.isPropertyAssignment(property)) {\n const name = property.getName();\n const initializer = property.getInitializer();\n\n if (initializer) {\n result[name] = parseExpression(initializer);\n }\n }\n }\n } else if (Node.isStringLiteral(firstArg)) {\n // First argument is a string literal - use it as the id\n result.id = parseExpression(firstArg);\n\n // Check if there's a second argument (options object)\n if (args.length > 1) {\n const secondArg = args[1];\n if (Node.isObjectLiteralExpression(secondArg)) {\n const properties = secondArg.getProperties();\n\n for (const property of properties) {\n if (Node.isPropertyAssignment(property)) {\n const name = property.getName();\n const initializer = property.getInitializer();\n\n if (initializer) {\n result[name] = parseExpression(initializer);\n }\n }\n }\n }\n }\n }\n\n return result;\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not parse decorator arguments: ${(error as Error).message}`);\n return result;\n }\n}\n\nfunction extractAttributesFromSource(sourceFile: SourceFile, className: string): Record<string, unknown>[] {\n const attributes: Record<string, unknown>[] = [];\n\n try {\n // Find the class declaration\n const classDeclaration = sourceFile.getClass(className);\n if (!classDeclaration) {\n return attributes;\n }\n\n // Get all properties in the class\n const properties = classDeclaration.getProperties();\n\n for (const property of properties) {\n // Check if the property has an @AttributeDefinition decorator\n const attributeDecorator = property.getDecorator('AttributeDefinition');\n if (!attributeDecorator) {\n continue;\n }\n\n const fieldName = property.getName();\n const config = parseDecoratorArgs(attributeDecorator);\n\n const isRequired = !property.hasQuestionToken();\n\n const inferredType = (config.type as string) || getTypeFromTsMorph(property, sourceFile);\n\n const attribute: Record<string, unknown> = {\n id: config.id || fieldName,\n name: config.name || toHumanReadableName(fieldName),\n type: resolveAttributeType(config.type as string, inferredType, fieldName),\n required: config.required !== undefined ? config.required : isRequired,\n description: config.description || `Field: ${fieldName}`,\n };\n\n if (config.values) {\n attribute.values = config.values;\n }\n\n if (config.defaultValue !== undefined) {\n attribute.default_value = config.defaultValue;\n }\n\n if (config.editorDefinition !== undefined) {\n attribute.editor_definition = config.editorDefinition;\n }\n\n if (config.searching !== undefined) {\n attribute.searching = mapAttributeSearching(\n config.searching as Record<string, unknown>,\n attribute.type as string,\n String(attribute.id)\n );\n }\n\n if (config.dynamicLookup !== undefined) {\n attribute.dynamic_lookup = mapAttributeDynamicLookup(\n config.dynamicLookup as Record<string, unknown>,\n String(attribute.id)\n );\n }\n\n attributes.push(attribute);\n }\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not extract attributes from class ${className}: ${(error as Error).message}`);\n }\n\n return attributes;\n}\n\nfunction normalizeComponentTypeId(typeId: string, defaultGroup: string): string {\n return typeId.includes('.') ? typeId : `${defaultGroup}.${typeId}`;\n}\n\nfunction extractRegionDefinitionsFromSource(\n sourceFile: SourceFile,\n className: string,\n defaultComponentGroup = DEFAULT_COMPONENT_GROUP\n): Record<string, unknown>[] {\n const regionDefinitions: Record<string, unknown>[] = [];\n\n try {\n // Find the class declaration\n const classDeclaration = sourceFile.getClass(className);\n if (!classDeclaration) {\n return regionDefinitions;\n }\n\n // Check for class-level @RegionDefinition decorator\n const classRegionDecorator = classDeclaration.getDecorator('RegionDefinition');\n if (classRegionDecorator) {\n const args = classRegionDecorator.getArguments();\n if (args.length > 0) {\n const firstArg = args[0];\n\n // Handle array literal argument (most common case)\n if (Node.isArrayLiteralExpression(firstArg)) {\n const elements = firstArg.getElements();\n for (const element of elements) {\n if (Node.isObjectLiteralExpression(element)) {\n const regionConfig = parseDecoratorArgs({\n getArguments: () => [element],\n } as unknown as Decorator);\n\n const regionDefinition: Record<string, unknown> = {\n id: regionConfig.id || 'region',\n name: regionConfig.name || 'Region',\n };\n\n // Add optional properties if they exist in the decorator\n if (regionConfig.description !== undefined) {\n regionDefinition.description = regionConfig.description;\n }\n\n if (regionConfig.componentTypes) {\n regionDefinition.component_types = regionConfig.componentTypes;\n }\n\n if (Array.isArray(regionConfig.componentTypeInclusions)) {\n regionDefinition.component_type_inclusions = regionConfig.componentTypeInclusions.map(\n (incl) => ({\n type_id: normalizeComponentTypeId(String(incl), defaultComponentGroup),\n })\n );\n }\n\n if (Array.isArray(regionConfig.componentTypeExclusions)) {\n regionDefinition.component_type_exclusions = regionConfig.componentTypeExclusions.map(\n (excl) => ({\n type_id: normalizeComponentTypeId(String(excl), defaultComponentGroup),\n })\n );\n }\n\n if (regionConfig.maxComponents !== undefined) {\n regionDefinition.max_components = regionConfig.maxComponents;\n }\n\n if (regionConfig.minComponents !== undefined) {\n regionDefinition.min_components = regionConfig.minComponents;\n }\n\n if (regionConfig.allowMultiple !== undefined) {\n regionDefinition.allow_multiple = regionConfig.allowMultiple;\n }\n\n if (Array.isArray(regionConfig.defaultComponentConstructors)) {\n // Map the decorator's authoring shape ({ id, typeId, data }) onto the\n // Page Designer componentconstructor schema, which only permits\n // `type_id` (required), `name`, and nested `region_component_constructors`.\n // The decorator's `id`/`data` fields have no place in the metadefinition\n // format (`additionalProperties: false`), so they are intentionally dropped.\n regionDefinition.default_component_constructors =\n regionConfig.defaultComponentConstructors.map((constructor) => {\n const { typeId, name } = constructor as {\n typeId?: unknown;\n name?: unknown;\n };\n const mapped: Record<string, unknown> = {\n type_id: normalizeComponentTypeId(String(typeId), defaultComponentGroup),\n };\n if (name !== undefined) {\n mapped.name = name;\n }\n return mapped;\n });\n }\n\n regionDefinitions.push(regionDefinition);\n }\n }\n }\n }\n }\n } catch (error) {\n logger.warn(\n `Warning: Could not extract region definitions from class ${className}: ${(error as Error).message}`\n );\n }\n\n return regionDefinitions;\n}\n\nasync function processComponentFile(filePath: string, _projectRoot: string): Promise<unknown[]> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const components: unknown[] = [];\n\n // Check if file contains @Component decorator\n if (!content.includes('@Component')) {\n return components;\n }\n\n // Convert file path to module path (currently unused but may be needed in future)\n // const relativePath = relative(join(projectRoot, 'src'), filePath);\n // const modulePath = relativePath.replace(/\\.tsx?$/, '').replace(/\\\\/g, '/');\n\n try {\n // Create a ts-morph project and add the source file\n const project = new Project({\n useInMemoryFileSystem: true,\n skipAddingFilesFromTsConfig: true,\n });\n\n const sourceFile = project.createSourceFile(filePath, content);\n\n const classes = sourceFile.getClasses();\n\n for (const classDeclaration of classes) {\n const componentDecorator = classDeclaration.getDecorator('Component');\n if (!componentDecorator) {\n continue;\n }\n\n const className = classDeclaration.getName();\n if (!className) {\n continue;\n }\n\n const componentConfig = parseDecoratorArgs(componentDecorator);\n const componentGroup = String(componentConfig.group || DEFAULT_COMPONENT_GROUP);\n\n const attributes = extractAttributesFromSource(sourceFile, className);\n const regionDefinitions = extractRegionDefinitionsFromSource(sourceFile, className, componentGroup);\n\n const componentMetadata: Record<string, unknown> = {\n typeId: componentConfig.id || className.toLowerCase(),\n name: componentConfig.name || toHumanReadableName(className),\n group: componentGroup,\n description: componentConfig.description || `Custom component: ${className}`,\n regionDefinitions,\n attributes,\n };\n\n if (typeof componentConfig.embedded === 'boolean') {\n componentMetadata.embedded = componentConfig.embedded;\n }\n if (componentConfig.component_id !== undefined) {\n componentMetadata.component_id = String(componentConfig.component_id);\n }\n\n components.push(componentMetadata);\n }\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not process file ${filePath}:`, (error as Error).message);\n }\n\n return components;\n } catch (error) {\n if (error instanceof UnresolvedConstantReferenceError) {\n throw error;\n }\n logger.warn(`Could not read file ${filePath}:`, (error as Error).message);\n return [];\n }\n}\n\nasync function processPageTypeFile(filePath: string, projectRoot: string): Promise<unknown[]> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const pageTypes: unknown[] = [];\n\n // Check if file contains @PageType decorator\n if (!content.includes('@PageType')) {\n return pageTypes;\n }\n\n try {\n // Create a ts-morph project and add the source file\n const project = new Project({\n useInMemoryFileSystem: true,\n skipAddingFilesFromTsConfig: true,\n });\n\n const sourceFile = project.createSourceFile(filePath, content);\n\n const classes = sourceFile.getClasses();\n\n for (const classDeclaration of classes) {\n const pageTypeDecorator = classDeclaration.getDecorator('PageType');\n if (!pageTypeDecorator) {\n continue;\n }\n\n const className = classDeclaration.getName();\n if (!className) {\n continue;\n }\n\n const pageTypeConfig = parseDecoratorArgs(pageTypeDecorator);\n\n const attributes = extractAttributesFromSource(sourceFile, className);\n const regionDefinitions = extractRegionDefinitionsFromSource(sourceFile, className);\n const route = filePathToRoute(filePath, projectRoot);\n\n const pageTypeMetadata = {\n typeId: pageTypeConfig.id || className.toLowerCase(),\n name: pageTypeConfig.name || toHumanReadableName(className),\n description: pageTypeConfig.description || `Custom page type: ${className}`,\n regionDefinitions,\n supportedAspectTypes: pageTypeConfig.supportedAspectTypes || [],\n attributes,\n route,\n // Only carry `preview` when the decorator declared it, so undeclared page types\n // stay clean and the emitted JSON omits the field entirely.\n ...(pageTypeConfig.preview !== undefined && { preview: pageTypeConfig.preview }),\n };\n\n pageTypes.push(pageTypeMetadata);\n }\n } catch (error) {\n logger.warn(`Could not process file ${filePath}:`, (error as Error).message);\n }\n\n return pageTypes;\n } catch (error) {\n logger.warn(`Could not read file ${filePath}:`, (error as Error).message);\n return [];\n }\n}\n\nasync function processAspectFile(filePath: string, _projectRoot: string): Promise<unknown[]> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const aspects: unknown[] = [];\n\n // Check if file is a JSON aspect file\n if (!filePath.endsWith('.json') || !content.trim().startsWith('{')) {\n return aspects;\n }\n\n // Check if file is in the aspects directory\n if (!filePath.includes('/aspects/') && !filePath.includes('\\\\aspects\\\\')) {\n return aspects;\n }\n\n try {\n // Parse the JSON content\n const aspectData = JSON.parse(content);\n\n // Extract filename without extension as the aspect ID\n const fileName = basename(filePath, '.json');\n\n // Validate that it looks like an aspect file\n if (!aspectData.name || !aspectData.attribute_definitions) {\n return aspects;\n }\n\n const aspectMetadata = {\n id: fileName,\n name: aspectData.name,\n description: aspectData.description || `Aspect type: ${aspectData.name}`,\n attributeDefinitions: aspectData.attribute_definitions || [],\n supportedObjectTypes: aspectData.supported_object_types || [],\n };\n\n aspects.push(aspectMetadata);\n } catch (parseError) {\n logger.warn(`Could not parse JSON in file ${filePath}:`, (parseError as Error).message);\n }\n\n return aspects;\n } catch (error) {\n logger.warn(`Could not read file ${filePath}:`, (error as Error).message);\n return [];\n }\n}\n\nasync function generateComponentCartridge(\n component: Record<string, unknown>,\n outputDir: string,\n dryRun = false\n): Promise<void> {\n const fileName = toCamelCaseFileName(component.typeId as string);\n const groupDir = join(outputDir, component.group as string);\n const outputPath = join(groupDir, `${fileName}.json`);\n\n if (!dryRun) {\n // Ensure the group directory exists\n try {\n await mkdir(groupDir, { recursive: true });\n } catch {\n // Directory might already exist, which is fine\n }\n\n const attributeDefinitionGroups = [\n {\n id: component.typeId,\n name: component.name,\n description: component.description,\n attribute_definitions: component.attributes,\n },\n ];\n\n const cartridgeData: Record<string, unknown> = {\n name: component.name,\n description: component.description,\n group: component.group,\n arch_type: ARCH_TYPE_HEADLESS,\n ...(typeof component.embedded === 'boolean' && { embedded: component.embedded }),\n component_id: component.component_id,\n region_definitions: component.regionDefinitions || [],\n attribute_definition_groups: attributeDefinitionGroups,\n };\n\n await writeFile(outputPath, JSON.stringify(cartridgeData, null, 2));\n }\n\n const prefix = dryRun ? ' - [DRY RUN]' : ' -';\n logger.debug(\n `${prefix} ${String(component.typeId)}: ${String(component.name)} (${String((component.attributes as unknown[]).length)} attributes) → ${fileName}.json`\n );\n}\n\nasync function generatePageTypeCartridge(\n pageType: Record<string, unknown>,\n outputDir: string,\n dryRun = false\n): Promise<void> {\n const fileName = toCamelCaseFileName(pageType.name as string);\n const outputPath = join(outputDir, `${fileName}.json`);\n\n if (!dryRun) {\n const cartridgeData: Record<string, unknown> = {\n name: pageType.name,\n description: pageType.description,\n arch_type: ARCH_TYPE_HEADLESS,\n region_definitions: pageType.regionDefinitions || [],\n };\n\n // Add attribute_definition_groups if there are attributes\n if (pageType.attributes && (pageType.attributes as unknown[]).length > 0) {\n const attributeDefinitionGroups = [\n {\n id: pageType.typeId || fileName,\n name: pageType.name,\n description: pageType.description,\n attribute_definitions: pageType.attributes,\n },\n ];\n cartridgeData.attribute_definition_groups = attributeDefinitionGroups;\n }\n\n // Add supported_aspect_types if specified\n if (pageType.supportedAspectTypes) {\n cartridgeData.supported_aspect_types = pageType.supportedAspectTypes;\n }\n\n if (pageType.route) {\n cartridgeData.route = pageType.route;\n }\n\n // Add preview only when the page type declared it (omitted otherwise to keep existing\n // page-type JSON byte-stable). Use the same presence check as processPageTypeFile so the\n // \"declared\" gate is identical on both sides.\n if (pageType.preview !== undefined) {\n cartridgeData.preview = pageType.preview;\n }\n\n await writeFile(outputPath, JSON.stringify(cartridgeData, null, 2));\n }\n\n const prefix = dryRun ? ' - [DRY RUN]' : ' -';\n logger.debug(\n `${prefix} ${String(pageType.name)}: ${String(pageType.description)} (${String((pageType.attributes as unknown[]).length)} attributes) → ${fileName}.json`\n );\n}\n\nasync function generateAspectCartridge(\n aspect: Record<string, unknown>,\n outputDir: string,\n dryRun = false\n): Promise<void> {\n const fileName = toCamelCaseFileName(aspect.id as string);\n const outputPath = join(outputDir, `${fileName}.json`);\n\n if (!dryRun) {\n const cartridgeData: Record<string, unknown> = {\n name: aspect.name,\n description: aspect.description,\n arch_type: ARCH_TYPE_HEADLESS,\n attribute_definitions: aspect.attributeDefinitions || [],\n };\n\n // Add supported_object_types if specified\n if (aspect.supportedObjectTypes) {\n cartridgeData.supported_object_types = aspect.supportedObjectTypes;\n }\n\n await writeFile(outputPath, JSON.stringify(cartridgeData, null, 2));\n }\n\n const prefix = dryRun ? ' - [DRY RUN]' : ' -';\n logger.debug(\n `${prefix} ${String(aspect.name)}: ${String(aspect.description)} (${String((aspect.attributeDefinitions as unknown[]).length)} attributes) → ${fileName}.json`\n );\n}\n\n/**\n * Options for generateMetadata function\n */\nexport interface GenerateMetadataOptions {\n /**\n * Optional array of specific file paths to process.\n * If provided, only these files will be processed and existing cartridge files will NOT be deleted.\n * If omitted, the entire src/ directory will be scanned and all existing cartridge files will be deleted first.\n */\n filePaths?: string[];\n\n /**\n * Whether to format generated JSON files with Biome so they match the project's formatting.\n * Defaults to true.\n */\n lintFix?: boolean;\n\n /**\n * If true, scans files and reports what would be generated without actually writing any files or deleting directories.\n * Defaults to false.\n */\n dryRun?: boolean;\n}\n\n/**\n * Result returned by generateMetadata function\n */\nexport interface GenerateMetadataResult {\n componentsGenerated: number;\n pageTypesGenerated: number;\n aspectsGenerated: number;\n totalFiles: number;\n}\n\n/**\n * Formats the generated JSON files in place so they match the project's `biome format` output\n * (and therefore pass `pnpm lint` out of the box). Delegates to the shared Biome helper, which\n * prefers the consuming project's Biome and is fail-safe (logs and leaves files valid-but-\n * unformatted rather than throwing) when Biome can't run.\n */\nfunction lintGeneratedFiles(metadataDir: string): void {\n logger.debug('🔧 Formatting generated JSON files with Biome...');\n formatDirectoryWithProjectBiome(metadataDir);\n}\n\n// Main function\nexport async function generateMetadata(\n projectDirectory: string,\n metadataDirectory: string,\n options?: GenerateMetadataOptions\n): Promise<GenerateMetadataResult> {\n try {\n const filePaths = options?.filePaths;\n const isIncrementalMode = filePaths && filePaths.length > 0;\n const dryRun = options?.dryRun || false;\n\n if (dryRun) {\n logger.debug('🔍 [DRY RUN] Scanning for decorated components and page types...');\n } else if (isIncrementalMode) {\n logger.debug(`🔍 Generating metadata for ${filePaths.length} specified file(s)...`);\n } else {\n logger.debug('🔍 Generating metadata for decorated components and page types...');\n }\n\n const projectRoot = resolve(projectDirectory);\n const srcDir = join(projectRoot, 'src');\n const metadataDir = resolve(metadataDirectory);\n const componentsOutputDir = join(metadataDir, 'components');\n const pagesOutputDir = join(metadataDir, 'pages');\n const aspectsOutputDir = join(metadataDir, 'aspects');\n\n // Skip directory operations in dry run mode\n if (!dryRun) {\n // Only delete existing directories in full scan mode (not incremental)\n if (!isIncrementalMode) {\n logger.debug('🗑️ Cleaning existing output directories...');\n for (const outputDir of [componentsOutputDir, pagesOutputDir, aspectsOutputDir]) {\n try {\n await rm(outputDir, { recursive: true, force: true });\n logger.debug(` - Deleted: ${outputDir}`);\n } catch {\n // Directory might not exist, which is fine\n logger.debug(` - Directory not found (skipping): ${outputDir}`);\n }\n }\n } else {\n logger.debug('📝 Incremental mode: existing cartridge files will be preserved/overwritten');\n }\n\n // Create output directories if they don't exist\n logger.debug('Creating output directories...');\n for (const outputDir of [componentsOutputDir, pagesOutputDir, aspectsOutputDir]) {\n try {\n await mkdir(outputDir, { recursive: true });\n } catch (error) {\n try {\n await access(outputDir);\n // Directory exists, that's fine\n } catch {\n const err = error as Error;\n logger.error(`❌ Failed to create output directory ${outputDir}: ${err.message}`);\n process.exit(1);\n throw err;\n }\n }\n }\n } else if (isIncrementalMode) {\n logger.debug(`📝 [DRY RUN] Would process ${filePaths.length} specific file(s)`);\n } else {\n logger.debug('📝 [DRY RUN] Would clean and regenerate all metadata files');\n }\n\n let files: string[] = [];\n\n if (isIncrementalMode && filePaths) {\n // Use the specified file paths (resolve them relative to project root)\n files = filePaths.map((fp) => resolve(projectRoot, fp));\n logger.debug(`📂 Processing ${files.length} specified file(s)...`);\n } else {\n // Full scan mode: scan entire src directory\n const scanDirectory = async (dir: string): Promise<void> => {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n\n if (entry.isDirectory()) {\n if (!SKIP_DIRECTORIES.includes(entry.name)) {\n await scanDirectory(fullPath);\n }\n } else if (\n entry.isFile() &&\n (extname(entry.name) === '.ts' ||\n extname(entry.name) === '.tsx' ||\n extname(entry.name) === '.json')\n ) {\n files.push(fullPath);\n }\n }\n };\n\n await scanDirectory(srcDir);\n\n const configMetadataDir = join(projectRoot, 'config-metadata');\n try {\n await access(configMetadataDir);\n await scanDirectory(configMetadataDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n logger.debug(` - Directory not found (skipping): ${configMetadataDir}`);\n } else {\n logger.warn(` - Unable to access ${configMetadataDir}:`, (error as Error).message);\n }\n }\n }\n\n // Process each file for both components and page types\n const allComponents: unknown[] = [];\n const allPageTypes: unknown[] = [];\n const allAspects: unknown[] = [];\n\n for (const file of files) {\n const components = await processComponentFile(file, projectRoot);\n allComponents.push(...components);\n\n const pageTypes = await processPageTypeFile(file, projectRoot);\n allPageTypes.push(...pageTypes);\n\n const aspects = await processAspectFile(file, projectRoot);\n allAspects.push(...aspects);\n }\n\n if (allComponents.length === 0 && allPageTypes.length === 0 && allAspects.length === 0) {\n logger.info('⚠️ No decorated components, page types, or aspect files found.');\n return {\n componentsGenerated: 0,\n pageTypesGenerated: 0,\n aspectsGenerated: 0,\n totalFiles: 0,\n };\n }\n\n // Generate component cartridge files\n if (allComponents.length > 0) {\n logger.debug(`✅ Found ${allComponents.length} decorated component(s)`);\n for (const component of allComponents) {\n await generateComponentCartridge(component as Record<string, unknown>, componentsOutputDir, dryRun);\n }\n if (dryRun) {\n logger.info(`[DRY RUN] Would generate ${allComponents.length} component metadata file(s)`);\n } else {\n logger.info(`Generated ${allComponents.length} component metadata file(s)`);\n }\n }\n\n // Generate page type cartridge files\n if (allPageTypes.length > 0) {\n logger.debug(`✅ Found ${allPageTypes.length} decorated page type(s)`);\n for (const pageType of allPageTypes) {\n await generatePageTypeCartridge(pageType as Record<string, unknown>, pagesOutputDir, dryRun);\n }\n if (dryRun) {\n logger.info(`[DRY RUN] Would generate ${allPageTypes.length} page type metadata file(s)`);\n } else {\n logger.info(`Generated ${allPageTypes.length} page type metadata file(s)`);\n }\n }\n\n if (allAspects.length > 0) {\n logger.debug(`✅ Found ${allAspects.length} decorated aspect(s)`);\n for (const aspect of allAspects) {\n await generateAspectCartridge(aspect as Record<string, unknown>, aspectsOutputDir, dryRun);\n }\n if (dryRun) {\n logger.info(`[DRY RUN] Would generate ${allAspects.length} aspect metadata file(s)`);\n } else {\n logger.info(`Generated ${allAspects.length} aspect metadata file(s)`);\n }\n }\n\n // Format generated JSON files with Biome so they match the project's formatting.\n const shouldLintFix = options?.lintFix !== false; // Default to true\n if (\n !dryRun &&\n shouldLintFix &&\n (allComponents.length > 0 || allPageTypes.length > 0 || allAspects.length > 0)\n ) {\n lintGeneratedFiles(metadataDir);\n }\n\n // Return statistics\n return {\n componentsGenerated: allComponents.length,\n pageTypesGenerated: allPageTypes.length,\n aspectsGenerated: allAspects.length,\n totalFiles: allComponents.length + allPageTypes.length + allAspects.length,\n };\n } catch (error) {\n const err = error as Error;\n logger.error('❌ Error:', err.message);\n process.exit(1);\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+DA,MAAMA,iBAA2C;CAC7C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACV;;;;;AAMD,SAAS,WAAW,OAAkC;AAClD,QAAO,OAAO,OAAO,gBAAgB,MAAM;;;;;;;;AAS/C,MAAMC,uBAAiD;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACR;AAED,IAAIC;;;;;;AAOJ,SAAS,qBAA8B;CACnC,MAAM,MAAM,QAAQ,IAAI,OAAO,MAAM;AACrC,KAAI,CAAC,IAAK,QAAO;CACjB,MAAM,aAAa,IAAI,aAAa;AACpC,KAAI;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AAgB,SAAS,YAAY;AAC3C,MACI,CAAC,UACD,kBACC,cAAc,SAAS,KAAK,aAAa,SAAS,KAAK,WAAW,SAAS,GAE5E,oBAAmB,YAAY;AAInC,SAAO;GACH,qBAAqB,cAAc;GACnC,oBAAoB,aAAa;GACjC,kBAAkB,WAAW;GAC7B,YAAY,cAAc,SAAS,aAAa,SAAS,WAAW;GACvE;UACI,OAAO;EACZ,MAAM,MAAM;AACZ,SAAO,MAAM,YAAY,IAAI,QAAQ;AACrC,UAAQ,KAAK,EAAE;AACf,QAAM"}
@@ -1,4 +1,4 @@
1
- import { r as commonFlags } from "../../flags.js";
1
+ import { i as withLegacyMrtShortFlags, r as commonFlags } from "../../flags.js";
2
2
  import { ux } from "@oclif/core";
3
3
  import fs from "fs-extra";
4
4
  import chalk from "chalk";
@@ -6,7 +6,7 @@ import { parseEnv } from "node:util";
6
6
  import { join, resolve } from "node:path";
7
7
  import { pathToFileURL } from "node:url";
8
8
  import { MrtCommand } from "@salesforce/b2c-tooling-sdk/cli";
9
- import { listEnvVars } from "@salesforce/b2c-tooling-sdk/operations/mrt";
9
+ import { listEnvVarsWithBackend } from "@salesforce/b2c-tooling-sdk/operations/mrt";
10
10
 
11
11
  //#region src/utils/objects.ts
12
12
  /**
@@ -110,8 +110,9 @@ function formatInspectOutput({ flatConfig, sources, localVars, mrtVars }) {
110
110
  * When MRT is configured, each override is marked [local only] or [MRT only] as applicable.
111
111
  *
112
112
  * Environment variables read:
113
- * MRT_PROJECT (optional) - MRT project slug, overridden by --project flag
114
- * MRT_TARGET (optional) - MRT target environment, overridden by --environment flag
113
+ * MRT_PROJECT (optional) - MRT project slug, overridden by --project flag
114
+ * MRT_ENVIRONMENT (optional) - MRT target environment, overridden by --environment flag (MRT_TARGET also accepted)
115
+ * MRT_BACKEND (optional) - legacy (default), scapi, or auto; overridden by --mrt-backend flag
115
116
  */
116
117
  var ConfigInspect = class ConfigInspect extends MrtCommand {
117
118
  static description = "Show which config.server.ts values are overridden by .env or MRT";
@@ -121,7 +122,7 @@ var ConfigInspect = class ConfigInspect extends MrtCommand {
121
122
  "<%= config.bin %> <%= command.id %> -d /path/to/my-storefront"
122
123
  ];
123
124
  static flags = {
124
- ...MrtCommand.baseFlags,
125
+ ...withLegacyMrtShortFlags(MrtCommand.baseFlags),
125
126
  ...commonFlags
126
127
  };
127
128
  operations = {
@@ -137,8 +138,11 @@ var ConfigInspect = class ConfigInspect extends MrtCommand {
137
138
  loadConfig: async (projectDirectory) => {
138
139
  return (await import(pathToFileURL(join(projectDirectory, "node_modules/@salesforce/storefront-next-runtime/dist/config-load.js")).href)).loadConfig();
139
140
  },
140
- listEnvVars
141
+ listEnvVarsWithBackend
141
142
  };
143
+ supportsScapiMrt() {
144
+ return true;
145
+ }
142
146
  async run() {
143
147
  const { flags, raw } = await this.parse(ConfigInspect);
144
148
  const projectDirectory = resolve(flags["project-directory"]);
@@ -159,20 +163,24 @@ var ConfigInspect = class ConfigInspect extends MrtCommand {
159
163
  const envKeys = new Set(Object.keys(rawEnvVars).filter((k) => k.startsWith("PUBLIC__")));
160
164
  const sources = getValueSources(flatConfig.map((e) => e.key), envKeys);
161
165
  const project = (explicitFlags.has("project") ? flags.project : void 0) || rawEnvVars.MRT_PROJECT || this.resolvedConfig.values.mrtProject;
162
- const environment = (explicitFlags.has("environment") ? flags.environment : void 0) || rawEnvVars.MRT_TARGET || this.resolvedConfig.values.mrtEnvironment;
166
+ const environment = (explicitFlags.has("environment") ? flags.environment : void 0) || rawEnvVars.MRT_ENVIRONMENT || rawEnvVars.MRT_TARGET || this.resolvedConfig.values.mrtEnvironment;
163
167
  let mrtVars = null;
164
168
  if (project && environment) try {
165
- this.requireMrtCredentials();
166
- const { variables } = await this.operations.listEnvVars({
169
+ const { preference, scapiConnection, legacyAuth } = this.getMrtBackendContext();
170
+ const { variables } = await this.operations.listEnvVarsWithBackend({
171
+ preference,
172
+ scapiConnection,
173
+ legacyAuth,
167
174
  projectSlug: project,
168
175
  environment,
169
- origin: this.resolvedConfig.values.mrtOrigin
170
- }, this.getMrtAuth());
176
+ origin: this.resolvedConfig.values.mrtOrigin,
177
+ onFallback: (reason) => this.warn(reason)
178
+ });
171
179
  mrtVars = new Map(variables.map((v) => [v.name, v.value]));
172
180
  } catch (err) {
173
181
  this.warn(`Could not fetch MRT env vars for ${project}/${environment}: ${err.message}`);
174
182
  }
175
- else ux.stdout("ℹ MRT project/environment not configured. Skipping MRT comparison.\n Use --project and --environment flags or set MRT_PROJECT/MRT_TARGET.\n");
183
+ else ux.stdout("ℹ MRT project/environment not configured. Skipping MRT comparison.\n Use --project and --environment flags or set MRT_PROJECT/MRT_ENVIRONMENT.\n");
176
184
  const output = formatInspectOutput({
177
185
  flatConfig,
178
186
  sources,
@@ -39,6 +39,10 @@ const VERTICALS = {
39
39
  furniture: {
40
40
  label: "Salesforce B2C Commerce Furniture Storefront (Furniture)",
41
41
  url: "https://github.com/SalesforceCommerceCloud/storefront-next-furniture"
42
+ },
43
+ luxury: {
44
+ label: "Salesforce B2C Commerce Luxury Storefront (Luxury)",
45
+ url: "https://github.com/SalesforceCommerceCloud/storefront-next-luxury"
42
46
  }
43
47
  };
44
48
  const DEFAULT_VERTICAL = "fashion";
@@ -257,7 +261,8 @@ var CreateStorefront = class CreateStorefront extends Command {
257
261
  "cosmetic",
258
262
  "foundations",
259
263
  "footwear",
260
- "furniture"
264
+ "furniture",
265
+ "luxury"
261
266
  ]
262
267
  }),
263
268
  "template-branch": Flags.string({
@@ -3,7 +3,7 @@ import { Flags } from "@oclif/core";
3
3
  import path from "path";
4
4
  import fs from "fs-extra";
5
5
  import { CartridgeCommand } from "@salesforce/b2c-tooling-sdk/cli";
6
- import { deleteCartridges, getActiveCodeVersion, reloadCodeVersion, uploadCartridges } from "@salesforce/b2c-tooling-sdk/operations/code";
6
+ import { createScriptsBackend, deleteCartridges, reloadCodeVersion, uploadCartridges } from "@salesforce/b2c-tooling-sdk/operations/code";
7
7
 
8
8
  //#region src/commands/deploy-cartridge.ts
9
9
  /**
@@ -18,6 +18,10 @@ import { deleteCartridges, getActiveCodeVersion, reloadCodeVersion, uploadCartri
18
18
  * Additional flags:
19
19
  * - --delete: Delete existing cartridges before upload
20
20
  * - --reload/-r: Reload (re-activate) code version after deploy (requires OAuth)
21
+ *
22
+ * Code version discovery and reload use SCAPI (scopes `sfcc.scripts` / `sfcc.scripts.rw`) when
23
+ * SFCC_SHORTCODE and SFCC_TENANT_ID are set with client-credentials auth, falling back to OCAPI.
24
+ * Override with --api-backend (env: SFCC_API_BACKEND): auto (default), scapi, or ocapi.
21
25
  */
22
26
  var Deploy = class Deploy extends CartridgeCommand {
23
27
  static description = "Deploy cartridges to B2C Commerce Cloud instance";
@@ -44,6 +48,12 @@ var Deploy = class Deploy extends CartridgeCommand {
44
48
  default: false
45
49
  })
46
50
  };
51
+ _scriptsBackend;
52
+ /** SCAPI-first code version backend with OCAPI fallback, honoring --api-backend. */
53
+ get scriptsBackend() {
54
+ this._scriptsBackend ??= createScriptsBackend({ instance: this.instance });
55
+ return this._scriptsBackend;
56
+ }
47
57
  async run() {
48
58
  const { flags } = await this.parse(Deploy);
49
59
  const projectDirectory = flags["project-directory"] || process.cwd();
@@ -55,14 +65,14 @@ var Deploy = class Deploy extends CartridgeCommand {
55
65
  this.requireWebDavCredentials();
56
66
  let version = this.resolvedConfig.values.codeVersion;
57
67
  if ((!version || flags.reload) && !this.hasOAuthCredentials()) {
58
- const reason = version ? "The --reload flag requires OAuth credentials to reload the code version via OCAPI." : "No code version specified. OAuth credentials are required to auto-discover the active code version.";
68
+ const reason = version ? "The --reload flag requires OAuth credentials to reload the code version via SCAPI or OCAPI." : "No code version specified. OAuth credentials are required to auto-discover the active code version.";
59
69
  this.error(`${reason}\n\nProvide --code-version to use basic auth only, or configure OAuth credentials (--client-id and --client-secret).`);
60
70
  }
61
71
  if (!version) {
62
72
  this.warn("No code version specified, discovering active code version...");
63
73
  let activeVersion;
64
74
  try {
65
- activeVersion = await getActiveCodeVersion(this.instance);
75
+ activeVersion = await this.scriptsBackend.getActiveCodeVersion();
66
76
  } catch (error) {
67
77
  this.error(`Failed to discover active code version: ${error instanceof Error ? error.message : String(error)}\n\nSpecify one explicitly with --code-version or in your dw.json config.`);
68
78
  }
@@ -80,7 +90,7 @@ var Deploy = class Deploy extends CartridgeCommand {
80
90
  }
81
91
  await uploadCartridges(this.instance, cartridges);
82
92
  if (flags.reload) try {
83
- await reloadCodeVersion(this.instance, version);
93
+ await reloadCodeVersion(this.scriptsBackend, version);
84
94
  this.log("Code version reloaded.");
85
95
  } catch (error) {
86
96
  this.warn(`Could not reload code version: ${error instanceof Error ? error.message : String(error)}`);