@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
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
+ <img src="assets/bati-mark.svg" alt="bati — map the shape of your codebase" width="168" />
3
+ <h1>bati</h1>
4
+ <p><strong>See how a codebase fits together, right from the terminal.</strong></p>
5
+ <p>Repository maps · API tooling · project health · AI-ready context</p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <p>
8
+ <a href="https://github.com/itashia/bati/actions/workflows/ci.yml"><img src="https://github.com/itashia/bati/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI status"></a>
9
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/Node.js-20%2B-9FE870?logo=nodedotjs&logoColor=101820" alt="Node.js 20+"></a>
10
+ <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-5-7AA2F7?logo=typescript&logoColor=101820" alt="TypeScript"></a>
11
+ </p>
12
+
13
+ <p><a href="#quickstart">Quickstart</a> · <a href="#analyze-a-project">Commands</a> · <a href="#work-with-openapi">OpenAPI</a> · <a href="#connect-an-mcp-client">MCP</a> · <a href="#run-in-ci">GitHub Actions</a></p>
14
+ </div>
15
+
16
+ ---
17
+
18
+ bati brings repository maps, API tooling, and project health checks into one CLI and Ink dashboard. Explore TypeScript, JavaScript, and PHP code from the terminal, then use the same commands with `--json` in CI.
19
+
20
+ ![Entity relationship diagram generated by bati from the Laravel fixture. Profiles reference users through user_id.](demo/schema.svg)
21
+
22
+ *Generated from the included Laravel migrations with `bati db --format svg`.*
23
+
24
+ ## Quickstart
25
+
26
+ Build from source with Node.js 24. The resulting CLI targets Node.js 20 and later.
27
+
28
+ ```sh
29
+ git clone https://github.com/itashia/bati.git
30
+ cd bati
31
+ npm ci
32
+ npm run build
33
+ node dist/cli.js
34
+ ```
35
+
36
+ Try the included fixtures to inspect a Laravel route tree, render an interactive dependency graph, and generate AI context.
37
+
38
+ ```sh
39
+ node dist/cli.js routes test/fixtures/laravel
40
+ node dist/cli.js deps test/fixtures/express --format html --out deps.html
41
+ node dist/cli.js pack test/fixtures/next --budget 12000 --out context.xml
42
+ ```
43
+
44
+ Open `deps.html` in a browser to pan, zoom, search by file name, or highlight a file’s neighbours. Run `npm link` from the repository root to use the `bati` command directly.
45
+
46
+ | Dashboard key | Action |
47
+ | --- | --- |
48
+ | **↑ / ↓** and **Enter** | Navigate and open a tool |
49
+ | **/** | Search commands and files |
50
+ | **s** | Search classes, routes, and OpenAPI endpoints |
51
+ | **p** | Switch recent projects or preview a diagram from its result screen |
52
+ | **Esc** | Return to the previous screen |
53
+
54
+ Kitty, iTerm2, and sixel-capable terminals can show diagrams inline. Other terminals display the generated file path.
55
+
56
+ ## Analyze a project
57
+
58
+ | Command | Result |
59
+ | --- | --- |
60
+ | `bati dashboard [dir]` | File roles, class and route counts, dependency cycles, and hotspots |
61
+ | `bati search <query> [dir]` | Fuzzy matches across files, classes, routes, and API operations |
62
+ | `bati recent [dir]` | List recent projects or remember a project directory |
63
+ | `bati map [dir]` | Directory tree with inferred file roles |
64
+ | `bati pack [dir] --budget 48000 --format xml --guides` | AI context and optional `CLAUDE.md` and `AGENTS.md` guides |
65
+ | `bati deps [dir] --format html --out deps.html` | File imports, cycles, orphan candidates, unused exports, and god modules |
66
+ | `bati routes [dir] --openapi` | Framework route tree and inferred OpenAPI skeleton |
67
+ | `bati classes [dir] --format svg` | Class diagram in SVG, PNG, Mermaid, or JSON |
68
+ | `bati db [dir] --format mermaid` | ER diagram in Mermaid, SVG, or PNG, or schema data in JSON |
69
+ | `bati db [dir] --format types` | TypeScript table types. Use `--format eloquent` for model docblocks |
70
+ | `bati preview <file>` | Inline PNG or SVG preview when supported |
71
+ | `bati fmt [paths...] --check` | Formatting diagnostics for TS, JS, PHP, JSON, CSS, Markdown, YAML, and other supported files |
72
+ | `bati doctor [dir] --env-schema` | Redacted secret findings, environment schema, dependency audit and outdated findings, and a health score |
73
+
74
+ Packs honor nested `.gitignore` rules and exclude common credential paths. They rank files by detected role, incoming imports, and Git churn. The packer currently uses UTF-8 bytes as a conservative token bound, so a pack can be smaller than a model-specific tokenizer would allow. Use `--format markdown` for fenced source blocks. Guide generation preserves existing `CLAUDE.md` and `AGENTS.md` files.
75
+
76
+ Dependency and route results come from static analysis. Dependency checks resolve TypeScript aliases, ESM extensions, CommonJS requires, and Composer PSR-4 imports. Cycle diagnostics identify strongly connected groups. Orphan and unused export findings are candidates for review, since runtime registrations and public package consumers may be invisible locally.
77
+
78
+ Route extraction recognizes Laravel routes and resource controllers, Next.js App and Pages routes, and statically identifiable Express, Fastify, and Hono handlers. Laravel request and response schemas come from literal FormRequest rules and API Resource mappings. The database extractor covers common Laravel migration operations, Prisma models, Drizzle table definitions, and SQL DDL. Dynamic framework registration, arbitrary migration code, and dialect-specific SQL can require review.
79
+
80
+ ## Work with OpenAPI
81
+
82
+ ```sh
83
+ bati api gen openapi.yaml --zod --query --split --out src/api --watch
84
+ bati api diff openapi.old.yaml openapi.yaml --out api-changes.md
85
+ bati api diff openapi.old.yaml openapi.yaml --format json --out api-changes.json
86
+ bati api mock openapi.yaml --port 4010
87
+ bati api probe --base http://localhost:3000 --routes routes.txt
88
+ ```
89
+
90
+ Generated validators use Zod, and generated hooks use TanStack Query. Install those packages in the consuming project when using those outputs. The mock server listens on loopback. It prefers examples supplied in the spec and otherwise generates sample values from schemas. Send `X-Mock-Status` to select a documented status. Watch mode accepts a local spec and re-runs generation after saves.
91
+
92
+ ## Configure a project
93
+
94
+ Create `bati.config.ts` at the project root. Install bati as a local dev dependency if the config imports `bati/config`. bati executes this file, including any imported plugins, so use configuration from repositories you trust.
95
+
96
+ ```ts
97
+ import { defineConfig, type Plugin } from 'bati/config';
98
+
99
+ const plugin: Plugin = {
100
+ name: 'project',
101
+ scanners: [async (_, file) => file.path.startsWith('domain/') ? { role: 'domain' } : undefined],
102
+ commands: [{
103
+ name: 'project-root',
104
+ description: 'Print the active project directory',
105
+ async run({ root }) {
106
+ return { title: 'Project directory', lines: [root] };
107
+ },
108
+ }],
109
+ };
110
+
111
+ export default defineConfig({
112
+ theme: { primary: '#7C5CFF', gradient: ['#7C5CFF', '#FF5CAA', '#00E5C7'] },
113
+ ignore: ['generated/**', '**/*.snap'],
114
+ outputs: { classes: 'artifacts/classes.svg', routes: 'artifacts/openapi.json' },
115
+ plugins: [plugin],
116
+ });
117
+ ```
118
+
119
+ Output paths in config are relative to the project root. The CLI resolves an explicit `--out` relative to the working directory. Output keys include `api`, `api-diff`, `classes`, `pack`, `deps`, `routes`, `db`, and `env`. Plugins can register scanners, generators, commands, and MCP tools with Zod input shapes. Run `bati config --json` to inspect resolved settings.
120
+
121
+ ## Connect an MCP client
122
+
123
+ ```sh
124
+ bati mcp --watch --print-config
125
+ bati mcp install --client claude-code --watch --dry-run
126
+ bati mcp install --client cursor --watch
127
+ ```
128
+
129
+ Claude Code uses the project’s `.mcp.json`, Cursor uses `.cursor/mcp.json`, and Claude Desktop uses its user configuration directory. The installer preserves other servers, backs up changed files, and requires `--replace` to replace a different bati configuration.
130
+
131
+ MCP includes project and class queries, `find_usages`, `impact_of_change`, `list_routes`, `explain_route`, `db_schema`, and `diff_summary`. File outlines are readable as `bati://outline/{id}` resources. `bati mcp --watch` serves MCP over stdio and refreshes caches after file changes. Use `--json` to print the client configuration.
132
+
133
+ ## Run in CI
134
+
135
+ Most commands emit a JSON object with `title`, `lines`, and command-specific `data`. The `map` command emits the project model, and MCP config output uses the client config shape. Exit code **0** means success, **1** means a failed check or operation, and **2** means invalid CLI usage or a required audit was unavailable. Dependency checks fail on cycles. API diffs fail on breaking changes. Doctor checks fail on error-level findings.
136
+
137
+ For a workflow in this repository, check out the base and proposed OpenAPI files and use the local composite action.
138
+
139
+ ```yaml
140
+ - uses: actions/checkout@v6
141
+ with:
142
+ fetch-depth: 0
143
+ - run: git show "origin/main:openapi.yaml" > "$RUNNER_TEMP/base-openapi.yaml"
144
+ - uses: ./
145
+ with:
146
+ directory: .
147
+ old-spec: ${{ runner.temp }}/base-openapi.yaml
148
+ new-spec: openapi.yaml
149
+ ```
150
+
151
+ The action runs all configured checks, writes annotations and a job summary, and skips API comparison when both spec inputs are empty. It disables executable bati project config. Set `offline: 'true'` if CI should run without package registry requests.
152
+
153
+ ## Develop, record, and release
154
+
155
+ ```sh
156
+ npm ci
157
+ npm run build
158
+ npm test
159
+ vhs demo/dashboard.tape
160
+ vhs demo/analysis.tape
161
+ ```
162
+
163
+ Use Node.js 24 for development and Vitest. The distributed CLI targets Node.js 20+. The VHS tapes record against the fixture projects and write GIFs under `demo/`. Build first and run VHS from the repository root.
164
+
165
+ Create a release note with `npm run changeset`. The release workflow opens a version PR and publishes an ESM bundle after the version lands on `main`. Configure npm trusted publishing for `publish.yml` and use a public GitHub repository for provenance. [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/)
@@ -0,0 +1,26 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 240" role="img" aria-labelledby="title desc">
2
+ <title id="title">bati</title>
3
+ <desc id="desc">A bright green terminal cursor framed by a map of connected code modules.</desc>
4
+ <defs>
5
+ <linearGradient id="glow" x1="0" y1="0" x2="1" y2="1">
6
+ <stop offset="0" stop-color="#b8ff6a"/>
7
+ <stop offset="1" stop-color="#62e6c6"/>
8
+ </linearGradient>
9
+ <linearGradient id="panel" x1="0" y1="0" x2="1" y2="1">
10
+ <stop offset="0" stop-color="#202b35"/>
11
+ <stop offset="1" stop-color="#111820"/>
12
+ </linearGradient>
13
+ </defs>
14
+ <rect x="8" y="8" width="224" height="224" rx="54" fill="#101820"/>
15
+ <rect x="9" y="9" width="222" height="222" rx="53" fill="none" stroke="#34434e" stroke-width="2"/>
16
+ <path d="M75 76h-9a9 9 0 0 0-9 9v20m0 30v20a9 9 0 0 0 9 9h9m90-88h9a9 9 0 0 1 9 9v20m0 30v20a9 9 0 0 1-9 9h-9" fill="none" stroke="#52636d" stroke-width="5" stroke-linecap="round"/>
17
+ <rect x="30" y="91" width="39" height="32" rx="10" fill="url(#panel)" stroke="#62e6c6" stroke-width="3"/>
18
+ <rect x="171" y="91" width="39" height="32" rx="10" fill="url(#panel)" stroke="#62e6c6" stroke-width="3"/>
19
+ <rect x="30" y="135" width="39" height="32" rx="10" fill="url(#panel)" stroke="#b8ff6a" stroke-width="3"/>
20
+ <rect x="171" y="135" width="39" height="32" rx="10" fill="url(#panel)" stroke="#b8ff6a" stroke-width="3"/>
21
+ <path d="M42 107h15m-15 44h15m126-44h-15m15 44h-15" stroke="#d5e0e3" stroke-width="4" stroke-linecap="round"/>
22
+ <path d="M89 68h62a12 12 0 0 1 12 12v80a12 12 0 0 1-12 12H89a12 12 0 0 1-12-12V80a12 12 0 0 1 12-12Z" fill="url(#panel)" stroke="#44545e" stroke-width="3"/>
23
+ <path d="m102 105 17 15-17 15" fill="none" stroke="url(#glow)" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/>
24
+ <path d="M130 137h17" stroke="#b8ff6a" stroke-width="8" stroke-linecap="round"/>
25
+ <circle cx="120" cy="47" r="4" fill="#b8ff6a"/>
26
+ </svg>
package/dist/api.ts ADDED
File without changes
Binary file
@@ -0,0 +1,8 @@
1
+ {
2
+ "openapi": "3.1.0",
3
+ "info": {
4
+ "title": "dist",
5
+ "version": "1.0.0"
6
+ },
7
+ "paths": {}
8
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ import { Command, CommanderError } from 'commander';
3
+ import { createRequire } from 'node:module';
4
+ import { loadConfig, pluginCommands } from './core/config.js';
5
+ const { version } = createRequire(import.meta.url)('../package.json');
6
+ const json = process.argv.includes('--json');
7
+ const program = new Command('bati')
8
+ .description('Terminal toolkit for API types, formatting, class maps and AI context')
9
+ .version(version)
10
+ .option('--json', 'emit machine-readable output')
11
+ .exitOverride()
12
+ .configureOutput({ writeErr: (message) => { if (!json)
13
+ process.stderr.write(message); } });
14
+ function show(result) {
15
+ process.exitCode = result.exitCode ?? 0;
16
+ if (json)
17
+ console.log(JSON.stringify(result));
18
+ else
19
+ console.log([result.title, ...result.lines.map((line) => ' ' + line)].join('\n'));
20
+ }
21
+ program.action(async () => {
22
+ const config = await loadConfig();
23
+ if (json)
24
+ return show({ title: 'bati commands', lines: program.commands.map((command) => command.name()) });
25
+ const [{ createElement }, { render }, { App }] = await Promise.all([import('react'), import('ink'), import('./ui/App.js')]);
26
+ render(createElement(App, { config }));
27
+ });
28
+ const api = program.command('api').description('API tooling');
29
+ api.command('gen <spec>')
30
+ .description('Generate TypeScript types and a typed client from OpenAPI')
31
+ .option('-o, --out <file>', 'output file')
32
+ .option('--types-only', 'skip the client')
33
+ .option('--base-url <url>', 'override the default base URL')
34
+ .option('--zod', 'generate Zod validators')
35
+ .option('--query', 'generate TanStack Query hooks')
36
+ .option('--split', 'emit separate files in the output directory')
37
+ .option('--watch', 'regenerate when a local spec changes')
38
+ .action(async (spec, options) => {
39
+ const { apiGen } = await import('./core/tasks.js');
40
+ const run = () => apiGen({ spec, ...options });
41
+ if (options.watch && /^https?:\/\//i.test(spec))
42
+ throw new Error('Watch mode requires a local specification');
43
+ show(await run());
44
+ if (options.watch)
45
+ (await import('./core/api.js')).watchSpec(spec, run, show);
46
+ });
47
+ api.command('diff <old> <next>').description('Compare OpenAPI specifications')
48
+ .option('-o, --out <file>', 'report file')
49
+ .option('-f, --format <format>', 'markdown | json')
50
+ .action(async (old, next, options) => show(await (await import('./core/api.js')).apiDiff({ old, next, ...options })));
51
+ api.command('mock <spec>').description('Run a local mock server')
52
+ .option('-p, --port <port>', 'local port', '4010')
53
+ .action(async (spec, options) => show((await (await import('./core/api.js')).startMock({ spec, port: Number(options.port) })).result));
54
+ api.command('probe')
55
+ .description('Build a client from a base URL and a routes file')
56
+ .requiredOption('-b, --base <url>', 'base API URL')
57
+ .requiredOption('-r, --routes <file>', 'routes.json, routes.txt or sitemap.xml')
58
+ .option('-o, --out <file>', 'output file')
59
+ .option('-H, --header <header...>', 'extra request headers')
60
+ .option('--offline', 'scaffold without calling the API')
61
+ .option('--types-only', 'skip the client')
62
+ .action(async (options) => show(await (await import('./core/tasks.js')).apiProbe({ ...options, headers: options.header })));
63
+ program.command('fmt [paths...]').description('Format TS, JS, PHP and other source files')
64
+ .option('--check', 'report formatting changes without writing')
65
+ .action(async (paths, options) => show(await (await import('./core/tasks.js')).fmt({ paths, ...options })));
66
+ program.command('classes [dir]').description('Render an object model')
67
+ .option('-f, --format <format>', 'png | svg | mermaid | json', 'png')
68
+ .option('-o, --out <file>', 'output file')
69
+ .option('--filter <text>', 'match classes and include their neighbours')
70
+ .action(async (dir = '.', options) => show(await (await import('./core/tasks.js')).classes({ dir, ...options })));
71
+ program.command('map [dir]').description('Print the project tree with file roles')
72
+ .action(async (dir = '.') => {
73
+ const { scanProject, treeRows, roleStats } = await import('./core/scan.js');
74
+ const model = await scanProject(dir);
75
+ if (json)
76
+ console.log(JSON.stringify(model));
77
+ else
78
+ show({ title: 'Project map', lines: [
79
+ ...treeRows(model).map((row) => row.prefix + row.name + (row.role ? ` ‹${row.role}›` : '') + (row.meta ? ' ' + row.meta : '')),
80
+ '',
81
+ roleStats(model).map(([role, count]) => `${role} ${count}`).join(' · ')
82
+ ] });
83
+ });
84
+ const mcp = program.command('mcp [dir]').description('Serve project information over MCP stdio')
85
+ .option('--watch', 'invalidate project caches on file changes')
86
+ .option('--print-config', 'print a client configuration snippet')
87
+ .action(async (dir = '.', options) => {
88
+ if (options.printConfig || json) {
89
+ const { mcpConfig } = await import('./core/mcp-install.js');
90
+ console.log(JSON.stringify(mcpConfig(dir, options.watch), null, 2));
91
+ }
92
+ else
93
+ await (await import('./core/mcp.js')).startMcp(dir, options.watch);
94
+ });
95
+ mcp.command('install [project]').description('Install a project server in MCP client settings')
96
+ .option('--client <client>', 'claude-desktop | claude-code | cursor')
97
+ .option('-o, --out <file>', 'alternate configuration path for one client')
98
+ .option('--replace', 'replace a different bati configuration')
99
+ .option('--dry-run', 'show the destination and server configuration')
100
+ .action(async (dir = '.', options) => show(await (await import('./core/mcp-install.js')).installMcp({ dir, ...options, watch: mcp.opts().watch })));
101
+ program.command('pack [dir]').description('Pack repository context for AI')
102
+ .option('--budget <tokens>', 'maximum token budget')
103
+ .option('-f, --format <format>', 'xml | markdown', 'xml')
104
+ .option('-o, --out <file>', 'output file')
105
+ .option('--guides', 'write CLAUDE.md and AGENTS.md')
106
+ .action(async (dir = '.', options) => show(await (await import('./core/pack.js')).pack({
107
+ dir, ...options, budget: options.budget === undefined ? undefined : Number(options.budget)
108
+ })));
109
+ program.command('deps [dir]').description('Analyze file-level imports')
110
+ .option('-f, --format <format>', 'svg | png | html | json')
111
+ .option('-o, --out <file>', 'output file')
112
+ .option('--check', 'fail if circular dependencies exist')
113
+ .action(async (dir = '.', options) => show(await (await import('./core/deps.js')).deps({ dir, ...options })));
114
+ program.command('routes [dir]').description('Extract framework routes')
115
+ .option('--openapi', 'export an OpenAPI skeleton')
116
+ .option('-o, --out <file>', 'output file')
117
+ .action(async (dir = '.', options) => show(await (await import('./core/routes.js')).routes({ dir, ...options })));
118
+ program.command('db [dir]').description('Extract and render database schemas')
119
+ .option('-f, --format <format>', 'svg | png | mermaid | json | types | eloquent', 'svg')
120
+ .option('-o, --out <file>', 'output file')
121
+ .action(async (dir = '.', options) => show(await (await import('./core/db.js')).db({ dir, ...options })));
122
+ program.command('preview <file>').description('Show a diagram in a supported terminal')
123
+ .action(async (file) => {
124
+ const { imageProtocol, previewImage } = await import('./core/preview.js');
125
+ const protocol = imageProtocol(process.env, !json && !!process.stdout.isTTY);
126
+ const { result, sequence } = await previewImage(file, protocol, process.stdout.columns);
127
+ if (sequence)
128
+ process.stdout.write(sequence + '\n');
129
+ show(result);
130
+ });
131
+ program.command('dashboard [dir]').description('Summarize live project statistics')
132
+ .action(async (dir = '.') => show(await (await import('./core/dashboard.js')).projectDashboard(dir)));
133
+ program.command('search <query> [dir]').description('Search project files, classes, routes and endpoints')
134
+ .action(async (query, dir = '.') => show(await (await import('./core/dashboard.js')).projectSearch(query, dir)));
135
+ program.command('recent [dir]').description('List recent projects or remember a directory')
136
+ .action(async (dir) => {
137
+ const { recentProjects, rememberProject } = await import('./core/dashboard.js');
138
+ const projects = dir ? await rememberProject(dir) : await recentProjects();
139
+ show({ title: 'Recent projects', lines: projects, data: projects });
140
+ });
141
+ program.command('doctor [dir]').description('Check repository health')
142
+ .option('--offline', 'skip registry reports')
143
+ .option('--env-schema', 'generate a typed environment schema')
144
+ .option('-o, --out <file>', 'environment schema output file')
145
+ .option('--check', 'fail on errors or unavailable audits')
146
+ .action(async (dir = '.', options) => show(await (await import('./core/doctor.js')).doctor({ dir, ...options })));
147
+ program.command('config [dir]').description('Inspect resolved project configuration')
148
+ .action(async (dir = '.') => {
149
+ const config = await loadConfig(dir);
150
+ show({ title: 'Project configuration', lines: pluginCommands(config).map((command) => command.name), data: config });
151
+ });
152
+ try {
153
+ const hasPluginCandidate = process.argv.slice(2).some((arg) => !arg.startsWith('-')) &&
154
+ !program.commands.some((command) => process.argv[2] === command.name());
155
+ if (hasPluginCandidate || process.argv.includes('--help') || process.argv.length <= 3) {
156
+ for (const command of pluginCommands(await loadConfig())) {
157
+ if (program.commands.some((builtIn) => builtIn.name() === command.name))
158
+ throw new Error(`Plugin command conflicts with built-in: ${command.name}`);
159
+ program.command(`${command.name} [args...]`).description(command.description)
160
+ .action(async (args) => show(await command.run({ root: process.cwd() }, args)));
161
+ }
162
+ }
163
+ await program.parseAsync(process.argv);
164
+ }
165
+ catch (error) {
166
+ if (!(error instanceof CommanderError) || error.exitCode) {
167
+ const message = error instanceof Error ? error.message : String(error);
168
+ process.exitCode = error instanceof CommanderError ? 2 : 1;
169
+ if (json)
170
+ console.log(JSON.stringify({ error: message, exitCode: process.exitCode }));
171
+ else if (!(error instanceof CommanderError))
172
+ console.error(message);
173
+ }
174
+ }
@@ -0,0 +1,9 @@
1
+ type Schema = Record<string, any>;
2
+ export declare function zodSource(spec: Schema): string;
3
+ export declare function querySource(ops: Array<{
4
+ name: string;
5
+ method: string;
6
+ argsType: string;
7
+ argsOptional: boolean;
8
+ }>): string;
9
+ export {};
@@ -0,0 +1,74 @@
1
+ export function zodSource(spec) {
2
+ const schemas = spec.components?.schemas ?? {};
3
+ const code = (schema) => {
4
+ if (schema === false)
5
+ return 'z.never()';
6
+ if (!schema || schema === true)
7
+ return 'z.unknown()';
8
+ let value = 'z.unknown()';
9
+ const combine = (items, operator) => items.length < 2 ? items[0] ?? 'z.unknown()' :
10
+ operator === 'union' ? `z.union([${items.join(', ')}])` : items.reduce((a, b) => `z.intersection(${a}, ${b})`);
11
+ if (typeof schema.$ref === 'string') {
12
+ const key = schema.$ref.split('/').at(-1)?.replace(/~1/g, '/').replace(/~0/g, '~') ?? '';
13
+ if (Object.hasOwn(schemas, key))
14
+ value = `z.lazy(() => schemas[${JSON.stringify(key)}])`;
15
+ }
16
+ else if (schema.allOf)
17
+ value = combine(schema.allOf.map(code), 'intersection');
18
+ else if (schema.oneOf || schema.anyOf)
19
+ value = combine((schema.oneOf ?? schema.anyOf).map(code), 'union');
20
+ else if (Array.isArray(schema.type))
21
+ value = combine(schema.type.map((type) => code({ ...schema, type, nullable: false })), 'union');
22
+ else if (schema.enum || Object.hasOwn(schema, 'const'))
23
+ value = combine((schema.enum ?? [schema.const]).map((item) => item === null ? 'z.null()' :
24
+ ['string', 'number', 'boolean'].includes(typeof item) ? `z.literal(${JSON.stringify(item)})` : 'z.unknown()'), 'union');
25
+ else if (schema.type === 'object' || schema.properties || schema.additionalProperties) {
26
+ value = `z.object({${Object.entries(schema.properties ?? {}).map(([key, child]) => `[${JSON.stringify(key)}]: ${code(child)}${schema.required?.includes(key) ? '' : '.optional()'}`).join(', ')}})`;
27
+ if (schema.additionalProperties === false)
28
+ value += '.strict()';
29
+ else if (schema.additionalProperties && typeof schema.additionalProperties === 'object')
30
+ value += `.catchall(${code(schema.additionalProperties)})`;
31
+ else
32
+ value += '.passthrough()';
33
+ }
34
+ else if (schema.type === 'array')
35
+ value = `z.array(${code(schema.items)})`;
36
+ else if (schema.type === 'null')
37
+ value = 'z.null()';
38
+ else if (schema.type === 'integer')
39
+ value = 'z.number().int()';
40
+ else if (schema.type === 'number')
41
+ value = 'z.number()';
42
+ else if (schema.type === 'boolean')
43
+ value = 'z.boolean()';
44
+ else if (schema.type === 'string') {
45
+ value = 'z.string()';
46
+ if (['email', 'uuid', 'url', 'datetime'].includes(schema.format))
47
+ value += `.${schema.format}()`;
48
+ if (schema.format === 'date-time')
49
+ value += '.datetime({ offset: true })';
50
+ if (schema.pattern)
51
+ value += `.regex(new RegExp(${JSON.stringify(schema.pattern)}))`;
52
+ }
53
+ const bounds = schema.type === 'string' ? [['minLength', 'min'], ['maxLength', 'max']] :
54
+ schema.type === 'array' ? [['minItems', 'min'], ['maxItems', 'max']] :
55
+ ['number', 'integer'].includes(schema.type) ? [['minimum', 'min'], ['maximum', 'max']] : [];
56
+ for (const [name, method] of bounds)
57
+ if (typeof schema[name] === 'number')
58
+ value += `.${method}(${schema[name]})`;
59
+ return schema.nullable ? value + '.nullable()' : value;
60
+ };
61
+ return `export const schemas: Record<string, z.ZodTypeAny> = {\n${Object.entries(schemas).map(([name, schema]) => ` [${JSON.stringify(name)}]: ${code(schema)},`).join('\n')}\n};`;
62
+ }
63
+ export function querySource(ops) {
64
+ return ops.map(({ name, method, argsType, argsOptional }) => {
65
+ const hook = 'use' + name[0].toUpperCase() + name.slice(1);
66
+ if (method === 'GET' || method === 'HEAD')
67
+ return `export function ${hook}(client: Client, args${argsOptional ? '?' : ''}: Omit<${argsType}, 'signal'>) {
68
+ return useQuery({ queryKey: [${JSON.stringify(name)}, args], queryFn: ({ signal }) => client[${JSON.stringify(name)}]({ ...args, signal }) });
69
+ }`;
70
+ return `export function ${hook}(client: Client) {
71
+ return useMutation({ mutationFn: (args: ${argsType}${argsOptional ? ' | void' : ''}) => client[${JSON.stringify(name)}](args${argsOptional ? ' ?? undefined' : ''}) });
72
+ }`;
73
+ }).join('\n\n');
74
+ }
@@ -0,0 +1,44 @@
1
+ import type { TaskResult } from './types.js';
2
+ type Spec = Record<string, any>;
3
+ export declare const operationsOf: (spec: Spec) => Map<`${string} ${string}`, {
4
+ readonly route: string;
5
+ readonly method: string;
6
+ readonly operation: Spec;
7
+ readonly item: Spec;
8
+ }>;
9
+ export declare function resolveRef(value: any, spec: Spec): any;
10
+ export interface ApiChange {
11
+ operation: string;
12
+ breaking: boolean;
13
+ message: string;
14
+ }
15
+ export declare function compareSpecs(previous: Spec, next: Spec): ApiChange[];
16
+ export declare function apiDiff(options: {
17
+ old: string;
18
+ next: string;
19
+ out?: string;
20
+ format?: string;
21
+ }): Promise<TaskResult>;
22
+ export declare function exampleValue(schema: any, spec: Spec, field?: string, depth?: number): unknown;
23
+ export declare function mockResponses(spec: Spec): {
24
+ count: number;
25
+ respond(method: string | undefined, target: string, requested?: string): {
26
+ status: number;
27
+ mime: string;
28
+ payload: string;
29
+ } | {
30
+ status: number;
31
+ mime?: undefined;
32
+ payload?: undefined;
33
+ };
34
+ };
35
+ export declare function startMock(options: {
36
+ spec: string;
37
+ port?: number;
38
+ signal?: AbortSignal;
39
+ }): Promise<{
40
+ result: TaskResult;
41
+ close: () => void;
42
+ }>;
43
+ export declare function watchSpec(file: string, run: () => Promise<TaskResult>, onResult: (result: TaskResult) => void, signal?: AbortSignal): () => void;
44
+ export {};