UNPKG

6.5 kBJavaScriptView Raw
1/*! shopify/graphql-client@0.10.4 -- Copyright (c) 2023-present, Shopify Inc. -- license (MIT): https://github.com/Shopify/shopify-app-js/blob/main/LICENSE.md */
2!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).ShopifyGraphQLClient={})}(this,(function(e){"use strict";const r="GraphQL Client",t=0,n=3,s="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",o="Response returned unexpected Content-Type:",a="An unknown error has occurred. The API did not return a data object or any errors in its response.",i={json:"application/json",multipart:"multipart/mixed"},c="X-SDK-Variant",u="X-SDK-Version",d="shopify-graphql-client",l="0.10.4",f=1e3,y=[429,503],h=/@(defer)\b/i,p=/boundary="?([^=";]+)"?/i,m="\r\n\r\n";function w(e,t=r){return e.startsWith(`${t}`)?e:`${t}: ${e}`}function g(e){return e instanceof Error?e.message:JSON.stringify(e)}function b(e){return e instanceof Error&&e.cause?e.cause:void 0}function x(e){return e.flatMap((({errors:e})=>e??[]))}function E({client:e,retries:r}){if(void 0!==r&&("number"!=typeof r||r<t||r>n))throw new Error(`${e}: The provided "retries" value (${r}) is invalid - it cannot be less than ${t} or greater than ${n}`)}function S(e,r){return r&&("object"!=typeof r||Array.isArray(r)||"object"==typeof r&&Object.keys(r).length>0)?{[e]:r}:{}}function A(e,r){if(0===e.length)return r;const t={[e.pop()]:r};return 0===e.length?t:A(e,t)}function T(e,r){return Object.keys(r||{}).reduce(((t,n)=>("object"==typeof r[n]||Array.isArray(r[n]))&&e[n]?(t[n]=T(e[n],r[n]),t):(t[n]=r[n],t)),Array.isArray(e)?[...e]:{...e})}function $([e,...r]){return r.reduce(T,{...e})}function j({clientLogger:e,customFetchApi:t=fetch,client:n=r,defaultRetryWaitTime:s=f,retriableCodes:o=y}){const a=async(r,i,c)=>{const u=i+1,d=c+1;let l;try{if(l=await t(...r),e({type:"HTTP-Response",content:{requestParams:r,response:l}}),!l.ok&&o.includes(l.status)&&u<=d)throw new Error;return l}catch(t){if(u<=d){const t=l?.headers.get("Retry-After");return await async function(e){return new Promise((r=>setTimeout(r,e)))}(t?parseInt(t,10):s),e({type:"HTTP-Retry",content:{requestParams:r,lastResponse:l,retryAttempt:i,maxRetries:c}}),a(r,u,c)}throw new Error(w(`${c>0?`Attempted maximum number of ${c} network retries. Last message - `:""}${g(t)}`,n))}};return a}async function k(e){const{errors:r,data:t,extensions:n}=await e.json();return{...S("data",t),...S("extensions",n),...r||!t?{errors:{networkStatusCode:e.status,message:w(r?s:a),...S("graphQLErrors",r),response:e}}:{}}}function R(e){return e.map((e=>{try{return JSON.parse(e)}catch(e){throw new Error(`Error in parsing multipart response - ${g(e)}`)}})).map((e=>{const{data:r,incremental:t,hasNext:n,extensions:s,errors:o}=e;if(!t)return{data:r||{},...S("errors",o),...S("extensions",s),hasNext:n};const a=t.map((({data:e,path:r,errors:t})=>({data:e&&r?A(r,e):{},...S("errors",t)})));return{data:1===a.length?a[0].data:$([...a.map((({data:e})=>e))]),...S("errors",x(a)),hasNext:n}}))}function I(e,r){if(e.length>0)throw new Error(s,{cause:{graphQLErrors:e}});if(0===Object.keys(r).length)throw new Error(a)}e.createGraphQLClient=function({headers:e,url:t,customFetchApi:n=fetch,retries:s=0,logger:a}){E({client:r,retries:s});const y={headers:e,url:t,retries:s},A=function(e){return r=>{e&&e(r)}}(a),fetch=function(e,{url:t,headers:n,retries:s}){return async(o,a={})=>{const{variables:i,headers:f,url:y,retries:h}=a,p=JSON.stringify({query:o,variables:i});E({client:r,retries:h});const m=Object.entries({...n,...f}).reduce(((e,[r,t])=>(e[r]=Array.isArray(t)?t.join(", "):t.toString(),e)),{});m[c]||m[u]||(m[c]=d,m[u]=l);return e([y??t,{method:"POST",headers:m,body:p}],1,h??s)}}(j({customFetchApi:n,clientLogger:A,defaultRetryWaitTime:f}),y),T=function(fetch){return async(...e)=>{if(h.test(e[0]))throw new Error(w("This operation will result in a streamable response - use requestStream() instead."));try{const r=await fetch(...e),{status:t,statusText:n}=r,s=r.headers.get("content-type")||"";return r.ok?s.includes(i.json)?k(r):{errors:{networkStatusCode:t,message:w(`${o} ${s}`),response:r}}:{errors:{networkStatusCode:t,message:w(n),response:r}}}catch(e){return{errors:{message:g(e)}}}}}(fetch),L=function(fetch){return async(...e)=>{if(!h.test(e[0]))throw new Error(w("This operation does not result in a streamable response - use request() instead."));try{const r=await fetch(...e),{statusText:t}=r;if(!r.ok)throw new Error(t,{cause:r});const n=r.headers.get("content-type")||"";switch(!0){case n.includes(i.json):return function(e){return{async*[Symbol.asyncIterator](){const r=await k(e);yield{...r,hasNext:!1}}}}(r);case n.includes(i.multipart):return function(e,r){const t=(r??"").match(p),n=`--${t?t[1]:"-"}`;if(!e.body?.getReader&&!e.body[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:e});const s=async function*(e){const r=new TextDecoder;if(e.body[Symbol.asyncIterator])for await(const t of e.body)yield r.decode(t);else{const t=e.body.getReader();let n;try{for(;!(n=await t.read()).done;)yield r.decode(n.value)}finally{t.cancel()}}}(e);let o,a={};return{async*[Symbol.asyncIterator](){try{let e=!0;for await(const r of function(e,r){return{async*[Symbol.asyncIterator](){try{let t="";for await(const n of e)if(t+=n,t.indexOf(r)>-1){const e=t.lastIndexOf(r),n=t.slice(0,e).split(r).filter((e=>e.trim().length>0)).map((e=>e.slice(e.indexOf(m)+m.length).trim()));n.length>0&&(yield n),t=t.slice(e+r.length),"--"===t.trim()&&(t="")}}catch(e){throw new Error(`Error occured while processing stream payload - ${g(e)}`)}}}}(s,n)){const t=R(r);o=t.find((e=>e.extensions))?.extensions??o;const n=x(t);a=$([a,...t.map((({data:e})=>e))]),e=t.slice(-1)[0].hasNext,I(n,a),yield{...S("data",a),...S("extensions",o),hasNext:e}}if(e)throw new Error("Response stream terminated unexpectedly")}catch(r){const t=b(r);yield{...S("data",a),...S("extensions",o),errors:{message:w(g(r)),networkStatusCode:e.status,...S("graphQLErrors",t?.graphQLErrors),response:e},hasNext:!1}}}}}(r,n);default:throw new Error(`${o} ${n}`,{cause:r})}}catch(e){return{async*[Symbol.asyncIterator](){const r=b(e);yield{errors:{message:w(g(e)),...S("networkStatusCode",r?.status),...S("response",r)},hasNext:!1}}}}}}(fetch);return{config:y,fetch:fetch,request:T,requestStream:L}}}));
3//# sourceMappingURL=graphql-client.min.js.map