@storyblok/js 1.8.5 → 1.8.6

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.
@@ -2,6 +2,6 @@
2
2
  * storyblok-js-client v4.5.2
3
3
  * Universal JavaScript SDK for Storyblok's API
4
4
  * (c) 2020-2022 Stobylok Team
5
- */function E(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function S(n,t,r){if(!E(t))throw new TypeError("Expected `limit` to be a finite number");if(!E(r))throw new TypeError("Expected `interval` to be a finite number");var e=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,e.length>0&&a(),s=s.filter(function(u){return u!==c})},r);s.indexOf(c)<0&&s.push(c);var l=e.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,y){e.push({resolve:u,reject:y,args:c,self:l}),o<t&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],e.forEach(function(c){c.reject(new throttle.AbortError)}),e.length=0},i}S.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const q=function(n,t){if(!n)return null;let r={};for(let e in n){let s=n[e];t.indexOf(e)>-1&&s!==null&&(r[e]=s)}return r};var B={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:q(n.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(n){const t=f({},n.attrs),{linktype:r="url"}=n.attrs;return r==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class L{constructor(t){t||(t=B),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,r){this.nodes[t]=r}addMark(t,r){this.marks[t]=r}render(t={}){if(t.content&&Array.isArray(t.content)){let r="";return t.content.forEach(e=>{r+=this.renderNode(e)}),r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let r=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderOpeningTag(o.tag))});const e=this.getMatchingNode(t);return e&&e.tag&&r.push(this.renderOpeningTag(e.tag)),t.content?t.content.forEach(s=>{r.push(this.renderNode(s))}):t.text?r.push(function(s){const o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(t.text)):e&&e.singleTag?r.push(this.renderTag(e.singleTag," /")):e&&e.html&&r.push(e.html),e&&e.tag&&r.push(this.renderClosingTag(e.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderClosingTag(o.tag))}),r.join("")}renderTag(t,r){return t.constructor===String?`<${t}${r}>`:t.map(e=>{if(e.constructor===String)return`<${e}${r}>`;{let s=`<${e.tag}`;if(e.attrs)for(let o in e.attrs){let a=e.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${r}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const z=(n=0,t=n)=>{const r=Math.abs(t-n)||0,e=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(r,(s,o)=>o*e+n)},b=(n,t,r)=>{const e=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=r?"":encodeURIComponent(s);let i;i=typeof o=="object"?b(o,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),e.push(i)}return e.join("&")};let m={},p={};class U{constructor(t,r){if(!r){let o=t.region?`-${t.region}`:"",a=t.https===!1?"http":"https";r=t.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let e=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(e.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new L(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=S(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=C.default.create({baseURL:r,timeout:t.timeout||0,headers:e,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",r=>{let e="";return r.attrs.body.forEach(s=>{e+=t(s.component,s)}),{html:e}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=p[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,r={}){return((e="")=>e.indexOf("/cdn/")>-1)(t)?this.parseParams(r):r}makeRequest(t,r,e,s){const o=this.factoryParamOptions(t,((a={},i=25,c=1)=>k(f({},a),{per_page:i,page:c}))(r,e,s));return this.cacheResponse(t,o)}get(t,r){let e=`/${t}`;const s=this.factoryParamOptions(e,r);return this.cacheResponse(e,s)}async getAll(t,r={},e){const s=r.per_page||25,o=`/${t}`,a=o.split("/");e=e||a[a.length-1];const i=await this.makeRequest(o,r,s,1),c=Math.ceil(i.total/s);return((l=[],u)=>l.map(u).reduce((y,Y)=>[...y,...Y],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(z(1,c),async l=>this.makeRequest(o,r,s,l+1))],l=>Object.values(l.data[e]))}post(t,r){let e=`/${t}`;return this.throttle("post",e,r)}put(t,r){let e=`/${t}`;return this.throttle("put",e,r)}delete(t,r){let e=`/${t}`;return this.throttle("delete",e,r)}getStories(t){return this.get("cdn/stories",t)}getStory(t,r){return this.get(`cdn/stories/${t}`,r)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,r){const e=t[r];e&&e.fieldtype=="multilink"&&e.linktype=="story"&&typeof e.id=="string"&&this.links[e.id]?e.story=this._cleanCopy(this.links[e.id]):e&&e.linktype==="story"&&typeof e.uuid=="string"&&this.links[e.uuid]&&(e.story=this._cleanCopy(this.links[e.uuid]))}_insertRelations(t,r,e){if(e.indexOf(t.component+"."+r)>-1){if(typeof t[r]=="string")this.relations[t[r]]&&(t[r]=this._cleanCopy(this.relations[t[r]]));else if(t[r].constructor===Array){let s=[];t[r].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),t[r]=s}}}_insertAssetsRelations(t,r){r.forEach(e=>{t.id===e.id&&(t.original=e,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,r){let e=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)e(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,o,r),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,r),e(s[o])}}};e(t.content)}async resolveLinks(t,r){let e=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:r.language,version:r.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{e.push(c)})}else e=t.links;e.forEach(s=>{this.links[s.uuid]=k(f({},s),{_stopResolving:!0})})}async resolveRelations(t,r){let e=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:r.language,version:r.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{e.push(c)})}else e=t.rels;e.forEach(s=>{this.relations[s.uuid]=k(f({},s),{_stopResolving:!0})})}async resolveStories(t,r){let e=[];if(r.resolve_relations!==void 0&&r.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(e=r.resolve_relations.split(","),await this.resolveRelations(t,r)),["1","story","url"].indexOf(r.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,r),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],e);t.story?this.iterateTree(t.story,e):t.stories.forEach(s=>{this.iterateTree(s,e)})}resolveAssetsRelations(t){const{assets:r,stories:e,story:s}=t;if(e)for(const o of e)this.iterateTree(o,r);else{if(!s)return t;this.iterateTree(s,r)}}cacheResponse(t,r,e){return e===void 0&&(e=0),new Promise(async(s,o)=>{let a=b({url:t,params:r}),i=this.cacheProvider();if(this.cache.clear==="auto"&&r.version==="draft"&&await this.flushCache(),r.version==="published"&&t!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",t,{params:r,paramsSerializer:y=>b(y)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,r),r.version==="published"&&t!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(r.version=="draft"&&p[r.token]!=u.data.cv&&this.flushCache(),p[r.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(e+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${e} seconds.`),await(c=1e3*e,new Promise(u=>setTimeout(u,c))),this.cacheResponse(t,r,e).then(s).catch(o);o(l)}var c})}throttledRequest(t,r,e){return this.client[t](r,e)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(t){this.accessToken&&(p[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>m[t],getAll:()=>m,set(t,r){m[t]=r},flush(){m={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const H=(n={})=>{const{apiOptions:t}=n;if(!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new U(t)}};var D=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let v;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",x=(n,t,r={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(r).on(["input","published","change"],s=>{s.action==="input"&&s.story.id===n?t(s.story):(s.action==="change"||s.action==="published")&&s.storyId===n&&window.location.reload()})})}},J=(n={})=>{const{bridge:t,accessToken:r,use:e=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||r;const a={bridge:t,apiOptions:s};let i={};return e.forEach(c=>{i=f(f({},i),c(a))}),t!==!1&&_(j),v=new $(o.schema),o.resolver&&O(v,o.resolver),i},O=(n,t)=>{n.addNode("blok",r=>{let e="";return r.attrs.body.forEach(s=>{e+=t(s.component,s)}),{html:e}})},V=(n,t,r)=>{let e=r||v;if(!e){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(t&&(e=new $(t.schema),t.resolver&&O(e,t.resolver)),e.render(n)):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
5
+ */function E(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function S(n,t,r){if(!E(t))throw new TypeError("Expected `limit` to be a finite number");if(!E(r))throw new TypeError("Expected `interval` to be a finite number");var e=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,e.length>0&&a(),s=s.filter(function(u){return u!==c})},r);s.indexOf(c)<0&&s.push(c);var l=e.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,y){e.push({resolve:u,reject:y,args:c,self:l}),o<t&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],e.forEach(function(c){c.reject(new throttle.AbortError)}),e.length=0},i}S.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const q=function(n,t){if(!n)return null;let r={};for(let e in n){let s=n[e];t.indexOf(e)>-1&&s!==null&&(r[e]=s)}return r};var B={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:q(n.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(n){const t=f({},n.attrs),{linktype:r="url"}=n.attrs;return r==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class L{constructor(t){t||(t=B),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,r){this.nodes[t]=r}addMark(t,r){this.marks[t]=r}render(t={}){if(t.content&&Array.isArray(t.content)){let r="";return t.content.forEach(e=>{r+=this.renderNode(e)}),r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let r=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderOpeningTag(o.tag))});const e=this.getMatchingNode(t);return e&&e.tag&&r.push(this.renderOpeningTag(e.tag)),t.content?t.content.forEach(s=>{r.push(this.renderNode(s))}):t.text?r.push(function(s){const o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(t.text)):e&&e.singleTag?r.push(this.renderTag(e.singleTag," /")):e&&e.html&&r.push(e.html),e&&e.tag&&r.push(this.renderClosingTag(e.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderClosingTag(o.tag))}),r.join("")}renderTag(t,r){return t.constructor===String?`<${t}${r}>`:t.map(e=>{if(e.constructor===String)return`<${e}${r}>`;{let s=`<${e.tag}`;if(e.attrs)for(let o in e.attrs){let a=e.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${r}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const z=(n=0,t=n)=>{const r=Math.abs(t-n)||0,e=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(r,(s,o)=>o*e+n)},b=(n,t,r)=>{const e=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=r?"":encodeURIComponent(s);let i;i=typeof o=="object"?b(o,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),e.push(i)}return e.join("&")};let m={},p={};class U{constructor(t,r){if(!r){let o=t.region?`-${t.region}`:"",a=t.https===!1?"http":"https";r=t.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let e=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(e.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new L(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=S(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=C.default.create({baseURL:r,timeout:t.timeout||0,headers:e,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",r=>{let e="";return r.attrs.body.forEach(s=>{e+=t(s.component,s)}),{html:e}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=p[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,r={}){return((e="")=>e.indexOf("/cdn/")>-1)(t)?this.parseParams(r):r}makeRequest(t,r,e,s){const o=this.factoryParamOptions(t,((a={},i=25,c=1)=>k(f({},a),{per_page:i,page:c}))(r,e,s));return this.cacheResponse(t,o)}get(t,r){let e=`/${t}`;const s=this.factoryParamOptions(e,r);return this.cacheResponse(e,s)}async getAll(t,r={},e){const s=r.per_page||25,o=`/${t}`,a=o.split("/");e=e||a[a.length-1];const i=await this.makeRequest(o,r,s,1),c=i.total?Math.ceil(i.total/s):1;return((l=[],u)=>l.map(u).reduce((y,Y)=>[...y,...Y],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(z(1,c),async l=>this.makeRequest(o,r,s,l+1))],l=>Object.values(l.data[e]))}post(t,r){let e=`/${t}`;return this.throttle("post",e,r)}put(t,r){let e=`/${t}`;return this.throttle("put",e,r)}delete(t,r){let e=`/${t}`;return this.throttle("delete",e,r)}getStories(t){return this.get("cdn/stories",t)}getStory(t,r){return this.get(`cdn/stories/${t}`,r)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,r){const e=t[r];e&&e.fieldtype=="multilink"&&e.linktype=="story"&&typeof e.id=="string"&&this.links[e.id]?e.story=this._cleanCopy(this.links[e.id]):e&&e.linktype==="story"&&typeof e.uuid=="string"&&this.links[e.uuid]&&(e.story=this._cleanCopy(this.links[e.uuid]))}_insertRelations(t,r,e){if(e.indexOf(t.component+"."+r)>-1){if(typeof t[r]=="string")this.relations[t[r]]&&(t[r]=this._cleanCopy(this.relations[t[r]]));else if(t[r].constructor===Array){let s=[];t[r].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),t[r]=s}}}_insertAssetsRelations(t,r){r.forEach(e=>{t.id===e.id&&(t.original=e,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,r){let e=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)e(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,o,r),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,r),e(s[o])}}};e(t.content)}async resolveLinks(t,r){let e=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:r.language,version:r.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{e.push(c)})}else e=t.links;e.forEach(s=>{this.links[s.uuid]=k(f({},s),{_stopResolving:!0})})}async resolveRelations(t,r){let e=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:r.language,version:r.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{e.push(c)})}else e=t.rels;e.forEach(s=>{this.relations[s.uuid]=k(f({},s),{_stopResolving:!0})})}async resolveStories(t,r){let e=[];if(r.resolve_relations!==void 0&&r.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(e=r.resolve_relations.split(","),await this.resolveRelations(t,r)),["1","story","url"].indexOf(r.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,r),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],e);t.story?this.iterateTree(t.story,e):t.stories.forEach(s=>{this.iterateTree(s,e)})}resolveAssetsRelations(t){const{assets:r,stories:e,story:s}=t;if(e)for(const o of e)this.iterateTree(o,r);else{if(!s)return t;this.iterateTree(s,r)}}cacheResponse(t,r,e){return e===void 0&&(e=0),new Promise(async(s,o)=>{let a=b({url:t,params:r}),i=this.cacheProvider();if(this.cache.clear==="auto"&&r.version==="draft"&&await this.flushCache(),r.version==="published"&&t!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",t,{params:r,paramsSerializer:y=>b(y)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),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 o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,r),r.version==="published"&&t!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(r.version=="draft"&&p[r.token]!=u.data.cv&&this.flushCache(),p[r.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(e+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${e} seconds.`),await(c=1e3*e,new Promise(u=>setTimeout(u,c))),this.cacheResponse(t,r,e).then(s).catch(o);o(l)}var c})}throttledRequest(t,r,e){return this.client[t](r,e)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(t){this.accessToken&&(p[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>m[t],getAll:()=>m,set(t,r){m[t]=r},flush(){m={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const H=(n={})=>{const{apiOptions:t}=n;if(!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new U(t)}};var D=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let v;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",x=(n,t,r={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(r).on(["input","published","change"],s=>{s.action==="input"&&s.story.id===n?t(s.story):(s.action==="change"||s.action==="published")&&s.storyId===n&&window.location.reload()})})}},J=(n={})=>{const{bridge:t,accessToken:r,use:e=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||r;const a={bridge:t,apiOptions:s};let i={};return e.forEach(c=>{i=f(f({},i),c(a))}),t!==!1&&_(j),v=new $(o.schema),o.resolver&&O(v,o.resolver),i},O=(n,t)=>{n.addNode("blok",r=>{let e="";return r.attrs.body.forEach(s=>{e+=t(s.component,s)}),{html:e}})},V=(n,t,r)=>{let e=r||v;if(!e){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(t&&(e=new $(t.schema),t.resolver&&O(e,t.resolver)),e.render(n)):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
6
6
 
7
7
  For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},F=()=>_(j);h.RichTextSchema=R,h.apiPlugin=H,h.loadStoryblokBridge=F,h.registerStoryblokBridge=x,h.renderRichText=V,h.storyblokEditable=D,h.storyblokInit=J,h.useStoryblokBridge=x,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
@@ -487,7 +487,7 @@ class h {
487
487
  async getAll(e2, t2 = {}, s2) {
488
488
  const r2 = t2.per_page || 25, i2 = `/${e2}`, n2 = i2.split("/");
489
489
  s2 = s2 || n2[n2.length - 1];
490
- const a2 = await this.makeRequest(i2, t2, r2, 1), l2 = Math.ceil(a2.total / r2);
490
+ const a2 = await this.makeRequest(i2, t2, r2, 1), l2 = a2.total ? Math.ceil(a2.total / r2) : 1;
491
491
  return ((e3 = [], t3) => e3.map(t3).reduce((e4, t4) => [...e4, ...t4], []))([a2, ...await (async (e3 = [], t3) => Promise.all(e3.map(t3)))(o(1, l2), async (e3) => this.makeRequest(i2, t2, r2, e3 + 1))], (e3) => Object.values(e3.data[s2]));
492
492
  }
493
493
  post(e2, t2) {
@@ -626,7 +626,7 @@ class h {
626
626
  }
627
627
  try {
628
628
  let s3 = await this.throttle("get", e2, { params: t2, paramsSerializer: (e3) => a(e3) }), l3 = { data: s3.data, headers: s3.headers };
629
- if (l3.data.assets && l3.data.assets.length && this.resolveAssetsRelations(l3.data), s3.headers["per-page"] && (l3 = Object.assign({}, l3, { perPage: parseInt(s3.headers["per-page"]), total: parseInt(s3.headers.total) })), s3.status != 200)
629
+ if (l3.data.assets && l3.data.assets.length && this.resolveAssetsRelations(l3.data), l3 = Object.assign({}, l3, { perPage: s3.headers["per-page"] ? parseInt(s3.headers["per-page"]) : 0, total: s3.headers["per-page"] ? parseInt(s3.headers.total) : 0 }), s3.status != 200)
630
630
  return i2(s3);
631
631
  (l3.data.story || l3.data.stories) && await this.resolveStories(l3.data, t2), t2.version === "published" && e2 != "/cdn/spaces/me" && o2.set(n2, l3), l3.data.cv && (t2.version == "draft" && c[t2.token] != l3.data.cv && this.flushCache(), c[t2.token] = l3.data.cv), r2(l3);
632
632
  } catch (n3) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/js",
3
- "version": "1.8.5",
3
+ "version": "1.8.6",
4
4
  "description": "SDK to integrate Storyblok into your project using JavaScript.",
5
5
  "main": "./dist/storyblok-js.js",
6
6
  "module": "./dist/storyblok-js.mjs",
@@ -27,7 +27,7 @@
27
27
  "prepublishOnly": "npm run build && cp ../README.md ./"
28
28
  },
29
29
  "dependencies": {
30
- "storyblok-js-client": "^4.5.7"
30
+ "storyblok-js-client": "^4.5.8"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@babel/core": "^7.19.0",