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.14.4 to 6.0.0

2

dist/index.umd.js

@@ -24,2 +24,2 @@ (function(p,h){typeof exports=="object"&&typeof module<"u"?module.exports=h():typeof define=="function"&&define.amd?define(h):(p=typeof globalThis<"u"?globalThis:p||self,p.StoryblokJSClient=h())})(this,function(){"use strict";var D=Object.defineProperty;var z=(p,h,f)=>h in p?D(p,h,{enumerable:!0,configurable:!0,writable:!0,value:f}):p[h]=f;var u=(p,h,f)=>(z(p,typeof h!="symbol"?h+"":h,f),f);function p(i){return!(i!==i||i===1/0||i===-1/0)}function h(i,e,t){if(!p(e))throw new TypeError("Expected `limit` to be a finite number");if(!p(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let o=[],n=0;const r=function(){n++;const a=setTimeout(function(){n--,s.length>0&&r(),o=o.filter(function(d){return d!==a})},t);o.indexOf(a)<0&&o.push(a);const c=s.shift();c.resolve(i.apply(c.self,c.args))},l=function(...a){const c=this;return new Promise(function(d,b){s.push({resolve:d,reject:b,args:a,self:c}),n<e&&r()})};return l.abort=function(){o.forEach(clearTimeout),o=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class f{constructor(){u(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);u(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));u(this,"delay",e=>new Promise(t=>setTimeout(t,e)));u(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));u(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,o=e<t?1:-1;return this.arrayFrom(s,(n,r)=>r*o+e)});u(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));u(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,o)=>[...s,...o],[]));u(this,"escapeHTML",function(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},s=/[&<>"']/g,o=RegExp(s.source);return e&&o.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const o=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=e[n],l=s?"":encodeURIComponent(n);let a;typeof r=="object"?a=this.stringify(r,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(r)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(r),o.push(a)}return o.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",o="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return o;default:return t}}}const L=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:f},Symbol.toStringTag,{value:"Module"})),N=function(i,e){const t={};for(const s in i){const o=i[s];e.indexOf(s)>-1&&o!==null&&(t[s]=o)}return t},S=i=>i==="email",I={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:N(i.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:i=>{if(!i.attrs)return{tag:""};const e=new f().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),S(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const o in t.custom)t[o]=t.custom[o];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:i=>({tag:[{tag:"span",attrs:i.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:i=>({tag:[{tag:"span",attrs:i.attrs}]}),highlight:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},textStyle:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}}}},U=function(i){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,o=>e[o]):i};class k{constructor(e){u(this,"marks");u(this,"nodes");e||(e=I),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}){if(e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(o=>{s+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.

type: 'doc'
}`),""}optimizeImages(e,t){let s=0,o=0,n="",r="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,o=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(r+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(r+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(r+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(r+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(r+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(r+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(r+=`:rotate(${t.filters.rotate})`),r.length>0&&(r="/filters"+r))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||o>0||r.length>0?`${s}x${o}${r}`:"";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,a=>{var d,b;const c=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const _={srcset:(d=t.srcset)==null?void 0:d.map(m=>{if(typeof m=="number")return`//${c}/m/${m}x0${r} ${m}w`;if(typeof m=="object"&&m.length===2){let O=0,C=0;return typeof m[0]=="number"&&(O=m[0]),typeof m[1]=="number"&&(C=m[1]),`//${c}/m/${O}x${C}${r} ${O}w`}}).join(", "),sizes:(b=t.sizes)==null?void 0:b.map(m=>m).join(", ")};let R="";return _.srcset&&(R+=`srcset="${_.srcset}" `),_.sizes&&(R+=`sizes="${_.sizes}" `),a.replace(/<img/g,`<img ${R.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(U(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(o=>{if(o.constructor===String)return`<${o}${t}>`;{let n=`<${o.tag}`;if(o.attrs)for(const r in o.attrs){const l=o.attrs[r];l!==null&&(n+=` ${r}="${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)}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 w{constructor(e){u(this,"baseURL");u(this,"timeout");u(this,"headers");u(this,"responseInterceptor");u(this,"fetch");u(this,"ejectInterceptor");u(this,"url");u(this,"parameters");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={}}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(o=>{s.data=o});for(const o of e.headers.entries())t[o[0]]=o[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new f;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:r}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${o}`,{method:e,headers:this.headers,body:s,signal:r});this.timeout&&clearTimeout(l);const c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,o)=>{if(t.test(`${e.status}`))return s(e);const n={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const v="SB-Agent",E={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"5.14.4"};let y={};const g={};class T{constructor(e,t){u(this,"client");u(this,"maxRetries");u(this,"throttle");u(this,"accessToken");u(this,"cache");u(this,"helpers");u(this,"resolveCounter");u(this,"relations");u(this,"links");u(this,"richTextResolver");u(this,"resolveNestedRelations");let s=e.endpoint||t;if(!s){const r=new f().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${r(e.region)}/v1`:s=`${l}://${r(e.region)}/v2`}const o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers)for(const r in e.headers)o.set(r,e.headers[r]);o.has(v)||(o.set(v,E.defaultAgentName),o.set(E.defaultAgentVersion,E.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=h(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new f,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new w({baseURL:s,timeout:e.timeout||0,headers:o,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(o=>{s+=e(o.component,o)}),{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,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,o));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,o=this.factoryParamOptions(s,t);return this.cacheResponse(s,o)}async getAll(e,t,s){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`,r=n.split("/"),l=s||r[r.length-1],a=1,c=await this.makeRequest(n,t,o,a),d=c.total?Math.ceil(c.total/o):1,b=await this.helpers.asyncMap(this.helpers.range(a,d),_=>this.makeRequest(n,t,o,_+1));return this.helpers.flatMap([c,...b],_=>Object.values(_.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,s){const o=e[t];o&&o.fieldtype=="multilink"&&o.linktype=="story"&&typeof o.id=="string"&&this.links[s][o.id]?o.story=this._cleanCopy(this.links[s][o.id]):o&&o.linktype==="story"&&typeof o.uuid=="string"&&this.links[s][o.uuid]&&(o.story=this._cleanCopy(this.links[s][o.uuid]))}_insertRelations(e,t,s,o){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[o][e[t]]&&(e[t]=this._cleanCopy(this.relations[o][e[t]]));else if(e[t]&&e[t].constructor===Array){const n=[];e[t].forEach(r=>{this.relations[o][r]&&n.push(this._cleanCopy(this.relations[o][r]))}),e[t]=n}}}iterateTree(e,t,s){const o=n=>{if(n!=null){if(n.constructor===Array)for(let r=0;r<n.length;r++)o(n[r]);else if(n.constructor===Object){if(n._stopResolving)return;for(const r in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,r,t,s),this._insertLinks(n,r,s)),o(n[r])}}};o(e.content)}async resolveLinks(e,t,s){let o=[];if(e.link_uuids){const n=e.link_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.link_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.links;o.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let o=[];if(e.rel_uuids){const n=e.rel_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.rel_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.rels;o&&o.length>0&&o.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var n,r;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((n=e.links)!=null&&n.length||(r=e.link_uuids)!=null&&r.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const o=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 r=await n.get(o);if(r)return Promise.resolve(r)}return new Promise(async(r,l)=>{var a;try{const c=await this.throttle("get",e,t);if(c.status!==200)return l(c);let d={data:c.data,headers:c.headers};if((a=c.headers)!=null&&a["per-page"]&&(d=Object.assign({},d,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),d.data.story||d.data.stories){const b=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${b}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(o,d),d.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=d.data.cv&&await this.flushCache(),g[t.token]=d.data.cv),r(d)}catch(c){if(c.response&&c.response.status===429&&(s=s?s+1:0,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${s} seconds.`),await this.helpers.delay(1e3*s),this.cacheResponse(e,t,s).then(r).catch(l);l(c.message)}})}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 A=(i,e)=>{for(const t in e)i[t]=e[t]};return A(T,{RichtextResolver:k,SbFetch:w,RichTextSchema:I}),A(T,L),T});
}`),""}optimizeImages(e,t){let s=0,o=0,n="",r="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,o=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(r+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(r+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(r+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(r+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(r+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(r+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(r+=`:rotate(${t.filters.rotate})`),r.length>0&&(r="/filters"+r))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||o>0||r.length>0?`${s}x${o}${r}`:"";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,a=>{var d,b;const c=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const _={srcset:(d=t.srcset)==null?void 0:d.map(m=>{if(typeof m=="number")return`//${c}/m/${m}x0${r} ${m}w`;if(typeof m=="object"&&m.length===2){let O=0,A=0;return typeof m[0]=="number"&&(O=m[0]),typeof m[1]=="number"&&(A=m[1]),`//${c}/m/${O}x${A}${r} ${O}w`}}).join(", "),sizes:(b=t.sizes)==null?void 0:b.map(m=>m).join(", ")};let R="";return _.srcset&&(R+=`srcset="${_.srcset}" `),_.sizes&&(R+=`sizes="${_.sizes}" `),a.replace(/<img/g,`<img ${R.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(U(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(o=>{if(o.constructor===String)return`<${o}${t}>`;{let n=`<${o.tag}`;if(o.attrs)for(const r in o.attrs){const l=o.attrs[r];l!==null&&(n+=` ${r}="${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)}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 w{constructor(e){u(this,"baseURL");u(this,"timeout");u(this,"headers");u(this,"responseInterceptor");u(this,"fetch");u(this,"ejectInterceptor");u(this,"url");u(this,"parameters");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={}}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(o=>{s.data=o});for(const o of e.headers.entries())t[o[0]]=o[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new f;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:r}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${o}`,{method:e,headers:this.headers,body:s,signal:r});this.timeout&&clearTimeout(l);const c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,o)=>{if(t.test(`${e.status}`))return s(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const v="SB-Agent",E={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let y={};const g={};class T{constructor(e,t){u(this,"client");u(this,"maxRetries");u(this,"throttle");u(this,"accessToken");u(this,"cache");u(this,"helpers");u(this,"resolveCounter");u(this,"relations");u(this,"links");u(this,"richTextResolver");u(this,"resolveNestedRelations");let s=e.endpoint||t;if(!s){const r=new f().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${r(e.region)}/v1`:s=`${l}://${r(e.region)}/v2`}const o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers)for(const r in e.headers)o.set(r,e.headers[r]);o.has(v)||(o.set(v,E.defaultAgentName),o.set(E.defaultAgentVersion,E.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=h(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new f,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new w({baseURL:s,timeout:e.timeout||0,headers:o,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(o=>{s+=e(o.component,o)}),{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,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,o));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,o=this.factoryParamOptions(s,t);return this.cacheResponse(s,o)}async getAll(e,t,s){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`,r=n.split("/"),l=s||r[r.length-1],a=1,c=await this.makeRequest(n,t,o,a),d=c.total?Math.ceil(c.total/o):1,b=await this.helpers.asyncMap(this.helpers.range(a,d),_=>this.makeRequest(n,t,o,_+1));return this.helpers.flatMap([c,...b],_=>Object.values(_.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,s){const o=e[t];o&&o.fieldtype=="multilink"&&o.linktype=="story"&&typeof o.id=="string"&&this.links[s][o.id]?o.story=this._cleanCopy(this.links[s][o.id]):o&&o.linktype==="story"&&typeof o.uuid=="string"&&this.links[s][o.uuid]&&(o.story=this._cleanCopy(this.links[s][o.uuid]))}_insertRelations(e,t,s,o){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[o][e[t]]&&(e[t]=this._cleanCopy(this.relations[o][e[t]]));else if(e[t]&&e[t].constructor===Array){const n=[];e[t].forEach(r=>{this.relations[o][r]&&n.push(this._cleanCopy(this.relations[o][r]))}),e[t]=n}}}iterateTree(e,t,s){const o=n=>{if(n!=null){if(n.constructor===Array)for(let r=0;r<n.length;r++)o(n[r]);else if(n.constructor===Object){if(n._stopResolving)return;for(const r in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,r,t,s),this._insertLinks(n,r,s)),o(n[r])}}};o(e.content)}async resolveLinks(e,t,s){let o=[];if(e.link_uuids){const n=e.link_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.link_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.links;o.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let o=[];if(e.rel_uuids){const n=e.rel_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.rel_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.rels;o&&o.length>0&&o.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var n,r;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((n=e.links)!=null&&n.length||(r=e.link_uuids)!=null&&r.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const o=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 r=await n.get(o);if(r)return Promise.resolve(r)}return new Promise(async(r,l)=>{var a;try{const c=await this.throttle("get",e,t);if(c.status!==200)return l(c);let d={data:c.data,headers:c.headers};if((a=c.headers)!=null&&a["per-page"]&&(d=Object.assign({},d,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),d.data.story||d.data.stories){const b=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${b}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(o,d),d.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=d.data.cv&&await this.flushCache(),g[t.token]=d.data.cv),r(d)}catch(c){if(c.response&&c.response.status===429&&(s=s?s+1:0,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${s} seconds.`),await this.helpers.delay(1e3*s),this.cacheResponse(e,t,s).then(r).catch(l);l(c)}})}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 C=(i,e)=>{for(const t in e)i[t]=e[t]};return C(T,{RichtextResolver:k,SbFetch:w,RichTextSchema:I}),C(T,L),T});

@@ -180,3 +180,3 @@ import { ResponseFn } from './sbFetch';

export interface ISbError {
message?: Error;
message?: string;
status?: number;

@@ -183,0 +183,0 @@ response?: ISbResponse;

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

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

@@ -95,5 +95,19 @@ <div align="center">

The old master branch containing version `4.x.y` has been moved to the `v4` branch.
We’ve renamed the `master` branch to `main` and now it contains version 5.0.0.
We’ve renamed the `master` branch to `main` and now it contains version >= 5.0.0.
If you wish to continue using the non Typescript version with `axios`, please use version `4`. You can install it by running `npm install https://github.com/storyblok/storyblok-js-client.git#4.x.x`.
### BREAKING CHANGES - FROM VERSION 6
Error handling from fetch has changed. Exceptions will be thrown as an object with the following structure:
```javascript
{
message: string
status: number
response: ISbResponse
}
```
You don't need to parse the response.
### BREAKING CHANGES - FROM VERSION 5

@@ -223,6 +237,11 @@

### Resolve relations using the Storyblok Bridge
With this parameter, you can resolve relations with live updates in the Storyblok JS Bridge input event. With the `resolve_relations` parameter, you can resolve content entries that are two levels deep, such as `resolve_relations=page.author,page.products`. Resolved relations can be found in the root of the response under the property `rels`. You can learn more about `resolve_relations` in [this tutorial](https://www.storyblok.com/tp/using-relationship-resolving-to-include-other-content-entries)
```javascript
window.storyblok.resolveRelations(storyObject, relationsToResolve, callbackWhenResolved) 
```javascript
window.storyblok.resolveRelations(
storyObject,
relationsToResolve,
callbackWhenResolved
)
```

@@ -234,5 +253,8 @@

window.storyblok.on('input', (event) => {
window.storyblok.addComments(event.story.content, event.story.id)
window.storyblok.resolveRelations(event.story, ['post.author', 'post.categories'], () => {
})
window.storyblok.addComments(event.story.content, event.story.id)
window.storyblok.resolveRelations(
event.story,
['post.author', 'post.categories'],
() => {}
)
})

@@ -301,12 +323,11 @@ ```

```javascript
Storyblok
.post('spaces/<YOUR_SPACE_ID>/stories', {
story: {name: 'xy', slug: 'xy'}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
Storyblok.post('spaces/<YOUR_SPACE_ID>/stories', {
story: { name: 'xy', slug: 'xy' },
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
```

@@ -325,12 +346,11 @@

```javascript
Storyblok
.put('spaces/<YOUR_SPACE_ID>/stories/1', {
story: {name: 'xy', slug: 'xy'}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
Storyblok.put('spaces/<YOUR_SPACE_ID>/stories/1', {
story: { name: 'xy', slug: 'xy' },
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
```

@@ -418,4 +438,4 @@

You can instruct the richtext resolver to optimize images using [Storyblok Image Service](https://www.storyblok.com/docs/image-service)
passing the option `optimizeImages: true`.
You can instruct the richtext resolver to optimize images using [Storyblok Image Service](https://www.storyblok.com/docs/image-service)
passing the option `optimizeImages: true`.

@@ -428,3 +448,3 @@ **Example**

Also, it is possible to customize this option passing an object.
Also, it is possible to customize this option passing an object.
All properties are optional and will be applied to each image in the field.

@@ -435,30 +455,26 @@

```js
const options = {
optimizeImages: {
class: 'w-full my-8 border-b border-black',
width: 640, // image width
height: 360, // image height
loading: 'lazy', // 'lazy' | 'eager'
filters: {
blur: 0, // 0 to 100
brightness: 0, // -100 to 100
fill: 'transparent', // Or any hexadecimal value like FFCC99
format: 'webp', // 'webp' | 'jpeg' | 'png'
grayscale: false,
quality: 95, // 0 to 100
rotate: 0 // 0 | 90 | 180 | 270
},
// srcset accepts an array with image widths.
// Example: [720, 1024, 1533]
// will render srcset="//../m/720x0 720w", "//../m/1024x0 1024w", "//../m/1533x0 1280w"
// Also accept an array to pass width and height.
// Example: [[720,500], 1024, [1500, 1000]]
// will render srcset="//../m/720x500 720w", "//../m/1024x0 1024w", "//../m/1500x1000 1280w"
srcset: [720, 1024, 1533],
sizes: [
'(max-width: 767px) 100vw',
'(max-width: 1024px) 768px',
'1500px'
]
}
const options = {
optimizeImages: {
class: 'w-full my-8 border-b border-black',
width: 640, // image width
height: 360, // image height
loading: 'lazy', // 'lazy' | 'eager'
filters: {
blur: 0, // 0 to 100
brightness: 0, // -100 to 100
fill: 'transparent', // Or any hexadecimal value like FFCC99
format: 'webp', // 'webp' | 'jpeg' | 'png'
grayscale: false,
quality: 95, // 0 to 100
rotate: 0, // 0 | 90 | 180 | 270
},
// srcset accepts an array with image widths.
// Example: [720, 1024, 1533]
// will render srcset="//../m/720x0 720w", "//../m/1024x0 1024w", "//../m/1533x0 1280w"
// Also accept an array to pass width and height.
// Example: [[720,500], 1024, [1500, 1000]]
// will render srcset="//../m/720x500 720w", "//../m/1024x0 1024w", "//../m/1500x1000 1280w"
srcset: [720, 1024, 1533],
sizes: ['(max-width: 767px) 100vw', '(max-width: 1024px) 768px', '1500px'],
},
}

@@ -658,4 +674,5 @@

### Handling access token overwrite
You can overwrite an access token, and prevent errors from the function call by adding a `.catch()` method for each access token as shown below.
You can overwrite an access token, and prevent errors from the function call by adding a `.catch()` method for each access token as shown below.
```javascript

@@ -667,3 +684,3 @@ const public = 'token1'

You can pass the tokens as follows:
```javascript

@@ -670,0 +687,0 @@ client.getStories({token: 'preview'...}).then(previewResponse => ... ).catch()

@@ -600,3 +600,3 @@ import throttledQueue from './throttlePromise'

}
reject(error.message)
reject(error)
}

@@ -603,0 +603,0 @@ })

@@ -197,3 +197,3 @@ import { ResponseFn } from './sbFetch'

export interface ISbError {
message?: Error
message?: string
status?: number

@@ -200,0 +200,0 @@ response?: ISbResponse

@@ -162,3 +162,3 @@ import { SbHelpers } from './sbHelpers'

const error: ISbError = {
message: new Error(res.statusText),
message: res.statusText,
status: res.status,

@@ -165,0 +165,0 @@ response: Array.isArray(res.data)

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