import _locreq from "locreq"; import { promises as fs } from "fs"; import { assertType, predicates } from "@sealcode/ts-predicates"; import { formatWithPrettier } from "./utils/prettier.js"; const target_locreq = _locreq(process.cwd()); export async function extractCollectionClassname( full_file_path: string ): Promise { const file_content = await fs.readFile(full_file_path, "utf-8"); const result = /export default class (\w+)/.exec(file_content); if (result === null) { throw new Error("Missing 'export default class' statement?"); } return assertType( result[1], predicates.string, `Missing export default class in '${full_file_path}'?` ); } export async function generateCollections(): Promise { const collections_dir = target_locreq.resolve("src/back/collections"); const files = (await fs.readdir(collections_dir)).filter( (f) => !/\.(sub)?test\./.exec(f) && f != "collections.ts" && !f.includes(".#") && f.endsWith(".ts") ); const file_data = await Promise.all( files.map(async (file) => { const full_path = target_locreq.resolve( "src/back/collections/" + file ); const class_name = await extractCollectionClassname(full_path); return { class_name, file, full_path, urlname: file.replace(".ts", ""), }; }) ); const content = `// DO NOT EDIT! This file is generated automaticaly with 'npm run generate-collections' import { App } from "sealious"; ${file_data .map( ({ class_name, urlname }) => `import _${class_name} from "./${urlname}.js";` ) .join("\n")} ${file_data .map( ({ class_name }) => `export const ${class_name} = new _${class_name}();` ) .join("\n")} export const collections = { ...App.BaseCollections, ${file_data .map(({ class_name, urlname }) => ` "${urlname}": ${class_name},`) .join("\n")} };`; await fs.writeFile( target_locreq.resolve("src/back/collections/collections.ts"), await formatWithPrettier(content) ); // eslint-disable-next-line no-console console.log( "Successfuly generated new src/back/collections/collections.ts file" ); }