very-express 0.7.9 → 0.8.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/AGENTS.md ADDED
@@ -0,0 +1,116 @@
1
+ # AGENTS.md
2
+
3
+ Canonical agent guide for this repo. `CLAUDE.md` and `.github/copilot-instructions.md` point here.
4
+
5
+ ## What this is
6
+
7
+ VeryExpress is a **code generator**. It reads JSON Schema files and writes a complete Express.js REST API (Mongoose or TypeORM, RBAC, OAuth2, Swagger) into `output/`.
8
+
9
+ Always distinguish the two sides:
10
+
11
+ | | What | Where |
12
+ |---|---|---|
13
+ | **The generator** | This repo, TypeScript | `src/` → built to `dist/` |
14
+ | **The generated app** | Standalone Express app, own `package.json` | `output/` |
15
+
16
+ Most of `output/` is gitignored. **Exception:** `output/jsonSchema/` is tracked — it holds the working sample schemas.
17
+
18
+ ## Build / run
19
+
20
+ ```bash
21
+ npm run dev # compile (esbuild → dist/index.js) + run CLI
22
+ npm run build # lint + compile
23
+ npm run lint # eslint --fix on src/**/*.ts
24
+ npm run compile # build only: scripts/build.js + scripts/copyTsTemplates.js
25
+ npm start # run dist/index.js directly
26
+ ```
27
+
28
+ Bundled to a single `dist/index.js` (esbuild, platform: node, target: es2016). `scripts/copyTsTemplates.js` then copies `src/templates/` → `dist/templates/`; the runtime reads templates from `__dirname/templates`.
29
+
30
+ **Editing `src/` changes nothing until you `npm run compile`** — `vex` executes `dist/index.js`.
31
+
32
+ ### Tests
33
+
34
+ ```bash
35
+ npm test # compile, then run every test
36
+ npm run test:update # recompile and rewrite the golden files
37
+ npm run test:watch # vitest in watch mode (no compile step)
38
+ npm run test:e2e # boot a real generated app + Postgres and drive it over HTTP (slow)
39
+ ```
40
+
41
+ `test/unit/` covers pure internals. `test/golden.test.ts` runs a full generation per
42
+ scenario in an isolated temp dir and compares the whole output tree against a
43
+ committed golden file — this is the main regression net for generator and template
44
+ changes. `npm test` compiles first because the golden tests spawn `dist/index.js`.
45
+
46
+ `test/e2e/contract.test.ts` is opt-in (`test:e2e`): it installs the generated app's
47
+ own dependencies, boots it against a Docker Postgres and asserts the HTTP contract.
48
+ Too slow for `npm test`, but it is the only layer that proves a generated app actually
49
+ compiles, starts and serves. See [`test/README.md`](test/README.md).
50
+
51
+ When a golden changes, decide whether the new output is correct before running
52
+ `test:update`.
53
+
54
+ ## Input schemas
55
+
56
+ Read from `vex.config.json → jsonSchemaDir` (this repo: `./output/jsonSchema`). `src/templates/jsonSchema/` and `src/templates/jsonSchemaRBAC/` hold a fresh sample set, re-copied into `jsonSchemaDir` on every generation run — **edits to `output/jsonSchema/*.json` are overwritten unless you also edit the template**. Working schemas you want kept belong in the template dir.
57
+
58
+ ## Hard rules
59
+
60
+ - **Never hand-edit `*.gen.ts`.** Regenerated on the next `vex` run. If a generated file genuinely needs a manual change, prefer fixing the generator or template.
61
+ - **`x-documentConfig.documentName` must match the JSON filename** — `User.json` → `"documentName": "User"`.
62
+ - **Never hand-place files under `sysDir`.** `cleanupStaleFiles()` deletes every file there not written during the current run.
63
+ - **`required` in source schemas uses the root array form.** Per-prop `required: true` is normalized into `required: string[]` by the preprocessor — do not write it that way.
64
+ - **`src/` is ESM-style TypeScript with `~/*` → `src/*` aliasing.** Use `~/generators/...`, `~/utils/...`, `~/types/...` for intra-repo imports.
65
+ - **Only `one-to-one` and `many-to-one` are declared in `x-foreignKey`.** `one-to-many` is derived from the other side and must not be hand-written.
66
+ - **RBAC is opt-in.** `utils.generator.isRbacEnabled()` is the single gate for every RBAC code path. Absent `useRBAC`, or `roles: []`, means RBAC off — never "RBAC with zero roles". Never branch on `compilerOptions.useRBAC` directly.
67
+ - **Boolean config defaults use `??`, not `||`.** `x || true` swallows an explicit `false`.
68
+
69
+ ## Conventions
70
+
71
+ | Artifact | Convention | Example |
72
+ |---|---|---|
73
+ | Generated files | `{DocName}{Type}.gen.ts` | `UserController.gen.ts` |
74
+ | Controller class | PascalCase | `UserController` |
75
+ | REST route | `documentName.toLowerCase()` | `/user` |
76
+ | Template function | camelCase default export beside its generator | `controllerTemplate()` |
77
+ | Role class | `Role{Name}` | `RoleAdmin` |
78
+
79
+ ## Code style
80
+
81
+ - Prefer readability and maintainability.
82
+ - Split distinct workflows into functions — no large monolithic blocks.
83
+ - Define types. Avoid `any` / `unknown` where possible.
84
+ - Name variables, functions, interfaces, classes descriptively.
85
+ - Idiomatic TypeScript. Code stays idiomatic even when prose does not.
86
+
87
+ ## Reply style
88
+
89
+ Smart caveman. Drop articles, filler, pleasantries, hedging. Fragments fine. Keep all technical substance.
90
+
91
+ - Technical terms stay exact — "polymorphism" stays "polymorphism".
92
+ - Code blocks unchanged. Caveman around code, not in code.
93
+ - Error messages quoted exact.
94
+
95
+ ## Documentation map
96
+
97
+ This file covers only what every session needs. Deeper material lives in `docs/`:
98
+
99
+ | Document | Content |
100
+ |---|---|
101
+ | [`test/README.md`](test/README.md) | Test layout, golden scenarios, how to update/add |
102
+ | [`docs/architecture/generatorPipeline.md`](docs/architecture/generatorPipeline.md) | Pipeline steps, source layout, generator contract, meta tracking, migrations, preprocessors |
103
+ | [`docs/architecture/templates.md`](docs/architecture/templates.md) | Static vs function templates, `FUNC{{ }}`, `allowOverwrite` |
104
+ | [`docs/architecture/databaseTargets.md`](docs/architecture/databaseTargets.md) | mongo vs sql, repository adapter, data isolation, join whitelist |
105
+ | [`docs/architecture/authAndRouting.md`](docs/architecture/authAndRouting.md) | tsoa, auth routes, swagger, RBAC |
106
+ | [`docs/vexJsonSchema.md`](docs/vexJsonSchema.md) | Full JSON Schema reference — `x-documentConfig`, `x-foreignKey`, `x-format`, `x-vexData` |
107
+ | [`docs/apiUsage.md`](docs/apiUsage.md) | API client guide — pagination, search, response format |
108
+ | [`docs/ForeignKey.md`](docs/ForeignKey.md) | FK joins via the API `join` parameter |
109
+ | [`docs/developmentNote.md`](docs/developmentNote.md) | Why no ts-node, esbuild/dist working dir, `FUNC{{ }}` intent |
110
+ | [`docs/CONTRIBUTING.md`](docs/CONTRIBUTING.md) | Setup, branch/PR workflow, PR checklist |
111
+ | [`docs/features/`](docs/features/) | rbac, dataIsolation, filterOperators, joinWhitelist, auditFields |
112
+ | [`docs/appGenerated/auth.md`](docs/appGenerated/auth.md) | JWT rolling keys, OAuth2 providers |
113
+ | [`docs/roadMap/`](docs/roadMap/) | Released features and version milestones |
114
+ | [`docs/releaseNote/`](docs/releaseNote/) | Per-version release notes |
115
+
116
+ When you learn something non-obvious that a future session needs every time, add it above. When it is deep or situational, put it in `docs/` and link it here.
package/CLAUDE.md CHANGED
@@ -1,166 +1,14 @@
1
1
  # CLAUDE.md
