@storyblok/svelte 2.4.4 → 2.4.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.
@@ -1,4 +1,4 @@
1
- (function(d,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(d=typeof globalThis<"u"?globalThis:d||self,g(d.storyblokSvelte={}))})(this,function(d){"use strict";let g=!1;const U=[],rt=s=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}g?r():U.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const n=document.createElement("script");n.async=!0,n.src=s,n.id="storyblok-javascript-bridge",n.onerror=r=>e(r),n.onload=r=>{U.forEach(o=>o()),g=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(n)});var ot=Object.defineProperty,it=(s,t,e)=>t in s?ot(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,h=(s,t,e)=>(it(s,typeof t!="symbol"?t+"":t,e),e);function H(s){return!(s!==s||s===1/0||s===-1/0)}function at(s,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");const n=[];let r=[],o=0;const c=function(){o++;const a=setTimeout(function(){o--,n.length>0&&c(),r=r.filter(function(u){return u!==a})},e);r.indexOf(a)<0&&r.push(a);const l=n.shift();l.resolve(s.apply(l.self,l.args))},i=function(...a){const l=this;return new Promise(function(u,f){n.push({resolve:u,reject:f,args:a,self:l}),o<t&&c()})};return i.abort=function(){r.forEach(clearTimeout),r=[],n.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),n.length=0},i}const ct=function(s,t){const e={};for(const n in s){const r=s[n];t.indexOf(n)>-1&&r!==null&&(e[n]=r)}return e},lt=s=>s==="email",ht=()=>({singleTag:"hr"}),ut=()=>({tag:"blockquote"}),dt=()=>({tag:"ul"}),ft=s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),pt=()=>({singleTag:"br"}),gt=s=>({tag:`h${s.attrs.level}`}),mt=s=>({singleTag:[{tag:"img",attrs:ct(s.attrs,["src","alt","title"])}]}),yt=()=>({tag:"li"}),kt=()=>({tag:"ol"}),bt=()=>({tag:"p"}),_t=()=>({tag:"b"}),vt=()=>({tag:"strike"}),wt=()=>({tag:"u"}),$t=()=>({tag:"strong"}),Tt=()=>({tag:"code"}),Rt=()=>({tag:"i"}),jt=s=>{const t={...s.attrs},{linktype:e="url"}=s.attrs;return lt(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},xt=s=>({tag:[{tag:"span",attrs:s.attrs}]}),q={nodes:{horizontal_rule:ht,blockquote:ut,bullet_list:dt,code_block:ft,hard_break:pt,heading:gt,image:mt,list_item:yt,ordered_list:kt,paragraph:bt},marks:{bold:_t,strike:vt,underline:wt,strong:$t,code:Tt,italic:Rt,link:jt,styled:xt}},Et=function(s){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,n=RegExp(e.source);return s&&n.test(s)?s.replace(e,r=>t[r]):s};class w{constructor(t){h(this,"marks"),h(this,"nodes"),t||(t=q),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(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){const e=[];t.marks&&t.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&e.push(this.renderOpeningTag(o.tag))});const n=this.getMatchingNode(t);return n&&n.tag&&e.push(this.renderOpeningTag(n.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(Et(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(r=>{const o=this.getMatchingMark(r);o&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(n=>{if(n.constructor===String)return`<${n}${e}>`;{let r=`<${n.tag}`;if(n.attrs)for(const o in n.attrs){const c=n.attrs[o];c!==null&&(r+=` ${o}="${c}"`)}return`${r}${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){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 D{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(t,e=25,n=1)=>({...t,per_page:e,page:n})),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 n=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(n,(o,c)=>c*r+t)}),h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),h(this,"flatMap",(t=[],e)=>t.map(e).reduce((n,r)=>[...n,...r],[]))}stringify(t,e,n){const r=[];for(const o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;const c=t[o],i=n?"":encodeURIComponent(o);let a;typeof c=="object"?a=this.stringify(c,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(c)):a=(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(c),r.push(a)}return r.join("&")}}class St{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||[],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=[],n={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{n.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return n.headers={...e},n.status=t.status,n.statusText=t.statusText,n}async _methodHandler(t){let e=`${this.baseURL}${this.url}}`,n=null;if(t==="get"){const a=new D;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else n=JSON.stringify(this.parameters);const r=new URL(e),o=new AbortController,{signal:c}=o;let i;this.timeout&&(i=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:n,signal:c});this.timeout&&clearTimeout(i);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return a}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((n,r)=>{if(e.test(`${t.status}`))return n(t);const o={message:new Error(t.statusText||`status: ${t.status}`),response:t};r(o)})}}let $={};const m={};class Pt{constructor(t,e){if(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"),!e){const o=t.region?`-${t.region}`:"",c=t.https===!1?"http":"https";t.oauthToken?e=`${c}://api${o}.storyblok.com/v1`:e=`${c}://api${o}.storyblok.com/v2`}const n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),n.forEach((o,c)=>{t.headers&&t.headers[c]&&n.set(c,t.headers[c])});let r=5;t.oauthToken&&(n.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new w(t.richTextSchema):this.richTextResolver=new w,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=at(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new D,this.resolveNestedRelations=!1,this.client=new St({baseURL:e,timeout:t.timeout||0,headers:n,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let n="";return e.attrs.body.forEach(r=>{n+=t(r.component,r)}),{html:n}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=m[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,n,r){const o=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,n,r));return this.cacheResponse(t,o)}get(t,e){e||(e={});const n=`/${t}`,r=this.factoryParamOptions(n,e);return this.cacheResponse(n,r)}async getAll(t,e,n){const r=(e==null?void 0:e.per_page)||25,o=`/${t}`,c=o.split("/"),i=n||c[c.length-1],a=1,l=await this.makeRequest(o,e,r,a),u=l.total?Math.ceil(l.total/r):1,f=await this.helpers.asyncMap(this.helpers.range(a,u),b=>this.makeRequest(o,e,r,b+1));return this.helpers.flatMap([l,...f],b=>Object.values(b.data[i]))}post(t,e){const n=`/${t}`;return Promise.resolve(this.throttle("post",n,e))}put(t,e){const n=`/${t}`;return Promise.resolve(this.throttle("put",n,e))}delete(t,e){const n=`/${t}`;return Promise.resolve(this.throttle("delete",n,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){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]&&t[e].constructor===Array){const r=[];t[e].forEach(o=>{this.relations[o]&&r.push(this._cleanCopy(this.relations[o]))}),t[e]=r}}}iterateTree(t,e){const n=r=>{if(r!=null){if(r.constructor===Array)for(let o=0;o<r.length;o++)n(r[o]);else if(r.constructor===Object){if(r._stopResolving)return;for(const o in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,o,e),this._insertLinks(r,o)),n(r[o])}}};n(t.content)}async resolveLinks(t,e){let n=[];if(t.link_uuids){const r=t.link_uuids.length,o=[],c=50;for(let i=0;i<r;i+=c){const a=Math.min(r,i+c);o.push(t.link_uuids.slice(i,a))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:o[i].join(",")})).data.stories.forEach(a=>{n.push(a)})}else n=t.links;n.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(t,e){let n=[];if(t.rel_uuids){const r=t.rel_uuids.length,o=[],c=50;for(let i=0;i<r;i+=c){const a=Math.min(r,i+c);o.push(t.rel_uuids.slice(i,a))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:o[i].join(",")})).data.stories.forEach(a=>{n.push(a)})}else n=t.rels;n&&n.length>0&&n.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(t,e){var n,r;let o=[];if(typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(o=e.resolve_relations.split(",")),await this.resolveRelations(t,e)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((n=t.links)!=null&&n.length||(r=t.link_uuids)!=null&&r.length)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const c in this.relations)this.iterateTree(this.relations[c],o);t.story?this.iterateTree(t.story,o):t.stories.forEach(c=>{this.iterateTree(c,o)})}cacheResponse(t,e,n){return new Promise((r,o)=>{const c=this.helpers.stringify({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const a=i.get(c);if(a)return r(a)}try{(async()=>{var a;const l=await this.throttle("get",t,e);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["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 o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&i.set(c,u),u.data.cv&&e.token&&(e.version=="draft"&&m[e.token]!=u.data.cv&&this.flushCache(),m[e.token]=u.data.cv),r(u)})()}catch{}})}throttledRequest(t,e,n){return this.client[t](e,n)}cacheVersions(){return m}cacheVersion(){return m[this.accessToken]}setCacheVersion(t){this.accessToken&&(m[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return $[t]},getAll(){return $},set(t,e){$[t]=e},flush(){$={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}flushCache(){return this.cacheProvider().flush(),this}}const Ot=(s={})=>{const{apiOptions:t}=s;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 Pt(t)}},Ct=s=>{if(typeof s!="object"||typeof s._editable>"u")return{};const t=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let x;const It="https://app.storyblok.com/f/storyblok-v2-latest.js",At=(s,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(!s){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],n=>{n.action==="input"&&n.story.id===s?t(n.story):(n.action==="change"||n.action==="published")&&n.storyId===s&&window.location.reload()})})}},Nt=(s={})=>{const{bridge:t,accessToken:e,use:n=[],apiOptions:r={},richText:o={}}=s;r.accessToken=r.accessToken||e;const c={bridge:t,apiOptions:r};let i={};return n.forEach(a=>{i={...i,...a(c)}}),t!==!1&&rt(It),x=new w(o.schema),o.resolver&&B(x,o.resolver),i},B=(s,t)=>{s.addNode("blok",e=>{let n="";return e.attrs.body.forEach(r=>{n+=t(r.component,r)}),{html:n}})},Mt=(s,t,e)=>{let n=e||x;if(!n){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return s===""?"":s?(t&&(n=new w(t.schema),t.resolver&&B(n,t.resolver)),n.render(s)):(console.warn(`${s} is not a valid Richtext object. This might be because the value of the richtext field is empty.
1
+ (function(d,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(d=typeof globalThis<"u"?globalThis:d||self,g(d.storyblokSvelte={}))})(this,function(d){"use strict";let g=!1;const U=[],rt=s=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}g?r():U.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const n=document.createElement("script");n.async=!0,n.src=s,n.id="storyblok-javascript-bridge",n.onerror=r=>e(r),n.onload=r=>{U.forEach(o=>o()),g=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(n)});var ot=Object.defineProperty,it=(s,t,e)=>t in s?ot(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,h=(s,t,e)=>(it(s,typeof t!="symbol"?t+"":t,e),e);function H(s){return!(s!==s||s===1/0||s===-1/0)}function at(s,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");const n=[];let r=[],o=0;const c=function(){o++;const a=setTimeout(function(){o--,n.length>0&&c(),r=r.filter(function(u){return u!==a})},e);r.indexOf(a)<0&&r.push(a);const l=n.shift();l.resolve(s.apply(l.self,l.args))},i=function(...a){const l=this;return new Promise(function(u,f){n.push({resolve:u,reject:f,args:a,self:l}),o<t&&c()})};return i.abort=function(){r.forEach(clearTimeout),r=[],n.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),n.length=0},i}const ct=function(s,t){const e={};for(const n in s){const r=s[n];t.indexOf(n)>-1&&r!==null&&(e[n]=r)}return e},lt=s=>s==="email",ht=()=>({singleTag:"hr"}),ut=()=>({tag:"blockquote"}),dt=()=>({tag:"ul"}),ft=s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),pt=()=>({singleTag:"br"}),gt=s=>({tag:`h${s.attrs.level}`}),mt=s=>({singleTag:[{tag:"img",attrs:ct(s.attrs,["src","alt","title"])}]}),yt=()=>({tag:"li"}),kt=()=>({tag:"ol"}),bt=()=>({tag:"p"}),_t=()=>({tag:"b"}),vt=()=>({tag:"strike"}),wt=()=>({tag:"u"}),$t=()=>({tag:"strong"}),Tt=()=>({tag:"code"}),Rt=()=>({tag:"i"}),jt=s=>{const t={...s.attrs},{linktype:e="url"}=s.attrs;return lt(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},xt=s=>({tag:[{tag:"span",attrs:s.attrs}]}),q={nodes:{horizontal_rule:ht,blockquote:ut,bullet_list:dt,code_block:ft,hard_break:pt,heading:gt,image:mt,list_item:yt,ordered_list:kt,paragraph:bt},marks:{bold:_t,strike:vt,underline:wt,strong:$t,code:Tt,italic:Rt,link:jt,styled:xt}},Et=function(s){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,n=RegExp(e.source);return s&&n.test(s)?s.replace(e,r=>t[r]):s};class w{constructor(t){h(this,"marks"),h(this,"nodes"),t||(t=q),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(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){const e=[];t.marks&&t.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&e.push(this.renderOpeningTag(o.tag))});const n=this.getMatchingNode(t);return n&&n.tag&&e.push(this.renderOpeningTag(n.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(Et(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(r=>{const o=this.getMatchingMark(r);o&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(n=>{if(n.constructor===String)return`<${n}${e}>`;{let r=`<${n.tag}`;if(n.attrs)for(const o in n.attrs){const c=n.attrs[o];c!==null&&(r+=` ${o}="${c}"`)}return`${r}${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){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 D{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(t,e=25,n=1)=>({...t,per_page:e,page:n})),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 n=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(n,(o,c)=>c*r+t)}),h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),h(this,"flatMap",(t=[],e)=>t.map(e).reduce((n,r)=>[...n,...r],[]))}stringify(t,e,n){const r=[];for(const o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;const c=t[o],i=n?"":encodeURIComponent(o);let a;typeof c=="object"?a=this.stringify(c,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(c)):a=(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(c),r.push(a)}return r.join("&")}}class St{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||[],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=[],n={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{n.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return n.headers={...e},n.status=t.status,n.statusText=t.statusText,n}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,n=null;if(t==="get"){const a=new D;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else n=JSON.stringify(this.parameters);const r=new URL(e),o=new AbortController,{signal:c}=o;let i;this.timeout&&(i=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:n,signal:c});this.timeout&&clearTimeout(i);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return a}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((n,r)=>{if(e.test(`${t.status}`))return n(t);const o={message:new Error(t.statusText||`status: ${t.status}`),response:t};r(o)})}}let $={};const m={};class Pt{constructor(t,e){if(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"),!e){const o=t.region?`-${t.region}`:"",c=t.https===!1?"http":"https";t.oauthToken?e=`${c}://api${o}.storyblok.com/v1`:e=`${c}://api${o}.storyblok.com/v2`}const n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),n.forEach((o,c)=>{t.headers&&t.headers[c]&&n.set(c,t.headers[c])});let r=5;t.oauthToken&&(n.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new w(t.richTextSchema):this.richTextResolver=new w,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=at(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new D,this.resolveNestedRelations=!1,this.client=new St({baseURL:e,timeout:t.timeout||0,headers:n,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let n="";return e.attrs.body.forEach(r=>{n+=t(r.component,r)}),{html:n}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=m[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,n,r){const o=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,n,r));return this.cacheResponse(t,o)}get(t,e){e||(e={});const n=`/${t}`,r=this.factoryParamOptions(n,e);return this.cacheResponse(n,r)}async getAll(t,e,n){const r=(e==null?void 0:e.per_page)||25,o=`/${t}`,c=o.split("/"),i=n||c[c.length-1],a=1,l=await this.makeRequest(o,e,r,a),u=l.total?Math.ceil(l.total/r):1,f=await this.helpers.asyncMap(this.helpers.range(a,u),b=>this.makeRequest(o,e,r,b+1));return this.helpers.flatMap([l,...f],b=>Object.values(b.data[i]))}post(t,e){const n=`/${t}`;return Promise.resolve(this.throttle("post",n,e))}put(t,e){const n=`/${t}`;return Promise.resolve(this.throttle("put",n,e))}delete(t,e){const n=`/${t}`;return Promise.resolve(this.throttle("delete",n,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){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]&&t[e].constructor===Array){const r=[];t[e].forEach(o=>{this.relations[o]&&r.push(this._cleanCopy(this.relations[o]))}),t[e]=r}}}iterateTree(t,e){const n=r=>{if(r!=null){if(r.constructor===Array)for(let o=0;o<r.length;o++)n(r[o]);else if(r.constructor===Object){if(r._stopResolving)return;for(const o in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,o,e),this._insertLinks(r,o)),n(r[o])}}};n(t.content)}async resolveLinks(t,e){let n=[];if(t.link_uuids){const r=t.link_uuids.length,o=[],c=50;for(let i=0;i<r;i+=c){const a=Math.min(r,i+c);o.push(t.link_uuids.slice(i,a))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:o[i].join(",")})).data.stories.forEach(a=>{n.push(a)})}else n=t.links;n.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(t,e){let n=[];if(t.rel_uuids){const r=t.rel_uuids.length,o=[],c=50;for(let i=0;i<r;i+=c){const a=Math.min(r,i+c);o.push(t.rel_uuids.slice(i,a))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:o[i].join(",")})).data.stories.forEach(a=>{n.push(a)})}else n=t.rels;n&&n.length>0&&n.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(t,e){var n,r;let o=[];if(typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(o=e.resolve_relations.split(",")),await this.resolveRelations(t,e)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((n=t.links)!=null&&n.length||(r=t.link_uuids)!=null&&r.length)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const c in this.relations)this.iterateTree(this.relations[c],o);t.story?this.iterateTree(t.story,o):t.stories.forEach(c=>{this.iterateTree(c,o)})}cacheResponse(t,e,n){return new Promise((r,o)=>{const c=this.helpers.stringify({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const a=i.get(c);if(a)return r(a)}try{(async()=>{var a;const l=await this.throttle("get",t,e);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["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 o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&i.set(c,u),u.data.cv&&e.token&&(e.version=="draft"&&m[e.token]!=u.data.cv&&this.flushCache(),m[e.token]=u.data.cv),r(u)})()}catch{}})}throttledRequest(t,e,n){return this.client[t](e,n)}cacheVersions(){return m}cacheVersion(){return m[this.accessToken]}setCacheVersion(t){this.accessToken&&(m[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return $[t]},getAll(){return $},set(t,e){$[t]=e},flush(){$={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}flushCache(){return this.cacheProvider().flush(),this}}const Ot=(s={})=>{const{apiOptions:t}=s;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 Pt(t)}},Ct=s=>{if(typeof s!="object"||typeof s._editable>"u")return{};const t=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let x;const It="https://app.storyblok.com/f/storyblok-v2-latest.js",At=(s,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(!s){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],n=>{n.action==="input"&&n.story.id===s?t(n.story):(n.action==="change"||n.action==="published")&&n.storyId===s&&window.location.reload()})})}},Nt=(s={})=>{const{bridge:t,accessToken:e,use:n=[],apiOptions:r={},richText:o={}}=s;r.accessToken=r.accessToken||e;const c={bridge:t,apiOptions:r};let i={};return n.forEach(a=>{i={...i,...a(c)}}),t!==!1&&rt(It),x=new w(o.schema),o.resolver&&B(x,o.resolver),i},B=(s,t)=>{s.addNode("blok",e=>{let n="";return e.attrs.body.forEach(r=>{n+=t(r.component,r)}),{html:n}})},Mt=(s,t,e)=>{let n=e||x;if(!n){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return s===""?"":s?(t&&(n=new w(t.schema),t.resolver&&B(n,t.resolver)),n.render(s)):(console.warn(`${s} is not a valid Richtext object. This might be because the value of the richtext field is empty.
2
2
 
3
3
  For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")};function E(){}function S(s,t){for(const e in t)s[e]=t[e];return s}function J(s){return s()}function F(){return Object.create(null)}function _(s){s.forEach(J)}function V(s){return typeof s=="function"}function Lt(s,t){return s!=s?t==t:s!==t||s&&typeof s=="object"||typeof s=="function"}function Ut(s){return Object.keys(s).length===0}function Ht(s){const t={};for(const e in s)e[0]!=="$"&&(t[e]=s[e]);return t}function Y(s,t){const e={};t=new Set(t);for(const n in s)!t.has(n)&&n[0]!=="$"&&(e[n]=s[n]);return e}function qt(s,t,e){s.insertBefore(t,e||null)}function z(s){s.parentNode&&s.parentNode.removeChild(s)}function Dt(s){return document.createTextNode(s)}function Bt(){return Dt("")}function Jt(s){return Array.from(s.childNodes)}function K(s,t){return new s(t)}let P;function v(s){P=s}const y=[],G=[],T=[],Q=[],Ft=Promise.resolve();let O=!1;function Vt(){O||(O=!0,Ft.then(W))}function C(s){T.push(s)}const I=new Set;let k=0;function W(){if(k!==0)return;const s=P;do{try{for(;k<y.length;){const t=y[k];k++,v(t),Yt(t.$$)}}catch(t){throw y.length=0,k=0,t}for(v(null),y.length=0,k=0;G.length;)G.pop()();for(let t=0;t<T.length;t+=1){const e=T[t];I.has(e)||(I.add(e),e())}T.length=0}while(y.length);for(;Q.length;)Q.pop()();O=!1,I.clear(),v(s)}function Yt(s){if(s.fragment!==null){s.update(),_(s.before_update);const t=s.dirty;s.dirty=[-1],s.fragment&&s.fragment.p(s.ctx,t),s.after_update.forEach(C)}}const R=new Set;let p;function zt(){p={r:0,c:[],p}}function Kt(){p.r||_(p.c),p=p.p}function A(s,t){s&&s.i&&(R.delete(s),s.i(t))}function X(s,t,e,n){if(s&&s.o){if(R.has(s))return;R.add(s),p.c.push(()=>{R.delete(s),n&&(e&&s.d(1),n())}),s.o(t)}else n&&n()}function Gt(s,t){const e={},n={},r={$$scope:1};let o=s.length;for(;o--;){const c=s[o],i=t[o];if(i){for(const a in c)a in i||(n[a]=1);for(const a in i)r[a]||(e[a]=i[a],r[a]=1);s[o]=i}else for(const a in c)r[a]=1}for(const c in n)c in e||(e[c]=void 0);return e}function Qt(s){return typeof s=="object"&&s!==null?s:{}}function Z(s){s&&s.c()}function N(s,t,e,n){const{fragment:r,after_update:o}=s.$$;r&&r.m(t,e),n||C(()=>{const c=s.$$.on_mount.map(J).filter(V);s.$$.on_destroy?s.$$.on_destroy.push(...c):_(c),s.$$.on_mount=[]}),o.forEach(C)}function M(s,t){const e=s.$$;e.fragment!==null&&(_(e.on_destroy),e.fragment&&e.fragment.d(t),e.on_destroy=e.fragment=null,e.ctx=[])}function Wt(s,t){s.$$.dirty[0]===-1&&(y.push(s),Vt(),s.$$.dirty.fill(0)),s.$$.dirty[t/31|0]|=1<<t%31}function Xt(s,t,e,n,r,o,c,i=[-1]){const a=P;v(s);const l=s.$$={fragment:null,ctx:[],props:o,update:E,not_equal:r,bound:F(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(a?a.$$.context:[])),callbacks:F(),dirty:i,skip_bound:!1,root:t.target||a.$$.root};c&&c(l.root);let u=!1;if(l.ctx=e?e(s,t.props||{},(f,b,...st)=>{const nt=st.length?st[0]:b;return l.ctx&&r(l.ctx[f],l.ctx[f]=nt)&&(!l.skip_bound&&l.bound[f]&&l.bound[f](nt),u&&Wt(s,f)),b}):[],l.update(),u=!0,_(l.before_update),l.fragment=n?n(l.ctx):!1,t.target){if(t.hydrate){const f=Jt(t.target);l.fragment&&l.fragment.l(f),f.forEach(z)}else l.fragment&&l.fragment.c();t.intro&&A(s.$$.fragment),N(s,t.target,t.anchor,t.customElement),W()}v(a)}class Zt{$destroy(){M(this,1),this.$destroy=E}$on(t,e){if(!V(e))return E;const n=this.$$.callbacks[t]||(this.$$.callbacks[t]=[]);return n.push(e),()=>{const r=n.indexOf(e);r!==-1&&n.splice(r,1)}}$set(t){this.$$set&&!Ut(t)&&(this.$$.skip_bound=!0,this.$$set(t),this.$$.skip_bound=!1)}}function te(s){let t,e,n;const r=[{blok:s[0]},s[2]];var o=s[1];function c(i){let a={};for(let l=0;l<r.length;l+=1)a=S(a,r[l]);return{props:a}}return o&&(t=K(o,c())),{c(){t&&Z(t.$$.fragment),e=Bt()},m(i,a){t&&N(t,i,a),qt(i,e,a),n=!0},p(i,[a]){const l=a&5?Gt(r,[a&1&&{blok:i[0]},a&4&&Qt(i[2])]):{};if(o!==(o=i[1])){if(t){zt();const u=t;X(u.$$.fragment,1,0,()=>{M(u,1)}),Kt()}o?(t=K(o,c()),Z(t.$$.fragment),A(t.$$.fragment,1),N(t,e.parentNode,e)):t=null}else o&&t.$set(l)},i(i){n||(t&&A(t.$$.fragment,i),n=!0)},o(i){t&&X(t.$$.fragment,i),n=!1},d(i){i&&z(e),t&&M(t,i)}}}function ee(s,t,e){const n=["blok"];let r=Y(t,n),o,{blok:c}=t;return c?o=et(c.component):console.error("Please provide a 'blok' property to the StoryblokComponent"),s.$$set=i=>{t=S(S({},t),Ht(i)),e(2,r=Y(t,n)),"blok"in i&&e(0,c=i.blok)},[c,o,r]}class se extends Zt{constructor(t){super(),Xt(this,t,ee,te,Lt,{blok:0})}}const ne=(s,t)=>{const e=n=>{const r=Ct(n);r["data-blok-c"]&&(s.setAttribute("data-blok-c",r["data-blok-c"]),s.setAttribute("data-blok-uid",r["data-blok-uid"]),s.classList.add("storyblok__outline"))};return e(t),{update(n){e(n)}}};let L=null;const tt=()=>(L||console.log("You can't use getStoryblokApi if you're not loading apiPlugin."),L);let j=null;const re=s=>{const{storyblokApi:t}=Nt(s);L=t,j=s.components||{}},et=s=>{let t=null;return t=typeof j=="function"?j()[s]:j[s],t||console.error(`You didn't load the ${s} component. Please load it in storyblokInit. For example:
4
4
  storyblokInit({
@@ -278,7 +278,7 @@ class xt {
278
278
  return r.headers = { ...e }, r.status = t.status, r.statusText = t.statusText, r;
279
279
  }
280
280
  async _methodHandler(t) {
281
- let e = `${this.baseURL}${this.url}}`, r = null;
281
+ let e = `${this.baseURL}${this.url}`, r = null;
282
282
  if (t === "get") {
283
283
  const a = new K();
284
284
  e = `${this.baseURL}${this.url}?${a.stringify(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/svelte",
3
- "version": "2.4.4",
3
+ "version": "2.4.6",
4
4
  "type": "module",
5
5
  "description": "Storyblok SDK to connect Storyblok with Svelte",
6
6
  "main": "./dist/storyblok-svelte.js",
@@ -27,14 +27,14 @@
27
27
  "prepublishOnly": "npm run build && cp ../README.md ./"
28
28
  },
29
29
  "dependencies": {
30
- "@storyblok/js": "^2.0.10"
30
+ "@storyblok/js": "^2.0.12"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@babel/core": "^7.20.12",
34
34
  "@tsconfig/svelte": "^3.0.0",
35
35
  "babel-jest": "^28.1.3",
36
36
  "eslint-plugin-jest": "^27.2.0",
37
- "jest": "^29.2.1",
37
+ "jest": "^29.4.1",
38
38
  "svelte-preprocess": "^5.0.1",
39
39
  "typescript": "^4.9.4",
40
40
  "vite": "^4.0.0"