@ahoo-wang/wow-generator 9.9.0 → 10.0.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -62
- package/README.zh-CN.md +85 -48
- package/dist/analysis/analyze.d.cts +5 -8
- package/dist/analysis/analyze.d.ts +5 -8
- package/dist/analysis/apiClients.d.cts +3 -4
- package/dist/analysis/apiClients.d.ts +3 -4
- package/dist/analysis/clientNames.d.cts +0 -20
- package/dist/analysis/clientNames.d.ts +0 -20
- package/dist/analysis/model.d.cts +2 -102
- package/dist/analysis/model.d.ts +2 -102
- package/dist/analysis/modelInfo.d.cts +12 -3
- package/dist/analysis/modelInfo.d.ts +12 -3
- package/dist/analysis/models.d.cts +3 -11
- package/dist/analysis/models.d.ts +3 -11
- package/dist/api/configuration.d.cts +1 -5
- package/dist/api/configuration.d.ts +1 -5
- package/dist/cli/program.d.cts +0 -5
- package/dist/cli/program.d.ts +0 -5
- package/dist/cli.cjs +9 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +102 -3
- package/dist/cli.js.map +1 -1
- package/dist/codeGenerator-CU1TGcUI.js +2407 -0
- package/dist/codeGenerator-CU1TGcUI.js.map +1 -0
- package/dist/codeGenerator-DzI0zCgM.cjs +27 -0
- package/dist/codeGenerator-DzI0zCgM.cjs.map +1 -0
- package/dist/emit/imports.d.cts +0 -9
- package/dist/emit/imports.d.ts +0 -9
- package/dist/emitters/decorators.d.cts +3 -18
- package/dist/emitters/decorators.d.ts +3 -18
- package/dist/emitters/emit.d.cts +2 -3
- package/dist/emitters/emit.d.ts +2 -3
- package/dist/emitters/manifestClients.d.cts +15 -0
- package/dist/emitters/manifestClients.d.ts +15 -0
- package/dist/emitters/models.d.cts +1 -1
- package/dist/emitters/models.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/input/configuration.d.cts +2 -4
- package/dist/input/configuration.d.ts +2 -4
- package/dist/input/parsers.d.cts +13 -0
- package/dist/input/parsers.d.ts +13 -0
- package/dist/manifest/analyze.d.cts +148 -0
- package/dist/manifest/analyze.d.ts +148 -0
- package/dist/manifest/document.d.cts +89 -0
- package/dist/manifest/document.d.ts +89 -0
- package/dist/naming/modelInfo.d.cts +1 -2
- package/dist/naming/modelInfo.d.ts +1 -2
- package/dist/naming/paths.d.cts +0 -5
- package/dist/naming/paths.d.ts +0 -5
- package/dist/output/outputStore.d.cts +2 -6
- package/dist/output/outputStore.d.ts +2 -6
- package/dist/pipeline/codeGenerator.d.cts +19 -11
- package/dist/pipeline/codeGenerator.d.ts +19 -11
- package/package.json +8 -8
- package/dist/analysis/aggregates.d.cts +0 -21
- package/dist/analysis/aggregates.d.ts +0 -21
- package/dist/codeGenerator-BMyiC0tW.cjs +0 -23
- package/dist/codeGenerator-BMyiC0tW.cjs.map +0 -1
- package/dist/codeGenerator-CsWf0pZy.js +0 -2572
- package/dist/codeGenerator-CsWf0pZy.js.map +0 -1
- package/dist/emitters/commandClients.d.cts +0 -14
- package/dist/emitters/commandClients.d.ts +0 -14
- package/dist/emitters/queryClients.d.cts +0 -11
- package/dist/emitters/queryClients.d.ts +0 -11
- package/dist/fetcherGeneratorCli.cjs +0 -3
- package/dist/fetcherGeneratorCli.cjs.map +0 -1
- package/dist/fetcherGeneratorCli.d.cts +0 -8
- package/dist/fetcherGeneratorCli.d.ts +0 -8
- package/dist/fetcherGeneratorCli.js +0 -6
- package/dist/fetcherGeneratorCli.js.map +0 -1
- package/dist/program-64WQvLq1.js +0 -103
- package/dist/program-64WQvLq1.js.map +0 -1
- package/dist/program-DWjbTSVJ.cjs +0 -10
- package/dist/program-DWjbTSVJ.cjs.map +0 -1
- package/dist/wow/conventions.d.cts +0 -154
- package/dist/wow/conventions.d.ts +0 -154
- package/dist/wow/model.d.cts +0 -116
- package/dist/wow/model.d.ts +0 -116
- package/dist/wow/resolveWowModel.d.cts +0 -21
- package/dist/wow/resolveWowModel.d.ts +0 -21
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codeGenerator-DzI0zCgM.cjs","names":["isObject","StructureKind","join","relative","sep","CodeBlockWriter","isObject","StructureKind","Scope","isObject","StructureKind","VariableDeclarationKind","Node","Node","SyntaxKind","ts","parse","path","isAbsolute","resolve","isObject","join","join","resolve","join","path","isAbsolute","relative","sep","ts","IndentationText","QuoteKind","Project","ts_morph","path","yaml","fs","node_path","DEFAULT_CONFIG_PATH","EXIT_CODES","GeneratorError","message","options","kind","errorMessage","error","defaultDecorate","ConsoleLogger","prefix","symbol","label","params","SilentLogger","combinePaths","relative","base","MODEL_FILE_NAME","modelFilePath","model","isReference","schema","resolveLocalPointer","pointer","ref","document","current","token","key","findDanglingReferences","dangling","seen","visit","value","item","location","index","child","COMPONENTS_PREFIX","COMPONENTS_PARAMETERS_REF","COMPONENTS_REQUEST_BODIES_REF","COMPONENTS_RESPONSES_REF","COMPONENTS_SCHEMAS_REF","extractComponentKey","reference","resolveComponent","visited","components","extractSchema","extractResponse","extractRequestBody","extractParameter","NAME_COLLATOR","compareNames","left","right","APPLICATION_JSON","TEXT_EVENT_STREAM","mediaTypeOf","contentType","isJsonContentType","mediaType","isTextContentType","findMediaType","exact","content","matches","extractResponseSchema","response","extractResponseJsonSchema","extractResponseEventStreamSchema","extractResponseWildcardSchema","hasTextResponse","isEnum","ENUM_TEXT_NAME","getEnumText","isObject$2","isArray","isAnyOf","isOneOf","isAllOf","isComposition","toArrayType","type","isMap","X_MAP_KEY_SCHEMA","getMapKeySchema","isReadOnly","resolvePrimitiveType","it","resolveOptionalFields","declared","required","admitsNull","walk","name","operationEndpointComparator","mergeParameters","parameters","parameter","inherited","own","resolved","extractOperationEndpoints","operationEndpoints","pathItem","paths","extractOperations","methodOperation","operation","okResponseStatus","statuses","status","extractOkResponse","extractParameters","inPathOrder","position","a","b","NAMING_SEPARATORS","RESERVED_WORDS","isIdentifier","prefixLeadingDigit","toIdentifier","identifier","camelCase","isTypeNamePart","part","toTypeIdentifier","pascalCase","splitName","tokenizeName","splitCamelCase","parts","result","i","char","isUpper","prevIsLower","firstChar","rest","pascalCaseName","upperSnakeCase","resolvePropertyName","quoteStringLiteral","enumMemberKey","OPERATION_METHOD_NAME_KEY","resolveMethodName","explicit","configured","isMethodName","uniqueParameterName","unique","suffix","used","resolveModelInfo","schemaKey","modelNameIndex","pathParts","resolveReferenceModelInfo","RESERVED_PARAMETER_NAMES","analyzeApiClients","ApiClientAnalysis","config","warnings","tags","operations","claimed","modelInfo","tagName","clientInfo","clientKey","className","file","apiClientFileName","methods","tag","endpoint","body","described","description","operationId","methodName","taken","located","cookies","cookie","parameterName","requestBody","json","okResponse","responseJsonSchema","jsonSchema","eventStreamSchema","operationTags","analyzeModels","schemas","keys","assertUniqueModelNames","info","byModel","collisions","analyze","ImportRegistry","imported","moduleSpecifier","names","requests","alias","except","ModuleBuilder","sourceFile","statement","statements","previous","declaration","blankLineBetween","blankLine","ModuleSet","open","filePath","module","writer","next","indexSignatureMember","returnType","IMPORT_ALIAS","addImport","namedImports","modelModuleSpecifier","relativeModuleSpecifier","outputDir","relativePath","fromDirectory","targetFilePath","jsDoc","descriptions","filtered","v","escapeJsDoc","separator","text","addJSDoc","jsdoc","node","schemaJSDoc","withNonNullBranch","main","addRequiredJsDoc","addJsonJsDoc","addNumericConstraintsJsDoc","addStringConstraintsJsDoc","addArrayConstraintsJsDoc","addSchemaJSDoc","addMainSchemaJSDoc","includeSchema","jsonJsDoc","keyword","members","nonNull","member","branch","merged","propertyName","constraintsDescriptions","createTypeContext","namesByPath","naming","GLOBAL_TYPE_NAMES","PRIMITIVE_TYPE_NAMES","ANNOTATION_KEYWORDS","sameKind","schemaKind","kinds","first","clashesWithIndexSignature","indexKind","additionalProperties","propertyKind","propSchema","requiresAdditionalPropertiesIntersection","isNullableReference","matchesLiteralType","resolveLiteral","properties","Resolution","scope","entry","owner","reservedNames","propName","resolvedPropName","doc","mapType","additionalProps","objectType","mapKeySchema","resolve","root","nodes","constrained","pending","groups","changed","allOf","oneOf","anyOf","isConstrained","simple","compositions","composed","baseType","literal","keywords","isNullMember","types","discriminator","componentKey","mapped","target","resolveWith","resolution","resolveType","resolveAdditionalProperties","resolveAdditionalPropertyType","resolveRequiredAdditionalPropertyType","resolveMapValueType","FETCHER_MODULE_SPECIFIER","FETCHER_NAMED_IMPORTS","DECORATOR_MODULE_SPECIFIER","DECORATOR_NAMED_IMPORTS","DEFAULT_RETURN_TYPE","STRING_RETURN_TYPE","STREAM_RESULT_EXTRACTOR_METADATA","addImportFetcher","addImportDecorator","createDecoratorClass","extendsClass","apiArgs","addApiMetadataCtor","classDeclaration","methodToDecorator","method","EVENTSTREAM_MODULE_SPECIFIER","addImportEventStream","emitApiClient","client","apiClientClass","clientTypes","apiMethod","optional","bodyType","returnTypeOf","returns","typeName","documentTypeContext","emitModel","ModelEmitter","uniqueEnumMemberNames","values","preferred","candidates","candidate","enumText","textNames","memberName","stringValues","memberNames","propertySignature","interfaceDeclaration","schemaProperties","itemType","emitGeneration","emitIndexFiles","indexDirectory","claim","children","dir","baseName","exportedNames","subDir","exports","dirPath","writeIndex","owners","ambiguous","specifiers","indexFile","exported","typeOnly","isTypeOnly","declarations","isTypePosition","parent","clause","planTypeOnlyImports","localNames","specifier","valueSymbols","traversal","applyTypeOnly","allTypeOnly","inline","applyTypeOnlyImports","plans","sourceFiles","apply","INTEGRITY_DIAGNOSTICS","verifyGeneratedCode","problems","diagnostic","GENERATED_FILE_HEADER","FORMAT_SETTINGS","finalizeSourceFiles","logger","DEFAULT_HTTP_TIMEOUT_MS","isHttpLocation","loadResource","loadHttpResource","loadFile","timeoutMs","timeout","url","reason","networkReason","cause","err","reject","data","loadDocument","inputPath","parseContent","validateOpenAPIDocument","source","inferFileFormat","trimmedContent","resolveConfiguration","configPath","loadConfiguration","describeSource","loaded","CONFIGURATION_KEYS","API_CLIENT_KEYS","origin","isFileNotFound","parsed","validateConfiguration","describe","path$11","typeOf","isRecord","warnUnknownKeys","unknown","known","validateApiClients","apiClients","apiClient","ignorePathParameters","methodNames","DEFS_PREFIX","isManifestDocument","isObject$1","validateManifest","manifest","context","where","at","aggregate","command","event","TEXT_NUMBER_FORMATS","LIFECYCLE_BODIES","LIFECYCLE_COMMANDS","MAX_FIELD_DEPTH","isObject","typesOf","t","join$2","SchemaTypes","defs","depth","byName","segments","exhausted","assigned","into","named","inner","reached","roots","option","extra","property","marks","alternative","mark","each","mergeTextNumbers","nextSeen","objects","object","all","emptyBody","aggregateRoots","lifecycleBodies","analyzeManifest","contexts","reach","typeModels","typeModel","contextModels","contextModel","references","s","aggregateModel","typeOfRef","generated","lifecycle","commands","routes","route","byId","unaddressed","stateNumbers","eventNumbers","wireNameOf","commandNumbers","textNumbers","stateKey","stateSchema","query","WOW_CLIENT","lines","line","indent","addStatement","union","importTypes","byFile","files","ownFile","emitManifestGeneration","emitType","modules","emitBoundedContext","emitAggregate","emitCommandClient","emitQueryClient","comment","constant","errors","hasSubscriptions","hops","textNumbersLiteral","textNumbersMember","numbers","group","events","commandDoc","creates","commandMethods","aggregateConstant","bodyParam","call","stream","lifecycleTypes","state","aggregateNames","constructor","openApiDocument","openAPI","GENERATION_MANIFEST","OutputStore","project","outputPath","manifestPath","readManifest","path$1","hash","fileName","assertWithinOutputDir","leaving","last","directory","path$2","path$3","signal","written","path$4","path$5","attempt","path$6","outputFailure","path$7","fileHash","path$8","remedy","version","action","path$9","change","path$10","normalized","rel","PROJECT_SEAM","SIGNAL_SEAM","CodeGenerator","createProject","warn","loadOptions","configuration","input","output","analysis","outputDirectory","tsConfigFilePath"],"sources":["../src/api/configuration.ts","../src/api/errors.ts","../src/api/logger.ts","../src/naming/paths.ts","../src/openapi/references.ts","../src/openapi/components.ts","../src/naming/order.ts","../src/openapi/responses.ts","../src/openapi/schemas.ts","../src/openapi/operations.ts","../src/naming/naming.ts","../src/analysis/clientNames.ts","../src/analysis/modelInfo.ts","../src/analysis/apiClients.ts","../src/analysis/models.ts","../src/analysis/analyze.ts","../src/emit/importRegistry.ts","../src/emit/moduleBuilder.ts","../src/emit/imports.ts","../src/emit/jsdoc.ts","../src/types/typeResolver.ts","../src/emitters/decorators.ts","../src/emitters/apiClients.ts","../src/emitters/models.ts","../src/emitters/emit.ts","../src/emitters/indexFiles.ts","../src/finalize/typeOnlyImports.ts","../src/finalize/verification.ts","../src/finalize/finalize.ts","../src/input/resources.ts","../src/input/parsers.ts","../src/input/configuration.ts","../src/manifest/document.ts","../src/manifest/analyze.ts","../src/emitters/manifestClients.ts","../src/openapi/document.ts","../src/output/outputStore.ts","../src/pipeline/seams.ts","../src/pipeline/codeGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Where the generator looks for its configuration when none is named.\n */\nexport const DEFAULT_CONFIG_PATH = './wow-generator.config.json';\n\n/**\n * The generator configuration, read from {@link DEFAULT_CONFIG_PATH} or the\n * path `GeneratorOptions.configPath` names.\n */\nexport interface GeneratorConfiguration {\n /**\n * tag name -> api client configuration\n */\n apiClients?: Record<string, ApiClientConfiguration>;\n}\n\nexport interface ApiClientConfiguration {\n /**\n * The path parameters the client leaves out, because an interceptor fills\n * them. Default: none.\n */\n ignorePathParameters?: string[];\n /**\n * Method names by operationId, overriding the name derived from it. Use it\n * when two operations of one tag derive the same name.\n */\n methodNames?: Record<string, string>;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What a generation failure is about, which decides the CLI's exit code.\n *\n * - `input`: the OpenAPI document cannot be read, fetched or parsed, or it is\n * not an OpenAPI 3 document.\n * - `configuration`: the generator configuration cannot be read, parsed or\n * understood.\n * - `specification`: the document was read, but it describes something the\n * generator cannot turn into code that compiles: a dangling, cyclic or\n * external reference, names that collide after normalisation, malformed Wow\n * metadata.\n * - `output`: the output directory cannot be written as asked: its manifest\n * (`.wow-generator.json`) is corrupt, a path resolves outside it, or writing\n * or deleting a file fails.\n */\nexport type GeneratorErrorKind =\n 'input' | 'configuration' | 'specification' | 'output';\n\n/**\n * Exit codes of the `wow-generator` CLI. Anything the generator did not\n * anticipate exits with {@link EXIT_CODES.internal}.\n */\nexport const EXIT_CODES = {\n success: 0,\n internal: 1,\n input: 2,\n configuration: 3,\n specification: 4,\n output: 5,\n interrupted: 130,\n} as const;\n\n/**\n * A failure the user can act on. Its message is written as one line that\n * names what went wrong and where; the CLI prints it without a stack trace.\n */\nexport class GeneratorError extends Error {\n constructor(\n readonly kind: GeneratorErrorKind,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'GeneratorError';\n }\n\n /** The CLI exit code this failure maps to. */\n get exitCode(): number {\n return EXIT_CODES[this.kind];\n }\n}\n\n/** Renders an error as the tail of a sentence. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Where a generation reports what it does.\n *\n * Each method takes a message and, optionally, values to print after it, as\n * `console.log` does. A run calls:\n *\n * - `debug` for every step and detail;\n * - `info` for the outcome of the run;\n * - `warn` for something it carried on past, but that the user probably did\n * not intend; `GenerationResult.warnings` counts these calls;\n * - `error` for a failure.\n */\nexport interface Logger {\n debug(message: string, ...params: unknown[]): void;\n info(message: string, ...params: unknown[]): void;\n warn(message: string, ...params: unknown[]): void;\n error(message: string, ...params: unknown[]): void;\n}\n\n/**\n * How much a {@link ConsoleLogger} prints.\n *\n * - `quiet`: warnings and errors only.\n * - `normal`: also `info`, the outcome of the run.\n * - `verbose`: also `debug`, every detail, with timestamps.\n */\nexport type LogLevel = 'quiet' | 'normal' | 'verbose';\n\nexport interface ConsoleLoggerOptions {\n /** Defaults to `normal`. */\n readonly level?: LogLevel;\n /**\n * Prefix lines with symbols. Defaults to true on a TTY unless `NO_COLOR`\n * is set, so CI logs and pipes stay plain.\n */\n readonly decorate?: boolean;\n}\n\nfunction defaultDecorate(): boolean {\n return !!process.stdout?.isTTY && !process.env.NO_COLOR;\n}\n\n/**\n * Console logger for the CLI.\n *\n * Details go to `debug`, which only `verbose` prints; the default prints the\n * outcome, warnings and errors, so a warning is not lost among hundreds of\n * detail lines.\n */\nexport class ConsoleLogger implements Logger {\n private readonly level: LogLevel;\n private readonly decorate: boolean;\n\n constructor(options: ConsoleLoggerOptions = {}) {\n this.level = options.level ?? 'normal';\n this.decorate = options.decorate ?? defaultDecorate();\n }\n\n private format(symbol: string, label: string, message: string): string {\n const prefix = this.decorate ? `${symbol} ` : label ? `${label}: ` : '';\n const timestamp =\n this.level === 'verbose'\n ? `[${new Date().toTimeString().slice(0, 8)}] `\n : '';\n return `${timestamp}${prefix}${message}`;\n }\n\n debug(message: string, ...params: unknown[]): void {\n if (this.level !== 'verbose') return;\n console.log(this.format('ℹ️ ', '', message), ...params);\n }\n\n info(message: string, ...params: unknown[]): void {\n if (this.level === 'quiet') return;\n console.log(this.format('✅', '', message), ...params);\n }\n\n warn(message: string, ...params: unknown[]): void {\n console.warn(this.format('⚠️ ', 'warning', message), ...params);\n }\n\n error(message: string, ...params: unknown[]): void {\n console.error(this.format('❌', 'error', message), ...params);\n }\n}\n\n/**\n * Logger that prints nothing.\n */\nexport class SilentLogger implements Logger {\n debug(): void {}\n\n info(): void {}\n\n warn(): void {}\n\n error(): void {}\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Joins a relative path onto a base with exactly one `/` between them, as\n * `@ahoo-wang/fetcher`'s `combineURLs` does, so the generator process need\n * not load fetcher for it: `('a/', '/b.ts')` → `a/b.ts`. An empty relative\n * path gives the base, and a URL with a scheme (`https://…`, `//host/…`)\n * replaces it.\n *\n * @param base - The path to join onto\n * @param relative - The path to join\n */\nexport function combinePaths(base: string, relative: string): string {\n if (/^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(relative)) return relative;\n return relative\n ? `${base.replace(/\\/+$/, '')}/${relative.replace(/^\\/+/, '')}`\n : base;\n}\n\n/** The file every model of a package is declared in. */\nexport const MODEL_FILE_NAME = 'types.ts';\n\n/**\n * The file a model is declared in, relative to the output directory: the\n * `types.ts` of its package.\n *\n * @param model - The model, whose path is its package (`/` for the root)\n */\nexport function modelFilePath(model: { readonly path: string }): string {\n return combinePaths(model.path, MODEL_FILE_NAME);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Reference } from '@ahoo-wang/fetcher-openapi';\n\nexport function isReference(schema: any): schema is Reference {\n return !!(schema && typeof schema === 'object' && '$ref' in schema);\n}\n\n/**\n * Resolves a local JSON pointer (`#/components/schemas/Item`) in a document.\n *\n * @param document - The document the pointer points into\n * @param ref - The `$ref` value, starting with `#`\n * @returns The value it points at, or undefined when there is none\n */\nexport function resolveLocalPointer(document: unknown, ref: string): unknown {\n let pointer = ref.slice(1);\n try {\n pointer = decodeURIComponent(pointer);\n } catch {\n // Not percent-encoded after all; read it as written.\n }\n if (pointer === '') return document;\n let current: unknown = document;\n for (const token of pointer.slice(1).split('/')) {\n if (current === null || typeof current !== 'object') return undefined;\n const key = token.replace(/~1/g, '/').replace(/~0/g, '~');\n if (!Object.hasOwn(current, key)) return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n\n/**\n * Finds every reference to a component (`#/components/...`) that points at\n * nothing.\n *\n * A dangling schema reference would otherwise generate a type that names an\n * undeclared model, and a dangling parameter reference would silently drop\n * the parameter. Other references are left alone: a reference to another\n * document is refused where it is read, with a request to bundle it, and a\n * schema may carry JSON Schema `definitions` it references relative to\n * itself (`#/definitions/...`), as Wow 8.11 writes its filter schema.\n *\n * @param document - The parsed OpenAPI document\n * @returns Each dangling reference with the JSON path of the object holding it\n */\nexport function findDanglingReferences(\n document: unknown,\n): { ref: string; location: string }[] {\n const dangling: { ref: string; location: string }[] = [];\n const seen = new Set<object>();\n const visit = (value: unknown, location: string) => {\n if (value === null || typeof value !== 'object' || seen.has(value)) return;\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) => visit(item, `${location}/${index}`));\n return;\n }\n const ref = (value as Record<string, unknown>).$ref;\n if (\n typeof ref === 'string' &&\n ref.startsWith('#/components/') &&\n resolveLocalPointer(document, ref) === undefined\n ) {\n dangling.push({ ref, location: location || '/' });\n }\n for (const [key, child] of Object.entries(value)) {\n visit(\n child,\n `${location}/${key.replace(/~/g, '~0').replace(/\\//g, '~1')}`,\n );\n }\n };\n visit(document, '');\n return dangling;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GeneratorError } from '../api/errors';\nimport type {\n Components,\n Parameter,\n Reference,\n RequestBody,\n Response,\n Schema,\n} from '@ahoo-wang/fetcher-openapi';\nimport { isReference } from './references';\n\n/** Prefix for OpenAPI components references */\nexport const COMPONENTS_PREFIX = '#/components/';\n/** Reference prefix for parameters components */\nexport const COMPONENTS_PARAMETERS_REF = `${COMPONENTS_PREFIX}parameters/`;\n/** Reference prefix for request bodies components */\nexport const COMPONENTS_REQUEST_BODIES_REF = `${COMPONENTS_PREFIX}requestBodies/`;\n/** Reference prefix for responses components */\nexport const COMPONENTS_RESPONSES_REF = `${COMPONENTS_PREFIX}responses/`;\n/** Reference prefix for schemas components */\nexport const COMPONENTS_SCHEMAS_REF = `${COMPONENTS_PREFIX}schemas/`;\n\n/**\n * Represents a schema with its key identifier.\n */\nexport interface KeySchema<T extends Schema | Reference = Schema> {\n /** The schema key */\n key: string;\n /** The schema definition */\n schema: T;\n}\n\n/**\n * Extracts the component key from an OpenAPI reference.\n * @param reference - The OpenAPI reference object\n * @returns The component key (last part of the reference path)\n */\nexport function extractComponentKey(reference: Reference): string {\n return reference.$ref.split('/').pop() as string;\n}\n\n/**\n * Extracts a schema from OpenAPI components using a reference.\n * @param reference - The reference to the schema\n * @param components - The OpenAPI components object\n * @returns The schema if found, undefined otherwise\n */\nfunction resolveComponent<T>(\n reference: Reference,\n components: Record<string, T | Reference> | undefined,\n prefix: string,\n): T | undefined {\n const visited = new Set<string>();\n let current: T | Reference | undefined = reference;\n while (isReference(current)) {\n // ponytail: local components only; bundle external references before generation.\n if (!current.$ref.startsWith(prefix)) return undefined;\n if (visited.has(current.$ref)) {\n throw new GeneratorError(\n 'specification',\n `Cyclic component reference: ${current.$ref}`,\n );\n }\n visited.add(current.$ref);\n current = components?.[current.$ref.slice(prefix.length)];\n }\n return current;\n}\n\nexport function extractSchema(\n reference: Reference,\n components: Components,\n): Schema | undefined {\n return resolveComponent(\n reference,\n components.schemas,\n COMPONENTS_SCHEMAS_REF,\n );\n}\n\n/**\n * Extracts a response from OpenAPI components using a reference.\n * @param reference - The reference to the response\n * @param components - The OpenAPI components object\n * @returns The response if found, undefined otherwise\n */\nexport function extractResponse(\n reference: Reference,\n components: Components,\n): Response | undefined {\n return resolveComponent(\n reference,\n components.responses,\n COMPONENTS_RESPONSES_REF,\n );\n}\n\n/**\n * Extracts a request body from OpenAPI components using a reference.\n * @param reference - The reference to the request body\n * @param components - The OpenAPI components object\n * @returns The request body if found, undefined otherwise\n */\nexport function extractRequestBody(\n reference: Reference,\n components: Components,\n): RequestBody | undefined {\n return resolveComponent(\n reference,\n components.requestBodies,\n COMPONENTS_REQUEST_BODIES_REF,\n );\n}\n\n/**\n * Extracts a parameter from OpenAPI components using a reference.\n * @param reference - The reference to the parameter\n * @param components - The OpenAPI components object\n * @returns The parameter if found, undefined otherwise\n */\nexport function extractParameter(\n reference: Reference,\n components: Components,\n): Parameter | undefined {\n return resolveComponent(\n reference,\n components.parameters,\n COMPONENTS_PARAMETERS_REF,\n );\n}\n\n/**\n * Creates a KeySchema object from a reference and components.\n * @param reference - The reference to the schema\n * @param components - The OpenAPI components object\n * @returns A KeySchema containing the key and resolved schema\n */\nexport function keySchema(\n reference: Reference,\n components: Components,\n): KeySchema {\n const componentKey = extractComponentKey(reference);\n return {\n key: componentKey,\n schema: extractSchema(reference, components)!,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Orders names the same way on every machine.\n *\n * `localeCompare` without a locale follows the default locale of the process,\n * which ICU takes from `LANG`: under `tr_TR` a name starting with `I` sorts\n * after one starting with `i`, so the order of a barrel's exports or of a\n * client's methods would depend on where the generator ran. The collator is\n * fixed to `en-US`, the order CI has always produced, so no output changes.\n */\nconst NAME_COLLATOR = new Intl.Collator('en-US');\n\n/** Compares two names in the fixed `en-US` order; a comparator for `sort`. */\nexport function compareNames(left: string, right: string): number {\n return NAME_COLLATOR.compare(left, right);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n MediaType,\n Reference,\n Response,\n Schema,\n} from '@ahoo-wang/fetcher-openapi';\nimport { isReference } from './references';\n\n/** The media type of JSON. */\nexport const APPLICATION_JSON = 'application/json';\n\n/** The media type of a server-sent event stream. */\nexport const TEXT_EVENT_STREAM = 'text/event-stream';\n\n/**\n * The media type part of a content type, without parameters and in lower\n * case: `application/json;charset=UTF-8` → `application/json`.\n */\nexport function mediaTypeOf(contentType: string): string {\n return contentType.split(';')[0].trim().toLowerCase();\n}\n\n/**\n * Tells whether a content type carries JSON: `application/json`, or any\n * `+json` type such as `application/hal+json` or `application/problem+json`,\n * with or without parameters.\n */\nexport function isJsonContentType(contentType: string): boolean {\n const mediaType = mediaTypeOf(contentType);\n return (\n mediaType === APPLICATION_JSON ||\n /^application\\/[^/]+\\+json$/.test(mediaType)\n );\n}\n\n/**\n * Tells whether a content type is text other than an event stream.\n */\nexport function isTextContentType(contentType: string): boolean {\n const mediaType = mediaTypeOf(contentType);\n return mediaType.startsWith('text/') && mediaType !== TEXT_EVENT_STREAM;\n}\n\n/**\n * Finds the entry of a content map that matches, preferring an exact key.\n *\n * @param content - The content map of a request body or a response\n * @param exact - The content type to prefer as written\n * @param matches - What else qualifies\n * @returns The media type object, or undefined\n */\nexport function findMediaType(\n content: Record<string, MediaType> | undefined,\n exact: string,\n matches: (contentType: string) => boolean = contentType =>\n mediaTypeOf(contentType) === exact,\n): MediaType | undefined {\n if (!content) return undefined;\n if (content[exact]) return content[exact];\n const key = Object.keys(content).find(matches);\n return key === undefined ? undefined : content[key];\n}\n\nexport function extractResponseSchema(\n contentType: string,\n response?: Response | Reference,\n): Schema | Reference | undefined {\n if (!response) {\n return;\n }\n if (isReference(response)) {\n return undefined;\n }\n return findMediaType(response.content, contentType)?.schema;\n}\n\n/**\n * Extracts the JSON schema of a response: `application/json` or any `+json`\n * type, with or without parameters.\n * @param response - The response object or reference\n * @returns The JSON schema from the response content or undefined if not found\n */\nexport function extractResponseJsonSchema(\n response?: Response | Reference,\n): Schema | Reference | undefined {\n if (!response || isReference(response)) return undefined;\n return findMediaType(response.content, APPLICATION_JSON, isJsonContentType)\n ?.schema;\n}\n\nexport function extractResponseEventStreamSchema(\n response?: Response | Reference,\n): Schema | Reference | undefined {\n return extractResponseSchema(TEXT_EVENT_STREAM, response);\n}\n\nexport function extractResponseWildcardSchema(\n response?: Response | Reference,\n): Schema | Reference | undefined {\n return extractResponseSchema('*/*', response);\n}\n\n/**\n * Tells whether a response carries text other than an event stream, such as\n * `text/plain`.\n */\nexport function hasTextResponse(response?: Response | Reference): boolean {\n if (!response || isReference(response)) return false;\n return Object.keys(response.content ?? {}).some(isTextContentType);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n Components,\n Reference,\n Schema,\n SchemaType,\n} from '@ahoo-wang/fetcher-openapi';\nimport { extractSchema } from './components';\nimport { isReference } from './references';\n\n/** List of primitive schema types */\nconst PRIMITIVE_TYPES: SchemaType[] = [\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'null',\n];\n\n/**\n * Checks if a schema type is primitive.\n * @param type - The schema type to check\n * @returns True if the type is primitive, false otherwise\n */\nexport function isPrimitive(type: SchemaType | SchemaType[]): boolean {\n if (Array.isArray(type)) {\n return true;\n }\n return PRIMITIVE_TYPES.includes(type);\n}\n\nexport type EnumSchema = Schema & { enum: any[] };\n\n/**\n * Checks if a schema represents an enum.\n * @param schema - The schema to check\n * @returns True if the schema has an enum property, false otherwise\n */\nexport function isEnum(schema: Schema): schema is EnumSchema {\n return Array.isArray(schema.enum) && schema.enum.length > 0;\n}\n\nexport type EnumText = Record<string, string>;\nconst ENUM_TEXT_NAME = 'x-enum-text';\n\nexport function getEnumText(schema: EnumSchema): EnumText | undefined {\n return schema[ENUM_TEXT_NAME];\n}\n\nexport type ObjectSchema = Schema & {\n type: 'object';\n properties: Record<string, Schema | Reference>;\n};\n\nexport function isObject(schema: Schema): schema is ObjectSchema {\n return schema.type === 'object' && !!schema.properties;\n}\n\nexport type ArraySchema = Schema & { type: 'array'; items: Schema | Reference };\n\n/**\n * Checks if a schema is an array type.\n * @param schema - The schema to check\n * @returns True if the schema is an array type, false otherwise\n */\nexport function isArray(schema: Schema): schema is ArraySchema {\n return schema.type === 'array' && !!schema.items;\n}\n\nexport type AnyOfSchema = Schema & { anyOf: any[] };\n\n/**\n * Checks if a schema is an anyOf composition.\n * @param schema - The schema to check\n * @returns True if the schema has a non-empty anyOf property, false otherwise\n */\nexport function isAnyOf(schema: Schema): schema is AnyOfSchema {\n return Array.isArray(schema.anyOf) && schema.anyOf.length > 0;\n}\n\nexport type OneOfSchema = Schema & { oneOf: any[] };\n\n/**\n * Checks if a schema is a oneOf composition.\n * @param schema - The schema to check\n * @returns True if the schema has a non-empty oneOf property, false otherwise\n */\nexport function isOneOf(schema: Schema): schema is OneOfSchema {\n return Array.isArray(schema.oneOf) && schema.oneOf.length > 0;\n}\n\nexport type AllOfSchema = Schema & { allOf: any[] };\n\n/**\n * Checks if a schema is an allOf composition.\n * @param schema - The schema to check\n * @returns True if the schema has a non-empty allOf property, false otherwise\n */\nexport function isAllOf(schema: Schema): schema is AllOfSchema {\n return Array.isArray(schema.allOf) && schema.allOf.length > 0;\n}\n\nexport type CompositionSchema = AnyOfSchema | OneOfSchema | AllOfSchema;\n\n/**\n * Checks if a schema is a composition (anyOf, oneOf, or allOf).\n * @param schema - The schema to check\n * @returns True if the schema is anyOf, oneOf, or allOf composition, false otherwise\n */\nexport function isComposition(schema: Schema): schema is CompositionSchema {\n return isAnyOf(schema) || isOneOf(schema) || isAllOf(schema);\n}\n\n/**\n * Converts a type string to an array type.\n * Wraps complex types (containing | or &) in parentheses before adding array notation.\n * @param type - The type string to convert to an array type\n * @returns The array type string\n */\nexport function toArrayType(type: string): string {\n if (type.includes('|') || type.includes('&')) {\n return `(${type})[]`;\n }\n return `${type}[]`;\n}\n\nexport type MapSchema = Schema & {\n type: 'object';\n additionalProperties: boolean | Schema | Reference;\n};\n\nexport function isMap(schema: Schema): schema is MapSchema {\n return (\n schema.type === 'object' &&\n !schema.properties &&\n schema.additionalProperties !== undefined\n );\n}\n\nconst X_MAP_KEY_SCHEMA = 'x-map-key-schema';\n\nexport function getMapKeySchema(\n schema: Schema,\n): Schema | Reference | undefined {\n return schema[X_MAP_KEY_SCHEMA];\n}\n\n/**\n * Checks if a schema represents an empty object.\n * @param schema - The schema to check\n * @returns True if the schema represents an empty object, false otherwise\n */\nexport function isEmptyObject(schema: Schema): boolean {\n if (schema.type !== 'object') {\n return false;\n }\n if (!schema.properties) {\n return true;\n }\n return Object.keys(schema.properties).length === 0;\n}\n\nexport function isReadOnly(schema: Schema | Reference): boolean {\n return (schema as Schema).readOnly === true;\n}\n\n/**\n * Resolves a schema type to its TypeScript equivalent.\n * @param type - The schema type(s) to resolve\n * @returns The TypeScript type string\n */\nexport function resolvePrimitiveType(type: SchemaType | SchemaType[]): string {\n if (Array.isArray(type)) {\n return type.map(it => resolvePrimitiveType(it)).join(' | ');\n }\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'null':\n return 'null';\n default:\n return 'any';\n }\n}\n\n/**\n * Lists the property names a command body may omit.\n *\n * A command type wraps its body in `PartialBy<Command, ...>` built from this\n * list, which is where a request's declared optionality lives: generated model\n * properties are always required. The walk follows `allOf` branches and\n * references, because a command that inherits a base schema declares its\n * properties there - reading only the top level would demand fields the\n * document leaves optional.\n *\n * A property is optional when no branch requires it. `anyOf` and `oneOf` are\n * not followed: a branch an instance need not match says nothing about the\n * properties a command carries.\n *\n * @param schema - The command body schema, or a reference to it\n * @param components - The components a reference resolves against\n * @returns The declared property names absent from every `required` list\n */\nexport function resolveOptionalFields(\n schema: Schema | Reference,\n components?: Components,\n): string[] {\n const declared: string[] = [];\n const required = new Set<string>();\n const visited = new Set<Schema | Reference>();\n // A schema that admits null generates `T | null`, whose `keyof` is `never`:\n // naming a field of it would make `PartialBy<Model, 'field'>` violate\n // `K extends keyof T` (TS2344). Such a command takes no PartialBy at all.\n let admitsNull = false;\n const walk = (current: Schema | Reference | undefined): void => {\n if (!current || visited.has(current) || admitsNull) {\n return;\n }\n visited.add(current);\n if (isReference(current)) {\n // A reference the document does not carry contributes nothing rather\n // than making every property of the command look required.\n walk(components && extractSchema(current, components));\n return;\n }\n if (current.nullable || Array.isArray(current.type)) {\n admitsNull = true;\n return;\n }\n for (const name of current.required ?? []) {\n required.add(name);\n }\n for (const name of Object.keys(current.properties ?? {})) {\n if (!declared.includes(name)) {\n declared.push(name);\n }\n }\n current.allOf?.forEach(walk);\n };\n walk(schema);\n return admitsNull ? [] : declared.filter(name => !required.has(name));\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n Components,\n HTTPMethod,\n Operation,\n Parameter,\n PathItem,\n Paths,\n Reference,\n Response,\n Schema,\n} from '@ahoo-wang/fetcher-openapi';\nimport { compareNames } from '../naming/order';\nimport { extractParameter, extractResponse } from './components';\nimport { isReference } from './references';\nimport { extractResponseJsonSchema } from './responses';\nimport { isPrimitive, resolvePrimitiveType } from './schemas';\n\n/**\n * Represents an HTTP method and its associated operation.\n */\nexport interface MethodOperation {\n /** The HTTP method */\n method: HTTPMethod;\n /** The OpenAPI operation */\n operation: Operation;\n}\n\nexport interface OperationEndpoint extends MethodOperation {\n path: string;\n}\n\nexport function operationEndpointComparator(\n left: OperationEndpoint,\n right: OperationEndpoint,\n): number {\n if (left.operation.operationId && right.operation.operationId) {\n return compareNames(\n left.operation.operationId,\n right.operation.operationId,\n );\n }\n if (left.path && right.path) {\n return compareNames(left.path, right.path);\n }\n if (left.method && right.method) {\n return compareNames(left.method, right.method);\n }\n return 0;\n}\n\nfunction mergeParameters(\n inherited: (Parameter | Reference)[],\n own: (Parameter | Reference)[],\n components?: Components,\n): (Parameter | Reference)[] {\n const parameters = new Map<string, Parameter | Reference>();\n for (const parameter of [...inherited, ...own]) {\n const resolved = isReference(parameter)\n ? components && extractParameter(parameter, components)\n : parameter;\n const key = resolved\n ? `${resolved.in}:${resolved.name}`\n : (parameter as Reference).$ref;\n parameters.set(key, parameter);\n }\n return [...parameters.values()];\n}\n\nexport function extractOperationEndpoints(\n paths: Paths,\n components?: Components,\n): Array<OperationEndpoint> {\n const operationEndpoints: OperationEndpoint[] = [];\n for (const [path, pathItem] of Object.entries(paths)) {\n extractOperations(pathItem).forEach(methodOperation => {\n operationEndpoints.push({\n method: methodOperation.method,\n operation: pathItem.parameters?.length\n ? {\n ...methodOperation.operation,\n parameters: mergeParameters(\n pathItem.parameters,\n methodOperation.operation.parameters ?? [],\n components,\n ),\n }\n : methodOperation.operation,\n path,\n });\n });\n }\n return operationEndpoints.sort(operationEndpointComparator);\n}\n\n/**\n * Extracts all operations from a path item.\n * @param pathItem - The OpenAPI path item\n * @returns Array of method-operation pairs\n */\nexport function extractOperations(pathItem: PathItem): MethodOperation[] {\n return [\n { method: 'get', operation: pathItem.get },\n { method: 'put', operation: pathItem.put },\n { method: 'post', operation: pathItem.post },\n { method: 'delete', operation: pathItem.delete },\n { method: 'options', operation: pathItem.options },\n { method: 'head', operation: pathItem.head },\n { method: 'patch', operation: pathItem.patch },\n { method: 'trace', operation: pathItem.trace },\n ].filter(({ operation }) => operation !== undefined) as Array<{\n method: HTTPMethod;\n operation: Operation;\n }>;\n}\n\n/**\n * Picks the status code of an operation's success response: `200`, else the\n * lowest other 2xx code, else `2XX`.\n *\n * @param operation - The OpenAPI operation\n * @returns The status code key, or undefined when no 2xx response is declared\n */\nexport function okResponseStatus(operation: Operation): string | undefined {\n const statuses = Object.keys(operation.responses ?? {});\n if (statuses.includes('200')) return '200';\n const exact = statuses.filter(status => /^2\\d\\d$/.test(status)).sort();\n if (exact.length > 0) return exact[0];\n return statuses.find(status => status.toUpperCase() === '2XX');\n}\n\n/**\n * Extracts the success response from an operation: `200`, else the lowest\n * other 2xx response, else `2XX`.\n * @param operation - The OpenAPI operation\n * @param components - Optional components used to resolve response references\n * @returns The success response or undefined if not found\n */\nexport function extractOkResponse(\n operation: Operation,\n components?: Components,\n): Response | Reference | undefined {\n const status = okResponseStatus(operation);\n const response = status ? operation.responses[status] : undefined;\n return components && isReference(response)\n ? extractResponse(response, components)\n : response;\n}\n\n/**\n * Extracts the JSON schema from the OK response of an operation.\n * @param operation - The OpenAPI operation\n * @param components - Optional components used to resolve response references\n * @returns The JSON schema from the OK response or undefined if not found\n */\nexport function extractOperationOkResponseJsonSchema(\n operation: Operation,\n components?: Components,\n): Schema | Reference | undefined {\n const okResponse = extractOkResponse(operation, components);\n return extractResponseJsonSchema(okResponse);\n}\n\n/**\n * Extracts the parameters of an operation, references resolved, in document\n * order.\n * @param operation - The OpenAPI operation\n * @param components - The OpenAPI components object used to resolve references\n * @returns The parameters\n */\nexport function extractParameters(\n operation: Operation,\n components: Components,\n): Parameter[] {\n return (operation.parameters ?? [])\n .map(parameter =>\n isReference(parameter)\n ? extractParameter(parameter, components)\n : parameter,\n )\n .filter((parameter): parameter is Parameter => parameter !== undefined);\n}\n\n/**\n * Extracts path parameters from an operation.\n * @param operation - The OpenAPI operation to extract path parameters from\n * @param components - The OpenAPI components object used to resolve references\n * @returns Array of path parameters\n */\nexport function extractPathParameters(\n operation: Operation,\n components: Components,\n): Parameter[] {\n if (!operation.parameters) {\n return [];\n }\n return operation.parameters\n .map(parameter => {\n if (isReference(parameter)) {\n return extractParameter(parameter, components);\n }\n return parameter;\n })\n .filter((parameter): parameter is Parameter => parameter?.in === 'path');\n}\n\n/**\n * Orders path parameters as the path holds them, whatever order the document\n * lists them in: `/cart/{id}/{customerId}` gives `id`, then `customerId`.\n * A method takes them in this order, so a route that gains a variable keeps\n * the arguments before it where they were. Parameters the path does not\n * hold keep their order, after the others.\n *\n * @param path - The route, with `{name}` variables\n * @param parameters - Its path parameters\n * @returns A new array, sorted\n */\nexport function inPathOrder<P extends Pick<Parameter, 'name'>>(\n path: string,\n parameters: readonly P[],\n): P[] {\n const position = (parameter: P) => {\n const index = path.indexOf(`{${parameter.name}}`);\n return index < 0 ? Number.MAX_SAFE_INTEGER : index;\n };\n return [...parameters].sort((a, b) => position(a) - position(b));\n}\n\nconst DEFAULT_PATH_PARAMETER_TYPE = 'string';\n\n/**\n * Resolves the type of a path parameter.\n * @param parameter - The path parameter to resolve the type for\n * @returns The resolved primitive type as a string, or the default path parameter type if the schema is missing,\n * is a reference, lacks a type, or the type is not primitive\n */\nexport function resolvePathParameterType(parameter: Parameter): string {\n if (\n !parameter.schema ||\n isReference(parameter.schema) ||\n !parameter.schema.type ||\n !isPrimitive(parameter.schema.type)\n ) {\n return DEFAULT_PATH_PARAMETER_TYPE;\n }\n return resolvePrimitiveType(parameter.schema.type);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Anything that is neither a letter, a digit nor `$` separates the words of a\n * name: `-`, `_`, `.`, spaces, and characters no identifier may hold, such as\n * the guillemets of a Springfox `Page«User»`.\n */\nconst NAMING_SEPARATORS = /[^\\p{L}\\p{N}$]+/u;\n\n/**\n * Words JavaScript reserves, in strict mode included, which may not name a\n * parameter or a variable.\n */\nconst RESERVED_WORDS = new Set([\n 'arguments',\n 'await',\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'interface',\n 'let',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'static',\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Tells whether a name is a valid identifier as written.\n *\n * @param name - The candidate\n * @returns True when it can name a variable, a parameter or a type\n */\nexport function isIdentifier(name: string): boolean {\n return (\n /^[\\p{ID_Start}$_][\\p{ID_Continue}$\\u200C\\u200D]*$/u.test(name) &&\n !RESERVED_WORDS.has(name)\n );\n}\n\nfunction prefixLeadingDigit(name: string): string {\n return /^\\p{N}/u.test(name) ? `_${name}` : name;\n}\n\n/**\n * Turns a name from the document into a value identifier: a parameter, a\n * method or a variable.\n *\n * A valid identifier is kept as written. Anything else is camel-cased on its\n * separators (`item-id` → `itemId`), prefixed with `_` when it starts with a\n * digit, and suffixed with `_` when it is a reserved word (`default` →\n * `default_`).\n *\n * @param name - The name the document uses\n * @returns A valid identifier\n */\nexport function toIdentifier(name: string): string {\n if (isIdentifier(name)) return name;\n const identifier = prefixLeadingDigit(camelCase(name) || '_');\n return RESERVED_WORDS.has(identifier) ? `${identifier}_` : identifier;\n}\n\n/**\n * Tells whether a part of a type name is kept as written: it starts with an\n * upper-case letter and holds only letters, digits and `$`, so its casing,\n * acronyms included, is the document's own (`MCPListTools`).\n */\nfunction isTypeNamePart(part: string): boolean {\n return /^\\p{Lu}[\\p{L}\\p{N}$]*$/u.test(part) && isIdentifier(part);\n}\n\n/**\n * Turns a name from the document into a type identifier: a model, an enum or\n * a class.\n *\n * Each part that starts with an upper-case letter and holds no separator is\n * kept as written, acronyms included (`MCPListTools` stays `MCPListTools`).\n * Any other part is pascal-cased on its separators (`order_item` →\n * `OrderItem`, `Page«User»` → `PageUser`). The result is prefixed with `_`\n * when it starts with a digit (`1stThing` → `_1stThing`).\n *\n * @param name - A name, or the parts of one\n * @returns A valid type identifier\n */\nexport function toTypeIdentifier(name: string | string[]): string {\n const parts = Array.isArray(name) ? name : [name];\n const identifier = parts\n .map(part => (isTypeNamePart(part) ? part : pascalCase(part)))\n .join('');\n return prefixLeadingDigit(identifier || '_');\n}\n\nexport function splitName(name: string) {\n return name.split(NAMING_SEPARATORS);\n}\n\n/**\n * Splits a name string or array of strings by common naming separators.\n *\n * This function takes a string or array of strings and splits them based on common naming\n * separators including hyphens, underscores, spaces, dots, and before uppercase letters.\n * If an array is provided, each element is split individually and the results are flattened.\n *\n * @param name - A string or array of strings to split by naming separators\n * @returns An array of string parts split by naming separators\n */\nexport function tokenizeName(name: string | string[]): string[] {\n if (Array.isArray(name)) {\n // If input is an array, split each element by naming separators and flatten the result\n return name.flatMap(part => splitCamelCase(splitName(part)));\n }\n return splitCamelCase(splitName(name));\n}\n\n/**\n * Splits camelCase strings properly, keeping consecutive uppercase letters together.\n *\n * @param parts - Array of string parts to process\n * @returns Array of properly split parts\n */\nexport function splitCamelCase(parts: string[]): string[] {\n return parts.flatMap(part => {\n if (part.length === 0) {\n return [];\n }\n\n // Split on uppercase letters that follow lowercase letters\n const result: string[] = [];\n let current = '';\n\n for (let i = 0; i < part.length; i++) {\n const char = part[i];\n const isUpper = /[A-Z]/.test(char);\n const prevIsLower = i > 0 && /[a-z]/.test(part[i - 1]);\n\n if (isUpper && prevIsLower && current) {\n result.push(current);\n current = char;\n } else {\n current += char;\n }\n }\n\n if (current) {\n result.push(current);\n }\n\n return result;\n });\n}\n\n/**\n * Converts a string or array of strings to PascalCase format.\n *\n * This function takes a string or array of strings and converts them to PascalCase format\n * by splitting the input based on common naming separators and capitalizing the first\n * letter of each part.\n *\n * @param name - A string or array of strings to convert to PascalCase\n * @returns The PascalCase formatted string\n */\nexport function pascalCase(name: string | string[]): string {\n if (name === '' || name.length === 0) {\n return '';\n }\n const names: string[] = tokenizeName(name);\n return names\n .filter(part => part.length > 0)\n .map(part => {\n const firstChar = part.charAt(0);\n const rest = part.slice(1);\n return (\n (/[a-zA-Z]/.test(firstChar) ? firstChar.toUpperCase() : firstChar) +\n rest.toLowerCase()\n );\n })\n .join('');\n}\n\n/**\n * Converts a string or array of strings to camelCase format.\n *\n * This function first converts the input to PascalCase and then converts the first character to lowercase.\n *\n * @param name - A string or array of strings to convert to camelCase\n * @returns The camelCase formatted string\n */\nexport function camelCase(name: string | string[]): string {\n const pascalCaseName = pascalCase(name);\n return pascalCaseName.charAt(0).toLowerCase() + pascalCaseName.slice(1);\n}\n\n/**\n * Converts a string or array of strings to UPPER_SNAKE_CASE format.\n *\n * This function takes a string or array of strings and converts them to UPPER_SNAKE_CASE format\n * by splitting the input based on common naming separators, converting each part to uppercase,\n * and joining them with underscores. It properly handles consecutive uppercase letters\n * (like acronyms) by treating them as single units.\n *\n * @param name - A string or array of strings to convert to UPPER_SNAKE_CASE\n * @returns The UPPER_SNAKE_CASE formatted string\n */\nexport function upperSnakeCase(name: string | string[]): string {\n if (name === '' || (Array.isArray(name) && name.length === 0)) {\n return '';\n }\n\n const names = tokenizeName(name);\n return names\n .filter(part => part.length > 0)\n .map(part => part.toUpperCase())\n .join('_');\n}\n\nexport function resolvePropertyName(name: string): string {\n if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n return name;\n }\n\n return quoteStringLiteral(name);\n}\n\n/**\n * The member key an enum value prefers, before quoting: its UPPER_SNAKE_CASE\n * form, `NUM_` and the digits for a number.\n */\nexport function enumMemberKey(name: string): string {\n if (/^\\d+$/.test(name)) {\n return `NUM_${name}`;\n }\n return upperSnakeCase(name) || name;\n}\n\n/**\n * Renders a value as a single-quoted TypeScript string literal.\n *\n * A property name is whatever the document says it is, so one carrying a\n * quote or a backslash has to be escaped rather than wrapped - `owner'sName`\n * would otherwise close the literal and generate a syntax error.\n *\n * @param value - The string to render\n * @returns The escaped string literal, quotes included\n */\nexport function quoteStringLiteral(value: string): string {\n // JSON escapes backslashes, double quotes, line breaks and control\n // characters; swap the double-quote escaping for single quotes.\n const escaped = JSON.stringify(value)\n .slice(1, -1)\n .replace(/\\\\\"/g, '\"')\n .replace(/'/g, \"\\\\'\");\n return `'${escaped}'`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GeneratorError } from '../api/errors';\nimport { camelCase, isIdentifier, toIdentifier } from '../naming/naming';\nimport type { Operation } from '@ahoo-wang/fetcher-openapi';\n\n/** Operation extension naming the method an operation generates. */\nexport const OPERATION_METHOD_NAME_KEY = 'x-fetcher-method';\n\n/**\n * Names the method an operation generates.\n *\n * The name depends on the operation alone, so adding an operation never\n * renames an existing method:\n *\n * 1. a name configured for the operationId (`apiClients[tag].methodNames`);\n * 2. else the operation's `x-fetcher-method` extension;\n * 3. else the last dot-separated segment of the operationId, camel-cased:\n * `getUserById` → `getUserById`, `delete_user_by_id` → `deleteUserById`,\n * `getUser_1` → `getUser1`, `users.list` → `list`,\n * `example.cart.add_cart_item` → `addCartItem`; a name starting with a\n * digit is prefixed with `_`.\n *\n * Two operations of one client that arrive at the same name are an error the\n * caller reports; the first two sources resolve it.\n *\n * @param operation - The OpenAPI operation\n * @param configured - The name configured for its operationId, if any\n * @returns The method name, or undefined for an operation without an operationId\n * @throws GeneratorError when a configured or extension name is not a valid method name\n */\nexport function resolveMethodName(\n operation: Operation,\n configured?: string,\n): string | undefined {\n const explicit = configured ?? operation[OPERATION_METHOD_NAME_KEY];\n if (explicit !== undefined) {\n if (typeof explicit !== 'string' || !isMethodName(explicit)) {\n throw new GeneratorError(\n 'specification',\n `${OPERATION_METHOD_NAME_KEY} of ${operation.operationId ?? 'an operation'} is ${JSON.stringify(explicit)}, which is not a valid method name.`,\n );\n }\n return explicit;\n }\n if (!operation.operationId) {\n return undefined;\n }\n const lastSegment = operation.operationId.split('.').pop()!;\n const name = camelCase(lastSegment) || '_';\n return /^\\p{N}/u.test(name) ? `_${name}` : name;\n}\n\n/**\n * Tells whether a name can name a method. Unlike a variable, a method may be\n * named by a reserved word: `delete()` is fine.\n */\nfunction isMethodName(name: string): boolean {\n return isIdentifier(name) || /^[a-z]+$/.test(name);\n}\n\n/**\n * Turns a parameter name from the document into a unique parameter\n * identifier: `item-id` → `itemId`, and `id` twice → `id`, `id2`.\n *\n * @param name - The name the document uses\n * @param used - The identifiers the method already uses; updated\n * @returns The identifier\n */\nexport function uniqueParameterName(name: string, used: Set<string>): string {\n const identifier = toIdentifier(name);\n let unique = identifier;\n for (let suffix = 2; used.has(unique); suffix++) {\n unique = `${identifier}${suffix}`;\n }\n used.add(unique);\n return unique;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GeneratorError } from '../api/errors';\nimport type { Components, Reference } from '@ahoo-wang/fetcher-openapi';\nimport {\n COMPONENTS_SCHEMAS_REF,\n extractComponentKey,\n extractSchema,\n} from '../openapi/components';\nimport type { ModelInfo } from '../naming/modelInfo';\nimport { toTypeIdentifier } from '../naming/naming';\n\nexport type { ModelInfo } from '../naming/modelInfo';\n\n/**\n * Resolves model information from a schema key.\n *\n * This function parses a dot-separated schema key and extracts the model name and path.\n * It assumes that the model name is the first part that starts with an uppercase letter.\n * All parts before the model name are treated as the path.\n *\n * @example\n *\n * - \"wow.api.BindingError\" -> {path:'/wow/api',name:'BindingError'}\n * - \"compensation.ApiVersion\" -> {path:'/compensation',name:'ApiVersion'}\n * - \"ai.AiMessage.Assistant\" -> {path:'/ai',name:'AiMessageAssistant'}\n * - \"Result\" -> {path:'/',name:'Result'}\n *\n * @param schemaKey - The dot-separated schema key (e.g., \"com.example.User\")\n * @returns ModelInfo object containing the parsed name and path\n */\nexport function resolveModelInfo(schemaKey: string): ModelInfo {\n if (!schemaKey) {\n return { name: '', path: '/' };\n }\n const parts = schemaKey.split('.');\n let modelNameIndex = -1;\n\n // Find the first part that starts with an uppercase letter\n for (let i = 0; i < parts.length; i++) {\n if (parts[i] && /^[A-Z]/.test(parts[i])) {\n modelNameIndex = i;\n break;\n }\n }\n\n // Construct the path from parts before the model name\n const pathParts = parts.slice(0, modelNameIndex);\n const path = pathParts.length > 0 ? `/${pathParts.join('/')}` : '/';\n\n // Construct the model name from the remaining parts\n const nameParts = parts.slice(modelNameIndex);\n const name = toTypeIdentifier(nameParts);\n\n return { name, path };\n}\n\n/**\n * The model a reference names.\n *\n * @param reference - A reference to a component schema\n * @param components - The document's components; given, the reference is\n * followed to its schema, so a chain of references that comes back to itself\n * fails here rather than as code that cannot compile\n * @throws GeneratorError for a reference outside the component schemas, or\n * a cyclic one\n */\nexport function resolveReferenceModelInfo(\n reference: Reference,\n components?: Components,\n): ModelInfo {\n if (!reference.$ref.startsWith(COMPONENTS_SCHEMAS_REF)) {\n throw new GeneratorError(\n 'specification',\n `Unsupported schema reference: ${reference.$ref}. Bundle or inline external schemas before generation.`,\n );\n }\n if (components) extractSchema(reference, components);\n return resolveModelInfo(extractComponentKey(reference));\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Operation, RequestBody, Tag } from '@ahoo-wang/fetcher-openapi';\nimport type { GeneratorConfiguration } from '../api/configuration';\nimport { GeneratorError } from '../api/errors';\nimport type { ModelInfo } from '../naming/modelInfo';\nimport { combinePaths } from '../naming/paths';\nimport { extractRequestBody, extractSchema } from '../openapi/components';\nimport type { OpenApiDocument } from '../openapi/document';\nimport type { OperationEndpoint } from '../openapi/operations';\nimport {\n extractOkResponse,\n extractParameters,\n inPathOrder,\n} from '../openapi/operations';\nimport { isReference } from '../openapi/references';\nimport {\n APPLICATION_JSON,\n extractResponseEventStreamSchema,\n extractResponseJsonSchema,\n extractResponseWildcardSchema,\n findMediaType,\n hasTextResponse,\n isJsonContentType,\n isTextContentType,\n} from '../openapi/responses';\nimport { isArray, resolveOptionalFields } from '../openapi/schemas';\nimport { resolveMethodName, uniqueParameterName } from './clientNames';\nimport type {\n ApiClientModel,\n ApiMethodModel,\n BodyModel,\n ParameterModel,\n ReturnModel,\n} from './model';\nimport { resolveModelInfo, resolveReferenceModelInfo } from './modelInfo';\n\n/** Parameter names every generated method uses itself. */\nconst RESERVED_PARAMETER_NAMES = ['httpRequest', 'attributes'];\n\n/**\n * The API clients of a document: one per tag, holding a method per\n * operation.\n *\n * @param warnings - Receives a line for every operation left out and every\n * client renamed\n * @throws GeneratorError when two operations of a client name the same\n * method, or a configured or extension method name is not one\n */\nexport function analyzeApiClients(\n document: OpenApiDocument,\n config: GeneratorConfiguration,\n warnings: string[],\n): ApiClientModel[] {\n const analysis = new ApiClientAnalysis(document, config, warnings);\n return analysis.clients();\n}\n\nclass ApiClientAnalysis {\n constructor(\n private readonly document: OpenApiDocument,\n private readonly config: GeneratorConfiguration,\n private readonly warnings: string[],\n ) {}\n\n /**\n * One client per tag, sorted by tag name.\n *\n * Two tags can name the same class once normalised - `user-controller` and\n * `UserController`. The tag sorting first keeps the name, the others get a\n * numbered one, with a warning.\n */\n clients(): ApiClientModel[] {\n const tags = this.tags();\n const operations = this.groupOperations();\n const claimed = new Map<string, string>();\n return [...operations.keys()].sort().map(tagName => {\n const modelInfo = resolveModelInfo(tagName);\n let clientInfo = modelInfo;\n for (let suffix = 2; claimed.has(clientKey(clientInfo)); suffix++) {\n clientInfo = { ...modelInfo, name: `${modelInfo.name}${suffix}` };\n }\n if (clientInfo !== modelInfo) {\n this.warnings.push(\n `Tags ${claimed.get(clientKey(modelInfo))} and ${tagName} both name the API client ${modelInfo.name}ApiClient; ${tagName} generates ${clientInfo.name}ApiClient.`,\n );\n }\n claimed.set(clientKey(clientInfo), tagName);\n return this.client(tags.get(tagName)!, clientInfo, [\n ...operations.get(tagName)!,\n ]);\n });\n }\n\n /** The client of a tag, under the name it was given. */\n private client(\n tag: Tag,\n modelInfo: ModelInfo,\n operations: readonly OperationEndpoint[],\n ): ApiClientModel {\n const className = `${modelInfo.name}ApiClient`;\n const file = combinePaths(modelInfo.path, apiClientFileName(className));\n const methods = new Map<string, string>();\n return {\n tagName: tag.name,\n className,\n file,\n description: tag.description,\n methods: operations.map(operation =>\n this.method(tag, className, operation, methods),\n ),\n };\n }\n\n /** The method an operation generates. */\n private method(\n tag: Tag,\n className: string,\n endpoint: OperationEndpoint,\n methods: Map<string, string>,\n ): ApiMethodModel {\n const { operation } = endpoint;\n const name = this.methodName(tag, className, endpoint, methods);\n const used = new Set(RESERVED_PARAMETER_NAMES);\n const parameters = this.parameters(tag, endpoint, used);\n const body = this.body(operation, used);\n // The method takes the required parameters first; its doc follows suit.\n const described = [\n ...parameters.filter(({ parameter }) => parameter.required),\n ...parameters.filter(({ parameter }) => !parameter.required),\n ].filter(({ description }) => description);\n return {\n name,\n httpMethod: endpoint.method,\n path: endpoint.path,\n parameters: parameters.map(({ parameter }) => parameter),\n body,\n returns: this.returns(operation),\n docs: [\n operation.summary,\n operation.description,\n `- operationId: \\`${operation.operationId}\\``,\n `- path: \\`${endpoint.path}\\``,\n ...described.map(\n ({ parameter, description }) =>\n `@param ${parameter.name} - ${description!.replace(/\\s*\\n\\s*/g, ' ')}`,\n ),\n ],\n };\n }\n\n /**\n * Names the method an operation generates, failing when another operation\n * of the client already took the name: renaming either one to make room\n * would rename an existing method when an operation is added.\n */\n private methodName(\n tag: Tag,\n className: string,\n endpoint: OperationEndpoint,\n methods: Map<string, string>,\n ): string {\n const operationId = endpoint.operation.operationId!;\n const methodName = resolveMethodName(\n endpoint.operation,\n this.config.apiClients?.[tag.name]?.methodNames?.[operationId],\n )!;\n const taken = methods.get(methodName);\n if (taken !== undefined) {\n throw new GeneratorError(\n 'specification',\n `Operations ${taken} and ${operationId} of tag ${tag.name} both generate the method ${className}.${methodName}(). Name one of them with apiClients[\"${tag.name}\"].methodNames in the generator configuration, or with the ${'x-fetcher-method'} extension.`,\n );\n }\n methods.set(methodName, operationId);\n return methodName;\n }\n\n /**\n * The path, query and header parameters of an operation, each named after\n * the document's name (`item-id` → `itemId`), in the order their types\n * resolve: the path parameters in the order the path holds them, then the\n * query and header parameters in the document's order. Path parameters the\n * configuration names are left out (see {@link ignoresPathParameter}), and\n * cookie parameters, which\n * the browser sends, are left out with a warning.\n */\n private parameters(\n tag: Tag,\n endpoint: OperationEndpoint,\n used: Set<string>,\n ): { parameter: ParameterModel; description?: string }[] {\n const declared = extractParameters(\n endpoint.operation,\n this.document.components ?? {},\n );\n const parameters: { parameter: ParameterModel; description?: string }[] =\n [];\n for (const location of ['path', 'query', 'header'] as const) {\n const located = declared.filter(parameter => parameter.in === location);\n for (const parameter of location === 'path'\n ? inPathOrder(endpoint.path, located)\n : located) {\n if (\n location === 'path' &&\n this.ignoresPathParameter(tag.name, parameter.name)\n ) {\n continue;\n }\n parameters.push({\n parameter: {\n name: uniqueParameterName(parameter.name, used),\n location,\n parameterName: parameter.name,\n schema: parameter.schema,\n required: location === 'path' || parameter.required === true,\n },\n description: parameter.description,\n });\n }\n }\n const cookies = declared.filter(parameter => parameter.in === 'cookie');\n if (cookies.length > 0) {\n this.warnings.push(\n `${endpoint.method.toUpperCase()} ${endpoint.path} leaves out its cookie parameter(s) ${cookies.map(cookie => cookie.name).join(', ')}: the browser sends cookies, and fetch cannot set them.`,\n );\n }\n return parameters;\n }\n\n /**\n * Tells whether an API client leaves a path parameter out: the ones the\n * configuration names for the tag, which an interceptor fills.\n */\n private ignoresPathParameter(tagName: string, parameterName: string) {\n const ignored = this.config.apiClients?.[tagName]?.ignorePathParameters;\n return ignored?.includes(parameterName) ?? false;\n }\n\n /**\n * The body an operation sends, by its content: JSON (`application/json`,\n * `+json`), `multipart/form-data`, `application/x-www-form-urlencoded`,\n * `text/*`, or anything else.\n */\n private body(operation: Operation, used: Set<string>): BodyModel | undefined {\n if (!operation.requestBody) {\n return undefined;\n }\n const requestBody: RequestBody | undefined = isReference(\n operation.requestBody,\n )\n ? extractRequestBody(operation.requestBody, this.document.components!)\n : operation.requestBody;\n if (!requestBody) {\n return undefined;\n }\n const required = requestBody.required === true;\n const content = requestBody.content ?? {};\n const json = findMediaType(content, APPLICATION_JSON, isJsonContentType);\n const name = uniqueParameterName('body', used);\n if (json?.schema) {\n return {\n name,\n required,\n content: {\n kind: 'json',\n schema: json.schema,\n optionalFields: resolveOptionalFields(\n json.schema,\n this.document.components,\n ),\n },\n };\n }\n if (findMediaType(content, 'multipart/form-data')) {\n return { name, required, content: { kind: 'formData' } };\n }\n if (findMediaType(content, 'application/x-www-form-urlencoded')) {\n return { name, required, content: { kind: 'urlEncoded' } };\n }\n if (Object.keys(content).some(isTextContentType)) {\n return { name, required, content: { kind: 'text' } };\n }\n return { name, required, content: { kind: 'binary' } };\n }\n\n /**\n * What an operation returns, read from its success response: `200`, else\n * the lowest other 2xx.\n */\n private returns(operation: Operation): ReturnModel {\n const okResponse = extractOkResponse(operation, this.document.components);\n if (!okResponse) {\n return { kind: 'response' };\n }\n const responseJsonSchema = extractResponseJsonSchema(okResponse);\n const jsonSchema =\n responseJsonSchema || extractResponseWildcardSchema(okResponse);\n if (jsonSchema) {\n return {\n kind: 'json',\n schema: jsonSchema,\n wildcard: !responseJsonSchema,\n };\n }\n const eventStreamSchema = extractResponseEventStreamSchema(okResponse);\n if (eventStreamSchema) {\n if (isReference(eventStreamSchema)) {\n const schema = extractSchema(\n eventStreamSchema,\n this.document.components!,\n )!;\n if (isArray(schema) && isReference(schema.items)) {\n const modelInfo = resolveReferenceModelInfo(\n schema.items,\n this.document.components,\n );\n return {\n kind: 'eventStream',\n items: schema.items,\n serverSentEvent: modelInfo.name.includes('ServerSentEvent'),\n };\n }\n }\n return { kind: 'eventStream', serverSentEvent: false };\n }\n if (hasTextResponse(okResponse)) {\n return { kind: 'text' };\n }\n return { kind: 'response' };\n }\n\n /**\n * Groups operations by their tags.\n *\n * An operation needs an operationId, which names its method, and a tag,\n * which names its client; one without either is skipped with a warning.\n */\n private groupOperations(): Map<string, Set<OperationEndpoint>> {\n const operations = new Map<string, Set<OperationEndpoint>>();\n for (const endpoint of this.document.endpoints) {\n const label = `${endpoint.method.toUpperCase()} ${endpoint.path}`;\n const operationTags = endpoint.operation.tags ?? [];\n if (operationTags.length === 0) {\n this.warnings.push(\n `Skipping ${label}: it has no tag, and the tag names its API client.`,\n );\n continue;\n }\n if (!endpoint.operation.operationId) {\n this.warnings.push(\n `Skipping ${label}: it has no operationId, and the operationId names its method.`,\n );\n continue;\n }\n for (const tagName of operationTags) {\n if (!operations.has(tagName)) {\n operations.set(tagName, new Set());\n }\n operations.get(tagName)!.add(endpoint);\n }\n }\n return operations;\n }\n\n /**\n * The tags that generate API clients: the ones the operations use or the\n * document declares.\n */\n private tags(): Map<string, Tag> {\n const tags = new Map<string, Tag>();\n for (const { operation } of this.document.endpoints) {\n operation.tags?.forEach(tagName => {\n if (!tags.has(tagName)) {\n tags.set(tagName, { name: tagName, description: '' });\n }\n });\n }\n this.document.openAPI.tags?.forEach(tag => tags.set(tag.name, tag));\n return tags;\n }\n}\n\n/**\n * The file an API client is declared in: its class name with the first\n * letter lowered, `CartApiClient` → `cartApiClient.ts`, camelCase like every\n * other generated file. Client names differ by more than case (see\n * {@link clientKey}), so no two clients share a file, even on a file system\n * that ignores case.\n */\nfunction apiClientFileName(className: string): string {\n return `${className.charAt(0).toLowerCase()}${className.slice(1)}.ts`;\n}\n\nfunction clientKey(modelInfo: ModelInfo): string {\n return `${modelInfo.path}/${modelInfo.name}`.toLowerCase();\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GeneratorError } from '../api/errors';\nimport { modelFilePath } from '../naming/paths';\nimport type { OpenApiDocument } from '../openapi/document';\nimport type { ModelDeclaration } from './model';\nimport { resolveModelInfo } from './modelInfo';\n\n/**\n * The models of a document: one per component schema, in the document's\n * order.\n *\n * @throws GeneratorError when two schemas generate the same model\n */\nexport function analyzeModels(document: OpenApiDocument): ModelDeclaration[] {\n const schemas = document.components?.schemas;\n if (!schemas) return [];\n const keys = Object.keys(schemas);\n assertUniqueModelNames(keys);\n return keys.map(key => {\n const schema = schemas[key];\n const info = resolveModelInfo(key);\n return { key, info, file: modelFilePath(info), schema };\n });\n}\n\n/**\n * Fails when two schemas generate the same model in the same file.\n *\n * Names are normalised to PascalCase, so `Foo-Bar`, `FooBar` and `foo_bar`\n * all become `FooBar`; TypeScript would silently merge three interfaces of\n * that name into one type that matches none of them.\n *\n * @throws GeneratorError listing every group of colliding schema keys\n */\nfunction assertUniqueModelNames(keys: readonly string[]) {\n const byModel = new Map<string, string[]>();\n for (const key of keys) {\n const modelInfo = resolveModelInfo(key);\n const model = `${modelInfo.path === '/' ? '' : modelInfo.path}/${modelInfo.name}`;\n byModel.set(model, [...(byModel.get(model) ?? []), key]);\n }\n const collisions = [...byModel].filter(([, keys]) => keys.length > 1);\n if (collisions.length === 0) return;\n throw new GeneratorError(\n 'specification',\n `Schemas generate the same model: ${collisions\n .map(([model, keys]) => `${keys.join(', ')} → ${model}`)\n .join('; ')}. Rename all but one of them in the document.`,\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { GeneratorConfiguration } from '../api/configuration';\nimport type { OpenApiDocument } from '../openapi/document';\nimport { analyzeApiClients } from './apiClients';\nimport type { Analysis } from './model';\nimport { analyzeModels } from './models';\n\n/**\n * Decides what an OpenAPI document generates: its models and API clients. A\n * pure function of the document and the configuration; nothing is written\n * and nothing logged.\n *\n * @param document - The document, left unchanged\n * @param config - The generator configuration\n * @returns The generation model, and the warnings for what it leaves out\n * @throws GeneratorError when the document asks for code that cannot\n * compile: two schemas of one model, two operations of one method\n */\nexport function analyze(\n document: OpenApiDocument,\n config: GeneratorConfiguration,\n): Analysis {\n const warnings: string[] = [];\n const models = analyzeModels(document);\n const apiClients = analyzeApiClients(document, config, warnings);\n return { model: { models, apiClients }, warnings };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ImportDeclarationStructure, OptionalKind } from 'ts-morph';\n\n/** A name one module imports from another, under an alias or its own name. */\nexport interface NamedImport {\n readonly name: string;\n alias?: string;\n}\n\n/**\n * The imports of one generated module, kept in memory until the module is\n * written.\n *\n * Declarations stay in the order their modules were first imported, and\n * names in the order they were first asked for, as the file would have\n * received them one by one; `organizeImports` sorts them when the file is\n * finished.\n */\nexport class ImportRegistry {\n private readonly declarations = new Map<string, NamedImport[]>();\n\n /**\n * Imports names from a module, keeping the ones it already imports.\n *\n * @param moduleSpecifier - The module to import from\n * @param names - The names to import\n * @returns The names the module now imports\n */\n add(\n moduleSpecifier: string,\n names: readonly string[],\n ): readonly NamedImport[] {\n let imported = this.declarations.get(moduleSpecifier);\n if (!imported) {\n imported = [];\n this.declarations.set(moduleSpecifier, imported);\n }\n for (const name of names) {\n if (!imported.some(item => item.name === name)) {\n imported.push({ name });\n }\n }\n return imported;\n }\n\n /**\n * Applies imports a resolved type asks for, in order: each name is\n * imported, and takes the alias the request gives it.\n *\n * @param requests - The imports, as `types/typeResolver.ts` returns them\n */\n apply(\n requests: readonly {\n moduleSpecifier: string;\n name: string;\n alias?: string;\n }[],\n ): void {\n for (const { moduleSpecifier, name, alias } of requests) {\n const item = this.add(moduleSpecifier, [name]).find(\n imported => imported.name === name,\n )!;\n if (alias !== undefined) item.alias = alias;\n }\n }\n\n /** Every name imported, with its module and alias, in the order first asked for. */\n entries(): { moduleSpecifier: string; name: string; alias?: string }[] {\n return [...this.declarations].flatMap(([moduleSpecifier, imported]) =>\n imported.map(({ name, alias }) =>\n alias === undefined\n ? { moduleSpecifier, name }\n : { moduleSpecifier, name, alias },\n ),\n );\n }\n\n /**\n * The local names every import binds, the ones of `except` aside: an\n * alias where it has one, else the name.\n */\n localNames(except?: NamedImport): string[] {\n return [...this.declarations.values()]\n .flat()\n .filter(item => item !== except)\n .map(item => item.alias ?? item.name);\n }\n\n /** The import declarations, in the order they were first asked for. */\n structures(): OptionalKind<ImportDeclarationStructure>[] {\n return [...this.declarations].map(([moduleSpecifier, imported]) => ({\n moduleSpecifier,\n namedImports: imported.map(({ name, alias }) =>\n alias === undefined ? name : { name, alias },\n ),\n }));\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ClassDeclarationStructure,\n CodeBlockWriter,\n EnumDeclarationStructure,\n EnumMemberStructure,\n ImportDeclarationStructure,\n InterfaceDeclarationStructure,\n OptionalKind,\n SourceFile,\n StatementStructures,\n TypeAliasDeclarationStructure,\n VariableStatementStructure,\n WriterFunction,\n} from 'ts-morph';\nimport { StructureKind } from 'ts-morph';\nimport { ImportRegistry } from './importRegistry';\n\n/** A top-level statement of a generated module. */\nexport type ModuleStatement =\n | ClassDeclarationStructure\n | EnumDeclarationStructure\n | InterfaceDeclarationStructure\n | TypeAliasDeclarationStructure\n | VariableStatementStructure\n | string;\n\n/**\n * A generated module, collected in memory and written into its source file\n * once.\n *\n * ts-morph re-parses the whole file on every change, so a file written a\n * declaration, a property and a doc comment at a time costs time that grows\n * with the square of its length: the root `types.ts` of a large document runs\n * to 20,000 lines. Here the emitters describe each declaration as a ts-morph\n * structure, with its members and docs, and {@link build} inserts the lot in\n * one change, printed by the same printers.\n *\n * The blank lines between statements are the ones the file would have got\n * receiving the statements one by one, so the output is byte for byte the\n * same: a type alias follows a type alias, and a variable statement a\n * variable statement, on the next line; anything else is set off by a blank\n * line.\n */\nexport class ModuleBuilder {\n /** The imports of the module. */\n readonly imports = new ImportRegistry();\n private readonly statements: ModuleStatement[] = [];\n\n /**\n * @param sourceFile - The file the module is written into; it stays empty\n * until {@link build}.\n */\n constructor(readonly sourceFile: SourceFile) {}\n\n /** The directory of the module's file, which relative imports start from. */\n get directoryPath(): string {\n return this.sourceFile.getDirectoryPath();\n }\n\n /**\n * Adds a top-level statement. A structure stays open to changes until the\n * module is built.\n *\n * @returns The statement added\n */\n add<T extends ModuleStatement>(statement: T): T {\n this.statements.push(statement);\n return statement;\n }\n\n /** Writes the imports and the statements into the file in one change. */\n build(): SourceFile {\n const statements: (StatementStructures | string | WriterFunction)[] = [];\n let previous: ModuleStatement | ImportDeclarationStructure | undefined;\n for (const declaration of this.imports.structures()) {\n previous = { ...declaration, kind: StructureKind.ImportDeclaration };\n statements.push(previous);\n }\n for (const statement of this.statements) {\n if (previous && blankLineBetween(previous, statement)) {\n statements.push(blankLine);\n }\n statements.push(statement);\n previous = statement;\n }\n if (statements.length > 0) {\n this.sourceFile.addStatements(statements);\n }\n return this.sourceFile;\n }\n}\n\n/**\n * The modules of one generation, one builder per file, written together at\n * the end.\n */\nexport class ModuleSet {\n private readonly modules = new Map<string, ModuleBuilder>();\n\n /**\n * @param open - Returns the source file a path relative to the output\n * directory is written to, claiming it for the generation\n */\n constructor(private readonly open: (filePath: string) => SourceFile) {}\n\n /**\n * The module written to a path under the output directory, created the\n * first time it is asked for.\n */\n module(filePath: string): ModuleBuilder {\n const sourceFile = this.open(filePath);\n const key = sourceFile.getFilePath();\n let module = this.modules.get(key);\n if (!module) {\n module = new ModuleBuilder(sourceFile);\n this.modules.set(key, module);\n }\n return module;\n }\n\n /** Writes every module into its file, each in one go. */\n build(): void {\n for (const module of this.modules.values()) module.build();\n this.modules.clear();\n }\n}\n\n/** Starts the next statement after a blank line. */\nconst blankLine: WriterFunction = (writer: CodeBlockWriter) => {\n writer.blankLineIfLastNot();\n};\n\n/**\n * Tells whether a statement added after another one is set off by a blank\n * line, as ts-morph separates statements added one at a time.\n */\nfunction blankLineBetween(\n previous: ModuleStatement | ImportDeclarationStructure,\n next: ModuleStatement,\n): boolean {\n if (typeof next === 'string') return false;\n switch (next.kind) {\n case StructureKind.TypeAlias:\n case StructureKind.VariableStatement:\n return typeof previous === 'string' || previous.kind !== next.kind;\n default:\n return true;\n }\n}\n\n/**\n * Enum members printed as adding them one at a time to an enum leaves them:\n * each one followed by a comma, the last one too. The printer separates\n * members with commas only where a member does not already end with one.\n *\n * @param members - The members, each with a string initializer\n */\nexport function membersWithTrailingComma(\n members: readonly OptionalKind<EnumMemberStructure>[],\n): OptionalKind<EnumMemberStructure>[] {\n return members.map(member => ({\n ...member,\n initializer: `${member.initializer as string},`,\n }));\n}\n\n/**\n * The index signature of an interface, as a member printed after its\n * properties, where adding it after them puts it: a structure's\n * `indexSignatures` are printed first.\n *\n * @param returnType - The type of the additional properties\n * @param docs - Its doc comments\n */\nexport function indexSignatureMember(\n returnType: string,\n docs?: string[],\n): OptionalKind<\n NonNullable<InterfaceDeclarationStructure['properties']>[number]\n> {\n return { name: '[key: string]', type: returnType, docs };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { join, relative, sep } from 'path';\nimport type { ModelInfo } from '../naming/modelInfo';\nimport { MODEL_FILE_NAME } from '../naming/paths';\nimport type { NamedImport } from './importRegistry';\nimport type { ModuleBuilder } from './moduleBuilder';\n\n/** Alias for import paths */\nconst IMPORT_ALIAS = '@';\n\n/**\n * Adds named imports to a module.\n * @param module - The module to modify\n * @param moduleSpecifier - The module to import from\n * @param namedImports - Array of named imports to add\n * @returns The names the module now imports from `moduleSpecifier`\n */\nexport function addImport(\n module: ModuleBuilder,\n moduleSpecifier: string,\n namedImports: string[],\n): readonly NamedImport[] {\n return module.imports.add(moduleSpecifier, namedImports);\n}\n\n/**\n * Adds an import for a referenced model.\n * @param module - The module to modify\n * @param outputDir - The output directory\n * @param refModelInfo - The referenced model information\n */\nexport function addImportRefModel(\n module: ModuleBuilder,\n outputDir: string,\n refModelInfo: ModelInfo,\n): readonly NamedImport[] {\n return addImport(\n module,\n modelModuleSpecifier(module, outputDir, refModelInfo),\n [refModelInfo.name],\n );\n}\n\n/**\n * The specifier a module imports a model by: the package of a model imported\n * from one (a path starting with `@`), else the relative path of the\n * `types.ts` that declares it.\n *\n * @param module - The importing module\n * @param outputDir - The output directory\n * @param model - The model\n */\nexport function modelModuleSpecifier(\n module: ModuleBuilder,\n outputDir: string,\n model: ModelInfo,\n): string {\n if (model.path.startsWith(IMPORT_ALIAS)) return model.path;\n return relativeModuleSpecifier(\n module.directoryPath,\n join(outputDir, model.path, MODEL_FILE_NAME),\n );\n}\n\n/**\n * The specifier a source file imports another generated file by.\n *\n * Relative specifiers carry the `.js` extension, which every module\n * resolution TypeScript offers accepts for a `.ts` file: `NodeNext` and\n * `Node16` require it, and `bundler` and `node10` map it back to the source.\n *\n * @param fromDirectory - The directory of the importing file\n * @param targetFilePath - The imported `.ts` file, or a directory holding an `index.ts`\n * @returns A specifier starting with `./` or `../` and ending with `.js`\n */\nexport function relativeModuleSpecifier(\n fromDirectory: string,\n targetFilePath: string,\n): string {\n let relativePath = relative(fromDirectory, targetFilePath)\n .split(sep)\n .join('/');\n relativePath = relativePath.endsWith('.ts')\n ? relativePath.replace(/\\.ts$/, '.js')\n : `${relativePath}/index.js`;\n return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Reference, Schema } from '@ahoo-wang/fetcher-openapi';\nimport type { JSDocableNodeStructure } from 'ts-morph';\n\n/**\n * Generates a JSDoc comment string from a title and description.\n * @returns The formatted JSDoc string or undefined if both title and description are empty\n */\nexport function jsDoc(\n descriptions: (string | undefined)[],\n separator = '\\n',\n): string | undefined {\n if (!Array.isArray(descriptions)) {\n return undefined;\n }\n const filtered = descriptions\n .filter((v): v is string => typeof v === 'string' && v.length > 0)\n .map(escapeJsDoc);\n return filtered.length > 0 ? filtered.join(separator) : undefined;\n}\n\n/**\n * Keeps document text from ending the comment it is written into: a\n * description holding `*` followed by `/` - a cron expression such as\n * `*` `/5 * * * *`, a glob - would otherwise close the JSDoc early.\n *\n * @param text - Text taken from the document\n * @returns The text with every comment terminator broken up\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, '*\\\\/');\n}\n\n/**\n * Adds a JSDoc comment to a declaration with the provided title and\n * description, after the ones it already has.\n */\nexport function addJSDoc(\n node: JSDocableNodeStructure,\n descriptions: (string | undefined)[],\n) {\n const jsdoc = jsDoc(descriptions);\n if (!jsdoc) {\n return;\n }\n node.docs = [...(node.docs ?? []), jsdoc];\n}\n\n/**\n * The doc comment lines of a schema.\n *\n * A nullable value written as `anyOf: [{type: null}, X]` (or `oneOf`) is\n * documented from its non-null branch too, so its `format` and constraints\n * are not lost; what the schema itself says comes first.\n *\n * @param schema - The schema\n * @param key - The schema's component key, given for a model\n * @param main - Whether the comment is a model's, which also lists the\n * properties its schema requires\n */\nexport function schemaJSDoc(schema: Schema, key?: string, main = false) {\n schema = withNonNullBranch(schema);\n const descriptions: (string | undefined)[] = [\n schema.title,\n schema.description,\n ];\n if (key) {\n descriptions.push(`- key: ${key}`);\n }\n if (main) {\n addRequiredJsDoc(descriptions, schema);\n }\n if (schema.format) {\n descriptions.push(\n schema.format === 'int64'\n ? '- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)'\n : `- format: ${schema.format}`,\n );\n }\n\n addJsonJsDoc(descriptions, schema, 'default');\n addJsonJsDoc(descriptions, schema, 'example');\n addNumericConstraintsJsDoc(descriptions, schema);\n addStringConstraintsJsDoc(descriptions, schema);\n addArrayConstraintsJsDoc(descriptions, schema);\n return descriptions;\n}\n\n/**\n * Adds a JSDoc comment to a declaration based on the schema's title and description.\n * @param node - The declaration to add the JSDoc comment to\n * @param schema - The schema containing title and description\n * @param key - The key associated with the schema\n */\nexport function addSchemaJSDoc(\n node: JSDocableNodeStructure,\n schema: Schema | Reference,\n key?: string,\n) {\n const descriptions = schemaJSDoc(schema as Schema, key);\n addJSDoc(node, descriptions);\n}\n\n/**\n * Adds the doc comment of a model.\n *\n * @param node - The model declaration\n * @param schema - The schema it is generated from\n * @param key - The schema's component key\n * @param includeSchema - Also embed the complete JSON schema\n */\nexport function addMainSchemaJSDoc(\n node: JSDocableNodeStructure,\n schema: Schema | Reference,\n key?: string,\n includeSchema = false,\n) {\n const descriptions = schemaJSDoc(schema as Schema, key, true);\n if (includeSchema) {\n jsonJsDoc(descriptions, 'schema', schema);\n }\n addJSDoc(node, descriptions);\n}\n\n/**\n * Merges the single non-null branch of a nullable composition under the\n * schema, so the schema's own keywords win. Any other schema is returned as\n * it is: a branch that is a reference documents itself.\n */\nfunction withNonNullBranch(schema: Schema): Schema {\n for (const keyword of ['anyOf', 'oneOf'] as const) {\n const members = schema[keyword];\n if (!Array.isArray(members) || members.length < 2) continue;\n const nonNull = members.filter(\n member => '$ref' in member || member.type !== 'null',\n );\n const [branch] = nonNull;\n if (nonNull.length !== 1 || '$ref' in branch) continue;\n const merged: Schema = { ...branch };\n for (const [name, value] of Object.entries(schema)) {\n if (name !== keyword && value !== undefined) {\n (merged as Record<string, unknown>)[name] = value;\n }\n }\n return merged;\n }\n return schema;\n}\n\n/**\n * Lists the properties an object schema requires, which the generated type\n * does not tell: every generated property is declared without `?`.\n */\nfunction addRequiredJsDoc(\n descriptions: (string | undefined)[],\n schema: Schema,\n) {\n const required = schema.required ?? [];\n if (!required.length && !Object.keys(schema.properties ?? {}).length) {\n return;\n }\n descriptions.push(\n `- required: ${required.length ? required.join(', ') : '(none)'}`,\n );\n}\n\nfunction addJsonJsDoc(\n descriptions: (string | undefined)[],\n schema: any,\n propertyName: keyof Schema,\n) {\n const json = schema[propertyName];\n if (!json) {\n return;\n }\n if (typeof json !== 'object') {\n descriptions.push(`- ${propertyName}: \\`${json}\\``);\n return;\n }\n jsonJsDoc(descriptions, propertyName, json);\n}\n\nfunction jsonJsDoc(\n descriptions: (string | undefined)[],\n name: string,\n json: any,\n) {\n descriptions.push(`- ${name}: `);\n descriptions.push('```json');\n descriptions.push(JSON.stringify(json, null, 2));\n descriptions.push('```');\n}\n\nfunction addNumericConstraintsJsDoc(\n descriptions: (string | undefined)[],\n schema: Schema,\n) {\n const constraintsDescriptions = ['- Numeric Constraints'];\n if (schema.minimum !== undefined) {\n constraintsDescriptions.push(` - minimum: ${schema.minimum}`);\n }\n if (schema.maximum !== undefined) {\n constraintsDescriptions.push(` - maximum: ${schema.maximum}`);\n }\n if (schema.exclusiveMinimum !== undefined) {\n constraintsDescriptions.push(\n ` - exclusiveMinimum: ${schema.exclusiveMinimum}`,\n );\n }\n if (schema.exclusiveMaximum !== undefined) {\n constraintsDescriptions.push(\n ` - exclusiveMaximum: ${schema.exclusiveMaximum}`,\n );\n }\n if (schema.multipleOf !== undefined) {\n constraintsDescriptions.push(` - multipleOf: ${schema.multipleOf}`);\n }\n if (constraintsDescriptions.length === 1) {\n return;\n }\n descriptions.push(...constraintsDescriptions);\n}\n\nfunction addStringConstraintsJsDoc(\n descriptions: (string | undefined)[],\n schema: Schema,\n) {\n const constraintsDescriptions = ['- String Constraints'];\n if (schema.minLength !== undefined) {\n constraintsDescriptions.push(` - minLength: ${schema.minLength}`);\n }\n if (schema.maxLength !== undefined) {\n constraintsDescriptions.push(` - maxLength: ${schema.maxLength}`);\n }\n if (schema.pattern !== undefined) {\n constraintsDescriptions.push(` - pattern: ${schema.pattern}`);\n }\n if (constraintsDescriptions.length === 1) {\n return;\n }\n descriptions.push(...constraintsDescriptions);\n}\n\nfunction addArrayConstraintsJsDoc(\n descriptions: (string | undefined)[],\n schema: Schema,\n) {\n const constraintsDescriptions = ['- Array Constraints'];\n if (schema.minItems !== undefined) {\n constraintsDescriptions.push(` - minItems: ${schema.minItems}`);\n }\n if (schema.maxItems !== undefined) {\n constraintsDescriptions.push(` - maxItems: ${schema.maxItems}`);\n }\n if (schema.uniqueItems !== undefined) {\n constraintsDescriptions.push(` - uniqueItems: ${schema.uniqueItems}`);\n }\n if (constraintsDescriptions.length === 1) {\n return;\n }\n descriptions.push(...constraintsDescriptions);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Components, Reference, Schema } from '@ahoo-wang/fetcher-openapi';\nimport { CodeBlockWriter } from 'ts-morph';\nimport { jsDoc, schemaJSDoc } from '../emit/jsdoc';\nimport type { ModelInfo } from '../naming/modelInfo';\nimport { quoteStringLiteral, resolvePropertyName } from '../naming/naming';\nimport { extractComponentKey, extractSchema } from '../openapi/components';\nimport { isReference } from '../openapi/references';\nimport type { MapSchema, ObjectSchema } from '../openapi/schemas';\nimport {\n getMapKeySchema,\n isAllOf,\n isComposition,\n isEnum,\n isMap,\n isObject,\n isReadOnly,\n resolvePrimitiveType,\n toArrayType,\n} from '../openapi/schemas';\n\n/**\n * Schema → TypeScript type expression, as pure functions.\n *\n * Every entry point takes a schema and a {@link TypeScope} - where the type\n * is written - and returns a {@link ResolvedType}: the type's text, and the\n * imports the module needs for it. Nothing is written; the caller applies the\n * imports to its module (`ImportRegistry.apply`) before it resolves the next\n * type, so a later reference sees the names and aliases an earlier one took.\n */\n\n/** An import a resolved type needs: a name, and the alias it goes by. */\nexport interface ImportRequest {\n readonly moduleSpecifier: string;\n readonly name: string;\n readonly alias?: string;\n}\n\n/** A type expression, and the imports it needs. */\nexport interface ResolvedType {\n readonly text: string;\n readonly imports: readonly ImportRequest[];\n}\n\n/** The imports a module already holds, as the resolver reads them. */\nexport interface ImportLookup {\n entries(): readonly ImportRequest[];\n}\n\n/**\n * What stays the same for every type of one document: its components, how a\n * component names its model, and the model names declared at each path.\n */\nexport interface TypeContext {\n readonly components?: Components;\n /** The model a reference names. */\n modelOf(reference: Reference): ModelInfo;\n /** The models declared at a path, with their `EnumText` companions. */\n namesAt(path: string): readonly string[];\n}\n\n/**\n * How a document's component keys name models: `resolveModelInfo` and\n * `resolveReferenceModelInfo` of `analysis/modelInfo.ts`.\n */\nexport interface ModelNaming {\n ofKey(key: string): ModelInfo;\n ofReference(reference: Reference, components?: Components): ModelInfo;\n}\n\n/**\n * Builds the context of a document. The model names of each path are read\n * once, on first use, rather than from every component for every reference.\n */\nexport function createTypeContext(\n components: Components | undefined,\n naming: ModelNaming,\n): TypeContext {\n let namesByPath: Map<string, string[]> | undefined;\n return {\n components,\n modelOf: reference => naming.ofReference(reference, components),\n namesAt(path) {\n if (!namesByPath) {\n namesByPath = new Map();\n for (const key of Object.keys(components?.schemas ?? {})) {\n const model = naming.ofKey(key);\n let names = namesByPath.get(model.path);\n if (!names) {\n names = [];\n namesByPath.set(model.path, names);\n }\n names.push(model.name, `${model.name}EnumText`);\n }\n }\n return namesByPath.get(path) ?? [];\n },\n };\n}\n\n/** Where a type is written. */\nexport interface TypeScope {\n readonly context: TypeContext;\n /**\n * The declaration the type belongs to. An import never takes its name.\n * With a `path`, it is a model: the models of that path are declared beside\n * it, so a reference to one needs no import, and an import takes none of\n * their names. Without, every referenced model is imported.\n */\n readonly owner: { readonly name: string; readonly path?: string };\n /** The specifier the module imports a model by. */\n specifierOf(model: ModelInfo): string;\n /** The imports the module holds. */\n readonly imports: ImportLookup;\n}\n\n/**\n * Global names generated code relies on. A model imported under one of these\n * names would shadow the global, so the import is aliased instead: a model\n * named `Response` must not turn `Promise<Response>` into a promise of the\n * model.\n */\nexport const GLOBAL_TYPE_NAMES: readonly string[] = [\n 'Array',\n 'Blob',\n 'Exclude',\n 'FormData',\n 'Partial',\n 'Promise',\n 'ReadonlyArray',\n 'Record',\n 'Response',\n 'Symbol',\n 'URLSearchParams',\n];\n\n/** The TypeScript types a primitive schema type resolves to. */\nconst PRIMITIVE_TYPE_NAMES = new Set(['string', 'number', 'boolean']);\n\n/**\n * Keywords that describe a schema without constraining its instances.\n */\nconst ANNOTATION_KEYWORDS = new Set([\n '$comment',\n '$schema',\n 'default',\n 'deprecated',\n 'description',\n 'example',\n 'examples',\n 'externalDocs',\n 'readOnly',\n 'title',\n 'writeOnly',\n 'xml',\n]);\n\n/**\n * What a schema generates, as far as assignability to an index signature goes.\n *\n * A primitive carries its resolved TypeScript type; `object` and `array` need\n * no further detail, since neither is ever assignable to a primitive.\n */\ntype SchemaKind = 'object' | 'array' | { primitive: string };\n\n/** Tells whether two classifications describe the same generated shape. */\nfunction sameKind(left: SchemaKind | undefined, right: SchemaKind): boolean {\n if (left === undefined) return false;\n if (typeof left === 'string' || typeof right === 'string') {\n return left === right;\n }\n return left.primitive === right.primitive;\n}\n\n/**\n * Classifies a schema, following references through the components.\n *\n * Returns undefined - undecided - for anything whose assignability cannot be\n * read off the schema: a composition, a const, a nullable schema, a type\n * union, a missing `type`, a reference that cannot be resolved and a\n * reference cycle. An enum is decided by the type it sits beside, since it\n * generates literals of exactly that type.\n *\n * @param schema - The schema to classify\n * @param components - The components a reference resolves against\n * @param seen - The references already followed, guarding against a cycle\n * @returns The schema's kind, or undefined when it cannot be decided\n */\nfunction schemaKind(\n schema: Schema | Reference,\n components?: Components,\n seen: Set<string> = new Set(),\n): SchemaKind | undefined {\n if (isReference(schema)) {\n if (!components || seen.has(schema.$ref)) return undefined;\n seen.add(schema.$ref);\n const resolved = extractSchema(schema, components);\n return resolved ? schemaKind(resolved, components, seen) : undefined;\n }\n if (schema.nullable || Array.isArray(schema.type)) {\n return undefined;\n }\n // An `allOf` narrows to whatever its branches agree on, so it is decided\n // when every one of them decides and they all say the same thing. `anyOf`\n // and `oneOf` widen instead, and stay undecided.\n if (isAllOf(schema) && schema.type === undefined) {\n const kinds = schema.allOf.map(member =>\n schemaKind(member, components, seen),\n );\n const [first] = kinds;\n return first !== undefined && kinds.every(kind => sameKind(kind, first))\n ? first\n : undefined;\n }\n if (\n isComposition(schema) ||\n schema.const !== undefined ||\n schema.type === undefined\n ) {\n return undefined;\n }\n // An enum beside a sibling type generates literals of that type, which a\n // matching primitive index accepts - `'a' | 'b'` sits beside `string`.\n if (schema.type === 'object') return 'object';\n if (schema.type === 'array') return 'array';\n return { primitive: resolvePrimitiveType(schema.type) };\n}\n\n/**\n * Tells whether a named property provably cannot sit beside the index signature.\n *\n * The index type has to resolve to a primitive. That is not about proving the\n * clash - it is what keeps the alias sound: `Record<string, T>` in a type alias\n * may not lead back to the alias itself (TS2456), and only a primitive `T` is\n * certain never to. A property may reference anything, including the model\n * itself, because an object member defers.\n *\n * Against a primitive index, an object and an array are as incompatible as a\n * different primitive is, and so is a property whose kind cannot be read off\n * the schema: a nullable property generates `T | null`, a type array and a\n * typeless enum generate a union, and none of those is assignable to a\n * primitive index (TS2411). Undecided therefore takes the intersection, which\n * has no index-assignability rule to break. It cannot be circular either\n * (TS2456), because the index resolved to a primitive before we got here, so\n * the `Record` this generates can never lead back to the alias.\n *\n * @param propSchema - The named property's schema\n * @param additionalProperties - The additional-property schema\n * @param components - The components a reference resolves against\n * @returns True when the property may not be assignable to the index type\n */\nfunction clashesWithIndexSignature(\n propSchema: Schema | Reference,\n additionalProperties: Schema | Reference,\n components?: Components,\n): boolean {\n const indexKind = schemaKind(additionalProperties, components);\n if (typeof indexKind !== 'object') return false;\n const propertyKind = schemaKind(propSchema, components);\n if (propertyKind === undefined) return true;\n return (\n typeof propertyKind === 'string' ||\n propertyKind.primitive !== indexKind.primitive\n );\n}\n\n/**\n * Chooses the intersection representation over an interface with an index\n * signature.\n *\n * An interface may only carry a named property whose type is assignable to\n * its index signature (TS2411). Every generated property is required, so\n * only a clash that can be PROVEN off the schemas moves one - see\n * {@link clashesWithIndexSignature}. Anything undecided keeps the interface,\n * which is the only form that can reference itself through an index\n * signature: an alias reaching itself through `Record` is circular (TS2456),\n * which is what a dictionary of its own type would generate.\n *\n * @param schema - The object schema to represent\n * @param components - The components a reference resolves against\n * @returns True when the schema needs the intersection form\n */\nexport function requiresAdditionalPropertiesIntersection(\n schema: Schema,\n components?: Components,\n): boolean {\n const additionalProperties = schema.additionalProperties;\n if (typeof additionalProperties !== 'object') {\n return false;\n }\n return Object.values(schema.properties ?? {}).some(propSchema =>\n clashesWithIndexSignature(propSchema, additionalProperties, components),\n );\n}\n\n/**\n * Tells whether a schema is the OpenAPI 3.0 idiom for a nullable reference:\n * `nullable: true` beside a composition of references alone, such as\n * `{nullable: true, allOf: [{$ref: X}]}`.\n *\n * Strictly, `nullable` only widens a sibling `type`, and a member that\n * requires an object rules null out; springdoc and Swagger nevertheless write\n * this form for a property that may be null, and mean `X | null`. An inline\n * member keeps the strict reading.\n */\nfunction isNullableReference(schema: Schema): boolean {\n if (schema.nullable !== true || isEnum(schema) || !isComposition(schema)) {\n return false;\n }\n return [schema.allOf, schema.oneOf, schema.anyOf].every(\n members => members === undefined || members.every(isReference),\n );\n}\n\nfunction matchesLiteralType(value: unknown, schema: Schema): boolean {\n if (schema.type === undefined) return true;\n if (value === null && schema.nullable) return true;\n return [schema.type].flat().some(type => {\n if (type === 'null') return value === null;\n if (type === 'array') return Array.isArray(value);\n if (type === 'object') {\n return (\n value !== null && typeof value === 'object' && !Array.isArray(value)\n );\n }\n if (type === 'integer')\n return typeof value === 'number' && Number.isInteger(value);\n return typeof value === type;\n });\n}\n\n/**\n * Renders a JSON value as a TypeScript literal type: a string in single\n * quotes, escaped as ts-morph's printer escapes it, an array as a tuple, an\n * object as an object type that no array matches.\n *\n * @param value - The value from the document\n * @returns The literal type\n */\nexport function resolveLiteral(value: unknown): string {\n if (typeof value === 'string') {\n return new CodeBlockWriter({ useSingleQuote: true })\n .quote(value)\n .toString();\n }\n if (Array.isArray(value)) {\n return `[${value.map(item => resolveLiteral(item)).join(', ')}]`;\n }\n if (value !== null && typeof value === 'object') {\n const properties = Object.entries(value).map(\n ([name, item]) => `${resolvePropertyName(name)}: ${resolveLiteral(item)}`,\n );\n return properties.length\n ? `{ ${properties.join('; ')}; readonly [globalThis.Symbol.iterator]?: never }`\n : 'globalThis.Record<string, never>';\n }\n return JSON.stringify(value) ?? 'never';\n}\n\n/** An import as one resolution sees it: the module's, or one it added. */\ninterface ImportEntry {\n readonly moduleSpecifier: string;\n readonly name: string;\n alias?: string;\n}\n\n/**\n * One resolution: the scope, and the imports it has seen and asked for. It\n * starts from the module's imports and never changes them; what it asks for\n * is its result.\n */\nclass Resolution {\n private readonly entries: ImportEntry[];\n private readonly requested: ImportEntry[] = [];\n\n constructor(private readonly scope: TypeScope) {\n this.entries = scope.imports.entries().map(entry => ({ ...entry }));\n }\n\n get components(): Components | undefined {\n return this.scope.context.components;\n }\n\n /** The imports asked for, in the order first asked, with their aliases. */\n imports(): ImportRequest[] {\n return this.requested.map(({ moduleSpecifier, name, alias }) =>\n alias === undefined\n ? { moduleSpecifier, name }\n : { moduleSpecifier, name, alias },\n );\n }\n\n private request(entry: ImportEntry): void {\n if (!this.requested.includes(entry)) this.requested.push(entry);\n }\n\n /**\n * The name a reference goes by in the module: the model's own name when it\n * is declared beside the owner or imported as it is, else the alias of its\n * import. An import whose name the owner, a global, a model beside the\n * owner or another import already takes is aliased with leading `_`s.\n */\n reference(reference: Reference): string {\n const model = this.scope.context.modelOf(reference);\n const { owner } = this.scope;\n if (owner.path === model.path) return model.name;\n const moduleSpecifier = this.scope.specifierOf(model);\n let entry = this.entries.find(\n item =>\n item.moduleSpecifier === moduleSpecifier && item.name === model.name,\n );\n if (!entry) {\n entry = { moduleSpecifier, name: model.name };\n this.entries.push(entry);\n }\n this.request(entry);\n if (entry.alias) return entry.alias;\n const reservedNames = new Set([\n ...GLOBAL_TYPE_NAMES,\n owner.name,\n ...(owner.path === undefined\n ? []\n : this.scope.context.namesAt(owner.path)),\n ...this.entries\n .filter(item => item !== entry)\n .map(item => item.alias ?? item.name),\n ]);\n if (!reservedNames.has(model.name)) return model.name;\n let alias = `_${model.name}`;\n while (reservedNames.has(alias)) alias = `_${alias}`;\n entry.alias = alias;\n return alias;\n }\n\n additionalProperties(schema: Schema): string {\n if (\n schema.additionalProperties === false ||\n (schema.additionalProperties === undefined &&\n !schema.required?.some(\n name => !Object.hasOwn(schema.properties ?? {}, name),\n ))\n ) {\n return '';\n }\n\n if (\n schema.additionalProperties === true ||\n schema.additionalProperties === undefined\n ) {\n return '[key: string]: any';\n }\n\n return `[key: string]: ${this.additionalPropertyType(schema)}`;\n }\n\n additionalPropertyType(schema: Schema): string {\n return this.type(\n typeof schema.additionalProperties === 'object'\n ? schema.additionalProperties\n : {},\n );\n }\n\n requiredAdditionalPropertyType(schema: Schema): string {\n if (schema.additionalProperties === false) return 'never';\n if (typeof schema.additionalProperties === 'object') {\n return this.type(schema.additionalProperties);\n }\n return 'null | string | number | boolean | globalThis.Record<string, unknown> | readonly unknown[]';\n }\n\n private propertyDefinitions(schema: ObjectSchema): string[] {\n const { properties } = schema;\n return Object.entries(properties).map(([propName, propSchema]) => {\n const type = this.type(propSchema);\n const resolvedPropName =\n (isReadOnly(propSchema) ? 'readonly ' : '') +\n resolvePropertyName(propName);\n if (!isReference(propSchema)) {\n const jsDocDescriptions = schemaJSDoc(propSchema);\n const doc = jsDoc(jsDocDescriptions, '\\n * ');\n if (doc) {\n return `\n /**\n * ${doc}\n */\n ${resolvedPropName}: ${type}\n `;\n }\n }\n return `${resolvedPropName}: ${type}`;\n });\n }\n\n private objectType(schema: Schema): string {\n const parts: string[] = [];\n if (isObject(schema)) {\n parts.push(...this.propertyDefinitions(schema));\n }\n\n for (const name of schema.required ?? []) {\n if (!Object.hasOwn(schema.properties ?? {}, name)) {\n parts.push(\n `${resolvePropertyName(name)}: ${this.requiredAdditionalPropertyType(schema)}`,\n );\n }\n }\n const mapType =\n isMap(schema) && getMapKeySchema(schema)\n ? this.mapType(schema)\n : requiresAdditionalPropertiesIntersection(schema, this.components)\n ? `globalThis.Record<string, ${this.additionalPropertyType(schema)}>`\n : undefined;\n const additionalProps = mapType ? '' : this.additionalProperties(schema);\n if (additionalProps) {\n parts.push(additionalProps);\n }\n\n if (parts.length === 0) {\n return 'globalThis.Record<string, any>';\n }\n\n const objectType = `{\\n ${parts.join(';\\n ')}; \\n}`;\n return mapType ? `(${objectType} & ${mapType})` : objectType;\n }\n\n mapValueType(schema: MapSchema): string {\n if (\n schema.additionalProperties === undefined ||\n schema.additionalProperties === false ||\n schema.additionalProperties === true\n ) {\n return 'any';\n }\n return this.type(schema.additionalProperties);\n }\n\n private mapKeyType(schema: Schema): string {\n const mapKeySchema = getMapKeySchema(schema);\n if (!mapKeySchema) {\n return 'string';\n }\n return this.type(mapKeySchema);\n }\n\n private mapType(schema: MapSchema): string {\n const keyType = this.mapKeyType(schema);\n const valueType = this.mapValueType(schema);\n return `globalThis.Record<${keyType},${valueType}>`;\n }\n\n private objectConstrained(schema: Schema | Reference): boolean {\n const resolve = (member: Schema | Reference): Schema | undefined =>\n isReference(member)\n ? this.components && extractSchema(member, this.components)\n : member;\n const root = resolve(schema);\n const nodes = new Map<Schema, (Schema | undefined)[][]>();\n const constrained = new Set<Schema>();\n const pending = root ? [root] : [];\n for (const current of pending) {\n if (nodes.has(current)) continue;\n const groups = [current.allOf, current.oneOf, current.anyOf].map(\n members => members?.map(resolve) ?? [],\n );\n nodes.set(current, groups);\n for (const members of groups) {\n for (const member of members) {\n if (member && !nodes.has(member)) pending.push(member);\n }\n }\n if (\n current.type === 'object' ||\n current.type === 'null' ||\n (Array.isArray(current.type) &&\n current.type.length > 0 &&\n current.type.every(type => type === 'object' || type === 'null'))\n )\n constrained.add(current);\n }\n\n // ponytail: O(V * (V + E)); use a dependency worklist for very large graphs.\n let changed = true;\n while (changed) {\n changed = false;\n for (const [current, [allOf, oneOf, anyOf]] of nodes) {\n if (constrained.has(current)) continue;\n const isConstrained = (member: Schema | undefined) =>\n member !== undefined && constrained.has(member);\n if (\n allOf.some(isConstrained) ||\n [oneOf, anyOf].some(\n members => members.length > 0 && members.every(isConstrained),\n )\n ) {\n constrained.add(current);\n changed = true;\n }\n }\n }\n return root !== undefined && constrained.has(root);\n }\n\n type(schema: Schema | Reference): string {\n if (isReference(schema)) {\n return this.reference(schema);\n }\n if (Array.isArray(schema.type)) {\n return schema.type\n .map(type => {\n const resolved = this.type({ ...schema, type });\n return /[|&]/.test(resolved) ? `(${resolved})` : resolved;\n })\n .join(' | ');\n }\n if (isNullableReference(schema)) {\n // OpenAPI 3.0 writes a nullable reference as {nullable, allOf: [$ref]}.\n return `(${this.type({ ...schema, nullable: false })}) | null`;\n }\n if (isComposition(schema)) {\n const simple = this.simpleComposition(schema);\n if (simple !== undefined) return simple;\n const compositions = (['allOf', 'oneOf', 'anyOf'] as const).flatMap(\n keyword => {\n const schemas = schema[keyword];\n if (!schemas?.length) return [];\n const types = schemas.map(member => {\n const type = this.memberType(schema, keyword, member);\n return type === 'any'\n ? 'unknown'\n : /[|&]/.test(type)\n ? `(${type})`\n : type;\n });\n return [`(${types.join(keyword === 'allOf' ? ' & ' : ' | ')})`];\n },\n );\n const composed =\n compositions.length === 1\n ? compositions[0]\n : `(${compositions.join(' & ')})`;\n const base = {\n ...schema,\n oneOf: undefined,\n anyOf: undefined,\n allOf: undefined,\n };\n const baseType = this.type(base);\n const type =\n baseType === 'any' ? composed : `(${composed} & (${baseType}))`;\n // Weak object types can otherwise admit non-object branches through intersections.\n return this.objectConstrained(schema)\n ? `globalThis.Exclude<${type}, string | number | boolean | readonly unknown[]> & ({ readonly [globalThis.Symbol.iterator]?: never } | null)`\n : type;\n }\n if (schema.const !== undefined) {\n if (!matchesLiteralType(schema.const, schema)) return 'never';\n const literal = resolveLiteral(schema.const);\n const baseType = this.type({ ...schema, const: undefined });\n return baseType === 'any' ? literal : `(${literal}) & (${baseType})`;\n }\n if (schema.nullable && schema.type && !isEnum(schema)) {\n return `(${this.type({ ...schema, nullable: false })}) | null`;\n }\n if (isEnum(schema)) {\n const literal =\n schema.enum\n .filter(value => matchesLiteralType(value, schema))\n .map(value => resolveLiteral(value))\n .join(' | ') || 'never';\n const baseType = this.type({ ...schema, enum: undefined });\n // Every literal already matches its primitive type, so intersecting\n // with a bare primitive adds nothing but noise.\n return baseType === 'any' || PRIMITIVE_TYPE_NAMES.has(baseType)\n ? literal\n : `(${literal}) & (${baseType})`;\n }\n if (isMap(schema) && !schema.required?.length) {\n return this.mapType(schema);\n }\n\n if (schema.type === 'array') {\n return toArrayType(this.type(schema.items ?? {}));\n }\n if (schema.type === 'object') {\n return this.objectType(schema);\n }\n if (!schema.type) {\n if (\n schema.required?.length ||\n Object.keys(schema.properties ?? {}).length > 0\n ) {\n // Object keywords constrain object instances without rejecting other JSON types.\n const objectType = this.objectType({\n ...schema,\n type: 'object',\n additionalProperties: schema.additionalProperties ?? true,\n });\n return `(${objectType} | null | string | number | boolean | readonly unknown[])`;\n }\n return 'any';\n }\n return resolvePrimitiveType(schema.type);\n }\n\n /**\n * Resolves a composition of references alone - `allOf: [$ref]`,\n * `anyOf: [$ref, {type: null}]`, a discriminated `oneOf` - to the plain\n * union or intersection of its members.\n *\n * With no sibling keyword that constrains the instance, the members say\n * everything, and none of the guards the general form needs applies.\n *\n * @returns The type, or undefined when the composition is not that simple\n */\n private simpleComposition(schema: Schema): string | undefined {\n const keywords = (['allOf', 'oneOf', 'anyOf'] as const).filter(\n keyword => schema[keyword]?.length,\n );\n if (keywords.length !== 1) return undefined;\n const [keyword] = keywords;\n const constraining = Object.keys(schema).filter(\n key =>\n key !== keyword &&\n key !== 'discriminator' &&\n !key.startsWith('x-') &&\n !ANNOTATION_KEYWORDS.has(key),\n );\n if (constraining.length > 0) return undefined;\n const members: (Schema | Reference)[] = schema[keyword]!;\n const isNullMember = (member: Schema) =>\n keyword !== 'allOf' &&\n [member.type].flat().every(type => type === 'null') &&\n member.type !== undefined &&\n Object.keys(member).every(\n key => key === 'type' || ANNOTATION_KEYWORDS.has(key),\n );\n if (!members.every(member => isReference(member) || isNullMember(member))) {\n return undefined;\n }\n const types = members.map(member =>\n isReference(member) ? this.memberType(schema, keyword, member) : 'null',\n );\n return [...new Set(types)].join(keyword === 'allOf' ? ' & ' : ' | ');\n }\n\n /**\n * Resolves one member of a composition. A member of a `oneOf` or `anyOf`\n * that carries a `discriminator` is intersected with the literal the\n * discriminator property holds for it, so checking that property narrows\n * the union: `(Cat & { petType: 'cat' }) | (Dog & { petType: 'dog' })`.\n */\n private memberType(\n schema: Schema,\n keyword: 'allOf' | 'oneOf' | 'anyOf',\n member: Schema | Reference,\n ): string {\n const type = this.type(member);\n const discriminator = schema.discriminator;\n if (\n keyword === 'allOf' ||\n !discriminator?.propertyName ||\n !isReference(member)\n ) {\n return type;\n }\n const componentKey = extractComponentKey(member);\n const mapped = Object.entries(discriminator.mapping ?? {})\n .filter(([, target]) => target === member.$ref || target === componentKey)\n .map(([value]) => value);\n const literal = (mapped.length > 0 ? mapped : [componentKey])\n .map(value => quoteStringLiteral(value))\n .join(' | ');\n return `(${type} & { ${resolvePropertyName(discriminator.propertyName)}: ${literal} })`;\n }\n}\n\nfunction resolveWith(\n scope: TypeScope,\n resolve: (resolution: Resolution) => string,\n): ResolvedType {\n const resolution = new Resolution(scope);\n const text = resolve(resolution);\n return { text, imports: resolution.imports() };\n}\n\n/**\n * The type a schema generates.\n *\n * @param schema - The schema, or a reference to a component\n * @param scope - Where the type is written\n * @returns The type expression and the imports it needs\n */\nexport function resolveType(\n schema: Schema | Reference,\n scope: TypeScope,\n): ResolvedType {\n return resolveWith(scope, resolution => resolution.type(schema));\n}\n\n/**\n * The index signature an object schema's additional properties generate, as\n * `[key: string]: T`, or `''` when it admits none beyond the ones it names.\n */\nexport function resolveAdditionalProperties(\n schema: Schema,\n scope: TypeScope,\n): ResolvedType {\n return resolveWith(scope, resolution =>\n resolution.additionalProperties(schema),\n );\n}\n\n/** The type of an object schema's additional properties; `any` when open. */\nexport function resolveAdditionalPropertyType(\n schema: Schema,\n scope: TypeScope,\n): ResolvedType {\n return resolveWith(scope, resolution =>\n resolution.additionalPropertyType(schema),\n );\n}\n\n/**\n * The type of a property an object schema requires without declaring it: its\n * additional-property type, `never` when it admits none, else any JSON value.\n */\nexport function resolveRequiredAdditionalPropertyType(\n schema: Schema,\n scope: TypeScope,\n): ResolvedType {\n return resolveWith(scope, resolution =>\n resolution.requiredAdditionalPropertyType(schema),\n );\n}\n\n/** The value type of a map schema; `any` when its values are open. */\nexport function resolveMapValueType(\n schema: MapSchema,\n scope: TypeScope,\n): ResolvedType {\n return resolveWith(scope, resolution => resolution.mapValueType(schema));\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ClassDeclarationStructure } from 'ts-morph';\nimport { Scope, StructureKind } from 'ts-morph';\nimport { addImport } from '../emit/imports';\nimport type { ModuleBuilder } from '../emit/moduleBuilder';\n\nexport const FETCHER_MODULE_SPECIFIER = '@ahoo-wang/fetcher';\nexport const FETCHER_NAMED_IMPORTS = ['ContentTypeValues', 'ResultExtractors'];\n\n/**\n * The module specifier for the fetcher-decorator package.\n */\nexport const DECORATOR_MODULE_SPECIFIER = '@ahoo-wang/fetcher-decorator';\n\n/**\n * Named imports from the fetcher-decorator package.\n */\nexport const DECORATOR_NAMED_IMPORTS = [\n 'ApiMetadata',\n 'ApiMetadataCapable',\n 'ParameterRequest',\n 'api',\n 'get',\n 'post',\n 'put',\n 'patch',\n 'del',\n 'request',\n 'attribute',\n 'path',\n 'query',\n 'header',\n 'body',\n 'autoGeneratedError',\n];\n\nexport interface MethodReturnType {\n type: string;\n metadata?: string;\n}\n\nexport const DEFAULT_RETURN_TYPE: MethodReturnType = {\n type: 'Promise<Response>',\n metadata: `{resultExtractor: ResultExtractors.Response }`,\n};\n\nexport const STRING_RETURN_TYPE: MethodReturnType = {\n type: 'Promise<string>',\n metadata: `{resultExtractor: ResultExtractors.Text }`,\n};\n\n/**\n * Metadata configuration for stream result extraction.\n */\nexport const STREAM_RESULT_EXTRACTOR_METADATA = `{\n headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },\n resultExtractor: JsonEventStreamResultExtractor,\n}`;\n\nexport function addImportFetcher(module: ModuleBuilder) {\n addImport(module, FETCHER_MODULE_SPECIFIER, FETCHER_NAMED_IMPORTS);\n}\n/**\n * Adds the necessary imports for decorator functionality to a module.\n *\n * @param module - The module to add imports to\n */\nexport function addImportDecorator(module: ModuleBuilder) {\n addImport(module, DECORATOR_MODULE_SPECIFIER, DECORATOR_NAMED_IMPORTS);\n}\n\n/**\n * Adds a class declaration with the @api decorator to a module.\n *\n * @param className - The name of the class to create\n * @param module - The module to add the class to\n * @param apiArgs - Optional arguments for the @api decorator\n * @param typeParameters - Optional type parameters for the class\n * @param extendsClass - Optional class to extend\n * @returns The class declaration, open to members until the module is built\n *\n * @example\n * ```typescript\n * const classDecl = createDecoratorClass('UserApi', module, ['baseUrl']);\n * ```\n */\nexport function createDecoratorClass(\n className: string,\n module: ModuleBuilder,\n apiArgs: string[] = [],\n typeParameters: string[] = [],\n extendsClass?: string,\n): ClassDeclarationStructure {\n return module.add<ClassDeclarationStructure>({\n kind: StructureKind.Class,\n name: className,\n isExported: true,\n typeParameters: typeParameters,\n extends: extendsClass,\n decorators: [\n {\n name: 'api',\n arguments: apiArgs,\n },\n ],\n });\n}\n\n/**\n * Adds the ApiMetadataCapable interface implementation and constructor to a class declaration:\n *\n * ```typescript\n * constructor(public readonly apiMetadata?: ApiMetadata) {}\n * ```\n *\n * @param classDeclaration - The class declaration to modify\n */\nexport function addApiMetadataCtor(\n classDeclaration: ClassDeclarationStructure,\n) {\n classDeclaration.implements = [\n ...[classDeclaration.implements ?? []].flat(),\n 'ApiMetadataCapable',\n ];\n classDeclaration.ctors ??= [];\n classDeclaration.ctors.push({\n parameters: [\n {\n name: 'apiMetadata',\n type: 'ApiMetadata',\n hasQuestionToken: true,\n scope: Scope.Public,\n isReadonly: true,\n },\n ],\n });\n}\n\n/**\n * The decorator of an HTTP method: its name, but `del` for `delete`, a\n * reserved word.\n *\n * @example\n * ```typescript\n * methodToDecorator('get'); // 'get'\n * methodToDecorator('delete'); // 'del'\n * ```\n */\nexport function methodToDecorator(method: string): string {\n return method === 'delete' ? 'del' : method;\n}\n\nexport const EVENTSTREAM_MODULE_SPECIFIER = '@ahoo-wang/fetcher-eventstream';\n\nexport function addImportEventStream(module: ModuleBuilder) {\n addImport(module, EVENTSTREAM_MODULE_SPECIFIER, [\n 'JsonEventStreamResultExtractor',\n 'JsonServerSentEventStream',\n ]);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Reference, Schema } from '@ahoo-wang/fetcher-openapi';\nimport type {\n MethodDeclarationStructure,\n OptionalKind,\n ParameterDeclarationStructure,\n} from 'ts-morph';\nimport type {\n ApiClientModel,\n ApiMethodModel,\n BodyModel,\n ReturnModel,\n} from '../analysis/model';\nimport { addImport, modelModuleSpecifier } from '../emit/imports';\nimport { addJSDoc } from '../emit/jsdoc';\nimport type { ModuleBuilder } from '../emit/moduleBuilder';\nimport { quoteStringLiteral } from '../naming/naming';\nimport type { TypeScope } from '../types/typeResolver';\nimport { resolveType } from '../types/typeResolver';\nimport type { MethodReturnType } from './decorators';\nimport {\n addApiMetadataCtor,\n addImportDecorator,\n addImportEventStream,\n addImportFetcher,\n createDecoratorClass,\n DEFAULT_RETURN_TYPE,\n FETCHER_MODULE_SPECIFIER,\n methodToDecorator,\n STREAM_RESULT_EXTRACTOR_METADATA,\n STRING_RETURN_TYPE,\n} from './decorators';\nimport type { EmitTarget } from './target';\n\n/** Resolves schemas to types in one client module, importing the models they use. */\ninterface ClientTypes {\n readonly module: ModuleBuilder;\n resolveType(schema: Schema | Reference): string;\n}\n\n/**\n * Writes the API client of a tag: a decorated class with a method per\n * operation.\n *\n * @param client - The client\n * @param target - Where it is written\n */\nexport function emitApiClient(\n client: ApiClientModel,\n target: EmitTarget,\n): void {\n const module = target.modules.module(client.file);\n addImportFetcher(module);\n addImportDecorator(module);\n addImportEventStream(module);\n const apiClientClass = createDecoratorClass(client.className, module);\n addJSDoc(apiClientClass, [client.description]);\n addApiMetadataCtor(apiClientClass);\n const types = clientTypes(client.className, module, target);\n for (const method of client.methods) {\n (apiClientClass.methods ??= []).push(apiMethod(method, types));\n }\n}\n\n/**\n * The types of a client module. The client imports every model it uses,\n * and no import takes the class's own name.\n */\nfunction clientTypes(\n className: string,\n module: ModuleBuilder,\n target: EmitTarget,\n): ClientTypes {\n const scope: TypeScope = {\n context: target.types,\n owner: { name: className },\n specifierOf: model => modelModuleSpecifier(module, target.outputDir, model),\n imports: module.imports,\n };\n return {\n module,\n resolveType(schema) {\n const resolved = resolveType(schema, scope);\n module.imports.apply(resolved.imports);\n return resolved.text;\n },\n };\n}\n\n/**\n * The method of an operation. Its types resolve in document order - the\n * parameters, the body, the response - so a later reference sees the\n * aliases an earlier one took; its parameters are then ordered required\n * first, so a caller never passes `undefined` to reach a required one:\n *\n * ```typescript\n * search(id: string, q: string, body: Filter, page?: number,\n * httpRequest?: ParameterRequest, attributes?: Record<string, unknown>)\n * ```\n *\n * `httpRequest` carries anything else a request may set: headers, a\n * timeout, a signal.\n */\nfunction apiMethod(\n method: ApiMethodModel,\n types: ClientTypes,\n): OptionalKind<MethodDeclarationStructure> {\n const required: OptionalKind<ParameterDeclarationStructure>[] = [];\n const optional: OptionalKind<ParameterDeclarationStructure>[] = [];\n for (const parameter of method.parameters) {\n (parameter.required ? required : optional).push({\n name: parameter.name,\n type: parameter.schema ? types.resolveType(parameter.schema) : 'string',\n hasQuestionToken: !parameter.required,\n decorators: [\n {\n name: parameter.location,\n arguments: [quoteStringLiteral(parameter.parameterName)],\n },\n ],\n });\n }\n if (method.body) {\n (method.body.required ? required : optional).push({\n name: method.body.name,\n type: bodyType(method.body, types),\n hasQuestionToken: !method.body.required,\n decorators: [{ name: 'body', arguments: [] }],\n });\n }\n const parameters = [\n ...required,\n ...optional,\n {\n name: 'httpRequest',\n hasQuestionToken: true,\n type: 'ParameterRequest',\n decorators: [{ name: 'request', arguments: [] }],\n },\n {\n name: 'attributes',\n hasQuestionToken: true,\n type: 'Record<string, unknown>',\n decorators: [{ name: 'attribute', arguments: [] }],\n },\n ];\n const returnType = returnTypeOf(method.returns, types);\n const path = quoteStringLiteral(method.path);\n const declaration: OptionalKind<MethodDeclarationStructure> = {\n name: method.name,\n decorators: [\n {\n name: methodToDecorator(method.httpMethod),\n arguments: returnType.metadata ? [path, returnType.metadata] : [path],\n },\n ],\n parameters,\n returnType: returnType.type,\n statements: [\n `throw autoGeneratedError(${parameters.map(parameter => parameter.name).join(',')});`,\n ],\n };\n addJSDoc(declaration, [...method.docs]);\n return declaration;\n}\n\n/**\n * The type of a body. A JSON body leaves optional the properties its schema\n * does not require, as a command body does (`PartialBy<Item, 'id'>`), unless\n * its type is a union, an intersection or `any`.\n */\nfunction bodyType(body: BodyModel, types: ClientTypes): string {\n const { content } = body;\n switch (content.kind) {\n case 'json': {\n const type = types.resolveType(content.schema);\n const optional = content.optionalFields;\n if (optional.length === 0 || /[|&]/.test(type) || type === 'any') {\n return type;\n }\n addImport(types.module, FETCHER_MODULE_SPECIFIER, ['PartialBy']);\n return `PartialBy<${type}, ${optional.map(quoteStringLiteral).join(' | ')}>`;\n }\n case 'formData':\n return 'FormData';\n case 'urlEncoded':\n return 'URLSearchParams';\n case 'text':\n return 'string';\n case 'binary':\n return 'BodyInit';\n }\n}\n\n/** The return type of a method, and the decorator metadata it needs. */\nfunction returnTypeOf(\n returns: ReturnModel,\n types: ClientTypes,\n): MethodReturnType {\n switch (returns.kind) {\n case 'json': {\n const type = types.resolveType(returns.schema);\n return returns.wildcard && type === 'string'\n ? STRING_RETURN_TYPE\n : { type: `Promise<${type}>` };\n }\n case 'eventStream': {\n if (!returns.items) {\n return {\n type: `Promise<JsonServerSentEventStream<any>>`,\n metadata: STREAM_RESULT_EXTRACTOR_METADATA,\n };\n }\n const typeName = types.resolveType(returns.items);\n const dataType = returns.serverSentEvent\n ? `${typeName}['data']`\n : typeName;\n return {\n type: `Promise<JsonServerSentEventStream<${dataType}>>`,\n metadata: STREAM_RESULT_EXTRACTOR_METADATA,\n };\n }\n case 'text':\n return STRING_RETURN_TYPE;\n case 'response':\n return DEFAULT_RETURN_TYPE;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Components, Reference, Schema } from '@ahoo-wang/fetcher-openapi';\nimport type {\n EnumDeclarationStructure,\n InterfaceDeclarationStructure,\n JSDocableNodeStructure,\n OptionalKind,\n PropertySignatureStructure,\n TypeAliasDeclarationStructure,\n} from 'ts-morph';\nimport { StructureKind, VariableDeclarationKind } from 'ts-morph';\nimport type { ModelDeclaration } from '../analysis/model';\nimport {\n resolveModelInfo,\n resolveReferenceModelInfo,\n} from '../analysis/modelInfo';\nimport { modelModuleSpecifier } from '../emit/imports';\nimport { addMainSchemaJSDoc, addSchemaJSDoc } from '../emit/jsdoc';\nimport type { ModuleBuilder } from '../emit/moduleBuilder';\nimport { indexSignatureMember } from '../emit/moduleBuilder';\nimport { enumMemberKey, resolvePropertyName } from '../naming/naming';\nimport { isReference } from '../openapi/references';\nimport type {\n ArraySchema,\n CompositionSchema,\n EnumSchema,\n MapSchema,\n ObjectSchema,\n} from '../openapi/schemas';\nimport {\n getEnumText,\n getMapKeySchema,\n isArray,\n isComposition,\n isEnum,\n isMap,\n isObject,\n isReadOnly,\n toArrayType,\n} from '../openapi/schemas';\nimport type {\n ResolvedType,\n TypeContext,\n TypeScope,\n} from '../types/typeResolver';\nimport {\n createTypeContext,\n requiresAdditionalPropertiesIntersection,\n resolveAdditionalProperties,\n resolveAdditionalPropertyType,\n resolveLiteral,\n resolveMapValueType,\n resolveRequiredAdditionalPropertyType,\n resolveType,\n} from '../types/typeResolver';\nimport type { EmitTarget } from './target';\n\n/**\n * The type context of a document: its components, named the way the\n * generator names models. Build it once per generation and share it, so the\n * model names of each path are read once.\n *\n * @param components - The document's components\n */\nexport function documentTypeContext(components?: Components): TypeContext {\n return createTypeContext(components, {\n ofKey: key => resolveModelInfo(key),\n ofReference: resolveReferenceModelInfo,\n });\n}\n\n/**\n * Writes a model into the `types.ts` of its package: an interface, an enum or\n * a type alias, with its doc comment, and imports the models it uses.\n *\n * @param declaration - The model\n * @param target - Where it is written\n */\nexport function emitModel(\n declaration: ModelDeclaration,\n target: EmitTarget,\n): void {\n const module = target.modules.module(declaration.file);\n new ModelEmitter(declaration, module, target).write();\n}\n\n/**\n * Names the members of an enum. Each value takes its UPPER_SNAKE_CASE form;\n * when another value already took that form - `in-progress`, `IN_PROGRESS`\n * and `inProgress` all give `IN_PROGRESS` - it takes its own value as a\n * quoted member name, or else a numbered form.\n *\n * @param values - The distinct values, in document order\n * @returns The member name of each value, quoted where it has to be\n */\nexport function uniqueEnumMemberNames(\n values: readonly string[],\n): Map<string, string> {\n const used = new Set<string>();\n const names = new Map<string, string>();\n for (const value of values) {\n const preferred = enumMemberKey(value);\n const candidates = [preferred];\n // A numeric name cannot name an enum member, even quoted.\n if (!/^\\d/.test(value)) candidates.push(value);\n let key = candidates.find(candidate => !used.has(candidate));\n for (let index = 2; key === undefined; index++) {\n if (!used.has(`${preferred}_${index}`)) key = `${preferred}_${index}`;\n }\n used.add(key);\n names.set(value, resolvePropertyName(key));\n }\n return names;\n}\n\n/** The model a {@link ModelEmitter} writes. */\nexport type ModelSource = Pick<ModelDeclaration, 'key' | 'info' | 'schema'>;\n\n/**\n * Writes one model into a module: the declaration its schema calls for,\n * with the model's doc comment.\n */\nexport class ModelEmitter {\n private readonly modelInfo: ModelSource['info'];\n private readonly components?: Components;\n\n /**\n * @param model - The model\n * @param module - The module the model is written into, which also\n * receives its imports\n * @param target - The output directory, the document's type context and\n * how much of the schema the doc comment carries\n */\n constructor(\n private readonly model: ModelSource,\n readonly module: ModuleBuilder,\n private readonly target: Pick<\n EmitTarget,\n 'outputDir' | 'types' | 'schemaDocs'\n >,\n ) {\n this.modelInfo = model.info;\n this.components = target.types.components;\n this.scope = {\n context: target.types,\n owner: model.info,\n specifierOf: info => modelModuleSpecifier(module, target.outputDir, info),\n imports: module.imports,\n };\n }\n\n /** Writes the model's declaration and its doc comment. */\n write(): void {\n const node = this.process();\n if (node) {\n addMainSchemaJSDoc(\n node,\n this.model.schema,\n this.model.key,\n this.target.schemaDocs === 'full',\n );\n }\n }\n\n private process(): JSDocableNodeStructure | undefined {\n const { schema } = this.model;\n if (isReference(schema)) {\n return this.processTypeAlias(schema);\n }\n if (isEnum(schema)) {\n return this.processEnum(schema);\n }\n if (schema.const !== undefined) {\n return this.processTypeAlias(schema);\n }\n if (\n (schema.nullable && schema.type) ||\n (isComposition(schema) &&\n (schema.type || schema.properties || schema.required))\n ) {\n return this.processTypeAlias(schema);\n }\n if (isObject(schema)) {\n return this.processInterface(schema);\n }\n if (\n isMap(schema) &&\n typeof schema.additionalProperties === 'object' &&\n !getMapKeySchema(schema) &&\n !schema.required?.length\n ) {\n return this.processIndexSignature(schema);\n }\n if (isArray(schema)) {\n return this.processArray(schema);\n }\n if (isComposition(schema)) {\n return this.processComposition(schema);\n }\n return this.processTypeAlias(schema);\n }\n\n /** Where the types of this model are written. */\n private readonly scope: TypeScope;\n\n /** Applies the imports a resolved type needs to the module. */\n private emit(resolved: ResolvedType): string {\n this.module.imports.apply(resolved.imports);\n return resolved.text;\n }\n\n /** The type a schema generates in this model's module, its imports added. */\n resolveType(schema: Schema | Reference): string {\n return this.emit(resolveType(schema, this.scope));\n }\n\n private processEnum(schema: EnumSchema): JSDocableNodeStructure | undefined {\n const enumText = getEnumText(schema);\n if (enumText) {\n const textNames = uniqueEnumMemberNames(Object.keys(enumText));\n this.module.add<EnumDeclarationStructure>({\n kind: StructureKind.Enum,\n name: this.modelInfo.name + 'EnumText',\n isExported: true,\n members: [...textNames].map(([name, memberName]) => {\n return {\n name: memberName,\n initializer: resolveLiteral(enumText[name]),\n };\n }),\n });\n }\n const stringValues = [\n ...new Set(\n schema.enum.filter(\n (value): value is string => typeof value === 'string',\n ),\n ),\n ];\n const memberNames = uniqueEnumMemberNames(stringValues);\n if (\n isComposition(schema) ||\n schema.const !== undefined ||\n (schema.type !== undefined && schema.type !== 'string') ||\n schema.enum.some(value => typeof value !== 'string')\n ) {\n if (stringValues.length) {\n this.module.add({\n kind: StructureKind.VariableStatement,\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: this.modelInfo.name,\n initializer: writer => {\n writer.inlineBlock(() => {\n for (const value of stringValues) {\n writer\n .write(`${memberNames.get(value)}: `)\n .quote(value)\n .write(',')\n .newLine();\n }\n });\n writer.write(' as const');\n },\n },\n ],\n });\n }\n return this.processTypeAlias(schema);\n }\n return this.module.add<EnumDeclarationStructure>({\n kind: StructureKind.Enum,\n name: this.modelInfo.name,\n isExported: true,\n members: stringValues.map(value => ({\n name: memberNames.get(value)!,\n initializer: resolveLiteral(value),\n })),\n });\n }\n\n /**\n * Adds a declared property. Property names are distinct, and\n * `resolvePropertyName` keeps them distinct: a name is kept or quoted.\n */\n private addPropertyToInterface(\n interfaceDeclaration: InterfaceDeclarationStructure,\n propName: string,\n propSchema: Schema | Reference,\n ): void {\n const propertySignature: OptionalKind<PropertySignatureStructure> = {\n name: resolvePropertyName(propName),\n type: this.resolveType(propSchema),\n isReadonly: isReadOnly(propSchema),\n };\n (interfaceDeclaration.properties ??= []).push(propertySignature);\n addSchemaJSDoc(propertySignature, propSchema);\n }\n\n private processInterface(\n schema: ObjectSchema,\n ): JSDocableNodeStructure | undefined {\n if (requiresAdditionalPropertiesIntersection(schema, this.components)) {\n return this.processTypeAlias(schema);\n }\n const properties: OptionalKind<PropertySignatureStructure>[] = [];\n const interfaceDeclaration = this.module.add<InterfaceDeclarationStructure>(\n {\n kind: StructureKind.Interface,\n name: this.modelInfo.name,\n isExported: true,\n properties,\n },\n );\n\n const schemaProperties = schema.properties || {};\n\n Object.entries(schemaProperties).forEach(([propName, propSchema]) => {\n this.addPropertyToInterface(interfaceDeclaration, propName, propSchema);\n });\n\n for (const name of schema.required ?? []) {\n if (!Object.hasOwn(schemaProperties, name)) {\n properties.push({\n name: resolvePropertyName(name),\n type: this.emit(\n resolveRequiredAdditionalPropertyType(schema, this.scope),\n ),\n });\n }\n }\n\n if (this.emit(resolveAdditionalProperties(schema, this.scope))) {\n properties.push(\n indexSignatureMember(\n this.emit(resolveAdditionalPropertyType(schema, this.scope)),\n ['Additional properties'],\n ),\n );\n }\n return interfaceDeclaration;\n }\n\n private processArray(\n schema: ArraySchema,\n ): JSDocableNodeStructure | undefined {\n const itemType = this.resolveType(schema.items);\n return this.module.add<TypeAliasDeclarationStructure>({\n kind: StructureKind.TypeAlias,\n name: this.modelInfo.name,\n type: toArrayType(itemType),\n isExported: true,\n });\n }\n\n /**\n * A string-keyed map is an interface with an index signature rather than an\n * alias of `Record`: an alias may not reference itself through `Record`\n * (TS2456), and a map of its own type - a tree of dictionaries - does.\n */\n private processIndexSignature(\n schema: MapSchema,\n ): JSDocableNodeStructure | undefined {\n return this.module.add<InterfaceDeclarationStructure>({\n kind: StructureKind.Interface,\n name: this.modelInfo.name,\n isExported: true,\n properties: [\n indexSignatureMember(\n this.emit(resolveMapValueType(schema, this.scope)),\n ),\n ],\n });\n }\n\n private processComposition(\n schema: CompositionSchema,\n ): JSDocableNodeStructure | undefined {\n return this.module.add<TypeAliasDeclarationStructure>({\n kind: StructureKind.TypeAlias,\n name: this.modelInfo.name,\n type: this.resolveType(schema),\n isExported: true,\n });\n }\n\n private processTypeAlias(\n schema: Schema | Reference,\n ): JSDocableNodeStructure | undefined {\n return this.module.add<TypeAliasDeclarationStructure>({\n kind: StructureKind.TypeAlias,\n name: this.modelInfo.name,\n type: this.resolveType(schema),\n isExported: true,\n });\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { GenerationModel } from '../analysis/model';\nimport { emitApiClient } from './apiClients';\nimport { emitModel } from './models';\nimport type { EmitTarget } from './target';\n\n/**\n * Describes every file of a generation to its module: the models, then the\n * API clients. Nothing reaches a source file until the modules are built.\n *\n * The order is the one the files have always been written in, so the\n * imports of a module, and the aliases a name clash gives them, come out\n * the same.\n *\n * @param model - What the document generates\n * @param target - Where it is written\n */\nexport function emitGeneration(\n model: GenerationModel,\n target: EmitTarget,\n): void {\n model.models.forEach(declaration => emitModel(declaration, target));\n model.apiClients.forEach(client => emitApiClient(client, target));\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Directory, SourceFile } from 'ts-morph';\nimport { Node } from 'ts-morph';\nimport { compareNames } from '../naming/order';\n\n/** A name a module exports, mapped to whether it is only a type. */\ntype ExportedNames = Map<string, boolean>;\n\n/** A module an index re-exports. */\ninterface IndexChild {\n readonly specifier: string;\n readonly exports: ExportedNames;\n}\n\n/**\n * Writes an `index.ts` into the output directory and each directory under\n * it, re-exporting its files and the indexes of its subdirectories.\n *\n * @param outputDir - The output directory, holding the files written\n * @param claim - Returns the index file of a directory, emptied and claimed\n * for the generation\n * @returns A warning for every name an index leaves out because two of its\n * children export it\n */\nexport function emitIndexFiles(\n outputDir: Directory,\n claim: (directoryPath: string) => SourceFile,\n): string[] {\n const warnings: string[] = [];\n indexDirectory(outputDir, claim, warnings);\n return warnings;\n}\n\n/**\n * Writes the index files of a directory and its subdirectories.\n *\n * @returns The names the directory's index exports, each mapped to whether\n * it is a type only; undefined when the directory has no index.\n */\nfunction indexDirectory(\n dir: Directory,\n claim: (directoryPath: string) => SourceFile,\n warnings: string[],\n): ExportedNames | undefined {\n const children: IndexChild[] = [];\n for (const file of dir.getSourceFiles()) {\n const baseName = file.getBaseName();\n if (!baseName.endsWith('.ts') || baseName === 'index.ts') continue;\n children.push({\n specifier: `./${file.getBaseNameWithoutExtension()}.js`,\n exports: exportedNames(file),\n });\n }\n for (const subDir of dir.getDirectories()) {\n const exports = indexDirectory(subDir, claim, warnings);\n if (exports) {\n children.push({\n specifier: `./${subDir.getBaseName()}/index.js`,\n exports,\n });\n }\n }\n const dirPath = dir.getPath();\n if (children.length === 0) {\n return dir.getProject().getSourceFile(`${dirPath}/index.ts`)\n ? new Map()\n : undefined;\n }\n return writeIndex(dirPath, children, claim, warnings);\n}\n\n/**\n * Writes one index file.\n *\n * `export *` from two modules that export the same name is an error\n * (TS2308); it happens when two packages hold a model of the same name. A\n * child exporting such a name is re-exported by name instead, leaving the\n * ambiguous names out: they stay importable from their own modules.\n *\n * @returns The names the index exports\n */\nfunction writeIndex(\n dirPath: string,\n children: IndexChild[],\n claim: (directoryPath: string) => SourceFile,\n warnings: string[],\n): ExportedNames {\n const owners = new Map<string, string[]>();\n for (const child of children) {\n for (const name of child.exports.keys()) {\n owners.set(name, [...(owners.get(name) ?? []), child.specifier]);\n }\n }\n const ambiguous = [...owners]\n .filter(([, specifiers]) => specifiers.length > 1)\n .map(([name]) => name)\n .sort();\n for (const name of ambiguous) {\n warnings.push(\n `${name} is exported by both ${owners.get(name)!.join(' and ')} in ${dirPath}; its index leaves it out, so import it from its own module.`,\n );\n }\n const indexFile = claim(dirPath);\n indexFile.removeText();\n const exported: ExportedNames = new Map();\n for (const child of children) {\n const names = [...child.exports]\n .filter(([name]) => !ambiguous.includes(name))\n .sort(([left], [right]) => compareNames(left, right));\n names.forEach(([name, typeOnly]) => exported.set(name, typeOnly));\n if (names.length === child.exports.size) {\n indexFile.addExportDeclaration({ moduleSpecifier: child.specifier });\n } else if (names.length > 0) {\n indexFile.addExportDeclaration({\n moduleSpecifier: child.specifier,\n namedExports: names.map(([name, isTypeOnly]) => ({\n name,\n isTypeOnly,\n })),\n });\n }\n }\n if (indexFile.getStatements().length === 0) {\n // Every name was ambiguous; the index stays a module its parent re-exports.\n indexFile.addStatements('export {};');\n }\n return exported;\n}\n\n/**\n * The names a generated file exports. A name is type-only when every one of\n * its declarations is an interface or a type alias; an enum or a class is a\n * value as well.\n */\nfunction exportedNames(file: SourceFile): ExportedNames {\n const names: ExportedNames = new Map();\n for (const [name, declarations] of file.getExportedDeclarations()) {\n names.set(\n name,\n declarations.every(\n declaration =>\n Node.isInterfaceDeclaration(declaration) ||\n Node.isTypeAliasDeclaration(declaration),\n ),\n );\n }\n return names;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ImportDeclaration,\n ImportSpecifier,\n SourceFile,\n ts,\n} from 'ts-morph';\nimport { Node, SyntaxKind } from 'ts-morph';\n\n/**\n * Whether an identifier sits in a position TypeScript erases: a type\n * annotation, a type argument, an `implements` clause, an interface's\n * `extends` clause or a `typeof` type query. A class's `extends` clause, a\n * decorator, an initializer or an `export { … }` is a value position.\n *\n * This is the classification `@typescript-eslint/consistent-type-imports`\n * applies, so the generated imports satisfy that rule.\n */\nfunction isTypePosition(identifier: Node): boolean {\n let child: Node = identifier;\n for (\n let parent = child.getParent();\n parent;\n child = parent, parent = parent.getParent()\n ) {\n // `Namespace.Type` and `namespace.value`: the reference is the leftmost name.\n if (Node.isQualifiedName(parent)) {\n if (parent.getLeft() !== child) return false;\n continue;\n }\n if (Node.isPropertyAccessExpression(parent)) {\n if (parent.getExpression() !== child) return false;\n continue;\n }\n if (Node.isExpressionWithTypeArguments(parent)) {\n const clause = parent.getParent();\n const owner = clause?.getParent();\n return !(\n Node.isHeritageClause(clause) &&\n clause.getToken() === SyntaxKind.ExtendsKeyword &&\n (Node.isClassDeclaration(owner) || Node.isClassExpression(owner))\n );\n }\n return Node.isTypeNode(parent);\n }\n return false;\n}\n\n/**\n * Plans the type-only form of every named import in a source file. Planning\n * reads the type checker; applying only edits text, so every file can be\n * planned against one program before any file changes.\n */\nfunction planTypeOnlyImports(sourceFile: SourceFile): (() => void)[] {\n const declarations = sourceFile\n .getImportDeclarations()\n .filter(\n declaration =>\n !declaration.getDefaultImport() &&\n !declaration.getNamespaceImport() &&\n declaration.getNamedImports().length > 0,\n );\n if (declarations.length === 0) return [];\n\n const localNames = new Set(\n declarations.flatMap(declaration =>\n declaration\n .getNamedImports()\n .map(specifier =>\n (specifier.getAliasNode() ?? specifier.getNameNode()).getText(),\n ),\n ),\n );\n const valueSymbols = new Set<ts.Symbol>();\n sourceFile.forEachDescendant((node, traversal) => {\n if (Node.isImportDeclaration(node)) {\n traversal.skip();\n return;\n }\n if (\n Node.isIdentifier(node) &&\n localNames.has(node.getText()) &&\n !isTypePosition(node)\n ) {\n // The checker resolves shadowing: a parameter named like an import is\n // a different symbol from the import's alias.\n const symbol = node.getSymbol();\n if (symbol) valueSymbols.add(symbol.compilerSymbol);\n }\n });\n\n return declarations.map(declaration =>\n applyTypeOnly(declaration, specifier => {\n const symbol = specifier.getSymbol();\n // Without a symbol the use cannot be proven type-only; keep it a value.\n return !!symbol && !valueSymbols.has(symbol.compilerSymbol);\n }),\n );\n}\n\nfunction applyTypeOnly(\n declaration: ImportDeclaration,\n isTypeOnly: (specifier: ImportSpecifier) => boolean,\n): () => void {\n const specifiers = declaration.getNamedImports();\n const typeOnly = specifiers.map(isTypeOnly);\n const allTypeOnly = typeOnly.every(Boolean);\n return () => {\n specifiers.forEach((specifier, index) => {\n const inline = !allTypeOnly && typeOnly[index];\n if (specifier.isTypeOnly() !== inline) specifier.setIsTypeOnly(inline);\n });\n if (declaration.isTypeOnly() !== allTypeOnly) {\n declaration.setIsTypeOnly(allTypeOnly);\n }\n };\n}\n\n/**\n * Rewrites named imports by how each file uses them, as\n * `@typescript-eslint/consistent-type-imports` expects:\n *\n * - every specifier used only as a type: `import type { A, B } from '…'`;\n * - values and types mixed: `import { type A, b } from '…'`;\n * - values only: `import { a, b } from '…'`.\n *\n * Usage alone decides, so an existing `type` modifier that a value use\n * contradicts is removed. Default and namespace imports are left as they are.\n */\nexport function applyTypeOnlyImports(sourceFiles: readonly SourceFile[]): void {\n const plans = sourceFiles.flatMap(planTypeOnlyImports);\n for (const apply of plans) apply();\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { SourceFile } from 'ts-morph';\nimport { ts } from 'ts-morph';\n\n/**\n * Diagnostics that mean the generated code itself is broken, whatever the\n * project around it resolves:\n *\n * - 2304, 2552, 2503: a name, possibly misspelled, or a namespace that is\n * neither declared nor imported;\n * - 2300, 2451, 2393: a name declared twice in one scope;\n * - 2308: an index re-exporting the same name from two modules;\n * - 2456: a type alias that references itself.\n *\n * Diagnostics that depend on the modules the output directory resolves -\n * a missing package (2307), a missing export (2305) - are the project's to\n * report, and are left out.\n */\nconst INTEGRITY_DIAGNOSTICS = new Set([\n 2300, 2304, 2308, 2393, 2451, 2456, 2503, 2552,\n]);\n\n/**\n * Fails when generated code references a name it does not declare or import,\n * or declares one twice.\n *\n * This is a safety net under the emitters, which write every import\n * explicitly: the output must be the same whether or not its directory\n * resolves `@ahoo-wang/*`, and it must never be saved in a state that cannot\n * compile.\n *\n * @param sourceFiles - The generated files\n * @throws Error listing each diagnostic with its file and line\n */\nexport function verifyGeneratedCode(sourceFiles: readonly SourceFile[]): void {\n const problems: string[] = [];\n for (const sourceFile of sourceFiles) {\n for (const diagnostic of sourceFile.getPreEmitDiagnostics()) {\n if (!INTEGRITY_DIAGNOSTICS.has(diagnostic.getCode())) continue;\n if (diagnostic.getSourceFile() !== sourceFile) continue;\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.compilerObject.messageText,\n ' ',\n );\n problems.push(\n `${sourceFile.getFilePath()}:${diagnostic.getLineNumber() ?? 0} TS${diagnostic.getCode()} ${message}`,\n );\n }\n }\n if (problems.length > 0) {\n throw new Error(\n `The generated code does not compile; nothing was written. This is a wow-generator bug:\\n${problems.join('\\n')}`,\n );\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FormatCodeSettings, SourceFile } from 'ts-morph';\nimport type { Logger } from '../api/logger';\nimport { applyTypeOnlyImports } from './typeOnlyImports';\nimport { verifyGeneratedCode } from './verification';\n\n/**\n * The first line of every generated file. \"Code generated … DO NOT EDIT.\" is\n * the marker tools recognise as generated code.\n */\nconst GENERATED_FILE_HEADER =\n '// Code generated by wow-generator. DO NOT EDIT.\\n\\n';\n\n/**\n * Formatting of the generated code: two-space indentation, single quotes and\n * semicolons, as Prettier's defaults close to what the rest of a TypeScript\n * project uses.\n */\nconst FORMAT_SETTINGS: FormatCodeSettings = {\n indentSize: 2,\n tabSize: 2,\n convertTabsToSpaces: true,\n semicolons: 'insert' as FormatCodeSettings['semicolons'],\n insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,\n};\n\n/**\n * Finishes the files a generation wrote: formats them, organizes and types\n * their imports, checks that the result declares or imports every name it\n * uses, and adds the generated-file header.\n *\n * Imports are written explicitly while generating, never inferred from\n * whatever the output directory happens to resolve, so the output is the\n * same wherever it is written.\n *\n * @param sourceFiles - The files to finish, each written by this generation\n * @param logger - Receives a debug line for each file\n * @throws Error listing each diagnostic when the code does not compile\n */\nexport function finalizeSourceFiles(\n sourceFiles: readonly SourceFile[],\n logger: Logger,\n): void {\n sourceFiles.forEach((sourceFile, index) => {\n logger.debug(\n `Optimizing file [${sourceFile.getFilePath()}] - ${index + 1}/${sourceFiles.length}`,\n );\n sourceFile.formatText(FORMAT_SETTINGS);\n sourceFile.organizeImports(FORMAT_SETTINGS);\n });\n applyTypeOnlyImports(sourceFiles);\n verifyGeneratedCode(sourceFiles);\n for (const sourceFile of sourceFiles) {\n sourceFile.insertText(0, GENERATED_FILE_HEADER);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { readFile } from 'fs';\n\n/** How long a remote document may take before the request is abandoned. */\nexport const DEFAULT_HTTP_TIMEOUT_MS = 30_000;\n\n/**\n * Options for loading a resource over HTTP. Files ignore them.\n */\nexport interface LoadResourceOptions {\n /** Request headers, for example `Authorization`. */\n readonly headers?: Record<string, string>;\n /** Milliseconds before the request is abandoned. */\n readonly timeoutMs?: number;\n /** Abandons the request when it aborts, as an interrupted run does. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Tells whether a location names an http(s) resource rather than a file.\n *\n * @param path - A file path or URL\n * @returns True for an `http://` or `https://` URL\n */\nexport function isHttpLocation(path: string): boolean {\n return /^https?:\\/\\//i.test(path);\n}\n\nexport function loadResource(\n path: string,\n options: LoadResourceOptions = {},\n): Promise<string> {\n if (isHttpLocation(path)) {\n return loadHttpResource(path, options);\n }\n return loadFile(path);\n}\n\n/**\n * Fetches a resource and returns its body.\n *\n * A response outside 2xx is a failure: a 401 or 404 page is not the document\n * the caller asked for, and parsing it would only fail later with a message\n * about the page instead of the request.\n *\n * @param url - The http(s) URL\n * @param options - Headers and timeout\n * @returns The response body as text\n * @throws Error naming the status, the timeout or the network failure; the\n * caller names the URL\n */\nexport async function loadHttpResource(\n url: string,\n options: LoadResourceOptions = {},\n): Promise<string> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS;\n let response: Response;\n try {\n const timeout = AbortSignal.timeout(timeoutMs);\n response = await fetch(url, {\n headers: options.headers,\n signal: options.signal\n ? AbortSignal.any([options.signal, timeout])\n : timeout,\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === 'TimeoutError'\n ? `no response within ${timeoutMs} ms`\n : networkReason(error);\n throw new Error(reason, { cause: error });\n }\n if (!response.ok) {\n const status = [response.status, response.statusText]\n .filter(Boolean)\n .join(' ');\n throw new Error(`HTTP ${status}`);\n }\n return await response.text();\n}\n\n/**\n * Explains a failed fetch. Node reports every network failure as \"fetch\n * failed\" and keeps the actual reason - DNS, refused connection, TLS - in\n * `cause`.\n */\nfunction networkReason(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const cause = error.cause;\n if (cause instanceof Error && cause.message) {\n return `${error.message} (${cause.message})`;\n }\n return error.message;\n}\n\nexport function loadFile(path: string): Promise<string> {\n return new Promise((resolve, reject) => {\n readFile(path, 'utf-8', (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n });\n });\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OpenAPI } from '@ahoo-wang/fetcher-openapi';\nimport { parse } from 'yaml';\nimport { errorMessage, GeneratorError } from '../api/errors';\nimport type { LoadResourceOptions } from './resources';\nimport { loadResource } from './resources';\n\n/**\n * Loads and parses an OpenAPI 3 document.\n *\n * Every failure is a {@link GeneratorError} of kind `input` whose message\n * names the document: it cannot be read or fetched, it is neither JSON nor\n * YAML, or it is not an OpenAPI 3 document. A Swagger 2.0 document is\n * refused rather than generated into clients without models.\n *\n * @param inputPath - The path or http(s) URL of the document\n * @param options - Headers and timeout for an http(s) document\n * @returns The parsed document; `paths` is an empty object when it has none\n */\nexport async function parseOpenAPI(\n inputPath: string,\n options?: LoadResourceOptions,\n): Promise<OpenAPI> {\n return validateOpenAPIDocument(\n await loadDocument(inputPath, options),\n inputPath,\n );\n}\n\n/**\n * Loads and parses the input document, an OpenAPI 3 document or a Wow\n * Manifest, without checking which it is.\n *\n * Every failure is a {@link GeneratorError} of kind `input` whose message\n * names the document: it cannot be read or fetched, or it is neither JSON\n * nor YAML.\n *\n * @param inputPath - The path or http(s) URL of the document\n * @param options - Headers and timeout for an http(s) document\n * @returns The parsed document\n */\nexport async function loadDocument(\n inputPath: string,\n options?: LoadResourceOptions,\n): Promise<unknown> {\n let content: string;\n try {\n content = await loadResource(inputPath, options);\n } catch (error) {\n throw new GeneratorError(\n 'input',\n `Cannot read the OpenAPI document ${inputPath}: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n try {\n return parseContent(content);\n } catch (error) {\n throw new GeneratorError(\n 'input',\n `Cannot parse the OpenAPI document ${inputPath}: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n}\n\n/**\n * Checks that a parsed document is an OpenAPI 3 document the generator reads.\n *\n * @param document - The parsed document\n * @param source - Where it came from, for messages\n * @returns The document, with `paths` defaulted to an empty object\n * @throws GeneratorError when it is not an OpenAPI 3.x document\n */\nexport function validateOpenAPIDocument(\n document: unknown,\n source: string,\n): OpenAPI {\n if (\n typeof document !== 'object' ||\n document === null ||\n Array.isArray(document)\n ) {\n throw new GeneratorError(\n 'input',\n `${source} is not an OpenAPI document: expected an object at the top level.`,\n );\n }\n const candidate = document as Record<string, unknown>;\n if (candidate.swagger !== undefined) {\n throw new GeneratorError(\n 'input',\n `${source} is a Swagger ${String(candidate.swagger)} document; wow-generator reads OpenAPI 3.x only. Convert it first, for example with swagger2openapi.`,\n );\n }\n if (\n typeof candidate.openapi !== 'string' ||\n !/^3\\.\\d+/.test(candidate.openapi)\n ) {\n throw new GeneratorError(\n 'input',\n `${source} is not an OpenAPI 3.x document: its \"openapi\" field is ${candidate.openapi === undefined ? 'missing' : JSON.stringify(candidate.openapi)}.`,\n );\n }\n if (\n typeof candidate.info !== 'object' ||\n candidate.info === null ||\n Array.isArray(candidate.info)\n ) {\n throw new GeneratorError(\n 'input',\n `${source} is not a valid OpenAPI document: its \"info\" object is missing.`,\n );\n }\n // OpenAPI 3.1 allows a document without paths (webhooks or components only).\n return { ...candidate, paths: candidate.paths ?? {} } as OpenAPI;\n}\n\n/**\n * Parses already-loaded document content in whichever format it is written.\n *\n * Callers name the source in their own error, so a failure here carries only\n * what went wrong with the text.\n *\n * @param content - The document text\n * @returns The parsed document\n */\nexport function parseContent<T>(content: string): T {\n // inferFileFormat answers with a format or throws, so the switch is\n // exhaustive - a `default` here would be a branch no input can reach.\n switch (inferFileFormat(content)) {\n case FileFormat.JSON:\n return JSON.parse(content);\n case FileFormat.YAML:\n return parse(content);\n }\n}\n\nexport enum FileFormat {\n JSON = 'json',\n YAML = 'yaml',\n}\n\nexport function inferFileFormat(content: string): FileFormat {\n // Trim whitespace and BOM characters from the beginning\n const trimmedContent = content.trimStart();\n\n if (trimmedContent.startsWith('{') || trimmedContent.startsWith('[')) {\n return FileFormat.JSON;\n }\n\n // YAML can start with various characters, but commonly with '-' (for arrays) or '%YAML'\n // We'll check for common YAML indicators\n if (trimmedContent.startsWith('-') || trimmedContent.startsWith('%YAML')) {\n return FileFormat.YAML;\n }\n\n // Try to parse as JSON to see if it's valid JSON despite not starting with { or [\n try {\n JSON.parse(trimmedContent);\n return FileFormat.JSON;\n } catch {\n // If it's not valid JSON, we'll assume it's YAML if it's not empty\n if (trimmedContent.length > 0) {\n return FileFormat.YAML;\n }\n }\n\n throw new Error('Unable to infer file format');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isAbsolute, resolve } from 'path';\nimport type { GeneratorConfiguration } from '../api/configuration';\nimport { DEFAULT_CONFIG_PATH } from '../api/configuration';\nimport { errorMessage, GeneratorError } from '../api/errors';\nimport type { Logger } from '../api/logger';\nimport { isIdentifier } from '../naming/naming';\nimport { parseContent } from './parsers';\nimport type { LoadResourceOptions } from './resources';\nimport { isHttpLocation, loadResource } from './resources';\n\n/**\n * A configuration, and the warnings reading it gave: keys the generator does\n * not read, an empty file.\n */\nexport interface LoadedConfiguration {\n readonly config: GeneratorConfiguration;\n /** One line each, in the order they arose. */\n readonly warnings: readonly string[];\n}\n\n/**\n * A configuration, the place it was read from, and the warnings reading it\n * gave.\n */\nexport interface ResolvedConfiguration extends LoadedConfiguration {\n /** The absolute path or URL read, or undefined when there was none. */\n readonly origin?: string;\n}\n\n/**\n * Finds and loads the generator configuration.\n *\n * A path the caller names has to exist. Without one the generator reads\n * {@link DEFAULT_CONFIG_PATH}, and generates with the defaults when it does\n * not exist.\n *\n * @param configPath - The path or URL the caller named, if any\n * @param logger - Receives what was read, at `debug`\n * @param options - Headers and timeout for a configuration read over http(s)\n * @returns The configuration, where it came from and the warnings it gave\n * @throws GeneratorError of kind `configuration` when it cannot be read,\n * parsed or understood\n */\nexport async function resolveConfiguration(\n configPath: string | undefined,\n logger: Logger,\n options?: LoadResourceOptions,\n): Promise<ResolvedConfiguration> {\n if (configPath !== undefined) {\n const loaded = await loadConfiguration(\n { path: configPath, explicit: true },\n logger,\n options,\n );\n return { ...loaded, origin: describeSource(configPath) };\n }\n const loaded = await loadConfiguration(\n { path: DEFAULT_CONFIG_PATH, explicit: false },\n logger,\n options,\n );\n if (loaded !== undefined) {\n return { ...loaded, origin: describeSource(DEFAULT_CONFIG_PATH) };\n }\n logger.debug('No configuration file found, generating with defaults');\n return { config: {}, warnings: [] };\n}\n\n/** Top-level keys a generator configuration may declare. */\nconst CONFIGURATION_KEYS = ['apiClients'];\n/** Keys an `apiClients` entry may declare. */\nconst API_CLIENT_KEYS = ['ignorePathParameters', 'methodNames'];\n\n/**\n * Where a configuration is read from, and whether the caller chose that place.\n */\nexport interface ConfigurationSource {\n /** A file path, or an http(s) URL. */\n readonly path: string;\n /**\n * True when the caller asked for this path. An absent file is then a\n * mistake worth failing on; under the default path it is merely the common\n * case of a project that has no configuration.\n */\n readonly explicit: boolean;\n}\n\n/**\n * Reads, validates and reports a generator configuration.\n *\n * A configuration that fails to load used to degrade to the defaults with a\n * single line among hundreds of progress lines, so a misplaced file looked\n * exactly like a generator that ignores its options. Loading now either\n * succeeds and says what it read, or fails loudly - with the sole exception of\n * the default path being absent, which stays a normal, quiet outcome.\n *\n * @param source - Where to read the configuration from\n * @param logger - Receives what was read and the settings it resolved to, at\n * `debug`\n * @param options - Headers and timeout for a configuration read over http(s)\n * @returns The validated configuration and the warnings about it; undefined\n * when a path the caller did not name does not exist\n * @throws GeneratorError of kind `configuration` when the configuration\n * cannot be read, parsed or understood\n */\nexport async function loadConfiguration(\n source: ConfigurationSource & { explicit: true },\n logger: Logger,\n options?: LoadResourceOptions,\n): Promise<LoadedConfiguration>;\nexport async function loadConfiguration(\n source: ConfigurationSource,\n logger: Logger,\n options?: LoadResourceOptions,\n): Promise<LoadedConfiguration | undefined>;\nexport async function loadConfiguration(\n source: ConfigurationSource,\n logger: Logger,\n options?: LoadResourceOptions,\n): Promise<LoadedConfiguration | undefined> {\n const origin = describeSource(source.path);\n logger.debug(`Reading configuration: ${origin}`);\n let content: string;\n try {\n content = await loadResource(source.path, options);\n } catch (error) {\n if (!source.explicit && isFileNotFound(error)) {\n logger.debug(`No configuration file at ${origin}`);\n return undefined;\n }\n throw new GeneratorError(\n 'configuration',\n `Cannot read configuration ${origin}: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n if (!content.trim()) {\n return {\n config: {},\n warnings: [`Configuration ${origin} is empty, generating with defaults`],\n };\n }\n let parsed: unknown;\n try {\n parsed = parseContent(content);\n } catch (error) {\n throw new GeneratorError(\n 'configuration',\n `Cannot parse configuration ${origin}: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n const loaded = validateConfiguration(parsed, origin);\n logger.debug(\n `Configuration loaded from ${origin}: ${describe(loaded.config)}`,\n );\n return loaded;\n}\n\n/**\n * Resolves a configuration path to what the user needs to see in a message.\n * A relative path is resolved against the working directory, because \"not\n * found\" is unactionable until it says which file was looked for.\n *\n * @param path - The configured file path or URL\n * @returns An absolute path, or the URL unchanged\n */\nfunction describeSource(path: string): string {\n if (isHttpLocation(path) || isAbsolute(path)) {\n return path;\n }\n return resolve(path);\n}\n\n/** Tells whether an error reports a missing file rather than a failed read. */\nfunction isFileNotFound(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as NodeJS.ErrnoException).code === 'ENOENT'\n );\n}\n\n/** Names a value's type the way a configuration author would recognise it. */\nfunction typeOf(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n return `a ${typeof value}`;\n}\n\n/** Tells whether a value is a plain object a configuration block can be. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Warns about keys the generator does not read.\n *\n * A misspelled key is the failure this whole module exists for: it parses,\n * it validates, and it does nothing at all.\n *\n * @param warnings - Receives the warning\n * @param origin - Where the configuration was read from\n * @param scope - The block the keys sit in, for the message\n * @param value - The block to inspect\n * @param known - The keys the generator reads\n */\nfunction warnUnknownKeys(\n warnings: string[],\n origin: string,\n scope: string,\n value: Record<string, unknown>,\n known: string[],\n): void {\n const unknown = Object.keys(value).filter(key => !known.includes(key));\n if (!unknown.length) {\n return;\n }\n warnings.push(\n `Ignoring unknown ${scope} option(s) in ${origin}: ${unknown.join(', ')}. Known option(s): ${known.join(', ')}`,\n );\n}\n\n/**\n * Checks a parsed configuration against the options the generator reads.\n *\n * Shape errors throw: a block the generator cannot read is a request the user\n * made and the generator would otherwise drop. Unknown keys only warn, so a\n * configuration written for a newer version still generates.\n *\n * @param parsed - The parsed configuration document\n * @param origin - Where it was read from, for messages\n * @returns The same configuration, typed, and a warning for every key the\n * generator ignores\n * @throws GeneratorError of kind `configuration` when a block or option has\n * a shape the generator cannot read\n */\nexport function validateConfiguration(\n parsed: unknown,\n origin: string,\n): LoadedConfiguration {\n if (!isRecord(parsed)) {\n throw new GeneratorError(\n 'configuration',\n `Configuration ${origin} must be a JSON or YAML object, found ${typeOf(parsed)}`,\n );\n }\n const warnings: string[] = [];\n warnUnknownKeys(\n warnings,\n origin,\n 'configuration',\n parsed,\n CONFIGURATION_KEYS,\n );\n validateApiClients(parsed.apiClients, origin, warnings);\n return { config: parsed as GeneratorConfiguration, warnings };\n}\n\n/** Checks the `apiClients` block and each tag entry within it. */\nfunction validateApiClients(\n apiClients: unknown,\n origin: string,\n warnings: string[],\n): void {\n if (apiClients === undefined) {\n return;\n }\n if (!isRecord(apiClients)) {\n throw new GeneratorError(\n 'configuration',\n `apiClients in ${origin} must be an object keyed by tag name, found ${typeOf(apiClients)}`,\n );\n }\n for (const [tag, apiClient] of Object.entries(apiClients)) {\n if (!isRecord(apiClient)) {\n throw new GeneratorError(\n 'configuration',\n `apiClients[\"${tag}\"] in ${origin} must be an object, found ${typeOf(apiClient)}`,\n );\n }\n warnUnknownKeys(\n warnings,\n origin,\n `apiClients[\"${tag}\"]`,\n apiClient,\n API_CLIENT_KEYS,\n );\n const { ignorePathParameters } = apiClient;\n if (\n ignorePathParameters !== undefined &&\n !(\n Array.isArray(ignorePathParameters) &&\n ignorePathParameters.every(name => typeof name === 'string')\n )\n ) {\n throw new GeneratorError(\n 'configuration',\n `apiClients[\"${tag}\"].ignorePathParameters in ${origin} must be an array of strings, found ${typeOf(ignorePathParameters)}`,\n );\n }\n const { methodNames } = apiClient;\n if (methodNames === undefined) continue;\n if (!isRecord(methodNames)) {\n throw new GeneratorError(\n 'configuration',\n `apiClients[\"${tag}\"].methodNames in ${origin} must be an object mapping operationIds to method names, found ${typeOf(methodNames)}`,\n );\n }\n for (const [operationId, methodName] of Object.entries(methodNames)) {\n if (typeof methodName !== 'string' || !isIdentifier(methodName)) {\n throw new GeneratorError(\n 'configuration',\n `apiClients[\"${tag}\"].methodNames[\"${operationId}\"] in ${origin} must be a valid method name, found ${JSON.stringify(methodName)}`,\n );\n }\n }\n }\n}\n\n/**\n * Summarises the settings a configuration resolved to, so the log answers\n * \"did my option take effect?\" without a second run.\n *\n * @param config - The validated configuration\n * @returns A one-line summary of every option the generator reads\n */\nfunction describe(config: GeneratorConfiguration): string {\n const tags = Object.keys(config.apiClients ?? {});\n return `apiClients=${tags.length ? tags.join(', ') : 'none'}`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GeneratorError } from '../api/errors';\n\n/**\n * The part of a Wow V10 service Manifest (`GET /wow/manifest`, or the\n * merged `manifest.json` of the build; decisions D73, D74) the generator\n * reads. Members it does not read are left out; a Manifest carries more.\n */\nexport interface ManifestDocument {\n readonly format: number;\n readonly service?: { readonly name: string; readonly version?: string };\n readonly contexts: readonly ManifestContext[];\n readonly errors?: readonly ManifestError[];\n readonly $defs?: Readonly<Record<string, JsonSchema>>;\n}\n\n/** A bounded context of the Manifest. */\nexport interface ManifestContext {\n readonly name: string;\n readonly description?: string;\n readonly aggregates?: readonly ManifestAggregate[];\n readonly subscriptions?: readonly { readonly name: string }[];\n readonly errors?: readonly ManifestError[];\n}\n\n/** An aggregate of a bounded context. */\nexport interface ManifestAggregate {\n readonly name: string;\n readonly description?: string;\n readonly state: { readonly schema: string };\n readonly snapshot?: { readonly enabled?: boolean };\n readonly commands?: readonly ManifestCommand[];\n readonly events?: readonly ManifestEvent[];\n readonly lifecycle?: readonly string[];\n readonly queries?: readonly { readonly model: string }[];\n readonly ownership?: string;\n}\n\n/** A command of an aggregate. */\nexport interface ManifestCommand {\n readonly name: string;\n readonly schema: string;\n readonly creation?: string;\n readonly produces?: readonly string[];\n readonly routes?: readonly {\n readonly method: string;\n readonly path: string;\n }[];\n readonly mounted?: boolean;\n readonly description?: string;\n}\n\n/** An event of an aggregate. */\nexport interface ManifestEvent {\n readonly name: string;\n readonly revision?: number;\n readonly schema: string;\n}\n\n/** An error code of the Manifest. */\nexport interface ManifestError {\n readonly code: string;\n readonly status: number;\n readonly description?: string;\n}\n\n/** A JSON Schema 2020-12 of `$defs`, as the Manifest writes them. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/** The Manifest format the generator reads (decision D59). */\nexport const MANIFEST_FORMAT = 1;\n\nconst DEFS_PREFIX = '#/$defs/';\n\n/** The `$defs` key a schema reference points to, or undefined for another. */\nexport function schemaKey(ref: string): string | undefined {\n return ref.startsWith(DEFS_PREFIX)\n ? ref.slice(DEFS_PREFIX.length)\n : undefined;\n}\n\n/**\n * Whether a parsed document is a Wow Manifest rather than an OpenAPI one: an\n * object with a numeric `format` and a `contexts` array, and no `openapi`.\n */\nexport function isManifestDocument(document: unknown): boolean {\n if (typeof document !== 'object' || document === null) return false;\n const candidate = document as Record<string, unknown>;\n return (\n candidate.openapi === undefined &&\n candidate.swagger === undefined &&\n typeof candidate.format === 'number' &&\n Array.isArray(candidate.contexts)\n );\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Checks that a document is a Manifest of the format the generator reads,\n * with the members it needs.\n *\n * @param document - The parsed document\n * @param source - Where it came from, for messages\n * @throws GeneratorError of kind `input` for another format, and of kind\n * `specification` for a Manifest that misses what it needs\n */\nexport function validateManifest(\n document: unknown,\n source: string,\n): ManifestDocument {\n const manifest = document as ManifestDocument;\n if (manifest.format !== MANIFEST_FORMAT) {\n throw new GeneratorError(\n 'input',\n `${source} is a Wow Manifest of format ${manifest.format}; wow-generator reads format ${MANIFEST_FORMAT}.`,\n );\n }\n const problems: string[] = [];\n manifest.contexts.forEach((context, index) => {\n if (!isObject(context) || typeof context.name !== 'string') {\n problems.push(`contexts[${index}] has no name`);\n return;\n }\n (context.aggregates ?? []).forEach((aggregate, at) => {\n const where = `${context.name}.aggregates[${at}]`;\n if (!isObject(aggregate) || typeof aggregate.name !== 'string') {\n problems.push(`${where} has no name`);\n } else if (\n !isObject(aggregate.state) ||\n typeof aggregate.state.schema !== 'string'\n ) {\n problems.push(`${context.name}.${aggregate.name} has no state schema`);\n } else {\n (aggregate.commands ?? []).forEach(command => {\n if (\n typeof command?.name !== 'string' ||\n typeof command.schema !== 'string'\n ) {\n problems.push(\n `a command of ${context.name}.${aggregate.name} has no name or schema`,\n );\n }\n });\n (aggregate.events ?? []).forEach(event => {\n if (\n typeof event?.name !== 'string' ||\n typeof event.schema !== 'string'\n ) {\n problems.push(\n `an event of ${context.name}.${aggregate.name} has no name or schema`,\n );\n }\n });\n }\n });\n });\n if (manifest.$defs !== undefined && !isObject(manifest.$defs)) {\n problems.push('$defs is not an object');\n }\n if (problems.length > 0) {\n throw new GeneratorError(\n 'specification',\n `${source} is not a Manifest wow-generator can read: ${problems.join('; ')}.`,\n );\n }\n return manifest;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n camelCase,\n pascalCase,\n quoteStringLiteral,\n resolvePropertyName,\n toIdentifier,\n toTypeIdentifier,\n upperSnakeCase,\n} from '../naming/naming';\nimport { compareNames } from '../naming/order';\nimport {\n type JsonSchema,\n type ManifestAggregate,\n type ManifestContext,\n type ManifestDocument,\n schemaKey,\n} from './document';\n\n/**\n * The formats of numbers a Wow Manifest marks for reading from their text,\n * typed `string` (review R4-Q, Q-9; decision D254): an integer past\n * JavaScript's safe range (`int64`, `bigint`) and an exact decimal\n * (`decimal`). The wire keeps JSON numbers; `@ahoo-wang/wow-client` reads these\n * from the response's source text. A plain OpenAPI document keeps `number`.\n */\nconst TEXT_NUMBER_FORMATS: ReadonlySet<string> = new Set([\n 'int64',\n 'bigint',\n 'decimal',\n]);\n\n/** A property of a generated interface. */\nexport interface PropertyModel {\n /** As written in the interface: quoted when it is no identifier. */\n readonly name: string;\n readonly type: string;\n readonly optional: boolean;\n readonly description?: string;\n}\n\n/** A type declared for a schema of `$defs`. */\nexport interface TypeModel {\n /** The `$defs` key. */\n readonly key: string;\n readonly name: string;\n /** The file it is declared in, relative to the output directory. */\n readonly file: string;\n readonly description?: string;\n /** An interface's properties, or undefined for a type alias. */\n readonly properties?: readonly PropertyModel[];\n /** A type alias's type; or, for an interface, its index signature's. */\n readonly type?: string;\n /** The type names it refers to. */\n readonly references: readonly string[];\n}\n\n/**\n * The numbers of a value read and written as their exact text, as\n * `@ahoo-wang/wow-client`'s `TextNumbers` holds them: `true` at such a number,\n * else its members' marks by name, `'*'` for every item or map value.\n */\nexport type TextNumbersModel =\n true | { readonly [member: string]: TextNumbersModel };\n\n/** A command of an aggregate client. */\nexport interface CommandModel {\n readonly name: string;\n readonly method: string;\n /** The `PATHS` member of its route by id, and of its route without one. */\n readonly byIdPath?: { readonly member: string; readonly path: string };\n readonly unaddressedPath?: { readonly member: string; readonly path: string };\n /** The body's type name, or undefined when its schema is unknown. */\n readonly bodyType: string;\n /** The body may be left out: its schema requires nothing. */\n readonly bodyOptional: boolean;\n readonly creation: string;\n readonly mounted: boolean;\n readonly produces: readonly string[];\n /** What the command's class says it is, as the Manifest describes it. */\n readonly description?: string;\n /** Its body has exact numbers, under `textNumbers.commands` of its aggregate. */\n readonly bodyNumbers?: boolean;\n}\n\n/** A lifecycle command an aggregate lists. */\nexport interface LifecycleModel {\n /** `wow.lifecycle.DeleteAggregate`, … */\n readonly name: string;\n /** The `LifecycleCommands` member. */\n readonly member: string;\n readonly method: string;\n /**\n * The body's type, or undefined for a command without one: the type\n * generated from the Manifest's `$defs` entry of the command's name when it\n * holds one (`bodyGenerated`), else `@ahoo-wang/wow-client`'s.\n */\n readonly bodyType?: string;\n /** The body's type is generated from the Manifest, not `@ahoo-wang/wow-client`'s. */\n readonly bodyGenerated?: boolean;\n /** What the Manifest's schema of the body says the command does. */\n readonly description?: string;\n}\n\n/** An aggregate and its clients. */\nexport interface AggregateModel {\n readonly context: string;\n readonly name: string;\n readonly description?: string;\n /** The type-name prefix: `Product`. */\n readonly typeName: string;\n /** The directory of its modules, relative to the output directory. */\n readonly directory: string;\n readonly ownership: string;\n readonly snapshot: boolean;\n readonly stateType: string;\n readonly stateFields: readonly string[];\n readonly commands: readonly CommandModel[];\n readonly events: readonly {\n /** The name the Manifest declares: `ProductCreated`. */\n readonly name: string;\n /**\n * The event type the server names it by on the wire (08-data-protocols §2):\n * `context.aggregate.EventName`, or the declared name when it is already\n * qualified.\n */\n readonly wireName: string;\n readonly revision: number;\n readonly type: string;\n }[];\n readonly lifecycle: readonly LifecycleModel[];\n readonly queryModels: readonly string[];\n /** The exact numbers of its state, events (by wire name) and commands; none when it has none. */\n readonly textNumbers?: {\n readonly state?: TextNumbersModel;\n readonly events?: Readonly<Record<string, TextNumbersModel>>;\n readonly commands?: Readonly<Record<string, TextNumbersModel>>;\n };\n}\n\n/** A bounded context and what its modules declare. */\nexport interface ContextModel {\n readonly name: string;\n readonly description?: string;\n /** The type-name prefix: `EshopCatalog`. */\n readonly typeName: string;\n /** The constant prefix: `ESHOP_CATALOG`. */\n readonly constantName: string;\n readonly directory: string;\n readonly errors: readonly {\n readonly member: string;\n readonly code: string;\n readonly status: number;\n readonly description?: string;\n }[];\n readonly subscriptions: readonly string[];\n readonly aggregates: readonly AggregateModel[];\n}\n\n/** What a Manifest generates, decided before anything is written. */\nexport interface ManifestModel {\n readonly service?: string;\n readonly types: readonly TypeModel[];\n readonly contexts: readonly ContextModel[];\n}\n\nconst LIFECYCLE_BODIES: Readonly<Record<string, string>> = {\n 'wow.lifecycle.TransferOwner': 'TransferOwner',\n 'wow.lifecycle.TransferSpace': 'TransferSpace',\n 'wow.lifecycle.ApplyTags': 'ApplyTags',\n};\n\n/** The lifecycle commands `@ahoo-wang/wow-client` sends (decision D113). */\nconst LIFECYCLE_COMMANDS: ReadonlySet<string> = new Set([\n 'wow.lifecycle.DeleteAggregate',\n 'wow.lifecycle.RestoreAggregate',\n 'wow.lifecycle.TransferOwner',\n 'wow.lifecycle.TransferSpace',\n 'wow.lifecycle.ApplyTags',\n]);\n\n/** The deepest `state.*` path listed as a query field. */\nconst MAX_FIELD_DEPTH = 4;\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction typesOf(schema: JsonSchema): string[] {\n const type = schema.type;\n if (typeof type === 'string') return [type];\n if (Array.isArray(type)) return type.filter(t => typeof t === 'string');\n return [];\n}\n\n/** A union or an intersection, its members set apart when they are compound. */\nfunction join(members: string[], separator: ' | ' | ' & '): string {\n const unique = [...new Set(members)];\n if (unique.length === 1) return unique[0];\n return unique\n .map(member =>\n / [|&] /.test(member) && !member.startsWith('{') ? `(${member})` : member,\n )\n .join(separator);\n}\n\nfunction literal(value: unknown): string {\n return typeof value === 'string'\n ? quoteStringLiteral(value)\n : JSON.stringify(value);\n}\n\n/**\n * Turns the schemas of a Manifest into types: names for `$defs` keys and\n * type text for any schema.\n */\nclass SchemaTypes {\n readonly names = new Map<string, string>();\n readonly warnings: string[] = [];\n\n constructor(readonly defs: Readonly<Record<string, JsonSchema>>) {}\n\n /**\n * Whether `key` is a parameterized type's, such as\n * `java.util.Map(java.lang.String,java.lang.Object)`: its schema is written\n * in place (`Record<string, unknown>`), never declared, since a name taken\n * from its last type argument would shadow a global such as `Object`.\n */\n inlined(key: string): boolean {\n return key.includes('(');\n }\n\n /** Names each key after its simple class name, qualified as far as needed to be unique. */\n name(keys: readonly string[]): void {\n const pending = new Set(keys);\n for (let depth = 0; pending.size > 0; depth++) {\n const byName = new Map<string, string[]>();\n for (const key of pending.keys()) {\n const segments = key.split('.');\n const simple = segments[segments.length - 1].split('$');\n const qualifier = segments.slice(\n Math.max(0, segments.length - 1 - depth),\n segments.length - 1,\n );\n const name = toTypeIdentifier(\n [...qualifier, ...simple].map(part =>\n /^[a-z]/.test(part) ? pascalCase(part) : part,\n ),\n );\n byName.set(name, [...(byName.get(name) ?? []), key]);\n }\n const taken = new Set(this.names.values());\n for (const [name, owners] of byName) {\n // A key whose packages are used up takes the name, numbered when it\n // is taken; the others take it alone, or qualify one package more.\n const exhausted = owners.filter(\n key => key.split('.').length - 1 <= depth,\n );\n const assigned =\n owners.length === 1 && !taken.has(name) ? owners : exhausted;\n for (const key of assigned) {\n let unique = name;\n for (let index = 2; taken.has(unique); index++) {\n unique = `${name}${index}`;\n }\n taken.add(unique);\n this.names.set(key, unique);\n pending.delete(key);\n }\n }\n }\n }\n\n /** The schema of a key, or undefined with a warning. */\n schemaOf(key: string): JsonSchema | undefined {\n const schema = this.defs[key];\n return isObject(schema) ? schema : undefined;\n }\n\n /** The schema a reference resolves to, through `$ref`s. */\n resolve(schema: JsonSchema, seen = new Set<string>()): JsonSchema {\n const ref = schema.$ref;\n if (typeof ref !== 'string') return schema;\n const key = schemaKey(ref);\n if (key === undefined || seen.has(key)) return schema;\n const target = this.schemaOf(key);\n return target ? this.resolve(target, new Set([...seen, key])) : schema;\n }\n\n /** The keys a schema refers to, directly. */\n references(schema: unknown, into: Set<string> = new Set()): Set<string> {\n if (Array.isArray(schema)) {\n schema.forEach(item => this.references(item, into));\n } else if (isObject(schema)) {\n for (const [member, value] of Object.entries(schema)) {\n if (member === '$ref' && typeof value === 'string') {\n const key = schemaKey(value);\n if (key !== undefined) into.add(key);\n } else if (member !== 'enum' && member !== 'const') {\n this.references(value, into);\n }\n }\n }\n return into;\n }\n\n /** The keys a schema refers to by name: an inlined key's own, in its place. */\n namedReferences(schema: unknown): Set<string> {\n const named = new Set<string>();\n for (const key of this.references(schema)) {\n const target = this.schemaOf(key);\n if (target !== undefined && this.inlined(key)) {\n this.namedReferences(target).forEach(inner => named.add(inner));\n } else {\n named.add(key);\n }\n }\n return named;\n }\n\n /** Every key reachable from `roots`. */\n closure(roots: Iterable<string>): string[] {\n const reached = new Set<string>();\n const pending = [...roots];\n while (pending.length > 0) {\n const key = pending.pop()!;\n if (reached.has(key)) continue;\n reached.add(key);\n const schema = this.schemaOf(key);\n if (schema) pending.push(...this.references(schema));\n }\n return [...reached];\n }\n\n /** The type of a reference to `key`. */\n refType(key: string, where: string): string {\n const schema = this.schemaOf(key);\n if (schema !== undefined && this.inlined(key)) {\n return this.type(schema, where);\n }\n const name = this.names.get(key);\n if (name !== undefined && this.schemaOf(key)) return name;\n this.warnings.push(\n `${where} refers to the schema ${key}, which the Manifest's $defs does not hold; it is typed as unknown.`,\n );\n return 'unknown';\n }\n\n /** The type text of a schema. */\n type(schema: unknown, where: string): string {\n if (schema === true || schema === undefined) return 'unknown';\n if (schema === false) return 'never';\n if (!isObject(schema)) return 'unknown';\n if (typeof schema.$ref === 'string') {\n const key = schemaKey(schema.$ref);\n return key === undefined ? 'unknown' : this.refType(key, where);\n }\n if ('const' in schema) return literal(schema.const);\n if (Array.isArray(schema.enum)) {\n return schema.enum.length === 0\n ? 'never'\n : join(schema.enum.map(literal), ' | ');\n }\n for (const [member, separator] of [\n ['oneOf', ' | '],\n ['anyOf', ' | '],\n ['allOf', ' & '],\n ] as const) {\n const options = schema[member];\n if (Array.isArray(options) && options.length > 0) {\n return join(\n options.map(option => this.type(option, where)),\n separator,\n );\n }\n }\n const types = typesOf(schema);\n if (types.length === 0) {\n return isObject(schema.properties)\n ? this.objectType(schema, where)\n : 'unknown';\n }\n return join(\n types.map(type => this.primitive(type, schema, where)),\n ' | ',\n );\n }\n\n private primitive(type: string, schema: JsonSchema, where: string): string {\n switch (type) {\n case 'string':\n return 'string';\n case 'integer':\n case 'number':\n return typeof schema.format === 'string' &&\n TEXT_NUMBER_FORMATS.has(schema.format)\n ? 'string'\n : 'number';\n case 'boolean':\n return 'boolean';\n case 'null':\n return 'null';\n case 'array': {\n const item =\n schema.items === undefined\n ? 'unknown'\n : this.type(schema.items, where);\n return / [|&] /.test(item) ? `(${item})[]` : `${item}[]`;\n }\n case 'object':\n return this.objectType(schema, where);\n default:\n return 'unknown';\n }\n }\n\n /** An inline object type. */\n private objectType(schema: JsonSchema, where: string): string {\n const properties = this.properties(schema, where);\n const extra = this.additional(schema, where);\n if (properties.length === 0) {\n return `Record<string, ${extra ?? 'unknown'}>`;\n }\n const members = properties.map(\n property =>\n `${property.name}${property.optional ? '?' : ''}: ${property.type}`,\n );\n // A typed index signature would have to admit every property's type.\n if (extra !== undefined) members.push('[key: string]: unknown');\n return `{ ${members.join('; ')} }`;\n }\n\n /** The properties of an object schema, in their order. */\n properties(schema: JsonSchema, where: string): PropertyModel[] {\n if (!isObject(schema.properties)) return [];\n const required = new Set(\n Array.isArray(schema.required) ? (schema.required as string[]) : [],\n );\n return Object.entries(schema.properties).map(([name, property]) => {\n const description = isObject(property) ? property.description : undefined;\n return {\n name: resolvePropertyName(name),\n type: this.type(property, `${where}.${name}`),\n optional: !required.has(name),\n ...(typeof description === 'string' ? { description } : {}),\n };\n });\n }\n\n /** The type of an object's additional properties, if it allows a typed set. */\n additional(schema: JsonSchema, where: string): string | undefined {\n const extra = schema.additionalProperties;\n if (extra === undefined || extra === false) return undefined;\n return this.type(extra, where);\n }\n\n /** Whether a schema is an object with properties, so it names an interface. */\n isInterface(schema: JsonSchema): boolean {\n const types = typesOf(schema);\n return (\n isObject(schema.properties) &&\n (types.length === 0 || (types.length === 1 && types[0] === 'object')) &&\n schema.$ref === undefined &&\n schema.allOf === undefined &&\n schema.oneOf === undefined &&\n schema.anyOf === undefined\n );\n }\n\n /**\n * The exact numbers of a schema: each `integer` or `number` of a\n * {@link TEXT_NUMBER_FORMATS} format, through objects, arrays, maps and\n * alternatives; undefined when it has none. A recursive reference is not\n * followed: its numbers read as numbers.\n */\n textNumbers(\n schema: unknown,\n seen: ReadonlySet<string> = new Set(),\n ): TextNumbersModel | undefined {\n if (!isObject(schema)) return undefined;\n const ref =\n typeof schema.$ref === 'string' ? schemaKey(schema.$ref) : undefined;\n if (ref !== undefined) {\n const target = this.schemaOf(ref);\n if (seen.has(ref) || target === undefined) return undefined;\n return this.textNumbers(target, new Set([...seen, ref]));\n }\n const alternatives = ['oneOf', 'anyOf', 'allOf'].flatMap(member =>\n Array.isArray(schema[member]) ? (schema[member] as unknown[]) : [],\n );\n const marks = alternatives\n .map(alternative => this.textNumbers(alternative, seen))\n .filter((mark): mark is TextNumbersModel => mark !== undefined);\n const types = typesOf(schema);\n if (\n (types.includes('integer') || types.includes('number')) &&\n typeof schema.format === 'string' &&\n TEXT_NUMBER_FORMATS.has(schema.format)\n ) {\n marks.push(true);\n }\n const members: Record<string, TextNumbersModel> = {};\n if (isObject(schema.properties)) {\n for (const [name, property] of Object.entries(schema.properties)) {\n const mark = this.textNumbers(property, seen);\n if (mark !== undefined) members[name] = mark;\n }\n }\n const each =\n this.textNumbers(schema.items, seen) ??\n this.textNumbers(schema.additionalProperties, seen);\n if (each !== undefined) members['*'] = each;\n if (Object.keys(members).length > 0) marks.push(members);\n return mergeTextNumbers(marks);\n }\n\n /** The `state.*` paths of a state schema a query can filter and sort on. */\n fields(\n schema: JsonSchema,\n prefix: string,\n depth = 1,\n seen = new Set<string>(),\n ): string[] {\n const resolved = this.resolve(schema);\n const ref =\n typeof schema.$ref === 'string' ? schemaKey(schema.$ref) : undefined;\n if (ref !== undefined && seen.has(ref)) return [];\n const nextSeen = ref === undefined ? seen : new Set([...seen, ref]);\n if (!isObject(resolved.properties)) return [];\n const paths: string[] = [];\n for (const [name, property] of Object.entries(resolved.properties)) {\n const path = `${prefix}.${name}`;\n paths.push(path);\n if (depth < MAX_FIELD_DEPTH && isObject(property)) {\n const target = this.resolve(property);\n if (!typesOf(target).includes('array')) {\n paths.push(...this.fields(property, path, depth + 1, nextSeen));\n }\n }\n }\n return paths;\n }\n}\n\n/**\n * The marks of a value any of `marks` describes: `true` when each is, else\n * the members of the objects among them merged (a value is a number or an\n * object, so its object marks are the ones that apply to members).\n */\nfunction mergeTextNumbers(\n marks: readonly TextNumbersModel[],\n): TextNumbersModel | undefined {\n if (marks.length === 0) return undefined;\n const objects = marks.filter(\n (mark): mark is { readonly [member: string]: TextNumbersModel } =>\n mark !== true,\n );\n if (objects.length === 0) return true;\n const merged: Record<string, TextNumbersModel[]> = {};\n for (const object of objects) {\n for (const [member, mark] of Object.entries(object)) {\n (merged[member] ??= []).push(mark);\n }\n }\n return Object.fromEntries(\n Object.entries(merged).map(([member, all]) => [\n member,\n mergeTextNumbers(all)!,\n ]),\n );\n}\n\nfunction emptyBody(\n types: SchemaTypes,\n schema: JsonSchema | undefined,\n): boolean {\n if (schema === undefined) return true;\n const resolved = types.resolve(schema);\n return !Array.isArray(resolved.required) || resolved.required.length === 0;\n}\n\nfunction aggregateRoots(\n types: SchemaTypes,\n aggregate: ManifestAggregate,\n): string[] {\n return [\n aggregate.state.schema,\n ...(aggregate.commands ?? []).map(command => command.schema),\n ...(aggregate.events ?? []).map(event => event.schema),\n ]\n .map(schemaKey)\n .filter((key): key is string => key !== undefined)\n .concat(lifecycleBodies(types, aggregate));\n}\n\n/**\n * The lifecycle commands with a body that `aggregate` lists and whose body\n * the Manifest's `$defs` holds, keyed by the command's name (roadmap 5a.1c).\n */\nfunction lifecycleBodies(\n types: SchemaTypes,\n aggregate: ManifestAggregate,\n): string[] {\n return (aggregate.lifecycle ?? []).filter(\n name => LIFECYCLE_BODIES[name] !== undefined && types.schemaOf(name),\n );\n}\n\n/**\n * Decides what a Manifest generates: a `types.ts` per bounded context with\n * the types of the schemas its aggregates reach (a schema two contexts reach\n * is declared in the first), a `boundedContext.ts` with its error codes and\n * wait helpers, and for each aggregate its `aggregate.ts`,\n * `commandClient.ts` and `queryClient.ts`.\n *\n * @param manifest - The Manifest\n * @returns The model and the warnings it raised\n */\nexport function analyzeManifest(manifest: ManifestDocument): {\n model: ManifestModel;\n warnings: string[];\n} {\n const types = new SchemaTypes(manifest.$defs ?? {});\n const contexts = manifest.contexts;\n const reach = new Map<string, string>();\n for (const context of contexts) {\n const roots = (context.aggregates ?? []).flatMap(aggregate =>\n aggregateRoots(types, aggregate),\n );\n for (const key of types.closure(roots).sort(compareNames)) {\n if (!reach.has(key)) reach.set(key, context.name);\n }\n }\n const keys = [...reach.keys()].filter(\n key => types.schemaOf(key) && !types.inlined(key),\n );\n types.name([...keys].sort(compareNames));\n\n const typeModels: TypeModel[] = keys\n .map(key => typeModel(types, key, `${reach.get(key)}/types.ts`))\n .sort(\n (left, right) =>\n compareNames(left.file, right.file) ||\n compareNames(left.name, right.name),\n );\n\n const contextModels = contexts.map(context => contextModel(types, context));\n return {\n model: {\n ...(manifest.service?.name ? { service: manifest.service.name } : {}),\n types: typeModels,\n contexts: contextModels,\n },\n warnings: [...new Set(types.warnings)],\n };\n}\n\nfunction typeModel(types: SchemaTypes, key: string, file: string): TypeModel {\n const schema = types.schemaOf(key)!;\n const name = types.names.get(key)!;\n const description =\n typeof schema.description === 'string' ? schema.description : undefined;\n const references = [...types.namedReferences(schema)]\n .map(ref => types.names.get(ref))\n .filter((ref): ref is string => ref !== undefined && ref !== name);\n const base = {\n key,\n name,\n file,\n ...(description === undefined ? {} : { description }),\n references: [...new Set(references)].sort(compareNames),\n };\n if (types.isInterface(schema)) {\n // A typed index signature would have to admit every property's type.\n const extra = types.additional(schema, key);\n return {\n ...base,\n properties: types.properties(schema, key),\n ...(extra === undefined ? {} : { type: 'unknown' }),\n };\n }\n return { ...base, type: types.type(schema, key) };\n}\n\nfunction contextModel(\n types: SchemaTypes,\n context: ManifestContext,\n): ContextModel {\n const prefix = `${context.name}.`;\n return {\n name: context.name,\n ...(context.description ? { description: context.description } : {}),\n typeName: toTypeIdentifier(pascalCase(context.name)),\n constantName: upperSnakeCase(context.name),\n directory: context.name,\n errors: (context.errors ?? []).map(error => ({\n member:\n upperSnakeCase(\n (error.code.startsWith(prefix)\n ? error.code.slice(prefix.length)\n : error.code\n ).split(/[^A-Za-z0-9]+/),\n ) || 'ERROR',\n code: error.code,\n status: error.status,\n ...(error.description ? { description: error.description } : {}),\n })),\n subscriptions: [\n ...new Set((context.subscriptions ?? []).map(s => s.name)),\n ].sort(compareNames),\n aggregates: (context.aggregates ?? []).map(aggregate =>\n aggregateModel(types, context, aggregate),\n ),\n };\n}\n\nfunction typeOfRef(types: SchemaTypes, ref: string, where: string): string {\n const key = schemaKey(ref);\n return key === undefined ? 'unknown' : types.refType(key, where);\n}\n\nfunction aggregateModel(\n types: SchemaTypes,\n context: ManifestContext,\n aggregate: ManifestAggregate,\n): AggregateModel {\n const where = `${context.name}.${aggregate.name}`;\n const typeName = toTypeIdentifier(pascalCase(aggregate.name));\n const generated = new Set(lifecycleBodies(types, aggregate));\n const lifecycle: LifecycleModel[] = (aggregate.lifecycle ?? [])\n .filter(name => LIFECYCLE_COMMANDS.has(name))\n .map(name => {\n const simple = name.split('.').pop()!;\n const description = types.schemaOf(name)?.description;\n return {\n name,\n member: upperSnakeCase(simple),\n method: toIdentifier(camelCase(simple)),\n ...(generated.has(name)\n ? { bodyType: types.refType(name, where), bodyGenerated: true }\n : LIFECYCLE_BODIES[name]\n ? { bodyType: LIFECYCLE_BODIES[name] }\n : {}),\n ...(typeof description === 'string' ? { description } : {}),\n };\n });\n const taken = new Set(lifecycle.map(item => item.method));\n const commands: CommandModel[] = (aggregate.commands ?? []).map(command => {\n let method = toIdentifier(camelCase(command.name));\n if (taken.has(method) || method === 'gateway') method = `${method}Command`;\n taken.add(method);\n const member = upperSnakeCase(command.name);\n const routes = (command.routes ?? []).filter(\n route => route.method === 'POST',\n );\n const byId = routes.find(route => route.path.includes('{id}'));\n const unaddressed = routes.find(route => !route.path.includes('{id}'));\n const key = schemaKey(command.schema);\n return {\n name: command.name,\n method,\n ...(byId ? { byIdPath: { member, path: byId.path } } : {}),\n ...(unaddressed\n ? {\n unaddressedPath: {\n member: byId ? `${member}_WITHOUT_ID` : member,\n path: unaddressed.path,\n },\n }\n : {}),\n bodyType: typeOfRef(types, command.schema, `${where}.${command.name}`),\n bodyOptional: emptyBody(\n types,\n key === undefined ? undefined : types.schemaOf(key),\n ),\n creation: command.creation ?? 'NONE',\n mounted: command.mounted ?? false,\n produces: command.produces ?? [],\n ...(command.description ? { description: command.description } : {}),\n ...(types.textNumbers({ $ref: command.schema }) === undefined\n ? {}\n : { bodyNumbers: true }),\n };\n });\n const stateNumbers = types.textNumbers({ $ref: aggregate.state.schema });\n const eventNumbers = Object.fromEntries(\n (aggregate.events ?? []).flatMap(event => {\n const mark = types.textNumbers({ $ref: event.schema });\n return mark === undefined\n ? []\n : [[wireNameOf(context, aggregate, event.name), mark]];\n }),\n );\n const commandNumbers = Object.fromEntries(\n (aggregate.commands ?? []).flatMap(command => {\n const mark = types.textNumbers({ $ref: command.schema });\n return mark === undefined ? [] : [[command.name, mark]];\n }),\n );\n const textNumbers = {\n ...(stateNumbers === undefined ? {} : { state: stateNumbers }),\n ...(Object.keys(eventNumbers).length === 0 ? {} : { events: eventNumbers }),\n ...(Object.keys(commandNumbers).length === 0\n ? {}\n : { commands: commandNumbers }),\n };\n const stateKey = schemaKey(aggregate.state.schema);\n const stateSchema =\n stateKey === undefined ? undefined : types.schemaOf(stateKey);\n return {\n context: context.name,\n name: aggregate.name,\n ...(aggregate.description ? { description: aggregate.description } : {}),\n typeName,\n directory: `${context.name}/${aggregate.name}`,\n ownership: aggregate.ownership ?? 'OWNER',\n snapshot: aggregate.snapshot?.enabled ?? true,\n stateType: typeOfRef(types, aggregate.state.schema, `${where} state`),\n stateFields:\n stateSchema === undefined\n ? []\n : types.fields({ $ref: aggregate.state.schema }, 'state'),\n commands,\n events: (aggregate.events ?? []).map(event => ({\n name: event.name,\n wireName: wireNameOf(context, aggregate, event.name),\n revision: event.revision ?? 1,\n type: typeOfRef(types, event.schema, `${where}.${event.name}`),\n })),\n lifecycle,\n queryModels: (aggregate.queries ?? []).map(query => query.model),\n ...(Object.keys(textNumbers).length === 0 ? {} : { textNumbers }),\n };\n}\n\n/** The name the server sends an event by: `context.aggregate.Event`, or a name already qualified. */\nfunction wireNameOf(\n context: ManifestContext,\n aggregate: ManifestAggregate,\n name: string,\n): string {\n return name.includes('.')\n ? name\n : `${context.name}.${aggregate.name}.${name}`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { join } from 'node:path';\nimport { escapeJsDoc } from '../emit/jsdoc';\nimport type { ModuleBuilder, ModuleSet } from '../emit/moduleBuilder';\nimport { relativeModuleSpecifier } from '../emit/imports';\nimport type {\n AggregateModel,\n CommandModel,\n ContextModel,\n ManifestModel,\n TypeModel,\n TextNumbersModel,\n} from '../manifest/analyze';\nimport {\n camelCase,\n quoteStringLiteral,\n resolvePropertyName,\n} from '../naming/naming';\n\n/** The entry of the client every generated module imports from. */\nexport const WOW_CLIENT = '@ahoo-wang/wow-client';\n\n/** A doc comment of the lines given, those without text left out. */\nfunction doc(lines: readonly (string | undefined)[], indent = ''): string {\n const text = lines\n .filter((line): line is string => typeof line === 'string' && line !== '')\n .flatMap(line => escapeJsDoc(line).split('\\n'));\n if (text.length === 0) return '';\n if (text.length === 1) return `${indent}/** ${text[0]} */\\n`;\n return `${indent}/**\\n${text.map(line => `${indent} * ${line}`.trimEnd()).join('\\n')}\\n${indent} */\\n`;\n}\n\n/**\n * Adds a statement set off from the one before by a blank line, as the\n * structures the other emitters add are.\n */\nfunction addStatement(module: ModuleBuilder, statement: string): void {\n module.add(`\\n${statement}`);\n}\n\nfunction union(members: readonly string[]): string {\n return members.length === 0 ? 'never' : members.join(' | ');\n}\n\n/** Where each generated type is declared, by its name. */\ntype TypeFiles = ReadonlyMap<string, string>;\n\n/**\n * Imports the generated types a module names from the files declaring them.\n */\nfunction importTypes(\n module: ModuleBuilder,\n outputDir: string,\n files: TypeFiles,\n names: readonly string[],\n ownFile?: string,\n): void {\n const byFile = new Map<string, string[]>();\n for (const name of new Set(names)) {\n const file = files.get(name);\n if (file === undefined || file === ownFile) continue;\n byFile.set(file, [...(byFile.get(file) ?? []), name]);\n }\n for (const [file, imported] of byFile) {\n module.imports.add(\n relativeModuleSpecifier(module.directoryPath, join(outputDir, file)),\n imported,\n );\n }\n}\n\n/**\n * Describes every file a Manifest generates to its module (decision D74,\n * roadmap 5a.3): the types of each bounded context, its error codes and wait\n * helpers, and the aggregate, command and query clients of each aggregate,\n * all on `@ahoo-wang/wow-client`.\n *\n * @param model - What the Manifest generates\n * @param modules - The modules of the run\n * @param outputDir - The output directory\n */\nexport function emitManifestGeneration(\n model: ManifestModel,\n modules: ModuleSet,\n outputDir: string,\n): void {\n const files: TypeFiles = new Map(\n model.types.map(type => [type.name, type.file]),\n );\n for (const type of model.types) {\n emitType(modules.module(type.file), type, files, outputDir);\n }\n for (const context of model.contexts) {\n emitBoundedContext(context, modules);\n for (const aggregate of context.aggregates) {\n emitAggregate(aggregate, context, modules, files, outputDir);\n emitCommandClient(aggregate, modules, files, outputDir);\n emitQueryClient(aggregate, modules, files, outputDir);\n }\n }\n}\n\nfunction emitType(\n module: ModuleBuilder,\n type: TypeModel,\n files: TypeFiles,\n outputDir: string,\n): void {\n importTypes(module, outputDir, files, type.references, type.file);\n const comment = doc([type.description, `- key: \\`${type.key}\\``]);\n if (type.properties === undefined) {\n addStatement(module, `${comment}export type ${type.name} = ${type.type};`);\n return;\n }\n const members = type.properties.map(\n property =>\n `${doc([property.description], ' ')} ${property.name}${property.optional ? '?' : ''}: ${property.type};`,\n );\n if (type.type !== undefined) members.push(` [key: string]: ${type.type};`);\n addStatement(\n module,\n `${comment}export interface ${type.name} {\\n${members.join('\\n')}\\n}`,\n );\n}\n\nfunction emitBoundedContext(context: ContextModel, modules: ModuleSet): void {\n const module = modules.module(`${context.directory}/boundedContext.ts`);\n const constant = `${context.constantName}_BOUNDED_CONTEXT`;\n module.imports.add(WOW_CLIENT, ['Hop', 'wait']);\n addStatement(\n module,\n `${doc([`The bounded context \\`${context.name}\\`.`, context.description])}export const ${constant} = ${quoteStringLiteral(context.name)};`,\n );\n const errors = context.errors.map(\n error =>\n `${doc([`${error.status}: ${error.description ?? error.code}`], ' ')} ${error.member}: ${quoteStringLiteral(error.code)},`,\n );\n addStatement(\n module,\n `${doc([\n `The domain error codes of \\`${context.name}\\`, each a problem's \\`code\\` with the status the Manifest gives it.`,\n ])}export const ${context.typeName}ErrorCodes = {\\n${errors.join('\\n')}\\n} as const;`,\n );\n addStatement(\n module,\n `${doc([`A {@link ${context.typeName}ErrorCodes} value.`])}export type ${context.typeName}ErrorCode = (typeof ${context.typeName}ErrorCodes)[keyof typeof ${context.typeName}ErrorCodes];`,\n );\n const hasSubscriptions = context.subscriptions.length > 0;\n if (hasSubscriptions) {\n addStatement(\n module,\n `${doc([`The subscriptions of \\`${context.name}\\` a \\`handled\\` hop names.`])}export type ${context.typeName}Subscription = ${union(context.subscriptions.map(quoteStringLiteral))};`,\n );\n }\n const hops = [\n ` /** Until a command of \\`${context.name}\\` passed admission. */\\n accepted: (): Hop => wait.accepted(${constant}),`,\n ` /** Until a command's events are appended to the log of \\`${context.name}\\`. */\\n committed: (): Hop => wait.committed(${constant}),`,\n ` /** Until the snapshot of \\`${context.name}\\` holds the commit. */\\n snapshot: (): Hop => wait.snapshot(${constant}),`,\n ];\n if (hasSubscriptions) {\n hops.push(\n ` /** Until a subscription of \\`${context.name}\\` handled the commit. */\\n handled: (subscription: ${context.typeName}Subscription): Hop => wait.handled(subscription, ${constant}),`,\n );\n }\n addStatement(\n module,\n `${doc([`The hops of a wait chain (\\`Wow-Wait\\`) in \\`${context.name}\\`.`])}export const ${camelCase(context.name)}Wait = {\\n${hops.join('\\n')}\\n} as const;`,\n );\n}\n\n/** A TypeScript literal of exact-number marks: `{ price: true, lines: { '*': { amount: true } } }`. */\nfunction textNumbersLiteral(marks: TextNumbersModel): string {\n if (marks === true) return 'true';\n return `{ ${Object.entries(marks)\n .map(\n ([member, mark]) =>\n `${resolvePropertyName(member)}: ${textNumbersLiteral(mark)}`,\n )\n .join(', ')} }`;\n}\n\n/** The `textNumbers` member of an aggregate constant, or nothing when it has none. */\nfunction textNumbersMember(aggregate: AggregateModel): string {\n const numbers = aggregate.textNumbers;\n if (numbers === undefined) return '';\n const groups = (['state', 'events', 'commands'] as const).flatMap(group => {\n const value = numbers[group];\n if (value === undefined) return [];\n if (group === 'state')\n return [` state: ${textNumbersLiteral(value as TextNumbersModel)},`];\n const entries = Object.entries(\n value as Readonly<Record<string, TextNumbersModel>>,\n ).map(\n ([name, mark]) =>\n ` ${resolvePropertyName(name)}: ${textNumbersLiteral(mark)},`,\n );\n return [` ${group}: {\\n${entries.join('\\n')}\\n },`];\n });\n return ` textNumbers: {\\n${groups.join('\\n')}\\n },\\n`;\n}\n\nfunction emitAggregate(\n aggregate: AggregateModel,\n context: ContextModel,\n modules: ModuleSet,\n files: TypeFiles,\n outputDir: string,\n): void {\n const module = modules.module(`${aggregate.directory}/aggregate.ts`);\n const name = aggregate.typeName;\n addStatement(\n module,\n `${doc([\n `The aggregate \\`${aggregate.context}.${aggregate.name}\\`.`,\n aggregate.description,\n ])}export const ${name}Aggregate = {\\n context: ${quoteStringLiteral(context.name)},\\n name: ${quoteStringLiteral(aggregate.name)},\\n path: ${quoteStringLiteral(`/${context.name}/${aggregate.name}`)},\\n ownership: ${quoteStringLiteral(aggregate.ownership)},\\n snapshot: ${aggregate.snapshot},\\n${textNumbersMember(aggregate)}} as const;`,\n );\n addStatement(\n module,\n `${doc([\n `The \\`state.*\\` paths of \\`${aggregate.name}\\`'s snapshots a query filters, sorts and projects on.`,\n ])}export type ${name}StateField = ${union(aggregate.stateFields.map(quoteStringLiteral))};`,\n );\n const events = aggregate.events.map(\n event => `EventView<${quoteStringLiteral(event.wireName)}, ${event.type}>`,\n );\n module.imports.add(\n WOW_CLIENT,\n events.length > 0 ? ['EventView', 'SystemEvent'] : ['SystemEvent'],\n );\n addStatement(\n module,\n `${doc([\n `The events of \\`${aggregate.name}\\`, named as the server sends them, \\`${aggregate.context}.${aggregate.name}.<Event>\\` at its current revision (the \\`events\\` query upgrades older records), and the system events every aggregate has.`,\n ])}export type ${name}Event = ${union([...events, 'SystemEvent'])};`,\n );\n importTypes(\n module,\n outputDir,\n files,\n aggregate.events.map(event => event.type),\n );\n}\n\nfunction commandDoc(command: CommandModel): string {\n const routes = [command.byIdPath, command.unaddressedPath]\n .filter(path => path !== undefined)\n .map(path => `\\`POST ${path.path}\\``)\n .join(', ');\n const creates =\n command.creation === 'REQUIRED'\n ? 'Creates the aggregate.'\n : command.creation === 'ALLOWED'\n ? 'Creates the aggregate, or acts on the one that exists.'\n : undefined;\n return doc(\n [\n command.description,\n `\\`${command.name}\\`${command.mounted ? ', mounted (a transformer finds its aggregate)' : ''}: ${routes}.`,\n creates,\n command.produces.length > 0\n ? `Produces ${command.produces.map(event => `\\`${event}\\``).join(', ')}.`\n : undefined,\n ],\n ' ',\n );\n}\n\nfunction commandMethods(\n command: CommandModel,\n paths: string,\n stream: boolean,\n aggregateConstant: string,\n): string {\n // A body with exact numbers sends them unquoted: its marks go with the options.\n const numbers = command.bodyNumbers\n ? `, bodyNumbers: ${aggregateConstant}.textNumbers.commands.${resolvePropertyName(command.name) === command.name ? command.name : `[${quoteStringLiteral(command.name)}]`}`\n : '';\n const body = command.bodyType === 'unknown' ? 'object' : command.bodyType;\n const bodyParam = command.bodyOptional\n ? `body: ${body} = {}`\n : `body: ${body}`;\n const call = stream ? 'stream' : 'send';\n const returns = stream\n ? 'Promise<CommandResultStream>'\n : 'Promise<CommandResult>';\n const name = stream ? `${command.method}Stream` : command.method;\n const comment = stream\n ? doc(\n [\n `\\`${command.name}\\`, answered as one result per hop of its wait (\\`text/event-stream\\`).`,\n ],\n ' ',\n )\n : commandDoc(command);\n const byId = command.byIdPath;\n const unaddressed = command.unaddressedPath;\n if (byId && unaddressed) {\n return `${comment} ${name}(${bodyParam}, options?: CreateCommandOptions): ${returns} {\\n return this.gateway.${call}(options?.id === undefined ? ${paths}.${unaddressed.member} : ${paths}.${byId.member}, body, ${numbers ? `{ ...options${numbers} }` : 'options'});\\n }`;\n }\n if (byId) {\n return `${comment} ${name}(id: string, ${bodyParam}, options?: CommandOptions): ${returns} {\\n return this.gateway.${call}(${paths}.${byId.member}, body, { ...options, id${numbers} });\\n }`;\n }\n return `${comment} ${name}(${bodyParam}, options?: CommandOptions): ${returns} {\\n return this.gateway.${call}(${paths}.${unaddressed!.member}, body, ${numbers ? `{ ...options${numbers} }` : 'options'});\\n }`;\n}\n\nfunction emitCommandClient(\n aggregate: AggregateModel,\n modules: ModuleSet,\n files: TypeFiles,\n outputDir: string,\n): void {\n const module = modules.module(`${aggregate.directory}/commandClient.ts`);\n const name = aggregate.typeName;\n const paths = `${name}CommandPaths`;\n const commands = aggregate.commands.filter(\n command => command.byIdPath || command.unaddressedPath,\n );\n const members = commands.flatMap(command =>\n [command.byIdPath, command.unaddressedPath]\n .filter(path => path !== undefined)\n .map(path => ` ${path.member}: ${quoteStringLiteral(path.path)},`),\n );\n addStatement(\n module,\n `${doc([`The command routes of \\`${aggregate.context}.${aggregate.name}\\`.`])}export const ${paths} = {\\n${members.join('\\n')}\\n} as const;`,\n );\n const methods = commands.flatMap(command => [\n commandMethods(command, paths, false, `${name}Aggregate`),\n commandMethods(command, paths, true, `${name}Aggregate`),\n ]);\n const client = ['CommandGateway', 'CommandResult', 'WowClientOptions'];\n if (commands.length > 0) client.push('CommandResultStream');\n if (commands.some(command => command.byIdPath && command.unaddressedPath)) {\n client.push('CreateCommandOptions');\n }\n if (\n commands.some(command => !(command.byIdPath && command.unaddressedPath)) ||\n aggregate.lifecycle.length > 0\n ) {\n client.push('CommandOptions');\n }\n const lifecycleTypes: string[] = [];\n for (const lifecycle of aggregate.lifecycle) {\n client.push('LifecycleCommands');\n if (lifecycle.bodyType) {\n (lifecycle.bodyGenerated ? lifecycleTypes : client).push(\n lifecycle.bodyType,\n );\n }\n const params = lifecycle.bodyType\n ? `id: string, body: ${lifecycle.bodyType}, options?: CommandOptions`\n : `id: string, options?: CommandOptions`;\n methods.push(\n `${doc([lifecycle.description, `The lifecycle command \\`${lifecycle.name}\\`.`], ' ')} ${lifecycle.method}(${params}): Promise<CommandResult> {\\n return this.gateway.lifecycle(${name}Aggregate.path, id, LifecycleCommands.${lifecycle.member}, ${lifecycle.bodyType ? 'body' : 'undefined'}, options);\\n }`,\n );\n }\n if (\n aggregate.lifecycle.length > 0 ||\n commands.some(command => command.bodyNumbers)\n ) {\n module.imports.add('./aggregate.js', [`${name}Aggregate`]);\n }\n module.imports.add(WOW_CLIENT, [...new Set(client)].sort());\n importTypes(module, outputDir, files, [\n ...commands.map(command => command.bodyType),\n ...lifecycleTypes,\n ]);\n addStatement(\n module,\n `${doc([\n `Sends the commands of \\`${aggregate.context}.${aggregate.name}\\`; a command that did not succeed rejects with a \\`WowProblemError\\` holding its result.`,\n ])}export class ${name}CommandClient {\\n readonly gateway: CommandGateway;\\n\\n /** @param options - How the service is reached */\\n constructor(options?: WowClientOptions) {\\n this.gateway = new CommandGateway(options);\\n }\\n\\n${methods.join('\\n\\n')}\\n}`,\n );\n}\n\nfunction emitQueryClient(\n aggregate: AggregateModel,\n modules: ModuleSet,\n files: TypeFiles,\n outputDir: string,\n): void {\n const module = modules.module(`${aggregate.directory}/queryClient.ts`);\n const name = aggregate.typeName;\n const state = aggregate.stateType;\n const client = ['StateClient', 'WowClientOptions'];\n const aggregateNames = [`${name}Aggregate`, `${name}Event`];\n const constructor = ` /** @param options - How the service is reached */\\n constructor(options?: WowClientOptions) {\\n super(${name}Aggregate, options);\\n }`;\n if (aggregate.queryModels.includes('snapshot')) {\n client.push('SnapshotQueryClient');\n aggregateNames.push(`${name}StateField`);\n addStatement(\n module,\n `${doc([`Queries the snapshots of \\`${aggregate.context}.${aggregate.name}\\`: \\`POST /${aggregate.context}/${aggregate.name}/snapshot/query\\`.`])}export class ${name}SnapshotQueryClient extends SnapshotQueryClient<${state}, ${name}StateField> {\\n${constructor}\\n}`,\n );\n }\n if (aggregate.queryModels.includes('events')) {\n client.push('EventQueryClient');\n addStatement(\n module,\n `${doc([`Queries the event streams of \\`${aggregate.context}.${aggregate.name}\\`, one record per commit: \\`POST /${aggregate.context}/${aggregate.name}/events/query\\`.`])}export class ${name}EventQueryClient extends EventQueryClient<${name}Event> {\\n${constructor}\\n}`,\n );\n }\n addStatement(\n module,\n `${doc([`Reads the states of \\`${aggregate.context}.${aggregate.name}\\`, at a version or a time, and their traces: \\`GET /${aggregate.context}/${aggregate.name}/{id}/state\\`.`])}export class ${name}StateClient extends StateClient<${state}, ${name}Event> {\\n${constructor}\\n}`,\n );\n module.imports.add(WOW_CLIENT, client.sort());\n module.imports.add('./aggregate.js', aggregateNames);\n importTypes(module, outputDir, files, [state]);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Components, OpenAPI } from '@ahoo-wang/fetcher-openapi';\nimport type { OperationEndpoint } from './operations';\nimport { extractOperationEndpoints } from './operations';\n\n/**\n * A parsed OpenAPI document as the generator reads it: the document itself,\n * which nothing changes, and its operations, listed once.\n */\nexport interface OpenApiDocument {\n /** The parsed document. Read only: every stage reads the same one. */\n readonly openAPI: OpenAPI;\n /** Its components, if it has any. */\n readonly components?: Components;\n /**\n * Every operation with its method and path, the path item's parameters\n * merged into its own (an operation's parameter overrides the path item's\n * one of the same name and location), ordered by operation id, then path,\n * then method.\n */\n readonly endpoints: readonly OperationEndpoint[];\n}\n\n/**\n * Reads a parsed document: lists its operations once, for every stage.\n *\n * @param openAPI - The parsed document; left unchanged\n */\nexport function openApiDocument(openAPI: OpenAPI): OpenApiDocument {\n return {\n openAPI,\n components: openAPI.components,\n endpoints: extractOperationEndpoints(openAPI.paths, openAPI.components),\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isAbsolute, join, relative, resolve, sep } from 'path';\nimport type { Project, SourceFile } from 'ts-morph';\nimport { ts } from 'ts-morph';\nimport { errorMessage, GeneratorError } from '../api/errors';\nimport { combinePaths } from '../naming/paths';\n\n/** The manifest that records the files a generation wrote, and their hashes. */\nexport const GENERATION_MANIFEST = '.wow-generator.json';\n\n/**\n * The version of the manifest format this generator reads and writes. A\n * change a reader of this version would misread bumps it; see section 3 of\n * docs/design/architecture.md.\n */\nexport const MANIFEST_VERSION = 1;\n\n/**\n * The output directory of one generation: which files it owns, which of the\n * files an earlier run wrote it may remove, and writing them.\n *\n * The manifest (`.wow-generator.json`) records every file a run wrote and\n * the hash it wrote. A file of the last run that this run does not write is\n * stale; it is removed only if its bytes are still the ones recorded, so a\n * hand-edited file is never lost. A file the manifest does not name is never\n * touched.\n *\n * One store per run: {@link open} reads the manifest, {@link claim} hands\n * out the files the run writes, {@link commit} writes them, removes the stale\n * ones and writes the new manifest.\n */\nexport class OutputStore {\n /** The files this run writes, by absolute path. */\n private readonly written = new Set<string>();\n /** Files of the last run this run does not write and may remove. */\n private readonly stale = new Set<string>();\n\n private constructor(\n private readonly project: Project,\n /** The output directory as the caller named it. */\n private readonly outputPath: string,\n /** The output directory, absolute. */\n private readonly outputDir: string,\n /** The files of the last run, with the hash each was written with. */\n private readonly previous: ReadonlyMap<string, string>,\n ) {}\n\n /**\n * Reads the manifest of an output directory and takes the files it names\n * out of the project: a run writes its files afresh.\n *\n * @param project - The project the run writes into\n * @param outputDir - The output directory, absolute or relative to the\n * project's working directory\n * @param last - The store of the last run into the same project, whose\n * files, written or only drafted, leave the project too\n * @throws GeneratorError (`output`) when the manifest cannot be parsed, was\n * written by a newer generator, is not one, or names a file outside the\n * output directory\n */\n static open(\n project: Project,\n outputDir: string,\n last?: OutputStore,\n ): OutputStore {\n const fs = project.getFileSystem();\n const outputPath = outputDir;\n outputDir = resolve(fs.getCurrentDirectory(), outputDir);\n const manifestPath = join(outputDir, GENERATION_MANIFEST);\n const previous = new Map<string, string>();\n if (fs.fileExistsSync(manifestPath)) {\n const manifest = readManifest(\n manifestPath,\n fs.readFileSync(manifestPath),\n );\n for (const [path, hash] of Object.entries(manifest.files)) {\n const fileName = resolve(outputDir, path);\n assertWithinOutputDir(outputDir, fileName);\n if (\n isAbsolute(path) ||\n !path.endsWith('.ts') ||\n typeof hash !== 'string' ||\n !/^[a-f0-9]{64}$/.test(hash)\n ) {\n throw new GeneratorError(\n 'output',\n `Invalid generated file entry in ${manifestPath}: ${path}`,\n );\n }\n previous.set(fileName, hash);\n }\n }\n // Looked up by the files the project holds, not by path: where the file\n // system ignores case, ts-morph remembers the case of a path it is asked\n // for, and a file this run creates under that path in another case\n // would take the old case.\n const leaving = new Set([...(last?.written ?? []), ...previous.keys()]);\n for (const file of project.getSourceFiles()) {\n if (leaving.has(file.getFilePath())) file.forget();\n }\n return new OutputStore(project, outputPath, outputDir, previous);\n }\n\n /** The files this run writes, by absolute path. */\n get files(): ReadonlySet<string> {\n return this.written;\n }\n\n /**\n * The source file of a path under a directory of the output, claimed for\n * this run: the first claim empties it, and {@link commit} writes it.\n *\n * @param filePath - The path, relative to `directory`\n * @param directory - The output directory as the caller named it, or a\n * directory under it\n * @throws GeneratorError (`output`) when the path resolves outside it\n */\n claim(filePath: string, directory: string = this.outputPath): SourceFile {\n const fileName = combinePaths(directory, filePath);\n assertWithinOutputDir(directory, fileName);\n const file =\n this.project.getSourceFile(fileName) ??\n this.project.createSourceFile(fileName, '', { overwrite: true });\n const path = file.getFilePath();\n if (!this.written.has(path)) {\n file.removeText();\n this.written.add(path);\n }\n return file;\n }\n\n /**\n * Takes the files of the last run this run does not write out of the\n * project, when they are still as that run wrote them, so the indexes do\n * not export them; {@link commit} removes them. Nothing on disk changes.\n */\n forgetStale(): void {\n for (const [path, hash] of this.previous) {\n if (!this.written.has(path) && this.isUnchanged(path, hash)) {\n this.stale.add(path);\n }\n }\n // By exact path: a file this run writes may differ from a stale one only\n // in case, which ts-morph matches where the file system ignores case.\n for (const file of this.project.getSourceFiles()) {\n if (this.stale.has(file.getFilePath())) file.forget();\n }\n }\n\n /**\n * Writes the files this run claimed, then removes the stale ones that are\n * still as the last run wrote them, then writes the manifest and deletes a\n * pre-Wow one. A stale file this run writes again under a name that\n * differs only in case is removed before the writing instead.\n *\n * @param signal - Stops the run after the files are written: nothing is\n * removed and the manifest stays the last run's, so an interrupted run\n * never records files it did not finish\n * @throws GeneratorError (`output`) when writing or removing a file fails;\n * the signal's reason when it was aborted\n */\n async commit(signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted();\n const fs = this.project.getFileSystem();\n // A stale file whose path differs from a written one only in case is the\n // same file where the file system ignores case (macOS, Windows): writing\n // first would keep the old name, and removing it after would remove the\n // new file. It goes first, so the new name is the one on disk.\n const written = new Set([...this.written].map(path => path.toLowerCase()));\n for (const path of this.stale) {\n if (\n !this.written.has(path) &&\n written.has(path.toLowerCase()) &&\n this.isUnchanged(path, this.previous.get(path)!)\n ) {\n await attempt('delete', path, () => fs.delete(path));\n this.stale.delete(path);\n }\n }\n const files = [...this.written]\n .sort()\n .map(path => this.project.getSourceFileOrThrow(path));\n const saved = await Promise.allSettled(files.map(file => file.save()));\n saved.forEach((result, index) => {\n if (result.status === 'rejected') {\n throw outputFailure('write', files[index].getFilePath(), result.reason);\n }\n });\n signal?.throwIfAborted();\n for (const path of this.stale) {\n if (\n !this.written.has(path) &&\n this.isUnchanged(path, this.previous.get(path)!)\n ) {\n await attempt('delete', path, () => fs.delete(path));\n }\n }\n const manifestPath = join(this.outputDir, GENERATION_MANIFEST);\n const manifest =\n JSON.stringify(\n {\n version: MANIFEST_VERSION,\n files: Object.fromEntries(\n files.map(file => [\n relative(this.outputDir, file.getFilePath()).split(sep).join('/'),\n fileHash(fs.readFileSync(file.getFilePath())),\n ]),\n ),\n },\n null,\n 2,\n ) + '\\n';\n await attempt('write', manifestPath, async () => {\n fs.mkdirSync(this.outputDir);\n await fs.writeFile(manifestPath, manifest);\n });\n }\n\n /**\n * Tells whether a file of the last run is still as it wrote it: present,\n * inside the output directory once links are followed, and of the hash the\n * manifest records.\n */\n private isUnchanged(path: string, hash: string): boolean {\n const fs = this.project.getFileSystem();\n if (!fs.fileExistsSync(path)) return false;\n assertWithinOutputDir(\n fs.realpathSync(this.outputDir),\n fs.realpathSync(path),\n );\n return fileHash(fs.readFileSync(path)) === hash;\n }\n}\n\n/**\n * Parses the text of a manifest, telling apart the failures a user resolves\n * differently: a file that is not JSON (a merge conflict, most often), one a\n * newer generator wrote, and one that is not a manifest at all.\n *\n * @throws GeneratorError (`output`) naming the manifest and what to do\n */\nfunction readManifest(\n manifestPath: string,\n text: string,\n): { files: Record<string, unknown> } {\n const remedy =\n 'delete it; without it this run cannot remove the stale files of the last run';\n let manifest;\n try {\n manifest = JSON.parse(text);\n } catch (error) {\n throw new GeneratorError(\n 'output',\n `Cannot parse the generation manifest ${manifestPath}: ${errorMessage(error)}. Resolve the merge conflict in it if it has one, or ${remedy}.`,\n { cause: error },\n );\n }\n const version = manifest?.version;\n if (\n typeof version === 'number' &&\n Number.isInteger(version) &&\n version > MANIFEST_VERSION\n ) {\n throw new GeneratorError(\n 'output',\n `The generation manifest ${manifestPath} was written by a newer wow-generator (manifest version ${version}); this one reads version ${MANIFEST_VERSION}. Upgrade wow-generator.`,\n );\n }\n if (\n version !== MANIFEST_VERSION ||\n !manifest.files ||\n typeof manifest.files !== 'object' ||\n Array.isArray(manifest.files)\n ) {\n throw new GeneratorError(\n 'output',\n `Invalid generation manifest ${manifestPath}: expected \"version\": ${MANIFEST_VERSION} and a \"files\" object. Restore it from version control, or ${remedy}.`,\n );\n }\n return manifest;\n}\n\nfunction fileHash(text: string): string {\n if (!ts.sys.createSHA256Hash) {\n throw new Error('SHA-256 hashing is unavailable in this environment.');\n }\n return ts.sys.createSHA256Hash(text);\n}\n\n/**\n * Reports a failure to change the output directory as an `output` error the\n * user can act on, keeping one that already is a {@link GeneratorError}.\n */\nfunction outputFailure(\n action: 'write' | 'delete',\n path: string,\n error: unknown,\n): GeneratorError {\n if (error instanceof GeneratorError) return error;\n return new GeneratorError(\n 'output',\n `Cannot ${action} ${path}: ${errorMessage(error)}`,\n { cause: error },\n );\n}\n\nasync function attempt(\n action: 'write' | 'delete',\n path: string,\n change: () => void | Promise<void>,\n): Promise<void> {\n try {\n await change();\n } catch (error) {\n throw outputFailure(action, path, error);\n }\n}\n\n/**\n * Guards against path traversal: `filePath` derives from a (possibly remote /\n * attacker-controlled) OpenAPI schema key. After joining with `outputDir`, the\n * resolved path must remain INSIDE `outputDir` — otherwise a key like\n * `../../etc/cron.d/pwn` would let `createSourceFile` write or clobber files\n * outside the output directory.\n *\n * `fileName` is the value actually handed to ts-morph (`combinePaths(outputDir,\n * filePath)`), so it is what gets written. We resolve THAT path (not a second\n * join against outputDir) and verify it stays under outputDir — otherwise the\n * checked path and the written path can diverge for relative outputDir values.\n *\n * @throws GeneratorError (`output`) if the resolved path escapes `outputDir`\n */\nfunction assertWithinOutputDir(outputDir: string, fileName: string): void {\n // `combinePaths` yields a URL-style path (forward slashes); normalize to the\n // platform filesystem path before resolving.\n const normalized = fileName.split('/').join(sep);\n const base = resolve(outputDir);\n // fileName already includes the outputDir prefix (it is the write target),\n // so resolve it directly (relative to cwd, or absolute as-is) — do NOT join\n // base again, which would double the prefix and check the wrong location.\n const target = resolve(normalized);\n const rel = relative(base, target);\n // An empty relative path means target === base (a directory, not a file);\n // a path starting with '..' or an absolute path escapes the base.\n const escapes = rel === '' || rel.startsWith('..') || isAbsolute(rel);\n if (escapes) {\n throw new GeneratorError(\n 'output',\n `Path traversal detected: \"${fileName}\" resolves outside the output directory \"${outputDir}\".`,\n );\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Project } from 'ts-morph';\nimport type { GeneratorOptions } from '../api/options';\n\n/**\n * Test seam: an option under this key hands a generator the ts-morph project\n * to write into, such as an in-memory one, instead of one it reads from\n * `tsConfigFilePath`. A symbol the package does not export, so it is no part\n * of the public options. It lives apart from `CodeGenerator`, whose\n * declaration therefore names neither it nor ts-morph, whose major version it\n * would follow.\n */\nexport const PROJECT_SEAM = Symbol('project');\n\n/**\n * The CLI's seam: an option under this key stops a run when it aborts, as\n * Ctrl-C does. A run stops at its next step; once it writes, it finishes\n * writing its files and then stops without removing anything or recording\n * the files in the manifest.\n */\nexport const SIGNAL_SEAM = Symbol('signal');\n\n/**\n * What the package itself may hand a generator beyond its public options,\n * each under a symbol it does not export.\n */\nexport interface Seams {\n readonly [PROJECT_SEAM]?: Project;\n readonly [SIGNAL_SEAM]?: AbortSignal;\n}\n\n/** The options, with the {@link Seams} the package may add. */\nexport interface SeamOptions extends GeneratorOptions, Seams {}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IndentationText, Project, QuoteKind } from 'ts-morph';\nimport { analyze } from '../analysis/analyze';\nimport { errorMessage, GeneratorError } from '../api/errors';\nimport type { Logger } from '../api/logger';\nimport { ConsoleLogger } from '../api/logger';\nimport type { GenerationResult, GeneratorOptions } from '../api/options';\nimport { ModuleSet } from '../emit/moduleBuilder';\nimport { emitGeneration } from '../emitters/emit';\nimport { emitIndexFiles } from '../emitters/indexFiles';\nimport { documentTypeContext } from '../emitters/models';\nimport { finalizeSourceFiles } from '../finalize/finalize';\nimport { resolveConfiguration } from '../input/configuration';\nimport { loadDocument, validateOpenAPIDocument } from '../input/parsers';\nimport { analyzeManifest } from '../manifest/analyze';\nimport {\n isManifestDocument,\n type ManifestDocument,\n validateManifest,\n} from '../manifest/document';\nimport { emitManifestGeneration } from '../emitters/manifestClients';\nimport { openApiDocument } from '../openapi/document';\nimport { findDanglingReferences } from '../openapi/references';\nimport { OutputStore } from '../output/outputStore';\nimport type { SeamOptions } from './seams';\nimport { PROJECT_SEAM, SIGNAL_SEAM } from './seams';\n\n/**\n * Main code generator class that orchestrates the generation of TypeScript code\n * from a Wow Manifest or an OpenAPI document. A Manifest generates the typed\n * clients of a Wow service on `@ahoo-wang/wow-client`; an OpenAPI\n * document generates its models and Fetcher decorator API clients.\n *\n * @example\n * ```typescript\n * const generator = new CodeGenerator({\n * inputPath: './openapi.yaml',\n * outputDir: './generated',\n * tsConfigFilePath: './tsconfig.json',\n * logger: new ConsoleLogger({ level: 'verbose' }),\n * });\n * const { files } = await generator.generate();\n * ```\n */\nexport class CodeGenerator {\n private readonly project: Project;\n private readonly logger: Logger;\n private readonly signal?: AbortSignal;\n /** The output of the last run, whose files the next run starts without. */\n private output?: OutputStore;\n\n /**\n * Creates a new CodeGenerator instance with the specified options.\n *\n * @param options - Input, output, configuration and logging of the run.\n * @throws GeneratorError of kind `configuration` if the TypeScript\n * configuration cannot be read.\n */\n constructor(private readonly options: GeneratorOptions) {\n this.logger = options.logger ?? new ConsoleLogger();\n this.signal = (options as SeamOptions)[SIGNAL_SEAM];\n this.project =\n (options as SeamOptions)[PROJECT_SEAM] ??\n createProject(options.tsConfigFilePath);\n this.project.manipulationSettings.set({\n indentationText: IndentationText.TwoSpaces,\n quoteKind: QuoteKind.Single,\n useTrailingCommas: true,\n });\n this.logger.debug(\n `Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`,\n );\n }\n\n /**\n * Generates TypeScript code from the input document:\n *\n * 1. reads the generator configuration, then the document; a Manifest goes\n * to `generateFromManifest`, an OpenAPI document is checked for\n * dangling references;\n * 2. decides what the document generates (`analysis/`);\n * 3. writes every module once (`emitters/`), then the index files;\n * 4. formats, organises and types the imports, and checks the output\n * compiles (`finalize/`);\n * 5. writes the files, removes the stale ones of the last run and records\n * the manifest (`output/`).\n *\n * Every warning is logged as it arises, and counted.\n *\n * @returns The files written, the configuration read and how many warnings\n * the run logged.\n * @throws GeneratorError when the document or the configuration cannot be\n * read or understood, the document describes code that cannot compile, or\n * the output cannot be written. A configuration is only optional at\n * `DEFAULT_CONFIG_PATH`; one the caller named has to exist.\n *\n * @example\n * ```typescript\n * await generator.generate();\n * ```\n */\n async generate(): Promise<GenerationResult> {\n const { logger, signal, options } = this;\n let warnings = 0;\n const warn = (lines: readonly string[]) => {\n for (const line of lines) {\n warnings++;\n logger.warn(line);\n }\n };\n logger.debug('Starting code generation');\n logger.debug(`Work directory: ${process.cwd()}`);\n logger.debug(`Input path: ${options.inputPath}`);\n logger.debug(`Output directory: ${options.outputDir}`);\n\n const loadOptions = {\n headers: options.headers,\n timeoutMs: options.timeoutMs,\n signal,\n };\n // The configuration first: a mistake in it fails before a remote\n // document is fetched and read.\n const configuration = await resolveConfiguration(\n options.configPath,\n logger,\n loadOptions,\n );\n warn(configuration.warnings);\n signal?.throwIfAborted();\n\n logger.debug('Parsing the input document');\n const input = await loadDocument(options.inputPath, loadOptions);\n signal?.throwIfAborted();\n if (isManifestDocument(input)) {\n return this.generateFromManifest(\n validateManifest(input, options.inputPath),\n configuration.origin,\n warn,\n () => warnings,\n );\n }\n const openAPI = validateOpenAPIDocument(input, options.inputPath);\n logger.debug('OpenAPI specification parsed successfully');\n const dangling = findDanglingReferences(openAPI);\n if (dangling.length > 0) {\n throw new GeneratorError(\n 'specification',\n `${options.inputPath} has ${dangling.length} $ref(s) that point at nothing: ${dangling\n .slice(0, 10)\n .map(({ ref, location }) => `${ref} (at ${location})`)\n .join(', ')}${dangling.length > 10 ? ', …' : ''}`,\n );\n }\n\n const document = openApiDocument(openAPI);\n\n const output = OutputStore.open(\n this.project,\n options.outputDir,\n this.output,\n );\n this.output = output;\n\n logger.debug('Analysing the document');\n const analysis = analyze(document, configuration.config);\n warn(analysis.warnings);\n\n logger.debug('Writing generated modules');\n const modules = new ModuleSet(filePath => output.claim(filePath));\n emitGeneration(analysis.model, {\n modules,\n outputDir: options.outputDir,\n types: documentTypeContext(document.components),\n schemaDocs: options.schemaDocs ?? 'summary',\n });\n modules.build();\n logger.debug('Generated modules written');\n output.forgetStale();\n const outputDirectory = this.project.getDirectory(options.outputDir);\n if (outputDirectory) {\n logger.debug('Generating index files');\n warn(\n emitIndexFiles(outputDirectory, directory =>\n output.claim('index.ts', directory),\n ),\n );\n logger.debug('Optimizing source files');\n const sourceFiles = outputDirectory\n .getDescendantSourceFiles()\n .filter(file => output.files.has(file.getFilePath()));\n finalizeSourceFiles(sourceFiles, logger);\n logger.debug('Source files optimized successfully');\n } else {\n logger.debug('Output directory not found.');\n }\n\n logger.debug('Saving project to disk');\n await output.commit(signal);\n logger.debug('Code generation completed successfully');\n return {\n files: [...output.files].sort(),\n configPath: configuration.origin,\n warnings,\n };\n }\n\n /**\n * Generates the clients of a Wow V10 service from its Manifest (decision\n * D74, roadmap 5a.3): the types of its schemas, and for each aggregate its\n * command, query and state clients on `@ahoo-wang/wow-client`. The\n * configuration's API clients are an OpenAPI document's and do not apply.\n */\n private async generateFromManifest(\n manifest: ManifestDocument,\n configPath: string | undefined,\n warn: (lines: readonly string[]) => void,\n warnings: () => number,\n ): Promise<GenerationResult> {\n const { logger, signal, options } = this;\n const output = OutputStore.open(\n this.project,\n options.outputDir,\n this.output,\n );\n this.output = output;\n logger.debug('Analysing the Manifest');\n const analysis = analyzeManifest(manifest);\n warn(analysis.warnings);\n const modules = new ModuleSet(filePath => output.claim(filePath));\n emitManifestGeneration(analysis.model, modules, options.outputDir);\n modules.build();\n output.forgetStale();\n const outputDirectory = this.project.getDirectory(options.outputDir);\n if (outputDirectory) {\n warn(\n emitIndexFiles(outputDirectory, directory =>\n output.claim('index.ts', directory),\n ),\n );\n finalizeSourceFiles(\n outputDirectory\n .getDescendantSourceFiles()\n .filter(file => output.files.has(file.getFilePath())),\n logger,\n );\n }\n await output.commit(signal);\n logger.debug('Code generation from the Manifest completed successfully');\n return {\n files: [...output.files].sort(),\n configPath,\n warnings: warnings(),\n };\n }\n}\n\n/**\n * The project a run writes into. Only the compiler options of the tsconfig\n * matter: the files it includes would be read, parsed and type-checked on\n * every run for nothing, and their global declarations could sway the\n * output.\n *\n * @throws GeneratorError of kind `configuration` when the tsconfig cannot be\n * read\n */\nfunction createProject(tsConfigFilePath: string | undefined): Project {\n try {\n return new Project({ tsConfigFilePath, skipAddingFilesFromTsConfig: true });\n } catch (error) {\n throw new GeneratorError(\n 'configuration',\n `Cannot read the TypeScript configuration ${tsConfigFilePath}: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n}\n"],"mappings":"qGAgBA,IAAasC,EAAsB,8BCmBtBC,EAAa,CACxB,QAAS,EACT,SAAU,EACV,MAAO,EACP,cAAe,EACf,cAAe,EACf,OAAQ,EACR,YAAa,GACf,EAMaC,EAAb,cAAoC,K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