@mgamadeus/ddd-web 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/ddd-web-specialist/references/consumer.md +1 -1
- package/CHANGELOG.md +8 -0
- package/dist/{chunk-J2RLNVKK.js → chunk-HVYT2X4V.js} +107 -3
- package/dist/chunk-HVYT2X4V.js.map +1 -0
- package/dist/codegen/cli.js +1 -1
- package/dist/codegen/index.d.ts +7 -0
- package/dist/codegen/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-J2RLNVKK.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/codegen/config.ts","../src/codegen/log.ts","../src/codegen/openapi.ts","../src/codegen/tags.ts","../src/codegen/enhance.ts","../src/codegen/document-endpoints.ts","../src/codegen/spec.ts","../src/codegen/generate.ts","../src/codegen/typescript.ts","../src/codegen/document-models.ts","../src/codegen/endpoints.ts","../src/codegen/files.ts","../src/codegen/format.ts","../src/codegen/models.ts","../src/contract/extensions.ts","../src/codegen/operations.ts","../src/codegen/response-handlers.ts","../src/codegen/multipart.ts","../src/codegen/output.ts","../src/codegen/registry.ts","../src/codegen/repair.ts","../src/codegen/rtk.ts","../src/codegen/module-resolution.ts","../src/codegen/workspace.ts","../src/codegen/link-skills.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { createJiti } from 'jiti';\nimport type { EndpointOptions } from './document-endpoints';\nimport type { ModelOptions } from './document-models';\nimport type { DddEntityExtension, HttpMethod, OpenApiOperation } from './openapi';\n\nexport type { EndpointNamingOperation, EndpointOptions } from './document-endpoints';\nexport type { ModelOptions } from './document-models';\n\n/** Selects operations by HTTP method (optional, case-insensitive) and path (exact string or RegExp). */\nexport interface OperationMatcher {\n method?: Uppercase<HttpMethod> | HttpMethod;\n path: string | RegExp;\n}\n\n/**\n * Classifies operations by whether they change server state, for specs that do not carry\n * `x-ddd-side-effects` yet. Matches on HTTP method and path (exact string or RegExp).\n */\nexport interface SideEffectsOverride extends OperationMatcher {\n sideEffects: boolean;\n /**\n * Force the generated hook kind. Default: a writing GET becomes a mutation, a reading POST becomes a\n * query. `'mutation'` keeps a reading POST a mutation (hook name unchanged) that invalidates nothing.\n */\n endpointType?: 'query' | 'mutation';\n}\n\n/**\n * Sets how an endpoint reads its successful response, for specs whose declared content type is missing or wrong\n * (e.g. an Excel export declared as `application/json`). Wins over content-type detection.\n * - `blob`: `responseHandler: blobResponseHandler`, result type `DddFileResponse` (`{ blob, filename, contentType }`)\n * - `text`: `responseHandler: \"text\"`, result type `string`\n * - `json`: RTK's JSON parsing, no handler (also turns off a detected `text` / `blob`)\n */\nexport interface ResponseHandlerOverride extends OperationMatcher {\n handler: 'blob' | 'text' | 'json';\n}\n\n/**\n * One cache tag a mutation invalidates, as returned by an `invalidation` resolver:\n * - `'Books'`: every cached entry of the tag type (`{ type: 'Books' }`)\n * - `{ type: 'Books', id: 'LIST' }`: a literal id (lists and filters provide `'LIST'`)\n * - `{ type: 'Books', arg: 'bookId' }`: the id read from the endpoint argument by a dotted path\n * (`'bookUpdateRequestDto.book.id'`; `''` = the argument itself, e.g. with `flattenArg`). A path parameter is read\n * as it is; any other path is optional-chained and the tag is left out while the value is `null` / `undefined` (a\n * create without id), because `{ type, id: undefined }` would invalidate the whole tag type.\n */\nexport type InvalidationTag = string | { type: string; id: string | number } | { type: string; arg: string };\n\n/** What an `invalidation` resolver gets for each generated mutation endpoint. */\nexport interface InvalidationOperation {\n /** Endpoint key in the generated api file, e.g. `patchApiAdminLibraryBooks`. */\n key: string;\n /** `exportName` of the api entry. */\n api: string;\n method: Uppercase<HttpMethod>;\n /** OpenAPI path, e.g. `/api/admin/library/books/{bookId}`. */\n path: string;\n /** Cache tag type chosen for the endpoint (entity, operation tag or path segment); `null` when none was found. */\n tag: string | null;\n /** The OpenAPI operation; absent when the endpoint could not be mapped back to one. */\n operation?: OpenApiOperation;\n /** `x-ddd-entity` of the operation, when present. */\n entity?: DddEntityExtension;\n /** Resolved side-effect classification; `false` = the default invalidates nothing. */\n sideEffects: boolean;\n /** Path parameter → dotted path in the endpoint argument (usable as `arg` of an {@link InvalidationTag}). */\n pathArgs: Record<string, string>;\n /** Dotted path of the request body in the endpoint argument (`''` = the argument itself); absent without body. */\n bodyArg?: string;\n /** Tags the generator emits when the resolver returns `undefined`. */\n defaultTags: InvalidationTag[];\n}\n\n/**\n * Overrides the tags a mutation invalidates. Return a list (an empty list invalidates nothing) or `undefined` to keep\n * the default. Called for every generated mutation endpoint.\n */\nexport type InvalidationResolver = (operation: InvalidationOperation) => InvalidationTag[] | undefined;\n\nexport interface HooksOptions {\n queries: boolean;\n lazyQueries: boolean;\n mutations: boolean;\n}\n\n/** One generated API (one OpenAPI document, typically one audience). */\nexport interface SdkApiConfig {\n /** Spec source: http(s) URL or local file path (relative to the config file). */\n schemaFile: string;\n /**\n * Module that exports the RTK base api: a path relative to the config file (e.g. `./src/api/baseApi.ts`)\n * or a bare module specifier used verbatim.\n */\n apiFile: string;\n /** Named export of the base api in `apiFile`. Default `api`. */\n apiImport?: string;\n /** Generated endpoints file, e.g. `./src/api/adminApi.ts`. Tags and enhanced files are written next to it. */\n outputFile: string;\n /** Name used for `--api` selection; also passed to RTK codegen. Default: stem of `outputFile`. */\n exportName?: string;\n hooks?: boolean | HooksOptions;\n /** Prefix stripped from operation tags (e.g. `admin`). Default: stem of `outputFile` without `Api`. */\n audience?: string;\n /**\n * Import specifier of the base api used by the `<stem>Enhanced.ts` file.\n * Default: `apiFile` relative to the output directory (e.g. `./baseApi`).\n */\n baseApiImport?: string;\n /** Overrides `SdkConfig.skipUpdatePostTwins` for this api. */\n skipUpdatePostTwins?: boolean;\n /** Added after the global `sideEffects`; the first match wins, so entries here are checked first. RegExp flags `g` / `y` are ignored for matching. */\n sideEffects?: SideEffectsOverride[];\n /** Added after the global `responseHandlers`; the first match wins, so entries here are checked first. */\n responseHandlers?: ResponseHandlerOverride[];\n /** Checked before the global `invalidation`; the first resolver that returns a list wins. */\n invalidation?: InvalidationResolver;\n /** Any further RTK codegen option (`argSuffix`, `flattenArg`, `endpointOverrides`, `filterEndpoints`, …). */\n [rtkOption: string]: unknown;\n}\n\n/** Optional resolution of a workspace/subdomain value that the config reads from an env variable. */\nexport interface WorkspaceOptions {\n /** Env variable the config file reads, e.g. `DEV_WORKSPACE`. */\n envVar: string;\n /** Files sniffed for a URL whose first host label is the workspace. Default `['.env', '.env.local']`. */\n envFiles?: string[];\n /** Keys looked up in those files. Default: common `*_API_URL` keys. */\n urlKeys?: string[];\n /** Ask on a TTY when nothing else resolves it. Never asks without a TTY. Default `true`. */\n prompt?: boolean;\n}\n\nexport interface SdkConfig {\n apis: SdkApiConfig[];\n /** Directory of generated model files. Default `<dir of first outputFile>/../models`. */\n modelsDir?: string;\n /**\n * Skip the POST twin of an upsert (DDD `#[Update]` serves POST and PATCH): only the PATCH is generated. With\n * `x-ddd-entity` both must be `upsert` of the same entity; without it summary, parameters, request body and\n * responses must be identical. Conflicting annotations never skip. Default `false`.\n */\n skipUpdatePostTwins?: boolean;\n sideEffects?: SideEffectsOverride[];\n /**\n * Response handler per operation, overriding content-type detection (binary 2xx → `blob`, text-only 2xx → `text`).\n * First match wins.\n */\n responseHandlers?: ResponseHandlerOverride[];\n /**\n * Escape hatch for the tags a mutation invalidates (see {@link InvalidationResolver}); `undefined` from the resolver\n * keeps the default. `broadInvalidation` restores the 0.2 behaviour (writes without an identity from `x-ddd-entity`\n * invalidate their whole tag type).\n */\n invalidation?: InvalidationResolver;\n workspace?: WorkspaceOptions;\n /**\n * How the models of the component schemas are written: names and folders as the document writes them, enums as\n * const objects, `| null` beside a nullable `$ref`, the `id` type. Every option is off by default (see\n * {@link ModelOptions}).\n */\n models?: ModelOptions;\n /**\n * How the endpoints and their body argument are named: RTK codegen's names (default), a rule of verb and path, or\n * your own function; the body as `requestBody` (see {@link EndpointOptions}).\n */\n endpoints?: EndpointOptions;\n /** tsconfig used for the final type check. Default `tsconfig.json` next to the config file. */\n tsconfig?: string;\n}\n\nexport function defineConfig(config: SdkConfig): SdkConfig {\n return config;\n}\n\nexport interface LoadedConfig {\n config: SdkConfig;\n configPath: string;\n rootDir: string;\n}\n\n/**\n * Loads `openapi-config.ts` (or .js/.mjs/.cjs) with jiti. Accepts `export default defineConfig({...})`\n * or a named `export const apis = [...]` (plain RTK codegen entries).\n */\nexport async function loadConfig(configPath: string): Promise<LoadedConfig> {\n const absolute = path.resolve(configPath);\n if (!fs.existsSync(absolute)) {\n throw new Error(`Config file not found: ${absolute}`);\n }\n // A fresh instance per load: the config may read env variables at evaluation time.\n const jiti = createJiti(absolute, { moduleCache: false, fsCache: false });\n const mod = (await jiti.import(absolute)) as Record<string, unknown>;\n const config = normalizeConfigModule(mod, absolute);\n return { config, configPath: absolute, rootDir: path.dirname(absolute) };\n}\n\nfunction normalizeConfigModule(mod: Record<string, unknown>, configPath: string): SdkConfig {\n const candidate = (mod.default ?? mod.config ?? mod) as Record<string, unknown> | unknown[];\n if (Array.isArray(candidate)) return { apis: candidate as SdkApiConfig[] };\n if (candidate && typeof candidate === 'object' && Array.isArray(candidate.apis)) {\n return candidate as unknown as SdkConfig;\n }\n if (Array.isArray(mod.apis)) return { apis: mod.apis as SdkApiConfig[] };\n throw new Error(\n `${configPath} must export a config (\\`export default defineConfig({ apis: [...] })\\`) or \\`export const apis = [...]\\`.`,\n );\n}\n\nexport interface ResolvedApi {\n config: SdkApiConfig;\n /** Stem of the output file, e.g. `adminApi`. */\n stem: string;\n exportName: string;\n audience: string;\n schemaSource: string;\n outputFile: string;\n apiFile: string;\n outputDir: string;\n skipUpdatePostTwins: boolean;\n sideEffects: SideEffectsOverride[];\n responseHandlers: ResponseHandlerOverride[];\n /** Api entry resolver first, then the global one. */\n invalidation: InvalidationResolver[];\n}\n\nexport function resolveApis(loaded: LoadedConfig): ResolvedApi[] {\n const { config, rootDir } = loaded;\n if (!Array.isArray(config.apis) || config.apis.length === 0) {\n throw new Error(`No apis configured in ${loaded.configPath}.`);\n }\n if (config.models?.enums === 'const' && config.models.naming !== 'document') {\n throw new Error(`models.enums 'const' needs models.naming 'document' (${loaded.configPath}).`);\n }\n return config.apis.map((entry, index) => {\n for (const key of ['schemaFile', 'apiFile', 'outputFile'] as const) {\n if (typeof entry[key] !== 'string' || entry[key] === '') {\n throw new Error(`apis[${index}].${key} must be a non-empty string.`);\n }\n }\n const outputFile = path.resolve(rootDir, entry.outputFile);\n const stem = path.basename(outputFile).replace(/\\.[cm]?[jt]sx?$/, '');\n return {\n config: entry,\n stem,\n exportName: typeof entry.exportName === 'string' ? entry.exportName : stem,\n audience: entry.audience ?? stem.replace(/Api$/, ''),\n schemaSource: isUrl(entry.schemaFile) ? entry.schemaFile : path.resolve(rootDir, entry.schemaFile),\n outputFile,\n apiFile: isPathLike(entry.apiFile) ? path.resolve(rootDir, entry.apiFile) : entry.apiFile,\n outputDir: path.dirname(outputFile),\n skipUpdatePostTwins: entry.skipUpdatePostTwins ?? config.skipUpdatePostTwins ?? false,\n sideEffects: [...(entry.sideEffects ?? []), ...(config.sideEffects ?? [])],\n responseHandlers: [...(entry.responseHandlers ?? []), ...(config.responseHandlers ?? [])],\n invalidation: [entry.invalidation, config.invalidation].filter(\n (resolver): resolver is InvalidationResolver => typeof resolver === 'function',\n ),\n };\n });\n}\n\nexport function resolveModelsDir(loaded: LoadedConfig, apis: ResolvedApi[]): string {\n if (loaded.config.modelsDir) return path.resolve(loaded.rootDir, loaded.config.modelsDir);\n const first = apis[0];\n if (!first) throw new Error('No apis configured.');\n for (const api of apis) {\n if (api.outputDir !== first.outputDir) {\n throw new Error(\n `All apis must share one output directory when modelsDir is not set (got ${api.outputFile} next to ${first.outputFile}).`,\n );\n }\n }\n return path.resolve(first.outputDir, '..', 'models');\n}\n\n/** Relative or absolute file path (as opposed to a bare module specifier such as `@/api/baseApi`). */\nexport function isPathLike(value: string): boolean {\n return value.startsWith('.') || path.isAbsolute(value);\n}\n\nexport function isUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value);\n}\n","export interface Logger {\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n}\n\nconst PREFIX = '[ddd-web-sdk]';\n\nexport const consoleLogger: Logger = {\n info: (message) => console.log(`${PREFIX} ${message}`),\n warn: (message) => console.warn(`${PREFIX} ${message}`),\n error: (message) => console.error(`${PREFIX} ${message}`),\n};\n\nexport const silentLogger: Logger = { info: () => {}, warn: () => {}, error: () => {} };\n\n/** Thrown for expected aborts (bad spec, bad config); the CLI prints the message without a stack. */\nexport class SdkGenerationError extends Error {\n override name = 'SdkGenerationError';\n}\n","/** Minimal OpenAPI 3 shapes the codegen reads. Unknown keys are passed through untouched. */\nimport type { DddContractInfo, DddEntityInfo, DddOperationExtensions, HttpMethod } from '../contract/extensions';\n\nexport type { DddEntityAction, HttpMethod } from '../contract/extensions';\n\nexport const HTTP_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const satisfies readonly HttpMethod[];\n\n/**\n * `info.x-ddd-contract` as read from a document: the contract types from `contract`, tolerant of a missing `ddd`\n * version (the codegen only needs the contract number).\n */\nexport type DddContractInfoInput = Pick<DddContractInfo, 'contract'> & Partial<Pick<DddContractInfo, 'ddd'>>;\n\n/** `x-ddd-entity` as read from a document: {@link DddEntityInfo}, tolerant of a missing `derived` flag. */\nexport type DddEntityExtension = Omit<DddEntityInfo, 'derived'> & Partial<Pick<DddEntityInfo, 'derived'>>;\n\nexport interface OpenApiOperation extends Omit<DddOperationExtensions, 'x-ddd-entity'> {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: unknown[];\n requestBody?: unknown;\n responses?: Record<string, { description?: string; content?: Record<string, unknown> } | undefined>;\n 'x-ddd-entity'?: DddEntityExtension;\n [key: string]: unknown;\n}\n\nexport type OpenApiPathItem = Partial<Record<HttpMethod, OpenApiOperation>> & Record<string, unknown>;\n\nexport interface OpenApiTag {\n name: string;\n description?: string;\n}\n\nexport interface OpenApiDocument {\n openapi?: string;\n info?: { title?: string; version?: string; 'x-ddd-contract'?: DddContractInfoInput; [key: string]: unknown };\n tags?: OpenApiTag[];\n paths?: Record<string, OpenApiPathItem | undefined>;\n components?: { schemas?: Record<string, unknown>; [key: string]: unknown };\n [key: string]: unknown;\n}\n\nexport interface OperationRef {\n method: HttpMethod;\n path: string;\n operation: OpenApiOperation;\n}\n\nexport function listOperations(doc: OpenApiDocument): OperationRef[] {\n const result: OperationRef[] = [];\n for (const [path, item] of Object.entries(doc.paths ?? {})) {\n if (!item) continue;\n for (const method of HTTP_METHODS) {\n const operation = item[method];\n if (operation) result.push({ method, path, operation });\n }\n }\n return result;\n}\n\nexport function operationKey(method: string, path: string): string {\n return `${method.toUpperCase()} ${path}`;\n}\n","import type { OpenApiDocument } from './openapi';\nimport { listOperations } from './openapi';\n\nexport const GENERATED_HEADER = '// AUTO-GENERATED by @mgamadeus/ddd-web (ddd-web-sdk) — do not edit manually.';\n\n/**\n * Normalises an operation tag into a PascalCase identifier, stripping the audience prefix word.\n * \"Admin Google Places\" (admin) → \"GooglePlaces\"; \"Admin AI Models\" → \"AIModels\"; \"BikeTypes \" → \"BikeTypes\"\n */\nexport function normalizeTag(tag: string, audiencePrefix?: string): string {\n const parts = tag.trim().split(/\\s+/);\n const filtered =\n audiencePrefix && parts[0]?.toLowerCase() === audiencePrefix.toLowerCase() ? parts.slice(1) : parts;\n return filtered\n .filter(Boolean)\n .map((part) => {\n if (part === part.toUpperCase() && part.length > 1) return part;\n return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();\n })\n .join('');\n}\n\nexport function collectOperationTags(doc: OpenApiDocument, audience: string): string[] {\n const raw = new Set<string>();\n for (const { operation } of listOperations(doc)) {\n for (const tag of operation.tags ?? []) raw.add(tag);\n }\n return [...new Set([...raw].map((tag) => normalizeTag(tag, audience)).filter(Boolean))].sort();\n}\n\n/**\n * Cache tag for an `x-ddd-entity` schema. Prefers an existing operation tag named after the entity's\n * namespace folder or its plural (`…Entities.BikeTypes.BikeType` → `BikeTypes`), so annotated and\n * unannotated operations of one entity share a tag.\n */\nexport function entityTag(schema: string, knownTags: Map<string, string>): string {\n const parts = schema.replace('#/components/schemas/', '').split('.');\n const leaf = parts[parts.length - 1] ?? schema;\n const folder = parts.length > 1 ? parts[parts.length - 2] : undefined;\n const candidates = [folder, `${leaf}s`, leaf].filter((value): value is string => !!value);\n for (const candidate of candidates) {\n const known = knownTags.get(normalizeTag(candidate).toLowerCase());\n if (known) return known;\n }\n return normalizeTag(folder && folder !== 'Entities' ? folder : leaf);\n}\n\nexport function tagFileNames(stem: string): { constName: string; typeName: string } {\n return {\n constName: `${stem}TagTypes`,\n typeName: `${stem.charAt(0).toUpperCase()}${stem.slice(1)}TagType`,\n };\n}\n\nexport function renderTagsFile(stem: string, tags: string[]): string {\n const { constName, typeName } = tagFileNames(stem);\n return [\n GENERATED_HEADER,\n '',\n `export const ${constName} = [`,\n ...tags.map((tag) => ` '${tag}',`),\n '] as const;',\n '',\n `export type ${typeName} = (typeof ${constName})[number];`,\n '',\n ].join('\\n');\n}\n","import type { InvalidationOperation, InvalidationResolver, InvalidationTag } from './config';\nimport type { EndpointInfo } from './endpoints';\nimport { type Logger, SdkGenerationError } from './log';\nimport type { HttpMethod, OpenApiDocument, OpenApiOperation } from './openapi';\nimport { operationKey } from './openapi';\nimport type { OperationIndex, OperationInfo } from './operations';\nimport { entityTag, GENERATED_HEADER, normalizeTag } from './tags';\n\n/** kebab-case URL segment → PascalCase; segments that already contain capitals stay as they are. */\nfunction segmentToPascal(segment: string): string {\n if (!segment) return '';\n if (/[A-Z]/.test(segment)) return segment;\n return segment\n .split('-')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('');\n}\n\n/** Fallback when the operation has no matching tag: the last path segment that names a known tag. */\nfunction tagFromPath(path: string, lookup: Map<string, string>): string | null {\n let matched: string | null = null;\n for (const segment of path.replace(/\\{[^}]+\\}/g, '').split('/').filter(Boolean)) {\n matched = lookup.get(segmentToPascal(segment).toLowerCase()) ?? matched;\n }\n return matched;\n}\n\nfunction tagFromOperation(info: OperationInfo | undefined, audience: string, lookup: Map<string, string>): string | null {\n for (const raw of info?.operation.tags ?? []) {\n const found = lookup.get(normalizeTag(raw, audience).toLowerCase());\n if (found) return found;\n }\n return null;\n}\n\n/** Name of the placeholder that ends the path (`/books/{bookId}` → `bookId`). */\nfunction trailingPlaceholder(path: string): string | null {\n return path.match(/\\{([^}]+)\\}\\/?$/)?.[1] ?? null;\n}\n\n/** `/<collection>/{id}` where the collection segment names the tag → single entity; otherwise a filter arg. */\nfunction isPrimaryEntityPath(path: string, tag: string): boolean {\n const segments = path\n .replace(/\\{[^}]+\\}\\/?$/, '')\n .split('/')\n .filter(Boolean);\n const last = segments[segments.length - 1];\n return last !== undefined && segmentToPascal(last).toLowerCase() === tag.toLowerCase();\n}\n\ntype TagKey = 'providesTags' | 'invalidatesTags';\ninterface TagExpression {\n key: TagKey;\n line: string;\n}\n\nconst list = (tag: string): string => `{ type: '${tag}' as const, id: 'LIST' }`;\n/** `accessor` reads the id from the endpoint argument, e.g. `arg.bookId` (or `arg` with `flattenArg`). */\nconst byArg = (tag: string, accessor: string): string => `{ type: '${tag}' as const, id: ${accessor} }`;\nconst withArg = (items: string): string => `(_result: unknown, _error: unknown, arg: any) => [${items}]`;\n\n/** Provided tags from `x-ddd-entity`: a query provides by its path identity, otherwise LIST. */\nfunction entityProvidesExpression(endpoint: EndpointInfo, info: OperationInfo, tag: string): TagExpression {\n const identity = info.entity?.identity?.startsWith('path:') ? info.entity.identity.slice('path:'.length) : null;\n const pathIdentity = identity ? (endpoint.pathArgs[identity] ?? null) : null;\n if (pathIdentity && info.entity?.action !== 'list') {\n return { key: 'providesTags', line: withArg(byArg(tag, pathIdentity)) };\n }\n return { key: 'providesTags', line: `[${list(tag)}]` };\n}\n\n/** Path heuristic: GET single (`/<collection>/{id}`) → provides by id; list / filter → provides LIST. */\nfunction heuristicProvidesExpression(endpoint: EndpointInfo, tag: string): TagExpression {\n const trailing = trailingPlaceholder(endpoint.path);\n const single = trailing !== null && isPrimaryEntityPath(endpoint.path, tag) ? (endpoint.pathArgs[trailing] ?? null) : null;\n return single\n ? { key: 'providesTags', line: withArg(byArg(tag, single)) }\n : { key: 'providesTags', line: `[${list(tag)}]` };\n}\n\n// ── invalidation ────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst DOTTED_PATH = /^([A-Za-z_$][A-Za-z0-9_$]*(\\.[A-Za-z_$][A-Za-z0-9_$]*)*)?$/;\n\n/** `arg.foo.bar` → `foo.bar`; `arg` → `''`. */\nfunction relativeAccessor(accessor: string): string | null {\n if (accessor === 'arg') return '';\n return accessor.startsWith('arg.') && DOTTED_PATH.test(accessor.slice(4)) ? accessor.slice(4) : null;\n}\n\nfunction joinPath(base: string, rest: string): string {\n return [base, rest].filter(Boolean).join('.');\n}\n\nconst listTag = (type: string): InvalidationTag => ({ type, id: 'LIST' });\nconst argTag = (type: string, arg: string): InvalidationTag => ({ type, arg });\n\n/** Lower-cased singular candidates of a tag (`Books` → `book`, `Categories` → `category`, `Media` → `media`). */\nfunction singularForms(tag: string): string[] {\n const lower = tag.toLowerCase();\n const forms = new Set([lower]);\n if (lower.endsWith('ies')) forms.add(`${lower.slice(0, -3)}y`);\n if (lower.endsWith('es')) forms.add(lower.slice(0, -2));\n if (lower.endsWith('s')) forms.add(lower.slice(0, -1));\n return [...forms];\n}\n\n/**\n * The path parameter that identifies an entity of `tag`, or null:\n * - named after the tag's entity (`{bookId}` for `Books`), anywhere in the path — also with an action\n * suffix (`/books/{bookId}/publish`);\n * - otherwise a parameter right after the tag's collection segment that does not name another entity\n * (`/books/{id}`, `/books/{slug}`, but not `/books/{authorId}/…`).\n * The last qualifying parameter wins.\n */\nexport function identityPathParameter(path: string, tag: string): string | null {\n const singulars = singularForms(tag);\n const segments = path.split('/').filter(Boolean);\n let found: string | null = null;\n segments.forEach((segment, index) => {\n const name = segment.match(/^\\{([^}]+)\\}$/)?.[1];\n if (!name) return;\n const idMatch = name.match(/^(.+?)(Id|ID|_id)$/);\n if (idMatch && singulars.includes(idMatch[1]!.toLowerCase())) {\n found = name;\n return;\n }\n const previous = segments[index - 1];\n const namesOtherEntity = idMatch !== null;\n if (!namesOtherEntity && previous && !previous.startsWith('{') && segmentToPascal(previous).toLowerCase() === tag.toLowerCase()) {\n found = name;\n }\n });\n return found;\n}\n\ntype JsonSchema = {\n $ref?: string;\n type?: string;\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema;\n allOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n anyOf?: JsonSchema[];\n content?: Record<string, { schema?: JsonSchema } | undefined>;\n};\n\nconst SCHEMA_PREFIX = '#/components/schemas/';\n\n/** Schema name referenced by a schema (directly or as the single member of allOf / oneOf / anyOf). */\nfunction referencedName(schema: JsonSchema | undefined): string | null {\n if (!schema) return null;\n if (typeof schema.$ref === 'string' && schema.$ref.startsWith(SCHEMA_PREFIX)) return schema.$ref.slice(SCHEMA_PREFIX.length);\n for (const key of ['allOf', 'oneOf', 'anyOf'] as const) {\n const members = (schema[key] ?? []).filter((member) => member && !(member as { type?: string }).type?.includes('null'));\n if (members.length === 1) return referencedName(members[0]);\n }\n return null;\n}\n\nfunction schemaByName(doc: OpenApiDocument, name: string): JsonSchema | undefined {\n return (doc.components?.schemas as Record<string, JsonSchema> | undefined)?.[name];\n}\n\n/** The request body schema of an operation (first content type with a schema; `#/components/requestBodies` refs resolved). */\nfunction requestBodySchema(doc: OpenApiDocument, operation: OpenApiOperation): JsonSchema | undefined {\n let body = operation.requestBody as JsonSchema | undefined;\n if (body?.$ref?.startsWith('#/components/requestBodies/')) {\n body = (doc.components?.requestBodies as Record<string, JsonSchema> | undefined)?.[body.$ref.slice('#/components/requestBodies/'.length)];\n }\n for (const media of Object.values(body?.content ?? {})) {\n if (media?.schema) return media.schema;\n }\n return undefined;\n}\n\n/**\n * Dotted path of the identity inside the request body, or null: the body is an entity of `tag` with an `id`\n * (`id`), or exactly one body property references the tag's entities and it is a single entity with an `id`\n * (`book.id` for `{ book: Book }`). A body that also carries a set or a second entity of the tag (merge, batch) has no\n * single identity.\n */\nexport function identityBodyPath(doc: OpenApiDocument, operation: OpenApiOperation, tag: string, lookup: Map<string, string>): string | null {\n const schema = requestBodySchema(doc, operation);\n if (!schema) return null;\n const isTag = (name: string): boolean => entityTag(name, lookup).toLowerCase() === tag.toLowerCase();\n const hasId = (name: string): boolean => !!schemaByName(doc, name)?.properties?.id;\n const bodyName = referencedName(schema);\n if (bodyName && isTag(bodyName) && hasId(bodyName)) return 'id';\n const resolved = bodyName ? schemaByName(doc, bodyName) : schema;\n let references = 0;\n let candidate: string | null = null;\n for (const [property, propertySchema] of Object.entries(resolved?.properties ?? {})) {\n const single = referencedName(propertySchema);\n const element = single ? null : referencedName(propertySchema?.items);\n const name = single ?? element;\n if (!name || !isTag(name)) continue;\n references++;\n if (single && hasId(single) && IDENTIFIER.test(property)) candidate = property;\n }\n return references === 1 && candidate ? `${candidate}.id` : null;\n}\n\n/** Tags from `x-ddd-entity` (authoritative): upsert / delete invalidate the identity + LIST, other writes the whole tag. */\nfunction entityInvalidation(endpoint: EndpointInfo, info: OperationInfo, tag: string): InvalidationTag[] {\n const action = info.entity?.action;\n const identity = info.entity?.identity ?? '';\n if (action === 'upsert' || action === 'delete') {\n if (identity.startsWith('path:')) {\n const accessor = endpoint.pathArgs[identity.slice('path:'.length)];\n const relative = accessor !== undefined ? relativeAccessor(accessor) : null;\n if (relative !== null) return [argTag(tag, relative), listTag(tag)];\n }\n if (identity.startsWith('body:') && endpoint.bodyArg !== undefined) {\n const body = relativeAccessor(endpoint.bodyArg);\n const inner = identity.slice('body:'.length);\n if (body !== null && DOTTED_PATH.test(inner)) return [listTag(tag), argTag(tag, joinPath(body, inner))];\n }\n }\n return [listTag(tag), tag];\n}\n\n/**\n * Identity heuristic (no `x-ddd-entity`): a path parameter naming the entity → the entity + LIST; else the entity\n * property of the request body (`<entity>.id`) → LIST + the entity when the body carries an id (a create without id\n * only invalidates LIST); else no identity is known → LIST + the whole tag type.\n */\nfunction heuristicInvalidation(endpoint: EndpointInfo, info: OperationInfo | undefined, tag: string, doc: OpenApiDocument, lookup: Map<string, string>): InvalidationTag[] {\n const parameter = identityPathParameter(endpoint.path, tag);\n const accessor = parameter ? endpoint.pathArgs[parameter] : undefined;\n const relative = accessor !== undefined ? relativeAccessor(accessor) : null;\n if (relative !== null) return [argTag(tag, relative), listTag(tag)];\n if (info && endpoint.bodyArg !== undefined) {\n const body = relativeAccessor(endpoint.bodyArg);\n const inner = identityBodyPath(doc, info.operation, tag, lookup);\n if (body !== null && inner) return [listTag(tag), argTag(tag, joinPath(body, inner))];\n }\n return [listTag(tag), tag];\n}\n\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\n/** Validates a resolver result; returns the tag types it uses. */\nfunction checkTags(tags: unknown, key: string): InvalidationTag[] {\n if (!Array.isArray(tags)) throw new SdkGenerationError(`invalidation for ${key} must return an array or undefined.`);\n for (const tag of tags as unknown[]) {\n const type = typeof tag === 'string' ? tag : (tag as { type?: unknown } | null)?.type;\n if (typeof type !== 'string' || type === '') {\n throw new SdkGenerationError(`invalidation for ${key}: every tag needs a non-empty type (got ${JSON.stringify(tag)}).`);\n }\n if (typeof tag === 'object') {\n const candidate = tag as { id?: unknown; arg?: unknown };\n const hasId = typeof candidate.id === 'string' || typeof candidate.id === 'number';\n const hasArg = typeof candidate.arg === 'string' && DOTTED_PATH.test(candidate.arg);\n if (hasId === hasArg) {\n throw new SdkGenerationError(\n `invalidation for ${key}: tag ${JSON.stringify(tag)} needs either an id (string / number) or an arg (dotted path).`,\n );\n }\n }\n }\n return tags as InvalidationTag[];\n}\n\n/** Helper emitted into the enhanced file for ids that may be absent (body identities). */\nconst ID_HELPER = 'tagWithId';\nconst ID_HELPER_SOURCE = [\n '// `{ type, id }` only when the id is known: a tag with `id: undefined` would invalidate every entry of the type.',\n `const ${ID_HELPER} = <T extends string>(type: T, id: unknown): Array<{ type: T; id: string | number }> =>`,\n \" typeof id === 'string' || typeof id === 'number' ? [{ type, id }] : [];\",\n];\n\n/** Renders invalidation tags; tags that read the argument make it a function. */\nfunction renderInvalidation(tags: InvalidationTag[], endpoint: EndpointInfo): string {\n const pathArgs = new Set(Object.values(endpoint.pathArgs).map(relativeAccessor));\n let readsArg = false;\n const items = tags.map((tag) => {\n if (typeof tag === 'string') return `{ type: ${quote(tag)} as const }`;\n if ('id' in tag) return `{ type: ${quote(tag.type)} as const, id: ${typeof tag.id === 'number' ? tag.id : quote(tag.id)} }`;\n readsArg = true;\n if (pathArgs.has(tag.arg)) return `{ type: ${quote(tag.type)} as const, id: ${tag.arg === '' ? 'arg' : `arg.${tag.arg}`} }`;\n const optional = tag.arg === '' ? 'arg' : `arg?.${tag.arg.split('.').join('?.')}`;\n return `...${ID_HELPER}(${quote(tag.type)} as const, ${optional})`;\n });\n return readsArg ? withArg(items.join(', ')) : `[${items.join(', ')}]`;\n}\n\n/** Tag types named by a tag list. */\nfunction tagTypes(tags: InvalidationTag[]): string[] {\n return tags.map((tag) => (typeof tag === 'string' ? tag : tag.type));\n}\n\n/**\n * `invalidation` resolver that restores the 0.2 default: writes without an identity from `x-ddd-entity` (a path\n * identity on an upsert / delete) invalidate LIST plus their whole tag type instead of the derived identity.\n * `defineConfig({ invalidation: broadInvalidation, … })`.\n */\nexport const broadInvalidation: InvalidationResolver = (operation) => {\n if (!operation.tag || !operation.sideEffects) return undefined;\n const entity = operation.entity;\n if (entity?.identity?.startsWith('path:') && (entity.action === 'upsert' || entity.action === 'delete')) return undefined;\n return [{ type: operation.tag, id: 'LIST' }, operation.tag];\n};\n\nexport interface EnhanceInput {\n stem: string;\n /** `exportName` of the api entry (passed to `invalidation` resolvers). */\n apiName?: string;\n apiModuleImport: string;\n baseApiImport: string;\n baseApiName: string;\n audience: string;\n endpoints: EndpointInfo[];\n index: OperationIndex;\n /** The spec (request body schemas for the identity heuristic). */\n doc?: OpenApiDocument;\n /** Operation tags of the whole spec (normalised, sorted): the names a generated endpoint's tag is matched to. */\n operationTags: string[];\n /** Resolvers checked in order; the first that returns a list wins. */\n invalidation?: InvalidationResolver[];\n logger: Logger;\n}\n\nexport interface EnhanceResult {\n source: string;\n /** Tags of the generated endpoints (operation tags, `x-ddd-entity`, `invalidation`), sorted. */\n tagTypes: string[];\n}\n\nexport function buildEnhancedEndpoints(input: EnhanceInput): EnhanceResult {\n const { endpoints, index, audience, logger } = input;\n const doc: OpenApiDocument = input.doc ?? {};\n const resolvers = input.invalidation ?? [];\n const lookup = new Map(input.operationTags.map((tag) => [tag.toLowerCase(), tag]));\n // The tag list holds the tags of the endpoints that are generated: an operation left out by `filterEndpoints` or\n // twin skipping adds none, although its tag stays known for naming (`lookup`).\n const allTags = new Set<string>();\n const used = new Set<string>();\n const lines: string[] = [];\n let skipped = 0;\n let urlFallbacks = 0;\n let identities = 0;\n let wholeType = 0;\n\n for (const endpoint of endpoints) {\n const info = index.byKey.get(operationKey(endpoint.method, endpoint.path));\n for (const raw of info?.operation.tags ?? []) {\n const known = lookup.get(normalizeTag(raw, audience).toLowerCase());\n if (known) allTags.add(known);\n }\n let tag: string | null;\n if (info?.entity) {\n tag = entityTag(info.entity.schema, lookup);\n allTags.add(tag);\n lookup.set(tag.toLowerCase(), tag);\n } else {\n tag = tagFromOperation(info, audience, lookup);\n if (!tag) {\n tag = tagFromPath(endpoint.path, lookup);\n if (tag) urlFallbacks++;\n }\n if (tag) allTags.add(tag);\n }\n\n let expression: TagExpression | null = null;\n if (endpoint.buildType === 'query') {\n if (tag) expression = info?.entity ? entityProvidesExpression(endpoint, info, tag) : heuristicProvidesExpression(endpoint, tag);\n } else {\n let defaultTags: InvalidationTag[] = [];\n if (tag && (!info || info.sideEffects)) {\n defaultTags = info?.entity ? entityInvalidation(endpoint, info, tag) : heuristicInvalidation(endpoint, info, tag, doc, lookup);\n }\n let tags = defaultTags;\n if (resolvers.length > 0) {\n const operation: InvalidationOperation = {\n key: endpoint.key,\n api: input.apiName ?? input.stem,\n method: endpoint.method.toUpperCase() as Uppercase<HttpMethod>,\n path: endpoint.path,\n tag,\n ...(info ? { operation: info.operation } : {}),\n ...(info?.entity ? { entity: info.entity } : {}),\n sideEffects: info?.sideEffects ?? true,\n pathArgs: Object.fromEntries(\n Object.entries(endpoint.pathArgs).flatMap(([name, accessor]) => {\n const relative = relativeAccessor(accessor);\n return relative === null ? [] : [[name, relative]];\n }),\n ),\n ...(endpoint.bodyArg !== undefined && relativeAccessor(endpoint.bodyArg) !== null\n ? { bodyArg: relativeAccessor(endpoint.bodyArg)! }\n : {}),\n defaultTags: defaultTags.map((entry) => (typeof entry === 'string' ? entry : { ...entry })),\n };\n for (const resolver of resolvers) {\n const result = resolver(operation);\n if (result !== undefined) {\n tags = checkTags(result, endpoint.key);\n break;\n }\n }\n }\n if (tag || tags.length > 0) {\n expression = { key: 'invalidatesTags', line: renderInvalidation(tags, endpoint) };\n for (const type of tagTypes(tags)) {\n used.add(type);\n allTags.add(type);\n }\n if (tags.some((entry) => typeof entry !== 'string' && 'arg' in entry)) identities++;\n else if (tags.some((entry) => typeof entry === 'string')) wholeType++;\n }\n }\n if (!expression) {\n logger.warn(`No tag for ${endpoint.key} (${endpoint.url}) — no cache tags generated.`);\n skipped++;\n continue;\n }\n lines.push(` ${endpoint.key}: {`, ` ${expression.key}: ${expression.line},`, ' },');\n if (tag) used.add(tag);\n }\n\n const varName = `${input.stem}Enhanced`;\n const source = [\n GENERATED_HEADER,\n '',\n `// Import ${input.stem} first (side effect: registers its endpoints on the base api).`,\n `import '${input.apiModuleImport}';`,\n `import { ${input.baseApiName} } from '${input.baseApiImport}';`,\n '',\n ...(lines.some((line) => line.includes(`...${ID_HELPER}(`)) ? [...ID_HELPER_SOURCE, ''] : []),\n '// enhanceEndpoints mutates the endpoint definitions in place: import this file once (e.g. in the store)',\n `// and keep using the hooks from ${input.stem} — they pick up the tags.`,\n `export const ${varName} = ${input.baseApiName}.enhanceEndpoints({`,\n ` addTagTypes: [${[...used].sort().map((tag) => quote(tag)).join(', ')}],`,\n ' endpoints: {',\n ...lines,\n ' },',\n '});',\n '',\n ].join('\\n');\n\n logger.info(\n ` enhanced ${endpoints.length - skipped} endpoints (${skipped} without tag, ${urlFallbacks} via URL fallback, ${used.size} tag types; ` +\n `${identities} writes by identity, ${wholeType} invalidate a whole tag type)`,\n );\n return { source, tagTypes: [...allTags].sort() };\n}\n","import { SdkGenerationError } from './log';\nimport { HTTP_METHODS, type HttpMethod, type OpenApiDocument, type OpenApiOperation } from './openapi';\n\n/** One operation an endpoint name is chosen for. */\nexport interface EndpointNamingOperation {\n method: HttpMethod;\n /** OpenAPI path, e.g. `/api/client/ai/conversations/{locationId}/list`. */\n path: string;\n operation: OpenApiOperation;\n}\n\n/** How the generator names the endpoints and their body argument. Every option is off by default. */\nexport interface EndpointOptions {\n /**\n * The endpoint names (and so the hook names):\n * - `rtk` (default): RTK codegen's names (the operation's `operationId`, else verb and path).\n * - `path`: a pure function of verb and path — the prefix (`stripPathPrefix`) is cut; every `{param}/` is cut out\n * and only the LAST one cut is kept; the rest is split on `/ _ - .`, each piece capitalised, the verb in front,\n * the first letter lowered; `By<LastInner>` is appended; a trailing `{param}` becomes `By<Param>` where it\n * stands. `POST /api/client/ai/conversations/{locationId}/purposed/{purposeName}` →\n * `postClientAiConversationsPurposedByPurposeNameByLocationId`.\n * - a function returning the name (a JavaScript identifier) per operation.\n */\n naming?: 'rtk' | 'path' | ((operation: EndpointNamingOperation) => string);\n /** The prefix `naming: 'path'` cuts from a path. Default `/^\\/(?:app\\/)?api(?=\\/)/` (`/api` or `/app/api`). */\n stripPathPrefix?: string | RegExp;\n /**\n * `requestBody`: the request body is the argument's `requestBody` property, whatever its schema is called (a DTO\n * class that moves keeps the name). `rtk` (default): the camel-cased schema name.\n */\n bodyArg?: 'rtk' | 'requestBody';\n}\n\nexport const REQUEST_BODY_ARG = 'requestBody';\n\nconst DEFAULT_STRIP_PATH_PREFIX = /^\\/(?:app\\/)?api(?=\\/)/;\n\nconst upperFirst = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n\n/** The endpoint name of `naming: 'path'` (see {@link EndpointOptions.naming}). */\nexport function buildEndpointNameFromPath(method: string, path: string, stripPathPrefix: string | RegExp = DEFAULT_STRIP_PATH_PREFIX): string {\n const stripped =\n typeof stripPathPrefix === 'string' ? (path.startsWith(stripPathPrefix) ? path.slice(stripPathPrefix.length) : path) : path.replace(stripPathPrefix, '');\n let lastInnerParameter: string | null = null;\n const withoutInnerParameters = stripped.replace(/\\{([^}]+)\\}\\//g, (_, parameter: string) => {\n lastInnerParameter = parameter;\n return '';\n });\n const pieces = withoutInnerParameters\n .split(/[/_.-]/)\n .filter((piece) => piece !== '')\n .map(upperFirst)\n .join('');\n const name = `${method.toLowerCase()}${pieces}${lastInnerParameter ? `By${upperFirst(lastInnerParameter)}` : ''}`;\n return name.replace(/\\{([^}]+)\\}/g, (_, parameter: string) => `By${upperFirst(parameter)}`);\n}\n\n/**\n * The document RTK codegen reads, with the endpoint options applied: the chosen name as each operation's\n * `operationId`, and the request body schemas titled `requestBody`. The document passed in stays unchanged. Two\n * operations with the same name are an error naming both.\n */\nexport function prepareDocumentForEndpoints(\n doc: OpenApiDocument,\n options: EndpointOptions,\n): { doc: OpenApiDocument; endpointNamesByPlaceholder: Map<string, string> } {\n const naming = options.naming ?? 'rtk';\n const bodyArg = options.bodyArg ?? 'rtk';\n const endpointNamesByPlaceholder = new Map<string, string>();\n if (naming === 'rtk' && bodyArg === 'rtk') return { doc, endpointNamesByPlaceholder };\n const prepared = structuredClone(doc) as OpenApiDocument;\n const pathByName = new Map<string, string>();\n for (const [path, item] of Object.entries(prepared.paths ?? {})) {\n if (!item) continue;\n for (const method of HTTP_METHODS) {\n const operation = item[method];\n if (!operation) continue;\n if (naming !== 'rtk') {\n const name =\n naming === 'path' ? buildEndpointNameFromPath(method, path, options.stripPathPrefix) : naming({ method, path, operation });\n if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {\n throw new SdkGenerationError(`endpoints.naming: \"${name}\" (${method.toUpperCase()} ${path}) is no identifier.`);\n }\n const other = pathByName.get(name);\n if (other !== undefined) {\n throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path} are both named \"${name}\".`);\n }\n pathByName.set(name, `${method.toUpperCase()} ${path}`);\n // RTK codegen camel-cases an operationId again (`…LegacyDB` → `…LegacyDb`): a placeholder it keeps as it is\n // goes in, and the name replaces it in the generated code ({@link restoreEndpointNames})\n const placeholder = `dddEndpoint${endpointNamesByPlaceholder.size}`;\n endpointNamesByPlaceholder.set(placeholder, name);\n operation.operationId = placeholder;\n }\n if (bodyArg === REQUEST_BODY_ARG) titleRequestBody(operation);\n }\n }\n return { doc: prepared, endpointNamesByPlaceholder };\n}\n\n/**\n * The generated code and the operation of each endpoint with the endpoint names in place of their placeholders: the\n * endpoint key (`dddEndpoint3`), and capitalised inside identifiers (`useDddEndpoint3Query`, `DddEndpoint3ApiArg`).\n */\nexport function restoreEndpointNames<Location>(\n code: string,\n locations: Map<string, Location>,\n endpointNamesByPlaceholder: ReadonlyMap<string, string>,\n): { code: string; locations: Map<string, Location> } {\n if (endpointNamesByPlaceholder.size === 0) return { code, locations };\n const restore = (text: string): string =>\n text.replace(/(d|D)ddEndpoint(\\d+)(?!\\d)/g, (match, first: string, number: string) => {\n const name = endpointNamesByPlaceholder.get(`dddEndpoint${number}`);\n if (name === undefined) return match;\n return first === 'D' ? upperFirst(name) : name;\n });\n const restoredLocations = new Map<string, Location>();\n for (const [key, location] of locations) restoredLocations.set(restore(key), location);\n return { code: restore(code), locations: restoredLocations };\n}\n\n/** RTK codegen names the body argument after a body schema's title when the schema is no `$ref`. */\nfunction titleRequestBody(operation: OpenApiOperation): void {\n const content = (operation.requestBody as { content?: Record<string, { schema?: Record<string, unknown> }> } | undefined)?.content;\n for (const media of Object.values(content ?? {})) {\n const schema = media?.schema;\n if (!schema) continue;\n media.schema = typeof schema.$ref === 'string' ? { title: REQUEST_BODY_ARG, allOf: [{ $ref: schema.$ref }] } : { ...schema, title: REQUEST_BODY_ARG };\n }\n}\n","import * as fs from 'node:fs';\nimport { isUrl } from './config';\nimport { SdkGenerationError, type Logger } from './log';\nimport type { OpenApiDocument } from './openapi';\n\n/** Contract numbers (`info.x-ddd-contract.contract`) this codegen understands. */\nexport const SUPPORTED_CONTRACT = { min: 1, max: 1 } as const;\n\nexport const SCHEMA_DEFINITION_MARKUP = '<SchemaDefinition schemaRef=';\n\n/** Loads a spec from an http(s) URL or a local JSON file. Each source is read once per run by the caller. */\nexport async function loadSpec(source: string, timeoutMs = 60_000): Promise<OpenApiDocument> {\n let text: string;\n if (isUrl(source)) {\n let response: Response;\n try {\n response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });\n } catch (error) {\n throw new SdkGenerationError(`Could not fetch spec ${source}: ${(error as Error).message}`);\n }\n if (!response.ok) {\n throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);\n }\n text = await response.text();\n } else {\n if (!fs.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);\n text = fs.readFileSync(source, 'utf-8');\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${(error as Error).message}`);\n }\n if (!parsed || typeof parsed !== 'object' || !('paths' in parsed)) {\n throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no \"paths\").`);\n }\n return parsed as OpenApiDocument;\n}\n\n/**\n * Checks the parts of the DDD contract the codegen depends on. Aborts on an unsupported contract\n * version and on a spec without SchemaDefinition tag markup (fetched with `removeSchemaTags=1`).\n */\nexport function validateSpec(doc: OpenApiDocument, source: string, logger: Logger): void {\n const contract = doc.info?.['x-ddd-contract'];\n if (contract === undefined) {\n logger.warn(`${source}: no info.x-ddd-contract — assuming a pre-contract DDD spec.`);\n } else {\n const number = typeof contract === 'object' && contract ? contract.contract : undefined;\n if (typeof number !== 'number' || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {\n throw new SdkGenerationError(\n `${source}: DDD contract ${JSON.stringify(number ?? contract)} is not supported by this @mgamadeus/ddd-web ` +\n `(supported: ${SUPPORTED_CONTRACT.min}–${SUPPORTED_CONTRACT.max}). Update @mgamadeus/ddd-web or the backend.`,\n );\n }\n }\n const hasSchemaTags = (doc.tags ?? []).some((tag) => tag.description?.includes(SCHEMA_DEFINITION_MARKUP));\n if (!hasSchemaTags) {\n throw new SdkGenerationError(\n `${source}: no <SchemaDefinition schemaRef=\"…\"/> markup in tags[].description. The codegen needs it to ` +\n `place models into namespace folders — fetch the spec without removeSchemaTags=1.`,\n );\n }\n}\n","import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport {\n isUrl,\n loadConfig,\n resolveApis,\n resolveModelsDir,\n type LoadedConfig,\n type ResolvedApi,\n type SdkConfig,\n} from './config';\nimport { prepareDocumentForEndpoints, restoreEndpointNames } from './document-endpoints';\nimport { prepareDocumentForModels } from './document-models';\nimport { buildEnhancedEndpoints } from './enhance';\nimport { parseApiEndpoints } from './endpoints';\nimport { OutputFiles } from './files';\nimport { formatFiles, typecheck } from './format';\nimport { consoleLogger, SdkGenerationError, type Logger } from './log';\nimport { extractModels } from './models';\nimport { detectMultipartEndpoints, injectMultipartBodies, MULTIPART_IMPORT } from './multipart';\nimport type { OpenApiDocument } from './openapi';\nimport { indexOperations } from './operations';\nimport { commitOutput } from './output';\nimport { buildRegistry } from './registry';\nimport { repairMissingPathParameters } from './repair';\nimport { detectResponseHandlerEndpoints, injectResponseHandlers } from './response-handlers';\nimport { findPrettierConfigFile, relativeImport, runRtkCodegen } from './rtk';\nimport { loadSpec, validateSpec } from './spec';\nimport { collectOperationTags, renderTagsFile } from './tags';\nimport { resolveWorkspace } from './workspace';\n\nexport interface GenerateSdkOptions {\n /** Config file path (default `openapi-config.ts`, relative to `cwd`) or an inline config. */\n config?: string | SdkConfig;\n /** Base directory for a relative config path and for an inline config's relative paths. Default `process.cwd()`. */\n cwd?: string;\n /** Generate only the api with this `exportName` (or output file stem). */\n api?: string;\n /** Spec source (URL or file) replacing `schemaFile`; requires a single selected api. */\n schema?: string;\n /** Workspace value for `config.workspace.envVar`. */\n workspace?: string;\n skipPrettier?: boolean;\n skipTsc?: boolean;\n logger?: Logger;\n}\n\nexport interface GenerateSdkResult {\n apis: string[];\n /** Absolute paths of all written files. */\n files: string[];\n modelsDir: string;\n typechecked: boolean;\n}\n\nasync function load(options: GenerateSdkOptions, cwd: string): Promise<LoadedConfig> {\n if (options.config && typeof options.config === 'object') {\n return { config: options.config, configPath: path.join(cwd, '<inline config>'), rootDir: cwd };\n }\n return loadConfig(path.resolve(cwd, options.config ?? 'openapi-config.ts'));\n}\n\nfunction selectApis(all: ResolvedApi[], options: GenerateSdkOptions): ResolvedApi[] {\n let selected = all;\n if (options.api) {\n selected = all.filter((api) => api.exportName === options.api || api.stem === options.api);\n if (selected.length === 0) {\n throw new SdkGenerationError(`No api \"${options.api}\" in the config (have: ${all.map((api) => api.exportName).join(', ')}).`);\n }\n }\n if (options.schema) {\n if (selected.length !== 1) throw new SdkGenerationError('--schema needs exactly one api (use --api).');\n const schemaSource = isUrl(options.schema) ? options.schema : path.resolve(options.cwd ?? process.cwd(), options.schema);\n selected = [{ ...selected[0]!, schemaSource }];\n }\n return selected;\n}\n\nexport async function generateSdk(options: GenerateSdkOptions = {}): Promise<GenerateSdkResult> {\n const logger = options.logger ?? consoleLogger;\n const cwd = path.resolve(options.cwd ?? process.cwd());\n\n let loaded = await load(options, cwd);\n if (loaded.config.workspace) {\n const value = await resolveWorkspace(loaded.rootDir, loaded.config.workspace, options.workspace, logger);\n // The config may build its URLs from the env variable at evaluation time.\n if (value && typeof options.config !== 'object') loaded = await loadConfig(loaded.configPath);\n }\n\n const allApis = resolveApis(loaded);\n const apis = selectApis(allApis, options);\n const modelsDir = resolveModelsDir(loaded, allApis);\n const partial = apis.length < allApis.length;\n logger.info(`${apis.length} api(s): ${apis.map((api) => api.exportName).join(', ')}${partial ? ' (partial run)' : ''}`);\n\n // Models are shared between apis. A partial run therefore still reads every configured spec and rebuilds the\n // shared models from all of them (in config order, as a full run does); only the selected apis' files are written.\n const selected = new Set(apis.map((api) => api.stem));\n const pipeline: Array<{ api: ResolvedApi; write: boolean }> = allApis.map((api) => ({\n api: apis.find((candidate) => candidate.stem === api.stem) ?? api,\n write: selected.has(api.stem),\n }));\n\n // Each spec is loaded once and handed to every step.\n const specCache = new Map<string, Promise<OpenApiDocument>>();\n const loadOnce = (api: ResolvedApi): Promise<OpenApiDocument> => {\n if (!specCache.has(api.schemaSource)) {\n logger.info(`loading ${api.schemaSource}`);\n specCache.set(api.schemaSource, loadSpec(api.schemaSource));\n }\n return specCache.get(api.schemaSource)!;\n };\n const loadedSpecs = await Promise.all(\n pipeline.map(async ({ api, write }) => {\n if (write) return loadOnce(api);\n try {\n return await loadOnce(api);\n } catch (error) {\n logger.warn(\n `${api.exportName}: spec not loadable (${(error as Error).message}) — its models are kept from the previous ` +\n 'output; models it shares with the selected apis may lose its fields until a full run.',\n );\n return null;\n }\n }),\n );\n const steps = pipeline\n .map((step, i) => ({ ...step, doc: loadedSpecs[i] }))\n .filter((step): step is { api: ResolvedApi; write: boolean; doc: OpenApiDocument } => step.doc !== null);\n steps.forEach(({ api, doc }) => validateSpec(doc, api.schemaSource, logger));\n\n const registry = buildRegistry(\n steps.map((step) => step.doc),\n logger,\n );\n logger.info(`registry: ${registry.length} namespaces`);\n\n const files = new OutputFiles();\n // Only needed when a contributing spec could not be loaded: its models stay as they are on disk.\n if (steps.length < pipeline.length) files.seedFromDisk(modelsDir);\n const prettierConfigFile = await findPrettierConfigFile(loaded.rootDir);\n const constsByFile = new Map<string, Map<string, string>>();\n const uniqueNameByPath = new Map<string, string>();\n const specDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ddd-web-spec-'));\n\n try {\n for (const [i, { api, write, doc: rawDoc }] of steps.entries()) {\n const doc = repairMissingPathParameters(rawDoc, logger);\n logger.info(`── ${api.stem} (${i + 1}/${steps.length})${write ? '' : ' (models only)'}`);\n const index = indexOperations(doc, api.sideEffects, api.skipUpdatePostTwins);\n if (index.skippedTwins.size > 0) logger.info(` skipping ${index.skippedTwins.size} POST twin(s) of PATCH upserts`);\n\n const modelOptions = loaded.config.models ?? {};\n const prepared = prepareDocumentForModels(doc, modelOptions);\n const preparedEndpoints = prepareDocumentForEndpoints(prepared.doc, loaded.config.endpoints ?? {});\n const generated = await runRtkCodegen(api, preparedEndpoints.doc, index, path.join(specDir, `${i}.json`), prettierConfigFile, (rtkName) =>\n preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName,\n );\n const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);\n const extractOptions = {\n apiFilePath: api.outputFile,\n modelsDir,\n registry,\n files,\n logger,\n esm: api.config.esmExtensions === true,\n documentModels: prepared.documentModels,\n enumConsts: modelOptions.enums === 'const',\n constsByFile,\n modelOptions,\n writeIndex: modelOptions.index !== false,\n uniqueNameByPath,\n };\n // models.scope 'all': the models of every operation, also those the endpoint filter leaves out of the api file\n if (modelOptions.scope === 'all' && api.config.filterEndpoints !== undefined) {\n const unfiltered = await runRtkCodegen(\n { ...api, config: { ...api.config, filterEndpoints: undefined } },\n preparedEndpoints.doc,\n index,\n path.join(specDir, `${i}-all.json`),\n prettierConfigFile,\n (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName,\n );\n const unfilteredCode = restoreEndpointNames(unfiltered.code, unfiltered.locations, preparedEndpoints.endpointNamesByPlaceholder).code;\n extractModels({ ...extractOptions, apiSource: unfilteredCode, modelsOnly: true });\n logger.info(' models of all operations written (models.scope all)');\n }\n const endpoints = parseApiEndpoints(rtk.code, logger, rtk.locations);\n const handlerEndpoints = detectResponseHandlerEndpoints(doc, endpoints, api.responseHandlers);\n const responseKinds = new Map<string, 'text' | 'blob'>();\n for (const endpoint of endpoints) {\n const kind = handlerEndpoints.get(endpoint.key);\n if (kind && endpoint.responseType) responseKinds.set(endpoint.responseType, kind);\n }\n const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === 'blob').length;\n if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);\n\n const multipart = injectMultipartBodies(rtk.code, detectMultipartEndpoints(doc, endpoints), logger);\n if (multipart.injected.length > 0) logger.info(` ${multipart.injected.length} multipart endpoint(s) (multipartFiles)`);\n\n const esm = api.config.esmExtensions === true;\n const apiSource = extractModels({ ...extractOptions, apiSource: multipart.source, responseKinds });\n if (!write) continue;\n const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints);\n files.set(api.outputFile, multipart.injected.length > 0 ? `${MULTIPART_IMPORT}\\n${withHandlers}` : withHandlers);\n\n const withExtension = (specifier: string): string => (esm ? `${specifier}.js` : specifier);\n const enhanced = buildEnhancedEndpoints({\n stem: api.stem,\n apiName: api.exportName,\n apiModuleImport: withExtension(`./${api.stem}`),\n baseApiImport: api.config.baseApiImport ?? withExtension(relativeImport(api.outputDir, api.apiFile).replace(/\\.[cm]?[jt]sx?$/, '')),\n baseApiName: api.config.apiImport ?? 'api',\n audience: api.audience,\n endpoints,\n index,\n doc,\n operationTags: collectOperationTags(doc, api.audience),\n invalidation: api.invalidation,\n logger,\n });\n files.set(path.join(api.outputDir, `${api.stem}Enhanced.ts`), enhanced.source);\n files.set(path.join(api.outputDir, `${api.stem}Tags.ts`), renderTagsFile(api.stem, enhanced.tagTypes));\n }\n } finally {\n fs.rmSync(specDir, { recursive: true, force: true });\n }\n\n if (!options.skipPrettier) {\n logger.info('formatting with prettier');\n await formatFiles(files);\n }\n\n const committed = commitOutput(files, modelsDir, loaded.rootDir);\n let typechecked = false;\n if (!options.skipTsc) {\n logger.info('type check (tsc --noEmit)');\n try {\n typechecked = typecheck(loaded.rootDir, path.resolve(loaded.rootDir, loaded.config.tsconfig ?? 'tsconfig.json'), logger);\n } catch (error) {\n committed.rollback();\n logger.error('type check failed — previous output restored');\n throw error;\n }\n }\n committed.finalize();\n logger.info(`done: ${files.paths().length} files`);\n return { apis: apis.map((api) => api.exportName), files: files.paths(), modelsDir, typechecked };\n}\n","import { createRequire } from 'node:module';\nimport type TypeScript from 'typescript';\n\nlet cached: typeof TypeScript | undefined;\n\n/**\n * The TypeScript compiler API, resolved through @rtk-query/codegen-openapi (which depends on it) so the\n * codegen parses with the same version that printed the code and needs no own typescript dependency.\n */\nexport function loadTypeScript(): typeof TypeScript {\n if (cached) return cached;\n const require = createRequire(import.meta.url);\n const codegenEntry = require.resolve('@rtk-query/codegen-openapi');\n cached = createRequire(codegenEntry)('typescript') as typeof TypeScript;\n return cached;\n}\n","import type TypeScript from 'typescript';\nimport type { OpenApiDocument } from './openapi';\nimport { loadTypeScript } from './typescript';\n\n/** How the generator writes the models of the document's component schemas. Every option is off by default. */\nexport interface ModelOptions {\n /**\n * `document`: a model is named and placed by its schema name as the document writes it — the last dot segment is\n * the model name, unchanged (`AIConversationMessage`, not `AiConversationMessage`), the segments before it are the\n * folders; a folder that happens to prefix the last segment never splits it (`…Messages.DelegationResults` stays\n * `DelegationResults` beside a `…Messages.Delegation` namespace). Every model file exports its own schema's name,\n * also when another folder holds the same name (the path tells them apart; an importer aliases it). `rtk` (default):\n * RTK codegen's names, placed by the namespace registry.\n */\n naming?: 'rtk' | 'document';\n /**\n * `all`: every schema an operation of the document reaches is written, also when `filterEndpoints` leaves its\n * operations out of the api file (a models-only pass over all operations; their argument types are not written).\n * `reachable` (default): the schemas of the generated endpoints.\n */\n scope?: 'reachable' | 'all';\n /**\n * `false`: no barrel `index.ts` in the models folder — the api file and the models import every model by its path.\n * Default `true`. With `naming: 'document'` the barrel leaves out a model whose name another folder holds too.\n */\n index?: boolean;\n /**\n * `const`: an enum property becomes two exported objects in its model's file, `<Model><Property>` and\n * `<Model><Property>Strict` (`as const`), keyed by the enum values; the property is typed from the Strict object\n * (`(typeof XStrict)[keyof typeof XStrict]`, `| null` when the property is nullable). `union` (default): the inline\n * union of RTK codegen. Needs `naming: 'document'` (the const names start with the document's model name).\n */\n enums?: 'union' | 'const';\n /**\n * With `enums: 'const'`: the property's type from the Strict object (`strict`, default: the union of the values) or\n * from the plain object (`wide`: `(typeof X)[keyof typeof X]`, in effect `string`).\n */\n enumPropertyType?: 'strict' | 'wide';\n /**\n * `const` (with `enums: 'const'`): a string property named `objectType` (the class name a DDD write reads) gets a\n * one-value enum const of its schema name with `\\\\` for `.` (`<Model>ObjectType` = `{ App_Domain_X: \"App\\\\Domain\\\\X\" }`)\n * and is required. Default `document` (as declared).\n */\n objectType?: 'document' | 'const';\n /** `| null` beside a `$ref` whose property is nullable (RTK codegen drops it). Default `false`. */\n nullableRefs?: boolean;\n /**\n * The type of an `id` property the document declares as `string | integer`: `number` or `string`. Default\n * `document` (the union as declared).\n */\n idType?: 'document' | 'number' | 'string';\n}\n\n/** The component schema behind one RTK type name. */\nexport interface DocumentModel {\n /** The schema's key in `components.schemas`, e.g. `DDD.Domain.AI.Entities.Conversations.Messages.AIConversationMessage`. */\n schemaKey: string;\n schema: SchemaObject;\n}\n\ntype SchemaObject = Record<string, unknown> & {\n properties?: Record<string, SchemaObject>;\n items?: SchemaObject;\n enum?: unknown[];\n oneOf?: SchemaObject[];\n nullable?: boolean;\n $ref?: string;\n type?: string;\n};\n\n/** The title RTK codegen names a component schema after (`O(title)` keeps `DddModel12` as it is). */\nconst titleOfSchema = (index: number): string => `DddModel${index}`;\n\nconst isObject = (value: unknown): value is SchemaObject => typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * The document RTK codegen reads, with the model options applied, and the component schema behind each RTK type name\n * (empty unless `naming: 'document'`). The document passed in stays unchanged.\n */\nexport function prepareDocumentForModels(\n doc: OpenApiDocument,\n options: ModelOptions,\n): { doc: OpenApiDocument; documentModels: Map<string, DocumentModel> } {\n const documentModels = new Map<string, DocumentModel>();\n const naming = options.naming === 'document';\n const enumConsts = options.enums === 'const';\n if (!naming && !enumConsts && !options.nullableRefs && (options.idType ?? 'document') === 'document') {\n return { doc, documentModels };\n }\n const prepared = structuredClone(doc) as OpenApiDocument;\n const schemas = prepared.components?.schemas ?? {};\n const original = doc.components?.schemas ?? {};\n Object.keys(schemas).forEach((schemaKey, index) => {\n const schema = schemas[schemaKey];\n if (!isObject(schema)) return;\n // RTK codegen names a schema after its title: a title of our own maps the type name back to the schema\n if (naming) {\n schema.title = titleOfSchema(index);\n documentModels.set(titleOfSchema(index), { schemaKey, schema: original[schemaKey] as SchemaObject });\n }\n for (const [propertyName, property] of Object.entries(schema.properties ?? {})) {\n if (!isObject(property)) continue;\n if (options.nullableRefs && typeof property.$ref === 'string' && property.nullable === true) {\n // a `$ref` carries no `nullable` for RTK codegen; inside `allOf` it does\n schema.properties![propertyName] = { allOf: [{ $ref: property.$ref }], nullable: true };\n continue;\n }\n const idType = options.idType ?? 'document';\n if (propertyName === 'id' && idType !== 'document' && isStringOrIntegerUnion(property)) {\n schema.properties![propertyName] = {\n type: idType === 'number' ? 'integer' : 'string',\n ...(isNullable(property) ? { nullable: true } : {}),\n };\n }\n }\n });\n return { doc: prepared, documentModels };\n}\n\nfunction isStringOrIntegerUnion(property: SchemaObject): boolean {\n const types = new Set((property.oneOf ?? []).map((variant) => (isObject(variant) ? variant.type : undefined)));\n return types.has('string') && (types.has('integer') || types.has('number'));\n}\n\nfunction isNullable(property: SchemaObject): boolean {\n return property.nullable === true || (property.oneOf ?? []).some((variant) => isObject(variant) && variant.nullable === true);\n}\n\n/** Where a model of `naming: 'document'` lives: the schema name's segments before the last, and the last one. */\nexport function placeDocumentModel(model: DocumentModel): { segments: string[]; leafName: string } {\n const parts = model.schemaKey.split('.');\n return { segments: parts.slice(0, -1), leafName: parts[parts.length - 1]! };\n}\n\n/** The RTK type name of a document model and its read/write variant suffix (`DddModel12Read` → `DddModel12`, `Read`). */\nexport function findDocumentModel(\n rtkName: string,\n documentModels: ReadonlyMap<string, DocumentModel>,\n): { model: DocumentModel; suffix: string } | null {\n const match = rtkName.match(/^(DddModel\\d+)(Read|Write)?$/);\n const model = match ? documentModels.get(match[1]!) : undefined;\n return model ? { model, suffix: match![2] ?? '' } : null;\n}\n\n/**\n * The key an enum value gets in its const object: a dash camel-cases (`gpt-realtime` → `gptRealtime`), spaces, `/` and\n * `\\` become `_`, an empty value `EMPTY`; a value that still gives no identifier is the key itself, quoted.\n */\nexport function enumKeyOf(value: string): string {\n if (value.trim() === '') return 'EMPTY';\n const key = value.replace(/-+([A-Za-z0-9])/g, (_, next: string) => next.toUpperCase()).replace(/[ /\\\\]+/g, '_');\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(value);\n}\n\n/**\n * The enum const objects of a model and its body with every enum property typed from them (`enums: 'const'`).\n * Covers a property's own `enum` (an array schema with an `enum` stays an array) and the `enum` of its array items;\n * with `objectType: 'const'` also the `objectType` string property (its schema name, required).\n */\nexport function applyEnumConsts(\n body: string,\n modelName: string,\n model: DocumentModel,\n options: Pick<ModelOptions, 'enumPropertyType' | 'objectType'> = {},\n): { body: string; consts: Map<string, string> } {\n const { schema, schemaKey } = model;\n const consts = new Map<string, string>();\n const typeTexts = new Map<string, string>();\n const requiredNames = new Set<string>();\n for (const [propertyName, property] of Object.entries(schema.properties ?? {})) {\n if (!isObject(property)) continue;\n const isItemsEnum = isObject(property.items) && Array.isArray(property.items.enum);\n const isArray = isItemsEnum || property.type === 'array';\n const isObjectType =\n options.objectType === 'const' && propertyName === 'objectType' && property.type === 'string' && !Array.isArray(property.enum);\n const declaredValues = isObjectType ? [schemaKey.split('.').join('\\\\')] : isItemsEnum ? property.items!.enum : property.enum;\n const values = declaredValues?.filter((value): value is string | number => typeof value === 'string' || typeof value === 'number');\n if (!values || values.length === 0) continue;\n const constName = `${modelName}${propertyName.charAt(0).toUpperCase()}${propertyName.slice(1)}`;\n if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(constName)) continue;\n const members = [...new Set(values.map(String))].map((value) => ` ${enumKeyOf(value)}: ${JSON.stringify(value)},`).join('\\n');\n consts.set(constName, `export const ${constName} = {\\n${members}\\n};\\n\\nexport const ${constName}Strict = {\\n${members}\\n} as const;`);\n const typedFrom = options.enumPropertyType === 'wide' ? constName : `${constName}Strict`;\n const memberType = `(typeof ${typedFrom})[keyof typeof ${typedFrom}]`;\n const nullable = property.nullable === true || (property.enum ?? []).includes(null);\n typeTexts.set(propertyName, `${isArray ? `Array<${memberType}>` : memberType}${nullable ? ' | null' : ''}`);\n if (isObjectType) requiredNames.add(propertyName);\n }\n return { body: replacePropertyTypes(body, typeTexts, requiredNames), consts };\n}\n\n/** The body with the types of the named properties of its first type declaration replaced. */\nfunction replacePropertyTypes(body: string, typeTexts: ReadonlyMap<string, string>, requiredNames: ReadonlySet<string> = new Set()): string {\n if (typeTexts.size === 0) return body;\n const ts: typeof TypeScript = loadTypeScript();\n const sourceFile = ts.createSourceFile('model.ts', body, ts.ScriptTarget.Latest, true);\n const declaration = sourceFile.statements.find(\n (statement): statement is TypeScript.TypeAliasDeclaration | TypeScript.InterfaceDeclaration =>\n ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement),\n );\n if (!declaration) return body;\n const members = ts.isInterfaceDeclaration(declaration)\n ? declaration.members\n : ts.isTypeLiteralNode(declaration.type)\n ? declaration.type.members\n : ts.isIntersectionTypeNode(declaration.type)\n ? declaration.type.types.flatMap((part) => (ts.isTypeLiteralNode(part) ? [...part.members] : []))\n : [];\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n for (const member of members) {\n if (!ts.isPropertySignature(member) || !member.type || !member.name) continue;\n const name = ts.isIdentifier(member.name) || ts.isStringLiteral(member.name) ? member.name.text : member.name.getText(sourceFile);\n const text = typeTexts.get(name);\n if (text !== undefined) replacements.push({ start: member.type.getStart(sourceFile), end: member.type.getEnd(), text });\n if (requiredNames.has(name) && member.questionToken) {\n replacements.push({ start: member.questionToken.getStart(sourceFile), end: member.questionToken.getEnd(), text: '' });\n }\n }\n let result = body;\n for (const { start, end, text } of replacements.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, start) + text + result.slice(end);\n }\n return result;\n}\n","import type TypeScript from 'typescript';\nimport type { Logger } from './log';\nimport type { HttpMethod } from './openapi';\nimport { loadTypeScript } from './typescript';\n\n/** HTTP method and OpenAPI path of a generated endpoint, recorded while RTK codegen selects the operations. */\nexport interface OperationLocation {\n method: HttpMethod;\n path: string;\n}\n\n/** One endpoint of a generated RTK api file. */\nexport interface EndpointInfo {\n key: string;\n buildType: 'query' | 'mutation';\n /** URL as written in the generated code, e.g. `/api/x/${queryArg.id}`. */\n url: string;\n /** HTTP method, uppercase. */\n method: string;\n /** OpenAPI path of the operation, e.g. `/api/x/{id}`. */\n path: string;\n /**\n * Path placeholder → expression reading its value from the endpoint argument `arg`, e.g. `{ id: 'arg.id' }`, or\n * `{ id: 'arg' }` with `flattenArg`. Independent of `encodePathParams`.\n */\n pathArgs: Record<string, string>;\n /**\n * Expression reading the request body from the endpoint argument `arg`, e.g. `arg.bookUpdateRequestDto`, or `arg`\n * with `flattenArg`. Absent when the endpoint sends no body.\n */\n bodyArg?: string;\n /** Name of the response type (first type argument of `build.query<…>` / `build.mutation<…>`). */\n responseType?: string;\n}\n\n/** `/api/x/${queryArg.fooId}` → `/api/x/{fooId}` (the OpenAPI path, for URLs without a recorded operation). */\nexport function toOpenApiPath(url: string): string {\n return url\n .replace(/\\$\\{encodeURIComponent\\(String\\(queryArg\\.([A-Za-z0-9_]+)\\)\\)\\}/g, '{$1}')\n .replace(/\\$\\{queryArg\\.([A-Za-z0-9_]+)\\}/g, '{$1}');\n}\n\nfunction objectReturnedBy(ts: typeof TypeScript, fn: TypeScript.ArrowFunction): TypeScript.ObjectLiteralExpression | null {\n const body = fn.body;\n if (ts.isParenthesizedExpression(body) && ts.isObjectLiteralExpression(body.expression)) return body.expression;\n if (ts.isObjectLiteralExpression(body)) return body;\n if (ts.isBlock(body)) {\n for (const statement of body.statements) {\n if (ts.isReturnStatement(statement) && statement.expression) {\n let expression = statement.expression;\n if (ts.isParenthesizedExpression(expression)) expression = expression.expression;\n if (ts.isObjectLiteralExpression(expression)) return expression;\n }\n }\n }\n return null;\n}\n\n/** `encodeURIComponent(String(x))` → `x`. */\nfunction unwrapEncoding(ts: typeof TypeScript, expression: TypeScript.Expression): TypeScript.Expression {\n let current = expression;\n while (\n ts.isCallExpression(current) &&\n ts.isIdentifier(current.expression) &&\n (current.expression.text === 'encodeURIComponent' || current.expression.text === 'String') &&\n current.arguments.length === 1\n ) {\n current = current.arguments[0]!;\n }\n return current;\n}\n\n/** Accessor expressions of the URL template's substitutions, in order (`queryArg` rewritten to `arg`). */\nfunction templateAccessors(ts: typeof TypeScript, init: TypeScript.TemplateExpression, sourceFile: TypeScript.SourceFile): string[] {\n return init.templateSpans.map((span) => unwrapEncoding(ts, span.expression).getText(sourceFile).replace(/^queryArg\\b/, 'arg'));\n}\n\nfunction readEndpoint(\n ts: typeof TypeScript,\n key: string,\n buildType: 'query' | 'mutation',\n call: TypeScript.CallExpression,\n sourceFile: TypeScript.SourceFile,\n location: OperationLocation | undefined,\n logger: Logger,\n): EndpointInfo | null {\n const definition = call.arguments[0];\n if (!definition || !ts.isObjectLiteralExpression(definition)) return null;\n const responseTypeNode = call.typeArguments?.[0];\n const responseType =\n responseTypeNode && ts.isTypeReferenceNode(responseTypeNode) && ts.isIdentifier(responseTypeNode.typeName)\n ? responseTypeNode.typeName.text\n : undefined;\n for (const property of definition.properties) {\n if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) || property.name.text !== 'query') continue;\n if (!ts.isArrowFunction(property.initializer)) continue;\n const returned = objectReturnedBy(ts, property.initializer);\n if (!returned) continue;\n let url: string | undefined;\n let method: string | undefined;\n let accessors: string[] = [];\n let bodyArg: string | undefined;\n for (const member of returned.properties) {\n if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;\n const init = member.initializer;\n if (member.name.text === 'url') {\n if (ts.isNoSubstitutionTemplateLiteral(init) || ts.isStringLiteral(init)) url = init.text;\n else if (ts.isTemplateExpression(init)) {\n url = init.getText(sourceFile).slice(1, -1);\n accessors = templateAccessors(ts, init, sourceFile);\n }\n }\n if (member.name.text === 'method' && ts.isStringLiteral(init)) method = init.text;\n if (member.name.text === 'body' && (ts.isIdentifier(init) || ts.isPropertyAccessExpression(init))) {\n const text = init.getText(sourceFile);\n if (/^queryArg(\\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(text)) bodyArg = text.replace(/^queryArg\\b/, 'arg');\n }\n }\n if (url === undefined) {\n logger.warn(`No extractable URL for endpoint \"${key}\" — skipping.`);\n return null;\n }\n const path = location?.path ?? toOpenApiPath(url);\n const placeholders = [...path.matchAll(/\\{([^}]+)\\}/g)].map((match) => match[1]!);\n const pathArgs: Record<string, string> = {};\n placeholders.forEach((name, index) => {\n const accessor = accessors[index];\n if (accessor !== undefined) pathArgs[name] = accessor;\n });\n return {\n key,\n buildType,\n url,\n method: (location?.method ?? method ?? 'GET').toUpperCase(),\n path,\n pathArgs,\n ...(bodyArg ? { bodyArg } : {}),\n ...(responseType ? { responseType } : {}),\n };\n }\n return null;\n}\n\n/**\n * Parses a generated RTK Query api file and returns every `build.query` / `build.mutation` endpoint. `locations`\n * (endpoint key → operation, recorded during generation) identifies each endpoint's operation; without an entry the\n * method and path are read back from the generated code.\n */\nexport function parseApiEndpoints(\n source: string,\n logger: Logger,\n locations: ReadonlyMap<string, OperationLocation> = new Map(),\n): EndpointInfo[] {\n const ts = loadTypeScript();\n const sourceFile = ts.createSourceFile('api.ts', source, ts.ScriptTarget.Latest, true);\n const results: EndpointInfo[] = [];\n const visit = (node: TypeScript.Node): void => {\n if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && ts.isCallExpression(node.initializer)) {\n const callee = node.initializer.expression;\n if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === 'build') {\n const buildType = callee.name.text;\n if (buildType === 'query' || buildType === 'mutation') {\n const key = node.name.text;\n const info = readEndpoint(ts, key, buildType, node.initializer, sourceFile, locations.get(key), logger);\n if (info) results.push(info);\n return;\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n ts.forEachChild(sourceFile, visit);\n return results;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\ninterface StoredFile {\n content: string;\n /** False for files seeded from the previous output (partial runs); those are overwritten, not merged. */\n generatedThisRun: boolean;\n}\n\n/** In-memory set of generated files keyed by their final absolute path. */\nexport class OutputFiles {\n protected files = new Map<string, StoredFile>();\n protected lowerCaseIndex = new Map<string, string>();\n\n set(filePath: string, content: string): void {\n const absolute = path.resolve(filePath);\n this.files.set(absolute, { content, generatedThisRun: true });\n this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);\n }\n\n get(filePath: string): string | undefined {\n return this.files.get(path.resolve(filePath))?.content;\n }\n\n isGeneratedThisRun(filePath: string): boolean {\n return this.files.get(path.resolve(filePath))?.generatedThisRun ?? false;\n }\n\n /** Case-insensitive lookup; returns the stored path spelling. */\n findPath(filePath: string): string | undefined {\n return this.lowerCaseIndex.get(path.resolve(filePath).toLowerCase());\n }\n\n paths(): string[] {\n return [...this.files.keys()];\n }\n\n /** Seeds the store with existing `.ts` files below `dir` (for runs that regenerate only some apis). */\n seedFromDisk(dir: string): void {\n for (const absolute of listTsFiles(dir)) {\n this.files.set(absolute, { content: fs.readFileSync(absolute, 'utf-8'), generatedThisRun: false });\n this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);\n }\n }\n}\n\nfunction listTsFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const result: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const absolute = path.join(dir, entry.name);\n if (entry.isDirectory()) result.push(...listTsFiles(absolute));\n else if (entry.isFile() && entry.name.endsWith('.ts')) result.push(absolute);\n }\n return result;\n}\n","import { execFileSync } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport prettier from 'prettier';\nimport type { OutputFiles } from './files';\nimport { SdkGenerationError, type Logger } from './log';\n\n/** Formats every file with the prettier config that applies at its final location. */\nexport async function formatFiles(files: OutputFiles): Promise<void> {\n for (const filePath of files.paths()) {\n const options = (await prettier.resolveConfig(filePath, { editorconfig: true })) ?? {};\n files.set(filePath, await prettier.format(files.get(filePath)!, { ...options, filepath: filePath }));\n }\n}\n\n/** The compiler the type check runs: its executable, its version and whose installation it is. */\nexport interface ResolvedTypeScriptCompiler {\n executable: string;\n version: string;\n origin: 'project' | 'generator';\n}\n\n/** The `tsc` of the TypeScript installation that `base` resolves, through its package.json `bin` (TypeScript 7 exports no `typescript/bin/tsc`). */\nfunction resolveTscOfInstallation(base: string): { executable: string; version: string } | null {\n let packageJsonPath: string;\n try {\n packageJsonPath = createRequire(base).resolve('typescript/package.json');\n } catch {\n return null;\n }\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as { version?: string; bin?: string | Record<string, string> };\n const binEntry = typeof packageJson.bin === 'string' ? packageJson.bin : packageJson.bin?.tsc;\n if (!binEntry) return null;\n const executable = path.resolve(path.dirname(packageJsonPath), binEntry);\n return fs.existsSync(executable) ? { executable, version: packageJson.version ?? 'unknown' } : null;\n}\n\n/** The project's own TypeScript compiler; the generator's (through its codegen dependency) only when the project has none. */\nexport function resolveTypeScriptCompiler(rootDir: string): ResolvedTypeScriptCompiler {\n const projectCompiler = resolveTscOfInstallation(path.join(rootDir, 'package.json'));\n if (projectCompiler) return { ...projectCompiler, origin: 'project' };\n const ownRequire = createRequire(import.meta.url);\n for (const base of [import.meta.url, ownRequire.resolve('@rtk-query/codegen-openapi')]) {\n const generatorCompiler = resolveTscOfInstallation(base);\n if (generatorCompiler) return { ...generatorCompiler, origin: 'generator' };\n }\n throw new SdkGenerationError('No TypeScript compiler found for the type check (install typescript in the project, or pass --skip-tsc).');\n}\n\n/**\n * The command line that runs the compiler: a JavaScript entry (`.js`/`.cjs`/`.mjs`, or a file starting with a `#!` line\n * that names node — TypeScript's `bin/tsc`) through this Node, any other file (a native compiler) directly.\n */\nfunction buildCompilerCommand(executable: string, args: string[]): [string, string[]] {\n if (/\\.(c|m)?js$/.test(executable)) return [process.execPath, [executable, ...args]];\n const head = fs.readFileSync(executable).subarray(0, 100).toString('latin1');\n return head.startsWith('#!') && head.split('\\n', 1)[0]!.includes('node')\n ? [process.execPath, [executable, ...args]]\n : [executable, args];\n}\n\n/** Runs `tsc --noEmit` for the consuming project. Returns false when there is no tsconfig to check. */\nexport function typecheck(rootDir: string, tsconfig: string, logger: Logger): boolean {\n if (!fs.existsSync(tsconfig)) {\n logger.warn(`No ${path.relative(rootDir, tsconfig) || tsconfig} — skipping the type check.`);\n return false;\n }\n const compiler = resolveTypeScriptCompiler(rootDir);\n logger.info(\n `Type check with TypeScript ${compiler.version} (${compiler.origin === 'project' ? \"the project's compiler\" : \"the generator's own compiler — the project has no typescript\"}).`,\n );\n const [command, args] = buildCompilerCommand(compiler.executable, ['--noEmit', '-p', tsconfig]);\n try {\n execFileSync(command, args, {\n cwd: rootDir,\n stdio: ['ignore', 'pipe', 'pipe'],\n encoding: 'utf-8',\n });\n } catch (error) {\n const output = (error as { stdout?: string }).stdout ?? '';\n throw new SdkGenerationError(`Type check failed:\\n${output.split('\\n').slice(0, 40).join('\\n')}`);\n }\n return true;\n}\n","import * as path from 'node:path';\nimport type TypeScript from 'typescript';\nimport type { OutputFiles } from './files';\nimport type { Logger } from './log';\nimport type { NamespacePath } from './registry';\nimport { DDD_WEB_API_IMPORT } from './response-handlers';\nimport { applyEnumConsts, findDocumentModel, placeDocumentModel, type DocumentModel, type ModelOptions } from './document-models';\nimport { loadTypeScript } from './typescript';\n\ninterface Declaration {\n name: string;\n /** Source text including leading trivia (doc comments). */\n text: string;\n start: number;\n end: number;\n}\n\nfunction hasExport(ts: typeof TypeScript, statement: TypeScript.Statement): boolean {\n if (!ts.canHaveModifiers(statement)) return false;\n return ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;\n}\n\nfunction exportedTypeDeclarations(source: string): Declaration[] {\n const ts = loadTypeScript();\n const sourceFile = ts.createSourceFile('input.ts', source, ts.ScriptTarget.Latest, true);\n const result: Declaration[] = [];\n for (const statement of sourceFile.statements) {\n if (!hasExport(ts, statement)) continue;\n if (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) {\n const start = statement.getFullStart();\n const end = statement.getEnd();\n result.push({ name: statement.name.text, text: source.slice(start, end), start, end });\n }\n }\n return result;\n}\n\nfunction stripDeclarations(source: string, declarations: Declaration[]): string {\n let result = source;\n for (const { start, end } of [...declarations].sort((a, b) => b.start - a.start)) {\n result = result.slice(0, start) + result.slice(end);\n }\n return result.trim();\n}\n\ninterface TypeMembers {\n header: string;\n members: Map<string, string>;\n}\n\nfunction parseTypeMembers(source: string): TypeMembers | null {\n const ts = loadTypeScript();\n const sourceFile = ts.createSourceFile('type.ts', source, ts.ScriptTarget.Latest, true);\n const declaration = sourceFile.statements.find(\n (statement): statement is TypeScript.TypeAliasDeclaration | TypeScript.InterfaceDeclaration =>\n ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement),\n );\n if (!declaration) return null;\n const isInterface = ts.isInterfaceDeclaration(declaration);\n const header = isInterface ? `export interface ${declaration.name.text} {` : `export type ${declaration.name.text} = {`;\n const elements = isInterface\n ? declaration.members\n : ts.isTypeLiteralNode(declaration.type)\n ? declaration.type.members\n : [];\n const members = new Map<string, string>();\n for (const member of elements) {\n let key: string;\n if (ts.isPropertySignature(member) && member.name) {\n key = ts.isIdentifier(member.name) ? member.name.text : member.name.getText(sourceFile);\n } else if (ts.isIndexSignatureDeclaration(member)) {\n key = '__index__';\n } else {\n continue;\n }\n members.set(key, source.slice(member.getFullStart(), member.getEnd()));\n }\n return { header, members };\n}\n\nfunction parseImportLines(source: string): Map<string, string> {\n const ts = loadTypeScript();\n const sourceFile = ts.createSourceFile('imports.ts', source, ts.ScriptTarget.Latest, true);\n const imports = new Map<string, string>();\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement)) continue;\n const bindings = statement.importClause?.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) continue;\n const line = source.slice(statement.getStart(sourceFile), statement.getEnd());\n for (const element of bindings.elements) imports.set(element.name.text, line);\n }\n return imports;\n}\n\n/** Union of properties when two apis emit the same model; properties already present win. */\nfunction mergeModel(existing: string, body: string, importLines: string, name: string, logger: Logger): string {\n const existingParsed = parseTypeMembers(existing);\n const incoming = parseTypeMembers(body);\n if (!existingParsed || !incoming) {\n return (importLines ? `${importLines}\\n\\n` : '') + `${body}\\n\\nexport default ${name};\\n`;\n }\n const merged = new Map(existingParsed.members);\n let added = 0;\n for (const [key, text] of incoming.members) {\n if (!merged.has(key)) {\n merged.set(key, text);\n added++;\n }\n }\n if (added === 0) return existing;\n const imports = parseImportLines(existing);\n for (const [symbol, line] of parseImportLines(importLines)) if (!imports.has(symbol)) imports.set(symbol, line);\n const importBlock = imports.size > 0 ? `${[...imports.values()].join('\\n')}\\n\\n` : '';\n logger.info(` merged ${added} new propert${added === 1 ? 'y' : 'ies'} into ${name}`);\n return `${importBlock}${existingParsed.header}\\n${[...merged.values()].join('\\n')}\\n};\\n\\nexport default ${name};\\n`;\n}\n\nconst escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nfunction alternation(names: string[]): RegExp | null {\n if (names.length === 0) return null;\n const sorted = [...names].sort((a, b) => b.length - a.length).map(escapeRegExp);\n return new RegExp(`(?<![A-Za-z0-9])(${sorted.join('|')})(?![A-Za-z0-9])`, 'g');\n}\n\n/**\n * Registry match for a type name. Case-insensitive because the registry key follows RTK's acronym\n * normalisation (AICosts → Aicosts) while the type name may differ in casing.\n */\nfunction registryMatch(name: string, registry: NamespacePath[]): { segments: string[]; leafName: string } | null {\n const lower = name.toLowerCase();\n for (const [prefix, segments] of registry) {\n if (lower.startsWith(prefix.toLowerCase())) {\n const leafName = name.slice(prefix.length);\n if (leafName.length > 0 && /^[A-Z]/.test(leafName)) return { segments, leafName };\n }\n }\n return null;\n}\n\nfunction importSpecifier(fromFile: string, toFile: string, esm: boolean): string {\n let relative = path.relative(path.dirname(fromFile), toFile.replace(/\\.ts$/, '')).replace(/\\\\/g, '/');\n if (!relative.startsWith('.')) relative = `./${relative}`;\n return esm ? `${relative}.js` : relative;\n}\n\nconst EXPORTED_NAME = /^export (?:type|interface) (\\w+)/m;\n\nexport interface ExtractModelsInput {\n /** Generated RTK source (types still inline). */\n apiSource: string;\n /** Final path of the api file (for the models import). */\n apiFilePath: string;\n modelsDir: string;\n registry: NamespacePath[];\n files: OutputFiles;\n logger: Logger;\n /** Write `.js` import specifiers (`esmExtensions`), incl. `index.js` for the models barrel. */\n esm?: boolean;\n /**\n * RTK names of response types of endpoints with a response handler: `text` becomes `string`, `blob` becomes\n * `DddFileResponse` (imported from the package's `api` entry). Every other type stays as RTK generated it.\n */\n responseKinds?: ReadonlyMap<string, 'text' | 'blob'>;\n /** RTK type name → component schema (`naming: 'document'`): such a model is named and placed by its schema name. */\n documentModels?: ReadonlyMap<string, DocumentModel>;\n /** `enums: 'const'`: the enum const objects of a document model go into its file. */\n enumConsts?: boolean;\n /** Enum const objects per model file, shared by every api of one run (a file merged across apis keeps them all). */\n constsByFile?: Map<string, Map<string, string>>;\n /** The `enumPropertyType` and `objectType` model options for the enum consts. */\n modelOptions?: Pick<ModelOptions, 'enumPropertyType' | 'objectType'>;\n /** `false` (`models.index`): no barrel; the api file imports every model by its path. Default `true`. */\n writeIndex?: boolean;\n /** The unique name of each model file (lower-case path), shared by every api of one run. */\n uniqueNameByPath?: Map<string, string>;\n /** Write the models only: the argument and response types of the endpoints (`_endpoints/`) are left out. */\n modelsOnly?: boolean;\n}\n\n/**\n * Moves every exported type of the RTK output into its own file under `modelsDir` (namespace folders\n * from the registry, `_endpoints/` for arg/response types, `_others/` otherwise), merges models shared\n * between apis, maintains the barrel `index.ts` and returns the api source importing from `modelsDir`.\n *\n * Every model file keeps one exported name across all apis. A model is named after its leaf (`…Books.Item` →\n * `Item`); when another model file already uses that name, the name is qualified with namespace segments\n * (`BooksItem`, then `EntitiesBooksItem`, …) so models of different namespaces never merge into one file and the\n * barrel can export every model.\n */\nexport function extractModels(input: ExtractModelsInput): string {\n const { modelsDir, registry, files, logger } = input;\n const esm = input.esm === true;\n const responseKinds = input.responseKinds ?? new Map<string, 'text' | 'blob'>();\n const indexPath = path.join(modelsDir, 'index.ts');\n\n // Exported name → model file (lower-case path), over everything already in the store (earlier apis, seeded files).\n const nameOwners = new Map<string, string>();\n for (const filePath of files.paths()) {\n const relative = path.relative(modelsDir, filePath);\n if (relative.startsWith('..') || path.isAbsolute(relative) || path.resolve(filePath) === path.resolve(indexPath)) continue;\n const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];\n if (name && !nameOwners.has(name)) nameOwners.set(name, path.resolve(filePath).toLowerCase());\n }\n\n const documentModels = input.documentModels ?? new Map<string, DocumentModel>();\n const constsByFile = input.constsByFile ?? new Map<string, Map<string, string>>();\n const placement = (oldName: string): { filePath: string; leafName: string; segments: string[] } => {\n const documentModel = findDocumentModel(oldName, documentModels);\n if (documentModel) {\n const { segments, leafName } = placeDocumentModel(documentModel.model);\n const planned = path.join(modelsDir, ...segments, `${leafName}${documentModel.suffix}.ts`);\n return { filePath: files.findPath(planned) ?? planned, leafName: `${leafName}${documentModel.suffix}`, segments };\n }\n const match = registryMatch(oldName, registry);\n if (match) {\n const planned = path.join(modelsDir, ...match.segments, `${match.leafName}.ts`);\n return { filePath: files.findPath(planned) ?? planned, leafName: match.leafName, segments: match.segments };\n }\n const folder = /^(Get|Post|Put|Patch|Delete)/.test(oldName) ? '_endpoints' : '_others';\n return { filePath: path.join(modelsDir, folder, `${oldName}.ts`), leafName: oldName, segments: [] };\n };\n\n const originalNames = exportedTypeDeclarations(input.apiSource).map((declaration) => declaration.name);\n const renameMap = new Map<string, string>();\n const documentModelByNewName = new Map<string, DocumentModel>();\n const targetByNewName = new Map<string, string>();\n const nameByPath = new Map<string, string>();\n // a document model's file exports its own schema's name; the unique name only wires the api file and the importers,\n // which alias it where the name repeats in another folder\n const exportNameByUniqueName = new Map<string, string>();\n const uniqueNameByPath = input.uniqueNameByPath ?? new Map<string, string>();\n for (const oldName of originalNames) {\n const { filePath, leafName, segments } = placement(oldName);\n const pathKey = path.resolve(filePath).toLowerCase();\n const isDocumentModel = findDocumentModel(oldName, documentModels) !== null;\n let name = nameByPath.get(pathKey) ?? uniqueNameByPath.get(pathKey) ?? (isDocumentModel ? undefined : files.get(filePath)?.match(EXPORTED_NAME)?.[1]);\n if (!name) {\n const owner = (candidate: string): string | undefined => nameOwners.get(candidate);\n name = leafName;\n for (let depth = 1; owner(name) !== undefined && owner(name) !== pathKey && depth <= segments.length; depth++) {\n name = segments.slice(-depth).join('') + leafName;\n }\n if (owner(name) !== undefined && owner(name) !== pathKey) name = oldName;\n if (name !== leafName && !isDocumentModel) logger.info(` ${oldName}: leaf name ${leafName} is taken — exported as ${name}`);\n }\n nameOwners.set(name, pathKey);\n nameByPath.set(pathKey, name);\n uniqueNameByPath.set(pathKey, name);\n exportNameByUniqueName.set(name, isDocumentModel ? leafName : name);\n renameMap.set(oldName, name);\n targetByNewName.set(name, filePath);\n const documentModel = findDocumentModel(oldName, documentModels);\n if (documentModel && documentModel.suffix === '') documentModelByNewName.set(name, documentModel.model);\n }\n\n const renameRegex = alternation([...renameMap.keys()]);\n const renamedSource = renameRegex\n ? input.apiSource.replace(renameRegex, (_, name: string) => renameMap.get(name) ?? name)\n : input.apiSource;\n const kindByName = new Map([...responseKinds].map(([name, kind]) => [renameMap.get(name) ?? name, kind] as const));\n\n const renamedDeclarations = exportedTypeDeclarations(renamedSource);\n const entries: Array<{ name: string; body: string; filePath: string }> = [];\n for (const { name, text } of renamedDeclarations) {\n const filePath = targetByNewName.get(name);\n if (!filePath) {\n logger.warn(`Re-extracted type \"${name}\" not in rename map — skipping.`);\n continue;\n }\n if (input.modelsOnly && path.relative(modelsDir, filePath).split(path.sep)[0] === '_endpoints') continue;\n entries.push({ name, body: text, filePath });\n }\n\n const pathByName = new Map(entries.map((entry) => [entry.name, entry.filePath]));\n const dependencyRegex = alternation([...pathByName.keys()]);\n\n const strippedSource = stripDeclarations(renamedSource, renamedDeclarations);\n const usedInApi = [...new Set(entries.map((entry) => entry.name))].filter((name) =>\n new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(name)}(?![A-Za-z0-9_$])`).test(strippedSource),\n );\n\n // Presentation DTOs are split per audience and share names with diverging shapes; re-exporting\n // them from one barrel would produce TS2308 duplicate exports.\n const isPresentation = (filePath: string): boolean => filePath.split(path.sep).includes('Presentation');\n const barrelEntries: string[] = [];\n\n const exportNameOf = (uniqueName: string): string => exportNameByUniqueName.get(uniqueName) ?? uniqueName;\n const writeIndex = input.writeIndex !== false;\n for (const { name: uniqueName, body: uniqueBody, filePath } of entries) {\n const dependencies = new Set<string>();\n if (dependencyRegex) {\n for (const match of uniqueBody.matchAll(new RegExp(dependencyRegex.source, 'g'))) {\n if (match[1] && match[1] !== uniqueName) dependencies.add(match[1]);\n }\n }\n // the file's own name and the local name of each import: a dependency whose unique name is this file's own name\n // is imported under an alias\n const name = exportNameOf(uniqueName);\n const localNameOf = new Map<string, string>();\n for (const dependency of dependencies) localNameOf.set(dependency, dependency === name ? `${dependency}Ref` : dependency);\n const renames = new Map<string, string>([[uniqueName, name], ...[...localNameOf].filter(([dependency, local]) => dependency !== local)]);\n const renameInBody = alternation([...renames.keys()].filter((key) => renames.get(key) !== key));\n const body = renameInBody ? uniqueBody.replace(renameInBody, (_, found: string) => renames.get(found) ?? found) : uniqueBody;\n const kind = kindByName.get(uniqueName);\n let typedBody = body;\n const documentModel = documentModelByNewName.get(uniqueName);\n if (input.enumConsts && documentModel) {\n const applied = applyEnumConsts(body, name, documentModel, input.modelOptions);\n typedBody = applied.body;\n const fileKey = path.resolve(filePath).toLowerCase();\n const fileConsts = constsByFile.get(fileKey) ?? new Map<string, string>();\n // the model's first document wins for its consts too, as it does for its properties\n for (const [constName, text] of applied.consts) if (!fileConsts.has(constName)) fileConsts.set(constName, text);\n if (fileConsts.size > 0) constsByFile.set(fileKey, fileConsts);\n }\n if (kind === 'text') {\n // Text-response endpoints come out of RTK as `= /** status 200 */ {}`; `string` is what arrives. A forced text\n // handler on a JSON-declared response replaces the whole type.\n const replaced = body.replace(/(=\\s*\\/\\*\\* status \\d+[^*]*\\*\\/)\\s*\\{\\}/g, '$1 string');\n typedBody = replaced !== body ? replaced : `export type ${name} = string;`;\n dependencies.clear();\n } else if (kind === 'blob') {\n typedBody = `export type ${name} = DddFileResponse;`;\n dependencies.clear();\n }\n const importLines = [\n ...(kind === 'blob' ? [`import type { DddFileResponse } from '${DDD_WEB_API_IMPORT}';`] : []),\n ...[...dependencies].map((dependency) => {\n const exported = exportNameOf(dependency);\n const local = localNameOf.get(dependency) ?? dependency;\n return `import { ${exported === local ? local : `${exported} as ${local}`} } from '${importSpecifier(filePath, pathByName.get(dependency)!, esm)}';`;\n }),\n ].join('\\n');\n\n const existing = files.isGeneratedThisRun(filePath) ? files.get(filePath) : undefined;\n const content =\n existing !== undefined\n ? mergeModel(existing, typedBody, importLines, name, logger)\n : (importLines ? `${importLines}\\n\\n` : '') + `${typedBody}\\n\\nexport default ${name};\\n`;\n const fileConsts = constsByFile.get(path.resolve(filePath).toLowerCase());\n files.set(filePath, fileConsts ? withEnumConsts(content, name, [...fileConsts.values()]) : content);\n\n if (isPresentation(path.relative(modelsDir, filePath))) continue;\n // a name another folder holds too stays out of the barrel (two `export *` of one name break it)\n if (name !== uniqueName) continue;\n barrelEntries.push(`export * from '${importSpecifier(indexPath, filePath, esm)}';`);\n }\n\n if (writeIndex) writeBarrel(files, indexPath, barrelEntries);\n\n const others = entries.filter((entry) => path.relative(modelsDir, entry.filePath).split(path.sep)[0] === '_others');\n if (others.length > 0) {\n logger.warn(`${others.length} type(s) without a namespace match placed in _others/: ${others.map((e) => e.name).join(', ')}`);\n }\n logger.info(` extracted ${entries.length} types`);\n\n // the api file imports each model by its path when there is no barrel or a model is missing from it\n if (!writeIndex || usedInApi.some((usedName) => exportNameOf(usedName) !== usedName) || documentModels.size > 0) {\n const importLines = usedInApi.map((usedName) => {\n const exported = exportNameOf(usedName);\n return `import { ${exported === usedName ? usedName : `${exported} as ${usedName}`} } from '${importSpecifier(input.apiFilePath, pathByName.get(usedName)!, esm)}';`;\n });\n return `${importLines.join('\\n')}\\n\\n${strippedSource}`;\n }\n const modelsImport = esm\n ? importSpecifier(input.apiFilePath, indexPath, true)\n : importSpecifier(input.apiFilePath, indexPath, false).replace(/\\/index$/, '');\n return `import {\\n ${usedInApi.join(',\\n ')}\\n} from '${modelsImport}';\\n\\n${strippedSource}`;\n}\n\n/**\n * Barrel: previous entries first, then new ones, each file once. Model names are unique per file (see\n * {@link extractModels}), so no entry is dropped; entries whose file no longer exists in the store are removed.\n */\nfunction writeBarrel(files: OutputFiles, indexPath: string, newEntries: string[]): void {\n const existing = (files.get(indexPath) ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.startsWith('export *'));\n const merged: string[] = [];\n const seen = new Set<string>();\n for (const entry of [...existing, ...newEntries]) {\n const specifier = entry.match(/from ['\"](.+)['\"];?\\s*$/)?.[1];\n if (!specifier) continue;\n const target = path.resolve(path.dirname(indexPath), specifier.replace(/\\.js$/, '')) + '.ts';\n const key = target.toLowerCase();\n if (seen.has(key) || !files.findPath(target)) continue;\n seen.add(key);\n merged.push(entry);\n }\n files.set(indexPath, `${merged.join('\\n')}\\n`);\n}\n\n/** The model file with its enum const objects before the default export (a merged file loses them; they come back). */\nfunction withEnumConsts(content: string, name: string, constTexts: string[]): string {\n const defaultExport = `export default ${name};`;\n const withoutConsts = content.replace(/\\nexport const \\w+ = \\{[\\s\\S]*?\\n\\}(?: as const)?;\\n/g, '\\n');\n const at = withoutConsts.lastIndexOf(defaultExport);\n const head = (at >= 0 ? withoutConsts.slice(0, at) : withoutConsts).replace(/\\s+$/, '');\n return `${head}\\n\\n${constTexts.join('\\n\\n')}\\n\\n${defaultExport}\\n`;\n}\n","import type { FilterOperator } from './operators';\n\n/**\n * Types of the `x-ddd-*` OpenAPI extensions emitted by DDD Core, plus the defaults that apply when an extension is\n * absent. All extensions are additive: a document without them is valid and is read with the defaults below.\n */\n\n/** `info.x-ddd-contract`: contract number and the emitting `mgamadeus/ddd` version. */\nexport interface DddContractInfo {\n /** Contract number; bumped on every change of an `x-ddd-*` key, an implicit part or a default. */\n contract: number;\n /** Version of the `mgamadeus/ddd` package that emitted the document, e.g. `3.14.0`. */\n ddd: string;\n}\n\n/**\n * Column kind of a filter (`FiltersDefinition::COLUMN_KIND_*`): what a filter value is validated and bound as.\n * `translatable` is a plain `#[Translatable]` (JSON of all languages), `translatable-searchable` one with\n * `fullTextIndex: true` (comparisons run on its virtual search column).\n */\nexport type DddColumnKind =\n | 'int'\n | 'float'\n | 'bool'\n | 'string'\n | 'datetime'\n | 'json'\n | 'translatable'\n | 'translatable-searchable';\n\n/**\n * Temporal kind of a filter (`FiltersDefinition::TEMPORAL_KIND_*`): `MOMENT` = an instant (date-time),\n * `DAY` = a calendar day (date, never zone-converted).\n */\nexport type DddTemporalKind = 'MOMENT' | 'DAY';\n\n/**\n * A value rule for one operator of a filter. Known rules:\n * - `wildcard-required`: the value must contain `*` (plain Translatable `eq` / `ne`, a LIKE on the JSON text);\n * - `null-only`: only a null comparison is allowed (JSON columns).\n * Further rules may be added by the contract; unknown rules must be ignored by clients.\n */\nexport type DddFilterValueRule = 'wildcard-required' | 'null-only' | (string & {});\n\n/** One filter definition inside `x-ddd-query.filters`. */\nexport interface DddFilterDefinition {\n /** Filter property name as used in `filters`, may be dotted (e.g. `author.name`). */\n name: string;\n /** Path of the filtered value in the response schema (e.g. `changeHistory.createdTime`); `null` if none. */\n path?: string | null;\n /** Column kind; absent or `null` = no value validation on the backend. */\n columnKind?: DddColumnKind | null;\n /** Temporal kind; absent or `null` = not temporal. */\n temporalKind?: DddTemporalKind | null;\n /** Whether `ft` / `fb` work on this filter (single-column FULLTEXT index). */\n supportsFulltext?: boolean;\n /** Allowed values (`FiltersDefinition::$options`); every value, also each list item, must be one of them. */\n options?: Array<string | number> | null;\n /** Operators allowed for this filter; absent = every operator the column kind accepts. */\n operators?: FilterOperator[];\n /** Value rules per operator. */\n valueRules?: Partial<Record<FilterOperator, DddFilterValueRule>>;\n /** Name of the expand that must be present in `expand` for this filter to be accepted; absent = none. */\n requiresExpand?: string | null;\n}\n\n/** One expand definition inside `x-ddd-query.expand`. */\nexport interface DddExpandDefinition {\n /** Property name to expand (no dots; nesting goes through `expand`). */\n name: string;\n /** `true` for a computed field (no relation, no clauses), e.g. a rendered SVG. */\n computed?: boolean;\n /** Default `top` inside the expand clause. */\n top?: number;\n /** Upper bound for `top` inside the expand clause. */\n maxTop?: number | null;\n /** Default `skip` inside the expand clause. */\n skip?: number;\n /** Filters available inside the expand clause (`filters=` in `(…)`). */\n filters?: DddFilterDefinition[];\n /** Sortable properties inside the expand clause. */\n orderBy?: string[];\n /** Nested expands (`expand=` in `(…)`). */\n expand?: DddExpandDefinition[];\n}\n\n/** `x-ddd-query` on an operation whose request DTO applies QueryOptions. */\nexport interface DddQueryDefinition {\n filters?: DddFilterDefinition[];\n /** Sortable property names. */\n orderBy?: string[];\n expand?: DddExpandDefinition[];\n /** `true` = `select` accepted (any property), a list = the selectable properties, `false`/absent = not exposed. */\n select?: boolean | string[];\n /** Default page size (backend default 50). */\n top?: number;\n /** Upper bound for `top` (`#[QueryOptions(maxTop: …)]`); a larger `top` answers 400. */\n maxTop?: number | null;\n}\n\n/** `x-ddd-entity.action`. DDD `#[Update]` is an upsert. */\nexport type DddEntityAction = 'list' | 'get' | 'upsert' | 'delete' | 'action';\n\n/**\n * `x-ddd-entity` on an operation. Absent = unknown entity: clients derive the identity from the path or the request body\n * and invalidate the whole tag type only when none is found.\n */\nexport interface DddEntityInfo {\n /** Entity schema name, e.g. `App.Domain.Library.Entities.Books.Book`. */\n schema: string;\n action: DddEntityAction;\n /** Identity source, `path:<parameter>` or `body:<dotted.path>` (e.g. `body:book.id`). */\n identity?: string;\n /** `true` when derived by DDD Core, `false` when set explicitly via `#[OperationEntity]`. */\n derived: boolean;\n}\n\n/** Field-level `x-ddd-translatable` (from `#[Translatable]`). */\nexport interface DddTranslatableInfo {\n fullTextIndex?: boolean;\n fullTextMode?: string;\n}\n\n/** Extensions on the document `info` object. */\nexport interface DddInfoExtensions {\n 'x-ddd-contract'?: DddContractInfo;\n}\n\n/** Extensions on an operation object. */\nexport interface DddOperationExtensions {\n 'x-ddd-query'?: DddQueryDefinition;\n /** Absent = default by HTTP method (see {@link hasSideEffects}). */\n 'x-ddd-side-effects'?: boolean;\n 'x-ddd-entity'?: DddEntityInfo;\n /** Cache TTL in seconds from `#[RequestCache]`. */\n 'x-ddd-cache-ttl'?: number;\n}\n\n/** Extensions on a schema property. */\nexport interface DddPropertyExtensions {\n 'x-ddd-translatable'?: DddTranslatableInfo;\n /** `#[HideProperty]`: never in responses, accepted in requests (write-only). Absent = visible. */\n 'x-ddd-hidden'?: boolean;\n /** The stored value is kept when the property is omitted on an update of an existing entity. */\n 'x-ddd-preserve-on-omission'?: boolean;\n}\n\n/** Extensions on an entity schema. */\nexport interface DddSchemaExtensions {\n /** Roles required to write the entity (`RolesRequiredForUpdate`). */\n 'x-ddd-roles-required-for-update'?: string[];\n}\n\n/** HTTP methods of OpenAPI operations (lowercase or uppercase accepted by the helpers). */\nexport type HttpMethod = 'get' | 'head' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'trace';\n\n/**\n * Whether an operation has side effects (contract defaults, Appendix A.6): `x-ddd-side-effects` wins when present,\n * otherwise `false` for GET/HEAD/OPTIONS/TRACE and `true` for POST/PUT/PATCH/DELETE.\n */\nexport function hasSideEffects(method: string, operation?: Pick<DddOperationExtensions, 'x-ddd-side-effects'> | null): boolean {\n const explicit = operation?.['x-ddd-side-effects'];\n if (typeof explicit === 'boolean') {\n return explicit;\n }\n return !['get', 'head', 'options', 'trace'].includes(method.toLowerCase());\n}\n\n/** Whether a property is write-only (`x-ddd-hidden: true`). Absent = visible. */\nexport function isHiddenProperty(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-hidden'] === true;\n}\n\n/** Whether a property keeps its stored value when omitted on an update (`x-ddd-preserve-on-omission: true`). */\nexport function isPreservedOnOmission(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-preserve-on-omission'] === true;\n}\n\n/** Whether a property is `#[Translatable]` (`x-ddd-translatable` present). */\nexport function isTranslatableProperty(property?: DddPropertyExtensions | null): boolean {\n return property?.['x-ddd-translatable'] !== undefined && property['x-ddd-translatable'] !== null;\n}\n\n/** Parsed `x-ddd-entity.identity`. */\nexport interface DddEntityIdentity {\n source: 'path' | 'body';\n /** Path parameter name (`source: 'path'`) or dotted body path (`source: 'body'`). */\n name: string;\n}\n\n/** Parses `x-ddd-entity.identity` (`path:bookId`, `body:book.id`); `null` for an absent or malformed value. */\nexport function parseEntityIdentity(identity: string | null | undefined): DddEntityIdentity | null {\n if (!identity) {\n return null;\n }\n const match = /^(path|body):(.+)$/.exec(identity);\n if (!match) {\n return null;\n }\n return { source: match[1] as 'path' | 'body', name: match[2] as string };\n}\n\n/** Reads `info.x-ddd-contract` from an OpenAPI document; `null` when the document carries no contract version. */\nexport function getContractInfo(document: { info?: DddInfoExtensions | null } | null | undefined): DddContractInfo | null {\n const contract = document?.info?.['x-ddd-contract'];\n if (!contract || typeof contract.contract !== 'number' || typeof contract.ddd !== 'string') {\n return null;\n }\n return contract;\n}\n","import { hasSideEffects } from '../contract/extensions';\nimport type { OperationMatcher, SideEffectsOverride } from './config';\nimport type { DddEntityExtension, HttpMethod, OpenApiDocument, OpenApiOperation } from './openapi';\nimport { listOperations, operationKey } from './openapi';\n\nexport interface OperationInfo {\n method: HttpMethod;\n path: string;\n operation: OpenApiOperation;\n /** Resolved: extension → config override → contract default (`hasSideEffects`: GET/HEAD/OPTIONS/TRACE read). */\n sideEffects: boolean;\n /** True when the classification came from `x-ddd-side-effects` or a config override. */\n sideEffectsExplicit: boolean;\n endpointType: 'query' | 'mutation';\n entity?: DddEntityExtension;\n}\n\nexport interface OperationIndex {\n byKey: Map<string, OperationInfo>;\n /** Keys (`POST /path`) of POST twins that are not generated. */\n skippedTwins: Set<string>;\n}\n\n/** `RegExp.test` without the `lastIndex` state of `g` / `y` expressions. */\nexport function testPattern(pattern: RegExp, value: string): boolean {\n pattern.lastIndex = 0;\n const result = pattern.test(value);\n pattern.lastIndex = 0;\n return result;\n}\n\n/** Whether a config override (`{ method?, path: string | RegExp }`) applies to an operation. */\nexport function matchesOperation(override: OperationMatcher, method: HttpMethod, path: string): boolean {\n if (override.method && override.method.toLowerCase() !== method) return false;\n return typeof override.path === 'string' ? override.path === path : testPattern(override.path, path);\n}\n\n/** JSON with sorted object keys, for structural comparison. */\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_key, inner: unknown) =>\n inner && typeof inner === 'object' && !Array.isArray(inner)\n ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, (inner as Record<string, unknown>)[key]]))\n : inner,\n ) ?? 'undefined';\n}\n\n/**\n * Whether the POST is the twin of an upsert PATCH on the same path (DDD `#[Update]` routes both verbs to one action).\n * With `x-ddd-entity` the annotation decides: both must be `upsert` of the same schema; a conflicting or one-sided\n * non-upsert annotation keeps the POST. Without annotations (older specs) summary, parameters, request body,\n * responses and the side-effect classification must all be identical.\n */\nfunction isUpsertTwin(post: OpenApiOperation, patch: OpenApiOperation): boolean {\n if (post['x-ddd-side-effects'] !== patch['x-ddd-side-effects']) return false;\n const postEntity = isEntityExtension(post['x-ddd-entity']) ? post['x-ddd-entity'] : undefined;\n const patchEntity = isEntityExtension(patch['x-ddd-entity']) ? patch['x-ddd-entity'] : undefined;\n if (postEntity && patchEntity) {\n return postEntity.action === 'upsert' && patchEntity.action === 'upsert' && postEntity.schema === patchEntity.schema;\n }\n if ((postEntity && postEntity.action !== 'upsert') || (patchEntity && patchEntity.action !== 'upsert')) return false;\n if (post.summary === undefined || post.summary !== patch.summary) return false;\n return (['parameters', 'requestBody', 'responses'] as const).every((key) => canonical(post[key]) === canonical(patch[key]));\n}\n\nfunction isEntityExtension(value: unknown): value is DddEntityExtension {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as DddEntityExtension).schema === 'string' &&\n typeof (value as DddEntityExtension).action === 'string'\n );\n}\n\nexport function indexOperations(\n doc: OpenApiDocument,\n overrides: SideEffectsOverride[],\n skipUpdatePostTwins: boolean,\n): OperationIndex {\n const byKey = new Map<string, OperationInfo>();\n for (const { method, path, operation } of listOperations(doc)) {\n const extension = operation['x-ddd-side-effects'];\n const override = overrides.find((candidate) => matchesOperation(candidate, method, path));\n let sideEffects = hasSideEffects(method, operation);\n let explicit = false;\n if (typeof extension === 'boolean') {\n sideEffects = extension;\n explicit = true;\n } else if (override) {\n sideEffects = override.sideEffects;\n explicit = true;\n }\n const naturalType = method === 'get' ? 'query' : 'mutation';\n const classifiedType = explicit ? (sideEffects ? 'mutation' : 'query') : naturalType;\n const endpointType = (typeof extension !== 'boolean' && override?.endpointType) || classifiedType;\n const entity = isEntityExtension(operation['x-ddd-entity']) ? operation['x-ddd-entity'] : undefined;\n byKey.set(operationKey(method, path), {\n method,\n path,\n operation,\n sideEffects,\n sideEffectsExplicit: explicit,\n endpointType,\n ...(entity ? { entity } : {}),\n });\n }\n\n const skippedTwins = new Set<string>();\n if (skipUpdatePostTwins) {\n for (const [path, item] of Object.entries(doc.paths ?? {})) {\n const post = item?.post;\n const patch = item?.patch;\n if (post && patch && isUpsertTwin(post, patch)) {\n skippedTwins.add(operationKey('post', path));\n }\n }\n }\n return { byKey, skippedTwins };\n}\n\n/** Operations whose generated hook kind differs from RTK's verb-based default (GET → query). */\nexport function endpointTypeOverrides(index: OperationIndex): Array<{ method: HttpMethod; path: string; type: 'query' | 'mutation' }> {\n const result: Array<{ method: HttpMethod; path: string; type: 'query' | 'mutation' }> = [];\n for (const info of index.byKey.values()) {\n const rtkDefault = info.method === 'get' ? 'query' : 'mutation';\n if (info.endpointType !== rtkDefault) result.push({ method: info.method, path: info.path, type: info.endpointType });\n }\n return result;\n}\n","import type { ResponseHandlerOverride } from './config';\nimport type { EndpointInfo } from './endpoints';\nimport type { OpenApiDocument } from './openapi';\nimport { listOperations, operationKey } from './openapi';\nimport type TypeScript from 'typescript';\nimport { SdkGenerationError } from './log';\nimport { matchesOperation } from './operations';\nimport { loadTypeScript } from './typescript';\n\n/** How a generated endpoint reads a successful response. `json` is RTK's default (no handler injected). */\nexport type ResponseKind = 'json' | 'text' | 'blob';\n\n/** Import specifier of the package's `api` entry, used by generated binary endpoints. */\nexport const DDD_WEB_API_IMPORT = '@mgamadeus/ddd-web/api';\n\nconst TEXT_CONTENT_TYPES = ['text/html', 'text/plain', 'text/xml'];\nconst FILE_CONTENT_TYPES = [\n 'application/octet-stream',\n 'application/zip',\n 'application/x-zip-compressed',\n 'application/gzip',\n 'application/x-gzip',\n 'application/x-tar',\n 'application/x-7z-compressed',\n 'application/pdf',\n 'application/msword',\n 'application/vnd.',\n 'text/csv',\n 'image/',\n 'audio/',\n 'video/',\n 'font/',\n];\n\n/** Media type without parameters, lower case (`Application/PDF; q=1` → `application/pdf`). */\nconst mediaType = (type: string): string => type.split(';')[0]!.trim().toLowerCase();\n\n/** JSON media types (`application/json`, `application/problem+json`, `application/vnd.api+json`, …). */\nconst isJsonType = (type: string): boolean => /(^|\\/|\\+)json$/.test(mediaType(type));\n\nexport const isTextContentType = (type: string): boolean =>\n !isJsonType(type) && TEXT_CONTENT_TYPES.some((text) => mediaType(type).startsWith(text));\n\n/** Binary / file media types: archives, PDF, office documents (`application/vnd.*`), CSV, images, audio, video, fonts. */\nexport const isFileContentType = (type: string): boolean =>\n !isJsonType(type) && FILE_CONTENT_TYPES.some((file) => mediaType(type).startsWith(file));\n\n/**\n * Response kind of one operation from its 2xx content types: a 2xx response with only file types (or file and text\n * types) is `blob`, one with only text types is `text`, everything else `json`. `blob` wins over `text`.\n */\nexport function detectResponseKind(responses: Record<string, { content?: Record<string, unknown> } | undefined> | undefined): ResponseKind {\n let kind: ResponseKind = 'json';\n for (const [status, response] of Object.entries(responses ?? {})) {\n const code = Number.parseInt(status, 10);\n if (Number.isNaN(code) || code < 200 || code >= 300) continue;\n const types = Object.keys(response?.content ?? {});\n if (types.length === 0) continue;\n if (!types.every((type) => isFileContentType(type) || isTextContentType(type))) continue;\n if (types.some(isFileContentType)) return 'blob';\n kind = 'text';\n }\n return kind;\n}\n\n/**\n * Response kind per generated endpoint key, for endpoints that need a `responseHandler` (`text` or `blob`).\n * Config overrides (first match wins) take precedence over content-type detection; an override `json` keeps RTK's\n * JSON parsing even for a detected text or file response.\n */\nexport function detectResponseHandlerEndpoints(\n doc: OpenApiDocument,\n endpoints: EndpointInfo[],\n overrides: ResponseHandlerOverride[] = [],\n): Map<string, Exclude<ResponseKind, 'json'>> {\n const kinds = new Map<string, ResponseKind>();\n for (const { method, path, operation } of listOperations(doc)) {\n const override = overrides.find((candidate) => matchesOperation(candidate, method, path));\n const kind = override ? override.handler : detectResponseKind(operation.responses);\n if (kind !== 'json') kinds.set(operationKey(method, path), kind);\n }\n const keys = new Map<string, Exclude<ResponseKind, 'json'>>();\n if (kinds.size === 0) return keys;\n for (const endpoint of endpoints) {\n const kind = kinds.get(operationKey(endpoint.method, endpoint.path));\n if (kind === 'text' || kind === 'blob') keys.set(endpoint.key, kind);\n }\n return keys;\n}\n\nconst HANDLER_EXPRESSION: Record<Exclude<ResponseKind, 'json'>, string> = {\n text: '\"text\"',\n blob: 'blobResponseHandler',\n};\n\n/**\n * Inserts `responseHandler: \"text\"` / `responseHandler: blobResponseHandler` into the object returned by each\n * endpoint's `query` function, and imports `blobResponseHandler` from {@link DDD_WEB_API_IMPORT} when needed.\n *\n * Endpoints are located on the TypeScript syntax tree (property `key: build.query<…>(…)` /\n * `build.mutation<…>(…)`), so the result does not depend on how the source is formatted or wrapped. Throws an\n * {@link SdkGenerationError} listing every endpoint whose handler could not be injected — the generated result type\n * already assumes the handler, so a silent skip would produce an SDK that lies about its responses.\n */\nexport function injectResponseHandlers(source: string, endpointKinds: ReadonlyMap<string, Exclude<ResponseKind, 'json'>>): string {\n if (endpointKinds.size === 0) return source;\n const ts = loadTypeScript();\n const file = ts.createSourceFile('api.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: { position: number; text: string }[] = [];\n const found = new Set<string>();\n const failed = new Map<string, string>();\n let usesBlob = false;\n\n const visit = (node: TypeScript.Node): void => {\n if (ts.isPropertyAssignment(node)) {\n const key = propertyName(ts, node.name);\n const kind = key === undefined ? undefined : endpointKinds.get(key);\n if (key !== undefined && kind && isBuildCall(ts, node.initializer)) {\n if (found.has(key)) {\n failed.set(key, 'defined more than once');\n return;\n }\n found.add(key);\n const target = queryReturnObject(ts, node.initializer);\n if (typeof target === 'string') {\n failed.set(key, target);\n return;\n }\n const edit = insertProperty(source, target, `responseHandler: ${HANDLER_EXPRESSION[kind]}`);\n if (typeof edit === 'string') {\n failed.set(key, edit);\n return;\n }\n edits.push(...edit);\n if (kind === 'blob') usesBlob = true;\n return;\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(file);\n\n for (const key of endpointKinds.keys()) {\n if (!found.has(key) && !failed.has(key)) failed.set(key, 'no `build.query` / `build.mutation` definition found');\n }\n if (failed.size > 0) {\n const list = [...failed].map(([key, reason]) => ` - ${key} (${endpointKinds.get(key)}): ${reason}`).join('\\n');\n throw new SdkGenerationError(`Could not inject the responseHandler into ${failed.size} endpoint(s):\\n${list}`);\n }\n\n let result = source;\n for (const { position, text } of edits.sort((a, b) => b.position - a.position)) {\n result = result.slice(0, position) + text + result.slice(position);\n }\n return usesBlob ? `import { blobResponseHandler } from '${DDD_WEB_API_IMPORT}';\\n${result}` : result;\n}\n\nexport function propertyName(ts: typeof TypeScript, name: TypeScript.PropertyName): string | undefined {\n if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) return name.text;\n return undefined;\n}\n\n/** `build.query<…>(…)` or `build.mutation<…>(…)`. */\nexport function isBuildCall(ts: typeof TypeScript, node: TypeScript.Expression): node is TypeScript.CallExpression {\n return (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n (node.expression.name.text === 'query' || node.expression.name.text === 'mutation')\n );\n}\n\n/** The object literal returned by the endpoint's `query` function, or the reason it could not be found. */\nexport function queryReturnObject(ts: typeof TypeScript, call: TypeScript.CallExpression): TypeScript.ObjectLiteralExpression | string {\n const definition = call.arguments[0];\n if (!definition || !ts.isObjectLiteralExpression(definition)) return 'endpoint definition is not an object literal';\n const query = definition.properties.find(\n (property) => property.name !== undefined && propertyName(ts, property.name) === 'query',\n );\n if (!query) return 'no `query` property';\n let fn: TypeScript.Expression | undefined;\n if (ts.isPropertyAssignment(query)) fn = query.initializer;\n if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return '`query` is not a function';\n let body: TypeScript.Node = fn.body;\n if (ts.isBlock(body)) {\n const returns = body.statements.filter(ts.isReturnStatement);\n if (returns.length !== 1 || !returns[0]!.expression) return '`query` does not have exactly one return statement';\n body = returns[0]!.expression;\n }\n while (ts.isParenthesizedExpression(body as TypeScript.Expression)) body = (body as TypeScript.ParenthesizedExpression).expression;\n if (!ts.isObjectLiteralExpression(body)) return '`query` does not return an object literal';\n if (body.properties.some((property) => property.name !== undefined && propertyName(ts, property.name) === 'responseHandler')) {\n return '`query` already returns a responseHandler';\n }\n return body;\n}\n\n/** Text edits that add `property` as the last member of `object`, matching its single- or multi-line layout. */\nfunction insertProperty(\n source: string,\n object: TypeScript.ObjectLiteralExpression,\n property: string,\n): { position: number; text: string }[] | string {\n const close = object.end - 1;\n if (source[close] !== '}') return 'unexpected object literal end';\n const last = object.properties[object.properties.length - 1];\n if (!last) return [{ position: close, text: ` ${property} ` }];\n const trailingComma = object.properties.hasTrailingComma === true;\n const lineStart = source.lastIndexOf('\\n', close) + 1;\n const indent = source.slice(lineStart, close);\n if (lineStart > last.end && /^[ \\t]*$/.test(indent)) {\n // closing brace on its own line: a new member line above it\n const edits = [{ position: lineStart, text: `${indent} ${property},\\n` }];\n if (!trailingComma) edits.push({ position: last.end, text: ',' });\n return edits;\n }\n // `{ url: … }` → `{ url: …, responseHandler: … }`\n return trailingComma ? [{ position: close, text: `${property} ` }] : [{ position: last.end, text: `, ${property}` }];\n}\n","import type TypeScript from 'typescript';\nimport type { EndpointInfo } from './endpoints';\nimport type { Logger } from './log';\nimport type { OpenApiDocument } from './openapi';\nimport { listOperations, operationKey } from './openapi';\nimport { DDD_WEB_API_IMPORT, isBuildCall, propertyName, queryReturnObject } from './response-handlers';\nimport { loadTypeScript } from './typescript';\n\n/** Name of the endpoint argument that carries the file parts. */\nexport const MULTIPART_FILES_ARG = 'multipartFiles';\n\n/** Form field of the JSON envelope in a DDD multipart request; never a file field. */\nconst BODY_FIELD = 'body';\n\nconst FILE_PART_TYPE = '(Blob | { uri: string; name: string; type: string })';\n\n/** The multipart side of one operation. */\nexport interface MultipartOperation {\n /** Form fields that carry files. */\n fields: string[];\n /** File fields the operation requires. */\n required: string[];\n /** True when the operation accepts no JSON body next to the multipart one. */\n multipartOnly: boolean;\n}\n\ntype JsonObject = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is JsonObject => !!value && typeof value === 'object' && !Array.isArray(value);\n\nfunction resolveRef(doc: OpenApiDocument, value: unknown): JsonObject | undefined {\n let current = value;\n for (let depth = 0; depth < 5 && isObject(current) && typeof current.$ref === 'string'; depth++) {\n const segments = current.$ref.replace(/^#\\//, '').split('/');\n let target: unknown = doc;\n for (const segment of segments) target = isObject(target) ? target[segment.replace(/~1/g, '/').replace(/~0/g, '~')] : undefined;\n current = target;\n }\n return isObject(current) ? current : undefined;\n}\n\nconst isJsonMediaType = (type: string): boolean => /(^|\\/|\\+)json$/.test(type.split(';')[0]!.trim().toLowerCase());\n\n/** The file fields of an operation's `multipart/form-data` request body, or `null` when it has none. */\nexport function readMultipartOperation(doc: OpenApiDocument, requestBody: unknown): MultipartOperation | null {\n const content = resolveRef(doc, requestBody)?.content;\n if (!isObject(content)) return null;\n const multipartKey = Object.keys(content).find((type) => type.split(';')[0]!.trim().toLowerCase() === 'multipart/form-data');\n if (!multipartKey || !isObject(content[multipartKey])) return null;\n const schema = resolveRef(doc, (content[multipartKey] as JsonObject).schema);\n const properties = isObject(schema?.properties) ? schema.properties : {};\n const fields = Object.keys(properties).filter((name) => name !== BODY_FIELD);\n if (fields.length === 0) return null;\n const requiredList = Array.isArray(schema?.required) ? schema.required.filter((name): name is string => typeof name === 'string') : [];\n return {\n fields,\n required: fields.filter((name) => requiredList.includes(name)),\n multipartOnly: !Object.keys(content).some(isJsonMediaType),\n };\n}\n\n/** Multipart operations per generated endpoint key. */\nexport function detectMultipartEndpoints(doc: OpenApiDocument, endpoints: EndpointInfo[]): Map<string, MultipartOperation> {\n const byOperation = new Map<string, MultipartOperation>();\n for (const { method, path, operation } of listOperations(doc)) {\n const multipart = readMultipartOperation(doc, operation.requestBody);\n if (multipart) byOperation.set(operationKey(method, path), multipart);\n }\n const keys = new Map<string, MultipartOperation>();\n if (byOperation.size === 0) return keys;\n for (const endpoint of endpoints) {\n const multipart = byOperation.get(operationKey(endpoint.method, endpoint.path));\n if (multipart) keys.set(endpoint.key, multipart);\n }\n return keys;\n}\n\nconst quoteKey = (name: string): string => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name));\n\nfunction filesMember(multipart: MultipartOperation): string {\n const members = multipart.fields\n .map((field) => {\n const required = multipart.multipartOnly && multipart.required.includes(field);\n return `${quoteKey(field)}${required ? '' : '?'}: readonly ${FILE_PART_TYPE}[]${required ? '' : ' | null'}`;\n })\n .join('; ');\n const required = multipart.multipartOnly && multipart.required.length > 0;\n const doc = multipart.multipartOnly\n ? '/** File parts of the multipart request. */'\n : '/** File parts: with at least one file the request is sent as multipart/form-data (JSON envelope in the field `body`), else as JSON. */';\n return `${doc}\\n ${MULTIPART_FILES_ARG}${required ? '' : '?'}: { ${members} };`;\n}\n\nexport interface MultipartInjection {\n source: string;\n /** Endpoint keys whose body was rewritten. */\n injected: string[];\n}\n\n/**\n * Makes the endpoints of multipart operations send files: the endpoint argument gets `multipartFiles` (one list per\n * file field) and the request body becomes `buildDddMultipartBody(<json body>, queryArg.multipartFiles)`. An\n * operation that accepts JSON and multipart keeps sending JSON while no file is given; a multipart-only operation\n * loses the body argument RTK codegen derived from the multipart schema.\n *\n * Runs on the RTK output while its types are still inline. An endpoint whose argument is not an object of named\n * members (`flattenArg`) is left as it is, with a warning.\n */\nexport function injectMultipartBodies(source: string, endpoints: ReadonlyMap<string, MultipartOperation>, logger: Logger): MultipartInjection {\n if (endpoints.size === 0) return { source, injected: [] };\n const ts = loadTypeScript();\n const file = ts.createSourceFile('api.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const typeAliases = new Map<string, TypeScript.TypeAliasDeclaration>();\n for (const statement of file.statements) if (ts.isTypeAliasDeclaration(statement)) typeAliases.set(statement.name.text, statement);\n\n const edits: { start: number; end: number; text: string }[] = [];\n const injected: string[] = [];\n const skip = (key: string, reason: string): void => logger.warn(` ${key}: multipart body not generated (${reason}) — the endpoint sends JSON only.`);\n\n const visit = (node: TypeScript.Node): void => {\n if (ts.isPropertyAssignment(node)) {\n const key = propertyName(ts, node.name);\n const multipart = key === undefined ? undefined : endpoints.get(key);\n if (key !== undefined && multipart && isBuildCall(ts, node.initializer)) {\n const call = node.initializer;\n const returned = queryReturnObject(ts, call);\n if (typeof returned === 'string') return skip(key, returned);\n const definition = call.arguments[0] as TypeScript.ObjectLiteralExpression;\n const query = definition.properties.find((property) => property.name !== undefined && propertyName(ts, property.name) === 'query');\n const fn = query && ts.isPropertyAssignment(query) ? query.initializer : undefined;\n const parameter = fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) ? fn.parameters[0] : undefined;\n if (!parameter || !ts.isIdentifier(parameter.name)) return skip(key, 'the endpoint takes no argument');\n const argName = parameter.name.text;\n\n const argTypeNode = call.typeArguments?.[1];\n const alias =\n argTypeNode && ts.isTypeReferenceNode(argTypeNode) && ts.isIdentifier(argTypeNode.typeName)\n ? typeAliases.get(argTypeNode.typeName.text)\n : undefined;\n if (!alias || !ts.isTypeLiteralNode(alias.type)) return skip(key, 'its argument type is not an object type (flattenArg?)');\n const literal = alias.type;\n const memberName = (member: TypeScript.TypeElement): string | undefined =>\n member.name ? propertyName(ts, member.name) : undefined;\n if (literal.members.some((member) => memberName(member) === MULTIPART_FILES_ARG)) {\n return skip(key, `the argument already has a member \"${MULTIPART_FILES_ARG}\"`);\n }\n\n const body = returned.properties.find((property) => property.name !== undefined && propertyName(ts, property.name) === 'body');\n let jsonBody = 'undefined';\n if (body) {\n if (!ts.isPropertyAssignment(body)) return skip(key, 'unexpected `body` member');\n const text = body.initializer.getText(file);\n if (text === argName) return skip(key, 'the argument is the request body itself (flattenArg)');\n if (multipart.multipartOnly) {\n // RTK codegen typed this member from the multipart schema; the files replace it.\n const accessor = new RegExp(`^${argName}\\\\.([A-Za-z_$][A-Za-z0-9_$]*)$`).exec(text)?.[1];\n const member = accessor ? literal.members.find((candidate) => memberName(candidate) === accessor) : undefined;\n if (member) edits.push({ start: member.getFullStart(), end: member.getEnd(), text: '' });\n } else {\n jsonBody = text;\n }\n edits.push({\n start: body.initializer.getStart(file),\n end: body.initializer.getEnd(),\n text: `buildDddMultipartBody(${jsonBody}, ${argName}.${MULTIPART_FILES_ARG})`,\n });\n } else {\n const close = returned.end - 1;\n const separator = returned.properties.length > 0 && !returned.properties.hasTrailingComma ? ', ' : ' ';\n edits.push({ start: close, end: close, text: `${separator}body: buildDddMultipartBody(undefined, ${argName}.${MULTIPART_FILES_ARG}) ` });\n }\n const close = literal.end - 1;\n edits.push({ start: close, end: close, text: `\\n ${filesMember(multipart)}\\n` });\n injected.push(key);\n return;\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(file);\n\n let result = source;\n for (const { start, end, text } of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {\n result = result.slice(0, start) + text + result.slice(end);\n }\n return { source: result, injected };\n}\n\n/** Import line of the multipart helper, for an api file with injected multipart bodies. */\nexport const MULTIPART_IMPORT = `import { buildDddMultipartBody } from '${DDD_WEB_API_IMPORT}';`;\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { OutputFiles } from './files';\nimport { SdkGenerationError } from './log';\n\n/** Moves a file or directory; falls back to copy + delete across devices. */\nexport function defaultMove(from: string, to: string): void {\n fs.mkdirSync(path.dirname(to), { recursive: true });\n try {\n fs.renameSync(from, to);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;\n fs.cpSync(from, to, { recursive: true });\n fs.rmSync(from, { recursive: true, force: true });\n }\n}\n\nexport interface CommitOutputOptions {\n /** File system move (injectable for tests). Default {@link defaultMove}. */\n move?: (from: string, to: string) => void;\n}\n\nexport interface CommittedOutput {\n /** Restores the previous output (used when the type check fails). Throws, keeping the backup, if a restore fails. */\n rollback(): void;\n /** Drops the backup of the previous output. */\n finalize(): void;\n}\n\n/**\n * Writes all files into a staging directory first, then swaps them in: the models directory as a whole\n * (stale models disappear), every other file individually. Nothing in the target is touched before\n * the staging write succeeded; a failure during the swap restores what was there.\n *\n * Every backup move registers its restore immediately, so a failure between \"old output moved away\" and \"new output\n * moved in\" still restores the old output. If a restore fails, the staging directory (with the backups) is kept and\n * the error names it.\n */\nexport function commitOutput(\n files: OutputFiles,\n modelsDir: string,\n stagingParent: string,\n options: CommitOutputOptions = {},\n): CommittedOutput {\n const move = options.move ?? defaultMove;\n fs.mkdirSync(stagingParent, { recursive: true });\n const staging = fs.mkdtempSync(path.join(stagingParent, '.ddd-web-sdk-'));\n const stagedModels = path.join(staging, 'models');\n const backupModels = path.join(staging, 'models.previous');\n const singles: Array<{ target: string; staged: string; backup: string }> = [];\n\n try {\n fs.mkdirSync(stagedModels, { recursive: true });\n for (const filePath of files.paths()) {\n const content = files.get(filePath)!;\n const relative = path.relative(modelsDir, filePath);\n if (!relative.startsWith('..') && !path.isAbsolute(relative)) {\n const staged = path.join(stagedModels, relative);\n fs.mkdirSync(path.dirname(staged), { recursive: true });\n fs.writeFileSync(staged, content);\n } else {\n const staged = path.join(staging, 'files', String(singles.length));\n fs.mkdirSync(path.dirname(staged), { recursive: true });\n fs.writeFileSync(staged, content);\n singles.push({ target: filePath, staged, backup: path.join(staging, 'files.previous', String(singles.length)) });\n }\n }\n } catch (error) {\n fs.rmSync(staging, { recursive: true, force: true });\n throw error;\n }\n\n const undo: Array<() => void> = [];\n const rollback = (): void => {\n const failures: unknown[] = [];\n for (const step of undo.reverse()) {\n try {\n step();\n } catch (error) {\n failures.push(error);\n }\n }\n undo.length = 0;\n if (failures.length > 0) {\n throw new SdkGenerationError(\n `Could not restore the previous output; the previous output is kept in ${staging} ` +\n `(models.previous/, files.previous/): ${failures.map((failure) => (failure as Error).message).join('; ')}`,\n );\n }\n fs.rmSync(staging, { recursive: true, force: true });\n };\n\n /** Moves `target` to `backup` (if it exists) and `staged` to `target`; the restore is registered before the swap. */\n const swap = (target: string, staged: string, backup: string, removeTarget: () => void): void => {\n const state = { backedUp: false, movedIn: false };\n undo.push(() => {\n if (state.movedIn) removeTarget();\n if (state.backedUp) move(backup, target);\n });\n if (fs.existsSync(target)) {\n move(target, backup);\n state.backedUp = true;\n }\n move(staged, target);\n state.movedIn = true;\n };\n\n try {\n swap(modelsDir, stagedModels, backupModels, () => fs.rmSync(modelsDir, { recursive: true, force: true }));\n for (const single of singles) {\n swap(single.target, single.staged, single.backup, () => fs.rmSync(single.target, { force: true }));\n }\n } catch (error) {\n rollback();\n throw error;\n }\n\n return {\n rollback,\n finalize: () => fs.rmSync(staging, { recursive: true, force: true }),\n };\n}\n","import type { Logger } from './log';\nimport type { OpenApiDocument } from './openapi';\n\n/** `[key, segments]`: key = RTK-normalised namespace prefix of a type name, segments = folder path. */\nexport type NamespacePath = [prefix: string, segments: string[]];\n\n/** Replicates RTK codegen's acronym normalisation for the lookup key: AI → Ai, DTOs → Dtos. */\nfunction normalizeSegment(segment: string): string {\n return segment.replace(/([A-Z])([A-Z]+)/g, (_, first: string, rest: string) => first + rest.toLowerCase());\n}\n\nexport function extractSchemaRef(description: string): string | null {\n return description.match(/schemaRef=\"([^\"]+)\"/)?.[1] ?? null;\n}\n\nfunction parseSchemaRef(ref: string): NamespacePath | null {\n const parts = ref.replace('#/components/schemas/', '').split('.');\n const folders = parts.slice(0, -1);\n if (folders.length === 0) return null;\n return [folders.map(normalizeSegment).join(''), folders];\n}\n\n/** Builds the namespace registry from the SchemaDefinition tags of all specs, longest key first. */\nexport function buildRegistry(docs: OpenApiDocument[], logger: Logger): NamespacePath[] {\n const registry = new Map<string, string[]>();\n for (const doc of docs) {\n for (const tag of doc.tags ?? []) {\n if (!tag.description?.includes('SchemaDefinition')) continue;\n const ref = extractSchemaRef(tag.description);\n const entry = ref ? parseSchemaRef(ref) : null;\n if (!entry) continue;\n const [key, segments] = entry;\n const existing = registry.get(key);\n if (existing) {\n if (existing.join('.') !== segments.join('.')) {\n logger.warn(`Registry key collision for \"${key}\" — keeping ${existing.join('.')}, skipping ${ref}`);\n }\n continue;\n }\n registry.set(key, segments);\n }\n }\n return [...registry.entries()].sort((a, b) => b[0].length - a[0].length);\n}\n","import type { Logger } from './log';\nimport type { OpenApiDocument } from './openapi';\nimport { listOperations } from './openapi';\n\ninterface ParameterLike {\n name?: string;\n in?: string;\n $ref?: string;\n}\n\n/** Resolves a local `#/components/parameters/…` reference (also chained); other values are returned as they are. */\nfunction resolveParameter(doc: OpenApiDocument, parameter: ParameterLike): ParameterLike | null {\n let current: ParameterLike | undefined = parameter;\n for (let hops = 0; current?.$ref !== undefined && hops < 10; hops++) {\n const match = /^#\\/components\\/parameters\\/(.+)$/.exec(current.$ref);\n if (!match) return null;\n const name = match[1]!.replace(/~1/g, '/').replace(/~0/g, '~');\n current = (doc.components?.parameters as Record<string, ParameterLike> | undefined)?.[name];\n }\n return current && current.$ref === undefined ? current : null;\n}\n\n/**\n * Adds a `string` path parameter for every `{placeholder}` an operation does not declare. RTK codegen\n * aborts on such operations; the backend should declare them, so each repair is reported. `$ref` parameters are\n * resolved and judged by their actual `name` / `in`.\n * Returns a copy when something was repaired, the original document otherwise.\n */\nexport function repairMissingPathParameters(doc: OpenApiDocument, logger: Logger): OpenApiDocument {\n const repairs: Array<{ path: string; method: string; names: string[] }> = [];\n for (const { method, path, operation } of listOperations(doc)) {\n const placeholders = [...path.matchAll(/\\{([^}]+)\\}/g)].map((match) => match[1]!);\n if (placeholders.length === 0) continue;\n const pathLevel = (doc.paths?.[path]?.parameters as ParameterLike[] | undefined) ?? [];\n const declared = new Set(\n [...pathLevel, ...((operation.parameters as ParameterLike[] | undefined) ?? [])]\n .map((parameter) => resolveParameter(doc, parameter))\n .filter((parameter): parameter is ParameterLike => parameter !== null && parameter.in === 'path')\n .map((parameter) => parameter.name),\n );\n const missing = placeholders.filter((name) => !declared.has(name));\n if (missing.length > 0) repairs.push({ path, method, names: missing });\n }\n if (repairs.length === 0) return doc;\n\n const copy = structuredClone(doc);\n for (const { path, method, names } of repairs) {\n const operation = copy.paths![path]![method as 'get'];\n operation!.parameters = [\n ...names.map((name) => ({ name, in: 'path', required: true, schema: { type: 'string' } })),\n ...(operation!.parameters ?? []),\n ];\n logger.warn(`${method.toUpperCase()} ${path}: path parameter(s) ${names.join(', ')} not declared in the spec — added as string.`);\n }\n return copy;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { generateEndpoints } from '@rtk-query/codegen-openapi';\nimport prettier from 'prettier';\nimport { isPathLike, type ResolvedApi } from './config';\nimport { loadRtkCodegen } from './module-resolution';\nimport type { OperationLocation } from './endpoints';\nimport { endpointTypeOverrides, testPattern, type OperationIndex } from './operations';\nimport type { HttpMethod, OpenApiDocument } from './openapi';\nimport { operationKey } from './openapi';\n\ntype GenerationOptions = Parameters<typeof generateEndpoints>[0];\ntype RtkOperationDefinition = { path: string; verb: string };\ntype Matcher = string | RegExp | Array<string | RegExp> | ((name: string, definition: RtkOperationDefinition) => boolean);\ntype EndpointOverride = { pattern?: Matcher; type?: 'query' | 'mutation'; [option: string]: unknown };\n\n/** Keys of the api config that are ddd-web's own and must not reach RTK codegen. */\nconst OWN_KEYS = new Set(['schemaFile', 'apiFile', 'outputFile', 'audience', 'baseApiImport', 'skipUpdatePostTwins', 'sideEffects', 'responseHandlers', 'invalidation']);\n\n/** RTK codegen's matcher semantics (an absent pattern matches everything); RegExps are tested statelessly. */\nfunction matches(matcher: Matcher | undefined, name: string, definition: RtkOperationDefinition): boolean {\n if (matcher === undefined) return true;\n if (typeof matcher === 'function') return matcher(name, definition);\n const list = Array.isArray(matcher) ? matcher : [matcher];\n return list.some((entry) => (typeof entry === 'string' ? entry === name : testPattern(entry, name)));\n}\n\nconst capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n\n/**\n * RTK codegen applies only the FIRST matching endpoint override. So that a user override (e.g. only a\n * `parameterFilter`) does not displace the side-effect classification, every classified operation gets one merged\n * override per matching user override, placed first: the user's options plus the classified `type` — unless the user\n * override sets `type` itself, which then wins. Plain classification overrides and the user overrides follow.\n */\nexport function mergeEndpointOverrides(\n userOverrides: EndpointOverride[],\n typeOverrides: Array<{ method: HttpMethod; path: string; type: 'query' | 'mutation' }>,\n): EndpointOverride[] {\n const merged: EndpointOverride[] = [];\n for (const operation of typeOverrides) {\n const isOperation = (definition: RtkOperationDefinition): boolean =>\n definition.verb === operation.method && definition.path === operation.path;\n for (const user of userOverrides) {\n merged.push({\n ...user,\n type: user.type ?? operation.type,\n pattern: (name: string, definition: RtkOperationDefinition) => isOperation(definition) && matches(user.pattern, name, definition),\n });\n }\n merged.push({ pattern: (_name: string, definition: RtkOperationDefinition) => isOperation(definition), type: operation.type });\n }\n return [...merged, ...userOverrides];\n}\n\nexport interface RtkCodegenResult {\n code: string;\n /** Endpoint key in the generated file → operation it was generated from. */\n locations: Map<string, OperationLocation>;\n}\n\nexport function relativeImport(fromDir: string, target: string): string {\n if (!isPathLike(target)) return target;\n let relative = path.relative(fromDir, target).replace(/\\\\/g, '/');\n if (!relative.startsWith('.')) relative = `./${relative}`;\n return relative;\n}\n\n/**\n * Runs RTK Query codegen in-process on the already loaded spec (written once to `specFile`) and\n * returns the generated source plus the operation of every endpoint. Side-effect classification is fed in as\n * `endpointOverrides`, twin skipping as `filterEndpoints`; the filter also records which endpoint key belongs to which\n * operation, so later steps never parse URLs back into paths.\n */\nexport async function runRtkCodegen(\n api: ResolvedApi,\n doc: OpenApiDocument,\n index: OperationIndex,\n specFile: string,\n prettierConfigFile: string | undefined,\n /** The endpoint name your matchers see for an RTK operation name (the `endpoints.naming` placeholders); default as is. */\n endpointNameOf: (rtkName: string) => string = (rtkName) => rtkName,\n): Promise<RtkCodegenResult> {\n fs.writeFileSync(specFile, JSON.stringify(doc));\n\n const passthrough: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(api.config)) if (!OWN_KEYS.has(key)) passthrough[key] = value;\n\n // your `endpointOverrides` and `filterEndpoints` match the endpoint names you configured, never a placeholder\n const userOverrides = ((passthrough.endpointOverrides as EndpointOverride[] | undefined) ?? []).map((override) =>\n override.pattern === undefined\n ? override\n : { ...override, pattern: (name: string, definition: RtkOperationDefinition) => matches(override.pattern, endpointNameOf(name), definition) },\n );\n const endpointOverrides = mergeEndpointOverrides(userOverrides, endpointTypeOverrides(index));\n\n const suffix = typeof passthrough.operationNameSuffix === 'string' ? passthrough.operationNameSuffix : '';\n const locations = new Map<string, OperationLocation>();\n const userFilter = passthrough.filterEndpoints as Matcher | undefined;\n const filterEndpoints = (name: string, definition: RtkOperationDefinition): boolean => {\n const included =\n !index.skippedTwins.has(operationKey(definition.verb, definition.path)) &&\n (userFilter === undefined || matches(userFilter, endpointNameOf(name), definition));\n if (included) {\n // Same key RTK codegen writes for the endpoint (`generateEndpoint`'s operationName).\n locations.set(suffix ? capitalize(name + suffix) : name, { method: definition.verb as HttpMethod, path: definition.path });\n }\n return included;\n };\n\n const options = {\n // A path parameter is one URL segment: a value with `/`, `?`, `#` or a space must not change the route.\n // `encodePathParams: false` in the api config switches it off for callers that encode themselves.\n encodePathParams: true,\n ...passthrough,\n schemaFile: specFile,\n apiFile: relativeImport(api.outputDir, api.apiFile),\n apiImport: api.config.apiImport ?? 'api',\n exportName: api.exportName,\n endpointOverrides,\n filterEndpoints,\n ...(prettierConfigFile ? { prettierConfigFile } : {}),\n } as GenerationOptions;\n\n const { generateEndpoints: generateRtkEndpoints } = await loadRtkCodegen();\n const code = await generateRtkEndpoints(options);\n if (typeof code !== 'string') throw new Error(`RTK codegen returned no code for ${api.stem}.`);\n return { code, locations };\n}\n\nexport async function findPrettierConfigFile(rootDir: string): Promise<string | undefined> {\n return (await prettier.resolveConfigFile(path.join(rootDir, 'openapi-config.ts'))) ?? undefined;\n}\n","import Module, { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\ntype ResolveFilename = (request: string, parent: { filename?: string | null } | undefined, ...rest: unknown[]) => string;\n\nlet installed = false;\n\n/**\n * Answers the `ajv` lookups of `ajv-draft-04` from the `ajv` 8 of the OpenAPI parser\n * (`@apidevtools/swagger-parser`, a dependency of `@rtk-query/codegen-openapi`).\n *\n * `ajv-draft-04` expects `ajv` 8 as a peer. A consumer that installs with `legacy-peer-deps` gets `ajv-draft-04` hoisted\n * to the top of `node_modules`, next to an `ajv` 6 of its own tooling, and the parser fails to load. The parser's own\n * `ajv` 8 is answered instead; a lookup the parser cannot answer keeps the default resolution. Installed once, before the\n * codegen is loaded ({@link loadRtkCodegen}).\n */\nexport function installParserModuleResolution(): void {\n if (installed) return;\n installed = true;\n const require = createRequire(import.meta.url);\n let parserRequire: NodeJS.Require;\n try {\n const codegenRequire = createRequire(require.resolve('@rtk-query/codegen-openapi'));\n parserRequire = createRequire(codegenRequire.resolve('@apidevtools/swagger-parser'));\n } catch {\n return;\n }\n const ajvDraft04Folder = `${path.sep}ajv-draft-04${path.sep}`;\n const moduleWithResolver = Module as unknown as { _resolveFilename: ResolveFilename };\n const defaultResolveFilename = moduleWithResolver._resolveFilename;\n moduleWithResolver._resolveFilename = function resolveAjvOfTheParser(request, parent, ...rest) {\n if ((request === 'ajv' || request.startsWith('ajv/')) && parent?.filename?.includes(ajvDraft04Folder)) {\n try {\n return parserRequire.resolve(request);\n } catch {\n // the parser has no such module: the default resolution answers\n }\n }\n return defaultResolveFilename.call(this, request, parent, ...rest);\n };\n}\n\n/** `@rtk-query/codegen-openapi`, loaded after {@link installParserModuleResolution}. */\nexport async function loadRtkCodegen(): Promise<typeof import('@rtk-query/codegen-openapi')> {\n installParserModuleResolution();\n return import('@rtk-query/codegen-openapi');\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as readline from 'node:readline';\nimport type { WorkspaceOptions } from './config';\nimport type { Logger } from './log';\n\nconst DEFAULT_ENV_FILES = ['.env', '.env.local'];\nconst DEFAULT_URL_KEYS = ['NEXT_PUBLIC_API_URL', 'EXPO_PUBLIC_API_URL', 'VITE_API_URL', 'VITE_API_ENDPOINT', 'API_URL'];\n\nfunction parseEnvFile(filePath: string): Record<string, string> {\n if (!fs.existsSync(filePath)) return {};\n const vars: Record<string, string> = {};\n for (const line of fs.readFileSync(filePath, 'utf-8').split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq < 1) continue;\n vars[trimmed.slice(0, eq).trim()] = trimmed\n .slice(eq + 1)\n .trim()\n .replace(/^[\"']|[\"']$/g, '');\n }\n return vars;\n}\n\nfunction firstHostLabel(url: string): string | null {\n try {\n return new URL(url).hostname.split('.')[0] || null;\n } catch {\n return null;\n }\n}\n\nexport function sniffWorkspace(rootDir: string, options: WorkspaceOptions): string | null {\n for (const file of options.envFiles ?? DEFAULT_ENV_FILES) {\n const vars = parseEnvFile(path.join(rootDir, file));\n for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {\n const value = vars[key];\n const label = value ? firstHostLabel(value) : null;\n if (label) return label;\n }\n }\n return null;\n}\n\nfunction ask(question: string): Promise<string> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n rl.on('close', () => resolve(''));\n rl.question(question, (answer) => {\n resolve(answer.trim());\n rl.close();\n });\n });\n}\n\n/**\n * Resolves the workspace value (explicit → env → .env sniff → TTY prompt) and exports it into the env\n * variable the config reads. Returns null when nothing resolved; the caller continues with whatever\n * default the config itself applies — a non-interactive run is never blocked.\n */\nexport async function resolveWorkspace(\n rootDir: string,\n options: WorkspaceOptions,\n explicit: string | undefined,\n logger: Logger,\n): Promise<string | null> {\n let value = explicit?.trim() || process.env[options.envVar]?.trim() || null;\n const sniffed = value ? null : sniffWorkspace(rootDir, options);\n if (!value && process.stdin.isTTY && options.prompt !== false) {\n const hint = sniffed ? ` [${sniffed}]` : '';\n value = (await ask(`[ddd-web-sdk] ${options.envVar}${hint}: `)) || sniffed;\n } else if (!value) {\n value = sniffed;\n }\n if (value) {\n process.env[options.envVar] = value;\n logger.info(`${options.envVar}=${value}`);\n } else {\n logger.warn(`${options.envVar} not set and not resolvable — using the config's own default.`);\n }\n return value;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { consoleLogger, type Logger } from './log';\n\nexport interface LinkSkillsOptions {\n cwd?: string;\n /** Directory holding the package's skills. Default `<cwd>/node_modules/@mgamadeus/ddd-web/.claude/skills`. */\n sourceDir?: string;\n logger?: Logger;\n}\n\nexport type LinkSkillAction = 'linked' | 'relinked' | 'unchanged' | 'skipped';\n\nexport interface LinkSkillsResult {\n skill: string;\n action: LinkSkillAction;\n target: string;\n}\n\n/** `@mgamadeus/ddd-web <version>` of the installed package, or the bare name when the version is unknown. */\nfunction packageLabel(packageDir: string | undefined): string {\n if (packageDir) {\n try {\n const version = (JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8')) as { version?: unknown }).version;\n if (typeof version === 'string') return `@mgamadeus/ddd-web ${version}`;\n } catch {\n // no readable manifest: fall back to the bare name\n }\n }\n return '@mgamadeus/ddd-web';\n}\n\n/**\n * Symlinks every skill directory of the installed package into `<cwd>/.claude/skills/`. Idempotent;\n * an existing symlink is repointed, a real file or directory is never touched. A package version that ships no\n * skills is reported as such (nothing is created).\n */\nexport function linkSkills(options: LinkSkillsOptions = {}): LinkSkillsResult[] {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n const logger = options.logger ?? consoleLogger;\n const packageDir = path.join(cwd, 'node_modules', '@mgamadeus', 'ddd-web');\n const sourceDir = options.sourceDir ? path.resolve(cwd, options.sourceDir) : path.join(packageDir, '.claude', 'skills');\n if (!options.sourceDir && !fs.existsSync(packageDir)) {\n logger.warn(`@mgamadeus/ddd-web is not installed in ${cwd} (no ${packageDir}) — nothing to link.`);\n return [];\n }\n const skills = fs.existsSync(sourceDir)\n ? fs.readdirSync(sourceDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() || entry.isSymbolicLink())\n : [];\n if (skills.length === 0) {\n logger.info(`${packageLabel(options.sourceDir ? undefined : packageDir)} ships no agent skills (${sourceDir}) — nothing to link.`);\n return [];\n }\n const targetDir = path.join(cwd, '.claude', 'skills');\n fs.mkdirSync(targetDir, { recursive: true });\n\n const results: LinkSkillsResult[] = [];\n for (const entry of skills) {\n const linkPath = path.join(targetDir, entry.name);\n const linkTarget = path.relative(targetDir, path.join(sourceDir, entry.name));\n let action: LinkSkillAction;\n const existing = fs.lstatSync(linkPath, { throwIfNoEntry: false });\n if (!existing) {\n fs.symlinkSync(linkTarget, linkPath, 'dir');\n action = 'linked';\n } else if (!existing.isSymbolicLink()) {\n action = 'skipped';\n } else if (fs.readlinkSync(linkPath) === linkTarget) {\n action = 'unchanged';\n } else {\n fs.unlinkSync(linkPath);\n fs.symlinkSync(linkTarget, linkPath, 'dir');\n action = 'relinked';\n }\n const message = `${action.padEnd(9)} .claude/skills/${entry.name} → ${linkTarget}`;\n if (action === 'skipped') logger.warn(`${message} (exists and is not a symlink — left as is)`);\n else logger.info(message);\n results.push({ skill: entry.name, action, target: linkTarget });\n }\n return results;\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,kBAAkB;AA2KpB,SAAS,aAAa,QAA8B;AACzD,SAAO;AACT;AAYA,eAAsB,WAAW,YAA2C;AAC1E,QAAM,WAAgB,aAAQ,UAAU;AACxC,MAAI,CAAI,cAAW,QAAQ,GAAG;AAC5B,UAAM,IAAI,MAAM,0BAA0B,QAAQ,EAAE;AAAA,EACtD;AAEA,QAAM,OAAO,WAAW,UAAU,EAAE,aAAa,OAAO,SAAS,MAAM,CAAC;AACxE,QAAM,MAAO,MAAM,KAAK,OAAO,QAAQ;AACvC,QAAM,SAAS,sBAAsB,KAAK,QAAQ;AAClD,SAAO,EAAE,QAAQ,YAAY,UAAU,SAAc,aAAQ,QAAQ,EAAE;AACzE;AAEA,SAAS,sBAAsB,KAA8B,YAA+B;AAC1F,QAAM,YAAa,IAAI,WAAW,IAAI,UAAU;AAChD,MAAI,MAAM,QAAQ,SAAS,EAAG,QAAO,EAAE,MAAM,UAA4B;AACzE,MAAI,aAAa,OAAO,cAAc,YAAY,MAAM,QAAQ,UAAU,IAAI,GAAG;AAC/E,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,IAAI,IAAI,EAAG,QAAO,EAAE,MAAM,IAAI,KAAuB;AACvE,QAAM,IAAI;AAAA,IACR,GAAG,UAAU;AAAA,EACf;AACF;AAmBO,SAAS,YAAY,QAAqC;AAC/D,QAAM,EAAE,QAAQ,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UAAU,MAAM,YAAY,KAAK,MAAM,eAAe,CAAC,IAClH,CAAC;AACL,MAAI,OAAO,WAAW,GAAG;AACvB,WAAO,KAAK,GAAG,aAAa,QAAQ,YAAY,SAAY,UAAU,CAAC,2BAA2B,SAAS,2BAAsB;AACjI,WAAO,CAAC;AAAA,EACV;AACA,QAAM,YAAiB,YAAK,KAAK,WAAW,QAAQ;AACpD,EAAG,cAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AAE3C,QAAM,UAA8B,CAAC;AACrC,aAAW,SAAS,QAAQ;AAC1B,UAAM,WAAgB,YAAK,WAAW,MAAM,IAAI;AAChD,UAAM,aAAkB,gBAAS,WAAgB,YAAK,WAAW,MAAM,IAAI,CAAC;AAC5E,QAAI;AACJ,UAAM,WAAc,cAAU,UAAU,EAAE,gBAAgB,MAAM,CAAC;AACjE,QAAI,CAAC,UAAU;AACb,MAAG,gBAAY,YAAY,UAAU,KAAK;AAC1C,eAAS;AAAA,IACX,WAAW,CAAC,SAAS,eAAe,GAAG;AACrC,eAAS;AAAA,IACX,WAAc,iBAAa,QAAQ,MAAM,YAAY;AACnD,eAAS;AAAA,IACX,OAAO;AACL,MAAG,eAAW,QAAQ;AACtB,MAAG,gBAAY,YAAY,UAAU,KAAK;AAC1C,eAAS;AAAA,IACX;AACA,UAAM,UAAU,GAAG,OAAO,OAAO,CAAC,CAAC,mBAAmB,MAAM,IAAI,WAAM,UAAU;AAChF,QAAI,WAAW,UAAW,QAAO,KAAK,GAAG,OAAO,kDAA6C;AAAA,QACxF,QAAO,KAAK,OAAO;AACxB,YAAQ,KAAK,EAAE,OAAO,MAAM,MAAM,QAAQ,QAAQ,WAAW,CAAC;AAAA,EAChE;AACA,SAAO;AACT;","names":["path","path","relative","path","fs","fs","path","require","propertyName","path","fs","path","fs","createRequire","path","createRequire","path","path","path","list","relative","fileConsts","isObject","path","required","close","fs","path","relative","path","fs","path","prettier","createRequire","path","require","list","relative","prettier","fs","path","resolve","fs","path"]}
|