const fs = require("fs"); const path = require("path"); const schemaPath = path.resolve(process.cwd(), "db-schema.json"); const outPath = path.resolve(process.cwd(), "src", "types", "db-client.d.ts"); if (!fs.existsSync(schemaPath)) { console.error("db-schema.json not found"); process.exit(1); } const schema = JSON.parse(fs.readFileSync(schemaPath, "utf8")); const tables = schema.tables || {}; function fieldTypeToTs(t) { switch (t) { case "number": return "number"; case "string": return "string"; case "boolean": return "boolean"; default: return "any"; } } let out = `// GENERATED FILE — edit db-schema.json and run npm run generate:db-types\n\n`; out += `type DBAction = (payload?: TRequest) => Promise;\n\n`; out += `// Generated tables\n`; out += `interface DBTables {\n`; for (const [table, def] of Object.entries(tables)) { out += ` ${table}: {\n`; out += ` create: DBAction<{ data: Partial<{`; const fields = def.fields || {}; const fPairs = Object.entries(fields).map( ([n, t]) => `${n}: ${fieldTypeToTs(t)}` ); out += fPairs.join("; "); out += `}> }, any>;\n`; out += ` update: DBAction<{ where: any; data: any }, any>;\n`; out += ` delete: DBAction<{ where: any }, any>;\n`; out += ` findFirst: DBAction<{ where?: any; include?: any; select?: any }, any>;\n`; out += ` findMany: DBAction;\n`; out += ` };\n`; } out += `}\n\n`; out += `type DBClient = {\n [K in keyof DBTables]: DBTables[K];\n} & { [table: string]: { [action: string]: DBAction } };\n\n`; out += `declare module "@/lib/dbClient" {\n const db: DBClient;\n export default db;\n}\n`; fs.mkdirSync(path.dirname(outPath), { recursive: true }); fs.writeFileSync(outPath, out, "utf8"); console.log("Wrote", outPath);