forked from orval-labs/orval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-resource.ts
More file actions
1707 lines (1552 loc) · 52.4 KB
/
Copy pathhttp-resource.ts
File metadata and controls
1707 lines (1552 loc) · 52.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
buildAngularParamsFilterExpression,
type ClientBuilder,
type ClientDependenciesBuilder,
type ClientExtraFilesBuilder,
type ClientFooterBuilder,
type ClientHeaderBuilder,
type ContextSpec,
conventionName,
escapeRegExp,
generateDependencyImports,
generateFormDataAndUrlEncodedFunction,
generateMutatorImports,
type GeneratorDependency,
type GeneratorImport,
type GeneratorVerbOptions,
getAngularFilteredParamsHelperBody,
getFileInfo,
getFullRoute,
GetterPropType,
getOperationTagKey,
getTagKey,
isObject,
isSyntheticDefaultImportsAllow,
jsDoc,
makeRouteSafe,
type NormalizedOutputOptions,
type OpenApiInfoObject,
OutputMode,
pascal,
type ResReqTypesValue,
toObjectString,
upath,
getImportExtension,
} from '@orval/core';
import {
ANGULAR_HTTP_CLIENT_DEPENDENCIES,
ANGULAR_HTTP_RESOURCE_DEPENDENCIES,
} from './constants';
import {
buildAcceptHelpers,
generateHttpClientImplementation,
getAcceptHelperName,
getHttpClientReturnTypes,
getUniqueContentTypes,
type HttpClientGeneratorContext,
resetHttpClientReturnTypes,
} from './http-client';
import {
buildServiceClassOpen,
type ClientOverride,
createReturnTypesRegistry,
createRouteRegistry,
getDefaultSuccessType,
getRelevantVerbOptionsForTag,
getSchemaOutputTypeRef,
isMutationVerb,
isPrimitiveType,
isRetrievalVerb,
isZodSchemaOutput,
} from './utils';
/**
* Reads the per-operation angular client override from the orval config.
*
* Mirrors the pattern used by `@orval/query` for `operationQueryOptions`:
* ```ts
* override: {
* operations: {
* myPostSearch: { angular: { retrievalClient: 'httpResource' } },
* }
* }
* ```
*/
interface AngularOperationOverride {
readonly client?: ClientOverride;
readonly httpResource?: AngularHttpResourceOptionsConfig;
}
interface AngularHttpResourceOptionsConfig {
defaultValue?: unknown;
debugName?: string;
injector?: string;
equal?: string;
}
const isAngularHttpResourceOptions = (
value: unknown,
): value is AngularHttpResourceOptionsConfig =>
value === undefined ||
(isObject(value) &&
(value.defaultValue === undefined ||
typeof value.defaultValue === 'string' ||
typeof value.defaultValue === 'number' ||
typeof value.defaultValue === 'boolean' ||
value.defaultValue === null ||
Array.isArray(value.defaultValue) ||
isObject(value.defaultValue)) &&
(value.debugName === undefined || typeof value.debugName === 'string') &&
(value.injector === undefined || typeof value.injector === 'string') &&
(value.equal === undefined || typeof value.equal === 'string'));
const isAngularOperationOverride = (
value: unknown,
): value is AngularOperationOverride =>
value !== undefined &&
typeof value === 'object' &&
value !== null &&
(!('client' in value) ||
value.client === 'httpClient' ||
value.client === 'httpResource' ||
value.client === 'both') &&
(!('httpResource' in value) ||
isAngularHttpResourceOptions(value.httpResource));
const getClientOverride = (
verbOption: GeneratorVerbOptions,
): ClientOverride | undefined => {
const angular =
verbOption.override.operations[verbOption.operationId]?.angular;
return isAngularOperationOverride(angular) ? angular.client : undefined;
};
/**
* Resolves the effective `httpResource` option override for an operation.
*
* Operation-level configuration takes precedence over the global
* `override.angular.httpResource` block while still inheriting unspecified
* values from the global configuration.
*
* @returns The merged resource options for the operation, or `undefined` when no override exists.
*/
const getHttpResourceOverride = (
verbOption: GeneratorVerbOptions,
output: NormalizedOutputOptions,
): AngularHttpResourceOptionsConfig | undefined => {
const operationAngular =
verbOption.override.operations[verbOption.operationId]?.angular;
const operationOverride = isAngularOperationOverride(operationAngular)
? operationAngular.httpResource
: undefined;
const angularOverride = output.override.angular as unknown;
const globalOverride =
isObject(angularOverride) &&
'httpResource' in angularOverride &&
isAngularHttpResourceOptions(angularOverride.httpResource)
? angularOverride.httpResource
: undefined;
if (globalOverride === undefined) return operationOverride;
if (operationOverride === undefined) return globalOverride;
return {
...globalOverride,
...operationOverride,
};
};
// NOTE: Module-level singletons — reset() is called by the header builder
// (generateAngularHttpResourceHeader) at the start of each generation pass.
const resourceReturnTypesRegistry = createReturnTypesRegistry();
/** @internal Exported for testing only */
export const routeRegistry = createRouteRegistry();
const getVerbOptionsRecord = (
verbOptions: readonly GeneratorVerbOptions[],
): Record<string, GeneratorVerbOptions> =>
Object.fromEntries(
verbOptions.map((verbOption) => [verbOption.operationId, verbOption]),
);
const getPrimaryTag = (verbOption: GeneratorVerbOptions): string =>
getOperationTagKey(verbOption);
const hasRetrievalOperations = (
verbOptions: Record<string, GeneratorVerbOptions>,
): boolean =>
Object.values(verbOptions).some((verbOption) =>
isRetrievalVerb(
verbOption.verb,
verbOption.operationName,
getClientOverride(verbOption),
),
);
const getHeader = (
option: false | ((info: OpenApiInfoObject) => string | string[]),
info: OpenApiInfoObject | undefined,
): string => {
if (!option || !info) {
return '';
}
const header = option(info);
return Array.isArray(header) ? jsDoc({ description: header }) : header;
};
const mergeDependencies = (
deps: GeneratorDependency[],
): GeneratorDependency[] => {
const merged = new Map<
string,
{ exports: GeneratorImport[]; dependency: string }
>();
for (const dep of deps) {
const existing = merged.get(dep.dependency);
if (!existing) {
merged.set(dep.dependency, {
exports: [...dep.exports],
dependency: dep.dependency,
});
continue;
}
for (const exp of dep.exports) {
if (
!existing.exports.some(
(current) => current.name === exp.name && current.alias === exp.alias,
)
) {
existing.exports.push(exp);
}
}
}
return [...merged.values()];
};
const cloneDependencies = (
deps: readonly GeneratorDependency[],
): GeneratorDependency[] =>
deps.map((dep) => ({
...dep,
exports: [...dep.exports],
}));
/**
* Returns the merged dependency list required when Angular `httpResource`
* output coexists with Angular `HttpClient` service generation.
*
* This is used for pure `httpResource` mode as well as mixed generation paths
* that still need Angular common HTTP symbols and service helpers.
*
* @returns The de-duplicated dependency descriptors for Angular resource generation.
*/
export const getAngularHttpResourceDependencies: ClientDependenciesBuilder =
() =>
mergeDependencies([
...ANGULAR_HTTP_CLIENT_DEPENDENCIES,
...ANGULAR_HTTP_RESOURCE_DEPENDENCIES,
]);
/**
* Returns only the dependencies required by standalone generated resource
* files, such as the sibling `*.resource.ts` output used in `both` mode.
*
* @returns The dependency descriptors required by resource-only files.
*/
export const getAngularHttpResourceOnlyDependencies: ClientDependenciesBuilder =
() => cloneDependencies(ANGULAR_HTTP_RESOURCE_DEPENDENCIES);
const isResponseText = (
contentType: string | undefined,
dataType: string,
): boolean => {
if (dataType === 'string') return true;
if (!contentType) return false;
return contentType.startsWith('text/') || contentType.includes('xml');
};
const isResponseArrayBuffer = (contentType: string | undefined): boolean => {
if (!contentType) return false;
return (
contentType.includes('application/octet-stream') ||
contentType.includes('application/pdf')
);
};
const isResponseBlob = (
contentType: string | undefined,
isBlob: boolean,
): boolean => {
if (isBlob) return true;
if (!contentType) return false;
return contentType.startsWith('image/') || contentType.includes('blob');
};
type HttpResourceFactoryName =
| 'httpResource'
| 'httpResource.text'
| 'httpResource.arrayBuffer'
| 'httpResource.blob';
const HTTP_RESOURCE_OPTIONS_TYPE_NAME = 'OrvalHttpResourceOptions';
const getHttpResourceFactory = (
response: { readonly isBlob: boolean },
contentType: string | undefined,
dataType: string,
): HttpResourceFactoryName => {
if (isResponseText(contentType, dataType)) return 'httpResource.text';
if (isResponseBlob(contentType, response.isBlob)) return 'httpResource.blob';
if (isResponseArrayBuffer(contentType)) return 'httpResource.arrayBuffer';
return 'httpResource';
};
const getHttpResourceRawType = (factory: HttpResourceFactoryName): string => {
switch (factory) {
case 'httpResource.text': {
return 'string';
}
case 'httpResource.arrayBuffer': {
return 'ArrayBuffer';
}
case 'httpResource.blob': {
return 'Blob';
}
default: {
return 'unknown';
}
}
};
const getTypeWithoutDefault = (definition: string): string => {
const match = /^([^:]+):\s*(.+)$/.exec(definition);
if (!match) return definition;
return match[2].replace(/\s*=\s*.*$/, '').trim();
};
const getDefaultValueFromImplementation = (
implementation: string,
): string | undefined => {
const match = /=\s*(.+)$/.exec(implementation);
return match ? match[1].trim() : undefined;
};
interface SignalProp {
readonly definition: string;
readonly implementation: string;
}
const withSignal = (
prop: GeneratorVerbOptions['props'][number],
options: { readonly hasDefault?: boolean } = {},
): SignalProp => {
const type = getTypeWithoutDefault(prop.definition);
// `prop.default` is `unknown`: for QUERY_PARAM/BODY/HEADER props (the only
// ones that reach this fallback — PARAM always supplies `options.hasDefault`
// explicitly) core always sets it to the sentinel `false`, never a real
// default value, so checking `!== undefined` is always (wrongly) true.
// Guard against the boolean sentinel so only a genuine default value counts.
const derivedDefault =
getDefaultValueFromImplementation(prop.implementation) !== undefined ||
(typeof prop.default !== 'boolean' && prop.default !== undefined);
const hasDefault = options.hasDefault ?? derivedDefault;
const nameMatch = /^([^:]+):/.exec(prop.definition);
const namePart = nameMatch ? nameMatch[1] : prop.name;
const hasOptionalMark = namePart.includes('?');
const optional = prop.required && !hasDefault && !hasOptionalMark ? '' : '?';
const definition = `${prop.name}${optional}: Signal<${type}>`;
return {
definition,
implementation: definition,
};
};
const buildSignalProps = (
props: GeneratorVerbOptions['props'],
params: GeneratorVerbOptions['params'],
): GeneratorVerbOptions['props'] => {
const paramDefaults = new Map<string, boolean>();
for (const param of params) {
const hasDefault =
getDefaultValueFromImplementation(param.implementation) !== undefined ||
param.default !== undefined;
paramDefaults.set(param.name, hasDefault);
}
return props.map((prop) => {
switch (prop.type) {
case GetterPropType.NAMED_PATH_PARAMS: {
return {
...prop,
name: 'pathParams',
definition: `pathParams: Signal<${prop.schema.name}>`,
implementation: `pathParams: Signal<${prop.schema.name}>`,
};
}
case GetterPropType.PARAM:
case GetterPropType.QUERY_PARAM:
case GetterPropType.BODY:
case GetterPropType.HEADER: {
const hasDefault =
prop.type === GetterPropType.PARAM
? (paramDefaults.get(prop.name) ?? false)
: undefined;
const signalProp = withSignal(prop, { hasDefault });
return {
...prop,
definition: signalProp.definition,
implementation: signalProp.implementation,
};
}
default: {
return prop;
}
}
});
};
const applySignalRoute = (
route: string,
params: GeneratorVerbOptions['params'],
useNamedParams: boolean,
): string => {
let updatedRoute = route;
for (const param of params) {
const template = '${' + param.name + '}';
const defaultValue = getDefaultValueFromImplementation(
param.implementation,
);
let replacement: string;
if (useNamedParams) {
replacement =
defaultValue === undefined
? '${pathParams().' + param.name + '}'
: '${pathParams()?.' + param.name + ' ?? ' + defaultValue + '}';
} else {
replacement =
defaultValue === undefined
? '${' + param.name + '()}'
: '${' + param.name + '?.() ?? ' + defaultValue + '}';
}
updatedRoute = updatedRoute.replaceAll(template, replacement);
}
return updatedRoute;
};
interface ResourceRequest {
readonly bodyForm: string;
readonly request: string;
readonly isUrlOnly: boolean;
readonly bodyGuard?: string;
}
const buildResourceRequest = (
{
verb,
body,
headers,
queryParams,
paramsSerializer,
paramsFilter,
override,
formData,
formUrlEncoded,
}: GeneratorVerbOptions,
route: string,
{ supportsIdleGuard }: { readonly supportsIdleGuard: boolean },
): ResourceRequest => {
const isFormData = !override.formData.disabled;
const isFormUrlEncoded = override.formUrlEncoded !== false;
const bodyForm = generateFormDataAndUrlEncodedFunction({
formData,
formUrlEncoded,
body,
isFormData,
isFormUrlEncoded,
});
const hasFormData = isFormData && body.formData;
const hasFormUrlEncoded = isFormUrlEncoded && body.formUrlEncoded;
// An optional request body is exposed as an optional `Signal` parameter. When
// the caller omits it, the `httpResource` request factory must return
// `undefined` so the resource stays idle, rather than firing a request with an
// undefined body. This mirrors Angular's `undefined`-request contract (#3700).
//
// The guard is only emitted where the request is built lazily inside the
// factory (single response content-type). The multi-content path builds the
// request eagerly at the function-body level, where returning `undefined`
// would violate the function's `HttpResourceRef` return type — there we keep
// the optional-call (`?.()`) form, which is already runtime-safe.
const isDirectBody = !!body.definition && !hasFormData && !hasFormUrlEncoded;
const bodyGuard =
supportsIdleGuard && isDirectBody && body.isOptional
? `if (!${body.implementation}) return undefined;`
: undefined;
const bodyAccess = body.definition
? body.isOptional && !bodyGuard
? `${body.implementation}?.()`
: `${body.implementation}()`
: undefined;
const bodyValue = hasFormData
? 'formData'
: hasFormUrlEncoded
? 'formUrlEncoded'
: bodyAccess;
const paramsAccess = queryParams ? 'params?.()' : undefined;
const headersAccess = headers ? 'headers?.()' : undefined;
const filteredParamsValue = paramsAccess
? buildAngularParamsFilterExpression({
paramsExpression: `${paramsAccess} ?? {}`,
requiredNullableParamKeys: queryParams?.requiredNullableKeys ?? [],
preserveRequiredNullables: !!paramsSerializer,
// Only pass non-primitive params through the built-in `filterParams`
// when a `paramsSerializer` can legally consume the raw object/array.
// Without one, the helper's `unknown` return type is not assignable
// to `HttpClient`'s params, so keep them filtered out. The
// `paramsFilter` branch bypasses the built-in helper entirely.
nonPrimitiveKeys: paramsSerializer
? (queryParams?.nonPrimitiveKeys ?? [])
: [],
paramsFilter,
useSharedHelper: true,
})
: undefined;
const paramsValue = paramsAccess
? paramsSerializer
? `params?.() ? ${paramsSerializer.name}(${filteredParamsValue}) : undefined`
: filteredParamsValue
: undefined;
const isGet = verb === 'get';
const hasExtras = !isGet || !!bodyValue || !!paramsValue || !!headersAccess;
const isUrlOnly = !hasExtras && !bodyForm;
const requestLines = [
`url: \`${route}\``,
isGet ? undefined : `method: '${verb.toUpperCase()}'`,
bodyValue ? `body: ${bodyValue}` : undefined,
paramsValue ? `params: ${paramsValue}` : undefined,
headersAccess ? `headers: ${headersAccess}` : undefined,
].filter(Boolean);
const request = isUrlOnly
? `\`${route}\``
: `({\n ${requestLines.join(',\n ')}\n })`;
return {
bodyForm,
request,
isUrlOnly,
bodyGuard,
};
};
const getHttpResourceResponseImports = (
response: GeneratorVerbOptions['response'],
): GeneratorImport[] => {
const successDefinition = response.definition.success;
if (!successDefinition) return [];
return response.imports.filter((imp) => {
const name = imp.alias ?? imp.name;
const pattern = new RegExp(String.raw`\b${escapeRegExp(name)}\b`, 'g');
return pattern.test(successDefinition);
});
};
const getParseSchemaName = (
response: {
readonly imports: readonly { name: string; isZodSchema?: boolean }[];
readonly definition: { readonly success?: string };
},
factory: HttpResourceFactoryName,
output: NormalizedOutputOptions,
responseTypeOverride?: string,
): string | undefined => {
if (factory !== 'httpResource') return undefined;
// Explicit isZodSchema flag on imports (forward-compatible)
const zodSchema = response.imports.find((imp) => imp.isZodSchema);
if (zodSchema) return zodSchema.name;
// Check if runtime validation is disabled
if (!output.override.angular.runtimeValidation) return undefined;
// Auto-detect: when schemas.type === 'zod', use the response type as the schema name
if (!isZodSchemaOutput(output)) return undefined;
const responseType = responseTypeOverride ?? response.definition.success;
if (!responseType) return undefined;
if (isPrimitiveType(responseType)) return undefined;
// Verify a matching import exists (the response type name resolves to a zod schema)
const hasMatchingImport = response.imports.some(
(imp) => imp.name === responseType,
);
if (!hasMatchingImport) return undefined;
return responseType;
};
const getHttpResourceZodParsedImportNames = (
response: GeneratorVerbOptions['response'],
output: NormalizedOutputOptions,
): Set<string> => {
const names = new Set<string>();
for (const successType of response.types.success) {
const schemaName = getParseSchemaName(
response,
getHttpResourceFactory(
response,
successType.contentType,
successType.value,
),
output,
successType.value,
);
if (schemaName) {
names.add(schemaName);
}
}
return names;
};
const getHttpResourceVerbImports = (
verbOptions: GeneratorVerbOptions,
output: NormalizedOutputOptions,
): GeneratorImport[] => {
const { response, body, queryParams, props, headers, params } = verbOptions;
const responseImports = getHttpResourceResponseImports(response);
const parsedZodImportNames = isZodSchemaOutput(output)
? getHttpResourceZodParsedImportNames(response, output)
: new Set<string>();
const parsedZodImports = responseImports.filter((imp) =>
parsedZodImportNames.has(imp.name),
);
return [
...responseImports.map((imp) =>
parsedZodImportNames.has(imp.name) ? { ...imp, values: true } : imp,
),
...parsedZodImports
.filter((imp) => !isPrimitiveType(imp.name))
.map((imp) => ({ name: getSchemaOutputTypeRef(imp.name) })),
...body.imports,
...props.flatMap((prop) =>
prop.type === GetterPropType.NAMED_PATH_PARAMS
? [{ name: prop.schema.name }]
: [],
),
...(queryParams ? [{ name: queryParams.schema.name }] : []),
...(headers ? [{ name: headers.schema.name }] : []),
...params.flatMap<GeneratorImport>(({ imports }) => imports),
{ name: 'map', values: true, importPath: 'rxjs' },
];
};
const getParseExpression = (
response: {
readonly imports: readonly { name: string; isZodSchema?: boolean }[];
readonly definition: { readonly success?: string };
},
factory: HttpResourceFactoryName,
output: NormalizedOutputOptions,
responseTypeOverride?: string,
): string | undefined => {
const schemaName = getParseSchemaName(
response,
factory,
output,
responseTypeOverride,
);
return schemaName ? `${schemaName}.parse` : undefined;
};
/**
* Builds the literal option entries that Orval injects into generated
* `httpResource()` calls.
*
* This merges user-supplied generator configuration such as `defaultValue` or
* `debugName` with automatically derived runtime-validation hooks like
* `parse: Schema.parse`.
*
* @returns The option entries plus metadata about whether a configured default value exists.
*/
const buildHttpResourceOptionsLiteral = (
verbOption: GeneratorVerbOptions,
factory: HttpResourceFactoryName,
output: NormalizedOutputOptions,
responseTypeOverride?: string,
): { entries: string[]; hasDefaultValue: boolean } => {
const override = getHttpResourceOverride(verbOption, output);
const parseExpression = getParseExpression(
verbOption.response,
factory,
output,
responseTypeOverride,
);
const defaultValueLiteral =
override?.defaultValue === undefined
? undefined
: JSON.stringify(override.defaultValue);
const optionEntries = [
parseExpression ? `parse: ${parseExpression}` : undefined,
defaultValueLiteral ? `defaultValue: ${defaultValueLiteral}` : undefined,
override?.debugName === undefined
? undefined
: `debugName: ${JSON.stringify(override.debugName)}`,
override?.injector ? `injector: ${override.injector}` : undefined,
override?.equal ? `equal: ${override.equal}` : undefined,
].filter((value): value is string => value !== undefined);
return {
entries: optionEntries,
hasDefaultValue: defaultValueLiteral !== undefined,
};
};
const appendArgument = (args: string, argument: string): string => {
const normalizedArgs = args.trim().replace(/,\s*$/, '');
return normalizedArgs.length > 0
? `${normalizedArgs},
${argument}`
: argument;
};
const normalizeOptionalParametersForRequiredTrailingArg = (
args: string,
): string =>
args.replaceAll(/(\w+)\?:\s*([^,\n]+)(,?)/g, '$1: $2 | undefined$3');
const buildHttpResourceOptionsArgument = (
valueType: string,
rawType: string,
options: { readonly requiresDefaultValue: boolean },
omitParse = false,
): string => {
const baseType = `${HTTP_RESOURCE_OPTIONS_TYPE_NAME}<${valueType}, ${rawType}${omitParse ? ', true' : ''}>`;
return options.requiresDefaultValue
? `options: ${baseType} & { defaultValue: NoInfer<${valueType}> }`
: `options?: ${baseType}`;
};
const buildHttpResourceOptionsExpression = (
configuredEntries: readonly string[],
): string | undefined => {
if (configuredEntries.length === 0) {
return 'options';
}
return `{
...(options ?? {}),
${configuredEntries.join(',\n ')}
}`;
};
const buildHttpResourceFunctionSignatures = (
resourceName: string,
args: string,
valueType: string,
rawType: string,
hasConfiguredDefaultValue: boolean,
omitParse = false,
): string => {
if (hasConfiguredDefaultValue) {
return `export function ${resourceName}(${appendArgument(
args,
buildHttpResourceOptionsArgument(
valueType,
rawType,
{
requiresDefaultValue: false,
},
omitParse,
),
)}): HttpResourceRef<${valueType}>`;
}
const overloadArgs = appendArgument(
normalizeOptionalParametersForRequiredTrailingArg(args),
buildHttpResourceOptionsArgument(
valueType,
rawType,
{
requiresDefaultValue: true,
},
omitParse,
),
);
const implementationArgs = appendArgument(
args,
buildHttpResourceOptionsArgument(
valueType,
rawType,
{
requiresDefaultValue: false,
},
omitParse,
),
);
return `export function ${resourceName}(${overloadArgs}): HttpResourceRef<${valueType}>;
export function ${resourceName}(${implementationArgs}): HttpResourceRef<${valueType} | undefined>`;
};
/**
* Generates a single Angular `httpResource` helper function for an operation.
*
* The generated output handles signal-wrapped parameters, route interpolation,
* request-body construction, content-type branching, runtime validation, and
* optional mutator integration when the mutator is compatible with standalone
* resource functions.
*
* @remarks
* This function emits overloads when content negotiation or caller-supplied
* `defaultValue` support requires multiple signatures.
*
* @returns A string containing the complete generated resource helper.
*/
const buildHttpResourceFunction = (
verbOption: GeneratorVerbOptions,
route: string,
output: NormalizedOutputOptions,
): string => {
const { operationName, typeName, response, props, params, mutator } =
verbOption;
const dataType = response.definition.success || 'unknown';
const omitParse = isZodSchemaOutput(output);
const responseSchemaImports = getHttpResourceResponseImports(response);
const hasResponseSchemaImport = responseSchemaImports.some(
(imp) => imp.name === dataType,
);
const resourceName = `${operationName}Resource`;
const parsedDataType =
omitParse &&
output.override.angular.runtimeValidation &&
!isPrimitiveType(dataType) &&
hasResponseSchemaImport
? getSchemaOutputTypeRef(dataType)
: dataType;
const successTypes = response.types.success;
const overallReturnType =
successTypes.length <= 1
? parsedDataType
: [
...new Set(
successTypes.map((type) =>
getHttpResourceGeneratedResponseType(
type.value,
type.contentType,
responseSchemaImports,
output,
),
),
),
].join(' | ') || parsedDataType;
resourceReturnTypesRegistry.set(
operationName,
`export type ${pascal(
typeName,
)}ResourceResult = NonNullable<${overallReturnType}>`,
);
const uniqueContentTypes = getUniqueContentTypes(successTypes);
const defaultSuccess = getDefaultSuccessType(successTypes, dataType);
const jsonContentType = successTypes.find((type) =>
type.contentType.includes('json'),
)?.contentType;
const preferredContentType = jsonContentType ?? defaultSuccess.contentType;
const resourceFactory = getHttpResourceFactory(
response,
preferredContentType,
dataType,
);
const hasNamedParams = props.some(
(prop) => prop.type === GetterPropType.NAMED_PATH_PARAMS,
);
const signalRoute = applySignalRoute(route, params, hasNamedParams);
// Opt-in URL-encoding of path parameters (`urlEncodeParameters`). Must run
// AFTER `applySignalRoute`: that step matches the literal `${param}` template
// to rewrite it to its signal form (e.g. `${param()}`), so encoding first
// would stop the substitution from matching. Wrapping the already-rewritten
// form yields `${encodeURIComponent(String(param()))}`, which is correct.
const encodedRoute = output.urlEncodeParameters
? makeRouteSafe(signalRoute)
: signalRoute;
const signalProps = buildSignalProps(props, params);
const args = toObjectString(signalProps, 'implementation');
const { bodyForm, request, isUrlOnly, bodyGuard } = buildResourceRequest(
verbOption,
encodedRoute,
{ supportsIdleGuard: uniqueContentTypes.length <= 1 },
);
if (uniqueContentTypes.length > 1) {
const defaultContentType = jsonContentType ?? defaultSuccess.contentType;
const acceptTypeName = getAcceptHelperName(typeName);
const requiredProps = signalProps.filter(
(_, index) => props[index]?.required && !props[index]?.default,
);
const optionalProps = signalProps.filter(
(_, index) => !props[index]?.required || props[index]?.default,
);
const requiredPart = requiredProps
.map((prop) => prop.implementation)
.join(',\n ');
const optionalPart = optionalProps
.map((prop) => prop.implementation)
.join(',\n ');
const getBranchReturnType = (type: ResReqTypesValue) =>
getHttpResourceGeneratedResponseType(
type.value,
type.contentType,
responseSchemaImports,
output,
);
const unionReturnType = [
...new Set(
successTypes
.filter((type) => type.contentType)
.map((type) => getBranchReturnType(type)),
),
].join(' | ');
const getBranchRawType = (type: ResReqTypesValue): string =>
getHttpResourceRawType(
getHttpResourceFactory(response, type.contentType, type.value),
);
// Per-branch options types (one per distinct content-type branch).
// Deduped so text-like content types (text/plain, application/xml) that
// share the same factory don't produce duplicate union members.
const branchOptionsTypes = [
...new Set(
successTypes
.filter((type) => type.contentType)
.map((type) =>
buildBranchOptionsType(
getBranchReturnType(type),
getBranchRawType(type),
omitParse,
),
),
),
];
// The implementation signature accepts the union of branch option types.
// This keeps each overload's narrow `options` assignable to the
// implementation signature (required for TS overload compatibility) while
// preventing mismatched `defaultValue`/`parse` across content types.
const implementationOptionsType = branchOptionsTypes.join(' | ');
// Per-accept overloads pin `options` to the branch-specific value/raw
// types so `defaultValue` / `parse` type-check against the actual content
// type — e.g. passing a `string` default to the `application/json`
// overload is now a type error.
const branchOverloads = successTypes
.filter((type) => type.contentType)
.map((type) => {
const returnType = getBranchReturnType(type);
const overloadArgs = [
requiredPart,
`accept: '${type.contentType}'`,
optionalPart,
`options?: ${buildBranchOptionsType(returnType, getBranchRawType(type), omitParse)}`,
]
.filter(Boolean)
.join(',\n ');
return `export function ${resourceName}(${overloadArgs}): HttpResourceRef<${returnType} | undefined>;`;
})
.join('\n');
const implementationArgsWithDefault = [
requiredPart,
`accept: ${acceptTypeName} = '${defaultContentType}'`,
optionalPart,
`options?: ${implementationOptionsType}`,
]
.filter(Boolean)
.join(',\n ');
const getBranchOptions = (type?: ResReqTypesValue) => {
if (!type) {
return `options as ${buildBranchOptionsType(unionReturnType, 'unknown', omitParse)}`;
}
const factory = getHttpResourceFactory(
response,
type.contentType,
type.value,
);
const branchOptions = buildHttpResourceOptionsLiteral(