@storyblok/js 3.3.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/storyblok-js.js +2 -2
- package/dist/storyblok-js.mjs +342 -334
- package/package.json +7 -5
package/dist/storyblok-js.js
CHANGED
@@ -4,7 +4,7 @@
|
|
4
4
|
* description: SDK to integrate Storyblok into your project using JavaScript.
|
5
5
|
* author: undefined
|
6
6
|
*/
|
7
|
-
(function(
|
7
|
+
(function(v,A){typeof exports=="object"&&typeof module<"u"?A(exports):typeof define=="function"&&define.amd?define(["exports"],A):(v=typeof globalThis<"u"?globalThis:v||self,A(v.storyblok={}))})(this,function(v){"use strict";let A=!1;const q=[],F=i=>new Promise((e,t)=>{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}A?r():q.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{q.forEach(o=>o()),A=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var Z=Object.defineProperty,ee=(i,e,t)=>e in i?Z(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,m=(i,e,t)=>ee(i,typeof e!="symbol"?e+"":e,t);class te extends Error{constructor(e){super(e),this.name="AbortError"}}function se(i,e,t){if(!Number.isFinite(e))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],o=0,n=!1;const c=async()=>{o++;const h=s.shift();if(h)try{const p=await i(...h.args);h.resolve(p)}catch(p){h.reject(p)}const u=setTimeout(()=>{o--,s.length>0&&c(),r=r.filter(p=>p!==u)},t);r.includes(u)||r.push(u)},a=(...h)=>n?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((u,p)=>{s.push({resolve:u,reject:p,args:h}),o<e&&c()});return a.abort=()=>{n=!0,r.forEach(clearTimeout),r=[],s.forEach(h=>h.reject(()=>new te("Throttle function aborted"))),s.length=0},a}class x{constructor(){m(this,"isCDNUrl",(e="")=>e.includes("/cdn/")),m(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),m(this,"delay",e=>new Promise(t=>setTimeout(t,e))),m(this,"arrayFrom",(e=0,t)=>Array.from({length:e},t)),m(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(o,n)=>n*r+e)}),m(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),m(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),m(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,r=new RegExp(s.source);return e&&r.test(e)?e.replace(s,o=>t[o]):e})}stringify(e,t,s){const r=[];for(const o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;const n=e[o];if(n==null)continue;const c=s?"":encodeURIComponent(o);let a;typeof n=="object"?a=this.stringify(n,t?t+encodeURIComponent(`[${c}]`):c,Array.isArray(n)):a=`${t?t+encodeURIComponent(`[${c}]`):c}=${encodeURIComponent(n)}`,r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn",o="api-ap.storyblok.com",n="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return o;case"ca":return n;default:return t}}}const re=function(i,e){const t={};for(const s in i){const r=i[s];e.includes(s)&&r!==null&&(t[s]=r)}return t},ie=i=>i==="email",oe=()=>({singleTag:"hr"}),ne=()=>({tag:"blockquote"}),ae=()=>({tag:"ul"}),le=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),ce=()=>({singleTag:"br"}),he=i=>({tag:`h${i.attrs.level}`}),ue=i=>({singleTag:[{tag:"img",attrs:re(i.attrs,["src","alt","title"])}]}),de=()=>({tag:"li"}),pe=()=>({tag:"ol"}),ge=()=>({tag:"p"}),fe=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),me=()=>({tag:"b"}),ye=()=>({tag:"s"}),be=()=>({tag:"u"}),ke=()=>({tag:"strong"}),ve=()=>({tag:"code"}),$e=()=>({tag:"i"}),Te=i=>{if(!i.attrs)return{tag:""};const e=new x().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),ie(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const r in t.custom)t[r]=t.custom[r];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},we=i=>({tag:[{tag:"span",attrs:i.attrs}]}),Re=()=>({tag:"sub"}),Ee=()=>({tag:"sup"}),_e=i=>({tag:[{tag:"span",attrs:i.attrs}]}),Se=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},je=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},G={nodes:{horizontal_rule:oe,blockquote:ne,bullet_list:ae,code_block:le,hard_break:ce,heading:he,image:ue,list_item:de,ordered_list:pe,paragraph:ge,emoji:fe},marks:{bold:me,strike:ye,underline:be,strong:ke,code:ve,italic:$e,link:Te,styled:we,subscript:Re,superscript:Ee,anchor:_e,highlight:Se,textStyle:je}},Ie=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=new RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};let J=!1,O=class{constructor(e){m(this,"marks"),m(this,"nodes"),e||(e=G),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,t={optimizeImages:!1},s=!0){if(!J&&s&&(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),J=!0),e&&e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(o=>{r+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field.
|
8
8
|
The "content" field must be an array of nodes as the type ISbRichtext.
|
9
9
|
ISbRichtext:
|
10
10
|
content?: ISbRichtext[]
|
@@ -27,4 +27,4 @@
|
|
27
27
|
}
|
28
28
|
],
|
29
29
|
type: 'doc'
|
30
|
-
}`),""}optimizeImages(e,t){let s=0,r=0,n="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(o+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(o+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-F]{6}/gi)||t.filters.fill==="transparent")&&(o+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(o+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(o+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(o+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(o+=`:rotate(${t.filters.rotate})`),o.length>0&&(o=`/filters${o}`))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var h,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(p&&p.length>0){const y={srcset:(h=t.srcset)==null?void 0:h.map(w=>{if(typeof w=="number")return`//${p}/m/${w}x0${o} ${w}w`;if(typeof w=="object"&&w.length===2){let j=0,L=0;return typeof w[0]=="number"&&(j=w[0]),typeof w[1]=="number"&&(L=w[1]),`//${p}/m/${j}x${L}${o} ${j}w`}return""}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(w=>w).join(", ")};let k="";return y.srcset&&(k+=`srcset="${y.srcset}" `),y.sizes&&(k+=`sizes="${y.sizes}" `),a.replace(/<img/g,`<img ${k.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(Se(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const o=s.attrs[n];o!==null&&(r+=` ${n}="${o}"`)}}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}class je{constructor(e){g(this,"baseURL"),g(this,"timeout"),g(this,"headers"),g(this,"responseInterceptor"),g(this,"fetch"),g(this,"ejectInterceptor"),g(this,"url"),g(this,"parameters"),g(this,"fetchOptions"),this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t??{},this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new x;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:o}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o,...this.fetchOptions});this.timeout&&clearTimeout(l);const h=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}catch(a){return{message:a}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(n)})}}const V="SB-Agent",H={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let C={};const S={};class Ie{constructor(e,t){g(this,"client"),g(this,"maxRetries"),g(this,"retriesDelay"),g(this,"throttle"),g(this,"accessToken"),g(this,"cache"),g(this,"helpers"),g(this,"resolveCounter"),g(this,"relations"),g(this,"links"),g(this,"richTextResolver"),g(this,"resolveNestedRelations"),g(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new x().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${o(e.region)}/v1`:s=`${l}://${o(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([o,l])=>{r.set(o,l)}),r.has(V)||(r.set(V,H.defaultAgentName),r.set(H.defaultAgentVersion,H.packageVersion));let n=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new A(e.richTextSchema):this.richTextResolver=new A,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=ee(this.throttledRequest.bind(this),n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new x,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new je({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=S[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r,n){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o,void 0,n)}get(e,t,s){t||(t={});const r=`/${e}`,n=this.factoryParamOptions(r,t);return this.cacheResponse(r,n,void 0,s)}async getAll(e,t,s,r){const n=(t==null?void 0:t.per_page)||25,o=`/${e}`.replace(/\/$/,""),l=s??o.substring(o.lastIndexOf("/")+1),a=1,h=await this.makeRequest(o,t,n,a,r),u=h.total?Math.ceil(h.total/n):1,p=await this.helpers.asyncMap(this.helpers.range(a,u),y=>this.makeRequest(o,t,n,y+1,r));return this.helpers.flatMap([h,...p],y=>Object.values(y.data[l]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){t||(t={});const r=`/${e}`;return Promise.resolve(this.throttle("delete",r,t,s))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,s){const r=e[t];typeof r=="string"?e[t]=this.getStoryReference(s,r):Array.isArray(r)&&(e[t]=r.map(n=>this.getStoryReference(s,n)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(o=>o.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,r);return}const n=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(n):s===n)&&this._resolveField(e,t,r)}iterateTree(e,t,s){const r=(n,o="")=>{if(!(!n||n._stopResolving)){if(Array.isArray(n))n.forEach((l,a)=>r(l,`${o}[${a}]`));else if(typeof n=="object")for(const l in n){const a=o?`${o}.${l}`:l;(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,l,t,s),this._insertLinks(n,l,s)),r(n[l],a)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const n=e.link_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const h=Math.min(n,a+l);o.push(e.link_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:o[a].join(",")})).data.stories.forEach(h=>{r.push(h)})}else r=e.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const n=e.rel_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const h=Math.min(n,a+l);o.push(e.rel_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:o[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{r.push(h)})}else r=e.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var r,n;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((r=e.links)!=null&&r.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const n=this.helpers.stringify({url:e,params:t}),o=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const l=await o.get(n);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var h;try{const u=await this.throttle("get",e,t,r);if(u.status!==200)return a(u);let p={data:u.data,headers:u.headers};if((h=u.headers)!=null&&h["per-page"]&&(p=Object.assign({},p,{perPage:u.headers["per-page"]?Number.parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?Number.parseInt(u.headers.total):0})),p.data.story||p.data.stories){const k=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(p.data,t,`${k}`)}t.version==="published"&&e!=="/cdn/spaces/me"&&await o.set(n,p);const y=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&p.data.cv&&(y&&S[t.token]&&S[t.token]!==p.data.cv&&await this.flushCache(),S[t.token]=p.data.cv),l(p)}catch(u){if(u.response&&u.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(l).catch(a);a(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return S}cacheVersion(){return S[this.accessToken]}setCacheVersion(e){this.accessToken&&(S[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(S[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(C[e])},getAll(){return Promise.resolve(C)},set(e,t){return C[e]=t,Promise.resolve(void 0)},flush(){return C={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this.clearCacheVersion(),this}}const Ae=(i={})=>{const{apiOptions:e}=i;if(!e||!e.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 Ie(e)}},Oe=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};try{const e=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":`${e.id}-${e.uid}`}:{}}catch{return{}}};function Le(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},n=[];function o(a,h,u,p,y){typeof a!="number"||a<=h||a>=u?console.warn(`[StoryblokRichText] - ${p.charAt(0).toUpperCase()+p.slice(1)} value must be a number between ${h} and ${u} (inclusive)`):y.push(`${p}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[StoryblokRichText] - Width value must be a number greater than 0"),e.height&&typeof e.height=="number"&&e.height>0?(r.height=e.height,s=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(r.loading=e.loading),e.class&&(r.class=e.class),e.filters){const{filters:a}=e||{},{blur:h,brightness:u,fill:p,format:y,grayscale:k,quality:w,rotate:j}=a||{};h&&o(h,0,100,"blur",n),w&&o(w,0,100,"quality",n),u&&o(u,0,100,"brightness",n),p&&n.push(`fill(${p})`),k&&n.push("grayscale()"),j&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${j})`),y&&["webp","png","jpeg"].includes(y)&&n.push(`format(${y})`)}e.srcset&&(r.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${i}/m/${a}x0/${n.length>0?`filters:${n.join(":")}`:""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[h,u]=a;return`${i}/m/${h}x${u}/${n.length>0?`filters:${n.join(":")}`:""} ${h}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let l=`${i}/m/`;return t>0&&s>0&&(l=`${l}${t}x${s}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:r}}var v=(i=>(i.DOCUMENT="doc",i.HEADING="heading",i.PARAGRAPH="paragraph",i.QUOTE="blockquote",i.OL_LIST="ordered_list",i.UL_LIST="bullet_list",i.LIST_ITEM="list_item",i.CODE_BLOCK="code_block",i.HR="horizontal_rule",i.BR="hard_break",i.IMAGE="image",i.EMOJI="emoji",i.COMPONENT="blok",i.TABLE="table",i.TABLE_ROW="tableRow",i.TABLE_CELL="tableCell",i.TABLE_HEADER="tableHeader",i))(v||{}),_=(i=>(i.BOLD="bold",i.STRONG="strong",i.STRIKE="strike",i.UNDERLINE="underline",i.ITALIC="italic",i.CODE="code",i.LINK="link",i.ANCHOR="anchor",i.STYLED="styled",i.SUPERSCRIPT="superscript",i.SUBSCRIPT="subscript",i.TEXT_STYLE="textStyle",i.HIGHLIGHT="highlight",i))(_||{}),B=(i=>(i.TEXT="text",i))(B||{}),O=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(O||{});const xe=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Ce=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),Pe=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function Ne(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const P=i=>Object.fromEntries(Object.entries(i).filter(([e,t])=>t!==void 0));function J(i,e={},t){const s=Ce(e),r=s?`${i} ${s}`:i,n=Array.isArray(t)?t.join(""):t||"";if(i){if(xe.includes(i))return`<${r}>`}else return n;return`<${r}>${n}</${i}>`}function He(i={}){let e=0;const{renderFn:t=J,textFn:s=Ne,resolvers:r={},optimizeImages:n=!1,keyedResolvers:o=!1}=i,l=t!==J,a=c=>d=>{const f=d.attrs||{};return o&&(f.key=`${c}-${e}`),t(c,f,d.children||null)},h=c=>{const{src:d,alt:f,title:b,srcset:E,sizes:T}=c.attrs||{};let m=d,R={};if(n){const{src:Ke,attrs:Ye}=Le(d,n);m=Ke,R=Ye}o&&(R={...R,key:`img-${e}`});const Je={src:m,alt:f,title:b,srcset:E,sizes:T,...R};return t("img",P(Je))},u=c=>{const{level:d,...f}=c.attrs||{},b={...f};return o&&(b.key=`h${d}-${e}`),t(`h${d}`,b,c.children)},p=c=>{var d,f,b,E;const T=t("img",{src:(d=c.attrs)==null?void 0:d.fallbackImage,alt:(f=c.attrs)==null?void 0:f.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"}),m={"data-type":"emoji","data-name":(b=c.attrs)==null?void 0:b.name,"data-emoji":(E=c.attrs)==null?void 0:E.emoji};return o&&(m.key=`emoji-${e}`),t("span",m,T)},y=c=>t("pre",{...c.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},c.children||"")),k=(c,d=!1)=>({text:f,attrs:b})=>{const{class:E,id:T,...m}=b||{},R=d?{class:E,id:T,style:Pe(m)||void 0}:b||{};return o&&(R.key=`${c}-${e}`),t(c,P(R),f)},w=c=>z(c),j=c=>{const{marks:d,...f}=c;return"text"in c?d?d.reduce((b,E)=>w({...E,text:b}),w({...f,children:f.children})):s(f.text):""},L=c=>{const{linktype:d,href:f,anchor:b,...E}=c.attrs||{};let T="";switch(d){case O.ASSET:case O.URL:T=f;break;case O.EMAIL:T=`mailto:${f}`;break;case O.STORY:T=f,b&&(T=`${T}#${b}`);break;default:T=f;break}const m={...E};return T&&(m.href=T),o&&(m.key=`a-${e}`),t("a",m,c.text)},ze=c=>{var d,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),t("span",{blok:(d=c==null?void 0:c.attrs)==null?void 0:d.body[0],id:(f=c.attrs)==null?void 0:f.id,key:`component-${e}`,style:"display: none"})},De=c=>{const d={};return o&&(d.key=`table-${e}`),t("table",d,c.children)},qe=c=>{const d={};return o&&(d.key=`tr-${e}`),t("tr",d,c.children)},Fe=c=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:E,...T}=c.attrs||{},m={...T};d>1&&(m.colspan=d),f>1&&(m.rowspan=f);const R=[];return b&&R.push(`width: ${b}px;`),E&&R.push(`background-color: ${E};`),R.length>0&&(m.style=R.join(" ")),o&&(m.key=`td-${e}`),t("td",P(m),c.children)},Ge=c=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:E,...T}=c.attrs||{},m={...T};d>1&&(m.colspan=d),f>1&&(m.rowspan=f);const R=[];return b&&R.push(`width: ${b}px;`),E&&R.push(`background-color: ${E};`),R.length>0&&(m.style=R.join(" ")),o&&(m.key=`th-${e}`),t("th",P(m),c.children)},Ve=new Map([[v.DOCUMENT,a("")],[v.HEADING,u],[v.PARAGRAPH,a("p")],[v.UL_LIST,a("ul")],[v.OL_LIST,a("ol")],[v.LIST_ITEM,a("li")],[v.IMAGE,h],[v.EMOJI,p],[v.CODE_BLOCK,y],[v.HR,a("hr")],[v.BR,a("br")],[v.QUOTE,a("blockquote")],[v.COMPONENT,ze],[B.TEXT,j],[_.LINK,L],[_.ANCHOR,L],[_.STYLED,k("span",!0)],[_.BOLD,k("strong")],[_.TEXT_STYLE,k("span",!0)],[_.ITALIC,k("em")],[_.UNDERLINE,k("u")],[_.STRIKE,k("s")],[_.CODE,k("code")],[_.SUPERSCRIPT,k("sup")],[_.SUBSCRIPT,k("sub")],[_.HIGHLIGHT,k("mark")],[v.TABLE,De],[v.TABLE_ROW,qe],[v.TABLE_CELL,Fe],[v.TABLE_HEADER,Ge],...Object.entries(r).map(([c,d])=>[c,d])]);function N(c){e+=1;const d=Ve.get(c.type);if(!d)return console.error("<Storyblok>",`No resolver found for node type ${c.type}`),"";if(c.type==="text")return d(c);const f=c.content?c.content.map(z):void 0;return d({...c,children:f})}function z(c){return c.type==="doc"?l?c.content.map(N):c.content.map(N).join(""):Array.isArray(c)?c.map(N):N(c)}return{render:z}}let M,U="https://app.storyblok.com/f/storyblok-v2-latest.js";const K=(i,e,t={})=>{var l;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok"),o=n!==null&&+n===i;if(!(!r||!o)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],h=>{var u;h&&(h.action==="input"&&((u=h.story)==null?void 0:u.id)===i?e(h.story):(h.action==="change"||h.action==="published")&&h.storyId===i&&window.location.reload())})})}},Y=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},Be=(i={})=>{var p,y;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:n={},bridgeUrl:o}=i;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach(k=>{a={...a,...k(l)}}),o&&(U=o);const u=!(typeof window>"u")&&((y=(p=window.location)==null?void 0:p.search)==null?void 0:y.includes("_storyblok_tk"));return e!==!1&&u&&q(U),M=new A(n.schema),n.resolver&&Y(M,n.resolver),a},W=i=>{var e;return!i||!((e=i==null?void 0:i.content)!=null&&e.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule"))},Me=(i,e,t)=>{let s=t||M;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return W(i)?"":(e&&(s=new A(e.schema),e.resolver&&Y(s,e.resolver)),s.render(i,{},!1))},Ue=()=>q(U);$.BlockTypes=v,$.MarkTypes=_,$.RichTextResolver=A,$.RichTextSchema=F,$.TextTypes=B,$.apiPlugin=Ae,$.isRichTextEmpty=W,$.loadStoryblokBridge=Ue,$.registerStoryblokBridge=K,$.renderRichText=Me,$.richTextResolver=He,$.storyblokEditable=Oe,$.storyblokInit=Be,$.useStoryblokBridge=K,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
|
30
|
+
}`),""}optimizeImages(e,t){let s=0,r=0,o="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(o+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(o+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(o+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(o+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(n+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(n+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-F]{6}/gi)||t.filters.fill==="transparent")&&(n+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(n+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(n+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(n+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(n+=`:rotate(${t.filters.rotate})`),n.length>0&&(n=`/filters${n}`))),o.length>0&&(e=e.replace(/<img/g,`<img ${o.trim()}`));const c=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var h,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(p&&p.length>0){const b={srcset:(h=t.srcset)==null?void 0:h.map(y=>{if(typeof y=="number")return`//${p}/m/${y}x0${n} ${y}w`;if(typeof y=="object"&&y.length===2){let j=0,N=0;return typeof y[0]=="number"&&(j=y[0]),typeof y[1]=="number"&&(N=y[1]),`//${p}/m/${j}x${N}${n} ${j}w`}return""}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(y=>y).join(", ")};let S="";return b.srcset&&(S+=`srcset="${b.srcset}" `),b.sizes&&(S+=`sizes="${b.sizes}" `),a.replace(/<img/g,`<img ${S.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&t.push(this.renderOpeningTag(o.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(Ie(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&t.push(this.renderClosingTag(o.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs){for(const o in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,o)){const n=s.attrs[o];n!==null&&(r+=` ${o}="${n}"`)}}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}};class Ae{constructor(e){m(this,"baseURL"),m(this,"timeout"),m(this,"headers"),m(this,"responseInterceptor"),m(this,"fetch"),m(this,"ejectInterceptor"),m(this,"url"),m(this,"parameters"),m(this,"fetchOptions"),this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t??{},this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new x;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),o=new AbortController,{signal:n}=o;let c;this.timeout&&(c=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(c);const h=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}catch(a){return{message:a}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const o={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(o)})}}const V="SB-Agent",H={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let C={};const I={};class Oe{constructor(e,t){m(this,"client"),m(this,"maxRetries"),m(this,"retriesDelay"),m(this,"throttle"),m(this,"accessToken"),m(this,"cache"),m(this,"helpers"),m(this,"resolveCounter"),m(this,"relations"),m(this,"links"),m(this,"richTextResolver"),m(this,"resolveNestedRelations"),m(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const n=new x().getRegionURL,c=e.https===!1?"http":"https";e.oauthToken?s=`${c}://${n(e.region)}/v1`:s=`${c}://${n(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([n,c])=>{r.set(n,c)}),r.has(V)||(r.set(V,H.defaultAgentName),r.set(H.defaultAgentVersion,H.packageVersion));let o=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),o=3),e.rateLimit&&(o=e.rateLimit),e.richTextSchema?this.richTextResolver=new O(e.richTextSchema):this.richTextResolver=new O,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=se(this.throttledRequest.bind(this),o,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new x,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new Ae({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=I[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n,void 0,o)}get(e,t,s){t||(t={});const r=`/${e}`,o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o,void 0,s)}async getAll(e,t,s,r){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),c=s??n.substring(n.lastIndexOf("/")+1),a=1,h=await this.makeRequest(n,t,o,a,r),u=h.total?Math.ceil(h.total/o):1,p=await this.helpers.asyncMap(this.helpers.range(a,u),b=>this.makeRequest(n,t,o,b+1,r));return this.helpers.flatMap([h,...p],b=>Object.values(b.data[c]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){t||(t={});const r=`/${e}`;return Promise.resolve(this.throttle("delete",r,t,s))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,s){const r=e[t];typeof r=="string"?e[t]=this.getStoryReference(s,r):Array.isArray(r)&&(e[t]=r.map(o=>this.getStoryReference(s,o)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(n=>n.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,r);return}const o=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(o):s===o)&&this._resolveField(e,t,r)}iterateTree(e,t,s){const r=(o,n="")=>{if(!(!o||o._stopResolving)){if(Array.isArray(o))o.forEach((c,a)=>r(c,`${n}[${a}]`));else if(typeof o=="object")for(const c in o){const a=n?`${n}.${c}`:c;(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,c,t,s),this._insertLinks(o,c,s)),r(o[c],a)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const o=e.link_uuids.length,n=[],c=50;for(let a=0;a<o;a+=c){const h=Math.min(o,a+c);n.push(e.link_uuids.slice(a,h))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[a].join(",")})).data.stories.forEach(h=>{r.push(h)})}else r=e.links;r.forEach(o=>{this.links[s][o.uuid]={...o,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length,n=[],c=50;for(let a=0;a<o;a+=c){const h=Math.min(o,a+c);n.push(e.rel_uuids.slice(a,h))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{r.push(h)})}else r=e.rels;r&&r.length>0&&r.forEach(o=>{this.relations[s][o.uuid]={...o,_stopResolving:!0}})}async resolveStories(e,t,s){var r,o;let n=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(n=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((r=e.links)!=null&&r.length||(o=e.link_uuids)!=null&&o.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],n,s);e.story?this.iterateTree(e.story,n,s):e.stories.forEach(c=>{this.iterateTree(c,n,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const o=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const c=await n.get(o);if(c)return Promise.resolve(c)}return new Promise(async(c,a)=>{var h;try{const u=await this.throttle("get",e,t,r);if(u.status!==200)return a(u);let p={data:u.data,headers:u.headers};if((h=u.headers)!=null&&h["per-page"]&&(p=Object.assign({},p,{perPage:u.headers["per-page"]?Number.parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?Number.parseInt(u.headers.total):0})),p.data.story||p.data.stories){const S=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(p.data,t,`${S}`)}t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(o,p);const b=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&p.data.cv&&(b&&I[t.token]&&I[t.token]!==p.data.cv&&await this.flushCache(),I[t.token]=p.data.cv),c(p)}catch(u){if(u.response&&u.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(c).catch(a);a(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return I}cacheVersion(){return I[this.accessToken]}setCacheVersion(e){this.accessToken&&(I[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(I[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(C[e])},getAll(){return Promise.resolve(C)},set(e,t){return C[e]=t,Promise.resolve(void 0)},flush(){return C={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this.clearCacheVersion(),this}}const Le=(i={})=>{const{apiOptions:e}=i;if(!e||!e.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 Oe(e)}},xe=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};try{const e=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":`${e.id}-${e.uid}`}:{}}catch{return{}}};function Ce(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},o=[];function n(a,h,u,p,b){typeof a!="number"||a<=h||a>=u?console.warn(`[StoryblokRichText] - ${p.charAt(0).toUpperCase()+p.slice(1)} value must be a number between ${h} and ${u} (inclusive)`):b.push(`${p}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[StoryblokRichText] - Width value must be a number greater than 0"),e.height&&typeof e.height=="number"&&e.height>0?(r.height=e.height,s=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(r.loading=e.loading),e.class&&(r.class=e.class),e.filters){const{filters:a}=e||{},{blur:h,brightness:u,fill:p,format:b,grayscale:S,quality:y,rotate:j}=a||{};h&&n(h,0,100,"blur",o),y&&n(y,0,100,"quality",o),u&&n(u,0,100,"brightness",o),p&&o.push(`fill(${p})`),S&&o.push("grayscale()"),j&&[0,90,180,270].includes(e.filters.rotate||0)&&o.push(`rotate(${j})`),b&&["webp","png","jpeg"].includes(b)&&o.push(`format(${b})`)}e.srcset&&(r.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${i}/m/${a}x0/${o.length>0?`filters:${o.join(":")}`:""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[h,u]=a;return`${i}/m/${h}x${u}/${o.length>0?`filters:${o.join(":")}`:""} ${h}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let c=`${i}/m/`;return t>0&&s>0&&(c=`${c}${t}x${s}/`),o.length>0&&(c=`${c}filters:${o.join(":")}`),{src:c,attrs:r}}var $=(i=>(i.DOCUMENT="doc",i.HEADING="heading",i.PARAGRAPH="paragraph",i.QUOTE="blockquote",i.OL_LIST="ordered_list",i.UL_LIST="bullet_list",i.LIST_ITEM="list_item",i.CODE_BLOCK="code_block",i.HR="horizontal_rule",i.BR="hard_break",i.IMAGE="image",i.EMOJI="emoji",i.COMPONENT="blok",i.TABLE="table",i.TABLE_ROW="tableRow",i.TABLE_CELL="tableCell",i.TABLE_HEADER="tableHeader",i))($||{}),E=(i=>(i.BOLD="bold",i.STRONG="strong",i.STRIKE="strike",i.UNDERLINE="underline",i.ITALIC="italic",i.CODE="code",i.LINK="link",i.ANCHOR="anchor",i.STYLED="styled",i.SUPERSCRIPT="superscript",i.SUBSCRIPT="subscript",i.TEXT_STYLE="textStyle",i.HIGHLIGHT="highlight",i))(E||{}),B=(i=>(i.TEXT="text",i))(B||{}),L=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(L||{});const Pe=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Ne=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),Me=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function He(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const P=i=>Object.fromEntries(Object.entries(i).filter(([e,t])=>t!==void 0));function K(i,e={},t){const s=Ne(e),r=s?`${i} ${s}`:i,o=Array.isArray(t)?t.join(""):t||"";if(i){if(Pe.includes(i))return`<${r}>`}else return o;return`<${r}>${o}</${i}>`}function Be(i={}){const e=new Map,{renderFn:t=K,textFn:s=He,resolvers:r={},optimizeImages:o=!1,keyedResolvers:n=!1}=i,c=t!==K,a=()=>({render:(l,d={},g)=>{if(n&&l){const f=e.get(l)||0;e.set(l,f+1),d.key=`${l}-${f}`}return t(l,d,g)}}),h=l=>(d,g)=>{const f=d.attrs||{};return g.render(l,f,d.children||null)},u=(l,d)=>{const{src:g,alt:f,title:k,srcset:R,sizes:T}=l.attrs||{};let w=g,_={};if(o){const{src:We,attrs:Xe}=Ce(g,o);w=We,_=Xe}const Ye={src:w,alt:f,title:k,srcset:R,sizes:T,..._};return d.render("img",P(Ye))},p=(l,d)=>{const{level:g,...f}=l.attrs||{};return d.render(`h${g}`,f,l.children)},b=(l,d)=>{var g,f,k,R;const T=d.render("img",{src:(g=l.attrs)==null?void 0:g.fallbackImage,alt:(f=l.attrs)==null?void 0:f.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return d.render("span",{"data-type":"emoji","data-name":(k=l.attrs)==null?void 0:k.name,"data-emoji":(R=l.attrs)==null?void 0:R.emoji},T)},S=(l,d)=>d.render("pre",l.attrs||{},d.render("code",{},l.children||"")),y=(l,d=!1)=>({text:g,attrs:f},k)=>{const{class:R,id:T,...w}=f||{},_=d?{class:R,id:T,style:Me(w)||void 0}:f||{};return k.render(l,P(_),g)},j=l=>D(l),N=l=>{const{marks:d,...g}=l;if("text"in l){if(d)return d.reduce((k,R)=>j({...R,text:k}),j({...g,children:g.children}));const f=l.attrs||{};if(n){const k=e.get("txt")||0;e.set("txt",k+1),f.key=`txt-${k}`}return s(g.text,f)}return""},Q=(l,d)=>{const{linktype:g,href:f,anchor:k,...R}=l.attrs||{};let T="";switch(g){case L.ASSET:case L.URL:T=f;break;case L.EMAIL:T=`mailto:${f}`;break;case L.STORY:T=f,k&&(T=`${T}#${k}`);break;default:T=f;break}const w={...R};return T&&(w.href=T),d.render("a",w,l.text)},qe=(l,d)=>{var g,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),d.render("span",{blok:(g=l==null?void 0:l.attrs)==null?void 0:g.body[0],id:(f=l.attrs)==null?void 0:f.id,style:"display: none"})},Fe=(l,d)=>{const g={},f=d.render("tbody",{},l.children);return d.render("table",g,f)},Ge=(l,d)=>{const g={};return d.render("tr",g,l.children)},Je=(l,d)=>{const{colspan:g,rowspan:f,colwidth:k,backgroundColor:R,...T}=l.attrs||{},w={...T};g>1&&(w.colspan=g),f>1&&(w.rowspan=f);const _=[];return k&&_.push(`width: ${k}px;`),R&&_.push(`background-color: ${R};`),_.length>0&&(w.style=_.join(" ")),d.render("td",P(w),l.children)},Ve=(l,d)=>{const{colspan:g,rowspan:f,colwidth:k,backgroundColor:R,...T}=l.attrs||{},w={...T};g>1&&(w.colspan=g),f>1&&(w.rowspan=f);const _=[];return k&&_.push(`width: ${k}px;`),R&&_.push(`background-color: ${R};`),_.length>0&&(w.style=_.join(" ")),d.render("th",P(w),l.children)},Ke=new Map([[$.DOCUMENT,h("")],[$.HEADING,p],[$.PARAGRAPH,h("p")],[$.UL_LIST,h("ul")],[$.OL_LIST,h("ol")],[$.LIST_ITEM,h("li")],[$.IMAGE,u],[$.EMOJI,b],[$.CODE_BLOCK,S],[$.HR,h("hr")],[$.BR,h("br")],[$.QUOTE,h("blockquote")],[$.COMPONENT,qe],[B.TEXT,N],[E.LINK,Q],[E.ANCHOR,Q],[E.STYLED,y("span",!0)],[E.BOLD,y("strong")],[E.TEXT_STYLE,y("span",!0)],[E.ITALIC,y("em")],[E.UNDERLINE,y("u")],[E.STRIKE,y("s")],[E.CODE,y("code")],[E.SUPERSCRIPT,y("sup")],[E.SUBSCRIPT,y("sub")],[E.HIGHLIGHT,y("mark")],[$.TABLE,Fe],[$.TABLE_ROW,Ge],[$.TABLE_CELL,Je],[$.TABLE_HEADER,Ve],...Object.entries(r).map(([l,d])=>[l,d])]);function M(l){const d=Ke.get(l.type);if(!d)return console.error("<Storyblok>",`No resolver found for node type ${l.type}`),"";const g=a();if(l.type==="text")return d(l,g);const f=l.content?l.content.map(D):void 0;return d({...l,children:f},g)}function D(l){return l.type==="doc"?c?l.content.map(M):l.content.map(M).join(""):Array.isArray(l)?l.map(M):M(l)}return{render:D}}let U,z="https://app.storyblok.com/f/storyblok-v2-latest.js";const Y=(i,e,t={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok"),n=o!==null&&+o===i;if(!(!r||!n)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],h=>{var u;h&&(h.action==="input"&&((u=h.story)==null?void 0:u.id)===i?e(h.story):(h.action==="change"||h.action==="published")&&h.storyId===i&&window.location.reload())})})}},W=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},Ue=(i={})=>{var p,b;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:o={},bridgeUrl:n}=i;r.accessToken=r.accessToken||t;const c={bridge:e,apiOptions:r};let a={};s.forEach(S=>{a={...a,...S(c)}}),n&&(z=n);const u=!(typeof window>"u")&&((b=(p=window.location)==null?void 0:p.search)==null?void 0:b.includes("_storyblok_tk"));return e!==!1&&u&&F(z),U=new O(o.schema),o.resolver&&W(U,o.resolver),a},X=i=>{var e;return!i||!((e=i==null?void 0:i.content)!=null&&e.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule"))},ze=(i,e,t)=>{let s=t||U;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return X(i)?"":(e&&(s=new O(e.schema),e.resolver&&W(s,e.resolver)),s.render(i,{},!1))},De=()=>F(z);v.BlockTypes=$,v.MarkTypes=E,v.RichTextResolver=O,v.RichTextSchema=G,v.TextTypes=B,v.apiPlugin=Le,v.isRichTextEmpty=X,v.loadStoryblokBridge=De,v.registerStoryblokBridge=Y,v.renderRichText=ze,v.richTextResolver=Be,v.storyblokEditable=xe,v.storyblokInit=Ue,v.useStoryblokBridge=Y,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
|