@goast/typescript 0.6.3-beta.1 → 0.7.1

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 (92) hide show
  1. package/LICENSE +21 -21
  2. package/assets/stubs/easy-network-stub/easy-network-stub.utils.ts +9 -7
  3. package/esm/src/generators/services/easy-network-stub/refs.d.ts +1 -0
  4. package/esm/src/generators/services/easy-network-stub/refs.d.ts.map +1 -1
  5. package/esm/src/generators/services/easy-network-stub/refs.js +1 -0
  6. package/package.json +2 -2
  7. package/script/src/generators/services/easy-network-stub/refs.d.ts +1 -0
  8. package/script/src/generators/services/easy-network-stub/refs.d.ts.map +1 -1
  9. package/script/src/generators/services/easy-network-stub/refs.js +1 -0
  10. package/src/mod.ts +7 -0
  11. package/src/src/assets.ts +9 -0
  12. package/src/src/ast/_index.ts +54 -0
  13. package/src/src/ast/common.ts +1 -0
  14. package/src/src/ast/index.ts +1 -0
  15. package/src/src/ast/node.ts +10 -0
  16. package/src/src/ast/nodes/argument.ts +40 -0
  17. package/src/src/ast/nodes/array-type.ts +49 -0
  18. package/src/src/ast/nodes/arrow-function.ts +91 -0
  19. package/src/src/ast/nodes/call.ts +55 -0
  20. package/src/src/ast/nodes/class.ts +133 -0
  21. package/src/src/ast/nodes/constructor-parameter.ts +70 -0
  22. package/src/src/ast/nodes/constructor.ts +77 -0
  23. package/src/src/ast/nodes/decorator.ts +76 -0
  24. package/src/src/ast/nodes/doc-tag.ts +291 -0
  25. package/src/src/ast/nodes/doc.ts +102 -0
  26. package/src/src/ast/nodes/enum-value.ts +72 -0
  27. package/src/src/ast/nodes/enum.ts +77 -0
  28. package/src/src/ast/nodes/export.ts +54 -0
  29. package/src/src/ast/nodes/function-type.ts +60 -0
  30. package/src/src/ast/nodes/function.ts +107 -0
  31. package/src/src/ast/nodes/generic-parameter.ts +71 -0
  32. package/src/src/ast/nodes/indexer.ts +60 -0
  33. package/src/src/ast/nodes/interface.ts +117 -0
  34. package/src/src/ast/nodes/intersection-type.ts +67 -0
  35. package/src/src/ast/nodes/lookup-type.ts +53 -0
  36. package/src/src/ast/nodes/method.ts +138 -0
  37. package/src/src/ast/nodes/object-type.ts +52 -0
  38. package/src/src/ast/nodes/object.ts +48 -0
  39. package/src/src/ast/nodes/parameter.ts +85 -0
  40. package/src/src/ast/nodes/property-accessor.ts +173 -0
  41. package/src/src/ast/nodes/property.ts +192 -0
  42. package/src/src/ast/nodes/reference.ts +194 -0
  43. package/src/src/ast/nodes/string.ts +49 -0
  44. package/src/src/ast/nodes/tuple.ts +53 -0
  45. package/src/src/ast/nodes/type-alias.ts +75 -0
  46. package/src/src/ast/nodes/typeof.ts +42 -0
  47. package/src/src/ast/nodes/types.ts +40 -0
  48. package/src/src/ast/nodes/union-type.ts +62 -0
  49. package/src/src/ast/nodes/variable.ts +73 -0
  50. package/src/src/ast/references/angular.ts +24 -0
  51. package/src/src/ast/references/easy-network-stub.ts +21 -0
  52. package/src/src/ast/references/index.ts +5 -0
  53. package/src/src/ast/references/k6.ts +8 -0
  54. package/src/src/ast/references/rxjs.ts +7 -0
  55. package/src/src/ast/references/typescript.ts +35 -0
  56. package/src/src/ast/utils/get-type-script-builder-options.ts +19 -0
  57. package/src/src/ast/utils/to-ts-node.ts +27 -0
  58. package/src/src/ast/utils/write-ts-generic-parameters.ts +25 -0
  59. package/src/src/ast/utils/write-ts-members.ts +28 -0
  60. package/src/src/ast/utils/write-ts-nodes.ts +35 -0
  61. package/src/src/ast/utils/write-ts-parameters.ts +25 -0
  62. package/src/src/common-results.ts +26 -0
  63. package/src/src/config.ts +89 -0
  64. package/src/src/file-builder.ts +137 -0
  65. package/src/src/generators/file-generator.ts +15 -0
  66. package/src/src/generators/index.ts +6 -0
  67. package/src/src/generators/models/index.ts +3 -0
  68. package/src/src/generators/models/model-generator.ts +481 -0
  69. package/src/src/generators/models/models-generator.ts +108 -0
  70. package/src/src/generators/models/models.ts +121 -0
  71. package/src/src/generators/services/angular-services/angular-service-generator.ts +414 -0
  72. package/src/src/generators/services/angular-services/angular-services-generator.ts +295 -0
  73. package/src/src/generators/services/angular-services/index.ts +3 -0
  74. package/src/src/generators/services/angular-services/models.ts +277 -0
  75. package/src/src/generators/services/angular-services/refs.ts +54 -0
  76. package/src/src/generators/services/easy-network-stub/easy-network-stub-generator.ts +250 -0
  77. package/src/src/generators/services/easy-network-stub/easy-network-stubs-generator.ts +211 -0
  78. package/src/src/generators/services/easy-network-stub/index.ts +3 -0
  79. package/src/src/generators/services/easy-network-stub/models.ts +124 -0
  80. package/src/src/generators/services/easy-network-stub/refs.ts +47 -0
  81. package/src/src/generators/services/fetch-clients/fetch-client-generator.ts +285 -0
  82. package/src/src/generators/services/fetch-clients/fetch-clients-generator.ts +163 -0
  83. package/src/src/generators/services/fetch-clients/index.ts +3 -0
  84. package/src/src/generators/services/fetch-clients/models.ts +130 -0
  85. package/src/src/generators/services/fetch-clients/refs.ts +21 -0
  86. package/src/src/generators/services/k6-clients/index.ts +3 -0
  87. package/src/src/generators/services/k6-clients/k6-client-generator.ts +474 -0
  88. package/src/src/generators/services/k6-clients/k6-clients-generator.ts +171 -0
  89. package/src/src/generators/services/k6-clients/models.ts +247 -0
  90. package/src/src/generators/services/k6-clients/refs.ts +16 -0
  91. package/src/src/import-collection.ts +236 -0
  92. package/src/src/utils.ts +72 -0
