@storyblok/react
Advanced tools
Comparing version 1.0.10 to 1.0.11
@@ -5,2 +5,2 @@ (function(l,h){typeof exports=="object"&&typeof module!="undefined"?h(exports,require("react"),require("axios")):typeof define=="function"&&define.amd?define(["exports","react","axios"],h):(l=typeof globalThis!="undefined"?globalThis:l||self,h(l.storyblokReact={},l.React,l.e))})(this,function(l,h,p){"use strict";var it=Object.defineProperty;var v=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var M=(l,h,p)=>h in l?it(l,h,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[h]=p,q=(l,h)=>{for(var p in h||(h={}))N.call(h,p)&&M(l,p,h[p]);if(v)for(var p of v(h))x.call(h,p)&&M(l,p,h[p]);return l};var B=(l,h)=>{var p={};for(var f in l)N.call(l,f)&&h.indexOf(f)<0&&(p[f]=l[f]);if(l!=null&&v)for(var f of v(l))h.indexOf(f)<0&&x.call(l,f)&&(p[f]=l[f]);return p};function f(o){return o&&typeof o=="object"&&"default"in o?o:{default:o}}var _=f(h),L=f(p),D=Object.defineProperty,z=Object.defineProperties,U=Object.getOwnPropertyDescriptors,E=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable,P=(o,t,e)=>t in o?D(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,g=(o,t)=>{for(var e in t||(t={}))V.call(t,e)&&P(o,e,t[e]);if(E)for(var e of E(t))J.call(t,e)&&P(o,e,t[e]);return o},w=(o,t)=>z(o,U(t));let O=!1;const $=[],Y=o=>new Promise((t,e)=>{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}O?s():$.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=o,r.id="storyblok-javascript-bridge",r.onerror=s=>e(s),r.onload=s=>{$.forEach(n=>n()),O=!0,t(s)},document.getElementsByTagName("head")[0].appendChild(r)});/*! | ||
* (c) 2020-2022 Stobylok Team | ||
*/function A(o){return typeof o=="number"&&o==o&&o!==1/0&&o!==-1/0}function j(o,t,e){if(!A(t))throw new TypeError("Expected `limit` to be a finite number");if(!A(e))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],n=0,i=function(){n++;var u=setTimeout(function(){n--,r.length>0&&i(),s=s.filter(function(d){return d!==u})},e);s.indexOf(u)<0&&s.push(u);var c=r.shift();c.resolve(o.apply(c.self,c.args))},a=function(){var u=arguments,c=this;return new Promise(function(d,k){r.push({resolve:d,reject:k,args:u,self:c}),n<t&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}j.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const F=function(o,t){if(!o)return null;let e={};for(let r in o){let s=o[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e};var H={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:o=>({tag:`h${o.attrs.level}`}),image:o=>({singleTag:[{tag:"img",attrs:F(o.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(o){const t=g({},o.attrs),{linktype:e="url"}=o.attrs;return e==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:o=>({tag:[{tag:"span",attrs:o.attrs}]})}};class G{constructor(t){t||(t=H),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.content&&Array.isArray(t.content)){let e="";return t.content.forEach(r=>{e+=this.renderNode(r)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(s=>{const n=this.getMatchingMark(s);n&&e.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(t);return r&&r.tag&&e.push(this.renderOpeningTag(r.tag)),t.content?t.content.forEach(s=>{e.push(this.renderNode(s))}):t.text?e.push(function(s){const n={"&":"&","<":"<",">":">",'"':""","'":"'"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,u=>n[u]):s}(t.text)):r&&r.singleTag?e.push(this.renderTag(r.singleTag," /")):r&&r.html&&e.push(r.html),r&&r.tag&&e.push(this.renderClosingTag(r.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const n=this.getMatchingMark(s);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let s=`<${r.tag}`;if(r.attrs)for(let n in r.attrs){let i=r.attrs[n];i!==null&&(s+=` ${n}="${i}"`)}return`${s}${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){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const Q=(o=0,t=o)=>{const e=Math.abs(t-o)||0,r=o<t?1:-1;return((s=0,n)=>[...Array(s)].map(n))(e,(s,n)=>n*r+o)},T=(o,t,e)=>{const r=[];for(const s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;const n=o[s],i=e?"":encodeURIComponent(s);let a;a=typeof n=="object"?T(n,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let b={},y={};class W{constructor(t,e){if(!e){let n=t.region?`-${t.region}`:"",i=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(r.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new G(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=j(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=L.default.create({baseURL:e,timeout:t.timeout||0,headers:r,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(n=>t.responseInterceptor(n)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let r="";return e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=y[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e={}){return((r="")=>r.indexOf("/cdn/")>-1)(t)?this.parseParams(e):e}makeRequest(t,e,r,s){const n=this.factoryParamOptions(t,((i={},a=25,u=1)=>w(g({},i),{per_page:a,page:u}))(e,r,s));return this.cacheResponse(t,n)}get(t,e){let r=`/${t}`;const s=this.factoryParamOptions(r,e);return this.cacheResponse(r,s)}async getAll(t,e={},r){const s=e.per_page||25,n=`/${t}`,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,e,s,1),u=Math.ceil(a.total/s);return((c=[],d)=>c.map(d).reduce((k,nt)=>[...k,...nt],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(Q(1,u),async c=>this.makeRequest(n,e,s,c+1))],c=>Object.values(c.data[r]))}post(t,e){let r=`/${t}`;return this.throttle("post",r,e)}put(t,e){let r=`/${t}`;return this.throttle("put",r,e)}delete(t,e){let r=`/${t}`;return this.throttle("delete",r,e)}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const r=t[e];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(t,e,r){if(r.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].constructor===Array){let s=[];t[e].forEach(n=>{this.relations[n]&&s.push(this._cleanCopy(this.relations[n]))}),t[e]=s}}}_insertAssetsRelations(t,e){e.forEach(r=>{t.id===r.id&&(t.original=r,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,e){let r=s=>{if(s!=null){if(s.constructor===Array)for(let n=0;n<s.length;n++)r(s[n]);else if(s.constructor===Object){if(s._stopResolving)return;for(let n in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,n,e),this._insertLinks(s,n)):s.fieldtype==="asset"&&this._insertAssetsRelations(s,e),r(s[n])}}};r(t.content)}async resolveLinks(t,e){let r=[];if(t.link_uuids){const s=t.link_uuids.length;let n=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);n.push(t.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(s=>{this.links[s.uuid]=w(g({},s),{_stopResolving:!0})})}async resolveRelations(t,e){let r=[];if(t.rel_uuids){const s=t.rel_uuids.length;let n=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);n.push(t.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r.forEach(s=>{this.relations[s.uuid]=w(g({},s),{_stopResolving:!0})})}async resolveStories(t,e){let r=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(r=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);t.story?this.iterateTree(t.story,r):t.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(t){const{assets:e,stories:r,story:s}=t;if(r)for(const n of r)this.iterateTree(n,e);else this.iterateTree(s,e)}cacheResponse(t,e,r){return r===void 0&&(r=0),new Promise(async(s,n)=>{let i=T({url:t,params:e}),a=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const c=await a.get(i);if(c)return s(c)}try{let c=await this.throttle("get",t,{params:e,paramsSerializer:k=>T(k)}),d={data:c.data,headers:c.headers};if(d.data.assets&&d.data.assets.length&&this.resolveAssetsRelations(d.data),c.headers["per-page"]&&(d=Object.assign({},d,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(d.data.story||d.data.stories)&&await this.resolveStories(d.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&a.set(i,d),d.data.cv&&(e.version=="draft"&&y[e.token]!=d.data.cv&&this.flushCache(),y[e.token]=d.data.cv),s(d)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(u=1e3*r,new Promise(d=>setTimeout(d,u))),this.cacheResponse(t,e,r).then(s).catch(n);n(c)}var u})}throttledRequest(t,e,r){return this.client[t](e,r)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(t){this.accessToken&&(y[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>b[t],getAll:()=>b,set(t,e){b[t]=e},flush(){b={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const X=(o={})=>{const{apiOptions:t}=o;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 W(t)}};var Z=o=>{if(typeof o!="object"||typeof o._editable=="undefined")return{};const t=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};const K="https://app.storyblok.com/f/storyblok-v2-latest.js",R=(o,t,e={})=>{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(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],s=>{s.action=="input"&&s.story.id===o?t(s.story):window.location.reload()})})}},tt=(o={})=>{const{bridge:t,accessToken:e,use:r=[],apiOptions:s={}}=o;s.accessToken=s.accessToken||e;const n={bridge:t,apiOptions:s};let i={};return r.forEach(a=>{i=g(g({},i),a(n))}),t!==!1&&Y(K),i},et=e=>{var r=e,{blok:o}=r,t=B(r,["blok"]);if(!o)return console.error("Please provide a 'blok' property to the StoryblokComponent"),_.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const s=I(o.component);return s?_.default.createElement(s,q({blok:o},t)):_.default.createElement("div",null)},rt=(o,t={},e={})=>{let[r,s]=h.useState({});return m?(R(r.id,n=>s(n),e),h.useEffect(()=>{async function n(){const{data:i}=await m.get(`cdn/stories/${o}`,t);s(i.story)}n()},[o]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},st=(o={},t={},e=!1)=>{let[r,s]=h.useState(o);return e?o:(R(r.id,n=>s(n),t),h.useEffect(()=>{s(o)},[o]),r)};let m=null;const C=()=>(m||console.error("You can't use getStoryblokApi if you're not loading apiPlugin."),m);let S={};const I=o=>S[o]?S[o]:(console.error(`Component ${o} doesn't exist.`),!1),ot=(o={})=>{const{storyblokApi:t}=tt(o);m=t,S=o.components};l.StoryblokComponent=et,l.apiPlugin=X,l.getComponent=I,l.getStoryblokApi=C,l.storyblokEditable=Z,l.storyblokInit=ot,l.useStoryblok=rt,l.useStoryblokApi=C,l.useStoryblokBridge=R,l.useStoryblokState=st,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); | ||
*/function A(o){return typeof o=="number"&&o==o&&o!==1/0&&o!==-1/0}function j(o,t,e){if(!A(t))throw new TypeError("Expected `limit` to be a finite number");if(!A(e))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],n=0,i=function(){n++;var u=setTimeout(function(){n--,r.length>0&&i(),s=s.filter(function(d){return d!==u})},e);s.indexOf(u)<0&&s.push(u);var c=r.shift();c.resolve(o.apply(c.self,c.args))},a=function(){var u=arguments,c=this;return new Promise(function(d,k){r.push({resolve:d,reject:k,args:u,self:c}),n<t&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}j.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const F=function(o,t){if(!o)return null;let e={};for(let r in o){let s=o[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e};var H={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:o=>({tag:`h${o.attrs.level}`}),image:o=>({singleTag:[{tag:"img",attrs:F(o.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(o){const t=g({},o.attrs),{linktype:e="url"}=o.attrs;return e==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:o=>({tag:[{tag:"span",attrs:o.attrs}]})}};class G{constructor(t){t||(t=H),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.content&&Array.isArray(t.content)){let e="";return t.content.forEach(r=>{e+=this.renderNode(r)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(s=>{const n=this.getMatchingMark(s);n&&e.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(t);return r&&r.tag&&e.push(this.renderOpeningTag(r.tag)),t.content?t.content.forEach(s=>{e.push(this.renderNode(s))}):t.text?e.push(function(s){const n={"&":"&","<":"<",">":">",'"':""","'":"'"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,u=>n[u]):s}(t.text)):r&&r.singleTag?e.push(this.renderTag(r.singleTag," /")):r&&r.html&&e.push(r.html),r&&r.tag&&e.push(this.renderClosingTag(r.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const n=this.getMatchingMark(s);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let s=`<${r.tag}`;if(r.attrs)for(let n in r.attrs){let i=r.attrs[n];i!==null&&(s+=` ${n}="${i}"`)}return`${s}${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){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const Q=(o=0,t=o)=>{const e=Math.abs(t-o)||0,r=o<t?1:-1;return((s=0,n)=>[...Array(s)].map(n))(e,(s,n)=>n*r+o)},T=(o,t,e)=>{const r=[];for(const s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;const n=o[s],i=e?"":encodeURIComponent(s);let a;a=typeof n=="object"?T(n,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let b={},y={};class W{constructor(t,e){if(!e){let n=t.region?`-${t.region}`:"",i=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(r.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new G(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=j(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=L.default.create({baseURL:e,timeout:t.timeout||0,headers:r,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(n=>t.responseInterceptor(n)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let r="";return e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=y[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e={}){return((r="")=>r.indexOf("/cdn/")>-1)(t)?this.parseParams(e):e}makeRequest(t,e,r,s){const n=this.factoryParamOptions(t,((i={},a=25,u=1)=>w(g({},i),{per_page:a,page:u}))(e,r,s));return this.cacheResponse(t,n)}get(t,e){let r=`/${t}`;const s=this.factoryParamOptions(r,e);return this.cacheResponse(r,s)}async getAll(t,e={},r){const s=e.per_page||25,n=`/${t}`,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,e,s,1),u=Math.ceil(a.total/s);return((c=[],d)=>c.map(d).reduce((k,nt)=>[...k,...nt],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(Q(1,u),async c=>this.makeRequest(n,e,s,c+1))],c=>Object.values(c.data[r]))}post(t,e){let r=`/${t}`;return this.throttle("post",r,e)}put(t,e){let r=`/${t}`;return this.throttle("put",r,e)}delete(t,e){let r=`/${t}`;return this.throttle("delete",r,e)}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const r=t[e];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(t,e,r){if(r.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].constructor===Array){let s=[];t[e].forEach(n=>{this.relations[n]&&s.push(this._cleanCopy(this.relations[n]))}),t[e]=s}}}_insertAssetsRelations(t,e){e.forEach(r=>{t.id===r.id&&(t.original=r,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,e){let r=s=>{if(s!=null){if(s.constructor===Array)for(let n=0;n<s.length;n++)r(s[n]);else if(s.constructor===Object){if(s._stopResolving)return;for(let n in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,n,e),this._insertLinks(s,n)):s.fieldtype==="asset"&&this._insertAssetsRelations(s,e),r(s[n])}}};r(t.content)}async resolveLinks(t,e){let r=[];if(t.link_uuids){const s=t.link_uuids.length;let n=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);n.push(t.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(s=>{this.links[s.uuid]=w(g({},s),{_stopResolving:!0})})}async resolveRelations(t,e){let r=[];if(t.rel_uuids){const s=t.rel_uuids.length;let n=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);n.push(t.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r.forEach(s=>{this.relations[s.uuid]=w(g({},s),{_stopResolving:!0})})}async resolveStories(t,e){let r=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(r=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);t.story?this.iterateTree(t.story,r):t.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(t){const{assets:e,stories:r,story:s}=t;if(r)for(const n of r)this.iterateTree(n,e);else this.iterateTree(s,e)}cacheResponse(t,e,r){return r===void 0&&(r=0),new Promise(async(s,n)=>{let i=T({url:t,params:e}),a=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const c=await a.get(i);if(c)return s(c)}try{let c=await this.throttle("get",t,{params:e,paramsSerializer:k=>T(k)}),d={data:c.data,headers:c.headers};if(d.data.assets&&d.data.assets.length&&this.resolveAssetsRelations(d.data),c.headers["per-page"]&&(d=Object.assign({},d,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(d.data.story||d.data.stories)&&await this.resolveStories(d.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&a.set(i,d),d.data.cv&&(e.version=="draft"&&y[e.token]!=d.data.cv&&this.flushCache(),y[e.token]=d.data.cv),s(d)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(u=1e3*r,new Promise(d=>setTimeout(d,u))),this.cacheResponse(t,e,r).then(s).catch(n);n(c)}var u})}throttledRequest(t,e,r){return this.client[t](e,r)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(t){this.accessToken&&(y[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>b[t],getAll:()=>b,set(t,e){b[t]=e},flush(){b={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const X=(o={})=>{const{apiOptions:t}=o;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 W(t)}};var Z=o=>{if(typeof o!="object"||typeof o._editable=="undefined")return{};const t=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};const K="https://app.storyblok.com/f/storyblok-v2-latest.js",R=(o,t,e={})=>{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(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],s=>{s.action=="input"&&s.story.id===o?t(s.story):window.location.reload()})})}},tt=(o={})=>{const{bridge:t,accessToken:e,use:r=[],apiOptions:s={}}=o;s.accessToken=s.accessToken||e;const n={bridge:t,apiOptions:s};let i={};return r.forEach(a=>{i=g(g({},i),a(n))}),t!==!1&&Y(K),i},et=e=>{var r=e,{blok:o}=r,t=B(r,["blok"]);if(!o)return console.error("Please provide a 'blok' property to the StoryblokComponent"),_.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const s=I(o.component);return s?_.default.createElement(s,q({blok:o},t)):_.default.createElement("div",null)},rt=(o,t={},e={})=>{let[r,s]=h.useState({});return m?(R(r.id,n=>s(n),e),h.useEffect(()=>{async function n(){const{data:i}=await m.get(`cdn/stories/${o}`,t);s(i.story)}n()},[o]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},st=(o={},t={},e=!0)=>{let[r,s]=h.useState(o);return e?(R(r.id,n=>s(n),t),h.useEffect(()=>{s(o)},[o]),r):o};let m=null;const C=()=>(m||console.error("You can't use getStoryblokApi if you're not loading apiPlugin."),m);let S={};const I=o=>S[o]?S[o]:(console.error(`Component ${o} doesn't exist.`),!1),ot=(o={})=>{const{storyblokApi:t}=tt(o);m=t,S=o.components};l.StoryblokComponent=et,l.apiPlugin=X,l.getComponent=I,l.getStoryblokApi=C,l.storyblokEditable=Z,l.storyblokInit=ot,l.useStoryblok=rt,l.useStoryblokApi=C,l.useStoryblokBridge=R,l.useStoryblokState=st,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); |
{ | ||
"name": "@storyblok/react", | ||
"version": "1.0.10", | ||
"version": "1.0.11", | ||
"description": "SDK to integrate Storyblok into your project using React.", | ||
@@ -30,4 +30,4 @@ "main": "./dist/storyblok-react.js", | ||
"devDependencies": { | ||
"@babel/core": "^7.18.2", | ||
"@babel/preset-env": "^7.18.2", | ||
"@babel/core": "^7.18.6", | ||
"@babel/preset-env": "^7.18.6", | ||
"@cypress/react": "^5.12.5", | ||
@@ -38,9 +38,9 @@ "@cypress/vite-dev-server": "^2.2.3", | ||
"@vitejs/plugin-react": "^1.3.2", | ||
"babel-jest": "^28.1.0", | ||
"babel-jest": "^28.1.2", | ||
"cypress": "^9.7.0", | ||
"eslint-plugin-cypress": "^2.12.1", | ||
"eslint-plugin-jest": "^26.5.3", | ||
"jest": "^28.1.0", | ||
"jest": "^28.1.2", | ||
"react": "18.1.0", | ||
"vite": "^2.9.9" | ||
"vite": "^2.9.13" | ||
}, | ||
@@ -47,0 +47,0 @@ "babel": { |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
51678