storyblok-js-client
Advanced tools
Comparing version 6.10.0 to 6.10.1
@@ -1,2 +0,2 @@ | ||
(function(g,d){typeof exports=="object"&&typeof module<"u"?module.exports=d():typeof define=="function"&&define.amd?define(d):(g=typeof globalThis<"u"?globalThis:g||self,g.StoryblokJSClient=d())})(this,function(){"use strict";var H=Object.defineProperty;var U=(g,d,y)=>d in g?H(g,d,{enumerable:!0,configurable:!0,writable:!0,value:y}):g[d]=y;var c=(g,d,y)=>U(g,typeof d!="symbol"?d+"":d,y);function g(a){return!(a!==a||a===1/0||a===-1/0)}function d(a,e,t){if(!g(e))throw new TypeError("Expected `limit` to be a finite number");if(!g(t))throw new TypeError("Expected `interval` to be a finite number");const r=[];let s=[],i=0;const n=function(){i++;const o=setTimeout(function(){i--,r.length>0&&n(),s=s.filter(function(h){return h!==o})},t);s.indexOf(o)<0&&s.push(o);const u=r.shift();u.resolve(a.apply(u.self,u.args))},l=function(...o){const u=this;return new Promise(function(h,f){r.push({resolve:h,reject:f,args:o,self:u}),i<e&&n()})};return l.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),r.length=0},l}class y{constructor(){c(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);c(this,"getOptionsPage",(e,t=25,r=1)=>({...e,per_page:t,page:r}));c(this,"delay",e=>new Promise(t=>setTimeout(t,e)));c(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));c(this,"range",(e=0,t=e)=>{const r=Math.abs(t-e)||0,s=e<t?1:-1;return this.arrayFrom(r,(i,n)=>n*s+e)});c(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));c(this,"flatMap",(e=[],t)=>e.map(t).reduce((r,s)=>[...r,...s],[]));c(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},r=/[&<>"']/g,s=RegExp(r.source);return e&&s.test(e)?e.replace(r,i=>t[i]):e})}stringify(e,t,r){const s=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i],l=r?"":encodeURIComponent(i);let o;typeof n=="object"?o=this.stringify(n,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(n)):o=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(n),s.push(o)}return s.join("&")}getRegionURL(e){const t="api.storyblok.com",r="api-us.storyblok.com",s="app.storyblokchina.cn",i="api-ap.storyblok.com",n="api-ca.storyblok.com";switch(e){case"us":return r;case"cn":return s;case"ap":return i;case"ca":return n;default:return t}}}const O=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:y},Symbol.toStringTag,{value:"Module"})),L=function(a,e){const t={};for(const r in a){const s=a[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t},E=a=>a==="email",w={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:L(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:a=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":a.attrs.name,emoji:a.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"s"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{if(!a.attrs)return{tag:""};const e=new y().escapeHTML,t={...a.attrs},{linktype:r="url"}=a.attrs;if(delete t.linktype,t.href&&(t.href=e(a.attrs.href||"")),E(r)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const s in t.custom)t[s]=t.custom[s];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:a=>({tag:[{tag:"span",attrs:a.attrs}]}),highlight:a=>{var t;return(t=a.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${a.attrs.color};`}}]}:{tag:""}},textStyle:a=>{var t;return(t=a.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${a.attrs.color}`}}]}:{tag:""}}}},j=function(a){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return a&&r.test(a)?a.replace(t,s=>e[s]):a};let S=!1;class _{constructor(e){c(this,"marks");c(this,"nodes");e||(e=w),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},r=!0){if(!S&&r&&(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/"),S=!0),e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(i=>{s+=this.renderNode(i)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field. | ||
(function(g,d){typeof exports=="object"&&typeof module<"u"?module.exports=d():typeof define=="function"&&define.amd?define(d):(g=typeof globalThis<"u"?globalThis:g||self,g.StoryblokJSClient=d())})(this,function(){"use strict";var H=Object.defineProperty;var U=(g,d,y)=>d in g?H(g,d,{enumerable:!0,configurable:!0,writable:!0,value:y}):g[d]=y;var c=(g,d,y)=>U(g,typeof d!="symbol"?d+"":d,y);function g(a){return!(a!==a||a===1/0||a===-1/0)}function d(a,e,t){if(!g(e))throw new TypeError("Expected `limit` to be a finite number");if(!g(t))throw new TypeError("Expected `interval` to be a finite number");const r=[];let s=[],i=0;const n=function(){i++;const o=setTimeout(function(){i--,r.length>0&&n(),s=s.filter(function(u){return u!==o})},t);s.indexOf(o)<0&&s.push(o);const h=r.shift();h.resolve(a.apply(h.self,h.args))},l=function(...o){const h=this;return new Promise(function(u,f){r.push({resolve:u,reject:f,args:o,self:h}),i<e&&n()})};return l.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),r.length=0},l}class y{constructor(){c(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);c(this,"getOptionsPage",(e,t=25,r=1)=>({...e,per_page:t,page:r}));c(this,"delay",e=>new Promise(t=>setTimeout(t,e)));c(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));c(this,"range",(e=0,t=e)=>{const r=Math.abs(t-e)||0,s=e<t?1:-1;return this.arrayFrom(r,(i,n)=>n*s+e)});c(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));c(this,"flatMap",(e=[],t)=>e.map(t).reduce((r,s)=>[...r,...s],[]));c(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},r=/[&<>"']/g,s=RegExp(r.source);return e&&s.test(e)?e.replace(r,i=>t[i]):e})}stringify(e,t,r){const s=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i],l=r?"":encodeURIComponent(i);let o;typeof n=="object"?o=this.stringify(n,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(n)):o=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(n),s.push(o)}return s.join("&")}getRegionURL(e){const t="api.storyblok.com",r="api-us.storyblok.com",s="app.storyblokchina.cn",i="api-ap.storyblok.com",n="api-ca.storyblok.com";switch(e){case"us":return r;case"cn":return s;case"ap":return i;case"ca":return n;default:return t}}}const O=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:y},Symbol.toStringTag,{value:"Module"})),L=function(a,e){const t={};for(const r in a){const s=a[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t},E=a=>a==="email",w={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:L(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:a=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":a.attrs.name,emoji:a.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"s"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{if(!a.attrs)return{tag:""};const e=new y().escapeHTML,t={...a.attrs},{linktype:r="url"}=a.attrs;if(delete t.linktype,t.href&&(t.href=e(a.attrs.href||"")),E(r)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const s in t.custom)t[s]=t.custom[s];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:a=>({tag:[{tag:"span",attrs:a.attrs}]}),highlight:a=>{var t;return(t=a.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${a.attrs.color};`}}]}:{tag:""}},textStyle:a=>{var t;return(t=a.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${a.attrs.color}`}}]}:{tag:""}}}},j=function(a){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return a&&r.test(a)?a.replace(t,s=>e[s]):a};let S=!1;class R{constructor(e){c(this,"marks");c(this,"nodes");e||(e=w),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},r=!0){if(!S&&r&&(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/"),S=!0),e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(i=>{s+=this.renderNode(i)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field. | ||
The "content" field must be an array of nodes as the type ISbRichtext. | ||
@@ -24,2 +24,2 @@ ISbRichtext: | ||
type: 'doc' | ||
}`),""}optimizeImages(e,t){let r=0,s=0,i="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,s=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`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-Fa-f]{6}/g)||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))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const l=r>0||s>0||n.length>0?`${r}x${s}${n}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,o=>{var h,f;const u=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(u&&u.length>0){const m={srcset:(h=t.srcset)==null?void 0:h.map(p=>{if(typeof p=="number")return`//${u}/m/${p}x0${n} ${p}w`;if(typeof p=="object"&&p.length===2){let $=0,C=0;return typeof p[0]=="number"&&($=p[0]),typeof p[1]=="number"&&(C=p[1]),`//${u}/m/${$}x${C}${n} ${$}w`}}).join(", "),sizes:(f=t.sizes)==null?void 0:f.map(p=>p).join(", ")};let b="";return m.srcset&&(b+=`srcset="${m.srcset}" `),m.sizes&&(b+=`sizes="${m.sizes}" `),o.replace(/<img/g,`<img ${b.trim()}`)}return o})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(s=>{t.push(this.renderNode(s))}):e.text?t.push(j(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&t.push(this.renderClosingTag(i.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let i=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const l=s.attrs[n];l!==null&&(i+=` ${n}="${l}"`)}}return`${i}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.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 x{constructor(e){c(this,"baseURL");c(this,"timeout");c(this,"headers");c(this,"responseInterceptor");c(this,"fetch");c(this,"ejectInterceptor");c(this,"url");c(this,"parameters");c(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=[],r={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(s=>{r.data=s});for(const s of e.headers.entries())t[s[0]]=s[1];return r.headers={...t},r.status=e.status,r.statusText=e.statusText,r}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,r=null;if(e==="get"){const o=new y;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else r=JSON.stringify(this.parameters);const s=new URL(t),i=new AbortController,{signal:n}=i;let l;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const o=await this.fetch(`${s}`,{method:e,headers:this.headers,body:r,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const u=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}catch(o){return{message:o}}}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((r,s)=>{if(t.test(`${e.status}`))return r(e);const i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};s(i)})}}const P="SB-Agent",T={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let R={};const k={};class v{constructor(e,t){c(this,"client");c(this,"maxRetries");c(this,"retriesDelay");c(this,"throttle");c(this,"accessToken");c(this,"cache");c(this,"helpers");c(this,"resolveCounter");c(this,"relations");c(this,"links");c(this,"richTextResolver");c(this,"resolveNestedRelations");c(this,"stringifiedStoriesCache");let r=e.endpoint||t;if(!r){const n=new y().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?r=`${l}://${n(e.region)}/v1`:r=`${l}://${n(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([l,o])=>{s.set(l,o)}),s.has(P)||(s.set(P,T.defaultAgentName),s.set(T.defaultAgentVersion,T.packageVersion));let i=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new _(e.richTextSchema):this.richTextResolver=new _,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=d(this.throttledRequest,i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new y,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new x({baseURL:r,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body&&t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=k[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,r,s,i){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,r,s));return this.cacheResponse(e,n,void 0,i)}get(e,t,r){t||(t={});const s=`/${e}`,i=this.factoryParamOptions(s,t);return this.cacheResponse(s,i,void 0,r)}async getAll(e,t,r,s){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`,l=n.split("/"),o=r||l[l.length-1],u=1,h=await this.makeRequest(n,t,i,u,s),f=h.total?Math.ceil(h.total/i):1,m=await this.helpers.asyncMap(this.helpers.range(u,f),b=>this.makeRequest(n,t,i,b+1,s));return this.helpers.flatMap([h,...m],b=>Object.values(b.data[o]))}post(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t,r))}put(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t,r))}delete(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t,r))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,r){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,r)}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,r){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[r][s.id]?s.story=this._cleanCopy(this.links[r][s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[r][s.uuid]&&(s.story=this._cleanCopy(this.links[r][s.uuid]))}getStoryReference(e,t){return this.relations[e][t]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,r,s){r.indexOf(`${e.component}.${t}`)>-1&&(typeof e[t]=="string"?e[t]=this.getStoryReference(s,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(i=>this.getStoryReference(s,i)).filter(Boolean)))}iterateTree(e,t,r){const s=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)s(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,t,r),this._insertLinks(i,n,r)),s(i[n])}}};s(e.content)}async resolveLinks(e,t,r){let s=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const u=Math.min(i,o+l);n.push(e.link_uuids.slice(o,u))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(h=>{s.push(h)})}else s=e.links;s.forEach(i=>{this.links[r][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,r){let s=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const u=Math.min(i,o+l);n.push(e.rel_uuids.slice(o,u))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{s.push(h)})}else s=e.rels;s&&s.length>0&&s.forEach(i=>{this.relations[r][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,r){var i,n;let s=[];if(this.links[r]={},this.relations[r]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(s=t.resolve_relations.split(",")),await this.resolveRelations(e,t,r)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,r),this.resolveNestedRelations)for(const l in this.relations[r])this.iterateTree(this.relations[r][l],s,r);e.story?this.iterateTree(e.story,s,r):e.stories.forEach(l=>{this.iterateTree(l,s,r)}),this.stringifiedStoriesCache={},delete this.links[r],delete this.relations[r]}async cacheResponse(e,t,r,s){const i=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await n.get(i);if(l)return Promise.resolve(l)}return new Promise(async(l,o)=>{var u;try{const h=await this.throttle("get",e,t,s);if(h.status!==200)return o(h);let f={data:h.data,headers:h.headers};if((u=h.headers)!=null&&u["per-page"]&&(f=Object.assign({},f,{perPage:h.headers["per-page"]?parseInt(h.headers["per-page"]):0,total:h.headers["per-page"]?parseInt(h.headers.total):0})),f.data.story||f.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(f.data,t,`${m}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(i,f),f.data.cv&&t.token&&k[t.token]!=f.data.cv&&(await this.flushCache(),k[t.token]=f.data.cv),l(f)}catch(h){if(h.response&&h.status===429&&(r=typeof r>"u"?0:r+1,r<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,r).then(l).catch(o);o(h)}})}throttledRequest(e,t,r,s){return this.client.setFetchOptions(s),this.client[e](t,r)}cacheVersions(){return k}cacheVersion(){return k[this.accessToken]}setCacheVersion(e){this.accessToken&&(k[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(k[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(R[e])},getAll(){return Promise.resolve(R)},set(e,t){return R[e]=t,Promise.resolve(void 0)},flush(){return R={},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 A=(a,e)=>{for(const t in e)a[t]=e[t]};return A(v,{RichtextResolver:_,SbFetch:x,RichTextSchema:w}),A(v,O),v}); | ||
}`),""}optimizeImages(e,t){let r=0,s=0,i="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,s=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`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-Fa-f]{6}/g)||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))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const l=r>0||s>0||n.length>0?`${r}x${s}${n}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,o=>{var u,f;const h=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(h&&h.length>0){const m={srcset:(u=t.srcset)==null?void 0:u.map(p=>{if(typeof p=="number")return`//${h}/m/${p}x0${n} ${p}w`;if(typeof p=="object"&&p.length===2){let $=0,C=0;return typeof p[0]=="number"&&($=p[0]),typeof p[1]=="number"&&(C=p[1]),`//${h}/m/${$}x${C}${n} ${$}w`}}).join(", "),sizes:(f=t.sizes)==null?void 0:f.map(p=>p).join(", ")};let v="";return m.srcset&&(v+=`srcset="${m.srcset}" `),m.sizes&&(v+=`sizes="${m.sizes}" `),o.replace(/<img/g,`<img ${v.trim()}`)}return o})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(s=>{t.push(this.renderNode(s))}):e.text?t.push(j(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&t.push(this.renderClosingTag(i.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let i=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const l=s.attrs[n];l!==null&&(i+=` ${n}="${l}"`)}}return`${i}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.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 x{constructor(e){c(this,"baseURL");c(this,"timeout");c(this,"headers");c(this,"responseInterceptor");c(this,"fetch");c(this,"ejectInterceptor");c(this,"url");c(this,"parameters");c(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=[],r={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(s=>{r.data=s});for(const s of e.headers.entries())t[s[0]]=s[1];return r.headers={...t},r.status=e.status,r.statusText=e.statusText,r}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,r=null;if(e==="get"){const o=new y;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else r=JSON.stringify(this.parameters);const s=new URL(t),i=new AbortController,{signal:n}=i;let l;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const o=await this.fetch(`${s}`,{method:e,headers:this.headers,body:r,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const h=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}catch(o){return{message:o}}}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((r,s)=>{if(t.test(`${e.status}`))return r(e);const i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};s(i)})}}const P="SB-Agent",_={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let b={};const k={};class T{constructor(e,t){c(this,"client");c(this,"maxRetries");c(this,"retriesDelay");c(this,"throttle");c(this,"accessToken");c(this,"cache");c(this,"helpers");c(this,"resolveCounter");c(this,"relations");c(this,"links");c(this,"richTextResolver");c(this,"resolveNestedRelations");c(this,"stringifiedStoriesCache");let r=e.endpoint||t;if(!r){const n=new y().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?r=`${l}://${n(e.region)}/v1`:r=`${l}://${n(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([l,o])=>{s.set(l,o)}),s.has(P)||(s.set(P,_.defaultAgentName),s.set(_.defaultAgentVersion,_.packageVersion));let i=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new R(e.richTextSchema):this.richTextResolver=new R,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=d(this.throttledRequest,i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new y,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new x({baseURL:r,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body&&t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=k[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,r,s,i){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,r,s));return this.cacheResponse(e,n,void 0,i)}get(e,t,r){t||(t={});const s=`/${e}`,i=this.factoryParamOptions(s,t);return this.cacheResponse(s,i,void 0,r)}async getAll(e,t,r,s){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),l=r??n.substring(n.lastIndexOf("/")+1),o=1,h=await this.makeRequest(n,t,i,o,s),u=h.total?Math.ceil(h.total/i):1,f=await this.helpers.asyncMap(this.helpers.range(o,u),m=>this.makeRequest(n,t,i,m+1,s));return this.helpers.flatMap([h,...f],m=>Object.values(m.data[l]))}post(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t,r))}put(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t,r))}delete(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t,r))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,r){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,r)}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,r){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[r][s.id]?s.story=this._cleanCopy(this.links[r][s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[r][s.uuid]&&(s.story=this._cleanCopy(this.links[r][s.uuid]))}getStoryReference(e,t){return this.relations[e][t]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,r,s){r.indexOf(`${e.component}.${t}`)>-1&&(typeof e[t]=="string"?e[t]=this.getStoryReference(s,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(i=>this.getStoryReference(s,i)).filter(Boolean)))}iterateTree(e,t,r){const s=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)s(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,t,r),this._insertLinks(i,n,r)),s(i[n])}}};s(e.content)}async resolveLinks(e,t,r){let s=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const h=Math.min(i,o+l);n.push(e.link_uuids.slice(o,h))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(u=>{s.push(u)})}else s=e.links;s.forEach(i=>{this.links[r][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,r){let s=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const h=Math.min(i,o+l);n.push(e.rel_uuids.slice(o,h))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(u=>{s.push(u)})}else s=e.rels;s&&s.length>0&&s.forEach(i=>{this.relations[r][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,r){var i,n;let s=[];if(this.links[r]={},this.relations[r]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(s=t.resolve_relations.split(",")),await this.resolveRelations(e,t,r)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,r),this.resolveNestedRelations)for(const l in this.relations[r])this.iterateTree(this.relations[r][l],s,r);e.story?this.iterateTree(e.story,s,r):e.stories.forEach(l=>{this.iterateTree(l,s,r)}),this.stringifiedStoriesCache={},delete this.links[r],delete this.relations[r]}async cacheResponse(e,t,r,s){const i=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await n.get(i);if(l)return Promise.resolve(l)}return new Promise(async(l,o)=>{var h;try{const u=await this.throttle("get",e,t,s);if(u.status!==200)return o(u);let f={data:u.data,headers:u.headers};if((h=u.headers)!=null&&h["per-page"]&&(f=Object.assign({},f,{perPage:u.headers["per-page"]?parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?parseInt(u.headers.total):0})),f.data.story||f.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(f.data,t,`${m}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(i,f),f.data.cv&&t.token&&k[t.token]!=f.data.cv&&(await this.flushCache(),k[t.token]=f.data.cv),l(f)}catch(u){if(u.response&&u.status===429&&(r=typeof r>"u"?0:r+1,r<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,r).then(l).catch(o);o(u)}})}throttledRequest(e,t,r,s){return this.client.setFetchOptions(s),this.client[e](t,r)}cacheVersions(){return k}cacheVersion(){return k[this.accessToken]}setCacheVersion(e){this.accessToken&&(k[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(k[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(b[e])},getAll(){return Promise.resolve(b)},set(e,t){return b[e]=t,Promise.resolve(void 0)},flush(){return b={},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 A=(a,e)=>{for(const t in e)a[t]=e[t]};return A(T,{RichtextResolver:R,SbFetch:x,RichTextSchema:w}),A(T,O),T}); |
{ | ||
"name": "storyblok-js-client", | ||
"module": "./dist/index.mjs", | ||
"version": "6.10.0", | ||
"version": "6.10.1", | ||
"packageManager": "pnpm@9.1.4", | ||
@@ -6,0 +6,0 @@ "description": "Universal JavaScript SDK for Storyblok's API", |
@@ -292,2 +292,21 @@ import StoryblokClient from '.' | ||
}) | ||
it('should get all stories if the slug is passed with the trailing slash', async () => { | ||
const mockMakeRequest = vi.fn().mockResolvedValue({ | ||
data: { | ||
stories: [ | ||
{ id: 1, name: 'Test Story 1' }, | ||
{ id: 2, name: 'Test Story 2' }, | ||
], | ||
}, | ||
total: 2, | ||
status: 200, | ||
}) | ||
client.makeRequest = mockMakeRequest | ||
const result = await client.getAll('cdn/stories/', { version: 'draft' }) | ||
expect(result).toEqual([ | ||
{ id: 1, name: 'Test Story 1' }, | ||
{ id: 2, name: 'Test Story 2' }, | ||
]) | ||
}) | ||
}) | ||
@@ -294,0 +313,0 @@ |
@@ -246,5 +246,4 @@ import throttledQueue from './throttlePromise' | ||
const perPage = params?.per_page || 25 | ||
const url = `/${slug}` | ||
const urlParts = url.split('/') | ||
const e = entity || urlParts[urlParts.length - 1] | ||
const url = `/${slug}`.replace(/\/$/, '') | ||
const e = entity ?? url.substring(url.lastIndexOf('/') + 1) | ||
@@ -251,0 +250,0 @@ const firstPage = 1 |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
205680
35
5045