@storyblok/react 1.1.5 → 1.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/storyblok-react.js +2 -2
- package/dist/storyblok-react.mjs +23 -2
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -54,6 +54,7 @@ Install the file from the CDN:
|
|
|
54
54
|
### Initialization
|
|
55
55
|
|
|
56
56
|
Register the plugin on your application and add the [access token](https://www.storyblok.com/docs/api/content-delivery#topics/authentication?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-react) of your Storyblok space. You can also add the `apiPlugin` in case that you want to use the Storyblok API Client:
|
|
57
|
+
For Spaces created under `US` region, you should pass the region like `{ apiOptions: { region: 'us' } }`. If your space is under `EU`, no further configuration is required.
|
|
57
58
|
|
|
58
59
|
```js
|
|
59
60
|
import { storyblokInit, apiPlugin } from "@storyblok/react";
|
|
@@ -61,7 +62,9 @@ import { storyblokInit, apiPlugin } from "@storyblok/react";
|
|
|
61
62
|
storyblokInit({
|
|
62
63
|
accessToken: "YOUR_ACCESS_TOKEN",
|
|
63
64
|
// bridge: false,
|
|
64
|
-
|
|
65
|
+
apiOptions: {
|
|
66
|
+
region: 'us' // Pass this key/value if your space was created under US region
|
|
67
|
+
},
|
|
65
68
|
use: [apiPlugin],
|
|
66
69
|
components: {
|
|
67
70
|
page: Page,
|
package/dist/storyblok-react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(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
|
|
1
|
+
(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 pt=Object.defineProperty;var v=Object.getOwnPropertySymbols;var I=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var x=(l,h,p)=>h in l?pt(l,h,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[h]=p,L=(l,h)=>{for(var p in h||(h={}))I.call(h,p)&&x(l,p,h[p]);if(v)for(var p of v(h))q.call(h,p)&&x(l,p,h[p]);return l};var B=(l,h)=>{var p={};for(var f in l)I.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&&q.call(l,f)&&(p[f]=l[f]);return p};function f(n){return n&&typeof n=="object"&&"default"in n?n:{default:n}}var _=f(h),z=f(p),D=Object.defineProperty,U=Object.defineProperties,H=Object.getOwnPropertyDescriptors,$=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable,S=(n,t,e)=>t in n?D(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,g=(n,t)=>{for(var e in t||(t={}))V.call(t,e)&&S(n,e,t[e]);if($)for(var e of $(t))J.call(t,e)&&S(n,e,t[e]);return n},T=(n,t)=>U(n,H(t));let O=!1;const P=[],Y=n=>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():P.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=n,r.id="storyblok-javascript-bridge",r.onerror=s=>e(s),r.onload=s=>{P.forEach(o=>o()),O=!0,t(s)},document.getElementsByTagName("head")[0].appendChild(r)}),F=function(n,t){if(!n)return null;let e={};for(let r in n){let s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e},G=n=>n==="email";var Q={nodes:{horizontal_rule(){return{singleTag:"hr"}},blockquote(){return{tag:"blockquote"}},bullet_list(){return{tag:"ul"}},code_block(n){return{tag:["pre",{tag:"code",attrs:n.attrs}]}},hard_break(){return{singleTag:"br"}},heading(n){return{tag:`h${n.attrs.level}`}},image(n){return{singleTag:[{tag:"img",attrs:F(n.attrs,["src","alt","title"])}]}},list_item(){return{tag:"li"}},ordered_list(){return{tag:"ol"}},paragraph(){return{tag:"p"}}},marks:{bold(){return{tag:"b"}},strike(){return{tag:"strike"}},underline(){return{tag:"u"}},strong(){return{tag:"strong"}},code(){return{tag:"code"}},italic(){return{tag:"i"}},link(n){const t=g({},n.attrs),{linktype:e="url"}=n.attrs;return G(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled(n){return{tag:[{tag:"span",attrs:n.attrs}]}}}};const W=function(n){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,r=RegExp(e.source);return n&&r.test(n)?n.replace(e,s=>t[s]):n};class X{constructor(t){t||(t=Q),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 o=this.getMatchingMark(s);o&&e.push(this.renderOpeningTag(o.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(W(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 o=this.getMatchingMark(s);o&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let o=`<${s.tag}`;if(s.attrs)for(let i in s.attrs){let a=s.attrs[i];a!==null&&(o+=` ${i}="${a}"`)}return`${o}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.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)}}/*!
|
|
2
2
|
* storyblok-js-client v4.5.2
|
|
3
3
|
* Universal JavaScript SDK for Storyblok's API
|
|
4
4
|
* (c) 2020-2022 Stobylok Team
|
|
5
|
-
*/function j(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function A(n,t,e){if(!j(t))throw new TypeError("Expected `limit` to be a finite number");if(!j(e))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],o=0,i=function(){o++;var u=setTimeout(function(){o--,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(n.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}),o<t&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}A.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const X=function(n,t){if(!n)return null;let e={};for(let r in n){let s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e};var Z={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:X(n.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(n){const t=g({},n.attrs),{linktype:e="url"}=n.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:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class K{constructor(t){t||(t=Z),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 o=this.getMatchingMark(s);o&&e.push(this.renderOpeningTag(o.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 o={"&":"&","<":"<",">":">",'"':""","'":"'"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,u=>o[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 o=this.getMatchingMark(s);o&&e.push(this.renderClosingTag(o.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 o in r.attrs){let i=r.attrs[o];i!==null&&(s+=` ${o}="${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 tt=(n=0,t=n)=>{const e=Math.abs(t-n)||0,r=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(e,(s,o)=>o*r+n)},w=(n,t,e)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],i=e?"":encodeURIComponent(s);let a;a=typeof o=="object"?w(o,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(o)):(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")};let b={},y={};class et{constructor(t,e){if(!e){let o=t.region?`-${t.region}`:"",i=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${i}://api${o}.storyblok.com/v2`:`${i}://api${o}.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 K(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=A(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=B.default.create({baseURL:e,timeout:t.timeout||0,headers:r,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),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 o=this.factoryParamOptions(t,((i={},a=25,u=1)=>T(g({},i),{per_page:a,page:u}))(e,r,s));return this.cacheResponse(t,o)}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,o=`/${t}`,i=o.split("/");r=r||i[i.length-1];const a=await this.makeRequest(o,e,s,1),u=Math.ceil(a.total/s);return((c=[],d)=>c.map(d).reduce((k,ut)=>[...k,...ut],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(tt(1,u),async c=>this.makeRequest(o,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(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),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 o=0;o<s.length;o++)r(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,e),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,e),r(s[o])}}};r(t.content)}async resolveLinks(t,e){let r=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);o.push(t.link_uuids.slice(a,u))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(s=>{this.links[s.uuid]=T(g({},s),{_stopResolving:!0})})}async resolveRelations(t,e){let r=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);o.push(t.rel_uuids.slice(a,u))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r.forEach(s=>{this.relations[s.uuid]=T(g({},s),{_stopResolving:!0})})}async resolveStories(t,e){let r=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(r=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&(t.links||t.link_uuids)&&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 o of r)this.iterateTree(o,e);else{if(!s)return t;this.iterateTree(s,e)}}cacheResponse(t,e,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let i=w({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=>w(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 o(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(o);o(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 rt=(n={})=>{const{apiOptions:t}=n;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 et(t)}};var st=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};new W;const nt="https://app.storyblok.com/f/storyblok-v2-latest.js",$=(n,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(!n){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.story.id===n&&(s.action==="input"?t(s.story):window.location.reload())})})}},ot=(n={})=>{const{bridge:t,accessToken:e,use:r=[],apiOptions:s={}}=n;s.accessToken=s.accessToken||e;const o={bridge:t,apiOptions:s};let i={};return r.forEach(a=>{i=g(g({},i),a(o))}),t!==!1&&J(nt),i},it=e=>{var r=e,{blok:n}=r,t=L(r,["blok"]);if(!n)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=M(n.component);return s?_.default.createElement(s,q({blok:n},t)):_.default.createElement("div",null)},at=(n,t={},e={})=>{let[r,s]=h.useState({});return m?(h.useEffect(()=>{$(r.id,i=>s(i),e);async function o(){const{data:i}=await m.get(`cdn/stories/${n}`,t);s(i.story)}o()},[n]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},lt=(n={},t={},e=!0)=>{let[r,s]=h.useState(n);return e?(h.useEffect(()=>{$(r.id,o=>s(o),t),s(n)},[n]),r):n};let m=null;const C=()=>(m||console.error("You can't use getStoryblokApi if you're not loading apiPlugin."),m);let E={};const M=n=>E[n]?E[n]:(console.error(`Component ${n} doesn't exist.`),!1),ct=(n={})=>{const{storyblokApi:t}=ot(n);m=t,E=n.components};l.StoryblokComponent=it,l.apiPlugin=rt,l.getComponent=M,l.getStoryblokApi=C,l.storyblokEditable=st,l.storyblokInit=ct,l.useStoryblok=at,l.useStoryblokApi=C,l.useStoryblokBridge=$,l.useStoryblokState=lt,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
5
|
+
*/function j(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function A(n,t,e){if(!j(t))throw new TypeError("Expected `limit` to be a finite number");if(!j(e))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],o=0,i=function(){o++;var u=setTimeout(function(){o--,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(n.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}),o<t&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}A.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const Z=function(n,t){if(!n)return null;let e={};for(let r in n){let s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e};var K={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:Z(n.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(n){const t=g({},n.attrs),{linktype:e="url"}=n.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:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class tt{constructor(t){t||(t=K),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 o=this.getMatchingMark(s);o&&e.push(this.renderOpeningTag(o.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 o={"&":"&","<":"<",">":">",'"':""","'":"'"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,u=>o[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 o=this.getMatchingMark(s);o&&e.push(this.renderClosingTag(o.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 o in r.attrs){let i=r.attrs[o];i!==null&&(s+=` ${o}="${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 et=(n=0,t=n)=>{const e=Math.abs(t-n)||0,r=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(e,(s,o)=>o*r+n)},w=(n,t,e)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],i=e?"":encodeURIComponent(s);let a;a=typeof o=="object"?w(o,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(o)):(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")};let b={},y={};class rt{constructor(t,e){if(!e){let o=t.region?`-${t.region}`:"",i=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${i}://api${o}.storyblok.com/v2`:`${i}://api${o}.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 tt(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=A(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=z.default.create({baseURL:e,timeout:t.timeout||0,headers:r,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),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 o=this.factoryParamOptions(t,((i={},a=25,u=1)=>T(g({},i),{per_page:a,page:u}))(e,r,s));return this.cacheResponse(t,o)}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,o=`/${t}`,i=o.split("/");r=r||i[i.length-1];const a=await this.makeRequest(o,e,s,1),u=Math.ceil(a.total/s);return((c=[],d)=>c.map(d).reduce((k,dt)=>[...k,...dt],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(et(1,u),async c=>this.makeRequest(o,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(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),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 o=0;o<s.length;o++)r(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,e),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,e),r(s[o])}}};r(t.content)}async resolveLinks(t,e){let r=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);o.push(t.link_uuids.slice(a,u))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(s=>{this.links[s.uuid]=T(g({},s),{_stopResolving:!0})})}async resolveRelations(t,e){let r=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const u=Math.min(s,a+i);o.push(t.rel_uuids.slice(a,u))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r.forEach(s=>{this.relations[s.uuid]=T(g({},s),{_stopResolving:!0})})}async resolveStories(t,e){let r=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(r=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&(t.links||t.link_uuids)&&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 o of r)this.iterateTree(o,e);else{if(!s)return t;this.iterateTree(s,e)}}cacheResponse(t,e,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let i=w({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=>w(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 o(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(o);o(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 st=(n={})=>{const{apiOptions:t}=n;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 rt(t)}};var nt=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let C;const ot="https://app.storyblok.com/f/storyblok-v2-latest.js",E=(n,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(!n){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.story.id===n&&(s.action==="input"?t(s.story):window.location.reload())})})}},it=(n={})=>{const{bridge:t,accessToken:e,use:r=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||e;const i={bridge:t,apiOptions:s};let a={};return r.forEach(u=>{a=g(g({},a),u(i))}),t!==!1&&Y(ot),C=new X(o.schema),o.resolver&&at(C,o.resolver),a},at=(n,t)=>{n.addNode("blok",e=>{let r="";return e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})},lt=e=>{var r=e,{blok:n}=r,t=B(r,["blok"]);if(!n)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=N(n.component);return s?_.default.createElement(s,L({blok:n},t)):_.default.createElement("div",null)},ct=(n,t={},e={})=>{let[r,s]=h.useState({});return m?(h.useEffect(()=>{E(r.id,i=>s(i),e);async function o(){const{data:i}=await m.get(`cdn/stories/${n}`,t);s(i.story)}o()},[n]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},ut=(n={},t={},e=!0)=>{let[r,s]=h.useState(n);return e?(h.useEffect(()=>{E(r.id,o=>s(o),t),s(n)},[n]),r):n};let m=null;const M=()=>(m||console.error("You can't use getStoryblokApi if you're not loading apiPlugin."),m);let R={};const N=n=>R[n]?R[n]:(console.error(`Component ${n} doesn't exist.`),!1),ht=(n={})=>{const{storyblokApi:t}=it(n);m=t,R=n.components};l.StoryblokComponent=lt,l.apiPlugin=st,l.getComponent=N,l.getStoryblokApi=M,l.storyblokEditable=nt,l.storyblokInit=ht,l.useStoryblok=ct,l.useStoryblokApi=M,l.useStoryblokBridge=E,l.useStoryblokState=ut,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
package/dist/storyblok-react.mjs
CHANGED
|
@@ -712,7 +712,7 @@ var editable = (blok) => {
|
|
|
712
712
|
"data-blok-uid": options.id + "-" + options.uid
|
|
713
713
|
};
|
|
714
714
|
};
|
|
715
|
-
|
|
715
|
+
let richTextResolver;
|
|
716
716
|
const bridgeLatest = "https://app.storyblok.com/f/storyblok-v2-latest.js";
|
|
717
717
|
const useStoryblokBridge = (id, cb, options = {}) => {
|
|
718
718
|
if (typeof window === "undefined") {
|
|
@@ -739,7 +739,13 @@ const useStoryblokBridge = (id, cb, options = {}) => {
|
|
|
739
739
|
});
|
|
740
740
|
};
|
|
741
741
|
const storyblokInit$1 = (pluginOptions = {}) => {
|
|
742
|
-
const {
|
|
742
|
+
const {
|
|
743
|
+
bridge,
|
|
744
|
+
accessToken,
|
|
745
|
+
use = [],
|
|
746
|
+
apiOptions = {},
|
|
747
|
+
richText = {}
|
|
748
|
+
} = pluginOptions;
|
|
743
749
|
apiOptions.accessToken = apiOptions.accessToken || accessToken;
|
|
744
750
|
const options = { bridge, apiOptions };
|
|
745
751
|
let result = {};
|
|
@@ -749,8 +755,23 @@ const storyblokInit$1 = (pluginOptions = {}) => {
|
|
|
749
755
|
if (bridge !== false) {
|
|
750
756
|
loadBridge(bridgeLatest);
|
|
751
757
|
}
|
|
758
|
+
richTextResolver = new RichTextResolver(richText.schema);
|
|
759
|
+
if (richText.resolver) {
|
|
760
|
+
setComponentResolver(richTextResolver, richText.resolver);
|
|
761
|
+
}
|
|
752
762
|
return result;
|
|
753
763
|
};
|
|
764
|
+
const setComponentResolver = (resolver, resolveFn) => {
|
|
765
|
+
resolver.addNode("blok", (node) => {
|
|
766
|
+
let html = "";
|
|
767
|
+
node.attrs.body.forEach((blok) => {
|
|
768
|
+
html += resolveFn(blok.component, blok);
|
|
769
|
+
});
|
|
770
|
+
return {
|
|
771
|
+
html
|
|
772
|
+
};
|
|
773
|
+
});
|
|
774
|
+
};
|
|
754
775
|
const StoryblokComponent = (_a) => {
|
|
755
776
|
var _b = _a, {
|
|
756
777
|
blok
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storyblok/react",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.6",
|
|
4
4
|
"description": "SDK to integrate Storyblok into your project using React.",
|
|
5
5
|
"main": "./dist/storyblok-react.js",
|
|
6
6
|
"module": "./dist/storyblok-react.mjs",
|
|
@@ -24,24 +24,24 @@
|
|
|
24
24
|
"prepublishOnly": "npm run build && cp ../README.md ./"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@storyblok/js": "^1.
|
|
27
|
+
"@storyblok/js": "^1.8.0"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@babel/core": "^7.18.
|
|
30
|
+
"@babel/core": "^7.18.13",
|
|
31
31
|
"@babel/preset-env": "^7.18.10",
|
|
32
32
|
"@cypress/react": "^5.12.5",
|
|
33
33
|
"@cypress/vite-dev-server": "^2.2.3",
|
|
34
34
|
"@tsconfig/recommended": "^1.0.1",
|
|
35
|
-
"@types/react": "18.0.
|
|
35
|
+
"@types/react": "18.0.18",
|
|
36
36
|
"@vitejs/plugin-react": "^1.3.2",
|
|
37
|
-
"babel-jest": "^
|
|
37
|
+
"babel-jest": "^29.0.2",
|
|
38
38
|
"cypress": "^9.7.0",
|
|
39
39
|
"eslint-plugin-cypress": "^2.12.1",
|
|
40
|
-
"eslint-plugin-jest": "^
|
|
41
|
-
"jest": "^
|
|
40
|
+
"eslint-plugin-jest": "^27.0.1",
|
|
41
|
+
"jest": "^29.0.2",
|
|
42
42
|
"react": "^18.2.0",
|
|
43
43
|
"react-dom": "^18.2.0",
|
|
44
|
-
"vite": "^2.9.
|
|
44
|
+
"vite": "^2.9.15"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"react": "^17.0.0 || ^18.0.0",
|