@ahoo-wang/wow-generator 10.0.0-alpha.3 → 10.0.0-alpha.5

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 (76) hide show
  1. package/README.md +99 -62
  2. package/README.zh-CN.md +85 -48
  3. package/dist/analysis/analyze.d.cts +5 -8
  4. package/dist/analysis/analyze.d.ts +5 -8
  5. package/dist/analysis/apiClients.d.cts +3 -4
  6. package/dist/analysis/apiClients.d.ts +3 -4
  7. package/dist/analysis/clientNames.d.cts +0 -20
  8. package/dist/analysis/clientNames.d.ts +0 -20
  9. package/dist/analysis/model.d.cts +2 -102
  10. package/dist/analysis/model.d.ts +2 -102
  11. package/dist/analysis/modelInfo.d.cts +12 -3
  12. package/dist/analysis/modelInfo.d.ts +12 -3
  13. package/dist/analysis/models.d.cts +3 -11
  14. package/dist/analysis/models.d.ts +3 -11
  15. package/dist/api/configuration.d.cts +1 -5
  16. package/dist/api/configuration.d.ts +1 -5
  17. package/dist/cli/program.d.cts +0 -5
  18. package/dist/cli/program.d.ts +0 -5
  19. package/dist/cli.cjs +9 -1
  20. package/dist/cli.cjs.map +1 -1
  21. package/dist/cli.js +102 -3
  22. package/dist/cli.js.map +1 -1
  23. package/dist/{codeGenerator-CXBTLKZP.js → codeGenerator-CU1TGcUI.js} +716 -1327
  24. package/dist/codeGenerator-CU1TGcUI.js.map +1 -0
  25. package/dist/codeGenerator-DzI0zCgM.cjs +27 -0
  26. package/dist/codeGenerator-DzI0zCgM.cjs.map +1 -0
  27. package/dist/emit/imports.d.cts +0 -9
  28. package/dist/emit/imports.d.ts +0 -9
  29. package/dist/emitters/decorators.d.cts +3 -18
  30. package/dist/emitters/decorators.d.ts +3 -18
  31. package/dist/emitters/emit.d.cts +2 -3
  32. package/dist/emitters/emit.d.ts +2 -3
  33. package/dist/emitters/manifestClients.d.cts +3 -3
  34. package/dist/emitters/manifestClients.d.ts +3 -3
  35. package/dist/emitters/models.d.cts +1 -1
  36. package/dist/emitters/models.d.ts +1 -1
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/input/configuration.d.cts +2 -4
  40. package/dist/input/configuration.d.ts +2 -4
  41. package/dist/manifest/analyze.d.cts +18 -2
  42. package/dist/manifest/analyze.d.ts +18 -2
  43. package/dist/naming/modelInfo.d.cts +1 -2
  44. package/dist/naming/modelInfo.d.ts +1 -2
  45. package/dist/naming/paths.d.cts +0 -5
  46. package/dist/naming/paths.d.ts +0 -5
  47. package/dist/output/outputStore.d.cts +2 -6
  48. package/dist/output/outputStore.d.ts +2 -6
  49. package/dist/pipeline/codeGenerator.d.cts +13 -12
  50. package/dist/pipeline/codeGenerator.d.ts +13 -12
  51. package/package.json +8 -8
  52. package/dist/analysis/aggregates.d.cts +0 -21
  53. package/dist/analysis/aggregates.d.ts +0 -21
  54. package/dist/codeGenerator-Ba5Cz8XW.cjs +0 -31
  55. package/dist/codeGenerator-Ba5Cz8XW.cjs.map +0 -1
  56. package/dist/codeGenerator-CXBTLKZP.js.map +0 -1
  57. package/dist/emitters/commandClients.d.cts +0 -14
  58. package/dist/emitters/commandClients.d.ts +0 -14
  59. package/dist/emitters/queryClients.d.cts +0 -11
  60. package/dist/emitters/queryClients.d.ts +0 -11
  61. package/dist/fetcherGeneratorCli.cjs +0 -3
  62. package/dist/fetcherGeneratorCli.cjs.map +0 -1
  63. package/dist/fetcherGeneratorCli.d.cts +0 -8
  64. package/dist/fetcherGeneratorCli.d.ts +0 -8
  65. package/dist/fetcherGeneratorCli.js +0 -6
  66. package/dist/fetcherGeneratorCli.js.map +0 -1
  67. package/dist/program-BnfzUfUQ.cjs +0 -10
  68. package/dist/program-BnfzUfUQ.cjs.map +0 -1
  69. package/dist/program-CU0GCZqM.js +0 -103
  70. package/dist/program-CU0GCZqM.js.map +0 -1
  71. package/dist/wow/conventions.d.cts +0 -154
  72. package/dist/wow/conventions.d.ts +0 -154
  73. package/dist/wow/model.d.cts +0 -116
  74. package/dist/wow/model.d.ts +0 -116
  75. package/dist/wow/resolveWowModel.d.cts +0 -21
  76. package/dist/wow/resolveWowModel.d.ts +0 -21
