@ahoo-wang/wow-generator 9.2.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +177 -0
  3. package/README.zh-CN.md +149 -0
  4. package/dist/analysis/aggregates.d.cts +21 -0
  5. package/dist/analysis/aggregates.d.ts +21 -0
  6. package/dist/analysis/analyze.d.cts +18 -0
  7. package/dist/analysis/analyze.d.ts +18 -0
  8. package/dist/analysis/apiClients.d.cts +14 -0
  9. package/dist/analysis/apiClients.d.ts +14 -0
  10. package/dist/analysis/clientNames.d.cts +55 -0
  11. package/dist/analysis/clientNames.d.ts +55 -0
  12. package/dist/analysis/model.d.cts +212 -0
  13. package/dist/analysis/model.d.ts +212 -0
  14. package/dist/analysis/modelInfo.d.cts +23 -0
  15. package/dist/analysis/modelInfo.d.ts +23 -0
  16. package/dist/analysis/models.d.cts +17 -0
  17. package/dist/analysis/models.d.ts +17 -0
  18. package/dist/api/configuration.d.cts +30 -0
  19. package/dist/api/configuration.d.ts +30 -0
  20. package/dist/api/errors.d.cts +41 -0
  21. package/dist/api/errors.d.ts +41 -0
  22. package/dist/api/logger.d.cts +61 -0
  23. package/dist/api/logger.d.ts +61 -0
  24. package/dist/api/options.d.cts +47 -0
  25. package/dist/api/options.d.ts +47 -0
  26. package/dist/cli/program.d.cts +35 -0
  27. package/dist/cli/program.d.ts +35 -0
  28. package/dist/cli/runGenerate.d.cts +65 -0
  29. package/dist/cli/runGenerate.d.ts +65 -0
  30. package/dist/cli.cjs +3 -0
  31. package/dist/cli.cjs.map +1 -0
  32. package/dist/cli.d.cts +6 -0
  33. package/dist/cli.d.ts +6 -0
  34. package/dist/cli.js +98 -0
  35. package/dist/cli.js.map +1 -0
  36. package/dist/codeGenerator-DpDTDC4o.cjs +23 -0
  37. package/dist/codeGenerator-DpDTDC4o.cjs.map +1 -0
  38. package/dist/codeGenerator-kyY9eLML.js +2583 -0
  39. package/dist/codeGenerator-kyY9eLML.js.map +1 -0
  40. package/dist/emit/importRegistry.d.cts +50 -0
  41. package/dist/emit/importRegistry.d.ts +50 -0
  42. package/dist/emit/imports.d.cts +49 -0
  43. package/dist/emit/imports.d.ts +49 -0
  44. package/dist/emit/jsdoc.d.cts +38 -0
  45. package/dist/emit/jsdoc.d.ts +38 -0
  46. package/dist/emit/moduleBuilder.d.cts +80 -0
  47. package/dist/emit/moduleBuilder.d.ts +80 -0
  48. package/dist/emitters/apiClients.d.cts +10 -0
  49. package/dist/emitters/apiClients.d.ts +10 -0
  50. package/dist/emitters/commandClients.d.cts +14 -0
  51. package/dist/emitters/commandClients.d.ts +14 -0
  52. package/dist/emitters/decorators.d.cts +83 -0
  53. package/dist/emitters/decorators.d.ts +83 -0
  54. package/dist/emitters/emit.d.cts +15 -0
  55. package/dist/emitters/emit.d.ts +15 -0
  56. package/dist/emitters/indexFiles.d.cts +12 -0
  57. package/dist/emitters/indexFiles.d.ts +12 -0
  58. package/dist/emitters/models.d.cts +77 -0
  59. package/dist/emitters/models.d.ts +77 -0
  60. package/dist/emitters/queryClients.d.cts +11 -0
  61. package/dist/emitters/queryClients.d.ts +11 -0
  62. package/dist/emitters/target.d.cts +14 -0
  63. package/dist/emitters/target.d.ts +14 -0
  64. package/dist/finalize/finalize.d.cts +16 -0
  65. package/dist/finalize/finalize.d.ts +16 -0
  66. package/dist/finalize/typeOnlyImports.d.cts +13 -0
  67. package/dist/finalize/typeOnlyImports.d.ts +13 -0
  68. package/dist/finalize/verification.d.cts +14 -0
  69. package/dist/finalize/verification.d.ts +14 -0
  70. package/dist/index.cjs +1 -0
  71. package/dist/index.d.cts +8 -0
  72. package/dist/index.d.ts +8 -0
  73. package/dist/index.js +2 -0
  74. package/dist/input/configuration.d.cts +87 -0
  75. package/dist/input/configuration.d.ts +87 -0
  76. package/dist/input/parsers.d.cts +39 -0
  77. package/dist/input/parsers.d.ts +39 -0
  78. package/dist/input/resources.d.cts +36 -0
  79. package/dist/input/resources.d.ts +36 -0
  80. package/dist/naming/modelInfo.d.cts +10 -0
  81. package/dist/naming/modelInfo.d.ts +10 -0
  82. package/dist/naming/naming.d.cts +102 -0
  83. package/dist/naming/naming.d.ts +102 -0
  84. package/dist/naming/order.d.cts +2 -0
  85. package/dist/naming/order.d.ts +2 -0
  86. package/dist/naming/paths.d.cts +27 -0
  87. package/dist/naming/paths.d.ts +27 -0
  88. package/dist/openapi/components.d.cts +55 -0
  89. package/dist/openapi/components.d.ts +55 -0
  90. package/dist/openapi/document.d.cts +25 -0
  91. package/dist/openapi/document.d.ts +25 -0
  92. package/dist/openapi/operations.d.cts +78 -0
  93. package/dist/openapi/operations.d.ts +78 -0
  94. package/dist/openapi/references.d.cts +28 -0
  95. package/dist/openapi/references.d.ts +28 -0
  96. package/dist/openapi/responses.d.cts +44 -0
  97. package/dist/openapi/responses.d.ts +44 -0
  98. package/dist/openapi/schemas.d.cts +112 -0
  99. package/dist/openapi/schemas.d.ts +112 -0
  100. package/dist/output/outputStore.d.cts +92 -0
  101. package/dist/output/outputStore.d.ts +92 -0
  102. package/dist/pipeline/codeGenerator.d.cts +61 -0
  103. package/dist/pipeline/codeGenerator.d.ts +61 -0
  104. package/dist/pipeline/seams.d.cts +29 -0
  105. package/dist/pipeline/seams.d.ts +29 -0
  106. package/dist/types/typeResolver.d.cts +124 -0
  107. package/dist/types/typeResolver.d.ts +124 -0
  108. package/dist/version.d.cts +2 -0
  109. package/dist/version.d.ts +2 -0
  110. package/dist/wow/conventions.d.cts +154 -0
  111. package/dist/wow/conventions.d.ts +154 -0
  112. package/dist/wow/model.d.cts +116 -0
  113. package/dist/wow/model.d.ts +116 -0
  114. package/dist/wow/resolveWowModel.d.cts +21 -0
  115. package/dist/wow/resolveWowModel.d.ts +21 -0
  116. package/package.json +108 -0
