@devbie/apits 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -2
- package/bin/apits +4 -0
- package/dist/cjs/core/cli.d.ts +29 -0
- package/dist/cjs/core/cli.js +396 -0
- package/dist/cjs/core/generator.js +301 -0
- package/dist/cjs/core/writeRequestClient.js +93 -0
- package/dist/cjs/index.js +25 -0
- package/dist/cjs/types.js +90 -0
- package/dist/cjs/utils/console.js +79 -0
- package/dist/cjs/utils/getOutputPath.js +43 -0
- package/dist/cjs/utils/helpers.js +166 -0
- package/dist/cjs/utils/openApiToInterfaces.js +229 -0
- package/dist/cjs/utils/spinner.js +69 -0
- package/dist/cjs/utils/utils.d.ts +56 -0
- package/dist/cjs/utils/utils.js +355 -0
- package/dist/cjs/utils/vtilsLite.js +123 -0
- package/dist/esm/core/cli.d.mts +29 -0
- package/dist/esm/core/cli.mjs +713 -0
- package/dist/esm/core/generator.mjs +463 -0
- package/dist/esm/core/writeRequestClient.mjs +54 -0
- package/dist/esm/index.mjs +2 -0
- package/dist/esm/types.mjs +94 -0
- package/dist/esm/utils/console.mjs +65 -0
- package/dist/esm/utils/getOutputPath.mjs +12 -0
- package/dist/esm/utils/helpers.mjs +226 -0
- package/dist/esm/utils/openApiToInterfaces.mjs +326 -0
- package/dist/esm/utils/spinner.mjs +58 -0
- package/dist/esm/utils/utils.d.mts +56 -0
- package/dist/esm/utils/utils.mjs +545 -0
- package/dist/esm/utils/vtilsLite.mjs +142 -0
- package/package.json +68 -4
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5;
|
|
2
|
+
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
|
|
3
|
+
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
|
|
4
|
+
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
|
|
5
|
+
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
|
|
6
|
+
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
|
|
7
|
+
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
|
|
8
|
+
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
|
|
9
|
+
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
|
|
10
|
+
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
|
|
11
|
+
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
12
|
+
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
|
|
13
|
+
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
|
|
14
|
+
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
|
|
15
|
+
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
|
|
16
|
+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
17
|
+
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
|
|
18
|
+
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
|
|
19
|
+
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
|
20
|
+
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
|
|
21
|
+
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
|
|
22
|
+
import * as changeCase from "change-case";
|
|
23
|
+
import fs from "fs-extra";
|
|
24
|
+
import path from "path";
|
|
25
|
+
import yaml from "js-yaml";
|
|
26
|
+
import JSON5 from "json5";
|
|
27
|
+
import * as conso from "../utils/console.mjs";
|
|
28
|
+
import got from "got";
|
|
29
|
+
import { openApiToInterfaces } from "../utils/openApiToInterfaces.mjs";
|
|
30
|
+
import { dedent } from "../utils/vtilsLite.mjs";
|
|
31
|
+
import { RequestBodyType } from "../types.mjs";
|
|
32
|
+
import { getRequestDataJsonSchema, getResponseDataJsonSchema, jsonSchemaToTsCode, formatContent, topNotesContent } from "../utils/utils.mjs";
|
|
33
|
+
import { getOutputFilePath } from "../utils/getOutputPath.mjs";
|
|
34
|
+
import writeRequestClient from "./writeRequestClient.mjs";
|
|
35
|
+
// Default client import snippet placed at the top of generated files.
|
|
36
|
+
function defaultClientImportTemplate(config) {
|
|
37
|
+
return "import request from './request'";
|
|
38
|
+
}
|
|
39
|
+
var getDataKeySetStr = function getDataKeySetStr(method) {
|
|
40
|
+
if (["head", "option", "get"].includes(method.toLowerCase())) {
|
|
41
|
+
return "params: data";
|
|
42
|
+
}
|
|
43
|
+
return "data";
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// Replace `{param}` placeholders in the path with `${data.param}` so the
|
|
47
|
+
// request function can substitute path params from the incoming data object.
|
|
48
|
+
function handlePathParam(path) {
|
|
49
|
+
if (path.match(/\{(\w+)\}/)) {
|
|
50
|
+
// eslint-disable-next-line no-template-curly-in-string
|
|
51
|
+
return "`".concat(path.replace(/\{(\w+)\}/g, "${data.$1}"), "`");
|
|
52
|
+
}
|
|
53
|
+
return JSON.stringify(path);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Detect whether a generated request type has degraded to a primitive or
|
|
58
|
+
* empty shape. A well-formed request DTO is an object literal or interface
|
|
59
|
+
* reference; these signatures mean the backend did not expose a usable
|
|
60
|
+
* request body schema (missing `@ApiBody({type})`, inline `@Body()` type,
|
|
61
|
+
* or a Prisma type bound to `@Body()`), so the generator fell back to a
|
|
62
|
+
* primitive/empty type. Used to emit a warning so the author can fix the
|
|
63
|
+
* decorator rather than silently shipping `string`/`{}` to the frontend.
|
|
64
|
+
*/
|
|
65
|
+
function isDegradedRequestType(typeCode) {
|
|
66
|
+
// Collapse whitespace so shape-matching regexes are stable regardless of
|
|
67
|
+
// prettier's spacing choices.
|
|
68
|
+
var code = typeCode.replace(/\s+/g, " ").trim();
|
|
69
|
+
// Pull the right-hand side of `export type Name = <body>;`.
|
|
70
|
+
var match = code.match(/^export type \w+ = (.*?);?$/);
|
|
71
|
+
if (!match) return false;
|
|
72
|
+
var body = match[1].trim();
|
|
73
|
+
// Bare primitive / unknown (no body schema inferred at all).
|
|
74
|
+
if (/^(string|unknown|number|boolean|null)$/.test(body)) return true;
|
|
75
|
+
// Empty object literal (schema stripped to nothing).
|
|
76
|
+
if (/^\{\s*\}$/.test(body)) return true;
|
|
77
|
+
// Index signature only — no named fields, just `[k: string]: unknown`.
|
|
78
|
+
if (/^\{\s*\[\s*\w+\s*:\s*string\s*\]\s*:\s*unknown\s*\}$/.test(body)) return true;
|
|
79
|
+
// Path-param merge with a primitive fallback (`{ id: string } & string`).
|
|
80
|
+
if (/&\s*(string|unknown)\b/.test(body)) return true;
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
// Default type of the per-request `extra` argument; matches the config
|
|
84
|
+
// accepted by the scaffolded axios client.
|
|
85
|
+
var DEFAULT_CLIENT_CONFIG_TYPE = "AxiosRequestConfig";
|
|
86
|
+
|
|
87
|
+
// Default request function body template.
|
|
88
|
+
function defaultRequestFunctionTemplate(props, config) {
|
|
89
|
+
var baseURL = props.baseURL,
|
|
90
|
+
requestFunctionName = props.requestFunctionName,
|
|
91
|
+
requestDataTypeName = props.requestDataTypeName,
|
|
92
|
+
responseDataTypeName = props.responseDataTypeName,
|
|
93
|
+
extendedInterfaceInfo = props.extendedInterfaceInfo;
|
|
94
|
+
var clientConfigType = (config === null || config === void 0 ? void 0 : config.clientConfigType) || DEFAULT_CLIENT_CONFIG_TYPE;
|
|
95
|
+
var req_params = extendedInterfaceInfo.req_params,
|
|
96
|
+
req_query = extendedInterfaceInfo.req_query,
|
|
97
|
+
req_body_type = extendedInterfaceInfo.req_body_type,
|
|
98
|
+
req_body_multipart = extendedInterfaceInfo.req_body_multipart,
|
|
99
|
+
req_body_form = extendedInterfaceInfo.req_body_form;
|
|
100
|
+
var hasData = req_params.length || req_query.length || Array.isArray(req_body_form) && req_body_form.length;
|
|
101
|
+
var method = extendedInterfaceInfo.method.toLowerCase();
|
|
102
|
+
var finalBaseUrl = "";
|
|
103
|
+
if (baseURL !== null && baseURL !== void 0 && baseURL.match(/^\[code\]:/)) {
|
|
104
|
+
// A `[code]:` prefix means the string should be executed as a code
|
|
105
|
+
// snippet; otherwise it is treated as a literal string.
|
|
106
|
+
finalBaseUrl = baseURL.replace(/^\[code\]:/, "");
|
|
107
|
+
} else {
|
|
108
|
+
finalBaseUrl = "\"".concat(baseURL, "\"");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Form endpoints (multipart or url-encoded) must build a FormData /
|
|
112
|
+
// URLSearchParams at runtime so the underlying client (axios / fetch)
|
|
113
|
+
// auto-sets the correct Content-Type with boundary. Without this, POST
|
|
114
|
+
// form bodies are sent as JSON and the backend never receives the files.
|
|
115
|
+
var isForm = req_body_type === RequestBodyType.form;
|
|
116
|
+
var isMultipart = isForm && req_body_multipart === true;
|
|
117
|
+
var formBuilder = isForm ? "const form = new ".concat(isMultipart ? "FormData" : "URLSearchParams", "();\n Object.entries(data).forEach(([k, v]) => {\n if (v == null) return;\n if (Array.isArray(v)) v.forEach(i => form.append(k, ").concat(isMultipart ? "i" : "String(i)", "));\n else form.append(k, ").concat(isMultipart ? "v" : "String(v)", ");\n });") : "";
|
|
118
|
+
var dataExpr = isForm ? "data: form" : getDataKeySetStr(method);
|
|
119
|
+
return "export const ".concat(requestFunctionName, " = (data").concat(hasData ? "" : "?", ": ").concat(requestDataTypeName, ",extra?:".concat(clientConfigType), ") => {\n ").concat(formBuilder, "\n return request.").concat(method, "<").concat(requestDataTypeName, ",").concat(responseDataTypeName, ">(").concat(handlePathParam(extendedInterfaceInfo.path), ", {\n ").concat(dataExpr, ",\n ").concat(baseURL ? "baseURL: ".concat(finalBaseUrl, ",") : "", "\n ", "...extra", "\n })\n }");
|
|
120
|
+
}
|
|
121
|
+
export var Generator = /*#__PURE__*/function () {
|
|
122
|
+
function Generator(config) {
|
|
123
|
+
_classCallCheck(this, Generator);
|
|
124
|
+
/** Generator configuration. */
|
|
125
|
+
_defineProperty(this, "config", void 0);
|
|
126
|
+
// `config` may be an object or an array; store it as-is.
|
|
127
|
+
this.config = config;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Whether an input points to a remote http(s) resource. */
|
|
131
|
+
_createClass(Generator, [{
|
|
132
|
+
key: "parseSpecDocument",
|
|
133
|
+
value: /** Parse a raw JSON / JSON5 / YAML document string. */
|
|
134
|
+
function parseSpecDocument(raw) {
|
|
135
|
+
var head = raw.trimStart();
|
|
136
|
+
if (head.startsWith("{") || head.startsWith("[")) {
|
|
137
|
+
return JSON5.parse(raw);
|
|
138
|
+
}
|
|
139
|
+
return yaml.load(raw);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Load the OpenAPI document from a remote URL or a local file.
|
|
144
|
+
* Both JSON (.json/.json5) and YAML (.yaml/.yml) are supported.
|
|
145
|
+
*/
|
|
146
|
+
}, {
|
|
147
|
+
key: "loadSpec",
|
|
148
|
+
value: (function () {
|
|
149
|
+
var _loadSpec = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(input) {
|
|
150
|
+
var res, filePath, raw;
|
|
151
|
+
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
152
|
+
while (1) switch (_context.prev = _context.next) {
|
|
153
|
+
case 0:
|
|
154
|
+
if (!Generator.isHttpInput(input)) {
|
|
155
|
+
_context.next = 5;
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
_context.next = 3;
|
|
159
|
+
return got.get(input, {
|
|
160
|
+
responseType: "text"
|
|
161
|
+
});
|
|
162
|
+
case 3:
|
|
163
|
+
res = _context.sent;
|
|
164
|
+
return _context.abrupt("return", this.parseSpecDocument(res.body));
|
|
165
|
+
case 5:
|
|
166
|
+
filePath = path.resolve(input);
|
|
167
|
+
_context.next = 8;
|
|
168
|
+
return fs.readFile(filePath, "utf-8");
|
|
169
|
+
case 8:
|
|
170
|
+
raw = _context.sent;
|
|
171
|
+
return _context.abrupt("return", this.parseSpecDocument(raw));
|
|
172
|
+
case 10:
|
|
173
|
+
case "end":
|
|
174
|
+
return _context.stop();
|
|
175
|
+
}
|
|
176
|
+
}, _callee, this);
|
|
177
|
+
}));
|
|
178
|
+
function loadSpec(_x) {
|
|
179
|
+
return _loadSpec.apply(this, arguments);
|
|
180
|
+
}
|
|
181
|
+
return loadSpec;
|
|
182
|
+
}()
|
|
183
|
+
/**
|
|
184
|
+
* Generate all code from the OpenAPI document.
|
|
185
|
+
* @returns map of output file path to file contents
|
|
186
|
+
*/
|
|
187
|
+
)
|
|
188
|
+
}, {
|
|
189
|
+
key: "generate",
|
|
190
|
+
value: (function () {
|
|
191
|
+
var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
|
|
192
|
+
var _openApiV3Json$compon, _openApiV3Json$compon2;
|
|
193
|
+
var outputFileList, _this$config, input, name, typesName, openApiV3Json, componentsSchemas, componentsCode, allApi, interfaceList, categoryCode, _iterator, _step, interfaceInfo, code, catOutputFilePath;
|
|
194
|
+
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
|
|
195
|
+
while (1) switch (_context3.prev = _context3.next) {
|
|
196
|
+
case 0:
|
|
197
|
+
outputFileList = Object.create(null);
|
|
198
|
+
_this$config = this.config, input = _this$config.input, name = _this$config.name;
|
|
199
|
+
typesName = name || Generator.deriveName(input);
|
|
200
|
+
_context3.next = 5;
|
|
201
|
+
return this.loadSpec(input);
|
|
202
|
+
case 5:
|
|
203
|
+
openApiV3Json = _context3.sent;
|
|
204
|
+
// Generate TypeScript interfaces for every schema declared under
|
|
205
|
+
// `components.schemas`. Use optional chaining: a valid OpenAPI document
|
|
206
|
+
// may omit `components` entirely (e.g. APIs with only path parameters
|
|
207
|
+
// and no schemas); without this guard generation would throw and abort.
|
|
208
|
+
componentsSchemas = (_openApiV3Json$compon = (_openApiV3Json$compon2 = openApiV3Json.components) === null || _openApiV3Json$compon2 === void 0 ? void 0 : _openApiV3Json$compon2.schemas) !== null && _openApiV3Json$compon !== void 0 ? _openApiV3Json$compon : {};
|
|
209
|
+
componentsCode = [];
|
|
210
|
+
_context3.next = 10;
|
|
211
|
+
return Promise.all(Object.keys(componentsSchemas).map( /*#__PURE__*/function () {
|
|
212
|
+
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(key) {
|
|
213
|
+
var code;
|
|
214
|
+
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
|
|
215
|
+
while (1) switch (_context2.prev = _context2.next) {
|
|
216
|
+
case 0:
|
|
217
|
+
_context2.next = 2;
|
|
218
|
+
return jsonSchemaToTsCode(_objectSpread(_objectSpread({}, componentsSchemas[key]), {}, {
|
|
219
|
+
components: openApiV3Json.components
|
|
220
|
+
}), key);
|
|
221
|
+
case 2:
|
|
222
|
+
code = _context2.sent;
|
|
223
|
+
componentsCode.push(code);
|
|
224
|
+
case 4:
|
|
225
|
+
case "end":
|
|
226
|
+
return _context2.stop();
|
|
227
|
+
}
|
|
228
|
+
}, _callee2);
|
|
229
|
+
}));
|
|
230
|
+
return function (_x2) {
|
|
231
|
+
return _ref.apply(this, arguments);
|
|
232
|
+
};
|
|
233
|
+
}()));
|
|
234
|
+
case 10:
|
|
235
|
+
_context3.next = 12;
|
|
236
|
+
return openApiToInterfaces(openApiV3Json);
|
|
237
|
+
case 12:
|
|
238
|
+
allApi = _context3.sent;
|
|
239
|
+
interfaceList = allApi.interfaces;
|
|
240
|
+
categoryCode = [].concat(componentsCode);
|
|
241
|
+
_iterator = _createForOfIteratorHelper(interfaceList);
|
|
242
|
+
_context3.prev = 16;
|
|
243
|
+
_iterator.s();
|
|
244
|
+
case 18:
|
|
245
|
+
if ((_step = _iterator.n()).done) {
|
|
246
|
+
_context3.next = 26;
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
interfaceInfo = _step.value;
|
|
250
|
+
_context3.next = 22;
|
|
251
|
+
return this.generateInterfaceCode(_objectSpread(_objectSpread({}, this.config), {}, {
|
|
252
|
+
components: openApiV3Json.components
|
|
253
|
+
}), interfaceInfo);
|
|
254
|
+
case 22:
|
|
255
|
+
code = _context3.sent;
|
|
256
|
+
categoryCode.push(code);
|
|
257
|
+
case 24:
|
|
258
|
+
_context3.next = 18;
|
|
259
|
+
break;
|
|
260
|
+
case 26:
|
|
261
|
+
_context3.next = 31;
|
|
262
|
+
break;
|
|
263
|
+
case 28:
|
|
264
|
+
_context3.prev = 28;
|
|
265
|
+
_context3.t0 = _context3["catch"](16);
|
|
266
|
+
_iterator.e(_context3.t0);
|
|
267
|
+
case 31:
|
|
268
|
+
_context3.prev = 31;
|
|
269
|
+
_iterator.f();
|
|
270
|
+
return _context3.finish(31);
|
|
271
|
+
case 34:
|
|
272
|
+
catOutputFilePath = getOutputFilePath(this.config, "/".concat(typesName, ".ts"));
|
|
273
|
+
if (categoryCode.length > 0) {
|
|
274
|
+
outputFileList[catOutputFilePath] = {
|
|
275
|
+
projectId: typesName,
|
|
276
|
+
categoryId: typesName,
|
|
277
|
+
syntheticalConfig: this.config,
|
|
278
|
+
content: categoryCode
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
return _context3.abrupt("return", outputFileList);
|
|
282
|
+
case 37:
|
|
283
|
+
case "end":
|
|
284
|
+
return _context3.stop();
|
|
285
|
+
}
|
|
286
|
+
}, _callee3, this, [[16, 28, 31, 34]]);
|
|
287
|
+
}));
|
|
288
|
+
function generate() {
|
|
289
|
+
return _generate.apply(this, arguments);
|
|
290
|
+
}
|
|
291
|
+
return generate;
|
|
292
|
+
}()
|
|
293
|
+
/**
|
|
294
|
+
* Write all generated files to disk.
|
|
295
|
+
* @param outputFileList generated files
|
|
296
|
+
*/
|
|
297
|
+
)
|
|
298
|
+
}, {
|
|
299
|
+
key: "write",
|
|
300
|
+
value: (function () {
|
|
301
|
+
var _write = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(outputFileList) {
|
|
302
|
+
var config;
|
|
303
|
+
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
|
|
304
|
+
while (1) switch (_context5.prev = _context5.next) {
|
|
305
|
+
case 0:
|
|
306
|
+
config = this.config || {}; // Scaffold the shared request client (request.ts) when enabled.
|
|
307
|
+
_context5.next = 3;
|
|
308
|
+
return writeRequestClient(config);
|
|
309
|
+
case 3:
|
|
310
|
+
return _context5.abrupt("return", Promise.all(Object.keys(outputFileList).map( /*#__PURE__*/function () {
|
|
311
|
+
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(outputFilePath) {
|
|
312
|
+
var _outputFileList$outpu, content, syntheticalConfig, resolvedPath, clientImportTemplate, clientConfigType, clientConfigImport, rawOutputContent, outputContent;
|
|
313
|
+
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
|
|
314
|
+
while (1) switch (_context4.prev = _context4.next) {
|
|
315
|
+
case 0:
|
|
316
|
+
_outputFileList$outpu = outputFileList[outputFilePath], content = _outputFileList$outpu.content, syntheticalConfig = _outputFileList$outpu.syntheticalConfig; // Rewrite `.jsx?` extensions to `.tsx?`.
|
|
317
|
+
resolvedPath = outputFilePath.replace(/\.js(x)?$/, ".ts$1");
|
|
318
|
+
clientImportTemplate = syntheticalConfig.clientImportTemplate || defaultClientImportTemplate;
|
|
319
|
+
clientConfigType = syntheticalConfig.clientConfigType || DEFAULT_CLIENT_CONFIG_TYPE; // With the default config type the generated functions reference
|
|
320
|
+
// AxiosRequestConfig, so its type-only import must accompany the
|
|
321
|
+
// client import. Custom config types must be imported by the
|
|
322
|
+
// project's own clientImportTemplate.
|
|
323
|
+
clientConfigImport = clientConfigType === DEFAULT_CLIENT_CONFIG_TYPE ? "import type { AxiosRequestConfig } from 'axios';" : "";
|
|
324
|
+
rawOutputContent = dedent(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n ", "\n ", "\n ", "\n\n ", "\n "])), topNotesContent(), clientImportTemplate(config), clientConfigImport, content.join("\n\n").trim());
|
|
325
|
+
_context4.next = 8;
|
|
326
|
+
return formatContent(dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["", ""])), rawOutputContent), resolvedPath);
|
|
327
|
+
case 8:
|
|
328
|
+
outputContent = _context4.sent;
|
|
329
|
+
_context4.next = 11;
|
|
330
|
+
return fs.outputFile(resolvedPath, outputContent);
|
|
331
|
+
case 11:
|
|
332
|
+
case "end":
|
|
333
|
+
return _context4.stop();
|
|
334
|
+
}
|
|
335
|
+
}, _callee4);
|
|
336
|
+
}));
|
|
337
|
+
return function (_x4) {
|
|
338
|
+
return _ref2.apply(this, arguments);
|
|
339
|
+
};
|
|
340
|
+
}())));
|
|
341
|
+
case 4:
|
|
342
|
+
case "end":
|
|
343
|
+
return _context5.stop();
|
|
344
|
+
}
|
|
345
|
+
}, _callee5, this);
|
|
346
|
+
}));
|
|
347
|
+
function write(_x3) {
|
|
348
|
+
return _write.apply(this, arguments);
|
|
349
|
+
}
|
|
350
|
+
return write;
|
|
351
|
+
}() /** Generate a request function name from the extended interface info. */)
|
|
352
|
+
}, {
|
|
353
|
+
key: "requestFunctionNameGen",
|
|
354
|
+
value: function requestFunctionNameGen(extendedInterfaceInfo) {
|
|
355
|
+
var path = extendedInterfaceInfo.parsedPath.dir;
|
|
356
|
+
// The same path may be used with different HTTP methods.
|
|
357
|
+
var method = extendedInterfaceInfo.method;
|
|
358
|
+
var words = [method].concat(_toConsumableArray(path.split("/")), [extendedInterfaceInfo.parsedPath.name]).join("_");
|
|
359
|
+
return changeCase.camelCase(words);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Generate TypeScript code (types + request function) for a single API. */
|
|
363
|
+
}, {
|
|
364
|
+
key: "generateInterfaceCode",
|
|
365
|
+
value: (function () {
|
|
366
|
+
var _generateInterfaceCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(syntheticalConfig, interfaceInfo) {
|
|
367
|
+
var extendedInterfaceInfo, requestFunctionName, requestDataTypeName, responseDataTypeName, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, genComment, requestFunctionTemplate, baseURL, baseUrl, code;
|
|
368
|
+
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
|
|
369
|
+
while (1) switch (_context6.prev = _context6.next) {
|
|
370
|
+
case 0:
|
|
371
|
+
extendedInterfaceInfo = _objectSpread(_objectSpread({}, interfaceInfo), {}, {
|
|
372
|
+
parsedPath: path.parse(interfaceInfo.path)
|
|
373
|
+
});
|
|
374
|
+
requestFunctionName = this.requestFunctionNameGen(extendedInterfaceInfo);
|
|
375
|
+
requestDataTypeName = changeCase.pascalCase("".concat(requestFunctionName, "Request"));
|
|
376
|
+
responseDataTypeName = changeCase.pascalCase("".concat(requestFunctionName, "Response"));
|
|
377
|
+
requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo); // Request parameters type.
|
|
378
|
+
_context6.next = 7;
|
|
379
|
+
return jsonSchemaToTsCode(_objectSpread(_objectSpread({}, requestDataJsonSchema), {}, {
|
|
380
|
+
components: syntheticalConfig.components
|
|
381
|
+
}), requestDataTypeName);
|
|
382
|
+
case 7:
|
|
383
|
+
requestDataType = _context6.sent;
|
|
384
|
+
// Surface request-body type degradation instead of silently shipping a
|
|
385
|
+
// primitive/empty type to the frontend. Common root causes: missing
|
|
386
|
+
// `@ApiBody({type: XxxDto})`, inline `@Body() body: {...}` literal, or a
|
|
387
|
+
// Prisma type bound to `@Body()`.
|
|
388
|
+
if (isDegradedRequestType(requestDataType)) {
|
|
389
|
+
conso.warn("[apits] Request type degraded for " + "".concat(extendedInterfaceInfo.method.toUpperCase(), " ").concat(extendedInterfaceInfo.path, " \u2014 ") + "check backend @Body()/@ApiBody decorator. Generated:\n".concat(requestDataType));
|
|
390
|
+
}
|
|
391
|
+
responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo);
|
|
392
|
+
_context6.next = 12;
|
|
393
|
+
return jsonSchemaToTsCode(_objectSpread(_objectSpread({}, responseDataJsonSchema), {}, {
|
|
394
|
+
components: syntheticalConfig.components
|
|
395
|
+
}), responseDataTypeName);
|
|
396
|
+
case 12:
|
|
397
|
+
responseDataType = _context6.sent;
|
|
398
|
+
// Build the JSDoc title comment for the generated types/function.
|
|
399
|
+
genComment = function genComment(genTitle) {
|
|
400
|
+
// Escape slashes in the title.
|
|
401
|
+
var escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, "\\/");
|
|
402
|
+
return dedent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n /**\n * ", "\n */\n "])), genTitle(escapedTitle));
|
|
403
|
+
};
|
|
404
|
+
requestFunctionTemplate = defaultRequestFunctionTemplate;
|
|
405
|
+
baseURL = syntheticalConfig.baseURL;
|
|
406
|
+
try {
|
|
407
|
+
baseUrl = typeof baseURL === "string" ? baseURL : typeof baseURL === "function" ? baseURL(extendedInterfaceInfo.path) : "";
|
|
408
|
+
} catch (e) {
|
|
409
|
+
conso.error(e);
|
|
410
|
+
}
|
|
411
|
+
code = dedent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "])), genComment(function (title) {
|
|
412
|
+
return "".concat(title, " request parameters");
|
|
413
|
+
}), requestDataType.trim(), genComment(function (title) {
|
|
414
|
+
return "".concat(title, " response data");
|
|
415
|
+
}), responseDataType.trim(), dedent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n ", "\n ", "\n "])), genComment(function (title) {
|
|
416
|
+
return "".concat(title);
|
|
417
|
+
}), requestFunctionTemplate({
|
|
418
|
+
baseURL: baseUrl,
|
|
419
|
+
requestFunctionName: requestFunctionName,
|
|
420
|
+
requestDataTypeName: requestDataTypeName,
|
|
421
|
+
responseDataTypeName: responseDataTypeName,
|
|
422
|
+
extendedInterfaceInfo: extendedInterfaceInfo
|
|
423
|
+
}, syntheticalConfig)));
|
|
424
|
+
return _context6.abrupt("return", code);
|
|
425
|
+
case 19:
|
|
426
|
+
case "end":
|
|
427
|
+
return _context6.stop();
|
|
428
|
+
}
|
|
429
|
+
}, _callee6, this);
|
|
430
|
+
}));
|
|
431
|
+
function generateInterfaceCode(_x5, _x6) {
|
|
432
|
+
return _generateInterfaceCode.apply(this, arguments);
|
|
433
|
+
}
|
|
434
|
+
return generateInterfaceCode;
|
|
435
|
+
}())
|
|
436
|
+
}], [{
|
|
437
|
+
key: "isHttpInput",
|
|
438
|
+
value: function isHttpInput(input) {
|
|
439
|
+
return /^https?:\/\//i.test(input);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Derive a file base name from the input: hostname for URLs, file name
|
|
444
|
+
* without extension for local paths. Falls back to `api`.
|
|
445
|
+
*/
|
|
446
|
+
}, {
|
|
447
|
+
key: "deriveName",
|
|
448
|
+
value: function deriveName(input) {
|
|
449
|
+
var raw = "";
|
|
450
|
+
if (Generator.isHttpInput(input)) {
|
|
451
|
+
try {
|
|
452
|
+
raw = new URL(input).hostname.replace(/^www\./, "");
|
|
453
|
+
} catch (_unused) {
|
|
454
|
+
raw = "";
|
|
455
|
+
}
|
|
456
|
+
} else {
|
|
457
|
+
raw = path.basename(input).replace(/\.(json5?|ya?ml)$/i, "");
|
|
458
|
+
}
|
|
459
|
+
return changeCase.camelCase(raw) || "api";
|
|
460
|
+
}
|
|
461
|
+
}]);
|
|
462
|
+
return Generator;
|
|
463
|
+
}();
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
|
|
2
|
+
var _templateObject;
|
|
3
|
+
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
|
|
4
|
+
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
|
|
5
|
+
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
|
|
6
|
+
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
|
|
7
|
+
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
8
|
+
import fs from "fs-extra";
|
|
9
|
+
import { dedent } from "../utils/vtilsLite.mjs";
|
|
10
|
+
import { getOutputFilePath } from "../utils/getOutputPath.mjs";
|
|
11
|
+
import { formatContent, topNotesContent } from "../utils/utils.mjs";
|
|
12
|
+
export default function writeRequestClient(_x) {
|
|
13
|
+
return _writeRequestClient.apply(this, arguments);
|
|
14
|
+
}
|
|
15
|
+
function _writeRequestClient() {
|
|
16
|
+
_writeRequestClient = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config) {
|
|
17
|
+
var client, rawRequestFunctionFilePath, content;
|
|
18
|
+
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
19
|
+
while (1) switch (_context.prev = _context.next) {
|
|
20
|
+
case 0:
|
|
21
|
+
client = config.client;
|
|
22
|
+
if (!(client === false)) {
|
|
23
|
+
_context.next = 3;
|
|
24
|
+
break;
|
|
25
|
+
}
|
|
26
|
+
return _context.abrupt("return");
|
|
27
|
+
case 3:
|
|
28
|
+
rawRequestFunctionFilePath = getOutputFilePath(config, "request.ts");
|
|
29
|
+
_context.next = 6;
|
|
30
|
+
return fs.pathExists(rawRequestFunctionFilePath);
|
|
31
|
+
case 6:
|
|
32
|
+
if (!_context.sent) {
|
|
33
|
+
_context.next = 8;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
return _context.abrupt("return");
|
|
37
|
+
case 8:
|
|
38
|
+
content = "\n ".concat(topNotesContent(), "\n\n import axios, { AxiosRequestConfig } from 'axios';\n\n const instance = axios.create({\n withCredentials: true,\n });\n\n // Custom request interceptor.\n instance.interceptors.request.use((config) => {\n return { ...config };\n });\n\n // Custom response interceptor \u2014 return res.data so the generated request\n // functions receive the response payload directly, matching the RP type.\n instance.interceptors.response.use((res) => {\n const { status } = res;\n if (status >= 200 && status < 300) {\n return res.data;\n }\n return Promise.reject(res);\n });\n\n export default {\n get: <RQ, RP>(url: string, config?: AxiosRequestConfig) => {\n return instance.get<RP>(url, config) as Promise<RP>;\n },\n post: <RQ, RP>(url: string, config?: AxiosRequestConfig) => {\n return instance.post<RP>(url, undefined, config) as Promise<RP>;\n },\n head: <RQ, RP>(url: string, config?: AxiosRequestConfig) => {\n return instance.head<RP>(url, config) as Promise<RP>;\n },\n put: <RQ, RP>(url: string, config?: AxiosRequestConfig) => {\n return instance.put<RP>(url, undefined, config) as Promise<RP>;\n },\n patch: <RQ, RP>(url: string, config?: AxiosRequestConfig) => {\n return instance.patch<RP>(url, undefined, config) as Promise<RP>;\n },\n delete: <RQ, RP>(url: string, config?: AxiosRequestConfig) => {\n return instance.delete<RP>(url, config) as Promise<RP>;\n },\n };\n");
|
|
39
|
+
_context.t0 = fs;
|
|
40
|
+
_context.t1 = rawRequestFunctionFilePath;
|
|
41
|
+
_context.next = 13;
|
|
42
|
+
return formatContent(dedent(_templateObject || (_templateObject = _taggedTemplateLiteral(["", ""])), content), rawRequestFunctionFilePath);
|
|
43
|
+
case 13:
|
|
44
|
+
_context.t2 = _context.sent;
|
|
45
|
+
_context.next = 16;
|
|
46
|
+
return _context.t0.outputFile.call(_context.t0, _context.t1, _context.t2);
|
|
47
|
+
case 16:
|
|
48
|
+
case "end":
|
|
49
|
+
return _context.stop();
|
|
50
|
+
}
|
|
51
|
+
}, _callee);
|
|
52
|
+
}));
|
|
53
|
+
return _writeRequestClient.apply(this, arguments);
|
|
54
|
+
}
|