@storyblok/react 4.0.0 → 4.2.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/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/client.js +1 -1
- package/dist/common/client.d.ts +3 -0
- package/dist/common/client.d.ts.map +1 -0
- package/dist/{types/common → common}/index.d.ts +2 -1
- package/dist/common/index.d.ts.map +1 -0
- package/dist/common/storyblok-component.d.ts +7 -0
- package/dist/common/storyblok-component.d.ts.map +1 -0
- package/dist/common.mjs +2 -2
- package/dist/{types/index.d.ts → index.d.ts} +2 -1
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +4 -4
- package/dist/jsx-runtime.js +2 -0
- package/dist/jsx-runtime.mjs +9 -0
- package/dist/jsx-runtime2.js +1 -0
- package/dist/jsx-runtime2.mjs +4 -0
- package/dist/live-editing.js +1 -1
- package/dist/react-jsx-runtime.development.js +23 -0
- package/dist/react-jsx-runtime.development.mjs +609 -0
- package/dist/react-jsx-runtime.development2.js +1 -0
- package/dist/react-jsx-runtime.development2.mjs +4 -0
- package/dist/react-jsx-runtime.production.min.js +10 -0
- package/dist/react-jsx-runtime.production.min.mjs +29 -0
- package/dist/react-jsx-runtime.production.min2.js +1 -0
- package/dist/react-jsx-runtime.production.min2.mjs +4 -0
- package/dist/{types/rsc → rsc}/common.d.ts +2 -1
- package/dist/rsc/common.d.ts.map +1 -0
- package/dist/{types/rsc → rsc}/index.d.ts +1 -0
- package/dist/rsc/index.d.ts.map +1 -0
- package/dist/{types/rsc → rsc}/live-edit-update-action.d.ts +1 -0
- package/dist/rsc/live-edit-update-action.d.ts.map +1 -0
- package/dist/{types/rsc → rsc}/live-editing.d.ts +1 -0
- package/dist/rsc/live-editing.d.ts.map +1 -0
- package/dist/rsc/server-component.d.ts +7 -0
- package/dist/rsc/server-component.d.ts.map +1 -0
- package/dist/rsc/story.d.ts +8 -0
- package/dist/rsc/story.d.ts.map +1 -0
- package/dist/server-component.js +1 -1
- package/dist/server-component.mjs +21 -15
- package/dist/story.js +1 -1
- package/dist/story.mjs +17 -13
- package/dist/storyblok-component.js +1 -1
- package/dist/storyblok-component.mjs +20 -14
- package/dist/storyblok-js.js +24 -24
- package/dist/storyblok-js.mjs +373 -354
- package/dist/{types/types.d.ts → types.d.ts} +2 -1
- package/dist/types.d.ts.map +1 -0
- package/package.json +52 -45
- package/dist/types/common/client.d.ts +0 -2
- package/dist/types/common/storyblok-component.d.ts +0 -8
- package/dist/types/rsc/server-component.d.ts +0 -8
- package/dist/types/rsc/story.d.ts +0 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live-edit-update-action.d.ts","sourceRoot":"","sources":["../../src/rsc/live-edit-update-action.ts"],"names":[],"mappings":"AAEA,wBAAsB,oBAAoB,CAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE;;;CAAA,iBAiBrE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live-editing.d.ts","sourceRoot":"","sources":["../../src/rsc/live-editing.tsx"],"names":[],"mappings":"AAMA,QAAA,MAAM,oBAAoB;;;SAoBzB,CAAC;AAEF,eAAe,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SbBlokData } from '@/types';
|
|
2
|
+
interface SbServerComponentProps {
|
|
3
|
+
blok: SbBlokData;
|
|
4
|
+
}
|
|
5
|
+
declare const StoryblokServerComponent: import("react").ForwardRefExoticComponent<SbServerComponentProps & import("react").RefAttributes<HTMLElement>>;
|
|
6
|
+
export default StoryblokServerComponent;
|
|
7
|
+
//# sourceMappingURL=server-component.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-component.d.ts","sourceRoot":"","sources":["../../src/rsc/server-component.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1C,UAAU,sBAAsB;IAC9B,IAAI,EAAE,UAAU,CAAC;CAClB;AAED,QAAA,MAAM,wBAAwB,gHAuC7B,CAAC;AAIF,eAAe,wBAAwB,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ISbStoryData, StoryblokBridgeConfigV2 } from '@/types';
|
|
2
|
+
interface StoryblokStoryProps {
|
|
3
|
+
story: ISbStoryData;
|
|
4
|
+
bridgeOptions?: StoryblokBridgeConfigV2;
|
|
5
|
+
}
|
|
6
|
+
declare const StoryblokStory: import("react").ForwardRefExoticComponent<StoryblokStoryProps & import("react").RefAttributes<HTMLElement>>;
|
|
7
|
+
export default StoryblokStory;
|
|
8
|
+
//# sourceMappingURL=story.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"story.d.ts","sourceRoot":"","sources":["../../src/rsc/story.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAIrE,UAAU,mBAAmB;IAC3B,KAAK,EAAE,YAAY,CAAC;IACpB,aAAa,CAAC,EAAE,uBAAuB,CAAC;CACzC;AAED,QAAA,MAAM,cAAc,6GAiCnB,CAAC;AAEF,eAAe,cAAc,CAAC"}
|
package/dist/server-component.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const e=require("react"),
|
|
1
|
+
"use strict";const e=require("./jsx-runtime.js"),m=require("react"),t=require("./common.js");require("./story.js");const i=m.forwardRef(({blok:o,...r},p)=>{if(!o)return console.error("Please provide a 'blok' property to the StoryblokComponent"),e.jsxRuntimeExports.jsx("div",{children:"Please provide a blok property to the StoryblokServerComponent"});const n=t.getComponent(o.component);if(n)return e.jsxRuntimeExports.jsx(n,{ref:p,blok:o,...r});if(t.getEnableFallbackComponent()){const s=t.getCustomFallbackComponent();return s?e.jsxRuntimeExports.jsx(s,{blok:o,...r}):e.jsxRuntimeExports.jsx(e.jsxRuntimeExports.Fragment,{children:e.jsxRuntimeExports.jsxs("p",{children:["Component could not be found for blok"," ",e.jsxRuntimeExports.jsx("strong",{children:o.component}),"! Is it configured correctly?"]})})}return e.jsxRuntimeExports.jsx("div",{})});i.displayName="StoryblokServerComponent";module.exports=i;
|
|
@@ -1,23 +1,29 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import { j as o } from "./jsx-runtime.mjs";
|
|
2
|
+
import { forwardRef as m } from "react";
|
|
3
|
+
import { getComponent as l, getEnableFallbackComponent as s, getCustomFallbackComponent as i } from "./common.mjs";
|
|
3
4
|
import "./story.mjs";
|
|
4
|
-
const
|
|
5
|
-
({ blok:
|
|
6
|
-
if (!
|
|
5
|
+
const a = m(
|
|
6
|
+
({ blok: e, ...r }, p) => {
|
|
7
|
+
if (!e)
|
|
7
8
|
return console.error(
|
|
8
9
|
"Please provide a 'blok' property to the StoryblokComponent"
|
|
9
|
-
), /* @__PURE__ */
|
|
10
|
-
const
|
|
11
|
-
if (
|
|
12
|
-
return /* @__PURE__ */
|
|
13
|
-
if (
|
|
14
|
-
const
|
|
15
|
-
return
|
|
10
|
+
), /* @__PURE__ */ o.jsx("div", { children: "Please provide a blok property to the StoryblokServerComponent" });
|
|
11
|
+
const t = l(e.component);
|
|
12
|
+
if (t)
|
|
13
|
+
return /* @__PURE__ */ o.jsx(t, { ref: p, blok: e, ...r });
|
|
14
|
+
if (s()) {
|
|
15
|
+
const n = i();
|
|
16
|
+
return n ? /* @__PURE__ */ o.jsx(n, { blok: e, ...r }) : /* @__PURE__ */ o.jsx(o.Fragment, { children: /* @__PURE__ */ o.jsxs("p", { children: [
|
|
17
|
+
"Component could not be found for blok",
|
|
18
|
+
" ",
|
|
19
|
+
/* @__PURE__ */ o.jsx("strong", { children: e.component }),
|
|
20
|
+
"! Is it configured correctly?"
|
|
21
|
+
] }) });
|
|
16
22
|
}
|
|
17
|
-
return /* @__PURE__ */
|
|
23
|
+
return /* @__PURE__ */ o.jsx("div", {});
|
|
18
24
|
}
|
|
19
25
|
);
|
|
20
|
-
|
|
26
|
+
a.displayName = "StoryblokServerComponent";
|
|
21
27
|
export {
|
|
22
|
-
|
|
28
|
+
a as default
|
|
23
29
|
};
|
package/dist/story.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const r=require("react");require("./common.js");const
|
|
1
|
+
"use strict";const r=require("./jsx-runtime.js"),s=require("react");require("./common.js");const c=require("./live-editing.js"),u=require("./server-component.js"),l=s.forwardRef(({story:e,bridgeOptions:t,...o},n)=>{if(!e)return console.error("Please provide a 'story' property to the StoryblokServerComponent"),null;if(globalThis.storyCache.has(e.uuid)&&(e=globalThis.storyCache.get(e.uuid)),typeof e.content=="string")try{e.content=JSON.parse(e.content)}catch(i){console.error("An error occurred while trying to parse the story content",i),e.content={}}return r.jsxRuntimeExports.jsxs(r.jsxRuntimeExports.Fragment,{children:[r.jsxRuntimeExports.jsx(u,{ref:n,blok:e.content,...o}),r.jsxRuntimeExports.jsx(c,{story:e,bridgeOptions:t})]})});module.exports=l;
|
package/dist/story.mjs
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { j as o } from "./jsx-runtime.mjs";
|
|
2
|
+
import { forwardRef as l } from "react";
|
|
2
3
|
import "./common.mjs";
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
const
|
|
6
|
-
({ story:
|
|
7
|
-
if (!
|
|
4
|
+
import c from "./live-editing.mjs";
|
|
5
|
+
import a from "./server-component.mjs";
|
|
6
|
+
const u = l(
|
|
7
|
+
({ story: r, bridgeOptions: e, ...t }, n) => {
|
|
8
|
+
if (!r)
|
|
8
9
|
return console.error(
|
|
9
10
|
"Please provide a 'story' property to the StoryblokServerComponent"
|
|
10
11
|
), null;
|
|
11
|
-
if (globalThis.storyCache.has(
|
|
12
|
+
if (globalThis.storyCache.has(r.uuid) && (r = globalThis.storyCache.get(r.uuid)), typeof r.content == "string")
|
|
12
13
|
try {
|
|
13
|
-
|
|
14
|
-
} catch (
|
|
14
|
+
r.content = JSON.parse(r.content);
|
|
15
|
+
} catch (i) {
|
|
15
16
|
console.error(
|
|
16
17
|
"An error occurred while trying to parse the story content",
|
|
17
|
-
|
|
18
|
-
),
|
|
18
|
+
i
|
|
19
|
+
), r.content = {};
|
|
19
20
|
}
|
|
20
|
-
return /* @__PURE__ */
|
|
21
|
+
return /* @__PURE__ */ o.jsxs(o.Fragment, { children: [
|
|
22
|
+
/* @__PURE__ */ o.jsx(a, { ref: n, blok: r.content, ...t }),
|
|
23
|
+
/* @__PURE__ */ o.jsx(c, { story: r, bridgeOptions: e })
|
|
24
|
+
] });
|
|
21
25
|
}
|
|
22
26
|
);
|
|
23
27
|
export {
|
|
24
|
-
|
|
28
|
+
u as default
|
|
25
29
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const e=require("react"),
|
|
1
|
+
"use strict";const e=require("./jsx-runtime.js"),x=require("react"),t=require("./index2.js"),i=x.forwardRef(({blok:o,...n},p)=>{if(!o)return console.error("Please provide a 'blok' property to the StoryblokComponent"),e.jsxRuntimeExports.jsx("div",{children:"Please provide a blok property to the StoryblokComponent"});const r=t.getComponent(o.component);if(r)return e.jsxRuntimeExports.jsx(r,{ref:p,blok:o,...n});if(t.getEnableFallbackComponent()){const s=t.getCustomFallbackComponent();return s?e.jsxRuntimeExports.jsx(s,{blok:o,...n}):e.jsxRuntimeExports.jsx(e.jsxRuntimeExports.Fragment,{children:e.jsxRuntimeExports.jsxs("p",{children:["Component could not be found for blok"," ",e.jsxRuntimeExports.jsx("strong",{children:o.component}),"! Is it configured correctly?"]})})}return e.jsxRuntimeExports.jsx("div",{})});i.displayName="StoryblokComponent";module.exports=i;
|
|
@@ -1,22 +1,28 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { j as o } from "./jsx-runtime.mjs";
|
|
2
|
+
import { forwardRef as m } from "react";
|
|
3
|
+
import { getComponent as l, getEnableFallbackComponent as s, getCustomFallbackComponent as i } from "./index2.mjs";
|
|
4
|
+
const a = m(
|
|
5
|
+
({ blok: e, ...t }, p) => {
|
|
6
|
+
if (!e)
|
|
6
7
|
return console.error(
|
|
7
8
|
"Please provide a 'blok' property to the StoryblokComponent"
|
|
8
|
-
), /* @__PURE__ */
|
|
9
|
-
const n =
|
|
9
|
+
), /* @__PURE__ */ o.jsx("div", { children: "Please provide a blok property to the StoryblokComponent" });
|
|
10
|
+
const n = l(e.component);
|
|
10
11
|
if (n)
|
|
11
|
-
return /* @__PURE__ */
|
|
12
|
-
if (
|
|
13
|
-
const r =
|
|
14
|
-
return r ? /* @__PURE__ */
|
|
12
|
+
return /* @__PURE__ */ o.jsx(n, { ref: p, blok: e, ...t });
|
|
13
|
+
if (s()) {
|
|
14
|
+
const r = i();
|
|
15
|
+
return r ? /* @__PURE__ */ o.jsx(r, { blok: e, ...t }) : /* @__PURE__ */ o.jsx(o.Fragment, { children: /* @__PURE__ */ o.jsxs("p", { children: [
|
|
16
|
+
"Component could not be found for blok",
|
|
17
|
+
" ",
|
|
18
|
+
/* @__PURE__ */ o.jsx("strong", { children: e.component }),
|
|
19
|
+
"! Is it configured correctly?"
|
|
20
|
+
] }) });
|
|
15
21
|
}
|
|
16
|
-
return /* @__PURE__ */
|
|
22
|
+
return /* @__PURE__ */ o.jsx("div", {});
|
|
17
23
|
}
|
|
18
24
|
);
|
|
19
|
-
|
|
25
|
+
a.displayName = "StoryblokComponent";
|
|
20
26
|
export {
|
|
21
|
-
|
|
27
|
+
a as default
|
|
22
28
|
};
|
package/dist/storyblok-js.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let _=!1;const j=[],
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}`),""}optimizeImages(e,t){let s=0,r=0,o="",i="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(o+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(o+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(o+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(o+=`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))),o.length>0&&(e=e.replace(/<img/g,`<img ${o.trim()}`));const l=s>0||r>0||i.length>0?`${s}x${r}${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/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var u,h;const d=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(d&&d.length>0){const g={srcset:(u=t.srcset)==null?void 0:u.map(p=>{if(typeof p=="number")return`//${d}/m/${p}x0${i} ${p}w`;if(typeof p=="object"&&p.length===2){let k=0,$=0;return typeof p[0]=="number"&&(k=p[0]),typeof p[1]=="number"&&($=p[1]),`//${d}/m/${k}x${$}${i} ${k}w`}}).join(", "),sizes:(h=t.sizes)==null?void 0:h.map(p=>p).join(", ")};let f="";return g.srcset&&(f+=`srcset="${g.srcset}" `),g.sizes&&(f+=`sizes="${g.sizes}" `),a.replace(/<img/g,`<img ${f.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&t.push(this.renderOpeningTag(o.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(ce(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&t.push(this.renderClosingTag(o.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs){for(const o in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,o)){const i=s.attrs[o];i!==null&&(r+=` ${o}="${i}"`)}}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const y=he;class ue{constructor(e){c(this,"baseURL"),c(this,"timeout"),c(this,"headers"),c(this,"responseInterceptor"),c(this,"fetch"),c(this,"ejectInterceptor"),c(this,"url"),c(this,"parameters"),c(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(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new v;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),o=new AbortController,{signal:i}=o;let l;this.timeout&&(l=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:i,...this.fetchOptions});this.timeout&&clearTimeout(l);const u=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}catch(a){return{message:a}}}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,r)=>{if(t.test(`${e.status}`))return s(e);const o={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(o)})}}const de=ue,S="SB-Agent",w={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let b={};const m={};class pe{constructor(e,t){c(this,"client"),c(this,"maxRetries"),c(this,"retriesDelay"),c(this,"throttle"),c(this,"accessToken"),c(this,"cache"),c(this,"helpers"),c(this,"resolveCounter"),c(this,"relations"),c(this,"links"),c(this,"richTextResolver"),c(this,"resolveNestedRelations"),c(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const i=new v().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${i(e.region)}/v1`:s=`${l}://${i(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([i,l])=>{r.set(i,l)}),r.has(S)||(r.set(S,w.defaultAgentName),r.set(w.defaultAgentVersion,w.packageVersion));let o=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),o=3),e.rateLimit&&(o=e.rateLimit),e.richTextSchema?this.richTextResolver=new y(e.richTextSchema):this.richTextResolver=new y,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=L(this.throttledRequest,o,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new v,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new de({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{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,r,o){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,i,void 0,o)}get(e,t,s){t||(t={});const r=`/${e}`,o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o,void 0,s)}async getAll(e,t,s,r){const o=(t==null?void 0:t.per_page)||25,i=`/${e}`,l=i.split("/"),a=s||l[l.length-1],u=1,h=await this.makeRequest(i,t,o,u,r),d=h.total?Math.ceil(h.total/o):1,g=await this.helpers.asyncMap(this.helpers.range(u,d),f=>this.makeRequest(i,t,o,f+1,r));return this.helpers.flatMap([h,...g],f=>Object.values(f.data[a]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("delete",r,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 r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,s,r){s.indexOf(`${e.component}.${t}`)>-1&&(typeof e[t]=="string"?e[t]=this.getStoryReference(r,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(o=>this.getStoryReference(r,o)).filter(Boolean)))}iterateTree(e,t,s){const r=o=>{if(o!=null){if(o.constructor===Array)for(let i=0;i<o.length;i++)r(o[i]);else if(o.constructor===Object){if(o._stopResolving)return;for(const i in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,i,t,s),this._insertLinks(o,i,s)),r(o[i])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const o=e.link_uuids.length,i=[],l=50;for(let a=0;a<o;a+=l){const u=Math.min(o,a+l);i.push(e.link_uuids.slice(a,u))}for(let a=0;a<i.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:i[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(o=>{this.links[s][o.uuid]={...o,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length,i=[],l=50;for(let a=0;a<o;a+=l){const u=Math.min(o,a+l);i.push(e.rel_uuids.slice(a,u))}for(let a=0;a<i.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:i[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r&&r.length>0&&r.forEach(o=>{this.relations[s][o.uuid]={...o,_stopResolving:!0}})}async resolveStories(e,t,s){var r,o;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"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(o=e.link_uuids)!=null&&o.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],i,s);e.story?this.iterateTree(e.story,i,s):e.stories.forEach(l=>{this.iterateTree(l,i,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const o=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await i.get(o);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var u;try{const h=await this.throttle("get",e,t,r);if(h.status!==200)return a(h);let d={data:h.data,headers:h.headers};if((u=h.headers)!=null&&u["per-page"]&&(d=Object.assign({},d,{perPage:h.headers["per-page"]?parseInt(h.headers["per-page"]):0,total:h.headers["per-page"]?parseInt(h.headers.total):0})),d.data.story||d.data.stories){const g=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${g}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await i.set(o,d),d.data.cv&&t.token&&(t.version==="draft"&&m[t.token]!=d.data.cv&&await this.flushCache(),m[t.token]=t.cv?t.cv:d.data.cv),l(d)}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(l).catch(a);a(h)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),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(b[e])},getAll(){return Promise.resolve(b)},set(e,t){return b[e]=t,Promise.resolve(void 0)},flush(){return b={},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 ge=(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 pe(e)}},fe=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};try{const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};let R,T="https://app.storyblok.com/f/storyblok-v2-latest.js";const E=(n,e,t={})=>{var s;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((s=window.location)==null?void 0:s.href).searchParams.get("_storyblok")===n;if(!(!r||!o)){if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],i=>{i.action==="input"&&i.story.id===n?e(i.story):(i.action==="change"||i.action==="published")&&i.storyId===n&&window.location.reload()})})}},me=(n={})=>{var e,t;const{bridge:s,accessToken:r,use:o=[],apiOptions:i={},richText:l={},bridgeUrl:a}=n;i.accessToken=i.accessToken||r;const u={bridge:s,apiOptions:i};let h={};o.forEach(g=>{h={...h,...g(u)}}),a&&(T=a);const d=!(typeof window>"u")&&((t=(e=window.location)==null?void 0:e.search)==null?void 0:t.includes("_storyblok_tk"));return s!==!1&&d&&O(T),R=new y(l.schema),l.resolver&&C(R,l.resolver),h},C=(n,e)=>{n.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},I=n=>!n||!(n!=null&&n.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),ye=(n,e,t)=>{let s=t||R;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return I(n)?"":(e&&(s=new y(e.schema),e.resolver&&C(s,e.resolver)),s.render(n))},be=()=>O(T);exports.RichTextResolver=y;exports.RichTextSchema=P;exports.apiPlugin=ge;exports.isRichTextEmpty=I;exports.loadStoryblokBridge=be;exports.registerStoryblokBridge=E;exports.renderRichText=ye;exports.storyblokEditable=fe;exports.storyblokInit=me;exports.useStoryblokBridge=E;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let _=!1;const j=[],P=o=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}_?r():j.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=o,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{j.forEach(i=>i()),_=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var N=Object.defineProperty,A=(o,e,t)=>e in o?N(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,c=(o,e,t)=>A(o,typeof e!="symbol"?e+"":e,t);class L extends Error{constructor(e){super(e),this.name="AbortError"}}function M(o,e,t){if(!Number.isFinite(e))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0,n=!1;const a=async()=>{i++;const h=s.shift();if(h)try{const d=await o(...h.args);h.resolve(d)}catch(d){h.reject(d)}const u=setTimeout(()=>{i--,s.length>0&&a(),r=r.filter(d=>d!==u)},t);r.includes(u)||r.push(u)},l=(...h)=>n?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((u,d)=>{s.push({resolve:u,reject:d,args:h}),i<e&&a()});return l.abort=()=>{n=!0,r.forEach(clearTimeout),r=[],s.forEach(h=>h.reject(()=>new L("Throttle function aborted"))),s.length=0},l}let b=class{constructor(){c(this,"isCDNUrl",(o="")=>o.includes("/cdn/")),c(this,"getOptionsPage",(o,e=25,t=1)=>({...o,per_page:e,page:t})),c(this,"delay",o=>new Promise(e=>setTimeout(e,o))),c(this,"arrayFrom",(o=0,e)=>Array.from({length:o},e)),c(this,"range",(o=0,e=o)=>{const t=Math.abs(e-o)||0,s=o<e?1:-1;return this.arrayFrom(t,(r,i)=>i*s+o)}),c(this,"asyncMap",async(o,e)=>Promise.all(o.map(e))),c(this,"flatMap",(o=[],e)=>o.map(e).reduce((t,s)=>[...t,...s],[])),c(this,"escapeHTML",function(o){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=new RegExp(t.source);return o&&s.test(o)?o.replace(t,r=>e[r]):o})}stringify(o,e,t){const s=[];for(const r in o){if(!Object.prototype.hasOwnProperty.call(o,r))continue;const i=o[r],n=t?"":encodeURIComponent(r);let a;typeof i=="object"?a=this.stringify(i,e?e+encodeURIComponent(`[${n}]`):n,Array.isArray(i)):a=`${e?e+encodeURIComponent(`[${n}]`):n}=${encodeURIComponent(i)}`,s.push(a)}return s.join("&")}getRegionURL(o){const e="api.storyblok.com",t="api-us.storyblok.com",s="app.storyblokchina.cn",r="api-ap.storyblok.com",i="api-ca.storyblok.com";switch(o){case"us":return t;case"cn":return s;case"ap":return r;case"ca":return i;default:return e}}};const z=function(o,e){const t={};for(const s in o){const r=o[s];e.includes(s)&&r!==null&&(t[s]=r)}return t},H=o=>o==="email",U=()=>({singleTag:"hr"}),q=()=>({tag:"blockquote"}),B=()=>({tag:"ul"}),V=o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),D=()=>({singleTag:"br"}),F=o=>({tag:`h${o.attrs.level}`}),J=o=>({singleTag:[{tag:"img",attrs:z(o.attrs,["src","alt","title"])}]}),W=()=>({tag:"li"}),Y=()=>({tag:"ol"}),G=()=>({tag:"p"}),K=o=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":o.attrs.name,emoji:o.attrs.emoji}}]}),Q=()=>({tag:"b"}),X=()=>({tag:"s"}),Z=()=>({tag:"u"}),ee=()=>({tag:"strong"}),te=()=>({tag:"code"}),se=()=>({tag:"i"}),re=o=>{if(!o.attrs)return{tag:""};const e=new b().escapeHTML,t={...o.attrs},{linktype:s="url"}=o.attrs;if(delete t.linktype,t.href&&(t.href=e(o.attrs.href||"")),H(s)&&(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}]}},oe=o=>({tag:[{tag:"span",attrs:o.attrs}]}),ie=()=>({tag:"sub"}),ne=()=>({tag:"sup"}),ae=o=>({tag:[{tag:"span",attrs:o.attrs}]}),le=o=>{var e;return(e=o.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${o.attrs.color};`}}]}:{tag:""}},ce=o=>{var e;return(e=o.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${o.attrs.color}`}}]}:{tag:""}},E={nodes:{horizontal_rule:U,blockquote:q,bullet_list:B,code_block:V,hard_break:D,heading:F,image:J,list_item:W,ordered_list:Y,paragraph:G,emoji:K},marks:{bold:Q,strike:X,underline:Z,strong:ee,code:te,italic:se,link:re,styled:oe,subscript:ie,superscript:ne,anchor:ae,highlight:le,textStyle:ce}},he=function(o){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=new RegExp(t.source);return o&&s.test(o)?o.replace(t,r=>e[r]):o};let S=!1;class ue{constructor(e){c(this,"marks"),c(this,"nodes"),e||(e=E),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},s=!0){if(!S&&s&&(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/"),S=!0),e&&e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(i=>{r+=this.renderNode(i)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field.
|
|
2
|
+
The "content" field must be an array of nodes as the type ISbRichtext.
|
|
3
|
+
ISbRichtext:
|
|
4
|
+
content?: ISbRichtext[]
|
|
5
|
+
marks?: ISbRichtext[]
|
|
6
|
+
attrs?: any
|
|
7
|
+
text?: string
|
|
8
|
+
type: string
|
|
9
|
+
|
|
10
|
+
Example:
|
|
11
|
+
{
|
|
12
|
+
content: [
|
|
13
|
+
{
|
|
14
|
+
content: [
|
|
15
|
+
{
|
|
16
|
+
text: 'Hello World',
|
|
17
|
+
type: 'text'
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
type: 'paragraph'
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
type: 'doc'
|
|
24
|
+
}`),""}optimizeImages(e,t){let s=0,r=0,i="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(n+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(n+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-F]{6}/gi)||t.filters.fill==="transparent")&&(n+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(n+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(n+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(n+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(n+=`:rotate(${t.filters.rotate})`),n.length>0&&(n=`/filters${n}`))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const a=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";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 h,u;const d=l.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(d&&d.length>0){const p={srcset:(h=t.srcset)==null?void 0:h.map(g=>{if(typeof g=="number")return`//${d}/m/${g}x0${n} ${g}w`;if(typeof g=="object"&&g.length===2){let k=0,T=0;return typeof g[0]=="number"&&(k=g[0]),typeof g[1]=="number"&&(T=g[1]),`//${d}/m/${k}x${T}${n} ${k}w`}return""}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(g=>g).join(", ")};let v="";return p.srcset&&(v+=`srcset="${p.srcset}" `),p.sizes&&(v+=`sizes="${p.sizes}" `),l.replace(/<img/g,`<img ${v.trim()}`)}return l})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(he(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const i=this.getMatchingMark(r);i&&i.tag!==""&&t.push(this.renderClosingTag(i.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs){for(const i in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,i)){const n=s.attrs[i];n!==null&&(r+=` ${i}="${n}"`)}}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const m=ue;class de{constructor(e){c(this,"baseURL"),c(this,"timeout"),c(this,"headers"),c(this,"responseInterceptor"),c(this,"fetch"),c(this,"ejectInterceptor"),c(this,"url"),c(this,"parameters"),c(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(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const l=new b;t=`${this.baseURL}${this.url}?${l.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let a;this.timeout&&(a=setTimeout(()=>i.abort(),this.timeout));try{const l=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(a);const h=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}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,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(i)})}}const pe=de,x="SB-Agent",w={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let y={};const f={};class ge{constructor(e,t){c(this,"client"),c(this,"maxRetries"),c(this,"retriesDelay"),c(this,"throttle"),c(this,"accessToken"),c(this,"cache"),c(this,"helpers"),c(this,"resolveCounter"),c(this,"relations"),c(this,"links"),c(this,"richTextResolver"),c(this,"resolveNestedRelations"),c(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const n=new b().getRegionURL,a=e.https===!1?"http":"https";e.oauthToken?s=`${a}://${n(e.region)}/v1`:s=`${a}://${n(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([n,a])=>{r.set(n,a)}),r.has(x)||(r.set(x,w.defaultAgentName),r.set(w.defaultAgentVersion,w.packageVersion));let i=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new m(e.richTextSchema):this.richTextResolver=new m,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=M(this.throttledRequest.bind(this),i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new b,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new pe({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return 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(",")),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,r,i){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n,void 0,i)}get(e,t,s){t||(t={});const r=`/${e}`,i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t,s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),a=s??n.substring(n.lastIndexOf("/")+1),l=1,h=await this.makeRequest(n,t,i,l,r),u=h.total?Math.ceil(h.total/i):1,d=await this.helpers.asyncMap(this.helpers.range(l,u),p=>this.makeRequest(n,t,i,p+1,r));return this.helpers.flatMap([h,...d],p=>Object.values(p.data[a]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("delete",r,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 r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,s,r){s.includes(`${e.component}.${t}`)&&(typeof e[t]=="string"?e[t]=this.getStoryReference(r,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(i=>this.getStoryReference(r,i)).filter(Boolean)))}iterateTree(e,t,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)r(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,t,s),this._insertLinks(i,n,s)),r(i[n])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],a=50;for(let l=0;l<i;l+=a){const h=Math.min(i,l+a);n.push(e.link_uuids.slice(l,h))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(h=>{r.push(h)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],a=50;for(let l=0;l<i;l+=a){const h=Math.min(i,l+a);n.push(e.rel_uuids.slice(l,h))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:n[l].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{r.push(h)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var r,i;let n=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(n=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((r=e.links)!=null&&r.length||(i=e.link_uuids)!=null&&i.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const a in this.relations[s])this.iterateTree(this.relations[s][a],n,s);e.story?this.iterateTree(e.story,n,s):e.stories.forEach(a=>{this.iterateTree(a,n,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const i=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 a=await n.get(i);if(a)return Promise.resolve(a)}return new Promise(async(a,l)=>{var h;try{const u=await this.throttle("get",e,t,r);if(u.status!==200)return l(u);let d={data:u.data,headers:u.headers};if((h=u.headers)!=null&&h["per-page"]&&(d=Object.assign({},d,{perPage:u.headers["per-page"]?Number.parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?Number.parseInt(u.headers.total):0})),d.data.story||d.data.stories){const p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${p}`)}return t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,d),d.data.cv&&t.token&&f[t.token]!==d.data.cv&&(await this.flushCache(),f[t.token]=d.data.cv),a(d)}catch(u){if(u.response&&u.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(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return f}cacheVersion(){return f[this.accessToken]}setCacheVersion(e){this.accessToken&&(f[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(f[this.accessToken]=0)}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()},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 fe=(o={})=>{const{apiOptions:e}=o;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 ge(e)}},me=o=>{if(typeof o!="object"||typeof o._editable>"u")return{};try{const e=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};let $,R="https://app.storyblok.com/f/storyblok-v2-latest.js";const O=(o,e,t={})=>{var s;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",i=+new URL((s=window.location)==null?void 0:s.href).searchParams.get("_storyblok")===o;if(!(!r||!i)){if(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],n=>{n.action==="input"&&n.story.id===o?e(n.story):(n.action==="change"||n.action==="published")&&n.storyId===o&&window.location.reload()})})}},ye=(o={})=>{var e,t;const{bridge:s,accessToken:r,use:i=[],apiOptions:n={},richText:a={},bridgeUrl:l}=o;n.accessToken=n.accessToken||r;const h={bridge:s,apiOptions:n};let u={};i.forEach(p=>{u={...u,...p(h)}}),l&&(R=l);const d=!(typeof window>"u")&&((t=(e=window.location)==null?void 0:e.search)==null?void 0:t.includes("_storyblok_tk"));return s!==!1&&d&&P(R),$=new m(a.schema),a.resolver&&I($,a.resolver),u},I=(o,e)=>{o.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},C=o=>!o||!(o!=null&&o.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),be=(o,e,t)=>{let s=t||$;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return C(o)?"":(e&&(s=new m(e.schema),e.resolver&&I(s,e.resolver)),s.render(o,{},!1))},ve=()=>P(R);exports.RichTextResolver=m;exports.RichTextSchema=E;exports.apiPlugin=fe;exports.isRichTextEmpty=C;exports.loadStoryblokBridge=ve;exports.registerStoryblokBridge=O;exports.renderRichText=be;exports.storyblokEditable=me;exports.storyblokInit=ye;exports.useStoryblokBridge=O;
|