@@ -0,0 +1,250 @@
1
+ import { resolve } from 'node:path';
2
+
3
+ import {
4
+ adjustCasing,
5
+ type ApiEndpoint,
6
+ type ApiSchema,
7
+ type AppendValueGroup,
8
+ appendValueGroup,
9
+ builderTemplate as s,
10
+ getSourceDisplayName,
11
+ type MaybePromise,
12
+ toCasing,
13
+ } from '@goast/core';
14
+
15
+ import { ts } from '../../../ast/index.js';
16
+ import { TypeScriptFileBuilder } from '../../../file-builder.js';
17
+ import { TypeScriptFileGenerator } from '../../file-generator.js';
18
+ import type { TypeScriptEasyNetworkStubGeneratorContext, TypeScriptEasyNetworkStubGeneratorOutput } from './models.js';
19
+
20
+ type Context = TypeScriptEasyNetworkStubGeneratorContext;
21
+ type Output = TypeScriptEasyNetworkStubGeneratorOutput;
22
+ type Builder = TypeScriptFileBuilder;
23
+
24
+ export interface TypeScriptEasyNetworkStubGenerator<TOutput extends Output = Output> {
25
+ generate(ctx: Context): MaybePromise<TOutput>;
26
+ }
27
+
28
+ export class DefaultTypeScriptEasyNetworkStubGenerator extends TypeScriptFileGenerator<Context, Output>
29
+ implements TypeScriptEasyNetworkStubGenerator {
30
+ public generate(ctx: Context): MaybePromise<Output> {
31
+ const filePath = this.getStubFilePath(ctx);
32
+ const name = this.getStubClassName(ctx);
33
+
34
+ TypeScriptFileBuilder.generate({
35
+ logName: `stub ${name}`,
36
+ filePath,
37
+ options: ctx.config,
38
+ generator: (b) => {
39
+ ctx.service.endpoints.forEach((endpoint) => {
40
+ console.log(
41
+ ` ${getSourceDisplayName(ctx.data, endpoint)} [${toCasing(endpoint.name, ctx.config.functionNameCasing)}]`,
42
+ );
43
+ });
44
+ b.append(this.getStubFileContent(ctx));
45
+ },
46
+ });
47
+
48
+ return {
49
+ filePath,
50
+ component: name,
51
+ };
52
+ }
53
+
54
+ protected getStubFileContent(ctx: Context): AppendValueGroup<Builder> {
55
+ return appendValueGroup(
56
+ [...ctx.service.endpoints.map((endpoint) => this.getResponderVariable(ctx, endpoint)), this.getStubClass(ctx)],
57
+ '\n',
58
+ );
59
+ }
60
+
61
+ protected getResponderVariable(ctx: Context, endpoint: ApiEndpoint): ts.Variable<Builder> {
62
+ return ts.variable(this.getResponderVariableName(ctx, endpoint), {
63
+ readonly: true,
64
+ value: ts.call(
65
+ ctx.refs.getStubResponder([
66
+ ts.objectType({
67
+ members: Object.entries(this.getEndpointStatusCodes(ctx, endpoint)).map(([statusCode, type]) =>
68
+ ts.property<Builder>(statusCode, { type })
69
+ ),
70
+ }),
71
+ ]),
72
+ [],
73
+ ),
74
+ });
75
+ }
76
+
77
+ protected getStubClass(ctx: Context): ts.Class<Builder> {
78
+ return ts.class(this.getStubClassName(ctx), {
79
+ export: true,
80
+ extends: ctx.refs.easyNetworkStubBase(),
81
+ members: [
82
+ ...ctx.service.endpoints.map((endpoint) =>
83
+ ts.property<Builder>(this.getEndpointPathPropertyName(ctx, endpoint), {
84
+ static: true,
85
+ readonly: true,
86
+ accessModifier: 'private',
87
+ value: s`${ts.string(this.getStubRoute(ctx, endpoint))} as const`,
88
+ })
89
+ ),
90
+ '\n',
91
+ ...ctx.service.endpoints.map((endpoint) =>
92
+ ts.property<Builder>(this.getEndpointRequestsFieldName(ctx, endpoint), {
93
+ readonly: true,
94
+ accessModifier: 'private',
95
+ type: this.getEndpointRequestsType(ctx, endpoint),
96
+ value: ts.tuple([]),
97
+ })
98
+ ),
99
+ '\n',
100
+ ...ctx.service.endpoints.map((endpoint) =>
101
+ ts.property<Builder>(this.getEndpointRequestsPropertyName(ctx, endpoint), {
102
+ readonly: true,
103
+ accessModifier: 'public',
104
+ type: this.getEndpointRequestsType(ctx, endpoint, { readonly: true }),
105
+ get: ts.property.getter({
106
+ body: appendValueGroup([`return this.${this.getEndpointRequestsFieldName(ctx, endpoint)};`], '\n'),
107
+ }),
108
+ })
109
+ ),
110
+ ...ctx.service.endpoints.map((endpoint) => this.getEndpointStubMethod(ctx, endpoint)),
111
+ ts.method('reset', {
112
+ accessModifier: 'public',
113
+ override: true,
114
+ returnType: ts.refs.void_(),
115
+ body: appendValueGroup(
116
+ [
117
+ ...ctx.service.endpoints.map((endpoint) =>
118
+ `this.${this.getEndpointRequestsFieldName(ctx, endpoint)}.length = 0;`
119
+ ),
120
+ 'super.reset();',
121
+ ],
122
+ '\n',
123
+ ),
124
+ }),
125
+ ],
126
+ });
127
+ }
128
+
129
+ protected getEndpointRequestsType(
130
+ ctx: Context,
131
+ endpoint: ApiEndpoint,
132
+ options?: { readonly?: boolean },
133
+ ): ts.Type<Builder> {
134
+ return ts.arrayType(
135
+ ctx.refs.stubRequestInfo([
136
+ ts.typeof(ts.call([this.getStubClassName(ctx), this.getEndpointPathPropertyName(ctx, endpoint)])),
137
+ this.getSchemaType(ctx, endpoint.requestBody?.content[0].schema),
138
+ ]),
139
+ options,
140
+ );
141
+ }
142
+
143
+ protected getEndpointStubMethod(ctx: Context, endpoint: ApiEndpoint): ts.Method<Builder> {
144
+ const requestType = this.getSchemaType(ctx, endpoint.requestBody?.content[0].schema);
145
+ return ts.method(this.getEndpointStubMethodName(ctx, endpoint), {
146
+ accessModifier: 'public',
147
+ parameters: [
148
+ ts.parameter('response', {
149
+ type: ctx.refs.strictRouteResponseCallback([
150
+ requestType,
151
+ ts.typeof(ts.call([this.getStubClassName(ctx), this.getEndpointPathPropertyName(ctx, endpoint)])),
152
+ ts.typeof(this.getResponderVariableName(ctx, endpoint)),
153
+ ]),
154
+ }),
155
+ ],
156
+ returnType: 'this',
157
+ body: appendValueGroup(
158
+ [
159
+ s`this.stubWrapper.stub2<${requestType}>()(${s.indent`
160
+ ${ts.string(endpoint.method.toUpperCase())},
161
+ ${this.getStubClassName(ctx)}.${this.getEndpointPathPropertyName(ctx, endpoint)},
162
+ async (request) => {${s.indent`
163
+ if (this.stubWrapper.options.rememberRequests) {${s.indent`
164
+ this.${this.getEndpointRequestsFieldName(ctx, endpoint)}.push(request);`}
165
+ }
166
+ throw await response(${this.getResponderVariableName(ctx, endpoint)}, request);`}
167
+ }`}
168
+ );`,
169
+ 'return this;',
170
+ ],
171
+ '\n',
172
+ ),
173
+ });
174
+ }
175
+
176
+ protected getStubFilePath(ctx: Context): string {
177
+ return resolve(
178
+ ctx.config.outputDir,
179
+ ctx.config.stubsDir,
180
+ `${toCasing(ctx.service.name, ctx.config.stubFileNameCasing ?? ctx.config.fileNameCasing)}.ts`,
181
+ );
182
+ }
183
+
184
+ protected getResponderVariableName(ctx: Context, endpoint: ApiEndpoint): string {
185
+ return toCasing(endpoint.name + '_Responder', ctx.config.propertyNameCasing);
186
+ }
187
+
188
+ protected getStubClassName(ctx: Context): string {
189
+ return toCasing(ctx.service.name + '_Stubs', ctx.config.typeNameCasing);
190
+ }
191
+
192
+ protected getEndpointPathPropertyName(ctx: Context, endpoint: ApiEndpoint): string {
193
+ return toCasing(endpoint.name + '_Path', ctx.config.constantNameCasing);
194
+ }
195
+
196
+ protected getEndpointRequestsFieldName(ctx: Context, endpoint: ApiEndpoint): string {
197
+ return toCasing(endpoint.name + '_Requests', adjustCasing(ctx.config.propertyNameCasing, { prefix: '_' }));
198
+ }
199
+
200
+ protected getEndpointRequestsPropertyName(ctx: Context, endpoint: ApiEndpoint): string {
201
+ return toCasing(endpoint.name + '_Requests', ctx.config.propertyNameCasing);
202
+ }
203
+
204
+ protected getEndpointStubMethodName(ctx: Context, endpoint: ApiEndpoint): string {
205
+ return toCasing('stub_' + endpoint.name, ctx.config.functionNameCasing);
206
+ }
207
+
208
+ protected getStubRoute(ctx: Context, endpoint: ApiEndpoint): string {
209
+ let path = endpoint.path;
210
+ let isFirstQueryParam = true;
211
+ for (const param of endpoint.parameters) {
212
+ let type = ((param.schema && ctx.input.typescript.models[param.schema.id]?.component) ?? ts.refs.unknown.name)
213
+ .replace(
214
+ /^readonly /,
215
+ '',
216
+ );
217
+
218
+ const arrayMatch = /^\((.*)\)\[\]$/.exec(type);
219
+ if (arrayMatch !== null) {
220
+ type = `${arrayMatch[1]}[]`;
221
+ }
222
+
223
+ if (param.target === 'path') {
224
+ path = path.replace(`{${param.name}}`, `{${param.name}${param.required ? '' : '?'}:${type}}`);
225
+ } else if (param.target === 'query') {
226
+ path = path + (isFirstQueryParam ? '?' : '&') + `{${param.name}${param.required ? '' : '?'}:${type}}`;
227
+ isFirstQueryParam = false;
228
+ }
229
+ }
230
+ return path.replace(/^\/+/, '');
231
+ }
232
+
233
+ protected getEndpointStatusCodes(ctx: Context, endpoint: ApiEndpoint): Record<number, ts.Type<Builder>> {
234
+ return Object.fromEntries([
235
+ ...Object.entries(ctx.config.defaultStatusCodeResponseTypes).map(([key, value]) => [
236
+ key,
237
+ typeof value === 'function' ? this.getSchemaType(ctx, value(ctx.data.schemas)) : value,
238
+ ]),
239
+ ...endpoint.responses
240
+ .filter((x) => x.statusCode)
241
+ .map((x) => [x.statusCode, this.getSchemaType(ctx, x.contentOptions[0]?.schema, ts.refs.never())]),
242
+ ]);
243
+ }
244
+
245
+ protected getSchemaType(ctx: Context, schema: ApiSchema | undefined, fallback?: ts.Type<Builder>): ts.Type<Builder> {
246
+ const output = schema && ctx.input.typescript.models[schema.id];
247
+ if (!output) return fallback ?? this.getAnyType(ctx);
248
+ return (b) => b.appendModelUsage(output);
249
+ }
250
+ }
@@ -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,47 @@
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
+ stubHandle: ts.ModuleReferenceFactory;
18
+ } {
19
+ const utilsDirPath = resolve(options.outputDir, options.utilsDir);
20
+ const easyNetworkStubUtilsPath = join(utilsDirPath, 'easy-network-stub.utils.ts');
21
+
22
+ return {
23
+ // easy-network-stub.utils.ts
24
+ easyNetworkStubWrapperOptions: ts.reference.factory('EasyNetworkStubWrapperOptions', easyNetworkStubUtilsPath, {
25
+ importType: 'type-import',
26
+ }),
27
+ stubRequestItem: ts.reference.factory('StubRequestItem', easyNetworkStubUtilsPath, { importType: 'type-import' }),
28
+ stubRequestInfo: ts.reference.genericFactory<2>('StubRequestInfo', easyNetworkStubUtilsPath, {
29
+ importType: 'type-import',
30
+ }),
31
+ strictRouteResponseCallback: ts.reference.genericFactory<3>(
32
+ 'StrictRouteResponseCallback',
33
+ easyNetworkStubUtilsPath,
34
+ {
35
+ importType: 'type-import',
36
+ },
37
+ ),
38
+ getStubResponder: ts.reference.genericFactory<1>('getStubResponder', easyNetworkStubUtilsPath),
39
+ easyNetworkStubWrapper: ts.reference.factory('EasyNetworkStubWrapper', easyNetworkStubUtilsPath),
40
+ easyNetworkStubBase: ts.reference.factory('EasyNetworkStubBase', easyNetworkStubUtilsPath),
41
+ easyNetworkStubGroup: ts.reference.genericFactory<2>('EasyNetworkStubGroup', easyNetworkStubUtilsPath, {
42
+ importType: 'type-import',
43
+ }),
44
+ createEasyNetworkStubGroup: ts.reference.genericFactory<2>('createEasyNetworkStubGroup', easyNetworkStubUtilsPath),
45
+ stubHandle: ts.reference.factory('StubHandle', 'easy-network-stub', { importType: 'type-import' }),
46
+ };
47
+ }