mikro-orm-markdown 0.1.1 → 0.1.2

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/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../node_modules/tsup/assets/cjs_shims.js","../src/docs/jsdoc.ts","../src/metadata/load.ts","../src/model/build.ts","../src/render/mermaid.ts","../src/render/escape.ts","../src/provider.ts","../src/render/markdown.ts","../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport * as syncFs from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { Options } from '@mikro-orm/core';\nimport { Command } from 'commander';\nimport { generateMarkdown } from './index.js';\nimport type { MermaidLayout, MermaidRenderOptions, MermaidTheme } from './render/mermaid.js';\nimport { MERMAID_LAYOUTS, MERMAID_THEMES } from './render/mermaid.js';\n\ninterface CliOptions {\n config: string;\n out: string;\n title: string;\n description?: string;\n tsconfig?: string;\n src?: string[];\n mermaidLayout?: string;\n mermaidTheme?: string;\n}\n\nexport function toConfigImportSpecifier(configPath: string): string {\n return pathToFileURL(path.resolve(configPath)).href;\n}\n\n/**\n * Walks up from the directory of `fromPath` looking for the nearest\n * `tsconfig.json`. Returns its absolute path, or `undefined` if none is found\n * before reaching the filesystem root.\n *\n * This lets `.ts` config loading resolve the tsconfig relative to the config\n * file itself rather than the current working directory, so the CLI behaves\n * the same regardless of where it is invoked from.\n */\nexport function findNearestTsconfig(fromPath: string): string | undefined {\n let dir = path.dirname(path.resolve(fromPath));\n\n for (;;) {\n const candidate = path.join(dir, 'tsconfig.json');\n if (syncFs.existsSync(candidate)) {\n return candidate;\n }\n\n const parent = path.dirname(dir);\n if (parent === dir) {\n return undefined;\n }\n dir = parent;\n }\n}\n\n/**\n * Loads the MikroORM Options object from a config file.\n *\n * For `.ts` config files, registers the `tsx` loader at runtime so plain\n * `node` can import TypeScript — the user only needs `tsx` installed,\n * not a special invocation (`node --import tsx ...`).\n *\n * The tsconfig handed to `tsx` is resolved relative to the config file (or\n * given explicitly via `tsconfigPath`), not the current working directory.\n * Without this, `tsx` picks up whatever tsconfig sits above the cwd, which may\n * not apply `emitDecoratorMetadata` to the entity files — making discovery\n * fail with a cryptic `Cannot read properties of undefined` error depending on\n * which directory the CLI was launched from.\n */\nexport async function loadOrmOptions(configPath: string, tsconfigPath?: string): Promise<Options> {\n const isTypeScriptConfig = configPath.endsWith('.ts');\n\n if (isTypeScriptConfig) {\n let register: typeof import('tsx/esm/api')['register'];\n try {\n ({ register } = await import('tsx/esm/api'));\n } catch {\n throw new Error('TypeScript config files require the \"tsx\" package.\\nInstall it with: npm install -D tsx');\n }\n\n let tsconfig: string | undefined;\n if (tsconfigPath !== undefined) {\n tsconfig = path.resolve(tsconfigPath);\n if (!syncFs.existsSync(tsconfig)) {\n throw new Error(`--tsconfig file not found: ${tsconfig}`);\n }\n } else {\n tsconfig = findNearestTsconfig(configPath);\n }\n\n register(tsconfig !== undefined ? { tsconfig } : {});\n }\n\n const configUrl = toConfigImportSpecifier(configPath);\n let mod: { default?: unknown };\n try {\n mod = (await import(/* @vite-ignore */ configUrl)) as { default?: unknown };\n } catch (cause) {\n if (isTypeScriptConfig) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `Failed to load TypeScript config.\\n${detail}\\n\\n` +\n 'If this looks like a decorator/metadata error, the tsconfig applied to your ' +\n 'entity files is likely missing \"experimentalDecorators\" / \"emitDecoratorMetadata\".\\n' +\n 'Make sure a tsconfig.json with those options sits next to your config file, ' +\n 'or pass one explicitly with --tsconfig <path>.',\n { cause }\n );\n }\n throw cause;\n }\n\n if (mod.default === undefined) {\n throw new Error('Config file must use a default export, e.g. `export default defineConfig({ ... })`.');\n }\n\n const config = mod.default;\n if (typeof config === 'function' || config instanceof Promise) {\n throw new Error(\n 'Config file default export must be a configuration object, not a function or Promise.\\n' +\n 'Resolve it first, or use the programmatic API instead (see README).'\n );\n }\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n throw new Error(\n 'Config file default export must be a configuration object, not a primitive value or array.\\n' +\n 'Export a plain MikroORM options object instead.'\n );\n }\n\n const options = config as Options;\n const withPreferTs = isTypeScriptConfig && options.preferTs === undefined ? { ...options, preferTs: true } : options;\n\n return withPreferTs;\n}\n\n/**\n * Renders an error together with its `cause` chain, one cause per line.\n *\n * Discovery failures wrap the real MikroORM error (missing driver, bad entities\n * glob, …) in `error.cause`. Printing only the top-level message hides the one\n * piece of information that actually tells the user what went wrong, so we walk\n * the chain and surface each underlying message.\n */\nexport function formatErrorChain(err: unknown): string {\n const lines: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = err;\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n lines.push(current.message);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A non-Error cause at the end of the chain still carries information.\n if (current !== undefined && !(current instanceof Error)) {\n lines.push(String(current));\n }\n\n return lines.map((line, i) => (i === 0 ? line : ` ↳ caused by: ${line}`)).join('\\n');\n}\n\nconst REFLECTION_METADATA_HINT =\n '\\n\\nNote: this tool loads configs via tsx (esbuild), which does not emit ' +\n \"'emitDecoratorMetadata' reflection data, so enabling it will not help here.\\n\" +\n \"Either give each entity property an explicit 'type:'/'entity:' attribute, or \" +\n \"install '@mikro-orm/reflection' — this tool then reads types from your TypeScript sources automatically.\";\n\n/**\n * Formats a discovery error, appending a CLI-specific hint when the failure is\n * MikroORM's reflection-based type resolution.\n *\n * MikroORM's default `ReflectMetadataProvider` infers property types from\n * `emitDecoratorMetadata` reflection and, when it is missing, tells the user to\n * enable that tsconfig option. But the CLI loads `.ts` configs through `tsx`\n * (esbuild), which never emits that metadata — so the advice cannot help. We\n * detect that message in the cause chain and point at the options that do work.\n */\nexport function formatDiscoveryError(err: unknown): string {\n const chain = formatErrorChain(err);\n return chain.includes('emitDecoratorMetadata') ? chain + REFLECTION_METADATA_HINT : chain;\n}\n\nfunction formatFileSystemError(cause: unknown): string {\n if (cause instanceof Error) {\n const code = 'code' in cause && typeof cause.code === 'string' ? ` (${cause.code})` : '';\n return `${cause.message}${code}`;\n }\n\n return String(cause);\n}\n\nexport async function writeMarkdownFile(outPath: string, markdown: string): Promise<void> {\n try {\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, markdown, 'utf-8');\n } catch (cause) {\n throw new Error(`Cannot write output file: ${outPath}\\n${formatFileSystemError(cause)}`, { cause });\n }\n}\n\nfunction parseMermaidOptions(opts: CliOptions): MermaidRenderOptions | undefined {\n const { mermaidLayout, mermaidTheme } = opts;\n\n if (mermaidLayout !== undefined && !(MERMAID_LAYOUTS as readonly string[]).includes(mermaidLayout)) {\n process.stderr.write(\n `Error: Invalid --mermaid-layout \"${mermaidLayout}\". Allowed values: ${MERMAID_LAYOUTS.join(', ')}\\n`\n );\n process.exit(1);\n }\n\n if (mermaidTheme !== undefined && !(MERMAID_THEMES as readonly string[]).includes(mermaidTheme)) {\n process.stderr.write(\n `Error: Invalid --mermaid-theme \"${mermaidTheme}\". Allowed values: ${MERMAID_THEMES.join(', ')}\\n`\n );\n process.exit(1);\n }\n\n if (mermaidLayout === undefined && mermaidTheme === undefined) {\n return undefined;\n }\n\n return {\n ...(mermaidLayout !== undefined && { layout: mermaidLayout as MermaidLayout }),\n ...(mermaidTheme !== undefined && { theme: mermaidTheme as MermaidTheme }),\n };\n}\n\nasync function run(opts: CliOptions): Promise<void> {\n const configPath = path.resolve(opts.config);\n const outPath = path.resolve(opts.out);\n const mermaid = parseMermaidOptions(opts);\n\n let ormOptions: Options;\n try {\n ormOptions = await loadOrmOptions(configPath, opts.tsconfig);\n } catch (err) {\n process.stderr.write(\n `Error: Cannot load config: ${configPath}\\n${err instanceof Error ? err.message : String(err)}\\n`\n );\n process.exit(1);\n }\n\n let markdown: string;\n try {\n markdown = await generateMarkdown({\n orm: ormOptions,\n title: opts.title,\n ...(opts.description !== undefined && { description: opts.description }),\n ...(opts.src !== undefined && { src: opts.src }),\n ...(mermaid !== undefined && { mermaid }),\n onWarn: (message: string): void => void process.stderr.write(`Warning: ${message}\\n`),\n });\n } catch (err) {\n process.stderr.write(`Error: ${formatDiscoveryError(err)}\\n`);\n process.exit(1);\n }\n\n try {\n await writeMarkdownFile(outPath, markdown);\n } catch (err) {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n }\n\n process.stdout.write(`✓ Written to ${path.relative(process.cwd(), outPath)}\\n`);\n}\n\nconst program = new Command()\n .name('mikro-orm-markdown')\n .description('Generate Mermaid ERD + markdown docs from MikroORM entities')\n .requiredOption('-c, --config <path>', 'MikroORM config file path')\n .option('-o, --out <path>', 'Output markdown file path', './ERD.md')\n .option('-t, --title <string>', 'Document title', 'Database Schema')\n .option('-d, --description <string>', 'Optional description paragraph shown below the title')\n .option(\n '--tsconfig <path>',\n 'tsconfig.json to use when loading a .ts config (defaults to the nearest one beside the config file)'\n )\n .option(\n '--src <paths...>',\n 'Source .ts file globs to read JSDoc from when entities run from compiled .js (comments are stripped at build time)'\n )\n .option('--mermaid-layout <layout>', `Mermaid layout engine injected as frontmatter (${MERMAID_LAYOUTS.join('|')})`)\n .option('--mermaid-theme <theme>', `Mermaid theme injected as frontmatter (${MERMAID_THEMES.join('|')})`)\n .action(run);\n\nfunction isDirectCliExecution(): boolean {\n const entryPoint = process.argv[1];\n\n if (entryPoint === undefined) {\n return false;\n }\n\n try {\n return syncFs.realpathSync(path.resolve(entryPoint)) === syncFs.realpathSync(fileURLToPath(import.meta.url));\n } catch {\n return false;\n }\n}\n\nif (isDirectCliExecution()) {\n program.parseAsync(process.argv).catch((err: unknown) => {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n });\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import type { JSDoc } from 'ts-morph';\nimport { Project } from 'ts-morph';\n\n/** JSDoc information extracted from an entity class. */\nexport interface EntityJsDocInfo {\n /** Class-level description (text before any @tags). */\n description?: string;\n /** Namespaces from @namespace tags — appears in both ERD and text table. */\n namespaces: string[];\n /** Namespaces from @erd tags — appears in ERD only. */\n erdNamespaces: string[];\n /** Namespaces from @describe tags — appears in text table only. */\n describeNamespaces: string[];\n /** True when @hidden tag is present — entity is excluded from all output. */\n hidden: boolean;\n}\n\n/** JSDoc information extracted from a single entity property. */\nexport interface PropJsDocInfo {\n /** Property description text. */\n description?: string;\n /** True when the @atLeastOne tag is present — a collection relation that must hold ≥1 elements. */\n atLeastOne: boolean;\n}\n\n/** Keyed by entity class name. */\nexport type EntityJsDocMap = Map<string, EntityJsDocInfo>;\n\n/** Outer key: entity class name. Inner key: property name. */\nexport type PropJsDocMap = Map<string, Map<string, PropJsDocInfo>>;\n\nexport interface JsDocResult {\n entities: EntityJsDocMap;\n props: PropJsDocMap;\n /** Number of TypeScript source files matched and loaded for JSDoc parsing. */\n sourceFileCount: number;\n /** Class declarations found in the loaded source files, including classes without JSDoc. */\n classNames: Set<string>;\n}\n\n/**\n * Parses the given TypeScript source files and extracts JSDoc descriptions\n * and custom tags (@namespace, @erd, @describe, @hidden) from entity classes\n * and their properties.\n *\n * Returns empty maps if no source files are given or no JSDoc is found.\n * Never throws — errors are reported through onWarn so missing docs don't block generation.\n */\nexport function loadJsDoc(filePaths: string[], onWarn?: (message: string) => void): JsDocResult {\n const entities: EntityJsDocMap = new Map();\n const props: PropJsDocMap = new Map();\n const classNames = new Set<string>();\n\n if (filePaths.length === 0) {\n return { entities, props, sourceFileCount: 0, classNames };\n }\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n skipLoadingLibFiles: true,\n compilerOptions: {\n experimentalDecorators: true,\n skipLibCheck: true,\n },\n });\n\n // Add each path independently so one unreadable file or bad glob (EACCES, a\n // directory, etc.) cannot abort the whole run — missing docs must never block\n // generation (the \"never throws\" contract).\n for (const filePath of filePaths) {\n try {\n const sourceFiles = project.addSourceFilesAtPaths(filePath);\n if (sourceFiles.length === 0 && !hasGlobPattern(filePath)) {\n onWarn?.(`No JSDoc source file matched path: ${filePath}`);\n }\n } catch (err) {\n onWarn?.(`Could not load JSDoc source path \"${filePath}\": ${formatUnknownError(err)}`);\n }\n }\n\n const sourceFiles = project.getSourceFiles();\n for (const sourceFile of sourceFiles) {\n try {\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className) {\n continue;\n }\n classNames.add(className);\n\n const classDocs = cls.getJsDocs();\n if (classDocs.length > 0) {\n entities.set(className, parseEntityJsDoc(classDocs));\n }\n\n const propMap = new Map<string, PropJsDocInfo>();\n for (const prop of cls.getProperties()) {\n const propDocs = prop.getJsDocs();\n if (propDocs.length === 0) {\n continue;\n }\n const info = parsePropJsDoc(propDocs);\n if (info.description !== undefined || info.atLeastOne) {\n propMap.set(prop.getName(), info);\n }\n }\n if (propMap.size > 0) {\n props.set(className, propMap);\n }\n }\n } catch (err) {\n onWarn?.(`Could not parse JSDoc source file \"${sourceFile.getFilePath()}\": ${formatUnknownError(err)}`);\n }\n }\n\n return { entities, props, sourceFileCount: sourceFiles.length, classNames };\n}\n\nfunction formatUnknownError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction hasGlobPattern(filePath: string): boolean {\n return /[*?[\\]{}]/.test(filePath);\n}\n\nfunction parseEntityJsDoc(jsDocs: JSDoc[]): EntityJsDocInfo {\n const namespaces: string[] = [];\n const erdNamespaces: string[] = [];\n const describeNamespaces: string[] = [];\n let hidden = false;\n let description: string | undefined;\n\n for (const doc of jsDocs) {\n const desc = doc.getDescription().trim();\n if (desc && description === undefined) {\n description = desc;\n }\n\n for (const tag of doc.getTags()) {\n const tagName = tag.getTagName();\n const comment = tag.getCommentText()?.trim();\n\n if (tagName === 'namespace' && comment) {\n namespaces.push(comment);\n } else if (tagName === 'erd' && comment) {\n erdNamespaces.push(comment);\n } else if (tagName === 'describe' && comment) {\n describeNamespaces.push(comment);\n } else if (tagName === 'hidden') {\n hidden = true;\n }\n }\n }\n\n return {\n ...(description !== undefined && { description }),\n namespaces,\n erdNamespaces,\n describeNamespaces,\n hidden,\n };\n}\n\nfunction parsePropJsDoc(jsDocs: JSDoc[]): PropJsDocInfo {\n let description: string | undefined;\n let atLeastOne = false;\n\n for (const doc of jsDocs) {\n const desc = doc.getDescription().trim();\n if (desc && description === undefined) {\n description = desc;\n }\n for (const tag of doc.getTags()) {\n if (tag.getTagName() === 'atLeastOne') {\n atLeastOne = true;\n }\n }\n }\n\n return { ...(description !== undefined && { description }), atLeastOne };\n}\n","import * as path from 'node:path';\nimport type { EntityMetadata, Options } from '@mikro-orm/core';\nimport { EntitySchema, MikroORM } from '@mikro-orm/core';\n\n/** Errors thrown during metadata loading */\nexport class MetadataLoadError extends Error {\n constructor(\n message: string,\n public override readonly cause?: unknown\n ) {\n super(message);\n this.name = 'MetadataLoadError';\n }\n}\n\nexport interface LoadedEntityMetadata {\n metas: EntityMetadata[];\n /** Absolute paths to the source files each entity class was declared in, deduped. */\n sourcePaths: string[];\n}\n\nasync function closeDiscoveryResources(orm: MikroORM): Promise<void> {\n // With connect=false, orm.close() can instantiate SQL clients just to close them.\n await orm.config.getMetadataCacheAdapter()?.close?.();\n await orm.config.getResultCacheAdapter()?.close?.();\n}\n\nfunction collectEntitySchemaNames(options: Options): string[] {\n const configuredEntities = [...(options.entities ?? []), ...(options.entitiesTs ?? [])];\n const names: string[] = [];\n\n for (const entity of configuredEntities) {\n if (entity instanceof EntitySchema) {\n names.push(entity.meta.className);\n continue;\n }\n\n if (entity !== null && typeof entity === 'object' && 'schema' in entity && entity.schema instanceof EntitySchema) {\n names.push(entity.schema.meta.className);\n }\n }\n\n return names;\n}\n\nfunction assertNoEntitySchemaEntities(options: Options): void {\n const schemaNames = collectEntitySchemaNames(options);\n if (schemaNames.length === 0) {\n return;\n }\n\n throw new MetadataLoadError(\n `EntitySchema-defined entities are not currently supported: ${schemaNames.join(', ')}.\\n` +\n 'Use decorator-based @Entity() classes instead.'\n );\n}\n\n/**\n * Runs MikroORM entity discovery without connecting to the database,\n * and returns all discovered EntityMetadata objects along with the\n * absolute source file paths they were declared in (for JSDoc extraction).\n *\n * The caller is responsible for filtering (e.g. excluding abstract,\n * embeddable, or pivot entities) based on rendering needs.\n */\nexport async function loadEntityMetadata(options: Options): Promise<LoadedEntityMetadata> {\n assertNoEntitySchemaEntities(options);\n\n let orm: MikroORM;\n try {\n orm = await MikroORM.init({\n ...options,\n debug: false,\n connect: false,\n // Always disable the metadata cache for one-shot doc runs so the project\n // is never littered with a temp/ folder, regardless of how metadataProvider\n // was configured.\n metadataCache: { ...options.metadataCache, enabled: false },\n });\n } catch (cause) {\n throw new MetadataLoadError(\n 'Failed to initialize MikroORM and run entity discovery. ' +\n 'Make sure your config is valid and all entity files are accessible.',\n cause\n );\n }\n\n try {\n const all = Object.values(orm.getMetadata().getAll());\n\n if (all.length === 0) {\n throw new MetadataLoadError(\n 'No entities were discovered. ' + 'Check that your config specifies at least one entity path or class.'\n );\n }\n\n const baseDir = orm.config.get('baseDir');\n const sourcePaths = [...new Set(all.filter((m) => m.path).map((m) => path.resolve(baseDir, m.path)))];\n\n return { metas: all, sourcePaths };\n } finally {\n await closeDiscoveryResources(orm);\n }\n}\n","import { type EntityMetadata, ReferenceKind } from '@mikro-orm/core';\nimport type { EntityJsDocInfo, JsDocResult, PropJsDocInfo, PropJsDocMap } from '../docs/jsdoc.js';\nimport { buildDiagramModel } from '../render/mermaid.js';\nimport type { ColumnModel, EntityModel, RelationEdge } from './types.js';\n\n// Mermaid cardinality tokens upgrading the \"many\" side from zero-or-more to one-or-more.\nconst FROM_ONE_OR_MORE = '}|';\nconst TO_ONE_OR_MORE = '|{';\n\n/** An entity with its structural model and JSDoc info merged together. */\nexport interface EnrichedEntity {\n model: EntityModel;\n /** Undefined if the entity has no class-level JSDoc. */\n jsDoc: EntityJsDocInfo | undefined;\n /** Per-property description map (empty map if no property JSDoc). */\n propDocs: Map<string, PropJsDocInfo>;\n}\n\n/**\n * A single namespace group, ready to render as one section of the document.\n *\n * - `erdEntities`: shown in the Mermaid ERD block (@namespace + @erd)\n * - `textEntities`: shown in the column-table sections (@namespace + @describe)\n * - `erdRelations`: relation edges where both endpoints are in `erdEntities`\n */\nexport interface NamespaceGroup {\n name: string;\n erdEntities: EnrichedEntity[];\n textEntities: EnrichedEntity[];\n erdRelations: RelationEdge[];\n}\n\n/** Complete document model — input to the markdown renderer. */\nexport interface DocumentModel {\n title: string;\n /** Optional paragraph rendered below the H1 heading. */\n description?: string;\n groups: NamespaceGroup[];\n}\n\n/**\n * Merges MikroORM structural metadata with JSDoc information and organises the\n * result into namespace groups for rendering.\n *\n * Entities with @hidden are excluded.\n * Entities with no namespace tags fall into the \"default\" group.\n * Groups are ordered alphabetically, with \"default\" always last.\n */\nexport function buildDocumentModel(\n metas: EntityMetadata[],\n jsDocResult: JsDocResult,\n title: string,\n description?: string,\n onWarn?: (message: string) => void\n): DocumentModel {\n const { entities: diagramEntities, relations } = buildDiagramModel(metas);\n const allRelations = applyAtLeastOne(relations, metas, jsDocResult.props, onWarn);\n\n // Classes excluded via @hidden — FK columns pointing at them would otherwise\n // dangle (their edge is dropped, but the column would still reference a target\n // that no longer appears anywhere).\n const hiddenClasses = new Set<string>();\n for (const model of diagramEntities) {\n if (jsDocResult.entities.get(model.className)?.hidden) {\n hiddenClasses.add(model.className);\n }\n }\n\n // Build enriched entity map, filtering out @hidden entities.\n const enrichedByClass = new Map<string, EnrichedEntity>();\n for (const model of diagramEntities) {\n const jsDoc = jsDocResult.entities.get(model.className);\n if (jsDoc?.hidden) {\n continue;\n }\n const columns = model.columns.filter(\n (col) => !(col.isForeignKey && col.referencedEntity !== undefined && hiddenClasses.has(col.referencedEntity))\n );\n const visibleModel = columns.length === model.columns.length ? model : { ...model, columns };\n const ownPropDocs = jsDocResult.props.get(model.className) ?? new Map<string, PropJsDocInfo>();\n const propDocs = withEmbeddedPropDocs(ownPropDocs, visibleModel.columns, jsDocResult.props);\n enrichedByClass.set(model.className, { model: visibleModel, jsDoc, propDocs });\n }\n\n // Collect all unique namespace names referenced by any entity.\n const groupNames = new Set<string>();\n let anyUntagged = false;\n for (const { jsDoc } of enrichedByClass.values()) {\n const allNs = [...(jsDoc?.namespaces ?? []), ...(jsDoc?.erdNamespaces ?? []), ...(jsDoc?.describeNamespaces ?? [])];\n if (allNs.length === 0) {\n anyUntagged = true;\n } else {\n for (const ns of allNs) {\n groupNames.add(ns);\n }\n }\n }\n if (anyUntagged) {\n groupNames.add('default');\n }\n\n const groups: NamespaceGroup[] = [];\n for (const groupName of groupNames) {\n const isDefault = groupName === 'default';\n\n const erdEntities = [...enrichedByClass.values()]\n .filter(({ jsDoc }) => belongsToGroupForErd(jsDoc, groupName, isDefault))\n .map((entity): EnrichedEntity | null => {\n if (isCrossNamespaceInGroup(entity.jsDoc, groupName, isDefault)) {\n const pkColumns = entity.model.columns.filter((col) => col.isPrimary);\n // If no PK columns remain (e.g. FK-as-PK to a @hidden entity was filtered out),\n // exclude the entity entirely: an empty box with dangling arrows is misleading.\n if (pkColumns.length === 0) {\n return null;\n }\n return { ...entity, model: { ...entity.model, columns: pkColumns } };\n }\n return entity;\n })\n .filter((entity): entity is EnrichedEntity => entity !== null);\n\n const textEntities = [...enrichedByClass.values()].filter(({ jsDoc }) =>\n belongsToGroupForText(jsDoc, groupName, isDefault)\n );\n\n const erdClassNames = new Set(erdEntities.map((e) => e.model.className));\n const erdRelations = allRelations.filter((r) => erdClassNames.has(r.fromEntity) && erdClassNames.has(r.toEntity));\n\n groups.push({ name: groupName, erdEntities, textEntities, erdRelations });\n }\n\n // Sort alphabetically; \"default\" is always last.\n groups.sort((a, b) => {\n if (a.name === 'default') {\n return 1;\n }\n if (b.name === 'default') {\n return -1;\n }\n return a.name.localeCompare(b.name);\n });\n\n return { title, groups, ...(description !== undefined && { description }) };\n}\n\n/**\n * Falls back to the @Embeddable class's own JSDoc for flattened embedded columns\n * (e.g. Customer's \"address_street\" picks up Address.street's JSDoc), since the\n * owning entity's source file never declares that synthetic property name.\n * Returns a new map; the input map is not mutated.\n */\nfunction withEmbeddedPropDocs(\n ownPropDocs: Map<string, PropJsDocInfo>,\n columns: ColumnModel[],\n allPropDocs: PropJsDocMap\n): Map<string, PropJsDocInfo> {\n const merged = new Map(ownPropDocs);\n for (const col of columns) {\n if (merged.has(col.propName) || col.embeddedIn === undefined || col.embeddedPropName === undefined) {\n continue;\n }\n const info = allPropDocs.get(col.embeddedIn)?.get(col.embeddedPropName);\n if (info) {\n merged.set(col.propName, info);\n }\n }\n return merged;\n}\n\n/**\n * Upgrades the \"many\" side of a relation edge to one-or-more for collection\n * properties tagged with @atLeastOne. The edge is always built from the owning\n * side, so a collection on the inverse side is matched back via its mappedBy.\n * Returns a new array; input edges are not mutated.\n */\nfunction applyAtLeastOne(\n relations: RelationEdge[],\n metas: EntityMetadata[],\n props: PropJsDocMap,\n onWarn?: (message: string) => void\n): RelationEdge[] {\n const adjusted = relations.map((edge) => ({ ...edge }));\n const metaByClass = new Map(metas.map((m) => [m.className, m]));\n\n for (const [className, propMap] of props) {\n const meta = metaByClass.get(className);\n if (!meta) {\n continue;\n }\n for (const [propName, info] of propMap) {\n if (!info.atLeastOne) {\n continue;\n }\n const prop = meta.properties[propName];\n if (!prop) {\n continue;\n }\n\n let edge: RelationEdge | undefined;\n // 1:N collection — the edge comes from the m:1 owning side; bump its \"many\" (from) side.\n if (prop.kind === ReferenceKind.ONE_TO_MANY && prop.mappedBy) {\n edge = adjusted.find(\n (e) => e.fromEntity === prop.type && e.toEntity === className && e.label === prop.mappedBy\n );\n if (edge) {\n edge.fromCardinality = FROM_ONE_OR_MORE;\n }\n }\n // M:N owning collection — edge built from this prop; the other (to) side becomes one-or-more.\n else if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner === true) {\n edge = adjusted.find((e) => e.fromEntity === className && e.toEntity === prop.type && e.label === propName);\n if (edge) {\n edge.toCardinality = TO_ONE_OR_MORE;\n }\n }\n // M:N inverse collection — edge built from the owner; this (from) side becomes one-or-more.\n else if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.mappedBy) {\n edge = adjusted.find(\n (e) => e.fromEntity === prop.type && e.toEntity === className && e.label === prop.mappedBy\n );\n if (edge) {\n edge.fromCardinality = FROM_ONE_OR_MORE;\n }\n }\n\n // No matching edge: a unidirectional @OneToMany (no mappedBy) or a label\n // mismatch leaves the cardinality unchanged. Warn instead of failing silently.\n if (!edge) {\n onWarn?.(\n `@atLeastOne on ${className}.${propName} had no effect: no matching relation edge was found. ` +\n 'It applies only to collection relations that can be matched to a rendered edge: ' +\n '@OneToMany with mappedBy, or @ManyToMany on either the owning side or an inverse mappedBy side.'\n );\n }\n }\n }\n\n return adjusted;\n}\n\nfunction hasNoNamespaceTags(jsDoc: EntityJsDocInfo | undefined): boolean {\n if (!jsDoc) {\n return true;\n }\n return jsDoc.namespaces.length === 0 && jsDoc.erdNamespaces.length === 0 && jsDoc.describeNamespaces.length === 0;\n}\n\nfunction belongsToGroupForErd(jsDoc: EntityJsDocInfo | undefined, groupName: string, isDefault: boolean): boolean {\n if (isDefault) {\n return hasNoNamespaceTags(jsDoc);\n }\n if (!jsDoc) {\n return false;\n }\n return jsDoc.namespaces.includes(groupName) || jsDoc.erdNamespaces.includes(groupName);\n}\n\nfunction belongsToGroupForText(jsDoc: EntityJsDocInfo | undefined, groupName: string, isDefault: boolean): boolean {\n if (isDefault) {\n return hasNoNamespaceTags(jsDoc);\n }\n if (!jsDoc) {\n return false;\n }\n return jsDoc.namespaces.includes(groupName) || jsDoc.describeNamespaces.includes(groupName);\n}\n\n/**\n * Returns true when an entity appears in a group's ERD only via @erd while its\n * home section is another namespace. Entities with only @erd tags have no text\n * home section, so their ERD section renders the full model.\n */\nfunction isCrossNamespaceInGroup(jsDoc: EntityJsDocInfo | undefined, groupName: string, isDefault: boolean): boolean {\n if (isDefault || !jsDoc) {\n return false;\n }\n const hasHomeNamespace = jsDoc.namespaces.length > 0 || jsDoc.describeNamespaces.length > 0;\n return (\n hasHomeNamespace &&\n jsDoc.erdNamespaces.includes(groupName) &&\n !jsDoc.namespaces.includes(groupName) &&\n !jsDoc.describeNamespaces.includes(groupName)\n );\n}\n","import type { EntityMetadata, EntityProperty, FormulaTable } from '@mikro-orm/core';\nimport { ReferenceKind } from '@mikro-orm/core';\nimport type { ColumnModel, ConstraintModel, DiagramModel, EntityModel, RelationEdge } from '../model/types.js';\nimport { escapeMermaidQuotedText, toMermaidIdentifier } from './escape.js';\n\nexport const MERMAID_LAYOUTS = ['dagre', 'elk', 'elk.stress'] as const;\nexport type MermaidLayout = (typeof MERMAID_LAYOUTS)[number];\n\nexport const MERMAID_THEMES = ['default', 'neutral', 'dark', 'forest', 'base'] as const;\nexport type MermaidTheme = (typeof MERMAID_THEMES)[number];\n\n/** Optional Mermaid rendering hints injected as YAML frontmatter inside the erDiagram fence. */\nexport interface MermaidRenderOptions {\n layout?: MermaidLayout;\n theme?: MermaidTheme;\n}\n\n// Dummy table descriptor used when resolving formula expressions for documentation.\n// String-based formulas ignore both arguments; function-based formulas use the alias.\nconst FORMULA_DUMMY_TABLE: FormulaTable = {\n alias: 'e0',\n name: '',\n qualifiedName: '',\n toString: () => 'e0',\n};\n\nconst UNRESOLVED_FORMULA = '<unresolved>';\n\n/**\n * Converts raw MikroORM EntityMetadata array into a DiagramModel.\n *\n * Excluded from entity boxes:\n * - Pivot tables (auto-generated M:N join tables) — represented as edges\n * - @Embeddable classes — their columns appear inline inside the owning entity\n */\nexport function buildDiagramModel(metas: EntityMetadata[]): DiagramModel {\n const metaByClass = new Map(metas.map((m) => [m.className, m]));\n\n const entities: EntityModel[] = metas\n .filter((meta) => !meta.pivotTable && !meta.embeddable)\n .map((meta) => buildEntityModel(meta, metaByClass));\n\n const relations: RelationEdge[] = buildRelationEdges(metas);\n\n return { entities, relations };\n}\n\nfunction buildEntityModel(meta: EntityMetadata, metaByClass: Map<string, EntityMetadata>): EntityModel {\n // STI root: defines the discriminatorColumn and does not itself extend a parent.\n // A *non-abstract* root is also assigned its own discriminatorValue by MikroORM,\n // so we must not key off the absence of discriminatorValue here — that would\n // misclassify non-abstract roots and leak every subclass column into them.\n // The root's properties list includes all child-only columns (inherited=true) — filter them out.\n const isStiRoot = meta.discriminatorColumn !== undefined && !meta.extends;\n const isStiChild = Boolean(meta.extends) && meta.discriminatorValue !== undefined;\n\n const columns: ColumnModel[] = [];\n for (const prop of Object.values(meta.properties)) {\n if (isStiRoot && prop.inherited === true) {\n continue;\n }\n columns.push(...buildColumns(prop, metaByClass, meta));\n }\n\n return {\n className: meta.className,\n tableName: meta.tableName,\n columns,\n isPivot: false,\n isEmbeddable: meta.embeddable === true,\n ...(isStiRoot && { discriminatorColumn: meta.discriminatorColumn as string }),\n ...(isStiChild && { extendsEntity: meta.extends }),\n ...(isStiChild && meta.discriminatorValue !== undefined && { discriminatorValue: String(meta.discriminatorValue) }),\n constraints: buildConstraints(meta),\n };\n}\n\n/** Returns ColumnModels for renderable properties, or an empty array to skip. */\nfunction buildColumns(\n prop: EntityProperty,\n metaByClass: Map<string, EntityMetadata>,\n owningMeta: EntityMetadata\n): ColumnModel[] {\n if (prop.kind === ReferenceKind.EMBEDDED) {\n // An object/array embedded is stored as a single JSON column, so render one\n // column for it. (`array: true` implies `object: true`.) A plain inline\n // embedded has no column of its own — its fields surface as flat SCALARs.\n if (prop.object === true || prop.array === true) {\n return [\n {\n propName: prop.name,\n fieldName: prop.fieldNames?.[0] ?? prop.name,\n type: 'json',\n isPrimary: false,\n isForeignKey: false,\n isUnique: prop.unique === true,\n isNullable: prop.nullable === true,\n ...(prop.comment !== undefined && { comment: prop.comment }),\n embeddedIn: prop.array === true ? `${prop.type}[]` : prop.type,\n },\n ];\n }\n return [];\n }\n\n if (prop.kind === ReferenceKind.SCALAR) {\n // Flat leaf of an object/array embedded: it lives inside the single JSON\n // column rendered above, so it is not a column of its own — skip it.\n if (prop.object === true && prop.embedded !== undefined) {\n return [];\n }\n\n // For @Formula columns, formula is set on a SCALAR-kinded property\n const formulaExpr: string | undefined =\n prop.formula !== undefined\n ? resolveFormulaExpr(prop.formula as (table: FormulaTable, cols: Record<string, string>) => string)\n : undefined;\n\n // Shadow property (persist: false, e.g. a cached/computed runtime value or a\n // getter-only property): MikroORM never writes or reads a DB column for it, so\n // it has no physical column to document. @Formula columns are persist: false\n // too, but they ARE meaningful to document (a real SELECT-time expression), so\n // only skip when there is no formula.\n if (prop.persist === false && formulaExpr === undefined) {\n return [];\n }\n\n // Flat embedded columns carry `embedded: [ownerPropName, embeddedPropName]`\n let embeddedIn: string | undefined;\n let embeddedPropName: string | undefined;\n if (prop.embedded !== undefined) {\n const parentPropName = prop.embedded[0];\n embeddedIn = owningMeta.properties[parentPropName]?.type;\n embeddedPropName = prop.embedded[1];\n }\n\n const isDiscriminator =\n owningMeta.discriminatorColumn !== undefined && prop.name === owningMeta.discriminatorColumn;\n\n const enumItems =\n prop.enum === true && Array.isArray(prop.items) && prop.items.length > 0\n ? prop.items.map((item) => String(item))\n : undefined;\n\n return [\n {\n propName: prop.name,\n fieldName: prop.fieldNames?.[0] ?? prop.name,\n // Store the original type (e.g. `varchar(255)`); the Mermaid renderer\n // sanitizes it for diagram identifiers, while the markdown table shows\n // it verbatim. Guard against a missing type so downstream string\n // handling never sees undefined (matches the FK path's defaulting).\n type: prop.type ?? 'unknown',\n isPrimary: prop.primary === true,\n isForeignKey: false,\n isUnique: prop.unique === true,\n isNullable: prop.nullable === true,\n ...(prop.comment !== undefined && { comment: prop.comment }),\n ...(formulaExpr !== undefined && { formula: formulaExpr }),\n ...(embeddedIn !== undefined && { embeddedIn }),\n ...(embeddedPropName !== undefined && { embeddedPropName }),\n ...(isDiscriminator && { isDiscriminator: true }),\n ...(enumItems !== undefined && { enumItems }),\n },\n ];\n }\n\n // FK columns: m:1 always owns the FK; 1:1 only when owner === true\n if (prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner === true)) {\n const cols = buildForeignKeyColumns(prop, metaByClass);\n if (prop.type === owningMeta.className) {\n return cols.map((col) => ({ ...col, isSelfReference: true }));\n }\n return cols;\n }\n\n // ONE_TO_MANY, MANY_TO_MANY (both owner and inverse) → no physical column\n return [];\n}\n\n/**\n * Calls the FormulaCallback with a dummy table and column proxy to extract the SQL expression.\n * String-based formulas (most common) ignore their arguments and return the literal string.\n * Function-based formulas use the alias/column names from the dummy objects.\n * Returns a visible fallback on unexpected errors so generated docs do not hide\n * that the expression could not be resolved.\n */\nfunction resolveFormulaExpr(cb: (table: FormulaTable, cols: Record<string, string>) => string): string {\n try {\n const cols = new Proxy<Record<string, string>>(\n {},\n {\n get: (_target: Record<string, string>, key: string | symbol): string => (typeof key === 'string' ? key : ''),\n }\n );\n const result = cb(FORMULA_DUMMY_TABLE, cols);\n // The callback is typed to return a string, but a misbehaving formula can\n // return anything; coerce so downstream string handling never crashes.\n return typeof result === 'string' ? result : String(result);\n } catch {\n return UNRESOLVED_FORMULA;\n }\n}\n\nfunction buildForeignKeyColumns(prop: EntityProperty, metaByClass: Map<string, EntityMetadata>): ColumnModel[] {\n const fieldNames = prop.fieldNames && prop.fieldNames.length > 0 ? prop.fieldNames : [`${prop.name}_id`];\n const fkTypes = resolveFkTypes(prop, metaByClass, fieldNames.length);\n\n return fieldNames.map((fieldName, index) => ({\n propName: prop.name,\n fieldName,\n type: fkTypes[index] ?? fkTypes[0] ?? 'integer',\n isPrimary: prop.primary === true,\n isForeignKey: true,\n isUnique: prop.unique === true,\n isNullable: prop.nullable === true,\n ...(prop.comment !== undefined && { comment: prop.comment }),\n referencedEntity: prop.type,\n }));\n}\n\n/** Looks up referenced PK types to use as FK column types, preserving composite key order. */\nfunction resolveFkTypes(\n prop: EntityProperty,\n metaByClass: Map<string, EntityMetadata>,\n fieldNameCount: number\n): string[] {\n const refMeta = metaByClass.get(prop.type);\n if (!refMeta) {\n return Array.from({ length: fieldNameCount }, () => 'integer');\n }\n\n const primaryProps = getPrimaryProps(refMeta);\n const referencedColumnNames = prop.referencedColumnNames ?? [];\n return Array.from({ length: fieldNameCount }, (_value, index) => {\n const referencedColumnName = referencedColumnNames[index];\n const pkProp =\n referencedColumnName !== undefined\n ? primaryProps.find((candidate) => candidate.fieldNames.includes(referencedColumnName))\n : undefined;\n\n const resolvedProp = pkProp ?? primaryProps[index] ?? primaryProps[0];\n const rawType = resolvedProp?.type ?? 'integer';\n // Pass the resolved prop's position so recursive calls follow the same column in\n // deeper entities (preserves composite-key alignment through FK-as-PK chains).\n const pkIndex = resolvedProp !== undefined ? primaryProps.indexOf(resolvedProp) : 0;\n return resolveScalarType(rawType, metaByClass, pkIndex);\n });\n}\n\n/**\n * Follows entity-class-name references until a non-entity scalar type is reached.\n * Handles supertype-subtype chains where B.id is FK to A, and C.id is FK to B.\n * pkIndex preserves composite-key column alignment at each level of the chain.\n */\nfunction resolveScalarType(type: string, metaByClass: Map<string, EntityMetadata>, pkIndex = 0, depth = 0): string {\n if (depth >= 5) {\n return 'integer';\n }\n const refMeta = metaByClass.get(type);\n if (!refMeta) {\n return type;\n }\n const primaryProps = getPrimaryProps(refMeta);\n if (primaryProps.length === 0) {\n return type;\n }\n const targetProp = primaryProps[pkIndex] ?? primaryProps[0];\n const nextType = targetProp?.type ?? type;\n if (nextType === type) {\n return type;\n }\n return resolveScalarType(nextType, metaByClass, pkIndex, depth + 1);\n}\n\nfunction getPrimaryProps(meta: EntityMetadata): EntityProperty[] {\n const primaryKeys = meta.primaryKeys ?? [];\n const orderedPrimaryProps = primaryKeys\n .map((key) => meta.properties[String(key)])\n .filter((prop): prop is EntityProperty => prop !== undefined);\n\n if (orderedPrimaryProps.length > 0) {\n return orderedPrimaryProps;\n }\n\n return Object.values(meta.properties).filter((prop) => prop.primary === true);\n}\n\n/** Collects indexes, unique constraints, and check constraints from entity-level metadata. */\nfunction buildConstraints(meta: EntityMetadata): ConstraintModel[] {\n const result: ConstraintModel[] = [];\n\n for (const idx of meta.indexes ?? []) {\n const props = idx.properties;\n result.push({\n type: 'index',\n properties: resolveConstraintProperties(meta, props),\n ...(idx.name !== undefined && { name: idx.name }),\n });\n }\n\n for (const uniq of meta.uniques ?? []) {\n const props = uniq.properties;\n result.push({\n type: 'unique',\n properties: resolveConstraintProperties(meta, props),\n ...(uniq.name !== undefined && { name: uniq.name }),\n });\n }\n\n for (const check of meta.checks ?? []) {\n // Skip function-based check expressions (they require column reference objects at runtime)\n if (typeof check.expression !== 'string') {\n continue;\n }\n result.push({\n type: 'check',\n properties: [],\n expression: check.expression,\n ...(check.name !== undefined && { name: check.name }),\n });\n }\n\n return result;\n}\n\nfunction resolveConstraintProperties(meta: EntityMetadata, props: string | string[] | undefined): string[] {\n const propNames = Array.isArray(props) ? props : props !== undefined ? [props] : [];\n\n return propNames.flatMap((propName) => {\n const prop = meta.properties[String(propName)];\n if (prop === undefined) {\n return [String(propName)];\n }\n\n if (prop.fieldNames !== undefined && prop.fieldNames.length > 0) {\n return prop.fieldNames;\n }\n\n return [prop.name];\n });\n}\n\n/**\n * Builds edges only from owning sides to avoid duplicate arrows.\n * STI inheritance is not drawn as an edge — it is conveyed through table captions instead.\n */\nfunction buildRelationEdges(metas: EntityMetadata[]): RelationEdge[] {\n const edges: RelationEdge[] = [];\n\n for (const meta of metas) {\n if (meta.pivotTable || meta.embeddable) {\n continue;\n }\n\n for (const prop of Object.values(meta.properties)) {\n const edge = buildEdge(meta.className, prop);\n if (edge !== null) {\n edges.push(edge);\n }\n }\n }\n\n return edges;\n}\n\nfunction buildEdge(fromEntity: string, prop: EntityProperty): RelationEdge | null {\n const isNullable = prop.nullable === true;\n\n if (prop.kind === ReferenceKind.MANY_TO_ONE) {\n if (prop.type === fromEntity) {\n return null; // self-reference: shown as column comment, not a relation line\n }\n return {\n fromEntity,\n toEntity: prop.type,\n fromCardinality: '}o',\n toCardinality: isNullable ? 'o|' : '||',\n label: prop.name,\n };\n }\n\n if (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner === true) {\n if (prop.type === fromEntity) {\n return null; // self-reference: shown as column comment, not a relation line\n }\n return {\n fromEntity,\n toEntity: prop.type,\n fromCardinality: '||',\n toCardinality: isNullable ? 'o|' : '||',\n label: prop.name,\n };\n }\n\n if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner === true) {\n return {\n fromEntity,\n toEntity: prop.type,\n fromCardinality: '}o',\n toCardinality: 'o{',\n label: prop.name,\n };\n }\n\n return null;\n}\n\n/**\n * Maps DB-specific or ORM-internal type strings to RDBMS-agnostic generic types\n * so the generated docs are portable across PostgreSQL, MySQL, SQLite, etc.\n */\nexport function normalizeType(type: string): string {\n const t = type.toLowerCase().trim();\n if (t === 'uuid' || t === 'text' || t === 'string' || t.startsWith('varchar')) {\n return 'string';\n }\n if (t === 'timestamptz' || t === 'timestamp' || t === 'datetime') {\n return 'datetime';\n }\n if (t === 'integer' || t === 'int' || t === 'bigint' || t === 'smallint') {\n return 'integer';\n }\n if (t === 'doubletype' || t === 'double precision' || t === 'double' || t === 'float' || t === 'decimal') {\n return 'float';\n }\n if (t === 'boolean' || t === 'bool') {\n return 'boolean';\n }\n if (t === 'jsonb') {\n return 'json';\n }\n return type;\n}\n\n/**\n * Renders a DiagramModel as a Mermaid erDiagram block string.\n * The returned string is ready to embed in a markdown code fence.\n * When `mermaid` options are provided, a YAML frontmatter block is prepended.\n */\nexport function renderErDiagram(model: DiagramModel, mermaid?: MermaidRenderOptions): string {\n const lines: string[] = [];\n\n if (mermaid?.layout !== undefined || mermaid?.theme !== undefined) {\n lines.push('---', 'config:');\n if (mermaid.layout !== undefined) {\n lines.push(` layout: ${mermaid.layout}`);\n }\n if (mermaid.theme !== undefined) {\n lines.push(` theme: ${mermaid.theme}`);\n }\n lines.push('---');\n }\n\n lines.push('erDiagram');\n\n for (const entity of model.entities) {\n lines.push(` ${toMermaidIdentifier(entity.className)} {`);\n for (const col of entity.columns) {\n lines.push(` ${renderColumnLine(col)}`);\n }\n lines.push(' }');\n }\n\n for (const rel of model.relations) {\n lines.push(\n ` ${toMermaidIdentifier(rel.fromEntity)} ${rel.fromCardinality}--${rel.toCardinality} ${toMermaidIdentifier(rel.toEntity)} : \"${escapeMermaidQuotedText(rel.label)}\"`\n );\n }\n\n return lines.join('\\n');\n}\n\nfunction renderColumnLine(col: ColumnModel): string {\n // Priority: PK > UK (FK qualifier omitted — relationship lines already convey FK relationships)\n let qualifier = '';\n if (col.isPrimary) {\n qualifier = ' PK';\n } else if (col.isUnique) {\n qualifier = ' UK';\n }\n\n // Comment priority (MikroORM-specific markers only — keeps the diagram uncluttered).\n // Renamed columns: FK columns surface their TS name in the markdown table's Key\n // cell (\"FK (propName)\"); plain renamed scalars show only the DB column name.\n // 1. @Formula SQL expression — \"formula: LENGTH(name)\"\n // 2. STI discriminator column — \"discriminator\"\n // 3. Embedded source type — \"[Address]\"\n let comment: string | undefined;\n if (col.formula !== undefined) {\n comment = col.formula ? `formula: ${col.formula}` : 'formula';\n } else if (col.isDiscriminator) {\n comment = 'discriminator';\n } else if (col.embeddedIn !== undefined) {\n comment = `[${col.embeddedIn}]`;\n } else if (col.isSelfReference) {\n comment = 'self-ref';\n }\n\n const commentStr = comment !== undefined ? ` \"${escapeMermaidQuotedText(comment)}\"` : '';\n return `${toMermaidIdentifier(normalizeType(col.type))} ${toMermaidIdentifier(col.fieldName)}${qualifier}${commentStr}`;\n}\n","const MARKDOWN_INLINE_SPECIAL_CHARS = /[\\\\`|*#]/g;\nconst MERMAID_IDENTIFIER_INVALID_CHARS = /[^a-zA-Z0-9_]/g;\n\nfunction normalizeInlineText(value: string): string {\n return value\n .replace(/\\r\\n?/g, '\\n')\n .replace(/[\\n\\t]+/g, ' ')\n .replace(/\\s{2,}/g, ' ')\n .trim();\n}\n\nfunction splitNormalizedLines(value: string): string[] {\n return value.replace(/\\r\\n?/g, '\\n').split('\\n');\n}\n\nfunction escapeHtmlText(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\nexport function escapeMarkdownInline(value: string): string {\n return escapeHtmlText(normalizeInlineText(value)).replace(MARKDOWN_INLINE_SPECIAL_CHARS, '\\\\$&');\n}\n\nexport function escapeMarkdownTableCell(value: string): string {\n return splitNormalizedLines(value)\n .map((line) => escapeMarkdownInline(line))\n .join('<br>');\n}\n\n/**\n * Escapes a multi-line paragraph for markdown body text, preserving line breaks\n * as hard breaks (two trailing spaces + newline) instead of collapsing them to\n * a single space. Used for the document description, which the programmatic API\n * accepts as free-form multi-line text.\n */\nexport function escapeMarkdownParagraph(value: string): string {\n return splitNormalizedLines(value)\n .map((line) => escapeMarkdownInline(line))\n .join(' \\n');\n}\n\nexport function renderMarkdownBlockQuote(value: string): string {\n return splitNormalizedLines(value)\n .map((line) => `> ${escapeMarkdownInline(line)}`)\n .join('\\n');\n}\n\nexport function renderMarkdownInlineCode(value: string): string {\n const normalized = normalizeInlineText(value);\n const backtickRuns = normalized.match(/`+/g) ?? [];\n const longestRun = Math.max(0, ...backtickRuns.map((run) => run.length));\n const fence = '`'.repeat(longestRun + 1);\n const needsPadding = normalized.startsWith('`') || normalized.endsWith('`');\n const content = needsPadding ? ` ${normalized} ` : normalized;\n return `${fence}${content}${fence}`;\n}\n\nexport function toMermaidIdentifier(value: string): string {\n const normalized = normalizeInlineText(value).replace(MERMAID_IDENTIFIER_INVALID_CHARS, '_').replace(/_+/g, '_');\n const identifier = normalized === '' ? '_' : normalized;\n return /^[a-zA-Z_]/.test(identifier) ? identifier : `_${identifier}`;\n}\n\nexport function escapeMermaidQuotedText(value: string): string {\n return normalizeInlineText(value).replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Builds a GitHub-style heading anchor slug for in-document links.\n * Lowercases, drops characters other than letters / numbers / underscores /\n * spaces / hyphens, then turns spaces into hyphens. The letter/number classes\n * are Unicode-aware (\\p{L}, \\p{N}), so non-ASCII headings such as a Korean\n * namespace name keep their characters and match GitHub's generated anchor.\n */\nexport function toMarkdownAnchor(value: string): string {\n return normalizeInlineText(value)\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s_-]/gu, '')\n .replace(/\\s+/g, '-');\n}\n","import type { Options } from '@mikro-orm/core';\n\n/**\n * When the config does not choose a metadata provider, opt into\n * `TsMorphMetadataProvider` if `@mikro-orm/reflection` is installed.\n *\n * The CLI loads `.ts` configs through `tsx` (esbuild), which strips\n * `emitDecoratorMetadata`, so MikroORM's default `ReflectMetadataProvider`\n * cannot infer types for entities that omit explicit `type:`/`entity:`\n * attributes. `TsMorphMetadataProvider` reads types from the TypeScript sources\n * instead. When the optional package is absent the original options are kept.\n */\nexport async function withTsMorphMetadataProvider(\n options: Options,\n onWarn?: (message: string) => void\n): Promise<Options> {\n if (options.metadataProvider !== undefined) {\n return options;\n }\n\n try {\n const { TsMorphMetadataProvider } = await import('@mikro-orm/reflection');\n return { ...options, metadataProvider: TsMorphMetadataProvider };\n } catch (err) {\n const code =\n err !== null && typeof err === 'object' && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;\n const isNotInstalled = code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND';\n\n if (!isNotInstalled && onWarn) {\n onWarn(\n `@mikro-orm/reflection is installed but failed to load: ${err instanceof Error ? err.message : String(err)}. ` +\n 'Ensure all @mikro-orm/* packages are installed at the same version.'\n );\n }\n\n return options;\n }\n}\n","import type { DocumentModel, EnrichedEntity, NamespaceGroup } from '../model/build.js';\nimport type { ColumnModel, ConstraintModel, DiagramModel } from '../model/types.js';\nimport {\n escapeMarkdownInline,\n escapeMarkdownParagraph,\n escapeMarkdownTableCell,\n renderMarkdownBlockQuote,\n renderMarkdownInlineCode,\n toMarkdownAnchor,\n} from './escape.js';\nimport { type MermaidRenderOptions, normalizeType, renderErDiagram } from './mermaid.js';\n\n/**\n * Renders a DocumentModel as a markdown string.\n * Each namespace group becomes a level-2 section with a Mermaid ERD block\n * followed by per-entity column tables.\n */\nexport function renderMarkdown(docModel: DocumentModel, mermaid?: MermaidRenderOptions): string {\n const sections: string[] = [`# ${escapeMarkdownInline(docModel.title)}`];\n\n if (docModel.description) {\n sections.push(escapeMarkdownParagraph(docModel.description));\n }\n\n // A table of contents only helps when there is more than one namespace section.\n if (docModel.groups.length > 1) {\n sections.push(renderTableOfContents(docModel.groups, resolveGroupAnchors(docModel)));\n }\n\n for (const group of docModel.groups) {\n sections.push(renderGroupSection(group, mermaid));\n }\n\n return sections.join('\\n\\n');\n}\n\n/**\n * Renders a bulleted markdown section: a header line, a blank line, then one\n * line per item. Shared by the Contents / Computed columns / Constraints\n * sections, which differ only in their header and per-item formatting.\n */\nfunction renderBulletSection<T>(header: string, items: T[], renderItem: (item: T) => string): string {\n const lines = [header, ''];\n for (const item of items) {\n lines.push(renderItem(item));\n }\n return lines.join('\\n');\n}\n\n/** Renders a namespace-level table of contents linking to each group's H2 section. */\nfunction renderTableOfContents(groups: NamespaceGroup[], anchors: Map<NamespaceGroup, string>): string {\n return renderBulletSection('## Contents', groups, (group) => {\n // escapeMarkdownInline does not touch brackets; escape them here so a name\n // containing `[` or `]` cannot prematurely close the link label `[...]`.\n const label = escapeMarkdownInline(group.name).replace(/[[\\]]/g, '\\\\$&');\n return `- [${label}](#${anchors.get(group) ?? toMarkdownAnchor(group.name)})`;\n });\n}\n\nfunction resolveGroupAnchors(docModel: DocumentModel): Map<NamespaceGroup, string> {\n const seenAnchors = new Map<string, number>();\n const groupAnchors = new Map<NamespaceGroup, string>();\n\n resolveHeadingAnchor(docModel.title, seenAnchors);\n resolveHeadingAnchor('Contents', seenAnchors);\n\n for (const group of docModel.groups) {\n groupAnchors.set(group, resolveHeadingAnchor(group.name, seenAnchors));\n for (const entity of group.textEntities) {\n resolveHeadingAnchor(entity.model.className, seenAnchors);\n }\n }\n\n return groupAnchors;\n}\n\nfunction resolveHeadingAnchor(value: string, seenAnchors: Map<string, number>): string {\n const baseAnchor = toMarkdownAnchor(value);\n const previousCount = seenAnchors.get(baseAnchor) ?? 0;\n seenAnchors.set(baseAnchor, previousCount + 1);\n return previousCount === 0 ? baseAnchor : `${baseAnchor}-${previousCount}`;\n}\n\nfunction renderGroupSection(group: NamespaceGroup, mermaid?: MermaidRenderOptions): string {\n const parts: string[] = [`## ${escapeMarkdownInline(group.name)}`];\n\n if (group.erdEntities.length > 0) {\n const diagramModel: DiagramModel = {\n entities: group.erdEntities.map((e) => e.model),\n relations: group.erdRelations,\n };\n parts.push('```mermaid\\n' + renderErDiagram(diagramModel, mermaid) + '\\n```');\n }\n\n for (const entity of group.textEntities) {\n parts.push(renderEntitySection(entity));\n }\n\n return parts.join('\\n\\n');\n}\n\nfunction renderEntitySection(entity: EnrichedEntity): string {\n const parts: string[] = [`### ${escapeMarkdownInline(entity.model.className)}`];\n\n // The actual DB table name is what readers of a schema doc look for first,\n // and it is not otherwise visible (the ERD and heading use the class name).\n parts.push(`*Table: ${renderMarkdownInlineCode(entity.model.tableName)}*`);\n\n if (entity.jsDoc?.description) {\n parts.push(renderMarkdownBlockQuote(entity.jsDoc.description));\n }\n\n // STI metadata note\n if (entity.model.discriminatorColumn) {\n parts.push(`*STI root — discriminator column: ${renderMarkdownInlineCode(entity.model.discriminatorColumn)}*`);\n } else if (entity.model.extendsEntity) {\n const discValue =\n entity.model.discriminatorValue !== undefined\n ? `, discriminator value: ${renderMarkdownInlineCode(entity.model.discriminatorValue)}`\n : '';\n parts.push(\n `*Extends ${renderMarkdownInlineCode(entity.model.extendsEntity)} (Single Table Inheritance${discValue})*`\n );\n }\n\n if (entity.model.columns.length > 0) {\n parts.push(renderColumnTable(entity));\n }\n\n if (entity.model.constraints.length > 0) {\n parts.push(renderConstraints(entity.model.constraints));\n }\n\n const computedColumns = entity.model.columns.filter((col) => col.formula !== undefined);\n if (computedColumns.length > 0) {\n parts.push(renderComputedColumns(computedColumns));\n }\n\n return parts.join('\\n\\n');\n}\n\nfunction renderColumnTable(entity: EnrichedEntity): string {\n const header = '| Column | Type | Key | Nullable | Description |';\n const sep = '|--------|------|-----|----------|-------------|';\n const rows = entity.model.columns.map((col) => {\n const key = resolveColumnKey(col);\n const nullable = col.isNullable && !col.isPrimary ? 'Y' : '';\n // JSDoc property description wins; fall back to the @Property({ comment }) DDL comment.\n const docDesc = entity.propDocs.get(col.propName)?.description ?? col.comment ?? '';\n // Surface @Enum allowed values; the table cell escapes backticks, so plain text.\n const enumDesc = col.enumItems !== undefined ? `One of: ${col.enumItems.join(', ')}` : '';\n const desc = [docDesc, enumDesc].filter((part) => part !== '').join('\\n');\n return `| ${escapeMarkdownTableCell(col.fieldName)} | ${escapeMarkdownTableCell(normalizeType(col.type))} | ${escapeMarkdownTableCell(key)} | ${nullable} | ${escapeMarkdownTableCell(desc)} |`;\n });\n return [header, sep, ...rows].join('\\n');\n}\n\n/** Returns the \"Key\" cell value for the column table. */\nfunction resolveColumnKey(col: ColumnModel): string {\n const fkKey = col.fieldName !== col.propName ? `FK (${col.propName})` : 'FK';\n\n if (col.isPrimary && col.isForeignKey) {\n return `PK, ${fkKey}`;\n }\n if (col.isPrimary) {\n return 'PK';\n }\n if (col.isForeignKey) {\n // Show TS property name in parentheses if it differs from the DB column name\n return fkKey;\n }\n if (col.isUnique) {\n return 'UK';\n }\n if (col.isDiscriminator) {\n return 'discriminator';\n }\n if (col.embeddedIn !== undefined) {\n return `[${col.embeddedIn}]`;\n }\n return '';\n}\n\nfunction renderComputedColumns(columns: ColumnModel[]): string {\n return renderBulletSection('**Computed columns:**', columns, (col) => {\n // An empty/unresolved formula expression renders as just the column name —\n // the \"Computed columns\" heading already conveys that it is computed, and\n // an empty inline-code span would be broken output.\n const expr = col.formula ? `: ${renderMarkdownInlineCode(col.formula)}` : '';\n return `- ${renderMarkdownInlineCode(col.fieldName)}${expr}`;\n });\n}\n\nfunction renderConstraints(constraints: ConstraintModel[]): string {\n return renderBulletSection('**Constraints:**', constraints, (c) => {\n const name = c.name ? ` ${renderMarkdownInlineCode(c.name)}` : '';\n const properties = c.properties.map(escapeMarkdownInline).join(', ');\n if (c.type === 'index') {\n return `- Index${name}: (${properties})`;\n }\n if (c.type === 'unique') {\n return `- Unique${name}: (${properties})`;\n }\n return `- Check${name}: ${renderMarkdownInlineCode(c.expression ?? '')}`;\n });\n}\n","import type { EntityMetadata, Options } from '@mikro-orm/core';\nimport { type JsDocResult, loadJsDoc } from './docs/jsdoc.js';\nimport { type LoadedEntityMetadata, loadEntityMetadata } from './metadata/load.js';\nimport { buildDocumentModel } from './model/build.js';\nimport { withTsMorphMetadataProvider } from './provider.js';\nimport { renderMarkdown } from './render/markdown.js';\nimport type { MermaidRenderOptions } from './render/mermaid.js';\n\nexport { MetadataLoadError } from './metadata/load.js';\nexport type { MermaidLayout, MermaidRenderOptions, MermaidTheme } from './render/mermaid.js';\n\n/** Options for the programmatic API. */\nexport interface GenerateMarkdownOptions {\n /** MikroORM configuration (driver, entities, dbName, …). */\n orm: Options;\n /** Title shown as the H1 heading in the generated document. */\n title?: string;\n /** Optional description paragraph rendered below the H1 heading. */\n description?: string;\n /**\n * Source globs/paths (`.ts`) to read JSDoc from. Use this when your entities\n * run from compiled JavaScript (`entities: ['./dist/**\\/*.js']`): build tools\n * strip comments, so descriptions and `@namespace`/`@hidden` tags would\n * otherwise be lost. Defaults to each entity's own discovered source file.\n */\n src?: string[];\n /** Receives non-fatal warnings (e.g. JSDoc cannot be read from compiled JS). */\n onWarn?: (message: string) => void;\n /**\n * Optional Mermaid rendering options. When provided, a YAML frontmatter block\n * is prepended to each erDiagram fence. Omit to preserve default viewer behavior.\n */\n mermaid?: MermaidRenderOptions;\n}\n\n/** File extensions produced by a TypeScript build, where comments are stripped. */\nconst COMPILED_JS = /\\.(c|m)?js$/i;\n\n/**\n * Decides which files JSDoc should be read from.\n *\n * When the caller provides `src`, those paths win. Otherwise we fall back to the\n * source files MikroORM discovered each entity from — and if those are compiled\n * JavaScript, JSDoc (descriptions, `@namespace`, and crucially `@hidden`) is\n * gone, so we warn the user and point them at `src`.\n */\nexport function resolveJsDocSources(\n sourcePaths: string[],\n src: string[] | undefined,\n onWarn?: (message: string) => void\n): string[] {\n if (src !== undefined && src.length > 0) {\n return src;\n }\n\n if (sourcePaths.some((p) => COMPILED_JS.test(p)) && onWarn) {\n onWarn(\n 'Entities were discovered from compiled JavaScript, so JSDoc descriptions ' +\n 'and @namespace/@hidden tags cannot be read (build tools strip comments). ' +\n 'Hidden entities may be exposed. Pass --src \"<glob to your .ts sources>\" ' +\n '(or the `src` option) to read JSDoc from the original TypeScript files.'\n );\n }\n\n return sourcePaths;\n}\n\nfunction assertExplicitJsDocSourceCoverage(\n metas: EntityMetadata[],\n jsDocResult: JsDocResult,\n src: string[],\n onWarn?: (message: string) => void\n): void {\n if (jsDocResult.sourceFileCount === 0) {\n throw new Error(\n `No source files matched the explicit src paths: ${src.join(', ')}\\n` +\n 'Check the --src glob/path (or the `src` option). Without matching TypeScript sources, ' +\n 'JSDoc tags such as @namespace and @hidden cannot be read.'\n );\n }\n\n const isRenderable = (meta: EntityMetadata): boolean => !meta.pivotTable && !meta.embeddable;\n\n const missingConcrete = metas\n .filter((meta) => isRenderable(meta) && !meta.abstract)\n .map((meta) => meta.className)\n .filter((className) => !jsDocResult.classNames.has(className));\n\n if (missingConcrete.length > 0) {\n throw new Error(\n `Explicit src paths did not include source declarations for discovered entities: ${missingConcrete.join(', ')}\\n` +\n 'Check that --src (or the `src` option) points at all TypeScript entity files. ' +\n 'JSDoc tags such as @namespace and @hidden for missing entities cannot be read.'\n );\n }\n\n // Abstract STI parents appear in the diagram but are often defined in a separate\n // base-class file that --src may not cover. Warn rather than error so the user\n // knows @hidden/@namespace won't apply to them.\n if (onWarn) {\n const missingAbstract = metas\n .filter((meta) => isRenderable(meta) && meta.abstract)\n .map((meta) => meta.className)\n .filter((className) => !jsDocResult.classNames.has(className));\n\n if (missingAbstract.length > 0) {\n onWarn(\n `Abstract STI parent entities were not found in the explicit src paths: ${missingAbstract.join(', ')}\\n` +\n '@hidden and @namespace tags for these entities will not be applied. ' +\n 'Include their source files in --src to enable JSDoc tags for them.'\n );\n }\n }\n}\n\nfunction errorMessages(err: unknown): string[] {\n const messages: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = err;\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n messages.push(current.message);\n current = (current as { cause?: unknown }).cause;\n }\n\n return messages;\n}\n\nfunction isMissingTsMorphSourceFile(err: unknown): boolean {\n return errorMessages(err).some((message) => message.includes('Source file') && message.includes('not found'));\n}\n\nasync function loadEntityMetadataWithTsMorphFallback(\n originalOrm: Options,\n effectiveOrm: Options\n): Promise<LoadedEntityMetadata> {\n try {\n return await loadEntityMetadata(effectiveOrm);\n } catch (err) {\n const wasAutoInjected = originalOrm.metadataProvider === undefined && effectiveOrm.metadataProvider !== undefined;\n if (!wasAutoInjected || !isMissingTsMorphSourceFile(err)) {\n throw err;\n }\n\n try {\n return await loadEntityMetadata(originalOrm);\n } catch {\n throw err;\n }\n }\n}\n\n/**\n * Generates a Mermaid ERD + markdown documentation document from MikroORM\n * entity metadata.\n *\n * JSDoc tags (@namespace, @erd, @describe, @hidden) and descriptions are\n * read directly from each entity's own source file — no separate path needs\n * to be specified. When entities run from compiled JavaScript (where comments\n * are stripped), pass `src` to read JSDoc from the original `.ts` files.\n *\n * @example\n * ```ts\n * import { generateMarkdown } from 'mikro-orm-markdown';\n * import ormConfig from './mikro-orm.config.js';\n *\n * const markdown = await generateMarkdown({\n * orm: ormConfig,\n * title: 'My Database',\n * });\n * ```\n */\nexport async function generateMarkdown(options: GenerateMarkdownOptions): Promise<string> {\n const { orm, title = 'Database Schema', description, src, onWarn, mermaid } = options;\n\n const effectiveOrm = await withTsMorphMetadataProvider(orm, onWarn);\n const { metas, sourcePaths } = await loadEntityMetadataWithTsMorphFallback(orm, effectiveOrm);\n const jsDocResult = loadJsDoc(resolveJsDocSources(sourcePaths, src, onWarn), onWarn);\n if (src !== undefined && src.length > 0) {\n assertExplicitJsDocSourceCoverage(metas, jsDocResult, src, onWarn);\n }\n const docModel = buildDocumentModel(metas, jsDocResult, title, description, onWarn);\n return renderMarkdown(docModel, mermaid);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ADV9D,aAAwB;AACxB,SAAoB;AACpB,IAAAA,QAAsB;AACtB,sBAA6C;AAE7C,uBAAwB;;;AENxB,sBAAwB;AA+CjB,SAAS,UAAU,WAAqB,QAAiD;AAC9F,QAAM,WAA2B,oBAAI,IAAI;AACzC,QAAM,QAAsB,oBAAI,IAAI;AACpC,QAAM,aAAa,oBAAI,IAAY;AAEnC,MAAI,UAAU,WAAW,GAAG;AAC1B,WAAO,EAAE,UAAU,OAAO,iBAAiB,GAAG,WAAW;AAAA,EAC3D;AAEA,QAAM,UAAU,IAAI,wBAAQ;AAAA,IAC1B,6BAA6B;AAAA,IAC7B,qBAAqB;AAAA,IACrB,iBAAiB;AAAA,MACf,wBAAwB;AAAA,MACxB,cAAc;AAAA,IAChB;AAAA,EACF,CAAC;AAKD,aAAW,YAAY,WAAW;AAChC,QAAI;AACF,YAAMC,eAAc,QAAQ,sBAAsB,QAAQ;AAC1D,UAAIA,aAAY,WAAW,KAAK,CAAC,eAAe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N,WAAO;AAAA,EACT;AACF;AAEA,IAAI,qBAAqB,GAAG;AAC1B,UAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAiB;AACvD,YAAQ,OAAO,MAAM,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC5E,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["path","sourceFiles","import_core","import_core","run"]}
1
+ {"version":3,"sources":["../src/cli.ts","../node_modules/tsup/assets/cjs_shims.js","../src/docs/jsdoc.ts","../src/metadata/load.ts","../src/model/build.ts","../src/model/diagram.ts","../src/provider.ts","../src/render/escape.ts","../src/render/mermaid.ts","../src/render/markdown.ts","../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport * as syncFs from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { Options } from '@mikro-orm/core';\nimport { Command, Option } from 'commander';\nimport { generateMarkdown } from './index.js';\nimport type { MermaidLayout, MermaidRenderOptions, MermaidTheme } from './render/mermaid.js';\nimport { MERMAID_LAYOUTS, MERMAID_THEMES } from './render/mermaid.js';\n\ninterface CliOptions {\n config: string;\n out: string;\n title: string;\n description?: string;\n tsconfig?: string;\n src?: string[];\n mermaidLayout?: MermaidLayout;\n mermaidTheme?: MermaidTheme;\n}\n\nexport interface LoadOrmOptionsOptions {\n keepTsxRegistered?: boolean;\n}\n\nlet activeTsxUnregister: (() => Promise<void>) | undefined;\n\nasync function unregisterActiveTsxLoader(): Promise<void> {\n const unregister = activeTsxUnregister;\n activeTsxUnregister = undefined;\n await unregister?.();\n}\n\nexport function toConfigImportSpecifier(configPath: string): string {\n return pathToFileURL(path.resolve(configPath)).href;\n}\n\n/**\n * Walks up from the directory of `fromPath` looking for the nearest\n * `tsconfig.json`. Returns its absolute path, or `undefined` if none is found\n * before reaching the filesystem root.\n *\n * This lets `.ts` config loading resolve the tsconfig relative to the config\n * file itself rather than the current working directory, so the CLI behaves\n * the same regardless of where it is invoked from.\n */\nexport function findNearestTsconfig(fromPath: string): string | undefined {\n let dir = path.dirname(path.resolve(fromPath));\n\n for (;;) {\n const candidate = path.join(dir, 'tsconfig.json');\n if (syncFs.existsSync(candidate)) {\n return candidate;\n }\n\n const parent = path.dirname(dir);\n if (parent === dir) {\n return undefined;\n }\n dir = parent;\n }\n}\n\n/**\n * Loads the MikroORM Options object from a config file.\n *\n * For `.ts` config files, registers the `tsx` loader at runtime so plain\n * `node` can import TypeScript — the user only needs `tsx` installed,\n * not a special invocation (`node --import tsx ...`).\n *\n * The tsconfig handed to `tsx` is resolved relative to the config file (or\n * given explicitly via `tsconfigPath`), not the current working directory.\n * Without this, `tsx` picks up whatever tsconfig sits above the cwd, which may\n * not apply `emitDecoratorMetadata` to the entity files — making discovery\n * fail with a cryptic `Cannot read properties of undefined` error depending on\n * which directory the CLI was launched from.\n */\nexport async function loadOrmOptions(\n configPath: string,\n tsconfigPath?: string,\n loadOptions: LoadOrmOptionsOptions = {}\n): Promise<Options> {\n const isTypeScriptConfig = configPath.endsWith('.ts');\n let unregisterTsx: (() => Promise<void>) | undefined;\n let shouldKeepTsxRegistered = false;\n\n try {\n if (isTypeScriptConfig) {\n await unregisterActiveTsxLoader();\n\n let register: typeof import('tsx/esm/api')['register'];\n try {\n ({ register } = await import('tsx/esm/api'));\n } catch {\n throw new Error('TypeScript config files require the \"tsx\" package.\\nInstall it with: npm install -D tsx');\n }\n\n let tsconfig: string | undefined;\n if (tsconfigPath !== undefined) {\n tsconfig = path.resolve(tsconfigPath);\n if (!syncFs.existsSync(tsconfig)) {\n throw new Error(`--tsconfig file not found: ${tsconfig}`);\n }\n } else {\n tsconfig = findNearestTsconfig(configPath);\n }\n\n unregisterTsx = register(tsconfig !== undefined ? { tsconfig } : {});\n }\n\n const configUrl = toConfigImportSpecifier(configPath);\n let mod: { default?: unknown };\n try {\n mod = (await import(/* @vite-ignore */ configUrl)) as { default?: unknown };\n } catch (cause) {\n if (isTypeScriptConfig) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `Failed to load TypeScript config.\\n${detail}\\n\\n` +\n 'If this looks like a decorator/metadata error, the tsconfig applied to your ' +\n 'entity files is likely missing \"experimentalDecorators\" / \"emitDecoratorMetadata\".\\n' +\n 'Make sure a tsconfig.json with those options sits next to your config file, ' +\n 'or pass one explicitly with --tsconfig <path>.',\n { cause }\n );\n }\n throw cause;\n }\n\n if (mod.default === undefined) {\n throw new Error('Config file must use a default export, e.g. `export default defineConfig({ ... })`.');\n }\n\n const config = mod.default;\n if (typeof config === 'function' || config instanceof Promise) {\n throw new Error(\n 'Config file default export must be a configuration object, not a function or Promise.\\n' +\n 'Resolve it first, or use the programmatic API instead (see README).'\n );\n }\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n throw new Error(\n 'Config file default export must be a configuration object, not a primitive value or array.\\n' +\n 'Export a plain MikroORM options object instead.'\n );\n }\n\n const options = config as Options;\n const withPreferTs =\n isTypeScriptConfig && options.preferTs === undefined ? { ...options, preferTs: true } : options;\n shouldKeepTsxRegistered = loadOptions.keepTsxRegistered === true;\n\n return withPreferTs;\n } finally {\n if (unregisterTsx !== undefined) {\n if (shouldKeepTsxRegistered) {\n activeTsxUnregister = unregisterTsx;\n } else {\n await unregisterTsx();\n }\n }\n }\n}\n\n/**\n * Renders an error together with its `cause` chain, one cause per line.\n *\n * Discovery failures wrap the real MikroORM error (missing driver, bad entities\n * glob, …) in `error.cause`. Printing only the top-level message hides the one\n * piece of information that actually tells the user what went wrong, so we walk\n * the chain and surface each underlying message.\n */\nexport function formatErrorChain(err: unknown): string {\n const lines: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = err;\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n lines.push(current.message);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A non-Error cause at the end of the chain still carries information.\n if (current !== undefined && !(current instanceof Error)) {\n lines.push(String(current));\n }\n\n return lines.map((line, i) => (i === 0 ? line : ` ↳ caused by: ${line}`)).join('\\n');\n}\n\nconst REFLECTION_METADATA_HINT =\n '\\n\\nNote: this tool loads configs via tsx (esbuild), which does not emit ' +\n \"'emitDecoratorMetadata' reflection data, so enabling it will not help here.\\n\" +\n \"Either give each entity property an explicit 'type:'/'entity:' attribute, or \" +\n \"install '@mikro-orm/reflection' — this tool then reads types from your TypeScript sources automatically.\";\n\n/**\n * Formats a discovery error, appending a CLI-specific hint when the failure is\n * MikroORM's reflection-based type resolution.\n *\n * MikroORM's default `ReflectMetadataProvider` infers property types from\n * `emitDecoratorMetadata` reflection and, when it is missing, tells the user to\n * enable that tsconfig option. But the CLI loads `.ts` configs through `tsx`\n * (esbuild), which never emits that metadata — so the advice cannot help. We\n * detect that message in the cause chain and point at the options that do work.\n */\nexport function formatDiscoveryError(err: unknown): string {\n const chain = formatErrorChain(err);\n return chain.includes('emitDecoratorMetadata') ? chain + REFLECTION_METADATA_HINT : chain;\n}\n\nfunction formatFileSystemError(cause: unknown): string {\n if (cause instanceof Error) {\n const code = 'code' in cause && typeof cause.code === 'string' ? ` (${cause.code})` : '';\n return `${cause.message}${code}`;\n }\n\n return String(cause);\n}\n\nexport async function writeMarkdownFile(outPath: string, markdown: string): Promise<void> {\n try {\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, markdown, 'utf-8');\n } catch (cause) {\n throw new Error(`Cannot write output file: ${outPath}\\n${formatFileSystemError(cause)}`, { cause });\n }\n}\n\nfunction parseMermaidOptions(opts: CliOptions): MermaidRenderOptions | undefined {\n const { mermaidLayout, mermaidTheme } = opts;\n\n if (mermaidLayout === undefined && mermaidTheme === undefined) {\n return undefined;\n }\n\n return {\n ...(mermaidLayout !== undefined && { layout: mermaidLayout }),\n ...(mermaidTheme !== undefined && { theme: mermaidTheme }),\n };\n}\n\nasync function run(opts: CliOptions): Promise<void> {\n const configPath = path.resolve(opts.config);\n const outPath = path.resolve(opts.out);\n const mermaid = parseMermaidOptions(opts);\n\n let ormOptions: Options;\n try {\n ormOptions = await loadOrmOptions(configPath, opts.tsconfig, { keepTsxRegistered: true });\n } catch (err) {\n process.stderr.write(\n `Error: Cannot load config: ${configPath}\\n${err instanceof Error ? err.message : String(err)}\\n`\n );\n process.exit(1);\n }\n\n let markdown: string;\n try {\n markdown = await generateMarkdown({\n orm: ormOptions,\n title: opts.title,\n ...(opts.description !== undefined && { description: opts.description }),\n ...(opts.src !== undefined && { src: opts.src }),\n ...(mermaid !== undefined && { mermaid }),\n onWarn: (message: string): void => void process.stderr.write(`Warning: ${message}\\n`),\n });\n } catch (err) {\n await unregisterActiveTsxLoader();\n process.stderr.write(`Error: ${formatDiscoveryError(err)}\\n`);\n process.exit(1);\n }\n\n await unregisterActiveTsxLoader();\n\n try {\n await writeMarkdownFile(outPath, markdown);\n } catch (err) {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n }\n\n process.stdout.write(`✓ Written to ${path.relative(process.cwd(), outPath)}\\n`);\n}\n\nconst program = new Command()\n .name('mikro-orm-markdown')\n .description('Generate Mermaid ERD + markdown docs from MikroORM entities')\n .requiredOption('-c, --config <path>', 'MikroORM config file path')\n .option('-o, --out <path>', 'Output markdown file path', './ERD.md')\n .option('-t, --title <string>', 'Document title', 'Database Schema')\n .option('-d, --description <string>', 'Optional description paragraph shown below the title')\n .option(\n '--tsconfig <path>',\n 'tsconfig.json to use when loading a .ts config (defaults to the nearest one beside the config file)'\n )\n .option(\n '--src <paths...>',\n 'Source .ts file globs to read JSDoc from when entities run from compiled .js (comments are stripped at build time)'\n )\n .addOption(\n new Option(\n '--mermaid-layout <layout>',\n `Mermaid layout engine injected as frontmatter (${MERMAID_LAYOUTS.join('|')})`\n ).choices(MERMAID_LAYOUTS)\n )\n .addOption(\n new Option(\n '--mermaid-theme <theme>',\n `Mermaid theme injected as frontmatter (${MERMAID_THEMES.join('|')})`\n ).choices(MERMAID_THEMES)\n )\n .action(run);\n\nfunction isDirectCliExecution(): boolean {\n const entryPoint = process.argv[1];\n\n if (entryPoint === undefined) {\n return false;\n }\n\n try {\n return syncFs.realpathSync(path.resolve(entryPoint)) === syncFs.realpathSync(fileURLToPath(import.meta.url));\n } catch {\n return false;\n }\n}\n\nif (isDirectCliExecution()) {\n program.parseAsync(process.argv).catch((err: unknown) => {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n });\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import type { ClassDeclaration, JSDoc as MorphJsDoc, ParameterDeclaration } from 'ts-morph';\nimport { Project, ts } from 'ts-morph';\n\n/** JSDoc information extracted from an entity class. */\nexport interface EntityJsDocInfo {\n /** Class-level description (text before any @tags). */\n description?: string;\n /** Namespaces from @namespace tags — appears in both ERD and text table. */\n namespaces: string[];\n /** Namespaces from @erd tags — appears in ERD only. */\n erdNamespaces: string[];\n /** Namespaces from @describe tags — appears in text table only. */\n describeNamespaces: string[];\n /** True when @hidden tag is present — entity is excluded from all output. */\n hidden: boolean;\n}\n\n/** JSDoc information extracted from a single entity property. */\nexport interface PropJsDocInfo {\n /** Property description text. */\n description?: string;\n /** True when the @atLeastOne tag is present — a collection relation that must hold ≥1 elements. */\n atLeastOne: boolean;\n}\n\n/** Keyed by entity class name. */\nexport type EntityJsDocMap = Map<string, EntityJsDocInfo>;\n\n/** Outer key: entity class name. Inner key: property name. */\nexport type PropJsDocMap = Map<string, Map<string, PropJsDocInfo>>;\n\nexport interface JsDocResult {\n entities: EntityJsDocMap;\n props: PropJsDocMap;\n /** Number of TypeScript source files matched and loaded for JSDoc parsing. */\n sourceFileCount: number;\n /** Class declarations found in the loaded source files, including classes without JSDoc. */\n classNames: Set<string>;\n}\n\n/**\n * Parses the given TypeScript source files and extracts JSDoc descriptions\n * and custom tags (@namespace, @erd, @describe, @hidden) from entity classes\n * and their properties.\n *\n * Returns empty maps if no source files are given or no JSDoc is found.\n * Never throws — errors are reported through onWarn so missing docs don't block generation.\n */\nexport function loadJsDoc(filePaths: string[], onWarn?: (message: string) => void): JsDocResult {\n const entities: EntityJsDocMap = new Map();\n const props: PropJsDocMap = new Map();\n const classNames = new Set<string>();\n\n if (filePaths.length === 0) {\n return { entities, props, sourceFileCount: 0, classNames };\n }\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n skipLoadingLibFiles: true,\n compilerOptions: {\n experimentalDecorators: true,\n skipLibCheck: true,\n },\n });\n\n // Add each path independently so one unreadable file or bad glob (EACCES, a\n // directory, etc.) cannot abort the whole run — missing docs must never block\n // generation (the \"never throws\" contract).\n for (const filePath of filePaths) {\n try {\n const sourceFiles = project.addSourceFilesAtPaths(filePath);\n if (sourceFiles.length === 0 && !hasGlobPattern(filePath)) {\n onWarn?.(`No JSDoc source file matched path: ${filePath}`);\n }\n } catch (err) {\n onWarn?.(`Could not load JSDoc source path \"${filePath}\": ${formatUnknownError(err)}`);\n }\n }\n\n const sourceFiles = project.getSourceFiles();\n for (const sourceFile of sourceFiles) {\n try {\n for (const cls of sourceFile.getClasses()) {\n const className = cls.getName();\n if (!className) {\n continue;\n }\n classNames.add(className);\n\n const classDocs = cls.getJsDocs();\n if (classDocs.length > 0) {\n entities.set(className, parseEntityJsDoc(classDocs));\n }\n\n const propMap = collectPropJsDocs(cls);\n if (propMap.size > 0) {\n props.set(className, propMap);\n }\n }\n } catch (err) {\n onWarn?.(`Could not parse JSDoc source file \"${sourceFile.getFilePath()}\": ${formatUnknownError(err)}`);\n }\n }\n\n return { entities, props, sourceFileCount: sourceFiles.length, classNames };\n}\n\nfunction formatUnknownError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction hasGlobPattern(filePath: string): boolean {\n return /[*?[\\]{}]/.test(filePath);\n}\n\nfunction collectPropJsDocs(cls: ClassDeclaration): Map<string, PropJsDocInfo> {\n const propMap = new Map<string, PropJsDocInfo>();\n\n for (const prop of [...cls.getProperties(), ...cls.getGetAccessors()]) {\n const info = parsePropJsDoc(prop.getJsDocs());\n addPropInfo(propMap, prop.getName(), info);\n }\n\n for (const prop of getConstructorParameterProperties(cls)) {\n const info = parseCompilerPropJsDoc(ts.getJSDocCommentsAndTags(prop.compilerNode));\n addPropInfo(propMap, prop.getName(), info);\n }\n\n return propMap;\n}\n\nfunction getConstructorParameterProperties(cls: ClassDeclaration): ParameterDeclaration[] {\n return cls\n .getConstructors()\n .flatMap((constructorDeclaration) =>\n constructorDeclaration.getParameters().filter((param) => param.isParameterProperty())\n );\n}\n\nfunction addPropInfo(propMap: Map<string, PropJsDocInfo>, propName: string, info: PropJsDocInfo): void {\n if (info.description !== undefined || info.atLeastOne) {\n propMap.set(propName, info);\n }\n}\n\nfunction parseEntityJsDoc(jsDocs: MorphJsDoc[]): EntityJsDocInfo {\n const namespaces: string[] = [];\n const erdNamespaces: string[] = [];\n const describeNamespaces: string[] = [];\n let hidden = false;\n let description: string | undefined;\n\n for (const doc of jsDocs) {\n const desc = doc.getDescription().trim();\n if (desc && description === undefined) {\n description = desc;\n }\n\n for (const tag of doc.getTags()) {\n const tagName = tag.getTagName();\n const comment = tag.getCommentText()?.trim();\n\n if (tagName === 'namespace' && comment) {\n namespaces.push(comment);\n } else if (tagName === 'erd' && comment) {\n erdNamespaces.push(comment);\n } else if (tagName === 'describe' && comment) {\n describeNamespaces.push(comment);\n } else if (tagName === 'hidden') {\n hidden = true;\n }\n }\n }\n\n return {\n ...(description !== undefined && { description }),\n namespaces,\n erdNamespaces,\n describeNamespaces,\n hidden,\n };\n}\n\nfunction parsePropJsDoc(jsDocs: MorphJsDoc[]): PropJsDocInfo {\n let description: string | undefined;\n let atLeastOne = false;\n\n for (const doc of jsDocs) {\n const desc = doc.getDescription().trim();\n if (desc && description === undefined) {\n description = desc;\n }\n for (const tag of doc.getTags()) {\n if (tag.getTagName() === 'atLeastOne') {\n atLeastOne = true;\n }\n }\n }\n\n return { ...(description !== undefined && { description }), atLeastOne };\n}\n\nfunction parseCompilerPropJsDoc(jsDocs: readonly (ts.JSDoc | ts.JSDocTag)[]): PropJsDocInfo {\n let description: string | undefined;\n let atLeastOne = false;\n\n for (const doc of jsDocs) {\n if (ts.isJSDoc(doc)) {\n const desc = formatCompilerJsDocComment(doc.comment);\n if (desc && description === undefined) {\n description = desc;\n }\n for (const tag of doc.tags ?? []) {\n if (tag.tagName.getText() === 'atLeastOne') {\n atLeastOne = true;\n }\n }\n continue;\n }\n\n if (doc.tagName.getText() === 'atLeastOne') {\n atLeastOne = true;\n }\n }\n\n return { ...(description !== undefined && { description }), atLeastOne };\n}\n\nfunction formatCompilerJsDocComment(comment: ts.JSDoc['comment'] | ts.JSDocTag['comment']): string | undefined {\n if (comment === undefined) {\n return undefined;\n }\n const trimmed = ts.getTextOfJSDocComment(comment)?.trim();\n return trimmed === undefined || trimmed === '' ? undefined : trimmed;\n}\n","import * as path from 'node:path';\nimport type { EntityClass, EntityMetadata, Options } from '@mikro-orm/core';\nimport { EntitySchema, MetadataStorage, MikroORM } from '@mikro-orm/core';\n\n/** Errors thrown during metadata loading */\nexport class MetadataLoadError extends Error {\n constructor(\n message: string,\n public override readonly cause?: unknown\n ) {\n super(message);\n this.name = 'MetadataLoadError';\n }\n}\n\nexport interface LoadedEntityMetadata {\n metas: EntityMetadata[];\n /** Absolute paths to the source files each entity class was declared in, deduped. */\n sourcePaths: string[];\n}\n\nasync function closeDiscoveryResources(orm: MikroORM): Promise<void> {\n // With connect=false, orm.close() can instantiate SQL clients just to close them.\n await orm.config.getMetadataCacheAdapter()?.close?.();\n await orm.config.getResultCacheAdapter()?.close?.();\n}\n\nfunction collectEntitySchemaNames(options: Options): string[] {\n const configuredEntities = [...(options.entities ?? []), ...(options.entitiesTs ?? [])];\n const names: string[] = [];\n\n for (const entity of configuredEntities) {\n if (entity instanceof EntitySchema) {\n names.push(entity.meta.className);\n continue;\n }\n\n if (entity !== null && typeof entity === 'object' && 'schema' in entity && entity.schema instanceof EntitySchema) {\n names.push(entity.schema.meta.className);\n }\n }\n\n return names;\n}\n\nfunction assertNoEntitySchemaEntities(options: Options): void {\n const schemaNames = collectEntitySchemaNames(options);\n if (schemaNames.length === 0) {\n return;\n }\n\n throw new MetadataLoadError(\n `EntitySchema-defined entities are not currently supported: ${schemaNames.join(', ')}.\\n` +\n 'Use decorator-based @Entity() classes instead.'\n );\n}\n\n/**\n * True when `target` was ever passed through a MikroORM property/class decorator\n * (@Entity, @Property, @PrimaryKey, ...). Every such decorator calls\n * `MetadataStorage.getMetadataFromDecorator`, which stamps a marker onto the\n * class the first time it runs — used here to catch EntitySchema entities that\n * were never decorated at all (see assertDiscoveredEntitiesAreSupported).\n *\n * The marker's name changed between MikroORM versions (verified by diffing\n * @mikro-orm/core release tarballs from npm): `__path` up to 6.2.8, then a\n * `MetadataStorage.PATH_SYMBOL`-keyed property from 6.2.9 onward. Both are\n * checked so this works across the whole >=6.0.0 peer range.\n */\nfunction hasDecoratorMarker(target: EntityClass<unknown>): boolean {\n const pathSymbol = MetadataStorage.PATH_SYMBOL;\n if (typeof pathSymbol === 'symbol' && pathSymbol in target) {\n return true;\n }\n return '__path' in target;\n}\n\n/** Entities collectEntitySchemaNames's pre-discovery scan cannot reason about: pivot tables and embeddables are not user-facing entities. */\nfunction isRenderableMeta(meta: EntityMetadata): boolean {\n return !meta.pivotTable && !meta.embeddable;\n}\n\n/**\n * Catches EntitySchema entities that assertNoEntitySchemaEntities cannot see:\n * ones discovered via a glob/folder pattern (`entities: ['./src/**\\/*.ts']`)\n * rather than listed directly in the config array. MikroORM only reveals the\n * actual EntitySchema instance by dynamically importing the matched files\n * during discovery — after the pre-discovery guard has already run — so this\n * must run on the discovered EntityMetadata[] instead.\n *\n * Two signals, in order of confidence:\n *\n * 1. `EntitySchema.REGISTRY` — definitive proof. A class-linked EntitySchema\n * (`new EntitySchema({ class: Book, ... })`) registers `Book` here; internal\n * per-discovery copies MikroORM makes for decorator-based entities are\n * marked `internal: true` and are never registered. No false positives are\n * structurally possible.\n * 2. Decorator marker absence — an inference, not proof. A name-only\n * EntitySchema (`new EntitySchema({ name: 'Publisher', ... })`, no `class:`\n * link) is never registered in (1) either, since there is no user class to\n * register against. The only signal left is that it never went through a\n * decorator. If some future MikroORM release changes the marker mechanism\n * again (it has happened once before, at 6.2.9), a validly decorated entity\n * could look \"markerless\" too — so this case still throws (the project's\n * policy is to reject EntitySchema outright, not just warn), but with a\n * softer message that invites a bug report instead of asserting certainty.\n */\nfunction assertDiscoveredEntitiesAreSupported(metas: EntityMetadata[]): void {\n const confirmed: string[] = [];\n const unconfirmed: string[] = [];\n\n for (const meta of metas) {\n if (!isRenderableMeta(meta)) {\n continue;\n }\n if (EntitySchema.REGISTRY.has(meta.class)) {\n confirmed.push(meta.className);\n } else if (!hasDecoratorMarker(meta.class)) {\n unconfirmed.push(meta.className);\n }\n }\n\n if (confirmed.length === 0 && unconfirmed.length === 0) {\n return;\n }\n\n const lines: string[] = [];\n if (confirmed.length > 0) {\n lines.push(`EntitySchema-defined entities are not currently supported: ${confirmed.join(', ')}.`);\n }\n if (unconfirmed.length > 0) {\n lines.push(\n `Could not confirm these entities are decorator-based @Entity() classes: ${unconfirmed.join(', ')}. ` +\n 'This usually means they are EntitySchema-defined entities (also not currently supported). ' +\n \"If you're certain these are valid @Entity() classes, this may be a detection false positive in \" +\n 'mikro-orm-markdown — please open an issue: https://github.com/iamkanguk97/mikro-orm-markdown/issues'\n );\n }\n lines.push('Use decorator-based @Entity() classes instead.');\n\n throw new MetadataLoadError(lines.join('\\n'));\n}\n\n/**\n * Runs MikroORM entity discovery without connecting to the database,\n * and returns all discovered EntityMetadata objects along with the\n * absolute source file paths they were declared in (for JSDoc extraction).\n *\n * The caller is responsible for filtering (e.g. excluding abstract,\n * embeddable, or pivot entities) based on rendering needs.\n */\nexport async function loadEntityMetadata(options: Options): Promise<LoadedEntityMetadata> {\n assertNoEntitySchemaEntities(options);\n\n let orm: MikroORM;\n try {\n orm = await MikroORM.init({\n ...options,\n debug: false,\n connect: false,\n // Always disable the metadata cache for one-shot doc runs so the project\n // is never littered with a temp/ folder, regardless of how metadataProvider\n // was configured.\n metadataCache: { ...options.metadataCache, enabled: false },\n });\n } catch (cause) {\n throw new MetadataLoadError(\n 'Failed to initialize MikroORM and run entity discovery. ' +\n 'Make sure your config is valid and all entity files are accessible.',\n cause\n );\n }\n\n try {\n const all = Object.values(orm.getMetadata().getAll());\n\n if (all.length === 0) {\n throw new MetadataLoadError(\n 'No entities were discovered. ' + 'Check that your config specifies at least one entity path or class.'\n );\n }\n\n assertDiscoveredEntitiesAreSupported(all);\n\n const baseDir = orm.config.get('baseDir');\n const sourcePaths = [...new Set(all.filter((m) => m.path).map((m) => path.resolve(baseDir, m.path)))];\n\n return { metas: all, sourcePaths };\n } finally {\n await closeDiscoveryResources(orm);\n }\n}\n","import { type EntityMetadata, ReferenceKind } from '@mikro-orm/core';\nimport type { EntityJsDocInfo, JsDocResult, PropJsDocInfo, PropJsDocMap } from '../docs/jsdoc.js';\nimport { buildDiagramModel } from './diagram.js';\nimport type { ColumnModel, EntityModel, RelationEdge } from './types.js';\n\n// Mermaid cardinality tokens upgrading the \"many\" side from zero-or-more to one-or-more.\nconst FROM_ONE_OR_MORE = '}|';\nconst TO_ONE_OR_MORE = '|{';\n\n/** An entity with its structural model and JSDoc info merged together. */\nexport interface EnrichedEntity {\n model: EntityModel;\n /** Undefined if the entity has no class-level JSDoc. */\n jsDoc: EntityJsDocInfo | undefined;\n /** Per-property description map (empty map if no property JSDoc). */\n propDocs: Map<string, PropJsDocInfo>;\n}\n\n/**\n * A single namespace group, ready to render as one section of the document.\n *\n * - `erdEntities`: shown in the Mermaid ERD block (@namespace + @erd)\n * - `textEntities`: shown in the column-table sections (@namespace + @describe)\n * - `erdRelations`: relation edges where both endpoints are in `erdEntities`\n */\nexport interface NamespaceGroup {\n name: string;\n erdEntities: EnrichedEntity[];\n textEntities: EnrichedEntity[];\n erdRelations: RelationEdge[];\n}\n\n/** Complete document model — input to the markdown renderer. */\nexport interface DocumentModel {\n title: string;\n /** Optional paragraph rendered below the H1 heading. */\n description?: string;\n groups: NamespaceGroup[];\n}\n\n/**\n * Merges MikroORM structural metadata with JSDoc information and organises the\n * result into namespace groups for rendering.\n *\n * Entities with @hidden are excluded.\n * Entities with no namespace tags fall into the \"default\" group.\n * Groups are ordered alphabetically, with \"default\" always last.\n */\nexport function buildDocumentModel(\n metas: EntityMetadata[],\n jsDocResult: JsDocResult,\n title: string,\n description?: string,\n onWarn?: (message: string) => void\n): DocumentModel {\n const { entities: diagramEntities, relations } = buildDiagramModel(metas);\n const allRelations = applyAtLeastOne(relations, metas, jsDocResult.props, onWarn);\n\n // Classes excluded via @hidden — FK columns pointing at them would otherwise\n // dangle (their edge is dropped, but the column would still reference a target\n // that no longer appears anywhere).\n const hiddenClasses = new Set<string>();\n for (const model of diagramEntities) {\n if (jsDocResult.entities.get(model.className)?.hidden) {\n hiddenClasses.add(model.className);\n }\n }\n\n // Build enriched entity map, filtering out @hidden entities.\n const enrichedByClass = new Map<string, EnrichedEntity>();\n for (const model of diagramEntities) {\n const jsDoc = jsDocResult.entities.get(model.className);\n if (jsDoc?.hidden) {\n continue;\n }\n const columns = model.columns.filter(\n (col) => !(col.isForeignKey && col.referencedEntity !== undefined && hiddenClasses.has(col.referencedEntity))\n );\n const visibleModel = removeHiddenEntityReferences(\n columns.length === model.columns.length ? model : { ...model, columns },\n hiddenClasses\n );\n const ownPropDocs = jsDocResult.props.get(model.className) ?? new Map<string, PropJsDocInfo>();\n const propDocs = withEmbeddedPropDocs(ownPropDocs, visibleModel.columns, jsDocResult.props);\n enrichedByClass.set(model.className, { model: visibleModel, jsDoc, propDocs });\n }\n\n // Collect all unique namespace names referenced by any entity.\n const groupNames = new Set<string>();\n let anyUntagged = false;\n for (const { jsDoc } of enrichedByClass.values()) {\n const allNs = [...(jsDoc?.namespaces ?? []), ...(jsDoc?.erdNamespaces ?? []), ...(jsDoc?.describeNamespaces ?? [])];\n if (allNs.length === 0) {\n anyUntagged = true;\n } else {\n for (const ns of allNs) {\n groupNames.add(ns);\n }\n }\n }\n if (anyUntagged) {\n groupNames.add('default');\n }\n\n const groups: NamespaceGroup[] = [];\n for (const groupName of groupNames) {\n const isDefault = groupName === 'default';\n\n const erdEntities = [...enrichedByClass.values()]\n .filter(({ jsDoc }) => belongsToGroupForErd(jsDoc, groupName, isDefault))\n .map((entity): EnrichedEntity | null => {\n if (isCrossNamespaceInGroup(entity.jsDoc, groupName, isDefault)) {\n const pkColumns = entity.model.columns.filter((col) => col.isPrimary);\n // If no PK columns remain (e.g. FK-as-PK to a @hidden entity was filtered out),\n // exclude the entity entirely: an empty box with dangling arrows is misleading.\n if (pkColumns.length === 0) {\n return null;\n }\n return { ...entity, model: { ...entity.model, columns: pkColumns } };\n }\n return entity;\n })\n .filter((entity): entity is EnrichedEntity => entity !== null);\n\n const textEntities = [...enrichedByClass.values()].filter(({ jsDoc }) =>\n belongsToGroupForText(jsDoc, groupName, isDefault)\n );\n\n const erdClassNames = new Set(erdEntities.map((e) => e.model.className));\n const erdRelations = allRelations.filter((r) => erdClassNames.has(r.fromEntity) && erdClassNames.has(r.toEntity));\n\n groups.push({ name: groupName, erdEntities, textEntities, erdRelations });\n }\n\n // Sort alphabetically; \"default\" is always last.\n groups.sort((a, b) => {\n if (a.name === 'default') {\n return 1;\n }\n if (b.name === 'default') {\n return -1;\n }\n return a.name.localeCompare(b.name);\n });\n\n return { title, groups, ...(description !== undefined && { description }) };\n}\n\nfunction removeHiddenEntityReferences(model: EntityModel, hiddenClasses: Set<string>): EntityModel {\n if (model.extendsEntity === undefined || !hiddenClasses.has(model.extendsEntity)) {\n return model;\n }\n\n const visibleModel = { ...model };\n delete visibleModel.extendsEntity;\n return visibleModel;\n}\n\n/**\n * Falls back to the @Embeddable class's own JSDoc for flattened embedded columns\n * (e.g. Customer's \"address_street\" picks up Address.street's JSDoc), since the\n * owning entity's source file never declares that synthetic property name.\n * Returns a new map; the input map is not mutated.\n */\nfunction withEmbeddedPropDocs(\n ownPropDocs: Map<string, PropJsDocInfo>,\n columns: ColumnModel[],\n allPropDocs: PropJsDocMap\n): Map<string, PropJsDocInfo> {\n const merged = new Map(ownPropDocs);\n for (const col of columns) {\n if (merged.has(col.propName) || col.embeddedIn === undefined || col.embeddedPropName === undefined) {\n continue;\n }\n const info = allPropDocs.get(col.embeddedIn)?.get(col.embeddedPropName);\n if (info) {\n merged.set(col.propName, info);\n }\n }\n return merged;\n}\n\n/**\n * Upgrades the \"many\" side of a relation edge to one-or-more for collection\n * properties tagged with @atLeastOne. The edge is always built from the owning\n * side, so a collection on the inverse side is matched back via its mappedBy.\n * Returns a new array; input edges are not mutated.\n */\nfunction applyAtLeastOne(\n relations: RelationEdge[],\n metas: EntityMetadata[],\n props: PropJsDocMap,\n onWarn?: (message: string) => void\n): RelationEdge[] {\n const adjusted = relations.map((edge) => ({ ...edge }));\n const metaByClass = new Map(metas.map((m) => [m.className, m]));\n\n for (const [className, propMap] of props) {\n const meta = metaByClass.get(className);\n if (!meta) {\n continue;\n }\n for (const [propName, info] of propMap) {\n if (!info.atLeastOne) {\n continue;\n }\n const prop = meta.properties[propName];\n if (!prop) {\n continue;\n }\n\n let edge: RelationEdge | undefined;\n // 1:N collection — the edge comes from the m:1 owning side; bump its \"many\" (from) side.\n if (prop.kind === ReferenceKind.ONE_TO_MANY && prop.mappedBy) {\n edge = adjusted.find(\n (e) => e.fromEntity === prop.type && e.toEntity === className && e.label === prop.mappedBy\n );\n if (edge) {\n edge.fromCardinality = FROM_ONE_OR_MORE;\n }\n }\n // M:N owning collection — edge built from this prop; the other (to) side becomes one-or-more.\n else if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner === true) {\n edge = adjusted.find((e) => e.fromEntity === className && e.toEntity === prop.type && e.label === propName);\n if (edge) {\n edge.toCardinality = TO_ONE_OR_MORE;\n }\n }\n // M:N inverse collection — edge built from the owner; this (from) side becomes one-or-more.\n else if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.mappedBy) {\n edge = adjusted.find(\n (e) => e.fromEntity === prop.type && e.toEntity === className && e.label === prop.mappedBy\n );\n if (edge) {\n edge.fromCardinality = FROM_ONE_OR_MORE;\n }\n }\n\n // No matching edge: a unidirectional @OneToMany (no mappedBy) or a label\n // mismatch leaves the cardinality unchanged. Warn instead of failing silently.\n if (!edge) {\n onWarn?.(\n `@atLeastOne on ${className}.${propName} had no effect: no matching relation edge was found. ` +\n 'It applies only to collection relations that can be matched to a rendered edge: ' +\n '@OneToMany with mappedBy, or @ManyToMany on either the owning side or an inverse mappedBy side.'\n );\n }\n }\n }\n\n return adjusted;\n}\n\nfunction hasNoNamespaceTags(jsDoc: EntityJsDocInfo | undefined): boolean {\n if (!jsDoc) {\n return true;\n }\n return jsDoc.namespaces.length === 0 && jsDoc.erdNamespaces.length === 0 && jsDoc.describeNamespaces.length === 0;\n}\n\nfunction belongsToGroupForErd(jsDoc: EntityJsDocInfo | undefined, groupName: string, isDefault: boolean): boolean {\n if (isDefault) {\n return hasNoNamespaceTags(jsDoc);\n }\n if (!jsDoc) {\n return false;\n }\n return jsDoc.namespaces.includes(groupName) || jsDoc.erdNamespaces.includes(groupName);\n}\n\nfunction belongsToGroupForText(jsDoc: EntityJsDocInfo | undefined, groupName: string, isDefault: boolean): boolean {\n if (isDefault) {\n return hasNoNamespaceTags(jsDoc);\n }\n if (!jsDoc) {\n return false;\n }\n return jsDoc.namespaces.includes(groupName) || jsDoc.describeNamespaces.includes(groupName);\n}\n\n/**\n * Returns true when an entity appears in a group's ERD only via @erd while its\n * home section is another namespace. Entities with only @erd tags have no text\n * home section, so their ERD section renders the full model.\n */\nfunction isCrossNamespaceInGroup(jsDoc: EntityJsDocInfo | undefined, groupName: string, isDefault: boolean): boolean {\n if (isDefault || !jsDoc) {\n return false;\n }\n const hasHomeNamespace = jsDoc.namespaces.length > 0 || jsDoc.describeNamespaces.length > 0;\n return (\n hasHomeNamespace &&\n jsDoc.erdNamespaces.includes(groupName) &&\n !jsDoc.namespaces.includes(groupName) &&\n !jsDoc.describeNamespaces.includes(groupName)\n );\n}\n","import type { EntityMetadata, EntityProperty, FormulaTable } from '@mikro-orm/core';\nimport { ReferenceKind } from '@mikro-orm/core';\nimport type { ColumnModel, ConstraintModel, DiagramModel, EntityModel, RelationEdge } from './types.js';\n\n// Dummy table descriptor used when resolving formula expressions for documentation.\n// String-based formulas ignore both arguments; function-based formulas use the alias.\nconst FORMULA_DUMMY_TABLE: FormulaTable = {\n alias: 'e0',\n name: '',\n qualifiedName: '',\n toString: () => 'e0',\n};\n\nconst UNRESOLVED_FORMULA = '<unresolved>';\n\n/**\n * Converts raw MikroORM EntityMetadata array into a DiagramModel.\n *\n * Excluded from entity boxes:\n * - Pivot tables (auto-generated M:N join tables) — represented as edges\n * - @Embeddable classes — their columns appear inline inside the owning entity\n */\nexport function buildDiagramModel(metas: EntityMetadata[]): DiagramModel {\n const metaByClass = new Map(metas.map((m) => [m.className, m]));\n\n const entities: EntityModel[] = metas\n .filter((meta) => !meta.pivotTable && !meta.embeddable)\n .map((meta) => buildEntityModel(meta, metaByClass));\n\n const relations: RelationEdge[] = buildRelationEdges(metas);\n\n return { entities, relations };\n}\n\nfunction buildEntityModel(meta: EntityMetadata, metaByClass: Map<string, EntityMetadata>): EntityModel {\n // STI root: defines the discriminatorColumn and does not itself extend a parent.\n // A *non-abstract* root is also assigned its own discriminatorValue by MikroORM,\n // so we must not key off the absence of discriminatorValue here — that would\n // misclassify non-abstract roots and leak every subclass column into them.\n // The root's properties list includes all child-only columns (inherited=true) — filter them out.\n const isStiRoot = meta.discriminatorColumn !== undefined && !meta.extends;\n const isStiChild = Boolean(meta.extends) && meta.discriminatorValue !== undefined;\n\n const columns: ColumnModel[] = [];\n for (const prop of Object.values(meta.properties)) {\n if (isStiRoot && prop.inherited === true) {\n continue;\n }\n columns.push(...buildColumns(prop, metaByClass, meta));\n }\n\n return {\n className: meta.className,\n tableName: meta.tableName,\n columns,\n isPivot: false,\n isEmbeddable: meta.embeddable === true,\n ...(isStiRoot && { discriminatorColumn: meta.discriminatorColumn as string }),\n ...(isStiChild && { extendsEntity: meta.extends }),\n ...(isStiChild && meta.discriminatorValue !== undefined && { discriminatorValue: String(meta.discriminatorValue) }),\n constraints: buildConstraints(meta),\n };\n}\n\n/** Returns ColumnModels for renderable properties, or an empty array to skip. */\nfunction buildColumns(\n prop: EntityProperty,\n metaByClass: Map<string, EntityMetadata>,\n owningMeta: EntityMetadata\n): ColumnModel[] {\n if (prop.kind === ReferenceKind.EMBEDDED) {\n // An object/array embedded is stored as a single JSON column, so render one\n // column for it. (`array: true` implies `object: true`.) A plain inline\n // embedded has no column of its own — its fields surface as flat SCALARs.\n if (prop.object === true || prop.array === true) {\n return [\n {\n propName: prop.name,\n fieldName: prop.fieldNames?.[0] ?? prop.name,\n type: 'json',\n isPrimary: false,\n isForeignKey: false,\n isUnique: prop.unique === true,\n isNullable: prop.nullable === true,\n ...(prop.comment !== undefined && { comment: prop.comment }),\n embeddedIn: prop.array === true ? `${prop.type}[]` : prop.type,\n },\n ];\n }\n return [];\n }\n\n if (prop.kind === ReferenceKind.SCALAR) {\n // Flat leaf of an object/array embedded: it lives inside the single JSON\n // column rendered above, so it is not a column of its own — skip it.\n if (prop.object === true && prop.embedded !== undefined) {\n return [];\n }\n\n // For @Formula columns, formula is set on a SCALAR-kinded property\n const formulaExpr: string | undefined =\n prop.formula !== undefined\n ? resolveFormulaExpr(prop.formula as (table: FormulaTable, cols: Record<string, string>) => string)\n : undefined;\n\n // Shadow property (persist: false, e.g. a cached/computed runtime value or a\n // getter-only property): MikroORM never writes or reads a DB column for it, so\n // it has no physical column to document. @Formula columns are persist: false\n // too, but they ARE meaningful to document (a real SELECT-time expression), so\n // only skip when there is no formula.\n if (prop.persist === false && formulaExpr === undefined) {\n return [];\n }\n\n // Flat embedded columns carry `embedded: [ownerPropName, embeddedPropName]`\n let embeddedIn: string | undefined;\n let embeddedPropName: string | undefined;\n if (prop.embedded !== undefined) {\n const parentPropName = prop.embedded[0];\n embeddedIn = owningMeta.properties[parentPropName]?.type;\n embeddedPropName = prop.embedded[1];\n }\n\n const isDiscriminator =\n owningMeta.discriminatorColumn !== undefined && prop.name === owningMeta.discriminatorColumn;\n\n const enumItems =\n prop.enum === true && Array.isArray(prop.items) && prop.items.length > 0\n ? prop.items.map((item) => String(item))\n : undefined;\n\n return [\n {\n propName: prop.name,\n fieldName: prop.fieldNames?.[0] ?? prop.name,\n // Store the original type (e.g. `varchar(255)`); the Mermaid renderer\n // sanitizes it for diagram identifiers, while the markdown table shows\n // it verbatim. Guard against a missing type so downstream string\n // handling never sees undefined (matches the FK path's defaulting).\n type: prop.type ?? 'unknown',\n isPrimary: prop.primary === true,\n isForeignKey: false,\n isUnique: prop.unique === true,\n isNullable: prop.nullable === true,\n ...(prop.comment !== undefined && { comment: prop.comment }),\n ...(formulaExpr !== undefined && { formula: formulaExpr }),\n ...(embeddedIn !== undefined && { embeddedIn }),\n ...(embeddedPropName !== undefined && { embeddedPropName }),\n ...(isDiscriminator && { isDiscriminator: true }),\n ...(enumItems !== undefined && { enumItems }),\n },\n ];\n }\n\n // FK columns: m:1 always owns the FK; 1:1 only when owner === true\n if (prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner === true)) {\n const cols = buildForeignKeyColumns(prop, metaByClass);\n if (prop.type === owningMeta.className) {\n return cols.map((col) => ({ ...col, isSelfReference: true }));\n }\n return cols;\n }\n\n // ONE_TO_MANY, MANY_TO_MANY (both owner and inverse) → no physical column\n return [];\n}\n\n/**\n * Calls the FormulaCallback with a dummy table and column proxy to extract the SQL expression.\n * String-based formulas (most common) ignore their arguments and return the literal string.\n * Function-based formulas use the alias/column names from the dummy objects.\n * Returns a visible fallback on unexpected errors so generated docs do not hide\n * that the expression could not be resolved.\n */\nfunction resolveFormulaExpr(cb: (table: FormulaTable, cols: Record<string, string>) => string): string {\n try {\n const cols = new Proxy<Record<string, string>>(\n {},\n {\n get: (_target: Record<string, string>, key: string | symbol): string => (typeof key === 'string' ? key : ''),\n }\n );\n const result = cb(FORMULA_DUMMY_TABLE, cols);\n // The callback is typed to return a string, but a misbehaving formula can\n // return anything; coerce so downstream string handling never crashes.\n return typeof result === 'string' ? result : String(result);\n } catch {\n return UNRESOLVED_FORMULA;\n }\n}\n\nfunction buildForeignKeyColumns(prop: EntityProperty, metaByClass: Map<string, EntityMetadata>): ColumnModel[] {\n const fieldNames = prop.fieldNames && prop.fieldNames.length > 0 ? prop.fieldNames : [`${prop.name}_id`];\n const fkTypes = resolveFkTypes(prop, metaByClass, fieldNames.length);\n\n return fieldNames.map((fieldName, index) => ({\n propName: prop.name,\n fieldName,\n type: fkTypes[index] ?? fkTypes[0] ?? 'integer',\n isPrimary: prop.primary === true,\n isForeignKey: true,\n isUnique: prop.unique === true,\n isNullable: prop.nullable === true,\n ...(prop.comment !== undefined && { comment: prop.comment }),\n referencedEntity: prop.type,\n }));\n}\n\n/** Looks up referenced PK types to use as FK column types, preserving composite key order. */\nfunction resolveFkTypes(\n prop: EntityProperty,\n metaByClass: Map<string, EntityMetadata>,\n fieldNameCount: number\n): string[] {\n const refMeta = metaByClass.get(prop.type);\n if (!refMeta) {\n return Array.from({ length: fieldNameCount }, () => 'integer');\n }\n\n const primaryProps = getPrimaryProps(refMeta);\n const referencedColumnNames = prop.referencedColumnNames ?? [];\n return Array.from({ length: fieldNameCount }, (_value, index) => {\n const referencedColumnName = referencedColumnNames[index];\n const pkProp =\n referencedColumnName !== undefined\n ? primaryProps.find((candidate) => candidate.fieldNames.includes(referencedColumnName))\n : undefined;\n\n const resolvedProp = pkProp ?? primaryProps[index] ?? primaryProps[0];\n const rawType = resolvedProp?.type ?? 'integer';\n // Pass the resolved prop's position so recursive calls follow the same column in\n // deeper entities (preserves composite-key alignment through FK-as-PK chains).\n const pkIndex = resolvedProp !== undefined ? primaryProps.indexOf(resolvedProp) : 0;\n return resolveScalarType(rawType, metaByClass, pkIndex);\n });\n}\n\n/**\n * Follows entity-class-name references until a non-entity scalar type is reached.\n * Handles supertype-subtype chains where B.id is FK to A, and C.id is FK to B.\n * pkIndex preserves composite-key column alignment at each level of the chain.\n */\nfunction resolveScalarType(type: string, metaByClass: Map<string, EntityMetadata>, pkIndex = 0, depth = 0): string {\n if (depth >= 5) {\n return 'integer';\n }\n const refMeta = metaByClass.get(type);\n if (!refMeta) {\n return type;\n }\n const primaryProps = getPrimaryProps(refMeta);\n if (primaryProps.length === 0) {\n return type;\n }\n const targetProp = primaryProps[pkIndex] ?? primaryProps[0];\n const nextType = targetProp?.type ?? type;\n if (nextType === type) {\n return type;\n }\n return resolveScalarType(nextType, metaByClass, pkIndex, depth + 1);\n}\n\nfunction getPrimaryProps(meta: EntityMetadata): EntityProperty[] {\n const primaryKeys = meta.primaryKeys ?? [];\n const orderedPrimaryProps = primaryKeys\n .map((key) => meta.properties[String(key)])\n .filter((prop): prop is EntityProperty => prop !== undefined);\n\n if (orderedPrimaryProps.length > 0) {\n return orderedPrimaryProps;\n }\n\n return Object.values(meta.properties).filter((prop) => prop.primary === true);\n}\n\n/** Collects indexes, unique constraints, and check constraints from entity-level metadata. */\nfunction buildConstraints(meta: EntityMetadata): ConstraintModel[] {\n const result: ConstraintModel[] = [];\n\n for (const idx of meta.indexes ?? []) {\n const props = idx.properties;\n result.push({\n type: 'index',\n properties: resolveConstraintProperties(meta, props),\n ...(idx.name !== undefined && { name: idx.name }),\n });\n }\n\n for (const uniq of meta.uniques ?? []) {\n const props = uniq.properties;\n result.push({\n type: 'unique',\n properties: resolveConstraintProperties(meta, props),\n ...(uniq.name !== undefined && { name: uniq.name }),\n });\n }\n\n for (const check of meta.checks ?? []) {\n // Skip function-based check expressions (they require column reference objects at runtime)\n if (typeof check.expression !== 'string') {\n continue;\n }\n result.push({\n type: 'check',\n properties: [],\n expression: check.expression,\n ...(check.name !== undefined && { name: check.name }),\n });\n }\n\n return result;\n}\n\nfunction resolveConstraintProperties(meta: EntityMetadata, props: string | string[] | undefined): string[] {\n const propNames = Array.isArray(props) ? props : props !== undefined ? [props] : [];\n\n return propNames.flatMap((propName) => {\n const prop = meta.properties[String(propName)];\n if (prop === undefined) {\n return [String(propName)];\n }\n\n if (prop.fieldNames !== undefined && prop.fieldNames.length > 0) {\n return prop.fieldNames;\n }\n\n return [prop.name];\n });\n}\n\n/**\n * Builds edges only from owning sides to avoid duplicate arrows.\n * STI inheritance is not drawn as an edge — it is conveyed through table captions instead.\n */\nfunction buildRelationEdges(metas: EntityMetadata[]): RelationEdge[] {\n const edges: RelationEdge[] = [];\n\n for (const meta of metas) {\n if (meta.pivotTable || meta.embeddable) {\n continue;\n }\n\n for (const prop of Object.values(meta.properties)) {\n const edge = buildEdge(meta.className, prop);\n if (edge !== null) {\n edges.push(edge);\n }\n }\n }\n\n return edges;\n}\n\nfunction buildEdge(fromEntity: string, prop: EntityProperty): RelationEdge | null {\n const isNullable = prop.nullable === true;\n\n if (prop.kind === ReferenceKind.MANY_TO_ONE) {\n if (prop.type === fromEntity) {\n return null; // self-reference: shown as column comment, not a relation line\n }\n return {\n fromEntity,\n toEntity: prop.type,\n fromCardinality: '}o',\n toCardinality: isNullable ? 'o|' : '||',\n label: prop.name,\n };\n }\n\n if (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner === true) {\n if (prop.type === fromEntity) {\n return null; // self-reference: shown as column comment, not a relation line\n }\n return {\n fromEntity,\n toEntity: prop.type,\n fromCardinality: '||',\n toCardinality: isNullable ? 'o|' : '||',\n label: prop.name,\n };\n }\n\n if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.owner === true) {\n return {\n fromEntity,\n toEntity: prop.type,\n fromCardinality: '}o',\n toCardinality: 'o{',\n label: prop.name,\n };\n }\n\n return null;\n}\n","import type { Options } from '@mikro-orm/core';\n\n/**\n * When the config does not choose a metadata provider, opt into\n * `TsMorphMetadataProvider` if `@mikro-orm/reflection` is installed.\n *\n * The CLI loads `.ts` configs through `tsx` (esbuild), which strips\n * `emitDecoratorMetadata`, so MikroORM's default `ReflectMetadataProvider`\n * cannot infer types for entities that omit explicit `type:`/`entity:`\n * attributes. `TsMorphMetadataProvider` reads types from the TypeScript sources\n * instead. When the optional package is absent the original options are kept.\n */\nexport async function withTsMorphMetadataProvider(\n options: Options,\n onWarn?: (message: string) => void\n): Promise<Options> {\n if (options.metadataProvider !== undefined) {\n return options;\n }\n\n try {\n const { TsMorphMetadataProvider } = await import('@mikro-orm/reflection');\n return { ...options, metadataProvider: TsMorphMetadataProvider };\n } catch (err) {\n const code =\n err !== null && typeof err === 'object' && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;\n const isNotInstalled = code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND';\n\n if (!isNotInstalled && onWarn) {\n onWarn(\n `@mikro-orm/reflection is installed but failed to load: ${err instanceof Error ? err.message : String(err)}. ` +\n 'Ensure all @mikro-orm/* packages are installed at the same version.'\n );\n }\n\n return options;\n }\n}\n","const MARKDOWN_INLINE_SPECIAL_CHARS = /[\\\\`|*#\\[\\]]/g;\nconst MARKDOWN_EMPHASIS_UNDERSCORE = /(?<![a-zA-Z0-9])_|_(?![a-zA-Z0-9])/g;\nconst MERMAID_IDENTIFIER_INVALID_CHARS = /[^a-zA-Z0-9_]/g;\n\nfunction normalizeInlineText(value: string): string {\n return value\n .replace(/\\r\\n?/g, '\\n')\n .replace(/[\\n\\t]+/g, ' ')\n .replace(/\\s{2,}/g, ' ')\n .trim();\n}\n\nfunction splitNormalizedLines(value: string): string[] {\n return value.replace(/\\r\\n?/g, '\\n').split('\\n');\n}\n\nfunction escapeHtmlText(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\nexport function escapeMarkdownInline(value: string): string {\n return escapeHtmlText(normalizeInlineText(value))\n .replace(MARKDOWN_INLINE_SPECIAL_CHARS, '\\\\$&')\n .replace(MARKDOWN_EMPHASIS_UNDERSCORE, '\\\\_');\n}\n\nexport function escapeMarkdownTableCell(value: string): string {\n return splitNormalizedLines(value)\n .map((line) => escapeMarkdownInline(line))\n .join('<br>');\n}\n\n/**\n * Escapes a multi-line paragraph for markdown body text, preserving line breaks\n * as hard breaks (two trailing spaces + newline) instead of collapsing them to\n * a single space. Used for the document description, which the programmatic API\n * accepts as free-form multi-line text.\n */\nexport function escapeMarkdownParagraph(value: string): string {\n return splitNormalizedLines(value)\n .map((line) => escapeMarkdownInline(line))\n .join(' \\n');\n}\n\nexport function renderMarkdownBlockQuote(value: string): string {\n return splitNormalizedLines(value)\n .map((line) => `> ${escapeMarkdownInline(line)}`)\n .join('\\n');\n}\n\nexport function renderMarkdownInlineCode(value: string): string {\n const normalized = normalizeInlineText(value);\n const backtickRuns = normalized.match(/`+/g) ?? [];\n const longestRun = Math.max(0, ...backtickRuns.map((run) => run.length));\n const fence = '`'.repeat(longestRun + 1);\n const needsPadding = normalized.startsWith('`') || normalized.endsWith('`');\n const content = needsPadding ? ` ${normalized} ` : normalized;\n return `${fence}${content}${fence}`;\n}\n\nexport function toMermaidIdentifier(value: string): string {\n const normalized = normalizeInlineText(value).replace(MERMAID_IDENTIFIER_INVALID_CHARS, '_').replace(/_+/g, '_');\n const identifier = normalized === '' ? '_' : normalized;\n return /^[a-zA-Z_]/.test(identifier) ? identifier : `_${identifier}`;\n}\n\nexport function escapeMermaidQuotedText(value: string): string {\n return normalizeInlineText(value).replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Builds a GitHub-style heading anchor slug for in-document links.\n * Lowercases, drops characters other than letters / numbers / underscores /\n * spaces / hyphens, then turns spaces into hyphens. The letter/number classes\n * are Unicode-aware (\\p{L}, \\p{N}), so non-ASCII headings such as a Korean\n * namespace name keep their characters and match GitHub's generated anchor.\n */\nexport function toMarkdownAnchor(value: string): string {\n return normalizeInlineText(value)\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s_-]/gu, '')\n .replace(/\\s+/g, '-');\n}\n","import type { ColumnModel, DiagramModel } from '../model/types.js';\nimport { escapeMermaidQuotedText, toMermaidIdentifier } from './escape.js';\n\nexport const MERMAID_LAYOUTS = ['dagre', 'elk', 'elk.stress'] as const;\nexport type MermaidLayout = (typeof MERMAID_LAYOUTS)[number];\n\nexport const MERMAID_THEMES = ['default', 'neutral', 'dark', 'forest', 'base'] as const;\nexport type MermaidTheme = (typeof MERMAID_THEMES)[number];\n\n/** Optional Mermaid rendering hints injected as YAML frontmatter inside the erDiagram fence. */\nexport interface MermaidRenderOptions {\n layout?: MermaidLayout;\n theme?: MermaidTheme;\n}\n\n/**\n * Generic type per base type name, covering the declaration strings produced\n * by the supported MikroORM platforms (PostgreSQL, MySQL, MariaDB, SQLite)\n * plus the dialect spellings users commonly write in `@Property({ type })`.\n */\nconst GENERIC_TYPE_BY_BASE_NAME = new Map<string, string>([\n ['uuid', 'string'],\n ['text', 'string'],\n ['string', 'string'],\n ['varchar', 'string'],\n ['character varying', 'string'],\n ['character', 'string'],\n ['char', 'string'],\n ['tinytext', 'string'],\n ['mediumtext', 'string'],\n ['longtext', 'string'],\n ['timestamptz', 'datetime'],\n ['timestamp', 'datetime'],\n ['datetime', 'datetime'],\n ['integer', 'integer'],\n ['int', 'integer'],\n ['bigint', 'integer'],\n ['smallint', 'integer'],\n ['tinyint', 'integer'],\n ['mediumint', 'integer'],\n ['serial', 'integer'],\n ['bigserial', 'integer'],\n ['doubletype', 'float'],\n ['double precision', 'float'],\n ['double', 'float'],\n ['float', 'float'],\n ['decimal', 'float'],\n ['numeric', 'float'],\n ['real', 'float'],\n ['boolean', 'boolean'],\n ['bool', 'boolean'],\n ['jsonb', 'json'],\n]);\n\n/**\n * Maps DB-specific or ORM-internal type strings to RDBMS-agnostic generic types\n * so the generated docs are portable across PostgreSQL, MySQL, SQLite, etc.\n *\n * Matching strips a trailing \"(…)\" parameter list (varchar(255), numeric(10,2))\n * and a MySQL \"unsigned\"/\"signed\" modifier, then looks up the base name exactly —\n * a prefix match would confuse e.g. PostgreSQL's `interval` with `int`.\n * Unrecognized types pass through unchanged.\n */\nexport function normalizeType(type: string): string {\n const t = type.toLowerCase().replace(/\\s+/g, ' ').trim();\n\n // MySQL declares booleans as tinyint(1); match before the generic tinyint -> integer rule.\n if (/^tinyint\\s*\\(\\s*1\\s*\\)$/.test(t)) {\n return 'boolean';\n }\n\n const baseName = t\n .replace(/\\(.*\\)/, '')\n .replace(/\\b(un)?signed\\b/, '')\n .trim();\n\n return GENERIC_TYPE_BY_BASE_NAME.get(baseName) ?? type;\n}\n\n/**\n * Renders a DiagramModel as a Mermaid erDiagram block string.\n * The returned string is ready to embed in a markdown code fence.\n * When `mermaid` options are provided, a YAML frontmatter block is prepended.\n */\nexport function renderErDiagram(model: DiagramModel, mermaid?: MermaidRenderOptions): string {\n const lines: string[] = [];\n\n if (mermaid?.layout !== undefined || mermaid?.theme !== undefined) {\n lines.push('---', 'config:');\n if (mermaid.layout !== undefined) {\n lines.push(` layout: ${mermaid.layout}`);\n }\n if (mermaid.theme !== undefined) {\n lines.push(` theme: ${mermaid.theme}`);\n }\n lines.push('---');\n }\n\n lines.push('erDiagram');\n\n for (const entity of model.entities) {\n lines.push(` ${toMermaidIdentifier(entity.className)} {`);\n for (const col of entity.columns) {\n lines.push(` ${renderColumnLine(col)}`);\n }\n lines.push(' }');\n }\n\n for (const rel of model.relations) {\n lines.push(\n ` ${toMermaidIdentifier(rel.fromEntity)} ${rel.fromCardinality}--${rel.toCardinality} ${toMermaidIdentifier(rel.toEntity)} : \"${escapeMermaidQuotedText(rel.label)}\"`\n );\n }\n\n return lines.join('\\n');\n}\n\nfunction renderColumnLine(col: ColumnModel): string {\n // Priority: PK > UK (FK qualifier omitted — relationship lines already convey FK relationships)\n let qualifier = '';\n if (col.isPrimary) {\n qualifier = ' PK';\n } else if (col.isUnique) {\n qualifier = ' UK';\n }\n\n // Comment priority (MikroORM-specific markers only — keeps the diagram uncluttered).\n // Renamed columns: FK columns surface their TS name in the markdown table's Key\n // cell (\"FK (propName)\"); plain renamed scalars show only the DB column name.\n // 1. @Formula SQL expression — \"formula: LENGTH(name)\"\n // 2. STI discriminator column — \"discriminator\"\n // 3. Embedded source type — \"[Address]\"\n let comment: string | undefined;\n if (col.formula !== undefined) {\n comment = col.formula ? `formula: ${col.formula}` : 'formula';\n } else if (col.isDiscriminator) {\n comment = 'discriminator';\n } else if (col.embeddedIn !== undefined) {\n comment = `[${col.embeddedIn}]`;\n } else if (col.isSelfReference) {\n comment = 'self-ref';\n }\n\n const commentStr = comment !== undefined ? ` \"${escapeMermaidQuotedText(comment)}\"` : '';\n return `${toMermaidIdentifier(normalizeType(col.type))} ${toMermaidIdentifier(col.fieldName)}${qualifier}${commentStr}`;\n}\n","import type { DocumentModel, EnrichedEntity, NamespaceGroup } from '../model/build.js';\nimport type { ColumnModel, ConstraintModel, DiagramModel } from '../model/types.js';\nimport {\n escapeMarkdownInline,\n escapeMarkdownParagraph,\n escapeMarkdownTableCell,\n renderMarkdownBlockQuote,\n renderMarkdownInlineCode,\n toMarkdownAnchor,\n} from './escape.js';\nimport { type MermaidRenderOptions, normalizeType, renderErDiagram } from './mermaid.js';\n\n/**\n * Renders a DocumentModel as a markdown string.\n * Each namespace group becomes a level-2 section with a Mermaid ERD block\n * followed by per-entity column tables.\n */\nexport function renderMarkdown(docModel: DocumentModel, mermaid?: MermaidRenderOptions): string {\n const sections: string[] = [`# ${escapeMarkdownInline(docModel.title)}`];\n\n if (docModel.description) {\n sections.push(escapeMarkdownParagraph(docModel.description));\n }\n\n // A table of contents only helps when there is more than one namespace section.\n if (docModel.groups.length > 1) {\n sections.push(renderTableOfContents(docModel.groups, resolveGroupAnchors(docModel)));\n }\n\n for (const group of docModel.groups) {\n sections.push(renderGroupSection(group, mermaid));\n }\n\n return sections.join('\\n\\n');\n}\n\n/**\n * Renders a bulleted markdown section: a header line, a blank line, then one\n * line per item. Shared by the Contents / Computed columns / Constraints\n * sections, which differ only in their header and per-item formatting.\n */\nfunction renderBulletSection<T>(header: string, items: T[], renderItem: (item: T) => string): string {\n const lines = [header, ''];\n for (const item of items) {\n lines.push(renderItem(item));\n }\n return lines.join('\\n');\n}\n\n/** Renders a namespace-level table of contents linking to each group's H2 section. */\nfunction renderTableOfContents(groups: NamespaceGroup[], anchors: Map<NamespaceGroup, string>): string {\n return renderBulletSection('## Contents', groups, (group) => {\n const label = escapeMarkdownInline(group.name);\n return `- [${label}](#${anchors.get(group) ?? toMarkdownAnchor(group.name)})`;\n });\n}\n\nfunction resolveGroupAnchors(docModel: DocumentModel): Map<NamespaceGroup, string> {\n const seenAnchors = new Map<string, number>();\n const groupAnchors = new Map<NamespaceGroup, string>();\n\n resolveHeadingAnchor(docModel.title, seenAnchors);\n resolveHeadingAnchor('Contents', seenAnchors);\n\n for (const group of docModel.groups) {\n groupAnchors.set(group, resolveHeadingAnchor(group.name, seenAnchors));\n for (const entity of group.textEntities) {\n resolveHeadingAnchor(entity.model.className, seenAnchors);\n }\n }\n\n return groupAnchors;\n}\n\nfunction resolveHeadingAnchor(value: string, seenAnchors: Map<string, number>): string {\n const baseAnchor = toMarkdownAnchor(value);\n const previousCount = seenAnchors.get(baseAnchor) ?? 0;\n seenAnchors.set(baseAnchor, previousCount + 1);\n return previousCount === 0 ? baseAnchor : `${baseAnchor}-${previousCount}`;\n}\n\nfunction renderGroupSection(group: NamespaceGroup, mermaid?: MermaidRenderOptions): string {\n const parts: string[] = [`## ${escapeMarkdownInline(group.name)}`];\n\n if (group.erdEntities.length > 0) {\n const diagramModel: DiagramModel = {\n entities: group.erdEntities.map((e) => e.model),\n relations: group.erdRelations,\n };\n parts.push('```mermaid\\n' + renderErDiagram(diagramModel, mermaid) + '\\n```');\n }\n\n for (const entity of group.textEntities) {\n parts.push(renderEntitySection(entity));\n }\n\n return parts.join('\\n\\n');\n}\n\nfunction renderEntitySection(entity: EnrichedEntity): string {\n const parts: string[] = [`### ${escapeMarkdownInline(entity.model.className)}`];\n\n // The actual DB table name is what readers of a schema doc look for first,\n // and it is not otherwise visible (the ERD and heading use the class name).\n parts.push(`*Table: ${renderMarkdownInlineCode(entity.model.tableName)}*`);\n\n if (entity.jsDoc?.description) {\n parts.push(renderMarkdownBlockQuote(entity.jsDoc.description));\n }\n\n // STI metadata note\n if (entity.model.discriminatorColumn) {\n parts.push(`*STI root — discriminator column: ${renderMarkdownInlineCode(entity.model.discriminatorColumn)}*`);\n } else if (entity.model.extendsEntity) {\n const discValue =\n entity.model.discriminatorValue !== undefined\n ? `, discriminator value: ${renderMarkdownInlineCode(entity.model.discriminatorValue)}`\n : '';\n parts.push(\n `*Extends ${renderMarkdownInlineCode(entity.model.extendsEntity)} (Single Table Inheritance${discValue})*`\n );\n }\n\n if (entity.model.columns.length > 0) {\n parts.push(renderColumnTable(entity));\n }\n\n if (entity.model.constraints.length > 0) {\n parts.push(renderConstraints(entity.model.constraints));\n }\n\n const computedColumns = entity.model.columns.filter((col) => col.formula !== undefined);\n if (computedColumns.length > 0) {\n parts.push(renderComputedColumns(computedColumns));\n }\n\n return parts.join('\\n\\n');\n}\n\nfunction renderColumnTable(entity: EnrichedEntity): string {\n const header = '| Column | Type | Key | Nullable | Description |';\n const sep = '|--------|------|-----|----------|-------------|';\n const rows = entity.model.columns.map((col) => {\n const key = resolveColumnKey(col);\n const nullable = col.isNullable && !col.isPrimary ? 'Y' : '';\n // JSDoc property description wins; fall back to the @Property({ comment }) DDL comment.\n const docDesc = entity.propDocs.get(col.propName)?.description ?? col.comment ?? '';\n // Surface @Enum allowed values; the table cell escapes backticks, so plain text.\n const enumDesc = col.enumItems !== undefined ? `One of: ${col.enumItems.join(', ')}` : '';\n const desc = [docDesc, enumDesc].filter((part) => part !== '').join('\\n');\n return `| ${escapeMarkdownTableCell(col.fieldName)} | ${escapeMarkdownTableCell(normalizeType(col.type))} | ${escapeMarkdownTableCell(key)} | ${nullable} | ${escapeMarkdownTableCell(desc)} |`;\n });\n return [header, sep, ...rows].join('\\n');\n}\n\n/** Returns the \"Key\" cell value for the column table. */\nfunction resolveColumnKey(col: ColumnModel): string {\n const fkKey = col.fieldName !== col.propName ? `FK (${col.propName})` : 'FK';\n\n if (col.isPrimary && col.isForeignKey) {\n return `PK, ${fkKey}`;\n }\n if (col.isPrimary) {\n return 'PK';\n }\n if (col.isForeignKey) {\n // Show TS property name in parentheses if it differs from the DB column name.\n // A unique FK (e.g. the owning side of a 1:1) keeps its UK marker so the\n // table agrees with the Mermaid ERD, which renders this column as UK.\n return col.isUnique ? `${fkKey}, UK` : fkKey;\n }\n if (col.isUnique) {\n return 'UK';\n }\n if (col.isDiscriminator) {\n return 'discriminator';\n }\n if (col.embeddedIn !== undefined) {\n return `[${col.embeddedIn}]`;\n }\n return '';\n}\n\nfunction renderComputedColumns(columns: ColumnModel[]): string {\n return renderBulletSection('**Computed columns:**', columns, (col) => {\n // An empty/unresolved formula expression renders as just the column name —\n // the \"Computed columns\" heading already conveys that it is computed, and\n // an empty inline-code span would be broken output.\n const expr = col.formula ? `: ${renderMarkdownInlineCode(col.formula)}` : '';\n return `- ${renderMarkdownInlineCode(col.fieldName)}${expr}`;\n });\n}\n\nfunction renderConstraints(constraints: ConstraintModel[]): string {\n return renderBulletSection('**Constraints:**', constraints, (c) => {\n const name = c.name ? ` ${renderMarkdownInlineCode(c.name)}` : '';\n const properties = c.properties.map(escapeMarkdownInline).join(', ');\n if (c.type === 'index') {\n return `- Index${name}: (${properties})`;\n }\n if (c.type === 'unique') {\n return `- Unique${name}: (${properties})`;\n }\n return `- Check${name}: ${renderMarkdownInlineCode(c.expression ?? '')}`;\n });\n}\n","import type { EntityMetadata, Options } from '@mikro-orm/core';\nimport { type JsDocResult, loadJsDoc } from './docs/jsdoc.js';\nimport { type LoadedEntityMetadata, loadEntityMetadata } from './metadata/load.js';\nimport { buildDocumentModel } from './model/build.js';\nimport { withTsMorphMetadataProvider } from './provider.js';\nimport { renderMarkdown } from './render/markdown.js';\nimport type { MermaidRenderOptions } from './render/mermaid.js';\n\nexport { MetadataLoadError } from './metadata/load.js';\nexport type { MermaidLayout, MermaidRenderOptions, MermaidTheme } from './render/mermaid.js';\n\n/** Options for the programmatic API. */\nexport interface GenerateMarkdownOptions {\n /** MikroORM configuration (driver, entities, dbName, …). */\n orm: Options;\n /** Title shown as the H1 heading in the generated document. */\n title?: string;\n /** Optional description paragraph rendered below the H1 heading. */\n description?: string;\n /**\n * Source globs/paths (`.ts`) to read JSDoc from. Use this when your entities\n * run from compiled JavaScript (`entities: ['./dist/**\\/*.js']`): build tools\n * strip comments, so descriptions and `@namespace`/`@hidden` tags would\n * otherwise be lost. Defaults to each entity's own discovered source file.\n */\n src?: string[];\n /** Receives non-fatal warnings (e.g. JSDoc cannot be read from compiled JS). */\n onWarn?: (message: string) => void;\n /**\n * Optional Mermaid rendering options. When provided, a YAML frontmatter block\n * is prepended to each erDiagram fence. Omit to preserve default viewer behavior.\n */\n mermaid?: MermaidRenderOptions;\n}\n\n/** File extensions produced by a TypeScript build, where comments are stripped. */\nconst COMPILED_JS = /\\.(c|m)?js$/i;\n\n/**\n * Decides which files JSDoc should be read from.\n *\n * When the caller provides `src`, those paths win. Otherwise we fall back to the\n * source files MikroORM discovered each entity from — and if those are compiled\n * JavaScript, JSDoc (descriptions, `@namespace`, and crucially `@hidden`) is\n * gone, so we warn the user and point them at `src`.\n */\nexport function resolveJsDocSources(\n sourcePaths: string[],\n src: string[] | undefined,\n onWarn?: (message: string) => void\n): string[] {\n if (src !== undefined && src.length > 0) {\n return src;\n }\n\n if (sourcePaths.some((p) => COMPILED_JS.test(p)) && onWarn) {\n onWarn(\n 'Entities were discovered from compiled JavaScript, so JSDoc descriptions ' +\n 'and @namespace/@hidden tags cannot be read (build tools strip comments). ' +\n 'Hidden entities may be exposed. Pass --src \"<glob to your .ts sources>\" ' +\n '(or the `src` option) to read JSDoc from the original TypeScript files.'\n );\n }\n\n return sourcePaths;\n}\n\nfunction assertExplicitJsDocSourceCoverage(\n metas: EntityMetadata[],\n jsDocResult: JsDocResult,\n src: string[],\n onWarn?: (message: string) => void\n): void {\n if (jsDocResult.sourceFileCount === 0) {\n throw new Error(\n `No source files matched the explicit src paths: ${src.join(', ')}\\n` +\n 'Check the --src glob/path (or the `src` option). Without matching TypeScript sources, ' +\n 'JSDoc tags such as @namespace and @hidden cannot be read.'\n );\n }\n\n const isRenderable = (meta: EntityMetadata): boolean => !meta.pivotTable && !meta.embeddable;\n\n const missingConcrete = metas\n .filter((meta) => isRenderable(meta) && !meta.abstract)\n .map((meta) => meta.className)\n .filter((className) => !jsDocResult.classNames.has(className));\n\n if (missingConcrete.length > 0) {\n throw new Error(\n `Explicit src paths did not include source declarations for discovered entities: ${missingConcrete.join(', ')}\\n` +\n 'Check that --src (or the `src` option) points at all TypeScript entity files. ' +\n 'JSDoc tags such as @namespace and @hidden for missing entities cannot be read.'\n );\n }\n\n // Abstract STI parents appear in the diagram but are often defined in a separate\n // base-class file that --src may not cover. Warn rather than error so the user\n // knows @hidden/@namespace won't apply to them.\n if (onWarn) {\n const missingAbstract = metas\n .filter((meta) => isRenderable(meta) && meta.abstract)\n .map((meta) => meta.className)\n .filter((className) => !jsDocResult.classNames.has(className));\n\n if (missingAbstract.length > 0) {\n onWarn(\n `Abstract STI parent entities were not found in the explicit src paths: ${missingAbstract.join(', ')}\\n` +\n '@hidden and @namespace tags for these entities will not be applied. ' +\n 'Include their source files in --src to enable JSDoc tags for them.'\n );\n }\n }\n}\n\nfunction errorMessages(err: unknown): string[] {\n const messages: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = err;\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n messages.push(current.message);\n current = (current as { cause?: unknown }).cause;\n }\n\n return messages;\n}\n\nfunction isMissingTsMorphSourceFile(err: unknown): boolean {\n return errorMessages(err).some((message) => message.includes('Source file') && message.includes('not found'));\n}\n\nasync function loadEntityMetadataWithTsMorphFallback(\n originalOrm: Options,\n effectiveOrm: Options\n): Promise<LoadedEntityMetadata> {\n try {\n return await loadEntityMetadata(effectiveOrm);\n } catch (err) {\n const wasAutoInjected = originalOrm.metadataProvider === undefined && effectiveOrm.metadataProvider !== undefined;\n if (!wasAutoInjected || !isMissingTsMorphSourceFile(err)) {\n throw err;\n }\n\n try {\n return await loadEntityMetadata(originalOrm);\n } catch {\n throw err;\n }\n }\n}\n\n/**\n * Generates a Mermaid ERD + markdown documentation document from MikroORM\n * entity metadata.\n *\n * JSDoc tags (@namespace, @erd, @describe, @hidden) and descriptions are\n * read directly from each entity's own source file — no separate path needs\n * to be specified. When entities run from compiled JavaScript (where comments\n * are stripped), pass `src` to read JSDoc from the original `.ts` files.\n *\n * @example\n * ```ts\n * import { generateMarkdown } from 'mikro-orm-markdown';\n * import ormConfig from './mikro-orm.config.js';\n *\n * const markdown = await generateMarkdown({\n * orm: ormConfig,\n * title: 'My Database',\n * });\n * ```\n */\nexport async function generateMarkdown(options: GenerateMarkdownOptions): Promise<string> {\n const { orm, title = 'Database Schema', description, src, onWarn, mermaid } = options;\n\n const effectiveOrm = await withTsMorphMetadataProvider(orm, onWarn);\n const { metas, sourcePaths } = await loadEntityMetadataWithTsMorphFallback(orm, effectiveOrm);\n const jsDocResult = loadJsDoc(resolveJsDocSources(sourcePaths, src, onWarn), onWarn);\n if (src !== undefined && src.length > 0) {\n assertExplicitJsDocSourceCoverage(metas, jsDocResult, src, onWarn);\n }\n const docModel = buildDocumentModel(metas, jsDocResult, title, description, onWarn);\n return renderMarkdown(docModel, mermaid);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,I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AAAA,IACF;AAAA,IACA,kDAAkD,gBAAgB,KAAK,GAAG,CAAC;AAAA,EAC7E,EAAE,QAAQ,eAAe;AAC3B,EACC;AAAA,EACC,IAAI;AAAA,IACF;AAAA,IACA,0CAA0C,eAAe,KAAK,GAAG,CAAC;AAAA,EACpE,EAAE,QAAQ,cAAc;AAC1B,EACC,OAAO,GAAG;AAEb,SAAS,uBAAgC;AACvC,QAAM,aAAa,QAAQ,KAAK,CAAC;AAEjC,MAAI,eAAe,QAAW;AAC5B,WAAO;AAAA,EACT;AAEA,MAAI;AACF,WAAc,oBAAkB,cAAQ,UAAU,CAAC,MAAa,wBAAa,+BAAc,aAAe,CAAC;AAAA,EAC7G,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAI,qBAAqB,GAAG;AAC1B,UAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAiB;AACvD,YAAQ,OAAO,MAAM,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC5E,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["path","sourceFiles","import_core","import_core","run"]}
package/dist/cli.d.cts CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { Options } from '@mikro-orm/core';
3
3
 
4
+ interface LoadOrmOptionsOptions {
5
+ keepTsxRegistered?: boolean;
6
+ }
4
7
  declare function toConfigImportSpecifier(configPath: string): string;
5
8
  /**
6
9
  * Walks up from the directory of `fromPath` looking for the nearest
@@ -26,7 +29,7 @@ declare function findNearestTsconfig(fromPath: string): string | undefined;
26
29
  * fail with a cryptic `Cannot read properties of undefined` error depending on
27
30
  * which directory the CLI was launched from.
28
31
  */
29
- declare function loadOrmOptions(configPath: string, tsconfigPath?: string): Promise<Options>;
32
+ declare function loadOrmOptions(configPath: string, tsconfigPath?: string, loadOptions?: LoadOrmOptionsOptions): Promise<Options>;
30
33
  /**
31
34
  * Renders an error together with its `cause` chain, one cause per line.
32
35
  *
@@ -49,4 +52,4 @@ declare function formatErrorChain(err: unknown): string;
49
52
  declare function formatDiscoveryError(err: unknown): string;
50
53
  declare function writeMarkdownFile(outPath: string, markdown: string): Promise<void>;
51
54
 
52
- export { findNearestTsconfig, formatDiscoveryError, formatErrorChain, loadOrmOptions, toConfigImportSpecifier, writeMarkdownFile };
55
+ export { type LoadOrmOptionsOptions, findNearestTsconfig, formatDiscoveryError, formatErrorChain, loadOrmOptions, toConfigImportSpecifier, writeMarkdownFile };
package/dist/cli.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { Options } from '@mikro-orm/core';
3
3
 
4
+ interface LoadOrmOptionsOptions {
5
+ keepTsxRegistered?: boolean;
6
+ }
4
7
  declare function toConfigImportSpecifier(configPath: string): string;
5
8
  /**
6
9
  * Walks up from the directory of `fromPath` looking for the nearest
@@ -26,7 +29,7 @@ declare function findNearestTsconfig(fromPath: string): string | undefined;
26
29
  * fail with a cryptic `Cannot read properties of undefined` error depending on
27
30
  * which directory the CLI was launched from.
28
31
  */
29
- declare function loadOrmOptions(configPath: string, tsconfigPath?: string): Promise<Options>;
32
+ declare function loadOrmOptions(configPath: string, tsconfigPath?: string, loadOptions?: LoadOrmOptionsOptions): Promise<Options>;
30
33
  /**
31
34
  * Renders an error together with its `cause` chain, one cause per line.
32
35
  *
@@ -49,4 +52,4 @@ declare function formatErrorChain(err: unknown): string;
49
52
  declare function formatDiscoveryError(err: unknown): string;
50
53
  declare function writeMarkdownFile(outPath: string, markdown: string): Promise<void>;
51
54
 
52
- export { findNearestTsconfig, formatDiscoveryError, formatErrorChain, loadOrmOptions, toConfigImportSpecifier, writeMarkdownFile };
55
+ export { type LoadOrmOptionsOptions, findNearestTsconfig, formatDiscoveryError, formatErrorChain, loadOrmOptions, toConfigImportSpecifier, writeMarkdownFile };