mikro-orm-markdown 0.1.0-alpha.2 → 0.1.0-alpha.3

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 CHANGED
@@ -10,25 +10,35 @@ Generate **Mermaid ERD + Markdown documentation** from your [MikroORM](https://m
10
10
 
11
11
  > Heavily inspired by [prisma-markdown](https://github.com/samchon/prisma-markdown) by [@samchon](https://github.com/samchon). Thank you for the great idea.
12
12
 
13
- This tool brings the same ERD + Markdown experience to MikroORM, with additional visualization for MikroORM-specific concepts that cannot be expressed in Prisma:
13
+ ## Features
14
14
 
15
- - **Embeddable** a value object whose fields are stored as flat columns inside the owning entity's table (e.g. `address_street`, `address_city`). No separate table is created.
16
- - **Single Table Inheritance (STI)** subclasses like `Dog` and `Cat` share one `animals` table. A discriminator column (e.g. `type`) distinguishes which subclass each row belongs to.
17
- - **@Formula** a virtual column with no physical DB column. Its value is computed by a SQL expression at SELECT time (e.g. `LENGTH(name)`).
15
+ - **Mermaid ERD diagrams** generated from MikroORM entity metadata
16
+ - **Markdown schema documentation** with per-entity column tables, actual DB column names, keys, nullability, descriptions, indexes, and constraints
17
+ - **JSDoc-driven grouping and visibility** via `@namespace`, `@erd`, `@describe`, and `@hidden`
18
+ - **No live database connection required** — uses MikroORM metadata discovery from your config
19
+ - **Works across common SQL drivers** — covered by smoke tests for SQLite, PostgreSQL, MySQL, and MariaDB
18
20
 
19
- > These features are fully supported by MikroORM but are less commonly used in practice. In particular, Embeddable is most relevant when MikroORM entities double as domain objects — if you separate your ORM layer from your domain model, you likely won't need it.
21
+ ### MikroORM-specific concepts
20
22
 
21
- - **Actual DB column names** derived from your NamingStrategy
22
- - **Indexes and constraints**
23
+ Beyond what Prisma-based tools can express, `mikro-orm-markdown` also visualizes concepts unique to MikroORM:
24
+
25
+ - **Embeddable** — a value object stored inside the owning entity's table, either as flattened columns (e.g. `address_street`, `address_city`) or as a JSON column depending on the `@Embedded` options. No separate table is created.
26
+ - **Single Table Inheritance (STI)** — subclasses like `Dog` and `Cat` share one `animals` table. A discriminator column (e.g. `type`) distinguishes which subclass each row belongs to.
27
+ - **@Formula** — a virtual column with no physical DB column. Its value is computed by a SQL expression at SELECT time (e.g. `LENGTH(name)`).
23
28
 
24
- Works with MikroORM SQL drivers such as PostgreSQL, MySQL/MariaDB, SQLite, and MSSQL. It reads entity metadata from your MikroORM config, so no live database connection is required.
29
+ > These are first-class MikroORM features, though not every project uses all of them. `Embeddable` is especially useful for value objects, such as an `Address` stored as `address_*` columns or as JSON, and can also reduce duplication when several entities share the same column group.
25
30
 
26
31
  ## Requirements
27
32
 
28
- - Node.js >= 18
29
- - `@mikro-orm/core` >= 6 (peer dependency)
30
- - A MikroORM config with the matching database driver package installed
31
- - TypeScript config files require `tsx` or `ts-node`
33
+ - **Node.js >= 18**
34
+ - **MikroORM >= 6** — `@mikro-orm/core` is a peer dependency.
35
+ - **A MikroORM config file** the CLI expects a default export of a plain MikroORM options object.
36
+ - **The matching MikroORM driver package** — for example `@mikro-orm/postgresql`, `@mikro-orm/mysql`, `@mikro-orm/mariadb`, or `@mikro-orm/sqlite`. A live database connection is not required, but MikroORM still needs the driver to discover metadata.
37
+ - **Decorator-based entities** — entities must be `@Entity()` classes. `EntitySchema`-defined entities are not currently supported.
38
+ - **Resolvable property types** — each entity property's type must be known during MikroORM discovery. Use explicit decorator options such as `type:` / `entity:`, or install `@mikro-orm/reflection` so the CLI can auto-use `TsMorphMetadataProvider` for TypeScript sources.
39
+ - **`tsx` for TypeScript config files** — required only when loading a `.ts` MikroORM config through the CLI. `.js` config files do not need it.
40
+
41
+ > If you install `@mikro-orm/reflection`, keep it at the **same exact version** as `@mikro-orm/core`. MikroORM expects official `@mikro-orm/*` packages to share one version, and mismatches can fail discovery.
32
42
 
33
43
  ## Installation
34
44
 
@@ -40,25 +50,18 @@ pnpm add -D mikro-orm-markdown
40
50
 
41
51
  ## Quick Start
42
52
 
43
- Add a script to your `package.json`:
53
+ Add a script to your `package.json`, pointing `--config` at your MikroORM config file:
44
54
 
45
55
  ```json
46
56
  {
47
57
  "scripts": {
48
- "erd": "mikro-orm-markdown --config ./mikro-orm.config.js --out ./ERD.md --title 'My Database' --src 'src/entities/**/*.ts'"
58
+ "erd": "mikro-orm-markdown --config ./mikro-orm.config.ts --out ./ERD.md --title 'My Database'"
49
59
  }
50
60
  }
51
61
  ```
52
62
 
53
- For TypeScript config files, use `tsx`:
54
-
55
- ```json
56
- {
57
- "scripts": {
58
- "erd": "tsx ./node_modules/.bin/mikro-orm-markdown --config ./mikro-orm.config.ts --out ./ERD.md --title 'My Database' --src 'src/entities/**/*.ts'"
59
- }
60
- }
61
- ```
63
+ - **`.ts` config** install `tsx` as a dev dependency (`npm install -D tsx`); the CLI loads it automatically and defaults MikroORM discovery to `entitiesTs` unless you explicitly set `preferTs`.
64
+ - **`.js` config** — no extra packages needed. Can be hand-written, or your own build output (e.g. `./dist/mikro-orm.config.js`).
62
65
 
63
66
  Then run:
64
67
 
@@ -73,11 +76,17 @@ npm run erd
73
76
  | `-c, --config <path>` | _(required)_ | Path to MikroORM config file |
74
77
  | `-o, --out <path>` | `./ERD.md` | Output Markdown file path |
75
78
  | `-t, --title <string>` | `Database Schema` | H1 heading of the generated document |
76
- | `-s, --src <glob>` | — | Glob pattern for entity source files (repeatable). Enables JSDoc tag extraction. |
79
+ | `-d, --description <string>` | — | Optional description paragraph shown below the title |
80
+ | `--tsconfig <path>` | — | `tsconfig.json` used when loading a `.ts` config; defaults to the nearest one beside the config file |
81
+ | `--src <paths...>` | — | Original TypeScript entity source paths/globs; only needed when MikroORM discovers entities from compiled JavaScript |
82
+
83
+ > For a long or multiline description, use the [programmatic API](#programmatic-api) instead — it accepts any string directly, without shell quoting limits.
77
84
 
78
85
  ## JSDoc Tags
79
86
 
80
- Annotate your entity classes to control sections and visibility in the generated document.
87
+ Annotate your entity classes to control sections and visibility in the generated document. JSDoc comments are read from TypeScript entity source files.
88
+
89
+ > **Recommended setup:** Use a `.ts` MikroORM config with `entitiesTs` pointing at your source entities. In this setup, JSDoc is read from the original TypeScript files and `--src` is not needed.
81
90
 
82
91
  ```typescript
83
92
  /**
@@ -92,6 +101,8 @@ export class Post {
92
101
  }
93
102
  ```
94
103
 
104
+ Plain JSDoc text (no tag) becomes a description: text above a **class** describes the entity, and text above a **property** describes its column. When a property has no JSDoc, its `@Property({ comment })` value (the DDL column comment) is used as the column description instead.
105
+
95
106
  | Tag | Description |
96
107
  | ------------------- | --------------------------------------------------- |
97
108
  | `@namespace <Name>` | Include entity in section `Name` (ERD + text table) |
@@ -102,14 +113,101 @@ export class Post {
102
113
  Entities with no tag are placed in the `default` section.
103
114
  An entity can carry multiple tags to appear in more than one section.
104
115
 
105
- > **NestJS Swagger Plugin**: `@namespace`, `@erd`, `@describe`, and `@hidden` are custom tags that Swagger does not recognize and will ignore. If you use your entity classes directly as DTOs, the JSDoc description may appear in your Swagger docs as well — but there is no functional conflict.
116
+ ### Compiled JavaScript Builds
117
+
118
+ If your MikroORM config discovers entities from compiled `.js` files, such as `entities: ['./dist/**/*.js']`, entity structure can still be discovered, but JSDoc comments may have been stripped.
119
+
120
+ That means descriptions and tags such as `@namespace` and `@hidden` cannot be read from those `.js` files.
121
+
122
+ Use `--src` only in this case:
123
+
124
+ ```bash
125
+ mikro-orm-markdown \
126
+ --config ./dist/mikro-orm.config.js \
127
+ --src "src/**/*.entity.ts"
128
+ ```
129
+
130
+ If `--src` matches no files or omits discovered entity declarations, generation fails instead of silently producing incomplete documentation.
131
+
132
+ ### Relation Cardinality: `@atLeastOne`
133
+
134
+ `@atLeastOne` is a JSDoc tag, not a TypeScript decorator.
135
+
136
+ A collection relation (`1:N` or `M:N`) renders as _zero-or-more_ by default. Tag the collection property with `@atLeastOne` to render that collection side as _one-or-more_ instead:
137
+
138
+ ```typescript
139
+ @Entity()
140
+ export class Author {
141
+ /** @atLeastOne */
142
+ @OneToMany(() => Post, (post) => post.author)
143
+ posts = new Collection<Post>(this);
144
+ }
145
+ ```
146
+
147
+ This turns the ERD edge `Post }o--|| Author` into `Post }|--|| Author`. It is a documentation hint only — MikroORM has no schema-level minimum, and the count is not enforced. (Mermaid distinguishes only zero-or-more vs. one-or-more, so no larger minimum can be expressed.)
148
+
149
+ A relation edge has **two ends, set independently**:
150
+
151
+ - **Singular side** (`@ManyToOne`, or the owning `@OneToOne`) — read from your schema automatically, no tag needed: _exactly-one_ (`||`) by default, or _zero-or-one_ (`o|`) when `nullable: true`.
152
+ - **Collection side** (`@OneToMany` / `@ManyToMany`) — _zero-or-more_ by default; `@atLeastOne` raises that side to _one-or-more_. Mermaid uses `}o` → `}|` or `o{` → `|{` depending on which side of the edge the collection is rendered on.
153
+
154
+ The four combinations (`Post` ↔ `Author`):
155
+
156
+ ```text
157
+ Post }o--|| Author → author 0+ posts, post exactly 1 author (default)
158
+ Post }o--o| Author → author 0+ posts, post 0-or-1 author (nullable: true)
159
+ Post }|--|| Author → author 1+ posts, post exactly 1 author (@atLeastOne)
160
+ Post }|--o| Author → author 1+ posts, post 0-or-1 author (both)
161
+ ```
162
+
163
+ > **NestJS Swagger Plugin**: `@namespace`, `@erd`, `@describe`, `@hidden`, and `@atLeastOne` are custom tags for `mikro-orm-markdown`. NestJS Swagger does not use these tags for OpenAPI metadata. If you use entity classes directly as DTOs and enable Swagger comment introspection, the plain JSDoc description may also appear in your Swagger docs, but these custom tags do not create a functional conflict.
106
164
 
107
165
  ## Output Example
108
166
 
109
- Each namespace becomes a section with a Mermaid ERD block followed by per-entity column tables.
167
+ Given these entities:
168
+
169
+ ```typescript
170
+ /**
171
+ * Blog post authored by a registered user.
172
+ * @namespace Blog
173
+ */
174
+ @Entity()
175
+ export class Post {
176
+ @PrimaryKey({ type: 'integer' })
177
+ id!: number;
178
+
179
+ /** Post title */
180
+ @Property({ type: 'string' })
181
+ title!: string;
182
+
183
+ @Property({ type: 'text', nullable: true })
184
+ body?: string;
185
+
186
+ @ManyToOne({ entity: () => Author })
187
+ author!: Author;
188
+ }
189
+
190
+ /** @namespace Blog */
191
+ @Entity()
192
+ export class Author {
193
+ @PrimaryKey({ type: 'integer' })
194
+ id!: number;
195
+
196
+ @Property({ type: 'string' })
197
+ name!: string;
198
+
199
+ @Property({ type: 'string', unique: true })
200
+ email!: string;
201
+
202
+ /** @atLeastOne */
203
+ @OneToMany({ entity: () => Post, mappedBy: 'author' })
204
+ posts = new Collection<Post>(this);
205
+ }
206
+ ```
207
+
208
+ > **Example notes:** Imports are omitted for brevity. This example uses explicit `type:` options so it works without extra reflection setup. If `@mikro-orm/reflection` is installed, MikroORM can also discover simple scalar types from `@Property() title!: string`.
110
209
 
111
- ````markdown
112
- ## Blog
210
+ Both entities share the `@namespace Blog` tag, so they land in one `## Blog` section. With MikroORM's default naming strategy, the generated `ERD.md` contains an ERD like this:
113
211
 
114
212
  ```mermaid
115
213
  erDiagram
@@ -117,18 +215,41 @@ erDiagram
117
215
  integer id PK
118
216
  string title
119
217
  text body
120
- integer author_id FK "author"
218
+ integer author_id FK
121
219
  }
122
220
  Author {
123
221
  integer id PK
124
222
  string name
125
223
  string email UK
126
224
  }
127
- Post }o--|| Author : "author"
225
+ Post }|--|| Author : "author"
128
226
  ```
129
227
 
228
+ **How the code maps to the output:**
229
+
230
+ - `@namespace Blog` → both entities are grouped under the `## Blog` section
231
+ - `@ManyToOne({ entity: () => Author })` → the `Post` to `Author` relation line and the `author_id FK` column
232
+ - `@atLeastOne` on `Author.posts` → the collection side is rendered as one-or-more: `Post }|--|| Author`
233
+ - `unique: true` on `email` → `email` is marked `UK` (unique key)
234
+ - `@Property({ nullable: true })` on `body` → the `Nullable` cell is marked `Y`
235
+ - `/** Post title */` → fills the **Description** cell for `title`
236
+
237
+ **Key legend:**
238
+
239
+ | Marker | Meaning |
240
+ | ------ | ------- |
241
+ | `PK` | Primary key |
242
+ | `FK` | Foreign key |
243
+ | `UK` | Unique key |
244
+ | `Y` in `Nullable` | Nullable column |
245
+
246
+ Each entity also gets a column table. For example, the generated `Post` section looks like this:
247
+
248
+ ```markdown
130
249
  ### Post
131
250
 
251
+ *Table: `post`*
252
+
132
253
  > Blog post authored by a registered user.
133
254
 
134
255
  | Column | Type | Key | Nullable | Description |
@@ -137,13 +258,13 @@ erDiagram
137
258
  | title | string | | | Post title |
138
259
  | body | text | | Y | |
139
260
  | author_id | integer | FK (author) | | |
140
- ````
261
+ ```
141
262
 
142
- MikroORM-specific annotations in the **Key** column:
263
+ MikroORM-specific annotations in the generated output:
143
264
 
144
265
  | Annotation | Meaning |
145
266
  | ------------------ | ---------------------------------------------------- |
146
- | `formula: <expr>` | `@Formula` computed column — no physical DB column |
267
+ | `formula: <expr>` | Mermaid comment for an `@Formula` computed column |
147
268
  | `[EmbeddableType]` | Flat column inlined from an `@Embedded` value object |
148
269
  | `discriminator` | STI discriminator column |
149
270
 
@@ -156,23 +277,91 @@ STI is a pattern where multiple entity classes share a single database table, us
156
277
  ```typescript
157
278
  @Entity({ discriminatorColumn: 'type', abstract: true })
158
279
  export class Animal {
159
- @PrimaryKey()
280
+ @PrimaryKey({ type: 'integer' })
160
281
  id!: number;
161
282
 
162
- @Property()
283
+ @Property({ type: 'string' })
163
284
  name!: string;
164
285
  }
165
286
 
166
287
  @Entity({ discriminatorValue: 'dog' })
167
288
  export class Dog extends Animal {
168
- @Property({ nullable: true })
289
+ @Property({ type: 'string', nullable: true })
169
290
  breed?: string;
170
291
  }
171
292
  ```
172
293
 
173
- When an entity uses `discriminatorColumn`, `mikro-orm-markdown` automatically detects it and marks the discriminator column in the output.
294
+ When an entity uses `discriminatorColumn`, `mikro-orm-markdown` detects it automatically. Even though the subclasses share one physical table, each class is drawn as its **own box** so the diagram shows the effective shape of every subclass:
295
+
296
+ ```mermaid
297
+ erDiagram
298
+ Animal {
299
+ integer id PK
300
+ string name
301
+ string type "discriminator"
302
+ }
303
+ Dog {
304
+ integer id PK
305
+ string name
306
+ string type
307
+ string breed
308
+ }
309
+ ```
310
+
311
+ The root (`Animal`) lists only the shared columns and marks the discriminator (`type`); each subclass (`Dog`) repeats the inherited columns and adds its own.
312
+
313
+ The generated Markdown table also includes STI notes, such as `STI root — discriminator column: type` on the root and `Extends Animal (Single Table Inheritance, discriminator value: dog)` on each subclass.
314
+
315
+ > **Trade-off:** STI keeps several entity types in one table, but can increase query complexity and produce sparse nullable columns. Use it when sharing one table is an intentional part of your model.
316
+
317
+ ## Troubleshooting
318
+
319
+ **"No entities were discovered"**
174
320
 
175
- > **Not recommended for most projects.** STI trades table simplicity for query complexity and sparse nullable columns. Use it only when you have a clear reason to store multiple entity types in one table.
321
+ Your MikroORM config found zero entities. This usually means the entity path doesn't match how the CLI is loading your config:
322
+
323
+ - If you're using a `.ts` config (the CLI loads `tsx` automatically and defaults to `preferTs: true`), make sure `entitiesTs` points to your TypeScript source files.
324
+ - If you're using a compiled `.js` config, make sure `entities` points to the **built output** (e.g. `./dist/**/*.entity.js`) and that you've run your build first.
325
+ - MikroORM uses `entitiesTs` when running in TypeScript mode and `entities` otherwise — if you use folder/file-based discovery, specify both.
326
+
327
+ **"Please provide either 'type' or 'entity' attribute"**
328
+
329
+ MikroORM could not resolve a property type during metadata discovery. The CLI loads `.ts` configs through `tsx`, so enabling `emitDecoratorMetadata` alone will not fix this path.
330
+
331
+ Fix it in one of these ways:
332
+
333
+ - Add explicit decorator options, such as `@Property({ type: 'string' })` or `@ManyToOne({ entity: () => User })`.
334
+ - Install `@mikro-orm/reflection` at the same exact version as `@mikro-orm/core` so the CLI can auto-use `TsMorphMetadataProvider`.
335
+
336
+ **"Cannot find module '@/...'" (path aliases)**
337
+
338
+ If your config or entities use `tsconfig` path aliases (e.g. `@/entities/user`), `tsx` may fail to resolve them when it cannot find the right `tsconfig.json`. Keeping the config file at your project root (next to `tsconfig.json`) avoids this. If your config lives elsewhere, pass the right file explicitly:
339
+
340
+ ```bash
341
+ mikro-orm-markdown --config ./packages/api/mikro-orm.config.ts --tsconfig ./packages/api/tsconfig.json
342
+ ```
343
+
344
+ **JSDoc tags are missing, or `@hidden` entities appear**
345
+
346
+ Your entities were probably discovered from compiled JavaScript. Build tools may strip comments from `.js` files, so descriptions, `@namespace`, and `@hidden` cannot be read there.
347
+
348
+ Prefer a `.ts` config with `entitiesTs` pointing at your source files. If you must run from compiled `.js`, pass the original TypeScript sources:
349
+
350
+ ```bash
351
+ mikro-orm-markdown --config ./dist/mikro-orm.config.js --src "src/**/*.entity.ts"
352
+ ```
353
+
354
+ **Config file requirements**
355
+
356
+ The config file must have a **default export** of a plain configuration object:
357
+
358
+ ```typescript
359
+ export default defineConfig({ ... }); // ✅
360
+ export const config = defineConfig({ ... }); // ❌ named export not supported
361
+ export default async () => defineConfig({ ... }); // ❌ functions/Promises not supported
362
+ ```
363
+
364
+ If you need to resolve the config asynchronously, use the programmatic API instead (see below).
176
365
 
177
366
  ## Advanced Usage
178
367
 
@@ -181,16 +370,34 @@ When an entity uses `discriminatorColumn`, `mikro-orm-markdown` automatically de
181
370
  If you need to integrate ERD generation into a custom build script or process the output programmatically:
182
371
 
183
372
  ```typescript
373
+ import { writeFile } from 'node:fs/promises';
184
374
  import { generateMarkdown } from 'mikro-orm-markdown';
185
375
  import ormConfig from './mikro-orm.config.js';
186
376
 
187
377
  const markdown = await generateMarkdown({
188
378
  orm: ormConfig,
189
379
  title: 'My Database',
190
- src: ['src/entities/**/*.ts'],
380
+ description: 'Schema documentation generated from MikroORM metadata.',
191
381
  });
192
382
 
193
- await fs.writeFile('./ERD.md', markdown, 'utf-8');
383
+ await writeFile('./ERD.md', markdown, 'utf-8');
384
+ ```
385
+
386
+ Programmatic options:
387
+
388
+ | Option | Description |
389
+ | ------ | ----------- |
390
+ | `orm` | MikroORM options object. Required. |
391
+ | `title` | H1 title. Defaults to `Database Schema`. |
392
+ | `description` | Optional paragraph below the title. Unlike the CLI flag, this can be any string without shell quoting concerns. |
393
+ | `src` | Original TypeScript entity source paths/globs. Only needed when `orm.entities` discovers compiled JavaScript. |
394
+ | `onWarn` | Callback for non-fatal warnings, such as compiled JavaScript JSDoc loss. |
395
+
396
+ If your MikroORM config is asynchronous, resolve it yourself and pass the resulting options object:
397
+
398
+ ```typescript
399
+ const ormConfig = await createOrmConfig();
400
+ const markdown = await generateMarkdown({ orm: ormConfig });
194
401
  ```
195
402
 
196
403
  ## License
package/SECURITY.md ADDED
@@ -0,0 +1,28 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Security fixes are provided for the latest published version of `mikro-orm-markdown`.
6
+
7
+ ## Reporting a Vulnerability
8
+
9
+ Please do not open a public issue with exploit details.
10
+
11
+ Use GitHub private vulnerability reporting if it is available for this repository. If a private channel is not available, open a public issue with a brief, non-sensitive summary and ask for a private contact path.
12
+
13
+ Helpful reports include:
14
+
15
+ - Affected package version
16
+ - Node.js and MikroORM versions
17
+ - Minimal reproduction steps
18
+ - Impact and expected behavior
19
+
20
+ The maintainer will review the report, coordinate a fix when needed, and publish release notes once the issue can be disclosed safely.
21
+
22
+ ## Dependency advisories
23
+
24
+ The shipped runtime dependency tree is clean — `npm audit --omit=dev` reports **0 vulnerabilities**.
25
+
26
+ `npm audit` (including dev dependencies) currently reports advisories that come entirely from the test/build toolchain (the `vitest`/`vite`/`esbuild` chain and `@mikro-orm/sqlite`'s native-build helpers such as `node-gyp`/`tar`). These do not affect anyone installing the published package, since they are not part of the runtime dependency tree.
27
+
28
+ Remediation requires major upgrades that are breaking (e.g. `vitest` 4.x, `@mikro-orm/sqlite` 7.x — the latter would also change the supported MikroORM major) and is tracked for a dedicated maintenance pass rather than forced here.