package/dist/cli.js ADDED
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ import { c as e, i as t, n, o as r, r as i, s as a, t as o } from "./codeGenerator-kyY9eLML.js";
3
+ import { relative as s } from "path";
4
+ import { CommanderError as c, program as l } from "commander";
5
+ //#region src/version.ts
6
+ var u = "9.2.0-rc.0";
7
+ //#endregion
8
+ //#region src/cli/runGenerate.ts
9
+ function d(e) {
10
+ if (!e) return !1;
11
+ let t;
12
+ try {
13
+ t = new URL(e);
14
+ } catch {
15
+ return !0;
16
+ }
17
+ return /^[a-z]:$/i.test(t.protocol) ? !0 : t.protocol === "http:" || t.protocol === "https:";
18
+ }
19
+ function f(e = []) {
20
+ let t = {};
21
+ for (let n of e) {
22
+ let e = n.indexOf(":"), r = e > 0 ? n.slice(0, e).trim() : "";
23
+ if (!r) throw new a("input", `Invalid --header "${n}": expected "Name: value".`);
24
+ t[r] = n.slice(e + 1).trim();
25
+ }
26
+ return t;
27
+ }
28
+ function p(e) {
29
+ if (e === void 0) return;
30
+ let t = Number(e);
31
+ if (!Number.isInteger(t) || t <= 0) throw new a("input", `Invalid --timeout "${e}": expected a positive number of milliseconds.`);
32
+ return t;
33
+ }
34
+ function m(e) {
35
+ if (e === void 0 || e === "summary") return "summary";
36
+ if (e === "full") return "full";
37
+ throw new a("input", `Invalid --schema-docs "${e}": expected "summary" or "full".`);
38
+ }
39
+ function h(e) {
40
+ return e.verbose ? "verbose" : e.quiet ? "quiet" : "normal";
41
+ }
42
+ function g(e, t, n) {
43
+ if (t instanceof a) return e.error(t.message), n && t.cause !== void 0 && e.error("Caused by:", t.cause), t.exitCode;
44
+ let i = t instanceof Error ? t.message : String(t);
45
+ return e.error(`Code generation failed: ${i}`), n ? e.error("", t) : e.error("Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid."), r.internal;
46
+ }
47
+ async function _(e, i = new t({ level: h(e) }), a = {}) {
48
+ if (!d(e.input)) return i.error(`Invalid input "${e.input}": expected a file path or an http(s) URL.`), r.input;
49
+ try {
50
+ i.debug(`wow-generator v${u}`);
51
+ let t = {
52
+ ...a,
53
+ inputPath: e.input,
54
+ outputDir: e.output,
55
+ configPath: e.config,
56
+ tsConfigFilePath: e.tsConfigFilePath,
57
+ headers: f(e.header),
58
+ timeoutMs: p(e.timeout),
59
+ schemaDocs: m(e.schemaDocs),
60
+ logger: i
61
+ }, n = await new o(t).generate(), c = n.warnings ? `, ${n.warnings} warning${n.warnings === 1 ? "" : "s"}` : "", l = n.configPath ? ` with ${s(process.cwd(), n.configPath) || n.configPath}` : "";
62
+ return i.info(`Generated ${n.files.length} files into ${e.output}${l}${c}`), e.strict && n.warnings > 0 ? (i.error(`--strict: the run logged ${n.warnings} warning${n.warnings === 1 ? "" : "s"}.`), r.specification) : r.success;
63
+ } catch (t) {
64
+ return a[n]?.aborted ? r.interrupted : g(i, t, !!e.verbose);
65
+ }
66
+ }
67
+ async function v(e) {
68
+ let t = new AbortController();
69
+ process.once("SIGINT", () => {
70
+ console.error("Generation interrupted by user"), t.abort();
71
+ }), process.exitCode = await _(e, void 0, { [n]: t.signal });
72
+ }
73
+ //#endregion
74
+ //#region src/cli/program.ts
75
+ function y(e, t = []) {
76
+ return [...t, e];
77
+ }
78
+ function b(t = l) {
79
+ return t.exitOverride(), t.name("wow-generator").description("OpenAPI Specification TypeScript code generator for Wow").version(u, "-v, --version"), t.command("generate").description("Generate TypeScript code from OpenAPI specification").requiredOption("-i, --input <file>", "Input OpenAPI specification file path or URL (http/https)").option("-o, --output <path>", "Output directory path", "src/generated").option("-c, --config <file>", `Configuration file path (default: ${e})`).option("-t, --ts-config-file-path <file>", "TypeScript configuration file path").option("-H, --header <header>", "Request header for an http(s) input or configuration, as \"Name: value\"; repeatable", y).option("--timeout <ms>", `Milliseconds before fetching an http(s) input is abandoned (default: ${i})`).option("--schema-docs <mode>", "What model doc comments carry: \"summary\" (title, description, constraints) or \"full\" (also the JSON schema)", "summary").option("--strict", "Exit with code 4 when the run logs a warning").option("--verbose", "Log every step, and the stack trace of a failure").option("--quiet", "Log only warnings and errors").action(v), t;
80
+ }
81
+ function x(e) {
82
+ return e.exitCode === 0 ? r.success : r.input;
83
+ }
84
+ async function S(e, t = b()) {
85
+ try {
86
+ e === void 0 ? await t.parseAsync() : await t.parseAsync(e, { from: "user" });
87
+ } catch (e) {
88
+ if (!(e instanceof c)) throw e;
89
+ process.exitCode = x(e);
90
+ }
91
+ }
92
+ //#endregion
93
+ //#region src/cli.ts
94
+ S();
95
+ //#endregion
96
+ export { y as collect, S as runCLI, b as setupCLI };
97
+
98
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":["DEFAULT_CONFIG_PATH","ConsoleLogger","EXIT_CODES","DEFAULT_HTTP_TIMEOUT_MS","GeneratorError","CodeGenerator","VERSION","validateInput","input","url","parseHeaders","parsed","header","headers","separator","name","parseTimeout","timeout","value","parseSchemaDocs","schemaDocs","logLevel","options","reportFailure","error","logger","verbose","message","runGenerate","generatorOptions","seams","result","warnings","config","relative","SIGNAL_SEAM","generateAction","interruption","collect","previous","setupCLI","program","target","commanderExitCode","runCLI","args","CommanderError"],"sources":["../src/version.ts","../src/cli/runGenerate.ts","../src/cli/program.ts","../src/cli.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// Replaced at build time with the `version` of this package's package.json\n// (`define` in vite.config.ts, which Vitest shares), so only the version string\n// reaches dist, not the manifest with its dependencies and workspace ranges.\ndeclare const __WOW_GENERATOR_VERSION__: string;\n\n/** The version of this package, as its package.json named it at build time. */\nexport const VERSION: string = __WOW_GENERATOR_VERSION__;\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 { relative } from 'path';\nimport { VERSION } from '../version';\nimport { EXIT_CODES, GeneratorError } from '../api/errors';\nimport { CodeGenerator } from '../pipeline/codeGenerator';\nimport type { Logger, LogLevel } from '../api/logger';\nimport { ConsoleLogger } from '../api/logger';\nimport type { SchemaDocs } from '../api/options';\nimport type { SeamOptions, Seams } from '../pipeline/seams';\nimport { SIGNAL_SEAM } from '../pipeline/seams';\n\n/**\n * Options of the `generate` command, as commander parses them.\n */\nexport interface GenerateCommandOptions {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n /** `Name: value` request headers for an http(s) input or configuration. */\n header?: string[];\n /** Milliseconds, as typed on the command line. */\n timeout?: string;\n /** `summary` or `full`. */\n schemaDocs?: string;\n /** Exit with a non-zero code when the run logged a warning. */\n strict?: boolean;\n verbose?: boolean;\n quiet?: boolean;\n}\n\n/**\n * Validates the input path or URL.\n *\n * Any file path is accepted here and checked when it is read. A URL must use\n * http or https; its host is not restricted, because the generator runs on\n * the developer's own machine against a document they chose, and fetching an\n * intranet service's `/v3/api-docs` is the common case.\n *\n * @param input - Input path or URL\n * @returns true if valid\n */\nexport function validateInput(input: string): boolean {\n if (!input) return false;\n let url: URL;\n try {\n url = new URL(input);\n } catch {\n // Not a URL: a file path, which parseOpenAPI reads.\n return true;\n }\n // A Windows path such as C:\\spec.json parses as a URL with scheme \"c:\".\n if (/^[a-z]:$/i.test(url.protocol)) return true;\n return url.protocol === 'http:' || url.protocol === 'https:';\n}\n\n/**\n * Parses `Name: value` header arguments.\n *\n * @param headers - The raw `--header` values\n * @returns The headers by name\n * @throws GeneratorError of kind `input` for a value without a name\n */\nexport function parseHeaders(\n headers: readonly string[] = [],\n): Record<string, string> {\n const parsed: Record<string, string> = {};\n for (const header of headers) {\n const separator = header.indexOf(':');\n const name = separator > 0 ? header.slice(0, separator).trim() : '';\n if (!name) {\n throw new GeneratorError(\n 'input',\n `Invalid --header \"${header}\": expected \"Name: value\".`,\n );\n }\n parsed[name] = header.slice(separator + 1).trim();\n }\n return parsed;\n}\n\nfunction parseTimeout(timeout: string | undefined): number | undefined {\n if (timeout === undefined) return undefined;\n const value = Number(timeout);\n if (!Number.isInteger(value) || value <= 0) {\n throw new GeneratorError(\n 'input',\n `Invalid --timeout \"${timeout}\": expected a positive number of milliseconds.`,\n );\n }\n return value;\n}\n\nfunction parseSchemaDocs(schemaDocs: string | undefined): SchemaDocs {\n if (schemaDocs === undefined || schemaDocs === 'summary') return 'summary';\n if (schemaDocs === 'full') return 'full';\n throw new GeneratorError(\n 'input',\n `Invalid --schema-docs \"${schemaDocs}\": expected \"summary\" or \"full\".`,\n );\n}\n\nfunction logLevel(options: GenerateCommandOptions): LogLevel {\n if (options.verbose) return 'verbose';\n if (options.quiet) return 'quiet';\n return 'normal';\n}\n\n/**\n * Reports a failure as one actionable line; the stack and the causes only\n * with `--verbose`.\n *\n * @returns The exit code the failure maps to\n */\nfunction reportFailure(\n logger: Logger,\n error: unknown,\n verbose: boolean,\n): number {\n if (error instanceof GeneratorError) {\n logger.error(error.message);\n if (verbose && error.cause !== undefined) {\n logger.error('Caused by:', error.cause);\n }\n return error.exitCode;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Code generation failed: ${message}`);\n if (verbose) {\n logger.error('', error);\n } else {\n logger.error(\n 'Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.',\n );\n }\n return EXIT_CODES.internal;\n}\n\n/**\n * Runs the `generate` command.\n *\n * @param options - The parsed command options\n * @param logger - Where to report; a console logger at the level the options ask for by default\n * @param seams - What the package hands the generator beyond the options;\n * a run stopped by the {@link SIGNAL_SEAM} exits with\n * {@link EXIT_CODES.interrupted}\n * @returns The exit code: see {@link EXIT_CODES}\n */\nexport async function runGenerate(\n options: GenerateCommandOptions,\n logger: Logger = new ConsoleLogger({ level: logLevel(options) }),\n seams: Seams = {},\n): Promise<number> {\n if (!validateInput(options.input)) {\n logger.error(\n `Invalid input \"${options.input}\": expected a file path or an http(s) URL.`,\n );\n return EXIT_CODES.input;\n }\n try {\n logger.debug(`wow-generator v${VERSION}`);\n const generatorOptions: SeamOptions = {\n ...seams,\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n headers: parseHeaders(options.header),\n timeoutMs: parseTimeout(options.timeout),\n schemaDocs: parseSchemaDocs(options.schemaDocs),\n logger,\n };\n const result = await new CodeGenerator(generatorOptions).generate();\n const warnings = result.warnings\n ? `, ${result.warnings} warning${result.warnings === 1 ? '' : 's'}`\n : '';\n const config = result.configPath\n ? ` with ${relative(process.cwd(), result.configPath) || result.configPath}`\n : '';\n logger.info(\n `Generated ${result.files.length} files into ${options.output}${config}${warnings}`,\n );\n if (options.strict && result.warnings > 0) {\n logger.error(\n `--strict: the run logged ${result.warnings} warning${result.warnings === 1 ? '' : 's'}.`,\n );\n return EXIT_CODES.specification;\n }\n return EXIT_CODES.success;\n } catch (error) {\n if (seams[SIGNAL_SEAM]?.aborted) return EXIT_CODES.interrupted;\n return reportFailure(logger, error, !!options.verbose);\n }\n}\n\n/**\n * Action handler for the generate command: runs it and sets the process exit\n * code.\n *\n * Ctrl-C stops the run at its next step and exits with\n * {@link EXIT_CODES.interrupted}. A run that has begun writing finishes\n * writing its files, then stops: it removes no stale file and leaves the\n * manifest as the last complete run wrote it, so the manifest never records\n * a run that did not finish. A second Ctrl-C ends the process at once.\n *\n * @param options - Command options\n */\nexport async function generateAction(options: GenerateCommandOptions) {\n const interruption = new AbortController();\n process.once('SIGINT', () => {\n console.error('Generation interrupted by user');\n interruption.abort();\n });\n process.exitCode = await runGenerate(options, undefined, {\n [SIGNAL_SEAM]: interruption.signal,\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 { Command } from 'commander';\nimport { CommanderError, program } from 'commander';\nimport { VERSION } from '../version';\nimport { DEFAULT_CONFIG_PATH } from '../api/configuration';\nimport { EXIT_CODES } from '../api/errors';\nimport { DEFAULT_HTTP_TIMEOUT_MS } from '../input/resources';\nimport { generateAction } from './runGenerate';\n\n/** Collects the values of an option given more than once, such as `--header`. */\nexport function collect(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\n/**\n * Sets up the CLI program with all commands and options.\n *\n * Commander does not exit the process: a usage error (a missing required\n * option, an unknown option or command, a missing argument, no command at\n * all) is thrown as a `CommanderError`, which {@link runCLI} maps to an exit\n * code.\n *\n * @param target - The program to set up; commander's global one by default.\n * Settings made on it before this call, such as `configureOutput`, reach the\n * `generate` command too.\n * @returns The configured commander program instance\n */\nexport function setupCLI(target: Command = program): Command {\n // Before `command()`: a subcommand copies the exit override when it is\n // created.\n target.exitOverride();\n // compat(fetcher): package.json also installs this CLI as `fetcher-generator`, the\n // name existing scripts call; drop that bin alias in v10.\n target\n .name('wow-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(VERSION, '-v, --version');\n\n target\n .command('generate')\n .description('Generate TypeScript code from OpenAPI specification')\n .requiredOption(\n '-i, --input <file>',\n 'Input OpenAPI specification file path or URL (http/https)',\n )\n .option('-o, --output <path>', 'Output directory path', 'src/generated')\n // No commander default: an omitted -c falls back to DEFAULT_CONFIG_PATH,\n // which may be absent, while a path the user named has to exist.\n .option(\n '-c, --config <file>',\n `Configuration file path (default: ${DEFAULT_CONFIG_PATH})`,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .option(\n '-H, --header <header>',\n 'Request header for an http(s) input or configuration, as \"Name: value\"; repeatable',\n collect,\n )\n .option(\n '--timeout <ms>',\n `Milliseconds before fetching an http(s) input is abandoned (default: ${DEFAULT_HTTP_TIMEOUT_MS})`,\n )\n .option(\n '--schema-docs <mode>',\n 'What model doc comments carry: \"summary\" (title, description, constraints) or \"full\" (also the JSON schema)',\n 'summary',\n )\n .option('--strict', 'Exit with code 4 when the run logs a warning')\n .option('--verbose', 'Log every step, and the stack trace of a failure')\n .option('--quiet', 'Log only warnings and errors')\n .action(generateAction);\n\n return target;\n}\n\n/**\n * The exit code of a command line commander stopped at: 0 for `--help`,\n * `help` and `--version`; {@link EXIT_CODES.input} for a usage error, which\n * commander has already reported. A usage error is an invalid command line,\n * the same category as an invalid option value such as `--timeout abc`.\n */\nexport function commanderExitCode(error: CommanderError): number {\n return error.exitCode === 0 ? EXIT_CODES.success : EXIT_CODES.input;\n}\n\n/**\n * Parses the command line and runs the command it names. The `generate`\n * command sets the process exit code itself; a command line commander stops\n * at sets it to {@link commanderExitCode}.\n *\n * @param args - The arguments after the executable and script;\n * `process.argv` by default\n * @param target - The program to run; {@link setupCLI} on commander's global\n * one by default\n */\nexport async function runCLI(\n args?: readonly string[],\n target: Command = setupCLI(),\n): Promise<void> {\n try {\n if (args === undefined) {\n await target.parseAsync();\n } else {\n await target.parseAsync(args, { from: 'user' });\n }\n } catch (error) {\n if (!(error instanceof CommanderError)) throw error;\n process.exitCode = commanderExitCode(error);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point of wow-generator: runs the program `cli/program.ts` sets\n * up on the process's command line.\n */\n\nimport { runCLI } from './cli/program';\n\nexport { collect, runCLI, setupCLI } from './cli/program';\n\nvoid runCLI();\n"],"mappings":";;;;;AAmBA,IAAaM,IAAA;;;ACmCb,SAAgBC,EAAc,GAAwB;CACpD,IAAI,CAACC,GAAO,OAAO;CACnB,IAAIC;CACJ,IAAI;EACF,IAAM,IAAI,IAAID,CAAK;CACrB,QAAQ;EAEN,OAAO;CACT;CAGA,OADI,YAAY,KAAKC,EAAI,QAAQ,IAAU,KACpCA,EAAI,aAAa,WAAWA,EAAI,aAAa;AACtD;AASA,SAAgBC,EACd,IAA6B,CAAC,GACN;CACxB,IAAMC,IAAiC,CAAC;CACxC,KAAK,IAAMC,KAAUC,GAAS;EAC5B,IAAMC,IAAYF,EAAO,QAAQ,GAAG,GAC9BG,IAAOD,IAAY,IAAIF,EAAO,MAAM,GAAGE,CAAS,CAAC,CAAC,KAAK,IAAI;EACjE,IAAI,CAACC,GACH,MAAM,IAAIX,EACR,SACA,qBAAqBQ,EAAO,2BAC9B;EAEF,EAAOG,KAAQH,EAAO,MAAME,IAAY,CAAC,CAAC,CAAC,KAAK;CAClD;CACA,OAAOH;AACT;AAEA,SAASK,EAAa,GAAiD;CACrE,IAAIC,MAAY,KAAA,GAAW;CAC3B,IAAMC,IAAQ,OAAOD,CAAO;CAC5B,IAAI,CAAC,OAAO,UAAUC,CAAK,KAAKA,KAAS,GACvC,MAAM,IAAId,EACR,SACA,sBAAsBa,EAAQ,+CAChC;CAEF,OAAOC;AACT;AAEA,SAASC,EAAgB,GAA4C;CACnE,IAAIC,MAAe,KAAA,KAAaA,MAAe,WAAW,OAAO;CACjE,IAAIA,MAAe,QAAQ,OAAO;CAClC,MAAM,IAAIhB,EACR,SACA,0BAA0BgB,EAAW,iCACvC;AACF;AAEA,SAASC,EAAS,GAA2C;CAG3D,OAFIC,EAAQ,UAAgB,YACxBA,EAAQ,QAAc,UACnB;AACT;AAQA,SAASC,EACP,GACA,GACA,GACQ;CACR,IAAIC,aAAiBpB,GAKnB,OAJAqB,EAAO,MAAMD,EAAM,OAAO,GACtBE,KAAWF,EAAM,UAAU,KAAA,KAC7BC,EAAO,MAAM,cAAcD,EAAM,KAAK,GAEjCA,EAAM;CAEf,IAAMG,IAAUH,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;CASrE,OARAC,EAAO,MAAM,2BAA2BE,GAAS,GAC7CD,IACFD,EAAO,MAAM,IAAID,CAAK,IAEtBC,EAAO,MACL,2HACF,GAEKvB,EAAW;AACpB;AAYA,eAAsB0B,EACpB,GACA,IAAiB,IAAI3B,EAAc,EAAE,OAAOoB,EAASC,CAAO,EAAE,CAAC,GAC/D,IAAe,CAAC,GACC;CACjB,IAAI,CAACf,EAAce,EAAQ,KAAK,GAI9B,OAHAG,EAAO,MACL,kBAAkBH,EAAQ,MAAM,2CAClC,GACOpB,EAAW;CAEpB,IAAI;EACF,EAAO,MAAM,kBAAkBI,GAAS;EACxC,IAAMuB,IAAgC;GACpC,GAAGC;GACH,WAAWR,EAAQ;GACnB,WAAWA,EAAQ;GACnB,YAAYA,EAAQ;GACpB,kBAAkBA,EAAQ;GAC1B,SAASZ,EAAaY,EAAQ,MAAM;GACpC,WAAWN,EAAaM,EAAQ,OAAO;GACvC,YAAYH,EAAgBG,EAAQ,UAAU;GAC9C;EACF,GACMS,IAAS,MAAM,IAAI1B,EAAcwB,CAAgB,CAAC,CAAC,SAAS,GAC5DG,IAAWD,EAAO,WACpB,KAAKA,EAAO,SAAS,UAAUA,EAAO,aAAa,IAAI,KAAK,QAC5D,IACEE,IAASF,EAAO,aAClB,SAASG,EAAS,QAAQ,IAAI,GAAGH,EAAO,UAAU,KAAKA,EAAO,eAC9D;EAUJ,OATAN,EAAO,KACL,aAAaM,EAAO,MAAM,OAAO,cAAcT,EAAQ,SAASW,IAASD,GAC3E,GACIV,EAAQ,UAAUS,EAAO,WAAW,KACtCN,EAAO,MACL,4BAA4BM,EAAO,SAAS,UAAUA,EAAO,aAAa,IAAI,KAAK,IAAI,EACzF,GACO7B,EAAW,iBAEbA,EAAW;CACpB,SAASsB,GAAO;EAEd,OADIM,EAAMK,EAAY,EAAE,UAAgBjC,EAAW,cAC5CqB,EAAcE,GAAQD,GAAO,CAAC,CAACF,EAAQ,OAAO;CACvD;AACF;AAcA,eAAsBc,EAAe,GAAiC;CACpE,IAAMC,IAAe,IAAI,gBAAgB;CAKzC,AAJA,QAAQ,KAAK,gBAAgB;EAE3B,AADA,QAAQ,MAAM,gCAAgC,GAC9CA,EAAa,MAAM;CACrB,CAAC,GACD,QAAQ,WAAW,MAAMT,EAAYN,GAAS,KAAA,GAAW,GACtDa,IAAcE,EAAa,OAC9B,CAAC;AACH;;;AC9MA,SAAgBC,EAAQ,GAAe,IAAqB,CAAC,GAAa;CACxE,OAAO,CAAC,GAAGC,GAAUrB,CAAK;AAC5B;AAeA,SAAgBsB,EAAS,IAAkBC,GAAkB;CAgD3D,OA7CAC,EAAO,aAAa,GAGpBA,EACG,KAAK,eAAe,CAAC,CACrB,YAAY,yDAAyD,CAAC,CACtE,QAAQpC,GAAS,eAAe,GAEnCoC,EACG,QAAQ,UAAU,CAAC,CACnB,YAAY,qDAAqD,CAAC,CAClE,eACC,sBACA,2DACF,CAAC,CACA,OAAO,uBAAuB,yBAAyB,eAAe,CAAC,CAGvE,OACC,uBACA,qCAAqC1C,EAAoB,EAC3D,CAAC,CACA,OACC,oCACA,oCACF,CAAC,CACA,OACC,yBACA,wFACAsC,CACF,CAAC,CACA,OACC,kBACA,wEAAwEnC,EAAwB,EAClG,CAAC,CACA,OACC,wBACA,mHACA,SACF,CAAC,CACA,OAAO,YAAY,8CAA8C,CAAC,CAClE,OAAO,aAAa,kDAAkD,CAAC,CACvE,OAAO,WAAW,8BAA8B,CAAC,CACjD,OAAOiC,CAAc,GAEjBM;AACT;AAQA,SAAgBC,EAAkB,GAA+B;CAC/D,OAAOnB,EAAM,aAAa,IAAItB,EAAW,UAAUA,EAAW;AAChE;AAYA,eAAsB0C,EACpB,GACA,IAAkBJ,EAAS,GACZ;CACf,IAAI;EACF,AAAIK,MAAS,KAAA,IACX,MAAMH,EAAO,WAAW,IAExB,MAAMA,EAAO,WAAWG,GAAM,EAAE,MAAM,OAAO,CAAC;CAElD,SAASrB,GAAO;EACd,IAAI,EAAEA,aAAiBsB,IAAiB,MAAMtB;EAC9C,QAAQ,WAAWmB,EAAkBnB,CAAK;CAC5C;AACF;;;ACjHKoB,EAAO"}
@@ -0,0 +1,23 @@
1
+ let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs");var i=`./wow-generator.config.json`,a={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},o=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return a[this.kind]}};function s(e){return e instanceof Error?e.message:String(e)}function c(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var l=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??c()}format(e,t,n){let r=this.decorate?`${e} `:t?`${t}: `:``;return`${this.level===`verbose`?`[${new Date().toTimeString().slice(0,8)}] `:``}${r}${n}`}debug(e,...t){this.level===`verbose`&&console.log(this.format(`ℹ️ `,``,e),...t)}info(e,...t){this.level!==`quiet`&&console.log(this.format(`✅`,``,e),...t)}warn(e,...t){console.warn(this.format(`⚠️ `,`warning`,e),...t)}error(e,...t){console.error(this.format(`❌`,`error`,e),...t)}},u=class{debug(){}info(){}warn(){}error(){}},d=/[^\p{L}\p{N}$]+/u,f=new Set(`arguments.await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.eval.export.extends.false.finally.for.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`));function p(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!f.has(e)}function m(e){return/^\p{N}/u.test(e)?`_${e}`:e}function h(e){if(p(e))return e;let t=m(v(e)||`_`);return f.has(t)?`${t}_`:t}function ee(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&p(e)}function te(e){return m((Array.isArray(e)?e:[e]).map(e=>ee(e)?e:re(e)).join(``)||`_`)}function g(e){return e.split(d)}function ne(e){return Array.isArray(e)?e.flatMap(e=>_(g(e))):_(g(e))}function _(e){return e.flatMap(e=>{if(e.length===0)return[];let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=/[A-Z]/.test(i),o=r>0&&/[a-z]/.test(e[r-1]);a&&o&&n?(t.push(n),n=i):n+=i}return n&&t.push(n),t})}function re(e){return e===``||e.length===0?``:ne(e).filter(e=>e.length>0).map(e=>{let t=e.charAt(0),n=e.slice(1);return(/[a-zA-Z]/.test(t)?t.toUpperCase():t)+n.toLowerCase()}).join(``)}function v(e){let t=re(e);return t.charAt(0).toLowerCase()+t.slice(1)}function ie(e){return e===``||Array.isArray(e)&&e.length===0?``:ne(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function y(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:b(e)}function ae(e){return/^\d+$/.test(e)?`NUM_${e}`:ie(e)||e}function b(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var oe=new Intl.Collator(`en-US`);function x(e,t){return oe.compare(e,t)}function S(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function se(e,t){let n=t.slice(1);try{n=decodeURIComponent(n)}catch{}if(n===``)return e;let r=e;for(let e of n.slice(1).split(`/`)){if(typeof r!=`object`||!r)return;let t=e.replace(/~1/g,`/`).replace(/~0/g,`~`);if(!Object.hasOwn(r,t))return;r=r[t]}return r}function ce(e){let t=[],n=new Set,r=(i,a)=>{if(typeof i!=`object`||!i||n.has(i))return;if(n.add(i),Array.isArray(i)){i.forEach((e,t)=>r(e,`${a}/${t}`));return}let o=i.$ref;typeof o==`string`&&o.startsWith(`#/components/`)&&se(e,o)===void 0&&t.push({ref:o,location:a||`/`});for(let[e,t]of Object.entries(i))r(t,`${a}/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`)};return r(e,``),t}var C=`#/components/`,le=`${C}parameters/`,ue=`${C}requestBodies/`,de=`${C}responses/`,fe=`${C}schemas/`;function pe(e){return e.$ref.split(`/`).pop()}function w(e,t,n){let r=new Set,i=e;for(;S(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new o(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function T(e,t){return w(e,t.schemas,fe)}function me(e,t){return w(e,t.responses,de)}function E(e,t){return w(e,t.requestBodies,ue)}function D(e,t){return w(e,t.parameters,le)}function O(e,t){return{key:pe(e),schema:T(e,t)}}var k=`application/json`,he=`text/event-stream`;function A(e){return e.split(`;`)[0].trim().toLowerCase()}function ge(e){let t=A(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function _e(e){let t=A(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function j(e,t,n=e=>A(e)===t){if(!e)return;if(e[t])return e[t];let r=Object.keys(e).find(n);return r===void 0?void 0:e[r]}function ve(e,t){if(t&&!S(t))return j(t.content,e)?.schema}function ye(e){if(e&&!S(e))return j(e.content,k,ge)?.schema}function be(e){return ve(he,e)}function xe(e){return ve(`*/*`,e)}function Se(e){return!e||S(e)?!1:Object.keys(e.content??{}).some(_e)}var Ce=[`string`,`number`,`integer`,`boolean`,`null`];function we(e){return Array.isArray(e)?!0:Ce.includes(e)}function M(e){return Array.isArray(e.enum)&&e.enum.length>0}var Te=`x-enum-text`;function Ee(e){return e[Te]}function De(e){return e.type===`object`&&!!e.properties}function Oe(e){return e.type===`array`&&!!e.items}function ke(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Ae(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function je(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function N(e){return ke(e)||Ae(e)||je(e)}function Me(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Ne(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var Pe=`x-map-key-schema`;function P(e){return e[Pe]}function Fe(e){return e.type===`object`?!e.properties||Object.keys(e.properties).length===0:!1}function Ie(e){return e.readOnly===!0}function F(e){if(Array.isArray(e))return e.map(e=>F(e)).join(` | `);switch(e){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`any`}}function Le(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),S(e)){o(t&&T(e,t));return}if(e.nullable||Array.isArray(e.type)){a=!0;return}for(let t of e.required??[])r.add(t);for(let t of Object.keys(e.properties??{}))n.includes(t)||n.push(t);e.allOf?.forEach(o)}};return o(e),a?[]:n.filter(e=>!r.has(e))}function Re(e,t){return e.operation.operationId&&t.operation.operationId?x(e.operation.operationId,t.operation.operationId):e.path&&t.path?x(e.path,t.path):e.method&&t.method?x(e.method,t.method):0}function ze(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=S(i)?n&&D(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Be(e,t){let n=[];for(let[r,i]of Object.entries(e))Ve(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:ze(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Re)}function Ve(e){return[{method:`get`,operation:e.get},{method:`put`,operation:e.put},{method:`post`,operation:e.post},{method:`delete`,operation:e.delete},{method:`options`,operation:e.options},{method:`head`,operation:e.head},{method:`patch`,operation:e.patch},{method:`trace`,operation:e.trace}].filter(({operation:e})=>e!==void 0)}function He(e){let t=Object.keys(e.responses??{});if(t.includes(`200`))return`200`;let n=t.filter(e=>/^2\d\d$/.test(e)).sort();return n.length>0?n[0]:t.find(e=>e.toUpperCase()===`2XX`)}function I(e,t){let n=He(e),r=n?e.responses[n]:void 0;return t&&S(r)?me(r,t):r}function Ue(e,t){return ye(I(e,t))}function We(e,t){return(e.parameters??[]).map(e=>S(e)?D(e,t):e).filter(e=>e!==void 0)}function Ge(e,t){return e.parameters?e.parameters.map(e=>S(e)?D(e,t):e).filter(e=>e?.in===`path`):[]}function Ke(e,t){let n=t=>{let n=e.indexOf(`{${t.name}}`);return n<0?2**53-1:n};return[...t].sort((e,t)=>n(e)-n(t))}var qe=`string`;function Je(e){return!e.schema||S(e.schema)||!e.schema.type||!we(e.schema.type)?qe:F(e.schema.type)}var Ye=`8.10`,Xe=`x-wow-context-alias`;function Ze(e){return e.info[Xe]}function Qe(e){let t=e.split(`.`);return t.length!=2||t[0].length===0||t[1].length===0?null:t}function $e(e){let t=Qe(e.name);return t?{tag:e,contextAlias:t[0],aggregateName:t[1]}:null}function et(e){if(!e)return null;let t=e.split(`.`);return t.length==3?t[2]:null}var tt=`.snapshot_state.single`,nt=`.snapshot.count`,rt=`x-wow-query-fields`,it=/^(?:\/tenant\/\{tenantId\})?(?:\/owner\/\{ownerId\})?\/(.+?)\/snapshot(?:\/|$)/,at=[`MaterializedSnapshot`,`MaterializedSnapshotPagedList`,`MaterializedSnapshotCursorPage`,`MaterializedSnapshotServerSentEventNonNullData`,`PagedList`,`ServerSentEventNonNullData`,`Snapshot`,`StateEvent`];function ot(e){return at.map(t=>e+t)}function st(e,t,n){return e!==`wow.api.query.PagedList`&&e.startsWith(`wow.api.query.`)&&e.endsWith(`PagedList`)||e.startsWith(`wow.api.query.Operator`)&&e.endsWith(`Map`)?!1:e.startsWith(`wow.`)||e.endsWith(`AggregatedCondition`)||e.endsWith(`AggregatedDomainEventStream`)||e.endsWith(`AggregatedDomainEventStreamPagedList`)||e.endsWith(`AggregatedDomainEventStreamCursorPage`)||e.endsWith(`AggregatedDomainEventStreamServerSentEventNonNullData`)||e.endsWith(`AggregatedListQuery`)||e.endsWith(`AggregatedPagedQuery`)||e.endsWith(`AggregatedSingleQuery`)?!0:n.has(t())}var L=`@ahoo-wang/wow-client`,ct=`@ahoo-wang/wow-client/legacy`,lt=new Set([`Condition`,`ConditionOptions`,`ListQuery`,`Operator`,`PagedQuery`]),ut={"wow.command.CommandResult":`CommandResult`,"wow.command.CommandResultArray":`CommandResultArray`,"wow.MessageHeaderSqlType":`MessageHeaderSqlType`,"wow.api.BindingError":`BindingError`,"wow.api.DefaultErrorInfo":`ErrorInfo`,"wow.api.RecoverableType":`RecoverableType`,"wow.api.command.DefaultDeleteAggregate":`DeleteAggregate`,"wow.api.command.DefaultRecoverAggregate":`RecoverAggregate`,"wow.api.abac.DefaultApplyResourceTags":`ApplyResourceTags`,"wow.api.messaging.FunctionInfoData":`FunctionInfo`,"wow.api.messaging.FunctionKind":`FunctionKind`,"wow.api.modeling.AggregateId":`AggregateId`,"wow.api.query.Condition":`Condition`,"wow.api.query.ConditionOptions":`ConditionOptions`,"wow.api.query.ListQuery":`ListQuery`,"wow.api.query.Operator":`Operator`,"wow.api.query.PagedQuery":`PagedQuery`,"wow.api.query.Pagination":`Pagination`,"wow.api.query.Projection":`Projection`,"wow.api.query.Sort":`FieldSort`,"wow.api.query.Sort.Direction":`SortDirection`,"wow.api.query.DynamicDocument":`DynamicDocument`,"wow.api.query.DynamicDocumentArray":`DynamicDocumentArray`,"wow.command.CommandStage":`CommandStage`,"wow.command.SimpleWaitSignal":`WaitSignal`,"wow.configuration.Aggregate":`Aggregate`,"wow.configuration.BoundedContext":`BoundedContext`,"wow.configuration.WowMetadata":`WowMetadata`,"wow.modeling.DomainEvent":`DomainEvent`,"wow.openapi.BatchResult":`BatchResult`,"wow.messaging.CompensationTarget":`CompensationTarget`};function dt(e,t){let n=ut[e];if(t&&`filter`in t&&(e===`wow.api.query.ListQuery`?n=`FilterListQuery`:e===`wow.api.query.PagedQuery`&&(n=`FilterPagedQuery`)),n)return{name:n,path:lt.has(n)?ct:L}}var ft=new Set([`wow`,`Actuator`]),pt=[`tenantId`,`ownerId`];function mt(e){let t=0,n=0;return e.commands.forEach(e=>{e.path.startsWith(`/tenant/{tenantId}`)&&(t+=1),e.path.startsWith(`/owner/{ownerId}`)&&(n+=1)}),t===0&&n===0?`ResourceAttributionPathSpec.NONE`:t>n?`ResourceAttributionPathSpec.TENANT`:`ResourceAttributionPathSpec.OWNER`}function ht(e,t){return`${e.contextAlias}/${e.aggregateName}/${t}.ts`}function R(e,t){return`${te(e.aggregateName)}${t}`}var gt=`x-fetcher-method`;function _t(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!vt(n))throw new o(`specification`,`${gt} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=v(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function vt(e){return p(e)||/^[a-z]+$/.test(e)}function yt(e,t){let n=h(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function z(e,t){if(!e)return{name:``,path:`/`};let n=dt(e,t?.properties);if(n)return n;let r=e.split(`.`),i=-1;for(let e=0;e<r.length;e++)if(r[e]&&/^[A-Z]/.test(r[e])){i=e;break}let a=r.slice(0,i),o=a.length>0?`/${a.join(`/`)}`:`/`;return{name:te(r.slice(i)),path:o}}function bt(e,t){if(!e.$ref.startsWith(fe))throw new o(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return z(pe(e),t?T(e,t):void 0)}function B(e){let t=`${ie(e)}_BOUNDED_CONTEXT_ALIAS`;return/^\p{N}/u.test(t)?`_${t}`:t}var xt=`Command`;function St(e,t){return[...t.contexts.values()].flatMap(t=>[...t].map(t=>Ct(e,t)))}function Ct(e,t){let{contextAlias:n,aggregateName:r}=t.aggregate;return{contextAlias:n,aggregateName:r,context:{alias:n,constantName:B(n)},commandClient:wt(e,t),queryClient:kt(t)}}function wt(e,t){let n=t.aggregate,r=Dt(t);return{file:ht(n,`commandClient`),endpointPathsName:R(n,`CommandEndpointPaths`),className:R(n,`CommandClient`),streamClassName:R(n,`StreamCommandClient`),commands:[...t.commands.values()].map(t=>{let n=z(t.schema.key),i=new Set([`commandRequest`,`attributes`]);return{path:t.path,endpointMember:r.get(t),httpMethod:t.method,methodName:Ot(t),typeName:Tt(n),body:n,bodyKey:t.schema.key,optionalFields:Le(t.schema.schema,e.components),requestOptional:Fe(t.schema.schema),pathParameters:Ke(t.path,t.pathParameters).filter(e=>!pt.includes(e.name)).map(e=>({name:yt(e.name,i),pathName:e.name,type:Je(e)})),docs:[t.summary,t.description,`- operationId: \`${t.operation.operationId}\``,`- path: \`${t.path}\``]}})}}function Tt(e){return e.path===`@ahoo-wang/wow-client`?`${e.name}Command`:e.name.endsWith(xt)?void 0:`${e.name}${xt}`}function Et(e,t){for(let n of e){let e=`/${n.contextAlias}/${n.aggregateName}`,r=new Map;for(let n of t)n.info.path===e&&r.set(n.info.name,{holder:`the model of schema ${n.key}`,key:n.key});for(let{body:e,bodyKey:t}of n.commandClient.commands)e.path!==`@ahoo-wang/wow-client`&&r.set(e.name,{holder:`the model of schema ${t}`,key:t});for(let e of n.commandClient.commands){let{typeName:t,bodyKey:i}=e;if(t===void 0||e.body.path===`@ahoo-wang/wow-client`)continue;let a=r.get(t);if(a!==void 0&&a.bodyKey!==i)throw new o(`specification`,`Command ${e.methodName}() of aggregate ${n.contextAlias}.${n.aggregateName} generates the type ${t} for its body ${i}, but ${a.holder} already has that name. Rename the schema ${i} or ${a.key} in the document.`);r.set(t,{holder:`the type of command ${e.methodName}()`,key:i,bodyKey:i})}}}function Dt(e){let t=new Map,n=new Set;for(let r of e.commands.values()){let e=r.name.toUpperCase().replace(/[^\p{L}\p{N}_$]/gu,`_`);(!e||/^\p{N}/u.test(e))&&(e=`_${e}`);let i=e;for(let t=2;n.has(i);t++)i=`${e}_${t}`;n.add(i),t.set(r,i)}return t}function Ot(e){let t=v(e.name)||`_`;return/^\p{N}/u.test(t)?`_${t}`:t}function kt(e){let t=e.aggregate,n=v(t.aggregateName)||`_`;return{file:ht(t,`queryClient`),resourceName:e.resourceName,resourceAttribution:mt(e),state:z(e.state.key),fields:z(e.fields.key),eventTitlesName:R(t,`DomainEventTypeMapTitle`),eventTypeName:R(t,`DomainEventType`),events:[...e.events.values()].map(e=>({memberName:y(e.name),title:e.title,body:z(e.schema.key)})),factoryName:`${/^\p{N}/u.test(n)?`_`:``}${n}QueryClientFactory`}}function V(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var At=`types.ts`;function jt(e){return V(e.path,At)}function Mt(e){return`${e}/boundedContext.ts`}function Nt(e){return e.contextAlias!==void 0||e.aggregateTags.size>0}function Pt(e,t){return t?{...e,...t}:e}var Ft=[`httpRequest`,`attributes`];function It(e,t,n,r){return new Lt(e,t,n,r).clients()}var Lt=class{document;wow;config;warnings;basePath;wowDocument;constructor(e,t,n,r){this.document=e,this.wow=t,this.config=n,this.warnings=r,this.wowDocument=Nt(t),t.contextAlias&&(this.basePath={alias:t.contextAlias,constantName:B(t.contextAlias)})}clients(){let e=this.tags(),t=this.groupOperations(e),n=new Map;return[...t.keys()].sort().map(r=>{let i=z(r),a=i;for(let e=2;n.has(H(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(H(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(H(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=t.path;this.wow.contextAlias&&(i=V(this.wow.contextAlias,i)),i=V(i,Rt(r));let a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,basePath:this.basePath,methods:n.map(t=>this.method(e,r,t,a))}}method(e,t,n,r){let{operation:i}=n,a=this.methodName(e,t,n,r),o=new Set(Ft),s=this.parameters(e,n,o),c=this.body(i,o),l=[...s.filter(({parameter:e})=>e.required),...s.filter(({parameter:e})=>!e.required)].filter(({description:e})=>e);return{name:a,httpMethod:n.method,path:n.path,parameters:s.map(({parameter:e})=>e),body:c,returns:this.returns(i),docs:[i.summary,i.description,`- operationId: \`${i.operationId}\``,`- path: \`${n.path}\``,...l.map(({parameter:e,description:t})=>`@param ${e.name} - ${t.replace(/\s*\n\s*/g,` `)}`)]}}methodName(e,t,n,r){let i=n.operation.operationId,a=_t(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),s=r.get(a);if(s!==void 0)throw new o(`specification`,`Operations ${s} and ${i} of tag ${e.name} both generate the method ${t}.${a}(). Name one of them with apiClients["${e.name}"].methodNames in the generator configuration, or with the x-fetcher-method extension.`);return r.set(a,i),a}parameters(e,t,n){let r=We(t.operation,this.document.components??{}),i=[];for(let a of[`path`,`query`,`header`]){let o=r.filter(e=>e.in===a);for(let r of a===`path`?Ke(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:yt(r.name,n),location:a,parameterName:r.name,schema:r.schema,required:a===`path`||r.required===!0},description:r.description})}let a=r.filter(e=>e.in===`cookie`);return a.length>0&&this.warnings.push(`${t.method.toUpperCase()} ${t.path} leaves out its cookie parameter(s) ${a.map(e=>e.name).join(`, `)}: the browser sends cookies, and fetch cannot set them.`),i}ignoresPathParameter(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters??(this.wowDocument?pt:[])).includes(t)}body(e,t){if(!e.requestBody)return;let n=S(e.requestBody)?E(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=j(i,k,ge),o=yt(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Le(a.schema,this.document.components)}}:j(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:j(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(_e)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=I(e,this.document.components);if(!t)return{kind:`response`};let n=ye(t),r=n||xe(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=be(t);if(i){if(S(i)){let e=T(i,this.document.components);if(Oe(e)&&S(e.items)){let t=bt(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return Se(t)?{kind:`text`}:{kind:`response`}}groupOperations(e){let t=new Map;for(let n of this.document.endpoints){let r=`${n.method.toUpperCase()} ${n.path}`,i=n.operation.tags??[];if(i.length===0){this.warnings.push(`Skipping ${r}: it has no tag, and the tag names its API client.`);continue}let a=i.filter(t=>e.has(t));if(!(a.length<i.length)){if(!n.operation.operationId){this.warnings.push(`Skipping ${r}: it has no operationId, and the operationId names its method.`);continue}for(let e of a)t.has(e)||t.set(e,new Set),t.get(e).add(n)}}return t}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{!this.ignoresTag(t)&&!e.has(t)&&e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>{this.ignoresTag(t.name)||e.set(t.name,t)}),e}ignoresTag(e){return ft.has(e)||this.wow.aggregateTags.has(e)}};function Rt(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function H(e){return`${e.path}/${e.name}`.toLowerCase()}function zt(e){let t=new Set(e.contexts.keys());return e.contextAlias&&t.add(e.contextAlias),[...t].sort().map(e=>({alias:e,constantName:B(e),file:Mt(e)}))}function Bt(e,t){let n=e.components?.schemas;if(!n)return[];let r=Ht(t),i=Vt(e,t),a=Object.keys(n).filter(e=>!st(e,()=>z(e).name,r)||!e.startsWith(`wow.`)&&i.has(e));Ut(a);let o=Wt(t);return a.map(e=>{let r=n[e],i=z(e);return{key:e,info:i,file:jt(i),schema:r,docSchema:Pt(r,t.schemaDocOverrides.get(e)),emptyMessageBody:o.has(e)&&Gt(r)}})}function Vt(e,t){let n=new Set,r=new Set,i=e.components??{},a=e=>{if(typeof e!=`object`||!e||r.has(e))return;if(r.add(e),Array.isArray(e)){e.forEach(a);return}let{$ref:t}=e;if(typeof t==`string`&&t.startsWith(`#/components/`)){let[e,...r]=t.slice(C.length).split(`/`),o=r.join(`/`);e===`schemas`&&n.add(o),a(i[e]?.[o])}Object.values(e).forEach(a)};for(let{operation:n}of e.endpoints){let e=n.tags??[];e.length>0&&e.every(e=>!ft.has(e)&&!t.aggregateTags.has(e))&&a(n)}return n}function Ht(e){let t=new Set;for(let n of e.contexts.values())for(let e of n)ot(z(e.state.key).name).forEach(e=>t.add(e));return t}function Ut(e){let t=new Map;for(let n of e){let e=z(n),r=`${e.path===`/`?``:e.path}/${e.name}`;t.set(r,[...t.get(r)??[],n])}let n=[...t].filter(([,e])=>e.length>1);if(n.length!==0)throw new o(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function Wt(e){return new Set([...e.contexts.values()].flatMap(e=>[...e].flatMap(e=>[...[...e.commands.values()].map(e=>e.schema.key),...[...e.events.values()].map(e=>e.schema.key)])))}function Gt(e){return!S(e)&&e.type===`object`&&Object.keys(e.properties??{}).length===0&&(e.additionalProperties===void 0||e.additionalProperties===!1)&&!e.required?.length&&!N(e)&&e.enum===void 0&&e.const===void 0}function Kt(e,t,n){let r=[],i=zt(t),a=Bt(e,t),o=St(e,t);return Et(o,a),{model:{contexts:i,models:a,aggregates:o,apiClients:It(e,t,n,r)},warnings:r}}var qt=class{declarations=new Map;add(e,t){let n=this.declarations.get(e);n||(n=[],this.declarations.set(e,n));for(let e of t)n.some(t=>t.name===e)||n.push({name:e});return n}apply(e){for(let{moduleSpecifier:t,name:n,alias:r}of e){let e=this.add(t,[n]).find(e=>e.name===n);r!==void 0&&(e.alias=r)}}entries(){return[...this.declarations].flatMap(([e,t])=>t.map(({name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n}))}localNames(e){return[...this.declarations.values()].flat().filter(t=>t!==e).map(e=>e.alias??e.name)}structures(){return[...this.declarations].map(([e,t])=>({moduleSpecifier:e,namedImports:t.map(({name:e,alias:t})=>t===void 0?e:{name:e,alias:t})}))}},Jt=class{sourceFile;imports=new qt;statements=[];constructor(e){this.sourceFile=e}get directoryPath(){return this.sourceFile.getDirectoryPath()}add(e){return this.statements.push(e),e}build(){let t=[],n;for(let r of this.imports.structures())n={...r,kind:e.StructureKind.ImportDeclaration},t.push(n);for(let e of this.statements)n&&Zt(n,e)&&t.push(Xt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},Yt=class{open;modules=new Map;constructor(e){this.open=e}module(e){let t=this.open(e),n=t.getFilePath(),r=this.modules.get(n);return r||(r=new Jt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},Xt=e=>{e.blankLineIfLastNot()};function Zt(t,n){if(typeof n==`string`)return!1;switch(n.kind){case e.StructureKind.TypeAlias:case e.StructureKind.VariableStatement:return typeof t==`string`||t.kind!==n.kind;default:return!0}}function Qt(e){return e.map(e=>({...e,initializer:`${e.initializer},`}))}function $t(e,t){return{name:`[key: string]`,type:e,docs:t}}var en=`@`;function U(e,t,n){return e.imports.add(t,n)}function W(e,t,n){return U(e,G(e,t,n),[n.name])}function G(e,n,r){return r.path.startsWith(en)?r.path:tn(e.directoryPath,(0,t.join)(n,r.path,At))}function tn(e,n){let r=(0,t.relative)(e,n).split(t.sep).join(`/`);return r=r.endsWith(`.ts`)?r.replace(/\.ts$/,`.js`):`${r}/index.js`,r.startsWith(`.`)?r:`./${r}`}function nn(e,n,r,i){return U(e,tn(e.directoryPath,(0,t.join)(n,Mt(r))),[i])}function rn(e,t=`
2
+ `){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(an);return n.length>0?n.join(t):void 0}function an(e){return e.replace(/\*\//g,`*\\/`)}function K(e,t){let n=rn(t);n&&(e.docs=[...e.docs??[],n])}function on(e,t){let n=[e.title,e.description];return t&&n.push(`- key: ${t}`),e.format&&n.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),ln(n,e,`default`),ln(n,e,`example`),dn(n,e),fn(n,e),pn(n,e),n}function sn(e,t,n){K(e,on(t,n))}function cn(e,t,n,r=!1){let i=on(t,n);r&&un(i,`schema`,t),K(e,i)}function ln(e,t,n){let r=t[n];if(r){if(typeof r!=`object`){e.push(`- ${n}: \`${r}\``);return}un(e,n,r)}}function un(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function dn(e,t){let n=[`- Numeric Constraints`];t.minimum!==void 0&&n.push(` - minimum: ${t.minimum}`),t.maximum!==void 0&&n.push(` - maximum: ${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(` - exclusiveMinimum: ${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(` - exclusiveMaximum: ${t.exclusiveMaximum}`),t.multipleOf!==void 0&&n.push(` - multipleOf: ${t.multipleOf}`),n.length!==1&&e.push(...n)}function fn(e,t){let n=[`- String Constraints`];t.minLength!==void 0&&n.push(` - minLength: ${t.minLength}`),t.maxLength!==void 0&&n.push(` - maxLength: ${t.maxLength}`),t.pattern!==void 0&&n.push(` - pattern: ${t.pattern}`),n.length!==1&&e.push(...n)}function pn(e,t){let n=[`- Array Constraints`];t.minItems!==void 0&&n.push(` - minItems: ${t.minItems}`),t.maxItems!==void 0&&n.push(` - maxItems: ${t.maxItems}`),t.uniqueItems!==void 0&&n.push(` - uniqueItems: ${t.uniqueItems}`),n.length!==1&&e.push(...n)}function mn(e,t){let n;return{components:e,modelOf:n=>t.ofReference(n,e),namesAt(r){if(!n){n=new Map;for(let r of Object.keys(e?.schemas??{})){let e=t.ofKey(r),i=n.get(e.path);i||(i=[],n.set(e.path,i)),i.push(e.name,`${e.name}EnumText`)}}return n.get(r)??[]}}}var hn=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],gn=new Set([`string`,`number`,`boolean`]),_n=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function vn(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function q(e,t,n=new Set){if(S(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=T(e,t);return r?q(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(je(e)&&e.type===void 0){let r=e.allOf.map(e=>q(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>vn(e,i))?i:void 0}if(!(N(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:F(e.type)}}}function yn(e,t,n){let r=q(t,n);if(typeof r!=`object`)return!1;let i=q(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function bn(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>yn(e,n,t))}function xn(e){return e.nullable!==!0||M(e)||!N(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(S))}function Sn(e,t){return t.type===void 0||e===null&&t.nullable?!0:[t.type].flat().some(t=>t===`null`?e===null:t===`array`?Array.isArray(e):t===`object`?typeof e==`object`&&!!e&&!Array.isArray(e):t===`integer`?typeof e==`number`&&Number.isInteger(e):typeof e===t)}function J(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>J(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${y(e)}: ${J(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var Cn=class{scope;entries;requested=[];constructor(e){this.scope=e,this.entries=e.imports.entries().map(e=>({...e}))}get components(){return this.scope.context.components}imports(){return this.requested.map(({moduleSpecifier:e,name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n})}request(e){this.requested.includes(e)||this.requested.push(e)}reference(e){let t=this.scope.context.modelOf(e),{owner:n}=this.scope;if(n.path===t.path)return t.name;let r=this.scope.specifierOf(t),i=this.entries.find(e=>e.moduleSpecifier===r&&e.name===t.name);if(i||(i={moduleSpecifier:r,name:t.name},this.entries.push(i)),this.request(i),i.alias)return i.alias;let a=new Set([...hn,n.name,...n.path===void 0?[]:this.scope.context.namesAt(n.path),...this.entries.filter(e=>e!==i).map(e=>e.alias??e.name)]);if(!a.has(t.name))return t.name;let o=`_${t.name}`;for(;a.has(o);)o=`_${o}`;return i.alias=o,o}additionalProperties(e){return e.additionalProperties===!1||e.additionalProperties===void 0&&!e.required?.some(t=>!Object.hasOwn(e.properties??{},t))?``:e.additionalProperties===!0||e.additionalProperties===void 0?`[key: string]: any`:`[key: string]: ${this.additionalPropertyType(e)}`}additionalPropertyType(e){return this.type(typeof e.additionalProperties==`object`?e.additionalProperties:{})}requiredAdditionalPropertyType(e){return e.additionalProperties===!1?`never`:typeof e.additionalProperties==`object`?this.type(e.additionalProperties):`null | string | number | boolean | globalThis.Record<string, unknown> | readonly unknown[]`}propertyDefinitions(e){let{properties:t}=e;return Object.entries(t).map(([e,t])=>{let n=this.type(t),r=(Ie(t)?`readonly `:``)+y(e);if(!S(t)){let e=rn(on(t),`
3
+ * `);if(e)return`
4
+ /**
5
+ * ${e}
6
+ */
7
+ ${r}: ${n}
8
+ `}return`${r}: ${n}`})}objectType(e){let t=[];De(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${y(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Ne(e)&&P(e)?this.mapType(e):bn(e,this.components)?`globalThis.Record<string, ${this.additionalPropertyType(e)}>`:void 0,r=n?``:this.additionalProperties(e);if(r&&t.push(r),t.length===0)return`globalThis.Record<string, any>`;let i=`{\n ${t.join(`;
9
+ `)}; \n}`;return n?`(${i} & ${n})`:i}mapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?`any`:this.type(e.additionalProperties)}mapKeyType(e){let t=P(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>S(e)?this.components&&T(e,this.components):e,n=t(e),r=new Map,i=new Set,a=n?[n]:[];for(let e of a){if(r.has(e))continue;let n=[e.allOf,e.oneOf,e.anyOf].map(e=>e?.map(t)??[]);r.set(e,n);for(let e of n)for(let t of e)t&&!r.has(t)&&a.push(t);(e.type===`object`||e.type===`null`||Array.isArray(e.type)&&e.type.length>0&&e.type.every(e=>e===`object`||e===`null`))&&i.add(e)}let o=!0;for(;o;){o=!1;for(let[e,[t,n,a]]of r){if(i.has(e))continue;let r=e=>e!==void 0&&i.has(e);(t.some(r)||[n,a].some(e=>e.length>0&&e.every(r)))&&(i.add(e),o=!0)}}return n!==void 0&&i.has(n)}type(e){if(S(e))return this.reference(e);if(Array.isArray(e.type))return e.type.map(t=>{let n=this.type({...e,type:t});return/[|&]/.test(n)?`(${n})`:n}).join(` | `);if(xn(e))return`(${this.type({...e,nullable:!1})}) | null`;if(N(e)){let t=this.simpleComposition(e);if(t!==void 0)return t;let n=[`allOf`,`oneOf`,`anyOf`].flatMap(t=>{let n=e[t];return n?.length?[`(${n.map(n=>{let r=this.memberType(e,t,n);return r===`any`?`unknown`:/[|&]/.test(r)?`(${r})`:r}).join(t===`allOf`?` & `:` | `)})`]:[]}),r=n.length===1?n[0]:`(${n.join(` & `)})`,i={...e,oneOf:void 0,anyOf:void 0,allOf:void 0},a=this.type(i),o=a===`any`?r:`(${r} & (${a}))`;return this.objectConstrained(e)?`globalThis.Exclude<${o}, string | number | boolean | readonly unknown[]> & ({ readonly [globalThis.Symbol.iterator]?: never } | null)`:o}if(e.const!==void 0){if(!Sn(e.const,e))return`never`;let t=J(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!M(e))return`(${this.type({...e,nullable:!1})}) | null`;if(M(e)){let t=e.enum.filter(t=>Sn(t,e)).map(e=>J(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||gn.has(n)?t:`(${t}) & (${n})`}return Ne(e)&&!e.required?.length?this.mapType(e):e.type===`array`?Me(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?F(e.type):e.required?.length||Object.keys(e.properties??{}).length>0?`(${this.objectType({...e,type:`object`,additionalProperties:e.additionalProperties??!0})} | null | string | number | boolean | readonly unknown[])`:`any`}simpleComposition(e){let t=[`allOf`,`oneOf`,`anyOf`].filter(t=>e[t]?.length);if(t.length!==1)return;let[n]=t;if(Object.keys(e).filter(e=>e!==n&&e!==`discriminator`&&!e.startsWith(`x-`)&&!_n.has(e)).length>0)return;let r=e[n],i=e=>n!==`allOf`&&[e.type].flat().every(e=>e===`null`)&&e.type!==void 0&&Object.keys(e).every(e=>e===`type`||_n.has(e));if(!r.every(e=>S(e)||i(e)))return;let a=r.map(t=>S(t)?this.memberType(e,n,t):`null`);return[...new Set(a)].join(n===`allOf`?` & `:` | `)}memberType(e,t,n){let r=this.type(n),i=e.discriminator;if(t===`allOf`||!i?.propertyName||!S(n))return r;let a=pe(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>b(e)).join(` | `);return`(${r} & { ${y(i.propertyName)}: ${s} })`}};function Y(e,t){let n=new Cn(e);return{text:t(n),imports:n.imports()}}function wn(e,t){return Y(t,t=>t.type(e))}function Tn(e,t){return Y(t,t=>t.additionalProperties(e))}function En(e,t){return Y(t,t=>t.additionalPropertyType(e))}function Dn(e,t){return Y(t,t=>t.requiredAdditionalPropertyType(e))}function On(e,t){return Y(t,t=>t.mapValueType(e))}var kn=`@ahoo-wang/fetcher`,An=[`ContentTypeValues`,`ResultExtractors`],jn=`@ahoo-wang/fetcher-decorator`,Mn=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Nn={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Pn={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Fn=`{
10
+ headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
11
+ resultExtractor: JsonEventStreamResultExtractor,
12
+ }`,In=`COMMAND_STREAM_ENDPOINT`;function Ln(e){U(e,kn,An)}function Rn(e){U(e,jn,Mn)}function zn(t,n,r=[],i=[],a){return n.add({kind:e.StructureKind.Class,name:t,isExported:!0,typeParameters:i,extends:a,decorators:[{name:`api`,arguments:r}]})}function Bn(t,n){if(t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],n===void 0){t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]});return}t.properties=[...t.properties??[],{name:`apiMetadata`,type:`ApiMetadata`,isReadonly:!0}],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0}],statements:`this.apiMetadata = { ${n}, ...apiMetadata };`,docs:["@param apiMetadata - Merged over the defaults, so passing only a `fetcher` keeps the base path."]})}function Vn(e){return e===`delete`?`del`:e}var Hn=`@ahoo-wang/fetcher-eventstream`;function Un(e){U(e,Hn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function Wn(e,t){let n=t.modules.module(e.file);Ln(n),Rn(n),Un(n);let r=zn(e.className,n);K(r,[e.description]);let i;e.basePath&&(nn(n,t.outputDir,e.basePath.alias,e.basePath.constantName),i=`basePath: ${e.basePath.constantName}`),Bn(r,i);let a=Gn(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(Kn(t,a))}function Gn(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>G(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=wn(e,r);return t.imports.apply(n.imports),n.text}}}function Kn(e,t){let n=[],r=[];for(let i of e.parameters)(i.required?n:r).push({name:i.name,type:i.schema?t.resolveType(i.schema):`string`,hasQuestionToken:!i.required,decorators:[{name:i.location,arguments:[b(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:qn(e.body,t),hasQuestionToken:!e.body.required,decorators:[{name:`body`,arguments:[]}]});let i=[...n,...r,{name:`httpRequest`,hasQuestionToken:!0,type:`ParameterRequest`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}],a=Jn(e.returns,t),o=b(e.path),s={name:e.name,decorators:[{name:Vn(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return K(s,[...e.docs]),s}function qn(e,t){let{content:n}=e;switch(n.kind){case`json`:{let e=t.resolveType(n.schema),r=n.optionalFields;return r.length===0||/[|&]/.test(e)||e===`any`?e:(U(t.module,kn,[`PartialBy`]),`PartialBy<${e}, ${r.map(b).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function Jn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Pn:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Fn};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Fn}}case`text`:return Pn;case`response`:return Nn}}var Yn=`DEFAULT_COMMAND_CLIENT_OPTIONS`;function Xn(t,n){let r=t.commandClient;if(r.commands.length===0)return;let i=n.modules.module(r.file);i.add({kind:e.StructureKind.Enum,name:r.endpointPathsName,isExported:!0,members:Qt(r.commands.map(e=>({name:e.endpointMember,initializer:b(e.path)})))});let a=new Set,o=r.commands.map(e=>Zn(i,n.outputDir,e,a));nn(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:Yn,type:`ApiMetadata`,initializer:`{
13
+ basePath: ${t.context.constantName}
14
+ }`}],isExported:!1}),U(i,L,[`CommandRequest`,`CommandResult`,`CommandResultEventStream`,`CommandBody`,In]),U(i,`@ahoo-wang/fetcher`,[`PartialBy`]),Rn(i);let s=zn(r.className,i,[],[`R = CommandResult`]);Bn(s,`...${Yn}`);for(let[e,t]of r.commands.entries()){let n=Qn(t,o[e]),i={name:t.methodName,decorators:[{name:Vn(t.httpMethod),arguments:[`${r.endpointPathsName}.${t.endpointMember}`]}],parameters:n,returnType:`Promise<R>`,statements:`throw autoGeneratedError(${n.map(e=>e.name).join(`,`)});`};(s.methods??=[]).push(i),K(i,[...t.docs])}zn(r.streamClassName,i,[`''`,In],[],`${r.className}<CommandResultEventStream>`)}function Zn(t,n,r,i){if(r.body.path===`@ahoo-wang/wow-client`)return U(t,L,[r.typeName]),r.typeName;W(t,n,r.body);let a=r.body.name,o=r.optionalFields.map(b).join(` | `);o!==``&&(a=`PartialBy<${a},${o}>`);let s=`CommandBody<${a}>`;return r.typeName===void 0?s:i.has(r.typeName)?r.typeName:(i.add(r.typeName),t.add({kind:e.StructureKind.TypeAlias,name:r.typeName,type:s,isExported:!0}),r.typeName)}function Qn(e,t){return[...e.pathParameters.map(e=>({name:e.name,type:e.type,hasQuestionToken:!1,decorators:[{name:`path`,arguments:[b(e.pathName)]}]})),{name:`commandRequest`,hasQuestionToken:e.requestOptional,type:`CommandRequest<${t}>`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}]}function $n(e){return mn(e,{ofKey:e=>z(e),ofReference:bt})}function er(t,n){let r=n.modules.module(t.file);if(t.emptyMessageBody){cn(r.add({kind:e.StructureKind.TypeAlias,name:t.info.name,type:`globalThis.Record<string, never>`,isExported:!0}),t.docSchema,t.key,n.schemaDocs===`full`);return}new nr(t,r,n).write()}function tr(e){let t=new Set,n=new Map;for(let r of e){let e=ae(r),i=[e];/^\d/.test(r)||i.push(r);let a=i.find(e=>!t.has(e));for(let n=2;a===void 0;n++)t.has(`${e}_${n}`)||(a=`${e}_${n}`);t.add(a),n.set(r,y(a))}return n}var nr=class{model;module;target;modelInfo;components;constructor(e,t,n){this.model=e,this.module=t,this.target=n,this.modelInfo=e.info,this.components=n.types.components,this.scope={context:n.types,owner:e.info,specifierOf:e=>G(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&cn(e,this.model.docSchema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return S(e)?this.processTypeAlias(e):M(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||N(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):De(e)?this.processInterface(e):Ne(e)&&typeof e.additionalProperties==`object`&&!P(e)&&!e.required?.length?this.processIndexSignature(e):Oe(e)?this.processArray(e):N(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(wn(e,this.scope))}processEnum(t){let n=Ee(t);if(n){let t=tr(Object.keys(n));this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name+`EnumText`,isExported:!0,members:[...t].map(([e,t])=>({name:t,initializer:J(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=tr(r);return N(t)||t.const!==void 0||t.type!==void 0&&t.type!==`string`||t.enum.some(e=>typeof e!=`string`)?(r.length&&this.module.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:this.modelInfo.name,initializer:e=>{e.inlineBlock(()=>{for(let t of r)e.write(`${i.get(t)}: `).quote(t).write(`,`).newLine()}),e.write(` as const`)}}]}),this.processTypeAlias(t)):this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name,isExported:!0,members:r.map(e=>({name:i.get(e),initializer:J(e)}))})}addPropertyToInterface(e,t,n){let r={name:y(t),type:this.resolveType(n),isReadonly:Ie(n)};(e.properties??=[]).push(r),sn(r,n)}processInterface(t){if(bn(t,this.components))return this.processTypeAlias(t);let n=[],r=this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:n}),i=t.properties||{};Object.entries(i).forEach(([e,t])=>{this.addPropertyToInterface(r,e,t)});for(let e of t.required??[])Object.hasOwn(i,e)||n.push({name:y(e),type:this.emit(Dn(t,this.scope))});return this.emit(Tn(t,this.scope))&&n.push($t(this.emit(En(t,this.scope)),[`Additional properties`])),r}processArray(t){let n=this.resolveType(t.items);return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:Me(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[$t(this.emit(On(t,this.scope)))]})}processComposition(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}processTypeAlias(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}},rr=`DEFAULT_QUERY_CLIENT_OPTIONS`;function ir(t,n){let r=t.queryClient,i=n.modules.module(r.file);U(i,L,[`QueryClientFactory`,`QueryClientOptions`,`ResourceAttributionPathSpec`]),nn(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:rr,type:`QueryClientOptions`,initializer:`{
15
+ contextAlias: ${t.context.constantName},
16
+ aggregateName: ${b(r.resourceName)},
17
+ resourceAttribution: ${r.resourceAttribution},
18
+ }`}],isExported:!1}),i.add({kind:e.StructureKind.Enum,name:r.eventTitlesName,isExported:!0,members:Qt(r.events.map(e=>({name:e.memberName,initializer:b(e.title)})))});for(let e of r.events)W(i,n.outputDir,e.body);i.add({kind:e.StructureKind.TypeAlias,isExported:!0,name:r.eventTypeName,type:r.events.map(e=>e.body.name).join(` | `)||`never`}),W(i,n.outputDir,r.state),W(i,n.outputDir,r.fields),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:r.factoryName,initializer:`new QueryClientFactory<${r.state.name}, \`\${${r.fields.name}}\`, ${r.eventTypeName}>(${rr})`}],isExported:!0})}function ar(e,t){e.contexts.forEach(e=>or(e,t)),e.models.forEach(e=>er(e,t)),e.aggregates.forEach(e=>ir(e,t)),e.aggregates.forEach(e=>Xn(e,t)),e.apiClients.forEach(e=>Wn(e,t))}function or(e,t){t.modules.module(e.file).add(`export const ${e.constantName} = ${b(e.alias)};`)}function sr(e,t){let n=[];return cr(e,t,n),n}function cr(e,t,n){let r=[];for(let t of e.getSourceFiles()){let e=t.getBaseName();e.endsWith(`.ts`)&&e!==`index.ts`&&r.push({specifier:`./${t.getBaseNameWithoutExtension()}.js`,exports:ur(t)})}for(let i of e.getDirectories()){let e=cr(i,t,n);e&&r.push({specifier:`./${i.getBaseName()}/index.js`,exports:e})}let i=e.getPath();return r.length===0?e.getProject().getSourceFile(`${i}/index.ts`)?new Map:void 0:lr(i,r,t,n)}function lr(e,t,n,r){let i=new Map;for(let e of t)for(let t of e.exports.keys())i.set(t,[...i.get(t)??[],e.specifier]);let a=[...i].filter(([,e])=>e.length>1).map(([e])=>e).sort();for(let t of a)r.push(`${t} is exported by both ${i.get(t).join(` and `)} in ${e}; its index leaves it out, so import it from its own module.`);let o=n(e);o.removeText();let s=new Map;for(let e of t){let t=[...e.exports].filter(([e])=>!a.includes(e)).sort(([e],[t])=>x(e,t));t.forEach(([e,t])=>s.set(e,t)),t.length===e.exports.size?o.addExportDeclaration({moduleSpecifier:e.specifier}):t.length>0&&o.addExportDeclaration({moduleSpecifier:e.specifier,namedExports:t.map(([e,t])=>({name:e,isTypeOnly:t}))})}return o.getStatements().length===0&&o.addStatements(`export {};`),s}function ur(t){let n=new Map;for(let[r,i]of t.getExportedDeclarations())n.set(r,i.every(t=>e.Node.isInterfaceDeclaration(t)||e.Node.isTypeAliasDeclaration(t)));return n}function dr(t){let n=t;for(let t=n.getParent();t;n=t,t=t.getParent()){if(e.Node.isQualifiedName(t)){if(t.getLeft()!==n)return!1;continue}if(e.Node.isPropertyAccessExpression(t)){if(t.getExpression()!==n)return!1;continue}if(e.Node.isExpressionWithTypeArguments(t)){let n=t.getParent(),r=n?.getParent();return!(e.Node.isHeritageClause(n)&&n.getToken()===e.SyntaxKind.ExtendsKeyword&&(e.Node.isClassDeclaration(r)||e.Node.isClassExpression(r)))}return e.Node.isTypeNode(t)}return!1}function fr(t){let n=t.getImportDeclarations().filter(e=>!e.getDefaultImport()&&!e.getNamespaceImport()&&e.getNamedImports().length>0);if(n.length===0)return[];let r=new Set(n.flatMap(e=>e.getNamedImports().map(e=>(e.getAliasNode()??e.getNameNode()).getText()))),i=new Set;return t.forEachDescendant((t,n)=>{if(e.Node.isImportDeclaration(t)){n.skip();return}if(e.Node.isIdentifier(t)&&r.has(t.getText())&&!dr(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>pr(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function pr(e,t){let n=e.getNamedImports(),r=n.map(t),i=r.every(Boolean);return()=>{n.forEach((e,t)=>{let n=!i&&r[t];e.isTypeOnly()!==n&&e.setIsTypeOnly(n)}),e.isTypeOnly()!==i&&e.setIsTypeOnly(i)}}function mr(e){let t=e.flatMap(fr);for(let e of t)e()}var hr=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function gr(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!hr.has(t.getCode())||t.getSourceFile()!==r)continue;let i=e.ts.flattenDiagnosticMessageText(t.compilerObject.messageText,` `);n.push(`${r.getFilePath()}:${t.getLineNumber()??0} TS${t.getCode()} ${i}`)}if(n.length>0)throw Error(`The generated code does not compile; nothing was written. This is a wow-generator bug:\n${n.join(`
19
+ `)}`)}var _r=`// Code generated by wow-generator. DO NOT EDIT.
20
+
21
+ `,vr={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function yr(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(vr),n.organizeImports(vr)}),mr(e),gr(e);for(let t of e)t.insertText(0,_r)}var br=3e4;function xr(e){return/^https?:\/\//i.test(e)}function Sr(e,t={}){return xr(e)?Cr(e,t):Tr(e)}async function Cr(e,t={}){let n=t.timeoutMs??3e4,r;try{let i=AbortSignal.timeout(n);r=await fetch(e,{headers:t.headers,signal:t.signal?AbortSignal.any([t.signal,i]):i})}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no response within ${n} ms`:wr(e);throw Error(t,{cause:e})}if(!r.ok){let e=[r.status,r.statusText].filter(Boolean).join(` `);throw Error(`HTTP ${e}`)}return await r.text()}function wr(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error&&t.message?`${e.message} (${t.message})`:e.message}function Tr(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Er(e,t){let n;try{n=await Sr(e,t)}catch(t){throw new o(`input`,`Cannot read the OpenAPI document ${e}: ${s(t)}`,{cause:t})}let r;try{r=Or(n)}catch(t){throw new o(`input`,`Cannot parse the OpenAPI document ${e}: ${s(t)}`,{cause:t})}return Dr(r,e)}function Dr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new o(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new o(`input`,`${t} is a Swagger ${String(n.swagger)} document; wow-generator reads OpenAPI 3.x only. Convert it first, for example with swagger2openapi.`);if(typeof n.openapi!=`string`||!/^3\.\d+/.test(n.openapi))throw new o(`input`,`${t} is not an OpenAPI 3.x document: its "openapi" field is ${n.openapi===void 0?`missing`:JSON.stringify(n.openapi)}.`);if(typeof n.info!=`object`||n.info===null||Array.isArray(n.info))throw new o(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Or(e){switch(kr(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function kr(e){let t=e.trimStart();if(t.startsWith(`{`)||t.startsWith(`[`))return`json`;if(t.startsWith(`-`)||t.startsWith(`%YAML`))return`yaml`;try{return JSON.parse(t),`json`}catch{if(t.length>0)return`yaml`}throw Error(`Unable to infer file format`)}var Ar=`./fetcher-generator.config.json`;async function jr(e,t,n){if(e!==void 0)return{...await Pr({path:e,explicit:!0},t,n),origin:X(e)};for(let e of[i,Ar]){let r=await Pr({path:e,explicit:!1},t,n);if(r===void 0)continue;let a=[...r.warnings];return e===`./fetcher-generator.config.json`&&a.push(`${X(e)} uses the deprecated name; rename it to ${i.slice(2)}. The old name is no longer read from v10.`),{config:r.config,origin:X(e),warnings:a}}return t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}}var Mr=[`apiClients`],Nr=[`ignorePathParameters`,`methodNames`];async function Pr(e,t,n){let r=X(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await Sr(e.path,n)}catch(n){if(!e.explicit&&Fr(n)){t.debug(`No configuration file at ${r}`);return}throw new o(`configuration`,`Cannot read configuration ${r}: ${s(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Or(i)}catch(e){throw new o(`configuration`,`Cannot parse configuration ${r}: ${s(e)}`,{cause:e})}let c=Lr(a,r);return t.debug(`Configuration loaded from ${r}: ${zr(c.config)}`),c}function X(e){return xr(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Fr(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function Z(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ir(e,t,n,r,i){let a=Object.keys(r).filter(e=>!i.includes(e));a.length&&e.push(`Ignoring unknown ${n} option(s) in ${t}: ${a.join(`, `)}. Known option(s): ${i.join(`, `)}`)}function Lr(e,t){if(!Q(e))throw new o(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${Z(e)}`);let n=[];return Ir(n,t,`configuration`,e,Mr),Rr(e.apiClients,t,n),{config:e,warnings:n}}function Rr(e,t,n){if(e!==void 0){if(!Q(e))throw new o(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${Z(e)}`);for(let[r,i]of Object.entries(e)){if(!Q(i))throw new o(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${Z(i)}`);Ir(n,t,`apiClients["${r}"]`,i,Nr);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new o(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${Z(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!Q(a))throw new o(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${Z(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!p(n))throw new o(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function zr(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}function Br(e){return{openAPI:e,components:e.components,endpoints:Be(e.paths,e.components)}}var Vr=`.wow-generator.json`,Hr=`.fetcher-generator.json`,Ur=class e{project;outputPath;outputDir;previous;legacyManifest;written=new Set;stale=new Set;constructor(e,t,n,r,i){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r,this.legacyManifest=i}static open(n,r,i){let a=n.getFileSystem(),s=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,Hr),l=a.fileExistsSync(c)?c:void 0,u=(0,t.join)(r,Vr);!a.fileExistsSync(u)&&l&&(u=l);let d=new Map;if(a.fileExistsSync(u)){let e=Wr(u,a.readFileSync(u));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(qr(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new o(`output`,`Invalid generated file entry in ${u}: ${n}`);d.set(e,i)}}let f=new Set([...i?.written??[],...d.keys()]);for(let e of n.getSourceFiles())f.has(e.getFilePath())&&e.forget();return new e(n,s,r,d,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=V(t,e);qr(t,n);let r=this.project.getSourceFile(n)??this.project.createSourceFile(n,``,{overwrite:!0}),i=r.getFilePath();return this.written.has(i)||(r.removeText(),this.written.add(i)),r}forgetStale(){for(let[e,t]of this.previous)!this.written.has(e)&&this.isUnchanged(e,t)&&this.stale.add(e);for(let e of this.project.getSourceFiles())this.stale.has(e.getFilePath())&&e.forget()}async commit(e){e?.throwIfAborted();let n=this.project.getFileSystem(),r=new Set([...this.written].map(e=>e.toLowerCase()));for(let e of this.stale)!this.written.has(e)&&r.has(e.toLowerCase())&&this.isUnchanged(e,this.previous.get(e))&&(await $(`delete`,e,()=>n.delete(e)),this.stale.delete(e));let i=[...this.written].sort().map(e=>this.project.getSourceFileOrThrow(e));(await Promise.allSettled(i.map(e=>e.save()))).forEach((e,t)=>{if(e.status===`rejected`)throw Kr(`write`,i[t].getFilePath(),e.reason)}),e?.throwIfAborted();for(let e of this.stale)!this.written.has(e)&&this.isUnchanged(e,this.previous.get(e))&&await $(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Vr),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),Gr(n.readFileSync(e.getFilePath()))]))},null,2)+`
22
+ `;await $(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)});let s=this.legacyManifest;s&&n.fileExistsSync(s)&&await $(`delete`,s,()=>n.delete(s))}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(qr(n.realpathSync(this.outputDir),n.realpathSync(e)),Gr(n.readFileSync(e))===t):!1}};function Wr(e,t){let n=`delete it; without it this run cannot remove the stale files of the last run`,r;try{r=JSON.parse(t)}catch(t){throw new o(`output`,`Cannot parse the generation manifest ${e}: ${s(t)}. Resolve the merge conflict in it if it has one, or ${n}.`,{cause:t})}let i=r?.version;if(typeof i==`number`&&Number.isInteger(i)&&i>1)throw new o(`output`,`The generation manifest ${e} was written by a newer wow-generator (manifest version ${i}); this one reads version 1. Upgrade wow-generator.`);if(i!==1||!r.files||typeof r.files!=`object`||Array.isArray(r.files))throw new o(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function Gr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Kr(e,t,n){return n instanceof o?n:new o(`output`,`Cannot ${e} ${t}: ${s(n)}`,{cause:n})}async function $(e,t,n){try{await n()}catch(n){throw Kr(e,t,n)}}function qr(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),s=(0,t.relative)(i,a);if(s===``||s.startsWith(`..`)||(0,t.isAbsolute)(s))throw new o(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}function Jr(e){let{openAPI:t,components:n,endpoints:r}=e,i=[],a=new Map,s=new Set,c=t.tags??[],l=new Set(c.map(e=>e.name)),u=new Set(r.flatMap(e=>e.operation.tags??[]).filter(e=>!l.has(e))),d=new Map;for(let e of[...c,...[...u].map(e=>({name:e}))]){let t=$e(e);t&&d.set(e.name,{aggregate:t,commands:new Map,events:new Map})}let f=e=>(e.tags??[]).flatMap(e=>{let t=d.get(e);return t?(s.add(e),[t]):[]}),p=(e,t,n)=>{let r=a.get(e.key);r||(r={},a.set(e.key,r));let i=t in r?r[t]:e.schema[t];r[t]=i||n},m=(e,t)=>new o(`specification`,`Cannot read the Wow metadata of ${e.operationId}: ${t}. wow-generator reads documents from Wow ${Ye} or later.`),h=(e,t)=>{let n=it.exec(t)?.[1];n&&e.forEach(e=>{e.resourceName??=n})},ee=e=>{let{operation:t,path:r}=e;if(t.operationId===`wow.command.send`)return;let a=et(t.operationId);if(!a)return;let s=I(t),c=new Set;for(;s&&S(s)&&s.$ref!==`#/components/responses/wow.CommandOk`;){if(!s.$ref.startsWith(de))return;if(c.has(s.$ref))throw new o(`specification`,`Cyclic component reference: ${s.$ref}`);c.add(s.$ref),s=n?.responses?.[s.$ref.slice(de.length)]}if(!s||!S(s)||s.$ref!==`#/components/responses/wow.CommandOk`)return;let l=f(t);if(!t.requestBody)return;let u=Ge(t,n??{}),d=(S(t.requestBody)?E(t.requestBody,n??{}):t.requestBody)?.content?.[k]?.schema;if(!S(d)){l.length>0&&i.push(`Skipping command ${t.operationId} (${e.method.toUpperCase()} ${r}): its application/json request body is not a $ref to a component schema.`);return}let m=O(d,n??{});if(!m.schema)return;p(m,`title`,t.summary),p(m,`description`,t.description);let h={name:a,method:e.method,path:r,pathParameters:u,summary:t.summary,description:t.description,schema:m,operation:t};l.forEach(e=>{e.commands.set(a,h)})},te=({operation:e,path:t})=>{if(!e.operationId?.endsWith(`.snapshot_state.single`))return;let r=f(e);h(r,t);let i=Ue(e,n);if(!S(i)){if(r.length>0)throw m(e,`its 200 application/json response is not a $ref to the state schema`);return}let a=O(i,n);r.forEach(e=>{e.state=a})},g=({operation:e})=>{if(!n||!e.operationId?.endsWith(`.event.list_query`))return;let t=f(e);if(t.length===0)return;let r=Ue(e,n);if(S(r))return;let i=r?.items;if(!S(i))throw m(e,`its 200 application/json response is not an array of a $ref to the event stream schema`);let a=Yr(T(i,n),[`properties`,`body`,`items`,`anyOf`]);if(!Array.isArray(a))throw m(e,`the event stream schema ${i.$ref} has no properties.body.items.anyOf listing the domain events`);let o=a.map((t,r)=>{let a=Yr(t,[`properties`,`name`,`const`]),o=Yr(t,[`properties`,`body`]);if(typeof a!=`string`||!S(o))throw m(e,`domain event ${r} of ${i.$ref} needs a properties.name.const and a properties.body that is a $ref to the event schema`);let s=O(o,n);return p(s,`title`,t.title),{title:t.title??a,name:a,schema:s}});t.forEach(e=>{o.forEach(t=>{e.events.set(t.name,t)})})},ne=({operation:e,path:t})=>{if(!n||!e.operationId?.endsWith(`.snapshot.count`))return;let r=f(e);if(r.length===0)return;h(r,t);let i=e.requestBody?S(e.requestBody)?E(e.requestBody,n):e.requestBody:void 0;if(!i)throw m(e,`it has no request body`);let a=i[rt],o;if(a!==void 0){if(!S(a))throw m(e,`${rt} must be a schema reference`);o=a}else{let t=i.content?.[k]?.schema,r=(S(t)?T(t,n):void 0)?.properties?.field;if(!S(r))throw m(e,`its request body has no ${rt}, and its condition schema has no field $ref to read the query fields from`);o=r}let s=O(o,n);r.forEach(e=>{e.fields=s})};for(let e of r)ee(e),te(e),g(e),ne(e);let _=new Map;for(let[e,t]of d){if(!t.state||!t.fields){if(s.has(e)){let n=[t.state?void 0:`${e}${tt}`,t.fields?void 0:`${e}${nt}`].filter(Boolean);i.push(`Skipping aggregate ${e}: the document has no ${n.join(` or `)} operation, so it generates neither command nor query clients for it.`)}continue}let n=t.aggregate.contextAlias,r=_.get(n);r||(r=new Set,_.set(n,r)),r.add({...t,resourceName:t.resourceName??t.aggregate.aggregateName})}return{contextAlias:Ze(t),contexts:_,aggregateTags:s,schemaDocOverrides:a,warnings:i}}function Yr(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}var Xr=Symbol(`project`),Zr=Symbol(`signal`),Qr=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new l,this.signal=t[Zr],this.project=t[Xr]??$r(t.tsConfigFilePath),this.project.manipulationSettings.set({indentationText:e.IndentationText.TwoSpaces,quoteKind:e.QuoteKind.Single,useTrailingCommas:!0}),this.logger.debug(`Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`)}async generate(){let{logger:e,signal:t,options:n}=this,r=0,i=t=>{for(let n of t)r++,e.warn(n)};e.debug(`Starting code generation from OpenAPI specification`),e.debug(`Work directory: ${process.cwd()}`),e.debug(`Input path: ${n.inputPath}`),e.debug(`Output directory: ${n.outputDir}`);let a={headers:n.headers,timeoutMs:n.timeoutMs,signal:t},s=await jr(n.configPath,e,a);i(s.warnings),t?.throwIfAborted(),e.debug(`Parsing OpenAPI specification`);let c=await Er(n.inputPath,a);t?.throwIfAborted(),e.debug(`OpenAPI specification parsed successfully`);let l=ce(c);if(l.length>0)throw new o(`specification`,`${n.inputPath} has ${l.length} $ref(s) that point at nothing: ${l.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${l.length>10?`, …`:``}`);let u=Br(c);e.debug(`Resolving bounded context aggregates`);let d=Jr(u);i(d.warnings),e.debug(`Resolved ${d.contexts.size} bounded context aggregates`);let f=Ur.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=Kt(u,d,s.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new Yt(e=>f.claim(e));ar(p.model,{modules:m,outputDir:n.outputDir,types:$n(u.components),schemaDocs:n.schemaDocs??`summary`}),m.build(),e.debug(`Generated modules written`),f.forgetStale();let h=this.project.getDirectory(n.outputDir);return h?(e.debug(`Generating index files`),i(sr(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),yr(h.getDescendantSourceFiles().filter(e=>f.files.has(e.getFilePath())),e),e.debug(`Source files optimized successfully`)):e.debug(`Output directory not found.`),e.debug(`Saving project to disk`),await f.commit(t),e.debug(`Code generation completed successfully`),{files:[...f.files].sort(),configPath:s.origin,warnings:r}}};function $r(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new o(`configuration`,`Cannot read the TypeScript configuration ${t}: ${s(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Zr}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return br}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Qr}});
23
+ //# sourceMappingURL=codeGenerator-DpDTDC4o.cjs.map