@storyblok/astro 6.1.0-alpha.2 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/StoryblokComponent.astro +9 -6
- package/dist/index.d.ts +1 -3
- package/dist/storyblok-astro.es.js +330 -893
- package/dist/storyblok-astro.umd.js +12 -12
- package/dist/vite-plugins/vite-plugin-storyblok-options.d.ts +1 -2
- package/package.json +2 -2
- package/dist/content-loader/storyblokLoader.d.ts +0 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(u,y){typeof exports=="object"&&typeof module<"u"?y(exports):typeof define=="function"&&define.amd?define(["exports"],y):(u=typeof globalThis<"u"?globalThis:u||self,y(u.storyblokAstro={}))})(this,function(u){"use strict";const y=`<svg width="45px" height="53px" viewBox="0 0 45 53" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
2
2
|
<g id="storyblok-logo-kit" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
|
3
3
|
<g id="storyblok-partner-logo" transform="translate(-59.000000, -169.000000)" fill-rule="nonzero">
|
|
4
4
|
<g id="storyblok-symbol" transform="translate(59.000000, 169.000000)">
|
|
@@ -7,17 +7,17 @@
|
|
|
7
7
|
</g>
|
|
8
8
|
</g>
|
|
9
9
|
</g>
|
|
10
|
-
</svg>`,
|
|
10
|
+
</svg>`,R=/[\p{Lu}]/u,M=/[\p{Ll}]/u,$=/^[\p{Lu}](?![\p{Lu}])/gu,v=/([\p{Alpha}\p{N}_]|$)/u,b=/[_.\- ]+/,O=new RegExp("^"+b.source),C=new RegExp(b.source+v.source,"gu"),S=new RegExp("\\d+"+v.source,"gu"),P=(r,t,e,o)=>{let s=!1,n=!1,a=!1,l=!1;for(let i=0;i<r.length;i++){const c=r[i];l=i>2?r[i-3]==="-":!0,s&&R.test(c)?(r=r.slice(0,i)+"-"+r.slice(i),s=!1,a=n,n=!0,i++):n&&a&&M.test(c)&&(!l||o)?(r=r.slice(0,i-1)+"-"+r.slice(i-1),a=n,n=!1,s=!0):(s=t(c)===c&&e(c)!==c,a=n,n=e(c)===c&&t(c)!==c)}return r},_=(r,t)=>($.lastIndex=0,r.replaceAll($,e=>t(e))),N=(r,t)=>(C.lastIndex=0,S.lastIndex=0,r.replaceAll(S,(e,o,s)=>["_","-"].includes(r.charAt(s+e.length))?e:t(e)).replaceAll(C,(e,o)=>t(o)));function z(r,t){if(!(typeof r=="string"||Array.isArray(r)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(r)?r=r.map(n=>n.trim()).filter(n=>n.length).join("-"):r=r.trim(),r.length===0)return"";const e=t.locale===!1?n=>n.toLowerCase():n=>n.toLocaleLowerCase(t.locale),o=t.locale===!1?n=>n.toUpperCase():n=>n.toLocaleUpperCase(t.locale);return r.length===1?b.test(r)?"":t.pascalCase?o(r):e(r):(r!==e(r)&&(r=P(r,e,o,t.preserveConsecutiveUppercase)),r=r.replace(O,""),r=t.preserveConsecutiveUppercase?_(r,e):e(r),t.pascalCase&&(r=o(r.charAt(0))+r.slice(1)),N(r,o))}function m(r){return z(r)}function B(r,t={},e,o){const s="virtual:storyblok-components",n=`\0${s}`;return{name:"vite-plugin-storyblok-components",async resolveId(a){if(a===s)return n},async load(a){if(a===n){const l=[],i=[];for await(const[d,f]of Object.entries(t)){const h=await this.resolve(`/${r}/${f}.astro`);if(h)l.push(`import ${m(d)} from "${h.id}"`);else if(e)i.push(d);else throw new Error(`Component could not be found for blok "${d}"! Does "${`/${r}/${f}`}.astro" exist?`)}let c="";if(e)if(c=",FallbackComponent",o){const d=await this.resolve(`/${r}/${o}.astro`);if(!d)throw new Error(`Custom fallback component could not be found. Does "${`/${r}/${o}`}.astro" exist?`);l.push(`import FallbackComponent from "${d.id}"`)}else l.push("import FallbackComponent from '@storyblok/astro/FallbackComponent.astro'");if(Object.values(t).length)return`${l.join(";")};export default {${Object.keys(t).filter(d=>!i.includes(d)).map(d=>m(d)).join(",")}${c}}`;if(e)return`${l[0]}; export default {${c.replace(",","")}}`;throw new Error(`Currently, no Storyblok components are registered in astro.config.mjs.
|
|
11
11
|
Please register your components or enable the fallback component.
|
|
12
|
-
Detailed information can be found here: https://github.com/storyblok/storyblok-astro`)}}}}function
|
|
12
|
+
Detailed information can be found here: https://github.com/storyblok/storyblok-astro`)}}}}function D(r,t,e){const o="virtual:storyblok-init",s=`\0${o}`;return{name:"vite-plugin-storyblok-init",async resolveId(n){if(n===o)return s},async load(n){if(n===s)return`
|
|
13
13
|
import { storyblokInit, apiPlugin } from "@storyblok/js";
|
|
14
14
|
const { storyblokApi } = storyblokInit({
|
|
15
15
|
accessToken: "${r}",
|
|
16
|
-
use: ${
|
|
17
|
-
apiOptions: ${JSON.stringify(
|
|
16
|
+
use: ${t?"[]":"[apiPlugin]"},
|
|
17
|
+
apiOptions: ${JSON.stringify(e)},
|
|
18
18
|
});
|
|
19
19
|
export const storyblokApiInstance = storyblokApi;
|
|
20
|
-
`}}}function
|
|
20
|
+
`}}}function F(r){const t="virtual:storyblok-options",e=`\0${t}`;return{name:"vite-plugin-storyblok-options",async resolveId(o){if(o===t)return e},async load(o){if(o===e)return`export default ${JSON.stringify(r)}`}}}let I=!1;const A=[],U=r=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}I?s():A.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const o=document.createElement("script");o.async=!0,o.src=r,o.id="storyblok-javascript-bridge",o.onerror=s=>e(s),o.onload=s=>{A.forEach(n=>n()),I=!0,t(s)},document.getElementsByTagName("head")[0].appendChild(o)});var q=Object.defineProperty,H=(r,t,e)=>t in r?q(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,p=(r,t,e)=>H(r,typeof t!="symbol"?t+"":t,e);class J{constructor(){p(this,"isCDNUrl",(t="")=>t.includes("/cdn/")),p(this,"getOptionsPage",(t,e=25,o=1)=>({...t,per_page:e,page:o})),p(this,"delay",t=>new Promise(e=>setTimeout(e,t))),p(this,"arrayFrom",(t=0,e)=>Array.from({length:t},e)),p(this,"range",(t=0,e=t)=>{const o=Math.abs(e-t)||0,s=t<e?1:-1;return this.arrayFrom(o,(n,a)=>a*s+t)}),p(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),p(this,"flatMap",(t=[],e)=>t.map(e).reduce((o,s)=>[...o,...s],[])),p(this,"escapeHTML",function(t){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},o=/[&<>"']/g,s=new RegExp(o.source);return t&&s.test(t)?t.replace(o,n=>e[n]):t})}stringify(t,e,o){const s=[];for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const a=t[n],l=o?"":encodeURIComponent(n);let i;typeof a=="object"?i=this.stringify(a,e?e+encodeURIComponent(`[${l}]`):l,Array.isArray(a)):i=`${e?e+encodeURIComponent(`[${l}]`):l}=${encodeURIComponent(a)}`,s.push(i)}return s.join("&")}getRegionURL(t){const e="api.storyblok.com",o="api-us.storyblok.com",s="app.storyblokchina.cn",n="api-ap.storyblok.com",a="api-ca.storyblok.com";switch(t){case"us":return o;case"cn":return s;case"ap":return n;case"ca":return a;default:return e}}}const W=function(r,t){const e={};for(const o in r){const s=r[o];t.includes(o)&&s!==null&&(e[o]=s)}return e},K=r=>r==="email",V=()=>({singleTag:"hr"}),Z=()=>({tag:"blockquote"}),G=()=>({tag:"ul"}),Y=r=>({tag:["pre",{tag:"code",attrs:r.attrs}]}),Q=()=>({singleTag:"br"}),X=r=>({tag:`h${r.attrs.level}`}),ee=r=>({singleTag:[{tag:"img",attrs:W(r.attrs,["src","alt","title"])}]}),te=()=>({tag:"li"}),re=()=>({tag:"ol"}),oe=()=>({tag:"p"}),se=r=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":r.attrs.name,emoji:r.attrs.emoji}}]}),ne=()=>({tag:"b"}),ae=()=>({tag:"s"}),le=()=>({tag:"u"}),ie=()=>({tag:"strong"}),ce=()=>({tag:"code"}),ue=()=>({tag:"i"}),de=r=>{if(!r.attrs)return{tag:""};const t=new J().escapeHTML,e={...r.attrs},{linktype:o="url"}=r.attrs;if(delete e.linktype,e.href&&(e.href=t(r.attrs.href||"")),K(o)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),e.custom){for(const s in e.custom)e[s]=e.custom[s];delete e.custom}return{tag:[{tag:"a",attrs:e}]}},ge=r=>({tag:[{tag:"span",attrs:r.attrs}]}),pe=()=>({tag:"sub"}),fe=()=>({tag:"sup"}),he=r=>({tag:[{tag:"span",attrs:r.attrs}]}),ye=r=>{var t;return(t=r.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${r.attrs.color};`}}]}:{tag:""}},be=r=>{var t;return(t=r.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${r.attrs.color}`}}]}:{tag:""}},T={nodes:{horizontal_rule:V,blockquote:Z,bullet_list:G,code_block:Y,hard_break:Q,heading:X,image:ee,list_item:te,ordered_list:re,paragraph:oe,emoji:se},marks:{bold:ne,strike:ae,underline:le,strong:ie,code:ce,italic:ue,link:de,styled:ge,subscript:pe,superscript:fe,anchor:he,highlight:ye,textStyle:be}},me=function(r){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,o=new RegExp(e.source);return r&&o.test(r)?r.replace(e,s=>t[s]):r};let E=!1;class L{constructor(t){p(this,"marks"),p(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,e={optimizeImages:!1},o=!0){if(!E&&o&&(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),E=!0),t&&t.content&&Array.isArray(t.content)){let s="";return t.content.forEach(n=>{s+=this.renderNode(n)}),e.optimizeImages?this.optimizeImages(s,e.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
|
|
21
21
|
The "content" field must be an array of nodes as the type ISbRichtext.
|
|
22
22
|
ISbRichtext:
|
|
23
23
|
content?: ISbRichtext[]
|
|
@@ -40,23 +40,23 @@ Detailed information can be found here: https://github.com/storyblok/storyblok-a
|
|
|
40
40
|
}
|
|
41
41
|
],
|
|
42
42
|
type: 'doc'
|
|
43
|
-
}`),""}optimizeImages(e,t){let s=0,o=0,n="",i="";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&&(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-F]{6}/gi)||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}`))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const a=s>0||o>0||i.length>0?`${s}x${o}${i}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${a}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,l=>{var c,h;const u=l.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(u&&u.length>0){const p={srcset:(c=t.srcset)==null?void 0:c.map(g=>{if(typeof g=="number")return`//${u}/m/${g}x0${i} ${g}w`;if(typeof g=="object"&&g.length===2){let v=0,k=0;return typeof g[0]=="number"&&(v=g[0]),typeof g[1]=="number"&&(k=g[1]),`//${u}/m/${v}x${k}${i} ${v}w`}return""}).join(", "),sizes:(h=t.sizes)==null?void 0:h.map(g=>g).join(", ")};let b="";return p.srcset&&(b+=`srcset="${p.srcset}" `),p.sizes&&(b+=`sizes="${p.sizes}" `),l.replace(/<img/g,`<img ${b.trim()}`)}return l})),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(Pe(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(s=>{if(s.constructor===String)return`<${s}${t}>`;{let o=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const i=s.attrs[n];i!==null&&(o+=` ${n}="${i}"`)}}return`${o}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}class je{constructor(e){d(this,"baseURL"),d(this,"timeout"),d(this,"headers"),d(this,"responseInterceptor"),d(this,"fetch"),d(this,"ejectInterceptor"),d(this,"url"),d(this,"parameters"),d(this,"fetchOptions"),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={},this.fetchOptions={}}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 l=new C;t=`${this.baseURL}${this.url}?${l.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:i}=n;let a;this.timeout&&(a=setTimeout(()=>n.abort(),this.timeout));try{const l=await this.fetch(`${o}`,{method:e,headers:this.headers,body:s,signal:i,...this.fetchOptions});this.timeout&&clearTimeout(a);const c=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(l){return{message:l}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}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:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const H="SB-Agent",I={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let A={};const m={};class xe{constructor(e,t){d(this,"client"),d(this,"maxRetries"),d(this,"retriesDelay"),d(this,"throttle"),d(this,"accessToken"),d(this,"cache"),d(this,"helpers"),d(this,"resolveCounter"),d(this,"relations"),d(this,"links"),d(this,"richTextResolver"),d(this,"resolveNestedRelations"),d(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const i=new C().getRegionURL,a=e.https===!1?"http":"https";e.oauthToken?s=`${a}://${i(e.region)}/v1`:s=`${a}://${i(e.region)}/v2`}const o=new Headers;o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([i,a])=>{o.set(i,a)}),o.has(H)||(o.set(H,I.defaultAgentName),o.set(I.defaultAgentVersion,I.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new $(e.richTextSchema):this.richTextResolver=new $,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=ne(this.throttledRequest.bind(this),n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new C,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new je({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.token||(e.token=this.getToken()),e.cv||(e.cv=m[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,o,n){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,o));return this.cacheResponse(e,i,void 0,n)}get(e,t,s){t||(t={});const o=`/${e}`,n=this.factoryParamOptions(o,t);return this.cacheResponse(o,n,void 0,s)}async getAll(e,t,s,o){const n=(t==null?void 0:t.per_page)||25,i=`/${e}`.replace(/\/$/,""),a=s??i.substring(i.lastIndexOf("/")+1),l=1,c=await this.makeRequest(i,t,n,l,o),h=c.total?Math.ceil(c.total/n):1,u=await this.helpers.asyncMap(this.helpers.range(l,h),p=>this.makeRequest(i,t,n,p+1,o));return this.helpers.flatMap([c,...u],p=>Object.values(p.data[a]))}post(e,t,s){const o=`/${e}`;return Promise.resolve(this.throttle("post",o,t,s))}put(e,t,s){const o=`/${e}`;return Promise.resolve(this.throttle("put",o,t,s))}delete(e,t,s){t||(t={});const o=`/${e}`;return Promise.resolve(this.throttle("delete",o,t,s))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_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]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,s){const o=e[t];typeof o=="string"?e[t]=this.getStoryReference(s,o):Array.isArray(o)&&(e[t]=o.map(n=>this.getStoryReference(s,n)).filter(Boolean))}_insertRelations(e,t,s,o){if(Array.isArray(s)?s.find(i=>i.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,o);return}const n=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(n):s===n)&&this._resolveField(e,t,o)}iterateTree(e,t,s){const o=(n,i="")=>{if(!(!n||n._stopResolving)){if(Array.isArray(n))n.forEach((a,l)=>o(a,`${i}[${l}]`));else if(typeof n=="object")for(const a in n){const l=i?`${i}.${a}`:a;(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,a,t,s),this._insertLinks(n,a,s)),o(n[a],l)}}};o(e.content)}async resolveLinks(e,t,s){let o=[];if(e.link_uuids){const n=e.link_uuids.length,i=[],a=50;for(let l=0;l<n;l+=a){const c=Math.min(n,l+a);i.push(e.link_uuids.slice(l,c))}for(let l=0;l<i.length;l++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:i[l].join(",")})).data.stories.forEach(c=>{o.push(c)})}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,i=[],a=50;for(let l=0;l<n;l+=a){const c=Math.min(n,l+a);i.push(e.rel_uuids.slice(l,c))}for(let l=0;l<i.length;l++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:i[l].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(c=>{o.push(c)})}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 o,n;let i=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(i=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((o=e.links)!=null&&o.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const a in this.relations[s])this.iterateTree(this.relations[s][a],i,s);e.story?this.iterateTree(e.story,i,s):e.stories.forEach(a=>{this.iterateTree(a,i,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,o){const n=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const a=await i.get(n);if(a)return Promise.resolve(a)}return new Promise(async(a,l)=>{var c;try{const h=await this.throttle("get",e,t,o);if(h.status!==200)return l(h);let u={data:h.data,headers:h.headers};if((c=h.headers)!=null&&c["per-page"]&&(u=Object.assign({},u,{perPage:h.headers["per-page"]?Number.parseInt(h.headers["per-page"]):0,total:h.headers["per-page"]?Number.parseInt(h.headers.total):0})),u.data.story||u.data.stories){const b=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${b}`)}t.version==="published"&&e!=="/cdn/spaces/me"&&await i.set(n,u);const p=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&u.data.cv&&(p&&m[t.token]&&m[t.token]!==u.data.cv&&await this.flushCache(),m[t.token]=u.data.cv),a(u)}catch(h){if(h.response&&h.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(a).catch(l);l(h)}})}throttledRequest(e,t,s,o){return this.client.setFetchOptions(o),this.client[e](t,s)}cacheVersions(){return m}cacheVersion(){return m[this.accessToken]}setCacheVersion(e){this.accessToken&&(m[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(m[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(A[e])},getAll(){return Promise.resolve(A)},set(e,t){return A[e]=t,Promise.resolve(void 0)},flush(){return A={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},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.clearCacheVersion(),this}}const Oe=(r={})=>{const{apiOptions:e}=r;if(!e||!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new xe(e)}},Ne=r=>{if(typeof r!="object"||typeof r._editable>"u")return{};try{const e=JSON.parse(r._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":`${e.id}-${e.uid}`}:{}}catch{return{}}};let L,E="https://app.storyblok.com/f/storyblok-v2-latest.js";const q=(r,e)=>{r.addNode("blok",t=>{let s="";return t.attrs.body.forEach(o=>{s+=e(o.component,o)}),{html:s}})},Me=(r={})=>{var e,t;const{bridge:s,accessToken:o,use:n=[],apiOptions:i={},richText:a={},bridgeUrl:l}=r;i.accessToken=i.accessToken||o;const c={bridge:s,apiOptions:i};let h={};n.forEach(p=>{h={...h,...p(c)}}),l&&(E=l);const u=!(typeof window>"u")&&((t=(e=window.location)==null?void 0:e.search)==null?void 0:t.includes("_storyblok_tk"));return s!==!1&&u&&B(E),L=new $(a.schema),a.resolver&&q(L,a.resolver),h},Ue=r=>{var e;return!r||!((e=r==null?void 0:r.content)!=null&&e.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule"))},Fe=(r,e,t)=>{let s=t||L;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return Ue(r)?"":(e&&(s=new $(e.schema),e.resolver&&q(s,e.resolver)),s.render(r,{},!1))},Be=()=>B(E);function De(){if(!globalThis.storyblokApiInstance)throw new Error("storyblokApiInstance has not been initialized correctly");return globalThis.storyblokApiInstance}async function ze(r){let e=null;return r&&r.locals._storyblok_preview_data&&(e=r.locals._storyblok_preview_data),e}function He(r,e){var s;const t=(s=globalThis==null?void 0:globalThis.storyblokApiInstance)==null?void 0:s.richTextResolver;if(!t)throw new Error("Please initialize the Storyblok SDK before calling the renderRichText function");return Fe(r,e,t)}function qe(r){return typeof r=="object"?`const storyblokInstance = new StoryblokBridge(${JSON.stringify(r)});`:"const storyblokInstance = new StoryblokBridge();"}function Ve(r){const e={useCustomApi:!1,bridge:!0,componentsDir:"src",enableFallbackComponent:!1,livePreview:!1,...r},t=qe(e.bridge);return{name:"@storyblok/astro",hooks:{"astro:config:setup":({injectScript:s,updateConfig:o,addDevToolbarApp:n,addMiddleware:i,config:a})=>{if(o({vite:{plugins:[ee(e.accessToken,e.useCustomApi,e.apiOptions),X(e.componentsDir,e.components,e.enableFallbackComponent,e.customFallbackComponent),te(e)]}}),e.livePreview&&(a==null?void 0:a.output)!=="server")throw new Error("To utilize the Astro Storyblok Live feature, Astro must be configured to run in SSR mode. Please disable this feature or switch Astro to SSR mode.");s("page-ssr",`
|
|
43
|
+
}`),""}optimizeImages(t,e){let o=0,s=0,n="",a="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(n+=`width="${e.width}" `,o=e.width),typeof e.height=="number"&&e.height>0&&(n+=`height="${e.height}" `,s=e.height),(e.loading==="lazy"||e.loading==="eager")&&(n+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(n+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(a+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(a+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-F]{6}/gi)||e.filters.fill==="transparent")&&(a+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(a+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(a+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(a+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(a+=`:rotate(${e.filters.rotate})`),a.length>0&&(a=`/filters${a}`))),n.length>0&&(t=t.replace(/<img/g,`<img ${n.trim()}`));const l=o>0||s>0||a.length>0?`${o}x${s}${a}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,i=>{var c,d;const f=i.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(f&&f.length>0){const h={srcset:(c=e.srcset)==null?void 0:c.map(g=>{if(typeof g=="number")return`//${f}/m/${g}x0${a} ${g}w`;if(typeof g=="object"&&g.length===2){let w=0,j=0;return typeof g[0]=="number"&&(w=g[0]),typeof g[1]=="number"&&(j=g[1]),`//${f}/m/${w}x${j}${a} ${w}w`}return""}).join(", "),sizes:(d=e.sizes)==null?void 0:d.map(g=>g).join(", ")};let k="";return h.srcset&&(k+=`srcset="${h.srcset}" `),h.sizes&&(k+=`sizes="${h.sizes}" `),i.replace(/<img/g,`<img ${k.trim()}`)}return i})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(s=>{const n=this.getMatchingMark(s);n&&n.tag!==""&&e.push(this.renderOpeningTag(n.tag))});const o=this.getMatchingNode(t);return o&&o.tag&&e.push(this.renderOpeningTag(o.tag)),t.content?t.content.forEach(s=>{e.push(this.renderNode(s))}):t.text?e.push(me(t.text)):o&&o.singleTag?e.push(this.renderTag(o.singleTag," /")):o&&o.html?e.push(o.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),o&&o.tag&&e.push(this.renderClosingTag(o.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const n=this.getMatchingMark(s);n&&n.tag!==""&&e.push(this.renderClosingTag(n.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(o=>{if(o.constructor===String)return`<${o}${e}>`;{let s=`<${o.tag}`;if(o.attrs){for(const n in o.attrs)if(Object.prototype.hasOwnProperty.call(o.attrs,n)){const a=o.attrs[n];a!==null&&(s+=` ${n}="${a}"`)}}return`${s}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){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," /")}}const ke=r=>{if(typeof r!="object"||typeof r._editable>"u")return{};try{const t=JSON.parse(r._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":`${t.id}-${t.uid}`}:{}}catch{return{}}};let we,$e="https://app.storyblok.com/f/storyblok-v2-latest.js";const ve=(r,t)=>{r.addNode("blok",e=>{let o="";return e.attrs.body.forEach(s=>{o+=t(s.component,s)}),{html:o}})},Ce=r=>{var t;return!r||!((t=r==null?void 0:r.content)!=null&&t.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule"))},Se=(r,t,e)=>{let o=e||we;if(!o){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return Ce(r)?"":(t&&(o=new L(t.schema),t.resolver&&ve(o,t.resolver)),o.render(r,{},!1))},Ie=()=>U($e);function Ae(){if(!(globalThis!=null&&globalThis.storyblokApiInstance))throw new Error("storyblokApiInstance has not been initialized correctly");return globalThis.storyblokApiInstance}async function Te(r){let t=null;return r&&r.locals._storyblok_preview_data&&(t=r.locals._storyblok_preview_data),t}function Ee(r,t){var o;const e=(o=globalThis==null?void 0:globalThis.storyblokApiInstance)==null?void 0:o.richTextResolver;if(!e)throw new Error("Please initialize the Storyblok SDK before calling the renderRichText function");return Se(r,t,e)}function Le(r){return typeof r=="object"?`const storyblokInstance = new StoryblokBridge(${JSON.stringify(r)});`:"const storyblokInstance = new StoryblokBridge();"}function xe(r){const t={useCustomApi:!1,bridge:!0,componentsDir:"src",enableFallbackComponent:!1,livePreview:!1,...r},e=Le(t.bridge);return{name:"@storyblok/astro",hooks:{"astro:config:setup":({injectScript:o,updateConfig:s,addDevToolbarApp:n,addMiddleware:a,config:l})=>{if(s({vite:{plugins:[D(t.accessToken,t.useCustomApi,t.apiOptions),B(t.componentsDir,t.components,t.enableFallbackComponent,t.customFallbackComponent),F(t)]}}),t.livePreview&&(l==null?void 0:l.output)!=="server")throw new Error("To utilize the Astro Storyblok Live feature, Astro must be configured to run in SSR mode. Please disable this feature or switch Astro to SSR mode.");o("page-ssr",`
|
|
44
44
|
import { storyblokApiInstance } from "virtual:storyblok-init";
|
|
45
45
|
globalThis.storyblokApiInstance = storyblokApiInstance;
|
|
46
|
-
`),
|
|
46
|
+
`),t.bridge&&!t.livePreview&&o("page",`import { loadStoryblokBridge } from "@storyblok/astro";
|
|
47
47
|
loadStoryblokBridge().then(() => {
|
|
48
48
|
const { StoryblokBridge, location } = window;
|
|
49
|
-
${
|
|
49
|
+
${e}
|
|
50
50
|
storyblokInstance.on(["published", "change"], (event) => {
|
|
51
51
|
if (!event.slugChanged) {
|
|
52
52
|
location.reload(true);
|
|
53
53
|
}
|
|
54
54
|
});
|
|
55
55
|
});
|
|
56
|
-
`),
|
|
56
|
+
`),t.livePreview&&(o("page",`import { loadStoryblokBridge, handleStoryblokMessage } from "@storyblok/astro";
|
|
57
57
|
loadStoryblokBridge().then(() => {
|
|
58
58
|
const { StoryblokBridge, location } = window;
|
|
59
|
-
${
|
|
59
|
+
${e}
|
|
60
60
|
storyblokInstance.on(["published", "change", "input"], handleStoryblokMessage);
|
|
61
61
|
});
|
|
62
|
-
`),
|
|
62
|
+
`),a({entrypoint:"@storyblok/astro/middleware.ts",order:"pre"})),n({id:"storyblok",name:"Storyblok",icon:y,entrypoint:"@storyblok/astro/toolbarApp.ts"})}}}}let x;async function je(r){const{action:t,story:e}=r||{};if(t==="input"&&e){const o=async()=>{const n=await Me(e),a=document.body;if(n.outerHTML===a.outerHTML)return;const l=document.querySelector('[data-blok-focused="true"]');Re(a,n,l),document.dispatchEvent(new Event("storyblok-live-preview-updated"))};clearTimeout(x),x=setTimeout(o,500)}["published","change"].includes(r==null?void 0:r.action)&&location.reload()}function Re(r,t,e){if(e){const o=e.getAttribute("data-blok-uid"),s=t.querySelector(`[data-blok-uid="${o}"]`);s&&(s.setAttribute("data-blok-focused","true"),e.replaceWith(s))}else r.replaceWith(t)}async function Me(r){const e=await(await fetch(location.href,{method:"POST",body:JSON.stringify({...r,is_storyblok_preview:!0}),headers:{"Content-Type":"application/json"}})).text();return new DOMParser().parseFromString(e,"text/html").body}u.RichTextResolver=L,u.RichTextSchema=T,u.getLiveStory=Te,u.handleStoryblokMessage=je,u.loadStoryblokBridge=Ie,u.renderRichText=Ee,u.storyblok=xe,u.storyblokEditable=ke,u.toCamelCase=m,u.useStoryblokApi=Ae,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storyblok/astro",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.1.0
|
|
4
|
+
"version": "6.1.0",
|
|
5
5
|
"private": false,
|
|
6
6
|
"packageManager": "pnpm@9.13.2",
|
|
7
7
|
"description": "Official Astro integration for the Storyblok Headless CMS",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"astro": "^3.0.0 || ^4.0.0 || ^5.0.0"
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@storyblok/js": "3.
|
|
75
|
+
"@storyblok/js": "3.3.0",
|
|
76
76
|
"camelcase": "^8.0.0"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { Loader } from 'astro/loaders';
|
|
2
|
-
import { ISbConfig, ISbStoriesParams } from '@storyblok/js';
|
|
3
|
-
interface StoryblokLoaderConfig {
|
|
4
|
-
accessToken: string;
|
|
5
|
-
version: 'draft' | 'published';
|
|
6
|
-
useCustomApi?: boolean;
|
|
7
|
-
apiOptions?: ISbConfig;
|
|
8
|
-
storiesParams?: ISbStoriesParams;
|
|
9
|
-
}
|
|
10
|
-
export declare function storyblokLoader(config: StoryblokLoaderConfig): Loader;
|
|
11
|
-
export {};
|