@topvisor/ui
Version:
Topvisor UI-kit Vue
281 lines (280 loc) • 10.9 kB
JavaScript
import { g as Y, a as Z } from "../.chunks/field-CyyFzM-Y.es.js";
const v = (o = {}) => {
var t;
return o = { ...o }, o.loadingEl ??= (t = globalThis.document) == null ? void 0 : t.body, o.loadingShowSpinner ??= !0, o.method ??= "POST", o.accept ??= "application/json", o;
}, W = (o, t, n) => ({
result: o,
errors: t,
response: n
}), H = (o) => o.startsWith("/system_2/common/"), N = (o = !1, t = window.location.href, n) => {
const { protocol: e, hostname: s, port: r } = new URL(t), i = s.split("."), d = !o || i.length <= 2 || /^[\d.]+$/.test(s) || s === "localhost" ? s : i.slice(-2).join(".");
return `${e}//${d}${r ? `:${r}` : ""}`;
}, $ = (o) => Object.values(o).some(
(t) => t instanceof FileList || t instanceof File || t instanceof Blob || Array.isArray(t) && t.some((n) => n instanceof File || n instanceof Blob)
), B = (o, t, n) => {
const e = {
inLoading: !1,
path: t,
url: o.options.baseUrl + t,
options: v(o.options.requestOptions),
mockerOptions: void 0,
params: {},
// незаполненное свойство
getInLoading: () => e.inLoading,
setParams: (s) => (e.params = { ...s }, e),
changeParams: (s) => (Object.assign(e.params, s), e),
setOptions: (s) => (Object.assign(e.options, s), e),
setMocker: (s) => (e.mockerOptions = s, e),
call: async (s) => e.exec(s),
callFetch: async (s, r) => e.exec(r, s),
callInNewWindow: async (s) => {
var p, u;
const r = e.genData(s), i = o.genMiddlewareCtx(e, r);
(u = (p = o.options).onPrepareData) == null || u.call(p, r, i);
const { postInWindow: d } = await import("../.chunks/lazy-40pjr8cZ.es.js");
d(e.url, r, "_blank");
},
callInSelfWindow: async (s) => {
var p, u;
const r = e.genData(s), i = o.genMiddlewareCtx(e, r);
(u = (p = o.options).onPrepareData) == null || u.call(p, r, i);
const { postInWindow: d } = await import("../.chunks/lazy-40pjr8cZ.es.js");
d(e.url, r, "_self");
},
genData: (s, r) => {
const i = { ...e.params };
if (delete i.fetch_style, s) {
let d = [...s];
n && (d = d.filter((p) => n.includes(p))), i.fields = d;
} else
n && (i.fields = n);
return r && (i.fetch_style = r), i;
},
/**
* Общая функция выполнения запросов
*/
async exec(s, r) {
var q, S, O, C, I, P, F, T, A, D, U, L, z, k, M;
const i = o.options.Request, d = o.options.fetch, p = e.genData(s, r), u = o.genMiddlewareCtx(e, p);
if ((S = (q = o.options).onPrepareData) == null || S.call(q, p, u), e.mockerOptions) {
const { genMockResponse: c } = await import("../.chunks/index-igPkes8X.es.js");
return await c(e.mockerOptions, s, p);
}
const y = $(p);
if (y && e.options.method !== "POST")
throw new Error("Files can be sent only in POST requests");
let b = e.url, R;
if (y) {
if (e.options.method !== "POST")
throw new Error("Files can be sent only in POST requests");
const { formDataSerializer: c } = await import("../.chunks/lazy-40pjr8cZ.es.js");
R = c(p);
} else e.options.method !== "POST" ? b += "?" + await o.options.querySerializer(p) : R = o.options.bodySerializer(p);
let E;
if (this.options.checkFingerprint) {
const c = this.path + this.options.checkFingerprint;
(O = o.abortControllers[c]) == null || O.abort();
const w = new AbortController();
o.abortControllers[c] = w, E = w.signal;
}
const _ = {
...o.options,
method: e.options.method,
body: R,
signal: E
};
let h = new i(b, _);
h.headers.set("x-request-id", u.id), h.headers.set("accept", e.options.accept), y || h.headers.set("content-type", "application/json");
const f = {
...u,
request: h
};
e.inLoading = !0, (I = (C = e.options).onLoading) == null || I.call(C, e.inLoading, f);
let l;
const x = await o.middlewareOnRequest(h, f);
if (x instanceof Response ? l = x : x instanceof i && (h = x), !l)
try {
l = await d(h);
} catch (c) {
l = await o.middlewareOnError(c, f);
} finally {
e.inLoading = !1, (F = (P = e.options).onLoading) == null || F.call(P, e.inLoading, f);
}
l = await o.middlewareOnResponse(l, f);
let a, m, g;
try {
const c = (T = l.headers.get("content-type")) == null ? void 0 : T.includes("application/json");
m = await l.text(), this.options.accept === "application/json" || c ? a = JSON.parse(m) : o.useExt ? a = W(m, void 0, l) : a = m;
} catch (c) {
if ((c instanceof SyntaxError || c instanceof TypeError) && (g = c, g.responseText = m), o.useExt && g) {
let w = l.status, j = l.statusText;
w === 200 && (w = 1e4, j = "Error API response"), a = W(null, [
{
code: w,
string: j
}
], l), o.options.useApiConsole && console.error(c);
} else
throw c;
}
return o.useExt && (a.response = l, a && ((D = (A = e.options).onApiLoaded) == null || D.call(A, a, f)), a != null && a.errors && (o.options.useApiConsole && console.warn(new Error("API error"), { res: a }), (z = (L = e.options).onApiError) == null || z.call(L, a, { ...f, formatError: g }, (U = o.options.requestOptions) == null ? void 0 : U.onApiError)), a != null && a.messages && ((M = (k = e.options).onApiMessage) == null || M.call(k, a, f))), a;
}
};
return e;
};
class J {
options;
useExt;
middlewares = [];
abortControllers = {};
constructor(t = {}, n) {
t.requestOptions = v(t.requestOptions), t.useApiConsole ??= !0, t.fetch ??= globalThis.fetch, t.Request ??= globalThis.Request, t.querySerializer ??= async (e) => {
const { querySerializer: s } = await import("../.chunks/lazy-40pjr8cZ.es.js");
return s(e);
}, t.bodySerializer ??= (e) => typeof e == "string" ? e : JSON.stringify(e), this.options = t, this.useExt = n;
}
generateUUID() {
return crypto != null && crypto.randomUUID ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (t) => {
const n = Math.random() * 16 | 0;
return (t === "x" ? n : n & 3 | 8).toString(16);
});
}
/**
* Зарегистрировать middleware
*/
use(t) {
this.middlewares.push(t);
}
/**
* Создать объект запроса
*
* После создания объекта он заполняется необходимыми данными и выполняет запросы к API с помощью APIRequest2.call();
*
* Опционально generic указывать нельзя, поэтому необходимо дублировать определение fetchStyle, [см.](https://github.com/Microsoft/TypeScript/issues/26242)
*
* @param path Путь метода API
* @param fieldsNarrow Список получаемых полей, для методов API с моделью. Если объект запроса переиспользуется, и список полей меняется, указывайте его непосредственно при вызове `api.call()`
*/
gen(t, n) {
return B(this, t, n);
}
/**
* Создать объект запроса, не описанного в OpenAPI
*/
genAny(t, n) {
return this.gen(t, n);
}
/**
* Создать контекст выполнения запроса
*/
genMiddlewareCtx(t, n) {
const e = this.generateUUID(), s = Object.freeze({
baseUrl: this.options.baseUrl,
querySerializer: this.options.querySerializer,
bodySerializer: this.options.bodySerializer,
Request: this.options.Request,
fetch: this.options.fetch
});
return {
useExt: this.useExt,
requestOptions: t.options,
data: n,
middlewareData: {},
options: s,
schemaPath: t.path,
id: e
};
}
/**
* Обработчик middleware.onRequest
*
* @param request Запрос для обработки
* @param middlewareCtx Контекст выполнения запроса
* @return Новый экземпляр `Request` или `Response` при модификации запроса, или undefined
*/
async middlewareOnRequest(t, n) {
var e;
for (const s of this.middlewares) {
const r = await ((e = s.onRequest) == null ? void 0 : e.call(s, {
...n,
request: t
}));
if (r)
if (r instanceof Request)
t = r;
else {
if (r instanceof Response)
return r;
throw new Error("onRequest: must return new Request() or Response() when modifying the request");
}
}
return t;
}
/**
* Обработчик middleware.onResponse
*
* @param `error` Ошибка, переданная для обработки
* @param middlewareCtx
* @return Новый экземпляр `Response` при успешной обработке или выбрасывает ошибку
*/
async middlewareOnError(t, n) {
var s;
let e = t;
for (const r of this.middlewares) {
const i = await ((s = r.onError) == null ? void 0 : s.call(r, {
...n,
error: e
}));
if (i) {
if (i instanceof Response)
return i;
if (i instanceof Error) {
e = i;
continue;
}
throw new Error("onError: must return new Response() or instance of Error");
}
}
throw e;
}
/**
* Обработчик middleware.onResponse
*
* @param response Ответ для обработки
* @param middlewareCtx Контекст выполнения запроса
* @return Новый экземпляр `Response` при модификации ответа, или undefined
*/
async middlewareOnResponse(t, n) {
var e;
for (const s of this.middlewares) {
const r = await ((e = s.onResponse) == null ? void 0 : e.call(s, {
...n,
response: t
}));
if (r) {
if (!(r instanceof Response))
throw new Error("onResponse: must return new Response() when modifying the response");
t = r;
}
}
return t;
}
}
const G = async (...o) => {
const { postInWindow: t } = await import("../.chunks/lazy-40pjr8cZ.es.js");
return t(...o);
}, K = async (...o) => {
const { dataToForm: t } = await import("../.chunks/lazy-40pjr8cZ.es.js");
return t(...o);
}, Q = (o = {}, t) => new J(o, t);
export {
Q as createClient,
K as dataToForm,
W as genExtRes,
Y as genFieldFilter,
Z as genFieldOrder,
N as getBaseDomainUrl,
H as isPublicAPI,
G as postInWindow
};
//# sourceMappingURL=index.js.map