@@ -1,7 +1,7 @@
1
1
  import { HTTPMethod, Reference, Schema } from '@ahoo-wang/fetcher-openapi';
2
2
  import { ModelInfo } from '../naming/modelInfo.cjs';
3
3
  /**
4
- * What a document generates, decided before anything is written: every
4
+ * What an OpenAPI document generates, decided before anything is written: every
5
5
  * name, file, parameter and kind of body or response, as plain data. It
6
6
  * holds no ts-morph node and no operation of the document; the emitters read
7
7
  * it, and only they resolve schemas to types, in this order, so the imports
@@ -10,12 +10,8 @@ import { ModelInfo } from '../naming/modelInfo.cjs';
10
10
  * Files are relative to the output directory.
11
11
  */
12
12
  export interface GenerationModel {
13
- /** The bounded contexts, each a file declaring its alias constant; sorted. */
14
- readonly contexts: readonly BoundedContextModel[];
15
13
  /** The models, in the order of the document's components. */
16
14
  readonly models: readonly ModelDeclaration[];
17
- /** The aggregates with a command and a query client, by bounded context. */
18
- readonly aggregates: readonly AggregateModel[];
19
15
  /** The API clients, one per tag, sorted by tag name. */
20
16
  readonly apiClients: readonly ApiClientModel[];
21
17
  }
@@ -25,17 +21,6 @@ export interface Analysis {
25
21
  /** One line each, in the order they arose. */
26
22
  readonly warnings: readonly string[];
27
23
  }
28
- /** A bounded context's alias constant: `export const SHOP_BOUNDED_CONTEXT_ALIAS = 'shop';`. */
29
- export interface BoundedContextModel {
30
- readonly alias: string;
31
- readonly constantName: string;
32
- readonly file: string;
33
- }
34
- /** The constant a module imports to name its bounded context. */
35
- export interface ContextReference {
36
- readonly alias: string;
37
- readonly constantName: string;
38
- }
39
24
  /** A model: one declaration (and its companions) of a component schema. */
