storyblok-js-client
Advanced tools
Comparing version 5.5.0 to 5.5.1
@@ -1,1 +0,1 @@ | ||
(function(f,d){typeof exports=="object"&&typeof module<"u"?module.exports=d():typeof define=="function"&&define.amd?define(d):(f=typeof globalThis<"u"?globalThis:f||self,f.StoryblokJSClient=d())})(this,function(){"use strict";var $=Object.defineProperty;var C=(f,d,p)=>d in f?$(f,d,{enumerable:!0,configurable:!0,writable:!0,value:p}):f[d]=p;var h=(f,d,p)=>(C(f,typeof d!="symbol"?d+"":d,p),p);function f(a){return!(a!==a||a===1/0||a===-1/0)}function d(a,e,t){if(!f(e))throw new TypeError("Expected `limit` to be a finite number");if(!f(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const i=function(){n++;const l=setTimeout(function(){n--,s.length>0&&i(),r=r.filter(function(u){return u!==l})},t);r.indexOf(l)<0&&r.push(l);const c=s.shift();c.resolve(a.apply(c.self,c.args))},o=function(...l){const c=this;return new Promise(function(u,_){s.push({resolve:u,reject:_,args:l,self:c}),n<e&&i()})};return o.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(l){l.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},o}const p=function(a,e){const t={};for(const s in a){const r=a[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},P=a=>a==="email",T={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:p(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{const e={...a.attrs},{linktype:t="url"}=a.attrs;return P(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]})}},x=function(a){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return a&&s.test(a)?a.replace(t,r=>e[r]):a};class v{constructor(e){h(this,"marks");h(this,"nodes");e||(e=T),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e){if(e&&e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(s=>{t+=this.renderNode(s)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(x(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html&&t.push(s.html),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let n=`<${r.tag}`;if(r.attrs)for(const i in r.attrs){const o=r.attrs[i];o!==null&&(n+=` ${i}="${o}"`)}return`${n}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}}class y{constructor(){h(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));h(this,"delay",e=>new Promise(t=>setTimeout(t,e)));h(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));h(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,i)=>i*r+e)});h(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));h(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const i=e[n],o=s?"":encodeURIComponent(n);let l;typeof i=="object"?l=this.stringify(i,t?t+encodeURIComponent("["+o+"]"):o,Array.isArray(i)):l=(t?t+encodeURIComponent("["+o+"]"):o)+"="+encodeURIComponent(i),r.push(l)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return r;default:return t}}}const S=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:y},Symbol.toStringTag,{value:"Module"}));class b{constructor(e){h(this,"baseURL");h(this,"timeout");h(this,"headers");h(this,"responseInterceptor");h(this,"fetch");h(this,"ejectInterceptor");h(this,"url");h(this,"parameters");this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const l=new y;t=`${this.baseURL}${this.url}?${l.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:i}=n;let o;this.timeout&&(o=setTimeout(()=>n.abort(),this.timeout));try{const l=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:i});this.timeout&&clearTimeout(o);const c=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(l){return{message:l}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const n={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(n)})}}let k={};const g={};class m{constructor(e,t){h(this,"client");h(this,"maxRetries");h(this,"throttle");h(this,"accessToken");h(this,"cache");h(this,"helpers");h(this,"relations");h(this,"links");h(this,"richTextResolver");h(this,"resolveNestedRelations");if(!t){const n=new y().getRegionURL,i=e.https===!1?"http":"https";e.oauthToken?t=`${i}://${n(e.region)}/v1`:t=`${i}://${n(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((n,i)=>{e.headers&&e.headers[i]&&s.set(i,e.headers[i])});let r=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new v(e.richTextSchema):this.richTextResolver=new v,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries,this.throttle=d(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new y,this.resolveNestedRelations=!1,this.client=new b({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,n=`/${e}`,i=n.split("/"),o=s||i[i.length-1],l=1,c=await this.makeRequest(n,t,r,l),u=c.total?Math.ceil(c.total/r):1,_=await this.helpers.asyncMap(this.helpers.range(l,u),R=>this.makeRequest(n,t,r,R+1));return this.helpers.flatMap([c,..._],R=>Object.values(R.data[o]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[s.id]?s.story=this._cleanCopy(this.links[s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[s.uuid]&&(s.story=this._cleanCopy(this.links[s.uuid]))}_insertRelations(e,t,s){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t]&&e[t].constructor===Array){const r=[];e[t].forEach(n=>{this.relations[n]&&r.push(this._cleanCopy(this.relations[n]))}),e[t]=r}}}iterateTree(e,t){const s=r=>{if(r!=null){if(r.constructor===Array)for(let n=0;n<r.length;n++)s(r[n]);else if(r.constructor===Object){if(r._stopResolving)return;for(const n in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,n,t),this._insertLinks(r,n)),s(r[n])}}};s(e.content)}async resolveLinks(e,t){let s=[];if(e.link_uuids){const r=e.link_uuids.length,n=[],i=50;for(let o=0;o<r;o+=i){const l=Math.min(r,o+i);n.push(e.link_uuids.slice(o,l))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.links;s.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(e,t){let s=[];if(e.rel_uuids){const r=e.rel_uuids.length,n=[],i=50;for(let o=0;o<r;o+=i){const l=Math.min(r,o+i);n.push(e.rel_uuids.slice(o,l))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(e,t){var r,n;let s=[];if(typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(s=t.resolve_relations.split(",")),await this.resolveRelations(e,t)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const i in this.relations)this.iterateTree(this.relations[i],s);e.story?this.iterateTree(e.story,s):e.stories.forEach(i=>{this.iterateTree(i,s)})}async cacheResponse(e,t,s){const r=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const i=await n.get(r);if(i)return Promise.resolve(i)}return new Promise((i,o)=>{try{(async()=>{var l;try{const c=await this.throttle("get",e,t);let u={data:c.data,headers:c.headers};return(l=c.headers)!=null&&l["per-page"]&&(u=Object.assign({},u,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),c.status!=200?o(c):((u.data.story||u.data.stories)&&await this.resolveStories(u.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=u.data.cv&&await this.flushCache(),g[t.token]=u.data.cv),i(u))}catch(c){return o(c)}})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(k[e])},getAll(){return Promise.resolve(k)},set(e,t){return k[e]=t,Promise.resolve(void 0)},flush(){return k={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this}}const w=(a,e)=>{for(const t in e)a[t]=e[t]};return w(m,{RichtextResolver:v,SbFetch:b,RichTextSchema:T}),w(m,S),m}); | ||
(function(f,d){typeof exports=="object"&&typeof module<"u"?module.exports=d():typeof define=="function"&&define.amd?define(d):(f=typeof globalThis<"u"?globalThis:f||self,f.StoryblokJSClient=d())})(this,function(){"use strict";var S=Object.defineProperty;var $=(f,d,p)=>d in f?S(f,d,{enumerable:!0,configurable:!0,writable:!0,value:p}):f[d]=p;var h=(f,d,p)=>($(f,typeof d!="symbol"?d+"":d,p),p);function f(a){return!(a!==a||a===1/0||a===-1/0)}function d(a,t,e){if(!f(t))throw new TypeError("Expected `limit` to be a finite number");if(!f(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const i=function(){n++;const o=setTimeout(function(){n--,s.length>0&&i(),r=r.filter(function(u){return u!==o})},e);r.indexOf(o)<0&&r.push(o);const l=s.shift();l.resolve(a.apply(l.self,l.args))},c=function(...o){const l=this;return new Promise(function(u,y){s.push({resolve:u,reject:y,args:o,self:l}),n<t&&i()})};return c.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},c}const p=function(a,t){const e={};for(const s in a){const r=a[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},P=a=>a==="email",T={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:p(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{const t={...a.attrs},{linktype:e="url"}=a.attrs;return P(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]})}},x=function(a){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,s=RegExp(e.source);return a&&s.test(a)?a.replace(e,r=>t[r]):a};class v{constructor(t){h(this,"marks");h(this,"nodes");t||(t=T),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t){if(t&&t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(s=>{e+=this.renderNode(s)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(x(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html&&e.push(s.html),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let n=`<${r.tag}`;if(r.attrs)for(const i in r.attrs){const c=r.attrs[i];c!==null&&(n+=` ${i}="${c}"`)}return`${n}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}class k{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s}));h(this,"delay",t=>new Promise(e=>setTimeout(e,t)));h(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e));h(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(n,i)=>i*r+t)});h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e)));h(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const i=t[n],c=s?"":encodeURIComponent(n);let o;typeof i=="object"?o=this.stringify(i,e?e+encodeURIComponent("["+c+"]"):c,Array.isArray(i)):o=(e?e+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(i),r.push(o)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}const C=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:k},Symbol.toStringTag,{value:"Module"}));class b{constructor(t){h(this,"baseURL");h(this,"timeout");h(this,"headers");h(this,"responseInterceptor");h(this,"fetch");h(this,"ejectInterceptor");h(this,"url");h(this,"parameters");this.baseURL=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const o=new k;e=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),n=new AbortController,{signal:i}=n;let c;this.timeout&&(c=setTimeout(()=>n.abort(),this.timeout));try{const o=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:i});this.timeout&&clearTimeout(c);const l=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(o){return{message:o}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const n={message:new Error(t.statusText),status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};r(n)})}}let m={};const g={};class _{constructor(t,e){h(this,"client");h(this,"maxRetries");h(this,"throttle");h(this,"accessToken");h(this,"cache");h(this,"helpers");h(this,"resolveCounter");h(this,"relations");h(this,"links");h(this,"richTextResolver");h(this,"resolveNestedRelations");if(!e){const n=new k().getRegionURL,i=t.https===!1?"http":"https";t.oauthToken?e=`${i}://${n(t.region)}/v1`:e=`${i}://${n(t.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((n,i)=>{t.headers&&t.headers[i]&&s.set(i,t.headers[i])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new v(t.richTextSchema):this.richTextResolver=new v,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=d(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=!1,this.client=new b({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=g[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const n=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,n)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,n=`/${t}`,i=n.split("/"),c=s||i[i.length-1],o=1,l=await this.makeRequest(n,e,r,o),u=l.total?Math.ceil(l.total/r):1,y=await this.helpers.asyncMap(this.helpers.range(o,u),R=>this.makeRequest(n,e,r,R+1));return this.helpers.flatMap([l,...y],R=>Object.values(R.data[c]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}_insertRelations(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const n=[];t[e].forEach(i=>{this.relations[r][i]&&n.push(this._cleanCopy(this.relations[r][i]))}),t[e]=n}}}iterateTree(t,e,s){const r=n=>{if(n!=null){if(n.constructor===Array)for(let i=0;i<n.length;i++)r(n[i]);else if(n.constructor===Object){if(n._stopResolving)return;for(const i in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,i,e,s),this._insertLinks(n,i,s)),r(n[i])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const n=t.link_uuids.length,i=[],c=50;for(let o=0;o<n;o+=c){const l=Math.min(n,o+c);i.push(t.link_uuids.slice(o,l))}for(let o=0;o<i.length;o++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:i[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const n=t.rel_uuids.length,i=[],c=50;for(let o=0;o<n;o+=c){const l=Math.min(n,o+c);i.push(t.rel_uuids.slice(o,l))}for(let o=0;o<i.length;o++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:i[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(t,e,s){var n,i;let r=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(r=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((n=t.links)!=null&&n.length||(i=t.link_uuids)!=null&&i.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],r,s);t.story?this.iterateTree(t.story,r,s):t.stories.forEach(c=>{this.iterateTree(c,r,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){const r=this.helpers.stringify({url:t,params:e}),n=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const i=await n.get(r);if(i)return Promise.resolve(i)}return new Promise((i,c)=>{try{(async()=>{var o;try{const l=await this.throttle("get",t,e);let u={data:l.data,headers:l.headers};if((o=l.headers)!=null&&o["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),l.status!=200)return c(l);if(u.data.story||u.data.stories){const y=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${y}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&g[e.token]!=u.data.cv&&await this.flushCache(),g[e.token]=u.data.cv),i(u)}catch(l){return c(l)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(m[t])},getAll(){return Promise.resolve(m)},set(t,e){return m[t]=e,Promise.resolve(void 0)},flush(){return m={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this}}const w=(a,t)=>{for(const e in t)a[e]=t[e]};return w(_,{RichtextResolver:v,SbFetch:b,RichTextSchema:T}),w(_,C),_}); |
@@ -29,2 +29,3 @@ import { ISbStoriesParams, ISbConfig, ISbResult, ISbStories, ISbStory, ISbStoryData, ISbStoryParams, ISbContentMangmntAPI } from './interfaces'; | ||
private helpers; | ||
private resolveCounter; | ||
relations: RelationsType; | ||
@@ -31,0 +32,0 @@ links: LinksType; |
{ | ||
"name": "storyblok-js-client", | ||
"version": "5.5.0", | ||
"version": "5.5.1", | ||
"description": "Universal JavaScript SDK for Storyblok's API", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
@@ -72,3 +72,3 @@ import throttledQueue from './throttlePromise' | ||
private helpers: SbHelpers | ||
private resolveCounter: number | ||
public relations: RelationsType | ||
@@ -135,2 +135,3 @@ public links: LinksType | ||
this.helpers = new SbHelpers() | ||
this.resolveCounter = 0 | ||
this.resolveNestedRelations = false | ||
@@ -286,3 +287,4 @@ | ||
jtree: ISbStoriesParams, | ||
treeItem: keyof ISbStoriesParams | ||
treeItem: keyof ISbStoriesParams, | ||
resolveId: string | ||
): void { | ||
@@ -296,5 +298,5 @@ const node = jtree[treeItem] | ||
typeof node.id === 'string' && | ||
this.links[node.id] | ||
this.links[resolveId][node.id] | ||
) { | ||
node.story = this._cleanCopy(this.links[node.id]) | ||
node.story = this._cleanCopy(this.links[resolveId][node.id]) | ||
} else if ( | ||
@@ -304,5 +306,5 @@ node && | ||
typeof node.uuid === 'string' && | ||
this.links[node.uuid] | ||
this.links[resolveId][node.uuid] | ||
) { | ||
node.story = this._cleanCopy(this.links[node.uuid]) | ||
node.story = this._cleanCopy(this.links[resolveId][node.uuid]) | ||
} | ||
@@ -314,8 +316,11 @@ } | ||
treeItem: keyof ISbStoriesParams, | ||
fields: string | Array<string> | ||
fields: string | Array<string>, | ||
resolveId: string | ||
): void { | ||
if (fields.indexOf(`${jtree.component}.${treeItem}`) > -1) { | ||
if (typeof jtree[treeItem] === 'string') { | ||
if (this.relations[jtree[treeItem]]) { | ||
jtree[treeItem] = this._cleanCopy(this.relations[jtree[treeItem]]) | ||
if (this.relations[resolveId][jtree[treeItem]]) { | ||
jtree[treeItem] = this._cleanCopy( | ||
this.relations[resolveId][jtree[treeItem]] | ||
) | ||
} | ||
@@ -325,4 +330,4 @@ } else if (jtree[treeItem] && jtree[treeItem].constructor === Array) { | ||
jtree[treeItem].forEach((uuid: string) => { | ||
if (this.relations[uuid]) { | ||
stories.push(this._cleanCopy(this.relations[uuid])) | ||
if (this.relations[resolveId][uuid]) { | ||
stories.push(this._cleanCopy(this.relations[resolveId][uuid])) | ||
} | ||
@@ -337,3 +342,4 @@ }) | ||
story: ISbStoryData, | ||
fields: string | Array<string> | ||
fields: string | Array<string>, | ||
resolveId: string | ||
): void { | ||
@@ -357,5 +363,10 @@ const enrich = (jtree: ISbStoriesParams | any) => { | ||
treeItem as keyof ISbStoriesParams, | ||
fields | ||
fields, | ||
resolveId | ||
) | ||
this._insertLinks(jtree, treeItem as keyof ISbStoriesParams) | ||
this._insertLinks( | ||
jtree, | ||
treeItem as keyof ISbStoriesParams, | ||
resolveId | ||
) | ||
} | ||
@@ -372,3 +383,4 @@ enrich(jtree[treeItem]) | ||
responseData: ISbResponseData, | ||
params: ISbStoriesParams | ||
params: ISbStoriesParams, | ||
resolveId: string | ||
): Promise<void> { | ||
@@ -406,3 +418,6 @@ let links: (ISbStoryData | ISbLinkURLObject | string)[] = [] | ||
links.forEach((story: ISbStoryData | any) => { | ||
this.links[story.uuid] = { ...story, ...{ _stopResolving: true } } | ||
this.links[resolveId][story.uuid] = { | ||
...story, | ||
...{ _stopResolving: true }, | ||
} | ||
}) | ||
@@ -413,3 +428,4 @@ } | ||
responseData: ISbResponseData, | ||
params: ISbStoriesParams | ||
params: ISbStoriesParams, | ||
resolveId: string | ||
): Promise<void> { | ||
@@ -446,3 +462,6 @@ let relations = [] | ||
relations.forEach((story: ISbStoryData) => { | ||
this.relations[story.uuid] = { ...story, ...{ _stopResolving: true } } | ||
this.relations[resolveId][story.uuid] = { | ||
...story, | ||
...{ _stopResolving: true }, | ||
} | ||
}) | ||
@@ -454,6 +473,10 @@ } | ||
responseData: ISbResponseData, | ||
params: ISbStoriesParams | ||
params: ISbStoriesParams, | ||
resolveId: string | ||
): Promise<void> { | ||
let relationParams: string[] = [] | ||
this.links[resolveId] = {} | ||
this.relations[resolveId] = {} | ||
if ( | ||
@@ -466,3 +489,3 @@ typeof params.resolve_relations !== 'undefined' && | ||
} | ||
await this.resolveRelations(responseData, params) | ||
await this.resolveRelations(responseData, params, resolveId) | ||
} | ||
@@ -475,8 +498,12 @@ | ||
) { | ||
await this.resolveLinks(responseData, params) | ||
await this.resolveLinks(responseData, params, resolveId) | ||
} | ||
if (this.resolveNestedRelations) { | ||
for (const relUuid in this.relations) { | ||
this.iterateTree(this.relations[relUuid], relationParams) | ||
for (const relUuid in this.relations[resolveId]) { | ||
this.iterateTree( | ||
this.relations[resolveId][relUuid], | ||
relationParams, | ||
resolveId | ||
) | ||
} | ||
@@ -486,8 +513,11 @@ } | ||
if (responseData.story) { | ||
this.iterateTree(responseData.story, relationParams) | ||
this.iterateTree(responseData.story, relationParams, resolveId) | ||
} else { | ||
responseData.stories.forEach((story: ISbStoryData) => { | ||
this.iterateTree(story, relationParams) | ||
this.iterateTree(story, relationParams, resolveId) | ||
}) | ||
} | ||
delete this.links[resolveId] | ||
delete this.relations[resolveId] | ||
} | ||
@@ -542,3 +572,5 @@ | ||
if (response.data.story || response.data.stories) { | ||
await this.resolveStories(response.data, params) | ||
const resolveId = (this.resolveCounter = | ||
++this.resolveCounter % 1000) | ||
await this.resolveStories(response.data, params, `${resolveId}`) | ||
} | ||
@@ -545,0 +577,0 @@ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
139453
3858