@storyblok/astro 1.0.1 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -5
- package/StoryblokComponent.astro +21 -4
- package/dist/storyblok-astro.js +4 -4
- package/dist/storyblok-astro.mjs +397 -366
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
<a href="https://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-astro" align="center">
|
|
3
|
-
<img src="https://a.storyblok.com/f/88751/
|
|
3
|
+
<img src="https://a.storyblok.com/f/88751/1500x500/7974d6bc34/storyblok-astro.png" width="300" height="100" alt="Storyblok + Astro">
|
|
4
4
|
</a>
|
|
5
5
|
<h1 align="center">@storyblok/astro</h1>
|
|
6
6
|
<p align="center">Astro module for the <a href="http://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-astro" target="_blank">Storyblok</a> Headless CMS.</p> <br />
|
|
@@ -61,7 +61,7 @@ export default defineConfig({
|
|
|
61
61
|
|
|
62
62
|
### Options
|
|
63
63
|
|
|
64
|
-
When you initialize the module, you can pass all [_@storyblok/js_ options](https://github.com/storyblok/storyblok-js#features-and-api)
|
|
64
|
+
When you initialize the module, you can pass all [_@storyblok/js_ options](https://github.com/storyblok/storyblok-js#features-and-api). For Spaces created in the United States, you have to set the `region` parameter accordingly `{ apiOptions: { region: 'us' } }`.
|
|
65
65
|
|
|
66
66
|
```js
|
|
67
67
|
// Defaults
|
|
@@ -143,7 +143,7 @@ For working examples, please refer to the [Live Demo on Stackblitz](https://stac
|
|
|
143
143
|
|
|
144
144
|
### 2. Getting Storyblok Stories and using the Storyblok Bridge
|
|
145
145
|
|
|
146
|
-
|
|
146
|
+
#### Fetching one Story
|
|
147
147
|
|
|
148
148
|
Use the `useStoryblokApi` function to have access to an instance of `storyblok-js-client`:
|
|
149
149
|
|
|
@@ -165,7 +165,7 @@ const story = data.story;
|
|
|
165
165
|
|
|
166
166
|
> Note: The available methods are described in the [storyblok-js-client] repository(https://github.com/storyblok/storyblok-js-client#method-storyblokget)
|
|
167
167
|
|
|
168
|
-
|
|
168
|
+
#### Dynamic Routing
|
|
169
169
|
|
|
170
170
|
In order to dynamically generate Astro pages based on the Stories in your Storyblok Space, you can use the [Storyblok Links API](https://www.storyblok.com/docs/api/content-delivery/v2#core-resources/links/links) and the Astro [`getStaticPaths()` function](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) similar to this example:
|
|
171
171
|
|
|
@@ -210,7 +210,7 @@ The Storyblok Bridge is automatically activated by default. If you would like to
|
|
|
210
210
|
|
|
211
211
|
> Note: Since Astro is not a reactive JavaScript framework and renders everything as HTML, the Storyblok Bridge will not provide real-time editing as you may know it from other frameworks. However, it automatically refreshes the site for you whenever you save or publish a story.
|
|
212
212
|
|
|
213
|
-
|
|
213
|
+
### Rendering Rich Text
|
|
214
214
|
|
|
215
215
|
You can easily render rich text by using the `renderRichText` function that comes with `@storyblok/astro`. Then you can use the [`set:html` directive](https://docs.astro.build/en/reference/directives-reference/#sethtml):
|
|
216
216
|
|
|
@@ -226,6 +226,32 @@ const renderedRichText = renderRichText(blok.text)
|
|
|
226
226
|
<div set:html={renderedRichText}></div>
|
|
227
227
|
```
|
|
228
228
|
|
|
229
|
+
You can also set a **custom Schema and component resolver** by passing the options as the second parameter of the `renderRichText` function:
|
|
230
|
+
|
|
231
|
+
```js
|
|
232
|
+
import { RichTextSchema, renderRichText } from "@storyblok/astro";
|
|
233
|
+
import cloneDeep from "clone-deep";
|
|
234
|
+
|
|
235
|
+
const mySchema = cloneDeep(RichTextSchema); // you can make a copy of the default RichTextSchema
|
|
236
|
+
// ... and edit the nodes and marks, or add your own.
|
|
237
|
+
// Check the base RichTextSchema source here https://github.com/storyblok/storyblok-js-client/blob/master/source/schema.js
|
|
238
|
+
|
|
239
|
+
const { blok } = Astro.props
|
|
240
|
+
|
|
241
|
+
const renderedRichText = renderRichText(blok.text, {
|
|
242
|
+
schema: mySchema,
|
|
243
|
+
resolver: (component, blok) => {
|
|
244
|
+
switch (component) {
|
|
245
|
+
case "my-custom-component":
|
|
246
|
+
return `<div class="my-component-class">${blok.text}</div>`;
|
|
247
|
+
break;
|
|
248
|
+
default:
|
|
249
|
+
return `Component ${component} not found`;
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
```
|
|
254
|
+
|
|
229
255
|
## API
|
|
230
256
|
|
|
231
257
|
### useStoryblokApi()
|
package/StoryblokComponent.astro
CHANGED
|
@@ -1,8 +1,25 @@
|
|
|
1
1
|
---
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import components from "virtual:storyblok-components";
|
|
3
|
+
import camelcase from "camelcase";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
const { blok, ...props } = Astro.props;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* convert blok components to camel case to match vite-plugin-storyblok
|
|
9
|
+
*/
|
|
10
|
+
const key = camelcase(blok.component);
|
|
11
|
+
|
|
12
|
+
if (!(key in components)) {
|
|
13
|
+
/**
|
|
14
|
+
* Component not found! Log an error with details on the blok name that could not be found
|
|
15
|
+
* TODO: Add support for a placeholder component as a fallback?
|
|
16
|
+
*/
|
|
17
|
+
throw new Error(
|
|
18
|
+
`Component could not be found for blok "${blok.component}"! Is it defined in astro.config.mjs?`
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const Component = components[key];
|
|
6
23
|
---
|
|
7
24
|
|
|
8
|
-
<Component blok={blok} />
|
|
25
|
+
<Component blok={blok} {...props} />
|
package/dist/storyblok-astro.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(u,p){typeof exports=="object"&&typeof module<"u"?p(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],p):(u=typeof globalThis<"u"?globalThis:u||self,p(u.storyblokAstro={},u.axios))})(this,function(u,p){"use strict";const M=(s=>s&&typeof s=="object"&&"default"in s?s:{default:s})(p),U=/[\p{Lu}]/u,D=/[\p{Ll}]/u,T=/^[\p{Lu}](?![\p{Lu}])/gu,_=/([\p{Alpha}\p{N}_]|$)/u,m=/[_.\- ]+/,q=new RegExp("^"+m.source),R=new RegExp(m.source+_.source,"gu"),w=new RegExp("\\d+"+_.source,"gu"),B=(s,e,t)=>{let r=!1,o=!1,n=!1;for(let i=0;i<s.length;i++){const a=s[i];r&&U.test(a)?(s=s.slice(0,i)+"-"+s.slice(i),r=!1,n=o,o=!0,i++):o&&n&&D.test(a)?(s=s.slice(0,i-1)+"-"+s.slice(i-1),n=o,o=!1,r=!0):(r=e(a)===a&&t(a)!==a,n=o,o=t(a)===a&&e(a)!==a)}return s},z=(s,e)=>(T.lastIndex=0,s.replace(T,t=>e(t))),H=(s,e)=>(R.lastIndex=0,w.lastIndex=0,s.replace(R,(t,r)=>e(r)).replace(w,t=>e(t)));function E(s,e){if(!(typeof s=="string"||Array.isArray(s)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(s)?s=s.map(n=>n.trim()).filter(n=>n.length).join("-"):s=s.trim(),s.length===0)return"";const t=e.locale===!1?n=>n.toLowerCase():n=>n.toLocaleLowerCase(e.locale),r=e.locale===!1?n=>n.toUpperCase():n=>n.toLocaleUpperCase(e.locale);return s.length===1?m.test(s)?"":e.pascalCase?r(s):t(s):(s!==t(s)&&(s=B(s,t,r)),s=s.replace(q,""),s=e.preserveConsecutiveUppercase?z(s,t):t(s),e.pascalCase&&(s=r(s.charAt(0))+s.slice(1)),H(s,r))}function V(s){const e="virtual:storyblok-components",t="\0"+e;return{name:"vite-plugin-storyblok",async resolveId(r){if(r===e)return t},async load(r){if(r===t){const o=[];for await(const[n,i]of Object.entries(s)){const{id:a}=await this.resolve("/src/"+i+".astro");o.push(`import ${E(n)} from "${a}"`)}return`${o.join(";")};export default {${Object.keys(s).map(n=>E(n)).join(",")}}`}}}}var F=Object.defineProperty,J=Object.defineProperties,G=Object.getOwnPropertyDescriptors,A=Object.getOwnPropertySymbols,K=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,$=(s,e,t)=>e in s?F(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,d=(s,e)=>{for(var t in e||(e={}))K.call(e,t)&&$(s,t,e[t]);if(A)for(var t of A(e))Y.call(e,t)&&$(s,t,e[t]);return s},k=(s,e)=>J(s,G(e));let S=!1;const O=[],x=s=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=o=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}S?o():O.push(o)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=s,r.id="storyblok-javascript-bridge",r.onerror=o=>t(o),r.onload=o=>{O.forEach(n=>n()),S=!0,e(o)},document.getElementsByTagName("head")[0].appendChild(r)}),W=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t},Q=s=>s==="email";var C={nodes:{horizontal_rule(){return{singleTag:"hr"}},blockquote(){return{tag:"blockquote"}},bullet_list(){return{tag:"ul"}},code_block(s){return{tag:["pre",{tag:"code",attrs:s.attrs}]}},hard_break(){return{singleTag:"br"}},heading(s){return{tag:`h${s.attrs.level}`}},image(s){return{singleTag:[{tag:"img",attrs:W(s.attrs,["src","alt","title"])}]}},list_item(){return{tag:"li"}},ordered_list(){return{tag:"ol"}},paragraph(){return{tag:"p"}}},marks:{bold(){return{tag:"b"}},strike(){return{tag:"strike"}},underline(){return{tag:"u"}},strong(){return{tag:"strong"}},code(){return{tag:"code"}},italic(){return{tag:"i"}},link(s){const e=d({},s.attrs),{linktype:t="url"}=s.attrs;return Q(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled(s){return{tag:[{tag:"span",attrs:s.attrs}]}}}};const X=function(s){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return s&&r.test(s)?s.replace(t,o=>e[o]):s};class I{constructor(e){e||(e=C),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(X(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&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(let i in o.attrs){let a=o.attrs[i];a!==null&&(n+=` ${i}="${a}"`)}return`${n}${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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}/*!
|
|
2
2
|
* storyblok-js-client v4.5.2
|
|
3
3
|
* Universal JavaScript SDK for Storyblok's API
|
|
4
4
|
* (c) 2020-2022 Stobylok Team
|
|
5
|
-
*/function O(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function E(n,e,t){if(!O(e))throw new TypeError("Expected `limit` to be a finite number");if(!O(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,r.length>0&&a(),s=s.filter(function(u){return u!==c})},t);s.indexOf(c)<0&&s.push(c);var l=r.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,f){r.push({resolve:u,reject:f,args:c,self:l}),o<e&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(c){c.reject(new throttle.AbortError)}),r.length=0},i}E.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const U=function(n,e){if(!n)return null;let t={};for(let r in n){let s=n[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t};var D={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:U(n.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(n){const e=d({},n.attrs),{linktype:t="url"}=n.attrs;return t==="email"&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class H{constructor(e){e||(e=D),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderOpeningTag(o.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(function(s){const o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderClosingTag(o.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let s=`<${r.tag}`;if(r.attrs)for(let o in r.attrs){let a=r.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const V=(n=0,e=n)=>{const t=Math.abs(e-n)||0,r=n<e?1:-1;return((s=0,o)=>[...Array(s)].map(o))(t,(s,o)=>o*r+n)},b=(n,e,t)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=t?"":encodeURIComponent(s);let i;i=typeof o=="object"?b(o,e?e+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(e?e+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),r.push(i)}return r.join("&")};let y={},p={};class J{constructor(e,t){if(!t){let o=e.region?`-${e.region}`:"",a=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let r=Object.assign({},e.headers),s=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,s=3),e.rateLimit!==void 0&&(s=e.rateLimit),this.richTextResolver=new H(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=E(this.throttledRequest,s,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=x.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(o=>e.responseInterceptor(o)),this.resolveNestedRelations=e.resolveNestedRelations||!0}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=p[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,s){const o=this.factoryParamOptions(e,((a={},i=25,c=1)=>m(d({},a),{per_page:i,page:c}))(t,r,s));return this.cacheResponse(e,o)}get(e,t){let r=`/${e}`;const s=this.factoryParamOptions(r,t);return this.cacheResponse(r,s)}async getAll(e,t={},r){const s=t.per_page||25,o=`/${e}`,a=o.split("/");r=r||a[a.length-1];const i=await this.makeRequest(o,t,s,1),c=Math.ceil(i.total/s);return((l=[],u)=>l.map(u).reduce((f,ee)=>[...f,...ee],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(V(1,c),async l=>this.makeRequest(o,t,s,l+1))],l=>Object.values(l.data[r]))}post(e,t){let r=`/${e}`;return this.throttle("post",r,t)}put(e,t){let r=`/${e}`;return this.throttle("put",r,t)}delete(e,t){let r=`/${e}`;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let s=[];e[t].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),e[t]=s}}}_insertAssetsRelations(e,t){t.forEach(r=>{e.id===r.id&&(e.original=r,e.original.filename=e.filename,e.original.filename=e.original.filename.includes("https://s3.amazonaws.com/")?e.original.filename:e.original.filename.replace("https://","https://s3.amazonaws.com/"),delete e.original.s3_filename)})}iterateTree(e,t){let r=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)r(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,o,t),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,t),r(s[o])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const s=e.link_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(e.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(s=>{this.links[s.uuid]=m(d({},s),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const s=e.rel_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(e.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r.forEach(s=>{this.relations[s.uuid]=m(d({},s),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];if(t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(e.rels||e.rel_uuids)&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&(e.links||e.link_uuids)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(e){const{assets:t,stories:r,story:s}=e;if(r)for(const o of r)this.iterateTree(o,t);else{if(!s)return e;this.iterateTree(s,t)}}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let a=b({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",e,{params:t,paramsSerializer:f=>b(f)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(t.version=="draft"&&p[t.token]!=u.data.cv&&this.flushCache(),p[t.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(c=1e3*r,new Promise(u=>setTimeout(u,c))),this.cacheResponse(e,t,r).then(s).catch(o);o(l)}var c})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(e){this.accessToken&&(p[this.accessToken]=e)}cacheProvider(){return this.cache.type==="memory"?{get:e=>y[e],getAll:()=>y,set(e,t){y[e]=t},flush(){y={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const F=(n={})=>{const{apiOptions:e}=n;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new J(e)}};var Y=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};let k;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",K=(n={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||t;const a={bridge:e,apiOptions:s};let i={};return r.forEach(c=>{i=d(d({},i),c(a))}),e!==!1&&R(j),k=new $(o.schema),o.resolver&&S(k,o.resolver),i},S=(n,e)=>{n.addNode("blok",t=>{let r="";return t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})},G=(n,e)=>{if(!k){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}if(n==="")return"";if(!n)return console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
|
5
|
+
*/function j(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function P(s,e,t){if(!j(e))throw new TypeError("Expected `limit` to be a finite number");if(!j(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var c=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(h){return h!==c})},t);o.indexOf(c)<0&&o.push(c);var l=r.shift();l.resolve(s.apply(l.self,l.args))},a=function(){var c=arguments,l=this;return new Promise(function(h,g){r.push({resolve:h,reject:g,args:c,self:l}),n<e&&i()})};return a.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(c){c.reject(new throttle.AbortError)}),r.length=0},a}P.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const Z=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var ee={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:Z(s.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=d({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class te{constructor(e){e||(e=ee),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(function(o){const n={"&":"&","<":"<",">":">",'"':""","'":"'"},i=/[&<>"']/g,a=RegExp(i.source);return o&&a.test(o)?o.replace(i,c=>n[c]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let o=`<${r.tag}`;if(r.attrs)for(let n in r.attrs){let i=r.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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const re=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},b=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let a;a=typeof n=="object"?b(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let y={},f={};class se{constructor(e,t){if(!t){let n=e.region?`-${e.region}`:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new te(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=P(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=M.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n)),this.resolveNestedRelations=e.resolveNestedRelations||!0}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=f[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},a=25,c=1)=>k(d({},i),{per_page:a,page:c}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r=`/${e}`;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n=`/${e}`,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,t,o,1),c=Math.ceil(a.total/o);return((l=[],h)=>l.map(h).reduce((g,fe)=>[...g,...fe],[]))([a,...await(async(l=[],h)=>Promise.all(l.map(h)))(re(1,c),async l=>this.makeRequest(n,t,o,l+1))],l=>Object.values(l.data[r]))}post(e,t){let r=`/${e}`;return this.throttle("post",r,t)}put(e,t){let r=`/${e}`;return this.throttle("put",r,t)}delete(e,t){let r=`/${e}`;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}_insertAssetsRelations(e,t){t.forEach(r=>{e.id===r.id&&(e.original=r,e.original.filename=e.filename,e.original.filename=e.original.filename.includes("https://s3.amazonaws.com/")?e.original.filename:e.original.filename.replace("https://","https://s3.amazonaws.com/"),delete e.original.s3_filename)})}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)o.component&&o._uid||o.type==="link"?(this._insertRelations(o,n,t),this._insertLinks(o,n)):"id"in o&&o.fieldtype==="asset"&&this._insertAssetsRelations(o,t),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const c=Math.min(o,a+i);n.push(e.link_uuids.slice(a,c))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=k(d({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const c=Math.min(o,a+i);n.push(e.rel_uuids.slice(a,c))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=k(d({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];if(t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(e.rels||e.rel_uuids)&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&(e.links||e.link_uuids)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}resolveAssetsRelations(e){const{assets:t,stories:r,story:o}=e;if(r)for(const n of r)this.iterateTree(n,t);else{if(!o)return e;this.iterateTree(o,t)}}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=b({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await a.get(i);if(l)return o(l)}try{let l=await this.throttle("get",e,{params:t,paramsSerializer:g=>b(g)}),h={data:l.data,headers:l.headers};if(h.data.assets&&h.data.assets.length&&this.resolveAssetsRelations(h.data),l.headers["per-page"]&&(h=Object.assign({},h,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return n(l);(h.data.story||h.data.stories)&&await this.resolveStories(h.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,h),h.data.cv&&(t.version=="draft"&&f[t.token]!=h.data.cv&&this.flushCache(),f[t.token]=h.data.cv),o(h)}catch(l){if(l.response&&l.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(c=1e3*r,new Promise(h=>setTimeout(h,c))),this.cacheResponse(e,t,r).then(o).catch(n);n(l)}var c})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return f}cacheVersion(){return f[this.accessToken]}setCacheVersion(e){this.accessToken&&(f[this.accessToken]=e)}cacheProvider(){return this.cache.type==="memory"?{get:e=>y[e],getAll:()=>y,set(e,t){y[e]=t},flush(){y={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const oe=(s={})=>{const{apiOptions:e}=s;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new se(e)}};var ne=s=>{if(typeof s!="object"||typeof s._editable>"u")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};let v;const N="https://app.storyblok.com/f/storyblok-v2-latest.js",ae=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={},richText:n={}}=s;o.accessToken=o.accessToken||t;const i={bridge:e,apiOptions:o};let a={};return r.forEach(c=>{a=d(d({},a),c(i))}),e!==!1&&x(N),v=new I(n.schema),n.resolver&&L(v,n.resolver),a},L=(s,e)=>{s.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})},ie=(s,e,t)=>{let r=t||v;if(!r){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return s===""?"":s?(e&&(r=new I(e.schema),e.resolver&&L(r,e.resolver)),r.render(s)):(console.warn(`${s} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
|
6
6
|
|
|
7
|
-
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),""
|
|
7
|
+
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},le=()=>x(N);function ce(s,e,t){const{storyblokApi:r}=ae({accessToken:s,use:e||[oe],apiOptions:{...t}});globalThis.storyblokApiInstance=r}function he(){return globalThis.storyblokApiInstance||console.error("storyblokApiInstance has not been initialized correctly"),globalThis.storyblokApiInstance}function ue(s,e){const t=globalThis.storyblokApiInstance.richTextResolver;if(!t){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return ie(s,e,t)}function de(s){return{name:"@storyblok/astro",hooks:{"astro:config:setup":({injectScript:e,updateConfig:t})=>{var o;t({vite:{plugins:[V(s.components)]}}),ce(s.accessToken,s.use,s.apiOptions),((o=s.bridge)!=null?o:!0)&&e("page",`
|
|
8
8
|
import { loadStoryblokBridge } from "@storyblok/astro";
|
|
9
9
|
loadStoryblokBridge().then(() => {
|
|
10
10
|
const { StoryblokBridge, location } = window;
|
|
@@ -16,4 +16,4 @@
|
|
|
16
16
|
}
|
|
17
17
|
});
|
|
18
18
|
});
|
|
19
|
-
`)}}}}
|
|
19
|
+
`)}}}}u.RichTextSchema=C,u.default=de,u.loadStoryblokBridge=le,u.renderRichText=ue,u.storyblokEditable=ne,u.useStoryblokApi=he,Object.defineProperties(u,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|