@storyblok/js 1.0.3 → 1.0.4

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  </a>
5
5
  <h1 align="center">@storyblok/js</h1>
6
6
  <p align="center">
7
- The JavaScript plugin you need to interact with <a href="http://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js" target="_blank">Storyblok API</a> and enable the <a href="https://www.storyblok.com/docs/guide/essentials/visual-editor?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js" target="_blank">Real-time Visual Editing Experience</a>.
7
+ The JavaScript SDK you need to interact with <a href="http://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js" target="_blank">Storyblok API</a> and enable the <a href="https://www.storyblok.com/docs/guide/essentials/visual-editor?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js" target="_blank">Real-time Visual Editing Experience</a>.
8
8
  </p>
9
9
  <br />
10
10
  </div>
@@ -41,8 +41,8 @@
41
41
  Install `@storyblok/js`:
42
42
 
43
43
  ```bash
44
- npm install --save-dev @storyblok/js
45
- // yarn add -D @storyblok/js
44
+ npm install @storyblok/js
45
+ // yarn add @storyblok/js
46
46
  ```
47
47
 
48
48
  #### From a CDN
@@ -1,5 +1,5 @@
1
- var B=Object.defineProperty,L=Object.defineProperties;var U=Object.getOwnPropertyDescriptors;var R=Object.getOwnPropertySymbols;var J=Object.prototype.hasOwnProperty,V=Object.prototype.propertyIsEnumerable;var E=(h,d,p)=>d in h?B(h,d,{enumerable:!0,configurable:!0,writable:!0,value:p}):h[d]=p,g=(h,d)=>{for(var p in d||(d={}))J.call(d,p)&&E(h,p,d[p]);if(R)for(var p of R(d))V.call(d,p)&&E(h,p,d[p]);return h},m=(h,d)=>L(h,U(d));(function(h,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],d):(h=typeof globalThis!="undefined"?globalThis:h||self,d(h.storyblok={},h.t))})(this,function(h,d){"use strict";function p(n){return n&&typeof n=="object"&&"default"in n?n:{default:n}}var j=p(d);let v=!1;const w=[],O=n=>new Promise((e,r)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}v?s():w.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const t=document.createElement("script");t.async=!0,t.src=n,t.id="storyblok-javascript-bridge",t.onerror=s=>r(s),t.onload=s=>{w.forEach(o=>o()),v=!0,e(s)},document.getElementsByTagName("head")[0].appendChild(t)});/*!
1
+ var B=Object.defineProperty,L=Object.defineProperties;var U=Object.getOwnPropertyDescriptors;var R=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable;var E=(h,d,p)=>d in h?B(h,d,{enumerable:!0,configurable:!0,writable:!0,value:p}):h[d]=p,g=(h,d)=>{for(var p in d||(d={}))D.call(d,p)&&E(h,p,d[p]);if(R)for(var p of R(d))J.call(d,p)&&E(h,p,d[p]);return h},m=(h,d)=>L(h,U(d));(function(h,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],d):(h=typeof globalThis!="undefined"?globalThis:h||self,d(h.storyblok={},h.t))})(this,function(h,d){"use strict";function p(n){return n&&typeof n=="object"&&"default"in n?n:{default:n}}var S=p(d);let v=!1;const w=[],j=n=>new Promise((e,r)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}v?s():w.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const t=document.createElement("script");t.async=!0,t.src=n,t.id="storyblok-javascript-bridge",t.onerror=s=>r(s),t.onload=s=>{w.forEach(o=>o()),v=!0,e(s)},document.getElementsByTagName("head")[0].appendChild(t)});/*!
2
2
  * storyblok-js-client v0.0.0-development
3
3
  * Universal JavaScript SDK for Storyblok's API
4
4
  * (c) 2020-2022 Stobylok Team
5
- */function T(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function _(n,e,r){if(!T(e))throw new TypeError("Expected `limit` to be a finite number");if(!T(r))throw new TypeError("Expected `interval` to be a finite number");var t=[],s=[],o=0,i=function(){o++;var c=setTimeout(function(){o--,t.length>0&&i(),s=s.filter(function(u){return u!==c})},r);s.indexOf(c)<0&&s.push(c);var l=t.shift();l.resolve(n.apply(l.self,l.args))},a=function(){var c=arguments,l=this;return new Promise(function(u,y){t.push({resolve:u,reject:y,args:c,self:l}),o<e&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],t.forEach(function(c){c.reject(new throttle.AbortError)}),t.length=0},a}_.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const S=function(n,e){if(!n)return null;let r={};for(let t in n){let s=n[t];e.indexOf(t)>-1&&s!==null&&(r[t]=s)}return r};var C={nodes:{horizontal_rule:n=>({singleTag:"hr"}),blockquote:n=>({tag:"blockquote"}),bullet_list:n=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:n=>({singleTag:"br"}),heading:n=>({tag:"h"+n.attrs.level}),image:n=>({singleTag:[{tag:"img",attrs:S(n.attrs,["src","alt","title"])}]}),list_item:n=>({tag:"li"}),ordered_list:n=>({tag:"ol"}),paragraph:n=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(n){const e=g({},n.attrs),{linktype:r="url"}=n.attrs;return r==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class A{constructor(e){e||(e=C),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,r){this.nodes[e]=r}addMark(e,r){this.marks[e]=r}render(e={}){if(e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(t=>{r+=this.renderNode(t)}),r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let r=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderOpeningTag(o.tag))});const t=this.getMatchingNode(e);return t&&t.tag&&r.push(this.renderOpeningTag(t.tag)),e.content?e.content.forEach(s=>{r.push(this.renderNode(s))}):e.text?r.push(function(s){const o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,c=>o[c]):s}(e.text)):t&&t.singleTag?r.push(this.renderTag(t.singleTag," /")):t&&t.html&&r.push(t.html),t&&t.tag&&r.push(this.renderClosingTag(t.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderClosingTag(o.tag))}),r.join("")}renderTag(e,r){return e.constructor===String?`<${e}${r}>`:e.map(t=>{if(t.constructor===String)return`<${t}${r}>`;{let s="<"+t.tag;if(t.attrs)for(let o in t.attrs){let i=t.attrs[o];i!==null&&(s+=` ${o}="${i}"`)}return`${s}${r}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(e){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const P=(n=0,e=n)=>{const r=Math.abs(e-n)||0,t=n<e?1:-1;return((s=0,o)=>[...Array(s)].map(o))(r,(s,o)=>o*t+n)},b=(n,e,r)=>{const t=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],i=r?"":encodeURIComponent(s);let a;a=typeof o=="object"?b(o,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(o)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(o),t.push(a)}return t.join("&")};let k={},f={};class ${constructor(e,r){if(!r){let o=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";r=e.oauthToken===void 0?`${i}://api${o}.storyblok.com/v2`:`${i}://api${o}.storyblok.com/v1`}let t=Object.assign({},e.headers),s=5;e.oauthToken!==void 0&&(t.Authorization=e.oauthToken,s=3),e.rateLimit!==void 0&&(s=e.rateLimit),this.richTextResolver=new A(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=_(this.throttledRequest,s,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=j.default.create({baseURL:r,timeout:e.timeout||0,headers:t,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(o=>e.responseInterceptor(o))}setComponentResolver(e){this.richTextResolver.addNode("blok",r=>{let t="";return r.attrs.body.forEach(s=>{t+=e(s.component,s)}),{html:t}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=f[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,r={}){return((t="")=>t.indexOf("/cdn/")>-1)(e)?this.parseParams(r):r}makeRequest(e,r,t,s){const o=this.factoryParamOptions(e,((i={},a=25,c=1)=>m(g({},i),{per_page:a,page:c}))(r,t,s));return this.cacheResponse(e,o)}get(e,r){let t="/"+e;const s=this.factoryParamOptions(t,r);return this.cacheResponse(t,s)}async getAll(e,r={},t){const s=r.per_page||25,o="/"+e,i=o.split("/");t=t||i[i.length-1];const a=await this.makeRequest(o,r,s,1),c=Math.ceil(a.total/s);return((l=[],u)=>l.map(u).reduce((y,q)=>[...y,...q],[]))([a,...await(async(l=[],u)=>Promise.all(l.map(u)))(P(1,c),async l=>this.makeRequest(o,r,s,l+1))],l=>Object.values(l.data[t]))}post(e,r){let t="/"+e;return this.throttle("post",t,r)}put(e,r){let t="/"+e;return this.throttle("put",t,r)}delete(e,r){let t="/"+e;return this.throttle("delete",t,r)}getStories(e){return this.get("cdn/stories",e)}getStory(e,r){return this.get("cdn/stories/"+e,r)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,r){const t=e[r];t&&t.fieldtype=="multilink"&&t.linktype=="story"&&typeof t.id=="string"&&this.links[t.id]?t.story=this._cleanCopy(this.links[t.id]):t&&t.linktype==="story"&&typeof t.uuid=="string"&&this.links[t.uuid]&&(t.story=this._cleanCopy(this.links[t.uuid]))}_insertRelations(e,r,t){if(t.indexOf(e.component+"."+r)>-1){if(typeof e[r]=="string")this.relations[e[r]]&&(e[r]=this._cleanCopy(this.relations[e[r]]));else if(e[r].constructor===Array){let s=[];e[r].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),e[r]=s}}}iterateTree(e,r){let t=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)t(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)(s.component&&s._uid||s.type==="link")&&(this._insertRelations(s,o,r),this._insertLinks(s,o)),t(s[o])}}};t(e.content)}async resolveLinks(e,r){let t=[];if(e.link_uuids){const s=e.link_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const c=Math.min(s,a+i);o.push(e.link_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:r.language,version:r.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{t.push(c)})}else t=e.links;t.forEach(s=>{this.links[s.uuid]=m(g({},s),{_stopResolving:!0})})}async resolveRelations(e,r){let t=[];if(e.rel_uuids){const s=e.rel_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const c=Math.min(s,a+i);o.push(e.rel_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:r.language,version:r.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{t.push(c)})}else t=e.rels;t.forEach(s=>{this.relations[s.uuid]=m(g({},s),{_stopResolving:!0})})}async resolveStories(e,r){let t=[];r.resolve_relations!==void 0&&r.resolve_relations.length>0&&(t=r.resolve_relations.split(","),await this.resolveRelations(e,r)),["1","story","url"].indexOf(r.resolve_links)>-1&&await this.resolveLinks(e,r);for(const s in this.relations)this.iterateTree(this.relations[s],t);e.story?this.iterateTree(e.story,t):e.stories.forEach(s=>{this.iterateTree(s,t)})}cacheResponse(e,r,t){return t===void 0&&(t=0),new Promise(async(s,o)=>{let i=b({url:e,params:r}),a=this.cacheProvider();if(this.cache.clear==="auto"&&r.version==="draft"&&await this.flushCache(),r.version==="published"&&e!="/cdn/spaces/me"){const l=await a.get(i);if(l)return s(l)}try{let l=await this.throttle("get",e,{params:r,paramsSerializer:y=>b(y)}),u={data:l.data,headers:l.headers};if(l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,r),r.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,u),u.data.cv&&(r.version=="draft"&&f[r.token]!=u.data.cv&&this.flushCache(),f[r.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(t+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${t} seconds.`),await(c=1e3*t,new Promise(u=>setTimeout(u,c))),this.cacheResponse(e,r,t).then(s).catch(o);o(l)}var c})}throttledRequest(e,r,t){return this.client[e](r,t)}cacheVersions(){return f}cacheVersion(){return f[this.accessToken]}setCacheVersion(e){this.accessToken&&(f[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>k[e],getAll:()=>k,set(e,r){k[e]=r},flush(){k={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var x=(n={})=>{const{apiOptions:e}=n;if(!e.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 $(e)}},M=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const I=(n,e,r={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(r).on(["input","published","change"],s=>{s.action=="input"&&s.story.id===n?e(s.story):window.location.reload()})})}},N=(n={})=>{const{bridge:e,accessToken:r,use:t=[],apiOptions:s={}}=n;s.accessToken=s.accessToken||r;const o={bridge:e,apiOptions:s};let i={};return t.forEach(a=>{i=g(g({},i),a(o))}),e!==!1&&O("https://app.storyblok.com/f/storyblok-v2-latest.js"),i};h.apiPlugin=x,h.storyblokEditable=M,h.storyblokInit=N,h.useStoryblokBridge=I,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
5
+ */function T(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function _(n,e,r){if(!T(e))throw new TypeError("Expected `limit` to be a finite number");if(!T(r))throw new TypeError("Expected `interval` to be a finite number");var t=[],s=[],o=0,i=function(){o++;var c=setTimeout(function(){o--,t.length>0&&i(),s=s.filter(function(u){return u!==c})},r);s.indexOf(c)<0&&s.push(c);var l=t.shift();l.resolve(n.apply(l.self,l.args))},a=function(){var c=arguments,l=this;return new Promise(function(u,y){t.push({resolve:u,reject:y,args:c,self:l}),o<e&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],t.forEach(function(c){c.reject(new throttle.AbortError)}),t.length=0},a}_.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const O=function(n,e){if(!n)return null;let r={};for(let t in n){let s=n[t];e.indexOf(t)>-1&&s!==null&&(r[t]=s)}return r};var C={nodes:{horizontal_rule:n=>({singleTag:"hr"}),blockquote:n=>({tag:"blockquote"}),bullet_list:n=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:n=>({singleTag:"br"}),heading:n=>({tag:"h"+n.attrs.level}),image:n=>({singleTag:[{tag:"img",attrs:O(n.attrs,["src","alt","title"])}]}),list_item:n=>({tag:"li"}),ordered_list:n=>({tag:"ol"}),paragraph:n=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(n){const e=g({},n.attrs),{linktype:r="url"}=n.attrs;return r==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class P{constructor(e){e||(e=C),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,r){this.nodes[e]=r}addMark(e,r){this.marks[e]=r}render(e={}){if(e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(t=>{r+=this.renderNode(t)}),r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let r=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderOpeningTag(o.tag))});const t=this.getMatchingNode(e);return t&&t.tag&&r.push(this.renderOpeningTag(t.tag)),e.content?e.content.forEach(s=>{r.push(this.renderNode(s))}):e.text?r.push(function(s){const o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,c=>o[c]):s}(e.text)):t&&t.singleTag?r.push(this.renderTag(t.singleTag," /")):t&&t.html&&r.push(t.html),t&&t.tag&&r.push(this.renderClosingTag(t.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderClosingTag(o.tag))}),r.join("")}renderTag(e,r){return e.constructor===String?`<${e}${r}>`:e.map(t=>{if(t.constructor===String)return`<${t}${r}>`;{let s="<"+t.tag;if(t.attrs)for(let o in t.attrs){let i=t.attrs[o];i!==null&&(s+=` ${o}="${i}"`)}return`${s}${r}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(e){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const A=(n=0,e=n)=>{const r=Math.abs(e-n)||0,t=n<e?1:-1;return((s=0,o)=>[...Array(s)].map(o))(r,(s,o)=>o*t+n)},b=(n,e,r)=>{const t=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],i=r?"":encodeURIComponent(s);let a;a=typeof o=="object"?b(o,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(o)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(o),t.push(a)}return t.join("&")};let k={},f={};class ${constructor(e,r){if(!r){let o=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";r=e.oauthToken===void 0?`${i}://api${o}.storyblok.com/v2`:`${i}://api${o}.storyblok.com/v1`}let t=Object.assign({},e.headers),s=5;e.oauthToken!==void 0&&(t.Authorization=e.oauthToken,s=3),e.rateLimit!==void 0&&(s=e.rateLimit),this.richTextResolver=new P(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=_(this.throttledRequest,s,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=S.default.create({baseURL:r,timeout:e.timeout||0,headers:t,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(o=>e.responseInterceptor(o))}setComponentResolver(e){this.richTextResolver.addNode("blok",r=>{let t="";return r.attrs.body.forEach(s=>{t+=e(s.component,s)}),{html:t}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=f[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,r={}){return((t="")=>t.indexOf("/cdn/")>-1)(e)?this.parseParams(r):r}makeRequest(e,r,t,s){const o=this.factoryParamOptions(e,((i={},a=25,c=1)=>m(g({},i),{per_page:a,page:c}))(r,t,s));return this.cacheResponse(e,o)}get(e,r){let t="/"+e;const s=this.factoryParamOptions(t,r);return this.cacheResponse(t,s)}async getAll(e,r={},t){const s=r.per_page||25,o="/"+e,i=o.split("/");t=t||i[i.length-1];const a=await this.makeRequest(o,r,s,1),c=Math.ceil(a.total/s);return((l=[],u)=>l.map(u).reduce((y,q)=>[...y,...q],[]))([a,...await(async(l=[],u)=>Promise.all(l.map(u)))(A(1,c),async l=>this.makeRequest(o,r,s,l+1))],l=>Object.values(l.data[t]))}post(e,r){let t="/"+e;return this.throttle("post",t,r)}put(e,r){let t="/"+e;return this.throttle("put",t,r)}delete(e,r){let t="/"+e;return this.throttle("delete",t,r)}getStories(e){return this.get("cdn/stories",e)}getStory(e,r){return this.get("cdn/stories/"+e,r)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,r){const t=e[r];t&&t.fieldtype=="multilink"&&t.linktype=="story"&&typeof t.id=="string"&&this.links[t.id]?t.story=this._cleanCopy(this.links[t.id]):t&&t.linktype==="story"&&typeof t.uuid=="string"&&this.links[t.uuid]&&(t.story=this._cleanCopy(this.links[t.uuid]))}_insertRelations(e,r,t){if(t.indexOf(e.component+"."+r)>-1){if(typeof e[r]=="string")this.relations[e[r]]&&(e[r]=this._cleanCopy(this.relations[e[r]]));else if(e[r].constructor===Array){let s=[];e[r].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),e[r]=s}}}iterateTree(e,r){let t=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)t(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)(s.component&&s._uid||s.type==="link")&&(this._insertRelations(s,o,r),this._insertLinks(s,o)),t(s[o])}}};t(e.content)}async resolveLinks(e,r){let t=[];if(e.link_uuids){const s=e.link_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const c=Math.min(s,a+i);o.push(e.link_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:r.language,version:r.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{t.push(c)})}else t=e.links;t.forEach(s=>{this.links[s.uuid]=m(g({},s),{_stopResolving:!0})})}async resolveRelations(e,r){let t=[];if(e.rel_uuids){const s=e.rel_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const c=Math.min(s,a+i);o.push(e.rel_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:r.language,version:r.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{t.push(c)})}else t=e.rels;t.forEach(s=>{this.relations[s.uuid]=m(g({},s),{_stopResolving:!0})})}async resolveStories(e,r){let t=[];r.resolve_relations!==void 0&&r.resolve_relations.length>0&&(t=r.resolve_relations.split(","),await this.resolveRelations(e,r)),["1","story","url"].indexOf(r.resolve_links)>-1&&await this.resolveLinks(e,r);for(const s in this.relations)this.iterateTree(this.relations[s],t);e.story?this.iterateTree(e.story,t):e.stories.forEach(s=>{this.iterateTree(s,t)})}cacheResponse(e,r,t){return t===void 0&&(t=0),new Promise(async(s,o)=>{let i=b({url:e,params:r}),a=this.cacheProvider();if(this.cache.clear==="auto"&&r.version==="draft"&&await this.flushCache(),r.version==="published"&&e!="/cdn/spaces/me"){const l=await a.get(i);if(l)return s(l)}try{let l=await this.throttle("get",e,{params:r,paramsSerializer:y=>b(y)}),u={data:l.data,headers:l.headers};if(l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,r),r.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,u),u.data.cv&&(r.version=="draft"&&f[r.token]!=u.data.cv&&this.flushCache(),f[r.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(t+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${t} seconds.`),await(c=1e3*t,new Promise(u=>setTimeout(u,c))),this.cacheResponse(e,r,t).then(s).catch(o);o(l)}var c})}throttledRequest(e,r,t){return this.client[e](r,t)}cacheVersions(){return f}cacheVersion(){return f[this.accessToken]}setCacheVersion(e){this.accessToken&&(f[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>k[e],getAll:()=>k,set(e,r){k[e]=r},flush(){k={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var x=(n={})=>{const{apiOptions:e}=n;if(!e.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 $(e)}},M=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const I=(n,e,r={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(r).on(["input","published","change"],s=>{s.action=="input"&&s.story.id===n?e(s.story):window.location.reload()})})}},N=(n={})=>{const{bridge:e,accessToken:r,use:t=[],apiOptions:s={}}=n;s.accessToken=s.accessToken||r;const o={bridge:e,apiOptions:s};let i={};return t.forEach(a=>{i=g(g({},i),a(o))}),e!==!1&&j("https://app.storyblok.com/f/storyblok-v2-latest.js"),i};h.apiPlugin=x,h.storyblokEditable=M,h.storyblokInit=N,h.useStoryblokBridge=I,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
@@ -414,6 +414,10 @@ const useStoryblokBridge = (id, cb, options = {}) => {
414
414
  console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");
415
415
  return;
416
416
  }
417
+ if (!id) {
418
+ console.warn("Story ID is not defined. Please provide a valid ID.");
419
+ return;
420
+ }
417
421
  window.storyblokRegisterEvent(() => {
418
422
  const sbBridge = new window.StoryblokBridge(options);
419
423
  sbBridge.on(["input", "published", "change"], (event) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/js",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "SDK to integrate Storyblok into your project using JavaScript.",
5
5
  "main": "./dist/storyblok-js.js",
6
6
  "module": "./dist/storyblok-js.mjs",