@goast/typescript 0.5.2-k6.1 → 0.5.2

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 (86) hide show
  1. package/LICENSE +21 -21
  2. package/assets/client/k6/request-builder.ts +362 -362
  3. package/package.json +1 -1
  4. package/src/mod.ts +7 -0
  5. package/src/src/assets.ts +9 -0
  6. package/src/src/ast/_index.ts +54 -0
  7. package/src/src/ast/common.ts +1 -0
  8. package/src/src/ast/index.ts +1 -0
  9. package/src/src/ast/node.ts +10 -0
  10. package/src/src/ast/nodes/argument.ts +40 -0
  11. package/src/src/ast/nodes/array-type.ts +49 -0
  12. package/src/src/ast/nodes/arrow-function.ts +91 -0
  13. package/src/src/ast/nodes/call.ts +55 -0
  14. package/src/src/ast/nodes/class.ts +133 -0
  15. package/src/src/ast/nodes/constructor-parameter.ts +70 -0
  16. package/src/src/ast/nodes/constructor.ts +77 -0
  17. package/src/src/ast/nodes/decorator.ts +76 -0
  18. package/src/src/ast/nodes/doc-tag.ts +291 -0
  19. package/src/src/ast/nodes/doc.ts +102 -0
  20. package/src/src/ast/nodes/enum-value.ts +72 -0
  21. package/src/src/ast/nodes/enum.ts +77 -0
  22. package/src/src/ast/nodes/export.ts +54 -0
  23. package/src/src/ast/nodes/function-type.ts +60 -0
  24. package/src/src/ast/nodes/function.ts +107 -0
  25. package/src/src/ast/nodes/generic-parameter.ts +71 -0
  26. package/src/src/ast/nodes/indexer.ts +60 -0
  27. package/src/src/ast/nodes/interface.ts +117 -0
  28. package/src/src/ast/nodes/intersection-type.ts +67 -0
  29. package/src/src/ast/nodes/lookup-type.ts +53 -0
  30. package/src/src/ast/nodes/method.ts +138 -0
  31. package/src/src/ast/nodes/object-type.ts +52 -0
  32. package/src/src/ast/nodes/object.ts +48 -0
  33. package/src/src/ast/nodes/parameter.ts +85 -0
  34. package/src/src/ast/nodes/property-accessor.ts +173 -0
  35. package/src/src/ast/nodes/property.ts +192 -0
  36. package/src/src/ast/nodes/reference.ts +194 -0
  37. package/src/src/ast/nodes/string.ts +49 -0
  38. package/src/src/ast/nodes/tuple.ts +53 -0
  39. package/src/src/ast/nodes/type-alias.ts +75 -0
  40. package/src/src/ast/nodes/typeof.ts +42 -0
  41. package/src/src/ast/nodes/types.ts +40 -0
  42. package/src/src/ast/nodes/union-type.ts +62 -0
  43. package/src/src/ast/nodes/variable.ts +73 -0
  44. package/src/src/ast/references/angular.ts +24 -0
  45. package/src/src/ast/references/easy-network-stub.ts +21 -0
  46. package/src/src/ast/references/index.ts +5 -0
  47. package/src/src/ast/references/k6.ts +8 -0
  48. package/src/src/ast/references/rxjs.ts +7 -0
  49. package/src/src/ast/references/typescript.ts +35 -0
  50. package/src/src/ast/utils/get-type-script-builder-options.ts +19 -0
  51. package/src/src/ast/utils/to-ts-node.ts +27 -0
  52. package/src/src/ast/utils/write-ts-generic-parameters.ts +25 -0
  53. package/src/src/ast/utils/write-ts-members.ts +28 -0
  54. package/src/src/ast/utils/write-ts-nodes.ts +35 -0
  55. package/src/src/ast/utils/write-ts-parameters.ts +25 -0
  56. package/src/src/common-results.ts +26 -0
  57. package/src/src/config.ts +89 -0
  58. package/src/src/file-builder.ts +136 -0
  59. package/src/src/generators/file-generator.ts +15 -0
  60. package/src/src/generators/index.ts +6 -0
  61. package/src/src/generators/models/index.ts +3 -0
  62. package/src/src/generators/models/model-generator.ts +469 -0
  63. package/src/src/generators/models/models-generator.ts +108 -0
  64. package/src/src/generators/models/models.ts +121 -0
  65. package/src/src/generators/services/angular-services/angular-service-generator.ts +406 -0
  66. package/src/src/generators/services/angular-services/angular-services-generator.ts +295 -0
  67. package/src/src/generators/services/angular-services/index.ts +3 -0
  68. package/src/src/generators/services/angular-services/models.ts +277 -0
  69. package/src/src/generators/services/angular-services/refs.ts +54 -0
  70. package/src/src/generators/services/easy-network-stub/easy-network-stub-generator.ts +242 -0
  71. package/src/src/generators/services/easy-network-stub/easy-network-stubs-generator.ts +211 -0
  72. package/src/src/generators/services/easy-network-stub/index.ts +3 -0
  73. package/src/src/generators/services/easy-network-stub/models.ts +124 -0
  74. package/src/src/generators/services/easy-network-stub/refs.ts +45 -0
  75. package/src/src/generators/services/fetch-clients/fetch-client-generator.ts +267 -0
  76. package/src/src/generators/services/fetch-clients/fetch-clients-generator.ts +163 -0
  77. package/src/src/generators/services/fetch-clients/index.ts +3 -0
  78. package/src/src/generators/services/fetch-clients/models.ts +130 -0
  79. package/src/src/generators/services/fetch-clients/refs.ts +21 -0
  80. package/src/src/generators/services/k6-clients/index.ts +3 -0
  81. package/src/src/generators/services/k6-clients/k6-client-generator.ts +465 -0
  82. package/src/src/generators/services/k6-clients/k6-clients-generator.ts +171 -0
  83. package/src/src/generators/services/k6-clients/models.ts +247 -0
  84. package/src/src/generators/services/k6-clients/refs.ts +16 -0
  85. package/src/src/import-collection.ts +236 -0
  86. package/src/src/utils.ts +72 -0
