@itarrshia/bati 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +164 -2
  2. package/assets/bati-mark.svg +26 -0
  3. package/dist/api.ts +0 -0
  4. package/dist/bati-db.png +0 -0
  5. package/dist/bati-openapi.json +8 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +174 -0
  8. package/dist/core/api-generate.d.ts +9 -0
  9. package/dist/core/api-generate.js +74 -0
  10. package/dist/core/api.d.ts +44 -0
  11. package/dist/core/api.js +292 -0
  12. package/dist/core/config.d.ts +40 -0
  13. package/dist/core/config.js +53 -0
  14. package/dist/core/dashboard.d.ts +37 -0
  15. package/dist/core/dashboard.js +95 -0
  16. package/dist/core/db.d.ts +31 -0
  17. package/dist/core/db.js +392 -0
  18. package/dist/core/deps.d.ts +35 -0
  19. package/dist/core/deps.js +242 -0
  20. package/dist/core/diagram.d.ts +4 -0
  21. package/dist/core/diagram.js +151 -0
  22. package/dist/core/doctor.d.ts +23 -0
  23. package/dist/core/doctor.js +148 -0
  24. package/dist/core/files.d.ts +5 -0
  25. package/dist/core/files.js +69 -0
  26. package/dist/core/format.d.ts +13 -0
  27. package/dist/core/format.js +54 -0
  28. package/dist/core/graph-view.d.ts +2 -0
  29. package/dist/core/graph-view.js +65 -0
  30. package/dist/core/mcp-install.d.ts +19 -0
  31. package/dist/core/mcp-install.js +105 -0
  32. package/dist/core/mcp.d.ts +12 -0
  33. package/dist/core/mcp.js +244 -0
  34. package/dist/core/openapi.d.ts +16 -0
  35. package/dist/core/openapi.js +270 -0
  36. package/dist/core/pack.d.ts +8 -0
  37. package/dist/core/pack.js +101 -0
  38. package/dist/core/php.d.ts +6 -0
  39. package/dist/core/php.js +50 -0
  40. package/dist/core/preview.d.ts +9 -0
  41. package/dist/core/preview.js +89 -0
  42. package/dist/core/probe.d.ts +21 -0
  43. package/dist/core/probe.js +119 -0
  44. package/dist/core/routes.d.ts +37 -0
  45. package/dist/core/routes.js +343 -0
  46. package/dist/core/scan.d.ts +13 -0
  47. package/dist/core/scan.js +395 -0
  48. package/dist/core/tasks.d.ts +34 -0
  49. package/dist/core/tasks.js +88 -0
  50. package/dist/core/types.d.ts +46 -0
  51. package/dist/core/types.js +1 -0
  52. package/dist/openapi.json +8 -0
  53. package/dist/theme.d.ts +12 -0
  54. package/dist/theme.js +32 -0
  55. package/dist/ui/App.d.ts +5 -0
  56. package/dist/ui/App.js +247 -0
  57. package/dist/ui/Banner.d.ts +5 -0
  58. package/dist/ui/Banner.js +9 -0
  59. package/dist/ui/Dashboard.d.ts +26 -0
  60. package/dist/ui/Dashboard.js +52 -0
  61. package/dist/ui/MapView.d.ts +5 -0
  62. package/dist/ui/MapView.js +47 -0
  63. package/dist/ui/Wizard.d.ts +17 -0
  64. package/dist/ui/Wizard.js +112 -0
  65. package/dist/ui/presentation.d.ts +24 -0
  66. package/dist/ui/presentation.js +15 -0
  67. package/package.json +80 -4
