storyblok-js-client
Advanced tools
Comparing version 5.2.1 to 5.2.2
@@ -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 S=Object.defineProperty;var O=(d,u,p)=>u in d?S(d,u,{enumerable:!0,configurable:!0,writable:!0,value:p}):d[u]=p;var a=(d,u,p)=>(O(d,typeof u!="symbol"?u+"":u,p),p);function d(i){return!(i!==i||i===1/0||i===-1/0)}function u(i,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 c=function(){n++;const l=setTimeout(function(){n--,s.length>0&&c(),r=r.filter(function(f){return f!==l})},t);r.indexOf(l)<0&&r.push(l);const h=s.shift();h.resolve(i.apply(h.self,h.args))},o=function(...l){const h=this;return new Promise(function(f,_){s.push({resolve:f,reject:_,args:l,self:h}),n<e&&c()})};return o.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(l){l.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},o}const p=function(i,e){const t={};for(const s in i){const r=i[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},E=i=>i==="email",R={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:i=>({tag:`h${i.attrs.level}`}),image:i=>({singleTag:[{tag:"img",attrs:p(i.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:i=>{const e={...i.attrs},{linktype:t="url"}=i.attrs;return E(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:i=>({tag:[{tag:"span",attrs:i.attrs}]})}},x=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};class v{constructor(e){a(this,"marks");a(this,"nodes");e||(e=R),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 c in r.attrs){const o=r.attrs[c];o!==null&&(n+=` ${c}="${o}"`)}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 T{constructor(){a(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);a(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));a(this,"delay",e=>new Promise(t=>setTimeout(t,e)));a(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));a(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,c)=>c*r+e)});a(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));a(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 c=e[n],o=s?"":encodeURIComponent(n);let l;typeof c=="object"?l=this.stringify(c,t?t+encodeURIComponent("["+o+"]"):o,Array.isArray(c)):l=(t?t+encodeURIComponent("["+o+"]"):o)+"="+encodeURIComponent(c),r.push(l)}return r.join("&")}}const P=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:T},Symbol.toStringTag,{value:"Module"}));var k=(i=>(i.GET="get",i.DELETE="delete",i.POST="post",i.PUT="put",i))(k||{});class w{constructor(e){a(this,"baseURL");a(this,"timeout");a(this,"headers");a(this,"responseInterceptor");a(this,"fetch");a(this,"ejectInterceptor");a(this,"url");a(this,"parameters");var t;this.baseURL=e.baseURL,this.timeout=e.timeout?e.timeout*1e3:1e3,this.headers=e.headers||[],this.responseInterceptor=e.responseInterceptor,this.fetch=(t=e.fetch)!=null?t:fetch,this.ejectInterceptor=!1,this.url="",this.parameters={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.GET)}post(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.POST)}put(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.PUT)}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.DELETE)}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};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){const t=new URL(`${this.baseURL}${this.url}`);let s=null;if(e==="get"){const o=new T;t.search=o.stringify(this.parameters)}else s=JSON.stringify(this.parameters);const r=new AbortController,{signal:n}=r,c=setTimeout(()=>r.abort(),this.timeout);try{const o=await this.fetch(`${t}`,{method:e,headers:this.headers,body:s,signal:n});clearTimeout(c);const l=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(o){return o}}eject(){this.ejectInterceptor=!0}_statusHandler(e){if(/20[01]/g.test(`${e.status}`))return e;throw{message:new Error(e.statusText||`status: ${e.status}`),response:e}}}let y={};const g={};class m{constructor(e,t){a(this,"client");a(this,"maxRetries");a(this,"throttle");a(this,"accessToken");a(this,"cache");a(this,"helpers");a(this,"relations");a(this,"links");a(this,"richTextResolver");a(this,"resolveNestedRelations");if(!t){const n=e.region?`-${e.region}`:"",c=e.https===!1?"http":"https";e.oauthToken?t=`${c}://api${n}.storyblok.com/v1`:t=`${c}://api${n}.storyblok.com/v2`}const s=Object.assign({"Content-Type":"application/json"},e.headers);let r=5;e.oauthToken&&(s.Authorization=e.oauthToken,r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new v(e.richTextSchema):this.richTextResolver=new v,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 T,this.resolveNestedRelations=!1,this.client=new w({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}`,c=n.split("/"),o=s||c[c.length-1],l=1,h=await this.makeRequest(n,t,r,l),f=h.total?Math.ceil(h.total/r):1,_=await this.helpers.asyncMap(this.helpers.range(l,f),b=>this.makeRequest(n,t,r,b+1));return this.helpers.flatMap([h,..._],b=>Object.values(b.data[o]))}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=[],c=50;for(let o=0;o<r;o+=c){const l=Math.min(r,o+c);n.push(e.link_uuids.slice(o,l))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(h=>{s.push(h)})}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=[],c=50;for(let o=0;o<r;o+=c){const l=Math.min(r,o+c);n.push(e.rel_uuids.slice(o,l))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(h=>{s.push(h)})}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&&(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?void 0:r.length)||((n=e.link_uuids)==null?void 0:n.length))&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const c in this.relations)this.iterateTree(this.relations[c],s);e.story?this.iterateTree(e.story,s):e.stories.forEach(c=>{this.iterateTree(c,s)})}cacheResponse(e,t,s){return new Promise((r,n)=>{const c=this.helpers.stringify({url:e,params:t}),o=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=o.get(c);if(l)return r(l)}try{(async()=>{var f;const l=await this.throttle("get",e,t);let h={data:l.data,headers:l.headers};if((f=l.headers)!=null&&f["per-page"]&&(h=Object.assign({},h,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),l.status!=200)return n(l);(h.data.story||h.data.stories)&&await this.resolveStories(h.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&o.set(c,h),h.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=h.data.cv&&this.flushCache(),g[t.token]=h.data.cv),r(h)})()}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 y[e]},getAll(){return y},set(e,t){y[e]=t},flush(){y={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}flushCache(){return this.cacheProvider().flush(),this}}const $=(i,e)=>{for(const t in e)i[t]=e[t]};return $(m,{RichtextResolver:v,SbFetch:w,RichTextSchema:R}),$(m,P),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 O=Object.defineProperty;var P=(d,u,p)=>u in d?O(d,u,{enumerable:!0,configurable:!0,writable:!0,value:p}):d[u]=p;var a=(d,u,p)=>(P(d,typeof u!="symbol"?u+"":u,p),p);function d(c){return!(c!==c||c===1/0||c===-1/0)}function u(c,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 l=function(){n++;const o=setTimeout(function(){n--,s.length>0&&l(),r=r.filter(function(f){return f!==o})},t);r.indexOf(o)<0&&r.push(o);const h=s.shift();h.resolve(c.apply(h.self,h.args))},i=function(...o){const h=this;return new Promise(function(f,_){s.push({resolve:f,reject:_,args:o,self:h}),n<e&&l()})};return i.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},i}const p=function(c,e){const t={};for(const s in c){const r=c[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},$=c=>c==="email",b={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:c=>({tag:["pre",{tag:"code",attrs:c.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:c=>({tag:`h${c.attrs.level}`}),image:c=>({singleTag:[{tag:"img",attrs:p(c.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:c=>{const e={...c.attrs},{linktype:t="url"}=c.attrs;return $(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:c=>({tag:[{tag:"span",attrs:c.attrs}]})}},x=function(c){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return c&&s.test(c)?c.replace(t,r=>e[r]):c};class y{constructor(e){a(this,"marks");a(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 l in r.attrs){const i=r.attrs[l];i!==null&&(n+=` ${l}="${i}"`)}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(){a(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);a(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));a(this,"delay",e=>new Promise(t=>setTimeout(t,e)));a(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));a(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,l)=>l*r+e)});a(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));a(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 l=e[n],i=s?"":encodeURIComponent(n);let o;typeof l=="object"?o=this.stringify(l,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(l)):o=(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(l),r.push(o)}return r.join("&")}}const S=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:v},Symbol.toStringTag,{value:"Module"}));class R{constructor(e){a(this,"baseURL");a(this,"timeout");a(this,"headers");a(this,"responseInterceptor");a(this,"fetch");a(this,"ejectInterceptor");a(this,"url");a(this,"parameters");var t;this.baseURL=e.baseURL,this.timeout=e.timeout?e.timeout*1e3:1e3,this.headers=e.headers||[],this.responseInterceptor=e.responseInterceptor,this.fetch=(t=e.fetch)!=null?t:fetch,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:""};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){const t=new URL(`${this.baseURL}${this.url}`);let s=null;if(e==="get"){const i=new v;t.search=i.stringify(this.parameters)}else s=JSON.stringify(this.parameters);const r=new AbortController,{signal:n}=r,l=setTimeout(()=>r.abort(),this.timeout);try{const i=await this.fetch(`${t}`,{method:e,headers:this.headers,body:s,signal:n});clearTimeout(l);const o=await this._responseHandler(i);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(o)):this._statusHandler(o)}catch(i){return i}}eject(){this.ejectInterceptor=!0}_statusHandler(e){if(/20[01]/g.test(`${e.status}`))return e;throw{message:new Error(e.statusText||`status: ${e.status}`),response:e}}}let k={};const g={};class m{constructor(e,t){a(this,"client");a(this,"maxRetries");a(this,"throttle");a(this,"accessToken");a(this,"cache");a(this,"helpers");a(this,"relations");a(this,"links");a(this,"richTextResolver");a(this,"resolveNestedRelations");if(!t){const n=e.region?`-${e.region}`:"",l=e.https===!1?"http":"https";e.oauthToken?t=`${l}://api${n}.storyblok.com/v1`:t=`${l}://api${n}.storyblok.com/v2`}const s=Object.assign({"Content-Type":"application/json"},e.headers);let r=5;e.oauthToken&&(s.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}`,l=n.split("/"),i=s||l[l.length-1],o=1,h=await this.makeRequest(n,t,r,o),f=h.total?Math.ceil(h.total/r):1,_=await this.helpers.asyncMap(this.helpers.range(o,f),T=>this.makeRequest(n,t,r,T+1));return this.helpers.flatMap([h,..._],T=>Object.values(T.data[i]))}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=[],l=50;for(let i=0;i<r;i+=l){const o=Math.min(r,i+l);n.push(e.link_uuids.slice(i,o))}for(let i=0;i<n.length;i++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[i].join(",")})).data.stories.forEach(h=>{s.push(h)})}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=[],l=50;for(let i=0;i<r;i+=l){const o=Math.min(r,i+l);n.push(e.rel_uuids.slice(i,o))}for(let i=0;i<n.length;i++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[i].join(",")})).data.stories.forEach(h=>{s.push(h)})}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&&(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?void 0:r.length)||((n=e.link_uuids)==null?void 0:n.length))&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const l in this.relations)this.iterateTree(this.relations[l],s);e.story?this.iterateTree(e.story,s):e.stories.forEach(l=>{this.iterateTree(l,s)})}cacheResponse(e,t,s){return new Promise((r,n)=>{const l=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const o=i.get(l);if(o)return r(o)}try{(async()=>{var f;const o=await this.throttle("get",e,t);let h={data:o.data,headers:o.headers};if((f=o.headers)!=null&&f["per-page"]&&(h=Object.assign({},h,{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 n(o);(h.data.story||h.data.stories)&&await this.resolveStories(h.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&i.set(l,h),h.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=h.data.cv&&this.flushCache(),g[t.token]=h.data.cv),r(h)})()}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=(c,e)=>{for(const t in e)c[t]=e[t]};return w(m,{RichtextResolver:y,SbFetch:R,RichTextSchema:b}),w(m,S),m}); |
import Client from './index'; | ||
export default Client; | ||
export * from './enum'; | ||
export * from './constants'; | ||
export * from './interfaces'; | ||
@@ -5,0 +5,0 @@ export { default as RichtextResolver } from './richTextResolver'; |
{ | ||
"name": "storyblok-js-client", | ||
"version": "5.2.1", | ||
"version": "5.2.2", | ||
"description": "Universal JavaScript SDK for Storyblok's API", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
@@ -103,3 +103,3 @@ <div align="center"> | ||
We added TypeScript to our codebase, improving our code quality and assuring the correct implementation from the client's side. This change will probably break your code, because your Storyblok client's current implementation is possibly sending the wrong types to the source. | ||
All the types are declared under `types`. If you use an IDE to code, you'll be able to hover the problematic cause and see what is being expected from the type. Yet, you can keep using our version without TypeScript. | ||
If you use an IDE to code, you'll be able to hover the problematic cause and see what is being expected from the type. Yet, you can keep using our version without TypeScript. | ||
@@ -106,0 +106,0 @@ ### Axios removal - Version 5 |
@@ -5,3 +5,3 @@ import Client from './index' | ||
export default Client | ||
export * from './enum' | ||
export * from './constants' | ||
export * from './interfaces' | ||
@@ -8,0 +8,0 @@ export { default as RichtextResolver } from './richTextResolver' |
@@ -6,3 +6,3 @@ import throttledQueue from './throttlePromise' | ||
import { Method } from './enum' | ||
import Method from './constants' | ||
import { | ||
@@ -67,7 +67,10 @@ ISbStoriesParams, | ||
enum Version { | ||
V1 = 'v1', | ||
V2 = 'v2', | ||
} | ||
const VERSION = { | ||
V1: 'v1', | ||
V2: 'v2', | ||
} as const | ||
type ObjectValues<T> = T[keyof T] | ||
type Version = ObjectValues<typeof VERSION> | ||
class Storyblok { | ||
@@ -97,5 +100,5 @@ private client: SbFetch | ||
if (!config.oauthToken) { | ||
endpoint = `${protocol}://api${region}.storyblok.com/${Version.V2}` | ||
endpoint = `${protocol}://api${region}.storyblok.com/${'v2' as Version}` | ||
} else { | ||
endpoint = `${protocol}://api${region}.storyblok.com/${Version.V1}` | ||
endpoint = `${protocol}://api${region}.storyblok.com/${'v1' as Version}` | ||
} | ||
@@ -106,4 +109,5 @@ } | ||
{ | ||
'Content-Type': 'application/json' | ||
}, config.headers | ||
'Content-Type': 'application/json', | ||
}, | ||
config.headers | ||
) | ||
@@ -110,0 +114,0 @@ |
import { SbHelpers } from './sbHelpers' | ||
import { ISbResponse, ISbError, ISbStoriesParams } from './interfaces' | ||
import { Method } from './enum' | ||
import Method from './constants' | ||
@@ -48,3 +48,3 @@ export type ResponseFn = { | ||
this.parameters = params | ||
return this._methodHandler(Method.GET) | ||
return this._methodHandler('get') | ||
} | ||
@@ -55,3 +55,3 @@ | ||
this.parameters = params | ||
return this._methodHandler(Method.POST) | ||
return this._methodHandler('post') | ||
} | ||
@@ -62,3 +62,3 @@ | ||
this.parameters = params | ||
return this._methodHandler(Method.PUT) | ||
return this._methodHandler('put') | ||
} | ||
@@ -69,3 +69,3 @@ | ||
this.parameters = params | ||
return this._methodHandler(Method.DELETE) | ||
return this._methodHandler('delete') | ||
} | ||
@@ -72,0 +72,0 @@ |
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
131116
3640