@ahoo-wang/wow-generator 10.0.0-beta.1 → 10.0.0-beta.11

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 (71) hide show
  1. package/README.md +2 -1
  2. package/README.zh-CN.md +1 -1
  3. package/dist/analysis/clientNames.d.cts +0 -9
  4. package/dist/analysis/clientNames.d.ts +0 -9
  5. package/dist/cli.cjs +1 -1
  6. package/dist/cli.cjs.map +1 -1
  7. package/dist/cli.js +2 -2
  8. package/dist/{codeGenerator-Cxlr_VOh.js → codeGenerator-CXowDsB9.js} +1233 -867
  9. package/dist/codeGenerator-CXowDsB9.js.map +1 -0
  10. package/dist/codeGenerator-q59QJpfT.cjs +38 -0
  11. package/dist/codeGenerator-q59QJpfT.cjs.map +1 -0
  12. package/dist/emitters/manifest/aggregate.d.cts +4 -0
  13. package/dist/emitters/manifest/aggregate.d.ts +4 -0
  14. package/dist/emitters/manifest/commandClient.d.cts +4 -0
  15. package/dist/emitters/manifest/commandClient.d.ts +4 -0
  16. package/dist/emitters/manifest/contextClient.d.cts +8 -0
  17. package/dist/emitters/manifest/contextClient.d.ts +8 -0
  18. package/dist/emitters/manifest/contract.d.cts +17 -0
  19. package/dist/emitters/manifest/contract.d.ts +17 -0
  20. package/dist/emitters/manifest/generatedModule.d.cts +19 -0
  21. package/dist/emitters/manifest/generatedModule.d.ts +19 -0
  22. package/dist/emitters/manifest/queryClient.d.cts +4 -0
  23. package/dist/emitters/manifest/queryClient.d.ts +4 -0
  24. package/dist/emitters/manifest/routing.d.cts +9 -0
  25. package/dist/emitters/manifest/routing.d.ts +9 -0
  26. package/dist/emitters/manifest/serviceRoutes.d.cts +11 -0
  27. package/dist/emitters/manifest/serviceRoutes.d.ts +11 -0
  28. package/dist/emitters/manifest/textNumbers.d.cts +24 -0
  29. package/dist/emitters/manifest/textNumbers.d.ts +24 -0
  30. package/dist/emitters/manifest/typeDeclarations.d.cts +4 -0
  31. package/dist/emitters/manifest/typeDeclarations.d.ts +4 -0
  32. package/dist/emitters/manifestClients.d.cts +1 -5
  33. package/dist/emitters/manifestClients.d.ts +1 -5
  34. package/dist/emitters/models.d.cts +1 -1
  35. package/dist/emitters/models.d.ts +1 -1
  36. package/dist/emitters/target.d.cts +1 -1
  37. package/dist/emitters/target.d.ts +1 -1
  38. package/dist/index.cjs +1 -1
  39. package/dist/index.js +1 -1
  40. package/dist/manifest/aggregates.d.cts +6 -0
  41. package/dist/manifest/aggregates.d.ts +6 -0
  42. package/dist/manifest/analyze.d.cts +1 -186
  43. package/dist/manifest/analyze.d.ts +1 -186
  44. package/dist/manifest/document.d.cts +4 -0
  45. package/dist/manifest/document.d.ts +4 -0
  46. package/dist/manifest/model.d.cts +180 -0
  47. package/dist/manifest/model.d.ts +180 -0
  48. package/dist/manifest/names.d.cts +30 -0
  49. package/dist/manifest/names.d.ts +30 -0
  50. package/dist/manifest/schemaTypes.d.cts +46 -0
  51. package/dist/manifest/schemaTypes.d.ts +46 -0
  52. package/dist/manifest/serviceRoutes.d.cts +45 -0
  53. package/dist/manifest/serviceRoutes.d.ts +45 -0
  54. package/dist/manifest/textNumbers.d.cts +108 -0
  55. package/dist/manifest/textNumbers.d.ts +108 -0
  56. package/dist/manifest/typeText.d.cts +11 -0
  57. package/dist/manifest/typeText.d.ts +11 -0
  58. package/dist/naming/naming.d.cts +9 -0
  59. package/dist/naming/naming.d.ts +9 -0
  60. package/dist/types/indexSignature.d.cts +18 -0
  61. package/dist/types/indexSignature.d.ts +18 -0
  62. package/dist/types/literalTypes.d.cts +11 -0
  63. package/dist/types/literalTypes.d.ts +11 -0
  64. package/dist/types/typeContext.d.cts +66 -0
  65. package/dist/types/typeContext.d.ts +66 -0
  66. package/dist/types/typeResolver.d.cts +2 -101
  67. package/dist/types/typeResolver.d.ts +2 -101
  68. package/package.json +14 -14
  69. package/dist/codeGenerator-CADTvm2G.cjs +0 -37
  70. package/dist/codeGenerator-CADTvm2G.cjs.map +0 -1
  71. package/dist/codeGenerator-Cxlr_VOh.js.map +0 -1
@@ -1,105 +1,6 @@
1
- import { Components, Reference, Schema } from '@ahoo-wang/fetcher-openapi';
2
- import { ModelInfo } from '../naming/modelInfo.cjs';
1
+ import { Reference, Schema } from '@ahoo-wang/fetcher-openapi';
3
2
  import { MapSchema } from '../openapi/schemas.cjs';
