@commercetools/ts-client 3.2.1 → 3.2.2
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/CHANGELOG.md +6 -0
- package/dist/commercetools-ts-client.browser.cjs.js +2 -2
- package/dist/commercetools-ts-client.browser.esm.js +2 -2
- package/dist/commercetools-ts-client.cjs.dev.js +2 -2
- package/dist/commercetools-ts-client.cjs.prod.js +2 -2
- package/dist/commercetools-ts-client.esm.js +2 -2
- package/dist/commercetools-ts-client.umd.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @commercetools/ts-client
|
|
2
2
|
|
|
3
|
+
## 3.2.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#1011](https://github.com/commercetools/commercetools-sdk-typescript/pull/1011) [`008f9df`](https://github.com/commercetools/commercetools-sdk-typescript/commit/008f9dfa4fd9ad82c9cdfe90ac4235389d6182b1) Thanks [@ajimae](https://github.com/ajimae)! - Fix typographical error in client user agent
|
|
8
|
+
|
|
3
9
|
## 3.2.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
|
@@ -436,7 +436,7 @@ function stringifyURLString(object, stringifier = urlStringifier) {
|
|
|
436
436
|
const isBrowser = () => window.document && window.document.nodeType === 9;
|
|
437
437
|
function getSystemInfo() {
|
|
438
438
|
if (isBrowser()) return window.navigator.userAgent;
|
|
439
|
-
const nodeVersion = process?.version?.slice(1) || '
|
|
439
|
+
const nodeVersion = process?.version?.slice(1) || 'unknown'; // unknow environment like React Native etc
|
|
440
440
|
const platformInfo = `(${process?.platform || ''}; ${process?.arch || ''})`;
|
|
441
441
|
return `node.js/${nodeVersion} ${platformInfo.trim()}`;
|
|
442
442
|
}
|
|
@@ -1169,7 +1169,7 @@ function createQueueMiddleware$1({
|
|
|
1169
1169
|
|
|
1170
1170
|
var packageJson = {
|
|
1171
1171
|
name: "@commercetools/ts-client",
|
|
1172
|
-
version: "3.2.
|
|
1172
|
+
version: "3.2.2",
|
|
1173
1173
|
engines: {
|
|
1174
1174
|
node: ">=18"
|
|
1175
1175
|
},
|
|
@@ -432,7 +432,7 @@ function stringifyURLString(object, stringifier = urlStringifier) {
|
|
|
432
432
|
const isBrowser = () => window.document && window.document.nodeType === 9;
|
|
433
433
|
function getSystemInfo() {
|
|
434
434
|
if (isBrowser()) return window.navigator.userAgent;
|
|
435
|
-
const nodeVersion = process?.version?.slice(1) || '
|
|
435
|
+
const nodeVersion = process?.version?.slice(1) || 'unknown'; // unknow environment like React Native etc
|
|
436
436
|
const platformInfo = `(${process?.platform || ''}; ${process?.arch || ''})`;
|
|
437
437
|
return `node.js/${nodeVersion} ${platformInfo.trim()}`;
|
|
438
438
|
}
|
|
@@ -1165,7 +1165,7 @@ function createQueueMiddleware$1({
|
|
|
1165
1165
|
|
|
1166
1166
|
var packageJson = {
|
|
1167
1167
|
name: "@commercetools/ts-client",
|
|
1168
|
-
version: "3.2.
|
|
1168
|
+
version: "3.2.2",
|
|
1169
1169
|
engines: {
|
|
1170
1170
|
node: ">=18"
|
|
1171
1171
|
},
|
|
@@ -436,7 +436,7 @@ function stringifyURLString(object, stringifier = urlStringifier) {
|
|
|
436
436
|
const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
|
|
437
437
|
function getSystemInfo() {
|
|
438
438
|
if (isBrowser()) return window.navigator.userAgent;
|
|
439
|
-
const nodeVersion = process?.version?.slice(1) || '
|
|
439
|
+
const nodeVersion = process?.version?.slice(1) || 'unknown'; // unknow environment like React Native etc
|
|
440
440
|
const platformInfo = `(${process?.platform || ''}; ${process?.arch || ''})`;
|
|
441
441
|
return `node.js/${nodeVersion} ${platformInfo.trim()}`;
|
|
442
442
|
}
|
|
@@ -1169,7 +1169,7 @@ function createQueueMiddleware$1({
|
|
|
1169
1169
|
|
|
1170
1170
|
var packageJson = {
|
|
1171
1171
|
name: "@commercetools/ts-client",
|
|
1172
|
-
version: "3.2.
|
|
1172
|
+
version: "3.2.2",
|
|
1173
1173
|
engines: {
|
|
1174
1174
|
node: ">=18"
|
|
1175
1175
|
},
|
|
@@ -436,7 +436,7 @@ function stringifyURLString(object, stringifier = urlStringifier) {
|
|
|
436
436
|
const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
|
|
437
437
|
function getSystemInfo() {
|
|
438
438
|
if (isBrowser()) return window.navigator.userAgent;
|
|
439
|
-
const nodeVersion = process?.version?.slice(1) || '
|
|
439
|
+
const nodeVersion = process?.version?.slice(1) || 'unknown'; // unknow environment like React Native etc
|
|
440
440
|
const platformInfo = `(${process?.platform || ''}; ${process?.arch || ''})`;
|
|
441
441
|
return `node.js/${nodeVersion} ${platformInfo.trim()}`;
|
|
442
442
|
}
|
|
@@ -1169,7 +1169,7 @@ function createQueueMiddleware$1({
|
|
|
1169
1169
|
|
|
1170
1170
|
var packageJson = {
|
|
1171
1171
|
name: "@commercetools/ts-client",
|
|
1172
|
-
version: "3.2.
|
|
1172
|
+
version: "3.2.2",
|
|
1173
1173
|
engines: {
|
|
1174
1174
|
node: ">=18"
|
|
1175
1175
|
},
|
|
@@ -432,7 +432,7 @@ function stringifyURLString(object, stringifier = urlStringifier) {
|
|
|
432
432
|
const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
|
|
433
433
|
function getSystemInfo() {
|
|
434
434
|
if (isBrowser()) return window.navigator.userAgent;
|
|
435
|
-
const nodeVersion = process?.version?.slice(1) || '
|
|
435
|
+
const nodeVersion = process?.version?.slice(1) || 'unknown'; // unknow environment like React Native etc
|
|
436
436
|
const platformInfo = `(${process?.platform || ''}; ${process?.arch || ''})`;
|
|
437
437
|
return `node.js/${nodeVersion} ${platformInfo.trim()}`;
|
|
438
438
|
}
|
|
@@ -1165,7 +1165,7 @@ function createQueueMiddleware$1({
|
|
|
1165
1165
|
|
|
1166
1166
|
var packageJson = {
|
|
1167
1167
|
name: "@commercetools/ts-client",
|
|
1168
|
-
version: "3.2.
|
|
1168
|
+
version: "3.2.2",
|
|
1169
1169
|
engines: {
|
|
1170
1170
|
node: ">=18"
|
|
1171
1171
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var window;(window||={})["@commercetools/ts-client"]=(()=>{var ue=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var ce=(e,t)=>{for(var r in t)ue(e,r,{get:t[r],enumerable:!0})},Ue=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ie(t))!Ne.call(e,i)&&i!==r&&ue(e,i,{get:()=>t[i],enumerable:!(o=Fe(t,i))||o.enumerable});return e};var je=e=>Ue(ue({},"__esModule",{value:!0}),e);var mt={};ce(mt,{ClientBuilder:()=>L,Process:()=>de,createAuthMiddlewareForAnonymousSessionFlow:()=>v,createAuthMiddlewareForClientCredentialsFlow:()=>H,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>B,createAuthMiddlewareForRefreshTokenFlow:()=>K,createClient:()=>P,createConcurrentModificationMiddleware:()=>z,createCorrelationIdMiddleware:()=>J,createHttpMiddleware:()=>V,createLoggerMiddleware:()=>G,createQueueMiddleware:()=>Y,createUserAgentMiddleware:()=>W});var Ae={};ce(Ae,{createAuthMiddlewareForAnonymousSessionFlow:()=>v,createAuthMiddlewareForClientCredentialsFlow:()=>H,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>B,createAuthMiddlewareForRefreshTokenFlow:()=>K,createConcurrentModificationMiddleware:()=>z,createCorrelationIdMiddleware:()=>J,createErrorMiddleware:()=>Re,createHttpMiddleware:()=>V,createLoggerMiddleware:()=>G,createQueueMiddleware:()=>Y,createUserAgentMiddleware:()=>W});function I(e){return e&&typeof e=="string"?new TextEncoder().encode(e).length.toString():e&&e instanceof Uint8Array?e.byteLength.toString():e&&typeof e=="object"?new TextEncoder().encode(JSON.stringify(e)).length.toString():"0"}var g={};ce(g,{CONCURRENCT_REQUEST:()=>He,CTP_API_URL:()=>_e,CTP_AUTH_URL:()=>Be,DEFAULT_HEADERS:()=>pe,HEADERS_CONTENT_TYPES:()=>ve});var ve=["application/json","application/graphql"],He=20,_e="https://api.europe-west1.gcp.commercetools.com",Be="https://auth.europe-west1.gcp.commercetools.com",pe=["content-type","access-control-allow-origin","access-control-allow-headers","access-control-allow-methods","access-control-expose-headers","access-control-max-ag","x-correlation-id","server-timing","date","server","transfer-encoding","access-control-max-age","content-encoding","x-envoy-upstream-service-time","via","alt-svc","connection"];function b(e,t,r={}){this.code=r.code??=this.constructor.name,this.statusCode=e,this.status=e,this.message=t,Object.assign(this,r),this.name=this.constructor.name,this.constructor.prototype.__proto__=Error.prototype,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}function be(...e){b.call(this,0,...e)}function Te(...e){b.call(this,...e)}function Ke(...e){b.call(this,400,...e)}function Le(...e){b.call(this,401,...e)}function $e(...e){b.call(this,403,...e)}function De(...e){b.call(this,404,...e)}function Qe(...e){b.call(this,409,...e)}function ze(...e){b.call(this,500,...e)}function Je(...e){b.call(this,503,...e)}function he(e){switch(e){case 0:return be;case 400:return Ke;case 401:return Le;case 403:return $e;case 404:return De;case 409:return Qe;case 500:return ze;case 503:return Je;default:return}}function Ve({statusCode:e,message:t,...r}){let o=t||"Unexpected non-JSON error response";e===404&&(o=`URI not found: ${r.originalRequest?.uri||r.uri}`);let i=he(e);return i?new i(o,r):new Te(e,o,r)}var N=Ve;function Ge(e,t){return[503,...e].includes(t?.status||t?.statusCode)}async function Ye(e,t){async function r(){return await e({...t,headers:{...t.headers}})}return r().catch(o=>Promise.reject(o))}async function U(e){let{url:t,httpClient:r,...o}=e;return await Ye(async s=>{let{enableRetry:a,retryConfig:n,timeout:u,getAbortController:l}=o,{retryCodes:d=[],maxDelay:c=1/0,maxRetries:M=3,backoff:C=!0,retryDelay:p=200,retryOnAbort:S=!0}=n||{},h,w,f=0,q;we(d);async function x(){return r(t,{...s,...o,headers:{...o.headers},...o.body?{data:o.body}:{},withCredentials:s.credentialsMode==="include"})}function X(){let y=(l?l():null)||new AbortController;return o.abortController=y,o.signal=y.signal,y}async function F(){let y=async(ee,qe)=>{let D={};if(u){let O=X();q=setTimeout(()=>{O.abort(),O=X()},u)}try{if(D=await x(),D.status>399&&Ge(ee,D))return{_response:D,shouldRetry:!0}}catch(O){if((O.name.includes("AbortError")||O.name.includes("TimeoutError"))&&qe)return{_response:O,shouldRetry:!0};throw O}finally{clearTimeout(q)}return{_response:D,shouldRetry:!1}},{_response:$,shouldRetry:Z}=await y(d,S);for(;a&&Z&&f<M;){f++,await re(te({retryCount:f,retryDelay:p,maxRetries:M,backoff:C,maxDelay:c}));let ee=await y(d,S);$=ee._response,Z=ee.shouldRetry}return $}let m=await F();try{m.text&&typeof m.text=="function"?(h=await m.text()||JSON.stringify(m[Object.getOwnPropertySymbols(m)[1]]),w=JSON.parse(h)):w=m.data||m}catch(y){throw y}return{data:w,retryCount:f,statusCode:m.status||m.statusCode||w.statusCode,headers:m.headers}},{validateStatus:s=>!0})}function oe(){return("1000000-1000-4000-8000"+-1e11).replace(/[018]/g,e=>(parseInt(e)^Math.floor(Math.random()*256)&15>>parseInt(e)/4).toString(16))}function We(e){return pe.reduce((t,r)=>{let o=e[r]?e[r]:typeof e.get=="function"?e.get(r):null;return o&&(t[r]=o),t},{})}function T(e){if(!e)return null;if(e.raw&&typeof e.raw=="function")return e.raw();if(!e.forEach)return We(e);let t={};return e.forEach((r,o)=>t[o]=r),t}function Q(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e)}function k(e){let t=JSON.parse(JSON.stringify(e));return t?.headers&&(t.headers.Authorization&&(t.headers.Authorization="Bearer ********"),t.headers.authorization&&(t.headers.authorization="Bearer ********")),t}function j(e,t){return{...t,headers:{...t.headers,Authorization:`Bearer ${e}`}}}var fe=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];function te({retryCount:e,retryDelay:t,backoff:r,maxDelay:o}){return r&&e!==0?Math.min(Math.round((Math.random()+1)*t*2**e),o):t}Math.min(Math.round((Math.random()+1)*200*2**10),1/0);function re(e){return new Promise(t=>{setTimeout(t,e)})}function R(e){if(!e?.credentials?.clientId||!e.projectKey||!e.host)throw new Error("Missing required options.");return{clientId:e.credentials.clientId,host:e.host,projectKey:e.projectKey}}function ie(e){return Date.now()+e*1e3-5*60*1e3}function A(e){let t=e;return{get:r=>t,set:(r,o)=>{t=r}}}function xe(e){return typeof e<"u"&&e!==null}function Xe(e){return xe(e)?typeof e=="string"?e:Object.fromEntries(Object.entries(e).filter(([t,r])=>![null,void 0,""].includes(r))):""}function Ze(e){let t={},r=new URLSearchParams(e);for(let o of r.keys())r.getAll(o).length>1?t[o]=r.getAll(o):t[o]=r.get(o);return t}function et(e){if(e=Xe(e),!e)return"";let t=new URLSearchParams(e);for(let[r,o]of Object.entries(e))Array.isArray(o)&&(t.delete(r),o.filter(xe).forEach(i=>t.append(r,i)));return t.toString()}function me(e,t=Ze){return t(e)}function ne(e,t=et){return t(e)}var tt=()=>typeof window<"u"&&window.document&&window.document.nodeType===9;function rt(){if(tt())return window.navigator.userAgent;let e=process?.version?.slice(1)||"unknow",t=`(${process?.platform||""}; ${process?.arch||""})`;return`node.js/${e} ${t.trim()}`}function se(e){let t=null,r=null;if(!e)throw new Error("Missing required option `name`");let o=e.version?`${e.name}/${e.version}`:e.name;e.libraryName&&!e.libraryVersion?t=e.libraryName:e.libraryName&&e.libraryVersion&&(t=`${e.libraryName}/${e.libraryVersion}`),e.contactUrl&&!e.contactEmail?r=`(+${e.contactUrl})`:!e.contactUrl&&e.contactEmail?r=`(+${e.contactEmail})`:e.contactUrl&&e.contactEmail&&(r=`(+${e.contactUrl}; +${e.contactEmail})`);let i=rt(),s=e.customAgent||"";return[o,i,t,r,s].filter(Boolean).join(" ")}function ye(e){if(!e.host)throw new Error("Request `host` or `url` is missing or invalid, please pass in a valid host e.g `host: http://a-valid-host-url`");if(!e.httpClient&&typeof e.httpClient!="function")throw new Error("An `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.");if(e.httpClientOptions&&Object.prototype.toString.call(e.httpClientOptions)!=="[object Object]")throw new Error("`httpClientOptions` must be an object type")}function we(e){if(!Array.isArray(e))throw new Error("`retryCodes` option must be an array of retry status (error) codes and/or messages.")}function Me(e){if(!e)throw new Error("Missing required options");if(e.middlewares&&!Array.isArray(e.middlewares))throw new Error("Middlewares should be an array");if(!e.middlewares||!Array.isArray(e.middlewares)||!e.middlewares.length)throw new Error("You need to provide at least one middleware")}function ae(e,t,r={allowedMethods:fe}){if(!t)throw new Error(`The "${e}" function requires a "Request" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(typeof t.uri!="string")throw new Error(`The "${e}" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(!r.allowedMethods.includes(t.method))throw new Error(`The "${e}" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`)}function ge(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:t,clientSecret:r}=e.credentials||{};if(!(t&&r))throw new Error("Missing required credentials (clientId, clientSecret)");let o=e.scopes?e.scopes.join(" "):void 0,i=btoa(`${t}:${r}`),s=e.oauthUri||"/oauth/token",a=e.host.replace(/\/$/,"")+s,n=`grant_type=client_credentials${o?`&scope=${o}`:""}`;return{url:a,body:n,basicAuth:i}}function Ee(e){if(!e)throw new Error("Missing required options");if(!e.projectKey)throw new Error("Missing required option (projectKey)");let t=e.projectKey;e.oauthUri=e.oauthUri||`/oauth/${t}/anonymous/token`;let r=ge(e);return e.credentials.anonymousId&&(r.body+=`&anonymous_id=${e.credentials.anonymousId}`),{...r}}function le(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");if(!e.refreshToken)throw new Error("Missing required option (refreshToken)");let{clientId:t,clientSecret:r}=e.credentials;if(!(t&&r))throw new Error("Missing required credentials (clientId, clientSecret)");let o=btoa(`${t}:${r}`),i=e.oauthUri||"/oauth/token",s=e.host.replace(/\/$/,"")+i,a=`grant_type=refresh_token&refresh_token=${encodeURIComponent(e.refreshToken)}`;return{basicAuth:o,url:s,body:a}}function Oe(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:t,clientSecret:r,user:o}=e.credentials,i=e.projectKey;if(!(t&&r&&o))throw new Error("Missing required credentials (clientId, clientSecret, user)");let{username:s,password:a}=o;if(!(s&&a))throw new Error("Missing required user credentials (username, password)");let n=(e.scopes||[]).join(" "),u=n?`&scope=${n}`:"",l=btoa(`${t}:${r}`),d=e.oauthUri||`/oauth/${i}/customers/token`,c=e.host.replace(/\/$/,"")+d,M=`grant_type=password&username=${encodeURIComponent(s)}&password=${encodeURIComponent(a)}${u}`;return{basicAuth:l,url:c,body:M}}async function Ce(e){let{httpClient:t,httpClientOptions:r,tokenCache:o,userOption:i,tokenCacheObject:s}=e,a=e.url,n=e.body,u=e.basicAuth;if(!t||typeof t!="function")throw new Error("an `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.");if(s&&s.refreshToken&&(!s.token||s.token&&Date.now()>s.expirationTime)){if(!i)throw new Error("Missing required options.");let d={...le({...i,refreshToken:s.refreshToken})};a=d.url,n=d.body,u=d.basicAuth}let l;try{if(l=await U({url:a,method:"POST",headers:{Authorization:`Basic ${u}`,"Content-Type":"application/x-www-form-urlencoded","Content-Length":I(n)},httpClient:t,httpClientOptions:r,body:n}),l.statusCode>=200&&l.statusCode<300){let{access_token:d,expires_in:c,refresh_token:M}=l?.data,C=ie(c);return o.set({token:d,expirationTime:C,refreshToken:M}),Promise.resolve(!0)}throw N({code:l.data.error,statusCode:l.data.statusCode,message:l.data.message,error:l.data.errors})}catch(d){throw d}}async function E(e,t=null,r,o,i,s,a,n){let u={request:e,tokenCache:i,httpClient:a.httpClient||fetch,httpClientOptions:a.httpClientOptions,...s(a),userOption:a,next:n},l=async d=>{let c=Object.assign({},d);return c.statusCode==401&&(t=Ce(u),await t,t=null,r=i.get(o),c=await n(j(r.token,e))),c};return e.headers&&(e.headers.Authorization||e.headers.authorization)?l(await n(e)):(r=i.get(o),r&&r.token&&Date.now()<r.expirationTime?l(await n(j(r.token,e))):(t?await t:(t=Ce(u),await t,t=null),r=i.get(o),n(j(r.token,e))))}function v(e){let t=e.tokenCache||A({token:"",expirationTime:-1}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,Ee,e,s)}function H(e){let t=e.tokenCache||A({token:"",expirationTime:-1}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,ge,e,s)}function _(e,t){return r=>async o=>{if(typeof e!="string")throw new Error("authorization must be a string");let i=t?.force===void 0?!0:t.force;if(!e||o.headers&&(o.headers.Authorization||o.headers.authorization)&&i===!1)return r(o);let s={...o,headers:{...o.headers,Authorization:e}};return r(s)}}function B(e){let t=e.tokenCache||A({token:"",expirationTime:-1}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,Oe,e,s)}function K(e){let t=e.tokenCache||A({token:"",tokenCacheKey:null}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,le,e,s)}function z(e){return t=>async r=>{let o=await t(r);if(o.statusCode==409){let i=o.error.body?.errors?.[0]?.currentVersion;if(i)return e&&typeof e=="function"?r.body=await e(i,r,o):r.body=typeof r.body=="string"?{...JSON.parse(r.body),version:i}:{...r.body,version:i},t(r)}return o}}function J(e){return t=>r=>{let o={...r,headers:{...r.headers,"X-Correlation-ID":e.generate&&typeof e.generate=="function"?e.generate():oe()}};return t(o)}}function Re(e){return t=>async r=>{let o=await t(r);if(o.error){let{error:i}=o;return{...o,statusCode:i.statusCode||0,headers:i.headers||T({}),error:{...i,body:i.data||i}}}return o}}async function ot({url:e,httpClient:t,clientOptions:r}){let{request:o,maskSensitiveHeaderData:i,includeRequestInErrorResponse:s,includeResponseHeaders:a}=r;try{let n=await U({url:e,...r,httpClient:t,method:r.method,...r.body?{body:r.body}:{}});if(a||(n.headers=null),n.statusCode>=200&&n.statusCode<300)return r.method=="HEAD"?{body:null,statusCode:n.statusCode,retryCount:n.retryCount,headers:T(n.headers)}:{body:n.data,statusCode:n.statusCode,retryCount:n.retryCount,headers:T(n.headers)};let u=N({code:n.data?.errors?.[0].code,message:n?.data?.message||n?.message,statusCode:n.statusCode||n?.data?.statusCode,method:r.method,headers:T(n.headers),body:n.data,error:n.data,retryCount:n.retryCount,...s?{originalRequest:i?k(o):o}:{uri:o.uri}});return{...u,error:u}}catch(n){let u=a?T(n.response?.headers):null,l=n.response?.status||n.response?.statusCode||n.response?.data.statusCode||0,d=n.response?.data?.message;throw{body:null,error:N({statusCode:l,code:"NetworkError",status:l,message:d||n.message,headers:u,body:n.response?.data||n,error:n.response?.data||n,...s?{originalRequest:i?k(o):o}:{uri:o.uri}})}}}function V(e){ye(e);let{host:t,credentialsMode:r,httpClient:o,timeout:i,enableRetry:s,retryConfig:a,getAbortController:n,includeOriginalRequest:u,includeRequestInErrorResponse:l=!0,includeResponseHeaders:d=!0,maskSensitiveHeaderData:c,httpClientOptions:M}=e;return C=>async p=>{let S=t.replace(/\/$/,"")+p.uri,h={...p.headers};Object.prototype.hasOwnProperty.call(h,"Content-Type")||Object.prototype.hasOwnProperty.call(h,"content-type")||(h["Content-Type"]="application/json"),h["Content-Type"]===null&&delete h["Content-Type"];let w=g.HEADERS_CONTENT_TYPES.indexOf(h["Content-Type"])>-1&&typeof p.body=="string"||Q(p.body)?p.body:JSON.stringify(p.body||void 0);w&&(typeof w=="string"||Q(w))&&(h["Content-Length"]=I(w));let f={enableRetry:s,retryConfig:a,request:p,method:p.method,headers:h,includeRequestInErrorResponse:l,maskSensitiveHeaderData:c,includeResponseHeaders:d,...M};r&&(f.credentialsMode=r),i&&(f.timeout=i,f.getAbortController=n),w&&(f.body=w);let q=await ot({url:S,clientOptions:f,httpClient:o}),x={...p,includeOriginalRequest:u,maskSensitiveHeaderData:c,response:q};return C(x)}}function G(e){return t=>async r=>{let o=await t(r),i=Object.assign({},o),{loggerFn:s=console.log}=e||{};return s&&typeof s=="function"&&s(o),i}}function Y({concurrency:e=20}){let t=0,r=[],o=()=>0>=e?Promise.resolve():new Promise(s=>{let a=()=>{t<e?(t++,s()):r.push(a)};a()}),i=()=>{if(t--,r.length>0){let s=r.shift();s&&s()}};return s=>a=>o().then(()=>{let n={...a,resolve(u){a.resolve(u),i()},reject(u){a.reject(u),i()}};return s(n).finally(()=>{i()})})}var ke={name:"@commercetools/ts-client",version:"3.2.1",engines:{node:">=18"},description:"commercetools Composable Commerce TypeScript SDK client.",keywords:["commercetools","composable commerce","sdk","typescript","client","middleware","http","oauth","auth"],homepage:"https://github.com/commercetools/commercetools-sdk-typescript",license:"MIT",directories:{lib:"lib",test:"test"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/commercetools/commercetools-sdk-typescript.git"},bugs:{url:"https://github.com/commercetools/commercetools-sdk-typescript/issues"},dependencies:{buffer:"^6.0.3"},files:["dist","CHANGELOG.md"],author:"Chukwuemeka Ajima <meeky.ae@gmail.com>",main:"dist/commercetools-ts-client.cjs.js",module:"dist/commercetools-ts-client.esm.js",browser:{"./dist/commercetools-ts-client.cjs.js":"./dist/commercetools-ts-client.browser.cjs.js","./dist/commercetools-ts-client.esm.js":"./dist/commercetools-ts-client.browser.esm.js"},devDependencies:{"common-tags":"1.8.2",dotenv:"16.4.7",jest:"29.7.0",nock:"14.0.1","organize-imports-cli":"0.10.0"},scripts:{organize_imports:"find src -type f -name '*.ts' | xargs organize-imports-cli",postbuild:"yarn organize_imports",post_process_generate:"yarn organize_imports",docs:"typedoc --out docs"}};function W(e){return t=>async r=>{let o=se({...e,name:`${e.name?e.name+"/":""}commercetools-sdk-javascript-v3/${ke.version}`}),i={...r,headers:{...r.headers,"User-Agent":o}};return t(i)}}function nt({middlewares:e}){return e.length===1?e[0]:e.slice().reduce((r,o)=>(...i)=>r(o.apply(null,i)))}var Pe;function de(e,t,r){if(ae("process",e,{allowedMethods:["GET"]}),typeof t!="function")throw new Error('The "process" function accepts a "Function" as a second argument that returns a Promise. See https://commercetools.github.io/nodejs/sdk/api/sdkClient.html#processrequest-processfn-options');let o={total:Number.POSITIVE_INFINITY,accumulate:!0,...r};return new Promise((i,s)=>{let a,n="";if(e&&e.uri){let[C,p]=e.uri.split("?");a=C,n=p}let l={limit:20,...{...me(n)}},d=o.total,c=!1,M=async(C,p=[])=>{let S=l.limit<d?l.limit:d,h=ne({...l,limit:S}),w={sort:"id asc",withTotal:!1,...C?{where:`id > "${C}"`}:{}},f=ne(w),q={...e,uri:`${a}?${f}&${h}`};try{let x=await P(Pe).execute(q),{results:X,count:F}=x?.body||{};if(!F&&c)return i(p||[]);let m=await Promise.resolve(t(x)),y;if(c=!0,o.accumulate&&(y=p.concat(m||[])),d-=F,F<l.limit||!d)return i(y||[]);let $=X[F-1],Z=$&&$.id;M(Z,y)}catch(x){s(x)}};M()})}function P(e){Pe=e,Me(e);let t=!1,r={async resolve(i){let{response:s,includeOriginalRequest:a,maskSensitiveHeaderData:n,...u}=i,{retryCount:l,...d}=s;return t=n,{body:null,error:null,reject:i.reject,resolve:i.resolve,...d,...a?{originalRequest:u}:{},...s?.retryCount?{retryCount:s.retryCount}:{}}}},o=nt(e)(r.resolve);return{process:de,execute(i){return ae("exec",i),new Promise(async(s,a)=>{try{let n=await o({reject:a,resolve:s,...i});if(n.error)return a(n.error);n.originalRequest&&t&&(n.originalRequest=k(n.originalRequest)),s(n)}catch(n){a(n)}})}}}var{createAuthMiddlewareForPasswordFlow:st,createAuthMiddlewareForAnonymousSessionFlow:at,createAuthMiddlewareForClientCredentialsFlow:lt,createAuthMiddlewareForRefreshTokenFlow:dt,createAuthMiddlewareForExistingTokenFlow:ut,createCorrelationIdMiddleware:ct,createHttpMiddleware:pt,createLoggerMiddleware:ht,createQueueMiddleware:wt,createUserAgentMiddleware:Se,createConcurrentModificationMiddleware:ft}=Ae,L=class{projectKey;authMiddleware;httpMiddleware;userAgentMiddleware;correlationIdMiddleware;loggerMiddleware;queueMiddleware;concurrentMiddleware;telemetryMiddleware;beforeMiddleware;afterMiddleware;middlewares=[];constructor(){this.userAgentMiddleware=Se({})}withProjectKey(t){return this.projectKey=t,this}defaultClient(t,r,o,i,s,a){return this.withClientCredentialsFlow({host:o,projectKey:i||this.projectKey,credentials:r,httpClient:a||fetch,scopes:s}).withHttpMiddleware({host:t,httpClient:a||fetch})}withAuthMiddleware(t){return this.authMiddleware=t,this}withMiddleware(t){return this.middlewares.push(t),this}withClientCredentialsFlow(t){return this.withAuthMiddleware(lt({host:t.host||g.CTP_AUTH_URL,projectKey:t.projectKey||this.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null},oauthUri:t.oauthUri||null,scopes:t.scopes,httpClient:t.httpClient||fetch,...t}))}withPasswordFlow(t){return this.withAuthMiddleware(st({host:t.host||g.CTP_AUTH_URL,projectKey:t.projectKey||this.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null,user:{username:t.credentials.user.username||null,password:t.credentials.user.password||null}},httpClient:t.httpClient||fetch,...t}))}withAnonymousSessionFlow(t){return this.withAuthMiddleware(at({host:t.host||g.CTP_AUTH_URL,projectKey:this.projectKey||t.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null,anonymousId:t.credentials.anonymousId||null},httpClient:t.httpClient||fetch,...t}))}withRefreshTokenFlow(t){return this.withAuthMiddleware(dt({host:t.host||g.CTP_AUTH_URL,projectKey:this.projectKey||t.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null},httpClient:t.httpClient||fetch,refreshToken:t.refreshToken||null,...t}))}withExistingTokenFlow(t,r){return this.withAuthMiddleware(ut(t,{force:r.force||!0,...r}))}withHttpMiddleware(t){return this.httpMiddleware=pt({host:t.host||g.CTP_API_URL,httpClient:t.httpClient||fetch,...t}),this}withUserAgentMiddleware(t){return this.userAgentMiddleware=Se(t),this}withQueueMiddleware(t){return this.queueMiddleware=wt({concurrency:t.concurrency||g.CONCURRENCT_REQUEST,...t}),this}withLoggerMiddleware(t){return this.loggerMiddleware=ht(t),this}withCorrelationIdMiddleware(t){return this.correlationIdMiddleware=ct({generate:t?.generate,...t}),this}withConcurrentModificationMiddleware(t){return this.concurrentMiddleware=ft(t?.concurrentModificationHandlerFn),this}withTelemetryMiddleware(t){let{createTelemetryMiddleware:r,...o}=t;return this.withUserAgentMiddleware({customAgent:o?.userAgent||"typescript-sdk-apm-middleware"}),this.telemetryMiddleware=r(o),this}withBeforeExecutionMiddleware(t){let{middleware:r,...o}=t||{};return this.beforeMiddleware=t.middleware(o),this}withAfterExecutionMiddleware(t){let{middleware:r,...o}=t||{};return this.afterMiddleware=t.middleware(o),this}build(){let t=this.middlewares.slice();return this.telemetryMiddleware&&t.push(this.telemetryMiddleware),this.correlationIdMiddleware&&t.push(this.correlationIdMiddleware),this.userAgentMiddleware&&t.push(this.userAgentMiddleware),this.authMiddleware&&t.push(this.authMiddleware),this.beforeMiddleware&&t.push(this.beforeMiddleware),this.queueMiddleware&&t.push(this.queueMiddleware),this.loggerMiddleware&&t.push(this.loggerMiddleware),this.concurrentMiddleware&&t.push(this.concurrentMiddleware),this.httpMiddleware&&t.push(this.httpMiddleware),this.afterMiddleware&&t.push(this.afterMiddleware),P({middlewares:t})}};return je(mt);})();
|
|
1
|
+
var window;(window||={})["@commercetools/ts-client"]=(()=>{var ue=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var ce=(e,t)=>{for(var r in t)ue(e,r,{get:t[r],enumerable:!0})},Ue=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ie(t))!Ne.call(e,i)&&i!==r&&ue(e,i,{get:()=>t[i],enumerable:!(o=Fe(t,i))||o.enumerable});return e};var je=e=>Ue(ue({},"__esModule",{value:!0}),e);var mt={};ce(mt,{ClientBuilder:()=>L,Process:()=>de,createAuthMiddlewareForAnonymousSessionFlow:()=>v,createAuthMiddlewareForClientCredentialsFlow:()=>H,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>B,createAuthMiddlewareForRefreshTokenFlow:()=>K,createClient:()=>P,createConcurrentModificationMiddleware:()=>z,createCorrelationIdMiddleware:()=>J,createHttpMiddleware:()=>V,createLoggerMiddleware:()=>G,createQueueMiddleware:()=>Y,createUserAgentMiddleware:()=>W});var Ae={};ce(Ae,{createAuthMiddlewareForAnonymousSessionFlow:()=>v,createAuthMiddlewareForClientCredentialsFlow:()=>H,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>B,createAuthMiddlewareForRefreshTokenFlow:()=>K,createConcurrentModificationMiddleware:()=>z,createCorrelationIdMiddleware:()=>J,createErrorMiddleware:()=>Re,createHttpMiddleware:()=>V,createLoggerMiddleware:()=>G,createQueueMiddleware:()=>Y,createUserAgentMiddleware:()=>W});function I(e){return e&&typeof e=="string"?new TextEncoder().encode(e).length.toString():e&&e instanceof Uint8Array?e.byteLength.toString():e&&typeof e=="object"?new TextEncoder().encode(JSON.stringify(e)).length.toString():"0"}var g={};ce(g,{CONCURRENCT_REQUEST:()=>He,CTP_API_URL:()=>_e,CTP_AUTH_URL:()=>Be,DEFAULT_HEADERS:()=>pe,HEADERS_CONTENT_TYPES:()=>ve});var ve=["application/json","application/graphql"],He=20,_e="https://api.europe-west1.gcp.commercetools.com",Be="https://auth.europe-west1.gcp.commercetools.com",pe=["content-type","access-control-allow-origin","access-control-allow-headers","access-control-allow-methods","access-control-expose-headers","access-control-max-ag","x-correlation-id","server-timing","date","server","transfer-encoding","access-control-max-age","content-encoding","x-envoy-upstream-service-time","via","alt-svc","connection"];function b(e,t,r={}){this.code=r.code??=this.constructor.name,this.statusCode=e,this.status=e,this.message=t,Object.assign(this,r),this.name=this.constructor.name,this.constructor.prototype.__proto__=Error.prototype,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}function be(...e){b.call(this,0,...e)}function Te(...e){b.call(this,...e)}function Ke(...e){b.call(this,400,...e)}function Le(...e){b.call(this,401,...e)}function $e(...e){b.call(this,403,...e)}function De(...e){b.call(this,404,...e)}function Qe(...e){b.call(this,409,...e)}function ze(...e){b.call(this,500,...e)}function Je(...e){b.call(this,503,...e)}function he(e){switch(e){case 0:return be;case 400:return Ke;case 401:return Le;case 403:return $e;case 404:return De;case 409:return Qe;case 500:return ze;case 503:return Je;default:return}}function Ve({statusCode:e,message:t,...r}){let o=t||"Unexpected non-JSON error response";e===404&&(o=`URI not found: ${r.originalRequest?.uri||r.uri}`);let i=he(e);return i?new i(o,r):new Te(e,o,r)}var N=Ve;function Ge(e,t){return[503,...e].includes(t?.status||t?.statusCode)}async function Ye(e,t){async function r(){return await e({...t,headers:{...t.headers}})}return r().catch(o=>Promise.reject(o))}async function U(e){let{url:t,httpClient:r,...o}=e;return await Ye(async s=>{let{enableRetry:a,retryConfig:n,timeout:u,getAbortController:l}=o,{retryCodes:d=[],maxDelay:c=1/0,maxRetries:M=3,backoff:C=!0,retryDelay:p=200,retryOnAbort:S=!0}=n||{},h,w,f=0,q;we(d);async function x(){return r(t,{...s,...o,headers:{...o.headers},...o.body?{data:o.body}:{},withCredentials:s.credentialsMode==="include"})}function X(){let y=(l?l():null)||new AbortController;return o.abortController=y,o.signal=y.signal,y}async function F(){let y=async(ee,qe)=>{let D={};if(u){let O=X();q=setTimeout(()=>{O.abort(),O=X()},u)}try{if(D=await x(),D.status>399&&Ge(ee,D))return{_response:D,shouldRetry:!0}}catch(O){if((O.name.includes("AbortError")||O.name.includes("TimeoutError"))&&qe)return{_response:O,shouldRetry:!0};throw O}finally{clearTimeout(q)}return{_response:D,shouldRetry:!1}},{_response:$,shouldRetry:Z}=await y(d,S);for(;a&&Z&&f<M;){f++,await re(te({retryCount:f,retryDelay:p,maxRetries:M,backoff:C,maxDelay:c}));let ee=await y(d,S);$=ee._response,Z=ee.shouldRetry}return $}let m=await F();try{m.text&&typeof m.text=="function"?(h=await m.text()||JSON.stringify(m[Object.getOwnPropertySymbols(m)[1]]),w=JSON.parse(h)):w=m.data||m}catch(y){throw y}return{data:w,retryCount:f,statusCode:m.status||m.statusCode||w.statusCode,headers:m.headers}},{validateStatus:s=>!0})}function oe(){return("1000000-1000-4000-8000"+-1e11).replace(/[018]/g,e=>(parseInt(e)^Math.floor(Math.random()*256)&15>>parseInt(e)/4).toString(16))}function We(e){return pe.reduce((t,r)=>{let o=e[r]?e[r]:typeof e.get=="function"?e.get(r):null;return o&&(t[r]=o),t},{})}function T(e){if(!e)return null;if(e.raw&&typeof e.raw=="function")return e.raw();if(!e.forEach)return We(e);let t={};return e.forEach((r,o)=>t[o]=r),t}function Q(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e)}function k(e){let t=JSON.parse(JSON.stringify(e));return t?.headers&&(t.headers.Authorization&&(t.headers.Authorization="Bearer ********"),t.headers.authorization&&(t.headers.authorization="Bearer ********")),t}function j(e,t){return{...t,headers:{...t.headers,Authorization:`Bearer ${e}`}}}var fe=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];function te({retryCount:e,retryDelay:t,backoff:r,maxDelay:o}){return r&&e!==0?Math.min(Math.round((Math.random()+1)*t*2**e),o):t}Math.min(Math.round((Math.random()+1)*200*2**10),1/0);function re(e){return new Promise(t=>{setTimeout(t,e)})}function R(e){if(!e?.credentials?.clientId||!e.projectKey||!e.host)throw new Error("Missing required options.");return{clientId:e.credentials.clientId,host:e.host,projectKey:e.projectKey}}function ie(e){return Date.now()+e*1e3-5*60*1e3}function A(e){let t=e;return{get:r=>t,set:(r,o)=>{t=r}}}function xe(e){return typeof e<"u"&&e!==null}function Xe(e){return xe(e)?typeof e=="string"?e:Object.fromEntries(Object.entries(e).filter(([t,r])=>![null,void 0,""].includes(r))):""}function Ze(e){let t={},r=new URLSearchParams(e);for(let o of r.keys())r.getAll(o).length>1?t[o]=r.getAll(o):t[o]=r.get(o);return t}function et(e){if(e=Xe(e),!e)return"";let t=new URLSearchParams(e);for(let[r,o]of Object.entries(e))Array.isArray(o)&&(t.delete(r),o.filter(xe).forEach(i=>t.append(r,i)));return t.toString()}function me(e,t=Ze){return t(e)}function ne(e,t=et){return t(e)}var tt=()=>typeof window<"u"&&window.document&&window.document.nodeType===9;function rt(){if(tt())return window.navigator.userAgent;let e=process?.version?.slice(1)||"unknown",t=`(${process?.platform||""}; ${process?.arch||""})`;return`node.js/${e} ${t.trim()}`}function se(e){let t=null,r=null;if(!e)throw new Error("Missing required option `name`");let o=e.version?`${e.name}/${e.version}`:e.name;e.libraryName&&!e.libraryVersion?t=e.libraryName:e.libraryName&&e.libraryVersion&&(t=`${e.libraryName}/${e.libraryVersion}`),e.contactUrl&&!e.contactEmail?r=`(+${e.contactUrl})`:!e.contactUrl&&e.contactEmail?r=`(+${e.contactEmail})`:e.contactUrl&&e.contactEmail&&(r=`(+${e.contactUrl}; +${e.contactEmail})`);let i=rt(),s=e.customAgent||"";return[o,i,t,r,s].filter(Boolean).join(" ")}function ye(e){if(!e.host)throw new Error("Request `host` or `url` is missing or invalid, please pass in a valid host e.g `host: http://a-valid-host-url`");if(!e.httpClient&&typeof e.httpClient!="function")throw new Error("An `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.");if(e.httpClientOptions&&Object.prototype.toString.call(e.httpClientOptions)!=="[object Object]")throw new Error("`httpClientOptions` must be an object type")}function we(e){if(!Array.isArray(e))throw new Error("`retryCodes` option must be an array of retry status (error) codes and/or messages.")}function Me(e){if(!e)throw new Error("Missing required options");if(e.middlewares&&!Array.isArray(e.middlewares))throw new Error("Middlewares should be an array");if(!e.middlewares||!Array.isArray(e.middlewares)||!e.middlewares.length)throw new Error("You need to provide at least one middleware")}function ae(e,t,r={allowedMethods:fe}){if(!t)throw new Error(`The "${e}" function requires a "Request" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(typeof t.uri!="string")throw new Error(`The "${e}" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(!r.allowedMethods.includes(t.method))throw new Error(`The "${e}" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`)}function ge(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:t,clientSecret:r}=e.credentials||{};if(!(t&&r))throw new Error("Missing required credentials (clientId, clientSecret)");let o=e.scopes?e.scopes.join(" "):void 0,i=btoa(`${t}:${r}`),s=e.oauthUri||"/oauth/token",a=e.host.replace(/\/$/,"")+s,n=`grant_type=client_credentials${o?`&scope=${o}`:""}`;return{url:a,body:n,basicAuth:i}}function Ee(e){if(!e)throw new Error("Missing required options");if(!e.projectKey)throw new Error("Missing required option (projectKey)");let t=e.projectKey;e.oauthUri=e.oauthUri||`/oauth/${t}/anonymous/token`;let r=ge(e);return e.credentials.anonymousId&&(r.body+=`&anonymous_id=${e.credentials.anonymousId}`),{...r}}function le(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");if(!e.refreshToken)throw new Error("Missing required option (refreshToken)");let{clientId:t,clientSecret:r}=e.credentials;if(!(t&&r))throw new Error("Missing required credentials (clientId, clientSecret)");let o=btoa(`${t}:${r}`),i=e.oauthUri||"/oauth/token",s=e.host.replace(/\/$/,"")+i,a=`grant_type=refresh_token&refresh_token=${encodeURIComponent(e.refreshToken)}`;return{basicAuth:o,url:s,body:a}}function Oe(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:t,clientSecret:r,user:o}=e.credentials,i=e.projectKey;if(!(t&&r&&o))throw new Error("Missing required credentials (clientId, clientSecret, user)");let{username:s,password:a}=o;if(!(s&&a))throw new Error("Missing required user credentials (username, password)");let n=(e.scopes||[]).join(" "),u=n?`&scope=${n}`:"",l=btoa(`${t}:${r}`),d=e.oauthUri||`/oauth/${i}/customers/token`,c=e.host.replace(/\/$/,"")+d,M=`grant_type=password&username=${encodeURIComponent(s)}&password=${encodeURIComponent(a)}${u}`;return{basicAuth:l,url:c,body:M}}async function Ce(e){let{httpClient:t,httpClientOptions:r,tokenCache:o,userOption:i,tokenCacheObject:s}=e,a=e.url,n=e.body,u=e.basicAuth;if(!t||typeof t!="function")throw new Error("an `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.");if(s&&s.refreshToken&&(!s.token||s.token&&Date.now()>s.expirationTime)){if(!i)throw new Error("Missing required options.");let d={...le({...i,refreshToken:s.refreshToken})};a=d.url,n=d.body,u=d.basicAuth}let l;try{if(l=await U({url:a,method:"POST",headers:{Authorization:`Basic ${u}`,"Content-Type":"application/x-www-form-urlencoded","Content-Length":I(n)},httpClient:t,httpClientOptions:r,body:n}),l.statusCode>=200&&l.statusCode<300){let{access_token:d,expires_in:c,refresh_token:M}=l?.data,C=ie(c);return o.set({token:d,expirationTime:C,refreshToken:M}),Promise.resolve(!0)}throw N({code:l.data.error,statusCode:l.data.statusCode,message:l.data.message,error:l.data.errors})}catch(d){throw d}}async function E(e,t=null,r,o,i,s,a,n){let u={request:e,tokenCache:i,httpClient:a.httpClient||fetch,httpClientOptions:a.httpClientOptions,...s(a),userOption:a,next:n},l=async d=>{let c=Object.assign({},d);return c.statusCode==401&&(t=Ce(u),await t,t=null,r=i.get(o),c=await n(j(r.token,e))),c};return e.headers&&(e.headers.Authorization||e.headers.authorization)?l(await n(e)):(r=i.get(o),r&&r.token&&Date.now()<r.expirationTime?l(await n(j(r.token,e))):(t?await t:(t=Ce(u),await t,t=null),r=i.get(o),n(j(r.token,e))))}function v(e){let t=e.tokenCache||A({token:"",expirationTime:-1}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,Ee,e,s)}function H(e){let t=e.tokenCache||A({token:"",expirationTime:-1}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,ge,e,s)}function _(e,t){return r=>async o=>{if(typeof e!="string")throw new Error("authorization must be a string");let i=t?.force===void 0?!0:t.force;if(!e||o.headers&&(o.headers.Authorization||o.headers.authorization)&&i===!1)return r(o);let s={...o,headers:{...o.headers,Authorization:e}};return r(s)}}function B(e){let t=e.tokenCache||A({token:"",expirationTime:-1}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,Oe,e,s)}function K(e){let t=e.tokenCache||A({token:"",tokenCacheKey:null}),r,o=null,i=R(e);return s=>async a=>E(a,o,r,i,t,le,e,s)}function z(e){return t=>async r=>{let o=await t(r);if(o.statusCode==409){let i=o.error.body?.errors?.[0]?.currentVersion;if(i)return e&&typeof e=="function"?r.body=await e(i,r,o):r.body=typeof r.body=="string"?{...JSON.parse(r.body),version:i}:{...r.body,version:i},t(r)}return o}}function J(e){return t=>r=>{let o={...r,headers:{...r.headers,"X-Correlation-ID":e.generate&&typeof e.generate=="function"?e.generate():oe()}};return t(o)}}function Re(e){return t=>async r=>{let o=await t(r);if(o.error){let{error:i}=o;return{...o,statusCode:i.statusCode||0,headers:i.headers||T({}),error:{...i,body:i.data||i}}}return o}}async function ot({url:e,httpClient:t,clientOptions:r}){let{request:o,maskSensitiveHeaderData:i,includeRequestInErrorResponse:s,includeResponseHeaders:a}=r;try{let n=await U({url:e,...r,httpClient:t,method:r.method,...r.body?{body:r.body}:{}});if(a||(n.headers=null),n.statusCode>=200&&n.statusCode<300)return r.method=="HEAD"?{body:null,statusCode:n.statusCode,retryCount:n.retryCount,headers:T(n.headers)}:{body:n.data,statusCode:n.statusCode,retryCount:n.retryCount,headers:T(n.headers)};let u=N({code:n.data?.errors?.[0].code,message:n?.data?.message||n?.message,statusCode:n.statusCode||n?.data?.statusCode,method:r.method,headers:T(n.headers),body:n.data,error:n.data,retryCount:n.retryCount,...s?{originalRequest:i?k(o):o}:{uri:o.uri}});return{...u,error:u}}catch(n){let u=a?T(n.response?.headers):null,l=n.response?.status||n.response?.statusCode||n.response?.data.statusCode||0,d=n.response?.data?.message;throw{body:null,error:N({statusCode:l,code:"NetworkError",status:l,message:d||n.message,headers:u,body:n.response?.data||n,error:n.response?.data||n,...s?{originalRequest:i?k(o):o}:{uri:o.uri}})}}}function V(e){ye(e);let{host:t,credentialsMode:r,httpClient:o,timeout:i,enableRetry:s,retryConfig:a,getAbortController:n,includeOriginalRequest:u,includeRequestInErrorResponse:l=!0,includeResponseHeaders:d=!0,maskSensitiveHeaderData:c,httpClientOptions:M}=e;return C=>async p=>{let S=t.replace(/\/$/,"")+p.uri,h={...p.headers};Object.prototype.hasOwnProperty.call(h,"Content-Type")||Object.prototype.hasOwnProperty.call(h,"content-type")||(h["Content-Type"]="application/json"),h["Content-Type"]===null&&delete h["Content-Type"];let w=g.HEADERS_CONTENT_TYPES.indexOf(h["Content-Type"])>-1&&typeof p.body=="string"||Q(p.body)?p.body:JSON.stringify(p.body||void 0);w&&(typeof w=="string"||Q(w))&&(h["Content-Length"]=I(w));let f={enableRetry:s,retryConfig:a,request:p,method:p.method,headers:h,includeRequestInErrorResponse:l,maskSensitiveHeaderData:c,includeResponseHeaders:d,...M};r&&(f.credentialsMode=r),i&&(f.timeout=i,f.getAbortController=n),w&&(f.body=w);let q=await ot({url:S,clientOptions:f,httpClient:o}),x={...p,includeOriginalRequest:u,maskSensitiveHeaderData:c,response:q};return C(x)}}function G(e){return t=>async r=>{let o=await t(r),i=Object.assign({},o),{loggerFn:s=console.log}=e||{};return s&&typeof s=="function"&&s(o),i}}function Y({concurrency:e=20}){let t=0,r=[],o=()=>0>=e?Promise.resolve():new Promise(s=>{let a=()=>{t<e?(t++,s()):r.push(a)};a()}),i=()=>{if(t--,r.length>0){let s=r.shift();s&&s()}};return s=>a=>o().then(()=>{let n={...a,resolve(u){a.resolve(u),i()},reject(u){a.reject(u),i()}};return s(n).finally(()=>{i()})})}var ke={name:"@commercetools/ts-client",version:"3.2.2",engines:{node:">=18"},description:"commercetools Composable Commerce TypeScript SDK client.",keywords:["commercetools","composable commerce","sdk","typescript","client","middleware","http","oauth","auth"],homepage:"https://github.com/commercetools/commercetools-sdk-typescript",license:"MIT",directories:{lib:"lib",test:"test"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/commercetools/commercetools-sdk-typescript.git"},bugs:{url:"https://github.com/commercetools/commercetools-sdk-typescript/issues"},dependencies:{buffer:"^6.0.3"},files:["dist","CHANGELOG.md"],author:"Chukwuemeka Ajima <meeky.ae@gmail.com>",main:"dist/commercetools-ts-client.cjs.js",module:"dist/commercetools-ts-client.esm.js",browser:{"./dist/commercetools-ts-client.cjs.js":"./dist/commercetools-ts-client.browser.cjs.js","./dist/commercetools-ts-client.esm.js":"./dist/commercetools-ts-client.browser.esm.js"},devDependencies:{"common-tags":"1.8.2",dotenv:"16.4.7",jest:"29.7.0",nock:"14.0.1","organize-imports-cli":"0.10.0"},scripts:{organize_imports:"find src -type f -name '*.ts' | xargs organize-imports-cli",postbuild:"yarn organize_imports",post_process_generate:"yarn organize_imports",docs:"typedoc --out docs"}};function W(e){return t=>async r=>{let o=se({...e,name:`${e.name?e.name+"/":""}commercetools-sdk-javascript-v3/${ke.version}`}),i={...r,headers:{...r.headers,"User-Agent":o}};return t(i)}}function nt({middlewares:e}){return e.length===1?e[0]:e.slice().reduce((r,o)=>(...i)=>r(o.apply(null,i)))}var Pe;function de(e,t,r){if(ae("process",e,{allowedMethods:["GET"]}),typeof t!="function")throw new Error('The "process" function accepts a "Function" as a second argument that returns a Promise. See https://commercetools.github.io/nodejs/sdk/api/sdkClient.html#processrequest-processfn-options');let o={total:Number.POSITIVE_INFINITY,accumulate:!0,...r};return new Promise((i,s)=>{let a,n="";if(e&&e.uri){let[C,p]=e.uri.split("?");a=C,n=p}let l={limit:20,...{...me(n)}},d=o.total,c=!1,M=async(C,p=[])=>{let S=l.limit<d?l.limit:d,h=ne({...l,limit:S}),w={sort:"id asc",withTotal:!1,...C?{where:`id > "${C}"`}:{}},f=ne(w),q={...e,uri:`${a}?${f}&${h}`};try{let x=await P(Pe).execute(q),{results:X,count:F}=x?.body||{};if(!F&&c)return i(p||[]);let m=await Promise.resolve(t(x)),y;if(c=!0,o.accumulate&&(y=p.concat(m||[])),d-=F,F<l.limit||!d)return i(y||[]);let $=X[F-1],Z=$&&$.id;M(Z,y)}catch(x){s(x)}};M()})}function P(e){Pe=e,Me(e);let t=!1,r={async resolve(i){let{response:s,includeOriginalRequest:a,maskSensitiveHeaderData:n,...u}=i,{retryCount:l,...d}=s;return t=n,{body:null,error:null,reject:i.reject,resolve:i.resolve,...d,...a?{originalRequest:u}:{},...s?.retryCount?{retryCount:s.retryCount}:{}}}},o=nt(e)(r.resolve);return{process:de,execute(i){return ae("exec",i),new Promise(async(s,a)=>{try{let n=await o({reject:a,resolve:s,...i});if(n.error)return a(n.error);n.originalRequest&&t&&(n.originalRequest=k(n.originalRequest)),s(n)}catch(n){a(n)}})}}}var{createAuthMiddlewareForPasswordFlow:st,createAuthMiddlewareForAnonymousSessionFlow:at,createAuthMiddlewareForClientCredentialsFlow:lt,createAuthMiddlewareForRefreshTokenFlow:dt,createAuthMiddlewareForExistingTokenFlow:ut,createCorrelationIdMiddleware:ct,createHttpMiddleware:pt,createLoggerMiddleware:ht,createQueueMiddleware:wt,createUserAgentMiddleware:Se,createConcurrentModificationMiddleware:ft}=Ae,L=class{projectKey;authMiddleware;httpMiddleware;userAgentMiddleware;correlationIdMiddleware;loggerMiddleware;queueMiddleware;concurrentMiddleware;telemetryMiddleware;beforeMiddleware;afterMiddleware;middlewares=[];constructor(){this.userAgentMiddleware=Se({})}withProjectKey(t){return this.projectKey=t,this}defaultClient(t,r,o,i,s,a){return this.withClientCredentialsFlow({host:o,projectKey:i||this.projectKey,credentials:r,httpClient:a||fetch,scopes:s}).withHttpMiddleware({host:t,httpClient:a||fetch})}withAuthMiddleware(t){return this.authMiddleware=t,this}withMiddleware(t){return this.middlewares.push(t),this}withClientCredentialsFlow(t){return this.withAuthMiddleware(lt({host:t.host||g.CTP_AUTH_URL,projectKey:t.projectKey||this.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null},oauthUri:t.oauthUri||null,scopes:t.scopes,httpClient:t.httpClient||fetch,...t}))}withPasswordFlow(t){return this.withAuthMiddleware(st({host:t.host||g.CTP_AUTH_URL,projectKey:t.projectKey||this.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null,user:{username:t.credentials.user.username||null,password:t.credentials.user.password||null}},httpClient:t.httpClient||fetch,...t}))}withAnonymousSessionFlow(t){return this.withAuthMiddleware(at({host:t.host||g.CTP_AUTH_URL,projectKey:this.projectKey||t.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null,anonymousId:t.credentials.anonymousId||null},httpClient:t.httpClient||fetch,...t}))}withRefreshTokenFlow(t){return this.withAuthMiddleware(dt({host:t.host||g.CTP_AUTH_URL,projectKey:this.projectKey||t.projectKey,credentials:{clientId:t.credentials.clientId||null,clientSecret:t.credentials.clientSecret||null},httpClient:t.httpClient||fetch,refreshToken:t.refreshToken||null,...t}))}withExistingTokenFlow(t,r){return this.withAuthMiddleware(ut(t,{force:r.force||!0,...r}))}withHttpMiddleware(t){return this.httpMiddleware=pt({host:t.host||g.CTP_API_URL,httpClient:t.httpClient||fetch,...t}),this}withUserAgentMiddleware(t){return this.userAgentMiddleware=Se(t),this}withQueueMiddleware(t){return this.queueMiddleware=wt({concurrency:t.concurrency||g.CONCURRENCT_REQUEST,...t}),this}withLoggerMiddleware(t){return this.loggerMiddleware=ht(t),this}withCorrelationIdMiddleware(t){return this.correlationIdMiddleware=ct({generate:t?.generate,...t}),this}withConcurrentModificationMiddleware(t){return this.concurrentMiddleware=ft(t?.concurrentModificationHandlerFn),this}withTelemetryMiddleware(t){let{createTelemetryMiddleware:r,...o}=t;return this.withUserAgentMiddleware({customAgent:o?.userAgent||"typescript-sdk-apm-middleware"}),this.telemetryMiddleware=r(o),this}withBeforeExecutionMiddleware(t){let{middleware:r,...o}=t||{};return this.beforeMiddleware=t.middleware(o),this}withAfterExecutionMiddleware(t){let{middleware:r,...o}=t||{};return this.afterMiddleware=t.middleware(o),this}build(){let t=this.middlewares.slice();return this.telemetryMiddleware&&t.push(this.telemetryMiddleware),this.correlationIdMiddleware&&t.push(this.correlationIdMiddleware),this.userAgentMiddleware&&t.push(this.userAgentMiddleware),this.authMiddleware&&t.push(this.authMiddleware),this.beforeMiddleware&&t.push(this.beforeMiddleware),this.queueMiddleware&&t.push(this.queueMiddleware),this.loggerMiddleware&&t.push(this.loggerMiddleware),this.concurrentMiddleware&&t.push(this.concurrentMiddleware),this.httpMiddleware&&t.push(this.httpMiddleware),this.afterMiddleware&&t.push(this.afterMiddleware),P({middlewares:t})}};return je(mt);})();
|