40
25
  export interface ModelDeclaration {
41
26
  /** The component key. */
@@ -43,91 +28,8 @@ export interface ModelDeclaration {
43
28
  /** Its name, and the package path of its file. */
44
29
  readonly info: ModelInfo;
45
30
  readonly file: string;
46
- /** The schema as the document has it; the types read this one. */
31
+ /** The schema as the document has it. */
47
32
  readonly schema: Schema | Reference;
48
- /**
49
- * The schema its doc comment reads: with the title and description the
50
- * Wow metadata lends it over it, when it lends any.
51
- */
52
- readonly docSchema: Schema | Reference;
53
- /**
54
- * A command or event body that declares nothing - a Kotlin `data object` -
55
- * which generates `Record<string, never>` rather than any object.
56
- */
57
- readonly emptyMessageBody: boolean;
58
- }
59
- /** An aggregate: its command client and its query client. */
60
- export interface AggregateModel {
61
- readonly contextAlias: string;
62
- readonly aggregateName: string;
63
- readonly context: ContextReference;
64
- readonly commandClient: CommandClientModel;
65
- readonly queryClient: QueryClientModel;
66
- }
67
- /** The command client of an aggregate, and its streaming twin. */
68
- export interface CommandClientModel {
69
- readonly file: string;
70
- /** The enum of the command routes: `CartCommandEndpointPaths`. */
71
- readonly endpointPathsName: string;
72
- readonly className: string;
73
- readonly streamClassName: string;
74
- readonly commands: readonly CommandModel[];
75
- }
76
- /** A command of an aggregate. */
77
- export interface CommandModel {
78
- /** The command's route, and the member of the route enum that holds it. */
79
- readonly path: string;
80
- readonly endpointMember: string;
81
- readonly httpMethod: HTTPMethod;
82
- readonly methodName: string;
83
- /**
84
- * The alias of the command's body type: `AddCartItemCommand`. None when
85
- * the body's name already ends in `Command`: its methods then take
86
- * `CommandBody<MountedCommand>` itself, so no name repeats the suffix.
87
- */
88
- readonly typeName?: string;
89
- /** The body's model; one of Wow's own lives in wow-client, with its type. */
90
- readonly body: ModelInfo;
91
- /** The component key of the body's schema. */
92
- readonly bodyKey: string;
93
- /** The body's properties a caller may leave out. */
94
- readonly optionalFields: readonly string[];
95
- /** Whether a request may leave out the body: it has no properties. */
96
- readonly requestOptional: boolean;
97
- /** The path parameters the caller passes. */
98
- readonly pathParameters: readonly PathParameterModel[];
99
- readonly docs: readonly (string | undefined)[];
100
- }
101
- /** A path parameter of a command method, in the order the route holds them. */
102
- export interface PathParameterModel {
103
- /** The method's parameter: an identifier. */
104
- readonly name: string;
105
- /** The name in the route. */
106
- readonly pathName: string;
107
- readonly type: string;
108
- }
109
- /** The query client factory of an aggregate. */
110
- export interface QueryClientModel {
111
- readonly file: string;
112
- /** The aggregate's route segment: its resource name. */
113
- readonly resourceName: string;
114
- /** A `ResourceAttributionPathSpec` member, as code. */
115
- readonly resourceAttribution: string;
116
- readonly state: ModelInfo;
117
- readonly fields: ModelInfo;
118
- /** The enum of the event titles: `CartDomainEventTypeMapTitle`. */
119
- readonly eventTitlesName: string;
120
- /** The union of the event types: `CartDomainEventType`. */
121
- readonly eventTypeName: string;
122
- readonly events: readonly EventModel[];
123
- readonly factoryName: string;
124
- }
125
- /** A domain event of an aggregate. */
126
- export interface EventModel {
127
- /** Its member of the event title enum. */
128
- readonly memberName: string;
129
- readonly title: string;
130
- readonly body: ModelInfo;
131
33
  }
132
34
  /** The API client of a tag. */
133
35
  export interface ApiClientModel {
@@ -136,8 +38,6 @@ export interface ApiClientModel {
136
38
  readonly file: string;
137
39
  /** The tag's description, the class's doc comment. */
138
40
  readonly description?: string;
139
- /** The bounded context whose alias is the base path, in a Wow document. */
140
- readonly basePath?: ContextReference;
141
41
  /** In the order of the document's operations, by operation id. */
142
42
  readonly methods: readonly ApiMethodModel[];
143
43
  }
@@ -1,7 +1,7 @@
1
1
  import { HTTPMethod, Reference, Schema } from '@ahoo-wang/fetcher-openapi';
2
2
  import { ModelInfo } from '../naming/modelInfo.js';
3
3
  /**
4
- * What a document generates, decided before anything is written: every
4
+ * What an OpenAPI document generates, decided before anything is written: every
5
5
  * name, file, parameter and kind of body or response, as plain data. It
6
6
  * holds no ts-morph node and no operation of the document; the emitters read
7
7
  * it, and only they resolve schemas to types, in this order, so the imports
@@ -10,12 +10,8 @@ import { ModelInfo } from '../naming/modelInfo.js';
10
10
  * Files are relative to the output directory.
11
11
  */
12
12
  export interface GenerationModel {
13
- /** The bounded contexts, each a file declaring its alias constant; sorted. */
14
- readonly contexts: readonly BoundedContextModel[];
15
13
  /** The models, in the order of the document's components. */
16
14
  readonly models: readonly ModelDeclaration[];
17
- /** The aggregates with a command and a query client, by bounded context. */
18
- readonly aggregates: readonly AggregateModel[];
19
15
  /** The API clients, one per tag, sorted by tag name. */
20
16
  readonly apiClients: readonly ApiClientModel[];
21
17
  }
@@ -25,17 +21,6 @@ export interface Analysis {
25
21
  /** One line each, in the order they arose. */
26
22
  readonly warnings: readonly string[];
27
23
  }
28
- /** A bounded context's alias constant: `export const SHOP_BOUNDED_CONTEXT_ALIAS = 'shop';`. */
29
- export interface BoundedContextModel {
30
- readonly alias: string;
31
- readonly constantName: string;
32
- readonly file: string;
33
- }
34
- /** The constant a module imports to name its bounded context. */
35
- export interface ContextReference {
36
- readonly alias: string;
37
- readonly constantName: string;
38
- }
39
24
  /** A model: one declaration (and its companions) of a component schema. */
40
25
  export interface ModelDeclaration {
41
26
  /** The component key. */
@@ -43,91 +28,8 @@ export interface ModelDeclaration {
43
28
  /** Its name, and the package path of its file. */
44
29
  readonly info: ModelInfo;
45
30
  readonly file: string;
46
- /** The schema as the document has it; the types read this one. */
31
+ /** The schema as the document has it. */
47
32
  readonly schema: Schema | Reference;
48
- /**
49
- * The schema its doc comment reads: with the title and description the
50
- * Wow metadata lends it over it, when it lends any.
51
- */
52
- readonly docSchema: Schema | Reference;
53
- /**
54
- * A command or event body that declares nothing - a Kotlin `data object` -
55
- * which generates `Record<string, never>` rather than any object.
56
- */
57
- readonly emptyMessageBody: boolean;
58
- }
59
- /** An aggregate: its command client and its query client. */
60
- export interface AggregateModel {
61
- readonly contextAlias: string;
62
- readonly aggregateName: string;
63
- readonly context: ContextReference;
64
- readonly commandClient: CommandClientModel;
65
- readonly queryClient: QueryClientModel;
66
- }
67
- /** The command client of an aggregate, and its streaming twin. */
68
- export interface CommandClientModel {
69
- readonly file: string;
70
- /** The enum of the command routes: `CartCommandEndpointPaths`. */
71
- readonly endpointPathsName: string;
72
- readonly className: string;
73
- readonly streamClassName: string;
74
- readonly commands: readonly CommandModel[];
75
- }
76
- /** A command of an aggregate. */
77
- export interface CommandModel {
78
- /** The command's route, and the member of the route enum that holds it. */
79
- readonly path: string;
80
- readonly endpointMember: string;
81
- readonly httpMethod: HTTPMethod;
82
- readonly methodName: string;
83
- /**
84
- * The alias of the command's body type: `AddCartItemCommand`. None when
85
- * the body's name already ends in `Command`: its methods then take
86
- * `CommandBody<MountedCommand>` itself, so no name repeats the suffix.
87
- */
88
- readonly typeName?: string;
89
- /** The body's model; one of Wow's own lives in wow-client, with its type. */
90
- readonly body: ModelInfo;
91
- /** The component key of the body's schema. */
92
- readonly bodyKey: string;
93
- /** The body's properties a caller may leave out. */
94
- readonly optionalFields: readonly string[];
95
- /** Whether a request may leave out the body: it has no properties. */
96
- readonly requestOptional: boolean;
97
- /** The path parameters the caller passes. */
98
- readonly pathParameters: readonly PathParameterModel[];
99
- readonly docs: readonly (string | undefined)[];
100
- }
101
- /** A path parameter of a command method, in the order the route holds them. */
102
- export interface PathParameterModel {
103
- /** The method's parameter: an identifier. */
104
- readonly name: string;
105
- /** The name in the route. */
106
- readonly pathName: string;
107
- readonly type: string;
108
- }
109
- /** The query client factory of an aggregate. */
110
- export interface QueryClientModel {
111
- readonly file: string;
112
- /** The aggregate's route segment: its resource name. */
113
- readonly resourceName: string;
114
- /** A `ResourceAttributionPathSpec` member, as code. */
115
- readonly resourceAttribution: string;
116
- readonly state: ModelInfo;
117
- readonly fields: ModelInfo;
118
- /** The enum of the event titles: `CartDomainEventTypeMapTitle`. */
119
- readonly eventTitlesName: string;
120
- /** The union of the event types: `CartDomainEventType`. */
121
- readonly eventTypeName: string;
122
- readonly events: readonly EventModel[];
123
- readonly factoryName: string;
124
- }
125
- /** A domain event of an aggregate. */
126
- export interface EventModel {
127
- /** Its member of the event title enum. */
128
- readonly memberName: string;
129
- readonly title: string;
130
- readonly body: ModelInfo;
131
33
  }
132
34
  /** The API client of a tag. */
133
35
  export interface ApiClientModel {
@@ -136,8 +38,6 @@ export interface ApiClientModel {
136
38
  readonly file: string;
137
39
  /** The tag's description, the class's doc comment. */
138
40
  readonly description?: string;
139
- /** The bounded context whose alias is the base path, in a Wow document. */
140
- readonly basePath?: ContextReference;
141
41
  /** In the order of the document's operations, by operation id. */
142
42
  readonly methods: readonly ApiMethodModel[];
143
43
  }
@@ -1,4 +1,4 @@
1
- import { Components, Reference, Schema } from '@ahoo-wang/fetcher-openapi';
1
+ import { Components, Reference } from '@ahoo-wang/fetcher-openapi';
2
2
  import { ModelInfo } from '../naming/modelInfo.cjs';
3
3
  export type { ModelInfo } from '../naming/modelInfo.cjs';
4
4
  /**
@@ -18,6 +18,15 @@ export type { ModelInfo } from '../naming/modelInfo.cjs';
18
18
  * @param schemaKey - The dot-separated schema key (e.g., "com.example.User")
19
19
  * @returns ModelInfo object containing the parsed name and path
20
20
  */
21
- export declare function resolveModelInfo(schemaKey: string, schema?: Schema): ModelInfo;
21
+ export declare function resolveModelInfo(schemaKey: string): ModelInfo;
22
+ /**
23
+ * The model a reference names.
24
+ *
25
+ * @param reference - A reference to a component schema
26
+ * @param components - The document's components; given, the reference is
27
+ * followed to its schema, so a chain of references that comes back to itself
28
+ * fails here rather than as code that cannot compile
29
+ * @throws GeneratorError for a reference outside the component schemas, or
30
+ * a cyclic one
31
+ */
22
32
  export declare function resolveReferenceModelInfo(reference: Reference, components?: Components): ModelInfo;
23
- export declare function resolveContextDeclarationName(contextAlias: string): string;
@@ -1,4 +1,4 @@
1
- import { Components, Reference, Schema } from '@ahoo-wang/fetcher-openapi';
1
+ import { Components, Reference } from '@ahoo-wang/fetcher-openapi';
2
2
  import { ModelInfo } from '../naming/modelInfo.js';
3
3
  export type { ModelInfo } from '../naming/modelInfo.js';
4
4
  /**
@@ -18,6 +18,15 @@ export type { ModelInfo } from '../naming/modelInfo.js';
18
18
  * @param schemaKey - The dot-separated schema key (e.g., "com.example.User")
19
19
  * @returns ModelInfo object containing the parsed name and path
20
20
  */
21
- export declare function resolveModelInfo(schemaKey: string, schema?: Schema): ModelInfo;
21
+ export declare function resolveModelInfo(schemaKey: string): ModelInfo;
22
+ /**
23
+ * The model a reference names.
24
+ *
25
+ * @param reference - A reference to a component schema
26
+ * @param components - The document's components; given, the reference is
27
+ * followed to its schema, so a chain of references that comes back to itself
28
+ * fails here rather than as code that cannot compile
29
+ * @throws GeneratorError for a reference outside the component schemas, or
30
+ * a cyclic one
31
+ */
22
32
  export declare function resolveReferenceModelInfo(reference: Reference, components?: Components): ModelInfo;
23
- export declare function resolveContextDeclarationName(contextAlias: string): string;
@@ -1,17 +1,9 @@
1
1
  import { OpenApiDocument } from '../openapi/document.cjs';
2
- import { WowModel } from '../wow/model.cjs';
3
- import { BoundedContextModel, ModelDeclaration } from './model.cjs';
4
- /**
5
- * The bounded contexts whose alias constant is generated: every context with
6
- * aggregates, and the document's own, which API clients take their base path
7
- * from. Sorted by alias.
8
- */
9
- export declare function analyzeContexts(wow: WowModel): BoundedContextModel[];
2
+ import { ModelDeclaration } from './model.cjs';
10
3
  /**
11
4
  * The models of a document: one per component schema, in the document's
12
- * order, but for Wow's own schemas, which wow-client declares (`wow.*`, and
13
- * the types every aggregate derives from its state).
5
+ * order.
14
6
  *
15
7
  * @throws GeneratorError when two schemas generate the same model
16
8
  */
17
- export declare function analyzeModels(document: OpenApiDocument, wow: WowModel): ModelDeclaration[];
9
+ export declare function analyzeModels(document: OpenApiDocument): ModelDeclaration[];
@@ -1,17 +1,9 @@
1
1
  import { OpenApiDocument } from '../openapi/document.js';
2
- import { WowModel } from '../wow/model.js';
3
- import { BoundedContextModel, ModelDeclaration } from './model.js';
4
- /**
5
- * The bounded contexts whose alias constant is generated: every context with
6
- * aggregates, and the document's own, which API clients take their base path
7
- * from. Sorted by alias.
8
- */
9
- export declare function analyzeContexts(wow: WowModel): BoundedContextModel[];
2
+ import { ModelDeclaration } from './model.js';
10
3
  /**
11
4
  * The models of a document: one per component schema, in the document's
12
- * order, but for Wow's own schemas, which wow-client declares (`wow.*`, and
13
- * the types every aggregate derives from its state).
5
+ * order.
14
6
  *
15
7
  * @throws GeneratorError when two schemas generate the same model
16
8
  */
17
- export declare function analyzeModels(document: OpenApiDocument, wow: WowModel): ModelDeclaration[];
9
+ export declare function analyzeModels(document: OpenApiDocument): ModelDeclaration[];
@@ -15,11 +15,7 @@ export interface GeneratorConfiguration {
15
15
  export interface ApiClientConfiguration {
16
16
  /**
17
17
  * The path parameters the client leaves out, because an interceptor fills
18
- * them.
19
- *
20
- * Default: `['tenantId', 'ownerId']` for a Wow document (one with
21
- * `x-wow-context-alias` or aggregates), whose CoSec interceptor fills them;
22
- * none for any other document.
18
+ * them. Default: none.
23
19
  */
24
20
  ignorePathParameters?: string[];
25
21
  /**
@@ -15,11 +15,7 @@ export interface GeneratorConfiguration {
15
15
  export interface ApiClientConfiguration {
16
16
  /**
17
17
  * The path parameters the client leaves out, because an interceptor fills
18
- * them.
19
- *
20
- * Default: `['tenantId', 'ownerId']` for a Wow document (one with
21
- * `x-wow-context-alias` or aggregates), whose CoSec interceptor fills them;
22
- * none for any other document.
18
+ * them. Default: none.
23
19
  */
24
20
  ignorePathParameters?: string[];
25
21
  /**
@@ -1,11 +1,6 @@
1
1
  import { Command, CommanderError } from 'commander';
2
2
  /** The exit codes `generate --help` lists, as the README's table does. */
3
3
  export declare const EXIT_CODE_HELP: string;
4
- /**
5
- * What the `fetcher-generator` bin prints to stderr before it runs: the name
6
- * still works, and goes in v10.
7
- */
8
- export declare const DEPRECATED_BIN_NOTICE = "fetcher-generator is deprecated and will be removed in v10; run wow-generator instead.";
9
4
  /** Collects the values of an option given more than once, such as `--header`. */
10
5
  export declare function collect(value: string, previous?: string[]): string[];
11
6
  /**
@@ -1,11 +1,6 @@
1
1
  import { Command, CommanderError } from 'commander';
2
2
  /** The exit codes `generate --help` lists, as the README's table does. */
3
3
  export declare const EXIT_CODE_HELP: string;
4
- /**
5
- * What the `fetcher-generator` bin prints to stderr before it runs: the name
6
- * still works, and goes in v10.
7
- */
8
- export declare const DEPRECATED_BIN_NOTICE = "fetcher-generator is deprecated and will be removed in v10; run wow-generator instead.";
9
4
  /** Collects the values of an option given more than once, such as `--header`. */
10
5
  export declare function collect(value: string, previous?: string[]): string[];
11
6
  /**
package/dist/cli.cjs CHANGED
@@ -1,3 +1,11 @@
1
1
  #!/usr/bin/env node
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./program-BnfzUfUQ.cjs");e.r(),exports.collect=e.n,exports.runCLI=e.r,exports.setupCLI=e.i;
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-DzI0zCgM.cjs");let t=require("path"),n=require("commander");var r=`10.0.0-alpha.5`;function i(e){if(!e)return!1;let t;try{t=new URL(e)}catch{return!0}return/^[a-z]:$/i.test(t.protocol)?!0:t.protocol===`http:`||t.protocol===`https:`}function a(t=[]){let n={};for(let r of t){let t=r.indexOf(`:`),i=t>0?r.slice(0,t).trim():``;if(!i)throw new e.s(`input`,`Invalid --header "${r}": expected "Name: value".`);n[i]=r.slice(t+1).trim()}return n}function o(t){if(t===void 0)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw new e.s(`input`,`Invalid --timeout "${t}": expected a positive number of milliseconds.`);return n}function s(t){if(t===void 0||t===`summary`)return`summary`;if(t===`full`)return`full`;throw new e.s(`input`,`Invalid --schema-docs "${t}": expected "summary" or "full".`)}function c(e){return e.verbose?`verbose`:e.quiet?`quiet`:`normal`}function l(t,n,r){if(n instanceof e.s)return t.error(n.message),r&&n.cause!==void 0&&t.error(`Caused by:`,n.cause),n.exitCode;let i=n instanceof Error?n.message:String(n);return t.error(`Code generation failed: ${i}`),r?t.error(``,n):t.error(`Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.`),e.o.internal}async function u(n,u=new e.i({level:c(n)}),d={}){if(!i(n.input))return u.error(`Invalid input "${n.input}": expected a file path or an http(s) URL.`),e.o.input;try{u.debug(`wow-generator v${r}`);let i={...d,inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,headers:a(n.header),timeoutMs:o(n.timeout),schemaDocs:s(n.schemaDocs),logger:u},c=await new e.t(i).generate(),l=c.warnings?`, ${c.warnings} warning${c.warnings===1?``:`s`}`:``,f=c.configPath?` with ${(0,t.relative)(process.cwd(),c.configPath)||c.configPath}`:``;return u.info(`Generated ${c.files.length} files into ${n.output}${f}${l}`),n.strict&&c.warnings>0?(u.error(`--strict: the run logged ${c.warnings} warning${c.warnings===1?``:`s`}.`),e.o.specification):e.o.success}catch(t){return d[e.n]?.aborted?e.o.interrupted:l(u,t,!!n.verbose)}}async function d(t){let n=new AbortController;process.once(`SIGINT`,()=>{console.error(`Generation interrupted by user`),n.abort()}),process.exitCode=await u(t,void 0,{[e.n]:n.signal})}var f=`
3
+ Exit codes:
4
+ ${e.o.success} generated; or --help, help or --version printed
5
+ ${e.o.internal} internal error; rerun with --verbose for the stack trace
6
+ ${e.o.input} input or usage: unreadable, unfetchable or not OpenAPI 3.x; an invalid option
7
+ ${e.o.configuration} configuration: cannot be read, parsed or validated
8
+ ${e.o.specification} specification: cannot be generated, or --strict and the run had warnings
9
+ ${e.o.output} output: the manifest, a path outside the output, or a failed write
10
+ ${e.o.interrupted} interrupted (Ctrl-C)`;function p(e,t=[]){return[...t,e]}function m(t=n.program){return t.exitOverride(),t.name(`wow-generator`).description(`TypeScript client generator for Wow: from a Wow Manifest or an OpenAPI 3 document`).version(r,`-v, --version`),t.command(`generate`).description(`Generate TypeScript code from a Wow Manifest or an OpenAPI 3 document`).requiredOption(`-i, --input <file>`,`Input OpenAPI specification or Wow Manifest (GET /wow/manifest) file path or URL (http/https)`).option(`-o, --output <path>`,`Output directory path`,`src/generated`).option(`-c, --config <file>`,`Configuration file path (default: ${e.c})`).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`,p).option(`--timeout <ms>`,`Milliseconds before fetching an http(s) input is abandoned (default: ${e.r})`).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`).addHelpText(`after`,f).action(d),t}function h(t){return t.exitCode===0?e.o.success:e.o.input}async function g(e,t=m()){try{e===void 0?await t.parseAsync():await t.parseAsync(e,{from:`user`})}catch(e){if(!(e instanceof n.CommanderError))throw e;process.exitCode=h(e)}}g(),exports.collect=p,exports.runCLI=g,exports.setupCLI=m;
3
11
  //# sourceMappingURL=cli.cjs.map
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.cjs","names":["runCLI","require_program"],"sources":["../src/cli.ts"],"sourcesContent":["#!/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":";6GAWKA,EAAAA,EAAO"}
1
+ {"version":3,"file":"cli.cjs","names":["GeneratorError","EXIT_CODES","ConsoleLogger","CodeGenerator","relative","SIGNAL_SEAM","EXIT_CODES","program","DEFAULT_CONFIG_PATH","DEFAULT_HTTP_TIMEOUT_MS","CommanderError","require_codeGenerator","path","commander","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","generateAction","interruption","EXIT_CODE_HELP","collect","previous","setupCLI","target","commanderExitCode","runCLI","args"],"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/** The exit codes `generate --help` lists, as the README's table does. */\nexport const EXIT_CODE_HELP = `\nExit codes:\n ${EXIT_CODES.success} generated; or --help, help or --version printed\n ${EXIT_CODES.internal} internal error; rerun with --verbose for the stack trace\n ${EXIT_CODES.input} input or usage: unreadable, unfetchable or not OpenAPI 3.x; an invalid option\n ${EXIT_CODES.configuration} configuration: cannot be read, parsed or validated\n ${EXIT_CODES.specification} specification: cannot be generated, or --strict and the run had warnings\n ${EXIT_CODES.output} output: the manifest, a path outside the output, or a failed write\n ${EXIT_CODES.interrupted} interrupted (Ctrl-C)`;\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 target\n .name('wow-generator')\n .description(\n 'TypeScript client generator for Wow: from a Wow Manifest or an OpenAPI 3 document',\n )\n .version(VERSION, '-v, --version');\n\n target\n .command('generate')\n .description(\n 'Generate TypeScript code from a Wow Manifest or an OpenAPI 3 document',\n )\n .requiredOption(\n '-i, --input <file>',\n 'Input OpenAPI specification or Wow Manifest (GET /wow/manifest) 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 .addHelpText('after', EXIT_CODE_HELP)\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":";gKAmBA,IAAac,EAAA,iBCmCb,SAAgBC,EAAc,EAAwB,CACpD,GAAI,CAACC,EAAO,MAAO,GACnB,IAAIC,EACJ,GAAI,CACF,EAAM,IAAI,IAAID,CAAK,CACrB,MAAQ,CAEN,MAAO,EACT,CAGA,MADI,YAAY,KAAKC,EAAI,QAAQ,EAAU,GACpCA,EAAI,WAAa,SAAWA,EAAI,WAAa,QACtD,CASA,SAAgBC,EACd,EAA6B,CAAC,EACN,CACxB,IAAMC,EAAiC,CAAC,EACxC,IAAK,IAAMC,KAAUC,EAAS,CAC5B,IAAMC,EAAYF,EAAO,QAAQ,GAAG,EAC9BG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CAAE,KAAM,MAAO,CAAC,CAElD,OAASnB,EAAO,CACd,GAAI,EAAEA,aAAiBtB,EAAAA,gBAAiB,MAAMsB,EAC9C,QAAQ,SAAWiB,EAAkBjB,CAAK,CAC5C,CACF,CC/HKkB,EAAO"}
package/dist/cli.js CHANGED
@@ -1,8 +1,107 @@
1
1
  #!/usr/bin/env node
2
- import { i as e, n as t, r as n } from "./program-CU0GCZqM.js";
2
+ import { c as e, i as t, n, o as r, r as i, s as a, t as o } from "./codeGenerator-CU1TGcUI.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 = "10.0.0-alpha.5";
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
+ var y = `
76
+ Exit codes:
77
+ ${r.success} generated; or --help, help or --version printed
78
+ ${r.internal} internal error; rerun with --verbose for the stack trace
79
+ ${r.input} input or usage: unreadable, unfetchable or not OpenAPI 3.x; an invalid option
80
+ ${r.configuration} configuration: cannot be read, parsed or validated
81
+ ${r.specification} specification: cannot be generated, or --strict and the run had warnings
82
+ ${r.output} output: the manifest, a path outside the output, or a failed write
83
+ ${r.interrupted} interrupted (Ctrl-C)`;
84
+ function b(e, t = []) {
85
+ return [...t, e];
86
+ }
87
+ function x(t = l) {
88
+ return t.exitOverride(), t.name("wow-generator").description("TypeScript client generator for Wow: from a Wow Manifest or an OpenAPI 3 document").version(u, "-v, --version"), t.command("generate").description("Generate TypeScript code from a Wow Manifest or an OpenAPI 3 document").requiredOption("-i, --input <file>", "Input OpenAPI specification or Wow Manifest (GET /wow/manifest) 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", b).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").addHelpText("after", y).action(v), t;
89
+ }
90
+ function S(e) {
91
+ return e.exitCode === 0 ? r.success : r.input;
92
+ }
93
+ async function C(e, t = x()) {
94
+ try {
95
+ e === void 0 ? await t.parseAsync() : await t.parseAsync(e, { from: "user" });
96
+ } catch (e) {
97
+ if (!(e instanceof c)) throw e;
98
+ process.exitCode = S(e);
99
+ }
100
+ }
101
+ //#endregion
3
102
  //#region src/cli.ts
4
- n();
103
+ C();
5
104
  //#endregion
6
- export { t as collect, n as runCLI, e as setupCLI };
105
+ export { b as collect, C as runCLI, x as setupCLI };
7
106
 
8
107
  //# sourceMappingURL=cli.js.map