httpsnippet-client-api 7.0.0-alpha.6 → 7.0.0-beta.3
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.
- package/dist/index.cjs +37 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +36 -10
- package/dist/index.js.map +1 -1
- package/package.json +6 -4
- package/src/index.ts +67 -12
- package/tsup.config.ts +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/index.ts
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/index.ts
|
|
2
2
|
var _codebuilder = require('@readme/httpsnippet/helpers/code-builder');
|
|
3
|
+
var _camelcase = require('camelcase'); var _camelcase2 = _interopRequireDefault(_camelcase);
|
|
3
4
|
var _contenttype = require('content-type'); var _contenttype2 = _interopRequireDefault(_contenttype);
|
|
4
5
|
var _oas = require('oas'); var _oas2 = _interopRequireDefault(_oas);
|
|
5
6
|
var _utils = require('oas/utils');
|
|
7
|
+
var _reserved2 = require('reserved2');
|
|
6
8
|
var _stringifyobject = require('stringify-object'); var _stringifyobject2 = _interopRequireDefault(_stringifyobject);
|
|
9
|
+
var registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;
|
|
10
|
+
function getProjectPrefixFromRegistryUUID(uri) {
|
|
11
|
+
const matches = uri.match(registryUUIDRegex);
|
|
12
|
+
if (!matches) {
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
return _optionalChain([matches, 'access', _ => _.groups, 'optionalAccess', _2 => _2.project]);
|
|
16
|
+
}
|
|
7
17
|
function stringify(obj, opts = {}) {
|
|
8
18
|
return _stringifyobject2.default.call(void 0, obj, { indent: " ", ...opts });
|
|
9
19
|
}
|
|
10
|
-
function buildAuthSnippet(authKey) {
|
|
20
|
+
function buildAuthSnippet(sdkVariable, authKey) {
|
|
11
21
|
if (Array.isArray(authKey)) {
|
|
12
22
|
const auth = [];
|
|
13
23
|
authKey.forEach((token, i) => {
|
|
@@ -16,9 +26,9 @@ function buildAuthSnippet(authKey) {
|
|
|
16
26
|
}
|
|
17
27
|
auth.push(`'${token.replace(/'/g, "\\'")}'`);
|
|
18
28
|
});
|
|
19
|
-
return
|
|
29
|
+
return `${sdkVariable}.auth(${auth.join(", ")});`;
|
|
20
30
|
}
|
|
21
|
-
return
|
|
31
|
+
return `${sdkVariable}.auth('${authKey.replace(/'/g, "\\'")}');`;
|
|
22
32
|
}
|
|
23
33
|
function getAuthSources(operation) {
|
|
24
34
|
const matchers = {
|
|
@@ -78,6 +88,18 @@ var client = {
|
|
|
78
88
|
`Unable to locate a matching operation in the supplied \`apiDefinition\` for: ${source.method} ${url}`
|
|
79
89
|
);
|
|
80
90
|
}
|
|
91
|
+
let sdkPackageName;
|
|
92
|
+
let sdkVariable;
|
|
93
|
+
if (opts.identifier) {
|
|
94
|
+
sdkPackageName = opts.identifier;
|
|
95
|
+
sdkVariable = _camelcase2.default.call(void 0, opts.identifier);
|
|
96
|
+
if (_reserved2.isReservedOrBuiltinsLC.call(void 0, sdkVariable)) {
|
|
97
|
+
sdkVariable = `_${sdkVariable}`;
|
|
98
|
+
}
|
|
99
|
+
} else {
|
|
100
|
+
sdkPackageName = getProjectPrefixFromRegistryUUID(opts.apiDefinitionUri);
|
|
101
|
+
sdkVariable = "sdk";
|
|
102
|
+
}
|
|
81
103
|
const operationSlugs = foundOperation.url.slugs;
|
|
82
104
|
const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);
|
|
83
105
|
const operationPathParameters = operation.getParameters().filter((param) => param.in === "path");
|
|
@@ -85,7 +107,7 @@ var client = {
|
|
|
85
107
|
const authData = [];
|
|
86
108
|
const authSources = getAuthSources(operation);
|
|
87
109
|
const { blank, push, join } = new (0, _codebuilder.CodeBuilder)({ indent: opts.indent || " " });
|
|
88
|
-
push(`
|
|
110
|
+
push(`import ${sdkVariable} from '@api/${sdkPackageName}';`);
|
|
89
111
|
blank();
|
|
90
112
|
const configData = [];
|
|
91
113
|
if ((apiDefinition.servers || []).length > 1) {
|
|
@@ -100,14 +122,14 @@ var client = {
|
|
|
100
122
|
let metadata = {};
|
|
101
123
|
Object.keys(queryObj).forEach((param) => {
|
|
102
124
|
if (authSources.query.includes(param)) {
|
|
103
|
-
authData.push(buildAuthSnippet(queryObj[param]));
|
|
125
|
+
authData.push(buildAuthSnippet(sdkVariable, queryObj[param]));
|
|
104
126
|
return;
|
|
105
127
|
}
|
|
106
128
|
metadata[param] = queryObj[param];
|
|
107
129
|
});
|
|
108
130
|
Object.keys(cookiesObj).forEach((cookie) => {
|
|
109
131
|
if (authSources.cookie.includes(cookie)) {
|
|
110
|
-
authData.push(buildAuthSnippet(cookiesObj[cookie]));
|
|
132
|
+
authData.push(buildAuthSnippet(sdkVariable, cookiesObj[cookie]));
|
|
111
133
|
return;
|
|
112
134
|
}
|
|
113
135
|
metadata[cookie] = cookiesObj[cookie];
|
|
@@ -131,14 +153,14 @@ var client = {
|
|
|
131
153
|
if (headerLower in authSources.header) {
|
|
132
154
|
const authScheme = authSources.header[headerLower];
|
|
133
155
|
if (authScheme === "*") {
|
|
134
|
-
authData.push(buildAuthSnippet(headers[header]));
|
|
156
|
+
authData.push(buildAuthSnippet(sdkVariable, headers[header]));
|
|
135
157
|
} else {
|
|
136
158
|
let authKey = headers[header].replace(`${authSources.header[headerLower]} `, "");
|
|
137
159
|
if (authScheme.toLowerCase() === "basic") {
|
|
138
160
|
authKey = Buffer.from(authKey, "base64").toString("ascii");
|
|
139
161
|
authKey = authKey.split(":");
|
|
140
162
|
}
|
|
141
|
-
authData.push(buildAuthSnippet(authKey));
|
|
163
|
+
authData.push(buildAuthSnippet(sdkVariable, authKey));
|
|
142
164
|
}
|
|
143
165
|
delete headers[header];
|
|
144
166
|
return;
|
|
@@ -154,7 +176,11 @@ var client = {
|
|
|
154
176
|
return;
|
|
155
177
|
}
|
|
156
178
|
}
|
|
157
|
-
|
|
179
|
+
if (["accept", "content-type"].includes(headerLower)) {
|
|
180
|
+
requestHeaders[headerLower] = headers[header];
|
|
181
|
+
} else {
|
|
182
|
+
requestHeaders[header] = headers[header];
|
|
183
|
+
}
|
|
158
184
|
});
|
|
159
185
|
if (Object.keys(requestHeaders).length > 0) {
|
|
160
186
|
metadata = Object.assign(metadata, requestHeaders);
|
|
@@ -205,7 +231,7 @@ var client = {
|
|
|
205
231
|
if (configData.length) {
|
|
206
232
|
push(configData.join("\n"));
|
|
207
233
|
}
|
|
208
|
-
push(
|
|
234
|
+
push(`${sdkVariable}.${accessor}(${args.join(", ")})`);
|
|
209
235
|
push(".then(({ data }) => console.log(data))", 1);
|
|
210
236
|
push(".catch(err => console.error(err));", 1);
|
|
211
237
|
return join();
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AAKA,SAAS,mBAAmB;AAC5B,OAAO,iBAAiB;AACxB,OAAO,SAAS;AAChB,SAAS,uBAAuB;AAChC,OAAO,qBAAqB;AAG5B,SAAS,UAAU,KAAU,OAAO,CAAC,GAAG;AACtC,SAAO,gBAAgB,KAAK,EAAE,QAAQ,MAAM,GAAG,KAAK,CAAC;A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Ac,EAAE,QAAQ,qBAAqB,MAAM,GAAG;AAC/F,mBAAO,SAAS,cAAc;AAAA,UAChC;AAEA,mBAAS,OAAO,QAAQ,WAAS;AAC/B,gBAAI,MAAM,UAAU;AAClB,mBAAK,MAAM,IAAI,IAAI,MAAM;AAAA,YAC3B,OAAO;AACL,mBAAK,MAAM,IAAI,IAAI,MAAM;AAAA,YAC3B;AAAA,UACF,CAAC;AAAA,QACH;AACA;AAAA,MAEF;AACE,YAAI,SAAS,MAAM;AACjB,iBAAO,SAAS;AAAA,QAClB;AAAA,IACJ;AAEA,UAAM,OAAO,CAAC;AAEd,UAAM,WAAW,UAAU,eAAe,EAAE,WAAW,KAAK,CAAC;AAI7D,UAAM,uBAAuB,OAAO,SAAS,eAAe,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,KAAK;AACpG,QAAI,OAAO,SAAS,aAAa;AAC/B,WAAK,KAAK,UAAU,MAAM,EAAE,qBAAqB,CAAC,CAAC;AAAA,IACrD;AAEA,QAAI,OAAO,KAAK,QAAQ,EAAE,SAAS,GAAG;AACpC,WAAK,KAAK,UAAU,UAAU,EAAE,qBAAqB,CAAC,CAAC;AAAA,IACzD;AAEA,QAAI,SAAS,QAAQ;AACnB,WAAK,SAAS,KAAK,IAAI,CAAC;AAAA,IAC1B;AAEA,QAAI,WAAW,QAAQ;AACrB,WAAK,WAAW,KAAK,IAAI,CAAC;AAAA,IAC5B;AAEA,SAAK,OAAO,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC,GAAG;AAC1C,SAAK,0CAA0C,CAAC;AAChD,SAAK,sCAAsC,CAAC;AAE5C,WAAO,KAAK;AAAA,EACd;AACF;AAEA,IAAO,cAAQ","sourcesContent":["import type { ReducedHelperObject } from '@readme/httpsnippet/helpers/reducer';\nimport type { Client } from '@readme/httpsnippet/targets';\nimport type Operation from 'oas/operation';\nimport type { HttpMethods, OASDocument } from 'oas/rmoas.types';\n\nimport { CodeBuilder } from '@readme/httpsnippet/helpers/code-builder';\nimport contentType from 'content-type';\nimport Oas from 'oas';\nimport { matchesMimeType } from 'oas/utils';\nimport stringifyObject from 'stringify-object';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringify(obj: any, opts = {}) {\n return stringifyObject(obj, { indent: ' ', ...opts });\n}\n\nfunction buildAuthSnippet(authKey: string | string[]) {\n // Auth key will be an array for Basic auth cases.\n if (Array.isArray(authKey)) {\n const auth: string[] = [];\n authKey.forEach((token, i) => {\n // If the token part is the last part of the key and it's empty, don't add it to the snippet.\n if (token.length === 0 && authKey.length > 1 && i === authKey.length - 1) {\n return;\n }\n\n auth.push(`'${token.replace(/'/g, \"\\\\'\")}'`);\n });\n\n return `sdk.auth(${auth.join(', ')});`;\n }\n\n return `sdk.auth('${authKey.replace(/'/g, \"\\\\'\")}');`;\n}\n\nfunction getAuthSources(operation: Operation) {\n const matchers: { cookie: string[]; header: Record<string, string>; query: string[] } = {\n header: {},\n query: [],\n cookie: [],\n };\n\n if (operation.getSecurity().length === 0) {\n return matchers;\n }\n\n Object.entries(operation.prepareSecurity()).forEach(([, schemes]) => {\n schemes.forEach(scheme => {\n if (scheme.type === 'http') {\n if (scheme.scheme === 'basic') {\n matchers.header.authorization = 'Basic';\n } else if (scheme.scheme === 'bearer') {\n matchers.header.authorization = 'Bearer';\n }\n } else if (scheme.type === 'oauth2') {\n matchers.header.authorization = 'Bearer';\n } else if (scheme.type === 'apiKey') {\n if (scheme.in === 'query') {\n matchers.query.push(scheme.name);\n } else if (scheme.in === 'header') {\n // The way that this asterisk header matcher works is that since this `apiKey` goes in a\n // named header (`scheme.name`) because the header is the key, we're matching against the\n // entire header -- counter to the way that the HTTP basic matcher above works where we\n // match and extract the API key from everything after `Basic ` in the `Authorization`\n // header.\n matchers.header[scheme.name.toLowerCase()] = '*';\n } else if (scheme.in === 'cookie') {\n matchers.cookie.push(scheme.name);\n }\n }\n });\n });\n\n return matchers;\n}\n\ninterface APIOptions {\n apiDefinition: OASDocument;\n apiDefinitionUri: string;\n escapeBrackets?: boolean;\n indent?: string | false;\n}\n\nconst client: Client<APIOptions> = {\n info: {\n key: 'api',\n title: 'API',\n link: 'https://npm.im/api',\n description: 'Automatic SDK generation from an OpenAPI definition.',\n extname: '.js',\n },\n convert: ({ cookiesObj, headersObj, postData, queryObj, url, ...source }, options) => {\n const opts = {\n ...options,\n } as APIOptions;\n\n if (!('apiDefinitionUri' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinitionUri` option supplied to it.');\n } else if (!('apiDefinition' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinition` option supplied to it.');\n }\n\n const method = source.method.toLowerCase() as HttpMethods;\n const oas = new Oas(opts.apiDefinition);\n const apiDefinition = oas.getDefinition();\n const foundOperation = oas.findOperation(url, method);\n if (!foundOperation) {\n throw new Error(\n `Unable to locate a matching operation in the supplied \\`apiDefinition\\` for: ${source.method} ${url}`,\n );\n }\n\n const operationSlugs = foundOperation.url.slugs;\n const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);\n const operationPathParameters = operation.getParameters().filter(param => param.in === 'path');\n const path = operation.path;\n const authData: string[] = [];\n const authSources = getAuthSources(operation);\n\n const { blank, push, join } = new CodeBuilder({ indent: opts.indent || ' ' });\n\n push(`const sdk = require('api')('${opts.apiDefinitionUri}');`);\n blank();\n\n // If we have multiple servers configured and our source URL differs from the stock URL that we\n // receive from our `oas` library then the URL either has server variables contained in it (that\n // don't match the defaults), or the OAS offers alternate server URLs and we should expose that\n // in the generated snippet.\n const configData = [];\n if ((apiDefinition.servers || []).length > 1) {\n const stockUrl = oas.url();\n const baseUrl = url.replace(path, '');\n if (baseUrl !== stockUrl) {\n const serverVars = oas.splitVariables(baseUrl);\n const serverUrl = serverVars ? oas.url(serverVars.selected, serverVars.variables) : baseUrl;\n\n configData.push(`sdk.server('${serverUrl}');`);\n }\n }\n\n let metadata: Record<string, string | string[]> = {};\n Object.keys(queryObj).forEach(param => {\n if (authSources.query.includes(param)) {\n authData.push(buildAuthSnippet(queryObj[param]));\n\n // If this query param is part of an auth source then we don't want it doubled up in the\n // snippet.\n return;\n }\n\n metadata[param] = queryObj[param];\n });\n\n Object.keys(cookiesObj).forEach(cookie => {\n if (authSources.cookie.includes(cookie)) {\n authData.push(buildAuthSnippet(cookiesObj[cookie]));\n\n // If this cookie is part of an auth source then we don't want it doubled up.\n return;\n }\n\n // Note that we may have the potential to overlap any cookie that also shares the name as\n // another metadata parameter. This problem is currently inherent to `api` and not this\n // snippet generator.\n metadata[cookie] = cookiesObj[cookie];\n });\n\n // If we have path parameters present we should add them into the metadata object.\n Array.from(Object.entries(operationSlugs)).forEach(([param, value]) => {\n // The keys in `operationSlugs` will always be prefixed with a `:` in the `oas` library so\n // we can safely do this substring here without asserting this context.\n const cleanedParam = param.substring(1);\n\n // If our incoming path slug out of `oas.findOperation()` has been sanitized and is missing\n // a hyphen, but there is a parameter in the OpenAPI definition that matches what our\n // hyphen-less slug is then we should use that for the snippet.\n const unsanitizedParam = operationPathParameters.find(p => {\n return p.name.includes('-') && p.name.replace(/-/g, '') === cleanedParam ? p.name : false;\n });\n\n if (unsanitizedParam) {\n metadata[unsanitizedParam.name] = value;\n } else {\n metadata[cleanedParam] = value;\n }\n });\n\n if (Object.keys(headersObj).length) {\n const headers = headersObj;\n const requestHeaders: ReducedHelperObject = {};\n\n Object.keys(headers).forEach(header => {\n // Headers in HTTPSnippet are case-insensitive so we need to add in some special handling to\n // make sure we're able to match them properly.\n const headerLower = header.toLowerCase();\n\n if (headerLower in authSources.header) {\n // If this header has been set up as an authentication header, let's remove it and add it\n // into our auth data so we can build up an `.auth()` snippet for the SDK.\n const authScheme = authSources.header[headerLower];\n if (authScheme === '*') {\n authData.push(buildAuthSnippet(headers[header]));\n } else {\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n let authKey = headers[header].replace(`${authSources.header[headerLower]} `, '');\n if (authScheme.toLowerCase() === 'basic') {\n authKey = Buffer.from(authKey, 'base64').toString('ascii');\n authKey = authKey.split(':');\n }\n\n authData.push(buildAuthSnippet(authKey));\n }\n\n delete headers[header];\n return;\n } else if (headerLower === 'content-type') {\n // `Content-Type` headers are automatically added within the SDK so we can filter them out\n // if they don't have parameters attached to them.\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n const parsedContentType = contentType.parse(headers[header]);\n if (!Object.keys(parsedContentType.parameters).length) {\n delete headers[header];\n return;\n }\n } else if (headerLower === 'accept') {\n // If the `Accept` header here is JSON-like header then we can remove it from the code\n // snippet because `api` natively supports and prioritizes JSON over any other mime type.\n if (matchesMimeType.json(headers[header] as string)) {\n delete headers[header];\n return;\n }\n }\n\n // If we haven't used our header anywhere else, or we've deleted it from the payload\n // because it'll be handled internally by `api` then we should add the lowercased version\n // of our header into the generated code snippet.\n requestHeaders[headerLower] = headers[header];\n });\n\n if (Object.keys(requestHeaders).length > 0) {\n metadata = Object.assign(metadata, requestHeaders);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let body: any;\n switch (postData.mimeType) {\n case 'application/x-www-form-urlencoded':\n body = postData.paramsObj;\n break;\n\n case 'application/json':\n if (postData.jsonObj) {\n body = postData.jsonObj;\n }\n break;\n\n case 'multipart/form-data':\n if (postData.params) {\n body = {};\n\n // If there's a `Content-Type` header present in the metadata, but it's for the\n // `multipart/form-data` request then dump it off the snippet. We shouldn't offload that\n // unnecessary bloat of multipart boundaries to the user, instead letting the SDK handle it\n // automatically.\n if ('content-type' in metadata && metadata['content-type'].indexOf('multipart/form-data') === 0) {\n delete metadata['content-type'];\n }\n\n postData.params.forEach(param => {\n if (param.fileName) {\n body[param.name] = param.fileName;\n } else {\n body[param.name] = param.value;\n }\n });\n }\n break;\n\n default:\n if (postData.text) {\n body = postData.text;\n }\n }\n\n const args = [];\n\n const accessor = operation.getOperationId({ camelCase: true });\n\n // If we're going to be rendering out body params and metadata we should cut their character\n // limit in half because we'll be rendering them in their own lines.\n const inlineCharacterLimit = typeof body !== 'undefined' && Object.keys(metadata).length > 0 ? 40 : 80;\n if (typeof body !== 'undefined') {\n args.push(stringify(body, { inlineCharacterLimit }));\n }\n\n if (Object.keys(metadata).length > 0) {\n args.push(stringify(metadata, { inlineCharacterLimit }));\n }\n\n if (authData.length) {\n push(authData.join('\\n'));\n }\n\n if (configData.length) {\n push(configData.join('\\n'));\n }\n\n push(`sdk.${accessor}(${args.join(', ')})`);\n push('.then(({ data }) => console.log(data))', 1);\n push('.catch(err => console.error(err));', 1);\n\n return join();\n },\n};\n\nexport default client;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AAKA,SAAS,mBAAmB;AAC5B,OAAO,eAAe;AACtB,OAAO,iBAAiB;AACxB,OAAO,SAAS;AAChB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,OAAO,qBAAqB;AAQ5B,IAAM,oBAAoB;AAK1B,SAAS,iCAAiC,KAAa;AACrD,QAAM,UAAU,IAAI,MAAM,iBAAiB;AAC3C,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,QAAQ;AACzB;AAGA,SAAS,UAAU,KAAU,OAAO,CAAC,GAAG;AACtC,SAAO,gBAAgB,KAAK,EAAE,QAAQ,MAAM,GAAG,KAAK,CAAC;AACvD;AAEA,SAAS,iBAAiB,aAAqB,SAA4B;AAEzE,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,OAAiB,CAAC;AACxB,YAAQ,QAAQ,CAAC,OAAO,MAAM;AAE5B,UAAI,MAAM,WAAW,KAAK,QAAQ,SAAS,KAAK,MAAM,QAAQ,SAAS,GAAG;AACxE;AAAA,MACF;AAEA,WAAK,KAAK,IAAI,MAAM,QAAQ,MAAM,KAAK,CAAC,GAAG;AAAA,IAC7C,CAAC;AAED,WAAO,GAAG,WAAW,SAAS,KAAK,KAAK,IAAI,CAAC;AAAA,EAC/C;AAEA,SAAO,GAAG,WAAW,UAAU,QAAQ,QAAQ,MAAM,KAAK,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EAAE,QAAQ,qBAAqB,MAAM,GAAG;AAC/F,mBAAO,SAAS,cAAc;AAAA,UAChC;AAEA,mBAAS,OAAO,QAAQ,WAAS;AAC/B,gBAAI,MAAM,UAAU;AAClB,mBAAK,MAAM,IAAI,IAAI,MAAM;AAAA,YAC3B,OAAO;AACL,mBAAK,MAAM,IAAI,IAAI,MAAM;AAAA,YAC3B;AAAA,UACF,CAAC;AAAA,QACH;AACA;AAAA,MAEF;AACE,YAAI,SAAS,MAAM;AACjB,iBAAO,SAAS;AAAA,QAClB;AAAA,IACJ;AAEA,UAAM,OAAO,CAAC;AAEd,UAAM,WAAW,UAAU,eAAe,EAAE,WAAW,KAAK,CAAC;AAI7D,UAAM,uBAAuB,OAAO,SAAS,eAAe,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,KAAK;AACpG,QAAI,OAAO,SAAS,aAAa;AAC/B,WAAK,KAAK,UAAU,MAAM,EAAE,qBAAqB,CAAC,CAAC;AAAA,IACrD;AAEA,QAAI,OAAO,KAAK,QAAQ,EAAE,SAAS,GAAG;AACpC,WAAK,KAAK,UAAU,UAAU,EAAE,qBAAqB,CAAC,CAAC;AAAA,IACzD;AAEA,QAAI,SAAS,QAAQ;AACnB,WAAK,SAAS,KAAK,IAAI,CAAC;AAAA,IAC1B;AAEA,QAAI,WAAW,QAAQ;AACrB,WAAK,WAAW,KAAK,IAAI,CAAC;AAAA,IAC5B;AAEA,SAAK,GAAG,WAAW,IAAI,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC,GAAG;AACrD,SAAK,0CAA0C,CAAC;AAChD,SAAK,sCAAsC,CAAC;AAE5C,WAAO,KAAK;AAAA,EACd;AACF;AAEA,IAAO,cAAQ","sourcesContent":["import type { ReducedHelperObject } from '@readme/httpsnippet/helpers/reducer';\nimport type { Client } from '@readme/httpsnippet/targets';\nimport type Operation from 'oas/operation';\nimport type { HttpMethods, OASDocument } from 'oas/rmoas.types';\n\nimport { CodeBuilder } from '@readme/httpsnippet/helpers/code-builder';\nimport camelCase from 'camelcase';\nimport contentType from 'content-type';\nimport Oas from 'oas';\nimport { matchesMimeType } from 'oas/utils';\nimport { isReservedOrBuiltinsLC } from 'reserved2';\nimport stringifyObject from 'stringify-object';\n\n/**\n * @note This regex also exists in `api/fetcher`.\n *\n * @example @petstore/v1.0#n6kvf10vakpemvplx\n * @example @petstore#n6kvf10vakpemvplx\n */\nconst registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;\n\n/**\n * @note This function also exists in `api/fetcher`.\n */\nfunction getProjectPrefixFromRegistryUUID(uri: string) {\n const matches = uri.match(registryUUIDRegex);\n if (!matches) {\n return undefined;\n }\n\n return matches.groups?.project;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringify(obj: any, opts = {}) {\n return stringifyObject(obj, { indent: ' ', ...opts });\n}\n\nfunction buildAuthSnippet(sdkVariable: string, authKey: string | string[]) {\n // Auth key will be an array for Basic auth cases.\n if (Array.isArray(authKey)) {\n const auth: string[] = [];\n authKey.forEach((token, i) => {\n // If the token part is the last part of the key and it's empty, don't add it to the snippet.\n if (token.length === 0 && authKey.length > 1 && i === authKey.length - 1) {\n return;\n }\n\n auth.push(`'${token.replace(/'/g, \"\\\\'\")}'`);\n });\n\n return `${sdkVariable}.auth(${auth.join(', ')});`;\n }\n\n return `${sdkVariable}.auth('${authKey.replace(/'/g, \"\\\\'\")}');`;\n}\n\nfunction getAuthSources(operation: Operation) {\n const matchers: { cookie: string[]; header: Record<string, string>; query: string[] } = {\n header: {},\n query: [],\n cookie: [],\n };\n\n if (operation.getSecurity().length === 0) {\n return matchers;\n }\n\n Object.entries(operation.prepareSecurity()).forEach(([, schemes]) => {\n schemes.forEach(scheme => {\n if (scheme.type === 'http') {\n if (scheme.scheme === 'basic') {\n matchers.header.authorization = 'Basic';\n } else if (scheme.scheme === 'bearer') {\n matchers.header.authorization = 'Bearer';\n }\n } else if (scheme.type === 'oauth2') {\n matchers.header.authorization = 'Bearer';\n } else if (scheme.type === 'apiKey') {\n if (scheme.in === 'query') {\n matchers.query.push(scheme.name);\n } else if (scheme.in === 'header') {\n // The way that this asterisk header matcher works is that since this `apiKey` goes in a\n // named header (`scheme.name`) because the header is the key, we're matching against the\n // entire header -- counter to the way that the HTTP basic matcher above works where we\n // match and extract the API key from everything after `Basic ` in the `Authorization`\n // header.\n matchers.header[scheme.name.toLowerCase()] = '*';\n } else if (scheme.in === 'cookie') {\n matchers.cookie.push(scheme.name);\n }\n }\n });\n });\n\n return matchers;\n}\n\ninterface APIOptions {\n apiDefinition: OASDocument;\n /**\n * The URI that is used to download this API definition from `npx api install`.\n *\n * @example @developers/v2.0#17273l2glm9fq4l5\n */\n apiDefinitionUri: string;\n escapeBrackets?: boolean;\n /**\n * The string to identify this SDK as. This is used in the `import sdk from '@api/<identifier>'`\n * sample as well as the the variable name we attach the SDK to.\n *\n * @example developers\n */\n identifier?: string;\n indent?: string | false;\n}\n\nconst client: Client<APIOptions> = {\n info: {\n key: 'api',\n title: 'API',\n link: 'https://npm.im/api',\n description: 'Automatic SDK generation from an OpenAPI definition.',\n extname: '.js',\n },\n convert: ({ cookiesObj, headersObj, postData, queryObj, url, ...source }, options) => {\n const opts = {\n ...options,\n } as APIOptions;\n\n if (!('apiDefinitionUri' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinitionUri` option supplied to it.');\n } else if (!('apiDefinition' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinition` option supplied to it.');\n }\n\n const method = source.method.toLowerCase() as HttpMethods;\n const oas = new Oas(opts.apiDefinition);\n const apiDefinition = oas.getDefinition();\n const foundOperation = oas.findOperation(url, method);\n if (!foundOperation) {\n throw new Error(\n `Unable to locate a matching operation in the supplied \\`apiDefinition\\` for: ${source.method} ${url}`,\n );\n }\n\n let sdkPackageName;\n let sdkVariable: string;\n if (opts.identifier) {\n sdkPackageName = opts.identifier;\n\n sdkVariable = camelCase(opts.identifier);\n if (isReservedOrBuiltinsLC(sdkVariable)) {\n // If this identifier is a reserved JS word then we should prefix it with an underscore so\n // this snippet can be valid code.\n sdkVariable = `_${sdkVariable}`;\n }\n } else {\n sdkPackageName = getProjectPrefixFromRegistryUUID(opts.apiDefinitionUri);\n sdkVariable = 'sdk';\n }\n\n const operationSlugs = foundOperation.url.slugs;\n const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);\n const operationPathParameters = operation.getParameters().filter(param => param.in === 'path');\n const path = operation.path;\n const authData: string[] = [];\n const authSources = getAuthSources(operation);\n\n const { blank, push, join } = new CodeBuilder({ indent: opts.indent || ' ' });\n\n push(`import ${sdkVariable} from '@api/${sdkPackageName}';`);\n blank();\n\n // If we have multiple servers configured and our source URL differs from the stock URL that we\n // receive from our `oas` library then the URL either has server variables contained in it (that\n // don't match the defaults), or the OAS offers alternate server URLs and we should expose that\n // in the generated snippet.\n const configData = [];\n if ((apiDefinition.servers || []).length > 1) {\n const stockUrl = oas.url();\n const baseUrl = url.replace(path, '');\n if (baseUrl !== stockUrl) {\n const serverVars = oas.splitVariables(baseUrl);\n const serverUrl = serverVars ? oas.url(serverVars.selected, serverVars.variables) : baseUrl;\n\n configData.push(`sdk.server('${serverUrl}');`);\n }\n }\n\n let metadata: Record<string, string | string[]> = {};\n Object.keys(queryObj).forEach(param => {\n if (authSources.query.includes(param)) {\n authData.push(buildAuthSnippet(sdkVariable, queryObj[param]));\n\n // If this query param is part of an auth source then we don't want it doubled up in the\n // snippet.\n return;\n }\n\n metadata[param] = queryObj[param];\n });\n\n Object.keys(cookiesObj).forEach(cookie => {\n if (authSources.cookie.includes(cookie)) {\n authData.push(buildAuthSnippet(sdkVariable, cookiesObj[cookie]));\n\n // If this cookie is part of an auth source then we don't want it doubled up.\n return;\n }\n\n // Note that we may have the potential to overlap any cookie that also shares the name as\n // another metadata parameter. This problem is currently inherent to `api` and not this\n // snippet generator.\n metadata[cookie] = cookiesObj[cookie];\n });\n\n // If we have path parameters present we should add them into the metadata object.\n Array.from(Object.entries(operationSlugs)).forEach(([param, value]) => {\n // The keys in `operationSlugs` will always be prefixed with a `:` in the `oas` library so\n // we can safely do this substring here without asserting this context.\n const cleanedParam = param.substring(1);\n\n // If our incoming path slug out of `oas.findOperation()` has been sanitized and is missing\n // a hyphen, but there is a parameter in the OpenAPI definition that matches what our\n // hyphen-less slug is then we should use that for the snippet.\n const unsanitizedParam = operationPathParameters.find(p => {\n return p.name.includes('-') && p.name.replace(/-/g, '') === cleanedParam ? p.name : false;\n });\n\n if (unsanitizedParam) {\n metadata[unsanitizedParam.name] = value;\n } else {\n metadata[cleanedParam] = value;\n }\n });\n\n if (Object.keys(headersObj).length) {\n const headers = headersObj;\n const requestHeaders: ReducedHelperObject = {};\n\n Object.keys(headers).forEach(header => {\n // Headers in HTTPSnippet are case-insensitive so we need to add in some special handling to\n // make sure we're able to match them properly.\n const headerLower = header.toLowerCase();\n\n if (headerLower in authSources.header) {\n // If this header has been set up as an authentication header, let's remove it and add it\n // into our auth data so we can build up an `.auth()` snippet for the SDK.\n const authScheme = authSources.header[headerLower];\n if (authScheme === '*') {\n authData.push(buildAuthSnippet(sdkVariable, headers[header]));\n } else {\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n let authKey = headers[header].replace(`${authSources.header[headerLower]} `, '');\n if (authScheme.toLowerCase() === 'basic') {\n authKey = Buffer.from(authKey, 'base64').toString('ascii');\n authKey = authKey.split(':');\n }\n\n authData.push(buildAuthSnippet(sdkVariable, authKey));\n }\n\n delete headers[header];\n return;\n } else if (headerLower === 'content-type') {\n // `Content-Type` headers are automatically added within the SDK so we can filter them out\n // if they don't have parameters attached to them.\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n const parsedContentType = contentType.parse(headers[header]);\n if (!Object.keys(parsedContentType.parameters).length) {\n delete headers[header];\n return;\n }\n } else if (headerLower === 'accept') {\n // If the `Accept` header here is JSON-like header then we can remove it from the code\n // snippet because `api` natively supports and prioritizes JSON over any other mime type.\n if (matchesMimeType.json(headers[header] as string)) {\n delete headers[header];\n return;\n }\n }\n\n // If we haven't used our header anywhere else, or we've deleted it from the payload\n // because it'll be handled internally by `api` then we should add it into our code snippet.\n if (['accept', 'content-type'].includes(headerLower)) {\n requestHeaders[headerLower] = headers[header];\n } else {\n // Non-reserved headers retain their casing because we want to generate a snippet that\n // matches the TS types that are created during codegeneration.\n requestHeaders[header] = headers[header];\n }\n });\n\n if (Object.keys(requestHeaders).length > 0) {\n metadata = Object.assign(metadata, requestHeaders);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let body: any;\n switch (postData.mimeType) {\n case 'application/x-www-form-urlencoded':\n body = postData.paramsObj;\n break;\n\n case 'application/json':\n if (postData.jsonObj) {\n body = postData.jsonObj;\n }\n break;\n\n case 'multipart/form-data':\n if (postData.params) {\n body = {};\n\n // If there's a `Content-Type` header present in the metadata, but it's for the\n // `multipart/form-data` request then dump it off the snippet. We shouldn't offload that\n // unnecessary bloat of multipart boundaries to the user, instead letting the SDK handle it\n // automatically.\n if ('content-type' in metadata && metadata['content-type'].indexOf('multipart/form-data') === 0) {\n delete metadata['content-type'];\n }\n\n postData.params.forEach(param => {\n if (param.fileName) {\n body[param.name] = param.fileName;\n } else {\n body[param.name] = param.value;\n }\n });\n }\n break;\n\n default:\n if (postData.text) {\n body = postData.text;\n }\n }\n\n const args = [];\n\n const accessor = operation.getOperationId({ camelCase: true });\n\n // If we're going to be rendering out body params and metadata we should cut their character\n // limit in half because we'll be rendering them in their own lines.\n const inlineCharacterLimit = typeof body !== 'undefined' && Object.keys(metadata).length > 0 ? 40 : 80;\n if (typeof body !== 'undefined') {\n args.push(stringify(body, { inlineCharacterLimit }));\n }\n\n if (Object.keys(metadata).length > 0) {\n args.push(stringify(metadata, { inlineCharacterLimit }));\n }\n\n if (authData.length) {\n push(authData.join('\\n'));\n }\n\n if (configData.length) {\n push(configData.join('\\n'));\n }\n\n push(`${sdkVariable}.${accessor}(${args.join(', ')})`);\n push('.then(({ data }) => console.log(data))', 1);\n push('.catch(err => console.error(err));', 1);\n\n return join();\n },\n};\n\nexport default client;\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -3,8 +3,20 @@ import { OASDocument } from 'oas/rmoas.types';
|
|
|
3
3
|
|
|
4
4
|
interface APIOptions {
|
|
5
5
|
apiDefinition: OASDocument;
|
|
6
|
+
/**
|
|
7
|
+
* The URI that is used to download this API definition from `npx api install`.
|
|
8
|
+
*
|
|
9
|
+
* @example @developers/v2.0#17273l2glm9fq4l5
|
|
10
|
+
*/
|
|
6
11
|
apiDefinitionUri: string;
|
|
7
12
|
escapeBrackets?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The string to identify this SDK as. This is used in the `import sdk from '@api/<identifier>'`
|
|
15
|
+
* sample as well as the the variable name we attach the SDK to.
|
|
16
|
+
*
|
|
17
|
+
* @example developers
|
|
18
|
+
*/
|
|
19
|
+
identifier?: string;
|
|
8
20
|
indent?: string | false;
|
|
9
21
|
}
|
|
10
22
|
declare const client: Client<APIOptions>;
|
package/dist/index.d.ts
CHANGED
|
@@ -3,8 +3,20 @@ import { OASDocument } from 'oas/rmoas.types';
|
|
|
3
3
|
|
|
4
4
|
interface APIOptions {
|
|
5
5
|
apiDefinition: OASDocument;
|
|
6
|
+
/**
|
|
7
|
+
* The URI that is used to download this API definition from `npx api install`.
|
|
8
|
+
*
|
|
9
|
+
* @example @developers/v2.0#17273l2glm9fq4l5
|
|
10
|
+
*/
|
|
6
11
|
apiDefinitionUri: string;
|
|
7
12
|
escapeBrackets?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The string to identify this SDK as. This is used in the `import sdk from '@api/<identifier>'`
|
|
15
|
+
* sample as well as the the variable name we attach the SDK to.
|
|
16
|
+
*
|
|
17
|
+
* @example developers
|
|
18
|
+
*/
|
|
19
|
+
identifier?: string;
|
|
8
20
|
indent?: string | false;
|
|
9
21
|
}
|
|
10
22
|
declare const client: Client<APIOptions>;
|
package/dist/index.js
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
2
|
import { CodeBuilder } from "@readme/httpsnippet/helpers/code-builder";
|
|
3
|
+
import camelCase from "camelcase";
|
|
3
4
|
import contentType from "content-type";
|
|
4
5
|
import Oas from "oas";
|
|
5
6
|
import { matchesMimeType } from "oas/utils";
|
|
7
|
+
import { isReservedOrBuiltinsLC } from "reserved2";
|
|
6
8
|
import stringifyObject from "stringify-object";
|
|
9
|
+
var registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;
|
|
10
|
+
function getProjectPrefixFromRegistryUUID(uri) {
|
|
11
|
+
const matches = uri.match(registryUUIDRegex);
|
|
12
|
+
if (!matches) {
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
return matches.groups?.project;
|
|
16
|
+
}
|
|
7
17
|
function stringify(obj, opts = {}) {
|
|
8
18
|
return stringifyObject(obj, { indent: " ", ...opts });
|
|
9
19
|
}
|
|
10
|
-
function buildAuthSnippet(authKey) {
|
|
20
|
+
function buildAuthSnippet(sdkVariable, authKey) {
|
|
11
21
|
if (Array.isArray(authKey)) {
|
|
12
22
|
const auth = [];
|
|
13
23
|
authKey.forEach((token, i) => {
|
|
@@ -16,9 +26,9 @@ function buildAuthSnippet(authKey) {
|
|
|
16
26
|
}
|
|
17
27
|
auth.push(`'${token.replace(/'/g, "\\'")}'`);
|
|
18
28
|
});
|
|
19
|
-
return
|
|
29
|
+
return `${sdkVariable}.auth(${auth.join(", ")});`;
|
|
20
30
|
}
|
|
21
|
-
return
|
|
31
|
+
return `${sdkVariable}.auth('${authKey.replace(/'/g, "\\'")}');`;
|
|
22
32
|
}
|
|
23
33
|
function getAuthSources(operation) {
|
|
24
34
|
const matchers = {
|
|
@@ -78,6 +88,18 @@ var client = {
|
|
|
78
88
|
`Unable to locate a matching operation in the supplied \`apiDefinition\` for: ${source.method} ${url}`
|
|
79
89
|
);
|
|
80
90
|
}
|
|
91
|
+
let sdkPackageName;
|
|
92
|
+
let sdkVariable;
|
|
93
|
+
if (opts.identifier) {
|
|
94
|
+
sdkPackageName = opts.identifier;
|
|
95
|
+
sdkVariable = camelCase(opts.identifier);
|
|
96
|
+
if (isReservedOrBuiltinsLC(sdkVariable)) {
|
|
97
|
+
sdkVariable = `_${sdkVariable}`;
|
|
98
|
+
}
|
|
99
|
+
} else {
|
|
100
|
+
sdkPackageName = getProjectPrefixFromRegistryUUID(opts.apiDefinitionUri);
|
|
101
|
+
sdkVariable = "sdk";
|
|
102
|
+
}
|
|
81
103
|
const operationSlugs = foundOperation.url.slugs;
|
|
82
104
|
const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);
|
|
83
105
|
const operationPathParameters = operation.getParameters().filter((param) => param.in === "path");
|
|
@@ -85,7 +107,7 @@ var client = {
|
|
|
85
107
|
const authData = [];
|
|
86
108
|
const authSources = getAuthSources(operation);
|
|
87
109
|
const { blank, push, join } = new CodeBuilder({ indent: opts.indent || " " });
|
|
88
|
-
push(`
|
|
110
|
+
push(`import ${sdkVariable} from '@api/${sdkPackageName}';`);
|
|
89
111
|
blank();
|
|
90
112
|
const configData = [];
|
|
91
113
|
if ((apiDefinition.servers || []).length > 1) {
|
|
@@ -100,14 +122,14 @@ var client = {
|
|
|
100
122
|
let metadata = {};
|
|
101
123
|
Object.keys(queryObj).forEach((param) => {
|
|
102
124
|
if (authSources.query.includes(param)) {
|
|
103
|
-
authData.push(buildAuthSnippet(queryObj[param]));
|
|
125
|
+
authData.push(buildAuthSnippet(sdkVariable, queryObj[param]));
|
|
104
126
|
return;
|
|
105
127
|
}
|
|
106
128
|
metadata[param] = queryObj[param];
|
|
107
129
|
});
|
|
108
130
|
Object.keys(cookiesObj).forEach((cookie) => {
|
|
109
131
|
if (authSources.cookie.includes(cookie)) {
|
|
110
|
-
authData.push(buildAuthSnippet(cookiesObj[cookie]));
|
|
132
|
+
authData.push(buildAuthSnippet(sdkVariable, cookiesObj[cookie]));
|
|
111
133
|
return;
|
|
112
134
|
}
|
|
113
135
|
metadata[cookie] = cookiesObj[cookie];
|
|
@@ -131,14 +153,14 @@ var client = {
|
|
|
131
153
|
if (headerLower in authSources.header) {
|
|
132
154
|
const authScheme = authSources.header[headerLower];
|
|
133
155
|
if (authScheme === "*") {
|
|
134
|
-
authData.push(buildAuthSnippet(headers[header]));
|
|
156
|
+
authData.push(buildAuthSnippet(sdkVariable, headers[header]));
|
|
135
157
|
} else {
|
|
136
158
|
let authKey = headers[header].replace(`${authSources.header[headerLower]} `, "");
|
|
137
159
|
if (authScheme.toLowerCase() === "basic") {
|
|
138
160
|
authKey = Buffer.from(authKey, "base64").toString("ascii");
|
|
139
161
|
authKey = authKey.split(":");
|
|
140
162
|
}
|
|
141
|
-
authData.push(buildAuthSnippet(authKey));
|
|
163
|
+
authData.push(buildAuthSnippet(sdkVariable, authKey));
|
|
142
164
|
}
|
|
143
165
|
delete headers[header];
|
|
144
166
|
return;
|
|
@@ -154,7 +176,11 @@ var client = {
|
|
|
154
176
|
return;
|
|
155
177
|
}
|
|
156
178
|
}
|
|
157
|
-
|
|
179
|
+
if (["accept", "content-type"].includes(headerLower)) {
|
|
180
|
+
requestHeaders[headerLower] = headers[header];
|
|
181
|
+
} else {
|
|
182
|
+
requestHeaders[header] = headers[header];
|
|
183
|
+
}
|
|
158
184
|
});
|
|
159
185
|
if (Object.keys(requestHeaders).length > 0) {
|
|
160
186
|
metadata = Object.assign(metadata, requestHeaders);
|
|
@@ -205,7 +231,7 @@ var client = {
|
|
|
205
231
|
if (configData.length) {
|
|
206
232
|
push(configData.join("\n"));
|
|
207
233
|
}
|
|
208
|
-
push(
|
|
234
|
+
push(`${sdkVariable}.${accessor}(${args.join(", ")})`);
|
|
209
235
|
push(".then(({ data }) => console.log(data))", 1);
|
|
210
236
|
push(".catch(err => console.error(err));", 1);
|
|
211
237
|
return join();
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { ReducedHelperObject } from '@readme/httpsnippet/helpers/reducer';\nimport type { Client } from '@readme/httpsnippet/targets';\nimport type Operation from 'oas/operation';\nimport type { HttpMethods, OASDocument } from 'oas/rmoas.types';\n\nimport { CodeBuilder } from '@readme/httpsnippet/helpers/code-builder';\nimport contentType from 'content-type';\nimport Oas from 'oas';\nimport { matchesMimeType } from 'oas/utils';\nimport stringifyObject from 'stringify-object';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringify(obj: any, opts = {}) {\n return stringifyObject(obj, { indent: ' ', ...opts });\n}\n\nfunction buildAuthSnippet(authKey: string | string[]) {\n // Auth key will be an array for Basic auth cases.\n if (Array.isArray(authKey)) {\n const auth: string[] = [];\n authKey.forEach((token, i) => {\n // If the token part is the last part of the key and it's empty, don't add it to the snippet.\n if (token.length === 0 && authKey.length > 1 && i === authKey.length - 1) {\n return;\n }\n\n auth.push(`'${token.replace(/'/g, \"\\\\'\")}'`);\n });\n\n return `sdk.auth(${auth.join(', ')});`;\n }\n\n return `sdk.auth('${authKey.replace(/'/g, \"\\\\'\")}');`;\n}\n\nfunction getAuthSources(operation: Operation) {\n const matchers: { cookie: string[]; header: Record<string, string>; query: string[] } = {\n header: {},\n query: [],\n cookie: [],\n };\n\n if (operation.getSecurity().length === 0) {\n return matchers;\n }\n\n Object.entries(operation.prepareSecurity()).forEach(([, schemes]) => {\n schemes.forEach(scheme => {\n if (scheme.type === 'http') {\n if (scheme.scheme === 'basic') {\n matchers.header.authorization = 'Basic';\n } else if (scheme.scheme === 'bearer') {\n matchers.header.authorization = 'Bearer';\n }\n } else if (scheme.type === 'oauth2') {\n matchers.header.authorization = 'Bearer';\n } else if (scheme.type === 'apiKey') {\n if (scheme.in === 'query') {\n matchers.query.push(scheme.name);\n } else if (scheme.in === 'header') {\n // The way that this asterisk header matcher works is that since this `apiKey` goes in a\n // named header (`scheme.name`) because the header is the key, we're matching against the\n // entire header -- counter to the way that the HTTP basic matcher above works where we\n // match and extract the API key from everything after `Basic ` in the `Authorization`\n // header.\n matchers.header[scheme.name.toLowerCase()] = '*';\n } else if (scheme.in === 'cookie') {\n matchers.cookie.push(scheme.name);\n }\n }\n });\n });\n\n return matchers;\n}\n\ninterface APIOptions {\n apiDefinition: OASDocument;\n apiDefinitionUri: string;\n escapeBrackets?: boolean;\n indent?: string | false;\n}\n\nconst client: Client<APIOptions> = {\n info: {\n key: 'api',\n title: 'API',\n link: 'https://npm.im/api',\n description: 'Automatic SDK generation from an OpenAPI definition.',\n extname: '.js',\n },\n convert: ({ cookiesObj, headersObj, postData, queryObj, url, ...source }, options) => {\n const opts = {\n ...options,\n } as APIOptions;\n\n if (!('apiDefinitionUri' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinitionUri` option supplied to it.');\n } else if (!('apiDefinition' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinition` option supplied to it.');\n }\n\n const method = source.method.toLowerCase() as HttpMethods;\n const oas = new Oas(opts.apiDefinition);\n const apiDefinition = oas.getDefinition();\n const foundOperation = oas.findOperation(url, method);\n if (!foundOperation) {\n throw new Error(\n `Unable to locate a matching operation in the supplied \\`apiDefinition\\` for: ${source.method} ${url}`,\n );\n }\n\n const operationSlugs = foundOperation.url.slugs;\n const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);\n const operationPathParameters = operation.getParameters().filter(param => param.in === 'path');\n const path = operation.path;\n const authData: string[] = [];\n const authSources = getAuthSources(operation);\n\n const { blank, push, join } = new CodeBuilder({ indent: opts.indent || ' ' });\n\n push(`const sdk = require('api')('${opts.apiDefinitionUri}');`);\n blank();\n\n // If we have multiple servers configured and our source URL differs from the stock URL that we\n // receive from our `oas` library then the URL either has server variables contained in it (that\n // don't match the defaults), or the OAS offers alternate server URLs and we should expose that\n // in the generated snippet.\n const configData = [];\n if ((apiDefinition.servers || []).length > 1) {\n const stockUrl = oas.url();\n const baseUrl = url.replace(path, '');\n if (baseUrl !== stockUrl) {\n const serverVars = oas.splitVariables(baseUrl);\n const serverUrl = serverVars ? oas.url(serverVars.selected, serverVars.variables) : baseUrl;\n\n configData.push(`sdk.server('${serverUrl}');`);\n }\n }\n\n let metadata: Record<string, string | string[]> = {};\n Object.keys(queryObj).forEach(param => {\n if (authSources.query.includes(param)) {\n authData.push(buildAuthSnippet(queryObj[param]));\n\n // If this query param is part of an auth source then we don't want it doubled up in the\n // snippet.\n return;\n }\n\n metadata[param] = queryObj[param];\n });\n\n Object.keys(cookiesObj).forEach(cookie => {\n if (authSources.cookie.includes(cookie)) {\n authData.push(buildAuthSnippet(cookiesObj[cookie]));\n\n // If this cookie is part of an auth source then we don't want it doubled up.\n return;\n }\n\n // Note that we may have the potential to overlap any cookie that also shares the name as\n // another metadata parameter. This problem is currently inherent to `api` and not this\n // snippet generator.\n metadata[cookie] = cookiesObj[cookie];\n });\n\n // If we have path parameters present we should add them into the metadata object.\n Array.from(Object.entries(operationSlugs)).forEach(([param, value]) => {\n // The keys in `operationSlugs` will always be prefixed with a `:` in the `oas` library so\n // we can safely do this substring here without asserting this context.\n const cleanedParam = param.substring(1);\n\n // If our incoming path slug out of `oas.findOperation()` has been sanitized and is missing\n // a hyphen, but there is a parameter in the OpenAPI definition that matches what our\n // hyphen-less slug is then we should use that for the snippet.\n const unsanitizedParam = operationPathParameters.find(p => {\n return p.name.includes('-') && p.name.replace(/-/g, '') === cleanedParam ? p.name : false;\n });\n\n if (unsanitizedParam) {\n metadata[unsanitizedParam.name] = value;\n } else {\n metadata[cleanedParam] = value;\n }\n });\n\n if (Object.keys(headersObj).length) {\n const headers = headersObj;\n const requestHeaders: ReducedHelperObject = {};\n\n Object.keys(headers).forEach(header => {\n // Headers in HTTPSnippet are case-insensitive so we need to add in some special handling to\n // make sure we're able to match them properly.\n const headerLower = header.toLowerCase();\n\n if (headerLower in authSources.header) {\n // If this header has been set up as an authentication header, let's remove it and add it\n // into our auth data so we can build up an `.auth()` snippet for the SDK.\n const authScheme = authSources.header[headerLower];\n if (authScheme === '*') {\n authData.push(buildAuthSnippet(headers[header]));\n } else {\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n let authKey = headers[header].replace(`${authSources.header[headerLower]} `, '');\n if (authScheme.toLowerCase() === 'basic') {\n authKey = Buffer.from(authKey, 'base64').toString('ascii');\n authKey = authKey.split(':');\n }\n\n authData.push(buildAuthSnippet(authKey));\n }\n\n delete headers[header];\n return;\n } else if (headerLower === 'content-type') {\n // `Content-Type` headers are automatically added within the SDK so we can filter them out\n // if they don't have parameters attached to them.\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n const parsedContentType = contentType.parse(headers[header]);\n if (!Object.keys(parsedContentType.parameters).length) {\n delete headers[header];\n return;\n }\n } else if (headerLower === 'accept') {\n // If the `Accept` header here is JSON-like header then we can remove it from the code\n // snippet because `api` natively supports and prioritizes JSON over any other mime type.\n if (matchesMimeType.json(headers[header] as string)) {\n delete headers[header];\n return;\n }\n }\n\n // If we haven't used our header anywhere else, or we've deleted it from the payload\n // because it'll be handled internally by `api` then we should add the lowercased version\n // of our header into the generated code snippet.\n requestHeaders[headerLower] = headers[header];\n });\n\n if (Object.keys(requestHeaders).length > 0) {\n metadata = Object.assign(metadata, requestHeaders);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let body: any;\n switch (postData.mimeType) {\n case 'application/x-www-form-urlencoded':\n body = postData.paramsObj;\n break;\n\n case 'application/json':\n if (postData.jsonObj) {\n body = postData.jsonObj;\n }\n break;\n\n case 'multipart/form-data':\n if (postData.params) {\n body = {};\n\n // If there's a `Content-Type` header present in the metadata, but it's for the\n // `multipart/form-data` request then dump it off the snippet. We shouldn't offload that\n // unnecessary bloat of multipart boundaries to the user, instead letting the SDK handle it\n // automatically.\n if ('content-type' in metadata && metadata['content-type'].indexOf('multipart/form-data') === 0) {\n delete metadata['content-type'];\n }\n\n postData.params.forEach(param => {\n if (param.fileName) {\n body[param.name] = param.fileName;\n } else {\n body[param.name] = param.value;\n }\n });\n }\n break;\n\n default:\n if (postData.text) {\n body = postData.text;\n }\n }\n\n const args = [];\n\n const accessor = operation.getOperationId({ camelCase: true });\n\n // If we're going to be rendering out body params and metadata we should cut their character\n // limit in half because we'll be rendering them in their own lines.\n const inlineCharacterLimit = typeof body !== 'undefined' && Object.keys(metadata).length > 0 ? 40 : 80;\n if (typeof body !== 'undefined') {\n args.push(stringify(body, { inlineCharacterLimit }));\n }\n\n if (Object.keys(metadata).length > 0) {\n args.push(stringify(metadata, { inlineCharacterLimit }));\n }\n\n if (authData.length) {\n push(authData.join('\\n'));\n }\n\n if (configData.length) {\n push(configData.join('\\n'));\n }\n\n push(`sdk.${accessor}(${args.join(', ')})`);\n push('.then(({ data }) => console.log(data))', 1);\n push('.catch(err => console.error(err));', 1);\n\n return join();\n },\n};\n\nexport default client;\n"],"mappings":";AAKA,SAAS,mBAAmB;AAC5B,OAAO,iBAAiB;AACxB,OAAO,SAAS;AAChB,SAAS,uBAAuB;AAChC,OAAO,qBAAqB;AAG5B,SAAS,UAAU,KAAU,OAAO,CAAC,GAAG;AACtC,SAAO,gBAAgB,KAAK,EAAE,QAAQ,MAAM,GAAG,KAAK,CAAC;AACvD;AAEA,SAAS,iBAAiB,SAA4B;AAEpD,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,OAAiB,CAAC;AACxB,YAAQ,QAAQ,CAAC,OAAO,MAAM;AAE5B,UAAI,MAAM,WAAW,KAAK,QAAQ,SAAS,KAAK,MAAM,QAAQ,SAAS,GAAG;AACxE;AAAA,MACF;AAEA,WAAK,KAAK,IAAI,MAAM,QAAQ,MAAM,KAAK,CAAC,GAAG;AAAA,IAC7C,CAAC;AAED,WAAO,YAAY,KAAK,KAAK,IAAI,CAAC;AAAA,EACpC;AAEA,SAAO,aAAa,QAAQ,QAAQ,MAAM,KAAK,CAAC;AAClD;AAEA,SAAS,eAAe,WAAsB;AAC5C,QAAM,W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AAS,eAAe,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,KAAK;AACpG,QAAI,OAAO,SAAS,aAAa;AAC/B,WAAK,KAAK,UAAU,MAAM,EAAE,qBAAqB,CAAC,CAAC;AAAA,IACrD;AAEA,QAAI,OAAO,KAAK,QAAQ,EAAE,SAAS,GAAG;AACpC,WAAK,KAAK,UAAU,UAAU,EAAE,qBAAqB,CAAC,CAAC;AAAA,IACzD;AAEA,QAAI,SAAS,QAAQ;AACnB,WAAK,SAAS,KAAK,IAAI,CAAC;AAAA,IAC1B;AAEA,QAAI,WAAW,QAAQ;AACrB,WAAK,WAAW,KAAK,IAAI,CAAC;AAAA,IAC5B;AAEA,SAAK,OAAO,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC,GAAG;AAC1C,SAAK,0CAA0C,CAAC;AAChD,SAAK,sCAAsC,CAAC;AAE5C,WAAO,KAAK;AAAA,EACd;AACF;AAEA,IAAO,cAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { ReducedHelperObject } from '@readme/httpsnippet/helpers/reducer';\nimport type { Client } from '@readme/httpsnippet/targets';\nimport type Operation from 'oas/operation';\nimport type { HttpMethods, OASDocument } from 'oas/rmoas.types';\n\nimport { CodeBuilder } from '@readme/httpsnippet/helpers/code-builder';\nimport camelCase from 'camelcase';\nimport contentType from 'content-type';\nimport Oas from 'oas';\nimport { matchesMimeType } from 'oas/utils';\nimport { isReservedOrBuiltinsLC } from 'reserved2';\nimport stringifyObject from 'stringify-object';\n\n/**\n * @note This regex also exists in `api/fetcher`.\n *\n * @example @petstore/v1.0#n6kvf10vakpemvplx\n * @example @petstore#n6kvf10vakpemvplx\n */\nconst registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;\n\n/**\n * @note This function also exists in `api/fetcher`.\n */\nfunction getProjectPrefixFromRegistryUUID(uri: string) {\n const matches = uri.match(registryUUIDRegex);\n if (!matches) {\n return undefined;\n }\n\n return matches.groups?.project;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringify(obj: any, opts = {}) {\n return stringifyObject(obj, { indent: ' ', ...opts });\n}\n\nfunction buildAuthSnippet(sdkVariable: string, authKey: string | string[]) {\n // Auth key will be an array for Basic auth cases.\n if (Array.isArray(authKey)) {\n const auth: string[] = [];\n authKey.forEach((token, i) => {\n // If the token part is the last part of the key and it's empty, don't add it to the snippet.\n if (token.length === 0 && authKey.length > 1 && i === authKey.length - 1) {\n return;\n }\n\n auth.push(`'${token.replace(/'/g, \"\\\\'\")}'`);\n });\n\n return `${sdkVariable}.auth(${auth.join(', ')});`;\n }\n\n return `${sdkVariable}.auth('${authKey.replace(/'/g, \"\\\\'\")}');`;\n}\n\nfunction getAuthSources(operation: Operation) {\n const matchers: { cookie: string[]; header: Record<string, string>; query: string[] } = {\n header: {},\n query: [],\n cookie: [],\n };\n\n if (operation.getSecurity().length === 0) {\n return matchers;\n }\n\n Object.entries(operation.prepareSecurity()).forEach(([, schemes]) => {\n schemes.forEach(scheme => {\n if (scheme.type === 'http') {\n if (scheme.scheme === 'basic') {\n matchers.header.authorization = 'Basic';\n } else if (scheme.scheme === 'bearer') {\n matchers.header.authorization = 'Bearer';\n }\n } else if (scheme.type === 'oauth2') {\n matchers.header.authorization = 'Bearer';\n } else if (scheme.type === 'apiKey') {\n if (scheme.in === 'query') {\n matchers.query.push(scheme.name);\n } else if (scheme.in === 'header') {\n // The way that this asterisk header matcher works is that since this `apiKey` goes in a\n // named header (`scheme.name`) because the header is the key, we're matching against the\n // entire header -- counter to the way that the HTTP basic matcher above works where we\n // match and extract the API key from everything after `Basic ` in the `Authorization`\n // header.\n matchers.header[scheme.name.toLowerCase()] = '*';\n } else if (scheme.in === 'cookie') {\n matchers.cookie.push(scheme.name);\n }\n }\n });\n });\n\n return matchers;\n}\n\ninterface APIOptions {\n apiDefinition: OASDocument;\n /**\n * The URI that is used to download this API definition from `npx api install`.\n *\n * @example @developers/v2.0#17273l2glm9fq4l5\n */\n apiDefinitionUri: string;\n escapeBrackets?: boolean;\n /**\n * The string to identify this SDK as. This is used in the `import sdk from '@api/<identifier>'`\n * sample as well as the the variable name we attach the SDK to.\n *\n * @example developers\n */\n identifier?: string;\n indent?: string | false;\n}\n\nconst client: Client<APIOptions> = {\n info: {\n key: 'api',\n title: 'API',\n link: 'https://npm.im/api',\n description: 'Automatic SDK generation from an OpenAPI definition.',\n extname: '.js',\n },\n convert: ({ cookiesObj, headersObj, postData, queryObj, url, ...source }, options) => {\n const opts = {\n ...options,\n } as APIOptions;\n\n if (!('apiDefinitionUri' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinitionUri` option supplied to it.');\n } else if (!('apiDefinition' in opts)) {\n throw new Error('This HTTP Snippet client must have an `apiDefinition` option supplied to it.');\n }\n\n const method = source.method.toLowerCase() as HttpMethods;\n const oas = new Oas(opts.apiDefinition);\n const apiDefinition = oas.getDefinition();\n const foundOperation = oas.findOperation(url, method);\n if (!foundOperation) {\n throw new Error(\n `Unable to locate a matching operation in the supplied \\`apiDefinition\\` for: ${source.method} ${url}`,\n );\n }\n\n let sdkPackageName;\n let sdkVariable: string;\n if (opts.identifier) {\n sdkPackageName = opts.identifier;\n\n sdkVariable = camelCase(opts.identifier);\n if (isReservedOrBuiltinsLC(sdkVariable)) {\n // If this identifier is a reserved JS word then we should prefix it with an underscore so\n // this snippet can be valid code.\n sdkVariable = `_${sdkVariable}`;\n }\n } else {\n sdkPackageName = getProjectPrefixFromRegistryUUID(opts.apiDefinitionUri);\n sdkVariable = 'sdk';\n }\n\n const operationSlugs = foundOperation.url.slugs;\n const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);\n const operationPathParameters = operation.getParameters().filter(param => param.in === 'path');\n const path = operation.path;\n const authData: string[] = [];\n const authSources = getAuthSources(operation);\n\n const { blank, push, join } = new CodeBuilder({ indent: opts.indent || ' ' });\n\n push(`import ${sdkVariable} from '@api/${sdkPackageName}';`);\n blank();\n\n // If we have multiple servers configured and our source URL differs from the stock URL that we\n // receive from our `oas` library then the URL either has server variables contained in it (that\n // don't match the defaults), or the OAS offers alternate server URLs and we should expose that\n // in the generated snippet.\n const configData = [];\n if ((apiDefinition.servers || []).length > 1) {\n const stockUrl = oas.url();\n const baseUrl = url.replace(path, '');\n if (baseUrl !== stockUrl) {\n const serverVars = oas.splitVariables(baseUrl);\n const serverUrl = serverVars ? oas.url(serverVars.selected, serverVars.variables) : baseUrl;\n\n configData.push(`sdk.server('${serverUrl}');`);\n }\n }\n\n let metadata: Record<string, string | string[]> = {};\n Object.keys(queryObj).forEach(param => {\n if (authSources.query.includes(param)) {\n authData.push(buildAuthSnippet(sdkVariable, queryObj[param]));\n\n // If this query param is part of an auth source then we don't want it doubled up in the\n // snippet.\n return;\n }\n\n metadata[param] = queryObj[param];\n });\n\n Object.keys(cookiesObj).forEach(cookie => {\n if (authSources.cookie.includes(cookie)) {\n authData.push(buildAuthSnippet(sdkVariable, cookiesObj[cookie]));\n\n // If this cookie is part of an auth source then we don't want it doubled up.\n return;\n }\n\n // Note that we may have the potential to overlap any cookie that also shares the name as\n // another metadata parameter. This problem is currently inherent to `api` and not this\n // snippet generator.\n metadata[cookie] = cookiesObj[cookie];\n });\n\n // If we have path parameters present we should add them into the metadata object.\n Array.from(Object.entries(operationSlugs)).forEach(([param, value]) => {\n // The keys in `operationSlugs` will always be prefixed with a `:` in the `oas` library so\n // we can safely do this substring here without asserting this context.\n const cleanedParam = param.substring(1);\n\n // If our incoming path slug out of `oas.findOperation()` has been sanitized and is missing\n // a hyphen, but there is a parameter in the OpenAPI definition that matches what our\n // hyphen-less slug is then we should use that for the snippet.\n const unsanitizedParam = operationPathParameters.find(p => {\n return p.name.includes('-') && p.name.replace(/-/g, '') === cleanedParam ? p.name : false;\n });\n\n if (unsanitizedParam) {\n metadata[unsanitizedParam.name] = value;\n } else {\n metadata[cleanedParam] = value;\n }\n });\n\n if (Object.keys(headersObj).length) {\n const headers = headersObj;\n const requestHeaders: ReducedHelperObject = {};\n\n Object.keys(headers).forEach(header => {\n // Headers in HTTPSnippet are case-insensitive so we need to add in some special handling to\n // make sure we're able to match them properly.\n const headerLower = header.toLowerCase();\n\n if (headerLower in authSources.header) {\n // If this header has been set up as an authentication header, let's remove it and add it\n // into our auth data so we can build up an `.auth()` snippet for the SDK.\n const authScheme = authSources.header[headerLower];\n if (authScheme === '*') {\n authData.push(buildAuthSnippet(sdkVariable, headers[header]));\n } else {\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n let authKey = headers[header].replace(`${authSources.header[headerLower]} `, '');\n if (authScheme.toLowerCase() === 'basic') {\n authKey = Buffer.from(authKey, 'base64').toString('ascii');\n authKey = authKey.split(':');\n }\n\n authData.push(buildAuthSnippet(sdkVariable, authKey));\n }\n\n delete headers[header];\n return;\n } else if (headerLower === 'content-type') {\n // `Content-Type` headers are automatically added within the SDK so we can filter them out\n // if they don't have parameters attached to them.\n // @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.\n const parsedContentType = contentType.parse(headers[header]);\n if (!Object.keys(parsedContentType.parameters).length) {\n delete headers[header];\n return;\n }\n } else if (headerLower === 'accept') {\n // If the `Accept` header here is JSON-like header then we can remove it from the code\n // snippet because `api` natively supports and prioritizes JSON over any other mime type.\n if (matchesMimeType.json(headers[header] as string)) {\n delete headers[header];\n return;\n }\n }\n\n // If we haven't used our header anywhere else, or we've deleted it from the payload\n // because it'll be handled internally by `api` then we should add it into our code snippet.\n if (['accept', 'content-type'].includes(headerLower)) {\n requestHeaders[headerLower] = headers[header];\n } else {\n // Non-reserved headers retain their casing because we want to generate a snippet that\n // matches the TS types that are created during codegeneration.\n requestHeaders[header] = headers[header];\n }\n });\n\n if (Object.keys(requestHeaders).length > 0) {\n metadata = Object.assign(metadata, requestHeaders);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let body: any;\n switch (postData.mimeType) {\n case 'application/x-www-form-urlencoded':\n body = postData.paramsObj;\n break;\n\n case 'application/json':\n if (postData.jsonObj) {\n body = postData.jsonObj;\n }\n break;\n\n case 'multipart/form-data':\n if (postData.params) {\n body = {};\n\n // If there's a `Content-Type` header present in the metadata, but it's for the\n // `multipart/form-data` request then dump it off the snippet. We shouldn't offload that\n // unnecessary bloat of multipart boundaries to the user, instead letting the SDK handle it\n // automatically.\n if ('content-type' in metadata && metadata['content-type'].indexOf('multipart/form-data') === 0) {\n delete metadata['content-type'];\n }\n\n postData.params.forEach(param => {\n if (param.fileName) {\n body[param.name] = param.fileName;\n } else {\n body[param.name] = param.value;\n }\n });\n }\n break;\n\n default:\n if (postData.text) {\n body = postData.text;\n }\n }\n\n const args = [];\n\n const accessor = operation.getOperationId({ camelCase: true });\n\n // If we're going to be rendering out body params and metadata we should cut their character\n // limit in half because we'll be rendering them in their own lines.\n const inlineCharacterLimit = typeof body !== 'undefined' && Object.keys(metadata).length > 0 ? 40 : 80;\n if (typeof body !== 'undefined') {\n args.push(stringify(body, { inlineCharacterLimit }));\n }\n\n if (Object.keys(metadata).length > 0) {\n args.push(stringify(metadata, { inlineCharacterLimit }));\n }\n\n if (authData.length) {\n push(authData.join('\\n'));\n }\n\n if (configData.length) {\n push(configData.join('\\n'));\n }\n\n push(`${sdkVariable}.${accessor}(${args.join(', ')})`);\n push('.then(({ data }) => console.log(data))', 1);\n push('.catch(err => console.error(err));', 1);\n\n return join();\n },\n};\n\nexport default client;\n"],"mappings":";AAKA,SAAS,mBAAmB;AAC5B,OAAO,eAAe;AACtB,OAAO,iBAAiB;AACxB,OAAO,SAAS;AAChB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,OAAO,qBAAqB;AAQ5B,IAAM,oBAAoB;AAK1B,SAAS,iCAAiC,KAAa;AACrD,QAAM,UAAU,IAAI,MAAM,iBAAiB;AAC3C,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,QAAQ;AACzB;AAGA,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E,qBAAqB,CAAC,CAAC;AAAA,IACzD;AAEA,QAAI,SAAS,QAAQ;AACnB,WAAK,SAAS,KAAK,IAAI,CAAC;AAAA,IAC1B;AAEA,QAAI,WAAW,QAAQ;AACrB,WAAK,WAAW,KAAK,IAAI,CAAC;AAAA,IAC5B;AAEA,SAAK,GAAG,WAAW,IAAI,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC,GAAG;AACrD,SAAK,0CAA0C,CAAC;AAChD,SAAK,sCAAsC,CAAC;AAE5C,WAAO,KAAK;AAAA,EACd;AACF;AAEA,IAAO,cAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "httpsnippet-client-api",
|
|
3
|
-
"version": "7.0.0-
|
|
3
|
+
"version": "7.0.0-beta.3",
|
|
4
4
|
"description": "An HTTPSnippet client for generating snippets for the `api` module.",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"type": "module",
|
|
@@ -36,8 +36,10 @@
|
|
|
36
36
|
"node": ">=18"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
+
"camelcase": "^8.0.0",
|
|
39
40
|
"content-type": "^1.0.5",
|
|
40
|
-
"
|
|
41
|
+
"reserved2": "^0.1.5",
|
|
42
|
+
"stringify-object": "^5.0.0"
|
|
41
43
|
},
|
|
42
44
|
"peerDependencies": {
|
|
43
45
|
"@readme/httpsnippet": ">=8",
|
|
@@ -47,11 +49,11 @@
|
|
|
47
49
|
"@readme/oas-examples": "^5.12.0",
|
|
48
50
|
"@readme/openapi-parser": "^2.5.0",
|
|
49
51
|
"@types/content-type": "^1.1.6",
|
|
50
|
-
"@types/stringify-object": "^
|
|
52
|
+
"@types/stringify-object": "^4.0.3",
|
|
51
53
|
"@vitest/coverage-v8": "^0.34.4",
|
|
52
54
|
"typescript": "^5.2.2",
|
|
53
55
|
"vitest": "^0.34.5"
|
|
54
56
|
},
|
|
55
57
|
"prettier": "@readme/eslint-config/prettier",
|
|
56
|
-
"gitHead": "
|
|
58
|
+
"gitHead": "9dbc86caab9ae4b49e7d0dac52ab6c25f5f46170"
|
|
57
59
|
}
|
package/src/index.ts
CHANGED
|
@@ -4,17 +4,39 @@ import type Operation from 'oas/operation';
|
|
|
4
4
|
import type { HttpMethods, OASDocument } from 'oas/rmoas.types';
|
|
5
5
|
|
|
6
6
|
import { CodeBuilder } from '@readme/httpsnippet/helpers/code-builder';
|
|
7
|
+
import camelCase from 'camelcase';
|
|
7
8
|
import contentType from 'content-type';
|
|
8
9
|
import Oas from 'oas';
|
|
9
10
|
import { matchesMimeType } from 'oas/utils';
|
|
11
|
+
import { isReservedOrBuiltinsLC } from 'reserved2';
|
|
10
12
|
import stringifyObject from 'stringify-object';
|
|
11
13
|
|
|
14
|
+
/**
|
|
15
|
+
* @note This regex also exists in `api/fetcher`.
|
|
16
|
+
*
|
|
17
|
+
* @example @petstore/v1.0#n6kvf10vakpemvplx
|
|
18
|
+
* @example @petstore#n6kvf10vakpemvplx
|
|
19
|
+
*/
|
|
20
|
+
const registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @note This function also exists in `api/fetcher`.
|
|
24
|
+
*/
|
|
25
|
+
function getProjectPrefixFromRegistryUUID(uri: string) {
|
|
26
|
+
const matches = uri.match(registryUUIDRegex);
|
|
27
|
+
if (!matches) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return matches.groups?.project;
|
|
32
|
+
}
|
|
33
|
+
|
|
12
34
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13
35
|
function stringify(obj: any, opts = {}) {
|
|
14
36
|
return stringifyObject(obj, { indent: ' ', ...opts });
|
|
15
37
|
}
|
|
16
38
|
|
|
17
|
-
function buildAuthSnippet(authKey: string | string[]) {
|
|
39
|
+
function buildAuthSnippet(sdkVariable: string, authKey: string | string[]) {
|
|
18
40
|
// Auth key will be an array for Basic auth cases.
|
|
19
41
|
if (Array.isArray(authKey)) {
|
|
20
42
|
const auth: string[] = [];
|
|
@@ -27,10 +49,10 @@ function buildAuthSnippet(authKey: string | string[]) {
|
|
|
27
49
|
auth.push(`'${token.replace(/'/g, "\\'")}'`);
|
|
28
50
|
});
|
|
29
51
|
|
|
30
|
-
return
|
|
52
|
+
return `${sdkVariable}.auth(${auth.join(', ')});`;
|
|
31
53
|
}
|
|
32
54
|
|
|
33
|
-
return
|
|
55
|
+
return `${sdkVariable}.auth('${authKey.replace(/'/g, "\\'")}');`;
|
|
34
56
|
}
|
|
35
57
|
|
|
36
58
|
function getAuthSources(operation: Operation) {
|
|
@@ -76,8 +98,20 @@ function getAuthSources(operation: Operation) {
|
|
|
76
98
|
|
|
77
99
|
interface APIOptions {
|
|
78
100
|
apiDefinition: OASDocument;
|
|
101
|
+
/**
|
|
102
|
+
* The URI that is used to download this API definition from `npx api install`.
|
|
103
|
+
*
|
|
104
|
+
* @example @developers/v2.0#17273l2glm9fq4l5
|
|
105
|
+
*/
|
|
79
106
|
apiDefinitionUri: string;
|
|
80
107
|
escapeBrackets?: boolean;
|
|
108
|
+
/**
|
|
109
|
+
* The string to identify this SDK as. This is used in the `import sdk from '@api/<identifier>'`
|
|
110
|
+
* sample as well as the the variable name we attach the SDK to.
|
|
111
|
+
*
|
|
112
|
+
* @example developers
|
|
113
|
+
*/
|
|
114
|
+
identifier?: string;
|
|
81
115
|
indent?: string | false;
|
|
82
116
|
}
|
|
83
117
|
|
|
@@ -110,6 +144,22 @@ const client: Client<APIOptions> = {
|
|
|
110
144
|
);
|
|
111
145
|
}
|
|
112
146
|
|
|
147
|
+
let sdkPackageName;
|
|
148
|
+
let sdkVariable: string;
|
|
149
|
+
if (opts.identifier) {
|
|
150
|
+
sdkPackageName = opts.identifier;
|
|
151
|
+
|
|
152
|
+
sdkVariable = camelCase(opts.identifier);
|
|
153
|
+
if (isReservedOrBuiltinsLC(sdkVariable)) {
|
|
154
|
+
// If this identifier is a reserved JS word then we should prefix it with an underscore so
|
|
155
|
+
// this snippet can be valid code.
|
|
156
|
+
sdkVariable = `_${sdkVariable}`;
|
|
157
|
+
}
|
|
158
|
+
} else {
|
|
159
|
+
sdkPackageName = getProjectPrefixFromRegistryUUID(opts.apiDefinitionUri);
|
|
160
|
+
sdkVariable = 'sdk';
|
|
161
|
+
}
|
|
162
|
+
|
|
113
163
|
const operationSlugs = foundOperation.url.slugs;
|
|
114
164
|
const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);
|
|
115
165
|
const operationPathParameters = operation.getParameters().filter(param => param.in === 'path');
|
|
@@ -119,7 +169,7 @@ const client: Client<APIOptions> = {
|
|
|
119
169
|
|
|
120
170
|
const { blank, push, join } = new CodeBuilder({ indent: opts.indent || ' ' });
|
|
121
171
|
|
|
122
|
-
push(`
|
|
172
|
+
push(`import ${sdkVariable} from '@api/${sdkPackageName}';`);
|
|
123
173
|
blank();
|
|
124
174
|
|
|
125
175
|
// If we have multiple servers configured and our source URL differs from the stock URL that we
|
|
@@ -141,7 +191,7 @@ const client: Client<APIOptions> = {
|
|
|
141
191
|
let metadata: Record<string, string | string[]> = {};
|
|
142
192
|
Object.keys(queryObj).forEach(param => {
|
|
143
193
|
if (authSources.query.includes(param)) {
|
|
144
|
-
authData.push(buildAuthSnippet(queryObj[param]));
|
|
194
|
+
authData.push(buildAuthSnippet(sdkVariable, queryObj[param]));
|
|
145
195
|
|
|
146
196
|
// If this query param is part of an auth source then we don't want it doubled up in the
|
|
147
197
|
// snippet.
|
|
@@ -153,7 +203,7 @@ const client: Client<APIOptions> = {
|
|
|
153
203
|
|
|
154
204
|
Object.keys(cookiesObj).forEach(cookie => {
|
|
155
205
|
if (authSources.cookie.includes(cookie)) {
|
|
156
|
-
authData.push(buildAuthSnippet(cookiesObj[cookie]));
|
|
206
|
+
authData.push(buildAuthSnippet(sdkVariable, cookiesObj[cookie]));
|
|
157
207
|
|
|
158
208
|
// If this cookie is part of an auth source then we don't want it doubled up.
|
|
159
209
|
return;
|
|
@@ -199,7 +249,7 @@ const client: Client<APIOptions> = {
|
|
|
199
249
|
// into our auth data so we can build up an `.auth()` snippet for the SDK.
|
|
200
250
|
const authScheme = authSources.header[headerLower];
|
|
201
251
|
if (authScheme === '*') {
|
|
202
|
-
authData.push(buildAuthSnippet(headers[header]));
|
|
252
|
+
authData.push(buildAuthSnippet(sdkVariable, headers[header]));
|
|
203
253
|
} else {
|
|
204
254
|
// @ts-expect-error `headers[header]` is typed improperly in HTTPSnippet.
|
|
205
255
|
let authKey = headers[header].replace(`${authSources.header[headerLower]} `, '');
|
|
@@ -208,7 +258,7 @@ const client: Client<APIOptions> = {
|
|
|
208
258
|
authKey = authKey.split(':');
|
|
209
259
|
}
|
|
210
260
|
|
|
211
|
-
authData.push(buildAuthSnippet(authKey));
|
|
261
|
+
authData.push(buildAuthSnippet(sdkVariable, authKey));
|
|
212
262
|
}
|
|
213
263
|
|
|
214
264
|
delete headers[header];
|
|
@@ -232,9 +282,14 @@ const client: Client<APIOptions> = {
|
|
|
232
282
|
}
|
|
233
283
|
|
|
234
284
|
// If we haven't used our header anywhere else, or we've deleted it from the payload
|
|
235
|
-
// because it'll be handled internally by `api` then we should add
|
|
236
|
-
|
|
237
|
-
|
|
285
|
+
// because it'll be handled internally by `api` then we should add it into our code snippet.
|
|
286
|
+
if (['accept', 'content-type'].includes(headerLower)) {
|
|
287
|
+
requestHeaders[headerLower] = headers[header];
|
|
288
|
+
} else {
|
|
289
|
+
// Non-reserved headers retain their casing because we want to generate a snippet that
|
|
290
|
+
// matches the TS types that are created during codegeneration.
|
|
291
|
+
requestHeaders[header] = headers[header];
|
|
292
|
+
}
|
|
238
293
|
});
|
|
239
294
|
|
|
240
295
|
if (Object.keys(requestHeaders).length > 0) {
|
|
@@ -306,7 +361,7 @@ const client: Client<APIOptions> = {
|
|
|
306
361
|
push(configData.join('\n'));
|
|
307
362
|
}
|
|
308
363
|
|
|
309
|
-
push(
|
|
364
|
+
push(`${sdkVariable}.${accessor}(${args.join(', ')})`);
|
|
310
365
|
push('.then(({ data }) => console.log(data))', 1);
|
|
311
366
|
push('.catch(err => console.error(err));', 1);
|
|
312
367
|
|
package/tsup.config.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
/* eslint-disable import/no-extraneous-dependencies, node/no-extraneous-import */
|
|
1
2
|
import type { Options } from 'tsup';
|
|
2
3
|
|
|
3
|
-
// eslint-disable-next-line import/no-extraneous-dependencies
|
|
4
4
|
import { defineConfig } from 'tsup';
|
|
5
5
|
|
|
6
6
|
// eslint-disable-next-line import/no-relative-packages
|