@storyblok/js 4.3.1 → 4.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/index.d.ts +1 -0
- package/dist/storyblok-js.js +1 -1
- package/dist/storyblok-js.mjs +26 -19
- package/dist/types/index.d.ts +1 -2
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -20,3 +20,4 @@ export { default as apiPlugin } from './api';
|
|
|
20
20
|
export { default as storyblokEditable } from './editable';
|
|
21
21
|
export * from './types';
|
|
22
22
|
export { BlockTypes, MarkTypes, richTextResolver, type StoryblokRichTextDocumentNode, type StoryblokRichTextImageOptimizationOptions, type StoryblokRichTextNode, type StoryblokRichTextNodeResolver, type StoryblokRichTextNodeTypes, type StoryblokRichTextOptions, type StoryblokRichTextResolvers, TextTypes, } from '@storyblok/richtext';
|
|
23
|
+
export { default as StoryblokClient } from 'storyblok-js-client';
|
package/dist/storyblok-js.js
CHANGED
|
@@ -4,4 +4,4 @@
|
|
|
4
4
|
* description: SDK to integrate Storyblok into your project using JavaScript.
|
|
5
5
|
* author: undefined
|
|
6
6
|
*/
|
|
7
|
-
(function(R,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(R=typeof globalThis<"u"?globalThis:R||self,g(R.storyblok={}))})(this,function(R){"use strict";var Pe=Object.defineProperty;var Ie=(R,g,w)=>g in R?Pe(R,g,{enumerable:!0,configurable:!0,writable:!0,value:w}):R[g]=w;var v=(R,g,w)=>Ie(R,typeof g!="symbol"?g+"":g,w);let g=function(e){return e.DOCUMENT="doc",e.HEADING="heading",e.PARAGRAPH="paragraph",e.QUOTE="blockquote",e.OL_LIST="ordered_list",e.UL_LIST="bullet_list",e.LIST_ITEM="list_item",e.CODE_BLOCK="code_block",e.HR="horizontal_rule",e.BR="hard_break",e.IMAGE="image",e.EMOJI="emoji",e.COMPONENT="blok",e.TABLE="table",e.TABLE_ROW="tableRow",e.TABLE_CELL="tableCell",e.TABLE_HEADER="tableHeader",e}({}),w=function(e){return e.BOLD="bold",e.STRONG="strong",e.STRIKE="strike",e.UNDERLINE="underline",e.ITALIC="italic",e.CODE="code",e.LINK="link",e.ANCHOR="anchor",e.STYLED="styled",e.SUPERSCRIPT="superscript",e.SUBSCRIPT="subscript",e.TEXT_STYLE="textStyle",e.HIGHLIGHT="highlight",e}({}),B=function(e){return e.TEXT="text",e}({}),P=function(e){return e.URL="url",e.STORY="story",e.ASSET="asset",e.EMAIL="email",e}({});const Q=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Z=(e={})=>Object.keys(e).map(t=>`${t}="${e[t]}"`).join(" "),ee=(e={})=>Object.keys(e).map(t=>`${t}: ${e[t]}`).join("; ");function te(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const L=e=>Object.fromEntries(Object.entries(e).filter(([t,s])=>s!==void 0));function re(e,t){if(!t)return{src:e,attrs:{}};let s=0,r=0;const i={},n=[];function c(u,a,y,m,A){typeof u!="number"||u<=a||u>=y?console.warn(`[StoryblokRichText] - ${m.charAt(0).toUpperCase()+m.slice(1)} value must be a number between ${a} and ${y} (inclusive)`):A.push(`${m}(${u})`)}if(typeof t=="object"){if(t.width!==void 0&&(typeof t.width=="number"&&t.width>=0?(i.width=t.width,s=t.width):console.warn("[StoryblokRichText] - Width value must be a number greater than or equal to 0")),t.height!==void 0&&(typeof t.height=="number"&&t.height>=0?(i.height=t.height,r=t.height):console.warn("[StoryblokRichText] - Height value must be a number greater than or equal to 0")),t.height===0&&t.width===0&&(delete i.width,delete i.height,console.warn("[StoryblokRichText] - Width and height values cannot both be 0")),t.loading&&["lazy","eager"].includes(t.loading)&&(i.loading=t.loading),t.class&&(i.class=t.class),t.filters){const{filters:u}=t||{},{blur:a,brightness:y,fill:m,format:A,grayscale:H,quality:S,rotate:O}=u||{};a&&c(a,0,100,"blur",n),S&&c(S,0,100,"quality",n),y&&c(y,0,100,"brightness",n),m&&n.push(`fill(${m})`),H&&n.push("grayscale()"),O&&[0,90,180,270].includes(t.filters.rotate||0)&&n.push(`rotate(${O})`),A&&["webp","png","jpeg"].includes(A)&&n.push(`format(${A})`)}t.srcset&&(i.srcset=t.srcset.map(u=>{if(typeof u=="number")return`${e}/m/${u}x0/${n.length>0?`filters:${n.join(":")}`:""} ${u}w`;if(Array.isArray(u)&&u.length===2){const[a,y]=u;return`${e}/m/${a}x${y}/${n.length>0?`filters:${n.join(":")}`:""} ${a}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),t.sizes&&(i.sizes=t.sizes.join(", "))}let l=`${e}/m/`;return(s>0||r>0)&&(l=`${l}${s}x${r}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:i}}function F(e,t={},s){const r=Z(t),i=r?`${e} ${r}`:e,n=Array.isArray(s)?s.join(""):s||"";if(e){if(Q.includes(e))return`<${i}>`}else return n;return`<${i}>${n}</${e}>`}function z(e={}){const t=new Map,{renderFn:s=F,textFn:r=te,resolvers:i={},optimizeImages:n=!1,keyedResolvers:c=!1}=e,l=s!==F,u=(o={})=>{const{textAlign:h,class:d,id:f,style:b,...k}=o,p=[];return b&&p.push(b.endsWith(";")?b:`${b};`),h&&p.push(`text-align: ${h};`),L({...k,class:d,id:f,...p.length>0?{style:p.join(" ")}:{}})},a=o=>(h,d)=>{const f=u(h.attrs);return d.render(o,f,h.children||null)},y=(o,h)=>{const{src:d,alt:f,title:b,srcset:k,sizes:p}=o.attrs||{};let E=d,_={};if(n){const{src:Oe,attrs:Ce}=re(d,n);E=Oe,_=Ce}const C={src:E,alt:f,title:b,srcset:k,sizes:p,..._};return h.render("img",L(C))},m=(o,h)=>{const{level:d,...f}=o.attrs||{},b=u(f);return h.render(`h${d}`,b,o.children)},A=(o,h)=>{var f,b,k,p;const d=h.render("img",{src:(f=o.attrs)==null?void 0:f.fallbackImage,alt:(b=o.attrs)==null?void 0:b.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return h.render("span",{"data-type":"emoji","data-name":(k=o.attrs)==null?void 0:k.name,"data-emoji":(p=o.attrs)==null?void 0:p.emoji},d)},H=(o,h)=>h.render("pre",o.attrs||{},h.render("code",{},o.children||"")),S=(o,h=!1)=>({text:d,attrs:f},b)=>{const{class:k,id:p,...E}=f||{},_=h?{class:k,id:p,style:ee(E)||void 0}:f||{};return b.render(o,L(_),d)},O=o=>U(o),we=o=>{const{marks:h,...d}=o;if("text"in o){if(h)return h.reduce((b,k)=>O({...k,text:b}),O({...d,children:d.children}));const f=o.attrs||{};if(c){const b=t.get("txt")||0;t.set("txt",b+1),f.key=`txt-${b}`}return r(d.text,f)}return""},Y=(o,h)=>{const{linktype:d,href:f,anchor:b,...k}=o.attrs||{};let p="";switch(d){case P.ASSET:case P.URL:p=f;break;case P.EMAIL:p=`mailto:${f}`;break;case P.STORY:p=f,b&&(p=`${p}#${b}`);break;default:p=f;break}const E={...k};return p&&(E.href=p),h.render("a",E,o.text)},_e=(o,h)=>{var d,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),h.render("span",{blok:(d=o==null?void 0:o.attrs)==null?void 0:d.body[0],id:(f=o.attrs)==null?void 0:f.id,style:"display: none"})},Se=(o,h)=>{const d=u(o.attrs),f=o.children||null;return h.render("table",d,h.render("tbody",{},f))},Ae=(o,h)=>{const d=u(o.attrs);return h.render("tr",d,o.children)},Ee=(o,h)=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:k,textAlign:p,...E}=o.attrs||{},_=[];b&&_.push(`width: ${b}px;`),k&&_.push(`background-color: ${k};`),p&&_.push(`text-align: ${p};`);const C={...E,...d>1?{colspan:d}:{},...f>1?{rowspan:f}:{},..._.length>0?{style:_.join(" ")}:{}};return h.render("td",L(C),o.children)},Te=(o,h)=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:k,textAlign:p,...E}=o.attrs||{},_=[];b&&_.push(`width: ${b}px;`),k&&_.push(`background-color: ${k};`),p&&_.push(`text-align: ${p};`);const C={...E,...d>1?{colspan:d}:{},...f>1?{rowspan:f}:{},..._.length>0?{style:_.join(" ")}:{}};return h.render("th",L(C),o.children)},W=new Map([[g.DOCUMENT,a("")],[g.HEADING,m],[g.PARAGRAPH,a("p")],[g.UL_LIST,a("ul")],[g.OL_LIST,a("ol")],[g.LIST_ITEM,a("li")],[g.IMAGE,y],[g.EMOJI,A],[g.CODE_BLOCK,H],[g.HR,a("hr")],[g.BR,a("br")],[g.QUOTE,a("blockquote")],[g.COMPONENT,_e],[B.TEXT,we],[w.LINK,Y],[w.ANCHOR,Y],[w.STYLED,S("span",!0)],[w.BOLD,S("strong")],[w.TEXT_STYLE,S("span",!0)],[w.ITALIC,S("em")],[w.UNDERLINE,S("u")],[w.STRIKE,S("s")],[w.CODE,S("code")],[w.SUPERSCRIPT,S("sup")],[w.SUBSCRIPT,S("sub")],[w.HIGHLIGHT,S("mark")],[g.TABLE,Se],[g.TABLE_ROW,Ae],[g.TABLE_CELL,Ee],[g.TABLE_HEADER,Te]]),X=new Map([...W,...Object.entries(i).map(([o,h])=>[o,h])]),Le=()=>({render:(d,f={},b)=>{if(c&&d){const k=t.get(d)||0;t.set(d,k+1),f.key=`${d}-${k}`}return s(d,f,b)},originalResolvers:W,mergedResolvers:X});function N(o){const h=X.get(o.type);if(!h)return console.error("<Storyblok>",`No resolver found for node type ${o.type}`),"";const d=Le();if(o.type==="text")return h(o,d);const f=o.content?o.content.map(U):void 0;return h({...o,children:f},d)}function U(o){return o.type==="doc"?l?o.content.map(N):o.content.map(N).join(""):Array.isArray(o)?o.map(N):N(o)}return{render:U}}let G=!1;const q=[],M=e=>new Promise((t,s)=>{if(typeof window>"u"){s(new Error("Cannot load Storyblok bridge: window is undefined (server-side environment)"));return}if(window.storyblokRegisterEvent=i=>{if(!window.location.search.includes("_storyblok")){console.warn("You are not in Draft Mode or in the Visual Editor.");return}G?i():q.push(i)},document.getElementById("storyblok-javascript-bridge")){t(void 0);return}const r=document.createElement("script");r.async=!0,r.src=e,r.id="storyblok-javascript-bridge",r.onerror=i=>s(i),r.onload=i=>{q.forEach(n=>n()),G=!0,t(i)},document.getElementsByTagName("head")[0].appendChild(r)});var se=class extends Error{constructor(e){super(e),this.name="AbortError"}};function ie(e,t,s){if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(s))throw new TypeError("Expected `interval` to be a finite number");const r=[];let i=[],n=0,c=!1;const l=async()=>{n++;const a=r.shift();if(a)try{const m=await e(...a.args);a.resolve(m)}catch(m){a.reject(m)}const y=setTimeout(()=>{n--,r.length>0&&l(),i=i.filter(m=>m!==y)},s);i.includes(y)||i.push(y)},u=(...a)=>c?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((y,m)=>{r.push({resolve:y,reject:m,args:a}),n<t&&l()});return u.abort=()=>{c=!0,i.forEach(clearTimeout),i=[],r.forEach(a=>a.reject(()=>new se("Throttle function aborted"))),r.length=0},u}var ne=ie;const V=(e="")=>e.includes("/cdn/"),oe=(e,t=25,s=1)=>({...e,per_page:t,page:s}),le=e=>new Promise(t=>setTimeout(t,e)),ae=(e=0,t)=>Array.from({length:e},t),ce=(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return ae(s,(i,n)=>n*r+e)},ue=async(e,t)=>Promise.all(e.map(t)),he=(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]),x=(e,t,s)=>{const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i];if(n==null)continue;const c=s?"":encodeURIComponent(i);let l;typeof n=="object"?l=x(n,t?t+encodeURIComponent(`[${c}]`):c,Array.isArray(n)):l=`${t?t+encodeURIComponent(`[${c}]`):c}=${encodeURIComponent(n)}`,r.push(l)}return r.join("&")},D=e=>{const t={eu:"api.storyblok.com",us:"api-us.storyblok.com",cn:"app.storyblokchina.cn",ap:"api-ap.storyblok.com",ca:"api-ca.storyblok.com"};return t[e]??t.eu};var de=class{constructor(e){v(this,"baseURL");v(this,"timeout");v(this,"headers");v(this,"responseInterceptor");v(this,"fetch");v(this,"ejectInterceptor");v(this,"url");v(this,"parameters");v(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;e==="get"?t=`${this.baseURL}${this.url}?${x(this.parameters)}`:s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const l=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(c);const u=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}catch(l){return{message:l}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_normalizeErrorMessage(e){if(Array.isArray(e))return e[0]||"Unknown error";if(e&&typeof e=="object"){if(e.error)return e.error;for(const t in e){if(Array.isArray(e[t]))return`${t}: ${e[t][0]}`;if(typeof e[t]=="string")return`${t}: ${e[t]}`}if(e.slug)return e.slug}return"Unknown error"}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:this._normalizeErrorMessage(e.data),status:e.status,response:e};r(i)})}},fe=de;const J="SB-Agent",$={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"7.0.0"},ye={PUBLISHED:"published"};let I={};const T={};var ge=class{constructor(e,t){v(this,"client");v(this,"maxRetries");v(this,"retriesDelay");v(this,"throttle");v(this,"accessToken");v(this,"cache");v(this,"resolveCounter");v(this,"relations");v(this,"links");v(this,"version");v(this,"richTextResolver");v(this,"resolveNestedRelations");v(this,"stringifiedStoriesCache");v(this,"inlineAssets");let s=e.endpoint||t;if(!s){const n=e.https===!1?"http":"https";e.oauthToken?s=`${n}://${D(e.region)}/v1`:s=`${n}://${D(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(([c,l])=>{r.set(c,l)}),r.has(J)||(r.set(J,$.defaultAgentName),r.set($.defaultAgentVersion,$.packageVersion));let i=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=ne(this.throttledRequest.bind(this),i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.version=e.version||ye.PUBLISHED,this.inlineAssets=e.inlineAssets||!1,this.client=new fe({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=T[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 V(e)?this.parseParams(t):t}makeRequest(e,t,s,r,i){const n=this.factoryParamOptions(e,oe(t,s,r));return this.cacheResponse(e,n,void 0,i)}get(e,t={},s){t||(t={});const r=`/${e}`;V(r)&&(t.version=t.version||this.version);const i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t={},s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),c=s??n.substring(n.lastIndexOf("/")+1);t.version=t.version||this.version;const l=1,u=await this.makeRequest(n,t,i,l,r),a=u.total?Math.ceil(u.total/(u.perPage||i)):1,y=await ue(ce(l,a),m=>this.makeRequest(n,t,i,m+1,r));return he([u,...y],m=>Object.values(m.data[c]))}post(e,t={},s){const r=`/${e}`;return this.throttle("post",r,t,s)}put(e,t={},s){const r=`/${e}`;return this.throttle("put",r,t,s)}delete(e,t={},s){t||(t={});const r=`/${e}`;return 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(i=>this.getStoryReference(s,i)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(c=>c.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=(i,n="")=>{if(!(!i||i._stopResolving)){if(Array.isArray(i))i.forEach((c,l)=>r(c,`${n}[${l}]`));else if(typeof i=="object")for(const c in i){const l=n?`${n}.${c}`:c;(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,c,t,s),this._insertLinks(i,c,s)),r(i[c],l)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],c=50;for(let l=0;l<i;l+=c){const u=Math.min(i,l+c);n.push(e.link_uuids.slice(l,u))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[l].join(",")})).data.stories.forEach(a=>{r.push(a)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],c=50;for(let l=0;l<i;l+=c){const u=Math.min(i,l+c);n.push(e.rel_uuids.slice(l,u))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[l].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(a=>{r.push(a)});r.length>0&&(e.rels=r,delete e.rel_uuids)}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var i,n;let r=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(r=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],r,s);e.story?this.iterateTree(e.story,r,s):e.stories.forEach(c=>{this.iterateTree(c,r,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const i=x({url:e,params:t}),n=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const c=await n.get(i);if(c)return Promise.resolve(c)}return new Promise(async(c,l)=>{var u;try{const a=await this.throttle("get",e,t,r);if(a.status!==200)return l(a);let y={data:a.data,headers:a.headers};if((u=a.headers)!=null&&u["per-page"]&&(y=Object.assign({},y,{perPage:a.headers["per-page"]?Number.parseInt(a.headers["per-page"]):0,total:a.headers["per-page"]?Number.parseInt(a.headers.total):0})),y.data.story||y.data.stories){const A=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(y.data,t,`${A}`),y=await this.processInlineAssets(y)}t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,y);const m=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&y.data.cv&&(m&&T[t.token]&&T[t.token]!==y.data.cv&&await this.flushCache(),T[t.token]=y.data.cv),c(y)}catch(a){if(a.response&&a.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 le(this.retriesDelay),this.cacheResponse(e,t,s).then(c).catch(l);l(a)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return T}cacheVersion(){return T[this.accessToken]}setCacheVersion(e){this.accessToken&&(T[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(T[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(I[e])},getAll(){return Promise.resolve(I)},set(e,t){return I[e]=t,Promise.resolve(void 0)},flush(){return I={},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}async processInlineAssets(e){if(!this.inlineAssets)return e;const t=s=>{if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(i=>t(i));let r={...s};r.fieldtype==="asset"&&Array.isArray(e.data.assets)&&(r={...e.data.assets.find(i=>i.id===r.id),...r});for(const i in r)typeof r[i]=="object"&&(r[i]=t(r[i]));return r};return e.data.story&&(e.data.story.content=t(e.data.story.content)),e.data.stories&&(e.data.stories=e.data.stories.map(s=>(s.content=t(s.content),s))),e}},be=ge;const pe=(e={})=>{const{apiOptions:t}=e;if(!t||!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 be(t)}},me=e=>{if(typeof e!="object"||typeof e._editable>"u")return{};try{const t=JSON.parse(e._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":`${t.id}-${t.uid}`}:{}}catch{return{}}};let j="https://app.storyblok.com/f/storyblok-v2-latest.js";const K=(e,t,s={})=>{var l;const i=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok"),c=n!==null&&+n===e;if(!(!i||!c)){if(!e){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(s).on(["input","published","change"],a=>{var y;a&&(a.action==="input"&&((y=a.story)==null?void 0:y.id)===e?t(a.story):(a.action==="change"||a.action==="published")&&a.storyId===e&&window.location.reload())})})}},ve=(e={})=>{var y,m;const{bridge:t,accessToken:s,use:r=[],apiOptions:i={},bridgeUrl:n}=e;i.accessToken=i.accessToken||s;const c={bridge:t,apiOptions:i};let l={};r.forEach(A=>{l={...l,...A(c)}}),n&&(j=n);const a=!(typeof window>"u")&&((m=(y=window.location)==null?void 0:y.search)==null?void 0:m.includes("_storyblok_tk"));return t!==!1&&a&&M(j),l};function Re(e,t){return z(t).render(e)}const ke=()=>M(j);R.BlockTypes=g,R.MarkTypes=w,R.TextTypes=B,R.apiPlugin=pe,R.loadStoryblokBridge=ke,R.registerStoryblokBridge=K,R.renderRichText=Re,R.richTextResolver=z,R.storyblokEditable=me,R.storyblokInit=ve,R.useStoryblokBridge=K,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
|
|
7
|
+
(function(R,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(R=typeof globalThis<"u"?globalThis:R||self,g(R.storyblok={}))})(this,function(R){"use strict";var Pe=Object.defineProperty;var Ie=(R,g,w)=>g in R?Pe(R,g,{enumerable:!0,configurable:!0,writable:!0,value:w}):R[g]=w;var v=(R,g,w)=>Ie(R,typeof g!="symbol"?g+"":g,w);let g=function(e){return e.DOCUMENT="doc",e.HEADING="heading",e.PARAGRAPH="paragraph",e.QUOTE="blockquote",e.OL_LIST="ordered_list",e.UL_LIST="bullet_list",e.LIST_ITEM="list_item",e.CODE_BLOCK="code_block",e.HR="horizontal_rule",e.BR="hard_break",e.IMAGE="image",e.EMOJI="emoji",e.COMPONENT="blok",e.TABLE="table",e.TABLE_ROW="tableRow",e.TABLE_CELL="tableCell",e.TABLE_HEADER="tableHeader",e}({}),w=function(e){return e.BOLD="bold",e.STRONG="strong",e.STRIKE="strike",e.UNDERLINE="underline",e.ITALIC="italic",e.CODE="code",e.LINK="link",e.ANCHOR="anchor",e.STYLED="styled",e.SUPERSCRIPT="superscript",e.SUBSCRIPT="subscript",e.TEXT_STYLE="textStyle",e.HIGHLIGHT="highlight",e}({}),B=function(e){return e.TEXT="text",e}({}),P=function(e){return e.URL="url",e.STORY="story",e.ASSET="asset",e.EMAIL="email",e}({});const Z=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],ee=(e={})=>{const{custom:t,...s}=e,r={...s,...t};return Object.keys(r).map(i=>`${i}="${r[i]}"`).join(" ")},te=(e={})=>Object.keys(e).map(t=>`${t}: ${e[t]}`).join("; ");function re(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const L=e=>Object.fromEntries(Object.entries(e).filter(([t,s])=>s!==void 0));function se(e,t){if(!t)return{src:e,attrs:{}};let s=0,r=0;const i={},n=[];function c(u,a,y,m,A){typeof u!="number"||u<=a||u>=y?console.warn(`[StoryblokRichText] - ${m.charAt(0).toUpperCase()+m.slice(1)} value must be a number between ${a} and ${y} (inclusive)`):A.push(`${m}(${u})`)}if(typeof t=="object"){if(t.width!==void 0&&(typeof t.width=="number"&&t.width>=0?(i.width=t.width,s=t.width):console.warn("[StoryblokRichText] - Width value must be a number greater than or equal to 0")),t.height!==void 0&&(typeof t.height=="number"&&t.height>=0?(i.height=t.height,r=t.height):console.warn("[StoryblokRichText] - Height value must be a number greater than or equal to 0")),t.height===0&&t.width===0&&(delete i.width,delete i.height,console.warn("[StoryblokRichText] - Width and height values cannot both be 0")),t.loading&&["lazy","eager"].includes(t.loading)&&(i.loading=t.loading),t.class&&(i.class=t.class),t.filters){const{filters:u}=t||{},{blur:a,brightness:y,fill:m,format:A,grayscale:H,quality:S,rotate:O}=u||{};a&&c(a,0,100,"blur",n),S&&c(S,0,100,"quality",n),y&&c(y,0,100,"brightness",n),m&&n.push(`fill(${m})`),H&&n.push("grayscale()"),O&&[0,90,180,270].includes(t.filters.rotate||0)&&n.push(`rotate(${O})`),A&&["webp","png","jpeg"].includes(A)&&n.push(`format(${A})`)}t.srcset&&(i.srcset=t.srcset.map(u=>{if(typeof u=="number")return`${e}/m/${u}x0/${n.length>0?`filters:${n.join(":")}`:""} ${u}w`;if(Array.isArray(u)&&u.length===2){const[a,y]=u;return`${e}/m/${a}x${y}/${n.length>0?`filters:${n.join(":")}`:""} ${a}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),t.sizes&&(i.sizes=t.sizes.join(", "))}let l=`${e}/m/`;return(s>0||r>0)&&(l=`${l}${s}x${r}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:i}}function z(e,t={},s){const r=ee(t),i=r?`${e} ${r}`:e,n=Array.isArray(s)?s.join(""):s||"";if(e){if(Z.includes(e))return`<${i}>`}else return n;return`<${i}>${n}</${e}>`}function F(e={}){const t=new Map,{renderFn:s=z,textFn:r=re,resolvers:i={},optimizeImages:n=!1,keyedResolvers:c=!1}=e,l=s!==z,u=(o={})=>{const{textAlign:h,class:d,id:f,style:b,...k}=o,p=[];return b&&p.push(b.endsWith(";")?b:`${b};`),h&&p.push(`text-align: ${h};`),L({...k,class:d,id:f,...p.length>0?{style:p.join(" ")}:{}})},a=o=>(h,d)=>{const f=u(h.attrs);return d.render(o,f,h.children||null)},y=(o,h)=>{const{src:d,alt:f,title:b,srcset:k,sizes:p}=o.attrs||{};let E=d,_={};if(n){const{src:Oe,attrs:Ce}=se(d,n);E=Oe,_=Ce}const C={src:E,alt:f,title:b,srcset:k,sizes:p,..._};return h.render("img",L(C))},m=(o,h)=>{const{level:d,...f}=o.attrs||{},b=u(f);return h.render(`h${d}`,b,o.children)},A=(o,h)=>{var f,b,k,p;const d=h.render("img",{src:(f=o.attrs)==null?void 0:f.fallbackImage,alt:(b=o.attrs)==null?void 0:b.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return h.render("span",{"data-type":"emoji","data-name":(k=o.attrs)==null?void 0:k.name,"data-emoji":(p=o.attrs)==null?void 0:p.emoji},d)},H=(o,h)=>h.render("pre",o.attrs||{},h.render("code",{},o.children||"")),S=(o,h=!1)=>({text:d,attrs:f},b)=>{const{class:k,id:p,...E}=f||{},_=h?{class:k,id:p,style:te(E)||void 0}:f||{};return b.render(o,L(_),d)},O=o=>U(o),we=o=>{const{marks:h,...d}=o;if("text"in o){if(h)return h.reduce((b,k)=>O({...k,text:b}),O({...d,children:d.children}));const f=o.attrs||{};if(c){const b=t.get("txt")||0;t.set("txt",b+1),f.key=`txt-${b}`}return r(d.text,f)}return""},W=(o,h)=>{const{linktype:d,href:f,anchor:b,...k}=o.attrs||{};let p="";switch(d){case P.ASSET:case P.URL:p=f;break;case P.EMAIL:p=`mailto:${f}`;break;case P.STORY:p=f,b&&(p=`${p}#${b}`);break;default:p=f;break}const E={...k};return p&&(E.href=p),h.render("a",E,o.text)},_e=(o,h)=>{var d,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),h.render("span",{blok:(d=o==null?void 0:o.attrs)==null?void 0:d.body[0],id:(f=o.attrs)==null?void 0:f.id,style:"display: none"})},Se=(o,h)=>{const d=u(o.attrs),f=o.children||null;return h.render("table",d,h.render("tbody",{},f))},Ae=(o,h)=>{const d=u(o.attrs);return h.render("tr",d,o.children)},Ee=(o,h)=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:k,textAlign:p,...E}=o.attrs||{},_=[];b&&_.push(`width: ${b}px;`),k&&_.push(`background-color: ${k};`),p&&_.push(`text-align: ${p};`);const C={...E,...d>1?{colspan:d}:{},...f>1?{rowspan:f}:{},..._.length>0?{style:_.join(" ")}:{}};return h.render("td",L(C),o.children)},Te=(o,h)=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:k,textAlign:p,...E}=o.attrs||{},_=[];b&&_.push(`width: ${b}px;`),k&&_.push(`background-color: ${k};`),p&&_.push(`text-align: ${p};`);const C={...E,...d>1?{colspan:d}:{},...f>1?{rowspan:f}:{},..._.length>0?{style:_.join(" ")}:{}};return h.render("th",L(C),o.children)},X=new Map([[g.DOCUMENT,a("")],[g.HEADING,m],[g.PARAGRAPH,a("p")],[g.UL_LIST,a("ul")],[g.OL_LIST,a("ol")],[g.LIST_ITEM,a("li")],[g.IMAGE,y],[g.EMOJI,A],[g.CODE_BLOCK,H],[g.HR,a("hr")],[g.BR,a("br")],[g.QUOTE,a("blockquote")],[g.COMPONENT,_e],[B.TEXT,we],[w.LINK,W],[w.ANCHOR,W],[w.STYLED,S("span",!0)],[w.BOLD,S("strong")],[w.TEXT_STYLE,S("span",!0)],[w.ITALIC,S("em")],[w.UNDERLINE,S("u")],[w.STRIKE,S("s")],[w.CODE,S("code")],[w.SUPERSCRIPT,S("sup")],[w.SUBSCRIPT,S("sub")],[w.HIGHLIGHT,S("mark")],[g.TABLE,Se],[g.TABLE_ROW,Ae],[g.TABLE_CELL,Ee],[g.TABLE_HEADER,Te]]),Q=new Map([...X,...Object.entries(i).map(([o,h])=>[o,h])]),Le=()=>({render:(d,f={},b)=>{if(c&&d){const k=t.get(d)||0;t.set(d,k+1),f.key=`${d}-${k}`}return s(d,f,b)},originalResolvers:X,mergedResolvers:Q});function N(o){const h=Q.get(o.type);if(!h)return console.error("<Storyblok>",`No resolver found for node type ${o.type}`),"";const d=Le();if(o.type==="text")return h(o,d);const f=o.content?o.content.map(U):void 0;return h({...o,children:f},d)}function U(o){return o.type==="doc"?l?o.content.map(N):o.content.map(N).join(""):Array.isArray(o)?o.map(N):N(o)}return{render:U}}let G=!1;const q=[],M=e=>new Promise((t,s)=>{if(typeof window>"u"){s(new Error("Cannot load Storyblok bridge: window is undefined (server-side environment)"));return}if(window.storyblokRegisterEvent=i=>{if(!window.location.search.includes("_storyblok")){console.warn("You are not in Draft Mode or in the Visual Editor.");return}G?i():q.push(i)},document.getElementById("storyblok-javascript-bridge")){t(void 0);return}const r=document.createElement("script");r.async=!0,r.src=e,r.id="storyblok-javascript-bridge",r.onerror=i=>s(i),r.onload=i=>{q.forEach(n=>n()),G=!0,t(i)},document.getElementsByTagName("head")[0].appendChild(r)});var ie=class extends Error{constructor(e){super(e),this.name="AbortError"}};function ne(e,t,s){if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(s))throw new TypeError("Expected `interval` to be a finite number");const r=[];let i=[],n=0,c=!1;const l=async()=>{n++;const a=r.shift();if(a)try{const m=await e(...a.args);a.resolve(m)}catch(m){a.reject(m)}const y=setTimeout(()=>{n--,r.length>0&&l(),i=i.filter(m=>m!==y)},s);i.includes(y)||i.push(y)},u=(...a)=>c?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((y,m)=>{r.push({resolve:y,reject:m,args:a}),n<t&&l()});return u.abort=()=>{c=!0,i.forEach(clearTimeout),i=[],r.forEach(a=>a.reject(()=>new ie("Throttle function aborted"))),r.length=0},u}var oe=ne;const V=(e="")=>e.includes("/cdn/"),le=(e,t=25,s=1)=>({...e,per_page:t,page:s}),ae=e=>new Promise(t=>setTimeout(t,e)),ce=(e=0,t)=>Array.from({length:e},t),ue=(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return ce(s,(i,n)=>n*r+e)},he=async(e,t)=>Promise.all(e.map(t)),de=(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]),$=(e,t,s)=>{const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i];if(n==null)continue;const c=s?"":encodeURIComponent(i);let l;typeof n=="object"?l=$(n,t?t+encodeURIComponent(`[${c}]`):c,Array.isArray(n)):l=`${t?t+encodeURIComponent(`[${c}]`):c}=${encodeURIComponent(n)}`,r.push(l)}return r.join("&")},D=e=>{const t={eu:"api.storyblok.com",us:"api-us.storyblok.com",cn:"app.storyblokchina.cn",ap:"api-ap.storyblok.com",ca:"api-ca.storyblok.com"};return t[e]??t.eu};var fe=class{constructor(e){v(this,"baseURL");v(this,"timeout");v(this,"headers");v(this,"responseInterceptor");v(this,"fetch");v(this,"ejectInterceptor");v(this,"url");v(this,"parameters");v(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;e==="get"?t=`${this.baseURL}${this.url}?${$(this.parameters)}`:s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const l=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(c);const u=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}catch(l){return{message:l}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_normalizeErrorMessage(e){if(Array.isArray(e))return e[0]||"Unknown error";if(e&&typeof e=="object"){if(e.error)return e.error;for(const t in e){if(Array.isArray(e[t]))return`${t}: ${e[t][0]}`;if(typeof e[t]=="string")return`${t}: ${e[t]}`}if(e.slug)return e.slug}return"Unknown error"}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:this._normalizeErrorMessage(e.data),status:e.status,response:e};r(i)})}},ye=fe;const J="SB-Agent",x={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"7.0.0"},ge={PUBLISHED:"published"};let I={};const T={};var be=class{constructor(e,t){v(this,"client");v(this,"maxRetries");v(this,"retriesDelay");v(this,"throttle");v(this,"accessToken");v(this,"cache");v(this,"resolveCounter");v(this,"relations");v(this,"links");v(this,"version");v(this,"richTextResolver");v(this,"resolveNestedRelations");v(this,"stringifiedStoriesCache");v(this,"inlineAssets");let s=e.endpoint||t;if(!s){const n=e.https===!1?"http":"https";e.oauthToken?s=`${n}://${D(e.region)}/v1`:s=`${n}://${D(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(([c,l])=>{r.set(c,l)}),r.has(J)||(r.set(J,x.defaultAgentName),r.set(x.defaultAgentVersion,x.packageVersion));let i=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=oe(this.throttledRequest.bind(this),i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.version=e.version||ge.PUBLISHED,this.inlineAssets=e.inlineAssets||!1,this.client=new ye({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=T[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 V(e)?this.parseParams(t):t}makeRequest(e,t,s,r,i){const n=this.factoryParamOptions(e,le(t,s,r));return this.cacheResponse(e,n,void 0,i)}get(e,t={},s){t||(t={});const r=`/${e}`;V(r)&&(t.version=t.version||this.version);const i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t={},s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),c=s??n.substring(n.lastIndexOf("/")+1);t.version=t.version||this.version;const l=1,u=await this.makeRequest(n,t,i,l,r),a=u.total?Math.ceil(u.total/(u.perPage||i)):1,y=await he(ue(l,a),m=>this.makeRequest(n,t,i,m+1,r));return de([u,...y],m=>Object.values(m.data[c]))}post(e,t={},s){const r=`/${e}`;return this.throttle("post",r,t,s)}put(e,t={},s){const r=`/${e}`;return this.throttle("put",r,t,s)}delete(e,t={},s){t||(t={});const r=`/${e}`;return 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(i=>this.getStoryReference(s,i)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(c=>c.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=(i,n="")=>{if(!(!i||i._stopResolving)){if(Array.isArray(i))i.forEach((c,l)=>r(c,`${n}[${l}]`));else if(typeof i=="object")for(const c in i){const l=n?`${n}.${c}`:c;(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,c,t,s),this._insertLinks(i,c,s)),r(i[c],l)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],c=50;for(let l=0;l<i;l+=c){const u=Math.min(i,l+c);n.push(e.link_uuids.slice(l,u))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[l].join(",")})).data.stories.forEach(a=>{r.push(a)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],c=50;for(let l=0;l<i;l+=c){const u=Math.min(i,l+c);n.push(e.rel_uuids.slice(l,u))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[l].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(a=>{r.push(a)});r.length>0&&(e.rels=r,delete e.rel_uuids)}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var i,n;let r=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(r=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],r,s);e.story?this.iterateTree(e.story,r,s):e.stories.forEach(c=>{this.iterateTree(c,r,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const i=$({url:e,params:t}),n=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const c=await n.get(i);if(c)return Promise.resolve(c)}return new Promise(async(c,l)=>{var u;try{const a=await this.throttle("get",e,t,r);if(a.status!==200)return l(a);let y={data:a.data,headers:a.headers};if((u=a.headers)!=null&&u["per-page"]&&(y=Object.assign({},y,{perPage:a.headers["per-page"]?Number.parseInt(a.headers["per-page"]):0,total:a.headers["per-page"]?Number.parseInt(a.headers.total):0})),y.data.story||y.data.stories){const A=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(y.data,t,`${A}`),y=await this.processInlineAssets(y)}t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,y);const m=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&y.data.cv&&(m&&T[t.token]&&T[t.token]!==y.data.cv&&await this.flushCache(),T[t.token]=y.data.cv),c(y)}catch(a){if(a.response&&a.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 ae(this.retriesDelay),this.cacheResponse(e,t,s).then(c).catch(l);l(a)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return T}cacheVersion(){return T[this.accessToken]}setCacheVersion(e){this.accessToken&&(T[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(T[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(I[e])},getAll(){return Promise.resolve(I)},set(e,t){return I[e]=t,Promise.resolve(void 0)},flush(){return I={},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}async processInlineAssets(e){if(!this.inlineAssets)return e;const t=s=>{if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(i=>t(i));let r={...s};r.fieldtype==="asset"&&Array.isArray(e.data.assets)&&(r={...e.data.assets.find(i=>i.id===r.id),...r});for(const i in r)typeof r[i]=="object"&&(r[i]=t(r[i]));return r};return e.data.story&&(e.data.story.content=t(e.data.story.content)),e.data.stories&&(e.data.stories=e.data.stories.map(s=>(s.content=t(s.content),s))),e}},K=be;const pe=(e={})=>{const{apiOptions:t}=e;if(!t||!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 K(t)}},me=e=>{if(typeof e!="object"||typeof e._editable>"u")return{};try{const t=JSON.parse(e._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":`${t.id}-${t.uid}`}:{}}catch{return{}}};let j="https://app.storyblok.com/f/storyblok-v2-latest.js";const Y=(e,t,s={})=>{var l;const i=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok"),c=n!==null&&+n===e;if(!(!i||!c)){if(!e){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(s).on(["input","published","change"],a=>{var y;a&&(a.action==="input"&&((y=a.story)==null?void 0:y.id)===e?t(a.story):(a.action==="change"||a.action==="published")&&a.storyId===e&&window.location.reload())})})}},ve=(e={})=>{var y,m;const{bridge:t,accessToken:s,use:r=[],apiOptions:i={},bridgeUrl:n}=e;i.accessToken=i.accessToken||s;const c={bridge:t,apiOptions:i};let l={};r.forEach(A=>{l={...l,...A(c)}}),n&&(j=n);const a=!(typeof window>"u")&&((m=(y=window.location)==null?void 0:y.search)==null?void 0:m.includes("_storyblok_tk"));return t!==!1&&a&&M(j),l};function Re(e,t){return F(t).render(e)}const ke=()=>M(j);R.BlockTypes=g,R.MarkTypes=w,R.StoryblokClient=K,R.TextTypes=B,R.apiPlugin=pe,R.loadStoryblokBridge=ke,R.registerStoryblokBridge=Y,R.renderRichText=Re,R.richTextResolver=F,R.storyblokEditable=me,R.storyblokInit=ve,R.useStoryblokBridge=Y,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
|
package/dist/storyblok-js.mjs
CHANGED
|
@@ -31,11 +31,17 @@ const oe = [
|
|
|
31
31
|
"source",
|
|
32
32
|
"track",
|
|
33
33
|
"wbr"
|
|
34
|
-
], le = (e = {}) =>
|
|
34
|
+
], le = (e = {}) => {
|
|
35
|
+
const { custom: t, ...s } = e, r = {
|
|
36
|
+
...s,
|
|
37
|
+
...t
|
|
38
|
+
};
|
|
39
|
+
return Object.keys(r).map((i) => `${i}="${r[i]}"`).join(" ");
|
|
40
|
+
}, ae = (e = {}) => Object.keys(e).map((t) => `${t}: ${e[t]}`).join("; ");
|
|
35
41
|
function ce(e) {
|
|
36
42
|
return e.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
37
43
|
}
|
|
38
|
-
const
|
|
44
|
+
const C = (e) => Object.fromEntries(Object.entries(e).filter(([t, s]) => s !== void 0));
|
|
39
45
|
function ue(e, t) {
|
|
40
46
|
if (!t) return {
|
|
41
47
|
src: e,
|
|
@@ -77,7 +83,7 @@ function ue(e, t) {
|
|
|
77
83
|
attrs: i
|
|
78
84
|
};
|
|
79
85
|
}
|
|
80
|
-
function
|
|
86
|
+
function F(e, t = {}, s) {
|
|
81
87
|
const r = le(t), i = r ? `${e} ${r}` : e, n = Array.isArray(s) ? s.join("") : s || "";
|
|
82
88
|
if (e) {
|
|
83
89
|
if (oe.includes(e)) return `<${i}>`;
|
|
@@ -85,9 +91,9 @@ function z(e, t = {}, s) {
|
|
|
85
91
|
return `<${i}>${n}</${e}>`;
|
|
86
92
|
}
|
|
87
93
|
function he(e = {}) {
|
|
88
|
-
const t = /* @__PURE__ */ new Map(), { renderFn: s =
|
|
94
|
+
const t = /* @__PURE__ */ new Map(), { renderFn: s = F, textFn: r = ce, resolvers: i = {}, optimizeImages: n = !1, keyedResolvers: c = !1 } = e, l = s !== F, u = (o = {}) => {
|
|
89
95
|
const { textAlign: h, class: d, id: f, style: y, ...v } = o, b = [];
|
|
90
|
-
return y && b.push(y.endsWith(";") ? y : `${y};`), h && b.push(`text-align: ${h};`),
|
|
96
|
+
return y && b.push(y.endsWith(";") ? y : `${y};`), h && b.push(`text-align: ${h};`), C({
|
|
91
97
|
...v,
|
|
92
98
|
class: d,
|
|
93
99
|
id: f,
|
|
@@ -111,7 +117,7 @@ function he(e = {}) {
|
|
|
111
117
|
sizes: b,
|
|
112
118
|
...w
|
|
113
119
|
};
|
|
114
|
-
return h.render("img",
|
|
120
|
+
return h.render("img", C(L));
|
|
115
121
|
}, p = (o, h) => {
|
|
116
122
|
const { level: d, ...f } = o.attrs || {}, y = u(f);
|
|
117
123
|
return h.render(`h${d}`, y, o.children);
|
|
@@ -135,7 +141,7 @@ function he(e = {}) {
|
|
|
135
141
|
id: b,
|
|
136
142
|
style: ae(A) || void 0
|
|
137
143
|
} : f || {};
|
|
138
|
-
return y.render(o,
|
|
144
|
+
return y.render(o, C(w), d);
|
|
139
145
|
}, T = (o) => N(o), K = (o) => {
|
|
140
146
|
const { marks: h, ...d } = o;
|
|
141
147
|
if ("text" in o) {
|
|
@@ -196,7 +202,7 @@ function he(e = {}) {
|
|
|
196
202
|
...f > 1 ? { rowspan: f } : {},
|
|
197
203
|
...w.length > 0 ? { style: w.join(" ") } : {}
|
|
198
204
|
};
|
|
199
|
-
return h.render("td",
|
|
205
|
+
return h.render("td", C(L), o.children);
|
|
200
206
|
}, Z = (o, h) => {
|
|
201
207
|
const { colspan: d, rowspan: f, colwidth: y, backgroundColor: v, textAlign: b, ...A } = o.attrs || {}, w = [];
|
|
202
208
|
y && w.push(`width: ${y}px;`), v && w.push(`background-color: ${v};`), b && w.push(`text-align: ${b};`);
|
|
@@ -206,7 +212,7 @@ function he(e = {}) {
|
|
|
206
212
|
...f > 1 ? { rowspan: f } : {},
|
|
207
213
|
...w.length > 0 ? { style: w.join(" ") } : {}
|
|
208
214
|
};
|
|
209
|
-
return h.render("th",
|
|
215
|
+
return h.render("th", C(L), o.children);
|
|
210
216
|
}, B = /* @__PURE__ */ new Map([
|
|
211
217
|
[R.DOCUMENT, a("")],
|
|
212
218
|
[R.HEADING, p],
|
|
@@ -238,7 +244,7 @@ function he(e = {}) {
|
|
|
238
244
|
[R.TABLE_ROW, X],
|
|
239
245
|
[R.TABLE_CELL, Q],
|
|
240
246
|
[R.TABLE_HEADER, Z]
|
|
241
|
-
]),
|
|
247
|
+
]), z = new Map([...B, ...Object.entries(i).map(([o, h]) => [o, h])]), ee = () => ({
|
|
242
248
|
render: (d, f = {}, y) => {
|
|
243
249
|
if (c && d) {
|
|
244
250
|
const v = t.get(d) || 0;
|
|
@@ -247,10 +253,10 @@ function he(e = {}) {
|
|
|
247
253
|
return s(d, f, y);
|
|
248
254
|
},
|
|
249
255
|
originalResolvers: B,
|
|
250
|
-
mergedResolvers:
|
|
256
|
+
mergedResolvers: z
|
|
251
257
|
});
|
|
252
|
-
function
|
|
253
|
-
const h =
|
|
258
|
+
function O(o) {
|
|
259
|
+
const h = z.get(o.type);
|
|
254
260
|
if (!h)
|
|
255
261
|
return console.error("<Storyblok>", `No resolver found for node type ${o.type}`), "";
|
|
256
262
|
const d = ee();
|
|
@@ -262,7 +268,7 @@ function he(e = {}) {
|
|
|
262
268
|
}, d);
|
|
263
269
|
}
|
|
264
270
|
function N(o) {
|
|
265
|
-
return o.type === "doc" ? l ? o.content.map(
|
|
271
|
+
return o.type === "doc" ? l ? o.content.map(O) : o.content.map(O).join("") : Array.isArray(o) ? o.map(O) : O(o);
|
|
266
272
|
}
|
|
267
273
|
return { render: N };
|
|
268
274
|
}
|
|
@@ -833,7 +839,7 @@ const Te = (e = {}) => {
|
|
|
833
839
|
}
|
|
834
840
|
};
|
|
835
841
|
let H = "https://app.storyblok.com/f/storyblok-v2-latest.js";
|
|
836
|
-
const
|
|
842
|
+
const Ce = (e, t, s = {}) => {
|
|
837
843
|
var l;
|
|
838
844
|
const i = !(typeof window > "u") && typeof window.storyblokRegisterEvent < "u", n = new URL((l = window.location) == null ? void 0 : l.href).searchParams.get(
|
|
839
845
|
"_storyblok"
|
|
@@ -850,7 +856,7 @@ const Oe = (e, t, s = {}) => {
|
|
|
850
856
|
});
|
|
851
857
|
});
|
|
852
858
|
}
|
|
853
|
-
},
|
|
859
|
+
}, Oe = (e = {}) => {
|
|
854
860
|
var g, p;
|
|
855
861
|
const {
|
|
856
862
|
bridge: t,
|
|
@@ -875,13 +881,14 @@ const xe = () => J(H);
|
|
|
875
881
|
export {
|
|
876
882
|
R as BlockTypes,
|
|
877
883
|
_ as MarkTypes,
|
|
884
|
+
Ae as StoryblokClient,
|
|
878
885
|
ne as TextTypes,
|
|
879
886
|
Te as apiPlugin,
|
|
880
887
|
xe as loadStoryblokBridge,
|
|
881
|
-
|
|
888
|
+
Ce as registerStoryblokBridge,
|
|
882
889
|
Pe as renderRichText,
|
|
883
890
|
he as richTextResolver,
|
|
884
891
|
Le as storyblokEditable,
|
|
885
|
-
|
|
886
|
-
|
|
892
|
+
Oe as storyblokInit,
|
|
893
|
+
Ce as useStoryblokBridge
|
|
887
894
|
};
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { ISbComponentType, ISbConfig, ISbStoryData, default as
|
|
2
|
-
export type StoryblokClient = StoryblokJSClient;
|
|
1
|
+
import { ISbComponentType, ISbConfig, ISbStoryData, default as StoryblokClient } from 'storyblok-js-client';
|
|
3
2
|
declare global {
|
|
4
3
|
interface Window {
|
|
5
4
|
storyblokRegisterEvent: (cb: () => void) => void;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storyblok/js",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.4.0",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "SDK to integrate Storyblok into your project using JavaScript.",
|
|
7
7
|
"license": "MIT",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"dist"
|
|
29
29
|
],
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@storyblok/richtext": "3.8.
|
|
31
|
+
"@storyblok/richtext": "3.8.2",
|
|
32
32
|
"storyblok-js-client": "7.1.5"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|