@rxap/open-api 21.0.1 → 22.0.0-dev.0

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 (117) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/compodoc/changelog.html +8 -0
  3. package/compodoc/dependencies.html +7 -7
  4. package/compodoc/js/search/search_index.js +2 -2
  5. package/compodoc/properties.html +1 -1
  6. package/docs/documentation.json +139 -139
  7. package/docs/html/classes/OpenApiConfigService.html +3 -3
  8. package/docs/html/classes/OpenApiHttpResponseError.html +10 -10
  9. package/docs/html/classes/RxapOpenApiError.html +5 -5
  10. package/docs/html/classes/SchemaValidationMixin.html +5 -5
  11. package/docs/html/functions/AssertOpenApiV3.html +1 -1
  12. package/docs/html/functions/IsOpenApiV3.html +1 -1
  13. package/docs/html/functions/IsReferenceObject.html +1 -1
  14. package/docs/html/functions/NotContainsReferenceObjects.html +1 -1
  15. package/docs/html/functions/OpenApiInit.html +1 -1
  16. package/docs/html/functions/getJsonContentSchema.html +1 -1
  17. package/docs/html/functions/getJsonSchema.html +1 -1
  18. package/docs/html/functions/hasJsonContentSchema.html +1 -1
  19. package/docs/html/functions/hasJsonSchema.html +1 -1
  20. package/docs/html/functions/injectOpenApiBaseUrlHttpInterceptorFn.html +1 -1
  21. package/docs/html/index.html +2 -2
  22. package/docs/html/interfaces/OpenApiInitOptions.html +3 -3
  23. package/docs/html/interfaces/OpenApiMetaData.html +5 -5
  24. package/docs/html/interfaces/OperationObjectWithMetadata.html +2 -2
  25. package/docs/html/interfaces/SchemaValidationResponse.html +2 -2
  26. package/docs/html/modules.html +1 -1
  27. package/docs/html/types/OperationMap.html +1 -1
  28. package/docs/html/variables/DEFAULT_OPEN_API_DATA_SOURCE_META_DATA.html +1 -1
  29. package/docs/html/variables/DEFAULT_OPEN_API_REMOTE_METHOD_META_DATA.html +1 -1
  30. package/docs/html/variables/DISABLE_SCHEMA_VALIDATION.html +1 -1
  31. package/docs/html/variables/DISABLE_VALIDATION.html +1 -1
  32. package/docs/html/variables/OPEN_API_OPERATION.html +1 -1
  33. package/docs/html/variables/OPEN_API_OPERATION_ID.html +1 -1
  34. package/docs/html/variables/OPEN_API_SERVER_ID.html +1 -1
  35. package/docs/html/variables/OPEN_API_SERVER_INDEX.html +1 -1
  36. package/docs/html/variables/RXAP_OPEN_API_CONFIG.html +1 -1
  37. package/docs/html/variables/RXAP_OPEN_API_STRICT_VALIDATOR.html +1 -1
  38. package/docs/markdown/README.md +1 -1
  39. package/docs/markdown/classes/OpenApiConfigService.md +14 -14
  40. package/docs/markdown/classes/OpenApiHttpResponseError.md +18 -18
  41. package/docs/markdown/classes/RxapOpenApiError.md +16 -16
  42. package/docs/markdown/classes/SchemaValidationMixin.md +13 -13
  43. package/docs/markdown/functions/AssertOpenApiV3.md +2 -2
  44. package/docs/markdown/functions/IsOpenApiV3.md +2 -2
  45. package/docs/markdown/functions/IsReferenceObject.md +2 -2
  46. package/docs/markdown/functions/NotContainsReferenceObjects.md +2 -2
  47. package/docs/markdown/functions/OpenApiInit.md +2 -2
  48. package/docs/markdown/functions/getJsonContentSchema.md +2 -2
  49. package/docs/markdown/functions/getJsonSchema.md +2 -2
  50. package/docs/markdown/functions/hasJsonContentSchema.md +2 -2
  51. package/docs/markdown/functions/hasJsonSchema.md +2 -2
  52. package/docs/markdown/functions/injectOpenApiBaseUrlHttpInterceptorFn.md +2 -2
  53. package/docs/markdown/globals.md +2 -2
  54. package/docs/markdown/interfaces/OpenApiInitOptions.md +4 -4
  55. package/docs/markdown/interfaces/OpenApiMetaData.md +7 -7
  56. package/docs/markdown/interfaces/OperationObjectWithMetadata.md +4 -4
  57. package/docs/markdown/interfaces/SchemaValidationResponse.md +6 -6
  58. package/docs/markdown/type-aliases/OperationMap.md +2 -2
  59. package/docs/markdown/variables/DEFAULT_OPEN_API_DATA_SOURCE_META_DATA.md +2 -2
  60. package/docs/markdown/variables/DEFAULT_OPEN_API_REMOTE_METHOD_META_DATA.md +2 -2
  61. package/docs/markdown/variables/DISABLE_SCHEMA_VALIDATION.md +2 -2
  62. package/docs/markdown/variables/DISABLE_VALIDATION.md +2 -2
  63. package/docs/markdown/variables/OPEN_API_OPERATION.md +2 -2
  64. package/docs/markdown/variables/OPEN_API_OPERATION_ID.md +2 -2
  65. package/docs/markdown/variables/OPEN_API_SERVER_ID.md +2 -2
  66. package/docs/markdown/variables/OPEN_API_SERVER_INDEX.md +2 -2
  67. package/docs/markdown/variables/RXAP_OPEN_API_CONFIG.md +2 -2
  68. package/docs/markdown/variables/RXAP_OPEN_API_STRICT_VALIDATOR.md +2 -2
  69. package/docs/wiki/Class.OpenApiConfigService.md +13 -13
  70. package/docs/wiki/Class.OpenApiHttpResponseError.md +17 -17
  71. package/docs/wiki/Class.RxapOpenApiError.md +15 -15
  72. package/docs/wiki/Class.SchemaValidationMixin.md +12 -12
  73. package/docs/wiki/Function.AssertOpenApiV3.md +1 -1
  74. package/docs/wiki/Function.IsOpenApiV3.md +1 -1
  75. package/docs/wiki/Function.IsReferenceObject.md +1 -1
  76. package/docs/wiki/Function.NotContainsReferenceObjects.md +1 -1
  77. package/docs/wiki/Function.OpenApiInit.md +1 -1
  78. package/docs/wiki/Function.getJsonContentSchema.md +1 -1
  79. package/docs/wiki/Function.getJsonSchema.md +1 -1
  80. package/docs/wiki/Function.hasJsonContentSchema.md +1 -1
  81. package/docs/wiki/Function.hasJsonSchema.md +1 -1
  82. package/docs/wiki/Function.injectOpenApiBaseUrlHttpInterceptorFn.md +1 -1
  83. package/docs/wiki/Interface.OpenApiInitOptions.md +3 -3
  84. package/docs/wiki/Interface.OpenApiMetaData.md +6 -6
  85. package/docs/wiki/Interface.OperationObjectWithMetadata.md +3 -3
  86. package/docs/wiki/Interface.SchemaValidationResponse.md +5 -5
  87. package/docs/wiki/TypeAlias.OperationMap.md +1 -1
  88. package/docs/wiki/Variable.DEFAULT_OPEN_API_DATA_SOURCE_META_DATA.md +1 -1
  89. package/docs/wiki/Variable.DEFAULT_OPEN_API_REMOTE_METHOD_META_DATA.md +1 -1
  90. package/docs/wiki/Variable.DISABLE_SCHEMA_VALIDATION.md +1 -1
  91. package/docs/wiki/Variable.DISABLE_VALIDATION.md +1 -1
  92. package/docs/wiki/Variable.OPEN_API_OPERATION.md +1 -1
  93. package/docs/wiki/Variable.OPEN_API_OPERATION_ID.md +1 -1
  94. package/docs/wiki/Variable.OPEN_API_SERVER_ID.md +1 -1
  95. package/docs/wiki/Variable.OPEN_API_SERVER_INDEX.md +1 -1
  96. package/docs/wiki/Variable.RXAP_OPEN_API_CONFIG.md +1 -1
  97. package/docs/wiki/Variable.RXAP_OPEN_API_STRICT_VALIDATOR.md +1 -1
  98. package/docs/wiki/globals.md +1 -1
  99. package/fesm2022/rxap-open-api-data-source-table.mjs +212 -162
  100. package/fesm2022/rxap-open-api-data-source-table.mjs.map +1 -1
  101. package/fesm2022/rxap-open-api-data-source.mjs +243 -188
  102. package/fesm2022/rxap-open-api-data-source.mjs.map +1 -1
  103. package/fesm2022/rxap-open-api-http-resource.mjs +13 -38
  104. package/fesm2022/rxap-open-api-http-resource.mjs.map +1 -1
  105. package/fesm2022/rxap-open-api-remote-method.mjs +295 -263
  106. package/fesm2022/rxap-open-api-remote-method.mjs.map +1 -1
  107. package/fesm2022/rxap-open-api-testing.mjs +55 -82
  108. package/fesm2022/rxap-open-api-testing.mjs.map +1 -1
  109. package/fesm2022/rxap-open-api.mjs +439 -633
  110. package/fesm2022/rxap-open-api.mjs.map +1 -1
  111. package/package.json +19 -19
  112. package/types/rxap-open-api-data-source-table.d.ts +47 -40
  113. package/types/rxap-open-api-data-source.d.ts +58 -52
  114. package/types/rxap-open-api-http-resource.d.ts +13 -17
  115. package/types/rxap-open-api-remote-method.d.ts +89 -86
  116. package/types/rxap-open-api-testing.d.ts +25 -28
  117. package/types/rxap-open-api.d.ts +153 -162