2
2
 
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
3
+ @AGENTS.md
4
4
 
5
- ## Build/Run
5
+ Canonical agent guide is [`AGENTS.md`](AGENTS.md) — imported above, read it.
6
6
 
7
- ```bash
8
- npm run dev # compile (esbuild → dist/index.js) + run CLI
9
- npm run build # lint + compile
10
- npm run lint # eslint --fix on src/**/*.ts
11
- npm start # run dist/index.js directly
12
- ```
7
+ Deep architecture material lives in `docs/architecture/`:
13
8
 
14
- Build bundles everything into a single `dist/index.js` (esbuild, platform: node, target: es2016). `scripts/copyTsTemplates.js` then copies static templates from `src/templates/` into `dist/templates/` — the runtime reads templates from `__dirname/templates/`.
9
+ - [`docs/architecture/generatorPipeline.md`](docs/architecture/generatorPipeline.md) — pipeline, generator contract, meta tracking, migrations
10
+ - [`docs/architecture/templates.md`](docs/architecture/templates.md) — static vs function templates, `FUNC{{ }}`, `allowOverwrite`
11
+ - [`docs/architecture/databaseTargets.md`](docs/architecture/databaseTargets.md) — mongo vs sql, repository adapter, data isolation
12
+ - [`docs/architecture/authAndRouting.md`](docs/architecture/authAndRouting.md) — tsoa, auth routes, swagger, RBAC
15
13
 
