UNPKG

@solfacil/plasma-utils

Version:

- 💚 [Nuxt 3](https://nuxt.com/) - Compatible with Nuxt 3 - 🍞 [BUN](https://bun.sh/) - A fast JavaScript all-in-one toolkit (runtime, bundler, test runner, package manager). - 🔑 [Keycloak](https://www.keycloak.org/) integration. - ⚡️ Vite - Instant HMR.

746 lines (745 loc) 22.9 kB
var ae = Object.defineProperty; var ue = (e, t, o) => t in e ? ae(e, t, { enumerable: !0, configurable: !0, writable: !0, value: o }) : e[t] = o; var d = (e, t, o) => (ue(e, typeof t != "symbol" ? t + "" : t, o), o); import { ref as fe } from "vue"; class At { constructor(t) { d(this, "_api"); this._api = t; } get api() { return this._api; } } const le = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/, pe = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/, he = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; function de(e, t) { if (e === "__proto__" || e === "constructor" && t && typeof t == "object" && "prototype" in t) { me(e); return; } return t; } function me(e) { console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`); } function ge(e, t = {}) { if (typeof e != "string") return e; const o = e.trim(); if ( // eslint-disable-next-line unicorn/prefer-at e[0] === '"' && e.at(-1) === '"' && !e.includes("\\") ) return o.slice(1, -1); if (o.length <= 9) { const r = o.toLowerCase(); if (r === "true") return !0; if (r === "false") return !1; if (r === "undefined") return; if (r === "null") return null; if (r === "nan") return Number.NaN; if (r === "infinity") return Number.POSITIVE_INFINITY; if (r === "-infinity") return Number.NEGATIVE_INFINITY; } if (!he.test(e)) { if (t.strict) throw new SyntaxError("[destr] Invalid JSON"); return e; } try { if (le.test(e) || pe.test(e)) { if (t.strict) throw new Error("[destr] Possible prototype pollution"); return JSON.parse(e, de); } return JSON.parse(e); } catch (r) { if (t.strict) throw r; return e; } } const ye = /#/g, Re = /&/g, _e = /=/g, q = /\+/g, we = /%5e/gi, Ee = /%60/gi, be = /%7c/gi, Te = /%20/gi; function Se(e) { return encodeURI("" + e).replace(be, "|"); } function N(e) { return Se(typeof e == "string" ? e : JSON.stringify(e)).replace(q, "%2B").replace(Te, "+").replace(ye, "%23").replace(Re, "%26").replace(Ee, "`").replace(we, "^"); } function O(e) { return N(e).replace(_e, "%3D"); } function J(e = "") { try { return decodeURIComponent("" + e); } catch { return "" + e; } } function Ae(e) { return J(e.replace(q, " ")); } function Oe(e) { return J(e.replace(q, " ")); } function Ce(e = "") { const t = {}; e[0] === "?" && (e = e.slice(1)); for (const o of e.split("&")) { const r = o.match(/([^=]+)=?(.*)/) || []; if (r.length < 2) continue; const s = Ae(r[1]); if (s === "__proto__" || s === "constructor") continue; const c = Oe(r[2] || ""); t[s] === void 0 ? t[s] = c : Array.isArray(t[s]) ? t[s].push(c) : t[s] = [t[s], c]; } return t; } function Ie(e, t) { return (typeof t == "number" || typeof t == "boolean") && (t = String(t)), t ? Array.isArray(t) ? t.map((o) => `${O(e)}=${N(o)}`).join("&") : `${O(e)}=${N(t)}` : O(e); } function Ne(e) { return Object.keys(e).filter((t) => e[t] !== void 0).map((t) => Ie(t, e[t])).filter(Boolean).join("&"); } const Ue = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/, $e = /^[\s\w\0+.-]{2,}:([/\\]{2})?/, Pe = /^([/\\]\s*){2,}[^/\\]/; function K(e, t = {}) { return typeof t == "boolean" && (t = { acceptRelative: t }), t.strict ? Ue.test(e) : $e.test(e) || (t.acceptRelative ? Pe.test(e) : !1); } const je = /\/$|\/\?|\/#/; function U(e = "", t) { return t ? je.test(e) : e.endsWith("/"); } function Le(e = "", t) { if (!t) return (U(e) ? e.slice(0, -1) : e) || "/"; if (!U(e, !0)) return e || "/"; let o = e, r = ""; const s = e.indexOf("#"); s >= 0 && (o = e.slice(0, s), r = e.slice(s)); const [c, ...i] = o.split("?"); return (c.slice(0, -1) || "/") + (i.length > 0 ? `?${i.join("?")}` : "") + r; } function qe(e = "", t) { if (!t) return e.endsWith("/") ? e : e + "/"; if (U(e, !0)) return e || "/"; let o = e, r = ""; const s = e.indexOf("#"); if (s >= 0 && (o = e.slice(0, s), r = e.slice(s), !o)) return r; const [c, ...i] = o.split("?"); return c + "/" + (i.length > 0 ? `?${i.join("?")}` : "") + r; } function ke(e, t) { if (De(t) || K(e)) return e; const o = Le(t); return e.startsWith(o) ? e : Be(o, e); } function ve(e, t) { const o = Q(e), r = { ...Ce(o.search), ...t }; return o.search = Ne(r), xe(o); } function De(e) { return !e || e === "/"; } function Fe(e) { return e && e !== "/"; } const Ve = /^\.?\//; function Be(e, ...t) { let o = e || ""; for (const r of t.filter((s) => Fe(s))) if (o) { const s = r.replace(Ve, ""); o = qe(o) + s; } else o = r; return o; } function Q(e = "", t) { const o = e.match( /^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i ); if (o) { const [, h, l = ""] = o; return { protocol: h.toLowerCase(), pathname: l, href: h + l, auth: "", host: "", search: "", hash: "" }; } if (!K(e, { acceptRelative: !0 })) return t ? Q(t + e) : V(e); const [, r = "", s, c = ""] = e.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || [], [, i = "", a = ""] = c.match(/([^#/?]*)(.*)?/) || [], { pathname: p, search: f, hash: n } = V( a.replace(/\/(?=[A-Za-z]:)/, "") ); return { protocol: r.toLowerCase(), auth: s ? s.slice(0, Math.max(0, s.length - 1)) : "", host: i, pathname: p, search: f, hash: n }; } function V(e = "") { const [t = "", o = "", r = ""] = (e.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1); return { pathname: t, search: o, hash: r }; } function xe(e) { const t = e.pathname || "", o = e.search ? (e.search.startsWith("?") ? "" : "?") + e.search : "", r = e.hash || "", s = e.auth ? e.auth + "@" : "", c = e.host || ""; return (e.protocol ? e.protocol + "//" : "") + s + c + t + o + r; } class ze extends Error { constructor(t, o) { super(t, o), this.name = "FetchError", o != null && o.cause && !this.cause && (this.cause = o.cause); } } function Je(e) { var p, f, n, h, l; const t = ((p = e.error) == null ? void 0 : p.message) || ((f = e.error) == null ? void 0 : f.toString()) || "", o = ((n = e.request) == null ? void 0 : n.method) || ((h = e.options) == null ? void 0 : h.method) || "GET", r = ((l = e.request) == null ? void 0 : l.url) || String(e.request) || "/", s = `[${o}] ${JSON.stringify(r)}`, c = e.response ? `${e.response.status} ${e.response.statusText}` : "<no response>", i = `${s}: ${c}${t ? ` ${t}` : ""}`, a = new ze( i, e.error ? { cause: e.error } : void 0 ); for (const u of ["request", "options", "response"]) Object.defineProperty(a, u, { get() { return e[u]; } }); for (const [u, A] of [ ["data", "_data"], ["status", "status"], ["statusCode", "status"], ["statusText", "statusText"], ["statusMessage", "statusText"] ]) Object.defineProperty(a, u, { get() { return e.response && e.response[A]; } }); return a; } const Ke = new Set( Object.freeze(["PATCH", "POST", "PUT", "DELETE"]) ); function B(e = "GET") { return Ke.has(e.toUpperCase()); } function Qe(e) { if (e === void 0) return !1; const t = typeof e; return t === "string" || t === "number" || t === "boolean" || t === null ? !0 : t !== "object" ? !1 : Array.isArray(e) ? !0 : e.buffer ? !1 : e.constructor && e.constructor.name === "Object" || typeof e.toJSON == "function"; } const Me = /* @__PURE__ */ new Set([ "image/svg", "application/xml", "application/xhtml", "application/html" ]), Ge = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i; function He(e = "") { if (!e) return "json"; const t = e.split(";").shift() || ""; return Ge.test(t) ? "json" : Me.has(t) || t.startsWith("text/") ? "text" : "blob"; } function We(e, t, o = globalThis.Headers) { const r = { ...t, ...e }; if (t != null && t.params && (e != null && e.params) && (r.params = { ...t == null ? void 0 : t.params, ...e == null ? void 0 : e.params }), t != null && t.query && (e != null && e.query) && (r.query = { ...t == null ? void 0 : t.query, ...e == null ? void 0 : e.query }), t != null && t.headers && (e != null && e.headers)) { r.headers = new o((t == null ? void 0 : t.headers) || {}); for (const [s, c] of new o((e == null ? void 0 : e.headers) || {})) r.headers.set(s, c); } return r; } const Ye = /* @__PURE__ */ new Set([ 408, // Request Timeout 409, // Conflict 425, // Too Early 429, // Too Many Requests 500, // Internal Server Error 502, // Bad Gateway 503, // Service Unavailable 504 // Gateway Timeout ]), Xe = /* @__PURE__ */ new Set([101, 204, 205, 304]); function M(e = {}) { const { fetch: t = globalThis.fetch, Headers: o = globalThis.Headers, AbortController: r = globalThis.AbortController } = e; async function s(a) { const p = a.error && a.error.name === "AbortError" && !a.options.timeout || !1; if (a.options.retry !== !1 && !p) { let n; typeof a.options.retry == "number" ? n = a.options.retry : n = B(a.options.method) ? 0 : 1; const h = a.response && a.response.status || 500; if (n > 0 && (Array.isArray(a.options.retryStatusCodes) ? a.options.retryStatusCodes.includes(h) : Ye.has(h))) { const l = a.options.retryDelay || 0; return l > 0 && await new Promise((u) => setTimeout(u, l)), c(a.request, { ...a.options, retry: n - 1, timeout: a.options.timeout }); } } const f = Je(a); throw Error.captureStackTrace && Error.captureStackTrace(f, c), f; } const c = async function(p, f = {}) { var l; const n = { request: p, options: We(f, e.defaults, o), response: void 0, error: void 0 }; if (n.options.method = (l = n.options.method) == null ? void 0 : l.toUpperCase(), n.options.onRequest && await n.options.onRequest(n), typeof n.request == "string" && (n.options.baseURL && (n.request = ke(n.request, n.options.baseURL)), (n.options.query || n.options.params) && (n.request = ve(n.request, { ...n.options.params, ...n.options.query }))), n.options.body && B(n.options.method) && (Qe(n.options.body) ? (n.options.body = typeof n.options.body == "string" ? n.options.body : JSON.stringify(n.options.body), n.options.headers = new o(n.options.headers || {}), n.options.headers.has("content-type") || n.options.headers.set("content-type", "application/json"), n.options.headers.has("accept") || n.options.headers.set("accept", "application/json")) : ( // ReadableStream Body ("pipeTo" in n.options.body && typeof n.options.body.pipeTo == "function" || // Node.js Stream Body typeof n.options.body.pipe == "function") && ("duplex" in n.options || (n.options.duplex = "half")) )), !n.options.signal && n.options.timeout) { const u = new r(); setTimeout(() => u.abort(), n.options.timeout), n.options.signal = u.signal; } try { n.response = await t( n.request, n.options ); } catch (u) { return n.error = u, n.options.onRequestError && await n.options.onRequestError(n), await s(n); } if (n.response.body && !Xe.has(n.response.status) && n.options.method !== "HEAD") { const u = (n.options.parseResponse ? "json" : n.options.responseType) || He(n.response.headers.get("content-type") || ""); switch (u) { case "json": { const A = await n.response.text(), ie = n.options.parseResponse || ge; n.response._data = ie(A); break; } case "stream": { n.response._data = n.response.body; break; } default: n.response._data = await n.response[u](); } } return n.options.onResponse && await n.options.onResponse(n), !n.options.ignoreResponseError && n.response.status >= 400 && n.response.status < 600 ? (n.options.onResponseError && await n.options.onResponseError(n), await s(n)) : n.response; }, i = async function(p, f) { return (await c(p, f))._data; }; return i.raw = c, i.native = (...a) => t(...a), i.create = (a = {}) => M({ ...e, defaults: { ...e.defaults, ...a } }), i; } const k = function() { if (typeof globalThis < "u") return globalThis; if (typeof self < "u") return self; if (typeof window < "u") return window; if (typeof global < "u") return global; throw new Error("unable to locate global object"); }(), Ze = k.fetch || (() => Promise.reject(new Error("[ofetch] global.fetch is not supported!"))), et = k.Headers, tt = k.AbortController, ot = M({ fetch: Ze, Headers: et, AbortController: tt }), R = ot; /*! typescript-cookie v1.0.6 | MIT */ const G = (e) => encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape), H = (e) => encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent), v = decodeURIComponent, D = (e) => (e[0] === '"' && (e = e.slice(1, -1)), e.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)); function nt(e) { return e = Object.assign({}, e), typeof e.expires == "number" && (e.expires = new Date(Date.now() + e.expires * 864e5)), e.expires != null && (e.expires = e.expires.toUTCString()), Object.entries(e).filter(([t, o]) => o != null && o !== !1).map(([t, o]) => o === !0 ? `; ${t}` : `; ${t}=${o.split(";")[0]}`).join(""); } function W(e, t, o) { const r = /(?:^|; )([^=]*)=([^;]*)/g, s = {}; let c; for (; (c = r.exec(document.cookie)) != null; ) try { const i = o(c[1]); if (s[i] = t(c[2], i), e === i) break; } catch { } return e != null ? s[e] : s; } const x = Object.freeze({ decodeName: v, decodeValue: D, encodeName: G, encodeValue: H }), F = Object.freeze({ path: "/" }); function S(e, t, o = F, { encodeValue: r = H, encodeName: s = G } = {}) { return document.cookie = `${s(e)}=${r(t, e)}${nt(o)}`; } function y(e, { decodeValue: t = D, decodeName: o = v } = {}) { return W(e, t, o); } function rt({ decodeValue: e = D, decodeName: t = v } = {}) { return W(void 0, e, t); } function Y(e, t = F) { S(e, "", Object.assign({}, t, { expires: -1 })); } function $(e, t) { const o = { set: function(s, c, i) { return S(s, c, Object.assign({}, this.attributes, i), { encodeValue: this.converter.write }); }, get: function(s) { if (arguments.length === 0) return rt(this.converter.read); if (s != null) return y(s, this.converter.read); }, remove: function(s, c) { Y(s, Object.assign({}, this.attributes, c)); }, withAttributes: function(s) { return $(this.converter, Object.assign({}, this.attributes, s)); }, withConverter: function(s) { return $(Object.assign({}, this.converter, s), this.attributes); } }, r = { attributes: { value: Object.freeze(t) }, converter: { value: Object.freeze(e) } }; return Object.create(o, r); } $({ read: x.decodeValue, write: x.encodeValue }, F); class m { } d(m, "UNAUTHORIZED", 401), d(m, "FORBIDDEN", 403), d(m, "NOT_FOUND", 404), d(m, "UNPROCESSABLE_ENTITY", 422), d(m, "INTERNAL_SERVER_ERROR", 500), d(m, "SERVICE_UNAVAILABLE", 503), d(m, "GATEWAY_TIMEOUT", 504); const P = "environment", X = "env"; function st() { return localStorage.getItem(P); } function Z() { const e = st(), t = z(e, T.graphql), o = z(e, T.rest), r = ee(e, T.keycloak); return { graphql: t, rest: o, keycloak: r }; } function z(e, t) { const o = {}; for (const r in t) { const s = t[r]; Object.assign(o, { [r]: ee(e, s) }); } return o; } function ee(e, t) { return e || console.warn("Environment not found"), t[e] || t.dev; } function ct() { return { set: (e, t) => { typeof t == "object" ? localStorage.setItem(e, JSON.stringify(t)) : localStorage.setItem(e, t); }, get: (e, t = void 0) => { const o = localStorage.getItem(e); if (o !== null) try { return JSON.parse(o); } catch { return o; } return t; }, remove: (e) => { localStorage.removeItem(e); }, clear: () => { localStorage.clear(); } }; } const it = 1e3 * 60 * 5; let w = "", E = new URLSearchParams(), _ = null, j, L; function b() { const e = y("access_token"), { keycloak: t } = Z(); return E = new URLSearchParams(decodeURIComponent(window.location.search)), w = `${location.origin}${location.pathname}`, { onAuthenticate: (o) => { j = o; }, onObtainToken: (o) => { L = o; }, check: () => { if (g.enableKeycloak !== !1) return E.get("code") && E.get("session_state") ? at(t) : lt(t); }, refreshToken: () => g.enableKeycloak === !1 ? Promise.resolve() : ne(t), isAuthenticated: () => g.enableKeycloak === !1 ? !0 : !!e, logout: async () => { ct().clear(), await re(t); } }; } async function at(e) { const t = new URLSearchParams(decodeURIComponent(window.location.search)), o = await ft( e, t.get("code") ); oe(o), te(e), ut(), j && j(); } function ut() { const e = localStorage.getItem("redirect_queries"); e ? location.replace(`${w}?${e}`) : location.replace(w), localStorage.removeItem("redirect_queries"); } function ft(e, t) { const o = `${e.url}/realms/${e.realm}/protocol/openid-connect/token`, r = new URLSearchParams([ ["grant_type", "authorization_code"], ["code", t], ["redirect_uri", w], ["client_id", e.client_id] ]); return R(o, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "*/*" }, body: r }); } function te(e) { _ && clearInterval(_), _ = setInterval( () => ne(e), it ); } function oe(e) { S("access_token", e.access_token, { // expires: calculateExpirationDate(token.expires_in), sameSite: "none", secure: !0, httpOnly: !1 }), S("refresh_token", e.refresh_token, { // expires: calculateExpirationDate(token.refresh_expires_in), sameSite: "none", secure: !0, httpOnly: !1 }), L && L(e); } async function ne(e) { const t = y("refresh_token"); t || se(e); const o = `${e.url}/realms/${e.realm}/protocol/openid-connect/token`, r = new URLSearchParams([ ["grant_type", "refresh_token"], ["refresh_token", t || ""], ["client_id", e.client_id] ]), s = await R(o, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "*/*" }, body: r }).catch(async () => { await re(e); }); oe(s); } async function lt(e) { const t = y("access_token"), o = `${e.url}/realms/${e.realm}/protocol/openid-connect/userinfo`; return await R.raw(o, { method: "GET", headers: { Authorization: `Bearer ${t}` } }).catch((r) => { var s; ((s = r.response) == null ? void 0 : s.status) === m.UNAUTHORIZED && ce(e); }).finally(() => { _ || te(e); }); } async function re(e) { const t = y("refresh_token"), o = `${e.url}/realms/${e.realm}/protocol/openid-connect/logout`, r = new URLSearchParams([ ["client_id", e.client_id], ["refresh_token", t] ]); await R.raw(o, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "*/*" }, body: r }).finally(() => se(e)); } function se(e) { clearInterval(_), Y("access_token"), localStorage.removeItem("tooltip_state"), ce(e); } function ce(e) { const t = { response_type: "code", client_id: e.client_id, scope: "openid profile email", redirect_uri: w }, o = `${e.url}/realms/${e.realm}/protocol/openid-connect/auth?${pt(t)}`; localStorage.setItem("redirect_queries", E.toString()), location.replace(o); } function pt(e) { const t = []; for (const o in e) Object.hasOwn(e, o) && t.push(`${encodeURIComponent(o)}=${encodeURIComponent(e[o])}`); return t.join("&"); } function Ot(e, t = !0) { const o = y("access_token"), { rest: r } = Z(); return ht(r, o || void 0, t)[e]; } function ht(e, t, o) { const r = {}; for (const s in e) { const c = e[s]; Object.assign(r, { [s]: dt(c, t, o) }); } return r; } function dt(e, t, o) { return R.create({ baseURL: e.url, headers: { "X-API-KEY": e.key ?? "", Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${t}` }, onRequest() { o && I().show(); }, async onResponse({ request: r, options: s, response: c }) { if (I().hide(), c.status === m.UNAUTHORIZED) { await b().refreshToken(); const i = y("access_token"); s.headers = { ...s.headers, Authorization: `Bearer ${i}` }, c = await R.raw(r, s); } }, onRequestError(r) { throw I().hide(), r; } }); } const C = fe(!1), I = () => ({ show: () => { C.value = !0; }, hide: () => { C.value = !1; }, loading: C }), mt = { install: (e, t) => { const o = yt(), r = o === t.configuration.hostProduction, s = o === t.configuration.hostStaging, c = new URLSearchParams(decodeURIComponent(gt())); let i = localStorage.getItem(P); !c.get(X) && i || (i = Rt(c, r, s), localStorage.setItem(P, i)); } }; function gt() { return location.search; } function yt() { return location.hostname; } function Rt(e, t, o) { let r = _t(e); return t && (r = "prod"), o && r === "dev" && (r = "stg"), r; } function _t(e) { return e.get(X) || "dev"; } function wt(e) { const t = /* @__PURE__ */ new Date(); return new Date(t.setSeconds(t.getSeconds() + e)); } function Et(e) { return new Promise((t) => setTimeout(t, e)); } const Ct = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, calculateExpirationDate: wt, sleep: Et }, Symbol.toStringTag, { value: "Module" })), bt = { environment: mt }; var T, g; const It = { install: (e, t) => { T = t.connections, g = t.configuration, e.use(bt.environment, { configuration: t.configuration }), b().onAuthenticate(g.onAuthenticate || (() => { })), b().onObtainToken(g.onObtainToken || (() => { })), g.router.beforeEach(async (o, r, s) => o.meta.public ? s() : s(!!await b().check())); } }; export { At as BaseApi, m as HttpStatus, g as configuration, T as connections, It as default, Ot as useApi, ct as useAppStorage, Z as useConnections, st as useEnvironment, b as useKeycloak, I as useLoading, Ct as utils };