very-express 0.6.20 → 0.7.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/CLAUDE.md ADDED
@@ -0,0 +1,166 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Build/Run
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
+ ```
13
+
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/`.
15
+
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.