@storyblok/astro 5.1.0-alpha.4 → 5.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -114
  3. package/{components → dist/components}/FallbackComponent.astro +1 -1
  4. package/dist/components/FallbackComponent.d.ts +6 -0
  5. package/{components → dist/components}/StoryblokComponent.astro +3 -3
  6. package/dist/components/StoryblokComponent.d.ts +6 -0
  7. package/dist/{types/dev-toolbar → dev-toolbar}/toolbarApp.d.ts +1 -1
  8. package/{dev-toolbar → dist/dev-toolbar}/toolbarApp.ts +143 -146
  9. package/dist/{types/index.d.ts → index.d.ts} +12 -17
  10. package/dist/{types/live-preview → live-preview}/handleStoryblokMessage.d.ts +1 -1
  11. package/dist/live-preview/middleware.d.ts +1 -0
  12. package/dist/live-preview/middleware.ts +25 -0
  13. package/dist/storyblok-astro.es.js +1324 -0
  14. package/dist/storyblok-astro.umd.js +69 -0
  15. package/dist/types.d.ts +12 -0
  16. package/dist/utils/generateFinalBridgeObject.d.ts +3 -0
  17. package/dist/utils/parseAstCode.d.ts +7 -0
  18. package/dist/utils/toCamelCase.d.ts +1 -0
  19. package/dist/vite-plugins/vite-plugin-storyblok-bridge.d.ts +12 -0
  20. package/dist/vite-plugins/vite-plugin-storyblok-components.d.ts +2 -0
  21. package/dist/vite-plugins/vite-plugin-storyblok-init.d.ts +3 -0
  22. package/dist/{types/vite-plugins → vite-plugins}/vite-plugin-storyblok-options.d.ts +1 -1
  23. package/package.json +123 -62
  24. package/components/FallbackComponent.ts +0 -2
  25. package/components/StoryblokComponent.ts +0 -2
  26. package/dist/storyblok-astro.js +0 -72
  27. package/dist/storyblok-astro.mjs +0 -1259
  28. package/dist/types/components/FallbackComponent.d.ts +0 -2
  29. package/dist/types/components/StoryblokComponent.d.ts +0 -2
  30. package/dist/types/content-layer/storyblokLoader.d.ts +0 -9
  31. package/dist/types/content-layer/syncContentUpdate.d.ts +0 -4
  32. package/dist/types/cypress/e2e/index.cy.d.ts +0 -0
  33. package/dist/types/cypress/plugins/index.d.ts +0 -2
  34. package/dist/types/cypress/support/commands.d.ts +0 -0
  35. package/dist/types/cypress/support/e2e.d.ts +0 -1
  36. package/dist/types/cypress.config.d.ts +0 -2
  37. package/dist/types/live-preview/middleware.d.ts +0 -1
  38. package/dist/types/node_modules/astro/dist/runtime/client/dev-toolbar/ui-library/icons.d.ts +0 -35
  39. package/dist/types/node_modules/astro/dist/toolbar/index.d.ts +0 -2
  40. package/dist/types/node_modules/camelcase/index.d.ts +0 -102
  41. package/dist/types/types.d.ts +0 -12
  42. package/dist/types/utils/initStoryblokBridge.d.ts +0 -2
  43. package/dist/types/vite-plugins/vite-plugin-storyblok-components.d.ts +0 -2
  44. package/dist/types/vite-plugins/vite-plugin-storyblok-init.d.ts +0 -3
  45. package/live-preview/handleStoryblokMessage.ts +0 -78
  46. package/live-preview/middleware.ts +0 -24
  47. package/utils/initStoryblokBridge.ts +0 -11
