@storyblok/svelte 2.3.4 → 2.3.5

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,7 +2,7 @@
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 H(r){return typeof r=="number"&&r==r&&r!==1/0&&r!==-1/0}function V(r,t,e){if(!H(t))throw new TypeError("Expected `limit` to be a finite number");if(!H(e))throw new TypeError("Expected `interval` to be a finite number");var n=[],o=[],s=0,a=function(){s++;var l=setTimeout(function(){s--,n.length>0&&a(),o=o.filter(function(u){return u!==l})},e);o.indexOf(l)<0&&o.push(l);var c=n.shift();c.resolve(r.apply(c.self,c.args))},i=function(){var l=arguments,c=this;return new Promise(function(u,f){n.push({resolve:u,reject:f,args:l,self:c}),s<t&&a()})};return i.abort=function(){o.forEach(clearTimeout),o=[],n.forEach(function(l){l.reject(new throttle.AbortError)}),n.length=0},i}V.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const yt=function(r,t){if(!r)return null;let e={};for(let n in r){let o=r[n];t.indexOf(n)>-1&&o!==null&&(e[n]=o)}return e};var kt={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:r=>({tag:["pre",{tag:"code",attrs:r.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:r=>({tag:`h${r.attrs.level}`}),image:r=>({singleTag:[{tag:"img",attrs:yt(r.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(r){const t=d({},r.attrs),{linktype:e="url"}=r.attrs;return e==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:r=>({tag:[{tag:"span",attrs:r.attrs}]})}};class _t{constructor(t){t||(t=kt),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.content&&Array.isArray(t.content)){let e="";return t.content.forEach(n=>{e+=this.renderNode(n)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(o=>{const s=this.getMatchingMark(o);s&&e.push(this.renderOpeningTag(s.tag))});const n=this.getMatchingNode(t);return n&&n.tag&&e.push(this.renderOpeningTag(n.tag)),t.content?t.content.forEach(o=>{e.push(this.renderNode(o))}):t.text?e.push(function(o){const s={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},a=/[&<>"']/g,i=RegExp(a.source);return o&&i.test(o)?o.replace(a,l=>s[l]):o}(t.text)):n&&n.singleTag?e.push(this.renderTag(n.singleTag," /")):n&&n.html&&e.push(n.html),n&&n.tag&&e.push(this.renderClosingTag(n.tag)),t.marks&&t.marks.slice(0).reverse().forEach(o=>{const s=this.getMatchingMark(o);s&&e.push(this.renderClosingTag(s.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(n=>{if(n.constructor===String)return`<${n}${e}>`;{let o=`<${n.tag}`;if(n.attrs)for(let s in n.attrs){let a=n.attrs[s];a!==null&&(o+=` ${s}="${a}"`)}return`${o}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.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 bt=(r=0,t=r)=>{const e=Math.abs(t-r)||0,n=r<t?1:-1;return((o=0,s)=>[...Array(o)].map(s))(e,(o,s)=>s*n+r)},E=(r,t,e)=>{const n=[];for(const o in r){if(!Object.prototype.hasOwnProperty.call(r,o))continue;const s=r[o],a=e?"":encodeURIComponent(o);let i;i=typeof s=="object"?E(s,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(s)):(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(s),n.push(i)}return n.join("&")};let b={},g={};class vt{constructor(t,e){if(!e){let s=t.region?`-${t.region}`:"",a=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${a}://api${s}.storyblok.com/v2`:`${a}://api${s}.storyblok.com/v1`}let n=Object.assign({},t.headers),o=5;t.oauthToken!==void 0&&(n.Authorization=t.oauthToken,o=3),t.rateLimit!==void 0&&(o=t.rateLimit),this.richTextResolver=new _t(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=V(this.throttledRequest,o,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=at.default.create({baseURL:e,timeout:t.timeout||0,headers:n,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(s=>t.responseInterceptor(s)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let n="";return e.attrs.body.forEach(o=>{n+=t(o.component,o)}),{html:n}})}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((n="")=>n.indexOf("/cdn/")>-1)(t)?this.parseParams(e):e}makeRequest(t,e,n,o){const s=this.factoryParamOptions(t,((a={},i=25,l=1)=>R(d({},a),{per_page:i,page:l}))(e,n,o));return this.cacheResponse(t,s)}get(t,e){let n=`/${t}`;const o=this.factoryParamOptions(n,e);return this.cacheResponse(n,o)}async getAll(t,e={},n){const o=e.per_page||25,s=`/${t}`,a=s.split("/");n=n||a[a.length-1];const i=await this.makeRequest(s,e,o,1),l=Math.ceil(i.total/o);return((c=[],u)=>c.map(u).reduce((f,$)=>[...f,...$],[]))([i,...await(async(c=[],u)=>Promise.all(c.map(u)))(bt(1,l),async c=>this.makeRequest(s,e,o,c+1))],c=>Object.values(c.data[n]))}post(t,e){let n=`/${t}`;return this.throttle("post",n,e)}put(t,e){let n=`/${t}`;return this.throttle("put",n,e)}delete(t,e){let n=`/${t}`;return this.throttle("delete",n,e)}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const n=t[e];n&&n.fieldtype=="multilink"&&n.linktype=="story"&&typeof n.id=="string"&&this.links[n.id]?n.story=this._cleanCopy(this.links[n.id]):n&&n.linktype==="story"&&typeof n.uuid=="string"&&this.links[n.uuid]&&(n.story=this._cleanCopy(this.links[n.uuid]))}_insertRelations(t,e,n){if(n.indexOf(t.component+"."+e)>-1){if(typeof t[e]=="string")this.relations[t[e]]&&(t[e]=this._cleanCopy(this.relations[t[e]]));else if(t[e].constructor===Array){let o=[];t[e].forEach(s=>{this.relations[s]&&o.push(this._cleanCopy(this.relations[s]))}),t[e]=o}}}_insertAssetsRelations(t,e){e.forEach(n=>{t.id===n.id&&(t.original=n,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,e){let n=o=>{if(o!=null){if(o.constructor===Array)for(let s=0;s<o.length;s++)n(o[s]);else if(o.constructor===Object){if(o._stopResolving)return;for(let s in o)o.component&&o._uid||o.type==="link"?(this._insertRelations(o,s,e),this._insertLinks(o,s)):"id"in o&&o.fieldtype==="asset"&&this._insertAssetsRelations(o,e),n(o[s])}}};n(t.content)}async resolveLinks(t,e){let n=[];if(t.link_uuids){const o=t.link_uuids.length;let s=[];const a=50;for(let i=0;i<o;i+=a){const l=Math.min(o,i+a);s.push(t.link_uuids.slice(i,l))}for(let i=0;i<s.length;i++)(await this.getStories({per_page:a,language:e.language,version:e.version,by_uuids:s[i].join(",")})).data.stories.forEach(l=>{n.push(l)})}else n=t.links;n.forEach(o=>{this.links[o.uuid]=R(d({},o),{_stopResolving:!0})})}async resolveRelations(t,e){let n=[];if(t.rel_uuids){const o=t.rel_uuids.length;let s=[];const a=50;for(let i=0;i<o;i+=a){const l=Math.min(o,i+a);s.push(t.rel_uuids.slice(i,l))}for(let i=0;i<s.length;i++)(await this.getStories({per_page:a,language:e.language,version:e.version,by_uuids:s[i].join(",")})).data.stories.forEach(l=>{n.push(l)})}else n=t.rels;n.forEach(o=>{this.relations[o.uuid]=R(d({},o),{_stopResolving:!0})})}async resolveStories(t,e){let n=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(n=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const o in this.relations)this.iterateTree(this.relations[o],n);t.story?this.iterateTree(t.story,n):t.stories.forEach(o=>{this.iterateTree(o,n)})}resolveAssetsRelations(t){const{assets:e,stories:n,story:o}=t;if(n)for(const s of n)this.iterateTree(s,e);else{if(!o)return t;this.iterateTree(o,e)}}cacheResponse(t,e,n){return n===void 0&&(n=0),new Promise(async(o,s)=>{let a=E({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const c=await i.get(a);if(c)return o(c)}try{let c=await this.throttle("get",t,{params:e,paramsSerializer:f=>E(f)}),u={data:c.data,headers:c.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),c.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return s(c);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(e.version=="draft"&&g[e.token]!=u.data.cv&&this.flushCache(),g[e.token]=u.data.cv),o(u)}catch(c){if(c.response&&c.response.status===429&&(n+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${n} seconds.`),await(l=1e3*n,new Promise(u=>setTimeout(u,l))),this.cacheResponse(t,e,n).then(o).catch(s);s(c)}var l})}throttledRequest(t,e,n){return this.client[t](e,n)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>b[t],getAll:()=>b,set(t,e){b[t]=e},flush(){b={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const wt=(r={})=>{const{apiOptions:t}=r;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 vt(t)}};var Tt=r=>{if(typeof r!="object"||typeof r._editable>"u")return{};const t=JSON.parse(r._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let S;const $t="https://app.storyblok.com/f/storyblok-v2-latest.js",Rt=(r,t,e={})=>{if(!(typeof window>"u")){if(typeof window.storyblokRegisterEvent>"u"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!r){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],o=>{o.action==="input"&&o.story.id===r?t(o.story):(o.action==="change"||o.action==="published")&&o.storyId===r&&window.location.reload()})})}},Et=(r={})=>{const{bridge:t,accessToken:e,use:n=[],apiOptions:o={},richText:s={}}=r;o.accessToken=o.accessToken||e;const a={bridge:t,apiOptions:o};let i={};return n.forEach(l=>{i=d(d({},i),l(a))}),t!==!1&&dt($t),S=new U(s.schema),s.resolver&&J(S,s.resolver),i},J=(r,t)=>{r.addNode("blok",e=>{let n="";return e.attrs.body.forEach(o=>{n+=t(o.component,o)}),{html:n}})},St=(r,t,e)=>{let n=e||S;if(!n){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return r===""?"":r?(t&&(n=new U(t.schema),t.resolver&&J(n,t.resolver)),n.render(r)):(console.warn(`${r} is not a valid Richtext object. This might be because the value of the richtext field is empty.
5
+ */function H(r){return typeof r=="number"&&r==r&&r!==1/0&&r!==-1/0}function V(r,t,e){if(!H(t))throw new TypeError("Expected `limit` to be a finite number");if(!H(e))throw new TypeError("Expected `interval` to be a finite number");var n=[],o=[],s=0,a=function(){s++;var l=setTimeout(function(){s--,n.length>0&&a(),o=o.filter(function(u){return u!==l})},e);o.indexOf(l)<0&&o.push(l);var c=n.shift();c.resolve(r.apply(c.self,c.args))},i=function(){var l=arguments,c=this;return new Promise(function(u,f){n.push({resolve:u,reject:f,args:l,self:c}),s<t&&a()})};return i.abort=function(){o.forEach(clearTimeout),o=[],n.forEach(function(l){l.reject(new throttle.AbortError)}),n.length=0},i}V.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const yt=function(r,t){if(!r)return null;let e={};for(let n in r){let o=r[n];t.indexOf(n)>-1&&o!==null&&(e[n]=o)}return e};var kt={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:r=>({tag:["pre",{tag:"code",attrs:r.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:r=>({tag:`h${r.attrs.level}`}),image:r=>({singleTag:[{tag:"img",attrs:yt(r.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(r){const t=d({},r.attrs),{linktype:e="url"}=r.attrs;return e==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:r=>({tag:[{tag:"span",attrs:r.attrs}]})}};class _t{constructor(t){t||(t=kt),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.content&&Array.isArray(t.content)){let e="";return t.content.forEach(n=>{e+=this.renderNode(n)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(o=>{const s=this.getMatchingMark(o);s&&e.push(this.renderOpeningTag(s.tag))});const n=this.getMatchingNode(t);return n&&n.tag&&e.push(this.renderOpeningTag(n.tag)),t.content?t.content.forEach(o=>{e.push(this.renderNode(o))}):t.text?e.push(function(o){const s={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},a=/[&<>"']/g,i=RegExp(a.source);return o&&i.test(o)?o.replace(a,l=>s[l]):o}(t.text)):n&&n.singleTag?e.push(this.renderTag(n.singleTag," /")):n&&n.html&&e.push(n.html),n&&n.tag&&e.push(this.renderClosingTag(n.tag)),t.marks&&t.marks.slice(0).reverse().forEach(o=>{const s=this.getMatchingMark(o);s&&e.push(this.renderClosingTag(s.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(n=>{if(n.constructor===String)return`<${n}${e}>`;{let o=`<${n.tag}`;if(n.attrs)for(let s in n.attrs){let a=n.attrs[s];a!==null&&(o+=` ${s}="${a}"`)}return`${o}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.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 bt=(r=0,t=r)=>{const e=Math.abs(t-r)||0,n=r<t?1:-1;return((o=0,s)=>[...Array(o)].map(s))(e,(o,s)=>s*n+r)},E=(r,t,e)=>{const n=[];for(const o in r){if(!Object.prototype.hasOwnProperty.call(r,o))continue;const s=r[o],a=e?"":encodeURIComponent(o);let i;i=typeof s=="object"?E(s,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(s)):(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(s),n.push(i)}return n.join("&")};let b={},g={};class vt{constructor(t,e){if(!e){let s=t.region?`-${t.region}`:"",a=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${a}://api${s}.storyblok.com/v2`:`${a}://api${s}.storyblok.com/v1`}let n=Object.assign({},t.headers),o=5;t.oauthToken!==void 0&&(n.Authorization=t.oauthToken,o=3),t.rateLimit!==void 0&&(o=t.rateLimit),this.richTextResolver=new _t(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=V(this.throttledRequest,o,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=at.default.create({baseURL:e,timeout:t.timeout||0,headers:n,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(s=>t.responseInterceptor(s)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let n="";return e.attrs.body.forEach(o=>{n+=t(o.component,o)}),{html:n}})}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((n="")=>n.indexOf("/cdn/")>-1)(t)?this.parseParams(e):e}makeRequest(t,e,n,o){const s=this.factoryParamOptions(t,((a={},i=25,l=1)=>R(d({},a),{per_page:i,page:l}))(e,n,o));return this.cacheResponse(t,s)}get(t,e){let n=`/${t}`;const o=this.factoryParamOptions(n,e);return this.cacheResponse(n,o)}async getAll(t,e={},n){const o=e.per_page||25,s=`/${t}`,a=s.split("/");n=n||a[a.length-1];const i=await this.makeRequest(s,e,o,1),l=i.total?Math.ceil(i.total/o):1;return((c=[],u)=>c.map(u).reduce((f,$)=>[...f,...$],[]))([i,...await(async(c=[],u)=>Promise.all(c.map(u)))(bt(1,l),async c=>this.makeRequest(s,e,o,c+1))],c=>Object.values(c.data[n]))}post(t,e){let n=`/${t}`;return this.throttle("post",n,e)}put(t,e){let n=`/${t}`;return this.throttle("put",n,e)}delete(t,e){let n=`/${t}`;return this.throttle("delete",n,e)}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const n=t[e];n&&n.fieldtype=="multilink"&&n.linktype=="story"&&typeof n.id=="string"&&this.links[n.id]?n.story=this._cleanCopy(this.links[n.id]):n&&n.linktype==="story"&&typeof n.uuid=="string"&&this.links[n.uuid]&&(n.story=this._cleanCopy(this.links[n.uuid]))}_insertRelations(t,e,n){if(n.indexOf(t.component+"."+e)>-1){if(typeof t[e]=="string")this.relations[t[e]]&&(t[e]=this._cleanCopy(this.relations[t[e]]));else if(t[e].constructor===Array){let o=[];t[e].forEach(s=>{this.relations[s]&&o.push(this._cleanCopy(this.relations[s]))}),t[e]=o}}}_insertAssetsRelations(t,e){e.forEach(n=>{t.id===n.id&&(t.original=n,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,e){let n=o=>{if(o!=null){if(o.constructor===Array)for(let s=0;s<o.length;s++)n(o[s]);else if(o.constructor===Object){if(o._stopResolving)return;for(let s in o)o.component&&o._uid||o.type==="link"?(this._insertRelations(o,s,e),this._insertLinks(o,s)):"id"in o&&o.fieldtype==="asset"&&this._insertAssetsRelations(o,e),n(o[s])}}};n(t.content)}async resolveLinks(t,e){let n=[];if(t.link_uuids){const o=t.link_uuids.length;let s=[];const a=50;for(let i=0;i<o;i+=a){const l=Math.min(o,i+a);s.push(t.link_uuids.slice(i,l))}for(let i=0;i<s.length;i++)(await this.getStories({per_page:a,language:e.language,version:e.version,by_uuids:s[i].join(",")})).data.stories.forEach(l=>{n.push(l)})}else n=t.links;n.forEach(o=>{this.links[o.uuid]=R(d({},o),{_stopResolving:!0})})}async resolveRelations(t,e){let n=[];if(t.rel_uuids){const o=t.rel_uuids.length;let s=[];const a=50;for(let i=0;i<o;i+=a){const l=Math.min(o,i+a);s.push(t.rel_uuids.slice(i,l))}for(let i=0;i<s.length;i++)(await this.getStories({per_page:a,language:e.language,version:e.version,by_uuids:s[i].join(",")})).data.stories.forEach(l=>{n.push(l)})}else n=t.rels;n.forEach(o=>{this.relations[o.uuid]=R(d({},o),{_stopResolving:!0})})}async resolveStories(t,e){let n=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(n=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const o in this.relations)this.iterateTree(this.relations[o],n);t.story?this.iterateTree(t.story,n):t.stories.forEach(o=>{this.iterateTree(o,n)})}resolveAssetsRelations(t){const{assets:e,stories:n,story:o}=t;if(n)for(const s of n)this.iterateTree(s,e);else{if(!o)return t;this.iterateTree(o,e)}}cacheResponse(t,e,n){return n===void 0&&(n=0),new Promise(async(o,s)=>{let a=E({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const c=await i.get(a);if(c)return o(c)}try{let c=await this.throttle("get",t,{params:e,paramsSerializer:f=>E(f)}),u={data:c.data,headers:c.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),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)return s(c);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(e.version=="draft"&&g[e.token]!=u.data.cv&&this.flushCache(),g[e.token]=u.data.cv),o(u)}catch(c){if(c.response&&c.response.status===429&&(n+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${n} seconds.`),await(l=1e3*n,new Promise(u=>setTimeout(u,l))),this.cacheResponse(t,e,n).then(o).catch(s);s(c)}var l})}throttledRequest(t,e,n){return this.client[t](e,n)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>b[t],getAll:()=>b,set(t,e){b[t]=e},flush(){b={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const wt=(r={})=>{const{apiOptions:t}=r;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 vt(t)}};var Tt=r=>{if(typeof r!="object"||typeof r._editable>"u")return{};const t=JSON.parse(r._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let S;const $t="https://app.storyblok.com/f/storyblok-v2-latest.js",Rt=(r,t,e={})=>{if(!(typeof window>"u")){if(typeof window.storyblokRegisterEvent>"u"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!r){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],o=>{o.action==="input"&&o.story.id===r?t(o.story):(o.action==="change"||o.action==="published")&&o.storyId===r&&window.location.reload()})})}},Et=(r={})=>{const{bridge:t,accessToken:e,use:n=[],apiOptions:o={},richText:s={}}=r;o.accessToken=o.accessToken||e;const a={bridge:t,apiOptions:o};let i={};return n.forEach(l=>{i=d(d({},i),l(a))}),t!==!1&&dt($t),S=new U(s.schema),s.resolver&&J(S,s.resolver),i},J=(r,t)=>{r.addNode("blok",e=>{let n="";return e.attrs.body.forEach(o=>{n+=t(o.component,o)}),{html:n}})},St=(r,t,e)=>{let n=e||S;if(!n){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return r===""?"":r?(t&&(n=new U(t.schema),t.resolver&&J(n,t.resolver)),n.render(r)):(console.warn(`${r} 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`),"")};function Y(){}function x(r,t){for(const e in t)r[e]=t[e];return r}function F(r){return r()}function K(){return Object.create(null)}function y(r){r.forEach(F)}function xt(r){return typeof r=="function"}function Ot(r,t){return r!=r?t==t:r!==t||r&&typeof r=="object"||typeof r=="function"}function jt(r){return Object.keys(r).length===0}function Pt(r){const t={};for(const e in r)e[0]!=="$"&&(t[e]=r[e]);return t}function G(r,t){const e={};t=new Set(t);for(const n in r)!t.has(n)&&n[0]!=="$"&&(e[n]=r[n]);return e}function At(r,t,e){r.insertBefore(t,e||null)}function Q(r){r.parentNode.removeChild(r)}function Ct(r){return document.createTextNode(r)}function Mt(){return Ct("")}function Nt(r){return Array.from(r.childNodes)}let O;function k(r){O=r}const _=[],W=[],v=[],X=[],It=Promise.resolve();let j=!1;function Lt(){j||(j=!0,It.then(Z))}function P(r){v.push(r)}const A=new Set;let w=0;function Z(){const r=O;do{for(;w<_.length;){const t=_[w];w++,k(t),qt(t.$$)}for(k(null),_.length=0,w=0;W.length;)W.pop()();for(let t=0;t<v.length;t+=1){const e=v[t];A.has(e)||(A.add(e),e())}v.length=0}while(_.length);for(;X.length;)X.pop()();j=!1,A.clear(),k(r)}function qt(r){if(r.fragment!==null){r.update(),y(r.before_update);const t=r.dirty;r.dirty=[-1],r.fragment&&r.fragment.p(r.ctx,t),r.after_update.forEach(P)}}const T=new Set;let p;function Bt(){p={r:0,c:[],p}}function Dt(){p.r||y(p.c),p=p.p}function C(r,t){r&&r.i&&(T.delete(r),r.i(t))}function tt(r,t,e,n){if(r&&r.o){if(T.has(r))return;T.add(r),p.c.push(()=>{T.delete(r),n&&(e&&r.d(1),n())}),r.o(t)}else n&&n()}function zt(r,t){const e={},n={},o={$$scope:1};let s=r.length;for(;s--;){const a=r[s],i=t[s];if(i){for(const l in a)l in i||(n[l]=1);for(const l in i)o[l]||(e[l]=i[l],o[l]=1);r[s]=i}else for(const l in a)o[l]=1}for(const a in n)a in e||(e[a]=void 0);return e}function Ut(r){return typeof r=="object"&&r!==null?r:{}}function et(r){r&&r.c()}function M(r,t,e,n){const{fragment:o,on_mount:s,on_destroy:a,after_update:i}=r.$$;o&&o.m(t,e),n||P(()=>{const l=s.map(F).filter(xt);a?a.push(...l):y(l),r.$$.on_mount=[]}),i.forEach(P)}function N(r,t){const e=r.$$;e.fragment!==null&&(y(e.on_destroy),e.fragment&&e.fragment.d(t),e.on_destroy=e.fragment=null,e.ctx=[])}function Ht(r,t){r.$$.dirty[0]===-1&&(_.push(r),Lt(),r.$$.dirty.fill(0)),r.$$.dirty[t/31|0]|=1<<t%31}function Vt(r,t,e,n,o,s,a,i=[-1]){const l=O;k(r);const c=r.$$={fragment:null,ctx:null,props:s,update:Y,not_equal:o,bound:K(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(l?l.$$.context:[])),callbacks:K(),dirty:i,skip_bound:!1,root:t.target||l.$$.root};a&&a(c.root);let u=!1;if(c.ctx=e?e(r,t.props||{},(f,$,...st)=>{const it=st.length?st[0]:$;return c.ctx&&o(c.ctx[f],c.ctx[f]=it)&&(!c.skip_bound&&c.bound[f]&&c.bound[f](it),u&&Ht(r,f)),$}):[],c.update(),u=!0,y(c.before_update),c.fragment=n?n(c.ctx):!1,t.target){if(t.hydrate){const f=Nt(t.target);c.fragment&&c.fragment.l(f),f.forEach(Q)}else c.fragment&&c.fragment.c();t.intro&&C(r.$$.fragment),M(r,t.target,t.anchor,t.customElement),Z()}k(l)}class Jt{$destroy(){N(this,1),this.$destroy=Y}$on(t,e){const n=this.$$.callbacks[t]||(this.$$.callbacks[t]=[]);return n.push(e),()=>{const o=n.indexOf(e);o!==-1&&n.splice(o,1)}}$set(t){this.$$set&&!jt(t)&&(this.$$.skip_bound=!0,this.$$set(t),this.$$.skip_bound=!1)}}function Yt(r){let t,e,n;const o=[{blok:r[0]},r[2]];var s=r[1];function a(i){let l={};for(let c=0;c<o.length;c+=1)l=x(l,o[c]);return{props:l}}return s&&(t=new s(a())),{c(){t&&et(t.$$.fragment),e=Mt()},m(i,l){t&&M(t,i,l),At(i,e,l),n=!0},p(i,[l]){const c=l&5?zt(o,[l&1&&{blok:i[0]},l&4&&Ut(i[2])]):{};if(s!==(s=i[1])){if(t){Bt();const u=t;tt(u.$$.fragment,1,0,()=>{N(u,1)}),Dt()}s?(t=new s(a()),et(t.$$.fragment),C(t.$$.fragment,1),M(t,e.parentNode,e)):t=null}else s&&t.$set(c)},i(i){n||(t&&C(t.$$.fragment,i),n=!0)},o(i){t&&tt(t.$$.fragment,i),n=!1},d(i){i&&Q(e),t&&N(t,i)}}}function Ft(r,t,e){const n=["blok"];let o=G(t,n),s,{blok:a}=t;return a?s=ot(a.component):console.error("Please provide a 'blok' property to the StoryblokComponent"),r.$$set=i=>{t=x(x({},t),Pt(i)),e(2,o=G(t,n)),"blok"in i&&e(0,a=i.blok)},[a,s,o]}class Kt extends Jt{constructor(t){super(),Vt(this,t,Ft,Yt,Ot,{blok:0})}}const Gt=(r,t)=>{const e=n=>{const o=Tt(n);o["data-blok-c"]&&(r.setAttribute("data-blok-c",o["data-blok-c"]),r.setAttribute("data-blok-uid",o["data-blok-uid"]),r.classList.add("storyblok__outline"))};return e(t),{update(n){e(n)}}};let I=null;const rt=()=>(I||console.log("You can't use getStoryblokApi if you're not loading apiPlugin."),I);let nt=null;const Qt=r=>{const{storyblokApi:t}=Et(r);I=t,nt=r.components||{}},ot=r=>{const t=nt[r];return t||console.error(`You didn't load the ${r} component. Please load it in storyblokInit. For example:
8
8
  storyblokInit({
@@ -390,7 +390,7 @@ class yt {
390
390
  async getAll(t, e = {}, n) {
391
391
  const s = e.per_page || 25, o = `/${t}`, a = o.split("/");
392
392
  n = n || a[a.length - 1];
393
- const i = await this.makeRequest(o, e, s, 1), l = Math.ceil(i.total / s);
393
+ const i = await this.makeRequest(o, e, s, 1), l = i.total ? Math.ceil(i.total / s) : 1;
394
394
  return ((c = [], u) => c.map(u).reduce((h, k) => [...h, ...k], []))([i, ...await (async (c = [], u) => Promise.all(c.map(u)))(mt(1, l), async (c) => this.makeRequest(o, e, s, c + 1))], (c) => Object.values(c.data[n]));
395
395
  }
396
396
  post(t, e) {
@@ -527,7 +527,7 @@ class yt {
527
527
  }
528
528
  try {
529
529
  let c = await this.throttle("get", t, { params: e, paramsSerializer: (h) => R(h) }), u = { data: c.data, headers: c.headers };
530
- if (u.data.assets && u.data.assets.length && this.resolveAssetsRelations(u.data), c.headers["per-page"] && (u = Object.assign({}, u, { perPage: parseInt(c.headers["per-page"]), total: parseInt(c.headers.total) })), c.status != 200)
530
+ if (u.data.assets && u.data.assets.length && this.resolveAssetsRelations(u.data), 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)
531
531
  return o(c);
532
532
  (u.data.story || u.data.stories) && await this.resolveStories(u.data, e), e.version === "published" && t != "/cdn/spaces/me" && i.set(a, u), u.data.cv && (e.version == "draft" && p[e.token] != u.data.cv && this.flushCache(), p[e.token] = u.data.cv), s(u);
533
533
  } catch (c) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/svelte",
3
- "version": "2.3.4",
3
+ "version": "2.3.5",
4
4
  "description": "Storyblok SDK to connect Storyblok with Svelte",
5
5
  "main": "./dist/storyblok-svelte.js",
6
6
  "module": "./dist/storyblok-svelte.mjs",
@@ -28,10 +28,10 @@
28
28
  "prepublishOnly": "npm run build && cp ../README.md ./"
29
29
  },
30
30
  "dependencies": {
31
- "@storyblok/js": "^1.8.5"
31
+ "@storyblok/js": "^1.8.6"
32
32
  },
33
33
  "devDependencies": {
34
- "@babel/core": "^7.19.1",
34
+ "@babel/core": "^7.19.3",
35
35
  "@cypress/vite-dev-server": "^2.2.3",
36
36
  "@tsconfig/svelte": "^3.0.0",
37
37
  "babel-jest": "^28.1.3",