@faststore/cli 4.8.0-dev.5 → 4.8.0-dev.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1663,9 +1663,10 @@ function updateNextConfig(basePath) {
1663
1663
  const { tmpDir } = withBasePath(basePath);
1664
1664
  const nextConfigPath = path9.join(tmpDir, "next.config.js");
1665
1665
  let nextConfigData = String(readFileSync(nextConfigPath));
1666
+ const normalizedCwd = process.cwd().replaceAll("\\", "/");
1666
1667
  nextConfigData = nextConfigData.replace(
1667
1668
  /outputFileTracingRoot\:\s+(.*),/,
1668
- `outputFileTracingRoot: '${process.cwd()}',`
1669
+ `outputFileTracingRoot: ${JSON.stringify(normalizedCwd)},`
1669
1670
  );
1670
1671
  writeFileSync2(nextConfigPath, nextConfigData);
1671
1672
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/commands/build.ts","../src/utils/binPaths.ts","../src/utils/commands.ts","../src/utils/logger.ts","../src/utils/deprecations.ts","../src/utils/directory.ts","../src/commands/cms-sync.ts","../src/utils/config.ts","../src/utils/cp-schema.ts","../src/utils/runCommandSync.ts","../src/utils/generate.ts","../src/utils/createNextjsPages.ts","../src/utils/readMyAccountCmsRoutes.ts","../src/utils/templates/myAccountCmsPage.ts","../src/utils/templates/myAccountPage.ts","../src/utils/dependencies.ts","../src/utils/plugins.ts","../src/utils/storefrontCopy.ts","../src/utils/hcms.ts","../src/utils/vtex.ts","../src/commands/create.ts","../src/commands/dev.ts","../src/commands/generate.ts","../src/utils/file.ts","../src/utils/generate-types.ts","../src/commands/prepare.ts","../src/commands/start.ts","../src/commands/test.ts","../src/commands/generate-types.ts","../src/commands/cache-graphql.ts","../src/commands/generate-i18n.ts"],"sourcesContent":["export { run } from '@oclif/core'\n\nimport { default as Build } from './commands/build'\nimport { default as CmsSync } from './commands/cms-sync'\nimport { default as Create } from './commands/create'\nimport { default as Dev } from './commands/dev'\nimport { default as Generate } from './commands/generate'\nimport { default as Prepare } from './commands/prepare'\nimport { default as Serve } from './commands/start'\nimport { default as Test } from './commands/test'\nimport { default as GenerateTypes } from './commands/generate-types'\nimport { default as CacheGraphql } from './commands/cache-graphql'\nimport { default as GenerateI18n } from './commands/generate-i18n'\n\nexport const commands = {\n create: Create,\n prepare: Prepare,\n dev: Dev,\n build: Build,\n serve: Serve,\n 'cms-sync': CmsSync,\n test: Test,\n generate: Generate,\n 'generate-types': GenerateTypes,\n 'cache-graphql': CacheGraphql,\n 'generate-i18n': GenerateI18n,\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport { spawnSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport fsExtra from 'fs-extra'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { withNodeModulesBins } from '../utils/binPaths'\nimport { getPreferredPackageManager } from '../utils/commands'\nimport { checkDeprecatedSecretFiles } from '../utils/deprecations'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { logger } from '../utils/logger'\n\nconst { copySync, moveSync, readdirSync, removeSync } = fsExtra\n\nexport default class Build extends Command {\n static args = {\n account: Args.string({\n description:\n 'The account for which the Discovery is running. Currently noop.',\n }),\n path: Args.string({\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n static flags = {\n ['no-verify']: Flags.boolean({\n description:\n 'Skips verification of faststore dependencies version string to prevent usage of packages outside npm registry.',\n }),\n }\n\n async run() {\n const { args, flags } = await this.parse(Build)\n\n const basePath = getBasePath(args.path)\n\n // Check for deprecated secret files\n checkDeprecatedSecretFiles(basePath)\n\n if (!flags['no-verify']) {\n const invalidPackages = await checkDeps(basePath)\n invalidPackages.forEach((pkg) =>\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Dependency ${pkg} has invalid version signature. Please use a semver like ^1.0.0 (check the official releases on https://github.com/vtex/faststore)`\n )\n )\n }\n\n const { tmpDir } = withBasePath(basePath)\n\n const packageManager = await getPreferredPackageManager()\n\n const binCli = path.join(\n fileURLToPath(\n import.meta.resolve('@faststore/cli/runner', import.meta.url)\n )\n )\n let scriptResult = spawnSync('node', [binCli, 'generate', basePath], {\n stdio: 'inherit',\n })\n\n if (scriptResult.error || scriptResult.status !== 0) {\n throw 'Error: Cant run generate' + (scriptResult.error?.message ?? '')\n }\n\n scriptResult = spawnSync('node', [binCli, 'cache-graphql', basePath], {\n stdio: 'inherit',\n })\n\n if (scriptResult.error || scriptResult.status !== 0) {\n throw (\n 'Error: Unable to run cache-graphql' +\n (scriptResult.error?.message ?? '')\n )\n }\n\n // generate-i18n will validate localization config and check if it's enabled\n scriptResult = spawnSync('node', [binCli, 'generate-i18n', basePath], {\n stdio: 'inherit',\n })\n\n if (scriptResult.error || scriptResult.status !== 0) {\n throw (\n 'Error: Unable to run generate-i18n' +\n (scriptResult.error?.message ?? '')\n )\n }\n\n scriptResult = spawnSync(`${packageManager} run build`, {\n shell: true,\n cwd: tmpDir,\n stdio: 'inherit',\n env: withNodeModulesBins(tmpDir),\n })\n\n if (scriptResult.status && scriptResult.status !== 0) {\n process.exit(scriptResult.status)\n }\n\n await normalizeStandaloneBuildDir(basePath)\n await copyResources(basePath)\n }\n}\n\nasync function copyResource(from: string, to: string) {\n try {\n if (existsSync(to)) {\n removeSync(to)\n }\n\n copySync(from, to)\n console.log(\n `${chalk.green('success')} - ${chalk.dim(from)} copied to ${chalk.dim(\n to\n )}`\n )\n } catch (err) {\n console.error(`${chalk.red('error')} - ${err}`)\n }\n}\n\nasync function normalizeStandaloneBuildDir(basePath: string) {\n const { tmpDir } = withBasePath(basePath)\n const isRunningFromMonorepo = process.cwd() !== basePath\n const prefix = isRunningFromMonorepo\n ? `${path.relative(process.cwd(), basePath).replace(/\\\\/g, '/')}/`\n : ''\n\n // Fix Next.js v13+ standalone build output directory\n if (existsSync(`${tmpDir}/.next/standalone/${prefix}.faststore`)) {\n const standaloneBuildFiles = readdirSync(\n `${tmpDir}/.next/standalone/${prefix}.faststore`\n )\n\n await Promise.all(\n standaloneBuildFiles.map((file) =>\n moveSync(\n `${tmpDir}/.next/standalone/${prefix}.faststore/${file}`,\n `${tmpDir}/.next/standalone/${file}`,\n { overwrite: true }\n )\n )\n )\n removeSync(`${tmpDir}/.next/standalone/${prefix}.faststore`)\n }\n}\n\nasync function copyResources(basePath: string) {\n const { tmpDir, userDir } = withBasePath(basePath)\n\n if (process.env.BUILD_CONTEXT === 'vercel') {\n const toDir = process.cwd()\n\n // Because of how copyResource works (delete the target directory if it exists),\n // if we're moving something to the same place it is it will break.\n const nextOutputDirectory = `${tmpDir}/.next`\n const expectedOutputDirectory = `${toDir}/.faststore/.next`\n if (nextOutputDirectory !== expectedOutputDirectory) {\n await copyResource(nextOutputDirectory, expectedOutputDirectory)\n }\n await copyResource(`${tmpDir}/public`, `${toDir}/public`)\n } else {\n await copyResource(`${tmpDir}/.next`, `${userDir}/.next`)\n await copyResource(\n `${tmpDir}/lighthouserc.js`,\n `${userDir}/lighthouserc.js`\n )\n await copyResource(`${tmpDir}/public`, `${userDir}/public`)\n }\n}\n\nasync function checkDeps(basePath: string): Promise<Array<string>> {\n const packageJsonPath = `${basePath}/package.json`\n if (!existsSync(packageJsonPath)) {\n console.log(\n `${chalk.yellow(\n 'warning'\n )} - package.json not found at ${packageJsonPath}`\n )\n }\n\n try {\n const mod = await import(pathToFileURL(packageJsonPath).href, {\n with: { type: 'json' },\n })\n const pkg = (mod.default ?? mod) as {\n devDependencies?: Record<string, string>\n dependencies?: Record<string, string>\n peerDependencies?: Record<string, string>\n }\n const {\n devDependencies = {},\n dependencies = {},\n peerDependencies = {},\n } = pkg\n\n const allDeps: Record<string, string> = Object.assign(\n {},\n peerDependencies,\n devDependencies,\n dependencies\n )\n\n const invalidPackages: Array<string> = []\n\n Object.entries(allDeps).forEach(([pkg, version]) => {\n if (/^@faststore\\/.+/i.test(pkg) === false) return\n\n if (version && /^(http|https|git):.+/.test(version) === true) {\n invalidPackages.push(pkg)\n }\n })\n\n return invalidPackages\n } catch (err) {\n console.log(\n `${chalk.yellow('warning')} - unable to check @faststore dependencies: ${err}`\n )\n\n return []\n }\n}\n","import fsExtra from 'fs-extra'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\n\nconst { existsSync } = fsExtra\n\n/**\n * Resolves a package's executable through Node's module resolution, starting\n * the lookup at `fromDir`.\n *\n * `withNodeModulesBins` can only order directories, so it runs whichever copy of\n * a binary the nearest ancestor `node_modules/.bin` happens to hold. That is not\n * necessarily the copy `@faststore/core` depends on: on a hoisted monorepo\n * another module's older Next can win the root `.bin` link, and the build then\n * fails on flags that version does not have. Module resolution follows the\n * dependency graph instead, so it returns the copy core would import — and it\n * still finds one where no ancestor `.bin` has it at all, as happens when a\n * package manager nests rather than hoists.\n *\n * Returns `undefined` when the specifier cannot be resolved, so callers can fall\n * back to the bare command name.\n */\nexport function resolvePackageBin(\n specifier: string,\n fromDir: string\n): string | undefined {\n try {\n // createRequire needs a file path to anchor the lookup. The file itself does\n // not have to exist; only the directory it sits in is used.\n return createRequire(path.join(fromDir, 'noop.js')).resolve(specifier)\n } catch {\n return undefined\n }\n}\n\nfunction collectBinDirs(fromDir: string) {\n const binDirs: string[] = []\n let currentDir = path.resolve(fromDir)\n\n while (true) {\n const binDir = path.join(currentDir, 'node_modules', '.bin')\n\n if (existsSync(binDir)) {\n binDirs.push(binDir)\n }\n\n const parentDir = path.dirname(currentDir)\n\n if (parentDir === currentDir) {\n return binDirs\n }\n\n currentDir = parentDir\n }\n}\n\n// Environment variables are case-insensitive on Windows, where the key is\n// usually `Path`. Reusing the existing key avoids handing the child process\n// both `Path` and `PATH`.\nfunction getPathKey(env: NodeJS.ProcessEnv) {\n return Object.keys(env).find((key) => key.toUpperCase() === 'PATH') ?? 'PATH'\n}\n\n/**\n * Prepends the `node_modules/.bin` of `fromDir` and of every ancestor\n * directory to `PATH`.\n *\n * The generated `.faststore` package has no `node_modules` of its own, so the\n * binaries its scripts call (`na`, `next`) live higher up the tree: in the\n * store root or, on hoisted monorepos, the workspace root.\n */\nexport function withNodeModulesBins(\n fromDir: string,\n env: NodeJS.ProcessEnv = process.env\n): NodeJS.ProcessEnv {\n const binDirs = collectBinDirs(fromDir)\n\n if (binDirs.length === 0) {\n return { ...env }\n }\n\n const pathKey = getPathKey(env)\n const currentEntries = env[pathKey]?.split(path.delimiter) ?? []\n // Package managers already put some of these directories in PATH when they\n // run a script, but not necessarily nearest first. Dropping their copies\n // before prepending `binDirs` keeps the nearest ancestor in charge instead\n // of letting a farther one that was missing from PATH jump ahead of it.\n const binDirSet = new Set(binDirs)\n const otherEntries = currentEntries.filter((entry) => !binDirSet.has(entry))\n\n return {\n ...env,\n [pathKey]: [...binDirs, ...otherEntries].join(path.delimiter),\n }\n}\n","import {\n LOCKS,\n agents,\n cmdExists,\n detect,\n getCommand,\n getVoltaPrefix,\n} from '@antfu/ni'\nimport type { Agent } from '@antfu/ni'\nimport chalk from 'chalk'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { logger } from './logger'\n\nexport interface ResolvedPackageManager {\n /** Agent id, validated against `ni`'s known agents. For comparisons, never for execution. */\n agent: Agent\n /** Executable form for `spawn`/`spawnSync` with `shell: true`. May carry a Volta prefix. */\n command: string\n /** Executable form for `spawn` without a shell. */\n argv: [string, ...string[]]\n}\n\nexport class UnknownAgentError extends Error {}\n\nexport class NoAvailablePackageManagerError extends Error {}\n\nexport interface ResolvePackageManagerOptions {\n /**\n * Whether a detected-but-not-installed agent may be substituted with an\n * available fallback. Callers that write to the project (dependency\n * installation) must pass `false`: installing with a substitute agent would\n * leave a second, conflicting lockfile next to the project's own.\n */\n substitute?: boolean\n}\n\nconst DEFAULT_AGENT: Agent = 'yarn'\n// yarn and npm first — they are what the store build images ship. The\n// remaining known agents are last resorts so an environment that only has\n// pnpm or bun still resolves instead of failing.\nconst FALLBACK_AGENTS: Agent[] = ['yarn', 'npm', 'pnpm', 'bun']\n\n/**\n * Resolves the package manager to use for `cwd`.\n *\n * `programmatic: true` is what keeps `ni` from going interactive. Without it, an\n * agent that is not installed makes `ni` render a confirm prompt to stdout, and\n * callers interpolate this value straight into shell commands.\n */\nexport async function resolvePackageManager(\n cwd: string = process.cwd(),\n { substitute = true }: ResolvePackageManagerOptions = {}\n): Promise<ResolvedPackageManager> {\n const detected = (await detect({ programmatic: true, cwd })) ?? DEFAULT_AGENT\n\n if (!agents.includes(detected)) {\n throw new UnknownAgentError(\n `\"${detected}\" is not a known package manager. Expected one of: ${agents.join(\n ', '\n )}.`\n )\n }\n\n let agent = detected\n\n if (!cmdExists(binOf(detected))) {\n if (!substitute) {\n throw new NoAvailablePackageManagerError(\n `Detected \"${detected}\", which is not installed in this environment. This operation writes a lockfile, so no other package manager can stand in for it. Install \"${detected}\", or remove the lockfile or \"packageManager\" field that selects it.`\n )\n }\n\n agent = substituteAgent(detected, cwd)\n }\n\n const argv: [string, ...string[]] = [binOf(agent)]\n const voltaPrefix = getVoltaPrefix()\n\n if (voltaPrefix) {\n argv.unshift(...voltaPrefix.split(' '))\n }\n\n return { agent, command: argv.join(' '), argv }\n}\n\n/** Shell-ready form of {@link resolvePackageManager}, for callers that only run a command. */\nexport async function getPreferredPackageManager(\n cwd?: string\n): Promise<string> {\n const { command } = await resolvePackageManager(cwd)\n\n return command\n}\n\nfunction binOf(agent: Agent): string {\n return getCommand(agent, 'agent')\n}\n\nfunction substituteAgent(detected: Agent, cwd: string): Agent {\n const available = FALLBACK_AGENTS.find((candidate) =>\n cmdExists(binOf(candidate))\n )\n\n if (!available) {\n throw new NoAvailablePackageManagerError(\n `Detected \"${detected}\", which is not installed, and none of ${FALLBACK_AGENTS.join(\n ', '\n )} is available either.`\n )\n }\n\n const lockfiles = Object.keys(LOCKS).filter((lockfile) =>\n existsSync(join(cwd, lockfile))\n )\n\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Detected \"${detected}\" but it is not installed in this environment. Using \"${available}\" instead.` +\n (lockfiles.length > 1\n ? `\\nMore than one lockfile is committed (${lockfiles.join(\n ', '\n )}). Keep a single one so the package manager is unambiguous.`\n : '')\n )\n\n return available\n}\n","export const logger = new Proxy(console, {\n get(target, prop: keyof Console) {\n if (prop === 'log') {\n return (...args: any[]) => {\n if (process.env.DISCOVERY_DEBUG === 'true') {\n target.log(...args)\n }\n }\n }\n return target[prop]\n },\n})\n","import { existsSync } from 'node:fs'\nimport chalk from 'chalk'\nimport { logger } from './logger'\n\n/**\n * Checks for the presence of deprecated secret files and logs a warning if found.\n *\n * @param basePath The base path where to look for the secret files\n */\nexport function checkDeprecatedSecretFiles(basePath: string) {\n const secretsFilePath = `${basePath}/secrets.hidden.json`\n const vtexEnvFilePath = `${basePath}/vtex.env`\n\n const secretsFileExists = existsSync(secretsFilePath)\n const vtexEnvFileExists = existsSync(vtexEnvFilePath)\n\n if (secretsFileExists || vtexEnvFileExists) {\n const filesFound = [\n secretsFileExists ? 'secrets.hidden.json' : null,\n vtexEnvFileExists ? 'vtex.env' : null,\n ]\n .filter(Boolean)\n .join(' and ')\n\n logger.warn(\n `${chalk.yellow('warning')} - Deprecated secret files detected: ${chalk.bold(filesFound)}\\n` +\n `Note: 'vtex.env' should only be used for local development and not in production.\\n` +\n `For production environments, please configure your secrets directly in the FastStore WebOps Settings page.`\n )\n logger.log('') // Add empty line for better readability\n }\n}\n","import path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport const getBasePath = (basePath?: string) => {\n if (basePath) {\n return path.resolve(basePath)\n }\n\n return process.cwd()\n}\n\nexport const withBasePath = (basepath: string) => {\n const tmpFolderName = '.faststore'\n\n // The basepath is where the discovery code is. It's either . or the path configured on faststore.json\n const getRoot = () => basepath\n\n /*\n * This will loop from the basepath until the process.cwd() looking for node_modules/@faststore/core\n *\n * If it reaches process.cwd() (or /, as a safeguard), without finding it, it will throw an exception\n */\n const getCorePackagePath = () =>\n path.dirname(\n fileURLToPath(import.meta.resolve('@faststore/core', import.meta.url))\n )\n\n const customizationsDir = getRoot()\n const tmpDir = path.join(getRoot(), tmpFolderName)\n const userSrcDir = path.join(customizationsDir, 'src')\n const getPackagePath = (...packagePath: string[]) =>\n path.join(customizationsDir, 'node_modules', ...packagePath)\n\n return {\n getRoot,\n getPackagePath,\n userDir: customizationsDir,\n userSrcDir,\n userThemesFileDir: path.join(userSrcDir, 'themes'),\n userCMSDir: path.join(customizationsDir, 'cms', 'faststore'),\n userLegacyStoreConfigFile: path.join(\n customizationsDir,\n 'faststore.config.js'\n ),\n userStoreConfigFile: path.join(customizationsDir, 'discovery.config.js'),\n\n tmpSeoConfig: path.join(tmpDir, 'next-seo.config.ts'),\n tmpFolderName,\n tmpDir,\n tmpCustomizationsSrcDir: path.join(tmpDir, 'src', 'customizations', 'src'),\n tmpThemesCustomizationsFile: path.join(\n tmpDir,\n 'src',\n 'customizations',\n 'src',\n 'themes',\n 'index.scss'\n ),\n tmpThemesPluginsFile: path.join(tmpDir, 'src', 'plugins', 'index.scss'),\n tmpCMSDir: (projectName = 'faststore') =>\n path.join(tmpDir, 'cms', projectName),\n tmpCMSWebhookUrlsFile: path.join(tmpDir, 'cms-webhook-urls.json'),\n tmpPagesDir: path.join(tmpDir, 'src', 'pages'),\n tmpApiDir: path.join(tmpDir, 'src', 'pages', 'api'),\n tmpPluginsDir: path.join(tmpDir, 'src', 'plugins'),\n tmpStoreConfigFile: path.join(\n tmpDir,\n 'src',\n 'customizations',\n 'discovery.config.js'\n ),\n\n coreDir: getCorePackagePath(),\n coreCMSDir: path.join(getCorePackagePath(), 'cms', 'faststore'),\n }\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n isMyAccountEnabled,\n resolveContentSource,\n type ResolvedContentSource,\n} from '../utils/config'\nimport {\n cleanupMyAccountMergeDir,\n errorNoCustomization,\n generateAndUploadSchema,\n getCpSchemaOutputPath,\n getExistingCpDirs,\n type MyAccountMerge,\n prepareMyAccountMergeDir,\n} from '../utils/cp-schema'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\nimport { mergeCMSFiles } from '../utils/hcms'\nimport { logger } from '../utils/logger'\nimport { assertVtexReadyForAccount } from '../utils/vtex'\n\ntype StoreConfig = {\n api?: {\n storeId?: string\n }\n contentSource?: {\n type?: string\n project?: string\n }\n experimental?: {\n enableFaststoreMyAccount?: boolean\n }\n}\n\nconst CONTENT_SOURCE_ACTION: Record<ResolvedContentSource, string> = {\n CMS: 'merging and syncing CMS content',\n CP: 'generating and uploading schema',\n}\n\nexport default class CmsSync extends Command {\n static flags = {\n ['dry-run']: Flags.boolean({ char: 'd' }),\n }\n\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being synched with the CMS is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { flags, args } = await this.parse(CmsSync)\n\n const basePath = getBasePath(args.path)\n const { userStoreConfigFile } = withBasePath(basePath)\n\n const storeConfig: StoreConfig | null = existsSync(userStoreConfigFile)\n ? (await import(pathToFileURL(path.resolve(userStoreConfigFile)).href))\n .default\n : null\n\n const source = resolveContentSource(storeConfig?.contentSource?.type)\n\n logger.info(\n `${chalk.blue('[Info]')} - Detected contentSource \"${source}\" — ${CONTENT_SOURCE_ACTION[source]}`\n )\n\n switch (source) {\n case 'CMS':\n return this.runLegacySync({\n basePath,\n storeConfig,\n dryRun: flags['dry-run'],\n })\n case 'CP':\n return this.runCpSync({\n basePath,\n storeConfig,\n dryRun: flags['dry-run'],\n })\n default: {\n return source\n }\n }\n }\n\n private async runLegacySync({\n basePath,\n storeConfig,\n dryRun,\n }: {\n basePath: string\n storeConfig: StoreConfig | null\n dryRun?: boolean\n }) {\n const { tmpDir } = withBasePath(basePath)\n const project = storeConfig?.contentSource?.project ?? 'faststore'\n\n await generate({ setup: true, basePath })\n await mergeCMSFiles(basePath)\n\n if (dryRun) {\n return\n }\n\n return spawn(`vtex cms sync ${project}`, {\n shell: true,\n cwd: tmpDir,\n stdio: 'inherit',\n })\n }\n\n private runCpSync({\n basePath,\n storeConfig,\n dryRun,\n }: {\n basePath: string\n storeConfig: StoreConfig | null\n dryRun?: boolean\n }) {\n assertVtexReadyForAccount(storeConfig?.api?.storeId)\n\n let merge: MyAccountMerge | undefined\n\n if (isMyAccountEnabled(storeConfig)) {\n logger.info(\n `${chalk.blue('[Info]')} - Merging My Account sections and content-types into the schema`\n )\n // The merge dir already contains the store's own customizations merged\n // with the core My Account schemas, so it replaces the raw store dirs.\n merge = prepareMyAccountMergeDir(basePath)\n }\n\n const dirs = merge ? merge.dirs : getExistingCpDirs(basePath)\n\n if (dirs.length === 0) {\n errorNoCustomization()\n }\n\n const schemaOut = getCpSchemaOutputPath(basePath)\n\n // A toolbelt failure inside generateAndUploadSchema exits via process.exit(),\n // which bypasses `finally`. Register the cleanup on `exit` so the staging dir\n // is removed on that path too, then run it synchronously and drop the hook on\n // every normal path (success, dry-run, or a thrown error).\n let cleanup: (() => void) | undefined\n if (merge) {\n const { mergeDir } = merge\n cleanup = () => cleanupMyAccountMergeDir(mergeDir)\n process.once('exit', cleanup)\n }\n\n try {\n generateAndUploadSchema({\n basePath,\n dirs,\n schemaOut,\n dryRun: dryRun ?? false,\n project: storeConfig?.contentSource?.project,\n })\n } finally {\n if (cleanup) {\n process.removeListener('exit', cleanup)\n cleanup()\n }\n }\n }\n}\n","import chalk from 'chalk'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\n\nimport { pathToFileURL } from 'node:url'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\n\nconst configFileName = 'discovery.config.js'\n\nexport type ResolvedContentSource = 'CMS' | 'CP'\n\n/**\n * Minimal config shape consumed when deciding whether to merge My Account\n * schemas. Kept loose on purpose so callers can pass their own store config.\n */\ntype MyAccountConfig = {\n experimental?: {\n enableFaststoreMyAccount?: boolean\n }\n}\n\n/**\n * Whether FastStore My Account is enabled in the store config.\n * When enabled (CP mode only), `cms-sync` merges the core My Account CMS\n * schemas into the generated schema. Defaults to false when absent.\n */\nexport function isMyAccountEnabled(config?: MyAccountConfig | null): boolean {\n return config?.experimental?.enableFaststoreMyAccount === true\n}\n\n/**\n * Resolves the store's contentSource.type to a supported CMS flow.\n * Absent or CMS → legacy Headless CMS; CP → Content Platform schema publish.\n */\nexport function resolveContentSource(rawType?: string): ResolvedContentSource {\n const normalized = rawType?.toUpperCase()\n\n switch (normalized) {\n case undefined:\n case 'CMS':\n return 'CMS'\n case 'CP':\n return 'CP'\n default: {\n logger.error(\n `${chalk.red('[Error]')} - Unsupported contentSource.type \"${rawType}\". Expected \"CMS\" or \"CP\".`\n )\n process.exit(1)\n }\n }\n}\n\n/**\n * Partial type for discovery config with only the properties used by this module\n */\ntype DiscoveryConfigSubset = {\n localization?: {\n enabled?: boolean\n }\n contentSource?: {\n type?: string\n }\n}\n\n/**\n * Reads and returns the discovery config from tmpDir or basePath.\n *\n * @param basePath - The base path where the FastStore is located\n * @returns Promise<DiscoveryConfigSubset | null> - The config object or null if not found\n */\nexport async function getDiscoveryConfig(\n basePath: string\n): Promise<DiscoveryConfigSubset | null> {\n const { tmpDir } = withBasePath(basePath)\n const configPaths = [\n path.join(tmpDir, configFileName),\n path.join(basePath, configFileName),\n ]\n\n for (const configPath of configPaths) {\n if (existsSync(configPath)) {\n try {\n const discoveryConfig = await import(pathToFileURL(configPath).href)\n return discoveryConfig?.default ?? discoveryConfig\n } catch (error) {\n logger.warn(\n `${chalk.yellow('warning')} - Could not read config file: ${configPath}.`\n )\n }\n }\n }\n\n return null\n}\n\n/**\n * Checks if localization feature is enabled in the discovery config.\n *\n * @param config - The discovery config object\n * @returns boolean - true if localization.enabled === true, false otherwise\n */\nfunction isLocalizationEnabled(config: DiscoveryConfigSubset): boolean {\n return config?.localization?.enabled === true\n}\n\n/**\n * Validates if contentSource is set to \"CP\" when localization is enabled.\n * Exits the process with an error message if validation fails.\n *\n * @param config - The discovery config object\n */\nfunction validateContentSourceForLocalization(\n config: DiscoveryConfigSubset\n): void {\n if (!isLocalizationEnabled(config)) {\n return\n }\n\n const currentContentSourceType = config?.contentSource?.type?.toUpperCase()\n\n if (currentContentSourceType !== 'CP') {\n logger.error(\n `\\n${chalk.red('[Error]')} - Localization is enabled but contentSource is set to \"${currentContentSourceType}\".\\n\\n` +\n `${chalk.cyan('Required Action:')}\\n` +\n `Update your ${chalk.bold('discovery.config.js')} file:\\n\\n` +\n ` contentSource: {\\n` +\n ` type: ${chalk.green('\"CP\"')}\\n` +\n ` },\\n\\n` +\n `${chalk.dim('When localization is enabled, Content Platform (CP) is required.')}\\n`\n )\n\n process.exit(1)\n }\n}\n\n/**\n * Checks localization status and validates configuration.\n * Reads the config file once and performs both checks.\n *\n * @param basePath - The base path where the FastStore is located\n * @returns Promise<boolean> - true if localization is enabled and valid, false otherwise\n */\nexport async function checkAndValidateLocalization(\n basePath: string\n): Promise<boolean> {\n const config = await getDiscoveryConfig(basePath)\n\n // If we can't read the config, default to false (backward compatibility)\n if (!config) {\n return false\n }\n\n validateContentSourceForLocalization(config)\n\n return isLocalizationEnabled(config)\n}\n","/**\n * CP (Content Platform) schema helpers for `cms-sync`.\n * Generates and uploads the store's custom CMS schema via `vtex content`.\n * Store context only: no `-l` / base.jsonc, no core merge.\n */\nimport chalk from 'chalk'\nimport { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'\nimport path from 'node:path'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport { runCommandSync } from './runCommandSync'\n\nconst MY_ACCOUNT_SUBDIRS = ['components', 'pages'] as const\n\nexport function getExistingCpDirs(basePath: string): string[] {\n const { userCMSDir } = withBasePath(basePath)\n const componentsDir = path.join(userCMSDir, 'components')\n const pagesDir = path.join(userCMSDir, 'pages')\n\n return [componentsDir, pagesDir]\n .filter((dir) => existsSync(dir))\n .map((dir) => path.relative(basePath, dir))\n}\n\nexport function errorNoCustomization(): never {\n logger.error(\n `${chalk.red('[Error]')} - No CMS customization found. Expected cms/faststore/components and/or cms/faststore/pages.`\n )\n process.exit(1)\n}\n\nexport function getCpSchemaOutputPath(basePath: string): string {\n // Relative to basePath: the toolbelt resolves -o against the cwd\n // (path.join(cwd, arg)), so an absolute path would be doubled into\n // <store>/<store>/cms/... and fail with ENOENT.\n return path.relative(\n basePath,\n path.join(withBasePath(basePath).userCMSDir, 'schema.json')\n )\n}\n\nexport type MyAccountMerge = {\n /** Absolute root directory holding the merged My Account JSONC. */\n mergeDir: string\n /**\n * Paths of the two merged directories, relative to `basePath` and ordered as\n * `[components, pages]`, so they can be passed positionally to\n * `generate-schema <componentsPath> <pagesPath>`.\n */\n dirs: string[]\n}\n\n/**\n * Builds a staging directory with exactly two subdirectories (`components` and\n * `pages`), each holding the file-level merge of the core My Account CMS JSONC\n * and the store's own customizations, ready to be fed to\n * `generate-schema <componentsPath> <pagesPath>`.\n *\n * The staging dir lives inside the store's `.faststore` tmp folder (created on\n * demand) and the returned paths are relative to `basePath`. The toolbelt\n * resolves positional args against the cwd (`path.join(cwd, arg)`), so an\n * absolute path under `os.tmpdir()` would be mangled into `<store>/var/...`\n * and fail with ENOENT.\n *\n * The My Account schemas are intentionally excluded from the published base\n * schema (and the Schema Registry), so they must be supplied locally when the\n * `experimental.enableFaststoreMyAccount` flag is on. They are copied from the\n * installed `@faststore/core`.\n *\n * Exits the process when the core My Account schemas are not found.\n */\nexport function prepareMyAccountMergeDir(basePath: string): MyAccountMerge {\n const { coreCMSDir, userCMSDir, tmpDir } = withBasePath(basePath)\n const coreMyAccountDir = path.join(coreCMSDir, 'my-account')\n\n if (!existsSync(coreMyAccountDir)) {\n logger.error(\n `${chalk.red('[Error]')} - My Account is enabled but the core My Account schemas were not found at ${coreMyAccountDir}. Update @faststore/core or disable experimental.enableFaststoreMyAccount.`\n )\n process.exit(1)\n }\n\n // `.faststore` may not exist yet in the CP flow (it does not run `generate`).\n mkdirSync(tmpDir, { recursive: true })\n const mergeDir = mkdtempSync(path.join(tmpDir, 'cms-myaccount-'))\n\n try {\n const dirs: string[] = []\n for (const subdir of MY_ACCOUNT_SUBDIRS) {\n const dest = path.join(mergeDir, subdir)\n mkdirSync(dest, { recursive: true })\n\n // Core My Account first; the store's customizations override on collision.\n const coreSource = path.join(coreMyAccountDir, subdir)\n if (existsSync(coreSource)) {\n cpSync(coreSource, dest, { recursive: true })\n }\n\n const storeSource = path.join(userCMSDir, subdir)\n if (existsSync(storeSource)) {\n cpSync(storeSource, dest, { recursive: true })\n }\n\n dirs.push(path.relative(basePath, dest))\n }\n\n return { mergeDir, dirs }\n } catch (error) {\n cleanupMyAccountMergeDir(mergeDir)\n throw error\n }\n}\n\n/**\n * Removes the temporary My Account merge directory. Safe to call on any\n * outcome (success, dry-run, or failure).\n */\nexport function cleanupMyAccountMergeDir(mergeDir: string): void {\n rmSync(mergeDir, { recursive: true, force: true })\n}\n\nexport function generateAndUploadSchema({\n basePath,\n dirs,\n schemaOut,\n dryRun,\n project,\n}: {\n basePath: string\n dirs: string[]\n schemaOut: string\n dryRun: boolean\n /**\n * The store's `contentSource.project`, forwarded as `--storeId` to\n * `vtex content upload-schema` so the published schema's `$id`\n * (`${account}.${storeId}`) matches the project declared in\n * `discovery.config.js`, mirroring the legacy CMS flow's use of `project`\n * in `vtex cms sync ${project}`. Falls back to `'faststore'`, the same\n * default already used there.\n */\n project?: string\n}): void {\n // Interactive: generate-schema prompts to confirm overriding base\n // definitions (no --yes flag), and upload-schema prompts for the schema\n // version to publish. stdio must reach the user's TTY.\n runCommandSync({\n cmd: `vtex content generate-schema ${dirs.join(' ')} -o ${schemaOut}`,\n cwd: basePath,\n throws: 'error',\n errorMessage: 'Failed to generate CMS schema',\n interactive: true,\n })\n\n if (dryRun) {\n return\n }\n\n const storeId = project ?? 'faststore'\n\n runCommandSync({\n cmd: `vtex content upload-schema ${schemaOut} --storeId ${storeId}`,\n cwd: basePath,\n throws: 'error',\n errorMessage: 'Failed to upload CMS schema',\n interactive: true,\n })\n}\n","import chalk from 'chalk'\nimport type { ChildProcess, ExecException } from 'node:child_process'\nimport { execSync } from 'node:child_process'\nimport { logger } from './logger'\n\ntype ExecSyncError = (ExecException & ChildProcess) | undefined\n\nconst showError = ({\n message,\n cmd,\n output,\n}: {\n message: string\n cmd: string\n output?: string\n}) => {\n logger.error(`${chalk.red('error')} - ${message}`)\n\n if (cmd && output) {\n logger.error(`${chalk.magenta('$')} ${cmd}`)\n logger.error(output)\n }\n\n process.exit(1)\n}\n\nconst showWarning = ({\n message,\n cmd,\n output,\n}: {\n message: string\n cmd: string\n output?: string\n}) => {\n logger.warn(`${chalk.yellow('warn')} - ${message}`)\n\n if (cmd && output) {\n logger.warn(`${chalk.magenta('$')} ${cmd}`)\n logger.warn(output)\n }\n}\n\nexport const runCommandSync = ({\n cmd,\n errorMessage,\n throws,\n cwd,\n env,\n interactive = false,\n}: {\n cmd: string\n errorMessage: string\n throws: 'warning' | 'error'\n cwd?: string\n env?: NodeJS.ProcessEnv\n interactive?: boolean\n}) => {\n try {\n logger.log(`[STARTED] ${cmd}`)\n\n // Interactive mode (stdio: 'inherit') wires the child to the parent TTY so\n // the toolbelt can prompt the user — e.g. generate-schema's \"override\n // default definitions?\" confirmation and upload-schema's version selection.\n // execSync stays synchronous, preserving generate → upload ordering. Output\n // goes straight to the terminal, so it can't be captured (and need not be).\n //\n // Non-interactive mode merges stdout + stderr via 2>&1 so the captured\n // output holds the tool's real error. We intentionally do not append\n // --debug/--verbose: strict toolbelt commands reject unknown flags. Verbose\n // progress logging is gated by DISCOVERY_DEBUG in the logger itself.\n const res = execSync(interactive ? cmd : `${cmd} 2>&1`, {\n stdio: interactive ? 'inherit' : 'pipe',\n cwd,\n env,\n })\n logger.log(`[STATUS] ${res?.toString() ?? 'Unknown'}`)\n logger.log(`[FINISHED] ${cmd}`)\n } catch (error) {\n const execError = error as ExecSyncError\n // Always surface the tool's own output (stdout+stderr are merged via 2>&1)\n // so store devs see the real root cause instead of only the generic message.\n const output =\n execError?.stdout?.toString() ||\n execError?.stderr?.toString() ||\n undefined\n\n if (throws === 'warning') {\n showWarning({ message: errorMessage, cmd, output })\n } else {\n showError({ message: errorMessage, cmd, output })\n }\n }\n}\n","import chalk from 'chalk'\nimport fsExtra from 'fs-extra'\n\nimport path from 'node:path'\n\nimport ora from 'ora'\n\nimport { pathToFileURL } from 'node:url'\nimport { resolvePackageBin } from './binPaths'\nimport { createNextJsPages } from './createNextjsPages'\nimport { installDependencies } from './dependencies'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport { installPlugins } from './plugins'\nimport {\n prepareStorefrontTsConfig,\n shouldCopyToStorefront,\n} from './storefrontCopy'\n\nconst {\n copyFileSync,\n copySync,\n existsSync,\n mkdirsSync,\n readFileSync,\n readdirSync,\n removeSync,\n statSync,\n writeFileSync,\n writeJsonSync,\n} = fsExtra\ninterface GenerateOptions {\n setup?: boolean\n basePath: string\n}\n\nfunction createTmpFolder(basePath: string) {\n const { tmpDir, tmpFolderName } = withBasePath(basePath)\n\n try {\n if (existsSync(tmpDir)) {\n removeSync(tmpDir)\n }\n\n mkdirsSync(tmpDir)\n logger.log(\n `${chalk.green('success')} - Temporary folder ${chalk.dim(\n tmpFolderName\n )} created`\n )\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n}\n\n/**\n * Builds the `.faststore/package.json` from `@faststore/core`'s manifest.\n * Strips `exports` and `packageManager` (the latter is pinned to pnpm and\n * breaks Yarn/Corepack on consumer stores).\n *\n * Propagates the store's `volta` config (when present) so Volta pins the same\n * Node/Yarn versions inside `.faststore`. Volta stops at the nearest\n * `package.json` and would otherwise fall back to a global Yarn Berry, which\n * breaks on the nested manifest.\n */\nexport function buildFaststorePackageJson(\n coreManifest: Record<string, unknown>,\n voltaConfig?: Record<string, unknown>,\n nextBin?: string\n): Record<string, unknown> {\n const {\n exports: _exports,\n packageManager: _packageManager,\n ...rest\n } = coreManifest\n\n const existingScripts =\n (rest.scripts as Record<string, string> | undefined) ?? {}\n\n /**\n * Invoking Next through the path resolved from `@faststore/core` rather than\n * by name, so a copy that won the root `.bin` link cannot answer instead. On\n * a monorepo where another module pins an older major, that copy is a\n * different Next than the one core was built against, and it rejects the\n * flags below outright. Falls back to the bare command when resolution fails,\n * which leaves the previous PATH-based behaviour in place.\n *\n * `nextBin` is relative to `.faststore`, which is where these scripts run.\n * An absolute path would carry the whole store directory into a shell string,\n * and a quote or a `$` anywhere above the project would break it — a relative\n * path only ever spans `node_modules` segments.\n */\n const next = nextBin ? `node ${nextBin}` : 'next'\n\n return {\n ...rest,\n name: 'dot-faststore',\n ...(voltaConfig ? { volta: voltaConfig } : {}),\n scripts: {\n ...existingScripts,\n generate: 'faststore generate',\n build: `${next} build --webpack`,\n serve: `${next} serve`,\n dev: `${next} dev --webpack`,\n 'dev-only': `${next} dev --webpack`,\n predev: 'na run partytown',\n prebuild: 'na run partytown',\n },\n }\n}\n\n/**\n * The Next executable `@faststore/core` resolves, expressed relative to the\n * `.faststore` directory its scripts run from. Returns undefined when it cannot\n * be resolved, or when no relative path exists — a different Windows drive —\n * so the caller falls back to the bare command.\n */\nexport function relativeNextBin(\n coreDir: string,\n tmpDir: string\n): string | undefined {\n const nextBin = resolvePackageBin('next/dist/bin/next', coreDir)\n\n if (!nextBin) {\n return undefined\n }\n\n const relative = path.relative(tmpDir, nextBin).replaceAll('\\\\', '/')\n\n return relative && !path.isAbsolute(relative) ? relative : undefined\n}\n\n/**\n * Reads the `volta` config from the store root `package.json`, if present.\n * Returns `undefined` when the file or the field is missing so the generated\n * manifest stays untouched for stores that do not use Volta.\n */\nfunction readRootVoltaConfig(\n rootDir: string\n): Record<string, unknown> | undefined {\n try {\n const rootManifestPath = path.join(rootDir, 'package.json')\n\n if (!existsSync(rootManifestPath)) {\n return undefined\n }\n\n const rootManifest = JSON.parse(readFileSync(rootManifestPath, 'utf8'))\n\n return rootManifest?.volta\n } catch {\n return undefined\n }\n}\n\n/**\n * Prevents imports from @faststore/core from randomly conflicting\n * where sometimes the package.json from the .faststore folder\n * took precedence over @faststore/core's package.json.\n */\nfunction filterAndCopyPackageJson(basePath: string) {\n const { coreDir, tmpDir, getRoot } = withBasePath(basePath)\n\n const coreManifest = JSON.parse(\n readFileSync(path.join(coreDir, 'package.json'), 'utf8')\n )\n\n const voltaConfig = readRootVoltaConfig(getRoot())\n\n const filteredFileContent = buildFaststorePackageJson(\n coreManifest,\n voltaConfig,\n relativeNextBin(coreDir, tmpDir)\n )\n\n writeJsonSync(path.join(tmpDir, 'package.json'), filteredFileContent, {\n spaces: 2,\n })\n}\n\n// Temporary array of strict rules enabled so far.\nconst TS_CONFIG_STRICT_RULES_ENABLED = ['noImplicitAny'] as const\n\n/**\n * Modify TypeScript compilation settings (tsconfig.json) to disable specific strict\n * type checking rules when files are moved to the .faststore folder.\n * TODO: The idea is to change the strict to false when all strict rules are migrated.\n */\nfunction disableTsConfigStrictRules(basePath: string) {\n const { coreDir, tmpDir } = withBasePath(basePath)\n\n const coreTsConfigPath = path.join(coreDir, 'tsconfig.json')\n\n const coreTsConfigFile = readFileSync(coreTsConfigPath, 'utf8')\n const tsConfig = JSON.parse(coreTsConfigFile)\n\n TS_CONFIG_STRICT_RULES_ENABLED.forEach((strictRule) => {\n tsConfig.compilerOptions[strictRule] = false\n })\n\n writeJsonSync(\n path.join(tmpDir, 'tsconfig.json'),\n prepareStorefrontTsConfig(tsConfig),\n {\n spaces: 2,\n }\n )\n}\n\nexport function copyCoreFiles(basePath: string) {\n const { coreDir, tmpDir } = withBasePath(basePath)\n\n try {\n copySync(coreDir, tmpDir, {\n dereference: true,\n filter(src) {\n return shouldCopyToStorefront(src)\n },\n })\n\n filterAndCopyPackageJson(basePath)\n disableTsConfigStrictRules(basePath)\n\n logger.log(`${chalk.green('success')} - Core files copied`)\n } catch (e) {\n logger.error(e)\n }\n}\n\n// File extensions allowed to be copied from the store's `public/` folder into\n// the build. Fonts are included so stores can self-host them (GDPR / CWV)\n// instead of relying on external CDNs.\nexport const PUBLIC_FILES_ALLOWED_EXTENSIONS = [\n '.json',\n '.txt',\n '.xml',\n '.ico',\n '.svg',\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n]\n\n/**\n * Decides whether an entry from the store's `public/` folder should be copied\n * to the build. Directories always pass so nested assets can be reached, and\n * files are matched by their real extension (not a substring of the path).\n */\nexport function isPublicFileAllowed(\n src: string,\n isDirectory: boolean\n): boolean {\n if (isDirectory) {\n return true\n }\n\n return PUBLIC_FILES_ALLOWED_EXTENSIONS.includes(\n path.extname(src).toLowerCase()\n )\n}\n\nexport function copyPublicFiles(basePath: string) {\n const { userDir, tmpDir } = withBasePath(basePath)\n\n try {\n if (existsSync(`${userDir}/public`)) {\n copySync(`${userDir}/public`, `${tmpDir}/public`, {\n dereference: true,\n overwrite: true,\n filter: (src) => {\n try {\n return isPublicFileAllowed(src, statSync(src).isDirectory())\n } catch {\n // Skip entries we can't stat (dangling symlinks, permission\n // errors) so a single bad file never aborts the whole public/ copy.\n return false\n }\n },\n })\n logger.log(`${chalk.green('success')} - Public files copied`)\n }\n } catch (e) {\n logger.error(e)\n }\n}\n\nasync function copyCypressFiles(basePath: string) {\n const { userDir, userStoreConfigFile, userLegacyStoreConfigFile, tmpDir } =\n withBasePath(basePath)\n\n try {\n // Cypress 9.x config file\n if (existsSync(`${userDir}/cypress.json`)) {\n copySync(`${userDir}/cypress.json`, `${tmpDir}/cypress.json`, {\n dereference: true,\n })\n }\n\n // Cypress 12.x config file\n if (existsSync(`${userDir}/cypress.config.ts`)) {\n copySync(`${userDir}/cypress.config.ts`, `${tmpDir}/cypress.config.ts`, {\n dereference: true,\n })\n }\n\n let userStoreConfig\n\n if (existsSync(userStoreConfigFile)) {\n userStoreConfig = (\n await import(pathToFileURL(path.resolve(userStoreConfigFile)).href)\n )?.default\n } else if (existsSync(userLegacyStoreConfigFile)) {\n userStoreConfig = (\n await import(\n pathToFileURL(path.resolve(userLegacyStoreConfigFile)).href\n )\n )?.default\n } else {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n }\n\n // Copy custom Cypress folder and files\n if (\n existsSync(`${userDir}/cypress`) &&\n userStoreConfig?.experimental?.enableCypressExtension\n ) {\n copySync(`${userDir}/cypress`, `${tmpDir}/cypress`, {\n overwrite: true,\n dereference: true,\n })\n\n logger.log(`${chalk.green('success')} - Cypress test files copied`)\n }\n\n // Create default Cypress 12.x (or superior) support file\n if (userStoreConfig?.experimental?.cypressVersion > 9) {\n copySync(\n `${tmpDir}/cypress/support/index.js`,\n `${tmpDir}/cypress/support/e2e.js`,\n { overwrite: false }\n )\n }\n } catch (e) {\n logger.error(e)\n }\n}\n\nfunction copyUserStarterToCustomizations(basePath: string) {\n const {\n userSrcDir,\n tmpCustomizationsSrcDir,\n userLegacyStoreConfigFile,\n userStoreConfigFile,\n tmpStoreConfigFile,\n } = withBasePath(basePath)\n\n try {\n if (existsSync(userSrcDir) && readdirSync(userSrcDir).length > 0) {\n copySync(userSrcDir, tmpCustomizationsSrcDir, { dereference: true })\n createNextJsPages(basePath)\n }\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n\n if (existsSync(userStoreConfigFile)) {\n copySync(userStoreConfigFile, tmpStoreConfigFile, { dereference: true })\n } else if (existsSync(userLegacyStoreConfigFile)) {\n copySync(userLegacyStoreConfigFile, tmpStoreConfigFile, {\n dereference: true,\n })\n } else {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n }\n\n logger.log(`${chalk.green('success')} - Starter files copied`)\n}\n\nasync function createCmsWebhookUrlsJsonFile(basePath: string) {\n const {\n userStoreConfigFile,\n userLegacyStoreConfigFile,\n tmpCMSWebhookUrlsFile,\n } = withBasePath(basePath)\n let userStoreConfig\n\n if (existsSync(userStoreConfigFile)) {\n userStoreConfig = (\n await import(pathToFileURL(path.resolve(userStoreConfigFile)).href)\n )?.default\n } else if (existsSync(userLegacyStoreConfigFile)) {\n userStoreConfig = (\n await import(pathToFileURL(path.resolve(userLegacyStoreConfigFile)).href)\n )?.default\n } else {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n }\n\n if (\n userStoreConfig?.vtexHeadlessCms &&\n userStoreConfig.vtexHeadlessCms?.webhookUrls\n ) {\n const { webhookUrls } = userStoreConfig?.vtexHeadlessCms\n\n try {\n writeJsonSync(tmpCMSWebhookUrlsFile, { urls: webhookUrls }, { spaces: 2 })\n logger.log(`${chalk.green('success')} - CMS webhook URLs file created`)\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n } else {\n logger.info(`${chalk.blue('info')} - No CMS webhook URLs were provided`)\n }\n}\n\nasync function copyTheme(basePath: string) {\n const {\n userStoreConfigFile,\n userThemesFileDir,\n tmpThemesCustomizationsFile,\n userLegacyStoreConfigFile,\n } = withBasePath(basePath)\n\n const storeConfigFile =\n (existsSync(userStoreConfigFile) && userStoreConfigFile) ||\n (existsSync(userLegacyStoreConfigFile) && userLegacyStoreConfigFile)\n\n const userStoreConfigFilePath =\n storeConfigFile && path.resolve(storeConfigFile)\n const importedStoreConfig =\n userStoreConfigFilePath &&\n (await import(pathToFileURL(userStoreConfigFilePath).href))\n const storeConfig =\n userStoreConfigFilePath &&\n (importedStoreConfig?.default || importedStoreConfig)\n\n if (!storeConfig)\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n\n if (storeConfig.theme) {\n const customTheme = path.join(\n userThemesFileDir,\n `${storeConfig.theme}.scss`\n )\n if (existsSync(customTheme)) {\n try {\n copyFileSync(customTheme, tmpThemesCustomizationsFile)\n logger.log(\n `${chalk.green('success')} - ${\n storeConfig.theme\n } theme has been applied`\n )\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n } else {\n logger.info(\n `${chalk.blue('info')} - The ${\n storeConfig.theme\n } theme was added to the config file but the ${\n storeConfig.theme\n }.scss file does not exist in the themes folder. Read more: https://developers.vtex.com/docs/guides/faststore/themes-overview`\n )\n }\n } else if (\n existsSync(userThemesFileDir) &&\n readdirSync(userThemesFileDir).length > 0\n ) {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - The theme needs to be added to the config file to be applied. Read more: https://www.faststore.dev/docs/themes/overview`\n )\n }\n}\n\nfunction updateBuildTime(basePath: string) {\n try {\n const { tmpSeoConfig } = withBasePath(basePath)\n let config = readFileSync(tmpSeoConfig, 'utf8')\n const newBuildTime = new Date().toISOString()\n\n config = config.replace(\n /const buildTime = .*?;/,\n `const buildTime = '${newBuildTime}';`\n )\n\n writeFileSync(tmpSeoConfig, config)\n\n logger.log(`${chalk.green('success')} - Build time updated`, newBuildTime)\n } catch (error) {\n logger.error(`${chalk.red('error')} - Updating build time:`, error)\n }\n}\n\nasync function checkDependencies(basePath: string, packagesToCheck: string[]) {\n const { coreDir, getRoot } = withBasePath(basePath)\n\n const corePackageJsonPath = path.join(coreDir, 'package.json')\n const rootPackageJsonPath = path.join(getRoot(), 'package.json')\n\n const { default: corePackageJson } = await import(\n pathToFileURL(corePackageJsonPath).href,\n {\n with: { type: 'json' },\n }\n )\n const { default: rootPackageJson } = await import(\n pathToFileURL(rootPackageJsonPath).href,\n {\n with: { type: 'json' },\n }\n )\n\n packagesToCheck.forEach((packageName) => {\n const coreVersion =\n corePackageJson.devDependencies[packageName] ||\n corePackageJson.dependencies[packageName]\n const rootVersion =\n rootPackageJson.devDependencies[packageName] ||\n rootPackageJson.dependencies[packageName]\n\n if (!coreVersion || !rootVersion) {\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Package ${packageName} not found in both core or root dependencies.`\n )\n } else if (coreVersion !== rootVersion) {\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Version mismatch detected for ${packageName}.\n Core: ${coreVersion}, Customization: ${rootVersion}. Please align both versions to prevent issues`\n )\n }\n })\n}\n\nfunction updateNextConfig(basePath: string) {\n const { tmpDir } = withBasePath(basePath)\n\n const nextConfigPath = path.join(tmpDir, 'next.config.js')\n\n let nextConfigData = String(readFileSync(nextConfigPath))\n nextConfigData = nextConfigData.replace(\n /outputFileTracingRoot\\:\\s+(.*),/,\n `outputFileTracingRoot: '${process.cwd()}',`\n )\n\n writeFileSync(nextConfigPath, nextConfigData)\n}\n\n// returns new (discovery.config.js) or legacy (faststore.config.js) store config file\nfunction getCurrentUserStoreConfigFile(basePath: string) {\n const { userStoreConfigFile, userLegacyStoreConfigFile } =\n withBasePath(basePath)\n\n if (existsSync(userStoreConfigFile)) {\n return userStoreConfigFile\n }\n\n if (existsSync(userLegacyStoreConfigFile)) {\n return userLegacyStoreConfigFile\n }\n\n return null\n}\n\nasync function validateAndInstallMissingDependencies(basePath: string) {\n const { userDir } = withBasePath(basePath)\n\n const currentUserStoreConfigFile = getCurrentUserStoreConfigFile(basePath)\n\n if (!currentUserStoreConfigFile) {\n return\n }\n\n const { default: userStoreConfig } = await import(\n pathToFileURL(currentUserStoreConfigFile).href\n )\n const { default: userPackageJson } = await import(\n pathToFileURL(path.join(userDir, 'package.json')).href,\n {\n with: { type: 'json' },\n }\n )\n\n const missingDependencies: Array<{\n feature: string\n dependencies: string[]\n }> = []\n\n if (userStoreConfig?.experimental?.preact) {\n missingDependencies.push({\n feature: 'Preact',\n dependencies: ['preact@10.23.1', 'preact-render-to-string@6.5.8'],\n })\n }\n\n missingDependencies.forEach(async ({ feature, dependencies }) => {\n const dependenciesToInstall = dependencies.filter((dependency) => {\n const dependencyName = dependency.split('@')[0]\n return !userPackageJson.dependencies[dependencyName]\n })\n\n if (dependenciesToInstall.length > 0) {\n const spinner = ora(\n `Installing ${feature} missing dependencies\\n`\n ).start()\n\n await installDependencies({\n dependencies: dependenciesToInstall,\n cwd: userDir,\n errorMessage: `failed to install ${feature} dependencies`,\n })\n\n spinner.stop()\n }\n })\n}\n\nasync function enableSearchSSR(basePath: string) {\n const storeConfigPath = getCurrentUserStoreConfigFile(basePath)\n\n if (!storeConfigPath) {\n return\n }\n const { default: storeConfig } = await import(\n pathToFileURL(storeConfigPath).href\n )\n if (!storeConfig.experimental.enableSearchSSR) {\n return\n }\n\n const { tmpDir } = withBasePath(basePath)\n const searchPagePath = path.join(tmpDir, 'src', 'pages', 's.tsx')\n const searchPageData = String(readFileSync(searchPagePath))\n\n const searchPageWithSSR = searchPageData.replaceAll(\n 'getStaticProps',\n 'getServerSideProps'\n )\n\n writeFileSync(searchPagePath, searchPageWithSSR)\n}\n\nexport async function generate(options: GenerateOptions) {\n const { basePath, setup = false } = options\n\n let setupPromise: Promise<unknown> | null = null\n\n await validateAndInstallMissingDependencies(basePath)\n\n if (setup) {\n setupPromise = Promise.all([\n createTmpFolder(basePath),\n copyCoreFiles(basePath),\n copyCypressFiles(basePath),\n copyPublicFiles(basePath),\n updateNextConfig(basePath),\n ])\n }\n\n await Promise.all([\n setupPromise,\n checkDependencies(basePath, ['typescript']),\n enableSearchSSR(basePath),\n updateBuildTime(basePath),\n copyUserStarterToCustomizations(basePath),\n copyTheme(basePath),\n createCmsWebhookUrlsJsonFile(basePath),\n installPlugins(basePath),\n ])\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport chalk from 'chalk'\n\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport {\n type MyAccountCmsRoute,\n readMyAccountCmsRoutes,\n} from './readMyAccountCmsRoutes'\nimport { myAccountCmsPageTemplate } from './templates/myAccountCmsPage'\nimport { myAccountPageTemplate } from './templates/myAccountPage'\n\nconst ALLOWED_PREFIX_PAGES = ['/pvt/account']\nconst ACCOUNT_ROUTE_PREFIX = '/pvt/account'\n\ntype CreateExternalPagesArgs = {\n customizationPagesDir: string\n corePagesDir: string\n baseCustomizationPagesDir: string\n /** Routes that already have a CMS generated page (keyed by normalized route). */\n cmsHandledRoutes: Set<string>\n}\n\nconst createExternalPages = ({\n customizationPagesDir,\n corePagesDir,\n baseCustomizationPagesDir,\n cmsHandledRoutes,\n}: CreateExternalPagesArgs) => {\n fs.readdirSync(customizationPagesDir).forEach((file) => {\n const filePath = path.join(customizationPagesDir, file)\n const destinationPath = path.join(corePagesDir, file)\n if (fs.statSync(filePath).isDirectory()) {\n if (!fs.existsSync(destinationPath)) {\n fs.mkdirSync(destinationPath, { recursive: true })\n }\n return createExternalPages({\n customizationPagesDir: filePath,\n corePagesDir: destinationPath,\n baseCustomizationPagesDir,\n cmsHandledRoutes,\n })\n }\n\n const isReactFile = filePath.endsWith('.tsx')\n\n /* Checks if the destination path does not exist as a file or as a folder containing an \"index.tsx\" file.\n * This ensures that the path is available before proceeding with file creation or other operations.\n */\n const isDestinationAvailable =\n !fs.existsSync(destinationPath) &&\n !fs.existsSync(\n path.join(destinationPath.replace('.tsx', ''), 'index.tsx')\n )\n\n if (isReactFile && isDestinationAvailable) {\n const relativePagePath = filePath\n .replace(baseCustomizationPagesDir, '')\n .replaceAll(/\\\\/g, '/')\n .replace(/\\.tsx$/, '')\n const normalizedRoute = normalizeAccountRoute(relativePagePath)\n\n // Already generated as a CMS/hybrid page — skip legacy wrap.\n if (cmsHandledRoutes.has(normalizedRoute)) {\n return\n }\n\n const externalPagePath = `src/customizations/src/pages${relativePagePath}`\n const content = myAccountPageTemplate(externalPagePath)\n fs.writeFileSync(destinationPath, content)\n }\n })\n}\n\nfunction isAllowedPrefixPage(file: string) {\n // Match on route-segment boundaries so `/pvt/accounting` is not treated as\n // a `/pvt/account` descendant.\n return ALLOWED_PREFIX_PAGES.some(\n (prefix) => file === prefix || file.startsWith(`${prefix}/`)\n )\n}\n\nfunction normalizeAccountRoute(routeOrRelativePath: string): string {\n const withSlash = routeOrRelativePath.startsWith('/')\n ? routeOrRelativePath\n : `/${routeOrRelativePath}`\n const withPvt = withSlash.startsWith('/pvt') ? withSlash : `/pvt${withSlash}`\n return withPvt.replace(/\\/index$/, '') || withPvt\n}\n\nfunction routeToPageFilePath(corePagesDir: string, route: string): string {\n const relative = route.replace(/^\\//, '') // pvt/account/wishlist\n return path.join(corePagesDir, `${relative}.tsx`)\n}\n\nfunction routeToCustomizationPagePath(\n customizationPagesDir: string,\n route: string\n): string | null {\n // /pvt/account/wishlist → pvt/account/wishlist.tsx under customization pages\n const relative = route.replace(/^\\//, '')\n if (!relative) return null\n\n const asFile = path.join(customizationPagesDir, `${relative}.tsx`)\n if (fs.existsSync(asFile)) return asFile\n\n const asIndex = path.join(customizationPagesDir, relative, 'index.tsx')\n if (fs.existsSync(asIndex)) return asIndex\n\n return null\n}\n\nfunction routeToExtensionImportBase(route: string): string {\n // /pvt/account/wishlist → wishlist ; /pvt/account/orders/foo → orders/foo\n return route.replace(ACCOUNT_ROUTE_PREFIX, '').replace(/^\\//, '')\n}\n\nfunction resolveExtensionPaths(\n tmpDir: string,\n route: string\n): { beforePath?: string; afterPath?: string } {\n const relative = routeToExtensionImportBase(route)\n if (!relative) return {}\n\n const extensionsDir = path.join(\n tmpDir,\n 'src/customizations/src/myAccount/extensions',\n relative\n )\n\n const beforeFile = path.join(extensionsDir, 'before.tsx')\n const afterFile = path.join(extensionsDir, 'after.tsx')\n\n const importBase = `src/customizations/src/myAccount/extensions/${relative}`\n\n return {\n ...(fs.existsSync(beforeFile)\n ? { beforePath: `${importBase}/before` }\n : {}),\n ...(fs.existsSync(afterFile) ? { afterPath: `${importBase}/after` } : {}),\n }\n}\n\nfunction destinationExists(destinationPath: string): boolean {\n if (fs.existsSync(destinationPath)) return true\n\n const asIndex = path.join(destinationPath.replace(/\\.tsx$/, ''), 'index.tsx')\n return fs.existsSync(asIndex)\n}\n\nfunction generateCmsPages({\n routes,\n corePagesDir,\n customizationPagesDir,\n tmpDir,\n}: {\n routes: MyAccountCmsRoute[]\n corePagesDir: string\n customizationPagesDir: string\n tmpDir: string\n}): Set<string> {\n const handled = new Set<string>()\n\n for (const { route, contentType } of routes) {\n const normalizedRoute = normalizeAccountRoute(route)\n\n if (!isAllowedPrefixPage(normalizedRoute)) {\n logger.warn(\n `${chalk.yellow('warning')} - Skipping CMS route ${normalizedRoute}: only ${ALLOWED_PREFIX_PAGES.join(', ')} prefixes are allowed`\n )\n continue\n }\n\n const destinationPath = routeToPageFilePath(corePagesDir, normalizedRoute)\n\n if (destinationExists(destinationPath)) {\n logger.warn(\n `${chalk.yellow('warning')} - Skipping CMS route ${normalizedRoute}: native page takes precedence`\n )\n continue\n }\n\n const customizationTsx = fs.existsSync(customizationPagesDir)\n ? routeToCustomizationPagePath(customizationPagesDir, normalizedRoute)\n : null\n\n const pagePath = customizationTsx\n ? `src/customizations/src/pages${customizationTsx\n .replace(customizationPagesDir, '')\n .replaceAll(/\\\\/g, '/')\n .replace(/\\.tsx$/, '')}`\n : undefined\n\n const { beforePath, afterPath } = resolveExtensionPaths(\n tmpDir,\n normalizedRoute\n )\n\n const content = myAccountCmsPageTemplate({\n contentType,\n routePath: normalizedRoute,\n pagePath,\n beforePath,\n afterPath,\n })\n\n fs.mkdirSync(path.dirname(destinationPath), { recursive: true })\n fs.writeFileSync(destinationPath, content)\n handled.add(normalizedRoute)\n\n logger.log(\n `${chalk.green('success')} - Generated CMS My Account page for ${normalizedRoute} (${contentType}${pagePath ? ', hybrid' : ''})`\n )\n }\n\n return handled\n}\n\nexport function createNextJsPages(basePath: string) {\n const { tmpDir } = withBasePath(basePath)\n\n const corePagesDir = path.join(tmpDir, 'src/pages')\n const customizationPagesDir = path.join(\n tmpDir,\n 'src/customizations/src/pages'\n )\n const navigationFilePath = path.join(\n tmpDir,\n 'src/customizations/src/myAccount/navigation.ts'\n )\n\n const cmsRoutes = readMyAccountCmsRoutes(navigationFilePath)\n const cmsHandledRoutes = generateCmsPages({\n routes: cmsRoutes,\n corePagesDir,\n customizationPagesDir,\n tmpDir,\n })\n\n if (!fs.existsSync(customizationPagesDir)) {\n // No customization pages — Mode A CMS pages (if any) were still generated above.\n return\n }\n\n const allPagesAreAllowed = ({\n basePath: pagesBase,\n dirPath,\n }: { basePath: string; dirPath: string }): boolean => {\n const items = fs.readdirSync(dirPath, { withFileTypes: true })\n\n // Empty pages dir is fine (Mode A only).\n if (items.length === 0) return true\n\n return items.every((item) => {\n const itemPath = path.join(dirPath, item.name)\n\n if (item.isDirectory()) {\n return allPagesAreAllowed({ basePath: pagesBase, dirPath: itemPath })\n }\n\n if (!item.isFile()) {\n return false // Reject anything that is not a file (symlinks, sockets, etc.)\n }\n\n const isNextPage = /\\.(js|jsx|ts|tsx)$/.test(item.name)\n if (!isNextPage) {\n return false // Reject files that are not Next.js pages\n }\n\n // For Next.js page files, check if they match allowed prefixes\n const relativePath = path.relative(pagesBase, itemPath)\n const normalizedPath =\n '/' + relativePath.replace(/\\\\/g, '/').replace(/\\.(js|jsx|ts|tsx)$/, '')\n\n return isAllowedPrefixPage(normalizedPath)\n })\n }\n\n const pagesAreAllowed = allPagesAreAllowed({\n basePath: customizationPagesDir,\n dirPath: customizationPagesDir,\n })\n\n if (!pagesAreAllowed) {\n throw new Error(\n `Only these prefix pages: (${ALLOWED_PREFIX_PAGES.join(', ')}) are allowed`\n )\n }\n\n createExternalPages({\n customizationPagesDir,\n corePagesDir,\n baseCustomizationPagesDir: customizationPagesDir,\n cmsHandledRoutes,\n })\n}\n","import fs from 'node:fs'\n\nimport { logger } from './logger'\n\nexport type MyAccountCmsRoute = {\n route: string\n title: string\n contentType: string\n}\n\n/**\n * Extracts a property value from a static object-literal fragment when the\n * value is a plain string literal (single or double quotes).\n */\nfunction readStringProp(\n objectLiteral: string,\n propName: string\n): string | undefined {\n const pattern = new RegExp(\n `${propName}\\\\s*:\\\\s*(['\"\\`])((?:\\\\\\\\.|(?!\\\\1).)*)\\\\1`,\n 'm'\n )\n const match = pattern.exec(objectLiteral)\n return match?.[2]\n}\n\n/**\n * Locates the `routes: [ ... ]` array passed to `getMyAccountRoutes({...})`\n * and returns each top-level object-literal that declares a `contentType`.\n *\n * Supports the documented static-literal authoring pattern only. Dynamic /\n * computed route entries are skipped with a warning (they still work as\n * legacy code-only pages when a `.tsx` exists).\n */\nexport function readMyAccountCmsRoutes(\n navigationFilePath: string\n): MyAccountCmsRoute[] {\n if (!fs.existsSync(navigationFilePath)) {\n return []\n }\n\n let sourceText: string\n try {\n sourceText = fs.readFileSync(navigationFilePath, 'utf8')\n } catch {\n logger.warn(\n `[my-account-cms] Could not read navigation file at ${navigationFilePath}`\n )\n return []\n }\n\n // Strip line comments to avoid false matches inside comments.\n const withoutLineComments = sourceText.replaceAll(/^\\s*\\/\\/.*$/gm, '')\n\n const routesMatch =\n /getMyAccountRoutes\\s*\\(\\s*\\{[\\s\\S]*?routes\\s*:\\s*\\[([\\s\\S]*?)\\]/.exec(\n withoutLineComments\n )\n\n if (!routesMatch) {\n logger.warn(\n `[my-account-cms] Could not statically parse routes in ${navigationFilePath}; skipping CMS page generation`\n )\n return []\n }\n\n const routesBody = routesMatch[1]\n const objectLiterals = routesBody.match(/\\{[^{}]*\\}/g) ?? []\n\n const routes: MyAccountCmsRoute[] = []\n\n for (const literal of objectLiterals) {\n const contentType = readStringProp(literal, 'contentType')\n if (!contentType) {\n continue\n }\n\n const route = readStringProp(literal, 'route')\n const title = readStringProp(literal, 'title')\n\n if (!route || !title) {\n logger.warn(\n `[my-account-cms] Skipping CMS route entry missing route/title in ${navigationFilePath}`\n )\n continue\n }\n\n routes.push({ route, title, contentType })\n }\n\n return routes\n}\n","type MyAccountCmsPageTemplateArgs = {\n contentType: string\n routePath: string\n pagePath?: string\n beforePath?: string\n afterPath?: string\n}\n\n/**\n * Template for CMS-driven custom My Account pages\n */\nexport const myAccountCmsPageTemplate = ({\n contentType,\n routePath,\n pagePath,\n beforePath,\n afterPath,\n}: MyAccountCmsPageTemplateArgs) => `\n import RenderSections, { RenderSectionsBase } from 'src/components/cms/RenderSections'\n import ACCOUNT_COMPONENTS from 'src/components/cms/account/Components'\n import { Layout } from 'src/components/account'\n import {\n myAccountCmsServerSideProps,\n type MyAccountCmsPageProps,\n } from 'src/experimental/myAccountCmsServerSideProps'\n import PageProvider from 'src/sdk/overrides/PageProvider'\n ${pagePath ? `import DynamicPage from '${pagePath}'` : ''}\n ${beforePath ? `import { default as BeforeSection } from '${beforePath}'` : ''}\n ${afterPath ? `import { default as AfterSection } from '${afterPath}'` : ''}\n\n export const getServerSideProps = myAccountCmsServerSideProps('${contentType}', '${routePath}')\n\n export default function Page({\n globalSections: globalSectionsProp,\n pageSections,\n navigationLabels,\n accountName,\n isRepresentative,\n }: MyAccountCmsPageProps) {\n const { sections: globalSections, settings: globalSettings } =\n globalSectionsProp ?? {}\n\n return (\n <PageProvider context={{ globalSettings, navigationLabels }}>\n <RenderSections\n globalSections={globalSections}\n components={ACCOUNT_COMPONENTS}\n >\n <Layout\n accountName={accountName}\n isRepresentative={isRepresentative}\n navigationLabels={navigationLabels}\n >\n ${beforePath ? '<BeforeSection />' : ''}\n <RenderSectionsBase\n sections={pageSections}\n components={ACCOUNT_COMPONENTS}\n />\n ${pagePath ? '<DynamicPage />' : ''}\n ${afterPath ? '<AfterSection />' : ''}\n </Layout>\n </RenderSections>\n </PageProvider>\n )\n }\n`\n","/*\n TODO: Code in a template string is not a good practice because it becomes very difficult to maintain.\n There will be a component called Layout that will wrap the entire My Account layout, including the global sections, menu, etc.\n This will reduce the amount of code inside the template string.\n*/\n\nexport const myAccountPageTemplate = (pagePath: string) => `\n import type { ComponentType } from 'react'\n import RenderSections from 'src/components/cms/RenderSections'\n import { default as GLOBAL_COMPONENTS } from 'src/components/cms/global/Components'\n import CUSTOM_COMPONENTS from 'src/customizations/src/components'\n import { Layout } from 'src/components/account'\n import {\n getServerSideProps,\n type MyAccountProps,\n } from 'src/experimental/myAccountServerSideProps'\n import DynamicPage from '${pagePath}';\n import PageProvider from 'src/sdk/overrides/PageProvider'\n /* A list of components that can be used in the CMS. */\n const COMPONENTS: Record<string, ComponentType<any>> = {\n ...GLOBAL_COMPONENTS,\n ...CUSTOM_COMPONENTS,\n }\n\n function Page({ globalSections: globalSectionsProp, accountName, isRepresentative }: MyAccountProps) {\n const { sections: globalSections, settings: globalSettings } = globalSectionsProp ?? {}\n\n return (\n <PageProvider context={{ globalSettings }}>\n <RenderSections\n globalSections={globalSections}\n components={COMPONENTS}\n >\n <Layout accountName={accountName} isRepresentative={isRepresentative}>\n <DynamicPage />\n </Layout>\n </RenderSections>\n </PageProvider>\n )\n }\n\n export { getServerSideProps }\n\n export default Page\n`\n","import chalk from 'chalk'\nimport {\n NoAvailablePackageManagerError,\n UnknownAgentError,\n resolvePackageManager,\n} from './commands'\nimport { logger } from './logger'\nimport { runCommandSync } from './runCommandSync'\n\ntype InstallDependenciesOptions = {\n dependencies: string[]\n cwd: string\n errorMessage: string\n}\n\nexport async function installDependencies({\n dependencies,\n cwd,\n errorMessage,\n}: InstallDependenciesOptions) {\n // Installing writes a lockfile: a substitute agent would leave a second,\n // conflicting one next to the project's (e.g. `yarn add` in a pnpm store\n // creates a `yarn.lock`), so only the detected agent is acceptable here.\n //\n // Resolve errors exit the process rather than reject: generate.ts still\n // walks missing features with forEach(async …), so a thrown error would\n // become an unhandled rejection and skip oclif handling. runCommandSync\n // already exits the process the same way on install failure.\n const { agent, command } = await resolvePackageManager(cwd, {\n substitute: false,\n }).catch((error: unknown) => {\n if (\n error instanceof NoAvailablePackageManagerError ||\n error instanceof UnknownAgentError\n ) {\n logger.error(`${chalk.red('error')} - ${error.message}`)\n process.exit(1)\n }\n\n throw error\n })\n const installCommand = agent === 'npm' ? 'install' : 'add'\n\n runCommandSync({\n // command is a validated package-manager invocation from resolvePackageManager\n cmd: `${command} ${installCommand} ${dependencies.join(' ')}`, // NOSONAR\n errorMessage,\n throws: 'error',\n cwd,\n })\n}\n","import fsExtra from 'fs-extra'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport { shouldCopyToStorefront } from './storefrontCopy'\n\nconst { copySync, existsSync, mkdirSync, readdirSync, writeFileSync } = fsExtra\n\nexport type PageConfig = {\n path: string\n appLayout: boolean\n name: string\n}\n\nexport type APIConfig = {\n path: string\n}\n\nexport type PluginConfig = {\n pages?: { [pageName: string]: Partial<PageConfig> }\n apis?: { [pageName: string]: Partial<APIConfig> }\n}\n\nexport type Plugin =\n | string\n | {\n [pluginName: string]: PluginConfig\n }\n\nconst PLUGIN_CONFIG_FILE = 'plugin.config.js'\n\nconst sanitizePluginName = (pluginName: string, pascalCase = false) => {\n const sanitized = pluginName.split('/')[1]\n\n if (pascalCase) {\n return sanitized\n .toLowerCase()\n .split('-')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('')\n }\n\n return sanitized\n}\n\nexport const getPluginName = (plugin: Plugin) => {\n if (typeof plugin === 'string') {\n return plugin\n }\n\n return Object.keys(plugin)[0]\n}\n\nconst getPluginCustomConfig = (plugin: Plugin) => {\n if (typeof plugin === 'string') {\n return {}\n }\n\n return plugin[getPluginName(plugin)]\n}\n\nconst getPluginSrcPath = async (basePath: string, pluginName: string) => {\n const { getPackagePath } = withBasePath(basePath)\n return getPackagePath(pluginName, 'src')\n}\n\nexport const getPluginsList = async (basePath: string): Promise<Plugin[]> => {\n const { tmpStoreConfigFile } = withBasePath(basePath)\n\n try {\n const {\n default: { plugins = [] },\n } = await import(pathToFileURL(tmpStoreConfigFile).href)\n return plugins\n } catch (error) {\n logger.error(`Could not load plugins from store config`)\n }\n\n return []\n}\n\nexport const copyPluginsSrc = async (basePath: string, plugins: Plugin[]) => {\n const { tmpPluginsDir } = withBasePath(basePath)\n\n logger.log('Copying plugins files')\n\n for (const plugin of plugins) {\n const pluginName = getPluginName(plugin)\n const pluginSrcPath = await getPluginSrcPath(\n basePath,\n getPluginName(pluginName)\n )\n const pluginDestPath = path.join(\n tmpPluginsDir,\n sanitizePluginName(pluginName)\n )\n\n copySync(pluginSrcPath, pluginDestPath, {\n filter: shouldCopyToStorefront,\n })\n logger.log(`Copied ${pluginName} files`)\n }\n}\n\nconst copyPluginPublicFiles = async (basePath: string, plugins: Plugin[]) => {\n const { tmpDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Copying plugin public files')\n\n plugins.forEach(async (plugin) => {\n const pluginName = getPluginName(plugin)\n const pluginPath = getPackagePath(getPluginName(pluginName))\n\n try {\n if (existsSync(`${pluginPath}/public`)) {\n copySync(`${pluginPath}/public`, `${tmpDir}/public`, {\n dereference: true,\n overwrite: true,\n })\n logger.log(`Plugin public files copied`)\n }\n } catch (e) {\n logger.error(e)\n }\n })\n}\n\nconst getPluginPageFileContent = (\n pluginName: string,\n pageName: string,\n appLayout: boolean\n) => `\n// GENERATED FILE\n// @ts-nocheck\nimport * as page from 'src/plugins/${pluginName}/pages/${pageName}'\n${appLayout ? `import { getGlobalSectionsData } from 'src/components/cms/GlobalSections'` : ``}\n${appLayout ? `import RenderSections from 'src/components/cms/RenderSections'` : ``}\nimport { withLocaleValidationSSR } from 'src/utils/localization/withLocaleValidation'\n\nasync function getServerSidePropsBase(${appLayout ? '{ previewData, ...otherProps }' : 'otherProps'}) {\n const noop = async function() {}\n const loaderData = await (page.loader || noop)(otherProps)\n${appLayout ? `const { sections = [] } = await getGlobalSectionsData(previewData)` : ``}\n\n return {\n props: {\n data: loaderData,\n ${appLayout ? 'globalSections: sections' : ``}\n }\n }\n}\n\nexport const getServerSideProps = withLocaleValidationSSR(getServerSidePropsBase)\nexport default function Page(props) {\n ${\n appLayout\n ? `return <RenderSections globalSections={props.globalSections}>\n {page.default(props.data)}\n </RenderSections>`\n : `return page.default(props.data)`\n }\n}\n `\n\nconst generatePluginPages = async (basePath: string, plugins: Plugin[]) => {\n const { tmpPagesDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Generating plugin pages')\n\n plugins.forEach(async (plugin) => {\n const pluginName = getPluginName(plugin)\n const pluginConfigPath = getPackagePath(pluginName, PLUGIN_CONFIG_FILE)\n\n const { default: pluginConfig } = await import(\n pathToFileURL(pluginConfigPath).href\n )\n\n const { pages: pagesCustom } = getPluginCustomConfig(plugin)\n\n const pagesConfig: Record<string, PageConfig> = {\n ...(pluginConfig.pages ?? {}),\n ...pagesCustom,\n }\n\n const pages = Object.keys(pagesConfig)\n\n pages.forEach(async (pageName) => {\n const paths = pagesConfig[pageName].path.split('/')\n\n const pageFile = paths.pop()\n const pagePaths = paths\n\n const pagePath = path.join(tmpPagesDir, ...pagePaths, pageFile + '.tsx')\n\n const fileContent = getPluginPageFileContent(\n sanitizePluginName(pluginName),\n pageName,\n pagesConfig[pageName].appLayout\n )\n\n mkdirSync(path.dirname(pagePath), { recursive: true })\n writeFileSync(pagePath, fileContent)\n })\n })\n}\n\nexport async function addPluginsSections(basePath: string, plugins: Plugin[]) {\n const { tmpPluginsDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Adding plugin sections')\n\n const indexPluginsOverrides = plugins\n .filter((plugin) =>\n existsSync(\n getPackagePath(getPluginName(plugin), 'src', 'components', 'index.ts')\n )\n )\n .map((plugin) => {\n const pluginReference =\n sanitizePluginName(getPluginName(plugin), true) + 'Components'\n\n return {\n import: `import { default as ${pluginReference} } from 'src/plugins/${sanitizePluginName(getPluginName(plugin))}/components'`,\n pluginReference,\n }\n })\n\n const pluginsImportFileContent = `\n ${indexPluginsOverrides.map((plugin) => plugin.import).join('\\n')}\n\n export default {\n ${indexPluginsOverrides.map((plugin) => `...${plugin.pluginReference}`).join(',\\n')}\n }\n `\n\n const sectionPath = path.join(tmpPluginsDir, 'index.ts')\n writeFileSync(sectionPath, pluginsImportFileContent)\n logger.log('Writing plugins overrides')\n logger.log(sectionPath)\n logger.log(pluginsImportFileContent)\n}\n\nexport async function addPluginsOverrides(basePath: string, plugins: Plugin[]) {\n const { tmpPluginsDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Adding plugin overrides')\n\n plugins\n .map((plugin) => ({\n pluginName: getPluginName(plugin),\n pluginOverridesPath: getPackagePath(\n getPluginName(plugin),\n 'src',\n 'components',\n 'overrides'\n ),\n }))\n .filter(({ pluginOverridesPath }) => existsSync(pluginOverridesPath))\n .reverse()\n .forEach(({ pluginName, pluginOverridesPath }) => {\n const overrideFilesAlreadyCopied: string[] = []\n\n const sanitizedPluginName = sanitizePluginName(pluginName)\n\n const overrideFiles = readdirSync(pluginOverridesPath)\n\n overrideFiles\n .filter((file) => !overrideFilesAlreadyCopied.includes(file))\n .forEach((overrideFileName) => {\n const overrideFileContent = `export { override } from 'src/plugins/${sanitizedPluginName}/components/overrides/${overrideFileName.split('.')[0]}'`\n\n writeFileSync(\n path.join(tmpPluginsDir, 'overrides', overrideFileName),\n overrideFileContent\n )\n overrideFilesAlreadyCopied.push(overrideFileName)\n })\n })\n}\n\nconst addPluginsTheme = async (basePath: string, plugins: Plugin[]) => {\n const { getPackagePath, tmpThemesPluginsFile } = withBasePath(basePath)\n\n const pluginImportsContent = plugins\n .filter((plugin) =>\n existsSync(\n getPackagePath(getPluginName(plugin), 'src', 'themes', 'index.scss')\n )\n )\n .map(\n (plugin) => `@use \"${getPluginName(plugin)}/src/themes/index.scss\" as *;`\n )\n .join('\\n')\n\n writeFileSync(tmpThemesPluginsFile, pluginImportsContent)\n}\n\nconst getPluginAPIFileContent = (pluginName: string, apiName: string) => `\n// GENERATED FILE\n// @ts-nocheck\nimport apiHandle from 'src/plugins/${pluginName}/apis/${apiName}'\nimport { NextApiRequest, NextApiResponse } from \"next/types\"\n\nexport default function handle(req: NextApiRequest, res: NextApiResponse) {\n return apiHandle(req, res)\n}\n`\n\nconst generatePluginApis = async (basePath: string, plugins: Plugin[]) => {\n const { tmpApiDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Generating plugin APIs')\n\n plugins.forEach(async (plugin) => {\n const pluginName = getPluginName(plugin)\n const pluginConfigPath = getPackagePath(pluginName, PLUGIN_CONFIG_FILE)\n\n const { default: pluginConfig } = await import(\n pathToFileURL(pluginConfigPath).href\n )\n\n const { apis: apisCustom } = getPluginCustomConfig(plugin)\n\n const apisConfig: Record<string, APIConfig> = {\n ...(pluginConfig.apis ?? {}),\n ...apisCustom,\n }\n\n const apis = Object.keys(apisConfig)\n\n apis.forEach(async (apiName) => {\n const paths = apisConfig[apiName].path.split('/')\n\n const apiFile = paths.pop()\n const apiPaths = paths\n\n const apiPath = path.join(\n tmpApiDir,\n 'plugins',\n ...apiPaths,\n apiFile + '.ts'\n )\n\n const fileContent = getPluginAPIFileContent(\n sanitizePluginName(pluginName),\n apiName\n )\n\n mkdirSync(path.dirname(apiPath), { recursive: true })\n writeFileSync(apiPath, fileContent)\n })\n })\n}\n\nexport const installPlugins = async (basePath: string) => {\n const plugins = await getPluginsList(basePath)\n\n await copyPluginsSrc(basePath, plugins)\n copyPluginPublicFiles(basePath, plugins)\n generatePluginPages(basePath, plugins)\n generatePluginApis(basePath, plugins)\n addPluginsSections(basePath, plugins)\n addPluginsOverrides(basePath, plugins)\n addPluginsTheme(basePath, plugins)\n}\n","import path from 'node:path'\n\nconst IGNORED_STOREFRONT_BASENAMES = new Set([\n 'package.json',\n 'node_modules',\n 'cypress.config.ts',\n 'base.jsonc', // CP special file, it must not be copied to the merchants' temp dir\n 'test',\n '__tests__',\n])\n\nconst TEST_FILE_RE = /\\.(?:test|spec|browser\\.test)\\.(?:js|jsx|ts|tsx)$/\n\n/**\n * Storefront `.faststore` is a Next.js app, not a test runner. Skip unit-test\n * trees and files so `next build` does not type-check vitest fixtures the\n * store does not install.\n */\nexport function shouldCopyToStorefront(src: string): boolean {\n const name = path.basename(src)\n\n if (!name) {\n return true\n }\n\n if (IGNORED_STOREFRONT_BASENAMES.has(name)) {\n return false\n }\n\n if (TEST_FILE_RE.test(name)) {\n return false\n }\n\n return true\n}\n\n/**\n * Globs `next build` must not type-check inside `.faststore`. Besides the core\n * test trees, stores keep Storybook stories and Jest manual mocks next to\n * their components under `src/`; those are copied into\n * `.faststore/src/customizations/src` and would otherwise be compiled against\n * dev-only dependencies (`@storybook/*`, `@jest/globals`) the build does not\n * have.\n */\nexport const STOREFRONT_TEST_EXCLUDE_GLOBS = [\n 'test',\n '**/*.test.ts',\n '**/*.test.tsx',\n '**/*.spec.ts',\n '**/*.spec.tsx',\n '**/*.stories.ts',\n '**/*.stories.tsx',\n '**/__tests__/**',\n '**/__mocks__/**',\n] as const\n\ntype TsConfig = {\n include?: string[]\n exclude?: string[]\n compilerOptions?: Record<string, unknown>\n [key: string]: unknown\n}\n\n/**\n * Drop core/plugin test globs from the tsconfig copied into `.faststore`.\n * Defense in depth if a test file still lands under `src/`.\n */\nexport function prepareStorefrontTsConfig(tsConfig: TsConfig): TsConfig {\n const include = (tsConfig.include ?? []).filter(\n (pattern) => !String(pattern).startsWith('test/')\n )\n const exclude = Array.from(\n new Set([...(tsConfig.exclude ?? []), ...STOREFRONT_TEST_EXCLUDE_GLOBS])\n )\n\n return {\n ...tsConfig,\n include,\n exclude,\n }\n}\n","import chalk from 'chalk'\nimport path from 'node:path'\n// import { ux } from '@oclif/core'\nimport { confirm } from '@inquirer/prompts'\nimport fsExtra from 'fs-extra'\nconst { readFileSync, existsSync, writeFileSync, mkdirSync } = fsExtra\n\nimport { pathToFileURL } from 'node:url'\nimport { withBasePath } from './directory'\nimport { getPluginName, getPluginsList } from './plugins'\n\nexport interface ContentTypeOrSectionDefinition {\n id?: string\n name?: string\n scopes?: string[]\n isSingleton?: boolean\n onlySettings?: boolean\n requiredScopes?: string[]\n schema?: Record<string, unknown>\n configurationSchemaSets?: ConfigurationSchemaSet[]\n}\n\nexport interface ConfigurationSchemaSet {\n name?: string\n configurations?: Array<{\n name?: string\n schema?: Record<string, unknown>\n }>\n}\n\nexport function splitCustomDefinitions(\n coreDefinitions: ContentTypeOrSectionDefinition[],\n customDefinitions: ContentTypeOrSectionDefinition[],\n primaryIdentifier: 'id' | 'name'\n) {\n const coreDefinitionIdentifiers = new Set<string>(\n coreDefinitions.map((definition) => definition[primaryIdentifier] ?? '')\n )\n\n const duplicates: ContentTypeOrSectionDefinition[] = []\n const newDefinitions: ContentTypeOrSectionDefinition[] = []\n\n customDefinitions.forEach((definition) => {\n if (!definition[primaryIdentifier]) {\n console.error('Ignoring invalid definition:', definition)\n return\n }\n\n if (\n coreDefinitionIdentifiers.has(definition[primaryIdentifier] as string)\n ) {\n duplicates.push(definition)\n return\n }\n\n newDefinitions.push(definition)\n })\n\n return { duplicates, newDefinitions }\n}\n\nexport function dedupeAndMergeDefinitions(\n coreDefinitions: ContentTypeOrSectionDefinition[],\n duplicates: ContentTypeOrSectionDefinition[],\n primaryIdentifier: 'id' | 'name'\n) {\n const sortedCoreDefs = coreDefinitions.filter((definition) =>\n Boolean(definition[primaryIdentifier])\n )\n sortedCoreDefs.sort((a, b) =>\n (a[primaryIdentifier] as string) < (b[primaryIdentifier] as string) ? -1 : 1\n )\n\n const sortedDuplicates = duplicates.filter((definition) =>\n Boolean(definition[primaryIdentifier])\n )\n sortedDuplicates.sort((a, b) =>\n (a[primaryIdentifier] as string) < (b[primaryIdentifier] as string) ? -1 : 1\n )\n\n let duplicateIdx = 0\n\n const result = sortedCoreDefs.map((currentDefinition) => {\n const isDuplicateMatch =\n currentDefinition[primaryIdentifier] ===\n sortedDuplicates[duplicateIdx]?.[primaryIdentifier]\n\n if (duplicateIdx < sortedDuplicates.length && isDuplicateMatch) {\n return sortedDuplicates[duplicateIdx++]\n }\n\n return currentDefinition\n })\n\n return result\n}\n\nasync function confirmUserChoice(\n duplicates: ContentTypeOrSectionDefinition[],\n fileName: string\n) {\n const goAhead = await confirm({\n message: `You are about to override default ${\n fileName.split('.')[0]\n }:\\n\\n${duplicates\n .map((definition) => definition.id || definition.name)\n .join('\\n')}\\n\\nAre you sure? [yes/no]`,\n })\n\n if (!goAhead) {\n throw new Error('cms-sync cancelled by user.')\n }\n\n return\n}\n\nexport async function mergeCMSFile(fileName: string, basePath: string) {\n const {\n coreCMSDir,\n userCMSDir,\n tmpCMSDir,\n getPackagePath,\n userStoreConfigFile,\n } = withBasePath(basePath)\n\n const { default: userStoreConfig } = await import(\n pathToFileURL(path.resolve(userStoreConfigFile)).href\n )\n const cmsProjectName = userStoreConfig.contentSource?.project ?? 'faststore'\n\n const coreFilePath = path.join(coreCMSDir, fileName)\n const customFilePath = path.join(userCMSDir, fileName)\n\n const coreFile = readFileSync(coreFilePath, 'utf8')\n const coreDefinitions: ContentTypeOrSectionDefinition[] = JSON.parse(coreFile)\n\n const primaryIdentifierForDefinitions =\n fileName === 'content-types.json' ? 'id' : 'name'\n\n let output: ContentTypeOrSectionDefinition[] = coreDefinitions\n\n const plugins = await getPluginsList(basePath)\n\n const pluginCMSFilePaths = plugins.map((plugin) =>\n getPackagePath(getPluginName(plugin), 'cms', 'faststore', fileName)\n )\n\n const customizations = [...pluginCMSFilePaths, customFilePath].filter(\n (pluginCMSFilePath) => existsSync(pluginCMSFilePath)\n )\n\n // TODO: create a validation when the CMS files exist but don't have a component for them\n for (const newFilePath of customizations) {\n const customFile = readFileSync(newFilePath, 'utf8')\n\n try {\n const customDefinitions = JSON.parse(customFile)\n\n const { duplicates, newDefinitions } = splitCustomDefinitions(\n output,\n customDefinitions,\n primaryIdentifierForDefinitions\n )\n\n if (duplicates.length) {\n if (newFilePath === customFilePath) {\n await confirmUserChoice(duplicates, fileName)\n }\n\n output = [\n ...dedupeAndMergeDefinitions(\n output,\n duplicates,\n primaryIdentifierForDefinitions\n ),\n ...newDefinitions,\n ]\n } else {\n output = [...output, ...newDefinitions]\n }\n } catch (err) {\n if (err instanceof SyntaxError) {\n console.info(\n `${chalk.red(\n 'error'\n )} - ${fileName} is a malformed JSON file, ignoring its contents.`\n )\n } else {\n throw err\n }\n }\n }\n\n try {\n if (!existsSync(tmpCMSDir(cmsProjectName))) {\n mkdirSync(tmpCMSDir(cmsProjectName))\n }\n writeFileSync(\n path.join(tmpCMSDir(cmsProjectName), fileName),\n JSON.stringify(output)\n )\n console.log(\n `${chalk.green('success')} - CMS file ${chalk.dim(fileName)} created`\n )\n } catch (err) {\n console.error(`${chalk.red('error')} - ${err}`)\n }\n}\n\nexport async function mergeCMSFiles(basePath: string) {\n try {\n await mergeCMSFile('content-types.json', basePath)\n await mergeCMSFile('sections.json', basePath)\n } catch (err) {\n console.error(`${chalk.red('error')} - ${err}`)\n }\n}\n","/**\n * Preflight checks for the `vtex` toolbelt used by the CP flow of `cms-sync`.\n *\n * The CP flow shells out to `vtex content generate-schema`/`upload-schema`. If\n * the toolbelt is missing, the user is logged out, or logged into the wrong\n * account, those commands either fail opaquely or stall on an interactive login\n * prompt before the dev can answer the real schema prompts. Running these\n * checks first surfaces an actionable error (install / `vtex login` /\n * `vtex switch`) up front, against the store's `api.storeId`.\n */\nimport { execSync } from 'node:child_process'\nimport chalk from 'chalk'\nimport { logger } from './logger'\n\n/**\n * Runs a command capturing its merged stdout/stderr.\n * Returns null when the command fails to run or exits non-zero.\n */\nfunction runCapture(cmd: string): string | null {\n try {\n return execSync(`${cmd} 2>&1`, { stdio: 'pipe' }).toString()\n } catch {\n return null\n }\n}\n\n/** Whether the `vtex` toolbelt is available on the PATH. */\nexport function isVtexCliInstalled(): boolean {\n return runCapture('vtex --version') !== null\n}\n\n/**\n * Extracts the logged-in account from `vtex whoami` output.\n * Returns null when the output indicates a logged-out state or can't be parsed.\n *\n * Handles the toolbelt formats observed in practice, e.g.:\n * - \"Logged into brandless as user@vtex.com at workspace master\"\n * - \"user@vtex.com @ brandless / master\"\n */\nexport function parseAccountFromWhoami(output: string): string | null {\n if (/not logged|isn't logged|no user|please login/i.test(output)) {\n return null\n }\n\n const patterns = [\n /@\\s+([\\w.-]+)\\s*\\//, // \"user@vtex.com @ brandless / master\"\n /logged in(?:to)?\\s+(?:account\\s+)?([\\w.-]+)/i, // \"Logged into brandless ...\"\n /account[:\\s]+([\\w.-]+)/i, // \"... account brandless ...\"\n ]\n\n for (const pattern of patterns) {\n const match = output.match(pattern)\n if (match?.[1]) {\n return match[1]\n }\n }\n\n return null\n}\n\n/** Returns the account currently logged into the toolbelt, or null. */\nexport function getLoggedVtexAccount(): string | null {\n const output = runCapture('vtex whoami')\n\n if (!output) {\n return null\n }\n\n return parseAccountFromWhoami(output)\n}\n\n/**\n * Ensures the `vtex` toolbelt is installed and authenticated against the\n * store's account before running CP schema commands. Exits the process with an\n * actionable message when any check fails.\n *\n * @param account - The store account from `discovery.config.js` (`api.storeId`).\n */\nexport function assertVtexReadyForAccount(account?: string): void {\n if (!isVtexCliInstalled()) {\n logger.error(\n `${chalk.red('[Error]')} - The VTEX toolbelt (\\`vtex\\`) was not found. Install it with ${chalk.bold('npm i -g vtex')} and try again.\\n` +\n `${chalk.dim('Docs: https://developers.vtex.com/docs/guides/vtex-io-documentation-vtex-io-cli-installation-and-command-reference')}`\n )\n process.exit(1)\n return\n }\n\n const loggedAccount = getLoggedVtexAccount()\n const loginHint = account ? `vtex login ${account}` : 'vtex login <account>'\n\n if (!loggedAccount) {\n logger.error(\n `${chalk.red('[Error]')} - You are not logged into the VTEX toolbelt.\\n` +\n `${chalk.cyan('Required Action:')} log into the store account by running ${chalk.bold(loginHint)}.`\n )\n process.exit(1)\n return\n }\n\n if (account && loggedAccount.toLowerCase() !== account.toLowerCase()) {\n logger.error(\n `${chalk.red('[Error]')} - You are logged into ${chalk.bold(loggedAccount)}, but this store targets ${chalk.bold(account)} (\\`api.storeId\\` in discovery.config.js).\\n` +\n `${chalk.cyan('Required Action:')} switch accounts with ${chalk.bold(`vtex switch ${account}`)} or ${chalk.bold(loginHint)}.`\n )\n process.exit(1)\n }\n}\n","import fs from 'node:fs'\nimport degit from 'degit'\nimport { Args, Command } from '@oclif/core'\nimport { confirm } from '@inquirer/prompts'\n\nexport default class Create extends Command {\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the Discovery folder will be created. Defaults to ./discovery.',\n }),\n }\n\n static description =\n 'Creates a discovery folder based on the starter.store template.'\n\n static examples = ['$ yarn faststore create discovery']\n\n async run() {\n const { args } = await this.parse(Create)\n\n const discoveryPath = args.path ?? './discovery'\n const discoveryFolderExists = fs.existsSync(discoveryPath)\n\n if (discoveryFolderExists) {\n const confirmOverride = await confirm({\n message: `It looks like you already have a discovery folder named \"${discoveryPath}\" in your store. Do you want to override it?`,\n })\n\n if (!confirmOverride)\n return this.log('🛑 Interrupted initializing discovery')\n }\n\n const discoveryEmitter = degit('vtex-sites/starter.store', {\n force: true,\n })\n\n this.log('Pulling starter.store template...')\n\n discoveryEmitter.clone(discoveryPath).then(() => {\n this.log(\n `Discovery created successfully! You can find it at ${discoveryPath}`\n )\n })\n }\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport { spawn, spawnSync } from 'node:child_process'\nimport chokidar from 'chokidar'\nimport dotenv from 'dotenv'\n\nimport { cpSync, existsSync, readFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { withNodeModulesBins } from '../utils/binPaths'\nimport { getPreferredPackageManager } from '../utils/commands'\nimport { checkDeprecatedSecretFiles } from '../utils/deprecations'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\nimport { logger } from '../utils/logger'\nimport { runCommandSync } from '../utils/runCommandSync'\n\n/**\n * Taken from toolbelt\n *\n * https://github.com/vtex/toolbelt/pull/442\n */\nconst stabilityThreshold = process.platform === 'darwin' ? 100 : 200\n\nconst defaultPatterns = ['*/**', '**']\n\nconst defaultIgnored = [\n '.DS_Store',\n 'README.md',\n '.gitignore',\n 'package.json',\n '.git/**',\n '.faststore/**',\n '**/.faststore/**',\n]\n\nconst defaultNodeModulesIgnored = ['node_modules/**', '**/node_modules/**']\n\nconst defaultNodeModulesIgnoredExceptVtexPackages = [\n '**/node_modules/!(@vtex)/**',\n]\n\nconst devAbortController = new AbortController()\n\nasync function storeDev(\n rootDir: string,\n tmpDir: string,\n coreDir: string,\n port: number | string\n) {\n // Only try to read vtex.env if it exists\n let envVars = {}\n const vtexEnvPath = path.join(rootDir, 'vtex.env')\n\n if (existsSync(vtexEnvPath)) {\n try {\n envVars = dotenv.parse(readFileSync(vtexEnvPath))\n } catch (err) {\n logger.log(\n `${chalk.yellow('warn')} - Error parsing vtex.env file: ${err}`\n )\n }\n }\n\n const packageManager = await getPreferredPackageManager()\n\n runCommandSync({\n cmd: `${packageManager} predev`,\n errorMessage: `The \"predev\" step (\"${packageManager} predev\") failed inside the \".faststore\" directory. See the error output below for details.`,\n throws: 'error',\n cwd: tmpDir,\n env: withNodeModulesBins(tmpDir),\n })\n\n const { success } = copyGenerated(\n path.join(tmpDir, '@generated'),\n path.join(coreDir, '@generated')\n )\n\n if (!success) {\n logger.log(\n `${chalk.yellow('warn')} - Failed to copy @generated schema back to node_modules, autocomplete and DX might be impacted.`\n )\n logger.log(\n `Attempted to copy from ${path.join(tmpDir, '@generated')} to ${path.join(coreDir, '@generated')}`\n )\n }\n\n const devProcess = spawn(`${packageManager} dev-only --port ${port}`, {\n shell: true,\n cwd: tmpDir,\n signal: devAbortController.signal,\n stdio: ['inherit', 'pipe', 'inherit'],\n env: withNodeModulesBins(tmpDir, {\n ...process.env,\n ...envVars,\n }),\n })\n\n let nextStdout = ''\n devProcess.stdout.on('data', (chunk) => {\n nextStdout += chunk\n const lines = nextStdout.split('\\n')\n while (lines.length > 1) {\n const line = lines.shift()\n console.log('[DISCOVERY] ', line)\n }\n nextStdout = lines.shift() || ''\n })\n devProcess.stdout.on('end', () => {\n console.log('[DISCOVERY] ', nextStdout)\n })\n\n devProcess.on('close', () => {\n devAbortController.abort()\n })\n}\n\nfunction copyGenerated(from: string, to: string) {\n try {\n cpSync(from, to, { recursive: true, force: true, dereference: true })\n\n return { success: true }\n } catch (err) {\n return { success: false }\n }\n}\n\nexport default class Dev extends Command {\n static args = {\n account: Args.string({\n name: 'account',\n description:\n 'The account for which the Discovery is running. Currently noop.',\n }),\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being run is. Defaults to cwd.',\n }),\n port: Args.string({\n name: 'port',\n description: 'The port where FastStore should run. Defaults to 3000.',\n }),\n }\n\n static flags = {\n 'watch-plugins': Flags.boolean({\n description: 'Enable watching for plugin changes',\n default: false,\n }),\n }\n\n async run() {\n const { args, flags } = await this.parse(Dev)\n const basePath = getBasePath(args.path)\n\n const port = args.port ?? '3000'\n const watchPlugins = flags['watch-plugins']\n\n const { getRoot, tmpDir, coreDir } = withBasePath(basePath)\n\n checkDeprecatedSecretFiles(basePath)\n\n const queueChange = (/* path: string, remove: boolean */) => {\n generate({ basePath })\n }\n\n const watcher = chokidar.watch([...defaultPatterns], {\n atomic: stabilityThreshold,\n awaitWriteFinish: {\n stabilityThreshold,\n },\n cwd: getRoot(),\n ignoreInitial: true,\n ignored: [\n ...defaultIgnored,\n ...(watchPlugins\n ? defaultNodeModulesIgnoredExceptVtexPackages\n : defaultNodeModulesIgnored),\n ],\n persistent: true,\n usePolling: process.platform === 'win32',\n })\n\n devAbortController.signal.addEventListener('abort', () => {\n watcher.close()\n })\n\n await generate({ setup: true, basePath })\n\n const cliPath = fileURLToPath(\n import.meta.resolve('@faststore/cli/runner', import.meta.url)\n )\n\n spawnSync('node', [cliPath, 'generate-types', tmpDir], {\n stdio: 'inherit',\n })\n\n spawnSync('node', [cliPath, 'cache-graphql', basePath], {\n stdio: 'inherit',\n })\n\n // generate-i18n will validate localization config and check if it's enabled\n spawnSync('node', [cliPath, 'generate-i18n', basePath], {\n stdio: 'inherit',\n })\n\n storeDev(getRoot(), tmpDir, coreDir, port)\n\n return await new Promise((resolve, reject) => {\n watcher\n .on('add', (/*file*/) => queueChange(/*file, false*/))\n .on('change', (/*file*/) => queueChange(/*file, false*/))\n .on('unlink', (/*file*/) => queueChange(/*file, true*/))\n .on('error', () => {\n devAbortController.abort()\n reject()\n })\n .on('ready', resolve)\n })\n }\n}\n","import { Args, Command } from '@oclif/core'\nimport chalk from 'chalk'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\nimport { logger } from '../utils/logger'\nimport genTsTypes from '../utils/generate-types'\n\nexport default class Generate extends Command {\n static flags = {}\n\n static args = {\n path: Args.string({\n name: 'path',\n hidden: true,\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Generate)\n const basePath = getBasePath(args.path)\n const { tmpDir } = withBasePath(basePath)\n\n await generate({ setup: true, basePath })\n\n genTsTypes(args.path ?? tmpDir)\n\n logger.log(\n `${chalk.green(\n 'success'\n )} - GraphQL schema, types, and optimizations successfully generated 🎉`\n )\n }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nexport function saveFile(fileLocation: string) {\n fs.mkdirSync(path.dirname(fileLocation), { recursive: true })\n\n return (content: string) => {\n fs.writeFileSync(fileLocation, content)\n }\n}\n","import { saveFile } from './file'\nimport { GraphqlVtexSchema } from '@faststore/api'\nimport {\n generate as codegenGenerate,\n type CodegenConfig,\n} from '@graphql-codegen/cli'\nimport { mergeTypeDefs } from '@graphql-tools/merge'\nimport { printSchemaWithDirectives } from '@graphql-tools/utils'\nimport { buildASTSchema, Kind, parse, type DocumentNode } from 'graphql'\nimport fs, { existsSync } from 'node:fs'\nimport path from 'node:path'\n\nconst schemaFileName = 'schema.graphql'\n\nexport default async function genTsTypes(at: string) {\n await generateSchemaFile(at)\n await generateSchemaTSTypes(at)\n}\n\n/**\n * Codegen pointers (documents glob, schema and output dir) for a project root.\n *\n * They are expressed relative to `cwd` — the directory graphql-codegen resolves\n * pointers from — instead of as absolute paths. `@graphql-tools/load` treats a\n * pointer that contains whitespace and is not a parseable SDL as a broken\n * inline document and throws, so an absolute glob under e.g.\n * `/Users/me/My Store/.faststore` made `faststore build` fail with\n * \"Failed to parse the GraphQL document\". The relative form never includes the\n * parent directories, so it is unaffected by their names.\n */\nexport async function getCodegenPointers(\n root: string,\n cwd: string = process.cwd()\n) {\n const globbyImport = (await import('globby')) as GlobbyModule & {\n default?: GlobbyModule\n }\n const globbyModule = globbyImport.default ?? globbyImport\n\n let finalRootPath = path.resolve(root)\n\n if (existsSync(path.resolve(root, '.faststore'))) {\n finalRootPath = path.resolve(root, '.faststore')\n }\n\n // resolve symlinks on both sides (e.g. /var -> /private/var on macOS) so the\n // relative path does not climb back through the parent directories\n const realCwd = realpathIfExists(cwd)\n const relativeTo = (target: string) =>\n path.relative(realCwd, realpathIfExists(target)) || '.'\n\n // globs must use forward slashes on every platform, and glob-special\n // characters in the relative segments (e.g. parentheses) must be escaped\n const toPattern = (target: string) =>\n globbyModule.convertPathToPattern(relativeTo(target))\n\n // plain relative path (no glob escaping): this one is used as a file path\n const toRelativePath = (target: string) =>\n relativeTo(target).split(path.sep).join('/')\n\n return {\n // glob to include all ts/tsx files\n documents: [`${toPattern(path.join(finalRootPath, 'src'))}/**/*.{ts,tsx}`],\n schema: toRelativePath(\n path.join(finalRootPath, '@generated', schemaFileName)\n ),\n // trailing slash: tells the client preset the output is a folder\n outputDir: `${toRelativePath(path.join(finalRootPath, '@generated'))}/`,\n }\n}\n\n/**\n * `fs.realpathSync` for paths that may not exist yet (e.g. `@generated` before\n * the first run): resolves the closest existing ancestor and re-appends the\n * missing tail.\n */\nfunction realpathIfExists(target: string): string {\n const missing: string[] = []\n let current = path.resolve(target)\n\n while (!existsSync(current)) {\n const parent = path.dirname(current)\n\n if (parent === current) {\n return path.resolve(target)\n }\n\n missing.unshift(path.basename(current))\n current = parent\n }\n\n return path.join(fs.realpathSync.native(current), ...missing)\n}\n\nasync function generateSchemaTSTypes(root: string) {\n const { documents, schema, outputDir } = await getCodegenPointers(root)\n\n const config: CodegenConfig = {\n documents,\n overwrite: true,\n errorsOnly: false,\n debug: false,\n verbose: true,\n schema,\n generates: {\n [outputDir]: {\n preset: 'client',\n config: {\n /** Not all of these properties are supported by the preset, but it reflects our previous config when we used typescript plugins directly */\n preResolveTypes: true,\n avoidOptionals: true,\n enumsAsTypes: true,\n skipTypeNameForRoot: true,\n skipTypename: true,\n allowEnumStringTypes: false,\n flattenGeneratedTypes: true,\n namingConvention: 'change-case-all#pascalCase',\n exportFragmentSpreadSubTypes: true,\n /** Removes useless AST definitions from documents */\n documentMode: 'string',\n },\n presetConfig: {\n // Disabled fragment masking - it wasn't being used by us. This can be reviewed in the future\n fragmentMasking: false,\n // Recognizes the gql(`query { ... }`) calls and generates the types for them\n gqlTagName: 'gql',\n onExecutableDocumentNode: (document: DocumentNode) => ({\n // This makes sure that the operation name is always present in the __meta__ field of each query\n // This helps us to identify the query in the persisted documents and to debug errors in the client\n operationName: getOperationName(document),\n }),\n persistedDocuments: {\n // Keeps document simple, including only necessary properties as '__meta__' and its properties\n mode: 'replaceDocumentWithHash',\n // replaces operation['__meta__']['hash'] with operation['__meta__']['operationHash']\n hashPropertyName: 'operationHash',\n },\n },\n },\n },\n }\n\n return codegenGenerate(config, true)\n}\n\nfunction getOperationName(document: DocumentNode) {\n for (const definition of document.definitions) {\n if (\n definition.kind === Kind.OPERATION_DEFINITION &&\n typeof definition.name?.value === 'string'\n ) {\n return definition.name.value\n }\n }\n\n return 'UnknownOperation'\n}\n\nasync function generateSchemaFile(rootPath: string) {\n const faststoreSchema = printSchemaWithDirectives(GraphqlVtexSchema())\n\n const getMergedSchema = async () => {\n const root = path.join(\n rootPath.endsWith('.faststore') ? [rootPath, '..'].join('/') : rootPath\n )\n\n const customizations = [\n ...(await getTypeDefsFromFolder(root, 'vtex')),\n ...(await getTypeDefsFromFolder(root, 'thirdParty')),\n ]\n try {\n const mergedTypeDefs = mergeTypeDefs(\n [faststoreSchema, ...customizations].filter(Boolean)\n )\n\n return buildASTSchema(mergedTypeDefs)\n } catch (e) {\n console.error(\n 'An error occurred while attempting to merge the GraphQL Schema Extensions. Check the custom typeDefs and resolvers located in the \"customizations/graphql/\" directory. The changes since the last successful schema merge will be ignored.'\n )\n\n throw e\n }\n }\n\n let pathToSave = path.resolve(rootPath, '@generated', schemaFileName)\n\n if (existsSync(path.resolve(rootPath, '.faststore'))) {\n pathToSave = path.resolve(\n rootPath,\n '.faststore',\n '@generated',\n schemaFileName\n )\n }\n\n const saveSchemaFile = saveFile(pathToSave)\n const finalSchema = printSchemaWithDirectives(await getMergedSchema())\n\n saveSchemaFile(finalSchema)\n}\n\ntype GlobbyModule = typeof import('globby')\n\nexport async function getTypeDefsFromFolder(\n root: string,\n customPath: string | string[]\n) {\n const globbyImport = (await import('globby')) as GlobbyModule & {\n default?: GlobbyModule\n }\n const globbyModule = globbyImport.default ?? globbyImport\n const basePath = [root, 'src', 'graphql']\n\n const pathArray = Array.isArray(customPath) ? customPath : [customPath]\n\n // globby patterns must use forward slashes — on Windows, path.join produces\n // backslashes, which globby treats as escape characters and matches nothing\n const pattern = globbyModule.convertPathToPattern(\n path.join(...basePath, ...pathArray)\n )\n\n // spell out the glob instead of using expandDirectories: it stats the\n // escaped pattern string, so it never expands paths that needed escaping\n // (e.g. parentheses in a parent directory name)\n return globbyModule\n .globbySync(`${pattern}/**/*.graphql`)\n .map((typeDef: string) =>\n parse(fs.readFileSync(typeDef, { encoding: 'utf-8' }))\n )\n}\n","import { Args, Command } from '@oclif/core'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { getBasePath } from '../utils/directory'\n\nexport default class Prepare extends Command {\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being run is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Prepare)\n const basePath = getBasePath(args.path)\n\n const clientPublicDir = path.join(basePath, 'public/')\n\n const corePublicDir = path.resolve(\n fileURLToPath(\n path.dirname(import.meta.resolve('@faststore/core', import.meta.url))\n ),\n 'public'\n )\n\n if (!corePublicDir) {\n throw Error('Please install @faststore/core package')\n }\n\n copyFolder(corePublicDir, clientPublicDir)\n }\n}\n\nfunction copyFolder(sourceDir: string, targetDir: string) {\n // Ensure target directory exists\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true })\n }\n\n // Read all items in the source directory\n const files = fs.readdirSync(sourceDir)\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file)\n const targetPath = path.join(targetDir, file)\n\n const stat = fs.statSync(sourcePath)\n\n if (stat.isFile()) {\n // Copy file\n fs.copyFileSync(sourcePath, targetPath)\n console.log(`Copied file: ${sourcePath} -> ${targetPath}`)\n } else if (stat.isDirectory()) {\n // Recursively copy subfolder\n copyFolder(sourcePath, targetPath)\n }\n }\n}\n","import { Args, Command } from '@oclif/core'\nimport { spawn, spawnSync } from 'node:child_process'\nimport fsExtra from 'fs-extra'\nimport path from 'node:path'\nimport { resolvePackageManager } from '../utils/commands'\nimport { getBasePath, withBasePath } from '../utils/directory'\n\nconst { existsSync } = fsExtra\n\n/** Validated package-manager argv only — never a shell string. */\nfunction spawnPackageManagerSync(bin: string, args: string[]) {\n return spawnSync(bin, args, { stdio: 'inherit' }) // NOSONAR\n}\n\nfunction spawnPackageManager(bin: string, args: string[]) {\n return spawn(bin, args, { stdio: 'inherit' }) // NOSONAR\n}\n\nexport default class Start extends Command {\n static args = {\n account: Args.string({\n description:\n 'The account for which the Discovery is running. Currently noop.',\n }),\n path: Args.string({\n description:\n 'The path where the FastStore being run is. Defaults to cwd.',\n }),\n port: Args.string({\n description: 'The port where FastStore should run. Defaults to 3000.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Start)\n const basePath = getBasePath(args.path)\n const port = args.port ?? 3000\n const { getRoot, tmpDir } = withBasePath(basePath)\n const { argv } = await resolvePackageManager(basePath)\n const [bin, ...runnerArgs] = argv\n\n if (!existsSync(path.join(getRoot(), '.next'))) {\n // argv is a validated package-manager binary (plus optional Volta\n // prefix), never a shell string — keep this off a shell so the original\n // FAS-1199 prompt leak cannot reach sh.\n const build = spawnPackageManagerSync(bin, [\n ...runnerArgs,\n 'faststore',\n 'build',\n ])\n\n if (build.status !== 0) {\n throw new Error(\n `\"${[bin, ...runnerArgs].join(' ')} faststore build\" failed, so there is no build to serve.`\n )\n }\n }\n\n return spawnPackageManager(bin, [\n ...runnerArgs,\n 'next',\n 'start',\n tmpDir,\n '-p',\n String(port),\n ])\n }\n}\n","import { Args, Command } from '@oclif/core'\nimport { spawn } from 'node:child_process'\nimport chokidar from 'chokidar'\n\nimport { withNodeModulesBins } from '../utils/binPaths'\nimport { getPreferredPackageManager } from '../utils/commands'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\n\n/**\n * Taken from toolbelt\n *\n * https://github.com/vtex/toolbelt/pull/442\n */\nconst stabilityThreshold = process.platform === 'darwin' ? 100 : 200\n\nconst defaultPatterns = ['*/**', '**']\n\nconst defaultIgnored = [\n '.DS_Store',\n 'README.md',\n '.gitignore',\n 'package.json',\n 'node_modules/**',\n '**/node_modules/**',\n '.git/**',\n '.faststore/**',\n '**/.faststore/**',\n]\n\nconst testAbortController = new AbortController()\n\nasync function storeTest(tmpDir: string) {\n const packageManager = await getPreferredPackageManager()\n\n const testProcess = spawn(`${packageManager} run test:e2e`, {\n shell: true,\n cwd: tmpDir,\n signal: testAbortController.signal,\n stdio: 'inherit',\n env: withNodeModulesBins(tmpDir),\n })\n\n testProcess.on('close', () => {\n testAbortController.abort()\n })\n}\n\nexport default class Test extends Command {\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being tested is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Test)\n const basePath = getBasePath(args.path)\n const { getRoot, tmpDir } = withBasePath(basePath)\n\n const watcher = chokidar.watch([...defaultPatterns], {\n atomic: stabilityThreshold,\n awaitWriteFinish: {\n stabilityThreshold,\n },\n cwd: getRoot(),\n ignoreInitial: true,\n ignored: defaultIgnored,\n persistent: true,\n usePolling: process.platform === 'win32',\n })\n\n testAbortController.signal.addEventListener('abort', () => {\n watcher.close()\n })\n\n await generate({ setup: true, basePath })\n\n storeTest(tmpDir)\n\n return await new Promise((resolve, reject) => {\n watcher\n .on('error', () => {\n testAbortController.abort()\n reject()\n })\n .on('ready', resolve)\n })\n }\n}\n","import path from 'node:path'\nimport { Args, Command } from '@oclif/core'\nimport chalk from 'chalk'\nimport { logger } from '../utils/logger'\nimport genTsTypes from '../utils/generate-types'\n\nexport default class Generate extends Command {\n static hidden = true\n static flags = {}\n\n static args = {\n path: Args.string({\n name: 'path',\n required: true,\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Generate)\n\n await genTsTypes(\n path.isAbsolute(args.path)\n ? args.path\n : path.resolve(process.env.PWD ?? process.cwd(), args.path)\n )\n\n logger.log(\n `${chalk.green(\n 'success'\n )} - GraphQL schema, types, and optimizations successfully generated 🎉`\n )\n }\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport fsExtra from 'fs-extra'\nimport graphql from 'graphql'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { saveFile } from '../utils/file'\nimport { logger } from '../utils/logger'\n\nconst { Kind, OperationTypeNode, parse: parseGraphql } = graphql\n\nconst persistedDocumentsName = 'persisted-documents.json'\nconst configFileName = 'discovery.config.default.js'\nconst cachedOperationsFileName = 'cached-operations.json'\n\nexport default class CacheGraphql extends Command {\n static flags = {\n queries: Flags.string({\n name: 'queries',\n description: 'The path to locate persisted-document file.',\n }),\n config: Flags.string({\n name: 'config',\n description: 'The path where the discovery.config is located',\n }),\n }\n\n static args = {\n store: Args.string({\n name: 'store',\n description:\n 'The path where the FastStore being built is or the persisted-document path. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args, flags } = await this.parse(CacheGraphql)\n\n const rootPath = getBasePath()\n const argPath =\n (args?.store && path.resolve(rootPath, args.store)) || rootPath\n const { tmpDir } = withBasePath(argPath)\n const configPath =\n this.getConfigFile(flags.config && path.resolve(argPath, flags.config)) ||\n this.getConfigFile(tmpDir) ||\n this.getConfigFile(argPath)\n const persistedDocumentsPath =\n this.getPersistedDocument(\n (flags?.queries && path.resolve(argPath, flags?.queries)) || argPath\n ) || this.getPersistedDocument(tmpDir)\n if (!configPath) {\n return this.errorFileNotFound(\n configFileName,\n `\\n ${tmpDir}\\n ${argPath}`\n )\n }\n\n if (!persistedDocumentsPath) {\n return this.errorFileNotFound(\n persistedDocumentsName,\n flags?.queries ?? argPath\n )\n }\n\n const cachedOperationsPath = path.join(\n path.dirname(persistedDocumentsPath),\n cachedOperationsFileName\n )\n const saveCachedOperationsFile = saveFile(cachedOperationsPath)\n\n if (fsExtra.pathExistsSync(tmpDir))\n logger.info(`${chalk.blue('[Info]')} - .faststore Path at: ${tmpDir}`)\n\n logger.info(`${chalk.blue('[Info]')} - Config file location: ${configPath}`)\n logger.info(\n `${chalk.blue('[Info]')} - Persisted documents at: ${persistedDocumentsPath}`\n )\n logger.info(\n `${chalk.blue('[Info]')} - Cached operations output: ${cachedOperationsPath}`\n )\n\n const { default: persistedDocuments } = await import(\n pathToFileURL(persistedDocumentsPath).href,\n { with: { type: 'json' } }\n )\n\n const cachedQueries = getQueries(persistedDocuments)\n\n saveCachedOperationsFile(\n `${JSON.stringify(cachedQueries ?? [], null, 2)}\\n`\n )\n\n logger.info(\n `${chalk.green('[Success]')} - GraphQL queries cached with success: 🎉\n Queries: ${cachedQueries.join(', ')}`\n )\n }\n\n getPersistedDocument(rootPath?: string) {\n return this.getFile(persistedDocumentsName, [\n '@generated',\n persistedDocumentsName,\n ])(rootPath)\n }\n\n getConfigFile(rootPath?: string) {\n return this.getFile(configFileName, [configFileName])(rootPath)\n }\n\n getFile(fileName: string, pathFromRoot?: string | Array<string>) {\n return (rootPath?: string) => {\n switch (true) {\n case !rootPath:\n return\n case rootPath?.endsWith(fileName) && fsExtra.existsSync(rootPath):\n return rootPath\n case fsExtra.existsSync(path.join(rootPath ?? '', fileName)):\n return path.join(rootPath, fileName)\n default:\n if (!pathFromRoot) return\n\n const filePath = path.join(\n rootPath,\n ...(Array.isArray(pathFromRoot) ? pathFromRoot : [pathFromRoot])\n )\n\n if (fsExtra.existsSync(filePath)) {\n return filePath\n }\n return\n }\n }\n }\n\n errorFileNotFound(fileName: string, rootDir: string) {\n logger.error(\n `${chalk.red('[Error]')} - Couldn't find ${fileName} at ${rootDir}`\n )\n\n process.exit(1)\n }\n}\n\nconst getQueries = (persistedDocuments: Record<string, string>) => {\n const operationNames: Array<string> = []\n for (const operation of Object.values(persistedDocuments)) {\n let currentNames: Array<string> = []\n const operationAST = parseGraphql(operation)\n const hasMutationDefinition = operationAST.definitions.some(\n (def) =>\n def.kind === Kind.OPERATION_DEFINITION &&\n def.operation === OperationTypeNode.MUTATION\n )\n\n if (hasMutationDefinition) continue\n\n operationAST.definitions.forEach((definition) => {\n if (\n definition.kind === Kind.OPERATION_DEFINITION &&\n definition.operation === OperationTypeNode.QUERY &&\n definition.name?.kind === Kind.NAME &&\n !!definition.name?.value\n ) {\n currentNames.push(definition.name.value)\n return\n }\n })\n\n if (currentNames.length) {\n operationNames.push(...currentNames)\n currentNames = []\n }\n }\n\n return operationNames\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport { FastStoreSDK } from '@vtex/faststore-sdk'\nimport chalk from 'chalk'\nimport dotenv from 'dotenv'\nimport fsExtra from 'fs-extra'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { format } from 'prettier'\nimport { checkAndValidateLocalization } from '../utils/config'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { saveFile } from '../utils/file'\nimport { logger } from '../utils/logger'\nimport { pathToFileURL } from 'node:url'\n\nconst configFileName = 'discovery.config.default.js'\n\nexport default class GenerateI18n extends Command {\n static hidden = true\n\n static flags = {\n config: Flags.string({\n name: 'config',\n description: 'The path where the discovery.config is located',\n }),\n }\n\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n getConfigFile(rootPath?: string) {\n return this.getFile(configFileName, [configFileName])(rootPath)\n }\n\n getFile(fileName: string, pathFromRoot?: string | Array<string>) {\n return (rootPath?: string) => {\n switch (true) {\n case !rootPath:\n return\n case rootPath?.endsWith(fileName) && fsExtra.existsSync(rootPath):\n return rootPath\n case fsExtra.existsSync(path.join(rootPath ?? '', fileName)):\n return path.join(rootPath, fileName)\n default:\n if (!pathFromRoot) return\n\n const filePath = path.join(\n rootPath,\n ...(Array.isArray(pathFromRoot) ? pathFromRoot : [pathFromRoot])\n )\n\n if (fsExtra.existsSync(filePath)) {\n return filePath\n }\n return\n }\n }\n }\n\n errorFileNotFound(fileName: string, rootDir: string) {\n logger.error(\n `${chalk.red('[Error]')} - Couldn't find ${fileName} at ${rootDir}`\n )\n\n process.exit(1)\n }\n\n async run() {\n const { args, flags } = await this.parse(GenerateI18n)\n const rootPath = getBasePath()\n const argPath =\n (args?.path && path.resolve(rootPath, args.path)) || rootPath\n\n // Check if localization is enabled and contentSource is set to CP\n const localizationEnabled = await checkAndValidateLocalization(argPath)\n\n if (!localizationEnabled) {\n return\n }\n\n const vtexEnvPath = path.join(argPath, 'vtex.env')\n if (existsSync(vtexEnvPath)) {\n dotenv.config({ path: vtexEnvPath })\n }\n\n const { VTEX_ACCOUNT, FS_DISCOVERY_APP_KEY, FS_DISCOVERY_APP_TOKEN } =\n process.env\n const hasCredentials =\n VTEX_ACCOUNT && FS_DISCOVERY_APP_KEY && FS_DISCOVERY_APP_TOKEN\n\n if (!hasCredentials) {\n logger.error(`${chalk.red('[Error]')} - Missing VTEX credentials.\\n\n ${chalk.cyan('Required Action:')}\\n\n Check your FastStore WebOps Settings page - to work in production, it should contain the following variables: ${chalk.cyan('VTEX_ACCOUNT')}, ${chalk.cyan('FS_DISCOVERY_APP_KEY')}, ${chalk.cyan('FS_DISCOVERY_APP_TOKEN')}.\\n\n If running locally, please check your ${chalk.bold('vtex.env')} file, it should also contain those variables.\n `)\n\n process.exit(1)\n }\n\n const { tmpDir } = withBasePath(argPath)\n const configPath =\n this.getConfigFile(flags.config && path.resolve(argPath, flags.config)) ||\n this.getConfigFile(tmpDir) ||\n this.getConfigFile(argPath)\n\n if (!configPath) {\n return this.errorFileNotFound(\n configFileName,\n `\\n ${tmpDir}\\n ${argPath}`\n )\n }\n\n const saveConfigFile = saveFile(configPath)\n\n if (fsExtra.pathExistsSync(tmpDir))\n logger.info(`${chalk.blue('[Info]')} - .faststore Path at: ${tmpDir}`)\n\n logger.info(`${chalk.blue('[Info]')} - Config file location: ${configPath}`)\n const discoveryConfig = await import(pathToFileURL(configPath).href)\n\n const faststore = new FastStoreSDK({\n account: VTEX_ACCOUNT,\n appKey: FS_DISCOVERY_APP_KEY,\n appToken: FS_DISCOVERY_APP_TOKEN,\n })\n\n const settings = await faststore.locales()\n const currentConfig = discoveryConfig?.default ?? discoveryConfig\n\n saveConfigFile(\n await format(\n `module.exports = ${JSON.stringify(\n {\n ...currentConfig,\n localization: {\n ...(currentConfig?.localization ?? {}),\n ...settings,\n },\n },\n undefined,\n 2\n )}`,\n {\n parser: 'typescript',\n quoteProps: 'as-needed',\n }\n )\n )\n\n logger.info(\n `${chalk.green('success')} - i18n configuration successfully generated 🎉`\n )\n }\n}\n"],"mappings":";AAAA,SAAS,WAAW;;;ACApB,SAAS,MAAM,SAAS,aAAa;AACrC,OAAOA,YAAW;AAClB,SAAS,iBAAiB;AAC1B,SAAS,cAAAC,mBAAkB;AAC3B,OAAOC,cAAa;AACpB,OAAOC,WAAU;AACjB,SAAS,iBAAAC,gBAAe,qBAAqB;;;ACN7C,OAAO,aAAa;AACpB,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AAEjB,IAAM,EAAE,WAAW,IAAI;AAkBhB,SAAS,kBACd,WACA,SACoB;AACpB,MAAI;AAGF,WAAO,cAAc,KAAK,KAAK,SAAS,SAAS,CAAC,EAAE,QAAQ,SAAS;AAAA,EACvE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,eAAe,SAAiB;AACvC,QAAM,UAAoB,CAAC;AAC3B,MAAI,aAAa,KAAK,QAAQ,OAAO;AAErC,SAAO,MAAM;AACX,UAAM,SAAS,KAAK,KAAK,YAAY,gBAAgB,MAAM;AAE3D,QAAI,WAAW,MAAM,GAAG;AACtB,cAAQ,KAAK,MAAM;AAAA,IACrB;AAEA,UAAM,YAAY,KAAK,QAAQ,UAAU;AAEzC,QAAI,cAAc,YAAY;AAC5B,aAAO;AAAA,IACT;AAEA,iBAAa;AAAA,EACf;AACF;AAKA,SAAS,WAAW,KAAwB;AAC1C,SAAO,OAAO,KAAK,GAAG,EAAE,KAAK,CAAC,QAAQ,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;AAAA,QACJ,oBAAoB,KAAK;AAAA,UACvB;AAAA,YACE,GAAG;AAAA,YACH,cAAc;AAAA,cACZ,GAAI,eAAe,gBAAgB,CAAC;AAAA,cACpC,GAAG;AAAA,YACL;AAAA,UACF;AAAA,UACA;AAAA,UACA;AAAA,QACF,CAAC;AAAA,QACD;AAAA,UACE,QAAQ;AAAA,UACR,YAAY;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,GAAGO,QAAM,MAAM,SAAS,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;;;A/BhJO,IAAM,WAAW;AAAA,EACtB,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,KAAK;AAAA,EACL,OAAO;AAAA,EACP,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,UAAU;AAAA,EACV,kBAAkBG;AAAA,EAClB,iBAAiB;AAAA,EACjB,iBAAiB;AACnB;","names":["chalk","existsSync","fsExtra","path","fileURLToPath","existsSync","existsSync","existsSync","chalk","existsSync","chalk","path","fsExtra","chalk","path","fileURLToPath","existsSync","pkg","Args","Command","Flags","chalk","existsSync","path","pathToFileURL","chalk","existsSync","path","pathToFileURL","chalk","path","existsSync","pathToFileURL","chalk","existsSync","path","chalk","chalk","path","existsSync","chalk","chalk","fsExtra","path","pathToFileURL","fs","path","chalk","fs","path","chalk","chalk","chalk","fsExtra","path","pathToFileURL","path","copySync","existsSync","mkdirSync","readdirSync","fsExtra","pathToFileURL","path","copySync","existsSync","readdirSync","removeSync","writeFileSync","fsExtra","chalk","path","pathToFileURL","chalk","path","fsExtra","pathToFileURL","readFileSync","existsSync","writeFileSync","mkdirSync","fsExtra","pathToFileURL","path","chalk","execSync","chalk","execSync","chalk","Command","Flags","Args","existsSync","pathToFileURL","path","chalk","fs","Args","Command","confirm","Args","Command","Flags","chalk","spawn","spawnSync","cpSync","existsSync","readFileSync","path","fileURLToPath","path","existsSync","readFileSync","chalk","spawn","cpSync","Command","Args","Flags","fileURLToPath","spawnSync","Args","Command","chalk","fs","path","fs","existsSync","path","Command","Args","chalk","Args","Command","fs","path","fileURLToPath","Command","Args","path","fileURLToPath","fs","Args","Command","spawn","spawnSync","fsExtra","path","existsSync","fsExtra","spawnSync","spawn","Command","Args","path","Args","Command","spawn","chokidar","stabilityThreshold","defaultPatterns","defaultIgnored","spawn","Command","Args","chokidar","path","Args","Command","chalk","Generate","Command","Args","path","chalk","Args","Command","Flags","chalk","fsExtra","path","pathToFileURL","Kind","configFileName","Command","Flags","Args","path","fsExtra","chalk","pathToFileURL","Args","Command","Flags","chalk","dotenv","fsExtra","existsSync","path","pathToFileURL","configFileName","Command","Flags","Args","fsExtra","path","chalk","existsSync","dotenv","Generate"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/commands/build.ts","../src/utils/binPaths.ts","../src/utils/commands.ts","../src/utils/logger.ts","../src/utils/deprecations.ts","../src/utils/directory.ts","../src/commands/cms-sync.ts","../src/utils/config.ts","../src/utils/cp-schema.ts","../src/utils/runCommandSync.ts","../src/utils/generate.ts","../src/utils/createNextjsPages.ts","../src/utils/readMyAccountCmsRoutes.ts","../src/utils/templates/myAccountCmsPage.ts","../src/utils/templates/myAccountPage.ts","../src/utils/dependencies.ts","../src/utils/plugins.ts","../src/utils/storefrontCopy.ts","../src/utils/hcms.ts","../src/utils/vtex.ts","../src/commands/create.ts","../src/commands/dev.ts","../src/commands/generate.ts","../src/utils/file.ts","../src/utils/generate-types.ts","../src/commands/prepare.ts","../src/commands/start.ts","../src/commands/test.ts","../src/commands/generate-types.ts","../src/commands/cache-graphql.ts","../src/commands/generate-i18n.ts"],"sourcesContent":["export { run } from '@oclif/core'\n\nimport { default as Build } from './commands/build'\nimport { default as CmsSync } from './commands/cms-sync'\nimport { default as Create } from './commands/create'\nimport { default as Dev } from './commands/dev'\nimport { default as Generate } from './commands/generate'\nimport { default as Prepare } from './commands/prepare'\nimport { default as Serve } from './commands/start'\nimport { default as Test } from './commands/test'\nimport { default as GenerateTypes } from './commands/generate-types'\nimport { default as CacheGraphql } from './commands/cache-graphql'\nimport { default as GenerateI18n } from './commands/generate-i18n'\n\nexport const commands = {\n create: Create,\n prepare: Prepare,\n dev: Dev,\n build: Build,\n serve: Serve,\n 'cms-sync': CmsSync,\n test: Test,\n generate: Generate,\n 'generate-types': GenerateTypes,\n 'cache-graphql': CacheGraphql,\n 'generate-i18n': GenerateI18n,\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport { spawnSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport fsExtra from 'fs-extra'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { withNodeModulesBins } from '../utils/binPaths'\nimport { getPreferredPackageManager } from '../utils/commands'\nimport { checkDeprecatedSecretFiles } from '../utils/deprecations'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { logger } from '../utils/logger'\n\nconst { copySync, moveSync, readdirSync, removeSync } = fsExtra\n\nexport default class Build extends Command {\n static args = {\n account: Args.string({\n description:\n 'The account for which the Discovery is running. Currently noop.',\n }),\n path: Args.string({\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n static flags = {\n ['no-verify']: Flags.boolean({\n description:\n 'Skips verification of faststore dependencies version string to prevent usage of packages outside npm registry.',\n }),\n }\n\n async run() {\n const { args, flags } = await this.parse(Build)\n\n const basePath = getBasePath(args.path)\n\n // Check for deprecated secret files\n checkDeprecatedSecretFiles(basePath)\n\n if (!flags['no-verify']) {\n const invalidPackages = await checkDeps(basePath)\n invalidPackages.forEach((pkg) =>\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Dependency ${pkg} has invalid version signature. Please use a semver like ^1.0.0 (check the official releases on https://github.com/vtex/faststore)`\n )\n )\n }\n\n const { tmpDir } = withBasePath(basePath)\n\n const packageManager = await getPreferredPackageManager()\n\n const binCli = path.join(\n fileURLToPath(\n import.meta.resolve('@faststore/cli/runner', import.meta.url)\n )\n )\n let scriptResult = spawnSync('node', [binCli, 'generate', basePath], {\n stdio: 'inherit',\n })\n\n if (scriptResult.error || scriptResult.status !== 0) {\n throw 'Error: Cant run generate' + (scriptResult.error?.message ?? '')\n }\n\n scriptResult = spawnSync('node', [binCli, 'cache-graphql', basePath], {\n stdio: 'inherit',\n })\n\n if (scriptResult.error || scriptResult.status !== 0) {\n throw (\n 'Error: Unable to run cache-graphql' +\n (scriptResult.error?.message ?? '')\n )\n }\n\n // generate-i18n will validate localization config and check if it's enabled\n scriptResult = spawnSync('node', [binCli, 'generate-i18n', basePath], {\n stdio: 'inherit',\n })\n\n if (scriptResult.error || scriptResult.status !== 0) {\n throw (\n 'Error: Unable to run generate-i18n' +\n (scriptResult.error?.message ?? '')\n )\n }\n\n scriptResult = spawnSync(`${packageManager} run build`, {\n shell: true,\n cwd: tmpDir,\n stdio: 'inherit',\n env: withNodeModulesBins(tmpDir),\n })\n\n if (scriptResult.status && scriptResult.status !== 0) {\n process.exit(scriptResult.status)\n }\n\n await normalizeStandaloneBuildDir(basePath)\n await copyResources(basePath)\n }\n}\n\nasync function copyResource(from: string, to: string) {\n try {\n if (existsSync(to)) {\n removeSync(to)\n }\n\n copySync(from, to)\n console.log(\n `${chalk.green('success')} - ${chalk.dim(from)} copied to ${chalk.dim(\n to\n )}`\n )\n } catch (err) {\n console.error(`${chalk.red('error')} - ${err}`)\n }\n}\n\nasync function normalizeStandaloneBuildDir(basePath: string) {\n const { tmpDir } = withBasePath(basePath)\n const isRunningFromMonorepo = process.cwd() !== basePath\n const prefix = isRunningFromMonorepo\n ? `${path.relative(process.cwd(), basePath).replace(/\\\\/g, '/')}/`\n : ''\n\n // Fix Next.js v13+ standalone build output directory\n if (existsSync(`${tmpDir}/.next/standalone/${prefix}.faststore`)) {\n const standaloneBuildFiles = readdirSync(\n `${tmpDir}/.next/standalone/${prefix}.faststore`\n )\n\n await Promise.all(\n standaloneBuildFiles.map((file) =>\n moveSync(\n `${tmpDir}/.next/standalone/${prefix}.faststore/${file}`,\n `${tmpDir}/.next/standalone/${file}`,\n { overwrite: true }\n )\n )\n )\n removeSync(`${tmpDir}/.next/standalone/${prefix}.faststore`)\n }\n}\n\nasync function copyResources(basePath: string) {\n const { tmpDir, userDir } = withBasePath(basePath)\n\n if (process.env.BUILD_CONTEXT === 'vercel') {\n const toDir = process.cwd()\n\n // Because of how copyResource works (delete the target directory if it exists),\n // if we're moving something to the same place it is it will break.\n const nextOutputDirectory = `${tmpDir}/.next`\n const expectedOutputDirectory = `${toDir}/.faststore/.next`\n if (nextOutputDirectory !== expectedOutputDirectory) {\n await copyResource(nextOutputDirectory, expectedOutputDirectory)\n }\n await copyResource(`${tmpDir}/public`, `${toDir}/public`)\n } else {\n await copyResource(`${tmpDir}/.next`, `${userDir}/.next`)\n await copyResource(\n `${tmpDir}/lighthouserc.js`,\n `${userDir}/lighthouserc.js`\n )\n await copyResource(`${tmpDir}/public`, `${userDir}/public`)\n }\n}\n\nasync function checkDeps(basePath: string): Promise<Array<string>> {\n const packageJsonPath = `${basePath}/package.json`\n if (!existsSync(packageJsonPath)) {\n console.log(\n `${chalk.yellow(\n 'warning'\n )} - package.json not found at ${packageJsonPath}`\n )\n }\n\n try {\n const mod = await import(pathToFileURL(packageJsonPath).href, {\n with: { type: 'json' },\n })\n const pkg = (mod.default ?? mod) as {\n devDependencies?: Record<string, string>\n dependencies?: Record<string, string>\n peerDependencies?: Record<string, string>\n }\n const {\n devDependencies = {},\n dependencies = {},\n peerDependencies = {},\n } = pkg\n\n const allDeps: Record<string, string> = Object.assign(\n {},\n peerDependencies,\n devDependencies,\n dependencies\n )\n\n const invalidPackages: Array<string> = []\n\n Object.entries(allDeps).forEach(([pkg, version]) => {\n if (/^@faststore\\/.+/i.test(pkg) === false) return\n\n if (version && /^(http|https|git):.+/.test(version) === true) {\n invalidPackages.push(pkg)\n }\n })\n\n return invalidPackages\n } catch (err) {\n console.log(\n `${chalk.yellow('warning')} - unable to check @faststore dependencies: ${err}`\n )\n\n return []\n }\n}\n","import fsExtra from 'fs-extra'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\n\nconst { existsSync } = fsExtra\n\n/**\n * Resolves a package's executable through Node's module resolution, starting\n * the lookup at `fromDir`.\n *\n * `withNodeModulesBins` can only order directories, so it runs whichever copy of\n * a binary the nearest ancestor `node_modules/.bin` happens to hold. That is not\n * necessarily the copy `@faststore/core` depends on: on a hoisted monorepo\n * another module's older Next can win the root `.bin` link, and the build then\n * fails on flags that version does not have. Module resolution follows the\n * dependency graph instead, so it returns the copy core would import — and it\n * still finds one where no ancestor `.bin` has it at all, as happens when a\n * package manager nests rather than hoists.\n *\n * Returns `undefined` when the specifier cannot be resolved, so callers can fall\n * back to the bare command name.\n */\nexport function resolvePackageBin(\n specifier: string,\n fromDir: string\n): string | undefined {\n try {\n // createRequire needs a file path to anchor the lookup. The file itself does\n // not have to exist; only the directory it sits in is used.\n return createRequire(path.join(fromDir, 'noop.js')).resolve(specifier)\n } catch {\n return undefined\n }\n}\n\nfunction collectBinDirs(fromDir: string) {\n const binDirs: string[] = []\n let currentDir = path.resolve(fromDir)\n\n while (true) {\n const binDir = path.join(currentDir, 'node_modules', '.bin')\n\n if (existsSync(binDir)) {\n binDirs.push(binDir)\n }\n\n const parentDir = path.dirname(currentDir)\n\n if (parentDir === currentDir) {\n return binDirs\n }\n\n currentDir = parentDir\n }\n}\n\n// Environment variables are case-insensitive on Windows, where the key is\n// usually `Path`. Reusing the existing key avoids handing the child process\n// both `Path` and `PATH`.\nfunction getPathKey(env: NodeJS.ProcessEnv) {\n return Object.keys(env).find((key) => key.toUpperCase() === 'PATH') ?? 'PATH'\n}\n\n/**\n * Prepends the `node_modules/.bin` of `fromDir` and of every ancestor\n * directory to `PATH`.\n *\n * The generated `.faststore` package has no `node_modules` of its own, so the\n * binaries its scripts call (`na`, `next`) live higher up the tree: in the\n * store root or, on hoisted monorepos, the workspace root.\n */\nexport function withNodeModulesBins(\n fromDir: string,\n env: NodeJS.ProcessEnv = process.env\n): NodeJS.ProcessEnv {\n const binDirs = collectBinDirs(fromDir)\n\n if (binDirs.length === 0) {\n return { ...env }\n }\n\n const pathKey = getPathKey(env)\n const currentEntries = env[pathKey]?.split(path.delimiter) ?? []\n // Package managers already put some of these directories in PATH when they\n // run a script, but not necessarily nearest first. Dropping their copies\n // before prepending `binDirs` keeps the nearest ancestor in charge instead\n // of letting a farther one that was missing from PATH jump ahead of it.\n const binDirSet = new Set(binDirs)\n const otherEntries = currentEntries.filter((entry) => !binDirSet.has(entry))\n\n return {\n ...env,\n [pathKey]: [...binDirs, ...otherEntries].join(path.delimiter),\n }\n}\n","import {\n LOCKS,\n agents,\n cmdExists,\n detect,\n getCommand,\n getVoltaPrefix,\n} from '@antfu/ni'\nimport type { Agent } from '@antfu/ni'\nimport chalk from 'chalk'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { logger } from './logger'\n\nexport interface ResolvedPackageManager {\n /** Agent id, validated against `ni`'s known agents. For comparisons, never for execution. */\n agent: Agent\n /** Executable form for `spawn`/`spawnSync` with `shell: true`. May carry a Volta prefix. */\n command: string\n /** Executable form for `spawn` without a shell. */\n argv: [string, ...string[]]\n}\n\nexport class UnknownAgentError extends Error {}\n\nexport class NoAvailablePackageManagerError extends Error {}\n\nexport interface ResolvePackageManagerOptions {\n /**\n * Whether a detected-but-not-installed agent may be substituted with an\n * available fallback. Callers that write to the project (dependency\n * installation) must pass `false`: installing with a substitute agent would\n * leave a second, conflicting lockfile next to the project's own.\n */\n substitute?: boolean\n}\n\nconst DEFAULT_AGENT: Agent = 'yarn'\n// yarn and npm first — they are what the store build images ship. The\n// remaining known agents are last resorts so an environment that only has\n// pnpm or bun still resolves instead of failing.\nconst FALLBACK_AGENTS: Agent[] = ['yarn', 'npm', 'pnpm', 'bun']\n\n/**\n * Resolves the package manager to use for `cwd`.\n *\n * `programmatic: true` is what keeps `ni` from going interactive. Without it, an\n * agent that is not installed makes `ni` render a confirm prompt to stdout, and\n * callers interpolate this value straight into shell commands.\n */\nexport async function resolvePackageManager(\n cwd: string = process.cwd(),\n { substitute = true }: ResolvePackageManagerOptions = {}\n): Promise<ResolvedPackageManager> {\n const detected = (await detect({ programmatic: true, cwd })) ?? DEFAULT_AGENT\n\n if (!agents.includes(detected)) {\n throw new UnknownAgentError(\n `\"${detected}\" is not a known package manager. Expected one of: ${agents.join(\n ', '\n )}.`\n )\n }\n\n let agent = detected\n\n if (!cmdExists(binOf(detected))) {\n if (!substitute) {\n throw new NoAvailablePackageManagerError(\n `Detected \"${detected}\", which is not installed in this environment. This operation writes a lockfile, so no other package manager can stand in for it. Install \"${detected}\", or remove the lockfile or \"packageManager\" field that selects it.`\n )\n }\n\n agent = substituteAgent(detected, cwd)\n }\n\n const argv: [string, ...string[]] = [binOf(agent)]\n const voltaPrefix = getVoltaPrefix()\n\n if (voltaPrefix) {\n argv.unshift(...voltaPrefix.split(' '))\n }\n\n return { agent, command: argv.join(' '), argv }\n}\n\n/** Shell-ready form of {@link resolvePackageManager}, for callers that only run a command. */\nexport async function getPreferredPackageManager(\n cwd?: string\n): Promise<string> {\n const { command } = await resolvePackageManager(cwd)\n\n return command\n}\n\nfunction binOf(agent: Agent): string {\n return getCommand(agent, 'agent')\n}\n\nfunction substituteAgent(detected: Agent, cwd: string): Agent {\n const available = FALLBACK_AGENTS.find((candidate) =>\n cmdExists(binOf(candidate))\n )\n\n if (!available) {\n throw new NoAvailablePackageManagerError(\n `Detected \"${detected}\", which is not installed, and none of ${FALLBACK_AGENTS.join(\n ', '\n )} is available either.`\n )\n }\n\n const lockfiles = Object.keys(LOCKS).filter((lockfile) =>\n existsSync(join(cwd, lockfile))\n )\n\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Detected \"${detected}\" but it is not installed in this environment. Using \"${available}\" instead.` +\n (lockfiles.length > 1\n ? `\\nMore than one lockfile is committed (${lockfiles.join(\n ', '\n )}). Keep a single one so the package manager is unambiguous.`\n : '')\n )\n\n return available\n}\n","export const logger = new Proxy(console, {\n get(target, prop: keyof Console) {\n if (prop === 'log') {\n return (...args: any[]) => {\n if (process.env.DISCOVERY_DEBUG === 'true') {\n target.log(...args)\n }\n }\n }\n return target[prop]\n },\n})\n","import { existsSync } from 'node:fs'\nimport chalk from 'chalk'\nimport { logger } from './logger'\n\n/**\n * Checks for the presence of deprecated secret files and logs a warning if found.\n *\n * @param basePath The base path where to look for the secret files\n */\nexport function checkDeprecatedSecretFiles(basePath: string) {\n const secretsFilePath = `${basePath}/secrets.hidden.json`\n const vtexEnvFilePath = `${basePath}/vtex.env`\n\n const secretsFileExists = existsSync(secretsFilePath)\n const vtexEnvFileExists = existsSync(vtexEnvFilePath)\n\n if (secretsFileExists || vtexEnvFileExists) {\n const filesFound = [\n secretsFileExists ? 'secrets.hidden.json' : null,\n vtexEnvFileExists ? 'vtex.env' : null,\n ]\n .filter(Boolean)\n .join(' and ')\n\n logger.warn(\n `${chalk.yellow('warning')} - Deprecated secret files detected: ${chalk.bold(filesFound)}\\n` +\n `Note: 'vtex.env' should only be used for local development and not in production.\\n` +\n `For production environments, please configure your secrets directly in the FastStore WebOps Settings page.`\n )\n logger.log('') // Add empty line for better readability\n }\n}\n","import path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport const getBasePath = (basePath?: string) => {\n if (basePath) {\n return path.resolve(basePath)\n }\n\n return process.cwd()\n}\n\nexport const withBasePath = (basepath: string) => {\n const tmpFolderName = '.faststore'\n\n // The basepath is where the discovery code is. It's either . or the path configured on faststore.json\n const getRoot = () => basepath\n\n /*\n * This will loop from the basepath until the process.cwd() looking for node_modules/@faststore/core\n *\n * If it reaches process.cwd() (or /, as a safeguard), without finding it, it will throw an exception\n */\n const getCorePackagePath = () =>\n path.dirname(\n fileURLToPath(import.meta.resolve('@faststore/core', import.meta.url))\n )\n\n const customizationsDir = getRoot()\n const tmpDir = path.join(getRoot(), tmpFolderName)\n const userSrcDir = path.join(customizationsDir, 'src')\n const getPackagePath = (...packagePath: string[]) =>\n path.join(customizationsDir, 'node_modules', ...packagePath)\n\n return {\n getRoot,\n getPackagePath,\n userDir: customizationsDir,\n userSrcDir,\n userThemesFileDir: path.join(userSrcDir, 'themes'),\n userCMSDir: path.join(customizationsDir, 'cms', 'faststore'),\n userLegacyStoreConfigFile: path.join(\n customizationsDir,\n 'faststore.config.js'\n ),\n userStoreConfigFile: path.join(customizationsDir, 'discovery.config.js'),\n\n tmpSeoConfig: path.join(tmpDir, 'next-seo.config.ts'),\n tmpFolderName,\n tmpDir,\n tmpCustomizationsSrcDir: path.join(tmpDir, 'src', 'customizations', 'src'),\n tmpThemesCustomizationsFile: path.join(\n tmpDir,\n 'src',\n 'customizations',\n 'src',\n 'themes',\n 'index.scss'\n ),\n tmpThemesPluginsFile: path.join(tmpDir, 'src', 'plugins', 'index.scss'),\n tmpCMSDir: (projectName = 'faststore') =>\n path.join(tmpDir, 'cms', projectName),\n tmpCMSWebhookUrlsFile: path.join(tmpDir, 'cms-webhook-urls.json'),\n tmpPagesDir: path.join(tmpDir, 'src', 'pages'),\n tmpApiDir: path.join(tmpDir, 'src', 'pages', 'api'),\n tmpPluginsDir: path.join(tmpDir, 'src', 'plugins'),\n tmpStoreConfigFile: path.join(\n tmpDir,\n 'src',\n 'customizations',\n 'discovery.config.js'\n ),\n\n coreDir: getCorePackagePath(),\n coreCMSDir: path.join(getCorePackagePath(), 'cms', 'faststore'),\n }\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n isMyAccountEnabled,\n resolveContentSource,\n type ResolvedContentSource,\n} from '../utils/config'\nimport {\n cleanupMyAccountMergeDir,\n errorNoCustomization,\n generateAndUploadSchema,\n getCpSchemaOutputPath,\n getExistingCpDirs,\n type MyAccountMerge,\n prepareMyAccountMergeDir,\n} from '../utils/cp-schema'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\nimport { mergeCMSFiles } from '../utils/hcms'\nimport { logger } from '../utils/logger'\nimport { assertVtexReadyForAccount } from '../utils/vtex'\n\ntype StoreConfig = {\n api?: {\n storeId?: string\n }\n contentSource?: {\n type?: string\n project?: string\n }\n experimental?: {\n enableFaststoreMyAccount?: boolean\n }\n}\n\nconst CONTENT_SOURCE_ACTION: Record<ResolvedContentSource, string> = {\n CMS: 'merging and syncing CMS content',\n CP: 'generating and uploading schema',\n}\n\nexport default class CmsSync extends Command {\n static flags = {\n ['dry-run']: Flags.boolean({ char: 'd' }),\n }\n\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being synched with the CMS is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { flags, args } = await this.parse(CmsSync)\n\n const basePath = getBasePath(args.path)\n const { userStoreConfigFile } = withBasePath(basePath)\n\n const storeConfig: StoreConfig | null = existsSync(userStoreConfigFile)\n ? (await import(pathToFileURL(path.resolve(userStoreConfigFile)).href))\n .default\n : null\n\n const source = resolveContentSource(storeConfig?.contentSource?.type)\n\n logger.info(\n `${chalk.blue('[Info]')} - Detected contentSource \"${source}\" — ${CONTENT_SOURCE_ACTION[source]}`\n )\n\n switch (source) {\n case 'CMS':\n return this.runLegacySync({\n basePath,\n storeConfig,\n dryRun: flags['dry-run'],\n })\n case 'CP':\n return this.runCpSync({\n basePath,\n storeConfig,\n dryRun: flags['dry-run'],\n })\n default: {\n return source\n }\n }\n }\n\n private async runLegacySync({\n basePath,\n storeConfig,\n dryRun,\n }: {\n basePath: string\n storeConfig: StoreConfig | null\n dryRun?: boolean\n }) {\n const { tmpDir } = withBasePath(basePath)\n const project = storeConfig?.contentSource?.project ?? 'faststore'\n\n await generate({ setup: true, basePath })\n await mergeCMSFiles(basePath)\n\n if (dryRun) {\n return\n }\n\n return spawn(`vtex cms sync ${project}`, {\n shell: true,\n cwd: tmpDir,\n stdio: 'inherit',\n })\n }\n\n private runCpSync({\n basePath,\n storeConfig,\n dryRun,\n }: {\n basePath: string\n storeConfig: StoreConfig | null\n dryRun?: boolean\n }) {\n assertVtexReadyForAccount(storeConfig?.api?.storeId)\n\n let merge: MyAccountMerge | undefined\n\n if (isMyAccountEnabled(storeConfig)) {\n logger.info(\n `${chalk.blue('[Info]')} - Merging My Account sections and content-types into the schema`\n )\n // The merge dir already contains the store's own customizations merged\n // with the core My Account schemas, so it replaces the raw store dirs.\n merge = prepareMyAccountMergeDir(basePath)\n }\n\n const dirs = merge ? merge.dirs : getExistingCpDirs(basePath)\n\n if (dirs.length === 0) {\n errorNoCustomization()\n }\n\n const schemaOut = getCpSchemaOutputPath(basePath)\n\n // A toolbelt failure inside generateAndUploadSchema exits via process.exit(),\n // which bypasses `finally`. Register the cleanup on `exit` so the staging dir\n // is removed on that path too, then run it synchronously and drop the hook on\n // every normal path (success, dry-run, or a thrown error).\n let cleanup: (() => void) | undefined\n if (merge) {\n const { mergeDir } = merge\n cleanup = () => cleanupMyAccountMergeDir(mergeDir)\n process.once('exit', cleanup)\n }\n\n try {\n generateAndUploadSchema({\n basePath,\n dirs,\n schemaOut,\n dryRun: dryRun ?? false,\n project: storeConfig?.contentSource?.project,\n })\n } finally {\n if (cleanup) {\n process.removeListener('exit', cleanup)\n cleanup()\n }\n }\n }\n}\n","import chalk from 'chalk'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\n\nimport { pathToFileURL } from 'node:url'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\n\nconst configFileName = 'discovery.config.js'\n\nexport type ResolvedContentSource = 'CMS' | 'CP'\n\n/**\n * Minimal config shape consumed when deciding whether to merge My Account\n * schemas. Kept loose on purpose so callers can pass their own store config.\n */\ntype MyAccountConfig = {\n experimental?: {\n enableFaststoreMyAccount?: boolean\n }\n}\n\n/**\n * Whether FastStore My Account is enabled in the store config.\n * When enabled (CP mode only), `cms-sync` merges the core My Account CMS\n * schemas into the generated schema. Defaults to false when absent.\n */\nexport function isMyAccountEnabled(config?: MyAccountConfig | null): boolean {\n return config?.experimental?.enableFaststoreMyAccount === true\n}\n\n/**\n * Resolves the store's contentSource.type to a supported CMS flow.\n * Absent or CMS → legacy Headless CMS; CP → Content Platform schema publish.\n */\nexport function resolveContentSource(rawType?: string): ResolvedContentSource {\n const normalized = rawType?.toUpperCase()\n\n switch (normalized) {\n case undefined:\n case 'CMS':\n return 'CMS'\n case 'CP':\n return 'CP'\n default: {\n logger.error(\n `${chalk.red('[Error]')} - Unsupported contentSource.type \"${rawType}\". Expected \"CMS\" or \"CP\".`\n )\n process.exit(1)\n }\n }\n}\n\n/**\n * Partial type for discovery config with only the properties used by this module\n */\ntype DiscoveryConfigSubset = {\n localization?: {\n enabled?: boolean\n }\n contentSource?: {\n type?: string\n }\n}\n\n/**\n * Reads and returns the discovery config from tmpDir or basePath.\n *\n * @param basePath - The base path where the FastStore is located\n * @returns Promise<DiscoveryConfigSubset | null> - The config object or null if not found\n */\nexport async function getDiscoveryConfig(\n basePath: string\n): Promise<DiscoveryConfigSubset | null> {\n const { tmpDir } = withBasePath(basePath)\n const configPaths = [\n path.join(tmpDir, configFileName),\n path.join(basePath, configFileName),\n ]\n\n for (const configPath of configPaths) {\n if (existsSync(configPath)) {\n try {\n const discoveryConfig = await import(pathToFileURL(configPath).href)\n return discoveryConfig?.default ?? discoveryConfig\n } catch (error) {\n logger.warn(\n `${chalk.yellow('warning')} - Could not read config file: ${configPath}.`\n )\n }\n }\n }\n\n return null\n}\n\n/**\n * Checks if localization feature is enabled in the discovery config.\n *\n * @param config - The discovery config object\n * @returns boolean - true if localization.enabled === true, false otherwise\n */\nfunction isLocalizationEnabled(config: DiscoveryConfigSubset): boolean {\n return config?.localization?.enabled === true\n}\n\n/**\n * Validates if contentSource is set to \"CP\" when localization is enabled.\n * Exits the process with an error message if validation fails.\n *\n * @param config - The discovery config object\n */\nfunction validateContentSourceForLocalization(\n config: DiscoveryConfigSubset\n): void {\n if (!isLocalizationEnabled(config)) {\n return\n }\n\n const currentContentSourceType = config?.contentSource?.type?.toUpperCase()\n\n if (currentContentSourceType !== 'CP') {\n logger.error(\n `\\n${chalk.red('[Error]')} - Localization is enabled but contentSource is set to \"${currentContentSourceType}\".\\n\\n` +\n `${chalk.cyan('Required Action:')}\\n` +\n `Update your ${chalk.bold('discovery.config.js')} file:\\n\\n` +\n ` contentSource: {\\n` +\n ` type: ${chalk.green('\"CP\"')}\\n` +\n ` },\\n\\n` +\n `${chalk.dim('When localization is enabled, Content Platform (CP) is required.')}\\n`\n )\n\n process.exit(1)\n }\n}\n\n/**\n * Checks localization status and validates configuration.\n * Reads the config file once and performs both checks.\n *\n * @param basePath - The base path where the FastStore is located\n * @returns Promise<boolean> - true if localization is enabled and valid, false otherwise\n */\nexport async function checkAndValidateLocalization(\n basePath: string\n): Promise<boolean> {\n const config = await getDiscoveryConfig(basePath)\n\n // If we can't read the config, default to false (backward compatibility)\n if (!config) {\n return false\n }\n\n validateContentSourceForLocalization(config)\n\n return isLocalizationEnabled(config)\n}\n","/**\n * CP (Content Platform) schema helpers for `cms-sync`.\n * Generates and uploads the store's custom CMS schema via `vtex content`.\n * Store context only: no `-l` / base.jsonc, no core merge.\n */\nimport chalk from 'chalk'\nimport { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'\nimport path from 'node:path'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport { runCommandSync } from './runCommandSync'\n\nconst MY_ACCOUNT_SUBDIRS = ['components', 'pages'] as const\n\nexport function getExistingCpDirs(basePath: string): string[] {\n const { userCMSDir } = withBasePath(basePath)\n const componentsDir = path.join(userCMSDir, 'components')\n const pagesDir = path.join(userCMSDir, 'pages')\n\n return [componentsDir, pagesDir]\n .filter((dir) => existsSync(dir))\n .map((dir) => path.relative(basePath, dir))\n}\n\nexport function errorNoCustomization(): never {\n logger.error(\n `${chalk.red('[Error]')} - No CMS customization found. Expected cms/faststore/components and/or cms/faststore/pages.`\n )\n process.exit(1)\n}\n\nexport function getCpSchemaOutputPath(basePath: string): string {\n // Relative to basePath: the toolbelt resolves -o against the cwd\n // (path.join(cwd, arg)), so an absolute path would be doubled into\n // <store>/<store>/cms/... and fail with ENOENT.\n return path.relative(\n basePath,\n path.join(withBasePath(basePath).userCMSDir, 'schema.json')\n )\n}\n\nexport type MyAccountMerge = {\n /** Absolute root directory holding the merged My Account JSONC. */\n mergeDir: string\n /**\n * Paths of the two merged directories, relative to `basePath` and ordered as\n * `[components, pages]`, so they can be passed positionally to\n * `generate-schema <componentsPath> <pagesPath>`.\n */\n dirs: string[]\n}\n\n/**\n * Builds a staging directory with exactly two subdirectories (`components` and\n * `pages`), each holding the file-level merge of the core My Account CMS JSONC\n * and the store's own customizations, ready to be fed to\n * `generate-schema <componentsPath> <pagesPath>`.\n *\n * The staging dir lives inside the store's `.faststore` tmp folder (created on\n * demand) and the returned paths are relative to `basePath`. The toolbelt\n * resolves positional args against the cwd (`path.join(cwd, arg)`), so an\n * absolute path under `os.tmpdir()` would be mangled into `<store>/var/...`\n * and fail with ENOENT.\n *\n * The My Account schemas are intentionally excluded from the published base\n * schema (and the Schema Registry), so they must be supplied locally when the\n * `experimental.enableFaststoreMyAccount` flag is on. They are copied from the\n * installed `@faststore/core`.\n *\n * Exits the process when the core My Account schemas are not found.\n */\nexport function prepareMyAccountMergeDir(basePath: string): MyAccountMerge {\n const { coreCMSDir, userCMSDir, tmpDir } = withBasePath(basePath)\n const coreMyAccountDir = path.join(coreCMSDir, 'my-account')\n\n if (!existsSync(coreMyAccountDir)) {\n logger.error(\n `${chalk.red('[Error]')} - My Account is enabled but the core My Account schemas were not found at ${coreMyAccountDir}. Update @faststore/core or disable experimental.enableFaststoreMyAccount.`\n )\n process.exit(1)\n }\n\n // `.faststore` may not exist yet in the CP flow (it does not run `generate`).\n mkdirSync(tmpDir, { recursive: true })\n const mergeDir = mkdtempSync(path.join(tmpDir, 'cms-myaccount-'))\n\n try {\n const dirs: string[] = []\n for (const subdir of MY_ACCOUNT_SUBDIRS) {\n const dest = path.join(mergeDir, subdir)\n mkdirSync(dest, { recursive: true })\n\n // Core My Account first; the store's customizations override on collision.\n const coreSource = path.join(coreMyAccountDir, subdir)\n if (existsSync(coreSource)) {\n cpSync(coreSource, dest, { recursive: true })\n }\n\n const storeSource = path.join(userCMSDir, subdir)\n if (existsSync(storeSource)) {\n cpSync(storeSource, dest, { recursive: true })\n }\n\n dirs.push(path.relative(basePath, dest))\n }\n\n return { mergeDir, dirs }\n } catch (error) {\n cleanupMyAccountMergeDir(mergeDir)\n throw error\n }\n}\n\n/**\n * Removes the temporary My Account merge directory. Safe to call on any\n * outcome (success, dry-run, or failure).\n */\nexport function cleanupMyAccountMergeDir(mergeDir: string): void {\n rmSync(mergeDir, { recursive: true, force: true })\n}\n\nexport function generateAndUploadSchema({\n basePath,\n dirs,\n schemaOut,\n dryRun,\n project,\n}: {\n basePath: string\n dirs: string[]\n schemaOut: string\n dryRun: boolean\n /**\n * The store's `contentSource.project`, forwarded as `--storeId` to\n * `vtex content upload-schema` so the published schema's `$id`\n * (`${account}.${storeId}`) matches the project declared in\n * `discovery.config.js`, mirroring the legacy CMS flow's use of `project`\n * in `vtex cms sync ${project}`. Falls back to `'faststore'`, the same\n * default already used there.\n */\n project?: string\n}): void {\n // Interactive: generate-schema prompts to confirm overriding base\n // definitions (no --yes flag), and upload-schema prompts for the schema\n // version to publish. stdio must reach the user's TTY.\n runCommandSync({\n cmd: `vtex content generate-schema ${dirs.join(' ')} -o ${schemaOut}`,\n cwd: basePath,\n throws: 'error',\n errorMessage: 'Failed to generate CMS schema',\n interactive: true,\n })\n\n if (dryRun) {\n return\n }\n\n const storeId = project ?? 'faststore'\n\n runCommandSync({\n cmd: `vtex content upload-schema ${schemaOut} --storeId ${storeId}`,\n cwd: basePath,\n throws: 'error',\n errorMessage: 'Failed to upload CMS schema',\n interactive: true,\n })\n}\n","import chalk from 'chalk'\nimport type { ChildProcess, ExecException } from 'node:child_process'\nimport { execSync } from 'node:child_process'\nimport { logger } from './logger'\n\ntype ExecSyncError = (ExecException & ChildProcess) | undefined\n\nconst showError = ({\n message,\n cmd,\n output,\n}: {\n message: string\n cmd: string\n output?: string\n}) => {\n logger.error(`${chalk.red('error')} - ${message}`)\n\n if (cmd && output) {\n logger.error(`${chalk.magenta('$')} ${cmd}`)\n logger.error(output)\n }\n\n process.exit(1)\n}\n\nconst showWarning = ({\n message,\n cmd,\n output,\n}: {\n message: string\n cmd: string\n output?: string\n}) => {\n logger.warn(`${chalk.yellow('warn')} - ${message}`)\n\n if (cmd && output) {\n logger.warn(`${chalk.magenta('$')} ${cmd}`)\n logger.warn(output)\n }\n}\n\nexport const runCommandSync = ({\n cmd,\n errorMessage,\n throws,\n cwd,\n env,\n interactive = false,\n}: {\n cmd: string\n errorMessage: string\n throws: 'warning' | 'error'\n cwd?: string\n env?: NodeJS.ProcessEnv\n interactive?: boolean\n}) => {\n try {\n logger.log(`[STARTED] ${cmd}`)\n\n // Interactive mode (stdio: 'inherit') wires the child to the parent TTY so\n // the toolbelt can prompt the user — e.g. generate-schema's \"override\n // default definitions?\" confirmation and upload-schema's version selection.\n // execSync stays synchronous, preserving generate → upload ordering. Output\n // goes straight to the terminal, so it can't be captured (and need not be).\n //\n // Non-interactive mode merges stdout + stderr via 2>&1 so the captured\n // output holds the tool's real error. We intentionally do not append\n // --debug/--verbose: strict toolbelt commands reject unknown flags. Verbose\n // progress logging is gated by DISCOVERY_DEBUG in the logger itself.\n const res = execSync(interactive ? cmd : `${cmd} 2>&1`, {\n stdio: interactive ? 'inherit' : 'pipe',\n cwd,\n env,\n })\n logger.log(`[STATUS] ${res?.toString() ?? 'Unknown'}`)\n logger.log(`[FINISHED] ${cmd}`)\n } catch (error) {\n const execError = error as ExecSyncError\n // Always surface the tool's own output (stdout+stderr are merged via 2>&1)\n // so store devs see the real root cause instead of only the generic message.\n const output =\n execError?.stdout?.toString() ||\n execError?.stderr?.toString() ||\n undefined\n\n if (throws === 'warning') {\n showWarning({ message: errorMessage, cmd, output })\n } else {\n showError({ message: errorMessage, cmd, output })\n }\n }\n}\n","import chalk from 'chalk'\nimport fsExtra from 'fs-extra'\n\nimport path from 'node:path'\n\nimport ora from 'ora'\n\nimport { pathToFileURL } from 'node:url'\nimport { resolvePackageBin } from './binPaths'\nimport { createNextJsPages } from './createNextjsPages'\nimport { installDependencies } from './dependencies'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport { installPlugins } from './plugins'\nimport {\n prepareStorefrontTsConfig,\n shouldCopyToStorefront,\n} from './storefrontCopy'\n\nconst {\n copyFileSync,\n copySync,\n existsSync,\n mkdirsSync,\n readFileSync,\n readdirSync,\n removeSync,\n statSync,\n writeFileSync,\n writeJsonSync,\n} = fsExtra\ninterface GenerateOptions {\n setup?: boolean\n basePath: string\n}\n\nfunction createTmpFolder(basePath: string) {\n const { tmpDir, tmpFolderName } = withBasePath(basePath)\n\n try {\n if (existsSync(tmpDir)) {\n removeSync(tmpDir)\n }\n\n mkdirsSync(tmpDir)\n logger.log(\n `${chalk.green('success')} - Temporary folder ${chalk.dim(\n tmpFolderName\n )} created`\n )\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n}\n\n/**\n * Builds the `.faststore/package.json` from `@faststore/core`'s manifest.\n * Strips `exports` and `packageManager` (the latter is pinned to pnpm and\n * breaks Yarn/Corepack on consumer stores).\n *\n * Propagates the store's `volta` config (when present) so Volta pins the same\n * Node/Yarn versions inside `.faststore`. Volta stops at the nearest\n * `package.json` and would otherwise fall back to a global Yarn Berry, which\n * breaks on the nested manifest.\n */\nexport function buildFaststorePackageJson(\n coreManifest: Record<string, unknown>,\n voltaConfig?: Record<string, unknown>,\n nextBin?: string\n): Record<string, unknown> {\n const {\n exports: _exports,\n packageManager: _packageManager,\n ...rest\n } = coreManifest\n\n const existingScripts =\n (rest.scripts as Record<string, string> | undefined) ?? {}\n\n /**\n * Invoking Next through the path resolved from `@faststore/core` rather than\n * by name, so a copy that won the root `.bin` link cannot answer instead. On\n * a monorepo where another module pins an older major, that copy is a\n * different Next than the one core was built against, and it rejects the\n * flags below outright. Falls back to the bare command when resolution fails,\n * which leaves the previous PATH-based behaviour in place.\n *\n * `nextBin` is relative to `.faststore`, which is where these scripts run.\n * An absolute path would carry the whole store directory into a shell string,\n * and a quote or a `$` anywhere above the project would break it — a relative\n * path only ever spans `node_modules` segments.\n */\n const next = nextBin ? `node ${nextBin}` : 'next'\n\n return {\n ...rest,\n name: 'dot-faststore',\n ...(voltaConfig ? { volta: voltaConfig } : {}),\n scripts: {\n ...existingScripts,\n generate: 'faststore generate',\n build: `${next} build --webpack`,\n serve: `${next} serve`,\n dev: `${next} dev --webpack`,\n 'dev-only': `${next} dev --webpack`,\n predev: 'na run partytown',\n prebuild: 'na run partytown',\n },\n }\n}\n\n/**\n * The Next executable `@faststore/core` resolves, expressed relative to the\n * `.faststore` directory its scripts run from. Returns undefined when it cannot\n * be resolved, or when no relative path exists — a different Windows drive —\n * so the caller falls back to the bare command.\n */\nexport function relativeNextBin(\n coreDir: string,\n tmpDir: string\n): string | undefined {\n const nextBin = resolvePackageBin('next/dist/bin/next', coreDir)\n\n if (!nextBin) {\n return undefined\n }\n\n const relative = path.relative(tmpDir, nextBin).replaceAll('\\\\', '/')\n\n return relative && !path.isAbsolute(relative) ? relative : undefined\n}\n\n/**\n * Reads the `volta` config from the store root `package.json`, if present.\n * Returns `undefined` when the file or the field is missing so the generated\n * manifest stays untouched for stores that do not use Volta.\n */\nfunction readRootVoltaConfig(\n rootDir: string\n): Record<string, unknown> | undefined {\n try {\n const rootManifestPath = path.join(rootDir, 'package.json')\n\n if (!existsSync(rootManifestPath)) {\n return undefined\n }\n\n const rootManifest = JSON.parse(readFileSync(rootManifestPath, 'utf8'))\n\n return rootManifest?.volta\n } catch {\n return undefined\n }\n}\n\n/**\n * Prevents imports from @faststore/core from randomly conflicting\n * where sometimes the package.json from the .faststore folder\n * took precedence over @faststore/core's package.json.\n */\nfunction filterAndCopyPackageJson(basePath: string) {\n const { coreDir, tmpDir, getRoot } = withBasePath(basePath)\n\n const coreManifest = JSON.parse(\n readFileSync(path.join(coreDir, 'package.json'), 'utf8')\n )\n\n const voltaConfig = readRootVoltaConfig(getRoot())\n\n const filteredFileContent = buildFaststorePackageJson(\n coreManifest,\n voltaConfig,\n relativeNextBin(coreDir, tmpDir)\n )\n\n writeJsonSync(path.join(tmpDir, 'package.json'), filteredFileContent, {\n spaces: 2,\n })\n}\n\n// Temporary array of strict rules enabled so far.\nconst TS_CONFIG_STRICT_RULES_ENABLED = ['noImplicitAny'] as const\n\n/**\n * Modify TypeScript compilation settings (tsconfig.json) to disable specific strict\n * type checking rules when files are moved to the .faststore folder.\n * TODO: The idea is to change the strict to false when all strict rules are migrated.\n */\nfunction disableTsConfigStrictRules(basePath: string) {\n const { coreDir, tmpDir } = withBasePath(basePath)\n\n const coreTsConfigPath = path.join(coreDir, 'tsconfig.json')\n\n const coreTsConfigFile = readFileSync(coreTsConfigPath, 'utf8')\n const tsConfig = JSON.parse(coreTsConfigFile)\n\n TS_CONFIG_STRICT_RULES_ENABLED.forEach((strictRule) => {\n tsConfig.compilerOptions[strictRule] = false\n })\n\n writeJsonSync(\n path.join(tmpDir, 'tsconfig.json'),\n prepareStorefrontTsConfig(tsConfig),\n {\n spaces: 2,\n }\n )\n}\n\nexport function copyCoreFiles(basePath: string) {\n const { coreDir, tmpDir } = withBasePath(basePath)\n\n try {\n copySync(coreDir, tmpDir, {\n dereference: true,\n filter(src) {\n return shouldCopyToStorefront(src)\n },\n })\n\n filterAndCopyPackageJson(basePath)\n disableTsConfigStrictRules(basePath)\n\n logger.log(`${chalk.green('success')} - Core files copied`)\n } catch (e) {\n logger.error(e)\n }\n}\n\n// File extensions allowed to be copied from the store's `public/` folder into\n// the build. Fonts are included so stores can self-host them (GDPR / CWV)\n// instead of relying on external CDNs.\nexport const PUBLIC_FILES_ALLOWED_EXTENSIONS = [\n '.json',\n '.txt',\n '.xml',\n '.ico',\n '.svg',\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n]\n\n/**\n * Decides whether an entry from the store's `public/` folder should be copied\n * to the build. Directories always pass so nested assets can be reached, and\n * files are matched by their real extension (not a substring of the path).\n */\nexport function isPublicFileAllowed(\n src: string,\n isDirectory: boolean\n): boolean {\n if (isDirectory) {\n return true\n }\n\n return PUBLIC_FILES_ALLOWED_EXTENSIONS.includes(\n path.extname(src).toLowerCase()\n )\n}\n\nexport function copyPublicFiles(basePath: string) {\n const { userDir, tmpDir } = withBasePath(basePath)\n\n try {\n if (existsSync(`${userDir}/public`)) {\n copySync(`${userDir}/public`, `${tmpDir}/public`, {\n dereference: true,\n overwrite: true,\n filter: (src) => {\n try {\n return isPublicFileAllowed(src, statSync(src).isDirectory())\n } catch {\n // Skip entries we can't stat (dangling symlinks, permission\n // errors) so a single bad file never aborts the whole public/ copy.\n return false\n }\n },\n })\n logger.log(`${chalk.green('success')} - Public files copied`)\n }\n } catch (e) {\n logger.error(e)\n }\n}\n\nasync function copyCypressFiles(basePath: string) {\n const { userDir, userStoreConfigFile, userLegacyStoreConfigFile, tmpDir } =\n withBasePath(basePath)\n\n try {\n // Cypress 9.x config file\n if (existsSync(`${userDir}/cypress.json`)) {\n copySync(`${userDir}/cypress.json`, `${tmpDir}/cypress.json`, {\n dereference: true,\n })\n }\n\n // Cypress 12.x config file\n if (existsSync(`${userDir}/cypress.config.ts`)) {\n copySync(`${userDir}/cypress.config.ts`, `${tmpDir}/cypress.config.ts`, {\n dereference: true,\n })\n }\n\n let userStoreConfig\n\n if (existsSync(userStoreConfigFile)) {\n userStoreConfig = (\n await import(pathToFileURL(path.resolve(userStoreConfigFile)).href)\n )?.default\n } else if (existsSync(userLegacyStoreConfigFile)) {\n userStoreConfig = (\n await import(\n pathToFileURL(path.resolve(userLegacyStoreConfigFile)).href\n )\n )?.default\n } else {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n }\n\n // Copy custom Cypress folder and files\n if (\n existsSync(`${userDir}/cypress`) &&\n userStoreConfig?.experimental?.enableCypressExtension\n ) {\n copySync(`${userDir}/cypress`, `${tmpDir}/cypress`, {\n overwrite: true,\n dereference: true,\n })\n\n logger.log(`${chalk.green('success')} - Cypress test files copied`)\n }\n\n // Create default Cypress 12.x (or superior) support file\n if (userStoreConfig?.experimental?.cypressVersion > 9) {\n copySync(\n `${tmpDir}/cypress/support/index.js`,\n `${tmpDir}/cypress/support/e2e.js`,\n { overwrite: false }\n )\n }\n } catch (e) {\n logger.error(e)\n }\n}\n\nfunction copyUserStarterToCustomizations(basePath: string) {\n const {\n userSrcDir,\n tmpCustomizationsSrcDir,\n userLegacyStoreConfigFile,\n userStoreConfigFile,\n tmpStoreConfigFile,\n } = withBasePath(basePath)\n\n try {\n if (existsSync(userSrcDir) && readdirSync(userSrcDir).length > 0) {\n copySync(userSrcDir, tmpCustomizationsSrcDir, { dereference: true })\n createNextJsPages(basePath)\n }\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n\n if (existsSync(userStoreConfigFile)) {\n copySync(userStoreConfigFile, tmpStoreConfigFile, { dereference: true })\n } else if (existsSync(userLegacyStoreConfigFile)) {\n copySync(userLegacyStoreConfigFile, tmpStoreConfigFile, {\n dereference: true,\n })\n } else {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n }\n\n logger.log(`${chalk.green('success')} - Starter files copied`)\n}\n\nasync function createCmsWebhookUrlsJsonFile(basePath: string) {\n const {\n userStoreConfigFile,\n userLegacyStoreConfigFile,\n tmpCMSWebhookUrlsFile,\n } = withBasePath(basePath)\n let userStoreConfig\n\n if (existsSync(userStoreConfigFile)) {\n userStoreConfig = (\n await import(pathToFileURL(path.resolve(userStoreConfigFile)).href)\n )?.default\n } else if (existsSync(userLegacyStoreConfigFile)) {\n userStoreConfig = (\n await import(pathToFileURL(path.resolve(userLegacyStoreConfigFile)).href)\n )?.default\n } else {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n }\n\n if (\n userStoreConfig?.vtexHeadlessCms &&\n userStoreConfig.vtexHeadlessCms?.webhookUrls\n ) {\n const { webhookUrls } = userStoreConfig?.vtexHeadlessCms\n\n try {\n writeJsonSync(tmpCMSWebhookUrlsFile, { urls: webhookUrls }, { spaces: 2 })\n logger.log(`${chalk.green('success')} - CMS webhook URLs file created`)\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n } else {\n logger.info(`${chalk.blue('info')} - No CMS webhook URLs were provided`)\n }\n}\n\nasync function copyTheme(basePath: string) {\n const {\n userStoreConfigFile,\n userThemesFileDir,\n tmpThemesCustomizationsFile,\n userLegacyStoreConfigFile,\n } = withBasePath(basePath)\n\n const storeConfigFile =\n (existsSync(userStoreConfigFile) && userStoreConfigFile) ||\n (existsSync(userLegacyStoreConfigFile) && userLegacyStoreConfigFile)\n\n const userStoreConfigFilePath =\n storeConfigFile && path.resolve(storeConfigFile)\n const importedStoreConfig =\n userStoreConfigFilePath &&\n (await import(pathToFileURL(userStoreConfigFilePath).href))\n const storeConfig =\n userStoreConfigFilePath &&\n (importedStoreConfig?.default || importedStoreConfig)\n\n if (!storeConfig)\n logger.info(\n `${chalk.blue(\n 'info'\n )} - No store config file was found in the root directory`\n )\n\n if (storeConfig.theme) {\n const customTheme = path.join(\n userThemesFileDir,\n `${storeConfig.theme}.scss`\n )\n if (existsSync(customTheme)) {\n try {\n copyFileSync(customTheme, tmpThemesCustomizationsFile)\n logger.log(\n `${chalk.green('success')} - ${\n storeConfig.theme\n } theme has been applied`\n )\n } catch (err) {\n logger.error(`${chalk.red('error')} - ${err}`)\n }\n } else {\n logger.info(\n `${chalk.blue('info')} - The ${\n storeConfig.theme\n } theme was added to the config file but the ${\n storeConfig.theme\n }.scss file does not exist in the themes folder. Read more: https://developers.vtex.com/docs/guides/faststore/themes-overview`\n )\n }\n } else if (\n existsSync(userThemesFileDir) &&\n readdirSync(userThemesFileDir).length > 0\n ) {\n logger.info(\n `${chalk.blue(\n 'info'\n )} - The theme needs to be added to the config file to be applied. Read more: https://www.faststore.dev/docs/themes/overview`\n )\n }\n}\n\nfunction updateBuildTime(basePath: string) {\n try {\n const { tmpSeoConfig } = withBasePath(basePath)\n let config = readFileSync(tmpSeoConfig, 'utf8')\n const newBuildTime = new Date().toISOString()\n\n config = config.replace(\n /const buildTime = .*?;/,\n `const buildTime = '${newBuildTime}';`\n )\n\n writeFileSync(tmpSeoConfig, config)\n\n logger.log(`${chalk.green('success')} - Build time updated`, newBuildTime)\n } catch (error) {\n logger.error(`${chalk.red('error')} - Updating build time:`, error)\n }\n}\n\nasync function checkDependencies(basePath: string, packagesToCheck: string[]) {\n const { coreDir, getRoot } = withBasePath(basePath)\n\n const corePackageJsonPath = path.join(coreDir, 'package.json')\n const rootPackageJsonPath = path.join(getRoot(), 'package.json')\n\n const { default: corePackageJson } = await import(\n pathToFileURL(corePackageJsonPath).href,\n {\n with: { type: 'json' },\n }\n )\n const { default: rootPackageJson } = await import(\n pathToFileURL(rootPackageJsonPath).href,\n {\n with: { type: 'json' },\n }\n )\n\n packagesToCheck.forEach((packageName) => {\n const coreVersion =\n corePackageJson.devDependencies[packageName] ||\n corePackageJson.dependencies[packageName]\n const rootVersion =\n rootPackageJson.devDependencies[packageName] ||\n rootPackageJson.dependencies[packageName]\n\n if (!coreVersion || !rootVersion) {\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Package ${packageName} not found in both core or root dependencies.`\n )\n } else if (coreVersion !== rootVersion) {\n logger.warn(\n `${chalk.yellow(\n 'warning'\n )} - Version mismatch detected for ${packageName}.\n Core: ${coreVersion}, Customization: ${rootVersion}. Please align both versions to prevent issues`\n )\n }\n })\n}\n\nexport function updateNextConfig(basePath: string) {\n const { tmpDir } = withBasePath(basePath)\n\n const nextConfigPath = path.join(tmpDir, 'next.config.js')\n\n let nextConfigData = String(readFileSync(nextConfigPath))\n // process.cwd() returns backslashes on Windows; next.config.js is later\n // parsed as JS source, where an unescaped backslash inside a string\n // literal is read as an escape sequence (e.g. `\\f` becomes a form feed),\n // corrupting the path. Forward slashes are valid on Windows too, and\n // match the same normalization already applied to nextBin below.\n // JSON.stringify (rather than wrapping in a template literal by hand)\n // also escapes quotes, so a path containing an apostrophe (e.g. a\n // Windows username like `C:\\Users\\O'Brien\\...`) doesn't terminate the\n // string literal early and produce invalid JS.\n const normalizedCwd = process.cwd().replaceAll('\\\\', '/')\n nextConfigData = nextConfigData.replace(\n /outputFileTracingRoot\\:\\s+(.*),/,\n `outputFileTracingRoot: ${JSON.stringify(normalizedCwd)},`\n )\n\n writeFileSync(nextConfigPath, nextConfigData)\n}\n\n// returns new (discovery.config.js) or legacy (faststore.config.js) store config file\nfunction getCurrentUserStoreConfigFile(basePath: string) {\n const { userStoreConfigFile, userLegacyStoreConfigFile } =\n withBasePath(basePath)\n\n if (existsSync(userStoreConfigFile)) {\n return userStoreConfigFile\n }\n\n if (existsSync(userLegacyStoreConfigFile)) {\n return userLegacyStoreConfigFile\n }\n\n return null\n}\n\nasync function validateAndInstallMissingDependencies(basePath: string) {\n const { userDir } = withBasePath(basePath)\n\n const currentUserStoreConfigFile = getCurrentUserStoreConfigFile(basePath)\n\n if (!currentUserStoreConfigFile) {\n return\n }\n\n const { default: userStoreConfig } = await import(\n pathToFileURL(currentUserStoreConfigFile).href\n )\n const { default: userPackageJson } = await import(\n pathToFileURL(path.join(userDir, 'package.json')).href,\n {\n with: { type: 'json' },\n }\n )\n\n const missingDependencies: Array<{\n feature: string\n dependencies: string[]\n }> = []\n\n if (userStoreConfig?.experimental?.preact) {\n missingDependencies.push({\n feature: 'Preact',\n dependencies: ['preact@10.23.1', 'preact-render-to-string@6.5.8'],\n })\n }\n\n missingDependencies.forEach(async ({ feature, dependencies }) => {\n const dependenciesToInstall = dependencies.filter((dependency) => {\n const dependencyName = dependency.split('@')[0]\n return !userPackageJson.dependencies[dependencyName]\n })\n\n if (dependenciesToInstall.length > 0) {\n const spinner = ora(\n `Installing ${feature} missing dependencies\\n`\n ).start()\n\n await installDependencies({\n dependencies: dependenciesToInstall,\n cwd: userDir,\n errorMessage: `failed to install ${feature} dependencies`,\n })\n\n spinner.stop()\n }\n })\n}\n\nasync function enableSearchSSR(basePath: string) {\n const storeConfigPath = getCurrentUserStoreConfigFile(basePath)\n\n if (!storeConfigPath) {\n return\n }\n const { default: storeConfig } = await import(\n pathToFileURL(storeConfigPath).href\n )\n if (!storeConfig.experimental.enableSearchSSR) {\n return\n }\n\n const { tmpDir } = withBasePath(basePath)\n const searchPagePath = path.join(tmpDir, 'src', 'pages', 's.tsx')\n const searchPageData = String(readFileSync(searchPagePath))\n\n const searchPageWithSSR = searchPageData.replaceAll(\n 'getStaticProps',\n 'getServerSideProps'\n )\n\n writeFileSync(searchPagePath, searchPageWithSSR)\n}\n\nexport async function generate(options: GenerateOptions) {\n const { basePath, setup = false } = options\n\n let setupPromise: Promise<unknown> | null = null\n\n await validateAndInstallMissingDependencies(basePath)\n\n if (setup) {\n setupPromise = Promise.all([\n createTmpFolder(basePath),\n copyCoreFiles(basePath),\n copyCypressFiles(basePath),\n copyPublicFiles(basePath),\n updateNextConfig(basePath),\n ])\n }\n\n await Promise.all([\n setupPromise,\n checkDependencies(basePath, ['typescript']),\n enableSearchSSR(basePath),\n updateBuildTime(basePath),\n copyUserStarterToCustomizations(basePath),\n copyTheme(basePath),\n createCmsWebhookUrlsJsonFile(basePath),\n installPlugins(basePath),\n ])\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport chalk from 'chalk'\n\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport {\n type MyAccountCmsRoute,\n readMyAccountCmsRoutes,\n} from './readMyAccountCmsRoutes'\nimport { myAccountCmsPageTemplate } from './templates/myAccountCmsPage'\nimport { myAccountPageTemplate } from './templates/myAccountPage'\n\nconst ALLOWED_PREFIX_PAGES = ['/pvt/account']\nconst ACCOUNT_ROUTE_PREFIX = '/pvt/account'\n\ntype CreateExternalPagesArgs = {\n customizationPagesDir: string\n corePagesDir: string\n baseCustomizationPagesDir: string\n /** Routes that already have a CMS generated page (keyed by normalized route). */\n cmsHandledRoutes: Set<string>\n}\n\nconst createExternalPages = ({\n customizationPagesDir,\n corePagesDir,\n baseCustomizationPagesDir,\n cmsHandledRoutes,\n}: CreateExternalPagesArgs) => {\n fs.readdirSync(customizationPagesDir).forEach((file) => {\n const filePath = path.join(customizationPagesDir, file)\n const destinationPath = path.join(corePagesDir, file)\n if (fs.statSync(filePath).isDirectory()) {\n if (!fs.existsSync(destinationPath)) {\n fs.mkdirSync(destinationPath, { recursive: true })\n }\n return createExternalPages({\n customizationPagesDir: filePath,\n corePagesDir: destinationPath,\n baseCustomizationPagesDir,\n cmsHandledRoutes,\n })\n }\n\n const isReactFile = filePath.endsWith('.tsx')\n\n /* Checks if the destination path does not exist as a file or as a folder containing an \"index.tsx\" file.\n * This ensures that the path is available before proceeding with file creation or other operations.\n */\n const isDestinationAvailable =\n !fs.existsSync(destinationPath) &&\n !fs.existsSync(\n path.join(destinationPath.replace('.tsx', ''), 'index.tsx')\n )\n\n if (isReactFile && isDestinationAvailable) {\n const relativePagePath = filePath\n .replace(baseCustomizationPagesDir, '')\n .replaceAll(/\\\\/g, '/')\n .replace(/\\.tsx$/, '')\n const normalizedRoute = normalizeAccountRoute(relativePagePath)\n\n // Already generated as a CMS/hybrid page — skip legacy wrap.\n if (cmsHandledRoutes.has(normalizedRoute)) {\n return\n }\n\n const externalPagePath = `src/customizations/src/pages${relativePagePath}`\n const content = myAccountPageTemplate(externalPagePath)\n fs.writeFileSync(destinationPath, content)\n }\n })\n}\n\nfunction isAllowedPrefixPage(file: string) {\n // Match on route-segment boundaries so `/pvt/accounting` is not treated as\n // a `/pvt/account` descendant.\n return ALLOWED_PREFIX_PAGES.some(\n (prefix) => file === prefix || file.startsWith(`${prefix}/`)\n )\n}\n\nfunction normalizeAccountRoute(routeOrRelativePath: string): string {\n const withSlash = routeOrRelativePath.startsWith('/')\n ? routeOrRelativePath\n : `/${routeOrRelativePath}`\n const withPvt = withSlash.startsWith('/pvt') ? withSlash : `/pvt${withSlash}`\n return withPvt.replace(/\\/index$/, '') || withPvt\n}\n\nfunction routeToPageFilePath(corePagesDir: string, route: string): string {\n const relative = route.replace(/^\\//, '') // pvt/account/wishlist\n return path.join(corePagesDir, `${relative}.tsx`)\n}\n\nfunction routeToCustomizationPagePath(\n customizationPagesDir: string,\n route: string\n): string | null {\n // /pvt/account/wishlist → pvt/account/wishlist.tsx under customization pages\n const relative = route.replace(/^\\//, '')\n if (!relative) return null\n\n const asFile = path.join(customizationPagesDir, `${relative}.tsx`)\n if (fs.existsSync(asFile)) return asFile\n\n const asIndex = path.join(customizationPagesDir, relative, 'index.tsx')\n if (fs.existsSync(asIndex)) return asIndex\n\n return null\n}\n\nfunction routeToExtensionImportBase(route: string): string {\n // /pvt/account/wishlist → wishlist ; /pvt/account/orders/foo → orders/foo\n return route.replace(ACCOUNT_ROUTE_PREFIX, '').replace(/^\\//, '')\n}\n\nfunction resolveExtensionPaths(\n tmpDir: string,\n route: string\n): { beforePath?: string; afterPath?: string } {\n const relative = routeToExtensionImportBase(route)\n if (!relative) return {}\n\n const extensionsDir = path.join(\n tmpDir,\n 'src/customizations/src/myAccount/extensions',\n relative\n )\n\n const beforeFile = path.join(extensionsDir, 'before.tsx')\n const afterFile = path.join(extensionsDir, 'after.tsx')\n\n const importBase = `src/customizations/src/myAccount/extensions/${relative}`\n\n return {\n ...(fs.existsSync(beforeFile)\n ? { beforePath: `${importBase}/before` }\n : {}),\n ...(fs.existsSync(afterFile) ? { afterPath: `${importBase}/after` } : {}),\n }\n}\n\nfunction destinationExists(destinationPath: string): boolean {\n if (fs.existsSync(destinationPath)) return true\n\n const asIndex = path.join(destinationPath.replace(/\\.tsx$/, ''), 'index.tsx')\n return fs.existsSync(asIndex)\n}\n\nfunction generateCmsPages({\n routes,\n corePagesDir,\n customizationPagesDir,\n tmpDir,\n}: {\n routes: MyAccountCmsRoute[]\n corePagesDir: string\n customizationPagesDir: string\n tmpDir: string\n}): Set<string> {\n const handled = new Set<string>()\n\n for (const { route, contentType } of routes) {\n const normalizedRoute = normalizeAccountRoute(route)\n\n if (!isAllowedPrefixPage(normalizedRoute)) {\n logger.warn(\n `${chalk.yellow('warning')} - Skipping CMS route ${normalizedRoute}: only ${ALLOWED_PREFIX_PAGES.join(', ')} prefixes are allowed`\n )\n continue\n }\n\n const destinationPath = routeToPageFilePath(corePagesDir, normalizedRoute)\n\n if (destinationExists(destinationPath)) {\n logger.warn(\n `${chalk.yellow('warning')} - Skipping CMS route ${normalizedRoute}: native page takes precedence`\n )\n continue\n }\n\n const customizationTsx = fs.existsSync(customizationPagesDir)\n ? routeToCustomizationPagePath(customizationPagesDir, normalizedRoute)\n : null\n\n const pagePath = customizationTsx\n ? `src/customizations/src/pages${customizationTsx\n .replace(customizationPagesDir, '')\n .replaceAll(/\\\\/g, '/')\n .replace(/\\.tsx$/, '')}`\n : undefined\n\n const { beforePath, afterPath } = resolveExtensionPaths(\n tmpDir,\n normalizedRoute\n )\n\n const content = myAccountCmsPageTemplate({\n contentType,\n routePath: normalizedRoute,\n pagePath,\n beforePath,\n afterPath,\n })\n\n fs.mkdirSync(path.dirname(destinationPath), { recursive: true })\n fs.writeFileSync(destinationPath, content)\n handled.add(normalizedRoute)\n\n logger.log(\n `${chalk.green('success')} - Generated CMS My Account page for ${normalizedRoute} (${contentType}${pagePath ? ', hybrid' : ''})`\n )\n }\n\n return handled\n}\n\nexport function createNextJsPages(basePath: string) {\n const { tmpDir } = withBasePath(basePath)\n\n const corePagesDir = path.join(tmpDir, 'src/pages')\n const customizationPagesDir = path.join(\n tmpDir,\n 'src/customizations/src/pages'\n )\n const navigationFilePath = path.join(\n tmpDir,\n 'src/customizations/src/myAccount/navigation.ts'\n )\n\n const cmsRoutes = readMyAccountCmsRoutes(navigationFilePath)\n const cmsHandledRoutes = generateCmsPages({\n routes: cmsRoutes,\n corePagesDir,\n customizationPagesDir,\n tmpDir,\n })\n\n if (!fs.existsSync(customizationPagesDir)) {\n // No customization pages — Mode A CMS pages (if any) were still generated above.\n return\n }\n\n const allPagesAreAllowed = ({\n basePath: pagesBase,\n dirPath,\n }: { basePath: string; dirPath: string }): boolean => {\n const items = fs.readdirSync(dirPath, { withFileTypes: true })\n\n // Empty pages dir is fine (Mode A only).\n if (items.length === 0) return true\n\n return items.every((item) => {\n const itemPath = path.join(dirPath, item.name)\n\n if (item.isDirectory()) {\n return allPagesAreAllowed({ basePath: pagesBase, dirPath: itemPath })\n }\n\n if (!item.isFile()) {\n return false // Reject anything that is not a file (symlinks, sockets, etc.)\n }\n\n const isNextPage = /\\.(js|jsx|ts|tsx)$/.test(item.name)\n if (!isNextPage) {\n return false // Reject files that are not Next.js pages\n }\n\n // For Next.js page files, check if they match allowed prefixes\n const relativePath = path.relative(pagesBase, itemPath)\n const normalizedPath =\n '/' + relativePath.replace(/\\\\/g, '/').replace(/\\.(js|jsx|ts|tsx)$/, '')\n\n return isAllowedPrefixPage(normalizedPath)\n })\n }\n\n const pagesAreAllowed = allPagesAreAllowed({\n basePath: customizationPagesDir,\n dirPath: customizationPagesDir,\n })\n\n if (!pagesAreAllowed) {\n throw new Error(\n `Only these prefix pages: (${ALLOWED_PREFIX_PAGES.join(', ')}) are allowed`\n )\n }\n\n createExternalPages({\n customizationPagesDir,\n corePagesDir,\n baseCustomizationPagesDir: customizationPagesDir,\n cmsHandledRoutes,\n })\n}\n","import fs from 'node:fs'\n\nimport { logger } from './logger'\n\nexport type MyAccountCmsRoute = {\n route: string\n title: string\n contentType: string\n}\n\n/**\n * Extracts a property value from a static object-literal fragment when the\n * value is a plain string literal (single or double quotes).\n */\nfunction readStringProp(\n objectLiteral: string,\n propName: string\n): string | undefined {\n const pattern = new RegExp(\n `${propName}\\\\s*:\\\\s*(['\"\\`])((?:\\\\\\\\.|(?!\\\\1).)*)\\\\1`,\n 'm'\n )\n const match = pattern.exec(objectLiteral)\n return match?.[2]\n}\n\n/**\n * Locates the `routes: [ ... ]` array passed to `getMyAccountRoutes({...})`\n * and returns each top-level object-literal that declares a `contentType`.\n *\n * Supports the documented static-literal authoring pattern only. Dynamic /\n * computed route entries are skipped with a warning (they still work as\n * legacy code-only pages when a `.tsx` exists).\n */\nexport function readMyAccountCmsRoutes(\n navigationFilePath: string\n): MyAccountCmsRoute[] {\n if (!fs.existsSync(navigationFilePath)) {\n return []\n }\n\n let sourceText: string\n try {\n sourceText = fs.readFileSync(navigationFilePath, 'utf8')\n } catch {\n logger.warn(\n `[my-account-cms] Could not read navigation file at ${navigationFilePath}`\n )\n return []\n }\n\n // Strip line comments to avoid false matches inside comments.\n const withoutLineComments = sourceText.replaceAll(/^\\s*\\/\\/.*$/gm, '')\n\n const routesMatch =\n /getMyAccountRoutes\\s*\\(\\s*\\{[\\s\\S]*?routes\\s*:\\s*\\[([\\s\\S]*?)\\]/.exec(\n withoutLineComments\n )\n\n if (!routesMatch) {\n logger.warn(\n `[my-account-cms] Could not statically parse routes in ${navigationFilePath}; skipping CMS page generation`\n )\n return []\n }\n\n const routesBody = routesMatch[1]\n const objectLiterals = routesBody.match(/\\{[^{}]*\\}/g) ?? []\n\n const routes: MyAccountCmsRoute[] = []\n\n for (const literal of objectLiterals) {\n const contentType = readStringProp(literal, 'contentType')\n if (!contentType) {\n continue\n }\n\n const route = readStringProp(literal, 'route')\n const title = readStringProp(literal, 'title')\n\n if (!route || !title) {\n logger.warn(\n `[my-account-cms] Skipping CMS route entry missing route/title in ${navigationFilePath}`\n )\n continue\n }\n\n routes.push({ route, title, contentType })\n }\n\n return routes\n}\n","type MyAccountCmsPageTemplateArgs = {\n contentType: string\n routePath: string\n pagePath?: string\n beforePath?: string\n afterPath?: string\n}\n\n/**\n * Template for CMS-driven custom My Account pages\n */\nexport const myAccountCmsPageTemplate = ({\n contentType,\n routePath,\n pagePath,\n beforePath,\n afterPath,\n}: MyAccountCmsPageTemplateArgs) => `\n import RenderSections, { RenderSectionsBase } from 'src/components/cms/RenderSections'\n import ACCOUNT_COMPONENTS from 'src/components/cms/account/Components'\n import { Layout } from 'src/components/account'\n import {\n myAccountCmsServerSideProps,\n type MyAccountCmsPageProps,\n } from 'src/experimental/myAccountCmsServerSideProps'\n import PageProvider from 'src/sdk/overrides/PageProvider'\n ${pagePath ? `import DynamicPage from '${pagePath}'` : ''}\n ${beforePath ? `import { default as BeforeSection } from '${beforePath}'` : ''}\n ${afterPath ? `import { default as AfterSection } from '${afterPath}'` : ''}\n\n export const getServerSideProps = myAccountCmsServerSideProps('${contentType}', '${routePath}')\n\n export default function Page({\n globalSections: globalSectionsProp,\n pageSections,\n navigationLabels,\n accountName,\n isRepresentative,\n }: MyAccountCmsPageProps) {\n const { sections: globalSections, settings: globalSettings } =\n globalSectionsProp ?? {}\n\n return (\n <PageProvider context={{ globalSettings, navigationLabels }}>\n <RenderSections\n globalSections={globalSections}\n components={ACCOUNT_COMPONENTS}\n >\n <Layout\n accountName={accountName}\n isRepresentative={isRepresentative}\n navigationLabels={navigationLabels}\n >\n ${beforePath ? '<BeforeSection />' : ''}\n <RenderSectionsBase\n sections={pageSections}\n components={ACCOUNT_COMPONENTS}\n />\n ${pagePath ? '<DynamicPage />' : ''}\n ${afterPath ? '<AfterSection />' : ''}\n </Layout>\n </RenderSections>\n </PageProvider>\n )\n }\n`\n","/*\n TODO: Code in a template string is not a good practice because it becomes very difficult to maintain.\n There will be a component called Layout that will wrap the entire My Account layout, including the global sections, menu, etc.\n This will reduce the amount of code inside the template string.\n*/\n\nexport const myAccountPageTemplate = (pagePath: string) => `\n import type { ComponentType } from 'react'\n import RenderSections from 'src/components/cms/RenderSections'\n import { default as GLOBAL_COMPONENTS } from 'src/components/cms/global/Components'\n import CUSTOM_COMPONENTS from 'src/customizations/src/components'\n import { Layout } from 'src/components/account'\n import {\n getServerSideProps,\n type MyAccountProps,\n } from 'src/experimental/myAccountServerSideProps'\n import DynamicPage from '${pagePath}';\n import PageProvider from 'src/sdk/overrides/PageProvider'\n /* A list of components that can be used in the CMS. */\n const COMPONENTS: Record<string, ComponentType<any>> = {\n ...GLOBAL_COMPONENTS,\n ...CUSTOM_COMPONENTS,\n }\n\n function Page({ globalSections: globalSectionsProp, accountName, isRepresentative }: MyAccountProps) {\n const { sections: globalSections, settings: globalSettings } = globalSectionsProp ?? {}\n\n return (\n <PageProvider context={{ globalSettings }}>\n <RenderSections\n globalSections={globalSections}\n components={COMPONENTS}\n >\n <Layout accountName={accountName} isRepresentative={isRepresentative}>\n <DynamicPage />\n </Layout>\n </RenderSections>\n </PageProvider>\n )\n }\n\n export { getServerSideProps }\n\n export default Page\n`\n","import chalk from 'chalk'\nimport {\n NoAvailablePackageManagerError,\n UnknownAgentError,\n resolvePackageManager,\n} from './commands'\nimport { logger } from './logger'\nimport { runCommandSync } from './runCommandSync'\n\ntype InstallDependenciesOptions = {\n dependencies: string[]\n cwd: string\n errorMessage: string\n}\n\nexport async function installDependencies({\n dependencies,\n cwd,\n errorMessage,\n}: InstallDependenciesOptions) {\n // Installing writes a lockfile: a substitute agent would leave a second,\n // conflicting one next to the project's (e.g. `yarn add` in a pnpm store\n // creates a `yarn.lock`), so only the detected agent is acceptable here.\n //\n // Resolve errors exit the process rather than reject: generate.ts still\n // walks missing features with forEach(async …), so a thrown error would\n // become an unhandled rejection and skip oclif handling. runCommandSync\n // already exits the process the same way on install failure.\n const { agent, command } = await resolvePackageManager(cwd, {\n substitute: false,\n }).catch((error: unknown) => {\n if (\n error instanceof NoAvailablePackageManagerError ||\n error instanceof UnknownAgentError\n ) {\n logger.error(`${chalk.red('error')} - ${error.message}`)\n process.exit(1)\n }\n\n throw error\n })\n const installCommand = agent === 'npm' ? 'install' : 'add'\n\n runCommandSync({\n // command is a validated package-manager invocation from resolvePackageManager\n cmd: `${command} ${installCommand} ${dependencies.join(' ')}`, // NOSONAR\n errorMessage,\n throws: 'error',\n cwd,\n })\n}\n","import fsExtra from 'fs-extra'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { withBasePath } from './directory'\nimport { logger } from './logger'\nimport { shouldCopyToStorefront } from './storefrontCopy'\n\nconst { copySync, existsSync, mkdirSync, readdirSync, writeFileSync } = fsExtra\n\nexport type PageConfig = {\n path: string\n appLayout: boolean\n name: string\n}\n\nexport type APIConfig = {\n path: string\n}\n\nexport type PluginConfig = {\n pages?: { [pageName: string]: Partial<PageConfig> }\n apis?: { [pageName: string]: Partial<APIConfig> }\n}\n\nexport type Plugin =\n | string\n | {\n [pluginName: string]: PluginConfig\n }\n\nconst PLUGIN_CONFIG_FILE = 'plugin.config.js'\n\nconst sanitizePluginName = (pluginName: string, pascalCase = false) => {\n const sanitized = pluginName.split('/')[1]\n\n if (pascalCase) {\n return sanitized\n .toLowerCase()\n .split('-')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('')\n }\n\n return sanitized\n}\n\nexport const getPluginName = (plugin: Plugin) => {\n if (typeof plugin === 'string') {\n return plugin\n }\n\n return Object.keys(plugin)[0]\n}\n\nconst getPluginCustomConfig = (plugin: Plugin) => {\n if (typeof plugin === 'string') {\n return {}\n }\n\n return plugin[getPluginName(plugin)]\n}\n\nconst getPluginSrcPath = async (basePath: string, pluginName: string) => {\n const { getPackagePath } = withBasePath(basePath)\n return getPackagePath(pluginName, 'src')\n}\n\nexport const getPluginsList = async (basePath: string): Promise<Plugin[]> => {\n const { tmpStoreConfigFile } = withBasePath(basePath)\n\n try {\n const {\n default: { plugins = [] },\n } = await import(pathToFileURL(tmpStoreConfigFile).href)\n return plugins\n } catch (error) {\n logger.error(`Could not load plugins from store config`)\n }\n\n return []\n}\n\nexport const copyPluginsSrc = async (basePath: string, plugins: Plugin[]) => {\n const { tmpPluginsDir } = withBasePath(basePath)\n\n logger.log('Copying plugins files')\n\n for (const plugin of plugins) {\n const pluginName = getPluginName(plugin)\n const pluginSrcPath = await getPluginSrcPath(\n basePath,\n getPluginName(pluginName)\n )\n const pluginDestPath = path.join(\n tmpPluginsDir,\n sanitizePluginName(pluginName)\n )\n\n copySync(pluginSrcPath, pluginDestPath, {\n filter: shouldCopyToStorefront,\n })\n logger.log(`Copied ${pluginName} files`)\n }\n}\n\nconst copyPluginPublicFiles = async (basePath: string, plugins: Plugin[]) => {\n const { tmpDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Copying plugin public files')\n\n plugins.forEach(async (plugin) => {\n const pluginName = getPluginName(plugin)\n const pluginPath = getPackagePath(getPluginName(pluginName))\n\n try {\n if (existsSync(`${pluginPath}/public`)) {\n copySync(`${pluginPath}/public`, `${tmpDir}/public`, {\n dereference: true,\n overwrite: true,\n })\n logger.log(`Plugin public files copied`)\n }\n } catch (e) {\n logger.error(e)\n }\n })\n}\n\nconst getPluginPageFileContent = (\n pluginName: string,\n pageName: string,\n appLayout: boolean\n) => `\n// GENERATED FILE\n// @ts-nocheck\nimport * as page from 'src/plugins/${pluginName}/pages/${pageName}'\n${appLayout ? `import { getGlobalSectionsData } from 'src/components/cms/GlobalSections'` : ``}\n${appLayout ? `import RenderSections from 'src/components/cms/RenderSections'` : ``}\nimport { withLocaleValidationSSR } from 'src/utils/localization/withLocaleValidation'\n\nasync function getServerSidePropsBase(${appLayout ? '{ previewData, ...otherProps }' : 'otherProps'}) {\n const noop = async function() {}\n const loaderData = await (page.loader || noop)(otherProps)\n${appLayout ? `const { sections = [] } = await getGlobalSectionsData(previewData)` : ``}\n\n return {\n props: {\n data: loaderData,\n ${appLayout ? 'globalSections: sections' : ``}\n }\n }\n}\n\nexport const getServerSideProps = withLocaleValidationSSR(getServerSidePropsBase)\nexport default function Page(props) {\n ${\n appLayout\n ? `return <RenderSections globalSections={props.globalSections}>\n {page.default(props.data)}\n </RenderSections>`\n : `return page.default(props.data)`\n }\n}\n `\n\nconst generatePluginPages = async (basePath: string, plugins: Plugin[]) => {\n const { tmpPagesDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Generating plugin pages')\n\n plugins.forEach(async (plugin) => {\n const pluginName = getPluginName(plugin)\n const pluginConfigPath = getPackagePath(pluginName, PLUGIN_CONFIG_FILE)\n\n const { default: pluginConfig } = await import(\n pathToFileURL(pluginConfigPath).href\n )\n\n const { pages: pagesCustom } = getPluginCustomConfig(plugin)\n\n const pagesConfig: Record<string, PageConfig> = {\n ...(pluginConfig.pages ?? {}),\n ...pagesCustom,\n }\n\n const pages = Object.keys(pagesConfig)\n\n pages.forEach(async (pageName) => {\n const paths = pagesConfig[pageName].path.split('/')\n\n const pageFile = paths.pop()\n const pagePaths = paths\n\n const pagePath = path.join(tmpPagesDir, ...pagePaths, pageFile + '.tsx')\n\n const fileContent = getPluginPageFileContent(\n sanitizePluginName(pluginName),\n pageName,\n pagesConfig[pageName].appLayout\n )\n\n mkdirSync(path.dirname(pagePath), { recursive: true })\n writeFileSync(pagePath, fileContent)\n })\n })\n}\n\nexport async function addPluginsSections(basePath: string, plugins: Plugin[]) {\n const { tmpPluginsDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Adding plugin sections')\n\n const indexPluginsOverrides = plugins\n .filter((plugin) =>\n existsSync(\n getPackagePath(getPluginName(plugin), 'src', 'components', 'index.ts')\n )\n )\n .map((plugin) => {\n const pluginReference =\n sanitizePluginName(getPluginName(plugin), true) + 'Components'\n\n return {\n import: `import { default as ${pluginReference} } from 'src/plugins/${sanitizePluginName(getPluginName(plugin))}/components'`,\n pluginReference,\n }\n })\n\n const pluginsImportFileContent = `\n ${indexPluginsOverrides.map((plugin) => plugin.import).join('\\n')}\n\n export default {\n ${indexPluginsOverrides.map((plugin) => `...${plugin.pluginReference}`).join(',\\n')}\n }\n `\n\n const sectionPath = path.join(tmpPluginsDir, 'index.ts')\n writeFileSync(sectionPath, pluginsImportFileContent)\n logger.log('Writing plugins overrides')\n logger.log(sectionPath)\n logger.log(pluginsImportFileContent)\n}\n\nexport async function addPluginsOverrides(basePath: string, plugins: Plugin[]) {\n const { tmpPluginsDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Adding plugin overrides')\n\n plugins\n .map((plugin) => ({\n pluginName: getPluginName(plugin),\n pluginOverridesPath: getPackagePath(\n getPluginName(plugin),\n 'src',\n 'components',\n 'overrides'\n ),\n }))\n .filter(({ pluginOverridesPath }) => existsSync(pluginOverridesPath))\n .reverse()\n .forEach(({ pluginName, pluginOverridesPath }) => {\n const overrideFilesAlreadyCopied: string[] = []\n\n const sanitizedPluginName = sanitizePluginName(pluginName)\n\n const overrideFiles = readdirSync(pluginOverridesPath)\n\n overrideFiles\n .filter((file) => !overrideFilesAlreadyCopied.includes(file))\n .forEach((overrideFileName) => {\n const overrideFileContent = `export { override } from 'src/plugins/${sanitizedPluginName}/components/overrides/${overrideFileName.split('.')[0]}'`\n\n writeFileSync(\n path.join(tmpPluginsDir, 'overrides', overrideFileName),\n overrideFileContent\n )\n overrideFilesAlreadyCopied.push(overrideFileName)\n })\n })\n}\n\nconst addPluginsTheme = async (basePath: string, plugins: Plugin[]) => {\n const { getPackagePath, tmpThemesPluginsFile } = withBasePath(basePath)\n\n const pluginImportsContent = plugins\n .filter((plugin) =>\n existsSync(\n getPackagePath(getPluginName(plugin), 'src', 'themes', 'index.scss')\n )\n )\n .map(\n (plugin) => `@use \"${getPluginName(plugin)}/src/themes/index.scss\" as *;`\n )\n .join('\\n')\n\n writeFileSync(tmpThemesPluginsFile, pluginImportsContent)\n}\n\nconst getPluginAPIFileContent = (pluginName: string, apiName: string) => `\n// GENERATED FILE\n// @ts-nocheck\nimport apiHandle from 'src/plugins/${pluginName}/apis/${apiName}'\nimport { NextApiRequest, NextApiResponse } from \"next/types\"\n\nexport default function handle(req: NextApiRequest, res: NextApiResponse) {\n return apiHandle(req, res)\n}\n`\n\nconst generatePluginApis = async (basePath: string, plugins: Plugin[]) => {\n const { tmpApiDir, getPackagePath } = withBasePath(basePath)\n\n logger.log('Generating plugin APIs')\n\n plugins.forEach(async (plugin) => {\n const pluginName = getPluginName(plugin)\n const pluginConfigPath = getPackagePath(pluginName, PLUGIN_CONFIG_FILE)\n\n const { default: pluginConfig } = await import(\n pathToFileURL(pluginConfigPath).href\n )\n\n const { apis: apisCustom } = getPluginCustomConfig(plugin)\n\n const apisConfig: Record<string, APIConfig> = {\n ...(pluginConfig.apis ?? {}),\n ...apisCustom,\n }\n\n const apis = Object.keys(apisConfig)\n\n apis.forEach(async (apiName) => {\n const paths = apisConfig[apiName].path.split('/')\n\n const apiFile = paths.pop()\n const apiPaths = paths\n\n const apiPath = path.join(\n tmpApiDir,\n 'plugins',\n ...apiPaths,\n apiFile + '.ts'\n )\n\n const fileContent = getPluginAPIFileContent(\n sanitizePluginName(pluginName),\n apiName\n )\n\n mkdirSync(path.dirname(apiPath), { recursive: true })\n writeFileSync(apiPath, fileContent)\n })\n })\n}\n\nexport const installPlugins = async (basePath: string) => {\n const plugins = await getPluginsList(basePath)\n\n await copyPluginsSrc(basePath, plugins)\n copyPluginPublicFiles(basePath, plugins)\n generatePluginPages(basePath, plugins)\n generatePluginApis(basePath, plugins)\n addPluginsSections(basePath, plugins)\n addPluginsOverrides(basePath, plugins)\n addPluginsTheme(basePath, plugins)\n}\n","import path from 'node:path'\n\nconst IGNORED_STOREFRONT_BASENAMES = new Set([\n 'package.json',\n 'node_modules',\n 'cypress.config.ts',\n 'base.jsonc', // CP special file, it must not be copied to the merchants' temp dir\n 'test',\n '__tests__',\n])\n\nconst TEST_FILE_RE = /\\.(?:test|spec|browser\\.test)\\.(?:js|jsx|ts|tsx)$/\n\n/**\n * Storefront `.faststore` is a Next.js app, not a test runner. Skip unit-test\n * trees and files so `next build` does not type-check vitest fixtures the\n * store does not install.\n */\nexport function shouldCopyToStorefront(src: string): boolean {\n const name = path.basename(src)\n\n if (!name) {\n return true\n }\n\n if (IGNORED_STOREFRONT_BASENAMES.has(name)) {\n return false\n }\n\n if (TEST_FILE_RE.test(name)) {\n return false\n }\n\n return true\n}\n\n/**\n * Globs `next build` must not type-check inside `.faststore`. Besides the core\n * test trees, stores keep Storybook stories and Jest manual mocks next to\n * their components under `src/`; those are copied into\n * `.faststore/src/customizations/src` and would otherwise be compiled against\n * dev-only dependencies (`@storybook/*`, `@jest/globals`) the build does not\n * have.\n */\nexport const STOREFRONT_TEST_EXCLUDE_GLOBS = [\n 'test',\n '**/*.test.ts',\n '**/*.test.tsx',\n '**/*.spec.ts',\n '**/*.spec.tsx',\n '**/*.stories.ts',\n '**/*.stories.tsx',\n '**/__tests__/**',\n '**/__mocks__/**',\n] as const\n\ntype TsConfig = {\n include?: string[]\n exclude?: string[]\n compilerOptions?: Record<string, unknown>\n [key: string]: unknown\n}\n\n/**\n * Drop core/plugin test globs from the tsconfig copied into `.faststore`.\n * Defense in depth if a test file still lands under `src/`.\n */\nexport function prepareStorefrontTsConfig(tsConfig: TsConfig): TsConfig {\n const include = (tsConfig.include ?? []).filter(\n (pattern) => !String(pattern).startsWith('test/')\n )\n const exclude = Array.from(\n new Set([...(tsConfig.exclude ?? []), ...STOREFRONT_TEST_EXCLUDE_GLOBS])\n )\n\n return {\n ...tsConfig,\n include,\n exclude,\n }\n}\n","import chalk from 'chalk'\nimport path from 'node:path'\n// import { ux } from '@oclif/core'\nimport { confirm } from '@inquirer/prompts'\nimport fsExtra from 'fs-extra'\nconst { readFileSync, existsSync, writeFileSync, mkdirSync } = fsExtra\n\nimport { pathToFileURL } from 'node:url'\nimport { withBasePath } from './directory'\nimport { getPluginName, getPluginsList } from './plugins'\n\nexport interface ContentTypeOrSectionDefinition {\n id?: string\n name?: string\n scopes?: string[]\n isSingleton?: boolean\n onlySettings?: boolean\n requiredScopes?: string[]\n schema?: Record<string, unknown>\n configurationSchemaSets?: ConfigurationSchemaSet[]\n}\n\nexport interface ConfigurationSchemaSet {\n name?: string\n configurations?: Array<{\n name?: string\n schema?: Record<string, unknown>\n }>\n}\n\nexport function splitCustomDefinitions(\n coreDefinitions: ContentTypeOrSectionDefinition[],\n customDefinitions: ContentTypeOrSectionDefinition[],\n primaryIdentifier: 'id' | 'name'\n) {\n const coreDefinitionIdentifiers = new Set<string>(\n coreDefinitions.map((definition) => definition[primaryIdentifier] ?? '')\n )\n\n const duplicates: ContentTypeOrSectionDefinition[] = []\n const newDefinitions: ContentTypeOrSectionDefinition[] = []\n\n customDefinitions.forEach((definition) => {\n if (!definition[primaryIdentifier]) {\n console.error('Ignoring invalid definition:', definition)\n return\n }\n\n if (\n coreDefinitionIdentifiers.has(definition[primaryIdentifier] as string)\n ) {\n duplicates.push(definition)\n return\n }\n\n newDefinitions.push(definition)\n })\n\n return { duplicates, newDefinitions }\n}\n\nexport function dedupeAndMergeDefinitions(\n coreDefinitions: ContentTypeOrSectionDefinition[],\n duplicates: ContentTypeOrSectionDefinition[],\n primaryIdentifier: 'id' | 'name'\n) {\n const sortedCoreDefs = coreDefinitions.filter((definition) =>\n Boolean(definition[primaryIdentifier])\n )\n sortedCoreDefs.sort((a, b) =>\n (a[primaryIdentifier] as string) < (b[primaryIdentifier] as string) ? -1 : 1\n )\n\n const sortedDuplicates = duplicates.filter((definition) =>\n Boolean(definition[primaryIdentifier])\n )\n sortedDuplicates.sort((a, b) =>\n (a[primaryIdentifier] as string) < (b[primaryIdentifier] as string) ? -1 : 1\n )\n\n let duplicateIdx = 0\n\n const result = sortedCoreDefs.map((currentDefinition) => {\n const isDuplicateMatch =\n currentDefinition[primaryIdentifier] ===\n sortedDuplicates[duplicateIdx]?.[primaryIdentifier]\n\n if (duplicateIdx < sortedDuplicates.length && isDuplicateMatch) {\n return sortedDuplicates[duplicateIdx++]\n }\n\n return currentDefinition\n })\n\n return result\n}\n\nasync function confirmUserChoice(\n duplicates: ContentTypeOrSectionDefinition[],\n fileName: string\n) {\n const goAhead = await confirm({\n message: `You are about to override default ${\n fileName.split('.')[0]\n }:\\n\\n${duplicates\n .map((definition) => definition.id || definition.name)\n .join('\\n')}\\n\\nAre you sure? [yes/no]`,\n })\n\n if (!goAhead) {\n throw new Error('cms-sync cancelled by user.')\n }\n\n return\n}\n\nexport async function mergeCMSFile(fileName: string, basePath: string) {\n const {\n coreCMSDir,\n userCMSDir,\n tmpCMSDir,\n getPackagePath,\n userStoreConfigFile,\n } = withBasePath(basePath)\n\n const { default: userStoreConfig } = await import(\n pathToFileURL(path.resolve(userStoreConfigFile)).href\n )\n const cmsProjectName = userStoreConfig.contentSource?.project ?? 'faststore'\n\n const coreFilePath = path.join(coreCMSDir, fileName)\n const customFilePath = path.join(userCMSDir, fileName)\n\n const coreFile = readFileSync(coreFilePath, 'utf8')\n const coreDefinitions: ContentTypeOrSectionDefinition[] = JSON.parse(coreFile)\n\n const primaryIdentifierForDefinitions =\n fileName === 'content-types.json' ? 'id' : 'name'\n\n let output: ContentTypeOrSectionDefinition[] = coreDefinitions\n\n const plugins = await getPluginsList(basePath)\n\n const pluginCMSFilePaths = plugins.map((plugin) =>\n getPackagePath(getPluginName(plugin), 'cms', 'faststore', fileName)\n )\n\n const customizations = [...pluginCMSFilePaths, customFilePath].filter(\n (pluginCMSFilePath) => existsSync(pluginCMSFilePath)\n )\n\n // TODO: create a validation when the CMS files exist but don't have a component for them\n for (const newFilePath of customizations) {\n const customFile = readFileSync(newFilePath, 'utf8')\n\n try {\n const customDefinitions = JSON.parse(customFile)\n\n const { duplicates, newDefinitions } = splitCustomDefinitions(\n output,\n customDefinitions,\n primaryIdentifierForDefinitions\n )\n\n if (duplicates.length) {\n if (newFilePath === customFilePath) {\n await confirmUserChoice(duplicates, fileName)\n }\n\n output = [\n ...dedupeAndMergeDefinitions(\n output,\n duplicates,\n primaryIdentifierForDefinitions\n ),\n ...newDefinitions,\n ]\n } else {\n output = [...output, ...newDefinitions]\n }\n } catch (err) {\n if (err instanceof SyntaxError) {\n console.info(\n `${chalk.red(\n 'error'\n )} - ${fileName} is a malformed JSON file, ignoring its contents.`\n )\n } else {\n throw err\n }\n }\n }\n\n try {\n if (!existsSync(tmpCMSDir(cmsProjectName))) {\n mkdirSync(tmpCMSDir(cmsProjectName))\n }\n writeFileSync(\n path.join(tmpCMSDir(cmsProjectName), fileName),\n JSON.stringify(output)\n )\n console.log(\n `${chalk.green('success')} - CMS file ${chalk.dim(fileName)} created`\n )\n } catch (err) {\n console.error(`${chalk.red('error')} - ${err}`)\n }\n}\n\nexport async function mergeCMSFiles(basePath: string) {\n try {\n await mergeCMSFile('content-types.json', basePath)\n await mergeCMSFile('sections.json', basePath)\n } catch (err) {\n console.error(`${chalk.red('error')} - ${err}`)\n }\n}\n","/**\n * Preflight checks for the `vtex` toolbelt used by the CP flow of `cms-sync`.\n *\n * The CP flow shells out to `vtex content generate-schema`/`upload-schema`. If\n * the toolbelt is missing, the user is logged out, or logged into the wrong\n * account, those commands either fail opaquely or stall on an interactive login\n * prompt before the dev can answer the real schema prompts. Running these\n * checks first surfaces an actionable error (install / `vtex login` /\n * `vtex switch`) up front, against the store's `api.storeId`.\n */\nimport { execSync } from 'node:child_process'\nimport chalk from 'chalk'\nimport { logger } from './logger'\n\n/**\n * Runs a command capturing its merged stdout/stderr.\n * Returns null when the command fails to run or exits non-zero.\n */\nfunction runCapture(cmd: string): string | null {\n try {\n return execSync(`${cmd} 2>&1`, { stdio: 'pipe' }).toString()\n } catch {\n return null\n }\n}\n\n/** Whether the `vtex` toolbelt is available on the PATH. */\nexport function isVtexCliInstalled(): boolean {\n return runCapture('vtex --version') !== null\n}\n\n/**\n * Extracts the logged-in account from `vtex whoami` output.\n * Returns null when the output indicates a logged-out state or can't be parsed.\n *\n * Handles the toolbelt formats observed in practice, e.g.:\n * - \"Logged into brandless as user@vtex.com at workspace master\"\n * - \"user@vtex.com @ brandless / master\"\n */\nexport function parseAccountFromWhoami(output: string): string | null {\n if (/not logged|isn't logged|no user|please login/i.test(output)) {\n return null\n }\n\n const patterns = [\n /@\\s+([\\w.-]+)\\s*\\//, // \"user@vtex.com @ brandless / master\"\n /logged in(?:to)?\\s+(?:account\\s+)?([\\w.-]+)/i, // \"Logged into brandless ...\"\n /account[:\\s]+([\\w.-]+)/i, // \"... account brandless ...\"\n ]\n\n for (const pattern of patterns) {\n const match = output.match(pattern)\n if (match?.[1]) {\n return match[1]\n }\n }\n\n return null\n}\n\n/** Returns the account currently logged into the toolbelt, or null. */\nexport function getLoggedVtexAccount(): string | null {\n const output = runCapture('vtex whoami')\n\n if (!output) {\n return null\n }\n\n return parseAccountFromWhoami(output)\n}\n\n/**\n * Ensures the `vtex` toolbelt is installed and authenticated against the\n * store's account before running CP schema commands. Exits the process with an\n * actionable message when any check fails.\n *\n * @param account - The store account from `discovery.config.js` (`api.storeId`).\n */\nexport function assertVtexReadyForAccount(account?: string): void {\n if (!isVtexCliInstalled()) {\n logger.error(\n `${chalk.red('[Error]')} - The VTEX toolbelt (\\`vtex\\`) was not found. Install it with ${chalk.bold('npm i -g vtex')} and try again.\\n` +\n `${chalk.dim('Docs: https://developers.vtex.com/docs/guides/vtex-io-documentation-vtex-io-cli-installation-and-command-reference')}`\n )\n process.exit(1)\n return\n }\n\n const loggedAccount = getLoggedVtexAccount()\n const loginHint = account ? `vtex login ${account}` : 'vtex login <account>'\n\n if (!loggedAccount) {\n logger.error(\n `${chalk.red('[Error]')} - You are not logged into the VTEX toolbelt.\\n` +\n `${chalk.cyan('Required Action:')} log into the store account by running ${chalk.bold(loginHint)}.`\n )\n process.exit(1)\n return\n }\n\n if (account && loggedAccount.toLowerCase() !== account.toLowerCase()) {\n logger.error(\n `${chalk.red('[Error]')} - You are logged into ${chalk.bold(loggedAccount)}, but this store targets ${chalk.bold(account)} (\\`api.storeId\\` in discovery.config.js).\\n` +\n `${chalk.cyan('Required Action:')} switch accounts with ${chalk.bold(`vtex switch ${account}`)} or ${chalk.bold(loginHint)}.`\n )\n process.exit(1)\n }\n}\n","import fs from 'node:fs'\nimport degit from 'degit'\nimport { Args, Command } from '@oclif/core'\nimport { confirm } from '@inquirer/prompts'\n\nexport default class Create extends Command {\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the Discovery folder will be created. Defaults to ./discovery.',\n }),\n }\n\n static description =\n 'Creates a discovery folder based on the starter.store template.'\n\n static examples = ['$ yarn faststore create discovery']\n\n async run() {\n const { args } = await this.parse(Create)\n\n const discoveryPath = args.path ?? './discovery'\n const discoveryFolderExists = fs.existsSync(discoveryPath)\n\n if (discoveryFolderExists) {\n const confirmOverride = await confirm({\n message: `It looks like you already have a discovery folder named \"${discoveryPath}\" in your store. Do you want to override it?`,\n })\n\n if (!confirmOverride)\n return this.log('🛑 Interrupted initializing discovery')\n }\n\n const discoveryEmitter = degit('vtex-sites/starter.store', {\n force: true,\n })\n\n this.log('Pulling starter.store template...')\n\n discoveryEmitter.clone(discoveryPath).then(() => {\n this.log(\n `Discovery created successfully! You can find it at ${discoveryPath}`\n )\n })\n }\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport { spawn, spawnSync } from 'node:child_process'\nimport chokidar from 'chokidar'\nimport dotenv from 'dotenv'\n\nimport { cpSync, existsSync, readFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { withNodeModulesBins } from '../utils/binPaths'\nimport { getPreferredPackageManager } from '../utils/commands'\nimport { checkDeprecatedSecretFiles } from '../utils/deprecations'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\nimport { logger } from '../utils/logger'\nimport { runCommandSync } from '../utils/runCommandSync'\n\n/**\n * Taken from toolbelt\n *\n * https://github.com/vtex/toolbelt/pull/442\n */\nconst stabilityThreshold = process.platform === 'darwin' ? 100 : 200\n\nconst defaultPatterns = ['*/**', '**']\n\nconst defaultIgnored = [\n '.DS_Store',\n 'README.md',\n '.gitignore',\n 'package.json',\n '.git/**',\n '.faststore/**',\n '**/.faststore/**',\n]\n\nconst defaultNodeModulesIgnored = ['node_modules/**', '**/node_modules/**']\n\nconst defaultNodeModulesIgnoredExceptVtexPackages = [\n '**/node_modules/!(@vtex)/**',\n]\n\nconst devAbortController = new AbortController()\n\nasync function storeDev(\n rootDir: string,\n tmpDir: string,\n coreDir: string,\n port: number | string\n) {\n // Only try to read vtex.env if it exists\n let envVars = {}\n const vtexEnvPath = path.join(rootDir, 'vtex.env')\n\n if (existsSync(vtexEnvPath)) {\n try {\n envVars = dotenv.parse(readFileSync(vtexEnvPath))\n } catch (err) {\n logger.log(\n `${chalk.yellow('warn')} - Error parsing vtex.env file: ${err}`\n )\n }\n }\n\n const packageManager = await getPreferredPackageManager()\n\n runCommandSync({\n cmd: `${packageManager} predev`,\n errorMessage: `The \"predev\" step (\"${packageManager} predev\") failed inside the \".faststore\" directory. See the error output below for details.`,\n throws: 'error',\n cwd: tmpDir,\n env: withNodeModulesBins(tmpDir),\n })\n\n const { success } = copyGenerated(\n path.join(tmpDir, '@generated'),\n path.join(coreDir, '@generated')\n )\n\n if (!success) {\n logger.log(\n `${chalk.yellow('warn')} - Failed to copy @generated schema back to node_modules, autocomplete and DX might be impacted.`\n )\n logger.log(\n `Attempted to copy from ${path.join(tmpDir, '@generated')} to ${path.join(coreDir, '@generated')}`\n )\n }\n\n const devProcess = spawn(`${packageManager} dev-only --port ${port}`, {\n shell: true,\n cwd: tmpDir,\n signal: devAbortController.signal,\n stdio: ['inherit', 'pipe', 'inherit'],\n env: withNodeModulesBins(tmpDir, {\n ...process.env,\n ...envVars,\n }),\n })\n\n let nextStdout = ''\n devProcess.stdout.on('data', (chunk) => {\n nextStdout += chunk\n const lines = nextStdout.split('\\n')\n while (lines.length > 1) {\n const line = lines.shift()\n console.log('[DISCOVERY] ', line)\n }\n nextStdout = lines.shift() || ''\n })\n devProcess.stdout.on('end', () => {\n console.log('[DISCOVERY] ', nextStdout)\n })\n\n devProcess.on('close', () => {\n devAbortController.abort()\n })\n}\n\nfunction copyGenerated(from: string, to: string) {\n try {\n cpSync(from, to, { recursive: true, force: true, dereference: true })\n\n return { success: true }\n } catch (err) {\n return { success: false }\n }\n}\n\nexport default class Dev extends Command {\n static args = {\n account: Args.string({\n name: 'account',\n description:\n 'The account for which the Discovery is running. Currently noop.',\n }),\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being run is. Defaults to cwd.',\n }),\n port: Args.string({\n name: 'port',\n description: 'The port where FastStore should run. Defaults to 3000.',\n }),\n }\n\n static flags = {\n 'watch-plugins': Flags.boolean({\n description: 'Enable watching for plugin changes',\n default: false,\n }),\n }\n\n async run() {\n const { args, flags } = await this.parse(Dev)\n const basePath = getBasePath(args.path)\n\n const port = args.port ?? '3000'\n const watchPlugins = flags['watch-plugins']\n\n const { getRoot, tmpDir, coreDir } = withBasePath(basePath)\n\n checkDeprecatedSecretFiles(basePath)\n\n const queueChange = (/* path: string, remove: boolean */) => {\n generate({ basePath })\n }\n\n const watcher = chokidar.watch([...defaultPatterns], {\n atomic: stabilityThreshold,\n awaitWriteFinish: {\n stabilityThreshold,\n },\n cwd: getRoot(),\n ignoreInitial: true,\n ignored: [\n ...defaultIgnored,\n ...(watchPlugins\n ? defaultNodeModulesIgnoredExceptVtexPackages\n : defaultNodeModulesIgnored),\n ],\n persistent: true,\n usePolling: process.platform === 'win32',\n })\n\n devAbortController.signal.addEventListener('abort', () => {\n watcher.close()\n })\n\n await generate({ setup: true, basePath })\n\n const cliPath = fileURLToPath(\n import.meta.resolve('@faststore/cli/runner', import.meta.url)\n )\n\n spawnSync('node', [cliPath, 'generate-types', tmpDir], {\n stdio: 'inherit',\n })\n\n spawnSync('node', [cliPath, 'cache-graphql', basePath], {\n stdio: 'inherit',\n })\n\n // generate-i18n will validate localization config and check if it's enabled\n spawnSync('node', [cliPath, 'generate-i18n', basePath], {\n stdio: 'inherit',\n })\n\n storeDev(getRoot(), tmpDir, coreDir, port)\n\n return await new Promise((resolve, reject) => {\n watcher\n .on('add', (/*file*/) => queueChange(/*file, false*/))\n .on('change', (/*file*/) => queueChange(/*file, false*/))\n .on('unlink', (/*file*/) => queueChange(/*file, true*/))\n .on('error', () => {\n devAbortController.abort()\n reject()\n })\n .on('ready', resolve)\n })\n }\n}\n","import { Args, Command } from '@oclif/core'\nimport chalk from 'chalk'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\nimport { logger } from '../utils/logger'\nimport genTsTypes from '../utils/generate-types'\n\nexport default class Generate extends Command {\n static flags = {}\n\n static args = {\n path: Args.string({\n name: 'path',\n hidden: true,\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Generate)\n const basePath = getBasePath(args.path)\n const { tmpDir } = withBasePath(basePath)\n\n await generate({ setup: true, basePath })\n\n genTsTypes(args.path ?? tmpDir)\n\n logger.log(\n `${chalk.green(\n 'success'\n )} - GraphQL schema, types, and optimizations successfully generated 🎉`\n )\n }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nexport function saveFile(fileLocation: string) {\n fs.mkdirSync(path.dirname(fileLocation), { recursive: true })\n\n return (content: string) => {\n fs.writeFileSync(fileLocation, content)\n }\n}\n","import { saveFile } from './file'\nimport { GraphqlVtexSchema } from '@faststore/api'\nimport {\n generate as codegenGenerate,\n type CodegenConfig,\n} from '@graphql-codegen/cli'\nimport { mergeTypeDefs } from '@graphql-tools/merge'\nimport { printSchemaWithDirectives } from '@graphql-tools/utils'\nimport { buildASTSchema, Kind, parse, type DocumentNode } from 'graphql'\nimport fs, { existsSync } from 'node:fs'\nimport path from 'node:path'\n\nconst schemaFileName = 'schema.graphql'\n\nexport default async function genTsTypes(at: string) {\n await generateSchemaFile(at)\n await generateSchemaTSTypes(at)\n}\n\n/**\n * Codegen pointers (documents glob, schema and output dir) for a project root.\n *\n * They are expressed relative to `cwd` — the directory graphql-codegen resolves\n * pointers from — instead of as absolute paths. `@graphql-tools/load` treats a\n * pointer that contains whitespace and is not a parseable SDL as a broken\n * inline document and throws, so an absolute glob under e.g.\n * `/Users/me/My Store/.faststore` made `faststore build` fail with\n * \"Failed to parse the GraphQL document\". The relative form never includes the\n * parent directories, so it is unaffected by their names.\n */\nexport async function getCodegenPointers(\n root: string,\n cwd: string = process.cwd()\n) {\n const globbyImport = (await import('globby')) as GlobbyModule & {\n default?: GlobbyModule\n }\n const globbyModule = globbyImport.default ?? globbyImport\n\n let finalRootPath = path.resolve(root)\n\n if (existsSync(path.resolve(root, '.faststore'))) {\n finalRootPath = path.resolve(root, '.faststore')\n }\n\n // resolve symlinks on both sides (e.g. /var -> /private/var on macOS) so the\n // relative path does not climb back through the parent directories\n const realCwd = realpathIfExists(cwd)\n const relativeTo = (target: string) =>\n path.relative(realCwd, realpathIfExists(target)) || '.'\n\n // globs must use forward slashes on every platform, and glob-special\n // characters in the relative segments (e.g. parentheses) must be escaped\n const toPattern = (target: string) =>\n globbyModule.convertPathToPattern(relativeTo(target))\n\n // plain relative path (no glob escaping): this one is used as a file path\n const toRelativePath = (target: string) =>\n relativeTo(target).split(path.sep).join('/')\n\n return {\n // glob to include all ts/tsx files\n documents: [`${toPattern(path.join(finalRootPath, 'src'))}/**/*.{ts,tsx}`],\n schema: toRelativePath(\n path.join(finalRootPath, '@generated', schemaFileName)\n ),\n // trailing slash: tells the client preset the output is a folder\n outputDir: `${toRelativePath(path.join(finalRootPath, '@generated'))}/`,\n }\n}\n\n/**\n * `fs.realpathSync` for paths that may not exist yet (e.g. `@generated` before\n * the first run): resolves the closest existing ancestor and re-appends the\n * missing tail.\n */\nfunction realpathIfExists(target: string): string {\n const missing: string[] = []\n let current = path.resolve(target)\n\n while (!existsSync(current)) {\n const parent = path.dirname(current)\n\n if (parent === current) {\n return path.resolve(target)\n }\n\n missing.unshift(path.basename(current))\n current = parent\n }\n\n return path.join(fs.realpathSync.native(current), ...missing)\n}\n\nasync function generateSchemaTSTypes(root: string) {\n const { documents, schema, outputDir } = await getCodegenPointers(root)\n\n const config: CodegenConfig = {\n documents,\n overwrite: true,\n errorsOnly: false,\n debug: false,\n verbose: true,\n schema,\n generates: {\n [outputDir]: {\n preset: 'client',\n config: {\n /** Not all of these properties are supported by the preset, but it reflects our previous config when we used typescript plugins directly */\n preResolveTypes: true,\n avoidOptionals: true,\n enumsAsTypes: true,\n skipTypeNameForRoot: true,\n skipTypename: true,\n allowEnumStringTypes: false,\n flattenGeneratedTypes: true,\n namingConvention: 'change-case-all#pascalCase',\n exportFragmentSpreadSubTypes: true,\n /** Removes useless AST definitions from documents */\n documentMode: 'string',\n },\n presetConfig: {\n // Disabled fragment masking - it wasn't being used by us. This can be reviewed in the future\n fragmentMasking: false,\n // Recognizes the gql(`query { ... }`) calls and generates the types for them\n gqlTagName: 'gql',\n onExecutableDocumentNode: (document: DocumentNode) => ({\n // This makes sure that the operation name is always present in the __meta__ field of each query\n // This helps us to identify the query in the persisted documents and to debug errors in the client\n operationName: getOperationName(document),\n }),\n persistedDocuments: {\n // Keeps document simple, including only necessary properties as '__meta__' and its properties\n mode: 'replaceDocumentWithHash',\n // replaces operation['__meta__']['hash'] with operation['__meta__']['operationHash']\n hashPropertyName: 'operationHash',\n },\n },\n },\n },\n }\n\n return codegenGenerate(config, true)\n}\n\nfunction getOperationName(document: DocumentNode) {\n for (const definition of document.definitions) {\n if (\n definition.kind === Kind.OPERATION_DEFINITION &&\n typeof definition.name?.value === 'string'\n ) {\n return definition.name.value\n }\n }\n\n return 'UnknownOperation'\n}\n\nasync function generateSchemaFile(rootPath: string) {\n const faststoreSchema = printSchemaWithDirectives(GraphqlVtexSchema())\n\n const getMergedSchema = async () => {\n const root = path.join(\n rootPath.endsWith('.faststore') ? [rootPath, '..'].join('/') : rootPath\n )\n\n const customizations = [\n ...(await getTypeDefsFromFolder(root, 'vtex')),\n ...(await getTypeDefsFromFolder(root, 'thirdParty')),\n ]\n try {\n const mergedTypeDefs = mergeTypeDefs(\n [faststoreSchema, ...customizations].filter(Boolean)\n )\n\n return buildASTSchema(mergedTypeDefs)\n } catch (e) {\n console.error(\n 'An error occurred while attempting to merge the GraphQL Schema Extensions. Check the custom typeDefs and resolvers located in the \"customizations/graphql/\" directory. The changes since the last successful schema merge will be ignored.'\n )\n\n throw e\n }\n }\n\n let pathToSave = path.resolve(rootPath, '@generated', schemaFileName)\n\n if (existsSync(path.resolve(rootPath, '.faststore'))) {\n pathToSave = path.resolve(\n rootPath,\n '.faststore',\n '@generated',\n schemaFileName\n )\n }\n\n const saveSchemaFile = saveFile(pathToSave)\n const finalSchema = printSchemaWithDirectives(await getMergedSchema())\n\n saveSchemaFile(finalSchema)\n}\n\ntype GlobbyModule = typeof import('globby')\n\nexport async function getTypeDefsFromFolder(\n root: string,\n customPath: string | string[]\n) {\n const globbyImport = (await import('globby')) as GlobbyModule & {\n default?: GlobbyModule\n }\n const globbyModule = globbyImport.default ?? globbyImport\n const basePath = [root, 'src', 'graphql']\n\n const pathArray = Array.isArray(customPath) ? customPath : [customPath]\n\n // globby patterns must use forward slashes — on Windows, path.join produces\n // backslashes, which globby treats as escape characters and matches nothing\n const pattern = globbyModule.convertPathToPattern(\n path.join(...basePath, ...pathArray)\n )\n\n // spell out the glob instead of using expandDirectories: it stats the\n // escaped pattern string, so it never expands paths that needed escaping\n // (e.g. parentheses in a parent directory name)\n return globbyModule\n .globbySync(`${pattern}/**/*.graphql`)\n .map((typeDef: string) =>\n parse(fs.readFileSync(typeDef, { encoding: 'utf-8' }))\n )\n}\n","import { Args, Command } from '@oclif/core'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { getBasePath } from '../utils/directory'\n\nexport default class Prepare extends Command {\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being run is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Prepare)\n const basePath = getBasePath(args.path)\n\n const clientPublicDir = path.join(basePath, 'public/')\n\n const corePublicDir = path.resolve(\n fileURLToPath(\n path.dirname(import.meta.resolve('@faststore/core', import.meta.url))\n ),\n 'public'\n )\n\n if (!corePublicDir) {\n throw Error('Please install @faststore/core package')\n }\n\n copyFolder(corePublicDir, clientPublicDir)\n }\n}\n\nfunction copyFolder(sourceDir: string, targetDir: string) {\n // Ensure target directory exists\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true })\n }\n\n // Read all items in the source directory\n const files = fs.readdirSync(sourceDir)\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file)\n const targetPath = path.join(targetDir, file)\n\n const stat = fs.statSync(sourcePath)\n\n if (stat.isFile()) {\n // Copy file\n fs.copyFileSync(sourcePath, targetPath)\n console.log(`Copied file: ${sourcePath} -> ${targetPath}`)\n } else if (stat.isDirectory()) {\n // Recursively copy subfolder\n copyFolder(sourcePath, targetPath)\n }\n }\n}\n","import { Args, Command } from '@oclif/core'\nimport { spawn, spawnSync } from 'node:child_process'\nimport fsExtra from 'fs-extra'\nimport path from 'node:path'\nimport { resolvePackageManager } from '../utils/commands'\nimport { getBasePath, withBasePath } from '../utils/directory'\n\nconst { existsSync } = fsExtra\n\n/** Validated package-manager argv only — never a shell string. */\nfunction spawnPackageManagerSync(bin: string, args: string[]) {\n return spawnSync(bin, args, { stdio: 'inherit' }) // NOSONAR\n}\n\nfunction spawnPackageManager(bin: string, args: string[]) {\n return spawn(bin, args, { stdio: 'inherit' }) // NOSONAR\n}\n\nexport default class Start extends Command {\n static args = {\n account: Args.string({\n description:\n 'The account for which the Discovery is running. Currently noop.',\n }),\n path: Args.string({\n description:\n 'The path where the FastStore being run is. Defaults to cwd.',\n }),\n port: Args.string({\n description: 'The port where FastStore should run. Defaults to 3000.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Start)\n const basePath = getBasePath(args.path)\n const port = args.port ?? 3000\n const { getRoot, tmpDir } = withBasePath(basePath)\n const { argv } = await resolvePackageManager(basePath)\n const [bin, ...runnerArgs] = argv\n\n if (!existsSync(path.join(getRoot(), '.next'))) {\n // argv is a validated package-manager binary (plus optional Volta\n // prefix), never a shell string — keep this off a shell so the original\n // FAS-1199 prompt leak cannot reach sh.\n const build = spawnPackageManagerSync(bin, [\n ...runnerArgs,\n 'faststore',\n 'build',\n ])\n\n if (build.status !== 0) {\n throw new Error(\n `\"${[bin, ...runnerArgs].join(' ')} faststore build\" failed, so there is no build to serve.`\n )\n }\n }\n\n return spawnPackageManager(bin, [\n ...runnerArgs,\n 'next',\n 'start',\n tmpDir,\n '-p',\n String(port),\n ])\n }\n}\n","import { Args, Command } from '@oclif/core'\nimport { spawn } from 'node:child_process'\nimport chokidar from 'chokidar'\n\nimport { withNodeModulesBins } from '../utils/binPaths'\nimport { getPreferredPackageManager } from '../utils/commands'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { generate } from '../utils/generate'\n\n/**\n * Taken from toolbelt\n *\n * https://github.com/vtex/toolbelt/pull/442\n */\nconst stabilityThreshold = process.platform === 'darwin' ? 100 : 200\n\nconst defaultPatterns = ['*/**', '**']\n\nconst defaultIgnored = [\n '.DS_Store',\n 'README.md',\n '.gitignore',\n 'package.json',\n 'node_modules/**',\n '**/node_modules/**',\n '.git/**',\n '.faststore/**',\n '**/.faststore/**',\n]\n\nconst testAbortController = new AbortController()\n\nasync function storeTest(tmpDir: string) {\n const packageManager = await getPreferredPackageManager()\n\n const testProcess = spawn(`${packageManager} run test:e2e`, {\n shell: true,\n cwd: tmpDir,\n signal: testAbortController.signal,\n stdio: 'inherit',\n env: withNodeModulesBins(tmpDir),\n })\n\n testProcess.on('close', () => {\n testAbortController.abort()\n })\n}\n\nexport default class Test extends Command {\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being tested is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Test)\n const basePath = getBasePath(args.path)\n const { getRoot, tmpDir } = withBasePath(basePath)\n\n const watcher = chokidar.watch([...defaultPatterns], {\n atomic: stabilityThreshold,\n awaitWriteFinish: {\n stabilityThreshold,\n },\n cwd: getRoot(),\n ignoreInitial: true,\n ignored: defaultIgnored,\n persistent: true,\n usePolling: process.platform === 'win32',\n })\n\n testAbortController.signal.addEventListener('abort', () => {\n watcher.close()\n })\n\n await generate({ setup: true, basePath })\n\n storeTest(tmpDir)\n\n return await new Promise((resolve, reject) => {\n watcher\n .on('error', () => {\n testAbortController.abort()\n reject()\n })\n .on('ready', resolve)\n })\n }\n}\n","import path from 'node:path'\nimport { Args, Command } from '@oclif/core'\nimport chalk from 'chalk'\nimport { logger } from '../utils/logger'\nimport genTsTypes from '../utils/generate-types'\n\nexport default class Generate extends Command {\n static hidden = true\n static flags = {}\n\n static args = {\n path: Args.string({\n name: 'path',\n required: true,\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args } = await this.parse(Generate)\n\n await genTsTypes(\n path.isAbsolute(args.path)\n ? args.path\n : path.resolve(process.env.PWD ?? process.cwd(), args.path)\n )\n\n logger.log(\n `${chalk.green(\n 'success'\n )} - GraphQL schema, types, and optimizations successfully generated 🎉`\n )\n }\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport chalk from 'chalk'\nimport fsExtra from 'fs-extra'\nimport graphql from 'graphql'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { saveFile } from '../utils/file'\nimport { logger } from '../utils/logger'\n\nconst { Kind, OperationTypeNode, parse: parseGraphql } = graphql\n\nconst persistedDocumentsName = 'persisted-documents.json'\nconst configFileName = 'discovery.config.default.js'\nconst cachedOperationsFileName = 'cached-operations.json'\n\nexport default class CacheGraphql extends Command {\n static flags = {\n queries: Flags.string({\n name: 'queries',\n description: 'The path to locate persisted-document file.',\n }),\n config: Flags.string({\n name: 'config',\n description: 'The path where the discovery.config is located',\n }),\n }\n\n static args = {\n store: Args.string({\n name: 'store',\n description:\n 'The path where the FastStore being built is or the persisted-document path. Defaults to cwd.',\n }),\n }\n\n async run() {\n const { args, flags } = await this.parse(CacheGraphql)\n\n const rootPath = getBasePath()\n const argPath =\n (args?.store && path.resolve(rootPath, args.store)) || rootPath\n const { tmpDir } = withBasePath(argPath)\n const configPath =\n this.getConfigFile(flags.config && path.resolve(argPath, flags.config)) ||\n this.getConfigFile(tmpDir) ||\n this.getConfigFile(argPath)\n const persistedDocumentsPath =\n this.getPersistedDocument(\n (flags?.queries && path.resolve(argPath, flags?.queries)) || argPath\n ) || this.getPersistedDocument(tmpDir)\n if (!configPath) {\n return this.errorFileNotFound(\n configFileName,\n `\\n ${tmpDir}\\n ${argPath}`\n )\n }\n\n if (!persistedDocumentsPath) {\n return this.errorFileNotFound(\n persistedDocumentsName,\n flags?.queries ?? argPath\n )\n }\n\n const cachedOperationsPath = path.join(\n path.dirname(persistedDocumentsPath),\n cachedOperationsFileName\n )\n const saveCachedOperationsFile = saveFile(cachedOperationsPath)\n\n if (fsExtra.pathExistsSync(tmpDir))\n logger.info(`${chalk.blue('[Info]')} - .faststore Path at: ${tmpDir}`)\n\n logger.info(`${chalk.blue('[Info]')} - Config file location: ${configPath}`)\n logger.info(\n `${chalk.blue('[Info]')} - Persisted documents at: ${persistedDocumentsPath}`\n )\n logger.info(\n `${chalk.blue('[Info]')} - Cached operations output: ${cachedOperationsPath}`\n )\n\n const { default: persistedDocuments } = await import(\n pathToFileURL(persistedDocumentsPath).href,\n { with: { type: 'json' } }\n )\n\n const cachedQueries = getQueries(persistedDocuments)\n\n saveCachedOperationsFile(\n `${JSON.stringify(cachedQueries ?? [], null, 2)}\\n`\n )\n\n logger.info(\n `${chalk.green('[Success]')} - GraphQL queries cached with success: 🎉\n Queries: ${cachedQueries.join(', ')}`\n )\n }\n\n getPersistedDocument(rootPath?: string) {\n return this.getFile(persistedDocumentsName, [\n '@generated',\n persistedDocumentsName,\n ])(rootPath)\n }\n\n getConfigFile(rootPath?: string) {\n return this.getFile(configFileName, [configFileName])(rootPath)\n }\n\n getFile(fileName: string, pathFromRoot?: string | Array<string>) {\n return (rootPath?: string) => {\n switch (true) {\n case !rootPath:\n return\n case rootPath?.endsWith(fileName) && fsExtra.existsSync(rootPath):\n return rootPath\n case fsExtra.existsSync(path.join(rootPath ?? '', fileName)):\n return path.join(rootPath, fileName)\n default:\n if (!pathFromRoot) return\n\n const filePath = path.join(\n rootPath,\n ...(Array.isArray(pathFromRoot) ? pathFromRoot : [pathFromRoot])\n )\n\n if (fsExtra.existsSync(filePath)) {\n return filePath\n }\n return\n }\n }\n }\n\n errorFileNotFound(fileName: string, rootDir: string) {\n logger.error(\n `${chalk.red('[Error]')} - Couldn't find ${fileName} at ${rootDir}`\n )\n\n process.exit(1)\n }\n}\n\nconst getQueries = (persistedDocuments: Record<string, string>) => {\n const operationNames: Array<string> = []\n for (const operation of Object.values(persistedDocuments)) {\n let currentNames: Array<string> = []\n const operationAST = parseGraphql(operation)\n const hasMutationDefinition = operationAST.definitions.some(\n (def) =>\n def.kind === Kind.OPERATION_DEFINITION &&\n def.operation === OperationTypeNode.MUTATION\n )\n\n if (hasMutationDefinition) continue\n\n operationAST.definitions.forEach((definition) => {\n if (\n definition.kind === Kind.OPERATION_DEFINITION &&\n definition.operation === OperationTypeNode.QUERY &&\n definition.name?.kind === Kind.NAME &&\n !!definition.name?.value\n ) {\n currentNames.push(definition.name.value)\n return\n }\n })\n\n if (currentNames.length) {\n operationNames.push(...currentNames)\n currentNames = []\n }\n }\n\n return operationNames\n}\n","import { Args, Command, Flags } from '@oclif/core'\nimport { FastStoreSDK } from '@vtex/faststore-sdk'\nimport chalk from 'chalk'\nimport dotenv from 'dotenv'\nimport fsExtra from 'fs-extra'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { format } from 'prettier'\nimport { checkAndValidateLocalization } from '../utils/config'\nimport { getBasePath, withBasePath } from '../utils/directory'\nimport { saveFile } from '../utils/file'\nimport { logger } from '../utils/logger'\nimport { pathToFileURL } from 'node:url'\n\nconst configFileName = 'discovery.config.default.js'\n\nexport default class GenerateI18n extends Command {\n static hidden = true\n\n static flags = {\n config: Flags.string({\n name: 'config',\n description: 'The path where the discovery.config is located',\n }),\n }\n\n static args = {\n path: Args.string({\n name: 'path',\n description:\n 'The path where the FastStore being built is. Defaults to cwd.',\n }),\n }\n\n getConfigFile(rootPath?: string) {\n return this.getFile(configFileName, [configFileName])(rootPath)\n }\n\n getFile(fileName: string, pathFromRoot?: string | Array<string>) {\n return (rootPath?: string) => {\n switch (true) {\n case !rootPath:\n return\n case rootPath?.endsWith(fileName) && fsExtra.existsSync(rootPath):\n return rootPath\n case fsExtra.existsSync(path.join(rootPath ?? '', fileName)):\n return path.join(rootPath, fileName)\n default:\n if (!pathFromRoot) return\n\n const filePath = path.join(\n rootPath,\n ...(Array.isArray(pathFromRoot) ? pathFromRoot : [pathFromRoot])\n )\n\n if (fsExtra.existsSync(filePath)) {\n return filePath\n }\n return\n }\n }\n }\n\n errorFileNotFound(fileName: string, rootDir: string) {\n logger.error(\n `${chalk.red('[Error]')} - Couldn't find ${fileName} at ${rootDir}`\n )\n\n process.exit(1)\n }\n\n async run() {\n const { args, flags } = await this.parse(GenerateI18n)\n const rootPath = getBasePath()\n const argPath =\n (args?.path && path.resolve(rootPath, args.path)) || rootPath\n\n // Check if localization is enabled and contentSource is set to CP\n const localizationEnabled = await checkAndValidateLocalization(argPath)\n\n if (!localizationEnabled) {\n return\n }\n\n const vtexEnvPath = path.join(argPath, 'vtex.env')\n if (existsSync(vtexEnvPath)) {\n dotenv.config({ path: vtexEnvPath })\n }\n\n const { VTEX_ACCOUNT, FS_DISCOVERY_APP_KEY, FS_DISCOVERY_APP_TOKEN } =\n process.env\n const hasCredentials =\n VTEX_ACCOUNT && FS_DISCOVERY_APP_KEY && FS_DISCOVERY_APP_TOKEN\n\n if (!hasCredentials) {\n logger.error(`${chalk.red('[Error]')} - Missing VTEX credentials.\\n\n ${chalk.cyan('Required Action:')}\\n\n Check your FastStore WebOps Settings page - to work in production, it should contain the following variables: ${chalk.cyan('VTEX_ACCOUNT')}, ${chalk.cyan('FS_DISCOVERY_APP_KEY')}, ${chalk.cyan('FS_DISCOVERY_APP_TOKEN')}.\\n\n If running locally, please check your ${chalk.bold('vtex.env')} file, it should also contain those variables.\n `)\n\n process.exit(1)\n }\n\n const { tmpDir } = withBasePath(argPath)\n const configPath =\n this.getConfigFile(flags.config && path.resolve(argPath, flags.config)) ||\n this.getConfigFile(tmpDir) ||\n this.getConfigFile(argPath)\n\n if (!configPath) {\n return this.errorFileNotFound(\n configFileName,\n `\\n ${tmpDir}\\n ${argPath}`\n )\n }\n\n const saveConfigFile = saveFile(configPath)\n\n if (fsExtra.pathExistsSync(tmpDir))\n logger.info(`${chalk.blue('[Info]')} - .faststore Path at: ${tmpDir}`)\n\n logger.info(`${chalk.blue('[Info]')} - Config file location: ${configPath}`)\n const discoveryConfig = await import(pathToFileURL(configPath).href)\n\n const faststore = new FastStoreSDK({\n account: VTEX_ACCOUNT,\n appKey: FS_DISCOVERY_APP_KEY,\n appToken: FS_DISCOVERY_APP_TOKEN,\n })\n\n const settings = await faststore.locales()\n const currentConfig = discoveryConfig?.default ?? discoveryConfig\n\n saveConfigFile(\n await format(\n `module.exports = ${JSON.stringify(\n {\n ...currentConfig,\n localization: {\n ...(currentConfig?.localization ?? {}),\n ...settings,\n },\n },\n undefined,\n 2\n )}`,\n {\n parser: 'typescript',\n quoteProps: 'as-needed',\n }\n )\n )\n\n logger.info(\n `${chalk.green('success')} - i18n configuration successfully generated 🎉`\n )\n }\n}\n"],"mappings":";AAAA,SAAS,WAAW;;;ACApB,SAAS,MAAM,SAAS,aAAa;AACrC,OAAOA,YAAW;AAClB,SAAS,iBAAiB;AAC1B,SAAS,cAAAC,mBAAkB;AAC3B,OAAOC,cAAa;AACpB,OAAOC,WAAU;AACjB,SAAS,iBAAAC,gBAAe,qBAAqB;;;ACN7C,OAAO,aAAa;AACpB,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AAEjB,IAAM,EAAE,WAAW,IAAI;AAkBhB,SAAS,kBACd,WACA,SACoB;AACpB,MAAI;AAGF,WAAO,cAAc,KAAK,KAAK,SAAS,SAAS,CAAC,EAAE,QAAQ,SAAS;AAAA,EACvE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,eAAe,SAAiB;AACvC,QAAM,UAAoB,CAAC;AAC3B,MAAI,aAAa,KAAK,QAAQ,OAAO;AAErC,SAAO,MAAM;AACX,UAAM,SAAS,KAAK,KAAK,YAAY,gBAAgB,MAAM;AAE3D,QAAI,WAAW,MAAM,GAAG;AACtB,cAAQ,KAAK,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AQ,CAAC,4BAA4B,UAAU,EAAE;AAC3E,UAAM,kBAAkB,MAAM,OAAOP,eAAc,UAAU,EAAE;AAE/D,UAAM,YAAY,IAAI,aAAa;AAAA,MACjC,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,IACZ,CAAC;AAED,UAAM,WAAW,MAAM,UAAU,QAAQ;AACzC,UAAM,gBAAgB,iBAAiB,WAAW;AAElD;AAAA,MACE,MAAM;AAAA,QACJ,oBAAoB,KAAK;AAAA,UACvB;AAAA,YACE,GAAG;AAAA,YACH,cAAc;AAAA,cACZ,GAAI,eAAe,gBAAgB,CAAC;AAAA,cACpC,GAAG;AAAA,YACL;AAAA,UACF;AAAA,UACA;AAAA,UACA;AAAA,QACF,CAAC;AAAA,QACD;AAAA,UACE,QAAQ;AAAA,UACR,YAAY;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,GAAGO,QAAM,MAAM,SAAS,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;;;A/BhJO,IAAM,WAAW;AAAA,EACtB,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,KAAK;AAAA,EACL,OAAO;AAAA,EACP,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,UAAU;AAAA,EACV,kBAAkBG;AAAA,EAClB,iBAAiB;AAAA,EACjB,iBAAiB;AACnB;","names":["chalk","existsSync","fsExtra","path","fileURLToPath","existsSync","existsSync","existsSync","chalk","existsSync","chalk","path","fsExtra","chalk","path","fileURLToPath","existsSync","pkg","Args","Command","Flags","chalk","existsSync","path","pathToFileURL","chalk","existsSync","path","pathToFileURL","chalk","path","existsSync","pathToFileURL","chalk","existsSync","path","chalk","chalk","path","existsSync","chalk","chalk","fsExtra","path","pathToFileURL","fs","path","chalk","fs","path","chalk","chalk","chalk","fsExtra","path","pathToFileURL","path","copySync","existsSync","mkdirSync","readdirSync","fsExtra","pathToFileURL","path","copySync","existsSync","readdirSync","removeSync","writeFileSync","fsExtra","chalk","path","pathToFileURL","chalk","path","fsExtra","pathToFileURL","readFileSync","existsSync","writeFileSync","mkdirSync","fsExtra","pathToFileURL","path","chalk","execSync","chalk","execSync","chalk","Command","Flags","Args","existsSync","pathToFileURL","path","chalk","fs","Args","Command","confirm","Args","Command","Flags","chalk","spawn","spawnSync","cpSync","existsSync","readFileSync","path","fileURLToPath","path","existsSync","readFileSync","chalk","spawn","cpSync","Command","Args","Flags","fileURLToPath","spawnSync","Args","Command","chalk","fs","path","fs","existsSync","path","Command","Args","chalk","Args","Command","fs","path","fileURLToPath","Command","Args","path","fileURLToPath","fs","Args","Command","spawn","spawnSync","fsExtra","path","existsSync","fsExtra","spawnSync","spawn","Command","Args","path","Args","Command","spawn","chokidar","stabilityThreshold","defaultPatterns","defaultIgnored","spawn","Command","Args","chokidar","path","Args","Command","chalk","Generate","Command","Args","path","chalk","Args","Command","Flags","chalk","fsExtra","path","pathToFileURL","Kind","configFileName","Command","Flags","Args","path","fsExtra","chalk","pathToFileURL","Args","Command","Flags","chalk","dotenv","fsExtra","existsSync","path","pathToFileURL","configFileName","Command","Flags","Args","fsExtra","path","chalk","existsSync","dotenv","Generate"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faststore/cli",
3
- "version": "4.8.0-dev.5",
3
+ "version": "4.8.0-dev.7",
4
4
  "description": "FastStore CLI",
5
5
  "author": "Emerson Laurentino @emersonlaurentino",
6
6
  "type": "module",
@@ -44,8 +44,8 @@
44
44
  "oclif": "^4",
45
45
  "ora": "5.4.1",
46
46
  "prettier": "^3.1.0",
47
- "@faststore/api": "4.8.0-dev.5",
48
- "@faststore/core": "4.8.0-dev.5"
47
+ "@faststore/api": "4.8.0-dev.7",
48
+ "@faststore/core": "4.8.0-dev.7"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@types/degit": "^2.8.6",