@kevinoid/openapi-transformers 0.1.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 (50) hide show
  1. package/LICENSE.txt +19 -0
  2. package/README.md +134 -0
  3. package/add-tag-to-operation-ids.js +60 -0
  4. package/add-x-ms-enum-name.js +96 -0
  5. package/add-x-ms-enum-value-names.js +142 -0
  6. package/additional-properties-to-object.js +35 -0
  7. package/additional-properties-to-unconstrained.js +115 -0
  8. package/any-of-null-to-nullable.js +50 -0
  9. package/assert-properties.js +56 -0
  10. package/binary-string-to-file.js +54 -0
  11. package/bool-enum-to-bool.js +100 -0
  12. package/clear-html-response-schema.js +77 -0
  13. package/client-params-to-global.js +97 -0
  14. package/const-to-enum.js +49 -0
  15. package/escape-enum-values.js +211 -0
  16. package/exclusive-min-max-to-bool.js +61 -0
  17. package/format-to-type.js +54 -0
  18. package/index.js +94 -0
  19. package/inline-non-object-schemas.js +120 -0
  20. package/lib/component-manager.js +60 -0
  21. package/lib/matching-component-manager.js +74 -0
  22. package/lib/matching-parameter-manager.js +36 -0
  23. package/merge-all-of.js +60 -0
  24. package/merge-any-of.js +48 -0
  25. package/merge-one-of.js +48 -0
  26. package/nullable-not-required.js +240 -0
  27. package/nullable-to-type-null.js +46 -0
  28. package/openapi31to30.js +54 -0
  29. package/package.json +131 -0
  30. package/path-parameters-to-operations.js +63 -0
  31. package/pattern-properties-to-additional-properties.js +62 -0
  32. package/queries-to-x-ms-paths.js +63 -0
  33. package/read-only-not-required.js +111 -0
  34. package/ref-path-parameters.js +73 -0
  35. package/remove-default-only-response-produces.js +58 -0
  36. package/remove-paths-with-servers.js +34 -0
  37. package/remove-query-from-paths.js +526 -0
  38. package/remove-ref-siblings.js +78 -0
  39. package/remove-request-body.js +102 -0
  40. package/remove-response-headers.js +42 -0
  41. package/remove-security-scheme-if.js +166 -0
  42. package/remove-type-if.js +65 -0
  43. package/rename-components.js +285 -0
  44. package/replaced-by-to-description.js +50 -0
  45. package/server-vars-to-path-params.js +224 -0
  46. package/server-vars-to-x-ms-parameterized-host.js +247 -0
  47. package/type-null-to-enum.js +47 -0
  48. package/type-null-to-nullable.js +57 -0
  49. package/urlencoded-to-string.js +160 -0
  50. package/x-enum-to-ms.js +92 -0
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @copyright Copyright 2019-2020 Kevin Locke <kevin@kevinlocke.name>
3
+ * @license MIT
4
+ * @module "openapi-transformers/server-vars-to-path-params.js"
5
+ */
6
+
7
+ import assert from 'node:assert';
8
+
9
+ // Note: Undocumented function which is part of the public API
10
+ // https://github.com/flitbit/json-ptr/issues/29
11
+ import { encodeUriFragmentIdentifier } from 'json-ptr';
12
+ import OpenApiTransformerBase from 'openapi-transformer-base';
13
+
14
+ import MatchingParameterManager from './lib/matching-parameter-manager.js';
15
+
16
+ /** Gets the longest common suffix of two strings.
17
+ *
18
+ * @private
19
+ */
20
+ function commonSuffix(s1, s2) {
21
+ let i = s1.length - 1;
22
+ for (let j = s2.length - 1; i >= 0 && j >= 0; i -= 1, j -= 1) {
23
+ if (s1[i] !== s2[j]) {
24
+ break;
25
+ }
26
+ }
27
+
28
+ return s1.slice(i + 1);
29
+ }
30
+
31
+ /** Get the path portion of a templated URL.
32
+ *
33
+ * @private
34
+ */
35
+ function getPath(url) {
36
+ // Note: url may be relative and lack scheme+authority
37
+ // Note: Can't use new URL() due to [/?#] in variable names
38
+ return url
39
+ // Remove scheme+authority, if present
40
+ .replace(/^(?:\{[^{}]*\}|[a-zA-Z_+.-])+:\/\/(?:\{[^{}]*\}|[^/{}])+/, '')
41
+ // Remove query or fragment, if present
42
+ .replace(/^((?:\{[^{}]*\}|[^{}?#])*)[?#].*$/, '$1');
43
+ }
44
+
45
+ /** Gets the common path segment suffix of the path part of all server URLs,
46
+ * containing at least one template expression.
47
+ *
48
+ * @private
49
+ */
50
+ function getCommonPathSuffix(servers) {
51
+ // Common suffix of path part of URLs (may be in middle of template expr)
52
+ const commonUrlSuffix = servers
53
+ .map((server) => getPath(server.url))
54
+ .reduce(commonSuffix);
55
+
56
+ // Smallest suffix of commonUrlSuffix which begins on a path segment
57
+ // (i.e. at beginning or after a slash) and includes all template exprs.
58
+ const match = /(?:^|\/)[^/]*(?:\{[^{}]*\}[^{}]*)+$/.exec(commonUrlSuffix);
59
+ return match ? match[0] : '';
60
+ }
61
+
62
+ function transformPaths(paths, serverPath, serverParams) {
63
+ return Object.keys(paths)
64
+ .reduce((newPaths, path) => {
65
+ const pathItem = paths[path];
66
+ const { parameters } = pathItem;
67
+ newPaths[serverPath + path] = {
68
+ parameters:
69
+ parameters ? [...serverParams, ...parameters] : serverParams,
70
+ ...pathItem,
71
+ };
72
+ return newPaths;
73
+ }, Object.create(Object.getPrototypeOf(paths)));
74
+ }
75
+
76
+ /**
77
+ * Transformer to convert Server Variables in path portion to Parameters on
78
+ * Path Item Objects for use with OpenAPI 2.
79
+ *
80
+ * TODO: Roll this into OpenAPI 3 -> 2 conversion?
81
+ */
82
+ export default class ServerVarsToPathParamsTransformer
83
+ extends OpenApiTransformerBase {
84
+ constructor({ omitDefault } = {}) {
85
+ super();
86
+
87
+ if (omitDefault !== undefined && !Array.isArray(omitDefault)) {
88
+ throw new TypeError('options.omitDefault must be an Array');
89
+ }
90
+
91
+ this.options = {
92
+ omitDefault: omitDefault || [],
93
+ };
94
+ }
95
+
96
+ transformOpenApi(spec) {
97
+ if (!spec || !spec.servers || spec.servers.length === 0) {
98
+ return spec;
99
+ }
100
+
101
+ const pathSuffix = getCommonPathSuffix(spec.servers);
102
+ if (!pathSuffix) {
103
+ return spec;
104
+ }
105
+
106
+ const pathSuffixVarNames = pathSuffix
107
+ .match(/\{[^{}]*\}/g)
108
+ .map((templateExpr) => templateExpr.slice(1, -1));
109
+
110
+ // Transform servers and get variables for common path suffix
111
+ let pathSuffixVars;
112
+ const newServers = spec.servers.map((server) => {
113
+ const newUrl = server.url.replace(pathSuffix, '');
114
+
115
+ // Separate path suffix variables from remaining server variables
116
+ const variables = server.variables || {};
117
+ let haveNewVars = false;
118
+ const newVars = {};
119
+ const suffixVars = {};
120
+ for (const varName of Object.keys(variables)) {
121
+ const variable = variables[varName];
122
+ if (pathSuffixVarNames.includes(varName)) {
123
+ // Variable in path suffix
124
+ if (this.options.omitDefault.includes(varName)
125
+ && Object.hasOwn(variable, 'default')) {
126
+ const newVariable = { ...variable };
127
+ delete newVariable.default;
128
+ suffixVars[varName] = newVariable;
129
+ } else {
130
+ suffixVars[varName] = variable;
131
+ }
132
+
133
+ // Check if variable is also in remaining server URL
134
+ if (newUrl.includes(`{${varName}}`)) {
135
+ haveNewVars = true;
136
+ newVars[varName] = variable;
137
+ }
138
+ } else {
139
+ haveNewVars = true;
140
+ newVars[varName] = variable;
141
+ }
142
+ }
143
+
144
+ if (pathSuffixVars === undefined) {
145
+ pathSuffixVars = suffixVars;
146
+ } else {
147
+ assert.deepStrictEqual(
148
+ pathSuffixVars,
149
+ suffixVars,
150
+ 'shared path variables must be the same in all servers',
151
+ );
152
+ }
153
+
154
+ const newServer = { ...server, url: newUrl };
155
+
156
+ if (haveNewVars) {
157
+ newServer.variables = newVars;
158
+ } else {
159
+ delete newServer.variables;
160
+ }
161
+
162
+ return newServer;
163
+ });
164
+
165
+ // Note: Autorest treats parameters defined globally as properties of the
166
+ // client, rather than the method, by default (which is what we want here).
167
+ // https://github.com/Azure/autorest/tree/master/docs/extensions#x-ms-parameter-location
168
+ let parameters, paramRefPrefix;
169
+ if (spec.openapi) {
170
+ parameters = { ...spec.components && spec.components.parameters };
171
+ paramRefPrefix = ['components', 'parameters'];
172
+ } else {
173
+ parameters = { ...spec.parameters };
174
+ paramRefPrefix = ['parameters'];
175
+ }
176
+ const paramManager = new MatchingParameterManager(parameters);
177
+
178
+ const serverParamRefs = Object.keys(pathSuffixVars).map((name) => {
179
+ const serverVar = pathSuffixVars[name];
180
+ const serverParam = {
181
+ name,
182
+ in: 'path',
183
+ required: true,
184
+ };
185
+ if (spec.openapi) {
186
+ serverParam.schema = {
187
+ type: 'string',
188
+ ...serverVar,
189
+ };
190
+
191
+ if (Object.hasOwn(serverVar, 'description')) {
192
+ serverParam.description = serverVar.description;
193
+ delete serverParam.schema.description;
194
+ }
195
+ } else {
196
+ serverParam.type = 'string';
197
+ Object.assign(serverParam, serverVar);
198
+ }
199
+
200
+ const defName = paramManager.add(serverParam, name);
201
+ return {
202
+ $ref: encodeUriFragmentIdentifier([...paramRefPrefix, defName]),
203
+ };
204
+ });
205
+
206
+ const newPathPrefix = pathSuffix.replace(/\/$/, '');
207
+ const newSpec = {
208
+ ...spec,
209
+ servers: newServers,
210
+ paths: transformPaths(spec.paths, newPathPrefix, serverParamRefs),
211
+ };
212
+
213
+ if (spec.openapi) {
214
+ newSpec.components = {
215
+ ...spec.components,
216
+ parameters,
217
+ };
218
+ } else {
219
+ newSpec.parameters = parameters;
220
+ }
221
+
222
+ return newSpec;
223
+ }
224
+ }
@@ -0,0 +1,247 @@
1
+ /**
2
+ * @copyright Copyright 2019-2020 Kevin Locke <kevin@kevinlocke.name>
3
+ * @license MIT
4
+ * @module "openapi-transformers/server-vars-to-x-ms-parameterized-host.js"
5
+ */
6
+
7
+ import OpenApiTransformerBase from 'openapi-transformer-base';
8
+ import visit from 'openapi-transformer-base/visit.js';
9
+
10
+ /** Gets the scheme and authority portions of a URL template.
11
+ *
12
+ * @private
13
+ */
14
+ function getSchemeAuthority(url) {
15
+ // Note: parameterized host may contain host and/or schema parameters.
16
+ // A single parameter may contain both schema and host.
17
+ // No way to disambiguate url like {schema}{host}{pathPrefix}.
18
+ // Assume the scheme+authority parts end at first slash following //
19
+ // (if present). (Note: protocol-relative url may start with //)
20
+ const match =
21
+ /^(?:(?:\{[^{}]*\}|[^/{}])*\/\/)?(?:\{[^{}]*\}|[^/{}])+/.exec(url);
22
+ return match && match[0];
23
+ }
24
+
25
+ function parseServerUrl(url) {
26
+ if (typeof url !== 'string') {
27
+ this.warn('Ignoring Server with non-string url', url);
28
+ return undefined;
29
+ }
30
+
31
+ const schemeAuth = getSchemeAuthority(url);
32
+ if (!schemeAuth) {
33
+ this.warn('Unable to determine scheme and authority for url', url);
34
+ return undefined;
35
+ }
36
+
37
+ // Remove non-templated scheme, if present
38
+ const hostTemplate = schemeAuth.replace(/^[a-zA-Z_+.-]+:\/\//, '');
39
+ if (!hostTemplate) {
40
+ this.warn('Unable to determine host for url', url);
41
+ return undefined;
42
+ }
43
+
44
+ const hostTemplateExprs = hostTemplate.match(/\{[^{}]*\}/g);
45
+ if (!hostTemplateExprs) {
46
+ this.warn('No template expressions in scheme and authority for url', url);
47
+ return undefined;
48
+ }
49
+
50
+ return {
51
+ hostTemplate,
52
+ // If non-templated scheme was removed, use the declared schemes
53
+ useSchemePrefix: hostTemplate !== schemeAuth,
54
+ hostTemplateVarNames: hostTemplateExprs
55
+ .map((templateExpr) => templateExpr.slice(1, -1)),
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Transformer to convert Server Variables in host portion to
61
+ * x-ms-parameterized-host for use with OpenAPI 2.
62
+ *
63
+ * https://github.com/Azure/autorest/tree/main/docs/extensions#x-ms-parameterized-host
64
+ *
65
+ * TODO: Roll this into OpenAPI 3 -> 2 conversion?
66
+ *
67
+ * Note: Currently expects OAS3 input (required for Server Objects) but
68
+ * produces OAS2 parameters as specified for x-ms-parameterized-host.
69
+ */
70
+ export default class ServerVarsToParamHostTransformer
71
+ extends OpenApiTransformerBase {
72
+ constructor({ omitDefault, parameter, xMsParameterizedHost } = {}) {
73
+ super();
74
+
75
+ if (omitDefault !== undefined && !Array.isArray(omitDefault)) {
76
+ throw new TypeError('options.omitDefault must be an Array');
77
+ }
78
+
79
+ if (parameter !== undefined
80
+ && (parameter === null
81
+ || typeof parameter !== 'object')) {
82
+ throw new TypeError('options.parameter must be a object');
83
+ }
84
+
85
+ if (xMsParameterizedHost !== undefined
86
+ && (xMsParameterizedHost === null
87
+ || typeof xMsParameterizedHost !== 'object')) {
88
+ throw new TypeError('options.xMsParameterizedHost must be a object');
89
+ }
90
+
91
+ this.options = {
92
+ omitDefault: omitDefault || [],
93
+ parameter,
94
+ xMsParameterizedHost,
95
+ };
96
+ }
97
+
98
+ transformServerVariableToParameter(serverVariable) {
99
+ if (serverVariable === null
100
+ || typeof serverVariable !== 'object'
101
+ || Array.isArray(serverVariable)) {
102
+ this.warn('Ignoring non-object Server Variable', serverVariable);
103
+ return undefined;
104
+ }
105
+
106
+ return {
107
+ name: undefined,
108
+ type: 'string',
109
+ ...serverVariable,
110
+ in: 'path',
111
+ required: true,
112
+ ...this.options.parameter,
113
+ };
114
+ }
115
+
116
+ transformServerVariablesToParameters(variables, varNames) {
117
+ if (variables === null
118
+ || typeof variables !== 'object'
119
+ || Array.isArray(variables)) {
120
+ this.warn('Ignoring non-object Map', variables);
121
+ return undefined;
122
+ }
123
+
124
+ const parameters = [];
125
+ for (const varName of varNames) {
126
+ const variable =
127
+ Object.hasOwn(variables, varName) ? variables[varName]
128
+ : undefined;
129
+ if (variable === undefined) {
130
+ this.warn('Unable to convert Server missing variable %j', varName);
131
+ return undefined;
132
+ }
133
+
134
+ const parameter = visit(
135
+ this,
136
+ this.transformServerVariableToParameter,
137
+ varName,
138
+ variable,
139
+ );
140
+ if (!parameter) {
141
+ return undefined;
142
+ }
143
+
144
+ parameter.name = varName;
145
+
146
+ if (this.options.omitDefault.includes(varName)
147
+ && Object.hasOwn(parameter, 'default')) {
148
+ delete parameter.default;
149
+ }
150
+
151
+ parameters.push(parameter);
152
+ }
153
+
154
+ return parameters;
155
+ }
156
+
157
+ transformServerToParameterizedHost(server) {
158
+ if (server === null
159
+ || typeof server !== 'object'
160
+ || Array.isArray(server)) {
161
+ this.warn('Ignoring non-object Server', server);
162
+ return undefined;
163
+ }
164
+
165
+ const { url, variables = {} } = server;
166
+
167
+ const urlParts = visit(this, parseServerUrl, 'url', url);
168
+ if (!urlParts) {
169
+ return undefined;
170
+ }
171
+
172
+ const {
173
+ hostTemplate,
174
+ useSchemePrefix,
175
+ hostTemplateVarNames,
176
+ } = urlParts;
177
+
178
+ const parameters = visit(
179
+ this,
180
+ this.transformServerVariablesToParameters,
181
+ 'variables',
182
+ variables,
183
+ hostTemplateVarNames,
184
+ );
185
+ if (!parameters) {
186
+ return undefined;
187
+ }
188
+
189
+ return {
190
+ hostTemplate,
191
+ useSchemePrefix,
192
+ parameters,
193
+ ...this.options.xMsParameterizedHost,
194
+ };
195
+ }
196
+
197
+ transformServersToParameterizedHost(servers) {
198
+ if (!Array.isArray(servers)) {
199
+ this.warn('Ignoring non-Array servers', servers);
200
+ return undefined;
201
+ }
202
+
203
+ if (servers.length === 0) {
204
+ this.warn('Ignoring empty servers', servers);
205
+ return undefined;
206
+ }
207
+
208
+ if (servers.length > 1) {
209
+ this.warn('Ignoring all but first server', servers);
210
+ }
211
+
212
+ return visit(
213
+ this,
214
+ this.transformServerToParameterizedHost,
215
+ '0',
216
+ servers[0],
217
+ );
218
+ }
219
+
220
+ transformOpenApi(openApi) {
221
+ if (openApi === null
222
+ || typeof openApi !== 'object'
223
+ || Array.isArray(openApi)) {
224
+ this.warn('Ignoring non-object OpenAPI', openApi);
225
+ return openApi;
226
+ }
227
+
228
+ if (openApi.servers === undefined) {
229
+ return openApi;
230
+ }
231
+
232
+ const parameterizedHost = visit(
233
+ this,
234
+ this.transformServersToParameterizedHost,
235
+ 'servers',
236
+ openApi.servers,
237
+ );
238
+ if (parameterizedHost === undefined) {
239
+ return openApi;
240
+ }
241
+
242
+ return {
243
+ ...openApi,
244
+ 'x-ms-parameterized-host': parameterizedHost,
245
+ };
246
+ }
247
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @copyright Copyright 2021 Kevin Locke <kevin@kevinlocke.name>
3
+ * @license MIT
4
+ * @module "openapi-transformers/type-null-to-enum.js"
5
+ */
6
+
7
+ import { isDeepStrictEqual } from 'node:util';
8
+
9
+ import OpenApiTransformerBase from 'openapi-transformer-base';
10
+
11
+ /**
12
+ * Transformer to convert Schema Objects with `type: 'null'` (as in OAS 3.1 and
13
+ * JSON Schema) to `enum: [null]` for OAS 3.0 and 2.0.
14
+ */
15
+ export default class TypeNullToEnumTransformer
16
+ extends OpenApiTransformerBase {
17
+ transformSchema(schema) {
18
+ const newSchema = super.transformSchema(schema);
19
+ if (newSchema === null
20
+ || typeof newSchema !== 'object'
21
+ || Array.isArray(newSchema)) {
22
+ return newSchema;
23
+ }
24
+
25
+ const { type } = newSchema;
26
+ if (type === 'null'
27
+ || (Array.isArray(type)
28
+ && type.length > 0
29
+ && type.every((t) => t === 'null'))) {
30
+ const { type: _, ...schemaNoType } = newSchema;
31
+ if (schemaNoType.enum === undefined) {
32
+ // eslint-disable-next-line unicorn/no-null
33
+ schemaNoType.enum = [null];
34
+ // eslint-disable-next-line unicorn/no-null
35
+ } else if (!isDeepStrictEqual(schemaNoType.enum, [null])) {
36
+ this.warn(
37
+ 'refusing to overwrite enum of schema with type: null',
38
+ newSchema,
39
+ );
40
+ }
41
+
42
+ return schemaNoType;
43
+ }
44
+
45
+ return newSchema;
46
+ }
47
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @copyright Copyright 2021 Kevin Locke <kevin@kevinlocke.name>
3
+ * @license MIT
4
+ * @module "openapi-transformers/type-null-to-nullable.js"
5
+ */
6
+
7
+ import OpenApiTransformerBase from 'openapi-transformer-base';
8
+
9
+ /**
10
+ * Transformer to convert Schema Objects with `'null'` in `type` (as in OAS
11
+ * 3.1 and JSON Schema) to `nullable: true`.
12
+ */
13
+ export default class TypeNullToNullableTransformer
14
+ extends OpenApiTransformerBase {
15
+ transformSchema(schema) {
16
+ const newSchema = super.transformSchema(schema);
17
+ if (newSchema === null
18
+ || typeof newSchema !== 'object'
19
+ || Array.isArray(newSchema)) {
20
+ return newSchema;
21
+ }
22
+
23
+ const { type } = newSchema;
24
+ if (!Array.isArray(type)) {
25
+ // Can't remove 'null' from non-Array type
26
+ // Note: See null-type-to-enum for handling `type: 'null'`
27
+ return newSchema;
28
+ }
29
+
30
+ const newType = type.filter((t) => t !== 'null');
31
+ if (newType.length === type.length) {
32
+ // type does not contain 'null'
33
+ return newSchema;
34
+ }
35
+
36
+ if (newType.length === 0) {
37
+ // Can't handle type with only 'null'
38
+ // Note: See null-type-to-enum for handling `type: 'null'`
39
+ return newSchema;
40
+ }
41
+
42
+ const { nullable } = newSchema;
43
+ if (nullable !== undefined && nullable !== true) {
44
+ this.warn(
45
+ 'schema with nullable: %o and type: null!?',
46
+ nullable,
47
+ newSchema,
48
+ );
49
+ }
50
+
51
+ return {
52
+ ...newSchema,
53
+ type: newType.length === 1 ? newType[0] : newType,
54
+ nullable: nullable === undefined ? true : nullable,
55
+ };
56
+ }
57
+ }