@@ -1,658 +1,464 @@
1
- import { RxapError, JoinPath, coerceArray, IsRecord, assertsObject, isPromiseLike } from '@rxap/utilities';
2
- import { HttpContextToken, HttpErrorResponse, HttpParams, HttpHeaders } from '@angular/common/http';
3
- import * as i0 from '@angular/core';
4
- import { InjectionToken, isDevMode, Optional, Inject, Injectable, inject } from '@angular/core';
5
- import { ConfigService } from '@rxap/config';
6
- import Ajv from 'ajv';
7
-
8
- class RxapOpenApiError extends RxapError {
9
- constructor(message, code, scope) {
10
- super('@rxap/open-api', message, code ?? '', scope);
11
- }
12
- }
13
-
14
- const OPEN_API_OPERATION_ID = new HttpContextToken(() => '');
1
+ import { IsRecord, JoinPath, RxapError, assertsObject, coerceArray, isPromiseLike } from "@rxap/utilities";
2
+ import { HttpContextToken, HttpErrorResponse, HttpHeaders, HttpParams } from "@angular/common/http";
3
+ import * as i0 from "@angular/core";
4
+ import { Inject, Injectable, InjectionToken, Optional, inject, isDevMode } from "@angular/core";
5
+ import { ConfigService } from "@rxap/config";
6
+ import Ajv from "ajv";
7
+ var RxapOpenApiError = class extends RxapError {
8
+ constructor(message, code, scope) {
9
+ super("@rxap/open-api", message, code ?? "", scope);
10
+ }
11
+ };
12
+ const OPEN_API_OPERATION_ID = new HttpContextToken(() => "");
15
13
  const OPEN_API_SERVER_ID = new HttpContextToken(() => null);
16
14
  const OPEN_API_SERVER_INDEX = new HttpContextToken(() => 0);
