storyblok-js-client
Advanced tools
Comparing version 5.12.1 to 5.13.0
@@ -1,2 +0,2 @@ | ||
(function(g,f){typeof exports=="object"&&typeof module<"u"?module.exports=f():typeof define=="function"&&define.amd?define(f):(g=typeof globalThis<"u"?globalThis:g||self,g.StoryblokJSClient=f())})(this,function(){"use strict";var L=Object.defineProperty;var N=(g,f,m)=>f in g?L(g,f,{enumerable:!0,configurable:!0,writable:!0,value:m}):g[f]=m;var h=(g,f,m)=>(N(g,typeof f!="symbol"?f+"":f,m),m);function g(a){return!(a!==a||a===1/0||a===-1/0)}function f(a,t,e){if(!g(t))throw new TypeError("Expected `limit` to be a finite number");if(!g(e))throw new TypeError("Expected `interval` to be a finite number");const r=[];let s=[],i=0;const n=function(){i++;const o=setTimeout(function(){i--,r.length>0&&n(),s=s.filter(function(u){return u!==o})},e);s.indexOf(o)<0&&s.push(o);const l=r.shift();l.resolve(a.apply(l.self,l.args))},c=function(...o){const l=this;return new Promise(function(u,p){r.push({resolve:u,reject:p,args:o,self:l}),i<t&&n()})};return c.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),r.length=0},c}const m=function(a,t){const e={};for(const r in a){const s=a[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e},E=a=>a==="email",x={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:m(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,emoji:a.attrs.emoji}}]})},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(E(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:a=>({tag:[{tag:"span",attrs:a.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:a=>({tag:[{tag:"span",attrs:a.attrs}]}),highlight:a=>{var e;return(e=a.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${a.attrs.color};`}}]}:{tag:""}},textStyle:a=>{var e;return(e=a.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${a.attrs.color}`}}]}:{tag:""}}}},O=function(a){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,r=RegExp(e.source);return a&&r.test(a)?a.replace(e,s=>t[s]):a};class R{constructor(t){h(this,"marks");h(this,"nodes");t||(t=x),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?this.optimizeImages(r,e.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field. | ||
(function(p,h){typeof exports=="object"&&typeof module<"u"?module.exports=h():typeof define=="function"&&define.amd?define(h):(p=typeof globalThis<"u"?globalThis:p||self,p.StoryblokJSClient=h())})(this,function(){"use strict";var D=Object.defineProperty;var z=(p,h,m)=>h in p?D(p,h,{enumerable:!0,configurable:!0,writable:!0,value:m}):p[h]=m;var u=(p,h,m)=>(z(p,typeof h!="symbol"?h+"":h,m),m);function p(i){return!(i!==i||i===1/0||i===-1/0)}function h(i,e,t){if(!p(e))throw new TypeError("Expected `limit` to be a finite number");if(!p(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let o=[],n=0;const r=function(){n++;const a=setTimeout(function(){n--,s.length>0&&r(),o=o.filter(function(d){return d!==a})},t);o.indexOf(a)<0&&o.push(a);const c=s.shift();c.resolve(i.apply(c.self,c.args))},l=function(...a){const c=this;return new Promise(function(d,b){s.push({resolve:d,reject:b,args:a,self:c}),n<e&&r()})};return l.abort=function(){o.forEach(clearTimeout),o=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class m{constructor(){u(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);u(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));u(this,"delay",e=>new Promise(t=>setTimeout(t,e)));u(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));u(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,o=e<t?1:-1;return this.arrayFrom(s,(n,r)=>r*o+e)});u(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));u(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,o)=>[...s,...o],[]));u(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,o=RegExp(s.source);return e&&o.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const o=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=e[n],l=s?"":encodeURIComponent(n);let a;typeof r=="object"?a=this.stringify(r,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(r)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(r),o.push(a)}return o.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",o="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return o;default:return t}}}const L=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:m},Symbol.toStringTag,{value:"Module"})),N=function(i,e){const t={};for(const s in i){const o=i[s];e.indexOf(s)>-1&&o!==null&&(t[s]=o)}return t},S=i=>i==="email",I={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:i=>({tag:`h${i.attrs.level}`}),image:i=>({singleTag:[{tag:"img",attrs:N(i.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:i=>{const e=new m().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(t.href&&(t.href=e(i.attrs.href||"")),S(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const o in t.custom)t[o]=t.custom[o];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:i=>({tag:[{tag:"span",attrs:i.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:i=>({tag:[{tag:"span",attrs:i.attrs}]}),highlight:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},textStyle:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}}}},U=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,o=>e[o]):i};class k{constructor(e){u(this,"marks");u(this,"nodes");e||(e=I),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(o=>{s+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field. | ||
The "content" field must be an array of nodes as the type ISbRichtext. | ||
@@ -24,2 +24,2 @@ ISbRichtext: | ||
type: 'doc' | ||
}`),""}optimizeImages(t,e){let r=0,s=0,i="",n="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(i+=`width="${e.width}" `,r=e.width),typeof e.height=="number"&&e.height>0&&(i+=`height="${e.height}" `,s=e.height),(e.loading==="lazy"||e.loading==="eager")&&(i+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(i+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(n+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(n+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-Fa-f]{6}/g)||e.filters.fill==="transparent")&&(n+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(n+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(n+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(n+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(n+=`:rotate(${e.filters.rotate})`),n.length>0&&(n="/filters"+n))),i.length>0&&(t=t.replace(/<img/g,`<img ${i.trim()}`));const c=r>0||s>0||n.length>0?`${r}x${s}${n}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,o=>{var u,p;const l=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(l&&l.length>0){const y={srcset:(u=e.srcset)==null?void 0:u.map(d=>{if(typeof d=="number")return`//${l}/m/${d}x0${n} ${d}w`;if(typeof d=="object"&&d.length===2){let w=0,C=0;return typeof d[0]=="number"&&(w=d[0]),typeof d[1]=="number"&&(C=d[1]),`//${l}/m/${w}x${C}${n} ${w}w`}}).join(", "),sizes:(p=e.sizes)==null?void 0:p.map(d=>d).join(", ")};let v="";return y.srcset&&(v+=`srcset="${y.srcset}" `),y.sizes&&(v+=`sizes="${y.sizes}" `),o.replace(/<img/g,`<img ${v.trim()}`)}return o})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&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(O(t.text)):r&&r.singleTag?e.push(this.renderTag(r.singleTag," /")):r&&r.html?e.push(r.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),r&&r.tag&&e.push(this.renderClosingTag(r.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&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 n in s.attrs){const c=s.attrs[n];c!==null&&(i+=` ${n}="${c}"`)}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)}renderEmoji(t){if(t.attrs.emoji)return t.attrs.emoji;const e=[{tag:"img",attrs:{src:t.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(e," /")}}class b{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1);h(this,"getOptionsPage",(t,e=25,r=1)=>({...t,per_page:e,page:r}));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 r=Math.abs(e-t)||0,s=t<e?1:-1;return this.arrayFrom(r,(i,n)=>n*s+t)});h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e)));h(this,"flatMap",(t=[],e)=>t.map(e).reduce((r,s)=>[...r,...s],[]))}stringify(t,e,r){const s=[];for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const n=t[i],c=r?"":encodeURIComponent(i);let o;typeof n=="object"?o=this.stringify(n,e?e+encodeURIComponent("["+c+"]"):c,Array.isArray(n)):o=(e?e+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(n),s.push(o)}return s.join("&")}getRegionURL(t){const e="api.storyblok.com",r="api-us.storyblok.com",s="app.storyblokchina.cn";switch(t){case"us":return r;case"cn":return s;default:return e}}}const j=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:b},Symbol.toStringTag,{value:"Module"}));class S{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=[],r={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(s=>{r.data=s});for(const s of t.headers.entries())e[s[0]]=s[1];return r.headers={...e},r.status=t.status,r.statusText=t.statusText,r}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,r=null;if(t==="get"){const o=new b;e=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else r=JSON.stringify(this.parameters);const s=new URL(e),i=new AbortController,{signal:n}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const o=await this.fetch(`${s}`,{method:t,headers:this.headers,body:r,signal:n});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((r,s)=>{if(e.test(`${t.status}`))return r(t);const i={message:new Error(t.statusText),status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};s(i)})}}const P="SB-Agent",T={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:process.env.npm_package_version||"5.0.0"};let _={};const k={};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");let r=t.endpoint||e;if(!r){const n=new b().getRegionURL,c=t.https===!1?"http":"https";t.oauthToken?r=`${c}://${n(t.region)}/v1`:r=`${c}://${n(t.region)}/v2`}const s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),t.headers)for(const n in t.headers)s.set(n,t.headers[n]);s.has(P)||(s.set(P,T.defaultAgentName),s.set(T.defaultAgentVersion,T.packageVersion));let i=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),i=3),t.rateLimit&&(i=t.rateLimit),t.richTextSchema?this.richTextResolver=new R(t.richTextSchema):this.richTextResolver=new R,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=f(this.throttledRequest,i,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new b,this.resolveCounter=0,this.resolveNestedRelations=t.resolveNestedRelations||!0,this.client=new S({baseURL:r,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let r="";return e.attrs.body&&e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=k[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,r,s){const i=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,r,s));return this.cacheResponse(t,i)}get(t,e){e||(e={});const r=`/${t}`,s=this.factoryParamOptions(r,e);return this.cacheResponse(r,s)}async getAll(t,e,r){const s=(e==null?void 0:e.per_page)||25,i=`/${t}`,n=i.split("/"),c=r||n[n.length-1],o=1,l=await this.makeRequest(i,e,s,o),u=l.total?Math.ceil(l.total/s):1,p=await this.helpers.asyncMap(this.helpers.range(o,u),y=>this.makeRequest(i,e,s,y+1));return this.helpers.flatMap([l,...p],y=>Object.values(y.data[c]))}post(t,e){const r=`/${t}`;return Promise.resolve(this.throttle("post",r,e))}put(t,e){const r=`/${t}`;return Promise.resolve(this.throttle("put",r,e))}delete(t,e){const r=`/${t}`;return Promise.resolve(this.throttle("delete",r,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,r){const s=t[e];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[r][s.id]?s.story=this._cleanCopy(this.links[r][s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[r][s.uuid]&&(s.story=this._cleanCopy(this.links[r][s.uuid]))}_insertRelations(t,e,r,s){if(r.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[s][t[e]]&&(t[e]=this._cleanCopy(this.relations[s][t[e]]));else if(t[e]&&t[e].constructor===Array){const i=[];t[e].forEach(n=>{this.relations[s][n]&&i.push(this._cleanCopy(this.relations[s][n]))}),t[e]=i}}}iterateTree(t,e,r){const s=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)s(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,e,r),this._insertLinks(i,n,r)),s(i[n])}}};s(t.content)}async resolveLinks(t,e,r){let s=[];if(t.link_uuids){const i=t.link_uuids.length,n=[],c=50;for(let o=0;o<i;o+=c){const l=Math.min(i,o+c);n.push(t.link_uuids.slice(o,l))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:n[o].join(",")})).data.stories.forEach(u=>{s.push(u)})}else s=t.links;s.forEach(i=>{this.links[r][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(t,e,r){let s=[];if(t.rel_uuids){const i=t.rel_uuids.length,n=[],c=50;for(let o=0;o<i;o+=c){const l=Math.min(i,o+c);n.push(t.rel_uuids.slice(o,l))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:n[o].join(",")})).data.stories.forEach(u=>{s.push(u)})}else s=t.rels;s&&s.length>0&&s.forEach(i=>{this.relations[r][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(t,e,r){var i,n;let s=[];if(this.links[r]={},this.relations[r]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(s=e.resolve_relations.split(",")),await this.resolveRelations(t,e,r)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((i=t.links)!=null&&i.length||(n=t.link_uuids)!=null&&n.length)&&await this.resolveLinks(t,e,r),this.resolveNestedRelations)for(const c in this.relations[r])this.iterateTree(this.relations[r][c],s,r);t.story?this.iterateTree(t.story,s,r):t.stories.forEach(c=>{this.iterateTree(c,s,r)}),delete this.links[r],delete this.relations[r]}async cacheResponse(t,e,r){const s=this.helpers.stringify({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const n=await i.get(s);if(n)return Promise.resolve(n)}return new Promise((n,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 p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${p}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await i.set(s,u),u.data.cv&&e.token&&(e.version=="draft"&&k[e.token]!=u.data.cv&&await this.flushCache(),k[e.token]=u.data.cv),n(u)}catch(l){return c(l)}})()}catch{}})}throttledRequest(t,e,r){return this.client[t](e,r)}cacheVersions(){return k}cacheVersion(){return k[this.accessToken]}setCacheVersion(t){this.accessToken&&(k[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(_[t])},getAll(){return Promise.resolve(_)},set(t,e){return _[t]=e,Promise.resolve(void 0)},flush(){return _={},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 A=(a,t)=>{for(const e in t)a[e]=t[e]};return A($,{RichtextResolver:R,SbFetch:S,RichTextSchema:x}),A($,j),$}); | ||
}`),""}optimizeImages(e,t){let s=0,o=0,n="",r="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,o=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(r+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(r+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(r+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(r+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(r+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(r+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(r+=`:rotate(${t.filters.rotate})`),r.length>0&&(r="/filters"+r))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||o>0||r.length>0?`${s}x${o}${r}`:"";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/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var d,b;const c=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const _={srcset:(d=t.srcset)==null?void 0:d.map(f=>{if(typeof f=="number")return`//${c}/m/${f}x0${r} ${f}w`;if(typeof f=="object"&&f.length===2){let O=0,C=0;return typeof f[0]=="number"&&(O=f[0]),typeof f[1]=="number"&&(C=f[1]),`//${c}/m/${O}x${C}${r} ${O}w`}}).join(", "),sizes:(b=t.sizes)==null?void 0:b.map(f=>f).join(", ")};let R="";return _.srcset&&(R+=`srcset="${_.srcset}" `),_.sizes&&(R+=`sizes="${_.sizes}" `),a.replace(/<img/g,`<img ${R.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(U(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(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(o=>{if(o.constructor===String)return`<${o}${t}>`;{let n=`<${o.tag}`;if(o.attrs)for(const r in o.attrs){const l=o.attrs[r];l!==null&&(n+=` ${r}="${l}"`)}return`${n}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.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 w{constructor(e){u(this,"baseURL");u(this,"timeout");u(this,"headers");u(this,"responseInterceptor");u(this,"fetch");u(this,"ejectInterceptor");u(this,"url");u(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(o=>{s.data=o});for(const o of e.headers.entries())t[o[0]]=o[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 m;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:r}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${o}`,{method:e,headers:this.headers,body:s,signal:r});this.timeout&&clearTimeout(l);const c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,o)=>{if(t.test(`${e.status}`))return s(e);const n={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const v="SB-Agent",E={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"5.13.0"};let y={};const g={};class T{constructor(e,t){u(this,"client");u(this,"maxRetries");u(this,"throttle");u(this,"accessToken");u(this,"cache");u(this,"helpers");u(this,"resolveCounter");u(this,"relations");u(this,"links");u(this,"richTextResolver");u(this,"resolveNestedRelations");let s=e.endpoint||t;if(!s){const r=new m().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${r(e.region)}/v1`:s=`${l}://${r(e.region)}/v2`}const o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers)for(const r in e.headers)o.set(r,e.headers[r]);o.has(v)||(o.set(v,E.defaultAgentName),o.set(E.defaultAgentVersion,E.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=h(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new m,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new w({baseURL:s,timeout:e.timeout||0,headers:o,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(o=>{s+=e(o.component,o)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[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,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,o));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,o=this.factoryParamOptions(s,t);return this.cacheResponse(s,o)}async getAll(e,t,s){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`,r=n.split("/"),l=s||r[r.length-1],a=1,c=await this.makeRequest(n,t,o,a),d=c.total?Math.ceil(c.total/o):1,b=await this.helpers.asyncMap(this.helpers.range(a,d),_=>this.makeRequest(n,t,o,_+1));return this.helpers.flatMap([c,...b],_=>Object.values(_.data[l]))}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 o=e[t];o&&o.fieldtype=="multilink"&&o.linktype=="story"&&typeof o.id=="string"&&this.links[s][o.id]?o.story=this._cleanCopy(this.links[s][o.id]):o&&o.linktype==="story"&&typeof o.uuid=="string"&&this.links[s][o.uuid]&&(o.story=this._cleanCopy(this.links[s][o.uuid]))}_insertRelations(e,t,s,o){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[o][e[t]]&&(e[t]=this._cleanCopy(this.relations[o][e[t]]));else if(e[t]&&e[t].constructor===Array){const n=[];e[t].forEach(r=>{this.relations[o][r]&&n.push(this._cleanCopy(this.relations[o][r]))}),e[t]=n}}}iterateTree(e,t,s){const o=n=>{if(n!=null){if(n.constructor===Array)for(let r=0;r<n.length;r++)o(n[r]);else if(n.constructor===Object){if(n._stopResolving)return;for(const r in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,r,t,s),this._insertLinks(n,r,s)),o(n[r])}}};o(e.content)}async resolveLinks(e,t,s){let o=[];if(e.link_uuids){const n=e.link_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.link_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.links;o.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let o=[];if(e.rel_uuids){const n=e.rel_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.rel_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.rels;o&&o.length>0&&o.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var n,r;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&&((n=e.links)!=null&&n.length||(r=e.link_uuids)!=null&&r.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const o=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const r=await n.get(o);if(r)return Promise.resolve(r)}return new Promise(async(r,l)=>{var a;try{const c=await this.throttle("get",e,t);let d={data:c.data,headers:c.headers};if((a=c.headers)!=null&&a["per-page"]&&(d=Object.assign({},d,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),d.data.story||d.data.stories){const b=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${b}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(o,d),d.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=d.data.cv&&await this.flushCache(),g[t.token]=d.data.cv),r(d)}catch(c){if(c.response&&c.response.status===429&&(s=s?s+1:0,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${s} seconds.`),await this.helpers.delay(1e3*s),this.cacheResponse(e,t,s).then(r).catch(l);l(c.message)}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(y[e])},getAll(){return Promise.resolve(y)},set(e,t){return y[e]=t,Promise.resolve(void 0)},flush(){return y={},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 A=(i,e)=>{for(const t in e)i[t]=e[t]};return A(T,{RichtextResolver:k,SbFetch:w,RichTextSchema:I}),A(T,L),T}); |
@@ -1,2 +0,2 @@ | ||
(function(c,l){typeof exports=="object"&&typeof module<"u"?module.exports=l():typeof define=="function"&&define.amd?define(l):(c=typeof globalThis<"u"?globalThis:c||self,c.RichTextResolver=l())})(this,function(){"use strict";var z=Object.defineProperty;var w=(c,l,g)=>l in c?z(c,l,{enumerable:!0,configurable:!0,writable:!0,value:g}):c[l]=g;var p=(c,l,g)=>(w(c,typeof l!="symbol"?l+"":l,g),g);const c=function(s,e){const t={};for(const r in s){const n=s[r];e.indexOf(r)>-1&&n!==null&&(t[r]=n)}return t},l=s=>s==="email",j={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:s=>({tag:`h${s.attrs.level}`}),image:s=>({singleTag:[{tag:"img",attrs:c(s.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:s=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:s.attrs.name,emoji:s.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:s=>{const e={...s.attrs},{linktype:t="url"}=s.attrs;if(l(t)&&(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:s=>({tag:[{tag:"span",attrs:s.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:s=>({tag:[{tag:"span",attrs:s.attrs}]}),highlight:s=>{var t;return(t=s.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${s.attrs.color};`}}]}:{tag:""}},textStyle:s=>{var t;return(t=s.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${s.attrs.color}`}}]}:{tag:""}}}},T=function(s){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return s&&r.test(s)?s.replace(t,n=>e[n]):s};class x{constructor(e){p(this,"marks");p(this,"nodes");e||(e=j),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 r="";return e.content.forEach(n=>{r+=this.renderNode(n)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field. | ||
(function(l,c){typeof exports=="object"&&typeof module<"u"?module.exports=c():typeof define=="function"&&define.amd?define(c):(l=typeof globalThis<"u"?globalThis:l||self,l.RichTextResolver=c())})(this,function(){"use strict";var _=Object.defineProperty;var I=(l,c,u)=>c in l?_(l,c,{enumerable:!0,configurable:!0,writable:!0,value:u}):l[c]=u;var f=(l,c,u)=>(I(l,typeof c!="symbol"?c+"":c,u),u);class l{constructor(){f(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);f(this,"getOptionsPage",(e,t=25,r=1)=>({...e,per_page:t,page:r}));f(this,"delay",e=>new Promise(t=>setTimeout(t,e)));f(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));f(this,"range",(e=0,t=e)=>{const r=Math.abs(t-e)||0,s=e<t?1:-1;return this.arrayFrom(r,(a,i)=>i*s+e)});f(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));f(this,"flatMap",(e=[],t)=>e.map(t).reduce((r,s)=>[...r,...s],[]));f(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},r=/[&<>"']/g,s=RegExp(r.source);return e&&s.test(e)?e.replace(r,a=>t[a]):e})}stringify(e,t,r){const s=[];for(const a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;const i=e[a],g=r?"":encodeURIComponent(a);let h;typeof i=="object"?h=this.stringify(i,t?t+encodeURIComponent("["+g+"]"):g,Array.isArray(i)):h=(t?t+encodeURIComponent("["+g+"]"):g)+"="+encodeURIComponent(i),s.push(h)}return s.join("&")}getRegionURL(e){const t="api.storyblok.com",r="api-us.storyblok.com",s="app.storyblokchina.cn";switch(e){case"us":return r;case"cn":return s;default:return t}}}const c=function(n,e){const t={};for(const r in n){const s=n[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t},u=n=>n==="email",j={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:c(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,emoji:n.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:n=>{const e=new l().escapeHTML,t={...n.attrs},{linktype:r="url"}=n.attrs;if(t.href&&(t.href=e(n.attrs.href||"")),u(r)&&(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:n=>({tag:[{tag:"span",attrs:n.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:n=>({tag:[{tag:"span",attrs:n.attrs}]}),highlight:n=>{var t;return(t=n.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${n.attrs.color};`}}]}:{tag:""}},textStyle:n=>{var t;return(t=n.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${n.attrs.color}`}}]}:{tag:""}}}},T=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return n&&r.test(n)?n.replace(t,s=>e[s]):n};class x{constructor(e){f(this,"marks");f(this,"nodes");e||(e=j),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 r="";return e.content.forEach(s=>{r+=this.renderNode(s)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field. | ||
The "content" field must be an array of nodes as the type ISbRichtext. | ||
@@ -24,2 +24,2 @@ ISbRichtext: | ||
type: 'doc' | ||
}`),""}optimizeImages(e,t){let r=0,n=0,a="",i="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(a+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(a+=`height="${t.height}" `,n=t.height),(t.loading==="lazy"||t.loading==="eager")&&(a+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(a+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(i+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(i+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(i+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(i+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(i+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(i+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(i+=`:rotate(${t.filters.rotate})`),i.length>0&&(i="/filters"+i))),a.length>0&&(e=e.replace(/<img/g,`<img ${a.trim()}`));const o=r>0||n>0||i.length>0?`${r}x${n}${i}`:"";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/${o}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,d=>{var y,$;const u=d.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(u&&u.length>0){const h={srcset:(y=t.srcset)==null?void 0:y.map(f=>{if(typeof f=="number")return`//${u}/m/${f}x0${i} ${f}w`;if(typeof f=="object"&&f.length===2){let b=0,k=0;return typeof f[0]=="number"&&(b=f[0]),typeof f[1]=="number"&&(k=f[1]),`//${u}/m/${b}x${k}${i} ${b}w`}}).join(", "),sizes:($=t.sizes)==null?void 0:$.map(f=>f).join(", ")};let m="";return h.srcset&&(m+=`srcset="${h.srcset}" `),h.sizes&&(m+=`sizes="${h.sizes}" `),d.replace(/<img/g,`<img ${m.trim()}`)}return d})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(n=>{const a=this.getMatchingMark(n);a&&a.tag!==""&&t.push(this.renderOpeningTag(a.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(n=>{t.push(this.renderNode(n))}):e.text?t.push(T(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(n=>{const a=this.getMatchingMark(n);a&&a.tag!==""&&t.push(this.renderClosingTag(a.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(n=>{if(n.constructor===String)return`<${n}${t}>`;{let a=`<${n.tag}`;if(n.attrs)for(const i in n.attrs){const o=n.attrs[i];o!==null&&(a+=` ${i}="${o}"`)}return`${a}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(e){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," /")}}return x}); | ||
}`),""}optimizeImages(e,t){let r=0,s=0,a="",i="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(a+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(a+=`height="${t.height}" `,s=t.height),(t.loading==="lazy"||t.loading==="eager")&&(a+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(a+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(i+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(i+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(i+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(i+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(i+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(i+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(i+=`:rotate(${t.filters.rotate})`),i.length>0&&(i="/filters"+i))),a.length>0&&(e=e.replace(/<img/g,`<img ${a.trim()}`));const g=r>0||s>0||i.length>0?`${r}x${s}${i}`:"";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/${g}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,h=>{var b,$;const d=h.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(d&&d.length>0){const m={srcset:(b=t.srcset)==null?void 0:b.map(o=>{if(typeof o=="number")return`//${d}/m/${o}x0${i} ${o}w`;if(typeof o=="object"&&o.length===2){let y=0,k=0;return typeof o[0]=="number"&&(y=o[0]),typeof o[1]=="number"&&(k=o[1]),`//${d}/m/${y}x${k}${i} ${y}w`}}).join(", "),sizes:($=t.sizes)==null?void 0:$.map(o=>o).join(", ")};let p="";return m.srcset&&(p+=`srcset="${m.srcset}" `),m.sizes&&(p+=`sizes="${m.sizes}" `),h.replace(/<img/g,`<img ${p.trim()}`)}return h})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(s=>{const a=this.getMatchingMark(s);a&&a.tag!==""&&t.push(this.renderOpeningTag(a.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(s=>{t.push(this.renderNode(s))}):e.text?t.push(T(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const a=this.getMatchingMark(s);a&&a.tag!==""&&t.push(this.renderClosingTag(a.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let a=`<${s.tag}`;if(s.attrs)for(const i in s.attrs){const g=s.attrs[i];g!==null&&(a+=` ${i}="${g}"`)}return`${a}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(e){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," /")}}return x}); |
@@ -1,1 +0,1 @@ | ||
(function(s,a){typeof exports=="object"&&typeof module<"u"?module.exports=a():typeof define=="function"&&define.amd?define(a):(s=typeof globalThis<"u"?globalThis:s||self,s.RichTextSchema=a())})(this,function(){"use strict";const s=function(t,r){const e={};for(const n in t){const o=t[n];r.indexOf(n)>-1&&o!==null&&(e[n]=o)}return e},a=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:s(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,emoji:t.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:t=>{const r={...t.attrs},{linktype:e="url"}=t.attrs;if(a(e)&&(r.href=`mailto:${r.href}`),r.anchor&&(r.href=`${r.href}#${r.anchor}`,delete r.anchor),r.custom){for(const n in r.custom)r[n]=r.custom[n];delete r.custom}return{tag:[{tag:"a",attrs:r}]}},styled:t=>({tag:[{tag:"span",attrs:t.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:t=>({tag:[{tag:"span",attrs:t.attrs}]}),highlight:t=>{var e;return(e=t.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${t.attrs.color};`}}]}:{tag:""}},textStyle:t=>{var e;return(e=t.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${t.attrs.color}`}}]}:{tag:""}}}}}); | ||
(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.RichTextSchema=o())})(this,function(){"use strict";var h=Object.defineProperty;var d=(a,o,i)=>o in a?h(a,o,{enumerable:!0,configurable:!0,writable:!0,value:i}):a[o]=i;var c=(a,o,i)=>(d(a,typeof o!="symbol"?o+"":o,i),i);class a{constructor(){c(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);c(this,"getOptionsPage",(e,t=25,n=1)=>({...e,per_page:t,page:n}));c(this,"delay",e=>new Promise(t=>setTimeout(t,e)));c(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));c(this,"range",(e=0,t=e)=>{const n=Math.abs(t-e)||0,s=e<t?1:-1;return this.arrayFrom(n,(l,u)=>u*s+e)});c(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));c(this,"flatMap",(e=[],t)=>e.map(t).reduce((n,s)=>[...n,...s],[]));c(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},n=/[&<>"']/g,s=RegExp(n.source);return e&&s.test(e)?e.replace(n,l=>t[l]):e})}stringify(e,t,n){const s=[];for(const l in e){if(!Object.prototype.hasOwnProperty.call(e,l))continue;const u=e[l],g=n?"":encodeURIComponent(l);let p;typeof u=="object"?p=this.stringify(u,t?t+encodeURIComponent("["+g+"]"):g,Array.isArray(u)):p=(t?t+encodeURIComponent("["+g+"]"):g)+"="+encodeURIComponent(u),s.push(p)}return s.join("&")}getRegionURL(e){const t="api.storyblok.com",n="api-us.storyblok.com",s="app.storyblokchina.cn";switch(e){case"us":return n;case"cn":return s;default:return t}}}const o=function(r,e){const t={};for(const n in r){const s=r[n];e.indexOf(n)>-1&&s!==null&&(t[n]=s)}return t},i=r=>r==="email";return{nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:r=>({tag:["pre",{tag:"code",attrs:r.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:r=>({tag:`h${r.attrs.level}`}),image:r=>({singleTag:[{tag:"img",attrs:o(r.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:r=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":r.attrs.name,emoji:r.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:r=>{const e=new a().escapeHTML,t={...r.attrs},{linktype:n="url"}=r.attrs;if(t.href&&(t.href=e(r.attrs.href||"")),i(n)&&(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:r=>({tag:[{tag:"span",attrs:r.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:r=>({tag:[{tag:"span",attrs:r.attrs}]}),highlight:r=>{var t;return(t=r.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${r.attrs.color};`}}]}:{tag:""}},textStyle:r=>{var t;return(t=r.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${r.attrs.color}`}}]}:{tag:""}}}}}); |
@@ -253,2 +253,5 @@ import { ResponseFn } from './sbFetch'; | ||
export type ArrayFn = (...args: any) => void; | ||
export type HtmlEscapes = { | ||
[key: string]: string; | ||
}; | ||
export {}; |
@@ -66,3 +66,9 @@ import { ISbStoriesParams, ISbResult, AsyncFn } from './interfaces'; | ||
getRegionURL(regionCode?: string): string; | ||
/** | ||
* @method escapeHTML | ||
* @param {String} string text to be parsed | ||
* @return {String} Text parsed | ||
*/ | ||
escapeHTML: (string: string) => string; | ||
} | ||
export {}; |
{ | ||
"name": "storyblok-js-client", | ||
"version": "5.12.1", | ||
"version": "5.13.0", | ||
"description": "Universal JavaScript SDK for Storyblok's API", | ||
@@ -64,5 +64,5 @@ "license": "MIT", | ||
"isomorphic-fetch": "^3.0.0", | ||
"prettier": "^2.7.1", | ||
"prettier": "^3.0.0", | ||
"typescript": "^5.0.2", | ||
"vite": "^4.0.4", | ||
"vite": "^4.4.8", | ||
"vitest": "^0.32.0" | ||
@@ -69,0 +69,0 @@ }, |
@@ -388,3 +388,3 @@ <div align="center"> | ||
Option 2: Dynamically render a component (Example in Vue.js): | ||
Option 2: Dynamically render a component (Example in Vue.js, which will only work with runtime template rendering enabled): | ||
@@ -449,3 +449,3 @@ ```javascript | ||
// Example: [[720,500], 1024, [1500, 1000]] | ||
// will render srcset="//../m/720x500 720w", "//../m/1024x0 1024w", "//../m/1280x0 1280w" | ||
// will render srcset="//../m/720x500 720w", "//../m/1024x0 1024w", "//../m/1500x1000 1280w" | ||
srcset: [720, 1024, 1533], | ||
@@ -515,3 +515,3 @@ sizes: [ | ||
Following a code example using the storyblok-js-client to backup all content on your local filesystem inside a 'backup' folder. | ||
Following a code example using the storyblok-js-client to back up all content on your local filesystem inside a 'backup' folder. | ||
@@ -653,3 +653,3 @@ ```javascript | ||
### Handling access token overwrite | ||
You can overwrte an access token, and prevent errors from the function call by adding a `.catch()` method for each access token as shown below. | ||
You can overwrite an access token, and prevent errors from the function call by adding a `.catch()` method for each access token as shown below. | ||
@@ -656,0 +656,0 @@ ```javascript |
@@ -18,3 +18,3 @@ const METHOD = { | ||
defaultAgentVersion: 'SB-Agent-Version', | ||
packageVersion: process.env.npm_package_version || '5.0.0' | ||
packageVersion: process.env.npm_package_version || '5.0.0', | ||
} |
104
src/index.ts
@@ -92,5 +92,9 @@ import throttledQueue from './throttlePromise' | ||
if (!config.oauthToken) { | ||
endpoint = `${protocol}://${getRegion(config.region)}/${'v2' as Version}` | ||
endpoint = `${protocol}://${getRegion(config.region)}/${ | ||
'v2' as Version | ||
}` | ||
} else { | ||
endpoint = `${protocol}://${getRegion(config.region)}/${'v1' as Version}` | ||
endpoint = `${protocol}://${getRegion(config.region)}/${ | ||
'v1' as Version | ||
}` | ||
} | ||
@@ -109,6 +113,9 @@ } | ||
} | ||
if (!headers.has(STORYBLOK_AGENT)) { | ||
headers.set(STORYBLOK_AGENT, STORYBLOK_JS_CLIENT_AGENT.defaultAgentName) | ||
headers.set( STORYBLOK_JS_CLIENT_AGENT.defaultAgentVersion, STORYBLOK_JS_CLIENT_AGENT.packageVersion) | ||
headers.set( | ||
STORYBLOK_JS_CLIENT_AGENT.defaultAgentVersion, | ||
STORYBLOK_JS_CLIENT_AGENT.packageVersion | ||
) | ||
} | ||
@@ -543,66 +550,51 @@ | ||
return new Promise((resolve, reject) => { | ||
return new Promise(async (resolve, reject) => { | ||
try { | ||
;(async () => { | ||
try { | ||
const res = await this.throttle('get', url, params) | ||
const res = await this.throttle('get', url, params) | ||
let response = { data: res.data, headers: res.headers } as ISbResult | ||
let response = { data: res.data, headers: res.headers } as ISbResult | ||
if (res.headers?.['per-page']) { | ||
response = Object.assign({}, response, { | ||
perPage: res.headers['per-page'] | ||
? parseInt(res.headers['per-page']) | ||
: 0, | ||
total: res.headers['per-page'] | ||
? parseInt(res.headers['total']) | ||
: 0, | ||
}) | ||
} | ||
if (res.headers?.['per-page']) { | ||
response = Object.assign({}, response, { | ||
perPage: res.headers['per-page'] | ||
? parseInt(res.headers['per-page']) | ||
: 0, | ||
total: res.headers['per-page'] ? parseInt(res.headers['total']) : 0, | ||
}) | ||
} | ||
if (res.status != 200) { | ||
return reject(res) | ||
} | ||
if (response.data.story || response.data.stories) { | ||
const resolveId = (this.resolveCounter = ++this.resolveCounter % 1000) | ||
await this.resolveStories(response.data, params, `${resolveId}`) | ||
} | ||
if (response.data.story || response.data.stories) { | ||
const resolveId = (this.resolveCounter = | ||
++this.resolveCounter % 1000) | ||
await this.resolveStories(response.data, params, `${resolveId}`) | ||
} | ||
if (params.version === 'published' && url != '/cdn/spaces/me') { | ||
await provider.set(cacheKey, response) | ||
} | ||
if (params.version === 'published' && url != '/cdn/spaces/me') { | ||
await provider.set(cacheKey, response) | ||
} | ||
if (response.data.cv && params.token) { | ||
if ( | ||
params.version == 'draft' && | ||
cacheVersions[params.token] != response.data.cv | ||
) { | ||
await this.flushCache() | ||
} | ||
if (response.data.cv && params.token) { | ||
if ( | ||
params.version == 'draft' && | ||
cacheVersions[params.token] != response.data.cv | ||
) { | ||
await this.flushCache() | ||
} | ||
cacheVersions[params.token] = response.data.cv | ||
} | ||
cacheVersions[params.token] = response.data.cv | ||
} | ||
return resolve(response) | ||
} catch (error: Error | any) { | ||
return reject(error) | ||
} | ||
})() | ||
return resolve(response) | ||
} catch (error: Error | any) { | ||
;async () => { | ||
if (error.response && error.response.status === 429) { | ||
retries = retries ? retries + 1 : 0 | ||
if (error.response && error.response.status === 429) { | ||
retries = retries ? retries + 1 : 0 | ||
if (retries < this.maxRetries) { | ||
console.log(`Hit rate limit. Retrying in ${retries} seconds.`) | ||
await this.helpers.delay(1000 * retries) | ||
return this.cacheResponse(url, params, retries) | ||
.then(resolve) | ||
.catch(reject) | ||
} | ||
if (retries < this.maxRetries) { | ||
console.log(`Hit rate limit. Retrying in ${retries} seconds.`) | ||
await this.helpers.delay(1000 * retries) | ||
return this.cacheResponse(url, params, retries) | ||
.then(resolve) | ||
.catch(reject) | ||
} | ||
reject(error.message) | ||
} | ||
reject(error.message) | ||
} | ||
@@ -609,0 +601,0 @@ }) |
@@ -281,1 +281,5 @@ import { ResponseFn } from './sbFetch' | ||
export type ArrayFn = (...args: any) => void | ||
export type HtmlEscapes = { | ||
[key: string]: string | ||
} |
@@ -1,2 +0,2 @@ | ||
import { ISbStoriesParams, ISbResult, AsyncFn } from './interfaces' | ||
import { ISbStoriesParams, ISbResult, AsyncFn, HtmlEscapes } from './interfaces' | ||
interface ISbParams extends ISbStoriesParams { | ||
@@ -99,2 +99,24 @@ [key: string]: any | ||
} | ||
/** | ||
* @method escapeHTML | ||
* @param {String} string text to be parsed | ||
* @return {String} Text parsed | ||
*/ | ||
public escapeHTML = function (string: string) { | ||
const htmlEscapes = { | ||
'&': '&', | ||
'<': '<', | ||
'>': '>', | ||
'"': '"', | ||
"'": ''', | ||
} as HtmlEscapes | ||
const reUnescapedHtml = /[&<>"']/g | ||
const reHasUnescapedHtml = RegExp(reUnescapedHtml.source) | ||
return string && reHasUnescapedHtml.test(string) | ||
? string.replace(reUnescapedHtml, (chr) => htmlEscapes[chr]) | ||
: string | ||
} | ||
} |
import { ISbNode, NodeSchema, MarkSchema, ISbComponentType } from './interfaces' | ||
import { SbHelpers } from './sbHelpers' | ||
@@ -134,5 +135,10 @@ const pick = function (attrs: Attrs, allowed: string[]) { | ||
const link: MarkSchema = (node: ISbNode) => { | ||
const escapeHTML = new SbHelpers().escapeHTML | ||
const attrs = { ...node.attrs } | ||
const { linktype = 'url' } = node.attrs | ||
if (attrs.href) { | ||
attrs.href = escapeHTML(node.attrs.href || '') | ||
} | ||
if (isEmailLinkType(linktype)) { | ||
@@ -139,0 +145,0 @@ attrs.href = `mailto:${attrs.href}` |
@@ -542,1 +542,37 @@ /* eslint-disable no-undef */ | ||
}) | ||
test('should escape ampersand in link attribute values', () => { | ||
const data = { | ||
type: 'doc', | ||
content: [ | ||
{ | ||
type: 'paragraph', | ||
content: [ | ||
{ | ||
text: 'test', | ||
type: 'text', | ||
marks: [ | ||
{ | ||
type: "link", | ||
attrs: { | ||
href: "https://www.storyblok.com/?foo=bar&bar=foo", | ||
uuid: null, | ||
anchor: null, | ||
target: "_self", | ||
linktype: "url", | ||
}, | ||
}, | ||
], | ||
}, | ||
], | ||
}, | ||
], | ||
} | ||
const result = resolver.render(data) | ||
const expected = '<p><a href="https://www.storyblok.com/?foo=bar&bar=foo" target="_self" linktype="url">test</a></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
201776
5503
3