@clicktap/ui 0.34.1 → 0.35.0
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/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ClientError, RequestDocument, Variables } from 'graphql-request';
|
|
2
2
|
import { GraphQLClientRequestHeaders } from 'graphql-request/build/esm/types';
|
|
3
3
|
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
|
|
4
|
+
export { ClientError, GraphQLClient } from 'graphql-request';
|
|
4
5
|
export type AuthAwareEventName = 'unauthenticated' | 'permissionDenied' | 'serverError';
|
|
5
6
|
export interface AuthAwareEventDetail {
|
|
6
7
|
status: number;
|
|
@@ -46,4 +47,3 @@ export declare function createAuthAwareGraphqlClient(): AuthAwareGraphqlClient;
|
|
|
46
47
|
* toast actors.
|
|
47
48
|
*/
|
|
48
49
|
export declare function createAuthAwareFetch(): typeof fetch;
|
|
49
|
-
export {};
|
|
@@ -53,4 +53,4 @@ spurious results.`)}}return!1};class Be{constructor(t,n="GraphQL request",r={lin
|
|
|
53
53
|
}`)}function E(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function K(e){return E(" ",e.replace(/\n/g,`
|
|
54
54
|
`))}function oe(e){var t;return(t=e?.some(n=>n.includes(`
|
|
55
55
|
`)))!==null&&t!==void 0?t:!1}const Ie=e=>{let t;const n=e.definitions.filter(r=>r.kind==="OperationDefinition");return n.length===1&&(t=n[0]?.name?.value),t},ae=e=>{if(typeof e=="string"){let n;try{const r=gt(e);n=Ie(r)}catch{}return{query:e,operationName:n}}const t=Ie(e);return{query:Ft(e),operationName:t}};class B extends Error{constructor(t,n){const r=`${B.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(r),Object.setPrototypeOf(this,B.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,B)}static extractMessage(t){return t.errors?.[0]?.message??`GraphQL Error (Code: ${t.status})`}}var X=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Mt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var W={exports:{}},Oe;function Ut(){return Oe||(Oe=1,(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof X<"u"&&X,r=(function(){function s(){this.fetch=!1,this.DOMException=n.DOMException}return s.prototype=n,new s})();(function(s){(function(c){var u=typeof s<"u"&&s||typeof self<"u"&&self||typeof X<"u"&&X||{},h={searchParams:"URLSearchParams"in u,iterable:"Symbol"in u&&"iterator"in Symbol,blob:"FileReader"in u&&"Blob"in u&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in u,arrayBuffer:"ArrayBuffer"in u};function d(o){return o&&DataView.prototype.isPrototypeOf(o)}if(h.arrayBuffer)var y=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(o){return o&&y.indexOf(Object.prototype.toString.call(o))>-1};function m(o){if(typeof o!="string"&&(o=String(o)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(o)||o==="")throw new TypeError('Invalid character in header field name: "'+o+'"');return o.toLowerCase()}function O(o){return typeof o!="string"&&(o=String(o)),o}function x(o){var l={next:function(){var N=o.shift();return{done:N===void 0,value:N}}};return h.iterable&&(l[Symbol.iterator]=function(){return l}),l}function T(o){this.map={},o instanceof T?o.forEach(function(l,N){this.append(N,l)},this):Array.isArray(o)?o.forEach(function(l){if(l.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+l.length);this.append(l[0],l[1])},this):o&&Object.getOwnPropertyNames(o).forEach(function(l){this.append(l,o[l])},this)}T.prototype.append=function(o,l){o=m(o),l=O(l);var N=this.map[o];this.map[o]=N?N+", "+l:l},T.prototype.delete=function(o){delete this.map[m(o)]},T.prototype.get=function(o){return o=m(o),this.has(o)?this.map[o]:null},T.prototype.has=function(o){return this.map.hasOwnProperty(m(o))},T.prototype.set=function(o,l){this.map[m(o)]=O(l)},T.prototype.forEach=function(o,l){for(var N in this.map)this.map.hasOwnProperty(N)&&o.call(l,this.map[N],N,this)},T.prototype.keys=function(){var o=[];return this.forEach(function(l,N){o.push(N)}),x(o)},T.prototype.values=function(){var o=[];return this.forEach(function(l){o.push(l)}),x(o)},T.prototype.entries=function(){var o=[];return this.forEach(function(l,N){o.push([N,l])}),x(o)},h.iterable&&(T.prototype[Symbol.iterator]=T.prototype.entries);function C(o){if(!o._noBody){if(o.bodyUsed)return Promise.reject(new TypeError("Already read"));o.bodyUsed=!0}}function w(o){return new Promise(function(l,N){o.onload=function(){l(o.result)},o.onerror=function(){N(o.error)}})}function Y(o){var l=new FileReader,N=w(l);return l.readAsArrayBuffer(o),N}function k(o){var l=new FileReader,N=w(l),I=/charset=([A-Za-z0-9_-]+)/.exec(o.type),_=I?I[1]:"utf-8";return l.readAsText(o,_),N}function L(o){for(var l=new Uint8Array(o),N=new Array(l.length),I=0;I<l.length;I++)N[I]=String.fromCharCode(l[I]);return N.join("")}function U(o){if(o.slice)return o.slice(0);var l=new Uint8Array(o.byteLength);return l.set(new Uint8Array(o)),l.buffer}function $(){return this.bodyUsed=!1,this._initBody=function(o){this.bodyUsed=this.bodyUsed,this._bodyInit=o,o?typeof o=="string"?this._bodyText=o:h.blob&&Blob.prototype.isPrototypeOf(o)?this._bodyBlob=o:h.formData&&FormData.prototype.isPrototypeOf(o)?this._bodyFormData=o:h.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)?this._bodyText=o.toString():h.arrayBuffer&&h.blob&&d(o)?(this._bodyArrayBuffer=U(o.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(o)||v(o))?this._bodyArrayBuffer=U(o):this._bodyText=o=Object.prototype.toString.call(o):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof o=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):h.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},h.blob&&(this.blob=function(){var o=C(this);if(o)return o;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var o=C(this);return o||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(h.blob)return this.blob().then(Y);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var o=C(this);if(o)return o;if(this._bodyBlob)return k(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},h.formData&&(this.formData=function(){return this.text().then(qe)}),this.json=function(){return this.text().then(JSON.parse)},this}var z=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ve(o){var l=o.toUpperCase();return z.indexOf(l)>-1?l:o}function F(o,l){if(!(this instanceof F))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');l=l||{};var N=l.body;if(o instanceof F){if(o.bodyUsed)throw new TypeError("Already read");this.url=o.url,this.credentials=o.credentials,l.headers||(this.headers=new T(o.headers)),this.method=o.method,this.mode=o.mode,this.signal=o.signal,!N&&o._bodyInit!=null&&(N=o._bodyInit,o.bodyUsed=!0)}else this.url=String(o);if(this.credentials=l.credentials||this.credentials||"same-origin",(l.headers||!this.headers)&&(this.headers=new T(l.headers)),this.method=Ve(l.method||this.method||"GET"),this.mode=l.mode||this.mode||null,this.signal=l.signal||this.signal||(function(){if("AbortController"in u){var A=new AbortController;return A.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&N)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(N),(this.method==="GET"||this.method==="HEAD")&&(l.cache==="no-store"||l.cache==="no-cache")){var I=/([?&])_=[^&]*/;if(I.test(this.url))this.url=this.url.replace(I,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}F.prototype.clone=function(){return new F(this,{body:this._bodyInit})};function qe(o){var l=new FormData;return o.trim().split("&").forEach(function(N){if(N){var I=N.split("="),_=I.shift().replace(/\+/g," "),A=I.join("=").replace(/\+/g," ");l.append(decodeURIComponent(_),decodeURIComponent(A))}}),l}function je(o){var l=new T,N=o.replace(/\r?\n[\t ]+/g," ");return N.split("\r").map(function(I){return I.indexOf(`
|
|
56
|
-
`)===0?I.substr(1,I.length):I}).forEach(function(I){var _=I.split(":"),A=_.shift().trim();if(A){var J=_.join(":").trim();try{l.append(A,J)}catch(re){console.warn("Response "+re.message)}}}),l}$.call(F.prototype);function S(o,l){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(l||(l={}),this.type="default",this.status=l.status===void 0?200:l.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=l.statusText===void 0?"":""+l.statusText,this.headers=new T(l.headers),this.url=l.url||"",this._initBody(o)}$.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new T(this.headers),url:this.url})},S.error=function(){var o=new S(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var $e=[301,302,303,307,308];S.redirect=function(o,l){if($e.indexOf(l)===-1)throw new RangeError("Invalid status code");return new S(null,{status:l,headers:{location:o}})},c.DOMException=u.DOMException;try{new c.DOMException}catch{c.DOMException=function(l,N){this.message=l,this.name=N;var I=Error(l);this.stack=I.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function ie(o,l){return new Promise(function(N,I){var _=new F(o,l);if(_.signal&&_.signal.aborted)return I(new c.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function J(){A.abort()}A.onload=function(){var D={statusText:A.statusText,headers:je(A.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(A.status<200||A.status>599)?D.status=200:D.status=A.status,D.url="responseURL"in A?A.responseURL:D.headers.get("X-Request-URL");var P="response"in A?A.response:A.responseText;setTimeout(function(){N(new S(P,D))},0)},A.onerror=function(){setTimeout(function(){I(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){I(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){I(new c.DOMException("Aborted","AbortError"))},0)};function re(D){try{return D===""&&u.location.href?u.location.href:D}catch{return D}}if(A.open(_.method,re(_.url),!0),_.credentials==="include"?A.withCredentials=!0:_.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(h.blob?A.responseType="blob":h.arrayBuffer&&(A.responseType="arraybuffer")),l&&typeof l.headers=="object"&&!(l.headers instanceof T||u.Headers&&l.headers instanceof u.Headers)){var Te=[];Object.getOwnPropertyNames(l.headers).forEach(function(D){Te.push(m(D)),A.setRequestHeader(D,O(l.headers[D]))}),_.headers.forEach(function(D,P){Te.indexOf(P)===-1&&A.setRequestHeader(P,D)})}else _.headers.forEach(function(D,P){A.setRequestHeader(P,D)});_.signal&&(_.signal.addEventListener("abort",J),A.onreadystatechange=function(){A.readyState===4&&_.signal.removeEventListener("abort",J)}),A.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return ie.polyfill=!0,u.fetch||(u.fetch=ie,u.Headers=T,u.Request=F,u.Response=S),c.Headers=T,c.Request=F,c.Response=S,c.fetch=ie,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})(W,W.exports)),W.exports}var de=Ut();const ee=Mt(de),Vt=Object.freeze(Object.defineProperty({__proto__:null,default:ee},Symbol.toStringTag,{value:"Module"})),V=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Vt&&de.Headers&&e instanceof de.Headers?t=He(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):t=e),t},_e=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),qt=e=>{if(!Array.isArray(e.query)){const r=e,i=[`query=${encodeURIComponent(_e(r.query))}`];return e.variables&&i.push(`variables=${encodeURIComponent(r.jsonSerializer.stringify(r.variables))}`),r.operationName&&i.push(`operationName=${encodeURIComponent(r.operationName)}`),i.join("&")}if(typeof e.variables<"u"&&!Array.isArray(e.variables))throw new Error("Cannot create query with given variable type, array expected");const t=e,n=e.query.reduce((r,i,s)=>(r.push({query:_e(i),variables:t.variables?t.jsonSerializer.stringify(t.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},jt=e=>async t=>{const{url:n,query:r,variables:i,operationName:s,fetch:c,fetchOptions:u,middleware:h}=t,d={...t.headers};let y="",v;e==="POST"?(v=$t(r,i,s,u.jsonSerializer),typeof v=="string"&&(d["Content-Type"]="application/json")):y=qt({query:r,variables:i,operationName:s,jsonSerializer:u.jsonSerializer??ye});const m={method:e,headers:d,body:v,...u};let O=n,x=m;if(h){const T=await Promise.resolve(h({...m,url:n,operationName:s,variables:i})),{url:C,...w}=T;O=C,x=w}return y&&(O=`${O}?${y}`),await c(O,x)};class ge{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...r)=>{const[i,s,c]=r,u=ze(i,s,c),{headers:h,fetch:d=ee,method:y="POST",requestMiddleware:v,responseMiddleware:m,...O}=this.requestConfig,{url:x}=this;u.signal!==void 0&&(O.signal=u.signal);const{operationName:T}=ae(u.query);return ce({url:x,query:u.query,variables:u.variables,headers:{...V(ue(h)),...V(u.requestHeaders)},operationName:T,fetch:d,method:y,fetchOptions:O,middleware:v}).then(C=>(m&&m(C),C)).catch(C=>{throw m&&m(C),C})}}async request(t,...n){const[r,i]=n,s=Ye(t,r,i),{headers:c,fetch:u=ee,method:h="POST",requestMiddleware:d,responseMiddleware:y,...v}=this.requestConfig,{url:m}=this;s.signal!==void 0&&(v.signal=s.signal);const{query:O,operationName:x}=ae(s.document);return ce({url:m,query:O,variables:s.variables,headers:{...V(ue(c)),...V(s.requestHeaders)},operationName:x,fetch:u,method:h,fetchOptions:v,middleware:d}).then(T=>(y&&y(T),T.data)).catch(T=>{throw y&&y(T),T})}batchRequests(t,n){const r=Je(t,n),{headers:i,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const c=r.documents.map(({document:h})=>ae(h).query),u=r.documents.map(({variables:h})=>h);return ce({url:this.url,query:c,variables:u,headers:{...V(ue(i)),...V(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??ee,method:this.requestConfig.method||"POST",fetchOptions:s,middleware:this.requestConfig.requestMiddleware}).then(h=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h.data)).catch(h=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h})}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const ce=async e=>{const{query:t,variables:n,fetchOptions:r}=e,i=jt(Ge(e.method??"post")),s=Array.isArray(e.query),c=await i(e),u=await Gt(c,r.jsonSerializer??ye),h=Array.isArray(u)?!u.some(({data:y})=>!y):!!u.data,d=Array.isArray(u)||!u.errors||Array.isArray(u.errors)&&!u.errors.length||r.errorPolicy==="all"||r.errorPolicy==="ignore";if(c.ok&&d&&h){const{errors:y,...v}=(Array.isArray(u),u),m=r.errorPolicy==="ignore"?v:u;return{...s?{data:m}:m,headers:c.headers,status:c.status}}else{const y=typeof u=="string"?{error:u}:u;throw new B({...y,status:c.status,headers:c.headers},{query:t,variables:n})}},$t=(e,t,n,r)=>{const i=r??ye;if(!Array.isArray(e))return i.stringify({query:e,variables:t,operationName:n});if(typeof t<"u"&&!Array.isArray(t))throw new Error("Cannot create request body with given variable type, array expected");const s=e.reduce((c,u,h)=>(c.push({query:u,variables:t?t[h]:void 0}),c),[]);return i.stringify(s)},Gt=async(e,t)=>{let n;return e.headers.forEach((r,i)=>{i.toLowerCase()==="content-type"&&(n=r)}),n&&(n.toLowerCase().startsWith("application/json")||n.toLowerCase().startsWith("application/graphql+json")||n.toLowerCase().startsWith("application/graphql-response+json"))?t.parse(await e.text()):e.text()},ue=e=>typeof e=="function"?e():e;class Ht{constructor(){this.listeners=new Map}subscribe(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n)}}dispatch(t,n){this.listeners.get(t)?.forEach(r=>r(n))}}const le=new Ht;function Ue(e,t){e===401?le.dispatch("unauthenticated",t):e===403?le.dispatch("permissionDenied",t):e>=500&&le.dispatch("serverError",t)}function be(e){if(!(e instanceof B))return;const t=e.response?.status;typeof t=="number"&&Ue(t,{status:t,error:e})}function De(e){if(e instanceof B&&e.response?.data){const{data:t,errors:n}=e.response;if(t){if(process.env.NODE_ENV==="development"&&n?.length){const{query:r,variables:i}=e.request??{},s=r?.match(/^\s*(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/)?.[1];for(const c of n)console.error(`[GraphQL] ${s??"operation"} — field error at ${c.path?.join(".")??"unknown"}: ${c.message}`,{error:c,request:{operationName:s,variables:i,query:r}})}return t}}throw e}function Yt(){const e=async(r,i,s,c)=>{const u=new ge(r,{headers:c});try{return await u.request({document:i,variables:s})}catch(h){return be(h),De(h)}},t=async r=>{const i=new ge(r.url,{headers:r.requestHeaders,signal:r.signal});try{return await i.request({document:r.document,variables:r.variables})}catch(s){return be(s),De(s)}},n=e;return n.withOptions=t,n}function zt(){return async function(t,n){const r=await fetch(t,n);return(r.status===401||r.status===403||r.status>=500)&&Ue(r.status,{status:r.status,response:r.clone()}),r}}export{le as authAwareEvents,zt as createAuthAwareFetch,Yt as createAuthAwareGraphqlClient};
|
|
56
|
+
`)===0?I.substr(1,I.length):I}).forEach(function(I){var _=I.split(":"),A=_.shift().trim();if(A){var J=_.join(":").trim();try{l.append(A,J)}catch(re){console.warn("Response "+re.message)}}}),l}$.call(F.prototype);function S(o,l){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(l||(l={}),this.type="default",this.status=l.status===void 0?200:l.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=l.statusText===void 0?"":""+l.statusText,this.headers=new T(l.headers),this.url=l.url||"",this._initBody(o)}$.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new T(this.headers),url:this.url})},S.error=function(){var o=new S(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var $e=[301,302,303,307,308];S.redirect=function(o,l){if($e.indexOf(l)===-1)throw new RangeError("Invalid status code");return new S(null,{status:l,headers:{location:o}})},c.DOMException=u.DOMException;try{new c.DOMException}catch{c.DOMException=function(l,N){this.message=l,this.name=N;var I=Error(l);this.stack=I.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function ie(o,l){return new Promise(function(N,I){var _=new F(o,l);if(_.signal&&_.signal.aborted)return I(new c.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function J(){A.abort()}A.onload=function(){var D={statusText:A.statusText,headers:je(A.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(A.status<200||A.status>599)?D.status=200:D.status=A.status,D.url="responseURL"in A?A.responseURL:D.headers.get("X-Request-URL");var P="response"in A?A.response:A.responseText;setTimeout(function(){N(new S(P,D))},0)},A.onerror=function(){setTimeout(function(){I(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){I(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){I(new c.DOMException("Aborted","AbortError"))},0)};function re(D){try{return D===""&&u.location.href?u.location.href:D}catch{return D}}if(A.open(_.method,re(_.url),!0),_.credentials==="include"?A.withCredentials=!0:_.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(h.blob?A.responseType="blob":h.arrayBuffer&&(A.responseType="arraybuffer")),l&&typeof l.headers=="object"&&!(l.headers instanceof T||u.Headers&&l.headers instanceof u.Headers)){var Te=[];Object.getOwnPropertyNames(l.headers).forEach(function(D){Te.push(m(D)),A.setRequestHeader(D,O(l.headers[D]))}),_.headers.forEach(function(D,P){Te.indexOf(P)===-1&&A.setRequestHeader(P,D)})}else _.headers.forEach(function(D,P){A.setRequestHeader(P,D)});_.signal&&(_.signal.addEventListener("abort",J),A.onreadystatechange=function(){A.readyState===4&&_.signal.removeEventListener("abort",J)}),A.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return ie.polyfill=!0,u.fetch||(u.fetch=ie,u.Headers=T,u.Request=F,u.Response=S),c.Headers=T,c.Request=F,c.Response=S,c.fetch=ie,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})(W,W.exports)),W.exports}var de=Ut();const ee=Mt(de),Vt=Object.freeze(Object.defineProperty({__proto__:null,default:ee},Symbol.toStringTag,{value:"Module"})),V=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Vt&&de.Headers&&e instanceof de.Headers?t=He(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):t=e),t},_e=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),qt=e=>{if(!Array.isArray(e.query)){const r=e,i=[`query=${encodeURIComponent(_e(r.query))}`];return e.variables&&i.push(`variables=${encodeURIComponent(r.jsonSerializer.stringify(r.variables))}`),r.operationName&&i.push(`operationName=${encodeURIComponent(r.operationName)}`),i.join("&")}if(typeof e.variables<"u"&&!Array.isArray(e.variables))throw new Error("Cannot create query with given variable type, array expected");const t=e,n=e.query.reduce((r,i,s)=>(r.push({query:_e(i),variables:t.variables?t.jsonSerializer.stringify(t.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},jt=e=>async t=>{const{url:n,query:r,variables:i,operationName:s,fetch:c,fetchOptions:u,middleware:h}=t,d={...t.headers};let y="",v;e==="POST"?(v=$t(r,i,s,u.jsonSerializer),typeof v=="string"&&(d["Content-Type"]="application/json")):y=qt({query:r,variables:i,operationName:s,jsonSerializer:u.jsonSerializer??ye});const m={method:e,headers:d,body:v,...u};let O=n,x=m;if(h){const T=await Promise.resolve(h({...m,url:n,operationName:s,variables:i})),{url:C,...w}=T;O=C,x=w}return y&&(O=`${O}?${y}`),await c(O,x)};class ge{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...r)=>{const[i,s,c]=r,u=ze(i,s,c),{headers:h,fetch:d=ee,method:y="POST",requestMiddleware:v,responseMiddleware:m,...O}=this.requestConfig,{url:x}=this;u.signal!==void 0&&(O.signal=u.signal);const{operationName:T}=ae(u.query);return ce({url:x,query:u.query,variables:u.variables,headers:{...V(ue(h)),...V(u.requestHeaders)},operationName:T,fetch:d,method:y,fetchOptions:O,middleware:v}).then(C=>(m&&m(C),C)).catch(C=>{throw m&&m(C),C})}}async request(t,...n){const[r,i]=n,s=Ye(t,r,i),{headers:c,fetch:u=ee,method:h="POST",requestMiddleware:d,responseMiddleware:y,...v}=this.requestConfig,{url:m}=this;s.signal!==void 0&&(v.signal=s.signal);const{query:O,operationName:x}=ae(s.document);return ce({url:m,query:O,variables:s.variables,headers:{...V(ue(c)),...V(s.requestHeaders)},operationName:x,fetch:u,method:h,fetchOptions:v,middleware:d}).then(T=>(y&&y(T),T.data)).catch(T=>{throw y&&y(T),T})}batchRequests(t,n){const r=Je(t,n),{headers:i,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const c=r.documents.map(({document:h})=>ae(h).query),u=r.documents.map(({variables:h})=>h);return ce({url:this.url,query:c,variables:u,headers:{...V(ue(i)),...V(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??ee,method:this.requestConfig.method||"POST",fetchOptions:s,middleware:this.requestConfig.requestMiddleware}).then(h=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h.data)).catch(h=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h})}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const ce=async e=>{const{query:t,variables:n,fetchOptions:r}=e,i=jt(Ge(e.method??"post")),s=Array.isArray(e.query),c=await i(e),u=await Gt(c,r.jsonSerializer??ye),h=Array.isArray(u)?!u.some(({data:y})=>!y):!!u.data,d=Array.isArray(u)||!u.errors||Array.isArray(u.errors)&&!u.errors.length||r.errorPolicy==="all"||r.errorPolicy==="ignore";if(c.ok&&d&&h){const{errors:y,...v}=(Array.isArray(u),u),m=r.errorPolicy==="ignore"?v:u;return{...s?{data:m}:m,headers:c.headers,status:c.status}}else{const y=typeof u=="string"?{error:u}:u;throw new B({...y,status:c.status,headers:c.headers},{query:t,variables:n})}},$t=(e,t,n,r)=>{const i=r??ye;if(!Array.isArray(e))return i.stringify({query:e,variables:t,operationName:n});if(typeof t<"u"&&!Array.isArray(t))throw new Error("Cannot create request body with given variable type, array expected");const s=e.reduce((c,u,h)=>(c.push({query:u,variables:t?t[h]:void 0}),c),[]);return i.stringify(s)},Gt=async(e,t)=>{let n;return e.headers.forEach((r,i)=>{i.toLowerCase()==="content-type"&&(n=r)}),n&&(n.toLowerCase().startsWith("application/json")||n.toLowerCase().startsWith("application/graphql+json")||n.toLowerCase().startsWith("application/graphql-response+json"))?t.parse(await e.text()):e.text()},ue=e=>typeof e=="function"?e():e;class Ht{constructor(){this.listeners=new Map}subscribe(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n)}}dispatch(t,n){this.listeners.get(t)?.forEach(r=>r(n))}}const le=new Ht;function Ue(e,t){e===401?le.dispatch("unauthenticated",t):e===403?le.dispatch("permissionDenied",t):e>=500&&le.dispatch("serverError",t)}function be(e){if(!(e instanceof B))return;const t=e.response?.status;typeof t=="number"&&Ue(t,{status:t,error:e})}function De(e){if(e instanceof B&&e.response?.data){const{data:t,errors:n}=e.response;if(t){if(process.env.NODE_ENV==="development"&&n?.length){const{query:r,variables:i}=e.request??{},s=r?.match(/^\s*(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/)?.[1];for(const c of n)console.error(`[GraphQL] ${s??"operation"} — field error at ${c.path?.join(".")??"unknown"}: ${c.message}`,{error:c,request:{operationName:s,variables:i,query:r}})}return t}}throw e}function Yt(){const e=async(r,i,s,c)=>{const u=new ge(r,{headers:c});try{return await u.request({document:i,variables:s})}catch(h){return be(h),De(h)}},t=async r=>{const i=new ge(r.url,{headers:r.requestHeaders,signal:r.signal});try{return await i.request({document:r.document,variables:r.variables})}catch(s){return be(s),De(s)}},n=e;return n.withOptions=t,n}function zt(){return async function(t,n){const r=await fetch(t,n);return(r.status===401||r.status===403||r.status>=500)&&Ue(r.status,{status:r.status,response:r.clone()}),r}}export{B as ClientError,ge as GraphQLClient,le as authAwareEvents,zt as createAuthAwareFetch,Yt as createAuthAwareGraphqlClient};
|
package/utils/error.d.ts
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structurally extract the HTTP status from a `graphql-request` `ClientError`
|
|
3
|
+
* (or any error carrying `response.status`) — without an `instanceof` check.
|
|
4
|
+
*
|
|
5
|
+
* `graphql-request` is bundled per consuming package, so an
|
|
6
|
+
* `error instanceof ClientError` using a consumer's *own* copy of the class
|
|
7
|
+
* fails for an error thrown by `@clicktap/ui`'s bundled copy (the dual-package
|
|
8
|
+
* hazard) — the redirect / logout path then silently never fires. Duck-typing
|
|
9
|
+
* `response.status` is identity-agnostic and works regardless of which copy
|
|
10
|
+
* threw, so prefer this at cross-package boundaries (SSR route/data fetches,
|
|
11
|
+
* actor error handlers) over `instanceof`.
|
|
12
|
+
*
|
|
13
|
+
* Returns `undefined` when no numeric status is present.
|
|
14
|
+
*/
|
|
15
|
+
export declare function getRequestErrorStatus(error: unknown): number | undefined;
|
|
1
16
|
/**
|
|
2
17
|
* Returns a safe, user-facing error message.
|
|
3
18
|
*
|
package/utils/error.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isDevelopment as
|
|
1
|
+
import{isDevelopment as n}from"./env.js";const o="Something went wrong. Please try again later.";function r(t){if(t==null||typeof t!="object"||!("response"in t))return;const e=t.response;if(e==null||typeof e!="object"||!("status"in e))return;const s=e.status;return typeof s=="number"?s:void 0}function i(t,e=o){if(n){const s=r(t);console.error("[Request Error]",...s?[s]:[],t)}return e}export{i as default,r as getRequestErrorStatus,i as getSafeErrorMessage};
|