17
- const OPEN_API_OPERATION = new HttpContextToken(() => '');
18
-
19
- const RXAP_OPEN_API_CONFIG = new InjectionToken('rxap/open-api/config');
20
- const RXAP_OPEN_API_STRICT_VALIDATOR = new InjectionToken('rxap/open-api/strict-validator');
21
- const DEFAULT_OPEN_API_REMOTE_METHOD_META_DATA = new InjectionToken('rxap/open-api/default-remote-method-meta-data');
22
- const DEFAULT_OPEN_API_DATA_SOURCE_META_DATA = new InjectionToken('rxap/open-api/default-data-source-meta-data');
23
- const DISABLE_SCHEMA_VALIDATION = new InjectionToken('rxap/open-api/disable-schema-validation', {
24
- providedIn: 'root',
25
- factory: () => true,
15
+ const OPEN_API_OPERATION = new HttpContextToken(() => "");
16
+ const RXAP_OPEN_API_CONFIG = new InjectionToken("rxap/open-api/config");
17
+ const RXAP_OPEN_API_STRICT_VALIDATOR = new InjectionToken("rxap/open-api/strict-validator");
18
+ const DEFAULT_OPEN_API_REMOTE_METHOD_META_DATA = new InjectionToken("rxap/open-api/default-remote-method-meta-data");
19
+ const DEFAULT_OPEN_API_DATA_SOURCE_META_DATA = new InjectionToken("rxap/open-api/default-data-source-meta-data");
20
+ const DISABLE_SCHEMA_VALIDATION = new InjectionToken("rxap/open-api/disable-schema-validation", {
21
+ providedIn: "root",
22
+ factory: () => true
26
23
  });
27
- const DISABLE_VALIDATION = new InjectionToken('rxap/open-api/disable-validation', {
28
- providedIn: 'root',
29
- factory: () => true,
24
+ const DISABLE_VALIDATION = new InjectionToken("rxap/open-api/disable-validation", {
25
+ providedIn: "root",
26
+ factory: () => true
30
27
  });
31
-
32
28
  function IsReferenceObject(obj) {
33
- return !!obj && obj.hasOwnProperty('$ref');
29
+ return !!obj && obj.hasOwnProperty("$ref");
34
30
  }
35
31
  function NotContainsReferenceObjects(array) {
36
- return !!array && array.every(item => !IsReferenceObject(item) && !!item);
32
+ return !!array && array.every((item) => !IsReferenceObject(item) && !!item);
37
33
  }
38
34
  function IsOpenApiV3(obj) {
39
- return !!obj && obj.hasOwnProperty('openapi') && obj.openapi.match(/^3\./);
35
+ return !!obj && obj.hasOwnProperty("openapi") && obj.openapi.match(/^3\./);
40
36
  }
41
37
  function AssertOpenApiV3(obj) {
42
- if (!IsOpenApiV3(obj)) {
43
- throw new RxapOpenApiError('Only openapi version 3.x.x is supported');
44
- }
38
+ if (!IsOpenApiV3(obj)) throw new RxapOpenApiError("Only openapi version 3.x.x is supported");
45
39
  }
46
40
  function hasJsonContentSchema(data) {
47
- return !!data && !IsReferenceObject(data) && 'content' in data && !!data.content && hasJsonSchema(data.content);
41
+ return !!data && !IsReferenceObject(data) && "content" in data && !!data.content && hasJsonSchema(data.content);
48
42
  }
49
43
  function getJsonContentSchema(data) {
50
- if (hasJsonContentSchema(data)) {
51
- return getJsonSchema(data.content);
52
- }
53
- return null;
44
+ if (hasJsonContentSchema(data)) return getJsonSchema(data.content);
45
+ return null;
54
46
  }
55
47
  function hasJsonSchema(map) {
56
- return !!map && Object.keys(map).some(key => key.match(/^application\/(.+\+)?json/));
48
+ return !!map && Object.keys(map).some((key) => key.match(/^application\/(.+\+)?json/));
57
49
  }
58
50
  function getJsonSchema(map) {
59
- if (!hasJsonSchema(map)) {
60
- return null;
61
- }
62
- let schema;
63
- if ('application/json' in map) {
64
- schema = map['application/json'].schema;
65
- }
66
- else {
67
- schema = Object.entries(map).find(([key]) => key.match(/^application\/(.+\+)?json/))?.[1]?.schema;
68
- }
69
- if (!schema) {
70
- return null;
71
- }
72
- if (IsReferenceObject(schema)) {
73
- return null;
74
- }
75
- return schema;
51
+ if (!hasJsonSchema(map)) return null;
52
+ let schema;
53
+ if ("application/json" in map) schema = map["application/json"].schema;
54
+ else schema = Object.entries(map).find(([key]) => key.match(/^application\/(.+\+)?json/))?.[1]?.schema;
55
+ if (!schema) return null;
56
+ if (IsReferenceObject(schema)) return null;
57
+ return schema;
76
58
  }
77
-
78
- class OpenApiConfigService {
79
- static { this.Config = null; }
80
- static { this.DefaultServerIndex = 0; }
81
- static { this._operations = null; }
82
- static { this.serverConfigMap = new Map(); }
83
- get serverConfigMap() {
84
- return OpenApiConfigService.serverConfigMap;
85
- }
86
- get serverIds() {
87
- return Object.keys(this.serverConfigMap);
88
- }
89
- constructor(config = null) {
90
- this.defaultServerIndex = OpenApiConfigService.DefaultServerIndex;
91
- this._operations = null;
92
- this._config = null;
93
- config = config ?? OpenApiConfigService.Config;
94
- if (config) {
95
- this._config = config;
96
- this._operations = OpenApiConfigService.LoadOperations(config);
97
- }
98
- OpenApiConfigService.Config ??= config;
99
- }
100
- get config() {
101
- if (!this._config) {
102
- throw new Error('Could not load open api config');
103
- }
104
- return this._config;
105
- }
106
- /**
107
- * Used to load the app open api config from a remote resource.
108
- *
109
- * Promise.all([ OpenApiDataSourceLoader.Load() ])
110
- * .then(() => platformBrowserDynamic().bootstrapModule(AppModule))
111
- * .catch(err => console.error(err))
112
- *
113
- */
114
- static async Load(openApiUrl = 'openapi.json') {
115
- if (!openApiUrl) {
116
- throw new Error('The open api url is not defined!');
117
- }
118
- let config = null;
119
- try {
120
- const response = await fetch(openApiUrl);
121
- config = await response.json();
122
- }
123
- catch (error) {
124
- console.debug(`Could not load the open api config from '${openApiUrl}'!`, error);
125
- console.error(`Could not load the open api config from '${openApiUrl}'!`, error.message);
126
- }
127
- if (config) {
128
- const expandedConfig = await this.ExpandOpenApi(config);
129
- AssertOpenApiV3(expandedConfig);
130
- this.Config = expandedConfig;
131
- }
132
- else {
133
- this.Config = null;
134
- }
135
- }
136
- static GetOperation(operationId) {
137
- if (!this.Config) {
138
- throw new Error('Could not load open api config');
139
- }
140
- if (!this._operations) {
141
- this._operations = this.LoadOperations(this.Config);
142
- }
143
- if (!this._operations.has(operationId)) {
144
- throw new Error(`The operation '${operationId}' is not defined in the openapi-json`);
145
- }
146
- return this._operations.get(operationId);
147
- }
148
- static LoadOperations(config) {
149
- const operations = new Map();
150
- Object.entries(config.paths)
151
- .filter((item) => item[0] !== undefined)
152
- .filter(([_, methods]) => methods &&
153
- Object.keys(methods).some((method) => ['get', 'put', 'post', 'delete', 'patch'].includes(method)))
154
- .forEach(([path, methods]) => Object.entries(methods)
155
- .filter((item) => item[0] !== undefined)
156
- .forEach(([method, operation]) => {
157
- if (!operation.operationId) {
158
- throw new Error('The OpenApu OperationId is not defined');
159
- }
160
- if (operations.has(operation.operationId)) {
161
- throw new Error(`The OpenApi Operation '${operation.operationId}' is already defined.`);
162
- }
163
- operations.set(operation.operationId, {
164
- ...operation,
165
- path: path,
166
- method: method.toUpperCase(),
167
- });
168
- }));
169
- return operations;
170
- }
171
- static GetBaseUrl(config, serverIndex = this.DefaultServerIndex) {
172
- const server = config.servers ? config.servers[serverIndex] : null;
173
- if (!server) {
174
- console.debug(`Could not extract the server config with the index '${serverIndex}' from the open api config`, config);
175
- throw new Error(`Could not extract the server config with the index '${serverIndex}' from the open api config`);
176
- }
177
- return server.url;
178
- }
179
- /**
180
- * Replaces all $ref with the concrete definition
181
- *
182
- * @param config
183
- * @private
184
- */
185
- static ExpandOpenApi(config) {
186
- return Promise.resolve(config);
187
- }
188
- getOperation(operationId) {
189
- if (!this._operations) {
190
- if (!this._config) {
191
- throw new Error('The operations map is not loaded and the config object is not loaded');
192
- }
193
- this._operations = OpenApiConfigService.LoadOperations(this._config);
194
- }
195
- if (!this._operations.has(operationId)) {
196
- console.error(`The operation '${operationId}' is not defined in the openapi-json`, isDevMode() ? this.config : undefined);
197
- throw new Error(`The operation '${operationId}' is not defined in the openapi-json`);
198
- }
199
- return this._operations.get(operationId);
200
- }
201
- getBaseUrl(serverIndex = this.defaultServerIndex, serverId) {
202
- let serverConfig;
203
- const servers = this._config?.servers ?? [];
204
- if (!serverId && servers) {
205
- serverConfig = servers[serverIndex];
206
- }
207
- if (this.serverConfigMap.has(serverId)) {
208
- serverConfig = this.serverConfigMap.get(serverId)[serverIndex];
209
- }
210
- if (!serverConfig) {
211
- console.error(`Could not determine the base url with the index '${serverIndex}' and the serverId '${serverId}'`, isDevMode() ? servers : undefined);
212
- throw new Error(`Could not determine the base url with the index '${serverIndex}' and the serverId '${serverId}'`);
213
- }
214
- return serverConfig.url;
215
- }
216
- static InsertServer(serverConfig, index, serverId, config = this.Config) {
217
- if (!serverId && config) {
218
- if (!config.servers) {
219
- config.servers = [];
220
- }
221
- config.servers.splice(index, 1, serverConfig);
222
- }
223
- if (!this.serverConfigMap.has(serverId)) {
224
- this.serverConfigMap.set(serverId, []);
225
- }
226
- const list = this.serverConfigMap.get(serverId);
227
- list[index] = serverConfig;
228
- this.serverConfigMap.set(serverId, list);
229
- }
230
- insertServer(serverConfig, index = this.defaultServerIndex, serverId) {
231
- OpenApiConfigService.InsertServer(serverConfig, index, serverId, this.config);
232
- }
233
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: OpenApiConfigService, deps: [{ token: RXAP_OPEN_API_CONFIG, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
234
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: OpenApiConfigService, providedIn: 'root' }); }
235
- }
236
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: OpenApiConfigService, decorators: [{
237
- type: Injectable,
238
- args: [{ providedIn: 'root' }]
239
- }], ctorParameters: () => [{ type: undefined, decorators: [{
240
- type: Optional
241
- }, {
242
- type: Inject,
243
- args: [RXAP_OPEN_API_CONFIG]
244
- }] }] });
245
-
59
+ var OpenApiConfigService = class OpenApiConfigService {
60
+ static {
61
+ this.Config = null;
62
+ }
63
+ static {
64
+ this.DefaultServerIndex = 0;
65
+ }
66
+ static {
67
+ this._operations = null;
68
+ }
69
+ static {
70
+ this.serverConfigMap = /* @__PURE__ */ new Map();
71
+ }
72
+ get serverConfigMap() {
73
+ return OpenApiConfigService.serverConfigMap;
74
+ }
75
+ get serverIds() {
76
+ return Object.keys(this.serverConfigMap);
77
+ }
78
+ constructor(config = null) {
79
+ this.defaultServerIndex = OpenApiConfigService.DefaultServerIndex;
80
+ this._operations = null;
81
+ this._config = null;
82
+ config = config ?? OpenApiConfigService.Config;
83
+ if (config) {
84
+ this._config = config;
85
+ this._operations = OpenApiConfigService.LoadOperations(config);
86
+ }
87
+ OpenApiConfigService.Config ??= config;
88
+ }
89
+ get config() {
90
+ if (!this._config) throw new Error("Could not load open api config");
91
+ return this._config;
92
+ }
93
+ static async Load(openApiUrl = "openapi.json") {
94
+ if (!openApiUrl) throw new Error("The open api url is not defined!");
95
+ let config = null;
96
+ try {
97
+ config = await (await fetch(openApiUrl)).json();
98
+ } catch (error) {
99
+ console.debug(`Could not load the open api config from '${openApiUrl}'!`, error);
100
+ console.error(`Could not load the open api config from '${openApiUrl}'!`, error.message);
101
+ }
102
+ if (config) {
103
+ const expandedConfig = await this.ExpandOpenApi(config);
104
+ AssertOpenApiV3(expandedConfig);
105
+ this.Config = expandedConfig;
106
+ } else this.Config = null;
107
+ }
108
+ static GetOperation(operationId) {
109
+ if (!this.Config) throw new Error("Could not load open api config");
110
+ if (!this._operations) this._operations = this.LoadOperations(this.Config);
111
+ if (!this._operations.has(operationId)) throw new Error(`The operation '${operationId}' is not defined in the openapi-json`);
112
+ return this._operations.get(operationId);
113
+ }
114
+ static LoadOperations(config) {
115
+ const operations = /* @__PURE__ */ new Map();
116
+ Object.entries(config.paths).filter((item) => item[0] !== void 0).filter(([_, methods]) => methods && Object.keys(methods).some((method) => [
117
+ "get",
118
+ "put",
119
+ "post",
120
+ "delete",
121
+ "patch"
122
+ ].includes(method))).forEach(([path, methods]) => Object.entries(methods).filter((item) => item[0] !== void 0).forEach(([method, operation]) => {
123
+ if (!operation.operationId) throw new Error("The OpenApu OperationId is not defined");
124
+ if (operations.has(operation.operationId)) throw new Error(`The OpenApi Operation '${operation.operationId}' is already defined.`);
125
+ operations.set(operation.operationId, {
126
+ ...operation,
127
+ path,
128
+ method: method.toUpperCase()
129
+ });
130
+ }));
131
+ return operations;
132
+ }
133
+ static GetBaseUrl(config, serverIndex = this.DefaultServerIndex) {
134
+ const server = config.servers ? config.servers[serverIndex] : null;
135
+ if (!server) {
136
+ console.debug(`Could not extract the server config with the index '${serverIndex}' from the open api config`, config);
137
+ throw new Error(`Could not extract the server config with the index '${serverIndex}' from the open api config`);
138
+ }
139
+ return server.url;
140
+ }
141
+ static ExpandOpenApi(config) {
142
+ return Promise.resolve(config);
143
+ }
144
+ getOperation(operationId) {
145
+ if (!this._operations) {
146
+ if (!this._config) throw new Error("The operations map is not loaded and the config object is not loaded");
147
+ this._operations = OpenApiConfigService.LoadOperations(this._config);
148
+ }
149
+ if (!this._operations.has(operationId)) {
150
+ console.error(`The operation '${operationId}' is not defined in the openapi-json`, isDevMode() ? this.config : void 0);
151
+ throw new Error(`The operation '${operationId}' is not defined in the openapi-json`);
152
+ }
153
+ return this._operations.get(operationId);
154
+ }
155
+ getBaseUrl(serverIndex = this.defaultServerIndex, serverId) {
156
+ let serverConfig;
157
+ const servers = this._config?.servers ?? [];
158
+ if (!serverId && servers) serverConfig = servers[serverIndex];
159
+ if (this.serverConfigMap.has(serverId)) serverConfig = this.serverConfigMap.get(serverId)[serverIndex];
160
+ if (!serverConfig) {
161
+ console.error(`Could not determine the base url with the index '${serverIndex}' and the serverId '${serverId}'`, isDevMode() ? servers : void 0);
162
+ throw new Error(`Could not determine the base url with the index '${serverIndex}' and the serverId '${serverId}'`);
163
+ }
164
+ return serverConfig.url;
165
+ }
166
+ static InsertServer(serverConfig, index, serverId, config = this.Config) {
167
+ if (!serverId && config) {
168
+ if (!config.servers) config.servers = [];
169
+ config.servers.splice(index, 1, serverConfig);
170
+ }
171
+ if (!this.serverConfigMap.has(serverId)) this.serverConfigMap.set(serverId, []);
172
+ const list = this.serverConfigMap.get(serverId);
173
+ list[index] = serverConfig;
174
+ this.serverConfigMap.set(serverId, list);
175
+ }
176
+ insertServer(serverConfig, index = this.defaultServerIndex, serverId) {
177
+ OpenApiConfigService.InsertServer(serverConfig, index, serverId, this.config);
178
+ }
179
+ static {
180
+ this.ɵfac = i0.ɵɵngDeclareFactory({
181
+ minVersion: "12.0.0",
182
+ version: "22.3.0",
183
+ ngImport: i0,
184
+ type: OpenApiConfigService,
185
+ deps: [{
186
+ token: RXAP_OPEN_API_CONFIG,
187
+ optional: true
188
+ }],
189
+ target: i0.ɵɵFactoryTarget.Injectable
190
+ });
191
+ }
192
+ static {
193
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
194
+ minVersion: "12.0.0",
195
+ version: "22.3.0",
196
+ ngImport: i0,
197
+ type: OpenApiConfigService,
198
+ providedIn: "root"
199
+ });
200
+ }
201
+ };
202
+ i0.ɵɵngDeclareClassMetadata({
203
+ minVersion: "12.0.0",
204
+ version: "22.3.0",
205
+ ngImport: i0,
206
+ type: OpenApiConfigService,
207
+ decorators: [{
208
+ type: Injectable,
209
+ args: [{ providedIn: "root" }]
210
+ }],
211
+ ctorParameters: () => [{
212
+ type: void 0,
213
+ decorators: [{ type: Optional }, {
214
+ type: Inject,
215
+ args: [RXAP_OPEN_API_CONFIG]
216
+ }]
217
+ }]
218
+ });
246
219
  const injectOpenApiBaseUrlHttpInterceptorFn = (req, next) => {
247
- const serverId = req.context.get(OPEN_API_SERVER_ID);
248
- const serverIndex = req.context.get(OPEN_API_SERVER_INDEX);
249
- const openApiConfigService = inject(OpenApiConfigService);
250
- if (serverId) {
251
- const baseUrl = openApiConfigService.getBaseUrl(serverIndex, serverId);
252
- if (req.url.startsWith('http')) {
253
- if (!req.url.startsWith(baseUrl)) {
254
- console.warn(`The url ${req.url} is not a valid url for the server ${serverId}. Expected base url ${baseUrl}`);
255
- }
256
- }
257
- else {
258
- const url = JoinPath(baseUrl, req.url);
259
- return next(req.clone({ url }));
260
- }
261
- }
262
- return next(req);
220
+ const serverId = req.context.get(OPEN_API_SERVER_ID);
221
+ const serverIndex = req.context.get(OPEN_API_SERVER_INDEX);
222
+ const openApiConfigService = inject(OpenApiConfigService);
223
+ if (serverId) {
224
+ const baseUrl = openApiConfigService.getBaseUrl(serverIndex, serverId);
225
+ if (req.url.startsWith("http")) {
226
+ if (!req.url.startsWith(baseUrl)) console.warn(`The url ${req.url} is not a valid url for the server ${serverId}. Expected base url ${baseUrl}`);
227
+ } else {
228
+ const url = JoinPath(baseUrl, req.url);
229
+ return next(req.clone({ url }));
230
+ }
231
+ }
232
+ return next(req);
233
+ };
234
+ var OpenApiHttpResponseError = class OpenApiHttpResponseError extends HttpErrorResponse {
235
+ constructor(httpErrorResponse, metadata) {
236
+ super({
237
+ error: httpErrorResponse.error,
238
+ headers: httpErrorResponse.headers,
239
+ status: httpErrorResponse.status,
240
+ statusText: httpErrorResponse.statusText,
241
+ url: httpErrorResponse.url ?? void 0
242
+ });
243
+ this.httpErrorResponse = httpErrorResponse;
244
+ this.metadata = metadata;
245
+ if (Error["captureStackTrace"]) Error["captureStackTrace"](this, OpenApiHttpResponseError);
246
+ Reflect.set(this, "name", "OpenApiHttpResponseError");
247
+ }
248
+ get operationId() {
249
+ return this.metadata.id;
250
+ }
251
+ get serverId() {
252
+ return this.metadata.serverId;
253
+ }
263
254
  };