4
- /**
5
- * Schema → TypeScript type expression, as pure functions.
6
- *
7
- * Every entry point takes a schema and a {@link TypeScope} - where the type
8
- * is written - and returns a {@link ResolvedType}: the type's text, and the
9
- * imports the module needs for it. Nothing is written; the caller applies the
10
- * imports to its module (`ImportRegistry.apply`) before it resolves the next
11
- * type, so a later reference sees the names and aliases an earlier one took.
12
- */
13
- /** An import a resolved type needs: a name, and the alias it goes by. */
14
- export interface ImportRequest {
15
- readonly moduleSpecifier: string;
16
- readonly name: string;
17
- readonly alias?: string;
18
- }
19
- /** A type expression, and the imports it needs. */
20
- export interface ResolvedType {
21
- readonly text: string;
22
- readonly imports: readonly ImportRequest[];
23
- }
24
- /** The imports a module already holds, as the resolver reads them. */
25
- export interface ImportLookup {
26
- entries(): readonly ImportRequest[];
27
- }
28
- /**
29
- * What stays the same for every type of one document: its components, how a
30
- * component names its model, and the model names declared at each path.
31
- */
32
- export interface TypeContext {
33
- readonly components?: Components;
34
- /** The model a reference names. */
35
- modelOf(reference: Reference): ModelInfo;
36
- /** The models declared at a path, with their `EnumText` companions. */
37
- namesAt(path: string): readonly string[];
38
- }
39
- /**
40
- * How a document's component keys name models: `resolveModelInfo` and
41
- * `resolveReferenceModelInfo` of `analysis/modelInfo.ts`.
42
- */
43
- export interface ModelNaming {
44
- ofKey(key: string): ModelInfo;
45
- ofReference(reference: Reference, components?: Components): ModelInfo;
46
- }
47
- /**
48
- * Builds the context of a document. The model names of each path are read
49
- * once, on first use, rather than from every component for every reference.
50
- */
51
- export declare function createTypeContext(components: Components | undefined, naming: ModelNaming): TypeContext;
52
- /** Where a type is written. */
53
- export interface TypeScope {
54
- readonly context: TypeContext;
55
- /**
56
- * The declaration the type belongs to. An import never takes its name.
57
- * With a `path`, it is a model: the models of that path are declared beside
58
- * it, so a reference to one needs no import, and an import takes none of
59
- * their names. Without, every referenced model is imported.
60
- */
61
- readonly owner: {
62
- readonly name: string;
63
- readonly path?: string;
64
- };
65
- /** The specifier the module imports a model by. */
66
- specifierOf(model: ModelInfo): string;
67
- /** The imports the module holds. */
68
- readonly imports: ImportLookup;
69
- }
70
- /**
71
- * Global names generated code relies on. A model imported under one of these
72
- * names would shadow the global, so the import is aliased instead: a model
73
- * named `Response` must not turn `Promise<Response>` into a promise of the
74
- * model.
75
- */
76
- export declare const GLOBAL_TYPE_NAMES: readonly string[];
77
- /**
78
- * Chooses the intersection representation over an interface with an index
79
- * signature.
80
- *
81
- * An interface may only carry a named property whose type is assignable to
82
- * its index signature (TS2411). Every generated property is required, so
83
- * only a clash that can be PROVEN off the schemas moves one - see
84
- * {@link clashesWithIndexSignature}. Anything undecided keeps the interface,
85
- * which is the only form that can reference itself through an index
86
- * signature: an alias reaching itself through `Record` is circular (TS2456),
87
- * which is what a dictionary of its own type would generate.
88
- *
89
- * @param schema - The object schema to represent
90
- * @param components - The components a reference resolves against
91
- * @returns True when the schema needs the intersection form
92
- */
93
- export declare function requiresAdditionalPropertiesIntersection(schema: Schema, components?: Components): boolean;
94
- /**
95
- * Renders a JSON value as a TypeScript literal type: a string in single
96
- * quotes, escaped as ts-morph's printer escapes it, an array as a tuple, an
97
- * object as an object type that no array matches.
98
- *
99
- * @param value - The value from the document
100
- * @returns The literal type
101
- */
102
- export declare function resolveLiteral(value: unknown): string;
3
+ import { ResolvedType, TypeScope } from './typeContext.cjs';
103
4
  /**
104
5
  * The type a schema generates.
105
6
  *
@@ -1,105 +1,6 @@
1
- import { Components, Reference, Schema } from '@ahoo-wang/fetcher-openapi';
2
- import { ModelInfo } from '../naming/modelInfo.js';
1
+ import { Reference, Schema } from '@ahoo-wang/fetcher-openapi';
3
2
  import { MapSchema } from '../openapi/schemas.js';
4
- /**
5
- * Schema → TypeScript type expression, as pure functions.
6
- *
7
- * Every entry point takes a schema and a {@link TypeScope} - where the type
8
- * is written - and returns a {@link ResolvedType}: the type's text, and the
9
- * imports the module needs for it. Nothing is written; the caller applies the
10
- * imports to its module (`ImportRegistry.apply`) before it resolves the next
11
- * type, so a later reference sees the names and aliases an earlier one took.
12
- */
13
- /** An import a resolved type needs: a name, and the alias it goes by. */
14
- export interface ImportRequest {
15
- readonly moduleSpecifier: string;
16
- readonly name: string;
17
- readonly alias?: string;
18
- }
19
- /** A type expression, and the imports it needs. */
20
- export interface ResolvedType {
21
- readonly text: string;
22
- readonly imports: readonly ImportRequest[];
23
- }
24
- /** The imports a module already holds, as the resolver reads them. */
25
- export interface ImportLookup {
26
- entries(): readonly ImportRequest[];
27
- }
28
- /**
29
- * What stays the same for every type of one document: its components, how a
30
- * component names its model, and the model names declared at each path.
31
- */
32
- export interface TypeContext {
33
- readonly components?: Components;
34
- /** The model a reference names. */
35
- modelOf(reference: Reference): ModelInfo;
36
- /** The models declared at a path, with their `EnumText` companions. */
37
- namesAt(path: string): readonly string[];
38
- }
39
- /**
40
- * How a document's component keys name models: `resolveModelInfo` and
41
- * `resolveReferenceModelInfo` of `analysis/modelInfo.ts`.
42
- */
43
- export interface ModelNaming {
44
- ofKey(key: string): ModelInfo;
45
- ofReference(reference: Reference, components?: Components): ModelInfo;
46
- }
47
- /**
48
- * Builds the context of a document. The model names of each path are read
49
- * once, on first use, rather than from every component for every reference.
50
- */
51
- export declare function createTypeContext(components: Components | undefined, naming: ModelNaming): TypeContext;
52
- /** Where a type is written. */
53
- export interface TypeScope {
54
- readonly context: TypeContext;
55
- /**
56
- * The declaration the type belongs to. An import never takes its name.
57
- * With a `path`, it is a model: the models of that path are declared beside
58
- * it, so a reference to one needs no import, and an import takes none of
59
- * their names. Without, every referenced model is imported.
60
- */
61
- readonly owner: {
62
- readonly name: string;
63
- readonly path?: string;
64
- };
65
- /** The specifier the module imports a model by. */
66
- specifierOf(model: ModelInfo): string;
67
- /** The imports the module holds. */
68
- readonly imports: ImportLookup;
69
- }
70
- /**
71
- * Global names generated code relies on. A model imported under one of these
72
- * names would shadow the global, so the import is aliased instead: a model
73
- * named `Response` must not turn `Promise<Response>` into a promise of the
74
- * model.
75
- */
76
- export declare const GLOBAL_TYPE_NAMES: readonly string[];
77
- /**
78
- * Chooses the intersection representation over an interface with an index
79
- * signature.
80
- *
81
- * An interface may only carry a named property whose type is assignable to
82
- * its index signature (TS2411). Every generated property is required, so
83
- * only a clash that can be PROVEN off the schemas moves one - see
84
- * {@link clashesWithIndexSignature}. Anything undecided keeps the interface,
85
- * which is the only form that can reference itself through an index
86
- * signature: an alias reaching itself through `Record` is circular (TS2456),
87
- * which is what a dictionary of its own type would generate.
88
- *
89
- * @param schema - The object schema to represent
90
- * @param components - The components a reference resolves against
91
- * @returns True when the schema needs the intersection form
92
- */
93
- export declare function requiresAdditionalPropertiesIntersection(schema: Schema, components?: Components): boolean;
94
- /**
95
- * Renders a JSON value as a TypeScript literal type: a string in single
96
- * quotes, escaped as ts-morph's printer escapes it, an array as a tuple, an
97
- * object as an object type that no array matches.
98
- *
99
- * @param value - The value from the document
100
- * @returns The literal type
101
- */
102
- export declare function resolveLiteral(value: unknown): string;
3
+ import { ResolvedType, TypeScope } from './typeContext.js';
103
4
  /**
104
5
  * The type a schema generates.
105
6
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/wow-generator",
3
- "version": "10.0.0-beta.1",
3
+ "version": "10.0.0-beta.11",
4
4
  "description": "Generates the typed TypeScript clients of a Wow service from its Manifest, and TypeScript models and Fetcher decorator clients from any OpenAPI 3 document (https://github.com/Ahoo-Wang/Wow).",
5
5
  "keywords": [
6
6
  "wow",
@@ -64,7 +64,7 @@
64
64
  "@ahoo-wang/fetcher": "^5.1.5 || ^6.0.0",
65
65
  "@ahoo-wang/fetcher-decorator": "^5.1.5 || ^6.0.0",
66
66
  "@ahoo-wang/fetcher-eventstream": "^5.1.5 || ^6.0.0",
67
- "@ahoo-wang/wow-client": "~10.0.0-beta.1"
67
+ "@ahoo-wang/wow-client": "~10.0.0-beta.11"
68
68
  },
69
69
  "peerDependenciesMeta": {
70
70
  "@ahoo-wang/fetcher-decorator": {
@@ -80,25 +80,25 @@
80
80
  "yaml": "^2.9.1"
81
81
  },
82
82
  "devDependencies": {
83
- "@ahoo-wang/fetcher": "^6.0.1",
84
- "@ahoo-wang/fetcher-decorator": "^6.0.1",
85
- "@ahoo-wang/fetcher-eventstream": "^6.0.1",
86
- "@ahoo-wang/fetcher-openapi": "^6.0.1",
83
+ "@ahoo-wang/fetcher": "^6.1.0",
84
+ "@ahoo-wang/fetcher-decorator": "^6.1.0",
85
+ "@ahoo-wang/fetcher-eventstream": "^6.1.0",
86
+ "@ahoo-wang/fetcher-openapi": "^6.1.0",
87
87
  "@eslint/js": "^10.0.1",
88
- "@types/node": "^26.6.5",
88
+ "@types/node": "^26.6.6",
89
89
  "@vitest/coverage-v8": "4.1.12",
90
90
  "@vitest/ui": "^4.1.12",
91
- "eslint": "^10.13.0",
92
- "eslint-plugin-import-x": "^4.17.1",
93
- "globals": "^17.13.0",
94
- "prettier": "3.9.10",
91
+ "eslint": "^10.15.0",
92
+ "eslint-plugin-import-x": "^4.18.1",
93
+ "globals": "^17.14.0",
94
+ "prettier": "3.10.1",
95
95
  "typescript": "~6.0.3",
96
- "typescript-eslint": "^8.72.0",
96
+ "typescript-eslint": "^8.72.2",
97
97
  "unplugin-dts": "1.1.2",
98
- "vite": "8.3.5",
98
+ "vite": "8.3.8",
99
99
  "vite-bundle-analyzer": "^1.3.9",
100
100
  "vitest": "^4.1.12",
101
- "@ahoo-wang/wow-client": "~10.0.0-beta.1"
101
+ "@ahoo-wang/wow-client": "~10.0.0-beta.11"
102
102
  },
103
103
  "scripts": {
104
104
  "build": "vite build && pnpm test:package",
@@ -1,37 +0,0 @@
1
- let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs"),i=require("node:path");var a=`./wow-generator.config.json`,o={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},s=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return o[this.kind]}};function c(e){return e instanceof Error?e.message:String(e)}function l(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var u=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??l()}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)}},d=class{debug(){}info(){}warn(){}error(){}};function f(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var p=`types.ts`;function m(e){return f(e.path,p)}function h(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function g(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 ee(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/`)&&g(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 _=`#/components/`,te=`${_}parameters/`,ne=`${_}requestBodies/`,re=`${_}responses/`,ie=`${_}schemas/`;function ae(e){return e.$ref.split(`/`).pop()}function v(e,t,n){let r=new Set,i=e;for(;h(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new s(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function y(e,t){return v(e,t.schemas,ie)}function oe(e,t){return v(e,t.responses,re)}function se(e,t){return v(e,t.requestBodies,ne)}function ce(e,t){return v(e,t.parameters,te)}var le=new Intl.Collator(`en-US`);function b(e,t){return le.compare(e,t)}var ue=`application/json`,de=`text/event-stream`;function fe(e){return e.split(`;`)[0].trim().toLowerCase()}function pe(e){let t=fe(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function me(e){let t=fe(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function x(e,t,n=e=>fe(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 he(e,t){if(t&&!h(t))return x(t.content,e)?.schema}function ge(e){if(e&&!h(e))return x(e.content,ue,pe)?.schema}function _e(e){return he(de,e)}function ve(e){return he(`*/*`,e)}function ye(e){return!e||h(e)?!1:Object.keys(e.content??{}).some(me)}function S(e){return Array.isArray(e.enum)&&e.enum.length>0}var be=`x-enum-text`;function xe(e){return e[be]}function Se(e){return e.type===`object`&&!!e.properties}function Ce(e){return e.type===`array`&&!!e.items}function we(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Te(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function Ee(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function C(e){return we(e)||Te(e)||Ee(e)}function De(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Oe(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var ke=`x-map-key-schema`;function Ae(e){return e[ke]}function je(e){return e.readOnly===!0}function Me(e){if(Array.isArray(e))return e.map(e=>Me(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 Ne(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),h(e))o(t&&y(e,t));else if(e.nullable||Array.isArray(e.type))a=!0;else{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 Pe(e,t){return e.operation.operationId&&t.operation.operationId?b(e.operation.operationId,t.operation.operationId):e.path&&t.path?b(e.path,t.path):e.method&&t.method?b(e.method,t.method):0}function Fe(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=h(i)?n&&ce(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Ie(e,t){let n=[];for(let[r,i]of Object.entries(e))Le(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Fe(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Pe)}function Le(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 Re(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 ze(e,t){let n=Re(e),r=n?e.responses[n]:void 0;return t&&h(r)?oe(r,t):r}function Be(e,t){return(e.parameters??[]).map(e=>h(e)?ce(e,t):e).filter(e=>e!==void 0)}function Ve(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 He=/[^\p{L}\p{N}$]+/u,Ue=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 w(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!Ue.has(e)}function We(e){return/^\p{N}/u.test(e)?`_${e}`:e}function T(e){if(w(e))return e;let t=We(O(e)||`_`);return Ue.has(t)?`${t}_`:t}function Ge(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&w(e)}function E(e){return We((Array.isArray(e)?e:[e]).map(e=>Ge(e)?e:D(e)).join(``)||`_`)}function Ke(e){return e.split(He)}function qe(e){return Array.isArray(e)?e.flatMap(e=>Je(Ke(e))):Je(Ke(e))}function Je(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 D(e){return e===``||e.length===0?``:qe(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 O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e===``||Array.isArray(e)&&e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function A(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:j(e)}function Ye(e){return/^\d+$/.test(e)?`NUM_${e}`:k(e)||e}function j(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var Xe=`x-fetcher-method`;function Ze(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!Qe(n))throw new s(`specification`,`${Xe} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=O(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function Qe(e){return w(e)||/^[a-z]+$/.test(e)}function $e(e,t){let n=T(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function M(e){if(!e)return{name:``,path:`/`};let t=e.split(`.`),n=-1;for(let e=0;e<t.length;e++)if(t[e]&&/^[A-Z]/.test(t[e])){n=e;break}let r=t.slice(0,n),i=r.length>0?`/${r.join(`/`)}`:`/`;return{name:E(t.slice(n)),path:i}}function et(e,t){if(!e.$ref.startsWith(`#/components/schemas/`))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return t&&y(e,t),M(ae(e))}var tt=[`httpRequest`,`attributes`];function nt(e,t,n){return new rt(e,t,n).clients()}var rt=class{document;config;warnings;constructor(e,t,n){this.document=e,this.config=t,this.warnings=n}clients(){let e=this.tags(),t=this.groupOperations(),n=new Map;return[...t.keys()].sort().map(r=>{let i=M(r),a=i;for(let e=2;n.has(at(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(at(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(at(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=f(t.path,it(r)),a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,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(tt),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=Ze(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),o=r.get(a);if(o!==void 0)throw new s(`specification`,`Operations ${o} 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=Be(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`?Ve(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:$e(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)?.includes(t)??!1}body(e,t){if(!e.requestBody)return;let n=h(e.requestBody)?se(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=x(i,ue,pe),o=$e(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Ne(a.schema,this.document.components)}}:x(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:x(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(me)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=ze(e,this.document.components);if(!t)return{kind:`response`};let n=ge(t),r=n||ve(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=_e(t);if(i){if(h(i)){let e=y(i,this.document.components);if(Ce(e)&&h(e.items)){let t=et(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return ye(t)?{kind:`text`}:{kind:`response`}}groupOperations(){let e=new Map;for(let t of this.document.endpoints){let n=`${t.method.toUpperCase()} ${t.path}`,r=t.operation.tags??[];if(r.length===0)this.warnings.push(`Skipping ${n}: it has no tag, and the tag names its API client.`);else if(!t.operation.operationId)this.warnings.push(`Skipping ${n}: it has no operationId, and the operationId names its method.`);else for(let n of r)e.has(n)||e.set(n,new Set),e.get(n).add(t)}return e}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{e.has(t)||e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>e.set(t.name,t)),e}};function it(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function at(e){return`${e.path}/${e.name}`.toLowerCase()}function ot(e){let t=e.components?.schemas;if(!t)return[];let n=Object.keys(t);return st(n),n.map(e=>{let n=t[e],r=M(e);return{key:e,info:r,file:m(r),schema:n}})}function st(e){let t=new Map;for(let n of e){let e=M(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 s(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function ct(e,t){let n=[];return{model:{models:ot(e),apiClients:nt(e,t,n)},warnings:n}}var lt=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})}))}},ut=class{sourceFile;imports=new lt;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&&pt(n,e)&&t.push(ft),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},dt=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 ut(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},ft=e=>{e.blankLineIfLastNot()};function pt(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 mt(e,t){return{name:`[key: string]`,type:e,docs:t}}var ht=`@`;function N(e,t,n){return e.imports.add(t,n)}function gt(e,n,r){return r.path.startsWith(ht)?r.path:P(e.directoryPath,(0,t.join)(n,r.path,p))}function P(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 _t(e,t=`
2
- `){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(vt);return n.length>0?n.join(t):void 0}function vt(e){return e.replace(/\*\//g,`*\\/`)}function F(e,t){let n=_t(t);n&&(e.docs=[...e.docs??[],n])}function I(e,t,n=!1){e=xt(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&St(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),Ct(r,e,`default`),Ct(r,e,`example`),Tt(r,e),Et(r,e),Dt(r,e),r}function yt(e,t,n){F(e,I(t,n))}function bt(e,t,n,r=!1){let i=I(t,n,!0);r&&wt(i,`schema`,t),F(e,i)}function xt(e){for(let t of[`anyOf`,`oneOf`]){let n=e[t];if(!Array.isArray(n)||n.length<2)continue;let r=n.filter(e=>`$ref`in e||e.type!==`null`),[i]=r;if(r.length!==1||`$ref`in i)continue;let a={...i};for(let[n,r]of Object.entries(e))n!==t&&r!==void 0&&(a[n]=r);return a}return e}function St(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function Ct(e,t,n){let r=t[n];r&&(typeof r==`object`?wt(e,n,r):e.push(`- ${n}: \`${r}\``))}function wt(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function Tt(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 Et(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 Dt(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 Ot(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 kt=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],At=new Set([`string`,`number`,`boolean`]),jt=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function Mt(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function L(e,t,n=new Set){if(h(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=y(e,t);return r?L(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(Ee(e)&&e.type===void 0){let r=e.allOf.map(e=>L(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>Mt(e,i))?i:void 0}if(!(C(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:Me(e.type)}}}function Nt(e,t,n){let r=L(t,n);if(typeof r!=`object`)return!1;let i=L(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function Pt(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>Nt(e,n,t))}function Ft(e){return e.nullable!==!0||S(e)||!C(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(h))}function It(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 R(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>R(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${A(e)}: ${R(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var Lt=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([...kt,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=(je(t)?`readonly `:``)+A(e);if(!h(t)){let e=_t(I(t),`
3
- * `);if(e)return`
4
- /**
5
- * ${e}
6
- */
7
- ${r}: ${n}
8
- `}return`${r}: ${n}`})}objectType(e){let t=[];Se(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${A(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Oe(e)&&Ae(e)?this.mapType(e):Pt(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=Ae(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>h(e)?this.components&&y(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(h(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(Ft(e))return`(${this.type({...e,nullable:!1})}) | null`;if(C(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(!It(e.const,e))return`never`;let t=R(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!S(e))return`(${this.type({...e,nullable:!1})}) | null`;if(S(e)){let t=e.enum.filter(t=>It(t,e)).map(e=>R(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||At.has(n)?t:`(${t}) & (${n})`}return Oe(e)&&!e.required?.length?this.mapType(e):e.type===`array`?De(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?Me(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-`)&&!jt.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`||jt.has(e));if(!r.every(e=>h(e)||i(e)))return;let a=r.map(t=>h(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||!h(n))return r;let a=ae(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>j(e)).join(` | `);return`(${r} & { ${A(i.propertyName)}: ${s} })`}};function z(e,t){let n=new Lt(e);return{text:t(n),imports:n.imports()}}function Rt(e,t){return z(t,t=>t.type(e))}function zt(e,t){return z(t,t=>t.additionalProperties(e))}function Bt(e,t){return z(t,t=>t.additionalPropertyType(e))}function Vt(e,t){return z(t,t=>t.requiredAdditionalPropertyType(e))}function Ht(e,t){return z(t,t=>t.mapValueType(e))}var Ut=`@ahoo-wang/fetcher`,Wt=[`ContentTypeValues`,`ResultExtractors`],Gt=`@ahoo-wang/fetcher-decorator`,Kt=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],qt={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Jt={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Yt=`{
10
- headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
11
- resultExtractor: JsonEventStreamResultExtractor,
12
- }`;function Xt(e){N(e,Ut,Wt)}function Zt(e){N(e,Gt,Kt)}function Qt(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 $t(t){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]})}function en(e){return e===`delete`?`del`:e}var tn=`@ahoo-wang/fetcher-eventstream`;function nn(e){N(e,tn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function rn(e,t){let n=t.modules.module(e.file);Xt(n),Zt(n),nn(n);let r=Qt(e.className,n);F(r,[e.description]),$t(r);let i=an(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(on(t,i))}function an(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>gt(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=Rt(e,r);return t.imports.apply(n.imports),n.text}}}function on(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:[j(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:sn(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=cn(e.returns,t),o=j(e.path),s={name:e.name,decorators:[{name:en(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return F(s,[...e.docs]),s}function sn(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:(N(t.module,Ut,[`PartialBy`]),`PartialBy<${e}, ${r.map(j).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function cn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Jt:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Yt};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Yt}}case`text`:return Jt;case`response`:return qt}}function ln(e){return Ot(e,{ofKey:e=>M(e),ofReference:et})}function un(e,t){new fn(e,t.modules.module(e.file),t).write()}function dn(e){let t=new Set,n=new Map;for(let r of e){let e=Ye(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,A(a))}return n}var fn=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=>gt(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&bt(e,this.model.schema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return h(e)?this.processTypeAlias(e):S(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||C(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):Se(e)?this.processInterface(e):Oe(e)&&typeof e.additionalProperties==`object`&&!Ae(e)&&!e.required?.length?this.processIndexSignature(e):Ce(e)?this.processArray(e):C(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(Rt(e,this.scope))}processEnum(t){let n=xe(t);if(n){let t=dn(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:R(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=dn(r);return C(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:R(e)}))})}addPropertyToInterface(e,t,n){let r={name:A(t),type:this.resolveType(n),isReadonly:je(n)};(e.properties??=[]).push(r),yt(r,n)}processInterface(t){if(Pt(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:A(e),type:this.emit(Vt(t,this.scope))});return this.emit(zt(t,this.scope))&&n.push(mt(this.emit(Bt(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:De(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[mt(this.emit(Ht(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})}};function pn(e,t){e.models.forEach(e=>un(e,t)),e.apiClients.forEach(e=>rn(e,t))}function mn(e,t){let n=[];return hn(e,t,n),n}function hn(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:_n(t)})}for(let i of e.getDirectories()){let e=hn(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:gn(i,r,t,n)}function gn(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])=>b(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 _n(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 vn(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}else if(e.Node.isPropertyAccessExpression(t)){if(t.getExpression()!==n)return!1}else{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 yn(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();else if(e.Node.isIdentifier(t)&&r.has(t.getText())&&!vn(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>bn(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function bn(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 xn(e){let t=e.flatMap(yn);for(let e of t)e()}var Sn=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function Cn(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!Sn.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(`
13
- `)}`)}var wn=`// Code generated by wow-generator. DO NOT EDIT.
14
-
15
- `,Tn={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function En(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(Tn),n.organizeImports(Tn)}),xn(e),Cn(e);for(let t of e)t.insertText(0,wn)}var Dn=3e4;function On(e){return/^https?:\/\//i.test(e)}function kn(e,t={}){return On(e)?An(e,t):Mn(e)}async function An(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`:jn(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 jn(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 Mn(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Nn(e,t){let n;try{n=await kn(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Fn(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Pn(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new s(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new s(`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 s(`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 s(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Fn(e){switch(In(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function In(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`)}async function Ln(e,t,n){if(e!==void 0)return{...await Bn({path:e,explicit:!0},t,n),origin:B(e)};let r=await Bn({path:a,explicit:!1},t,n);return r===void 0?(t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}):{...r,origin:B(a)}}var Rn=[`apiClients`],zn=[`ignorePathParameters`,`methodNames`];async function Bn(e,t,n){let r=B(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await kn(e.path,n)}catch(n){if(!e.explicit&&Vn(n)){t.debug(`No configuration file at ${r}`);return}throw new s(`configuration`,`Cannot read configuration ${r}: ${c(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Fn(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Un(a,r);return t.debug(`Configuration loaded from ${r}: ${Gn(o.config)}`),o}function B(e){return On(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Vn(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function V(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hn(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 Un(e,t){if(!H(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${V(e)}`);let n=[];return Hn(n,t,`configuration`,e,Rn),Wn(e.apiClients,t,n),{config:e,warnings:n}}function Wn(e,t,n){if(e!==void 0){if(!H(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${V(e)}`);for(let[r,i]of Object.entries(e)){if(!H(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${V(i)}`);Hn(n,t,`apiClients["${r}"]`,i,zn);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new s(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${V(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!H(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${V(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!w(n))throw new s(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Gn(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var Kn=new Set,qn=`#/$defs/`;function U(e){return e.startsWith(qn)?e.slice(8):void 0}function Jn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.openapi===void 0&&t.swagger===void 0&&typeof t.format==`number`&&Array.isArray(t.contexts)}function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yn(e,t){let n=e;if(n.format!==1)throw new s(`input`,`${t} is a Wow Manifest of format ${n.format}; wow-generator reads format 1.`);let r=(n.requires??[]).filter(e=>!Kn.has(e));if(r.length>0)throw new s(`input`,`${t} requires ${r.join(`, `)}, which this wow-generator does not understand: generate with a newer one.`);let i=[];if(n.contexts.forEach((e,t)=>{!W(e)||typeof e.name!=`string`?i.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let r=`${e.name}.aggregates[${n}]`;!W(t)||typeof t.name!=`string`?i.push(`${r} has no name`):!W(t.state)||typeof t.state.schema!=`string`?i.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`a command of ${e.name}.${t.name} has no name or schema`)}),(t.events??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!W(n.$defs)&&i.push(`$defs is not an object`),i.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${i.join(`; `)}.`);return n}var Xn=new Set([`int64`,`bigint`,`decimal`]),Zn={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`,"wow.lifecycle.ApplyTags":`ApplyTags`},Qn=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`,`wow.lifecycle.ApplyTags`]),$n=4;function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function q(e,t){let n=[...new Set(e)];return n.length===1?n[0]:n.map(e=>/ [|&] /.test(e)&&!e.startsWith(`{`)?`(${e})`:e).join(t)}function er(e){return typeof e==`string`?j(e):JSON.stringify(e)}var tr=class{defs;names=new Map;warnings=[];constructor(e){this.defs=e}inlined(e){return e.includes(`(`)}name(e){let t=new Set(e);for(let e=0;t.size>0;e++){let n=new Map;for(let r of t.keys()){let t=r.split(`.`),i=t[t.length-1].split(`$`),a=E([...t.slice(Math.max(0,t.length-1-e),t.length-1),...i].map(e=>/^[a-z]/.test(e)?D(e):e));n.set(a,[...n.get(a)??[],r])}let r=new Set(this.names.values());for(let[i,a]of n){let n=a.filter(t=>t.split(`.`).length-1<=e),o=a.length===1&&!r.has(i)?a:n;for(let e of o){let n=i;for(let e=2;r.has(n);e++)n=`${i}${e}`;r.add(n),this.names.set(e,n),t.delete(e)}}}}schemaOf(e){let t=this.defs[e];return G(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=U(n);if(r===void 0||t.has(r))return e;let i=this.schemaOf(r);return i?this.resolve(i,new Set([...t,r])):e}references(e,t=new Set){if(Array.isArray(e))e.forEach(e=>this.references(e,t));else if(G(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=U(r);e!==void 0&&t.add(e)}else n!==`enum`&&n!==`const`&&this.references(r,t);return t}namedReferences(e){let t=new Set;for(let n of this.references(e)){let e=this.schemaOf(n);e!==void 0&&this.inlined(n)?this.namedReferences(e).forEach(e=>t.add(e)):t.add(n)}return t}closure(e){let t=new Set,n=[...e];for(;n.length>0;){let e=n.pop();if(t.has(e))continue;t.add(e);let r=this.schemaOf(e);r&&n.push(...this.references(r))}return[...t]}refType(e,t){let n=this.schemaOf(e);if(n!==void 0&&this.inlined(e))return this.type(n,t);let r=this.names.get(e);return r!==void 0&&this.schemaOf(e)?r:(this.warnings.push(`${t} refers to the schema ${e}, which the Manifest's $defs does not hold; it is typed as unknown.`),`unknown`)}type(e,t){if(e===!0||e===void 0)return`unknown`;if(e===!1)return`never`;if(!G(e))return`unknown`;if(typeof e.$ref==`string`){let n=U(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return er(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:q(e.enum.map(er),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return q(i.map(e=>this.type(e,t)),r)}let n=K(e);return n.length===0?G(e.properties)?this.objectType(e,t):`unknown`:q(n.map(n=>this.primitive(n,e,t)),` | `)}primitive(e,t,n){switch(e){case`string`:return`string`;case`integer`:case`number`:return typeof t.format==`string`&&Xn.has(t.format)?`string`:`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:{let e=t.items===void 0?`unknown`:this.type(t.items,n);return/ [|&] /.test(e)?`(${e})[]`:`${e}[]`}case`object`:return this.objectType(t,n);default:return`unknown`}}objectType(e,t){let n=this.properties(e,t),r=this.additional(e,t);if(n.length===0)return`Record<string, ${r??`unknown`}>`;let i=n.map(e=>`${e.name}${e.optional?`?`:``}: ${e.type}`);return r!==void 0&&i.push(`[key: string]: unknown`),`{ ${i.join(`; `)} }`}properties(e,t){if(!G(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=G(r)?r.description:void 0;return{name:A(e),type:this.type(r,`${t}.${e}`),optional:!n.has(e),...typeof i==`string`?{description:i}:{}}})}additional(e,t){let n=e.additionalProperties;if(n!==void 0&&n!==!1)return this.type(n,t)}isInterface(e){let t=K(e);return G(e.properties)&&(t.length===0||t.length===1&&t[0]===`object`)&&e.$ref===void 0&&e.allOf===void 0&&e.oneOf===void 0&&e.anyOf===void 0}textNumbers(e,t=new Set){if(!G(e))return;let n=typeof e.$ref==`string`?U(e.$ref):void 0;if(n!==void 0){let e=this.schemaOf(n);return t.has(n)||e===void 0?void 0:this.textNumbers(e,new Set([...t,n]))}let r=[`oneOf`,`anyOf`,`allOf`].flatMap(t=>Array.isArray(e[t])?e[t]:[]).map(e=>this.textNumbers(e,t)).filter(e=>e!==void 0),i=K(e);(i.includes(`integer`)||i.includes(`number`))&&typeof e.format==`string`&&Xn.has(e.format)&&r.push(!0);let a={};if(G(e.properties))for(let[n,r]of Object.entries(e.properties)){let e=this.textNumbers(r,t);e!==void 0&&(a[n]=e)}let o=this.textNumbers(e.items,t)??this.textNumbers(e.additionalProperties,t);return o!==void 0&&(a[`*`]=o),Object.keys(a).length>0&&r.push(a),nr(r)}fields(e,t,n=1,r=new Set){let i=this.resolve(e),a=typeof e.$ref==`string`?U(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!G(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<$n&&G(r)&&(K(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function nr(e){if(e.length===0)return;let t=e.filter(e=>e!==!0);if(t.length===0)return!0;let n={};for(let e of t)for(let[t,r]of Object.entries(e))(n[t]??=[]).push(r);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,nr(t)]))}function rr(e,t,n){if(t===void 0)return!0;let r=e.resolve(t);return!Array.isArray(r.required)||r.required.every(e=>e===n)}function ir(e,t,n){if(t===void 0)return!1;let r=e.resolve(t).properties,i=G(r)?r[n]:void 0;return G(i)&&i.readOnly===!0}function ar(e){return(e.commands??[]).filter(e=>e.system!==!0)}function or(e){return(e.commands??[]).filter(e=>e.system===!0&&e.name.startsWith(`wow.lifecycle.`))}function sr(e,t){return[t.state.schema,...ar(t).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(U).filter(e=>e!==void 0).concat(cr(e,t))}function cr(e,t){return or(t).map(e=>e.name).filter(t=>Zn[t]!==void 0&&e.schemaOf(t))}function lr(e){let t=new tr(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=[...(e.aggregates??[]).flatMap(e=>sr(t,e)),...(e.routes??[]).flatMap(e=>[...t.references(e.request),...t.references(e.response)])];for(let i of t.closure(n).sort(b))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(b));let a=i.map(e=>ur(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>b(e.file,t.file)||b(e.name,t.name)),o=n.map(e=>dr(t,e));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:o},warnings:[...new Set(t.warnings)]}}function ur(e,t,n){let r=e.schemaOf(t),i=e.names.get(t),a=typeof r.description==`string`?r.description:void 0,o=[...e.namedReferences(r)].map(t=>e.names.get(t)).filter(e=>e!==void 0&&e!==i),s={key:t,name:i,file:n,...a===void 0?{}:{description:a},references:[...new Set(o)].sort(b)};if(e.isInterface(r)){let n=e.additional(r,t);return{...s,properties:e.properties(r,t),...n===void 0?{}:{type:`unknown`}}}return{...s,type:e.type(r,t)}}function dr(e,t){return{name:t.name,...t.description?{description:t.description}:{},typeName:E(D(t.name)),constantName:k(t.name),directory:t.name,errors:(t.errors??[]).map(e=>({code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((t.subscriptions??[]).map(e=>e.name))].sort(b),aggregates:(t.aggregates??[]).map(n=>mr(e,t,n)),routes:(t.routes??[]).map(n=>{let r=`${t.name} route ${n.name}`;return{name:n.name,method:n.route.method,path:n.route.path,...n.description?{description:n.description}:{},deprecated:n.deprecated===!0,parameters:(n.parameters??[]).map(t=>({name:t.name,location:t.in===`path`?`path`:`query`,type:e.type(t.schema,`${r} ${t.name}`),required:t.required})),...n.request===void 0?{}:{requestType:e.type(n.request,`${r} body`)},...n.response===void 0?{}:{responseType:e.type(n.response,`${r} answer`)}}})}}function fr(e){return(e.routes??[]).map(e=>({method:e.method,path:e.path}))}function pr(e,t,n){let r=U(t);return r===void 0?`unknown`:e.refType(r,n)}function mr(e,t,n){let r=`${t.name}.${n.name}`,i=E(D(n.name)),a=n.idSource??`assigned`,o=a===`owner`,s=new Set(cr(e,n)),c=or(n).filter(e=>Qn.has(e.name)).map(t=>{let n=t.name,i=n.split(`.`).pop(),a=e.schemaOf(n)?.description,c=T(O(i)),l=o&&(t.routes??[]).some(e=>!e.path.includes(`{id}`));return{name:n,member:k(i),method:c,routes:fr(t),...l?{ownMethod:`${c}Own`}:{},...s.has(n)?{bodyType:e.refType(n,r),bodyGenerated:!0}:Zn[n]?{bodyType:Zn[n]}:{},...typeof a==`string`?{description:a}:{}}}),l=new Set(c.flatMap(e=>[e.method,e.ownMethod??e.method])),u=ar(n).map(t=>{let n=T(O(t.name));(l.has(n)||n===`gateway`)&&(n=`${n}Command`),l.add(n);let i=(t.routes??[]).filter(e=>e.method===`POST`),a=i.find(e=>e.path.includes(`{id}`)),s=i.find(e=>!e.path.includes(`{id}`)),c;o&&a&&s&&!(t.mounted??!1)&&(c=`${n}Own`,l.has(c)&&(c=`${c}Command`),l.add(c));let u=U(t.schema),d=u===void 0?void 0:e.schemaOf(u),f=t.idProperty,p=f!==void 0&&ir(e,d,f);return{name:t.name,method:n,routes:fr(t),...a?{byIdPath:{path:a.path}}:{},...s?{unaddressedPath:{path:s.path}}:{},...c===void 0?{}:{ownMethod:c},bodyType:pr(e,t.schema,`${r}.${t.name}`),bodyOptional:rr(e,d,p?f:void 0),...f===void 0?{}:{idProperty:f},...p?{idComputed:p}:{},creation:t.creation??`none`,mounted:t.mounted??!1,produces:t.produces??[],...t.description?{description:t.description}:{},...e.textNumbers({$ref:t.schema})===void 0?{}:{bodyNumbers:!0}}}),d=e.textNumbers({$ref:n.state.schema}),f=Object.fromEntries((n.events??[]).flatMap(r=>{let i=e.textNumbers({$ref:r.schema});return i===void 0?[]:[[hr(t,n,r.name),i]]})),p=Object.fromEntries(ar(n).flatMap(t=>{let n=e.textNumbers({$ref:t.schema});return n===void 0?[]:[[t.name,n]]})),m={...d===void 0?{}:{state:d},...Object.keys(f).length===0?{}:{events:f},...Object.keys(p).length===0?{}:{commands:p}},h=U(n.state.schema),g=h===void 0?void 0:e.schemaOf(h);return{context:t.name,name:n.name,...n.description?{description:n.description}:{},typeName:i,directory:`${t.name}/${n.name}`,ownership:n.ownership??`owner`,idSource:a,snapshot:n.snapshot?.enabled??!0,stateType:pr(e,n.state.schema,`${r} state`),stateFields:g===void 0?[]:e.fields({$ref:n.state.schema},`state`),commands:u,events:(n.events??[]).map(i=>({name:i.name,wireName:hr(t,n,i.name),revision:i.revision??1,type:pr(e,i.schema,`${r}.${i.name}`)})),lifecycle:c,queryModels:(n.queries??[]).map(e=>e.model),...Object.keys(m).length===0?{}:{textNumbers:m}}}function hr(e,t,n){return n.includes(`.`)?n:`${e.name}.${t.name}.${n}`}var J=`@ahoo-wang/wow-client`,gr=`@ahoo-wang/wow-client/routes`;function Y(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>vt(e).split(`
16
- `));return n.length===0?``:n.length===1?`${t}/** ${n[0]} */\n`:`${t}/**\n${n.map(e=>`${t} * ${e}`.trimEnd()).join(`
17
- `)}\n${t} */\n`}function X(e,t){e.add(`\n${t}`)}function Z(e){return e.length===0?`never`:e.join(` | `)}function Q(e,t,n,r,a){let o=new Map;for(let e of new Set(r)){let t=n.get(e);t!==void 0&&t!==a&&o.set(t,[...o.get(t)??[],e])}for(let[n,r]of o)e.imports.add(P(e.directoryPath,(0,i.join)(t,n)),r)}function _r(e,t,n){let r=new Map(e.types.map(e=>[e.name,e.file]));for(let i of e.types)vr(t.module(i.file),i,r,n);for(let i of e.contexts){xr(i,t,n);for(let e of i.aggregates)Or(e,i,t,r,n),Mr(e,i,t,r,n),Nr(e,t,r,n);Sr(i,t),Cr(i,t,r,n),Tr(i,t,n)}}function vr(e,t,n,r){Q(e,r,n,t.references,t.file);let i=Y([t.description,`- key: \`${t.key}\``]);if(t.properties===void 0){X(e,`${i}export type ${t.name} = ${t.type};`);return}let a=t.properties.map(e=>`${Y([e.description],` `)} ${e.name}${e.optional?`?`:``}: ${e.type};`);t.type!==void 0&&a.push(` [key: string]: ${t.type};`),X(e,`${i}export interface ${t.name} {\n${a.join(`
18
- `)}\n}`)}function yr(e,t){let n=e.aggregates.map(t=>`${e.name}.${t.name}.`),r=t===void 0?`${e.name}.`:`${e.name}.${t.name}.`;return e.errors.filter(e=>t===void 0?!n.some(t=>e.code.startsWith(t)):e.code.startsWith(r)).map(e=>({member:k((e.code.startsWith(r)?e.code.slice(r.length):e.code).split(/[^A-Za-z0-9]+/))||`ERROR`,error:e}))}function br(e,t){return e.length===0?``:`${t}Errors: {\n${e.map(({member:e,error:n})=>`${Y([`${n.status}: ${n.description??n.code}`],`${t} `)}${t} ${e}: ${j(n.code)},`).join(`
19
- `)}\n${t}},\n`}function xr(e,t,n){let r=t.module(`${e.directory}/contract.ts`),a=`${e.typeName}Contract`;r.imports.add(J,[`Hop`,`wait`]);for(let t of e.aggregates)r.imports.add(P(r.directoryPath,(0,i.join)(n,t.directory,`aggregate.ts`)),[`${t.typeName}Aggregate`]);let o=e.aggregates.map(e=>` ${e.typeName}: ${e.typeName}Aggregate,\n`);X(r,`${Y([`The bounded context \`${e.name}\`: its name, its error codes and its aggregates, as the Kotlin \`${a}\` names them. A problem's \`code\` is one of its \`Errors\`, or of an aggregate's.`,e.description])}export const ${a} = {\n NAME: ${j(e.name)},\n${br(yr(e),` `)}${o.join(``)}} as const;`),X(r,`${Y([`An error code of \`${e.name}\`, of the context or of one of its aggregates.`])}export type ${e.typeName}ErrorCode = ${Z(e.errors.map(e=>j(e.code)))};`);let s=e.subscriptions.length>0;s&&X(r,`${Y([`The subscriptions of \`${e.name}\` a \`handled\` hop names.`])}export type ${e.typeName}Subscription = ${Z(e.subscriptions.map(j))};`);let c=`${a}.NAME`,l=[` /** Until a command of \`${e.name}\` passed admission. */\n accepted: (): Hop => wait.accepted(${c}),`,` /** Until a command's events are appended to the log of \`${e.name}\`. */\n committed: (): Hop => wait.committed(${c}),`,` /** Until the snapshot of \`${e.name}\` holds the commit. */\n snapshot: (): Hop => wait.snapshot(${c}),`];s&&l.push(` /** Until a subscription of \`${e.name}\` handled the commit. */\n handled: (subscription: ${e.typeName}Subscription): Hop => wait.handled(subscription, ${c}),`),X(r,`${Y([`The hops of a wait chain (\`Wow-Wait\`) in \`${e.name}\`.`])}export const ${O(e.name)}Wait = {\n${l.join(`
20
- `)}\n} as const;`)}function Sr(e,t){let n=t.module(`${e.directory}/manifest.ts`),r=`${e.typeName}Manifest`;n.imports.add(J,[`MANIFEST_FORMAT`,`RoutingManifest`]);let i=(e,t,n)=>` { name: ${j(e)}, routes: ${Ar(t)}${n===void 0?``:`, idProperty: ${j(n)}`} },`,a=e.aggregates.map(e=>{let t=[...e.commands.filter(e=>e.routes.length>0).map(e=>i(e.name,e.routes,e.idProperty)),...e.lifecycle.map(e=>i(e.name,e.routes))];return` {\n name: ${j(e.name)},\n commands: [\n${t.join(`
21
- `)}\n ],\n },`}),o=e.routes.map(e=>` { name: ${j(e.name)}, route: { method: ${j(e.method)}, path: ${j(e.path)} } },`),s=o.length===0?``:` routes: [\n${o.join(`
22
- `)}\n ],\n`;X(n,`${Y([o.length===0?`The routes of \`${e.name}\`'s commands, as its Manifest lists them: what its command clients send by, with no Manifest fetched and no schema.`:`The routes of \`${e.name}\`'s commands and service routes, as its Manifest lists them: what its clients send by, with no Manifest fetched and no schema.`])}export const ${r}: RoutingManifest = {\n format: MANIFEST_FORMAT,\n contexts: [\n {\n name: ${j(e.name)},\n aggregates: [\n${a.join(`
23
- `)}\n ],\n${s} },\n ],\n};`)}function Cr(e,t,n,r){if(e.routes.length===0)return;let i=t.module(`${e.directory}/routes.ts`),a=`${e.typeName}Routes`;i.imports.add(J,[`RequestOptions`,`WowClientOptions`]),i.imports.add(gr,[`ServiceRoutes`]),i.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]),Q(i,r,n,e.routes.flatMap(e=>[e.requestType,e.responseType,...e.parameters.map(e=>e.type)].filter(e=>e!==void 0).flatMap(e=>e.match(/[A-Za-z_$][A-Za-z0-9_$]*/g)??[])));let o=e.routes.map(t=>wr(e,t));X(i,`${Y([`The service routes of \`${e.name}\`: routes whose handler is the service's own code, each called by its Manifest's name.`])}export class ${a} {\n /** Calls any route of the service by its name. */\n readonly routes: ServiceRoutes;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.routes = new ServiceRoutes(options, { manifest: ${e.typeName}Manifest });\n }\n\n${o.join(`
24
-
25
- `)}\n}`)}function wr(e,t){let n=t.parameters.filter(e=>e.location===`path`),r=t.parameters.filter(e=>e.location===`query`),i=n.map(e=>`${e.name}: ${e.type}`);if(t.requestType!==void 0&&i.push(`body: ${t.requestType}`),r.length>0){let e=r.map(e=>`readonly ${A(e.name)}${e.required?``:`?`}: ${e.type}`).join(`; `),t=r.some(e=>e.required);i.push(`query${t?``:`?`}: { ${e} }`)}i.push(`options?: RequestOptions`);let a=t.responseType??`void`,o=[...n.length===0?[]:[`path: { ${n.map(e=>A(e.name)).join(`, `)} }`],...t.requestType===void 0?[]:[`body`],...r.length===0?[]:[`query`]];return`${Y([t.description,`\`${t.method} ${t.path}\``,t.deprecated?`@deprecated The service deprecates this route.`:void 0],` `)} ${A(t.name)}(${i.join(`, `)}): Promise<${a}> {\n return this.routes.call(${j(e.name)}, ${j(t.name)}, { ${o.join(`, `)} }, options) as Promise<${a}>;\n }`}function Tr(e,t,n){let r=t.module(`${e.directory}/client.ts`),a=`${e.typeName}Client`;r.imports.add(J,[`CommandClient`,`WowClientOptions`]),r.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]);let o=[],s=[];for(let t of e.aggregates){let e=t.typeName,a=e=>P(r.directoryPath,(0,i.join)(n,t.directory,e)),c=[[`commands`,`${e}CommandClient`]];t.queryModels.includes(`snapshot`)&&c.push([`snapshots`,`${e}SnapshotQueryClient`]),t.queryModels.includes(`events`)&&c.push([`events`,`${e}EventQueryClient`]),c.push([`state`,`${e}StateClient`]),r.imports.add(a(`commandClient.ts`),[`${e}CommandClient`]),r.imports.add(a(`queryClient.ts`),c.slice(1).map(([,e])=>e));let l=A(O(t.name));o.push(`${Y([`The clients of \`${t.context}.${t.name}\`.`],` `)} readonly ${l}: {\n${c.map(([e,t])=>` readonly ${e}: ${t};`).join(`
26
- `)}\n };`),s.push(` this.${l} = {\n${c.map(([e,t])=>` ${e}: new ${t}(options),`).join(`
27
- `)}\n };`)}e.routes.length>0&&(r.imports.add(`./routes.js`,[`${e.typeName}Routes`]),o.push(`${Y([`The service routes of \`${e.name}\`.`],` `)} readonly routes: ${e.typeName}Routes;`),s.push(` this.routes = new ${e.typeName}Routes(options);`)),X(r,`${Y([e.routes.length===0?`The clients of \`${e.name}\`: its command client, and per aggregate its command, query and state clients.`:`The clients of \`${e.name}\`: its command client, per aggregate its command, query and state clients, and its service routes.`])}export class ${a} {\n /** Sends any command of the service, by its Manifest's routes: \`send\`, \`wait\` and \`stream\`. */\n readonly commands: CommandClient;\n\n${o.join(`
28
-
29
- `)}\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.commands = new CommandClient(options, { manifest: ${e.typeName}Manifest });\n${s.join(`
30
- `)}\n }\n}`)}function Er(e){return e===!0?`true`:`{ ${Object.entries(e).map(([e,t])=>`${A(e)}: ${Er(t)}`).join(`, `)} }`}function Dr(e){let t=e.textNumbers;return t===void 0?``:` textNumbers: {\n${[`state`,`events`,`commands`].flatMap(e=>{let n=t[e];return n===void 0?[]:e===`state`?[` state: ${Er(n)},`]:[` ${e}: {\n${Object.entries(n).map(([e,t])=>` ${A(e)}: ${Er(t)},`).join(`
31
- `)}\n },`]}).join(`
32
- `)}\n },\n`}function Or(e,t,n,r,i){let a=n.module(`${e.directory}/aggregate.ts`),o=e.typeName;X(a,`${Y([`The aggregate \`${e.context}.${e.name}\`.`,e.description])}export const ${o}Aggregate = {\n context: ${j(t.name)},\n name: ${j(e.name)},\n path: ${j(`/${t.name}/${e.name}`)},\n ownership: ${j(e.ownership)},\n${e.idSource===`assigned`?``:` idSource: ${j(e.idSource)},\n`} snapshot: ${e.snapshot},\n${Dr(e)}${br(yr(t,e),` `)}} as const;`),X(a,`${Y([`The \`state.*\` paths of \`${e.name}\`'s snapshots a query filters, sorts and projects on.`])}export type ${o}StateField = ${Z(e.stateFields.map(j))};`);let s=e.events.map(e=>`CommittedEvent<${j(e.wireName)}, ${e.type}>`);a.imports.add(J,s.length>0?[`CommittedEvent`,`SystemEvent`]:[`SystemEvent`]),X(a,`${Y([`The events of \`${e.name}\`, named as the server sends them, \`${e.context}.${e.name}.<Event>\` at its current revision (the \`events\` query upgrades older records), and the system events every aggregate has.`])}export type ${o}Event = ${Z([...s,`SystemEvent`])};`),Q(a,i,r,e.events.map(e=>e.type))}function kr(e,t){let n=(t===void 0?[e.byIdPath,e.unaddressedPath]:[t?e.unaddressedPath:e.byIdPath]).filter(e=>e!==void 0).map(e=>`\`POST ${e.path}\``).join(`, `),r=e.creation===`required`?`Creates the aggregate.`:e.creation===`allowed`?`Creates the aggregate, or acts on the one that exists.`:void 0;return Y([e.description,`\`${e.name}\`${e.mounted?`, mounted (a transformer finds its aggregate)`:``}${t===!0?`, to the caller's own aggregate, whose id is the caller's owner`:``}: ${n}.`,t===!1?"By id, for a caller with no owner; `"+e.ownMethod+"` sends it to the caller's own.":void 0,e.idProperty===void 0?void 0:`Its body names its aggregate: \`${e.idProperty}\`${e.idComputed?`, which the service computes from the fields given`:``}.`,r,e.produces.length>0?`Produces ${e.produces.map(e=>`\`${e}\``).join(`, `)}.`:void 0],` `)}function Ar(e){return`[${e.map(e=>`{ method: ${j(e.method)}, path: ${j(e.path)} }`).join(`, `)}]`}function $(e,t,n,r){let i=e.bodyType===`unknown`?`object`:e.bodyType,a=e.idComputed?`Omit<${i}, ${j(e.idProperty)}>`:i,o=e.bodyOptional?`body: ${a} = {}`:`body: ${a}`,s=n?`stream`:`wait`,c=n?`Promise<CommandResultStream>`:`Promise<CommandResult>`,l=r===!0?e.ownMethod:e.method,u=n?`${l}Stream`:l,d=n?Y([`\`${e.name}\`${r===!0?` to the caller's own aggregate`:``}, answered as one result per hop of its wait (\`text/event-stream\`).`],` `):kr(e,r),f=j(`${t.context}.${t.name}.${e.name}`),p=e=>`{ ...options, command: ${f}, body${e} }`,m=r===void 0?e.byIdPath:!r,h=r===void 0?e.unaddressedPath:r,g=m&&h?`CreateCommandOptions`:`CommandOptions`,ee=m&&!h?`id: string, `:``,_=p(m&&!h?`, id`:``);return n?`${d} ${u}(${ee}${o}, options?: ${g}): ${c} {\n return this.client.${s}(${_});\n }`:jr(d,u,`${ee}${o}`,g,_)}function jr(e,t,n,r,i){return`${e} ${t}(${n?`${n}, `:``}options?: ${r}): Promise<CommandResult> {\n return this.client.wait(${i});\n }`}function Mr(e,t,n,r,a){let o=n.module(`${e.directory}/commandClient.ts`),s=e.typeName,c=e.commands.filter(e=>e.byIdPath||e.unaddressedPath),l=c.flatMap(t=>t.ownMethod===void 0?[$(t,e,!1),$(t,e,!0)]:[!1,!0].flatMap(n=>[$(t,e,!1,n),$(t,e,!0,n)])),u=[`CommandClient`,`CommandResult`,`WowClientOptions`];c.length>0&&u.push(`CommandResultStream`);let d=e=>e.byIdPath!==void 0&&e.unaddressedPath!==void 0&&e.ownMethod===void 0;c.some(d)&&u.push(`CreateCommandOptions`),(c.some(e=>!d(e))||e.lifecycle.length>0)&&u.push(`CommandOptions`);let f=[];for(let t of e.lifecycle){u.push(`LifecycleCommands`),t.bodyType&&(t.bodyGenerated?f:u).push(t.bodyType);let n=t.bodyType?`body: ${t.bodyType}`:``,r=n=>`{ ...options, command: LifecycleCommands.${t.member}, type: { context: ${j(e.context)}, name: ${j(e.name)} }${n?`, id`:``}${t.bodyType?`, body`:``} }`;l.push(jr(Y([t.description,`The lifecycle command \`${t.name}\`.`,t.ownMethod===void 0?void 0:`By id, for a caller with no owner; \`${t.ownMethod}\` sends it to the caller's own.`],` `),t.method,n?`id: string, ${n}`:`id: string`,`CommandOptions`,r(!0))),t.ownMethod!==void 0&&l.push(jr(Y([t.description,`The lifecycle command \`${t.name}\`, to the caller's own aggregate, whose id is the caller's owner.`],` `),t.ownMethod,n,`CommandOptions`,r(!1)))}let p=c.filter(e=>e.bodyNumbers);p.length>0&&o.imports.add(`./aggregate.js`,[`${s}Aggregate`]);let m=p.length?`, bodyNumbers: {\n${p.map(t=>` ${j(`${e.context}.${e.name}.${t.name}`)}: ${s}Aggregate.textNumbers.commands.${A(t.name)===t.name?t.name:`[${j(t.name)}]`},`).join(`
33
- `)}\n }`:``,h=`${t.typeName}Manifest`;o.imports.add(P(o.directoryPath,(0,i.join)(a,t.directory,`manifest.ts`)),[h]),o.imports.add(J,[...new Set(u)].sort()),Q(o,a,r,[...c.map(e=>e.bodyType),...f]),X(o,`${Y([`Sends the commands of \`${e.context}.${e.name}\` by its service's routes (\`${h}\`). Each method answers the result its wait plan ends with, as \`CommandClient.wait\` does: the server's default plan unless the options give one, \`{ wait: WaitPlan.ACCEPTED }\` to answer once it is accepted. A rejected command rejects with a \`CommandRejectedError\`; anything else that did not succeed with a \`WowProblemError\`.`])}export class ${s}CommandClient {\n readonly client: CommandClient;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.client = new CommandClient(options, { manifest: ${h}${m} });\n }\n\n${l.join(`
34
-
35
- `)}\n}`)}function Nr(e,t,n,r){let i=t.module(`${e.directory}/queryClient.ts`),a=e.typeName,o=e.stateType,s=e.idSource===`owner`,c=s?`OwnStateClient`:`StateClient`,l=[c,`WowClientOptions`],u=[`${a}Aggregate`,`${a}Event`],d=` /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(${a}Aggregate, options);\n }`;e.queryModels.includes(`snapshot`)&&(l.push(`SnapshotQueryClient`),u.push(`${a}StateField`),X(i,`${Y([`Queries the snapshots of \`${e.context}.${e.name}\`: \`POST /${e.context}/${e.name}/snapshot/query\`.`])}export class ${a}SnapshotQueryClient extends SnapshotQueryClient<${o}, ${a}StateField> {\n${d}\n}`)),e.queryModels.includes(`events`)&&(l.push(`EventQueryClient`),X(i,`${Y([`Queries the event streams of \`${e.context}.${e.name}\`, one record per commit: \`POST /${e.context}/${e.name}/events/query\`.`])}export class ${a}EventQueryClient extends EventQueryClient<${a}Event> {\n${d}\n}`)),X(i,`${Y([s?`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: the caller's own by no id (\`readOwn\`, \`getOwn\`, \`findOwn\`, \`traceOwn\`: \`GET /${e.context}/${e.name}/state\`), and by id for a caller with no owner (\`GET /${e.context}/${e.name}/{id}/state\`).`:`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: \`GET /${e.context}/${e.name}/{id}/state\`.`])}export class ${a}StateClient extends ${c}<${o}, ${a}Event> {\n${d}\n}`),i.imports.add(J,l.sort()),i.imports.add(`./aggregate.js`,u),Q(i,r,n,[o])}function Pr(e){return{openAPI:e,components:e.components,endpoints:Ie(e.paths,e.components)}}var Fr=`.wow-generator.json`,Ir=class e{project;outputPath;outputDir;previous;written=new Set;stale=new Set;constructor(e,t,n,r){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r}static open(n,r,i){let a=n.getFileSystem(),o=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,Fr),l=new Map;if(a.fileExistsSync(c)){let e=Lr(c,a.readFileSync(c));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Vr(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new s(`output`,`Invalid generated file entry in ${c}: ${n}`);l.set(e,i)}}let u=new Set([...i?.written??[],...l.keys()]);for(let e of n.getSourceFiles())u.has(e.getFilePath())&&e.forget();return new e(n,o,r,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=f(t,e);Vr(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 Br(`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 zr(`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 Br(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Fr),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),Rr(n.readFileSync(e.getFilePath()))]))},null,2)+`
36
- `;await Br(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)})}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Vr(n.realpathSync(this.outputDir),n.realpathSync(e)),Rr(n.readFileSync(e))===t):!1}};function Lr(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 s(`output`,`Cannot parse the generation manifest ${e}: ${c(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 s(`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 s(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function Rr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function zr(e,t,n){return n instanceof s?n:new s(`output`,`Cannot ${e} ${t}: ${c(n)}`,{cause:n})}async function Br(e,t,n){try{await n()}catch(n){throw zr(e,t,n)}}function Vr(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),o=(0,t.relative)(i,a);if(o===``||o.startsWith(`..`)||(0,t.isAbsolute)(o))throw new s(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}var Hr=Symbol(`project`),Ur=Symbol(`signal`),Wr=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new u,this.signal=t[Ur],this.project=t[Hr]??Gr(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`),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},o=await Ln(n.configPath,e,a);i(o.warnings),t?.throwIfAborted(),e.debug(`Parsing the input document`);let c=await Nn(n.inputPath,a);if(t?.throwIfAborted(),Jn(c))return this.generateFromManifest(Yn(c,n.inputPath),o.origin,i,()=>r);let l=Pn(c,n.inputPath);e.debug(`OpenAPI specification parsed successfully`);let u=ee(l);if(u.length>0)throw new s(`specification`,`${n.inputPath} has ${u.length} $ref(s) that point at nothing: ${u.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${u.length>10?`, …`:``}`);let d=Pr(l),f=Ir.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=ct(d,o.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new dt(e=>f.claim(e));pn(p.model,{modules:m,outputDir:n.outputDir,types:ln(d.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(mn(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),En(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:o.origin,warnings:r}}async generateFromManifest(e,t,n,r){let{logger:i,signal:a,options:o}=this,s=Ir.open(this.project,o.outputDir,this.output);this.output=s,i.debug(`Analysing the Manifest`);let c=lr(e);n(c.warnings);let l=new dt(e=>s.claim(e));_r(c.model,l,o.outputDir),l.build(),s.forgetStale();let u=this.project.getDirectory(o.outputDir);return u&&(n(mn(u,e=>s.claim(`index.ts`,e))),En(u.getDescendantSourceFiles().filter(e=>s.files.has(e.getFilePath())),i)),await s.commit(a),i.debug(`Code generation from the Manifest completed successfully`),{files:[...s.files].sort(),configPath:t,warnings:r()}}};function Gr(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new s(`configuration`,`Cannot read the TypeScript configuration ${t}: ${c(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Ur}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Dn}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Wr}});
37
- //# sourceMappingURL=codeGenerator-CADTvm2G.cjs.map