@storyblok/js 2.1.3 → 2.1.4
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +28 -4
- package/dist/storyblok-js.js +25 -2
- package/dist/storyblok-js.mjs +37 -14
- package/package.json +4 -4
package/README.md
CHANGED
@@ -65,10 +65,6 @@ import { storyblokInit, apiPlugin } from "@storyblok/js";
|
|
65
65
|
const { storyblokApi } = storyblokInit({
|
66
66
|
accessToken: "YOUR_ACCESS_TOKEN",
|
67
67
|
use: [apiPlugin],
|
68
|
-
// if you are using a space located in US region, use apiOptions.region:
|
69
|
-
// apiOptions: {
|
70
|
-
// region: "us" // region code here
|
71
|
-
// }
|
72
68
|
});
|
73
69
|
```
|
74
70
|
|
@@ -76,6 +72,30 @@ That's it! All the features are enabled for you: the _Api Client_ for interactin
|
|
76
72
|
|
77
73
|
> You can enable/disable some of these features if you don't need them, so you save some KB. Please read the "Features and API" section
|
78
74
|
|
75
|
+
#### Region parameter
|
76
|
+
|
77
|
+
Possible values:
|
78
|
+
|
79
|
+
- `eu` (default): For spaces created in the EU
|
80
|
+
- `us`: For spaces created in the US
|
81
|
+
- `cn`: For spaces created in China
|
82
|
+
|
83
|
+
Full example for a space created in the US:
|
84
|
+
|
85
|
+
```js
|
86
|
+
import { storyblokInit, apiPlugin } from "@storyblok/js";
|
87
|
+
|
88
|
+
const { storyblokApi } = storyblokInit({
|
89
|
+
accessToken: "YOUR_ACCESS_TOKEN",
|
90
|
+
use: [apiPlugin],
|
91
|
+
apiOptions: {
|
92
|
+
region: "us",
|
93
|
+
},
|
94
|
+
});
|
95
|
+
```
|
96
|
+
|
97
|
+
> Note: For spaces created in the United States or China, the `region` parameter **must** be specified.
|
98
|
+
|
79
99
|
### Getting Started
|
80
100
|
|
81
101
|
`@storyblok/js` does three actions when you initialize it:
|
@@ -251,6 +271,10 @@ renderRichText(blok.richTextField, {
|
|
251
271
|
});
|
252
272
|
```
|
253
273
|
|
274
|
+
## The Storyblok JavaScript SDK Ecosystem
|
275
|
+
|
276
|
+
![A visual representation of the Storyblok JavaScript SDK Ecosystem](https://a.storyblok.com/f/88751/2400x1350/be4a4a4180/sdk-ecosystem.png/m/1200x0)
|
277
|
+
|
254
278
|
## 🔗 Related Links
|
255
279
|
|
256
280
|
- **[Storyblok Technology Hub](https://www.storyblok.com/technologies?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)**: Storyblok integrates with every framework so that you are free to choose the best fit for your project. We prepared the technology hub so that you can find selected beginner tutorials, videos, boilerplates, and even cheatsheets all in one place.
|
package/dist/storyblok-js.js
CHANGED
@@ -1,3 +1,26 @@
|
|
1
|
-
(function(d,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(d=typeof globalThis<"u"?globalThis:d||self,m(d.storyblok={}))})(this,function(d){"use strict";let m=!1;const R=[],_=n=>new Promise((e,t)=>{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}m?r():R.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=n,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{R.forEach(i=>i()),m=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var C=Object.defineProperty,O=(n,e,t)=>e in n?C(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,h=(n,e,t)=>(O(n,typeof e!="symbol"?e+"":e,t),t);function j(n){return!(n!==n||n===1/0||n===-1/0)}function A(n,e,t){if(!j(e))throw new TypeError("Expected `limit` to be a finite number");if(!j(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0;const o=function(){i++;const a=setTimeout(function(){i--,s.length>0&&o(),r=r.filter(function(u){return u!==a})},t);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(n.apply(l.self,l.args))},c=function(...a){const l=this;return new Promise(function(u,g){s.push({resolve:u,reject:g,args:a,self:l}),i<e&&o()})};return c.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},c}const N=function(n,e){const t={};for(const s in n){const r=n[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},M=n=>n==="email",L=()=>({singleTag:"hr"}),z=()=>({tag:"blockquote"}),U=()=>({tag:"ul"}),q=n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),B=()=>({singleTag:"br"}),H=n=>({tag:`h${n.attrs.level}`}),D=n=>({singleTag:[{tag:"img",attrs:N(n.attrs,["src","alt","title"])}]}),F=()=>({tag:"li"}),J=()=>({tag:"ol"}),V=()=>({tag:"p"}),Y=n=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:n.attrs.name,emoji:n.attrs.emoji}}]}),K=()=>({tag:"b"}),G=()=>({tag:"strike"}),Q=()=>({tag:"u"}),W=()=>({tag:"strong"}),X=()=>({tag:"code"}),Z=()=>({tag:"i"}),ee=n=>{const e={...n.attrs},{linktype:t="url"}=n.attrs;if(M(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),e.custom){for(const s in e.custom)e[s]=e.custom[s];delete e.custom}return{tag:[{tag:"a",attrs:e}]}},te=n=>({tag:[{tag:"span",attrs:n.attrs}]}),se=()=>({tag:"sub"}),re=()=>({tag:"sup"}),ie=n=>({tag:[{tag:"span",attrs:n.attrs}]}),oe=n=>({tag:[{tag:"span",attrs:{style:`background-color:${n.attrs.color};`}}]}),ne=n=>({tag:[{tag:"span",attrs:{style:`background-color:${n.attrs.color}`}}]}),P={nodes:{horizontal_rule:L,blockquote:z,bullet_list:U,code_block:q,hard_break:B,heading:H,image:D,list_item:F,ordered_list:J,paragraph:V,emoji:Y},marks:{bold:K,strike:G,underline:Q,strong:W,code:X,italic:Z,link:ee,styled:te,subscript:se,superscript:re,anchor:ie,highlight:oe,textStyle:ne}},ae=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return n&&s.test(n)?n.replace(t,r=>e[r]):n};class b{constructor(e){h(this,"marks"),h(this,"nodes"),e||(e=P),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,t={optimizeImages:!1}){if(e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(r=>{s+=this.renderNode(r)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn("The render method must receive an object with a content field, which is an array"),""}optimizeImages(e,t){let s=0,r=0,i="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(o+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(o+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(o+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(o+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(o+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(o+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(o+=`:rotate(${t.filters.rotate})`),o.length>0&&(o="/filters"+o))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const c=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,u;const g=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(g&&g.length>0){const f={srcset:(l=t.srcset)==null?void 0:l.map(p=>{if(typeof p=="number")return`//${g}/m/${p}x0${o} ${p}w`;if(typeof p=="object"&&p.length===2){let T=0,x=0;return typeof p[0]=="number"&&(T=p[0]),typeof p[1]=="number"&&(x=p[1]),`//${g}/m/${T}x${x}${o} ${T}w`}}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(p=>p).join(", ")};let $="";return f.srcset&&($+=`srcset="${f.srcset}" `),f.sizes&&($+=`sizes="${f.sizes}" `),a.replace(/<img/g,`<img ${$.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&t.push(this.renderOpeningTag(i.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(ae(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const i=this.getMatchingMark(r);i&&t.push(this.renderClosingTag(i.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs)for(const i in s.attrs){const o=s.attrs[i];o!==null&&(r+=` ${i}="${o}"`)}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}class v{constructor(){h(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),h(this,"delay",e=>new Promise(t=>setTimeout(t,e))),h(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),h(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(i,o)=>o*r+e)}),h(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),h(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const o=e[i],c=s?"":encodeURIComponent(i);let a;typeof o=="object"?a=this.stringify(o,t?t+encodeURIComponent("["+c+"]"):c,Array.isArray(o)):a=(t?t+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return r;default:return t}}}class le{constructor(e){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new v;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:o}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o});this.timeout&&clearTimeout(c);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(i)})}}let k={};const y={};class ce{constructor(e,t){if(h(this,"client"),h(this,"maxRetries"),h(this,"throttle"),h(this,"accessToken"),h(this,"cache"),h(this,"helpers"),h(this,"resolveCounter"),h(this,"relations"),h(this,"links"),h(this,"richTextResolver"),h(this,"resolveNestedRelations"),!t){const i=new v().getRegionURL,o=e.https===!1?"http":"https";e.oauthToken?t=`${o}://${i(e.region)}/v1`:t=`${o}://${i(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((i,o)=>{e.headers&&e.headers[o]&&s.set(o,e.headers[o])});let r=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new b(e.richTextSchema):this.richTextResolver=new b,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries,this.throttle=A(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new v,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new le({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,i)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,i=`/${e}`,o=i.split("/"),c=s||o[o.length-1],a=1,l=await this.makeRequest(i,t,r,a),u=l.total?Math.ceil(l.total/r):1,g=await this.helpers.asyncMap(this.helpers.range(a,u),f=>this.makeRequest(i,t,r,f+1));return this.helpers.flatMap([l,...g],f=>Object.values(f.data[c]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}_insertRelations(e,t,s,r){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[r][e[t]]&&(e[t]=this._cleanCopy(this.relations[r][e[t]]));else if(e[t]&&e[t].constructor===Array){const i=[];e[t].forEach(o=>{this.relations[r][o]&&i.push(this._cleanCopy(this.relations[r][o]))}),e[t]=i}}}iterateTree(e,t,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let o=0;o<i.length;o++)r(i[o]);else if(i.constructor===Object){if(i._stopResolving)return;for(const o in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,o,t,s),this._insertLinks(i,o,s)),r(i[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,o=[],c=50;for(let a=0;a<i;a+=c){const l=Math.min(i,a+c);o.push(e.link_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,o=[],c=50;for(let a=0;a<i;a+=c){const l=Math.min(i,a+c);o.push(e.rel_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var r,i;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(i=e.link_uuids)!=null&&i.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(c=>{this.iterateTree(c,o,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){const r=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const o=await i.get(r);if(o)return Promise.resolve(o)}return new Promise((o,c)=>{try{(async()=>{var a;try{const l=await this.throttle("get",e,t);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),l.status!=200)return c(l);if(u.data.story||u.data.stories){const g=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${g}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await i.set(r,u),u.data.cv&&t.token&&(t.version=="draft"&&y[t.token]!=u.data.cv&&await this.flushCache(),y[t.token]=u.data.cv),o(u)}catch(l){return c(l)}})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(k[e])},getAll(){return Promise.resolve(k)},set(e,t){return k[e]=t,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 he=(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 ce(e)}},ue=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};let w;const E="https://app.storyblok.com/f/storyblok-v2-latest.js",S=(n,e,t={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok")===n;if(!(!r||!o)){if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],l=>{l.action==="input"&&l.story.id===n?e(l.story):(l.action==="change"||l.action==="published")&&l.storyId===n&&window.location.reload()})})}},de=(n={})=>{var u,g;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:i={}}=n;r.accessToken=r.accessToken||t;const o={bridge:e,apiOptions:r};let c={};s.forEach(f=>{c={...c,...f(o)}});const l=!(typeof window>"u")&&((g=(u=window.location)==null?void 0:u.search)==null?void 0:g.includes("_storyblok_tk"));return e!==!1&&l&&_(E),w=new b(i.schema),i.resolver&&I(w,i.resolver),c},I=(n,e)=>{n.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},ge=(n,e,t)=>{let s=t||w;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(e&&(s=new b(e.schema),e.resolver&&I(s,e.resolver)),s.render(n)):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
1
|
+
(function(d,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(d=typeof globalThis<"u"?globalThis:d||self,m(d.storyblok={}))})(this,function(d){"use strict";let m=!1;const R=[],_=n=>new Promise((e,t)=>{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}m?r():R.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=n,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{R.forEach(i=>i()),m=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var C=Object.defineProperty,O=(n,e,t)=>e in n?C(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,h=(n,e,t)=>(O(n,typeof e!="symbol"?e+"":e,t),t);function j(n){return!(n!==n||n===1/0||n===-1/0)}function A(n,e,t){if(!j(e))throw new TypeError("Expected `limit` to be a finite number");if(!j(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0;const o=function(){i++;const a=setTimeout(function(){i--,s.length>0&&o(),r=r.filter(function(u){return u!==a})},t);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(n.apply(l.self,l.args))},c=function(...a){const l=this;return new Promise(function(u,p){s.push({resolve:u,reject:p,args:a,self:l}),i<e&&o()})};return c.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},c}const N=function(n,e){const t={};for(const s in n){const r=n[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},M=n=>n==="email",L=()=>({singleTag:"hr"}),z=()=>({tag:"blockquote"}),U=()=>({tag:"ul"}),q=n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),H=()=>({singleTag:"br"}),B=n=>({tag:`h${n.attrs.level}`}),D=n=>({singleTag:[{tag:"img",attrs:N(n.attrs,["src","alt","title"])}]}),F=()=>({tag:"li"}),J=()=>({tag:"ol"}),V=()=>({tag:"p"}),Y=n=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:n.attrs.name,emoji:n.attrs.emoji}}]}),K=()=>({tag:"b"}),W=()=>({tag:"strike"}),G=()=>({tag:"u"}),Q=()=>({tag:"strong"}),X=()=>({tag:"code"}),Z=()=>({tag:"i"}),ee=n=>{const e={...n.attrs},{linktype:t="url"}=n.attrs;if(M(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),e.custom){for(const s in e.custom)e[s]=e.custom[s];delete e.custom}return{tag:[{tag:"a",attrs:e}]}},te=n=>({tag:[{tag:"span",attrs:n.attrs}]}),se=()=>({tag:"sub"}),re=()=>({tag:"sup"}),ie=n=>({tag:[{tag:"span",attrs:n.attrs}]}),oe=n=>({tag:[{tag:"span",attrs:{style:`background-color:${n.attrs.color};`}}]}),ne=n=>({tag:[{tag:"span",attrs:{style:`color:${n.attrs.color}`}}]}),x={nodes:{horizontal_rule:L,blockquote:z,bullet_list:U,code_block:q,hard_break:H,heading:B,image:D,list_item:F,ordered_list:J,paragraph:V,emoji:Y},marks:{bold:K,strike:W,underline:G,strong:Q,code:X,italic:Z,link:ee,styled:te,subscript:se,superscript:re,anchor:ie,highlight:oe,textStyle:ne}},ae=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return n&&s.test(n)?n.replace(t,r=>e[r]):n};class b{constructor(e){h(this,"marks"),h(this,"nodes"),e||(e=x),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,t={optimizeImages:!1}){if(e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(r=>{s+=this.renderNode(r)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
|
2
|
+
The "content" field must be an array of nodes as the type ISbRichtext.
|
3
|
+
ISbRichtext:
|
4
|
+
content?: ISbRichtext[]
|
5
|
+
marks?: ISbRichtext[]
|
6
|
+
attrs?: any
|
7
|
+
text?: string
|
8
|
+
type: string
|
9
|
+
|
10
|
+
Example:
|
11
|
+
{
|
12
|
+
content: [
|
13
|
+
{
|
14
|
+
content: [
|
15
|
+
{
|
16
|
+
text: 'Hello World',
|
17
|
+
type: 'text'
|
18
|
+
}
|
19
|
+
],
|
20
|
+
type: 'paragraph'
|
21
|
+
}
|
22
|
+
],
|
23
|
+
type: 'doc'
|
24
|
+
}`),""}optimizeImages(e,t){let s=0,r=0,i="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(o+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(o+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(o+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(o+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(o+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(o+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(o+=`:rotate(${t.filters.rotate})`),o.length>0&&(o="/filters"+o))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const c=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(p&&p.length>0){const f={srcset:(l=t.srcset)==null?void 0:l.map(g=>{if(typeof g=="number")return`//${p}/m/${g}x0${o} ${g}w`;if(typeof g=="object"&&g.length===2){let T=0,P=0;return typeof g[0]=="number"&&(T=g[0]),typeof g[1]=="number"&&(P=g[1]),`//${p}/m/${T}x${P}${o} ${T}w`}}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(g=>g).join(", ")};let $="";return f.srcset&&($+=`srcset="${f.srcset}" `),f.sizes&&($+=`sizes="${f.sizes}" `),a.replace(/<img/g,`<img ${$.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&t.push(this.renderOpeningTag(i.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(ae(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const i=this.getMatchingMark(r);i&&t.push(this.renderClosingTag(i.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs)for(const i in s.attrs){const o=s.attrs[i];o!==null&&(r+=` ${i}="${o}"`)}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}class v{constructor(){h(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),h(this,"delay",e=>new Promise(t=>setTimeout(t,e))),h(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),h(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(i,o)=>o*r+e)}),h(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),h(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const o=e[i],c=s?"":encodeURIComponent(i);let a;typeof o=="object"?a=this.stringify(o,t?t+encodeURIComponent("["+c+"]"):c,Array.isArray(o)):a=(t?t+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return r;default:return t}}}class le{constructor(e){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new v;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:o}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o});this.timeout&&clearTimeout(c);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(i)})}}let k={};const y={};class ce{constructor(e,t){if(h(this,"client"),h(this,"maxRetries"),h(this,"throttle"),h(this,"accessToken"),h(this,"cache"),h(this,"helpers"),h(this,"resolveCounter"),h(this,"relations"),h(this,"links"),h(this,"richTextResolver"),h(this,"resolveNestedRelations"),!t){const i=new v().getRegionURL,o=e.https===!1?"http":"https";e.oauthToken?t=`${o}://${i(e.region)}/v1`:t=`${o}://${i(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((i,o)=>{e.headers&&e.headers[o]&&s.set(o,e.headers[o])});let r=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new b(e.richTextSchema):this.richTextResolver=new b,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=A(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new v,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new le({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,i)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,i=`/${e}`,o=i.split("/"),c=s||o[o.length-1],a=1,l=await this.makeRequest(i,t,r,a),u=l.total?Math.ceil(l.total/r):1,p=await this.helpers.asyncMap(this.helpers.range(a,u),f=>this.makeRequest(i,t,r,f+1));return this.helpers.flatMap([l,...p],f=>Object.values(f.data[c]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}_insertRelations(e,t,s,r){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[r][e[t]]&&(e[t]=this._cleanCopy(this.relations[r][e[t]]));else if(e[t]&&e[t].constructor===Array){const i=[];e[t].forEach(o=>{this.relations[r][o]&&i.push(this._cleanCopy(this.relations[r][o]))}),e[t]=i}}}iterateTree(e,t,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let o=0;o<i.length;o++)r(i[o]);else if(i.constructor===Object){if(i._stopResolving)return;for(const o in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,o,t,s),this._insertLinks(i,o,s)),r(i[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,o=[],c=50;for(let a=0;a<i;a+=c){const l=Math.min(i,a+c);o.push(e.link_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,o=[],c=50;for(let a=0;a<i;a+=c){const l=Math.min(i,a+c);o.push(e.rel_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var r,i;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(i=e.link_uuids)!=null&&i.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(c=>{this.iterateTree(c,o,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){const r=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const o=await i.get(r);if(o)return Promise.resolve(o)}return new Promise((o,c)=>{try{(async()=>{var a;try{const l=await this.throttle("get",e,t);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),l.status!=200)return c(l);if(u.data.story||u.data.stories){const p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${p}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await i.set(r,u),u.data.cv&&t.token&&(t.version=="draft"&&y[t.token]!=u.data.cv&&await this.flushCache(),y[t.token]=u.data.cv),o(u)}catch(l){return c(l)}})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(k[e])},getAll(){return Promise.resolve(k)},set(e,t){return k[e]=t,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 he=(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 ce(e)}},ue=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};let w;const S="https://app.storyblok.com/f/storyblok-v2-latest.js",E=(n,e,t={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok")===n;if(!(!r||!o)){if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],l=>{l.action==="input"&&l.story.id===n?e(l.story):(l.action==="change"||l.action==="published")&&l.storyId===n&&window.location.reload()})})}},de=(n={})=>{var u,p;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:i={}}=n;r.accessToken=r.accessToken||t;const o={bridge:e,apiOptions:r};let c={};s.forEach(f=>{c={...c,...f(o)}});const l=!(typeof window>"u")&&((p=(u=window.location)==null?void 0:u.search)==null?void 0:p.includes("_storyblok_tk"));return e!==!1&&l&&_(S),w=new b(i.schema),i.resolver&&I(w,i.resolver),c},I=(n,e)=>{n.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},pe=(n,e,t)=>{let s=t||w;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(e&&(s=new b(e.schema),e.resolver&&I(s,e.resolver)),s.render(n)):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
2
25
|
|
3
|
-
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},
|
26
|
+
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},ge=()=>_(S);d.RichTextResolver=b,d.RichTextSchema=x,d.apiPlugin=he,d.loadStoryblokBridge=ge,d.registerStoryblokBridge=E,d.renderRichText=pe,d.storyblokEditable=ue,d.storyblokInit=de,d.useStoryblokBridge=E,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
|
package/dist/storyblok-js.mjs
CHANGED
@@ -1,19 +1,19 @@
|
|
1
|
-
let
|
2
|
-
const
|
1
|
+
let R = !1;
|
2
|
+
const T = [], j = (n) => new Promise((e, t) => {
|
3
3
|
if (typeof window > "u" || (window.storyblokRegisterEvent = (r) => {
|
4
4
|
if (window.location === window.parent.location) {
|
5
5
|
console.warn("You are not in Draft Mode or in the Visual Editor.");
|
6
6
|
return;
|
7
7
|
}
|
8
|
-
|
8
|
+
R ? r() : T.push(r);
|
9
9
|
}, document.getElementById("storyblok-javascript-bridge")))
|
10
10
|
return;
|
11
11
|
const s = document.createElement("script");
|
12
12
|
s.async = !0, s.src = n, s.id = "storyblok-javascript-bridge", s.onerror = (r) => t(r), s.onload = (r) => {
|
13
|
-
|
13
|
+
T.forEach((i) => i()), R = !0, e(r);
|
14
14
|
}, document.getElementsByTagName("head")[0].appendChild(s);
|
15
15
|
});
|
16
|
-
var
|
16
|
+
var I = Object.defineProperty, P = (n, e, t) => e in n ? I(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, h = (n, e, t) => (P(n, typeof e != "symbol" ? e + "" : e, t), t);
|
17
17
|
function _(n) {
|
18
18
|
return !(n !== n || n === 1 / 0 || n === -1 / 0);
|
19
19
|
}
|
@@ -110,11 +110,11 @@ const C = function(n, e) {
|
|
110
110
|
tag: "u"
|
111
111
|
}), K = () => ({
|
112
112
|
tag: "strong"
|
113
|
-
}),
|
113
|
+
}), W = () => ({
|
114
114
|
tag: "code"
|
115
|
-
}),
|
115
|
+
}), G = () => ({
|
116
116
|
tag: "i"
|
117
|
-
}),
|
117
|
+
}), Q = (n) => {
|
118
118
|
const e = { ...n.attrs }, { linktype: t = "url" } = n.attrs;
|
119
119
|
if (O(t) && (e.href = `mailto:${e.href}`), e.anchor && (e.href = `${e.href}#${e.anchor}`, delete e.anchor), e.custom) {
|
120
120
|
for (const s in e.custom)
|
@@ -161,7 +161,7 @@ const C = function(n, e) {
|
|
161
161
|
{
|
162
162
|
tag: "span",
|
163
163
|
attrs: {
|
164
|
-
style: `
|
164
|
+
style: `color:${n.attrs.color}`
|
165
165
|
}
|
166
166
|
}
|
167
167
|
]
|
@@ -184,9 +184,9 @@ const C = function(n, e) {
|
|
184
184
|
strike: V,
|
185
185
|
underline: Y,
|
186
186
|
strong: K,
|
187
|
-
code:
|
188
|
-
italic:
|
189
|
-
link:
|
187
|
+
code: W,
|
188
|
+
italic: G,
|
189
|
+
link: Q,
|
190
190
|
styled: X,
|
191
191
|
subscript: Z,
|
192
192
|
superscript: ee,
|
@@ -222,7 +222,30 @@ class y {
|
|
222
222
|
}), t.optimizeImages ? this.optimizeImages(s, t.optimizeImages) : s;
|
223
223
|
}
|
224
224
|
return console.warn(
|
225
|
-
|
225
|
+
`The render method must receive an Object with a "content" field.
|
226
|
+
The "content" field must be an array of nodes as the type ISbRichtext.
|
227
|
+
ISbRichtext:
|
228
|
+
content?: ISbRichtext[]
|
229
|
+
marks?: ISbRichtext[]
|
230
|
+
attrs?: any
|
231
|
+
text?: string
|
232
|
+
type: string
|
233
|
+
|
234
|
+
Example:
|
235
|
+
{
|
236
|
+
content: [
|
237
|
+
{
|
238
|
+
content: [
|
239
|
+
{
|
240
|
+
text: 'Hello World',
|
241
|
+
type: 'text'
|
242
|
+
}
|
243
|
+
],
|
244
|
+
type: 'paragraph'
|
245
|
+
}
|
246
|
+
],
|
247
|
+
type: 'doc'
|
248
|
+
}`
|
226
249
|
), "";
|
227
250
|
}
|
228
251
|
optimizeImages(e, t) {
|
@@ -466,7 +489,7 @@ class ae {
|
|
466
489
|
e.headers && e.headers[o] && s.set(o, e.headers[o]);
|
467
490
|
});
|
468
491
|
let r = 5;
|
469
|
-
e.oauthToken && (s.set("Authorization", e.oauthToken), r = 3), e.rateLimit && (r = e.rateLimit), e.richTextSchema ? this.richTextResolver = new y(e.richTextSchema) : this.richTextResolver = new y(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries, this.throttle = S(this.throttledRequest, r, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new v(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || !0, this.client = new ne({
|
492
|
+
e.oauthToken && (s.set("Authorization", e.oauthToken), r = 3), e.rateLimit && (r = e.rateLimit), e.richTextSchema ? this.richTextResolver = new y(e.richTextSchema) : this.richTextResolver = new y(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries || 5, this.throttle = S(this.throttledRequest, r, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new v(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || !0, this.client = new ne({
|
470
493
|
baseURL: t,
|
471
494
|
timeout: e.timeout || 0,
|
472
495
|
headers: s,
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storyblok/js",
|
3
|
-
"version": "2.1.
|
3
|
+
"version": "2.1.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",
|
@@ -27,17 +27,17 @@
|
|
27
27
|
"prepublishOnly": "npm run build && cp ../README.md ./"
|
28
28
|
},
|
29
29
|
"dependencies": {
|
30
|
-
"storyblok-js-client": "^5.10.
|
30
|
+
"storyblok-js-client": "^5.10.5"
|
31
31
|
},
|
32
32
|
"devDependencies": {
|
33
33
|
"@tsconfig/recommended": "^1.0.1",
|
34
34
|
"cypress": "^12.3.0",
|
35
|
-
"eslint-plugin-cypress": "^2.
|
35
|
+
"eslint-plugin-cypress": "^2.13.3",
|
36
36
|
"eslint-plugin-jest": "^26.9.0",
|
37
37
|
"isomorphic-fetch": "^3.0.0",
|
38
38
|
"start-server-and-test": "^1.15.2",
|
39
39
|
"vite": "^4.0.4",
|
40
|
-
"vitest": "^0.
|
40
|
+
"vitest": "^0.31.0"
|
41
41
|
},
|
42
42
|
"babel": {
|
43
43
|
"presets": [
|