Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

storyblok-js-client

Package Overview
Dependencies
Maintainers
7
Versions
197
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

storyblok-js-client - npm Package Compare versions

Comparing version 5.3.8 to 5.4.0

2

dist/index.umd.js

@@ -1,1 +0,1 @@

(function(d,u){typeof exports=="object"&&typeof module<"u"?module.exports=u():typeof define=="function"&&define.amd?define(u):(d=typeof globalThis<"u"?globalThis:d||self,d.StoryblokJSClient=u())})(this,function(){"use strict";var P=Object.defineProperty;var C=(d,u,p)=>u in d?P(d,u,{enumerable:!0,configurable:!0,writable:!0,value:p}):d[u]=p;var h=(d,u,p)=>(C(d,typeof u!="symbol"?u+"":u,p),p);function d(a){return!(a!==a||a===1/0||a===-1/0)}function u(a,e,t){if(!d(e))throw new TypeError("Expected `limit` to be a finite number");if(!d(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const o=function(){n++;const i=setTimeout(function(){n--,s.length>0&&o(),r=r.filter(function(f){return f!==i})},t);r.indexOf(i)<0&&r.push(i);const c=s.shift();c.resolve(a.apply(c.self,c.args))},l=function(...i){const c=this;return new Promise(function(f,_){s.push({resolve:f,reject:_,args:i,self:c}),n<e&&o()})};return l.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(i){i.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}const p=function(a,e){const t={};for(const s in a){const r=a[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},x=a=>a==="email",b={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:p(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{const e={...a.attrs},{linktype:t="url"}=a.attrs;return x(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]})}},S=function(a){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=RegExp(t.source);return a&&s.test(a)?a.replace(t,r=>e[r]):a};class y{constructor(e){h(this,"marks");h(this,"nodes");e||(e=b),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e){if(e&&e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(s=>{t+=this.renderNode(s)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&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(S(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html&&t.push(s.html),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let n=`<${r.tag}`;if(r.attrs)for(const o in r.attrs){const l=r.attrs[o];l!==null&&(n+=` ${o}="${l}"`)}return`${n}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.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)}}class v{constructor(){h(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));h(this,"delay",e=>new Promise(t=>setTimeout(t,e)));h(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));h(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,o)=>o*r+e)});h(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));h(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const o=e[n],l=s?"":encodeURIComponent(n);let i;typeof o=="object"?i=this.stringify(o,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(o)):i=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(o),r.push(i)}return r.join("&")}}const $=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:v},Symbol.toStringTag,{value:"Module"}));class R{constructor(e){h(this,"baseURL");h(this,"timeout");h(this,"headers");h(this,"responseInterceptor");h(this,"fetch");h(this,"ejectInterceptor");h(this,"url");h(this,"parameters");this.baseURL=e.baseURL,this.headers=e.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={}}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 i=new v;t=`${this.baseURL}${this.url}?${i.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 i=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o});this.timeout&&clearTimeout(l);const c=await this._responseHandler(i);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(i){return{message:i}}}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:new Error(e.statusText),status:e.status,response:e.data.error||e.data.slug};r(n)})}}let k={};const g={};class m{constructor(e,t){h(this,"client");h(this,"maxRetries");h(this,"throttle");h(this,"accessToken");h(this,"cache");h(this,"helpers");h(this,"relations");h(this,"links");h(this,"richTextResolver");h(this,"resolveNestedRelations");if(!t){const n=e.region?`-${e.region}`:"",o=e.https===!1?"http":"https";e.oauthToken?t=`${o}://api${n}.storyblok.com/v1`:t=`${o}://api${n}.storyblok.com/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((n,o)=>{e.headers&&e.headers[o]&&s.set(o,e.headers[o])});let r=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new y(e.richTextSchema):this.richTextResolver=new y,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries,this.throttle=u(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new v,this.resolveNestedRelations=!1,this.client=new R({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,n=`/${e}`,o=n.split("/"),l=s||o[o.length-1],i=1,c=await this.makeRequest(n,t,r,i),f=c.total?Math.ceil(c.total/r):1,_=await this.helpers.asyncMap(this.helpers.range(i,f),T=>this.makeRequest(n,t,r,T+1));return this.helpers.flatMap([c,..._],T=>Object.values(T.data[l]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[s.id]?s.story=this._cleanCopy(this.links[s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[s.uuid]&&(s.story=this._cleanCopy(this.links[s.uuid]))}_insertRelations(e,t,s){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t]&&e[t].constructor===Array){const r=[];e[t].forEach(n=>{this.relations[n]&&r.push(this._cleanCopy(this.relations[n]))}),e[t]=r}}}iterateTree(e,t){const s=r=>{if(r!=null){if(r.constructor===Array)for(let n=0;n<r.length;n++)s(r[n]);else if(r.constructor===Object){if(r._stopResolving)return;for(const n in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,n,t),this._insertLinks(r,n)),s(r[n])}}};s(e.content)}async resolveLinks(e,t){let s=[];if(e.link_uuids){const r=e.link_uuids.length,n=[],o=50;for(let l=0;l<r;l+=o){const i=Math.min(r,l+o);n.push(e.link_uuids.slice(l,i))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:o,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.links;s.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(e,t){let s=[];if(e.rel_uuids){const r=e.rel_uuids.length,n=[],o=50;for(let l=0;l<r;l+=o){const i=Math.min(r,l+o);n.push(e.rel_uuids.slice(l,i))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:o,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(e,t){var r,n;let s=[];if(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)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const o in this.relations)this.iterateTree(this.relations[o],s);e.story?this.iterateTree(e.story,s):e.stories.forEach(o=>{this.iterateTree(o,s)})}cacheResponse(e,t,s){return new Promise((r,n)=>{const o=this.helpers.stringify({url:e,params:t}),l=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const i=l.get(o);if(i)return r(i)}try{(async()=>{var f;const i=await this.throttle("get",e,t);let c={data:i.data,headers:i.headers};if((f=i.headers)!=null&&f["per-page"]&&(c=Object.assign({},c,{perPage:i.headers["per-page"]?parseInt(i.headers["per-page"]):0,total:i.headers["per-page"]?parseInt(i.headers.total):0})),i.status!=200)return n(i);(c.data.story||c.data.stories)&&await this.resolveStories(c.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&l.set(o,c),c.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=c.data.cv&&this.flushCache(),g[t.token]=c.data.cv),r(c)})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return k[e]},getAll(){return k},set(e,t){k[e]=t},flush(){k={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}flushCache(){return this.cacheProvider().flush(),this}}const w=(a,e)=>{for(const t in e)a[t]=e[t]};return w(m,{RichtextResolver:y,SbFetch:R,RichTextSchema:b}),w(m,$),m});
(function(d,u){typeof exports=="object"&&typeof module<"u"?module.exports=u():typeof define=="function"&&define.amd?define(u):(d=typeof globalThis<"u"?globalThis:d||self,d.StoryblokJSClient=u())})(this,function(){"use strict";var $=Object.defineProperty;var C=(d,u,p)=>u in d?$(d,u,{enumerable:!0,configurable:!0,writable:!0,value:p}):d[u]=p;var h=(d,u,p)=>(C(d,typeof u!="symbol"?u+"":u,p),p);function d(a){return!(a!==a||a===1/0||a===-1/0)}function u(a,e,t){if(!d(e))throw new TypeError("Expected `limit` to be a finite number");if(!d(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const i=function(){n++;const o=setTimeout(function(){n--,s.length>0&&i(),r=r.filter(function(f){return f!==o})},t);r.indexOf(o)<0&&r.push(o);const c=s.shift();c.resolve(a.apply(c.self,c.args))},l=function(...o){const c=this;return new Promise(function(f,_){s.push({resolve:f,reject:_,args:o,self:c}),n<e&&i()})};return l.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}const p=function(a,e){const t={};for(const s in a){const r=a[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},P=a=>a==="email",b={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:p(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{const e={...a.attrs},{linktype:t="url"}=a.attrs;return P(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]})}},x=function(a){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=RegExp(t.source);return a&&s.test(a)?a.replace(t,r=>e[r]):a};class k{constructor(e){h(this,"marks");h(this,"nodes");e||(e=b),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e){if(e&&e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(s=>{t+=this.renderNode(s)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&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(x(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html&&t.push(s.html),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let n=`<${r.tag}`;if(r.attrs)for(const i in r.attrs){const l=r.attrs[i];l!==null&&(n+=` ${i}="${l}"`)}return`${n}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.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)}}class v{constructor(){h(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));h(this,"delay",e=>new Promise(t=>setTimeout(t,e)));h(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));h(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,i)=>i*r+e)});h(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));h(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const i=e[n],l=s?"":encodeURIComponent(n);let o;typeof i=="object"?o=this.stringify(i,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(i)):o=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(i),r.push(o)}return r.join("&")}}const S=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:v},Symbol.toStringTag,{value:"Module"}));class R{constructor(e){h(this,"baseURL");h(this,"timeout");h(this,"headers");h(this,"responseInterceptor");h(this,"fetch");h(this,"ejectInterceptor");h(this,"url");h(this,"parameters");this.baseURL=e.baseURL,this.headers=e.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={}}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 o=new v;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:i}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const o=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:i});this.timeout&&clearTimeout(l);const c=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(o){return{message:o}}}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:new Error(e.statusText),status:e.status,response:e.data.error||e.data.slug};r(n)})}}let y={};const g={};class m{constructor(e,t){h(this,"client");h(this,"maxRetries");h(this,"throttle");h(this,"accessToken");h(this,"cache");h(this,"helpers");h(this,"relations");h(this,"links");h(this,"richTextResolver");h(this,"resolveNestedRelations");if(!t){const n=e.region?`-${e.region}`:"",i=e.https===!1?"http":"https";e.oauthToken?t=`${i}://api${n}.storyblok.com/v1`:t=`${i}://api${n}.storyblok.com/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((n,i)=>{e.headers&&e.headers[i]&&s.set(i,e.headers[i])});let r=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries,this.throttle=u(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new v,this.resolveNestedRelations=!1,this.client=new R({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,n=`/${e}`,i=n.split("/"),l=s||i[i.length-1],o=1,c=await this.makeRequest(n,t,r,o),f=c.total?Math.ceil(c.total/r):1,_=await this.helpers.asyncMap(this.helpers.range(o,f),T=>this.makeRequest(n,t,r,T+1));return this.helpers.flatMap([c,..._],T=>Object.values(T.data[l]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[s.id]?s.story=this._cleanCopy(this.links[s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[s.uuid]&&(s.story=this._cleanCopy(this.links[s.uuid]))}_insertRelations(e,t,s){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t]&&e[t].constructor===Array){const r=[];e[t].forEach(n=>{this.relations[n]&&r.push(this._cleanCopy(this.relations[n]))}),e[t]=r}}}iterateTree(e,t){const s=r=>{if(r!=null){if(r.constructor===Array)for(let n=0;n<r.length;n++)s(r[n]);else if(r.constructor===Object){if(r._stopResolving)return;for(const n in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,n,t),this._insertLinks(r,n)),s(r[n])}}};s(e.content)}async resolveLinks(e,t){let s=[];if(e.link_uuids){const r=e.link_uuids.length,n=[],i=50;for(let l=0;l<r;l+=i){const o=Math.min(r,l+i);n.push(e.link_uuids.slice(l,o))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.links;s.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(e,t){let s=[];if(e.rel_uuids){const r=e.rel_uuids.length,n=[],i=50;for(let l=0;l<r;l+=i){const o=Math.min(r,l+i);n.push(e.rel_uuids.slice(l,o))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(e,t){var r,n;let s=[];if(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)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const i in this.relations)this.iterateTree(this.relations[i],s);e.story?this.iterateTree(e.story,s):e.stories.forEach(i=>{this.iterateTree(i,s)})}async cacheResponse(e,t,s){const r=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 i=await n.get(r);if(i)return Promise.resolve(i)}return new Promise((i,l)=>{try{(async()=>{var f;const o=await this.throttle("get",e,t);let c={data:o.data,headers:o.headers};if((f=o.headers)!=null&&f["per-page"]&&(c=Object.assign({},c,{perPage:o.headers["per-page"]?parseInt(o.headers["per-page"]):0,total:o.headers["per-page"]?parseInt(o.headers.total):0})),o.status!=200)return l(o);(c.data.story||c.data.stories)&&await this.resolveStories(c.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(r,c),c.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=c.data.cv&&await this.flushCache(),g[t.token]=c.data.cv),i(c)})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(y[e])},getAll(){return Promise.resolve(y)},set(e,t){return y[e]=t,Promise.resolve(void 0)},flush(){return y={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},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}}const w=(a,e)=>{for(const t in e)a[t]=e[t]};return w(m,{RichtextResolver:k,SbFetch:R,RichTextSchema:b}),w(m,S),m});

@@ -65,4 +65,4 @@ import { ISbStoriesParams, ISbConfig, ISbResult, ISbStories, ISbStory, ISbStoryData, ISbStoryParams, ISbContentMangmntAPI } from './interfaces';

private cacheProvider;
flushCache(): this;
flushCache(): Promise<this>;
}
export default Storyblok;

@@ -137,5 +137,15 @@ import { ResponseFn } from './sbFetch';

}
export interface IMemoryType extends ISbResult {
[key: string]: any;
}
export interface ICacheProvider {
get: (key: string) => Promise<IMemoryType | void>;
set: (key: string, content: ISbResult) => Promise<void>;
getAll: () => Promise<IMemoryType | void>;
flush: () => Promise<void>;
}
export interface ISbCache {
type?: 'none' | 'memory';
type?: 'none' | 'memory' | 'custom';
clear?: 'auto' | 'manual';
custom?: ICacheProvider;
}

@@ -142,0 +152,0 @@ export interface ISbConfig {

{
"name": "storyblok-js-client",
"version": "5.3.8",
"version": "5.4.0",
"description": "Universal JavaScript SDK for Storyblok's API",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -20,2 +20,4 @@ import throttledQueue from './throttlePromise'

ThrottleFn,
IMemoryType,
ICacheProvider,
} from './interfaces'

@@ -43,6 +45,2 @@

interface IMemoryType extends ISbResult {
[key: string]: any
}
interface ISbFlatMapped {

@@ -52,9 +50,2 @@ data: any

interface ICacheProvider {
get: (key: string) => IMemoryType | void
set: (key: string, content: ISbResult) => void
getAll: () => IMemoryType | void
flush: () => void
}
interface ISbResponseData {

@@ -490,3 +481,3 @@ link_uuids: string[]

private cacheResponse(
private async cacheResponse(
url: string,

@@ -500,17 +491,17 @@ params: ISbStoriesParams,

return new Promise((resolve, reject) => {
const cacheKey = this.helpers.stringify({ url: url, params: params })
const provider = this.cacheProvider()
const cacheKey = this.helpers.stringify({ url: url, params: params })
const provider = this.cacheProvider()
if (this.cache.clear === 'auto' && params.version === 'draft') {
this.flushCache()
}
if (this.cache.clear === 'auto' && params.version === 'draft') {
await this.flushCache()
}
if (params.version === 'published' && url != '/cdn/spaces/me') {
const cache = provider.get(cacheKey)
if (cache) {
return resolve(cache)
}
if (params.version === 'published' && url != '/cdn/spaces/me') {
const cache = await provider.get(cacheKey)
if (cache) {
return Promise.resolve(cache)
}
}
return new Promise((resolve, reject) => {
try {

@@ -542,3 +533,3 @@ ;(async () => {

if (params.version === 'published' && url != '/cdn/spaces/me') {
provider.set(cacheKey, response)
await provider.set(cacheKey, response)
}

@@ -551,3 +542,3 @@

) {
this.flushCache()
await this.flushCache()
}

@@ -605,27 +596,32 @@

get(key: string) {
return memory[key]
return Promise.resolve(memory[key])
},
getAll() {
return memory as IMemoryType
return Promise.resolve(memory as IMemoryType)
},
set(key: string, content: ISbResult) {
memory[key] = content
return Promise.resolve(undefined)
},
flush() {
memory = {}
return Promise.resolve(undefined)
},
}
case 'custom':
if (this.cache.custom) return this.cache.custom
// eslint-disable-next-line no-fallthrough
default:
return {
get() {
return undefined
return Promise.resolve(undefined)
},
getAll() {
return undefined
return Promise.resolve(undefined)
},
set() {
return undefined
return Promise.resolve(undefined)
},
flush() {
return undefined
return Promise.resolve(undefined)
},

@@ -636,4 +632,4 @@ }

public flushCache(): this {
this.cacheProvider().flush()
public async flushCache(): Promise<this> {
await this.cacheProvider().flush()
return this

@@ -640,0 +636,0 @@ }

@@ -148,5 +148,17 @@ import { ResponseFn } from './sbFetch'

export interface IMemoryType extends ISbResult {
[key: string]: any
}
export interface ICacheProvider {
get: (key: string) => Promise<IMemoryType | void>
set: (key: string, content: ISbResult) => Promise<void>
getAll: () => Promise<IMemoryType | void>
flush: () => Promise<void>
}
export interface ISbCache {
type?: 'none' | 'memory'
type?: 'none' | 'memory' | 'custom'
clear?: 'auto' | 'manual'
custom?: ICacheProvider
}

@@ -153,0 +165,0 @@

@@ -61,3 +61,3 @@ /* eslint-disable no-undef */

let provider = Storyblok.cacheProvider()
provider.flush()
await provider.flush()
await Storyblok.get('cdn/spaces/me')

@@ -64,0 +64,0 @@ expect(Object.values(provider.getAll()).length).toBe(0)

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc