import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import type { ProjectTemplateId } from '../../shared/project-config'; import { getResourcesDir } from '../utils/paths'; const TEMPLATE_RELATIVE_DIRECTORY = join('project-templates', 'works-compose'); const SHARED_FILES = [ '.dockerignore', 'Dockerfile', 'docker-compose.yml', 'nginx.conf', 'niancode.yml', 'deploy/works-deploy-check.schema.json', 'deploy/部署报告模板.md', ] as const; const EXAMPLE_BY_TEMPLATE: Record = { 'standard-development': 'deploy/examples/works-deploy-check.web.json', 'game-development': 'deploy/examples/works-deploy-check.game.json', }; export type WorksPackageTemplateOptions = { resourcesDirectory?: string; }; export function resolveWorksPackageTemplateDirectory(resourcesDirectory = getResourcesDir()): string { return join(resourcesDirectory, TEMPLATE_RELATIVE_DIRECTORY); } export async function initializeWorksPackageTemplate( projectPath: string, templateId: ProjectTemplateId, options: WorksPackageTemplateOptions = {}, ): Promise<{ files: string[] }> { const templateDirectory = resolveWorksPackageTemplateDirectory(options.resourcesDirectory); const files = [...SHARED_FILES, EXAMPLE_BY_TEMPLATE[templateId]]; for (const relativePath of files) { const sourcePath = join(templateDirectory, relativePath); try { const contents = await readFile(sourcePath); if (relativePath.endsWith('.json')) JSON.parse(contents.toString('utf8')); const destinationPath = join(projectPath, relativePath); await mkdir(dirname(destinationPath), { recursive: true }); await writeFile(destinationPath, contents, { flag: 'wx' }); } catch (error) { throw new Error( `Works package template initialization failed for ${relativePath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error }, ); } } return { files }; }