@@ -1,1259 +0,0 @@
1
- function B(o, e, t) {
2
- const s = "virtual:storyblok-init", r = "\0" + s;
3
- return {
4
- name: "vite-plugin-storyblok-init",
5
- async resolveId(n) {
6
- if (n === s)
7
- return r;
8
- },
9
- async load(n) {
10
- if (n === r)
11
- return `
12
- import { storyblokInit, apiPlugin } from "@storyblok/js";
13
- const { storyblokApi } = storyblokInit({
14
- accessToken: "${o}",
15
- use: ${e ? "[]" : "[apiPlugin]"},
16
- apiOptions: ${JSON.stringify(t)},
17
- });
18
- export const storyblokApiInstance = storyblokApi;
19
- `;
20
- }
21
- };
22
- }
23
- const H = /[\p{Lu}]/u, z = /[\p{Ll}]/u, R = /^[\p{Lu}](?![\p{Lu}])/gu, N = /([\p{Alpha}\p{N}_]|$)/u, C = /[_.\- ]+/, D = new RegExp("^" + C.source), _ = new RegExp(C.source + N.source, "gu"), A = new RegExp("\\d+" + N.source, "gu"), F = (o, e, t, s) => {
24
- let r = !1, n = !1, i = !1, l = !1;
25
- for (let a = 0; a < o.length; a++) {
26
- const c = o[a];
27
- l = a > 2 ? o[a - 3] === "-" : !0, r && H.test(c) ? (o = o.slice(0, a) + "-" + o.slice(a), r = !1, i = n, n = !0, a++) : n && i && z.test(c) && (!l || s) ? (o = o.slice(0, a - 1) + "-" + o.slice(a - 1), i = n, n = !1, r = !0) : (r = e(c) === c && t(c) !== c, i = n, n = t(c) === c && e(c) !== c);
28
- }
29
- return o;
30
- }, J = (o, e) => (R.lastIndex = 0, o.replaceAll(R, (t) => e(t))), q = (o, e) => (_.lastIndex = 0, A.lastIndex = 0, o.replaceAll(A, (t, s, r) => ["_", "-"].includes(o.charAt(r + t.length)) ? t : e(t)).replaceAll(_, (t, s) => e(s)));
31
- function I(o, e) {
32
- if (!(typeof o == "string" || Array.isArray(o)))
33
- throw new TypeError("Expected the input to be `string | string[]`");
34
- if (e = {
35
- pascalCase: !1,
36
- preserveConsecutiveUppercase: !1,
37
- ...e
38
- }, Array.isArray(o) ? o = o.map((n) => n.trim()).filter((n) => n.length).join("-") : o = o.trim(), o.length === 0)
39
- return "";
40
- const t = e.locale === !1 ? (n) => n.toLowerCase() : (n) => n.toLocaleLowerCase(e.locale), s = e.locale === !1 ? (n) => n.toUpperCase() : (n) => n.toLocaleUpperCase(e.locale);
41
- return o.length === 1 ? C.test(o) ? "" : e.pascalCase ? s(o) : t(o) : (o !== t(o) && (o = F(o, t, s, e.preserveConsecutiveUppercase)), o = o.replace(D, ""), o = e.preserveConsecutiveUppercase ? J(o, t) : t(o), e.pascalCase && (o = s(o.charAt(0)) + o.slice(1)), q(o, s));
42
- }
43
- function V(o, e, t, s) {
44
- const r = "virtual:storyblok-components", n = "\0" + r;
45
- return {
46
- name: "vite-plugin-storyblok-components",
47
- async resolveId(i) {
48
- if (i === r)
49
- return n;
50
- },
51
- async load(i) {
52
- if (i === n) {
53
- const l = [], a = [];
54
- for await (const [h, u] of Object.entries(e)) {
55
- const p = await this.resolve(
56
- "/" + o + "/" + u + ".astro"
57
- );
58
- if (p)
59
- l.push(`import ${I(h)} from "${p.id}"`);
60
- else if (t)
61
- a.push(h);
62
- else
63
- throw new Error(
64
- `Component could not be found for blok "${h}"! Does "${"/" + o + "/" + u}.astro" exist?`
65
- );
66
- }
67
- let c = "";
68
- if (t)
69
- if (c = ",FallbackComponent", s) {
70
- const h = await this.resolve(
71
- "/" + o + "/" + s + ".astro"
72
- );
73
- if (!h)
74
- throw new Error(
75
- `Custom fallback component could not be found. Does "${"/" + o + "/" + s}.astro" exist?`
76
- );
77
- l.push(
78
- `import FallbackComponent from "${h.id}"`
79
- );
80
- } else
81
- l.push(
82
- "import FallbackComponent from '@storyblok/astro/FallbackComponent.astro'"
83
- );
84
- if (Object.values(e).length)
85
- return `${l.join(";")};export default {${Object.keys(e).filter((h) => !a.includes(h)).map((h) => I(h)).join(",")}${c}}`;
86
- if (t)
87
- return `${l[0]}; export default {${c.replace(",", "")}}`;
88
- throw new Error(
89
- `Currently, no Storyblok components are registered in astro.config.mjs.
90
- Please register your components or enable the fallback component.
91
- Detailed information can be found here: https://github.com/storyblok/storyblok-astro`
92
- );
93
- }
94
- }
95
- };
96
- }
97
- function W(o) {
98
- const e = "virtual:storyblok-options", t = "\0" + e;
99
- return {
100
- name: "vite-plugin-storyblok-options",
101
- async resolveId(s) {
102
- if (s === e)
103
- return t;
104
- },
105
- async load(s) {
106
- if (s === t)
107
- return `export default ${JSON.stringify(o)}`;
108
- }
109
- };
110
- }
111
- let x = !1;
112
- const O = [], M = (o) => new Promise((e, t) => {
113
- if (typeof window > "u" || (window.storyblokRegisterEvent = (r) => {
114
- if (window.location === window.parent.location) {
115
- console.warn("You are not in Draft Mode or in the Visual Editor.");
116
- return;
117
- }
118
- x ? r() : O.push(r);
119
- }, document.getElementById("storyblok-javascript-bridge"))) return;
120
- const s = document.createElement("script");
121
- s.async = !0, s.src = o, s.id = "storyblok-javascript-bridge", s.onerror = (r) => t(r), s.onload = (r) => {
122
- O.forEach((n) => n()), x = !0, e(r);
123
- }, document.getElementsByTagName("head")[0].appendChild(s);
124
- });
125
- var K = Object.defineProperty, Z = (o, e, t) => e in o ? K(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t, d = (o, e, t) => Z(o, typeof e != "symbol" ? e + "" : e, t);
126
- function E(o) {
127
- return !(o !== o || o === 1 / 0 || o === -1 / 0);
128
- }
129
- function G(o, e, t) {
130
- if (!E(e))
131
- throw new TypeError("Expected `limit` to be a finite number");
132
- if (!E(t))
133
- throw new TypeError("Expected `interval` to be a finite number");
134
- const s = [];
135
- let r = [], n = 0;
136
- const i = function() {
137
- n++;
138
- const a = setTimeout(function() {
139
- n--, s.length > 0 && i(), r = r.filter(function(h) {
140
- return h !== a;
141
- });
142
- }, t);
143
- r.indexOf(a) < 0 && r.push(a);
144
- const c = s.shift();
145
- c.resolve(o.apply(c.self, c.args));
146
- }, l = function(...a) {
147
- const c = this;
148
- return new Promise(function(h, u) {
149
- s.push({
150
- resolve: h,
151
- reject: u,
152
- args: a,
153
- self: c
154
- }), n < e && i();
155
- });
156
- };
157
- return l.abort = function() {
158
- r.forEach(clearTimeout), r = [], s.forEach(function(a) {
159
- a.reject(function() {
160
- Error.call(this, "Throttled function aborted"), this.name = "AbortError";
161
- });
162
- }), s.length = 0;
163
- }, l;
164
- }
165
- class b {
166
- constructor() {
167
- d(this, "isCDNUrl", (e = "") => e.indexOf("/cdn/") > -1), d(this, "getOptionsPage", (e, t = 25, s = 1) => ({
168
- ...e,
169
- per_page: t,
170
- page: s
171
- })), d(this, "delay", (e) => new Promise((t) => setTimeout(t, e))), d(this, "arrayFrom", (e = 0, t) => [...Array(e)].map(t)), d(this, "range", (e = 0, t = e) => {
172
- const s = Math.abs(t - e) || 0, r = e < t ? 1 : -1;
173
- return this.arrayFrom(s, (n, i) => i * r + e);
174
- }), d(this, "asyncMap", async (e, t) => Promise.all(e.map(t))), d(this, "flatMap", (e = [], t) => e.map(t).reduce((s, r) => [...s, ...r], [])), d(this, "escapeHTML", function(e) {
175
- const t = {
176
- "&": "&amp;",
177
- "<": "&lt;",
178
- ">": "&gt;",
179
- '"': "&quot;",
180
- "'": "&#39;"
181
- }, s = /[&<>"']/g, r = RegExp(s.source);
182
- return e && r.test(e) ? e.replace(s, (n) => t[n]) : e;
183
- });
184
- }
185
- /**
186
- * @method stringify
187
- * @param {Object} params
188
- * @param {String} prefix
189
- * @param {Boolean} isArray
190
- * @return {String} Stringified object
191
- */
192
- stringify(e, t, s) {
193
- const r = [];
194
- for (const n in e) {
195
- if (!Object.prototype.hasOwnProperty.call(e, n))
196
- continue;
197
- const i = e[n], l = s ? "" : encodeURIComponent(n);
198
- let a;
199
- typeof i == "object" ? a = this.stringify(
200
- i,
201
- t ? t + encodeURIComponent("[" + l + "]") : l,
202
- Array.isArray(i)
203
- ) : a = (t ? t + encodeURIComponent("[" + l + "]") : l) + "=" + encodeURIComponent(i), r.push(a);
204
- }
205
- return r.join("&");
206
- }
207
- /**
208
- * @method getRegionURL
209
- * @param {String} regionCode region code, could be eu, us, cn, ap or ca
210
- * @return {String} The base URL of the region
211
- */
212
- getRegionURL(e) {
213
- const t = "api.storyblok.com", s = "api-us.storyblok.com", r = "app.storyblokchina.cn", n = "api-ap.storyblok.com", i = "api-ca.storyblok.com";
214
- switch (e) {
215
- case "us":
216
- return s;
217
- case "cn":
218
- return r;
219
- case "ap":
220
- return n;
221
- case "ca":
222
- return i;
223
- default:
224
- return t;
225
- }
226
- }
227
- }
228
- const Y = function(o, e) {
229
- const t = {};
230
- for (const s in o) {
231
- const r = o[s];
232
- e.indexOf(s) > -1 && r !== null && (t[s] = r);
233
- }
234
- return t;
235
- }, Q = (o) => o === "email", X = () => ({
236
- singleTag: "hr"
237
- }), ee = () => ({
238
- tag: "blockquote"
239
- }), te = () => ({
240
- tag: "ul"
241
- }), se = (o) => ({
242
- tag: [
243
- "pre",
244
- {
245
- tag: "code",
246
- attrs: o.attrs
247
- }
248
- ]
249
- }), re = () => ({
250
- singleTag: "br"
251
- }), oe = (o) => ({
252
- tag: `h${o.attrs.level}`
253
- }), ne = (o) => ({
254
- singleTag: [
255
- {
256
- tag: "img",
257
- attrs: Y(o.attrs, ["src", "alt", "title"])
258
- }
259
- ]
260
- }), ie = () => ({
261
- tag: "li"
262
- }), ae = () => ({
263
- tag: "ol"
264
- }), le = () => ({
265
- tag: "p"
266
- }), ce = (o) => ({
267
- tag: [
268
- {
269
- tag: "span",
270
- attrs: {
271
- "data-type": "emoji",
272
- "data-name": o.attrs.name,
273
- emoji: o.attrs.emoji
274
- }
275
- }
276
- ]
277
- }), he = () => ({
278
- tag: "b"
279
- }), ue = () => ({
280
- tag: "s"
281
- }), de = () => ({
282
- tag: "u"
283
- }), pe = () => ({
284
- tag: "strong"
285
- }), ge = () => ({
286
- tag: "code"
287
- }), fe = () => ({
288
- tag: "i"
289
- }), ye = (o) => {
290
- if (!o.attrs)
291
- return {
292
- tag: ""
293
- };
294
- const e = new b().escapeHTML, t = { ...o.attrs }, { linktype: s = "url" } = o.attrs;
295
- if (delete t.linktype, t.href && (t.href = e(o.attrs.href || "")), Q(s) && (t.href = `mailto:${t.href}`), t.anchor && (t.href = `${t.href}#${t.anchor}`, delete t.anchor), t.custom) {
296
- for (const r in t.custom)
297
- t[r] = t.custom[r];
298
- delete t.custom;
299
- }
300
- return {
301
- tag: [
302
- {
303
- tag: "a",
304
- attrs: t
305
- }
306
- ]
307
- };
308
- }, me = (o) => ({
309
- tag: [
310
- {
311
- tag: "span",
312
- attrs: o.attrs
313
- }
314
- ]
315
- }), be = () => ({
316
- tag: "sub"
317
- }), ke = () => ({
318
- tag: "sup"
319
- }), ve = (o) => ({
320
- tag: [
321
- {
322
- tag: "span",
323
- attrs: o.attrs
324
- }
325
- ]
326
- }), we = (o) => {
327
- var e;
328
- return (e = o.attrs) != null && e.color ? {
329
- tag: [
330
- {
331
- tag: "span",
332
- attrs: {
333
- style: `background-color:${o.attrs.color};`
334
- }
335
- }
336
- ]
337
- } : {
338
- tag: ""
339
- };
340
- }, Se = (o) => {
341
- var e;
342
- return (e = o.attrs) != null && e.color ? {
343
- tag: [
344
- {
345
- tag: "span",
346
- attrs: {
347
- style: `color:${o.attrs.color}`
348
- }
349
- }
350
- ]
351
- } : {
352
- tag: ""
353
- };
354
- }, Te = {
355
- nodes: {
356
- horizontal_rule: X,
357
- blockquote: ee,
358
- bullet_list: te,
359
- code_block: se,
360
- hard_break: re,
361
- heading: oe,
362
- image: ne,
363
- list_item: ie,
364
- ordered_list: ae,
365
- paragraph: le,
366
- emoji: ce
367
- },
368
- marks: {
369
- bold: he,
370
- strike: ue,
371
- underline: de,
372
- strong: pe,
373
- code: ge,
374
- italic: fe,
375
- link: ye,
376
- styled: me,
377
- subscript: be,
378
- superscript: ke,
379
- anchor: ve,
380
- highlight: we,
381
- textStyle: Se
382
- }
383
- }, Ce = function(o) {
384
- const e = {
385
- "&": "&amp;",
386
- "<": "&lt;",
387
- ">": "&gt;",
388
- '"': "&quot;",
389
- "'": "&#39;"
390
- }, t = /[&<>"']/g, s = RegExp(t.source);
391
- return o && s.test(o) ? o.replace(t, (r) => e[r]) : o;
392
- };
393
- let L = !1;
394
- class $e {
395
- constructor(e) {
396
- d(this, "marks"), d(this, "nodes"), e || (e = Te), this.marks = e.marks || [], this.nodes = e.nodes || [];
397
- }
398
- addNode(e, t) {
399
- this.nodes[e] = t;
400
- }
401
- addMark(e, t) {
402
- this.marks[e] = t;
403
- }
404
- render(e, t = { optimizeImages: !1 }, s = !0) {
405
- if (!L && s && (console.warn(
406
- "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/"
407
- ), L = !0), e && e.content && Array.isArray(e.content)) {
408
- let r = "";
409
- return e.content.forEach((n) => {
410
- r += this.renderNode(n);
411
- }), t.optimizeImages ? this.optimizeImages(r, t.optimizeImages) : r;
412
- }
413
- return console.warn(
414
- `The render method must receive an Object with a "content" field.
415
- The "content" field must be an array of nodes as the type ISbRichtext.
416
- ISbRichtext:
417
- content?: ISbRichtext[]
418
- marks?: ISbRichtext[]
419
- attrs?: any
420
- text?: string
421
- type: string
422
-
423
- Example:
424
- {
425
- content: [
426
- {
427
- content: [
428
- {
429
- text: 'Hello World',
430
- type: 'text'
431
- }
432
- ],
433
- type: 'paragraph'
434
- }
435
- ],
436
- type: 'doc'
437
- }`
438
- ), "";
439
- }
440
- optimizeImages(e, t) {
441
- let s = 0, r = 0, n = "", i = "";
442
- 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}" `, r = 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-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))), n.length > 0 && (e = e.replace(/<img/g, `<img ${n.trim()}`));
443
- const l = s > 0 || r > 0 || i.length > 0 ? `${s}x${r}${i}` : "";
444
- return e = e.replace(
445
- /a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,
446
- `a.storyblok.com/f/$1/$2.$3/m/${l}`
447
- ), typeof t != "boolean" && (t.sizes || t.srcset) && (e = e.replace(/<img.*?src=["|'](.*?)["|']/g, (a) => {
448
- var c, h;
449
- const u = a.match(
450
- /a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g
451
- );
452
- if (u && u.length > 0) {
453
- const p = {
454
- srcset: (c = t.srcset) == null ? void 0 : c.map((g) => {
455
- if (typeof g == "number")
456
- return `//${u}/m/${g}x0${i} ${g}w`;
457
- if (typeof g == "object" && g.length === 2) {
458
- let v = 0, $ = 0;
459
- return typeof g[0] == "number" && (v = g[0]), typeof g[1] == "number" && ($ = g[1]), `//${u}/m/${v}x${$}${i} ${v}w`;
460
- }
461
- }).join(", "),
462
- sizes: (h = t.sizes) == null ? void 0 : h.map((g) => g).join(", ")
463
- };
464
- let f = "";
465
- return p.srcset && (f += `srcset="${p.srcset}" `), p.sizes && (f += `sizes="${p.sizes}" `), a.replace(/<img/g, `<img ${f.trim()}`);
466
- }
467
- return a;
468
- })), e;
469
- }
470
- renderNode(e) {
471
- const t = [];
472
- e.marks && e.marks.forEach((r) => {
473
- const n = this.getMatchingMark(r);
474
- n && n.tag !== "" && t.push(this.renderOpeningTag(n.tag));
475
- });
476
- const s = this.getMatchingNode(e);
477
- return s && s.tag && t.push(this.renderOpeningTag(s.tag)), e.content ? e.content.forEach((r) => {
478
- t.push(this.renderNode(r));
479
- }) : 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) => {
480
- const n = this.getMatchingMark(r);
481
- n && n.tag !== "" && t.push(this.renderClosingTag(n.tag));
482
- }), t.join("");
483
- }
484
- renderTag(e, t) {
485
- return e.constructor === String ? `<${e}${t}>` : e.map((s) => {
486
- if (s.constructor === String)
487
- return `<${s}${t}>`;
488
- {
489
- let r = `<${s.tag}`;
490
- if (s.attrs) {
491
- for (const n in s.attrs)
492
- if (Object.prototype.hasOwnProperty.call(s.attrs, n)) {
493
- const i = s.attrs[n];
494
- i !== null && (r += ` ${n}="${i}"`);
495
- }
496
- }
497
- return `${r}${t}>`;
498
- }
499
- }).join("");
500
- }
501
- renderOpeningTag(e) {
502
- return this.renderTag(e, "");
503
- }
504
- renderClosingTag(e) {
505
- return e.constructor === String ? `</${e}>` : e.slice(0).reverse().map((t) => t.constructor === String ? `</${t}>` : `</${t.tag}>`).join("");
506
- }
507
- getMatchingNode(e) {
508
- const t = this.nodes[e.type];
509
- if (typeof t == "function")
510
- return t(e);
511
- }
512
- getMatchingMark(e) {
513
- const t = this.marks[e.type];
514
- if (typeof t == "function")
515
- return t(e);
516
- }
517
- renderEmoji(e) {
518
- if (e.attrs.emoji)
519
- return e.attrs.emoji;
520
- const t = [
521
- {
522
- tag: "img",
523
- attrs: {
524
- src: e.attrs.fallbackImage,
525
- draggable: "false",
526
- loading: "lazy",
527
- align: "absmiddle"
528
- }
529
- }
530
- ];
531
- return this.renderTag(t, " /");
532
- }
533
- }
534
- const k = $e;
535
- class Re {
536
- constructor(e) {
537
- 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 = {};
538
- }
539
- /**
540
- *
541
- * @param url string
542
- * @param params ISbStoriesParams
543
- * @returns Promise<ISbResponse | Error>
544
- */
545
- get(e, t) {
546
- return this.url = e, this.parameters = t, this._methodHandler("get");
547
- }
548
- post(e, t) {
549
- return this.url = e, this.parameters = t, this._methodHandler("post");
550
- }
551
- put(e, t) {
552
- return this.url = e, this.parameters = t, this._methodHandler("put");
553
- }
554
- delete(e, t) {
555
- return this.url = e, this.parameters = t, this._methodHandler("delete");
556
- }
557
- async _responseHandler(e) {
558
- const t = [], s = {
559
- data: {},
560
- headers: {},
561
- status: 0,
562
- statusText: ""
563
- };
564
- e.status !== 204 && await e.json().then((r) => {
565
- s.data = r;
566
- });
567
- for (const r of e.headers.entries())
568
- t[r[0]] = r[1];
569
- return s.headers = { ...t }, s.status = e.status, s.statusText = e.statusText, s;
570
- }
571
- async _methodHandler(e) {
572
- let t = `${this.baseURL}${this.url}`, s = null;
573
- if (e === "get") {
574
- const a = new b();
575
- t = `${this.baseURL}${this.url}?${a.stringify(
576
- this.parameters
577
- )}`;
578
- } else
579
- s = JSON.stringify(this.parameters);
580
- const r = new URL(t), n = new AbortController(), { signal: i } = n;
581
- let l;
582
- this.timeout && (l = setTimeout(() => n.abort(), this.timeout));
583
- try {
584
- const a = await this.fetch(`${r}`, {
585
- method: e,
586
- headers: this.headers,
587
- body: s,
588
- signal: i,
589
- ...this.fetchOptions
590
- });
591
- this.timeout && clearTimeout(l);
592
- const c = await this._responseHandler(
593
- a
594
- );
595
- return this.responseInterceptor && !this.ejectInterceptor ? this._statusHandler(this.responseInterceptor(c)) : this._statusHandler(c);
596
- } catch (a) {
597
- return {
598
- message: a
599
- };
600
- }
601
- }
602
- setFetchOptions(e = {}) {
603
- Object.keys(e).length > 0 && "method" in e && delete e.method, this.fetchOptions = { ...e };
604
- }
605
- eject() {
606
- this.ejectInterceptor = !0;
607
- }
608
- _statusHandler(e) {
609
- const t = /20[0-6]/g;
610
- return new Promise((s, r) => {
611
- if (t.test(`${e.status}`))
612
- return s(e);
613
- const n = {
614
- message: e.statusText,
615
- status: e.status,
616
- response: Array.isArray(e.data) ? e.data[0] : e.data.error || e.data.slug
617
- };
618
- r(n);
619
- });
620
- }
621
- }
622
- const _e = Re, j = "SB-Agent", w = {
623
- defaultAgentName: "SB-JS-CLIENT",
624
- defaultAgentVersion: "SB-Agent-Version",
625
- packageVersion: "6.0.0"
626
- };
627
- let m = {};
628
- const y = {};
629
- class Ae {
630
- /**
631
- *
632
- * @param config ISbConfig interface
633
- * @param endpoint string, optional
634
- */
635
- constructor(e, t) {
636
- 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");
637
- let s = e.endpoint || t;
638
- if (!s) {
639
- const i = new b().getRegionURL, l = e.https === !1 ? "http" : "https";
640
- e.oauthToken ? s = `${l}://${i(e.region)}/v1` : s = `${l}://${i(e.region)}/v2`;
641
- }
642
- const r = new Headers();
643
- 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]) => {
644
- r.set(i, l);
645
- }), r.has(j) || (r.set(j, w.defaultAgentName), r.set(
646
- w.defaultAgentVersion,
647
- w.packageVersion
648
- ));
649
- let n = 5;
650
- e.oauthToken && (r.set("Authorization", e.oauthToken), n = 3), e.rateLimit && (n = e.rateLimit), e.richTextSchema ? this.richTextResolver = new k(e.richTextSchema) : this.richTextResolver = new k(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries || 10, this.retriesDelay = 300, this.throttle = G(this.throttledRequest, n, 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 _e({
651
- baseURL: s,
652
- timeout: e.timeout || 0,
653
- headers: r,
654
- responseInterceptor: e.responseInterceptor,
655
- fetch: e.fetch
656
- });
657
- }
658
- setComponentResolver(e) {
659
- this.richTextResolver.addNode("blok", (t) => {
660
- let s = "";
661
- return t.attrs.body && t.attrs.body.forEach((r) => {
662
- s += e(r.component, r);
663
- }), {
664
- html: s
665
- };
666
- });
667
- }
668
- parseParams(e) {
669
- return e.token || (e.token = this.getToken()), e.cv || (e.cv = y[e.token]), Array.isArray(e.resolve_relations) && (e.resolve_relations = e.resolve_relations.join(",")), typeof e.resolve_relations < "u" && (e.resolve_level = 2), e;
670
- }
671
- factoryParamOptions(e, t) {
672
- return this.helpers.isCDNUrl(e) ? this.parseParams(t) : t;
673
- }
674
- makeRequest(e, t, s, r, n) {
675
- const i = this.factoryParamOptions(
676
- e,
677
- this.helpers.getOptionsPage(t, s, r)
678
- );
679
- return this.cacheResponse(e, i, void 0, n);
680
- }
681
- get(e, t, s) {
682
- t || (t = {});
683
- const r = `/${e}`, n = this.factoryParamOptions(r, t);
684
- return this.cacheResponse(r, n, void 0, s);
685
- }
686
- async getAll(e, t, s, r) {
687
- const n = (t == null ? void 0 : t.per_page) || 25, i = `/${e}`, l = i.split("/"), a = s || l[l.length - 1], c = 1, h = await this.makeRequest(
688
- i,
689
- t,
690
- n,
691
- c,
692
- r
693
- ), u = h.total ? Math.ceil(h.total / n) : 1, p = await this.helpers.asyncMap(
694
- this.helpers.range(c, u),
695
- (f) => this.makeRequest(i, t, n, f + 1, r)
696
- );
697
- return this.helpers.flatMap(
698
- [h, ...p],
699
- (f) => Object.values(f.data[a])
700
- );
701
- }
702
- post(e, t, s) {
703
- const r = `/${e}`;
704
- return Promise.resolve(this.throttle("post", r, t, s));
705
- }
706
- put(e, t, s) {
707
- const r = `/${e}`;
708
- return Promise.resolve(this.throttle("put", r, t, s));
709
- }
710
- delete(e, t, s) {
711
- const r = `/${e}`;
712
- return Promise.resolve(this.throttle("delete", r, t, s));
713
- }
714
- getStories(e, t) {
715
- return this._addResolveLevel(e), this.get("cdn/stories", e, t);
716
- }
717
- getStory(e, t, s) {
718
- return this._addResolveLevel(t), this.get(`cdn/stories/${e}`, t, s);
719
- }
720
- getToken() {
721
- return this.accessToken;
722
- }
723
- ejectInterceptor() {
724
- this.client.eject();
725
- }
726
- _addResolveLevel(e) {
727
- typeof e.resolve_relations < "u" && (e.resolve_level = 2);
728
- }
729
- _cleanCopy(e) {
730
- return JSON.parse(JSON.stringify(e));
731
- }
732
- _insertLinks(e, t, s) {
733
- const r = e[t];
734
- 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]));
735
- }
736
- /**
737
- *
738
- * @param resolveId A counter number as a string
739
- * @param uuid The uuid of the story
740
- * @returns string | object
741
- */
742
- getStoryReference(e, t) {
743
- return this.relations[e][t] ? (this.stringifiedStoriesCache[t] || (this.stringifiedStoriesCache[t] = JSON.stringify(
744
- this.relations[e][t]
745
- )), JSON.parse(this.stringifiedStoriesCache[t])) : t;
746
- }
747
- _insertRelations(e, t, s, r) {
748
- 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((n) => this.getStoryReference(r, n)).filter(Boolean)));
749
- }
750
- iterateTree(e, t, s) {
751
- const r = (n) => {
752
- if (n != null) {
753
- if (n.constructor === Array)
754
- for (let i = 0; i < n.length; i++)
755
- r(n[i]);
756
- else if (n.constructor === Object) {
757
- if (n._stopResolving)
758
- return;
759
- for (const i in n)
760
- (n.component && n._uid || n.type === "link") && (this._insertRelations(
761
- n,
762
- i,
763
- t,
764
- s
765
- ), this._insertLinks(
766
- n,
767
- i,
768
- s
769
- )), r(n[i]);
770
- }
771
- }
772
- };
773
- r(e.content);
774
- }
775
- async resolveLinks(e, t, s) {
776
- let r = [];
777
- if (e.link_uuids) {
778
- const n = e.link_uuids.length, i = [], l = 50;
779
- for (let a = 0; a < n; a += l) {
780
- const c = Math.min(n, a + l);
781
- i.push(e.link_uuids.slice(a, c));
782
- }
783
- for (let a = 0; a < i.length; a++)
784
- (await this.getStories({
785
- per_page: l,
786
- language: t.language,
787
- version: t.version,
788
- by_uuids: i[a].join(",")
789
- })).data.stories.forEach(
790
- (c) => {
791
- r.push(c);
792
- }
793
- );
794
- } else
795
- r = e.links;
796
- r.forEach((n) => {
797
- this.links[s][n.uuid] = {
798
- ...n,
799
- _stopResolving: !0
800
- };
801
- });
802
- }
803
- async resolveRelations(e, t, s) {
804
- let r = [];
805
- if (e.rel_uuids) {
806
- const n = e.rel_uuids.length, i = [], l = 50;
807
- for (let a = 0; a < n; a += l) {
808
- const c = Math.min(n, a + l);
809
- i.push(e.rel_uuids.slice(a, c));
810
- }
811
- for (let a = 0; a < i.length; a++)
812
- (await this.getStories({
813
- per_page: l,
814
- language: t.language,
815
- version: t.version,
816
- by_uuids: i[a].join(","),
817
- excluding_fields: t.excluding_fields
818
- })).data.stories.forEach((c) => {
819
- r.push(c);
820
- });
821
- } else
822
- r = e.rels;
823
- r && r.length > 0 && r.forEach((n) => {
824
- this.relations[s][n.uuid] = {
825
- ...n,
826
- _stopResolving: !0
827
- };
828
- });
829
- }
830
- /**
831
- *
832
- * @param responseData
833
- * @param params
834
- * @param resolveId
835
- * @description Resolves the relations and links of the stories
836
- * @returns Promise<void>
837
- *
838
- */
839
- async resolveStories(e, t, s) {
840
- var r, n;
841
- let i = [];
842
- 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 || (n = e.link_uuids) != null && n.length) && await this.resolveLinks(e, t, s), this.resolveNestedRelations)
843
- for (const l in this.relations[s])
844
- this.iterateTree(
845
- this.relations[s][l],
846
- i,
847
- s
848
- );
849
- e.story ? this.iterateTree(e.story, i, s) : e.stories.forEach((l) => {
850
- this.iterateTree(l, i, s);
851
- }), this.stringifiedStoriesCache = {}, delete this.links[s], delete this.relations[s];
852
- }
853
- async cacheResponse(e, t, s, r) {
854
- const n = this.helpers.stringify({ url: e, params: t }), i = this.cacheProvider();
855
- if (this.cache.clear === "auto" && t.version === "draft" && await this.flushCache(), t.version === "published" && e != "/cdn/spaces/me") {
856
- const l = await i.get(n);
857
- if (l)
858
- return Promise.resolve(l);
859
- }
860
- return new Promise(async (l, a) => {
861
- var c;
862
- try {
863
- const h = await this.throttle("get", e, t, r);
864
- if (h.status !== 200)
865
- return a(h);
866
- let u = { data: h.data, headers: h.headers };
867
- if ((c = h.headers) != null && c["per-page"] && (u = Object.assign({}, u, {
868
- perPage: h.headers["per-page"] ? parseInt(h.headers["per-page"]) : 0,
869
- total: h.headers["per-page"] ? parseInt(h.headers.total) : 0
870
- })), u.data.story || u.data.stories) {
871
- const p = this.resolveCounter = ++this.resolveCounter % 1e3;
872
- await this.resolveStories(u.data, t, `${p}`);
873
- }
874
- return t.version === "published" && e != "/cdn/spaces/me" && await i.set(n, u), u.data.cv && t.token && (t.version === "draft" && y[t.token] != u.data.cv && await this.flushCache(), y[t.token] = t.cv ? t.cv : u.data.cv), l(u);
875
- } catch (h) {
876
- if (h.response && h.status === 429 && (s = typeof s > "u" ? 0 : s + 1, s < this.maxRetries))
877
- return console.log(
878
- `Hit rate limit. Retrying in ${this.retriesDelay / 1e3} seconds.`
879
- ), await this.helpers.delay(this.retriesDelay), this.cacheResponse(e, t, s).then(l).catch(a);
880
- a(h);
881
- }
882
- });
883
- }
884
- throttledRequest(e, t, s, r) {
885
- return this.client.setFetchOptions(r), this.client[e](t, s);
886
- }
887
- cacheVersions() {
888
- return y;
889
- }
890
- cacheVersion() {
891
- return y[this.accessToken];
892
- }
893
- setCacheVersion(e) {
894
- this.accessToken && (y[this.accessToken] = e);
895
- }
896
- clearCacheVersion() {
897
- this.accessToken && (y[this.accessToken] = 0);
898
- }
899
- cacheProvider() {
900
- switch (this.cache.type) {
901
- case "memory":
902
- return {
903
- get(e) {
904
- return Promise.resolve(m[e]);
905
- },
906
- getAll() {
907
- return Promise.resolve(m);
908
- },
909
- set(e, t) {
910
- return m[e] = t, Promise.resolve(void 0);
911
- },
912
- flush() {
913
- return m = {}, Promise.resolve(void 0);
914
- }
915
- };
916
- case "custom":
917
- if (this.cache.custom) return this.cache.custom;
918
- default:
919
- return {
920
- get() {
921
- return Promise.resolve();
922
- },
923
- getAll() {
924
- return Promise.resolve(void 0);
925
- },
926
- set() {
927
- return Promise.resolve(void 0);
928
- },
929
- flush() {
930
- return Promise.resolve(void 0);
931
- }
932
- };
933
- }
934
- }
935
- async flushCache() {
936
- return await this.cacheProvider().flush(), this.clearCacheVersion(), this;
937
- }
938
- }
939
- const Ie = (o = {}) => {
940
- const { apiOptions: e } = o;
941
- if (!e.accessToken) {
942
- console.error(
943
- "You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication"
944
- );
945
- return;
946
- }
947
- return { storyblokApi: new Ae(e) };
948
- }, Me = (o) => {
949
- if (typeof o != "object" || typeof o._editable > "u")
950
- return {};
951
- try {
952
- const e = JSON.parse(
953
- o._editable.replace(/^<!--#storyblok#/, "").replace(/-->$/, "")
954
- );
955
- return e ? {
956
- "data-blok-c": JSON.stringify(e),
957
- "data-blok-uid": e.id + "-" + e.uid
958
- } : {};
959
- } catch {
960
- return {};
961
- }
962
- };
963
- let S, T = "https://app.storyblok.com/f/storyblok-v2-latest.js";
964
- const xe = (o = {}) => {
965
- var e, t;
966
- const {
967
- bridge: s,
968
- accessToken: r,
969
- use: n = [],
970
- apiOptions: i = {},
971
- richText: l = {},
972
- bridgeUrl: a
973
- } = o;
974
- i.accessToken = i.accessToken || r;
975
- const c = { bridge: s, apiOptions: i };
976
- let h = {};
977
- n.forEach((p) => {
978
- h = { ...h, ...p(c) };
979
- }), a && (T = a);
980
- const u = !(typeof window > "u") && ((t = (e = window.location) == null ? void 0 : e.search) == null ? void 0 : t.includes("_storyblok_tk"));
981
- return s !== !1 && u && M(T), S = new k(l.schema), l.resolver && U(S, l.resolver), h;
982
- }, U = (o, e) => {
983
- o.addNode("blok", (t) => {
984
- let s = "";
985
- return t.attrs.body.forEach((r) => {
986
- s += e(r.component, r);
987
- }), {
988
- html: s
989
- };
990
- });
991
- }, Oe = (o) => !o || !(o != null && o.content.some((e) => e.content || e.type === "blok" || e.type === "horizontal_rule")), Ee = (o, e, t) => {
992
- let s = t || S;
993
- if (!s) {
994
- console.error(
995
- "Please initialize the Storyblok SDK before calling the renderRichText function"
996
- );
997
- return;
998
- }
999
- return Oe(o) ? "" : (e && (s = new k(e.schema), e.resolver && U(s, e.resolver)), s.render(o, {}, !1));
1000
- }, Ue = () => M(T);
1001
- function Le(o) {
1002
- return typeof o == "object" ? `const storyblokInstance = new StoryblokBridge(${JSON.stringify(o)});` : "const storyblokInstance = new StoryblokBridge();";
1003
- }
1004
- const je = `<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">
1005
- <g id="storyblok-logo-kit" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
1006
- <g id="storyblok-partner-logo" transform="translate(-59.000000, -169.000000)" fill-rule="nonzero">
1007
- <g id="storyblok-symbol" transform="translate(59.000000, 169.000000)">
1008
- <path d="M2.32662261,0 C1.03405449,0 0,1.0331384 0,2.27290448 L0,42.8752437 C0,44.1150097 1.03405449,44.8898635 2.27491989,44.8898635 L8.27243596,44.8898635 L8.27243596,53 L15.7176283,44.9415205 L42.9132615,44.9415205 C44.1541269,44.9415205 44.9296678,44.1666667 44.9296678,42.8752437 L44.9296678,2.3245614 C44.9296678,1.08479532 44.2058296,0 42.9132615,0 L2.32662261,0 Z" id="Shape-path-Copy" fill="#0AB3AF"></path>
1009
- <path d="M29.1016723,8.11483254 C30.1351059,8.11483254 31.0135245,8.32132604 31.8402713,8.78593643 C32.6153465,9.19892344 33.33875,9.76678059 33.9071385,10.4378845 C35.0647615,11.8482391 35.6869248,13.6215753 35.6639755,15.445352 C35.6639755,16.7875598 35.3022738,18.0781442 34.630542,19.3171053 C33.9341248,20.5632996 32.8438147,21.5436614 31.5302412,22.1047676 C33.183735,22.569378 34.4755269,23.395352 35.4572888,24.5826897 C36.387379,25.8216507 36.8524241,27.4219754 36.8524241,29.4352871 C36.8524241,30.7258715 36.6168825,31.8756998 36.1290206,32.7391832 C35.6123039,33.668404 34.8372287,34.4427546 33.9071385,35.0106118 C32.9253766,35.6300923 31.8402713,36.1979494 30.600151,36.4560663 C29.3600307,36.7658066 28.0165671,37.0239234 26.6214318,37.0239234 L8.32965751,37.0239234 L8.32965751,8.11483254 L29.1016723,8.11483254 Z M26.1340815,24.271851 L15.77813,24.271851 L15.77813,29.1552028 L25.8851404,29.1552028 C26.4825991,29.1552028 27.0302696,28.9110352 27.4783637,28.5203671 C27.8766695,28.1296989 28.1256107,27.5436967 28.1256107,26.811194 C28.140051,26.1827412 27.948041,25.5663945 27.5779401,25.0531873 C27.1796343,24.5648522 26.7315403,24.271851 26.1340815,24.271851 Z M25.2876816,14.5051475 L15.77813,14.5051475 L15.77813,18.9001641 L25.0885287,18.9001641 C25.586411,18.9001641 26.0842933,18.6559965 26.4825991,18.3629954 C26.9306932,18.0699943 27.1298461,17.4351586 27.1298461,16.6049888 C27.1298461,15.872486 26.9306932,15.3353173 26.5821756,14.9934827 C26.233658,14.7004816 25.7855639,14.5051475 25.2876816,14.5051475 Z" id="Combined-Shape-Copy-3" fill="#FFFFFF"></path>
1010
- </g>
1011
- </g>
1012
- </g>
1013
- </svg>`;
1014
- let P;
1015
- async function Be(o) {
1016
- const { action: e, story: t } = o || {};
1017
- if (e === "input" && t) {
1018
- const s = async () => {
1019
- const n = await Ne(t), i = document.body;
1020
- if (n.outerHTML === i.outerHTML) return;
1021
- const l = document.querySelector('[data-blok-focused="true"]');
1022
- Pe(i, n, l), document.dispatchEvent(new Event("storyblok-live-preview-updated"));
1023
- };
1024
- clearTimeout(P), P = setTimeout(s, 500);
1025
- }
1026
- ["published", "change"].includes(o == null ? void 0 : o.action) && location.reload();
1027
- }
1028
- function Pe(o, e, t) {
1029
- if (t) {
1030
- const s = t.getAttribute("data-blok-uid"), r = e.querySelector(
1031
- `[data-blok-uid="${s}"]`
1032
- );
1033
- r && (r.setAttribute("data-blok-focused", "true"), t.replaceWith(r));
1034
- } else
1035
- o.replaceWith(e);
1036
- }
1037
- async function Ne(o) {
1038
- const t = await (await fetch(location.href, {
1039
- method: "POST",
1040
- body: JSON.stringify({
1041
- ...o,
1042
- is_storyblok_preview: !0
1043
- }),
1044
- headers: {
1045
- "Content-Type": "application/json"
1046
- }
1047
- })).text();
1048
- return new DOMParser().parseFromString(t, "text/html").body;
1049
- }
1050
- async function He(o) {
1051
- const { story: e } = o || {};
1052
- await fetch(location.origin + "/_refresh", {
1053
- method: "POST",
1054
- body: JSON.stringify(e),
1055
- headers: {
1056
- "Content-Type": "application/json"
1057
- }
1058
- });
1059
- }
1060
- function ze(o) {
1061
- const { storyblokApi: e } = xe({
1062
- accessToken: o.accessToken,
1063
- apiOptions: o.apiOptions,
1064
- use: [Ie]
1065
- });
1066
- return {
1067
- name: "story-loader",
1068
- load: async ({ store: t, meta: s, logger: r, refreshContextData: n }) => {
1069
- if (!e)
1070
- throw new Error("storyblokApi is not loaded");
1071
- if (n != null && n.story) {
1072
- r.info("Syncing... story updated in Storyblok");
1073
- const h = n.story;
1074
- t.set({
1075
- data: h,
1076
- id: h.uuid
1077
- });
1078
- return;
1079
- }
1080
- r.info("Loading stories");
1081
- const i = s.get("lastPublishedAt"), l = i && o.version === "published" ? { published_at_gt: i } : {}, a = await (e == null ? void 0 : e.getAll("cdn/stories", {
1082
- version: o.version,
1083
- ...l
1084
- }));
1085
- console.log("total = ", a.length), r.info("Clearing store"), o.version === "draft" && t.clear();
1086
- let c = i ? new Date(i) : null;
1087
- for (const h of a) {
1088
- const u = h.published_at ? new Date(h.published_at) : null;
1089
- u && (!c || u > c) && (c = u), t.set({
1090
- data: h,
1091
- id: h.uuid
1092
- }), c && s.set("lastPublishedAt", c.toISOString());
1093
- }
1094
- }
1095
- };
1096
- }
1097
- function De() {
1098
- return globalThis.storyblokApiInstance || console.error("storyblokApiInstance has not been initialized correctly"), globalThis.storyblokApiInstance;
1099
- }
1100
- async function Fe(o) {
1101
- let e = null;
1102
- return o && o.locals._storyblok_preview_data && (e = o.locals._storyblok_preview_data), e;
1103
- }
1104
- function Je(o, e) {
1105
- const t = globalThis.storyblokApiInstance.richTextResolver;
1106
- if (!t) {
1107
- console.error(
1108
- "Please initialize the Storyblok SDK before calling the renderRichText function"
1109
- );
1110
- return;
1111
- }
1112
- return Ee(o, e, t);
1113
- }
1114
- function qe({
1115
- useCustomApi: o = !1,
1116
- bridge: e = !0,
1117
- componentsDir: t = "src",
1118
- enableFallbackComponent: s = !1,
1119
- livePreview: r = !1,
1120
- contentLayer: n = !1,
1121
- ...i
1122
- }) {
1123
- const l = {
1124
- useCustomApi: o,
1125
- bridge: e,
1126
- componentsDir: t,
1127
- enableFallbackComponent: s,
1128
- livePreview: r,
1129
- contentLayer: n,
1130
- ...i
1131
- }, a = Le(e);
1132
- return {
1133
- name: "@storyblok/astro",
1134
- hooks: {
1135
- "astro:config:setup": ({
1136
- injectScript: c,
1137
- updateConfig: h,
1138
- addDevToolbarApp: u,
1139
- addMiddleware: p,
1140
- config: f
1141
- }) => {
1142
- if (h({
1143
- vite: {
1144
- plugins: [
1145
- B(
1146
- l.accessToken,
1147
- l.useCustomApi,
1148
- l.apiOptions
1149
- ),
1150
- V(
1151
- l.componentsDir,
1152
- l.components,
1153
- l.enableFallbackComponent,
1154
- l.customFallbackComponent
1155
- ),
1156
- W(l)
1157
- ]
1158
- }
1159
- }), l.livePreview && (f == null ? void 0 : f.output) !== "server")
1160
- throw new Error(
1161
- "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."
1162
- );
1163
- c(
1164
- "page-ssr",
1165
- `
1166
- import { storyblokApiInstance } from "virtual:storyblok-init";
1167
- globalThis.storyblokApiInstance = storyblokApiInstance;
1168
- `
1169
- ), e && !r && c(
1170
- "page",
1171
- `
1172
- import { loadStoryblokBridge } from "@storyblok/astro";
1173
- loadStoryblokBridge().then(() => {
1174
- const { StoryblokBridge, location } = window;
1175
- ${a}
1176
- storyblokInstance.on(["published", "change"], (event) => {
1177
- if (!event.slugChanged) {
1178
- location.reload(true);
1179
- }
1180
- });
1181
- });
1182
- `
1183
- ), r && (c(
1184
- "page",
1185
- `
1186
- import { loadStoryblokBridge, handleStoryblokMessage } from "@storyblok/astro";
1187
- console.info("The Storyblok Astro live preview feature is currently in an experimental phase, and its API is subject to change in the future.")
1188
- loadStoryblokBridge().then(() => {
1189
- const { StoryblokBridge, location } = window;
1190
- ${a}
1191
- storyblokInstance.on(["published", "change", "input"], handleStoryblokMessage);
1192
- });
1193
- `
1194
- ), p({
1195
- entrypoint: "@storyblok/astro/middleware.ts",
1196
- order: "pre"
1197
- })), n && c(
1198
- "page",
1199
- `
1200
- import { loadStoryblokBridge, syncContentUpdate } from "@storyblok/astro";
1201
- loadStoryblokBridge().then(() => {
1202
- const { StoryblokBridge } = window;
1203
- const storyblokInstance = new StoryblokBridge()
1204
- storyblokInstance.on(["published", "change", "input"], syncContentUpdate);
1205
- });
1206
- `
1207
- ), u({
1208
- id: "storyblok",
1209
- name: "Storyblok",
1210
- icon: je,
1211
- entrypoint: "@storyblok/astro/toolbarApp.ts"
1212
- });
1213
- },
1214
- ...n ? {
1215
- "astro:server:setup": async ({ server: c, refreshContent: h }) => {
1216
- c.middlewares.use("/_refresh", async (u, p) => {
1217
- if (u.method !== "POST") {
1218
- p.writeHead(405, { "Content-Type": "application/json" }), p.end(JSON.stringify({ error: "Method Not Allowed" }));
1219
- return;
1220
- }
1221
- let f = [];
1222
- u.on("data", (g) => f.push(g)), u.on("end", async () => {
1223
- try {
1224
- const g = JSON.parse(Buffer.concat(f).toString());
1225
- await (h == null ? void 0 : h({
1226
- context: { story: g },
1227
- loaders: ["story-loader"]
1228
- })), p.writeHead(200, { "Content-Type": "application/json" }), p.end(
1229
- JSON.stringify({
1230
- message: "Content refreshed successfully"
1231
- })
1232
- );
1233
- } catch (g) {
1234
- p.writeHead(500, { "Content-Type": "application/json" }), p.end(
1235
- JSON.stringify({
1236
- error: `Failed to refresh content: ${g.message}`
1237
- })
1238
- );
1239
- }
1240
- });
1241
- });
1242
- }
1243
- } : {}
1244
- }
1245
- };
1246
- }
1247
- export {
1248
- k as RichTextResolver,
1249
- Te as RichTextSchema,
1250
- qe as default,
1251
- Fe as getLiveStory,
1252
- Be as handleStoryblokMessage,
1253
- Ue as loadStoryblokBridge,
1254
- Je as renderRichText,
1255
- Me as storyblokEditable,
1256
- ze as storyblokLoader,
1257
- He as syncContentUpdate,
1258
- De as useStoryblokApi
1259
- };