16
- No test suite. Validate changes by running `npm run dev` and inspecting `output/`.
17
-
18
- **Working on this project vs. using it:** this repo is the *generator itself*. Running `vex` reads schema files, runs the generator pipeline, and writes `output/` — a standalone Express app. The output has its own `package.json` and dependencies. Changes to generator source (`src/`) need `npm run compile` before `vex` picks them up.
19
-
20
- ## Docs
21
-
22
- Project documentation lives in `docs/`. Key references:
23
-
24
- | Document | Content |
25
- |----------|---------|
26
- | `docs/vexJsonSchema.md` | Full JSON Schema reference — `x-documentConfig`, `x-foreignKey`, `x-format`, `x-vexData` |
27
- | `docs/apiUsage.md` | API client guide — pagination, search, response format |
28
- | `docs/appGenerated/auth.md` | Auth system — JWT rolling keys, OAuth2 providers |
29
- | `docs/features/rbac.md` | Role-based access control — role files, permission model |
30
- | `docs/features/dataIsolation.md` | Row-level ownership — declarative per-entity query scoping |
31
- | `docs/features/filterOperators.md` | Filter query operators — `$and`, `$or`, `$like`, `$in`, comparison |
32
- | `docs/features/joinWhitelist.md` | Join whitelist — restricting relation joins at the API level |
33
- | `docs/ForeignKey.md` | Foreign-key joining via API `join` parameter |
34
- | `docs/roadMap/` | Future plans and version milestones |
35
-
36
- ## Architecture
37
-
38
- VeryExpress is a **code generator** — it reads JSON Schema files and produces a complete Express.js REST API.
39
-
40
- ```
41
- jsonSchema/*.json → preprocess (validate/normalize) → generators → output/
42
- ```
43
-
44
- | Directory | Role |
45
- |-----------|------|
46
- | `src/cli.ts` | CLI entry (`vex` command), minimal config parsing, delegates to `generate()` |
47
- | `src/index.ts` | Orchestrator — creates dirs, copies static templates, preprocesses schemas, runs all generators in order |
48
- | `src/generators/` | Async `compile()` functions that generate code files into `output/` |
49
- | `src/templates/` | Static base files copied verbatim (renamed `.ts` → `.gen.ts`) into the generated app |
50
- | `src/preprocess/` | Schema validation, normalization, FK metadata wiring before generation |
51
- | `src/types/types.ts` | Core interfaces: `compilerOptions`, `jsonSchema`, `jsonSchemaPropsItem`, `documentConfig` |
52
- | `src/utils/` | File I/O, logging, JSON-schema helpers, template formatter, config defaults |
53
-
54
- ### Generation pipeline (in `src/index.ts → generate()`)
55
-
56
- 1. Validate config, set up directories
57
- 2. Copy static templates into `output/src/system/`
58
- 3. Preprocess schemas — normalize `required` arrays, validate FK configs, sync role enums
59
- 4. For each JSON schema file in parallel: generate TypeScript interface, DB model (Mongoose or TypeORM), and controller
60
- 5. Generate join whitelist registry, SQL migrations (if `dbType === "sql"`)
61
- 6. Generate routes, server entrypoint, and project settings files (package.json, tsoa.json, env config)
62
-
63
- ### Generator pattern
64
-
65
- Every generator exports an async `compile(options)` that:
66
- 1. Extracts/validates data from options
67
- 2. Calls a `*Template()` function that returns a string
68
- 3. Writes with `utils.common.writeFile()` — it compares normalized content (stripping header comments) and skips if unchanged
69
-
70
- ### Template system
71
-
72
- Two kinds of templates:
73
-
74
- - **Static templates** in `src/templates/` — copied as-is to `output/`, with `.ts` → `.gen.ts` renaming (except `index.ts`). Generated files are considered write-once (hand-editable between runs).
75
- - **Template functions** in `*.template.ts` beside their generator — use `{{placeholder}}` syntax replaced via `.replace()`.
76
-
77
- `FUNC{{ <code> }}` syntax embeds runnable JS in generated output. The formatter in `src/utils/template.ts` strips the wrapping `'FUNC{{...}}'` quotes so the inner code runs as JavaScript in the generated file.
78
-
79
- ### Path aliases
80
-
81
- `tsconfig.json` maps `~/*` → `src/*`. Imports can use `~/generators/...`, `~/utils/...`, `~/types/...`.
82
-
83
- ### DB targets
84
-
85
- Controlled by `vex.config.json` → `dbType`:
86
- - `"mongo"` — Mongoose models (`src/generators/db/mongooseModel.generator.ts`)
87
- - `"sql"` — TypeORM entities + Knex SQL migrations (`src/generators/db/typeormEntity.generator.ts`, `src/generators/db/sqlMigration.generator.ts`)
88
-
89
- ### TSOA integration (current branch)
90
-
91
- Generates `tsoa.json` in output root so `tsoa` CLI produces routes + OpenAPI spec. Controller decorators use `@Route`, `@Security`, `@Tags`, etc. The authentication middleware at `src/templates/_middlewares/tsoaAuthentication.ts` handles `BearerAuth` and `AuthIndex` security schemes.
92
-
93
- ### Preprocessing
94
-
95
- Three preprocessors run before generation, in `src/preprocess/`:
96
-
97
- | File | Role |
98
- |------|------|
99
- | `jsonschemaFormat.ts` | Validate schema structure (`x-documentConfig`, FK config, `x-format` type constraints). Normalize per-prop `required: true` into root `required: string[]`. For SQL target, convert `ObjectId` → `Primary` on `_id`, warn on nested index/FK/vexData. |
100
- | `jsonSchemaForeignKeys.ts` | Wire reverse-relation metadata (`one-to-many` derived from other side's `many-to-one`). Auto-populate `restApi.joinWhitelist` if not set. |
101
- | `roleDefinitions.ts` | For RBAC schemas, ensure per-role JSON files exist with default CRUD permissions for each resource document. |
102
-
103
- ### Interface generation
104
-
105
- Uses `json-schema-to-typescript` to emit TypeScript interfaces from each JSON schema. Then injects FK relation types (`{DocName}Relations`, `{DocName}ApiRelations`, `{DocName}WithRelations`, `{DocName}WithApiRelations`) and generates enums for fields with `enum` arrays.
106
-
107
- ### Repository adapter pattern
108
-
109
- Controllers never touch ORM/ODM directly. They call `VexDb.getRepository(Entity)` which returns a `VexRepository<T>` (an interface in `src/templates/_types/vex/`). Two adapters implement it:
110
-
111
- | Adapter | DB target | Notes |
112
- |---------|-----------|-------|
113
- | `TypeOrmRepositoryAdapter` | SQL | Maps `$and`/`$or`/`$like`/`$gt` etc. → TypeORM `FindOptions`. Applies data isolation ownership filter if configured. |
114
- | `MongooseRepositoryAdapter` | Mongo | Thin wrapper. Many features (join, select, pagination, count) are TODO — Mongoose support is less mature. |
115
-
116
- The `VexRepository<T>` interface defines: `find`, `count`, `findOne`, `findOneWhere`, `create`, `replace`, `update`, `delete`, `deleteWhere`.
117
-
118
- ### Data isolation
119
-
120
- Entities can declare `dataIsolation: { field: "ownerId" }` in `x-documentConfig.restApi`. This generates:
121
-
122
- 1. A `DataIsolationRegistry.gen.ts` mapping entity → ownership field
123
- 2. The `DataIsolationContext` middleware (AsyncLocalStorage) injected into the request pipeline
124
- 3. The TypeORM adapter reads the current user ID from context and injects `{ [field]: userId }` into every query — transparent row-level ownership
125
-
126
- The RBAC middleware generator (`src/generators/middlewares/RBACmiddleware.generator.ts`) produces `RoleBaseAccessControl.gen.ts` which enforces per-document CRUD permissions based on role JSON files.
127
-
128
- ### Routing & auth generation
129
-
130
- The route generator (`src/generators/routes/`) produces three kinds of routes:
131
-
132
- - **API routes** — generated by tsoa from controller decorators (`@Route`, `@Get`, `@Post`, etc.)
133
- - **Auth routes** — `AuthController.gen.ts` (tsoa-based: login, register, token refresh) and `AuthRouter.gen.ts` (express OAuth passport redirect flows)
134
- - **Swagger UI** — `SwaggerRouter.gen.ts` serving OpenAPI spec + Swagger UI
135
-
136
- ### Migration system
137
-
138
- `src/migration.ts` runs pending migrations before generation. Each migration in `src/migrations/<version>.ts` exports `run(jsonSchemaDir: string): void`. Versions are compared semver-wise against `lastGeneratedVersion` in `.vex/meta.json`. To add a migration, import it in `src/migration.ts` and push to the `migrations` array.
139
-
140
- ### Project settings generation
141
-
142
- `src/generators/projectSettings/` produces non-code files: `package.json`, `.env`, tsoa config, build scripts (for the *generated* app, not this repo).
143
-
144
- ### Meta tracking
145
-
146
- `.vex/meta.json` in the generated project root tracks `lastGeneratedVersion` and per-file `allowOverwrite` flags. On version major/minor change, `sysDir` is wiped for clean regeneration. The migration system (`src/migration.ts`) runs pending version-bumped migrations before generation.
147
-
148
- ## JSON Schema extensions (custom `x-*` properties)
149
-
150
- - `x-documentConfig` — REST methods, document name (must match filename)
151
- - `x-foreignKey` — relationships, only `one-to-one` and `many-to-one` on owning side; `one-to-many` auto-derived
152
- - `x-vexData: "role"` — marks field for RBAC
153
- - `x-format: "ObjectId"` — MongoDB ObjectId, auto-converted to `"Primary"` for SQL target
154
- - Full reference: `docs/vexJsonSchema.md`
155
-
156
- ## Key conventions
157
-
158
- - Generated files: `{DocName}{Type}.gen.ts` — never hand-edit (regenerated on next `vex` run)
159
- - Controller class: PascalCase (e.g. `UserController`)
160
- - REST endpoint: lowercase documentName (e.g. `/user`)
161
- - `required` fields: preprocessor normalizes `required: true` on individual props into root-level `required: string[]`, but source schemas use the array form
162
- - `interface.fkProps` on each schema holds reverse-relation metadata populated during preprocessing
163
-
164
- ## Style
165
-
166
- Caveman speak — drop articles, filler, pleasantries. Short, direct, technical. Code itself remains idiomatic TypeScript.
14
+ Full doc index: the Documentation map section of `AGENTS.md`.