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