@@ -0,0 +1,211 @@
1
+ import { resolve } from 'node:path';
2
+
3
+
4
+ import fs from 'fs-extra';
5
+
6
+ import {
7
+ adjustCasing,
8
+ type ApiService,
9
+ type AppendValueGroup,
10
+ appendValueGroup,
11
+ builderTemplate as s,
12
+ Factory,
13
+ type MaybePromise,
14
+ type OpenApiGeneratorContext,
15
+ OpenApiServicesGenerationProviderBase,
16
+ toCasing,
17
+ } from '@goast/core';
18
+
19
+ import { copyAssetFile } from '../../../assets.js';
20
+ import { ts } from '../../../ast/index.js';
21
+ import type { TypeScriptExportOutput } from '../../../common-results.js';
22
+ import { TypeScriptFileBuilder } from '../../../file-builder.js';
23
+ import {
24
+ DefaultTypeScriptEasyNetworkStubGenerator,
25
+ type TypeScriptEasyNetworkStubGenerator,
26
+ } from './easy-network-stub-generator.js';
27
+ import {
28
+ defaultTypeScriptEasyNetworkStubsGeneratorConfig,
29
+ type TypeScriptEasyNetworkStubGeneratorOutput,
30
+ type TypeScriptEasyNetworkStubsGeneratorConfig,
31
+ type TypeScriptEasyNetworkStubsGeneratorContext,
32
+ type TypeScriptEasyNetworkStubsGeneratorInput,
33
+ type TypeScriptEasyNetworkStubsGeneratorOutput,
34
+ } from './models.js';
35
+ import { getReferenceFactories } from './refs.js';
36
+
37
+ type Input = TypeScriptEasyNetworkStubsGeneratorInput;
38
+ type Output = TypeScriptEasyNetworkStubsGeneratorOutput;
39
+ type Config = TypeScriptEasyNetworkStubsGeneratorConfig;
40
+ type ServiceOutput = TypeScriptEasyNetworkStubGeneratorOutput;
41
+ type Context = TypeScriptEasyNetworkStubsGeneratorContext;
42
+
43
+ export class TypeScriptEasyNetworkStubsGenerator extends OpenApiServicesGenerationProviderBase<
44
+ Input,
45
+ Output,
46
+ Config,
47
+ ServiceOutput,
48
+ Context
49
+ > {
50
+ private readonly _generatorFactory: Factory<TypeScriptEasyNetworkStubGenerator, []>;
51
+
52
+ constructor(generatorFactory?: Factory<TypeScriptEasyNetworkStubGenerator, []>) {
53
+ super();
54
+ this._generatorFactory = generatorFactory ?? Factory.fromValue(new DefaultTypeScriptEasyNetworkStubGenerator());
55
+ }
56
+
57
+ protected override initResult(): Output {
58
+ return {
59
+ typescript: {
60
+ stubs: {},
61
+ indexFiles: { stubs: undefined },
62
+ },
63
+ };
64
+ }
65
+
66
+ protected override buildContext(
67
+ context: OpenApiGeneratorContext<Input>,
68
+ config?: Partial<Config> | undefined,
69
+ ): Context {
70
+ const providerContext = this.getProviderContext(context, config, defaultTypeScriptEasyNetworkStubsGeneratorConfig);
71
+ return Object.assign(providerContext, {
72
+ refs: getReferenceFactories(providerContext.config),
73
+ });
74
+ }
75
+
76
+ protected override async generateAdditionalFiles(ctx: TypeScriptEasyNetworkStubsGeneratorContext): Promise<void> {
77
+ await this.generateUtilsFiles(ctx);
78
+ ctx.output.typescript.indexFiles = this.generateIndexFiles(ctx);
79
+ }
80
+
81
+ protected override generateService(ctx: Context, service: ApiService): MaybePromise<TypeScriptExportOutput> {
82
+ const clientGenerator = this._generatorFactory.create();
83
+ return clientGenerator.generate({
84
+ ...ctx,
85
+ service,
86
+ });
87
+ }
88
+
89
+ protected override addServiceResult(ctx: Context, service: ApiService, result: TypeScriptExportOutput): void {
90
+ ctx.output.typescript.stubs[service.id] = result;
91
+ }
92
+
93
+ protected async generateUtilsFiles(ctx: Context): Promise<void> {
94
+ const targetDir = resolve(ctx.config.outputDir, ctx.config.utilsDir);
95
+ await fs.ensureDir(targetDir);
96
+
97
+ await copyAssetFile('stubs/easy-network-stub/easy-network-stub.utils.ts', targetDir, 'easy-network-stub utils');
98
+ }
99
+
100
+ protected generateIndexFiles(ctx: Context): Output['typescript']['indexFiles'] {
101
+ const stubsIndexFilePath = this.getStubsIndexFilePath(ctx);
102
+
103
+ TypeScriptFileBuilder.tryGenerate({
104
+ logName: 'stubs index file',
105
+ filePath: stubsIndexFilePath,
106
+ options: ctx.config,
107
+ generator: (b) => b.append(this.getStubsIndexFileContent(ctx)),
108
+ });
109
+
110
+ return {
111
+ stubs: stubsIndexFilePath,
112
+ };
113
+ }
114
+
115
+ protected getStubsIndexFileContent(ctx: Context): AppendValueGroup<TypeScriptFileBuilder> {
116
+ return appendValueGroup(
117
+ [
118
+ appendValueGroup(Object.values(ctx.output.typescript.stubs).map((x) => ts.export(x.component, x.filePath))),
119
+ this.getStubsClass(ctx),
120
+ ],
121
+ '\n',
122
+ );
123
+ }
124
+
125
+ protected getStubsClass(ctx: Context): ts.Class<TypeScriptFileBuilder> {
126
+ const fieldCasing = adjustCasing(ctx.config.propertyNameCasing, { prefix: '_' });
127
+ const serviceNames = Object.fromEntries(ctx.data.services.map((x) => [x.id, x.name]));
128
+ return ts.class(this.getStubsClassName(ctx), {
129
+ export: true,
130
+ members: [
131
+ ts.property('_stubWrapper', {
132
+ accessModifier: 'private',
133
+ readonly: true,
134
+ type: ctx.refs.easyNetworkStubWrapper(),
135
+ }),
136
+ ...Object.entries(ctx.output.typescript.stubs).map(([id, x]) =>
137
+ ts.property<TypeScriptFileBuilder>(toCasing(serviceNames[id], fieldCasing), {
138
+ accessModifier: 'private',
139
+ optional: true,
140
+ type: ctx.refs.easyNetworkStubGroup([ts.reference(x.component, x.filePath), 'this']),
141
+ })
142
+ ),
143
+ ts.constructor({
144
+ parameters: [
145
+ ts.constructorParameter('stub', { type: ts.refs.easyNetworkStub.easyNetworkStub() }),
146
+ ts.constructorParameter('options', {
147
+ type: ts.refs.partial([ctx.refs.easyNetworkStubWrapperOptions()]),
148
+ optional: true,
149
+ }),
150
+ ],
151
+ body: appendValueGroup(
152
+ [s`this._stubWrapper = new ${ctx.refs.easyNetworkStubWrapper()}(stub, options);`],
153
+ '\n',
154
+ ),
155
+ }),
156
+ ts.property('requests', {
157
+ accessModifier: 'public',
158
+ type: ts.arrayType(ctx.refs.stubRequestItem(), { readonly: true }),
159
+ get: ts.property.getter({
160
+ body: appendValueGroup(['return this._stubWrapper.requests;'], '\n'),
161
+ }),
162
+ }),
163
+ ...Object.entries(ctx.output.typescript.stubs).map(([id, x]) =>
164
+ ts.property<TypeScriptFileBuilder>(toCasing(serviceNames[id], ctx.config.propertyNameCasing), {
165
+ accessModifier: 'public',
166
+ type: ctx.refs.easyNetworkStubGroup([ts.reference(x.component, x.filePath), 'this']),
167
+ get: ts.property.getter({
168
+ body: appendValueGroup(
169
+ [
170
+ s`return this.${
171
+ toCasing(
172
+ serviceNames[id],
173
+ fieldCasing,
174
+ )
175
+ } ??= ${ctx.refs.createEasyNetworkStubGroup.infer()}(this, this._stubWrapper, ${
176
+ ts.reference(
177
+ x.component,
178
+ x.filePath,
179
+ )
180
+ });`,
181
+ ],
182
+ '\n',
183
+ ),
184
+ }),
185
+ })
186
+ ),
187
+ ts.method('resetStubs', {
188
+ accessModifier: 'public',
189
+ returnType: 'this',
190
+ body: appendValueGroup(
191
+ [
192
+ ...Object.keys(ctx.output.typescript.stubs).map((id) =>
193
+ `this.${toCasing(serviceNames[id], fieldCasing)}?.reset();`
194
+ ),
195
+ 'return this;',
196
+ ],
197
+ '\n',
198
+ ),
199
+ }),
200
+ ],
201
+ });
202
+ }
203
+
204
+ protected getStubsIndexFilePath(ctx: Context): string | null {
205
+ return ctx.config.stubsIndexFile ? resolve(ctx.config.outputDir, ctx.config.stubsIndexFile) : null;
206
+ }
207
+
208
+ protected getStubsClassName(ctx: Context): string {
209
+ return toCasing(`${ctx.config.domainName ?? ''}_ApiStubs`, ctx.config.typeNameCasing);
210
+ }
211
+ }
@@ -0,0 +1,3 @@
1
+ export * from './easy-network-stub-generator.js';
2
+ export * from './easy-network-stubs-generator.js';
3
+ export * from './models.js';
@@ -0,0 +1,124 @@
1
+ import type {
2
+ ApiSchema,
3
+ ApiService,
4
+ DefaultGenerationProviderConfig,
5
+ ExtendedStringCasing,
6
+ Nullable,
7
+ OpenApiServicesGenerationProviderContext,
8
+ } from '@goast/core';
9
+
10
+ import { ts } from '../../../ast/index.js';
11
+ import type { TypeScriptExportOutput } from '../../../common-results.js';
12
+ import { defaultTypeScriptGeneratorConfig, type TypeScriptGeneratorConfig } from '../../../config.js';
13
+ import type { TypeScriptFileBuilder } from '../../../file-builder.js';
14
+ import type { TypeScriptModelGeneratorOutput } from '../../models/index.js';
15
+ import type { getReferenceFactories } from './refs.js';
16
+
17
+ export type TypeScriptEasyNetworkStubsGeneratorConfig = TypeScriptGeneratorConfig & {
18
+ /**
19
+ * The domain name of the API. Used as a prefix for exported components (e.g. `ApiStubs`).
20
+ * @default undefined
21
+ */
22
+ domainName: Nullable<string>;
23
+
24
+ /**
25
+ * The default response types for status codes that are not defined in the OpenAPI specification.
26
+ * @example
27
+ * {
28
+ * 400: schemas =>
29
+ * schemas.find(s => s.name === 'BadRequestResponse')
30
+ * ?? throwExp('BadRequestResponse not found'),
31
+ * 404: 'never',
32
+ * 500: ts.refs.any(),
33
+ * }
34
+ * @default
35
+ * {
36
+ * 401: ts.refs.never(),
37
+ * 403: ts.refs.never(),
38
+ * 500: ts.refs.never(),
39
+ * }
40
+ */
41
+ defaultStatusCodeResponseTypes: Record<
42
+ number,
43
+ // deno-lint-ignore ban-types
44
+ Exclude<ts.Type<TypeScriptFileBuilder>, Function> | ((schemas: readonly ApiSchema[]) => ApiSchema)
45
+ >;
46
+
47
+ /**
48
+ * The directory where the stubs should be saved. The path is relative to the output directory.
49
+ * @default 'stubs'
50
+ */
51
+ stubsDir: string;
52
+
53
+ /**
54
+ * The casing of the stub file names. If nullish, the `fileNameCasing` is used.
55
+ * @default { casing: 'kebab', suffix: '.stubs' }
56
+ */
57
+ stubFileNameCasing: Nullable<ExtendedStringCasing>;
58
+
59
+ /**
60
+ * The index file where all stubs should be exported. The path is relative to the output directory. If nullish, no index file will be generated.
61
+ * @default 'stubs.ts'
62
+ */
63
+ stubsIndexFile: Nullable<string>;
64
+
65
+ /**
66
+ * The directory where the utilies should be saved. The path is relative to the output directory.
67
+ * @default 'utils'
68
+ */
69
+ utilsDir: string;
70
+ };
71
+
72
+ export const defaultTypeScriptEasyNetworkStubsGeneratorConfig: DefaultGenerationProviderConfig<
73
+ TypeScriptEasyNetworkStubsGeneratorConfig
74
+ > = {
75
+ ...defaultTypeScriptGeneratorConfig,
76
+
77
+ domainName: undefined,
78
+ defaultStatusCodeResponseTypes: {
79
+ 401: ts.refs.never(),
80
+ 403: ts.refs.never(),
81
+ 500: ts.refs.never(),
82
+ },
83
+
84
+ stubsDir: 'stubs',
85
+ stubFileNameCasing: { casing: 'kebab', suffix: '.stubs' },
86
+ stubsIndexFile: 'stubs.ts',
87
+ utilsDir: 'utils',
88
+ };
89
+
90
+ export type TypeScriptEasyNetworkStubsGeneratorInput = {
91
+ typescript: {
92
+ models: {
93
+ [schemaId: string]: TypeScriptModelGeneratorOutput;
94
+ };
95
+ };
96
+ };
97
+
98
+ export type TypeScriptEasyNetworkStubsGeneratorOutput = {
99
+ typescript: {
100
+ stubs: {
101
+ [serviceId: string]: TypeScriptEasyNetworkStubGeneratorOutput;
102
+ };
103
+ indexFiles: {
104
+ stubs: Nullable<string>;
105
+ };
106
+ };
107
+ };
108
+
109
+ export type TypeScriptEasyNetworkStubGeneratorOutput = TypeScriptExportOutput;
110
+
111
+ export type TypeScriptEasyNetworkStubsGeneratorContext =
112
+ & OpenApiServicesGenerationProviderContext<
113
+ TypeScriptEasyNetworkStubsGeneratorInput,
114
+ TypeScriptEasyNetworkStubsGeneratorOutput,
115
+ TypeScriptEasyNetworkStubsGeneratorConfig,
116
+ TypeScriptEasyNetworkStubGeneratorOutput
117
+ >
118
+ & {
119
+ refs: ReturnType<typeof getReferenceFactories>;
120
+ };
121
+
122
+ export type TypeScriptEasyNetworkStubGeneratorContext = TypeScriptEasyNetworkStubsGeneratorContext & {
123
+ readonly service: ApiService;
124
+ };
@@ -0,0 +1,45 @@
1
+ import { join, resolve } from 'node:path';
2
+
3
+ import { ts } from '../../../ast/index.js';
4
+ import type { TypeScriptEasyNetworkStubsGeneratorConfig } from './models.js';
5
+
6
+ // See packages/typescript/assets/stubs/easy-network-stub for reference
7
+ export function getReferenceFactories(options: TypeScriptEasyNetworkStubsGeneratorConfig): {
8
+ easyNetworkStubWrapperOptions: ts.ModuleReferenceFactory;
9
+ stubRequestItem: ts.ModuleReferenceFactory;
10
+ stubRequestInfo: ts.GenericModuleReferenceFactory<2>;
11
+ strictRouteResponseCallback: ts.GenericModuleReferenceFactory<3>;
12
+ getStubResponder: ts.GenericModuleReferenceFactory<1>;
13
+ easyNetworkStubWrapper: ts.ModuleReferenceFactory;
14
+ easyNetworkStubBase: ts.ModuleReferenceFactory;
15
+ easyNetworkStubGroup: ts.GenericModuleReferenceFactory<2>;
16
+ createEasyNetworkStubGroup: ts.GenericModuleReferenceFactory<2>;
17
+ } {
18
+ const utilsDirPath = resolve(options.outputDir, options.utilsDir);
19
+ const easyNetworkStubUtilsPath = join(utilsDirPath, 'easy-network-stub.utils.ts');
20
+
21
+ return {
22
+ // easy-network-stub.utils.ts
23
+ easyNetworkStubWrapperOptions: ts.reference.factory('EasyNetworkStubWrapperOptions', easyNetworkStubUtilsPath, {
24
+ importType: 'type-import',
25
+ }),
26
+ stubRequestItem: ts.reference.factory('StubRequestItem', easyNetworkStubUtilsPath, { importType: 'type-import' }),
27
+ stubRequestInfo: ts.reference.genericFactory<2>('StubRequestInfo', easyNetworkStubUtilsPath, {
28
+ importType: 'type-import',
29
+ }),
30
+ strictRouteResponseCallback: ts.reference.genericFactory<3>(
31
+ 'StrictRouteResponseCallback',
32
+ easyNetworkStubUtilsPath,
33
+ {
34
+ importType: 'type-import',
35
+ },
36
+ ),
37
+ getStubResponder: ts.reference.genericFactory<1>('getStubResponder', easyNetworkStubUtilsPath),
38
+ easyNetworkStubWrapper: ts.reference.factory('EasyNetworkStubWrapper', easyNetworkStubUtilsPath),
39
+ easyNetworkStubBase: ts.reference.factory('EasyNetworkStubBase', easyNetworkStubUtilsPath),
40
+ easyNetworkStubGroup: ts.reference.genericFactory<2>('EasyNetworkStubGroup', easyNetworkStubUtilsPath, {
41
+ importType: 'type-import',
42
+ }),
43
+ createEasyNetworkStubGroup: ts.reference.genericFactory<2>('createEasyNetworkStubGroup', easyNetworkStubUtilsPath),
44
+ };
45
+ }
@@ -0,0 +1,267 @@
1
+ import { resolve } from 'node:path';
2
+
3
+ import {
4
+ type ApiEndpoint,
5
+ type ApiSchema,
6
+ type AppendValueGroup,
7
+ appendValueGroup,
8
+ builderTemplate as s,
9
+ type MaybePromise,
10
+ toCasing,
11
+ } from '@goast/core';
12
+
13
+ import { ts } from '../../../ast/index.js';
14
+ import { TypeScriptFileBuilder } from '../../../file-builder.js';
15
+ import { TypeScriptFileGenerator } from '../../file-generator.js';
16
+ import type { TypeScriptFetchClientGeneratorContext, TypeScriptFetchClientGeneratorOutput } from './models.js';
17
+
18
+ type Context = TypeScriptFetchClientGeneratorContext;
19
+ type Output = TypeScriptFetchClientGeneratorOutput;
20
+ type Builder = TypeScriptFileBuilder;
21
+
22
+ export interface TypeScriptFetchClientGenerator<TOutput extends Output = Output> {
23
+ generate(ctx: Context): MaybePromise<TOutput>;
24
+ }
25
+
26
+ export class DefaultTypeScriptFetchClientGenerator extends TypeScriptFileGenerator<Context, Output>
27
+ implements TypeScriptFetchClientGenerator {
28
+ public generate(ctx: Context): MaybePromise<Output> {
29
+ const result: Output = {};
30
+
31
+ if (this.shouldGenerateInterface(ctx)) {
32
+ const filePath = this.getInterfaceFilePath(ctx);
33
+ const name = this.getInterfaceName(ctx);
34
+
35
+ TypeScriptFileBuilder.generate({
36
+ logName: `interface ${name}`,
37
+ filePath,
38
+ options: ctx.config,
39
+ generator: (b) => b.append(this.getInterfaceFileContent(ctx)),
40
+ });
41
+
42
+ result.clientInterface = { filePath, component: name };
43
+ }
44
+
45
+ if (this.shouldGenerateClass(ctx)) {
46
+ const filePath = this.getClassFilePath(ctx);
47
+ const name = this.getClassName(ctx);
48
+
49
+ TypeScriptFileBuilder.generate({
50
+ logName: `class ${name}`,
51
+ filePath,
52
+ options: ctx.config,
53
+ generator: (b) => b.append(this.getClassFileContent(ctx)),
54
+ });
55
+
56
+ result.client = { filePath, component: name };
57
+ }
58
+
59
+ return result;
60
+ }
61
+
62
+ // #region Interface
63
+ protected getInterfaceFileContent(ctx: Context): AppendValueGroup<Builder> {
64
+ return appendValueGroup([this.getInterface(ctx)], '\n');
65
+ }
66
+
67
+ protected getInterface(ctx: Context): ts.Interface<Builder> {
68
+ return ts.interface(this.getInterfaceName(ctx), {
69
+ doc: ts.doc({
70
+ description: ctx.service.description,
71
+ tags: [
72
+ ctx.service.endpoints.length === 0 || ctx.service.endpoints.some((x) => !x.deprecated)
73
+ ? null
74
+ : ts.docTag('deprecated'),
75
+ ],
76
+ }),
77
+ export: true,
78
+ members: ctx.service.endpoints.map((endpoint) => this.getInterfaceEndpointMethod(ctx, endpoint)),
79
+ });
80
+ }
81
+
82
+ protected getInterfaceEndpointMethod(ctx: Context, endpoint: ApiEndpoint): ts.Method<Builder> {
83
+ const params = endpoint.parameters.filter((x) => x.target === 'path' || x.target === 'query');
84
+ const bodySchema = endpoint.requestBody?.content[0]?.schema;
85
+ const responseSchema = this.getResponseSchema(ctx, endpoint);
86
+ return ts.method(toCasing(endpoint.name, ctx.config.functionNameCasing), {
87
+ doc: ts.doc({ description: endpoint.description, tags: [endpoint.deprecated ? ts.docTag('deprecated') : null] }),
88
+ parameters: [
89
+ params.length > 0
90
+ ? ts.parameter('params', {
91
+ description: 'Parameters for the endpoint.',
92
+ type: ts.objectType({
93
+ members: params.map((x) =>
94
+ ts.property(toCasing(x.name, ctx.config.propertyNameCasing), {
95
+ doc: ts.doc({ tags: [x.deprecated ? ts.docTag('deprecated') : null] }),
96
+ type: this.getSchemaType(ctx, x.schema),
97
+ optional: !x.required,
98
+ })
99
+ ),
100
+ }),
101
+ })
102
+ : null,
103
+ bodySchema &&
104
+ ts.parameter('body', {
105
+ description: 'Body for the endpoint.',
106
+ type: this.getSchemaType(ctx, bodySchema),
107
+ }),
108
+ ],
109
+ returnType: ts.refs.promise([ctx.refs.typedResponse([this.getSchemaType(ctx, responseSchema, ts.refs.void_())])]),
110
+ });
111
+ }
112
+ // #endregion
113
+
114
+ // #region Class
115
+ protected getClassFileContent(ctx: Context): AppendValueGroup<Builder> {
116
+ return appendValueGroup([this.getDefaultOptionsConstant(ctx), this.getClass(ctx)], '\n');
117
+ }
118
+
119
+ protected getDefaultOptionsConstant(ctx: Context): ts.Variable<Builder> {
120
+ const baseUrl = ctx.service.endpoints.map((x) => x.$src?.document.servers?.find((x) => x.url)?.url).find((x) =>
121
+ !!x
122
+ );
123
+ return ts.variable(this.getDefaultOptionsConstantName(ctx), {
124
+ export: true,
125
+ readonly: true,
126
+ type: ctx.refs.fetchClientOptions(),
127
+ value: ts.object({
128
+ members: [baseUrl && ts.property('baseUrl', { value: ts.string(baseUrl) })],
129
+ }),
130
+ });
131
+ }
132
+
133
+ protected getClass(ctx: Context): ts.Class<Builder> {
134
+ return ts.class(this.getClassName(ctx), {
135
+ doc: ts.doc({
136
+ description: ctx.service.description,
137
+ tags: [
138
+ ctx.service.endpoints.length === 0 || ctx.service.endpoints.some((x) => !x.deprecated)
139
+ ? null
140
+ : ts.docTag('deprecated'),
141
+ ],
142
+ }),
143
+ export: true,
144
+ implements: this.shouldGenerateInterface(ctx)
145
+ ? [ts.reference(this.getInterfaceName(ctx), this.getInterfaceFilePath(ctx))]
146
+ : undefined,
147
+ members: [
148
+ ts.property('options', {
149
+ doc: ts.doc({ description: 'Options for the fetch client.' }),
150
+ accessModifier: 'public',
151
+ type: ctx.refs.fetchClientOptions(),
152
+ }),
153
+ ts.constructor({
154
+ parameters: [
155
+ ts.constructorParameter('options', {
156
+ type: ts.refs.partial([ctx.refs.fetchClientOptions()]),
157
+ optional: true,
158
+ }),
159
+ ],
160
+ body: appendValueGroup(
161
+ [s`this.options = { ...${this.getDefaultOptionsConstantName(ctx)}, ...options };`],
162
+ '\n',
163
+ ),
164
+ }),
165
+ ...ctx.service.endpoints.map((endpoint) => this.getServiceMethod(ctx, endpoint)),
166
+ ],
167
+ });
168
+ }
169
+
170
+ protected getServiceMethod(ctx: Context, endpoint: ApiEndpoint): ts.Method<Builder> {
171
+ const method = this.getInterfaceEndpointMethod(ctx, endpoint);
172
+ method.accessModifier = 'public';
173
+ method.body = appendValueGroup(
174
+ [
175
+ s`const url = new ${ctx.refs.urlBuilder()}(this.options.baseUrl)${s.indent`
176
+ .withPath(${ts.string(endpoint.path)})${(b) =>
177
+ b.forEach(endpoint.parameters, (b, p) => {
178
+ switch (p.target) {
179
+ case 'path':
180
+ b.append(
181
+ s<Builder>`\n.withPathParam(${ts.string(p.name)}, params.${
182
+ toCasing(p.name, ctx.config.paramNameCasing)
183
+ })`,
184
+ );
185
+ break;
186
+ case 'query':
187
+ b.append(
188
+ s<Builder>`\n.withQueryParam(${ts.string(p.name)}, params.${
189
+ toCasing(p.name, ctx.config.paramNameCasing)
190
+ })`,
191
+ );
192
+ break;
193
+ }
194
+ })}
195
+ .build();`}`,
196
+ s`const response = (this.options.fetch ?? fetch)(url, ${
197
+ ts.object({
198
+ members: [
199
+ ts.property('method', { value: ts.string(toCasing(endpoint.method, 'all-upper')) }),
200
+ ts.property('headers', { value: 'this.options.headers' }),
201
+ endpoint.requestBody?.content[0]?.schema ? ts.property('body', { value: 'JSON.stringify(body)' }) : null,
202
+ ],
203
+ })
204
+ });`,
205
+ s`Object.defineProperty(response, 'isVoidResponse', { value: ${
206
+ this.getResponseSchema(ctx, endpoint) ? 'false' : 'true'
207
+ } });`,
208
+ s`return response as unknown as ${method.returnType ?? 'unknown'};`,
209
+ ],
210
+ '\n',
211
+ );
212
+ return method;
213
+ }
214
+ // #endregion
215
+
216
+ protected getSchemaType(ctx: Context, schema: ApiSchema | undefined, fallback?: ts.Type<Builder>): ts.Type<Builder> {
217
+ const output = schema && ctx.input.typescript.models[schema.id];
218
+ if (!output) return fallback ?? this.getAnyType(ctx);
219
+ return (b) => b.appendModelUsage(output);
220
+ }
221
+
222
+ protected shouldGenerateInterface(ctx: Context): boolean {
223
+ return ctx.config.clientFileKind === 'interface' || ctx.config.clientFileKind === 'class-and-interface';
224
+ }
225
+
226
+ protected shouldGenerateClass(ctx: Context): boolean {
227
+ return ctx.config.clientFileKind === 'class' || ctx.config.clientFileKind === 'class-and-interface';
228
+ }
229
+
230
+ protected getInterfaceName(ctx: Context): string {
231
+ return toCasing(ctx.service.name, ctx.config.clientInterfaceNameCasing ?? ctx.config.typeNameCasing);
232
+ }
233
+
234
+ protected getClassName(ctx: Context): string {
235
+ return toCasing(ctx.service.name, ctx.config.clientNameCasing ?? ctx.config.typeNameCasing);
236
+ }
237
+
238
+ protected getDefaultOptionsConstantName(ctx: Context): string {
239
+ return toCasing(this.getClassName(ctx) + '-default-options', ctx.config.constantNameCasing);
240
+ }
241
+
242
+ protected getInterfaceFilePath(ctx: Context): string {
243
+ return resolve(
244
+ ctx.config.outputDir,
245
+ ctx.config.clientInterfaceDir ?? ctx.config.clientDir,
246
+ `${toCasing(ctx.service.name, ctx.config.clientInterfaceFileNameCasing ?? ctx.config.fileNameCasing)}.ts`,
247
+ );
248
+ }
249
+
250
+ protected getClassFilePath(ctx: Context): string {
251
+ return resolve(
252
+ ctx.config.outputDir,
253
+ ctx.config.clientDir,
254
+ `${toCasing(ctx.service.name, ctx.config.clientFileNameCasing ?? ctx.config.fileNameCasing)}.ts`,
255
+ );
256
+ }
257
+
258
+ protected getUtilPath(ctx: Context, fileName: string): string {
259
+ return resolve(ctx.config.outputDir, ctx.config.utilsDir, fileName);
260
+ }
261
+
262
+ private getResponseSchema(_ctx: Context, endpoint: ApiEndpoint) {
263
+ const successResponse = endpoint.responses.find((x) => x.statusCode === 200) ??
264
+ endpoint.responses.find((x) => x.statusCode && x.statusCode > 200 && x.statusCode < 300);
265
+ return successResponse?.contentOptions?.find((x) => x.schema !== undefined)?.schema;
266
+ }
267
+ }