264
-
265
- class OpenApiHttpResponseError extends HttpErrorResponse {
266
- constructor(httpErrorResponse, metadata) {
267
- super({
268
- error: httpErrorResponse.error,
269
- headers: httpErrorResponse.headers,
270
- status: httpErrorResponse.status,
271
- statusText: httpErrorResponse.statusText,
272
- url: httpErrorResponse.url ?? undefined,
273
- });
274
- this.httpErrorResponse = httpErrorResponse;
275
- this.metadata = metadata;
276
- if (Error['captureStackTrace']) {
277
- Error['captureStackTrace'](this, OpenApiHttpResponseError);
278
- }
279
- Reflect.set(this, 'name', 'OpenApiHttpResponseError');
280
- }
281
- get operationId() {
282
- return this.metadata.id;
283
- }
284
- get serverId() {
285
- return this.metadata.serverId;
286
- }
287
- }
288
-
289
255
  function OpenApiInit(environment, options = {}) {
290
- const api = ConfigService.Get('api', {}, ConfigService.Config);
291
- options.origin ??= environment.origin ?? location.origin;
292
- options.load ??= environment.openApi?.load ?? false;
293
- if (api.baseUrl) {
294
- OpenApiConfigService.InsertServer({
295
- url: api.baseUrl.match(/^https?:\/\//) ? api.baseUrl : JoinPath(options.origin, api.baseUrl),
296
- }, OpenApiConfigService.DefaultServerIndex);
297
- }
298
- for (const [serverId, config] of Object.entries(api)) {
299
- if (config && typeof config === 'object') {
300
- const baseUrl = config.baseUrl;
301
- if (baseUrl) {
302
- const url = baseUrl.match(/^https?:\/\//) ? baseUrl : JoinPath(options.origin, baseUrl);
303
- console.debug(`Add server '${serverId}' with url '${url}'`);
304
- OpenApiConfigService.InsertServer({ url }, OpenApiConfigService.DefaultServerIndex, serverId);
305
- }
306
- }
307
- }
308
- if (options.load) {
309
- return OpenApiConfigService.Load(typeof options.load === 'object' ? options.load.openApiUrl : undefined);
310
- }
311
- return undefined;
312
- }
313
-
314
- class SchemaValidationMixin {
315
- static { this.STRICT = false; }
316
- /**
317
- * Validates the parameters against the schema specified in the operation object
318
- *
319
- * @param operation
320
- * @param parameters
321
- * @param strict
322
- * @protected
323
- */
324
- validateParameters(operation, parameters, strict = false) {
325
- const operationParameters = coerceArray(operation.parameters);
326
- if (!NotContainsReferenceObjects(operationParameters)) {
327
- throw new RxapOpenApiError('The operation parameters contains ReferenceObject!');
328
- }
329
- if (parameters === undefined) {
330
- // TODO : find concept to definition witch parameter should not be checked if required
331
- // header parameters are never required if changes the semantic release manager breaks
332
- const requiredParameters = operationParameters.filter(parameter => parameter.required &&
333
- parameter.in !==
334
- 'header');
335
- if (requiredParameters.length) {
336
- if (isDevMode()) {
337
- console.debug('Some operation parameters are required!', requiredParameters.map(p => p.name));
338
- }
339
- this.validationError('Some operation parameters are required!', strict);
340
- }
341
- }
342
- else if (IsRecord(parameters)) {
343
- for (const parameter of operationParameters) {
344
- if (parameter.required) {
345
- // header parameters are never required if changes the semantic release manager breaks
346
- if (parameter.in !== 'header') {
347
- if (!parameters.hasOwnProperty(parameter.name)) {
348
- this.validationError(`The operation parameter '${parameter.name}' is required!`, strict);
349
- }
350
- }
351
- }
352
- if (parameter.schema) {
353
- if (parameters.hasOwnProperty(parameter.name)) {
354
- const value = parameters[parameter.name];
355
- if (!this.validate(parameter.schema, value)) {
356
- this.validationError(`The parameter '${parameter.name}' is not valid against the schema!`, strict, parameter.schema, value);
357
- }
358
- }
359
- }
360
- }
361
- }
362
- else {
363
- if (operationParameters.length === 0 || operationParameters.every(op => !op.required)) {
364
- if (isDevMode()) {
365
- console.warn(`The operation ${operation.operationId} does not expect any parameters. But a parameter is provided.`, parameters);
366
- }
367
- }
368
- else {
369
- throw new Error('The parameters object is not a record');
370
- }
371
- }
372
- }
373
- /**
374
- * Validates the http response against the schema specified in the operation object
375
- *
376
- * @param operation
377
- * @param response
378
- * @param strict
379
- * @protected
380
- */
381
- validateResponse(operation, response, strict = false) {
382
- // region only validate the response if the content type is undefined or json like
383
- const contentType = response.headers.get('Content-Type');
384
- if (contentType && !contentType.match(/^application\/(.+\+)?json/)) {
385
- if (isDevMode()) {
386
- console.warn('Response validation is only supported for content types that are json like.');
387
- }
388
- return;
389
- }
390
- // endregion
391
- if (operation.responses) {
392
- const status = response.status;
393
- // region extract the response object based on the response status
394
- let responseObject;
395
- if (operation.responses[status]) {
396
- responseObject = operation.responses[status];
397
- }
398
- else {
399
- // use the default response object if no matching was found.
400
- responseObject = operation.responses['default'];
401
- }
402
- // endregion
403
- if (responseObject) {
404
- if (IsReferenceObject(responseObject)) {
405
- throw new RxapOpenApiError('Found a reference object. The operation config is not expand!');
406
- }
407
- // region validate the response against the schema if defined
408
- // TODO : create schema that validates all parameters at once
409
- if (hasJsonContentSchema(responseObject)) {
410
- const schema = getJsonContentSchema(responseObject);
411
- if (schema) {
412
- const data = response.body ?? response.data;
413
- if (!this.validate(schema, data)) {
414
- this.validationError('The response is not valid ageist the operation schema!', strict, schema, data);
415
- }
416
- }
417
- }
418
- // endregion
419
- }
420
- }
421
- }
422
- validateRequestBody(operation, body, strict = false) {
423
- // only validate body if type of object
424
- if (typeof body !== 'object') {
425
- return;
426
- }
427
- if (operation.requestBody) {
428
- if (IsReferenceObject(operation.requestBody)) {
429
- throw new RxapOpenApiError('Found a reference object. The operation config is not expand!');
430
- }
431
- if (body === undefined && operation.requestBody.required) {
432
- this.validationError('The request body is required!', strict);
433
- }
434
- if (hasJsonContentSchema(operation.requestBody)) {
435
- const schema = getJsonContentSchema(operation.requestBody);
436
- if (schema) {
437
- if (!this.validate(schema, body)) {
438
- this.validationError('The request body is not valid!', strict, schema, body);
439
- }
440
- }
441
- }
442
- }
443
- }
444
- validationError(message, strict, schema, value) {
445
- if (isDevMode() && schema !== undefined) {
446
- console.debug(message, {
447
- schema,
448
- value,
449
- });
450
- }
451
- if (strict || SchemaValidationMixin.STRICT) {
452
- throw new RxapOpenApiError(message, '', 'SchemaValidationMixin');
453
- }
454
- else {
455
- console.warn(message);
456
- }
457
- }
458
- buildHttpParams(operationParameters, parameters, ignoreUndefined = true) {
459
- let params = new HttpParams();
460
- if (IsRecord(parameters)) {
461
- for (const parameter of operationParameters.filter(p => p.in === 'query')) {
462
- const parameterName = parameter.name;
463
- if (parameters.hasOwnProperty(parameter.name)) {
464
- const value = parameters[parameter.name];
465
- if (value === undefined && ignoreUndefined) {
466
- continue;
467
- }
468
- if (Array.isArray(value)) {
469
- if (value.length) {
470
- const first = value.shift();
471
- params = params.set(parameterName, typeof first === 'object' ? JSON.stringify(first) : first);
472
- for (const item of value) {
473
- params = params.append(parameterName, typeof item === 'object' ? JSON.stringify(item) : item);
474
- }
475
- }
476
- }
477
- else {
478
- params = params.set(parameter.name, typeof value === 'object' ? JSON.stringify(value) : value);
479
- }
480
- }
481
- }
482
- }
483
- return params;
484
- }
485
- buildHttpHeaders(operationParameters, parameters) {
486
- const headers = {};
487
- if (IsRecord(parameters)) {
488
- for (const parameter of operationParameters.filter((p) => p.in === 'header')) {
489
- if (parameters.hasOwnProperty(parameter.name)) {
490
- const value = parameters[parameter.name];
491
- if (Array.isArray(value)) {
492
- if (value.length) {
493
- if (value.length === 1) {
494
- const first = value.shift();
495
- headers[parameter.name] =
496
- typeof first === 'object' ? JSON.stringify(first) : first;
497
- }
498
- else {
499
- headers[parameter.name] = value.map((item) => typeof item === 'object' ? JSON.stringify(item) : item);
500
- }
501
- }
502
- }
503
- else {
504
- headers[parameter.name] =
505
- typeof value === 'object' ? JSON.stringify(value) : value;
506
- }
507
- }
508
- }
509
- }
510
- return new HttpHeaders(headers);
511
- }
512
- buildHttpPathParams(operationParameters, parameters) {
513
- const pathParams = {};
514
- if (IsRecord(parameters)) {
515
- for (const parameter of operationParameters.filter(p => p.in === 'path')) {
516
- if (parameter.name in parameters) {
517
- pathParams[parameter.name] = this.normalizePathParamValue(parameters[parameter.name], parameter.name);
518
- }
519
- }
520
- }
521
- return pathParams;
522
- }
523
- normalizePathParamValue(value, paramName) {
524
- if (!value) {
525
- throw new Error(`The path parameter '${paramName}' is empty or undefined!`);
526
- }
527
- if (Array.isArray(value)) {
528
- if (value.length === 0) {
529
- throw new Error(`The path parameter '${paramName}' is an empty array!`);
530
- }
531
- return value.map((item, index) => this.normalizePathParamValue(item, `${paramName}[${index}]`)).join('/');
532
- }
533
- else if (typeof value === 'object') {
534
- return encodeURIComponent(JSON.stringify(value));
535
- }
536
- else if (typeof value === `string`) {
537
- return encodeURIComponent(value);
538
- }
539
- return value.toString();
540
- }
541
- /**
542
- * Converts open api parameters into the corresponding http options to
543
- * create a http request. The transformation is guided by the openapi definition
544
- *
545
- * @param operation
546
- * @param parameters
547
- * @param requestBody
548
- * @param ignoreUndefined
549
- */
550
- buildHttpOptions(operation, parameters, requestBody, ignoreUndefined = true) {
551
- const options = {};
552
- const operationParameters = coerceArray(operation.parameters);
553
- if (!NotContainsReferenceObjects(operationParameters)) {
554
- throw new RxapOpenApiError('The operation parameters contains ReferenceObject!');
555
- }
556
- const params = this.buildHttpParams(operationParameters, parameters, ignoreUndefined);
557
- const headers = this.buildHttpHeaders(operationParameters, parameters);
558
- const pathParams = this.buildHttpPathParams(operationParameters, parameters);
559
- if (params.keys().length) {
560
- options.params = params;
561
- }
562
- if (headers.keys().length) {
563
- options.headers = headers;
564
- }
565
- if (Object.keys(pathParams).length) {
566
- options.pathParams = pathParams;
567
- }
568
- if (requestBody !== undefined) {
569
- const [body, contentType] = this.buildBody(operation, requestBody);
570
- if (body !== undefined) {
571
- options.body = body;
572
- if (contentType !== undefined) {
573
- options.headers ??= new HttpHeaders();
574
- options.headers.set('Content-Type', contentType);
575
- }
576
- }
577
- }
578
- return options;
579
- }
580
- buildBody(operation, requestBody) {
581
- const accept = [];
582
- if (operation.requestBody && !IsReferenceObject(operation.requestBody)) {
583
- if (operation.requestBody.content) {
584
- for (const contentType of Object.keys(operation.requestBody.content)) {
585
- accept.push(contentType);
586
- }
587
- }
588
- }
589
- if (!accept.length) {
590
- console.warn('No content type found for the request body! Omitting the body!');
591
- return [undefined, undefined];
592
- }
593
- if (accept.length > 1) {
594
- console.warn('Multiple content types found for the request body! Using the first one!');
595
- }
596
- const contentType = accept[0];
597
- switch (contentType) {
598
- case 'application/json':
599
- case 'application/ld+json':
600
- assertsObject(requestBody);
601
- return [requestBody, contentType];
602
- case 'application/x-www-form-urlencoded':
603
- assertsObject(requestBody);
604
- // eslint-disable-next-line no-case-declarations
605
- let params = new HttpParams();
606
- for (const [key, value] of Object.entries(requestBody)) {
607
- params = params.set(key, value);
608
- }
609
- return [params.toString(), contentType];
610
- case 'multipart/form-data':
611
- assertsObject(requestBody);
612
- // eslint-disable-next-line no-case-declarations
613
- const formData = new FormData();
614
- // Iterate through the JSON object and append each field to FormData
615
- for (const [key, value] of Object.entries(requestBody)) {
616
- formData.append(key, value);
617
- }
618
- return [formData, contentType];
619
- default:
620
- return [requestBody, contentType];
621
- }
622
- }
623
- validate(schema, value) {
624
- if (this.disableSchemaValidation) {
625
- return true;
626
- }
627
- if (typeof schema !== 'object') {
628
- throw new Error('The schema must be an object!');
629
- }
630
- if (!schema) {
631
- throw new Error('The schema must not be null or undefined!');
632
- }
633
- let result;
634
- const ajv = new Ajv();
635
- const validate = ajv.compile(schema);
636
- try {
637
- result = validate(value);
638
- }
639
- catch (e) {
640
- console.error(e.message);
641
- return false;
642
- }
643
- if (isPromiseLike(result)) {
644
- throw new Error('Async schema validation is not yet supported. Ensure the all refs in the openapi schema are internal!');
645
- }
646
- return result;
647
- }
256
+ const api = ConfigService.Get("api", {}, ConfigService.Config);
257
+ options.origin ??= environment.origin ?? location.origin;
258
+ options.load ??= environment.openApi?.load ?? false;
259
+ if (api.baseUrl) OpenApiConfigService.InsertServer({ url: api.baseUrl.match(/^https?:\/\//) ? api.baseUrl : JoinPath(options.origin, api.baseUrl) }, OpenApiConfigService.DefaultServerIndex);
260
+ for (const [serverId, config] of Object.entries(api)) if (config && typeof config === "object") {
261
+ const baseUrl = config.baseUrl;
262
+ if (baseUrl) {
263
+ const url = baseUrl.match(/^https?:\/\//) ? baseUrl : JoinPath(options.origin, baseUrl);
264
+ console.debug(`Add server '${serverId}' with url '${url}'`);
265
+ OpenApiConfigService.InsertServer({ url }, OpenApiConfigService.DefaultServerIndex, serverId);
266
+ }
267
+ }
268
+ if (options.load) return OpenApiConfigService.Load(typeof options.load === "object" ? options.load.openApiUrl : void 0);
648
269
  }
649
-
650
- // region
651
- // endregion
652
-
653
- /**
654
- * Generated bundle index. Do not edit.
655
- */
656
-
270
+ var SchemaValidationMixin = class SchemaValidationMixin {
271
+ static {
272
+ this.STRICT = false;
273
+ }
274
+ validateParameters(operation, parameters, strict = false) {
275
+ const operationParameters = coerceArray(operation.parameters);
276
+ if (!NotContainsReferenceObjects(operationParameters)) throw new RxapOpenApiError("The operation parameters contains ReferenceObject!");
277
+ if (parameters === void 0) {
278
+ const requiredParameters = operationParameters.filter((parameter) => parameter.required && parameter.in !== "header");
279
+ if (requiredParameters.length) {
280
+ if (isDevMode()) console.debug("Some operation parameters are required!", requiredParameters.map((p) => p.name));
281
+ this.validationError("Some operation parameters are required!", strict);
282
+ }
283
+ } else if (IsRecord(parameters)) for (const parameter of operationParameters) {
284
+ if (parameter.required) {
285
+ if (parameter.in !== "header") {
286
+ if (!parameters.hasOwnProperty(parameter.name)) this.validationError(`The operation parameter '${parameter.name}' is required!`, strict);
287
+ }
288
+ }
289
+ if (parameter.schema) {
290
+ if (parameters.hasOwnProperty(parameter.name)) {
291
+ const value = parameters[parameter.name];
292
+ if (!this.validate(parameter.schema, value)) this.validationError(`The parameter '${parameter.name}' is not valid against the schema!`, strict, parameter.schema, value);
293
+ }
294
+ }
295
+ }
296
+ else if (operationParameters.length === 0 || operationParameters.every((op) => !op.required)) {
297
+ if (isDevMode()) console.warn(`The operation ${operation.operationId} does not expect any parameters. But a parameter is provided.`, parameters);
298
+ } else throw new Error("The parameters object is not a record");
299
+ }
300
+ validateResponse(operation, response, strict = false) {
301
+ const contentType = response.headers.get("Content-Type");
302
+ if (contentType && !contentType.match(/^application\/(.+\+)?json/)) {
303
+ if (isDevMode()) console.warn("Response validation is only supported for content types that are json like.");
304
+ return;
305
+ }
306
+ if (operation.responses) {
307
+ const status = response.status;
308
+ let responseObject;
309
+ if (operation.responses[status]) responseObject = operation.responses[status];
310
+ else responseObject = operation.responses["default"];
311
+ if (responseObject) {
312
+ if (IsReferenceObject(responseObject)) throw new RxapOpenApiError("Found a reference object. The operation config is not expand!");
313
+ if (hasJsonContentSchema(responseObject)) {
314
+ const schema = getJsonContentSchema(responseObject);
315
+ if (schema) {
316
+ const data = response.body ?? response.data;
317
+ if (!this.validate(schema, data)) this.validationError("The response is not valid ageist the operation schema!", strict, schema, data);
318
+ }
319
+ }
320
+ }
321
+ }
322
+ }
323
+ validateRequestBody(operation, body, strict = false) {
324
+ if (typeof body !== "object") return;
325
+ if (operation.requestBody) {
326
+ if (IsReferenceObject(operation.requestBody)) throw new RxapOpenApiError("Found a reference object. The operation config is not expand!");
327
+ if (body === void 0 && operation.requestBody.required) this.validationError("The request body is required!", strict);
328
+ if (hasJsonContentSchema(operation.requestBody)) {
329
+ const schema = getJsonContentSchema(operation.requestBody);
330
+ if (schema) {
331
+ if (!this.validate(schema, body)) this.validationError("The request body is not valid!", strict, schema, body);
332
+ }
333
+ }
334
+ }
335
+ }
336
+ validationError(message, strict, schema, value) {
337
+ if (isDevMode() && schema !== void 0) console.debug(message, {
338
+ schema,
339
+ value
340
+ });
341
+ if (strict || SchemaValidationMixin.STRICT) throw new RxapOpenApiError(message, "", "SchemaValidationMixin");
342
+ else console.warn(message);
343
+ }
344
+ buildHttpParams(operationParameters, parameters, ignoreUndefined = true) {
345
+ let params = new HttpParams();
346
+ if (IsRecord(parameters)) for (const parameter of operationParameters.filter((p) => p.in === "query")) {
347
+ const parameterName = parameter.name;
348
+ if (parameters.hasOwnProperty(parameter.name)) {
349
+ const value = parameters[parameter.name];
350
+ if (value === void 0 && ignoreUndefined) continue;
351
+ if (Array.isArray(value)) {
352
+ if (value.length) {
353
+ const first = value.shift();
354
+ params = params.set(parameterName, typeof first === "object" ? JSON.stringify(first) : first);
355
+ for (const item of value) params = params.append(parameterName, typeof item === "object" ? JSON.stringify(item) : item);
356
+ }
357
+ } else params = params.set(parameter.name, typeof value === "object" ? JSON.stringify(value) : value);
358
+ }
359
+ }
360
+ return params;
361
+ }
362
+ buildHttpHeaders(operationParameters, parameters) {
363
+ const headers = {};
364
+ if (IsRecord(parameters)) {
365
+ for (const parameter of operationParameters.filter((p) => p.in === "header")) if (parameters.hasOwnProperty(parameter.name)) {
366
+ const value = parameters[parameter.name];
367
+ if (Array.isArray(value)) {
368
+ if (value.length) {
369
+ if (value.length === 1) {
370
+ const first = value.shift();
371
+ headers[parameter.name] = typeof first === "object" ? JSON.stringify(first) : first;
372
+ } else headers[parameter.name] = value.map((item) => typeof item === "object" ? JSON.stringify(item) : item);
373
+ }
374
+ } else headers[parameter.name] = typeof value === "object" ? JSON.stringify(value) : value;
375
+ }
376
+ }
377
+ return new HttpHeaders(headers);
378
+ }
379
+ buildHttpPathParams(operationParameters, parameters) {
380
+ const pathParams = {};
381
+ if (IsRecord(parameters)) {
382
+ for (const parameter of operationParameters.filter((p) => p.in === "path")) if (parameter.name in parameters) pathParams[parameter.name] = this.normalizePathParamValue(parameters[parameter.name], parameter.name);
383
+ }
384
+ return pathParams;
385
+ }
386
+ normalizePathParamValue(value, paramName) {
387
+ if (!value) throw new Error(`The path parameter '${paramName}' is empty or undefined!`);
388
+ if (Array.isArray(value)) {
389
+ if (value.length === 0) throw new Error(`The path parameter '${paramName}' is an empty array!`);
390
+ return value.map((item, index) => this.normalizePathParamValue(item, `${paramName}[${index}]`)).join("/");
391
+ } else if (typeof value === "object") return encodeURIComponent(JSON.stringify(value));
392
+ else if (typeof value === `string`) return encodeURIComponent(value);
393
+ return value.toString();
394
+ }
395
+ buildHttpOptions(operation, parameters, requestBody, ignoreUndefined = true) {
396
+ const options = {};
397
+ const operationParameters = coerceArray(operation.parameters);
398
+ if (!NotContainsReferenceObjects(operationParameters)) throw new RxapOpenApiError("The operation parameters contains ReferenceObject!");
399
+ const params = this.buildHttpParams(operationParameters, parameters, ignoreUndefined);
400
+ const headers = this.buildHttpHeaders(operationParameters, parameters);
401
+ const pathParams = this.buildHttpPathParams(operationParameters, parameters);
402
+ if (params.keys().length) options.params = params;
403
+ if (headers.keys().length) options.headers = headers;
404
+ if (Object.keys(pathParams).length) options.pathParams = pathParams;
405
+ if (requestBody !== void 0) {
406
+ const [body, contentType] = this.buildBody(operation, requestBody);
407
+ if (body !== void 0) {
408
+ options.body = body;
409
+ if (contentType !== void 0) {
410
+ options.headers ??= new HttpHeaders();
411
+ options.headers.set("Content-Type", contentType);
412
+ }
413
+ }
414
+ }
415
+ return options;
416
+ }
417
+ buildBody(operation, requestBody) {
418
+ const accept = [];
419
+ if (operation.requestBody && !IsReferenceObject(operation.requestBody)) {
420
+ if (operation.requestBody.content) for (const contentType of Object.keys(operation.requestBody.content)) accept.push(contentType);
421
+ }
422
+ if (!accept.length) {
423
+ console.warn("No content type found for the request body! Omitting the body!");
424
+ return [void 0, void 0];
425
+ }
426
+ if (accept.length > 1) console.warn("Multiple content types found for the request body! Using the first one!");
427
+ const contentType = accept[0];
428
+ switch (contentType) {
429
+ case "application/json":
430
+ case "application/ld+json":
431
+ assertsObject(requestBody);
432
+ return [requestBody, contentType];
433
+ case "application/x-www-form-urlencoded":
434
+ assertsObject(requestBody);
435
+ let params = new HttpParams();
436
+ for (const [key, value] of Object.entries(requestBody)) params = params.set(key, value);
437
+ return [params.toString(), contentType];
438
+ case "multipart/form-data":
439
+ assertsObject(requestBody);
440
+ const formData = new FormData();
441
+ for (const [key, value] of Object.entries(requestBody)) formData.append(key, value);
442
+ return [formData, contentType];
443
+ default: return [requestBody, contentType];
444
+ }
445
+ }
446
+ validate(schema, value) {
447
+ if (this.disableSchemaValidation) return true;
448
+ if (typeof schema !== "object") throw new Error("The schema must be an object!");
449
+ if (!schema) throw new Error("The schema must not be null or undefined!");
450
+ let result;
451
+ const validate = new Ajv().compile(schema);
452
+ try {
453
+ result = validate(value);
454
+ } catch (e) {
455
+ console.error(e.message);
456
+ return false;
457
+ }
458
+ if (isPromiseLike(result)) throw new Error("Async schema validation is not yet supported. Ensure the all refs in the openapi schema are internal!");
459
+ return result;
460
+ }
461
+ };
657
462
  export { AssertOpenApiV3, DEFAULT_OPEN_API_DATA_SOURCE_META_DATA, DEFAULT_OPEN_API_REMOTE_METHOD_META_DATA, DISABLE_SCHEMA_VALIDATION, DISABLE_VALIDATION, IsOpenApiV3, IsReferenceObject, NotContainsReferenceObjects, OPEN_API_OPERATION, OPEN_API_OPERATION_ID, OPEN_API_SERVER_ID, OPEN_API_SERVER_INDEX, OpenApiConfigService, OpenApiHttpResponseError, OpenApiInit, RXAP_OPEN_API_CONFIG, RXAP_OPEN_API_STRICT_VALIDATOR, RxapOpenApiError, SchemaValidationMixin, getJsonContentSchema, getJsonSchema, hasJsonContentSchema, hasJsonSchema, injectOpenApiBaseUrlHttpInterceptorFn };
658
- //# sourceMappingURL=rxap-open-api.mjs.map
463
+
464
+ //# sourceMappingURL=rxap-open-api.mjs.map