@@ -0,0 +1,392 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { configuredOutput, loadConfig } from './config.js';
4
+ import { listFiles, writeOutput } from './files.js';
5
+ const identifier = (value) => value.trim().replace(/^[`"\[]|[`"\]]$/g, '');
6
+ const split = (source, separator = ',') => {
7
+ const values = [];
8
+ let depth = 0;
9
+ let quote = '';
10
+ let start = 0;
11
+ for (let i = 0; i < source.length; i++) {
12
+ const character = source[i];
13
+ if (quote) {
14
+ if (character === quote && source[i + 1] === quote)
15
+ i++;
16
+ else if (character === quote)
17
+ quote = '';
18
+ else if (character === '\\')
19
+ i++;
20
+ }
21
+ else if (["'", '"', '`'].includes(character))
22
+ quote = character;
23
+ else if (character === '(')
24
+ depth++;
25
+ else if (character === ')')
26
+ depth--;
27
+ else if (character === separator && depth === 0) {
28
+ values.push(source.slice(start, i).trim());
29
+ start = i + 1;
30
+ }
31
+ }
32
+ values.push(source.slice(start).trim());
33
+ return values.filter(Boolean);
34
+ };
35
+ const newColumn = (name, type, properties = {}) => ({ name, type, nullable: false, primary: false, unique: false, ...properties });
36
+ const columnNames = (value) => split(value).map(identifier);
37
+ const sqlId = '(?:"(?:""|[^"])+"|`[^`]+`|\\[[^\\]]+\\]|[\\w$.-]+)';
38
+ function parseSql(source, file, tables) {
39
+ const key = new RegExp(`^FOREIGN\\s+KEY\\s*\\(([^)]+)\\)\\s*REFERENCES\\s+(${sqlId})\\s*\\(([^)]+)\\)`, 'i');
40
+ const definition = new RegExp(`^(${sqlId})\\s+(.+)`, 'is');
41
+ const apply = (table, raw) => {
42
+ const line = raw.replace(new RegExp(`^CONSTRAINT\\s+${sqlId}\\s+`, 'i'), '');
43
+ const fk = line.match(key);
44
+ if (fk) {
45
+ table.foreignKeys.push({ columns: columnNames(fk[1]), table: identifier(fk[2]), references: columnNames(fk[3]) });
46
+ return;
47
+ }
48
+ const index = line.match(/^(PRIMARY KEY|UNIQUE)\s*\(([^)]+)\)/i);
49
+ if (index) {
50
+ for (const column of table.columns.filter((column) => columnNames(index[2]).includes(column.name))) {
51
+ if (index[1].toUpperCase() === 'PRIMARY KEY') {
52
+ column.primary = true;
53
+ column.nullable = false;
54
+ }
55
+ else if (columnNames(index[2]).length === 1)
56
+ column.unique = true;
57
+ }
58
+ return;
59
+ }
60
+ if (/^(CHECK|KEY|INDEX|FOREIGN)\b/i.test(line))
61
+ return;
62
+ const match = line.match(definition);
63
+ if (!match)
64
+ return;
65
+ const [, name, rest] = match;
66
+ const field = identifier(name);
67
+ const type = rest.split(/\s+(?=(?:NOT NULL|NULL|DEFAULT|PRIMARY KEY|UNIQUE|REFERENCES|CHECK|GENERATED|COLLATE|CONSTRAINT)\b)/i)[0].trim();
68
+ const primary = /\bPRIMARY\s+KEY\b/i.test(rest);
69
+ const value = rest.match(/\bDEFAULT\s+(.+?)(?=\s+(?:NOT NULL|UNIQUE|PRIMARY KEY|REFERENCES|CHECK)\b|$)/is)?.[1];
70
+ table.columns = table.columns.filter((column) => column.name !== field);
71
+ table.columns.push(newColumn(field, type, { primary, nullable: !primary && !/\bNOT NULL\b/i.test(rest), unique: /\bUNIQUE\b/i.test(rest), default: value }));
72
+ const reference = rest.match(new RegExp(`\\bREFERENCES\\s+(${sqlId})\\s*\\(([^)]+)\\)`, 'i'));
73
+ if (reference)
74
+ table.foreignKeys.push({ columns: [field], table: identifier(reference[1]), references: columnNames(reference[2]) });
75
+ };
76
+ const withoutComments = source.replace(/'(?:''|[^'])*'|"(?:""|[^"])*"|`[^`]*`|--[^\r\n]*|\/\*[\s\S]*?\*\//g, (value) => /^--|^\/\*/.test(value) ? ' ' : value);
77
+ for (const statement of split(withoutComments, ';')) {
78
+ const create = statement.match(new RegExp(`^CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?TABLE\\s+(?:IF NOT EXISTS\\s+)?(${sqlId})\\s*\\(([\\s\\S]*)\\)\\s*[^()]*$`, 'i'));
79
+ if (create) {
80
+ const table = { name: identifier(create[1]), file, source: 'sql', columns: [], foreignKeys: [] };
81
+ const definitions = split(create[2]);
82
+ for (const line of [...definitions.filter((line) => !/^(?:CONSTRAINT|PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/i.test(line)), ...definitions.filter((line) => /^(?:CONSTRAINT|PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/i.test(line))])
83
+ apply(table, line);
84
+ tables.set(table.name, table);
85
+ continue;
86
+ }
87
+ const alter = statement.match(new RegExp(`^ALTER\\s+TABLE\\s+(?:ONLY\\s+)?(${sqlId})\\s+([\\s\\S]+)$`, 'i'));
88
+ if (alter) {
89
+ const table = tables.get(identifier(alter[1]));
90
+ if (!table)
91
+ continue;
92
+ for (const action of split(alter[2])) {
93
+ const added = action.match(/^ADD\s+(?:COLUMN\s+)?(?:IF NOT EXISTS\s+)?([\s\S]+)/i);
94
+ if (added)
95
+ apply(table, added[1]);
96
+ const dropped = action.match(new RegExp(`^DROP\\s+COLUMN\\s+(?:IF EXISTS\\s+)?(${sqlId})`, 'i'));
97
+ if (dropped)
98
+ table.columns = table.columns.filter((column) => column.name !== identifier(dropped[1]));
99
+ const renamed = action.match(new RegExp(`^RENAME\\s+COLUMN\\s+(${sqlId})\\s+TO\\s+(${sqlId})`, 'i'));
100
+ if (renamed) {
101
+ const column = table.columns.find((item) => item.name === identifier(renamed[1]));
102
+ if (column)
103
+ column.name = identifier(renamed[2]);
104
+ }
105
+ }
106
+ }
107
+ const dropped = statement.match(new RegExp(`^DROP\\s+TABLE\\s+(?:IF EXISTS\\s+)?(${sqlId})`, 'i'));
108
+ if (dropped)
109
+ tables.delete(identifier(dropped[1]));
110
+ }
111
+ }
112
+ function parsePrisma(source, file, tables) {
113
+ const blocks = [...source.matchAll(/^\s*(model|enum)\s+(\w+)\s*\{([\s\S]*?)^\s*\}/gm)];
114
+ const models = new Map(blocks.filter((match) => match[1] === 'model').map((match) => [match[2], {
115
+ name: match[3].match(/@@map\(\s*"([^"]+)"\s*\)/)?.[1] ?? match[2],
116
+ fields: match[3].split('\n').map((line) => line.replace(/\/\/.*$/, '').trim().match(/^(\w+)\s+(\w+)(\[\]|\?)?\s*(.*)$/)).filter((line) => !!line)
117
+ }]));
118
+ const fieldMapping = (attribute) => attribute.match(/(?<!@)@map\(\s*"([^"]+)"\s*\)/)?.[1];
119
+ for (const model of models.values()) {
120
+ const table = { name: model.name, file, source: 'prisma', columns: [], foreignKeys: [] };
121
+ const fieldName = (fields, name) => fieldMapping(fields.find((field) => field[1] === name)?.[4] ?? '') ?? name;
122
+ for (const [, name, type, modifier, attributes] of model.fields) {
123
+ const target = models.get(type);
124
+ if (target) {
125
+ const relation = attributes.match(/fields\s*:\s*\[([^\]]+)\][\s\S]*?references\s*:\s*\[([^\]]+)\]/);
126
+ if (relation)
127
+ table.foreignKeys.push({
128
+ columns: columnNames(relation[1]).map((field) => fieldName(model.fields, field)),
129
+ table: target.name,
130
+ references: columnNames(relation[2]).map((field) => fieldName(target.fields, field))
131
+ });
132
+ }
133
+ else {
134
+ const enumeration = blocks.some((match) => match[1] === 'enum' && match[2] === type);
135
+ table.columns.push(newColumn(fieldMapping(attributes) ?? name, (enumeration ? 'enum' : type) + (modifier === '[]' ? '[]' : ''), {
136
+ nullable: modifier === '?', primary: /@id\b/.test(attributes), unique: /@unique\b/.test(attributes),
137
+ default: attributes.match(/@default\((.+)\)(?=\s+@|$)/)?.[1]
138
+ }));
139
+ }
140
+ }
141
+ const block = blocks.find((item) => item[1] === 'model' && models.get(item[2]) === model)?.[3];
142
+ for (const match of block?.matchAll(/@@id\(\s*\[([^\]]+)\]/g) ?? []) {
143
+ const names = columnNames(match[1]).map((field) => fieldName(model.fields, field));
144
+ for (const column of table.columns)
145
+ if (names.includes(column.name))
146
+ column.primary = true;
147
+ }
148
+ tables.set(table.name, table);
149
+ }
150
+ }
151
+ async function parseLaravel(source, file, tables) {
152
+ const { parsePhpSource, walkPhp, phpName, phpString } = await import('./php.js');
153
+ const chain = (node) => {
154
+ const calls = [];
155
+ let cursor = node;
156
+ while (cursor?.kind === 'call' && ['propertylookup', 'staticlookup'].includes(cursor.what?.kind)) {
157
+ calls.unshift({ method: phpName(cursor.what.offset), args: cursor.arguments });
158
+ cursor = cursor.what.what;
159
+ }
160
+ return { calls, cursor };
161
+ };
162
+ const ignored = new Set(['index', 'fullText', 'spatialIndex', 'dropIndex', 'dropForeign', 'comment', 'engine', 'charset', 'collation']);
163
+ const arg = (node) => phpString(node) ?? (node?.kind === 'array' ? node.items.map((item) => phpString(item.value)).filter(Boolean) : undefined);
164
+ for (const method of [...walkPhp(parsePhpSource(source, file))].filter((node) => node.kind === 'method' && phpName(node.name) === 'up')) {
165
+ for (const node of walkPhp(method.body)) {
166
+ if (node.kind !== 'call' || node.what?.kind !== 'staticlookup' || phpName(node.what.what).split('\\').at(-1) !== 'Schema')
167
+ continue;
168
+ const name = phpString(node.arguments[0]);
169
+ const action = phpName(node.what.offset);
170
+ if (!name)
171
+ continue;
172
+ if (['drop', 'dropIfExists'].includes(action)) {
173
+ tables.delete(name);
174
+ continue;
175
+ }
176
+ if (action === 'rename') {
177
+ const target = phpString(node.arguments[1]);
178
+ const existing = tables.get(name);
179
+ if (target && existing) {
180
+ tables.delete(name);
181
+ existing.name = target;
182
+ tables.set(target, existing);
183
+ for (const table of tables.values())
184
+ for (const key of table.foreignKeys)
185
+ if (key.table === name)
186
+ key.table = target;
187
+ }
188
+ continue;
189
+ }
190
+ if (!['create', 'table'].includes(action))
191
+ continue;
192
+ const table = tables.get(name) ?? { name, file, source: 'laravel', columns: [], foreignKeys: [] };
193
+ tables.set(name, table);
194
+ const callback = node.arguments[1];
195
+ const receiver = phpName(callback?.arguments?.[0]?.name);
196
+ for (const statement of walkPhp(callback?.body)) {
197
+ if (statement.kind !== 'expressionstatement')
198
+ continue;
199
+ const { calls, cursor } = chain(statement.expression);
200
+ if (cursor?.kind !== 'variable' || phpName(cursor) !== receiver || !calls.length)
201
+ continue;
202
+ const [{ method, args }, ...modifiers] = calls;
203
+ const named = phpString(args[0]);
204
+ const find = (name) => modifiers.find((call) => call.method === name);
205
+ const add = (column) => {
206
+ table.columns = table.columns.filter((entry) => entry.name !== column.name);
207
+ table.columns.push(column);
208
+ };
209
+ if (ignored.has(method))
210
+ continue;
211
+ if (['dropColumn', 'renameColumn'].includes(method)) {
212
+ const names = [arg(args[0])].flat().filter(Boolean);
213
+ if (method === 'dropColumn')
214
+ table.columns = table.columns.filter((column) => !names.includes(column.name));
215
+ else {
216
+ const column = table.columns.find((column) => column.name === named);
217
+ const target = phpString(args[1]);
218
+ if (column && target)
219
+ column.name = target;
220
+ }
221
+ continue;
222
+ }
223
+ if (['timestamps', 'timestampsTz', 'nullableTimestamps', 'softDeletes', 'softDeletesTz', 'rememberToken'].includes(method)) {
224
+ const columns = method.toLowerCase().includes('timestamps') ? ['created_at', 'updated_at'] : [named ?? (method === 'rememberToken' ? 'remember_token' : 'deleted_at')];
225
+ for (const column of columns)
226
+ add(newColumn(column, method === 'rememberToken' ? 'string' : 'timestamp', { nullable: true }));
227
+ continue;
228
+ }
229
+ if (method === 'primary' || method === 'unique') {
230
+ const names = [arg(args[0])].flat();
231
+ for (const column of table.columns.filter((column) => names.includes(column.name))) {
232
+ if (method === 'primary')
233
+ column.primary = true;
234
+ else if (names.length === 1)
235
+ column.unique = true;
236
+ }
237
+ continue;
238
+ }
239
+ if (method !== 'foreign') {
240
+ if (!named && method !== 'id' && !/increments$/i.test(method))
241
+ continue;
242
+ const primary = method === 'id' || /increments$/i.test(method) || !!find('primary');
243
+ const type = primary && (method === 'id' || /increments$/i.test(method)) || ['foreignId', 'foreignIdFor'].includes(method) ? 'bigint' :
244
+ method === 'foreignUuid' ? 'uuid' : method === 'foreignUlid' ? 'ulid' : method;
245
+ const value = find('default')?.args[0];
246
+ add(newColumn(named ?? 'id', type, { primary, nullable: !!find('nullable') && find('nullable')?.args[0]?.value !== false,
247
+ unique: !!find('unique'), default: value?.loc?.source ?? value?.raw ?? (value ? String(value.value) : undefined) }));
248
+ }
249
+ const constrained = find('constrained');
250
+ const on = phpString(find('on')?.args[0]);
251
+ const refers = arg(find('references')?.args[0]);
252
+ const columns = [arg(args[0])].flat().filter((value) => !!value);
253
+ const target = on ?? (constrained && named ? phpString(constrained.args[0]) ?? named.replace(/_id$/, '').replace(/y$/, 'ie') + 's' : undefined);
254
+ if (target && columns.length)
255
+ table.foreignKeys.push({ columns, table: target, references: refers ? [refers].flat() : [phpString(constrained?.args[1]) ?? 'id'] });
256
+ }
257
+ }
258
+ }
259
+ }
260
+ async function parseDrizzle(files, tables) {
261
+ const { default: ts } = await import('typescript');
262
+ const keys = new Map();
263
+ const deferred = [];
264
+ for (const { file, source } of files) {
265
+ if (!/\b(?:pgTable|mysqlTable|sqliteTable|singlestoreTable)\b/.test(source))
266
+ continue;
267
+ const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
268
+ const text = (node) => node.getText(ast);
269
+ const literal = (node) => node && ts.isStringLiteralLike(node) ? node.text : undefined;
270
+ const visit = (node) => {
271
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && ts.isCallExpression(node.initializer) && /^(?:\w+\.)?(?:pgTable|mysqlTable|sqliteTable|singlestoreTable)$/.test(text(node.initializer.expression))) {
272
+ const [name, rawColumns] = node.initializer.arguments;
273
+ const tableName = literal(name);
274
+ if (tableName && rawColumns && ts.isObjectLiteralExpression(rawColumns)) {
275
+ const table = { name: tableName, file, source: 'drizzle', columns: [], foreignKeys: [] };
276
+ const names = new Map();
277
+ keys.set(node.name.text, { table, columns: names });
278
+ tables.set(tableName, table);
279
+ for (const field of rawColumns.properties) {
280
+ if (!ts.isPropertyAssignment(field))
281
+ continue;
282
+ const key = literal(field.name) ?? text(field.name);
283
+ let expression = field.initializer;
284
+ const methods = new Map();
285
+ while (ts.isCallExpression(expression) && ts.isPropertyAccessExpression(expression.expression) && ts.isCallExpression(expression.expression.expression)) {
286
+ methods.set(expression.expression.name.text, expression.arguments);
287
+ expression = expression.expression.expression;
288
+ }
289
+ if (!ts.isCallExpression(expression))
290
+ continue;
291
+ const name = literal(expression.arguments[0]) ?? key;
292
+ const type = text(expression.expression).split('.').at(-1);
293
+ const primary = methods.has('primaryKey');
294
+ const value = methods.get('default')?.[0];
295
+ table.columns.push(newColumn(name, type + (methods.has('array') ? '[]' : ''), { primary,
296
+ nullable: !primary && !methods.has('notNull'), unique: methods.has('unique'), default: value ? text(value) : undefined }));
297
+ names.set(key, name);
298
+ const reference = methods.get('references')?.[0];
299
+ if (reference && ts.isArrowFunction(reference) && ts.isPropertyAccessExpression(reference.body) && ts.isIdentifier(reference.body.expression)) {
300
+ deferred.push({ from: table, column: name, variable: reference.body.expression.text, key: reference.body.name.text });
301
+ }
302
+ }
303
+ }
304
+ }
305
+ ts.forEachChild(node, visit);
306
+ };
307
+ visit(ast);
308
+ }
309
+ for (const item of deferred) {
310
+ const to = keys.get(item.variable);
311
+ const field = to?.columns.get(item.key);
312
+ if (to && field)
313
+ item.from.foreignKeys.push({ columns: [item.column], table: to.table.name, references: [field] });
314
+ }
315
+ }
316
+ export async function collectSchema(dir) {
317
+ const root = path.resolve(dir);
318
+ const files = await listFiles(root, ['**/*.prisma', '**/*.sql', '**/migrations/**/*.php', '**/*.{ts,js,mts,cts,mjs,cjs}']);
319
+ const tables = new Map();
320
+ const drizzle = [];
321
+ for (const file of files) {
322
+ const source = await readFile(path.join(root, file), 'utf8');
323
+ if (file.endsWith('.sql'))
324
+ parseSql(source, file, tables);
325
+ else if (file.endsWith('.prisma'))
326
+ parsePrisma(source, file, tables);
327
+ else if (file.endsWith('.php'))
328
+ await parseLaravel(source, file, tables);
329
+ else
330
+ drizzle.push({ file, source });
331
+ }
332
+ if (drizzle.length)
333
+ await parseDrizzle(drizzle, tables);
334
+ return { root, tables: [...tables.values()].sort((a, b) => a.name.localeCompare(b.name)) };
335
+ }
336
+ const tsType = (type) => {
337
+ if (type.endsWith('[]'))
338
+ return `Array<${tsType(type.slice(0, -2))}>`;
339
+ if (/^(?:bit|bool)/i.test(type))
340
+ return 'boolean';
341
+ if (/^(?:unsigned)?(?:tiny|small|medium|big)?int|^(?:numeric|serial|decimal|number|double|float|real|money)/i.test(type))
342
+ return 'number';
343
+ if (/^(?:bytea|blob|binary|bytes)/i.test(type))
344
+ return 'Uint8Array';
345
+ if (/^(?:json|array|object|unsupported)/i.test(type))
346
+ return 'unknown';
347
+ return 'string';
348
+ };
349
+ export function schemaText(tables, format) {
350
+ if (format === 'json')
351
+ return JSON.stringify(tables, null, 2);
352
+ if (format === 'types')
353
+ return `export interface Database {\n${tables.map((table) => ` ${JSON.stringify(table.name)}: {\n${table.columns.map((column) => ` ${JSON.stringify(column.name)}: ${tsType(column.type)}${column.nullable ? ' | null' : ''};`).join('\n')}\n };\n`).join('')}}\n`;
354
+ if (format === 'eloquent') {
355
+ const phpType = (type) => ({ number: 'int|float', string: 'string', boolean: 'bool', unknown: 'mixed', Uint8Array: 'string' })[tsType(type)] ?? 'array';
356
+ return tables.map((table) => [`### ${JSON.stringify(table.name)}`, '', '```php', '/**', ...table.columns.map((column) => ` * @property ${phpType(column.type)}${column.nullable ? '|null' : ''} $${column.name.replace(/[^\w]/g, '_')}`), ' */', '```'].join('\n')).join('\n\n');
357
+ }
358
+ const ids = new Map(tables.map((table, index) => [table.name, 'T' + index]));
359
+ const label = (name) => name.replace(/[^\w]/g, '_') || '_';
360
+ return ['erDiagram', ...tables.flatMap((table) => [
361
+ ` ${ids.get(table.name)}["${table.name.replace(/["\r\n]/g, '')}"] {`,
362
+ ...table.columns.map((column) => ` ${label(column.type)} ${label(column.name)}${column.primary ? ' PK' : table.foreignKeys.some((key) => key.columns.includes(column.name)) ? ' FK' : column.unique ? ' UK' : ''}`),
363
+ ' }',
364
+ ...table.foreignKeys.filter((key) => ids.has(key.table)).map((key) => ` ${ids.get(key.table)} ||--o{ ${ids.get(table.name)} : "${label(key.columns.join('_'))}"`)
365
+ ])].join('\n');
366
+ }
367
+ export async function db(options) {
368
+ const schema = await collectSchema(options.dir);
369
+ const format = options.format ?? 'svg';
370
+ const suffix = { svg: 'svg', png: 'png', mermaid: 'mmd', json: 'json', types: 'ts', eloquent: 'md' };
371
+ if (!Object.hasOwn(suffix, format))
372
+ throw new Error('Database format must be svg, png, mermaid, json, types, or eloquent');
373
+ const relations = schema.tables.reduce((total, table) => total + table.foreignKeys.length, 0);
374
+ let content;
375
+ if (format === 'svg' || format === 'png') {
376
+ const { renderSvg, toPng } = await import('./diagram.js');
377
+ const names = new Set(schema.tables.map((table) => table.name));
378
+ const model = { root: schema.root, files: [], classes: schema.tables.map((table) => ({
379
+ id: table.name, name: table.name, kind: 'class', file: table.file, lang: table.source === 'laravel' ? 'php' : 'ts',
380
+ props: table.columns.map((column) => ({ name: column.name, visibility: 'public', static: false,
381
+ type: [column.type, column.primary ? 'PK' : '', column.nullable ? 'NULL' : ''].filter(Boolean).join(' · ') })),
382
+ methods: [], traits: [], implements: []
383
+ })), edges: schema.tables.flatMap((table) => table.foreignKeys.filter((key) => names.has(key.table)).map((key) => ({ from: table.name, to: key.table, kind: 'uses' }))) };
384
+ const svg = renderSvg(model, schema.tables.length, 'TABLE', 'tables');
385
+ content = format === 'png' ? toPng(svg, 1) : svg;
386
+ }
387
+ else
388
+ content = schemaText(schema.tables, format) + '\n';
389
+ const target = configuredOutput(schema.root, await loadConfig(schema.root), 'db', `bati-db.${suffix[format]}`, options.out);
390
+ const output = await writeOutput(target, content);
391
+ return { title: 'Database schema', output, lines: [`${schema.tables.length} tables · ${relations} relations`, output], data: schema };
392
+ }
@@ -0,0 +1,35 @@
1
+ import type { TaskResult } from './types.js';
2
+ export declare const codePattern = "**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,php}";
3
+ export interface DependencyFile {
4
+ path: string;
5
+ lines: number;
6
+ complexity: number;
7
+ exports: string[];
8
+ importedBy: number;
9
+ imports: number;
10
+ }
11
+ export interface DependencyEdge {
12
+ from: string;
13
+ to: string;
14
+ imports: string[];
15
+ lines: number[];
16
+ }
17
+ export interface DependencyGraph {
18
+ root: string;
19
+ files: DependencyFile[];
20
+ edges: DependencyEdge[];
21
+ cycles: string[][];
22
+ orphans: string[];
23
+ unusedExports: {
24
+ file: string;
25
+ name: string;
26
+ }[];
27
+ godModules: string[];
28
+ }
29
+ export declare function analyzeDeps(dir: string): Promise<DependencyGraph>;
30
+ export declare function deps(options: {
31
+ dir: string;
32
+ format?: string;
33
+ out?: string;
34
+ check?: boolean;
35
+ }): Promise<TaskResult>;