@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.
- package/README.md +164 -2
- package/assets/bati-mark.svg +26 -0
- package/dist/api.ts +0 -0
- package/dist/bati-db.png +0 -0
- package/dist/bati-openapi.json +8 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +174 -0
- package/dist/core/api-generate.d.ts +9 -0
- package/dist/core/api-generate.js +74 -0
- package/dist/core/api.d.ts +44 -0
- package/dist/core/api.js +292 -0
- package/dist/core/config.d.ts +40 -0
- package/dist/core/config.js +53 -0
- package/dist/core/dashboard.d.ts +37 -0
- package/dist/core/dashboard.js +95 -0
- package/dist/core/db.d.ts +31 -0
- package/dist/core/db.js +392 -0
- package/dist/core/deps.d.ts +35 -0
- package/dist/core/deps.js +242 -0
- package/dist/core/diagram.d.ts +4 -0
- package/dist/core/diagram.js +151 -0
- package/dist/core/doctor.d.ts +23 -0
- package/dist/core/doctor.js +148 -0
- package/dist/core/files.d.ts +5 -0
- package/dist/core/files.js +69 -0
- package/dist/core/format.d.ts +13 -0
- package/dist/core/format.js +54 -0
- package/dist/core/graph-view.d.ts +2 -0
- package/dist/core/graph-view.js +65 -0
- package/dist/core/mcp-install.d.ts +19 -0
- package/dist/core/mcp-install.js +105 -0
- package/dist/core/mcp.d.ts +12 -0
- package/dist/core/mcp.js +244 -0
- package/dist/core/openapi.d.ts +16 -0
- package/dist/core/openapi.js +270 -0
- package/dist/core/pack.d.ts +8 -0
- package/dist/core/pack.js +101 -0
- package/dist/core/php.d.ts +6 -0
- package/dist/core/php.js +50 -0
- package/dist/core/preview.d.ts +9 -0
- package/dist/core/preview.js +89 -0
- package/dist/core/probe.d.ts +21 -0
- package/dist/core/probe.js +119 -0
- package/dist/core/routes.d.ts +37 -0
- package/dist/core/routes.js +343 -0
- package/dist/core/scan.d.ts +13 -0
- package/dist/core/scan.js +395 -0
- package/dist/core/tasks.d.ts +34 -0
- package/dist/core/tasks.js +88 -0
- package/dist/core/types.d.ts +46 -0
- package/dist/core/types.js +1 -0
- package/dist/openapi.json +8 -0
- package/dist/theme.d.ts +12 -0
- package/dist/theme.js +32 -0
- package/dist/ui/App.d.ts +5 -0
- package/dist/ui/App.js +247 -0
- package/dist/ui/Banner.d.ts +5 -0
- package/dist/ui/Banner.js +9 -0
- package/dist/ui/Dashboard.d.ts +26 -0
- package/dist/ui/Dashboard.js +52 -0
- package/dist/ui/MapView.d.ts +5 -0
- package/dist/ui/MapView.js +47 -0
- package/dist/ui/Wizard.d.ts +17 -0
- package/dist/ui/Wizard.js +112 -0
- package/dist/ui/presentation.d.ts +24 -0
- package/dist/ui/presentation.js +15 -0
- package/package.json +80 -4
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
const normalize = (p) => '/' + p.replace(/^https?:\/\/[^/]+/, '').replace(/[?#].*$/, '').replace(/:(\w+)/g, '{$1}').replace(/^\/+/, '');
|
|
3
|
+
export const parseRoutes = (text, base) => {
|
|
4
|
+
const out = [];
|
|
5
|
+
const push = (method, p) => {
|
|
6
|
+
let path = p;
|
|
7
|
+
if (base && path.startsWith(base))
|
|
8
|
+
path = path.slice(base.length);
|
|
9
|
+
out.push({ method: method.toUpperCase(), path: normalize(path) });
|
|
10
|
+
};
|
|
11
|
+
try {
|
|
12
|
+
const j = JSON.parse(text);
|
|
13
|
+
const list = Array.isArray(j) ? j : Array.isArray(j.routes) ? j.routes : j.paths ? Object.keys(j.paths) : [];
|
|
14
|
+
for (const r of list) {
|
|
15
|
+
if (typeof r === 'string') {
|
|
16
|
+
const m = r.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.+)$/i);
|
|
17
|
+
m ? push(m[1], m[2]) : push('GET', r);
|
|
18
|
+
}
|
|
19
|
+
else if (r?.path || r?.url || r?.uri)
|
|
20
|
+
push(r.method ?? (Array.isArray(r.methods) ? r.methods[0] : 'GET'), r.path ?? r.url ?? r.uri);
|
|
21
|
+
}
|
|
22
|
+
return dedupe(out);
|
|
23
|
+
}
|
|
24
|
+
catch { }
|
|
25
|
+
if (/<loc>/i.test(text)) {
|
|
26
|
+
for (const m of text.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/gi))
|
|
27
|
+
push('GET', m[1]);
|
|
28
|
+
return dedupe(out);
|
|
29
|
+
}
|
|
30
|
+
for (const line of text.split('\n')) {
|
|
31
|
+
const t = line.trim();
|
|
32
|
+
if (!t || t.startsWith('#'))
|
|
33
|
+
continue;
|
|
34
|
+
const m = t.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(\S+)/i);
|
|
35
|
+
m ? push(m[1], m[2]) : push('GET', t.split(/\s+/)[0]);
|
|
36
|
+
}
|
|
37
|
+
return dedupe(out);
|
|
38
|
+
};
|
|
39
|
+
const dedupe = (r) => [...new Map(r.map((x) => [x.method + x.path, x])).values()];
|
|
40
|
+
const merge = (a, b) => {
|
|
41
|
+
if (!a)
|
|
42
|
+
return b;
|
|
43
|
+
if (!b)
|
|
44
|
+
return a;
|
|
45
|
+
if (a.type === 'null' && b.type !== 'null')
|
|
46
|
+
return { ...b, nullable: true };
|
|
47
|
+
if (b.type === 'null' && a.type !== 'null')
|
|
48
|
+
return { ...a, nullable: true };
|
|
49
|
+
if (a.type === 'object' && b.type === 'object') {
|
|
50
|
+
const props = { ...a.properties };
|
|
51
|
+
for (const k of Object.keys(b.properties))
|
|
52
|
+
props[k] = props[k] ? merge(props[k], b.properties[k]) : b.properties[k];
|
|
53
|
+
const ra = new Set(a.required);
|
|
54
|
+
return { type: 'object', properties: props, required: b.required.filter((k) => ra.has(k)) };
|
|
55
|
+
}
|
|
56
|
+
if (a.type === 'array' && b.type === 'array')
|
|
57
|
+
return { type: 'array', items: merge(a.items, b.items) };
|
|
58
|
+
if (a.type === b.type)
|
|
59
|
+
return a;
|
|
60
|
+
if ((a.type === 'integer' && b.type === 'number') || (a.type === 'number' && b.type === 'integer'))
|
|
61
|
+
return { type: 'number' };
|
|
62
|
+
return { oneOf: [a, b] };
|
|
63
|
+
};
|
|
64
|
+
export const infer = (v) => {
|
|
65
|
+
if (v === null)
|
|
66
|
+
return { type: 'null' };
|
|
67
|
+
if (Array.isArray(v))
|
|
68
|
+
return { type: 'array', items: v.length ? v.map(infer).reduce(merge) : {} };
|
|
69
|
+
switch (typeof v) {
|
|
70
|
+
case 'string':
|
|
71
|
+
return { type: 'string' };
|
|
72
|
+
case 'number':
|
|
73
|
+
return { type: Number.isInteger(v) ? 'integer' : 'number' };
|
|
74
|
+
case 'boolean':
|
|
75
|
+
return { type: 'boolean' };
|
|
76
|
+
case 'object':
|
|
77
|
+
return { type: 'object', properties: Object.fromEntries(Object.entries(v).map(([k, x]) => [k, infer(x)])), required: Object.keys(v) };
|
|
78
|
+
}
|
|
79
|
+
return {};
|
|
80
|
+
};
|
|
81
|
+
export const probe = async (opts) => {
|
|
82
|
+
const base = opts.base.replace(/\/$/, '');
|
|
83
|
+
const defs = parseRoutes(readFileSync(opts.routes, 'utf8'), base);
|
|
84
|
+
const headers = { Accept: 'application/json' };
|
|
85
|
+
for (const h of opts.headers ?? []) {
|
|
86
|
+
const i = h.indexOf(':');
|
|
87
|
+
if (i > 0)
|
|
88
|
+
headers[h.slice(0, i).trim()] = h.slice(i + 1).trim();
|
|
89
|
+
}
|
|
90
|
+
const paths = {};
|
|
91
|
+
const results = [];
|
|
92
|
+
for (const d of defs) {
|
|
93
|
+
const paramNames = [...d.path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
|
|
94
|
+
const op = {
|
|
95
|
+
responses: { '200': { description: 'OK' } },
|
|
96
|
+
parameters: paramNames.map((name) => ({ name, in: 'path', required: true, schema: { type: 'string' } }))
|
|
97
|
+
};
|
|
98
|
+
let status = 'skipped';
|
|
99
|
+
if (d.method === 'GET' && !opts.offline) {
|
|
100
|
+
try {
|
|
101
|
+
const url = base + d.path.replace(/\{[^}]+\}/g, '1');
|
|
102
|
+
const res = await fetch(url, { headers, signal: AbortSignal.timeout(12000) });
|
|
103
|
+
status = String(res.status);
|
|
104
|
+
if (res.ok && (res.headers.get('content-type') ?? '').includes('json')) {
|
|
105
|
+
op.responses['200'].content = { 'application/json': { schema: infer(await res.json()) } };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
status = 'error';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
else if (d.method !== 'GET') {
|
|
113
|
+
op.requestBody = { content: { 'application/json': { schema: {} } } };
|
|
114
|
+
}
|
|
115
|
+
(paths[d.path] ??= {})[d.method.toLowerCase()] = op;
|
|
116
|
+
results.push({ route: `${d.method} ${d.path}`, status });
|
|
117
|
+
}
|
|
118
|
+
return { spec: { openapi: '3.0.3', info: { title: 'bati-probe', version: '0.0.0' }, servers: [{ url: base }], paths }, results };
|
|
119
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { TaskResult } from './types.js';
|
|
2
|
+
export declare const httpMethods: string[];
|
|
3
|
+
type Shape = {
|
|
4
|
+
type?: string | string[];
|
|
5
|
+
properties?: Record<string, Shape>;
|
|
6
|
+
required?: string[];
|
|
7
|
+
items?: Shape;
|
|
8
|
+
format?: string;
|
|
9
|
+
};
|
|
10
|
+
export interface Route {
|
|
11
|
+
method: string;
|
|
12
|
+
path: string;
|
|
13
|
+
framework: string;
|
|
14
|
+
file: string;
|
|
15
|
+
line: number;
|
|
16
|
+
middleware: string[];
|
|
17
|
+
controller?: string;
|
|
18
|
+
controllerFile?: string;
|
|
19
|
+
controllerLine?: number;
|
|
20
|
+
request?: Shape;
|
|
21
|
+
response?: Shape;
|
|
22
|
+
}
|
|
23
|
+
export declare function collectRoutes(dir: string): Promise<Route[]>;
|
|
24
|
+
export declare function routesToSpec(rows: Route[], title: string): {
|
|
25
|
+
openapi: string;
|
|
26
|
+
info: {
|
|
27
|
+
title: string;
|
|
28
|
+
version: string;
|
|
29
|
+
};
|
|
30
|
+
paths: Record<string, Record<string, unknown>>;
|
|
31
|
+
};
|
|
32
|
+
export declare function routes(options: {
|
|
33
|
+
dir: string;
|
|
34
|
+
openapi?: boolean;
|
|
35
|
+
out?: string;
|
|
36
|
+
}): Promise<TaskResult>;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { configuredOutput, loadConfig } from './config.js';
|
|
4
|
+
import { codePattern } from './deps.js';
|
|
5
|
+
import { listFiles, writeOutput } from './files.js';
|
|
6
|
+
export const httpMethods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];
|
|
7
|
+
const normalize = (...parts) => ('/' + parts.join('/')).replace(/\/{2,}/g, '/').replace(/\/$/, '') || '/';
|
|
8
|
+
const routePath = (value) => value.replace(/:([a-zA-Z_]\w*)\??/g, '{$1}').replace(/\{([^}]+)\?\}/g, '{$1}');
|
|
9
|
+
const staticRoutes = (verb) => verb === 'all' || verb === 'any' ? httpMethods : httpMethods.includes(verb) ? [verb] : [];
|
|
10
|
+
async function laravelRoutes(root, files) {
|
|
11
|
+
const php = await import('./php.js');
|
|
12
|
+
const resolve = await php.phpResolver(root, new Set(files));
|
|
13
|
+
const result = [];
|
|
14
|
+
const sources = new Map();
|
|
15
|
+
const load = async (file) => {
|
|
16
|
+
const cached = sources.get(file);
|
|
17
|
+
if (cached)
|
|
18
|
+
return cached;
|
|
19
|
+
const ast = php.parsePhpSource(await readFile(path.join(root, file), 'utf8'), file);
|
|
20
|
+
const imports = new Map();
|
|
21
|
+
let namespace = '';
|
|
22
|
+
for (const node of php.walkPhp(ast)) {
|
|
23
|
+
if (node.kind === 'namespace')
|
|
24
|
+
namespace = node.name;
|
|
25
|
+
if (node.kind === 'usegroup')
|
|
26
|
+
for (const item of node.items) {
|
|
27
|
+
const name = [node.name, item.name].filter(Boolean).join('\\');
|
|
28
|
+
imports.set(php.phpName(item.alias) || name.split('\\').at(-1), name);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const value = { ast, imports, namespace };
|
|
32
|
+
sources.set(file, value);
|
|
33
|
+
return value;
|
|
34
|
+
};
|
|
35
|
+
const lookup = (name, data) => {
|
|
36
|
+
const qualified = name.replace(/^\\/, '');
|
|
37
|
+
if (name.startsWith('\\'))
|
|
38
|
+
return resolve(qualified);
|
|
39
|
+
const [head, ...tail] = qualified.split('\\');
|
|
40
|
+
const imported = data.imports.get(head);
|
|
41
|
+
return resolve(imported ? [imported, ...tail].join('\\') : [data.namespace, qualified].filter(Boolean).join('\\')) ?? resolve(qualified);
|
|
42
|
+
};
|
|
43
|
+
const entries = (node) => node?.kind === 'array' ? node.items : [];
|
|
44
|
+
const list = (node) => (node?.kind === 'array' ? entries(node).map((entry) => entry.value) : [node]).flatMap((item) => {
|
|
45
|
+
const value = php.phpString(item) ?? (item?.kind === 'staticlookup' ? php.phpName(item.what) : '');
|
|
46
|
+
return value ? [value] : [];
|
|
47
|
+
});
|
|
48
|
+
const extract = async (name, data, method, request) => {
|
|
49
|
+
const file = lookup(name, data);
|
|
50
|
+
if (!file)
|
|
51
|
+
return;
|
|
52
|
+
const target = await load(file);
|
|
53
|
+
const methodNode = [...php.walkPhp(target.ast)].find((node) => node.kind === 'method' && php.phpName(node.name) === method);
|
|
54
|
+
const returned = [...php.walkPhp(methodNode?.body)].find((node) => node.kind === 'return' && node.expr?.kind === 'array');
|
|
55
|
+
if (!returned)
|
|
56
|
+
return;
|
|
57
|
+
const fields = Object.create(null);
|
|
58
|
+
const required = [];
|
|
59
|
+
for (const item of entries(returned.expr)) {
|
|
60
|
+
const field = php.phpString(item.key);
|
|
61
|
+
if (!field)
|
|
62
|
+
continue;
|
|
63
|
+
const rules = list(item.value).flatMap((rule) => rule.split('|'));
|
|
64
|
+
const valueType = request
|
|
65
|
+
? rules.find((rule) => ['integer', 'numeric', 'boolean', 'array', 'string', 'email', 'date', 'uuid'].includes(rule))
|
|
66
|
+
: { string: 'string', number: 'numeric', boolean: 'boolean', array: 'array' }[item.value.kind];
|
|
67
|
+
const type = valueType === 'numeric' ? 'number' : ['email', 'uuid', 'date'].includes(valueType ?? '') ? 'string' : valueType;
|
|
68
|
+
fields[field] = { ...(type ? { type: request && rules.includes('nullable') ? [type, 'null'] : type } : {}),
|
|
69
|
+
...(['email', 'uuid', 'date'].includes(valueType ?? '') ? { format: valueType } : {}), ...(type === 'array' ? { items: {} } : {}) };
|
|
70
|
+
if (request && rules.includes('required'))
|
|
71
|
+
required.push(field);
|
|
72
|
+
}
|
|
73
|
+
return { type: 'object', properties: fields, ...(required.length ? { required } : {}) };
|
|
74
|
+
};
|
|
75
|
+
for (const file of files.filter((name) => /^routes\/.*\.php$/.test(name))) {
|
|
76
|
+
const data = await load(file);
|
|
77
|
+
const register = async (scope, node, verb, uri, target, resourceMethod, resourceClass) => {
|
|
78
|
+
const literal = php.phpString(target);
|
|
79
|
+
const targetParts = entries(target).map((item) => item.value);
|
|
80
|
+
const controllerName = resourceClass || (literal?.includes('@') ? literal.split('@')[0] : undefined) ||
|
|
81
|
+
php.phpName(targetParts[0]?.what) || php.phpName(target?.what) || scope.controller;
|
|
82
|
+
const method = resourceMethod || (literal?.includes('@') ? literal.split('@')[1] : undefined) ||
|
|
83
|
+
php.phpString(targetParts[1]) || (controllerName === scope.controller ? literal : undefined) || '__invoke';
|
|
84
|
+
const route = { framework: 'Laravel', method: verb.toUpperCase(), path: routePath(normalize(scope.prefix, uri)), file,
|
|
85
|
+
line: node.loc?.start.line ?? 1, middleware: [...new Set(scope.middleware)] };
|
|
86
|
+
if (controllerName) {
|
|
87
|
+
route.controller = `${controllerName}::${method}`;
|
|
88
|
+
route.controllerFile = lookup(controllerName, data);
|
|
89
|
+
if (route.controllerFile) {
|
|
90
|
+
const controller = await load(route.controllerFile);
|
|
91
|
+
const action = [...php.walkPhp(controller.ast)].find((member) => member.kind === 'method' && php.phpName(member.name) === method);
|
|
92
|
+
route.controllerLine = action?.loc?.start.line;
|
|
93
|
+
for (const argument of action?.arguments ?? []) {
|
|
94
|
+
const type = php.phpName(argument.type);
|
|
95
|
+
if (type)
|
|
96
|
+
route.request ??= await extract(type, controller, 'rules', true);
|
|
97
|
+
}
|
|
98
|
+
const names = [php.phpName(action?.type), ...[...php.walkPhp(action?.body)].flatMap((child) => child.kind === 'new' ? [php.phpName(child.what)] : child.kind === 'staticlookup' && php.phpName(child.offset) === 'collection' ? [php.phpName(child.what)] : [])];
|
|
99
|
+
for (const name of names.filter(Boolean))
|
|
100
|
+
route.response ??= await extract(name, controller, 'toArray', false);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
result.push(route);
|
|
104
|
+
};
|
|
105
|
+
const walk = async (node, inherited) => {
|
|
106
|
+
if (Array.isArray(node)) {
|
|
107
|
+
for (const item of node)
|
|
108
|
+
await walk(item, inherited);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (!node || typeof node !== 'object')
|
|
112
|
+
return;
|
|
113
|
+
const value = node;
|
|
114
|
+
if (!value.kind)
|
|
115
|
+
return;
|
|
116
|
+
const calls = [];
|
|
117
|
+
let cursor = value;
|
|
118
|
+
while (cursor?.kind === 'call' && ['staticlookup', 'propertylookup'].includes(cursor.what?.kind)) {
|
|
119
|
+
calls.unshift({ name: php.phpName(cursor.what.offset).toLowerCase(), args: cursor.arguments });
|
|
120
|
+
cursor = cursor.what.what;
|
|
121
|
+
}
|
|
122
|
+
const facade = php.phpName(cursor);
|
|
123
|
+
if (calls.length && (facade.split('\\').at(-1) === 'Route' || data.imports.get(facade)?.endsWith('\\Route'))) {
|
|
124
|
+
const scope = { ...inherited, middleware: [...inherited.middleware] };
|
|
125
|
+
for (const { name, args } of calls) {
|
|
126
|
+
if (name === 'prefix')
|
|
127
|
+
scope.prefix = normalize(scope.prefix, php.phpString(args[0]) ?? '');
|
|
128
|
+
if (name === 'middleware')
|
|
129
|
+
scope.middleware.push(...list(args[0]));
|
|
130
|
+
if (name === 'controller')
|
|
131
|
+
scope.controller = php.phpName(args[0]?.what) || php.phpString(args[0]);
|
|
132
|
+
}
|
|
133
|
+
const group = calls.find(({ name }) => name === 'group');
|
|
134
|
+
if (group) {
|
|
135
|
+
const callback = group.args.at(-1);
|
|
136
|
+
for (const entry of entries(group.args[0])) {
|
|
137
|
+
if (php.phpString(entry.key) === 'prefix')
|
|
138
|
+
scope.prefix = normalize(scope.prefix, php.phpString(entry.value) ?? '');
|
|
139
|
+
if (php.phpString(entry.key) === 'middleware')
|
|
140
|
+
scope.middleware.push(...list(entry.value));
|
|
141
|
+
}
|
|
142
|
+
await walk(callback?.body, scope);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const call = calls.find(({ name }) => ['resource', 'apiresource', 'match', 'any', ...httpMethods].includes(name));
|
|
146
|
+
if (!call)
|
|
147
|
+
return;
|
|
148
|
+
if (['resource', 'apiresource'].includes(call.name)) {
|
|
149
|
+
const rawUri = php.phpString(call.args[0]);
|
|
150
|
+
if (rawUri === undefined)
|
|
151
|
+
return;
|
|
152
|
+
const singular = rawUri.split('/').at(-1).replace(/ies$/, 'y').replace(/(?<!i)s$/, '').replace(/-/g, '_');
|
|
153
|
+
const item = `${rawUri}/{${singular}}`;
|
|
154
|
+
const entries = [['get', rawUri, 'index'], ['post', rawUri, 'store'], ['get', item, 'show'],
|
|
155
|
+
['put', item, 'update'], ['patch', item, 'update'], ['delete', item, 'destroy']];
|
|
156
|
+
if (call.name === 'resource')
|
|
157
|
+
entries.push(['get', rawUri + '/create', 'create'], ['get', item + '/edit', 'edit']);
|
|
158
|
+
const only = calls.find(({ name }) => name === 'only');
|
|
159
|
+
const except = calls.find(({ name }) => name === 'except');
|
|
160
|
+
for (const [verb, uri, method] of entries)
|
|
161
|
+
if ((!only || only.args.flatMap(list).includes(method)) && !except?.args.flatMap(list).includes(method)) {
|
|
162
|
+
await register(scope, value, verb, uri, undefined, method, php.phpName(call.args[1]?.what) || php.phpString(call.args[1]));
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const match = call.name === 'match';
|
|
167
|
+
const uri = php.phpString(call.args[match ? 1 : 0]);
|
|
168
|
+
if (uri !== undefined)
|
|
169
|
+
for (const method of match ? list(call.args[0]).flatMap((verb) => staticRoutes(verb.toLowerCase())) : staticRoutes(call.name)) {
|
|
170
|
+
await register(scope, value, method, uri, call.args[match ? 2 : 1]);
|
|
171
|
+
}
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
for (const [key, child] of Object.entries(value))
|
|
175
|
+
if (key !== 'loc')
|
|
176
|
+
await walk(child, inherited);
|
|
177
|
+
};
|
|
178
|
+
const prefix = file === 'routes/api.php' ? '/api' : '';
|
|
179
|
+
await walk(data.ast, { prefix, middleware: [prefix ? 'api' : 'web'] });
|
|
180
|
+
}
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
async function javascriptRoutes(root, files) {
|
|
184
|
+
const { default: ts } = await import('typescript');
|
|
185
|
+
const results = [];
|
|
186
|
+
const mounts = [];
|
|
187
|
+
const locals = [];
|
|
188
|
+
for (const file of files.filter((name) => !name.endsWith('.php'))) {
|
|
189
|
+
const source = ts.createSourceFile(file, await readFile(path.join(root, file), 'utf8'), ts.ScriptTarget.Latest, true);
|
|
190
|
+
const location = (node) => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
|
|
191
|
+
const literal = (node) => node && ts.isStringLiteralLike(node) ? node.text : undefined;
|
|
192
|
+
const next = file.match(/^(?:src\/)?(app|pages)\/(.+)\.[jt]sx?$/);
|
|
193
|
+
if (next) {
|
|
194
|
+
const app = next[1] === 'app';
|
|
195
|
+
const isAppRoute = /(?:^|\/)route$/.test(next[2]);
|
|
196
|
+
const tail = next[2].split('/');
|
|
197
|
+
if ((app && (isAppRoute || tail.at(-1) === 'page')) || (!app && !/^_/.test(tail[0]))) {
|
|
198
|
+
const segments = (app ? tail.slice(0, -1) : tail.filter((part, index) => part !== 'index' || index !== tail.length - 1))
|
|
199
|
+
.filter((part) => !part.startsWith('@') && !/^\([^)]*\)$/.test(part))
|
|
200
|
+
.map((part) => part.replace(/^\[\[?\.{0,3}([^\]]+)\]\]?$/, '{$1}'));
|
|
201
|
+
const url = normalize(...segments);
|
|
202
|
+
const methods = new Set();
|
|
203
|
+
const addMethod = (name) => { if (name && httpMethods.includes(name.toLowerCase()))
|
|
204
|
+
methods.add(name.toUpperCase()); };
|
|
205
|
+
const visit = (node) => {
|
|
206
|
+
if (isAppRoute) {
|
|
207
|
+
if (ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
208
|
+
if (ts.isFunctionDeclaration(node))
|
|
209
|
+
addMethod(node.name?.text);
|
|
210
|
+
if (ts.isVariableStatement(node))
|
|
211
|
+
node.declarationList.declarations.forEach((value) => addMethod(value.name.getText(source)));
|
|
212
|
+
}
|
|
213
|
+
if (ts.isExportDeclaration(node) && node.exportClause && ts.isNamedExports(node.exportClause))
|
|
214
|
+
node.exportClause.elements.forEach((element) => addMethod(element.name.text));
|
|
215
|
+
}
|
|
216
|
+
else if (tail[0] === 'api' && ts.isBinaryExpression(node)) {
|
|
217
|
+
if (/^(?:\w+\.)method$/.test(node.left.getText(source)))
|
|
218
|
+
addMethod(literal(node.right));
|
|
219
|
+
if (/^(?:\w+\.)method$/.test(node.right.getText(source)))
|
|
220
|
+
addMethod(literal(node.left));
|
|
221
|
+
}
|
|
222
|
+
else if (tail[0] === 'api' && ts.isSwitchStatement(node) && /\.method$/.test(node.expression.getText(source))) {
|
|
223
|
+
for (const clause of node.caseBlock.clauses)
|
|
224
|
+
if (ts.isCaseClause(clause))
|
|
225
|
+
addMethod(literal(clause.expression));
|
|
226
|
+
}
|
|
227
|
+
ts.forEachChild(node, visit);
|
|
228
|
+
};
|
|
229
|
+
visit(source);
|
|
230
|
+
if (!isAppRoute && !methods.size)
|
|
231
|
+
methods.add(!app && tail[0] === 'api' ? 'ANY' : 'GET');
|
|
232
|
+
for (const method of methods)
|
|
233
|
+
results.push({ method, path: url, framework: app ? 'Next.js App' : 'Next.js Pages', file, line: 1, middleware: [] });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const routerNames = new Map();
|
|
237
|
+
const imports = new Map();
|
|
238
|
+
for (const node of source.statements)
|
|
239
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
240
|
+
const specifier = node.moduleSpecifier.text;
|
|
241
|
+
const clause = node.importClause;
|
|
242
|
+
const names = clause?.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements.map((element) => element.name.text) : [];
|
|
243
|
+
if (clause?.name)
|
|
244
|
+
names.push(clause.name.text);
|
|
245
|
+
for (const name of names)
|
|
246
|
+
imports.set(name, specifier);
|
|
247
|
+
}
|
|
248
|
+
const discover = (node) => {
|
|
249
|
+
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && (ts.isCallExpression(node.initializer) || ts.isNewExpression(node.initializer))) {
|
|
250
|
+
const expression = node.initializer.expression.getText(source);
|
|
251
|
+
const framework = imports.get(expression.split('.')[0]);
|
|
252
|
+
if (framework && ['express', 'fastify', 'hono'].includes(framework))
|
|
253
|
+
routerNames.set(node.name.text, framework);
|
|
254
|
+
}
|
|
255
|
+
ts.forEachChild(node, discover);
|
|
256
|
+
};
|
|
257
|
+
discover(source);
|
|
258
|
+
const visit = (node) => {
|
|
259
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
|
|
260
|
+
const owner = node.expression.expression.getText(source);
|
|
261
|
+
const framework = routerNames.get(owner);
|
|
262
|
+
if (framework) {
|
|
263
|
+
const method = node.expression.name.text.toLowerCase();
|
|
264
|
+
const router = `${file}:${owner}`;
|
|
265
|
+
const add = (verbs, pathname, handlers) => {
|
|
266
|
+
for (const verb of verbs)
|
|
267
|
+
locals.push({ method: verb.toUpperCase(), path: routePath(normalize(pathname)), framework, file, line: location(node), router,
|
|
268
|
+
middleware: handlers.slice(0, -1).map((handler) => handler.getText(source)), controller: handlers.at(-1) && (ts.isIdentifier(handlers.at(-1)) || ts.isPropertyAccessExpression(handlers.at(-1))) ? handlers.at(-1).getText(source) : undefined });
|
|
269
|
+
};
|
|
270
|
+
const first = node.arguments[0];
|
|
271
|
+
const pathname = literal(first);
|
|
272
|
+
if (pathname !== undefined)
|
|
273
|
+
add(staticRoutes(method), pathname, node.arguments.slice(1));
|
|
274
|
+
if (method === 'route' && first && ts.isObjectLiteralExpression(first)) {
|
|
275
|
+
const props = new Map(first.properties.flatMap((prop) => ts.isPropertyAssignment(prop) ? [[prop.name.getText(source).replace(/['"]/g, ''), prop.initializer]] : []));
|
|
276
|
+
const position = literal(props.get('url')) ?? literal(props.get('path'));
|
|
277
|
+
const methods = props.get('method');
|
|
278
|
+
const preHandler = props.get('preHandler');
|
|
279
|
+
if (position && methods)
|
|
280
|
+
add((ts.isArrayLiteralExpression(methods) ? methods.elements : [methods]).flatMap((item) => staticRoutes(literal(item)?.toLowerCase() ?? '')), position, [preHandler, props.get('handler')].filter((item) => !!item));
|
|
281
|
+
}
|
|
282
|
+
if (['use', 'route'].includes(method) && pathname !== undefined) {
|
|
283
|
+
const child = node.arguments.at(-1)?.getText(source);
|
|
284
|
+
if (child && routerNames.has(child) && child !== owner)
|
|
285
|
+
mounts.push({ parent: router, child: `${file}:${child}`, prefix: pathname, middleware: node.arguments.slice(1, -1).map((item) => item.getText(source)) });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
ts.forEachChild(node, visit);
|
|
290
|
+
};
|
|
291
|
+
visit(source);
|
|
292
|
+
}
|
|
293
|
+
const expand = (route, router, seen) => {
|
|
294
|
+
if (seen.has(router))
|
|
295
|
+
return [];
|
|
296
|
+
const parents = mounts.filter((mount) => mount.child === router);
|
|
297
|
+
if (!parents.length)
|
|
298
|
+
return [route];
|
|
299
|
+
return parents.flatMap((parent) => expand({ ...route, path: normalize(parent.prefix, route.path), middleware: [...parent.middleware, ...route.middleware] }, parent.parent, new Set([...seen, router])));
|
|
300
|
+
};
|
|
301
|
+
for (const { router, ...route } of locals)
|
|
302
|
+
results.push(...expand(route, router, new Set()));
|
|
303
|
+
return results;
|
|
304
|
+
}
|
|
305
|
+
export async function collectRoutes(dir) {
|
|
306
|
+
const root = path.resolve(dir);
|
|
307
|
+
const files = await listFiles(root, codePattern);
|
|
308
|
+
const [laravel, javascript] = await Promise.all([laravelRoutes(root, files), javascriptRoutes(root, files)]);
|
|
309
|
+
return [...laravel, ...javascript].sort((a, b) => a.framework.localeCompare(b.framework) || a.path.localeCompare(b.path) || a.method.localeCompare(b.method));
|
|
310
|
+
}
|
|
311
|
+
export function routesToSpec(rows, title) {
|
|
312
|
+
const paths = Object.create(null);
|
|
313
|
+
for (const row of rows) {
|
|
314
|
+
for (const method of row.method === 'ANY' ? httpMethods : [row.method.toLowerCase()]) {
|
|
315
|
+
const parameters = [...row.path.matchAll(/\{([^}]+)\}/g)].map((match) => ({ name: match[1], in: 'path', required: true, schema: { type: 'string' } }));
|
|
316
|
+
(paths[row.path] ??= {})[method] = {
|
|
317
|
+
...(parameters.length ? { parameters } : {}),
|
|
318
|
+
...(row.middleware.length ? { 'x-middleware': row.middleware } : {}),
|
|
319
|
+
...(row.controller ? { 'x-controller': row.controller } : {}),
|
|
320
|
+
...(row.request && !['get', 'head'].includes(method) ? { requestBody: { content: { 'application/json': { schema: row.request } } } } : {}),
|
|
321
|
+
responses: { '200': { description: 'Successful response', ...(row.response ? { content: { 'application/json': { schema: row.response } } } : {}) } }
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return { openapi: '3.1.0', info: { title, version: '1.0.0' }, paths };
|
|
326
|
+
}
|
|
327
|
+
export async function routes(options) {
|
|
328
|
+
const root = path.resolve(options.dir);
|
|
329
|
+
const rows = await collectRoutes(root);
|
|
330
|
+
let output;
|
|
331
|
+
if (options.openapi || options.out) {
|
|
332
|
+
const file = configuredOutput(root, await loadConfig(root), 'routes', 'bati-openapi.json', options.out);
|
|
333
|
+
output = await writeOutput(file, JSON.stringify(routesToSpec(rows, path.basename(root)), null, 2) + '\n');
|
|
334
|
+
}
|
|
335
|
+
const lines = [`${rows.length} routes`];
|
|
336
|
+
let framework = '';
|
|
337
|
+
for (const row of rows) {
|
|
338
|
+
if (row.framework !== framework)
|
|
339
|
+
lines.push(framework = row.framework);
|
|
340
|
+
lines.push(` ${row.method.padEnd(7)} ${row.path}${row.middleware.length ? ' [' + row.middleware.join(', ') + ']' : ''}${row.controller ? ' → ' + row.controller : ''} ${row.controllerFile ?? row.file}:${row.controllerLine ?? row.line}`);
|
|
341
|
+
}
|
|
342
|
+
return { title: 'Project routes', output, lines: [...lines, ...(output ? [output] : [])], data: rows };
|
|
343
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ProjectModel } from './types.js';
|
|
2
|
+
export declare const IGNORE: string[];
|
|
3
|
+
export declare const scanProject: (dir: string) => Promise<ProjectModel>;
|
|
4
|
+
export declare const filterModel: (model: ProjectModel, query?: string) => ProjectModel;
|
|
5
|
+
export interface TreeRow {
|
|
6
|
+
prefix: string;
|
|
7
|
+
name: string;
|
|
8
|
+
dir: boolean;
|
|
9
|
+
role?: string;
|
|
10
|
+
meta?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare const treeRows: (model: ProjectModel) => TreeRow[];
|
|
13
|
+
export declare const roleStats: (model: ProjectModel) => Array<[string, number]>;
|