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

@storyblok/js

Package Overview
Dependencies
Maintainers
7
Versions
91
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@storyblok/js - npm Package Compare versions

Comparing version 2.0.16 to 2.1.0

4

dist/storyblok-js.js

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

(function(d,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(d=typeof globalThis<"u"?globalThis:d||self,p(d.storyblok={}))})(this,function(d){"use strict";let p=!1;const b=[],w=i=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}p?r():b.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>e(r),s.onload=r=>{b.forEach(n=>n()),p=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(s)});var E=Object.defineProperty,S=(i,t,e)=>t in i?E(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,c=(i,t,e)=>(S(i,typeof t!="symbol"?t+"":t,e),e);function T(i){return!(i!==i||i===1/0||i===-1/0)}function x(i,t,e){if(!T(t))throw new TypeError("Expected `limit` to be a finite number");if(!T(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const o=function(){n++;const l=setTimeout(function(){n--,s.length>0&&o(),r=r.filter(function(u){return u!==l})},e);r.indexOf(l)<0&&r.push(l);const h=s.shift();h.resolve(i.apply(h.self,h.args))},a=function(...l){const h=this;return new Promise(function(u,k){s.push({resolve:u,reject:k,args:l,self:h}),n<t&&o()})};return a.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},a}const O=function(i,t){const e={};for(const s in i){const r=i[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},I=i=>i==="email",C=()=>({singleTag:"hr"}),A=()=>({tag:"blockquote"}),M=()=>({tag:"ul"}),N=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),L=()=>({singleTag:"br"}),U=i=>({tag:`h${i.attrs.level}`}),B=i=>({singleTag:[{tag:"img",attrs:O(i.attrs,["src","alt","title"])}]}),H=()=>({tag:"li"}),q=()=>({tag:"ol"}),D=()=>({tag:"p"}),J=()=>({tag:"b"}),F=()=>({tag:"strike"}),V=()=>({tag:"u"}),z=()=>({tag:"strong"}),Y=()=>({tag:"code"}),K=()=>({tag:"i"}),Q=i=>{const t={...i.attrs},{linktype:e="url"}=i.attrs;return I(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},G=i=>({tag:[{tag:"span",attrs:i.attrs}]}),R={nodes:{horizontal_rule:C,blockquote:A,bullet_list:M,code_block:N,hard_break:L,heading:U,image:B,list_item:H,ordered_list:q,paragraph:D},marks:{bold:J,strike:F,underline:V,strong:z,code:Y,italic:K,link:Q,styled:G}},W=function(i){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,s=RegExp(e.source);return i&&s.test(i)?i.replace(e,r=>t[r]):i};class f{constructor(t){c(this,"marks"),c(this,"nodes"),t||(t=R),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t){if(t&&t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(s=>{e+=this.renderNode(s)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(W(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html&&e.push(s.html),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const n in s.attrs){const o=s.attrs[n];o!==null&&(r+=` ${n}="${o}"`)}return`${r}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}class _{constructor(){c(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),c(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s})),c(this,"delay",t=>new Promise(e=>setTimeout(e,t))),c(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e)),c(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(n,o)=>o*r+t)}),c(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),c(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const o=t[n],a=s?"":encodeURIComponent(n);let l;typeof o=="object"?l=this.stringify(o,e?e+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):l=(e?e+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),r.push(l)}return r.join("&")}}class X{constructor(t){c(this,"baseURL"),c(this,"timeout"),c(this,"headers"),c(this,"responseInterceptor"),c(this,"fetch"),c(this,"ejectInterceptor"),c(this,"url"),c(this,"parameters"),this.baseURL=t.baseURL,this.headers=t.headers||[],this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const l=new _;e=`${this.baseURL}${this.url}?${l.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),n=new AbortController,{signal:o}=n;let a;this.timeout&&(a=setTimeout(()=>n.abort(),this.timeout));try{const l=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:o});this.timeout&&clearTimeout(a);const h=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}catch(l){return{message:l}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const n={message:new Error(t.statusText),status:t.status,response:t.data.error||t.data.slug};r(n)})}}let m={};const g={};class Z{constructor(t,e){if(c(this,"client"),c(this,"maxRetries"),c(this,"throttle"),c(this,"accessToken"),c(this,"cache"),c(this,"helpers"),c(this,"relations"),c(this,"links"),c(this,"richTextResolver"),c(this,"resolveNestedRelations"),!e){const n=t.region?`-${t.region}`:"",o=t.https===!1?"http":"https";t.oauthToken?e=`${o}://api${n}.storyblok.com/v1`:e=`${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)=>{t.headers&&t.headers[o]&&s.set(o,t.headers[o])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new f(t.richTextSchema):this.richTextResolver=new f,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=x(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new _,this.resolveNestedRelations=!1,this.client=new X({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=g[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const n=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,n)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,n=`/${t}`,o=n.split("/"),a=s||o[o.length-1],l=1,h=await this.makeRequest(n,e,r,l),u=h.total?Math.ceil(h.total/r):1,k=await this.helpers.asyncMap(this.helpers.range(l,u),v=>this.makeRequest(n,e,r,v+1));return this.helpers.flatMap([h,...k],v=>Object.values(v.data[a]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const s=t[e];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(t,e,s){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[t[e]]&&(t[e]=this._cleanCopy(this.relations[t[e]]));else if(t[e]&&t[e].constructor===Array){const r=[];t[e].forEach(n=>{this.relations[n]&&r.push(this._cleanCopy(this.relations[n]))}),t[e]=r}}}iterateTree(t,e){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,e),this._insertLinks(r,n)),s(r[n])}}};s(t.content)}async resolveLinks(t,e){let s=[];if(t.link_uuids){const r=t.link_uuids.length,n=[],o=50;for(let a=0;a<r;a+=o){const l=Math.min(r,a+o);n.push(t.link_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:o,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{s.push(l)})}else s=t.links;s.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(t,e){let s=[];if(t.rel_uuids){const r=t.rel_uuids.length,n=[],o=50;for(let a=0;a<r;a+=o){const l=Math.min(r,a+o);n.push(t.rel_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:o,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{s.push(l)})}else s=t.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(t,e){var s,r;let n=[];if(typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(n=e.resolve_relations.split(",")),await this.resolveRelations(t,e)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((s=t.links)!=null&&s.length||(r=t.link_uuids)!=null&&r.length)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const o in this.relations)this.iterateTree(this.relations[o],n);t.story?this.iterateTree(t.story,n):t.stories.forEach(o=>{this.iterateTree(o,n)})}async cacheResponse(t,e,s){const r=this.helpers.stringify({url:t,params:e}),n=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const o=await n.get(r);if(o)return Promise.resolve(o)}return new Promise((o,a)=>{try{(async()=>{var l;try{const h=await this.throttle("get",t,e);let u={data:h.data,headers:h.headers};return(l=h.headers)!=null&&l["per-page"]&&(u=Object.assign({},u,{perPage:h.headers["per-page"]?parseInt(h.headers["per-page"]):0,total:h.headers["per-page"]?parseInt(h.headers.total):0})),h.status!=200?a(h):((u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&g[e.token]!=u.data.cv&&await this.flushCache(),g[e.token]=u.data.cv),o(u))}catch(h){return a(h)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(m[t])},getAll(){return Promise.resolve(m)},set(t,e){return m[t]=e,Promise.resolve(void 0)},flush(){return m={},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 tt=(i={})=>{const{apiOptions:t}=i;if(!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new Z(t)}},et=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};const t=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let y;const $="https://app.storyblok.com/f/storyblok-v2-latest.js",P=(i,t,e={})=>{if(!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u"){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],o=>{o.action==="input"&&o.story.id===i?t(o.story):(o.action==="change"||o.action==="published")&&o.storyId===i&&window.location.reload()})})}},st=(i={})=>{const{bridge:t,accessToken:e,use:s=[],apiOptions:r={},richText:n={}}=i;r.accessToken=r.accessToken||e;const o={bridge:t,apiOptions:r};let a={};return s.forEach(l=>{a={...a,...l(o)}}),t!==!1&&w($),y=new f(n.schema),n.resolver&&j(y,n.resolver),a},j=(i,t)=>{i.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},rt=(i,t,e)=>{let s=e||y;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return i===""?"":i?(t&&(s=new f(t.schema),t.resolver&&j(s,t.resolver)),s.render(i)):(console.warn(`${i} is not a valid Richtext object. This might be because the value of the richtext field is empty.
(function(d,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(d=typeof globalThis<"u"?globalThis:d||self,p(d.storyblok={}))})(this,function(d){"use strict";let p=!1;const b=[],w=i=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}p?r():b.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>e(r),s.onload=r=>{b.forEach(n=>n()),p=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(s)});var E=Object.defineProperty,S=(i,t,e)=>t in i?E(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,l=(i,t,e)=>(S(i,typeof t!="symbol"?t+"":t,e),e);function T(i){return!(i!==i||i===1/0||i===-1/0)}function x(i,t,e){if(!T(t))throw new TypeError("Expected `limit` to be a finite number");if(!T(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const o=function(){n++;const c=setTimeout(function(){n--,s.length>0&&o(),r=r.filter(function(u){return u!==c})},e);r.indexOf(c)<0&&r.push(c);const h=s.shift();h.resolve(i.apply(h.self,h.args))},a=function(...c){const h=this;return new Promise(function(u,f){s.push({resolve:u,reject:f,args:c,self:h}),n<t&&o()})};return a.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(c){c.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},a}const O=function(i,t){const e={};for(const s in i){const r=i[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},I=i=>i==="email",C=()=>({singleTag:"hr"}),A=()=>({tag:"blockquote"}),M=()=>({tag:"ul"}),N=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),L=()=>({singleTag:"br"}),U=i=>({tag:`h${i.attrs.level}`}),B=i=>({singleTag:[{tag:"img",attrs:O(i.attrs,["src","alt","title"])}]}),H=()=>({tag:"li"}),q=()=>({tag:"ol"}),D=()=>({tag:"p"}),J=()=>({tag:"b"}),F=()=>({tag:"strike"}),V=()=>({tag:"u"}),z=()=>({tag:"strong"}),Y=()=>({tag:"code"}),K=()=>({tag:"i"}),Q=i=>{const t={...i.attrs},{linktype:e="url"}=i.attrs;return I(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},G=i=>({tag:[{tag:"span",attrs:i.attrs}]}),R={nodes:{horizontal_rule:C,blockquote:A,bullet_list:M,code_block:N,hard_break:L,heading:U,image:B,list_item:H,ordered_list:q,paragraph:D},marks:{bold:J,strike:F,underline:V,strong:z,code:Y,italic:K,link:Q,styled:G}},W=function(i){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,s=RegExp(e.source);return i&&s.test(i)?i.replace(e,r=>t[r]):i};class m{constructor(t){l(this,"marks"),l(this,"nodes"),t||(t=R),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t){if(t&&t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(s=>{e+=this.renderNode(s)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(W(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html&&e.push(s.html),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const n in s.attrs){const o=s.attrs[n];o!==null&&(r+=` ${n}="${o}"`)}return`${r}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}class _{constructor(){l(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),l(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s})),l(this,"delay",t=>new Promise(e=>setTimeout(e,t))),l(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e)),l(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(n,o)=>o*r+t)}),l(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),l(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const o=t[n],a=s?"":encodeURIComponent(n);let c;typeof o=="object"?c=this.stringify(o,e?e+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):c=(e?e+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),r.push(c)}return r.join("&")}}class X{constructor(t){l(this,"baseURL"),l(this,"timeout"),l(this,"headers"),l(this,"responseInterceptor"),l(this,"fetch"),l(this,"ejectInterceptor"),l(this,"url"),l(this,"parameters"),this.baseURL=t.baseURL,this.headers=t.headers||[],this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const c=new _;e=`${this.baseURL}${this.url}?${c.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),n=new AbortController,{signal:o}=n;let a;this.timeout&&(a=setTimeout(()=>n.abort(),this.timeout));try{const c=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:o});this.timeout&&clearTimeout(a);const h=await this._responseHandler(c);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}catch(c){return{message:c}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const n={message:new Error(t.statusText),status:t.status,response:t.data.error||t.data.slug};r(n)})}}let k={};const g={};class Z{constructor(t,e){if(l(this,"client"),l(this,"maxRetries"),l(this,"throttle"),l(this,"accessToken"),l(this,"cache"),l(this,"helpers"),l(this,"relations"),l(this,"links"),l(this,"richTextResolver"),l(this,"resolveNestedRelations"),!e){const n=t.region?`-${t.region}`:"",o=t.https===!1?"http":"https";t.oauthToken?e=`${o}://api${n}.storyblok.com/v1`:e=`${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)=>{t.headers&&t.headers[o]&&s.set(o,t.headers[o])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new m(t.richTextSchema):this.richTextResolver=new m,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=x(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new _,this.resolveNestedRelations=!1,this.client=new X({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=g[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const n=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,n)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,n=`/${t}`,o=n.split("/"),a=s||o[o.length-1],c=1,h=await this.makeRequest(n,e,r,c),u=h.total?Math.ceil(h.total/r):1,f=await this.helpers.asyncMap(this.helpers.range(c,u),y=>this.makeRequest(n,e,r,y+1));return this.helpers.flatMap([h,...f],y=>Object.values(y.data[a]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const s=t[e];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(t,e,s){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[t[e]]&&(t[e]=this._cleanCopy(this.relations[t[e]]));else if(t[e]&&t[e].constructor===Array){const r=[];t[e].forEach(n=>{this.relations[n]&&r.push(this._cleanCopy(this.relations[n]))}),t[e]=r}}}iterateTree(t,e){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,e),this._insertLinks(r,n)),s(r[n])}}};s(t.content)}async resolveLinks(t,e){let s=[];if(t.link_uuids){const r=t.link_uuids.length,n=[],o=50;for(let a=0;a<r;a+=o){const c=Math.min(r,a+o);n.push(t.link_uuids.slice(a,c))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:o,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=t.links;s.forEach(r=>{this.links[r.uuid]={...r,_stopResolving:!0}})}async resolveRelations(t,e){let s=[];if(t.rel_uuids){const r=t.rel_uuids.length,n=[],o=50;for(let a=0;a<r;a+=o){const c=Math.min(r,a+o);n.push(t.rel_uuids.slice(a,c))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:o,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=t.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]={...r,_stopResolving:!0}})}async resolveStories(t,e){var s,r;let n=[];if(typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(n=e.resolve_relations.split(",")),await this.resolveRelations(t,e)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((s=t.links)!=null&&s.length||(r=t.link_uuids)!=null&&r.length)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const o in this.relations)this.iterateTree(this.relations[o],n);t.story?this.iterateTree(t.story,n):t.stories.forEach(o=>{this.iterateTree(o,n)})}async cacheResponse(t,e,s){const r=this.helpers.stringify({url:t,params:e}),n=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const o=await n.get(r);if(o)return Promise.resolve(o)}return new Promise((o,a)=>{try{(async()=>{var c;try{const h=await this.throttle("get",t,e);let u={data:h.data,headers:h.headers};return(c=h.headers)!=null&&c["per-page"]&&(u=Object.assign({},u,{perPage:h.headers["per-page"]?parseInt(h.headers["per-page"]):0,total:h.headers["per-page"]?parseInt(h.headers.total):0})),h.status!=200?a(h):((u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&g[e.token]!=u.data.cv&&await this.flushCache(),g[e.token]=u.data.cv),o(u))}catch(h){return a(h)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(k[t])},getAll(){return Promise.resolve(k)},set(t,e){return k[t]=e,Promise.resolve(void 0)},flush(){return k={},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 tt=(i={})=>{const{apiOptions:t}=i;if(!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new Z(t)}},et=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};const t=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let v;const $="https://app.storyblok.com/f/storyblok-v2-latest.js",P=(i,t,e={})=>{if(!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u"){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],o=>{o.action==="input"&&o.story.id===i?t(o.story):(o.action==="change"||o.action==="published")&&o.storyId===i&&window.location.reload()})})}},st=(i={})=>{var u,f;const{bridge:t,accessToken:e,use:s=[],apiOptions:r={},richText:n={}}=i;r.accessToken=r.accessToken||e;const o={bridge:t,apiOptions:r};let a={};s.forEach(y=>{a={...a,...y(o)}});const h=!(typeof window>"u")&&((f=(u=window.location)==null?void 0:u.search)==null?void 0:f.includes("_storyblok_tk"));return t!==!1&&h&&w($),v=new m(n.schema),n.resolver&&j(v,n.resolver),a},j=(i,t)=>{i.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},rt=(i,t,e)=>{let s=e||v;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return i===""?"":i?(t&&(s=new m(t.schema),t.resolver&&j(s,t.resolver)),s.render(i)):(console.warn(`${i} is not a valid Richtext object. This might be because the value of the richtext field is empty.
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},nt=()=>w($);d.RichTextResolver=f,d.RichTextSchema=R,d.apiPlugin=tt,d.loadStoryblokBridge=nt,d.registerStoryblokBridge=P,d.renderRichText=rt,d.storyblokEditable=et,d.storyblokInit=st,d.useStoryblokBridge=P,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},nt=()=>w($);d.RichTextResolver=m,d.RichTextSchema=R,d.apiPlugin=tt,d.loadStoryblokBridge=nt,d.registerStoryblokBridge=P,d.renderRichText=rt,d.storyblokEditable=et,d.storyblokInit=st,d.useStoryblokBridge=P,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
{
"name": "@storyblok/js",
"version": "2.0.16",
"version": "2.1.0",
"description": "SDK to integrate Storyblok into your project using JavaScript.",

@@ -5,0 +5,0 @@ "main": "./dist/storyblok-js.js",

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