import { execSync } from 'node:child_process' import { copyFileSync, cpSync, existsSync, mkdirSync, rmSync, statSync, writeFileSync, } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') process.chdir(root) const runtimeDir = path.join(root, 'runtime') const engineName = 'libquery_engine-debian-openssl-3.0.x.so.node' const engineSrc = path.join(root, 'node_modules', '.prisma', 'client', engineName) function mb(file) { return `${(statSync(file).size / (1024 * 1024)).toFixed(1)}MB` } console.log('==> nest build') rmSync(path.join(root, 'dist'), { recursive: true, force: true }) rmSync(path.join(root, 'tsconfig.build.tsbuildinfo'), { force: true }) execSync('npx nest build', { stdio: 'inherit' }) if (!existsSync(path.join(root, 'dist', 'main.js'))) { throw new Error('dist/main.js ساخته نشد') } console.log('==> prisma generate (debian engine)') execSync('npx prisma generate', { stdio: 'inherit', env: { ...process.env, DATABASE_URL: process.env.DATABASE_URL || 'postgresql://build:build@localhost:5432/build?schema=public', }, }) if (!existsSync(engineSrc)) { throw new Error(`${engineName} ساخته نشد. binaryTargets را در schema.prisma چک کنید.`) } rmSync(runtimeDir, { recursive: true, force: true }) mkdirSync(runtimeDir, { recursive: true }) console.log('==> esbuild bundle (بدون node_modules در ایمیج)') execSync( [ 'npx --yes esbuild dist/main.js', '--bundle', '--platform=node', '--target=node22', '--format=cjs', '--outfile=runtime/server.cjs', '--keep-names', '--legal-comments=none', '--alias:class-transformer/storage=node_modules/class-transformer/cjs/storage.js', '--external:@nestjs/microservices', '--external:@nestjs/microservices/microservices-module', '--external:@nestjs/websockets', '--external:@nestjs/websockets/socket-module', ].join(' '), { stdio: 'inherit' }, ) copyFileSync(engineSrc, path.join(runtimeDir, engineName)) const schemaSrc = path.join(root, 'node_modules', '.prisma', 'client', 'schema.prisma') if (existsSync(schemaSrc)) { copyFileSync(schemaSrc, path.join(runtimeDir, 'schema.prisma')) } const migrationsSrc = path.join(root, 'prisma', 'migrations') if (existsSync(migrationsSrc)) { cpSync(migrationsSrc, path.join(runtimeDir, 'migrations'), { recursive: true }) } writeFileSync( path.join(runtimeDir, 'package.json'), `${JSON.stringify({ name: 'fabric-trade-runtime', private: true, type: 'commonjs' }, null, 2)}\n`, ) if (!existsSync(path.join(runtimeDir, 'server.cjs'))) { throw new Error('runtime/server.cjs ساخته نشد') } console.log(`runtime/server.cjs ${mb(path.join(runtimeDir, 'server.cjs'))}`) console.log(`runtime/${engineName} ${mb(path.join(runtimeDir, engineName))}`) console.log('runtime آماده است. commit و push کنید. مایگریت روی سرور اجرا می‌شود.')