import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import execa from 'execa' import type { Options as ExecaOptions } from 'execa' import prompts from 'prompts' import { getOutputPath } from './paths.mts' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) export async function applyCodemod(codemod: string, target: string) { const args = [ '--fail-on-error', '-t', // These commands run with `shell: true`, so the paths have to be quoted // to survive shell parsing when they contain spaces (the CI test projects // deliberately live in paths with spaces) `"${path.resolve(__dirname, 'codemods', codemod)}"`, `"${target}"`, '--parser', 'tsx', '--verbose=2', ] const result = await exec( 'yarn jscodeshift', args, getExecaOptions(path.resolve(import.meta.dirname)), ) // jscodeshift exits with code 0 even when the target path doesn't exist or // no files were modified, which would leave the project silently // unconverted. All codemods here are expected to modify their target file. if (/\b0 ok\b/.test(result.stdout)) { throw new Error( `Codemod ${codemod} did not modify ${target}:\n` + `${result.stdout}\n${result.stderr}`, ) } return result } export const getExecaOptions = ( cwd: string, stdio: 'inherit' | 'pipe' = 'pipe', ): ExecaOptions => { // Yarn sets PROJECT_CWD which causes @cedarjs/web/dist/bins/cedar.js to // chdir to the Yarn project root, overriding our explicit cwd. Unset it so // that the child process inherits our intended working directory. // // Yarn also sets npm_config_user_agent, which getPackageManager() trusts // over the target directory's own lockfiles. When this script is invoked // via `yarn rebuild-test-project-fixture --pm npm/pnpm`, that leaked agent // makes nested tools (cfw's script dispatch, the CLI's internal // ` cedar prisma generate` spawn, ...) pick yarn inside npm/pnpm // projects. Unset it so detection falls back to lockfiles, which are // correct both in the framework repo (yarn) and in the test project. // // Database URLs from the caller's shell take precedence over the test // project's .env files. They're unset so every Prisma command, including // `migrate reset`, runs against the generated project's own database const droppedEnvVars = [ 'PROJECT_CWD', 'npm_config_user_agent', 'DATABASE_URL', 'DIRECT_DATABASE_URL', ] const env = Object.fromEntries( Object.entries(process.env).filter( ([key]) => !droppedEnvVars.includes(key), ), ) env.RW_PATH = path.join(__dirname, '../../') env.CFW_PATH = path.join(__dirname, '../../') env.RWFW_PATH = path.join(__dirname, '../../') return { shell: true, stdio, cleanup: true, cwd, env, extendEnv: false, } } /** * Returns a copy of `options` whose env carries consent for Prisma's AI-agent * guard, so `prisma migrate reset` can run unattended under agents like * Claude Code. A value the caller already set in `process.env` is kept as-is. */ export function withPrismaResetConsent(options: T): T { if ('PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION' in process.env) { return options } // The test-project scripts only ever reset the database of a freshly // generated, throwaway project (SQLite, or a newly provisioned Neon database // for the live project), so there is no real data to lose return { ...options, env: { ...options.env, PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION: "Cedar's test-project script is resetting the database of a freshly " + 'generated, throwaway test project.', }, } } // Confirmation prompt when using --no-copyFromFixture --no-link' export async function confirmNoFixtureNoLink( copyFromFixtureOption: boolean, linkOption: boolean, ) { if (!copyFromFixtureOption && !linkOption) { const { checkNoLink } = await prompts( { type: 'confirm', name: 'checkNoLink', message: 'WARNING: You are building a raw project without the `--link` option.' + '\nThe new test-project will NOT build with templates from this branch.' + '\nInstead it will build using latest release generator template code.' + '\nIf not intended, exit and add the `--link` option.' + '\nOtherwise, enter "(y)es" to continue:', }, { onCancel: () => { process.exit(1) }, }, ) return checkNoLink } } export class ExecaError extends Error { stdout: string stderr: string exitCode: number constructor({ stdout, stderr, exitCode, }: { stdout: string stderr: string exitCode: number }) { super(`execa failed with exit code ${exitCode}`) this.stdout = stdout this.stderr = stderr this.exitCode = exitCode } } export async function exec( file: string, args?: string[], options?: ExecaOptions, ) { return execa(file, args ?? [], options) .then(({ stdout, stderr, exitCode }) => { if (exitCode !== 0) { throw new ExecaError({ stdout, stderr, exitCode }) } return { stdout, stderr, exitCode } }) .catch((error) => { if (error instanceof ExecaError) { // Rethrow ExecaError throw error } else { const { stdout = '', stderr = '', exitCode = 1 } = error throw new ExecaError({ stdout, stderr, exitCode }) } }) } // TODO: Remove this as soon as cfw is part of a stable Cedar release, and then // instead just use `cfw` directly everywhere export function getCfwBin(projectPath: string) { return fs.existsSync(path.join(projectPath, 'node_modules/.bin/cfw')) ? 'cfw' : 'rwfw' } export async function addModel(model: string) { const prismaPath = `${getOutputPath()}/api/db/schema.prisma` const schema = await fs.promises.readFile(prismaPath, 'utf-8') return fs.promises.writeFile(prismaPath, `${schema.trim()}\n\n${model}\n`) } /** * @param cmd The command to run */ export function createBuilder(cmd: string, dir = '') { const execaOptions = getExecaOptions(path.join(getOutputPath(), dir)) return async function createItem(positionals?: string | string[]) { const args = positionals ? Array.isArray(positionals) ? positionals : [positionals] : [] return execa(cmd, args, execaOptions) } }