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

storyblok-js-client

Package Overview
Dependencies
Maintainers
7
Versions
197
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

storyblok-js-client - npm Package Compare versions

Comparing version 5.5.1 to 5.6.0

tests/constants/richTextResolver.js

2

dist/index.umd.js

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

(function(f,d){typeof exports=="object"&&typeof module<"u"?module.exports=d():typeof define=="function"&&define.amd?define(d):(f=typeof globalThis<"u"?globalThis:f||self,f.StoryblokJSClient=d())})(this,function(){"use strict";var S=Object.defineProperty;var $=(f,d,p)=>d in f?S(f,d,{enumerable:!0,configurable:!0,writable:!0,value:p}):f[d]=p;var h=(f,d,p)=>($(f,typeof d!="symbol"?d+"":d,p),p);function f(a){return!(a!==a||a===1/0||a===-1/0)}function d(a,t,e){if(!f(t))throw new TypeError("Expected `limit` to be a finite number");if(!f(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const i=function(){n++;const o=setTimeout(function(){n--,s.length>0&&i(),r=r.filter(function(u){return u!==o})},e);r.indexOf(o)<0&&r.push(o);const l=s.shift();l.resolve(a.apply(l.self,l.args))},c=function(...o){const l=this;return new Promise(function(u,y){s.push({resolve:u,reject:y,args:o,self:l}),n<t&&i()})};return c.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},c}const p=function(a,t){const e={};for(const s in a){const r=a[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},P=a=>a==="email",T={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:p(a.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:a=>{const t={...a.attrs},{linktype:e="url"}=a.attrs;return P(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]})}},x=function(a){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,s=RegExp(e.source);return a&&s.test(a)?a.replace(e,r=>t[r]):a};class v{constructor(t){h(this,"marks");h(this,"nodes");t||(t=T),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t){if(t&&t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(s=>{e+=this.renderNode(s)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(x(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html&&e.push(s.html),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let n=`<${r.tag}`;if(r.attrs)for(const i in r.attrs){const c=r.attrs[i];c!==null&&(n+=` ${i}="${c}"`)}return`${n}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}class k{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s}));h(this,"delay",t=>new Promise(e=>setTimeout(e,t)));h(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e));h(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(n,i)=>i*r+t)});h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e)));h(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const i=t[n],c=s?"":encodeURIComponent(n);let o;typeof i=="object"?o=this.stringify(i,e?e+encodeURIComponent("["+c+"]"):c,Array.isArray(i)):o=(e?e+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(i),r.push(o)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}const C=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:k},Symbol.toStringTag,{value:"Module"}));class b{constructor(t){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=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const o=new k;e=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),n=new AbortController,{signal:i}=n;let c;this.timeout&&(c=setTimeout(()=>n.abort(),this.timeout));try{const o=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:i});this.timeout&&clearTimeout(c);const l=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(o){return{message:o}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const n={message:new Error(t.statusText),status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};r(n)})}}let m={};const g={};class _{constructor(t,e){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");if(!e){const n=new k().getRegionURL,i=t.https===!1?"http":"https";t.oauthToken?e=`${i}://${n(t.region)}/v1`:e=`${i}://${n(t.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((n,i)=>{t.headers&&t.headers[i]&&s.set(i,t.headers[i])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new v(t.richTextSchema):this.richTextResolver=new v,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=d(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=!1,this.client=new b({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=g[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const n=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,n)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,n=`/${t}`,i=n.split("/"),c=s||i[i.length-1],o=1,l=await this.makeRequest(n,e,r,o),u=l.total?Math.ceil(l.total/r):1,y=await this.helpers.asyncMap(this.helpers.range(o,u),R=>this.makeRequest(n,e,r,R+1));return this.helpers.flatMap([l,...y],R=>Object.values(R.data[c]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];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(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const n=[];t[e].forEach(i=>{this.relations[r][i]&&n.push(this._cleanCopy(this.relations[r][i]))}),t[e]=n}}}iterateTree(t,e,s){const r=n=>{if(n!=null){if(n.constructor===Array)for(let i=0;i<n.length;i++)r(n[i]);else if(n.constructor===Object){if(n._stopResolving)return;for(const i in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,i,e,s),this._insertLinks(n,i,s)),r(n[i])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const n=t.link_uuids.length,i=[],c=50;for(let o=0;o<n;o+=c){const l=Math.min(n,o+c);i.push(t.link_uuids.slice(o,l))}for(let o=0;o<i.length;o++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:i[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const n=t.rel_uuids.length,i=[],c=50;for(let o=0;o<n;o+=c){const l=Math.min(n,o+c);i.push(t.rel_uuids.slice(o,l))}for(let o=0;o<i.length;o++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:i[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(t,e,s){var n,i;let r=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(r=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((n=t.links)!=null&&n.length||(i=t.link_uuids)!=null&&i.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],r,s);t.story?this.iterateTree(t.story,r,s):t.stories.forEach(c=>{this.iterateTree(c,r,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){const r=this.helpers.stringify({url:t,params:e}),n=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const i=await n.get(r);if(i)return Promise.resolve(i)}return new Promise((i,c)=>{try{(async()=>{var o;try{const l=await this.throttle("get",t,e);let u={data:l.data,headers:l.headers};if((o=l.headers)!=null&&o["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 y=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${y}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&g[e.token]!=u.data.cv&&await this.flushCache(),g[e.token]=u.data.cv),i(u)}catch(l){return c(l)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(m[t])},getAll(){return Promise.resolve(m)},set(t,e){return m[t]=e,Promise.resolve(void 0)},flush(){return m={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this}}const w=(a,t)=>{for(const e in t)a[e]=t[e]};return w(_,{RichtextResolver:v,SbFetch:b,RichTextSchema:T}),w(_,C),_});
(function(d,f){typeof exports=="object"&&typeof module<"u"?module.exports=f():typeof define=="function"&&define.amd?define(f):(d=typeof globalThis<"u"?globalThis:d||self,d.StoryblokJSClient=f())})(this,function(){"use strict";var C=Object.defineProperty;var S=(d,f,p)=>f in d?C(d,f,{enumerable:!0,configurable:!0,writable:!0,value:p}):d[f]=p;var h=(d,f,p)=>(S(d,typeof f!="symbol"?f+"":f,p),p);function d(a){return!(a!==a||a===1/0||a===-1/0)}function f(a,t,e){if(!d(t))throw new TypeError("Expected `limit` to be a finite number");if(!d(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const i=function(){n++;const o=setTimeout(function(){n--,s.length>0&&i(),r=r.filter(function(u){return u!==o})},e);r.indexOf(o)<0&&r.push(o);const c=s.shift();c.resolve(a.apply(c.self,c.args))},l=function(...o){const c=this;return new Promise(function(u,y){s.push({resolve:u,reject:y,args:o,self:c}),n<t&&i()})};return l.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}const p=function(a,t){const e={};for(const s in a){const r=a[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},P=a=>a==="email",R={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:p(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:a=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:a.attrs.name}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{const t={...a.attrs},{linktype:e="url"}=a.attrs;if(P(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const s in t.custom)t[s]=t.custom[s];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"})}},$=function(a){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,s=RegExp(e.source);return a&&s.test(a)?a.replace(e,r=>t[r]):a};class v{constructor(t){h(this,"marks");h(this,"nodes");t||(t=R),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t,e={optimizeImages:!1}){if(t&&t.content&&Array.isArray(t.content)){let s="";return t.content.forEach(r=>{s+=this.renderNode(r)}),e.optimizeImages?s.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,"a.storyblok.com/f/$1/$2.$3/m/"):s}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push($(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html&&e.push(s.html),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let n=`<${r.tag}`;if(r.attrs)for(const i in r.attrs){const l=r.attrs[i];l!==null&&(n+=` ${i}="${l}"`)}return`${n}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}class k{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s}));h(this,"delay",t=>new Promise(e=>setTimeout(e,t)));h(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e));h(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(n,i)=>i*r+t)});h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e)));h(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const i=t[n],l=s?"":encodeURIComponent(n);let o;typeof i=="object"?o=this.stringify(i,e?e+encodeURIComponent("["+l+"]"):l,Array.isArray(i)):o=(e?e+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(i),r.push(o)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}const x=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:k},Symbol.toStringTag,{value:"Module"}));class T{constructor(t){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=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const o=new k;e=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),n=new AbortController,{signal:i}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const o=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:i});this.timeout&&clearTimeout(l);const c=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(o){return{message:o}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const n={message:new Error(t.statusText),status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};r(n)})}}let m={};const g={};class _{constructor(t,e){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");if(!e){const n=new k().getRegionURL,i=t.https===!1?"http":"https";t.oauthToken?e=`${i}://${n(t.region)}/v1`:e=`${i}://${n(t.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((n,i)=>{t.headers&&t.headers[i]&&s.set(i,t.headers[i])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new v(t.richTextSchema):this.richTextResolver=new v,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=f(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=!1,this.client=new T({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=g[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const n=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,n)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,n=`/${t}`,i=n.split("/"),l=s||i[i.length-1],o=1,c=await this.makeRequest(n,e,r,o),u=c.total?Math.ceil(c.total/r):1,y=await this.helpers.asyncMap(this.helpers.range(o,u),b=>this.makeRequest(n,e,r,b+1));return this.helpers.flatMap([c,...y],b=>Object.values(b.data[l]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];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(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const n=[];t[e].forEach(i=>{this.relations[r][i]&&n.push(this._cleanCopy(this.relations[r][i]))}),t[e]=n}}}iterateTree(t,e,s){const r=n=>{if(n!=null){if(n.constructor===Array)for(let i=0;i<n.length;i++)r(n[i]);else if(n.constructor===Object){if(n._stopResolving)return;for(const i in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,i,e,s),this._insertLinks(n,i,s)),r(n[i])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const n=t.link_uuids.length,i=[],l=50;for(let o=0;o<n;o+=l){const c=Math.min(n,o+l);i.push(t.link_uuids.slice(o,c))}for(let o=0;o<i.length;o++)(await this.getStories({per_page:l,language:e.language,version:e.version,by_uuids:i[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const n=t.rel_uuids.length,i=[],l=50;for(let o=0;o<n;o+=l){const c=Math.min(n,o+l);i.push(t.rel_uuids.slice(o,c))}for(let o=0;o<i.length;o++)(await this.getStories({per_page:l,language:e.language,version:e.version,by_uuids:i[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=t.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(t,e,s){var n,i;let r=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(r=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((n=t.links)!=null&&n.length||(i=t.link_uuids)!=null&&i.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],r,s);t.story?this.iterateTree(t.story,r,s):t.stories.forEach(l=>{this.iterateTree(l,r,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){const r=this.helpers.stringify({url:t,params:e}),n=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const i=await n.get(r);if(i)return Promise.resolve(i)}return new Promise((i,l)=>{try{(async()=>{var o;try{const c=await this.throttle("get",t,e);let u={data:c.data,headers:c.headers};if((o=c.headers)!=null&&o["per-page"]&&(u=Object.assign({},u,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),c.status!=200)return l(c);if(u.data.story||u.data.stories){const y=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${y}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&g[e.token]!=u.data.cv&&await this.flushCache(),g[e.token]=u.data.cv),i(u)}catch(c){return l(c)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(t){this.accessToken&&(g[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(m[t])},getAll(){return Promise.resolve(m)},set(t,e){return m[t]=e,Promise.resolve(void 0)},flush(){return m={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this}}const w=(a,t)=>{for(const e in t)a[e]=t[e]};return w(_,{RichtextResolver:v,SbFetch:T,RichTextSchema:R}),w(_,x),_});

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

(function(i,o){typeof exports=="object"&&typeof module<"u"?module.exports=o():typeof define=="function"&&define.amd?define(o):(i=typeof globalThis<"u"?globalThis:i||self,i.RichTextResolver=o())})(this,function(){"use strict";var p=Object.defineProperty;var k=(i,o,c)=>o in i?p(i,o,{enumerable:!0,configurable:!0,writable:!0,value:c}):i[o]=c;var l=(i,o,c)=>(k(i,typeof o!="symbol"?o+"":o,c),c);const i=function(n,t){const e={};for(const r in n){const s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e},o=n=>n==="email",d={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:i(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={...n.attrs},{linktype:e="url"}=n.attrs;return o(e)&&(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}]})}},g=function(n){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,r=RegExp(e.source);return n&&r.test(n)?n.replace(e,s=>t[s]):n};class f{constructor(t){l(this,"marks");l(this,"nodes");t||(t=d),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t){if(t&&t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(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){const e=[];t.marks&&t.marks.forEach(s=>{const a=this.getMatchingMark(s);a&&e.push(this.renderOpeningTag(a.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(g(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 a=this.getMatchingMark(s);a&&e.push(this.renderClosingTag(a.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let a=`<${s.tag}`;if(s.attrs)for(const u in s.attrs){const h=s.attrs[u];h!==null&&(a+=` ${u}="${h}"`)}return`${a}${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){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}return f});
(function(a,o){typeof exports=="object"&&typeof module<"u"?module.exports=o():typeof define=="function"&&define.amd?define(o):(a=typeof globalThis<"u"?globalThis:a||self,a.RichTextResolver=o())})(this,function(){"use strict";var p=Object.defineProperty;var m=(a,o,c)=>o in a?p(a,o,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[o]=c;var l=(a,o,c)=>(m(a,typeof o!="symbol"?o+"":o,c),c);const a=function(n,t){const e={};for(const r in n){const s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e},o=n=>n==="email",d={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:a(n.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:n=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:n.attrs.name}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:n=>{const t={...n.attrs},{linktype:e="url"}=n.attrs;if(o(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const r in t.custom)t[r]=t.custom[r];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"})}},h=function(n){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,r=RegExp(e.source);return n&&r.test(n)?n.replace(e,s=>t[s]):n};class f{constructor(t){l(this,"marks");l(this,"nodes");t||(t=d),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t,e={optimizeImages:!1}){if(t&&t.content&&Array.isArray(t.content)){let r="";return t.content.forEach(s=>{r+=this.renderNode(s)}),e.optimizeImages?r.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,"a.storyblok.com/f/$1/$2.$3/m/"):r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){const e=[];t.marks&&t.marks.forEach(s=>{const i=this.getMatchingMark(s);i&&e.push(this.renderOpeningTag(i.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(h(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 i=this.getMatchingMark(s);i&&e.push(this.renderClosingTag(i.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let i=`<${s.tag}`;if(s.attrs)for(const u in s.attrs){const g=s.attrs[u];g!==null&&(i+=` ${u}="${g}"`)}return`${i}${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){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}}return f});

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

(function(r,n){typeof exports=="object"&&typeof module<"u"?module.exports=n():typeof define=="function"&&define.amd?define(n):(r=typeof globalThis<"u"?globalThis:r||self,r.RichTextSchema=n())})(this,function(){"use strict";const r=function(t,e){const o={};for(const s in t){const a=t[s];e.indexOf(s)>-1&&a!==null&&(o[s]=a)}return o},n=t=>t==="email";return{nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:t=>({tag:["pre",{tag:"code",attrs:t.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:t=>({tag:`h${t.attrs.level}`}),image:t=>({singleTag:[{tag:"img",attrs:r(t.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:t=>{const e={...t.attrs},{linktype:o="url"}=t.attrs;return n(o)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:t=>({tag:[{tag:"span",attrs:t.attrs}]})}}});
(function(n,s){typeof exports=="object"&&typeof module<"u"?module.exports=s():typeof define=="function"&&define.amd?define(s):(n=typeof globalThis<"u"?globalThis:n||self,n.RichTextSchema=s())})(this,function(){"use strict";const n=function(t,e){const o={};for(const r in t){const a=t[r];e.indexOf(r)>-1&&a!==null&&(o[r]=a)}return o},s=t=>t==="email";return{nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:t=>({tag:["pre",{tag:"code",attrs:t.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:t=>({tag:`h${t.attrs.level}`}),image:t=>({singleTag:[{tag:"img",attrs:n(t.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:t=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:t.attrs.name}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:t=>{const e={...t.attrs},{linktype:o="url"}=t.attrs;if(s(o)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),e.custom){for(const r in e.custom)e[r]=e.custom[r];delete e.custom}return{tag:[{tag:"a",attrs:e}]}},styled:t=>({tag:[{tag:"span",attrs:t.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"})}}});

@@ -190,2 +190,4 @@ import { ResponseFn } from './sbFetch';

linktype?: string;
custom?: LinkCustomAttributes;
[key: string]: any;
};

@@ -240,2 +242,7 @@ }

}
export interface LinkCustomAttributes {
rel?: string;
title?: string;
[key: string]: any;
}
export type ThrottleFn = {

@@ -242,0 +249,0 @@ (...args: any): any;

import { ISbSchema, ISbRichtext } from './interfaces';
type RenderOptions = {
optimizeImages: boolean;
};
declare class RichTextResolver {

@@ -8,3 +11,3 @@ private marks;

addMark(key: string, schema: ISbSchema): void;
render(data?: ISbRichtext): string;
render(data?: ISbRichtext, options?: RenderOptions): string;
private renderNode;

@@ -11,0 +14,0 @@ private renderTag;

@@ -14,2 +14,3 @@ import { NodeSchema, MarkSchema } from './interfaces';

paragraph: NodeSchema;
emoji: NodeSchema;
};

@@ -25,4 +26,6 @@ marks: {

styled: MarkSchema;
subscript: MarkSchema;
superscript: MarkSchema;
};
};
export default _default;
{
"name": "storyblok-js-client",
"version": "5.5.1",
"version": "5.6.0",
"description": "Universal JavaScript SDK for Storyblok's API",

@@ -64,3 +64,3 @@ "license": "MIT",

"vite": "^4.0.4",
"vitest": "^0.28.3"
"vitest": "^0.29.1"
},

@@ -67,0 +67,0 @@ "release": {

@@ -208,2 +208,4 @@ import { ResponseFn } from './sbFetch'

linktype?: string
custom?: LinkCustomAttributes,
[key: string]: any,
}

@@ -265,2 +267,8 @@ }

export interface LinkCustomAttributes {
rel?: string,
title?: string,
[key: string]: any
}
export type ThrottleFn = {

@@ -267,0 +275,0 @@ (...args: any): any

@@ -8,2 +8,6 @@ import defaultHtmlSerializer from './schema'

type RenderOptions = {
optimizeImages: boolean
}
const escapeHTML = function (string: string) {

@@ -55,3 +59,3 @@ const htmlEscapes = {

public render(data?: ISbRichtext) {
public render(data?: ISbRichtext, options: RenderOptions = { optimizeImages: false } ) {
if (data && data.content && Array.isArray(data.content)) {

@@ -64,2 +68,5 @@ let html = ''

if (options.optimizeImages)
return html.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g, "a.storyblok.com/f/$1/$2.$3/m/")
return html

@@ -66,0 +73,0 @@ }

@@ -84,2 +84,18 @@ import { ISbNode, NodeSchema, MarkSchema, ISbComponentType } from './interfaces'

const emoji: NodeSchema = (node: ISbNode) => {
const attrs = {
['data-type']: 'emoji',
['data-name']: node.attrs.name
}
return {
tag: [
{
tag: 'span',
attrs: attrs,
},
],
}
}
// marks

@@ -129,2 +145,9 @@ const bold: MarkSchema = () => {

if (attrs.custom) {
for (const key in attrs.custom) {
attrs[key] = attrs.custom[key]
}
delete attrs.custom
}
return {

@@ -150,2 +173,14 @@ tag: [

const subscript: MarkSchema = () => {
return {
tag: 'sub',
}
}
const superscript: MarkSchema = () => {
return {
tag: 'sup'
}
}
export default {

@@ -163,2 +198,3 @@ nodes: {

paragraph,
emoji
},

@@ -174,3 +210,5 @@ marks: {

styled,
subscript,
superscript,
},
}

@@ -5,2 +5,12 @@ /* eslint-disable no-undef */

import customSchema from './customSchema'
import {
IMAGE_DATA,
SPAN_WITH_RED_CLASS,
LINK_DATA,
EMAIL_LINK_DATA,
LONG_TEXT_FOR_IMMUTABILITY_TEST,
CUSTOM_ATTRIBUTE_DATA,
LONG_TEXT_WITH_LINKS_SUB_SUP_SCRIPTS,
LINK_WITH_ANCHOR_FOR_CUSTOM_SCHEMA,
} from './constants/richTextResolver'

@@ -31,21 +41,3 @@ const TOKEN = 'w0yFvs04aKF2rpz6F8OfIQtt'

test('styled mark to add span with red class', () => {
const doc = {
type: 'doc',
content: [
{
text: 'red text',
type: 'text',
marks: [
{
type: 'styled',
attrs: {
class: 'red',
},
},
],
},
],
}
expect(resolver.render(doc)).toBe('<span class="red">red text</span>')
expect(resolver.render(SPAN_WITH_RED_CLASS)).toBe('<span class="red">red text</span>')
})

@@ -80,2 +72,6 @@

test('image to generate img tag', () => {
expect(resolver.render(IMAGE_DATA)).toBe('<img src="https://asset" />')
})
test('image to generate img tag with optimization', () => {
const doc = {

@@ -87,3 +83,3 @@ type: 'doc',

attrs: {
src: 'https://asset',
src: 'https://a.storyblok.com/f/000000/00a00a00a0/image-name.png',
},

@@ -94,26 +90,7 @@ },

expect(resolver.render(doc)).toBe('<img src="https://asset" />')
expect(resolver.render(doc, { optimizeImages: true })).toBe('<img src="https://a.storyblok.com/f/000000/00a00a00a0/image-name.png/m/" />')
})
test('link to generate a tag', () => {
const doc = {
type: 'doc',
content: [
{
text: 'link text',
type: 'text',
marks: [
{
type: 'link',
attrs: {
href: '/link',
target: '_blank',
uuid: '300aeadc-c82d-4529-9484-f3f8f09cf9f5',
},
},
],
},
],
}
const result = resolver.render(doc)
const result = resolver.render(LINK_DATA)
const expected =

@@ -126,24 +103,3 @@ '<a href="/link" target="_blank" uuid="300aeadc-c82d-4529-9484-f3f8f09cf9f5">link text</a>'

test('link to generate a tag with an email', () => {
const doc = {
type: 'doc',
content: [
{
text: 'an email link',
type: 'text',
marks: [
{
type: 'link',
attrs: {
href: 'email@client.com',
target: '_blank',
uuid: null,
linktype: 'email',
},
},
],
},
],
}
const result = resolver.render(doc)
const result = resolver.render(EMAIL_LINK_DATA)
const expected =

@@ -272,139 +228,3 @@ '<a href="mailto:email@client.com" target="_blank" linktype="email">an email link</a>'

test('Complex and immutability test', () => {
const doc = {
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{
text: 'Lorem',
type: 'text',
marks: [
{
type: 'bold',
},
],
},
{
text: ' ipsum, ',
type: 'text',
},
{
text: 'dolor',
type: 'text',
marks: [
{
type: 'strike',
},
],
},
{
text: ' sit amet ',
type: 'text',
},
{
text: 'consectetur',
type: 'text',
marks: [
{
type: 'underline',
},
],
},
{
text: ' adipisicing elit. ',
type: 'text',
},
{
text: 'Eos architecto',
type: 'text',
marks: [
{
type: 'code',
},
],
},
{
text: ' asperiores temporibus ',
type: 'text',
},
{
text: 'suscipit harum ',
type: 'text',
marks: [
{
type: 'link',
attrs: {
href: '/test/our-service',
uuid: '931e04b7-f701-4fe4-8ec0-78be0bee8809',
anchor: 'anchor-text',
target: '_blank',
linktype: 'story',
},
},
],
},
{
text: 'ut, fugit, cumque ',
type: 'text',
},
{
text: 'molestiae ',
type: 'text',
marks: [
{
type: 'link',
attrs: {
href: 'asdfsdfasf',
uuid: null,
anchor: null,
target: '_blank',
linktype: 'url',
},
},
],
},
{
text: 'ratione non adipisci, ',
type: 'text',
},
{
text: 'facilis',
type: 'text',
marks: [
{
type: 'italic',
},
],
},
{
text: ' inventore optio dolores. Rem, perspiciatis ',
type: 'text',
},
{
text: 'deserunt!',
type: 'text',
marks: [
{
type: 'link',
attrs: {
href: '/home',
uuid: 'fc6a453f-9aa6-4a00-a22d-49c5878f7983',
anchor: null,
target: '_self',
linktype: 'story',
},
},
],
},
{
text: ' Esse, maiores!',
type: 'text',
},
],
},
],
}
const result = resolver.render(doc)
const result = resolver.render(LONG_TEXT_FOR_IMMUTABILITY_TEST)
const expected =

@@ -422,28 +242,90 @@ '<p><b>Lorem</b> ipsum, <strike>dolor</strike> sit amet <u>consectetur</u> adipisicing elit. <code>Eos architecto</code> asperiores temporibus <a href="/test/our-service#anchor-text" uuid="931e04b7-f701-4fe4-8ec0-78be0bee8809" target="_blank" linktype="story">suscipit harum </a>ut, fugit, cumque <a href="asdfsdfasf" target="_blank" linktype="url">molestiae </a>ratione non adipisci, <i>facilis</i> inventore optio dolores. Rem, perspiciatis <a href="/home" uuid="fc6a453f-9aa6-4a00-a22d-49c5878f7983" target="_self" linktype="story">deserunt!</a> Esse, maiores!</p>'

const doc = {
type: 'doc',
const result = internalClient.richTextResolver.render(LINK_WITH_ANCHOR_FOR_CUSTOM_SCHEMA)
const expected =
'<a href="/link%anchor-text" target="_blank" uuid="300aeadc-c82d-4529-9484-f3f8f09cf9f5">link text from custom schema</a>'
expect(result).toBe(expected)
})
test('should render a custom attribute in a link tag', () => {
const result = resolver.render(CUSTOM_ATTRIBUTE_DATA)
const expected =
'<a href="www.storyblok.com" uuid="300aeadc-c82d-4529-9484-f3f8f09cf9f5" target="_blank" linktype="url" rel="nofollow" title="nice test">A nice link with custom attr</a>'
expect(result).toBe(expected)
})
test('should render a subscript', () => {
const subscriptData = {
type: 'paragraph',
content: [
{
text: 'link text from custom schema',
text: 'A Subscript text',
type: 'text',
marks: [
{
type: 'link',
type: 'subscript'
}
]
}
]
}
const result = resolver.render(subscriptData)
const expected = '<sub>A Subscript text</sub>'
expect(result).toBe(expected)
})
test('should render a superscript', () => {
const subscriptData = {
type: 'paragraph',
content: [
{
text: 'A superscript text',
type: 'text',
marks: [
{
type: 'superscript'
}
]
}
]
}
const result = resolver.render(subscriptData)
const expected = '<sup>A superscript text</sup>'
expect(result).toBe(expected)
})
test('should render an emoji', () => {
const emojiData = {
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{
type: 'emoji',
attrs: {
href: '/link',
target: '_blank',
uuid: '300aeadc-c82d-4529-9484-f3f8f09cf9f5',
anchor: 'anchor-text',
},
},
],
},
],
name: 'smiley'
}
}
]
}
]
}
const result = internalClient.richTextResolver.render(doc)
const expected =
'<a href="/link%anchor-text" target="_blank" uuid="300aeadc-c82d-4529-9484-f3f8f09cf9f5">link text from custom schema</a>'
const result = resolver.render(emojiData)
const expected = '<p><span data-type="emoji" data-name="smiley"></span></p>'
expect(result).toBe(expected)
})
test('should render a text with links, subscripts and superscripts', () => {
const result = resolver.render(LONG_TEXT_WITH_LINKS_SUB_SUP_SCRIPTS)
const expected = '<p><b>Lorem Ipsum</b> is simply dummy text of the <a href="test.com" linktype="url" target="_self" title="test one" rel="test two">printing and typesetting industry</a>. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the <sup>1500s</sup>, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the <sub>1960s</sub> with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like <sup>Aldus PageMaker</sup> including versions of <sub>Lorem Ipsum</sub>.</p>'
expect(result).toBe(expected)
})

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc