@storyblok/react 2.2.1 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,864 +0,0 @@
1
- let I = false;
2
- const O = [], A = (n) => new Promise((e, t) => {
3
- if (typeof window > "u" || (window.storyblokRegisterEvent = (r) => {
4
- if (window.location === window.parent.location) {
5
- console.warn("You are not in Draft Mode or in the Visual Editor.");
6
- return;
7
- }
8
- I ? r() : O.push(r);
9
- }, document.getElementById("storyblok-javascript-bridge")))
10
- return;
11
- const s = document.createElement("script");
12
- s.async = true, s.src = n, s.id = "storyblok-javascript-bridge", s.onerror = (r) => t(r), s.onload = (r) => {
13
- O.forEach((o) => o()), I = true, e(r);
14
- }, document.getElementsByTagName("head")[0].appendChild(s);
15
- });
16
- var j = Object.defineProperty, U = (n, e, t) => e in n ? j(n, e, { enumerable: true, configurable: true, writable: true, value: t }) : n[e] = t, h = (n, e, t) => (U(n, typeof e != "symbol" ? e + "" : e, t), t);
17
- function v(n) {
18
- return !(n !== n || n === 1 / 0 || n === -1 / 0);
19
- }
20
- function H(n, e, t) {
21
- if (!v(e))
22
- throw new TypeError("Expected `limit` to be a finite number");
23
- if (!v(t))
24
- throw new TypeError("Expected `interval` to be a finite number");
25
- const s = [];
26
- let r = [], o = 0;
27
- const i = function() {
28
- o++;
29
- const a = setTimeout(function() {
30
- o--, s.length > 0 && i(), r = r.filter(function(u) {
31
- return u !== a;
32
- });
33
- }, t);
34
- r.indexOf(a) < 0 && r.push(a);
35
- const l = s.shift();
36
- l.resolve(n.apply(l.self, l.args));
37
- }, c = function(...a) {
38
- const l = this;
39
- return new Promise(function(u, d) {
40
- s.push({
41
- resolve: u,
42
- reject: d,
43
- args: a,
44
- self: l
45
- }), o < e && i();
46
- });
47
- };
48
- return c.abort = function() {
49
- r.forEach(clearTimeout), r = [], s.forEach(function(a) {
50
- a.reject(function() {
51
- Error.call(this, "Throttled function aborted"), this.name = "AbortError";
52
- });
53
- }), s.length = 0;
54
- }, c;
55
- }
56
- const P = function(n, e) {
57
- const t = {};
58
- for (const s in n) {
59
- const r = n[s];
60
- e.indexOf(s) > -1 && r !== null && (t[s] = r);
61
- }
62
- return t;
63
- }, x = (n) => n === "email", C = () => ({
64
- singleTag: "hr"
65
- }), G = () => ({
66
- tag: "blockquote"
67
- }), $ = () => ({
68
- tag: "ul"
69
- }), B = (n) => ({
70
- tag: [
71
- "pre",
72
- {
73
- tag: "code",
74
- attrs: n.attrs
75
- }
76
- ]
77
- }), D = () => ({
78
- singleTag: "br"
79
- }), M = (n) => ({
80
- tag: `h${n.attrs.level}`
81
- }), L = (n) => ({
82
- singleTag: [
83
- {
84
- tag: "img",
85
- attrs: P(n.attrs, ["src", "alt", "title"])
86
- }
87
- ]
88
- }), V = () => ({
89
- tag: "li"
90
- }), F = () => ({
91
- tag: "ol"
92
- }), W = () => ({
93
- tag: "p"
94
- }), K = (n) => ({
95
- tag: [
96
- {
97
- tag: "span",
98
- attrs: {
99
- ["data-type"]: "emoji",
100
- ["data-name"]: n.attrs.name,
101
- emoji: n.attrs.emoji
102
- }
103
- }
104
- ]
105
- }), q = () => ({
106
- tag: "b"
107
- }), z = () => ({
108
- tag: "strike"
109
- }), X = () => ({
110
- tag: "u"
111
- }), Y = () => ({
112
- tag: "strong"
113
- }), J = () => ({
114
- tag: "code"
115
- }), Z = () => ({
116
- tag: "i"
117
- }), Q = (n) => {
118
- const e = { ...n.attrs }, { linktype: t = "url" } = n.attrs;
119
- if (x(t) && (e.href = `mailto:${e.href}`), e.anchor && (e.href = `${e.href}#${e.anchor}`, delete e.anchor), e.custom) {
120
- for (const s in e.custom)
121
- e[s] = e.custom[s];
122
- delete e.custom;
123
- }
124
- return {
125
- tag: [
126
- {
127
- tag: "a",
128
- attrs: e
129
- }
130
- ]
131
- };
132
- }, ee = (n) => ({
133
- tag: [
134
- {
135
- tag: "span",
136
- attrs: n.attrs
137
- }
138
- ]
139
- }), te = () => ({
140
- tag: "sub"
141
- }), se = () => ({
142
- tag: "sup"
143
- }), re = (n) => ({
144
- tag: [
145
- {
146
- tag: "span",
147
- attrs: n.attrs
148
- }
149
- ]
150
- }), oe = (n) => {
151
- var e;
152
- return (e = n.attrs) != null && e.color ? {
153
- tag: [
154
- {
155
- tag: "span",
156
- attrs: {
157
- style: `background-color:${n.attrs.color};`
158
- }
159
- }
160
- ]
161
- } : {
162
- tag: ""
163
- };
164
- }, ne = (n) => {
165
- var e;
166
- return (e = n.attrs) != null && e.color ? {
167
- tag: [
168
- {
169
- tag: "span",
170
- attrs: {
171
- style: `color:${n.attrs.color}`
172
- }
173
- }
174
- ]
175
- } : {
176
- tag: ""
177
- };
178
- }, ie = {
179
- nodes: {
180
- horizontal_rule: C,
181
- blockquote: G,
182
- bullet_list: $,
183
- code_block: B,
184
- hard_break: D,
185
- heading: M,
186
- image: L,
187
- list_item: V,
188
- ordered_list: F,
189
- paragraph: W,
190
- emoji: K
191
- },
192
- marks: {
193
- bold: q,
194
- strike: z,
195
- underline: X,
196
- strong: Y,
197
- code: J,
198
- italic: Z,
199
- link: Q,
200
- styled: ee,
201
- subscript: te,
202
- superscript: se,
203
- anchor: re,
204
- highlight: oe,
205
- textStyle: ne
206
- }
207
- }, ae = function(n) {
208
- const e = {
209
- "&": "&amp;",
210
- "<": "&lt;",
211
- ">": "&gt;",
212
- '"': "&quot;",
213
- "'": "&#39;"
214
- }, t = /[&<>"']/g, s = RegExp(t.source);
215
- return n && s.test(n) ? n.replace(t, (r) => e[r]) : n;
216
- };
217
- class b {
218
- constructor(e) {
219
- h(this, "marks"), h(this, "nodes"), e || (e = ie), this.marks = e.marks || [], this.nodes = e.nodes || [];
220
- }
221
- addNode(e, t) {
222
- this.nodes[e] = t;
223
- }
224
- addMark(e, t) {
225
- this.marks[e] = t;
226
- }
227
- render(e, t = { optimizeImages: false }) {
228
- if (e && e.content && Array.isArray(e.content)) {
229
- let s = "";
230
- return e.content.forEach((r) => {
231
- s += this.renderNode(r);
232
- }), t.optimizeImages ? this.optimizeImages(s, t.optimizeImages) : s;
233
- }
234
- return console.warn(
235
- `The render method must receive an Object with a "content" field.
236
- The "content" field must be an array of nodes as the type ISbRichtext.
237
- ISbRichtext:
238
- content?: ISbRichtext[]
239
- marks?: ISbRichtext[]
240
- attrs?: any
241
- text?: string
242
- type: string
243
-
244
- Example:
245
- {
246
- content: [
247
- {
248
- content: [
249
- {
250
- text: 'Hello World',
251
- type: 'text'
252
- }
253
- ],
254
- type: 'paragraph'
255
- }
256
- ],
257
- type: 'doc'
258
- }`
259
- ), "";
260
- }
261
- optimizeImages(e, t) {
262
- let s = 0, r = 0, o = "", i = "";
263
- 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()}`));
264
- const c = s > 0 || r > 0 || i.length > 0 ? `${s}x${r}${i}` : "";
265
- return e = e.replace(
266
- /a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,
267
- `a.storyblok.com/f/$1/$2.$3/m/${c}`
268
- ), typeof t != "boolean" && (t.sizes || t.srcset) && (e = e.replace(/<img.*?src=["|'](.*?)["|']/g, (a) => {
269
- var l, u;
270
- const d = a.match(
271
- /a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g
272
- );
273
- if (d && d.length > 0) {
274
- const m = {
275
- srcset: (l = t.srcset) == null ? void 0 : l.map((p) => {
276
- if (typeof p == "number")
277
- return `//${d}/m/${p}x0${i} ${p}w`;
278
- if (typeof p == "object" && p.length === 2) {
279
- let T = 0, E = 0;
280
- return typeof p[0] == "number" && (T = p[0]), typeof p[1] == "number" && (E = p[1]), `//${d}/m/${T}x${E}${i} ${T}w`;
281
- }
282
- }).join(", "),
283
- sizes: (u = t.sizes) == null ? void 0 : u.map((p) => p).join(", ")
284
- };
285
- let f = "";
286
- return m.srcset && (f += `srcset="${m.srcset}" `), m.sizes && (f += `sizes="${m.sizes}" `), a.replace(/<img/g, `<img ${f.trim()}`);
287
- }
288
- return a;
289
- })), e;
290
- }
291
- renderNode(e) {
292
- const t = [];
293
- e.marks && e.marks.forEach((r) => {
294
- const o = this.getMatchingMark(r);
295
- o && o.tag !== "" && t.push(this.renderOpeningTag(o.tag));
296
- });
297
- const s = this.getMatchingNode(e);
298
- return s && s.tag && t.push(this.renderOpeningTag(s.tag)), e.content ? e.content.forEach((r) => {
299
- t.push(this.renderNode(r));
300
- }) : e.text ? t.push(ae(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) => {
301
- const o = this.getMatchingMark(r);
302
- o && o.tag !== "" && t.push(this.renderClosingTag(o.tag));
303
- }), t.join("");
304
- }
305
- renderTag(e, t) {
306
- return e.constructor === String ? `<${e}${t}>` : e.map((s) => {
307
- if (s.constructor === String)
308
- return `<${s}${t}>`;
309
- {
310
- let r = `<${s.tag}`;
311
- if (s.attrs)
312
- for (const o in s.attrs) {
313
- const i = s.attrs[o];
314
- i !== null && (r += ` ${o}="${i}"`);
315
- }
316
- return `${r}${t}>`;
317
- }
318
- }).join("");
319
- }
320
- renderOpeningTag(e) {
321
- return this.renderTag(e, "");
322
- }
323
- renderClosingTag(e) {
324
- return e.constructor === String ? `</${e}>` : e.slice(0).reverse().map((t) => t.constructor === String ? `</${t}>` : `</${t.tag}>`).join("");
325
- }
326
- getMatchingNode(e) {
327
- const t = this.nodes[e.type];
328
- if (typeof t == "function")
329
- return t(e);
330
- }
331
- getMatchingMark(e) {
332
- const t = this.marks[e.type];
333
- if (typeof t == "function")
334
- return t(e);
335
- }
336
- renderEmoji(e) {
337
- if (e.attrs.emoji)
338
- return e.attrs.emoji;
339
- const t = [
340
- {
341
- tag: "img",
342
- attrs: {
343
- src: e.attrs.fallbackImage,
344
- draggable: "false",
345
- loading: "lazy",
346
- align: "absmiddle"
347
- }
348
- }
349
- ];
350
- return this.renderTag(t, " /");
351
- }
352
- }
353
- class k {
354
- constructor() {
355
- h(this, "isCDNUrl", (e = "") => e.indexOf("/cdn/") > -1), h(this, "getOptionsPage", (e, t = 25, s = 1) => ({
356
- ...e,
357
- per_page: t,
358
- page: s
359
- })), h(this, "delay", (e) => new Promise((t) => setTimeout(t, e))), h(this, "arrayFrom", (e = 0, t) => [...Array(e)].map(t)), h(this, "range", (e = 0, t = e) => {
360
- const s = Math.abs(t - e) || 0, r = e < t ? 1 : -1;
361
- return this.arrayFrom(s, (o, i) => i * r + e);
362
- }), h(this, "asyncMap", async (e, t) => Promise.all(e.map(t))), h(this, "flatMap", (e = [], t) => e.map(t).reduce((s, r) => [...s, ...r], []));
363
- }
364
- /**
365
- * @method stringify
366
- * @param {Object} params
367
- * @param {String} prefix
368
- * @param {Boolean} isArray
369
- * @return {String} Stringified object
370
- */
371
- stringify(e, t, s) {
372
- const r = [];
373
- for (const o in e) {
374
- if (!Object.prototype.hasOwnProperty.call(e, o))
375
- continue;
376
- const i = e[o], c = s ? "" : encodeURIComponent(o);
377
- let a;
378
- typeof i == "object" ? a = this.stringify(
379
- i,
380
- t ? t + encodeURIComponent("[" + c + "]") : c,
381
- Array.isArray(i)
382
- ) : a = (t ? t + encodeURIComponent("[" + c + "]") : c) + "=" + encodeURIComponent(i), r.push(a);
383
- }
384
- return r.join("&");
385
- }
386
- /**
387
- * @method getRegionURL
388
- * @param {String} regionCode region code, could be eu, us or cn
389
- * @return {String} The base URL of the region
390
- */
391
- getRegionURL(e) {
392
- const t = "api.storyblok.com", s = "api-us.storyblok.com", r = "app.storyblokchina.cn";
393
- switch (e) {
394
- case "us":
395
- return s;
396
- case "cn":
397
- return r;
398
- default:
399
- return t;
400
- }
401
- }
402
- }
403
- class le {
404
- constructor(e) {
405
- h(this, "baseURL"), h(this, "timeout"), h(this, "headers"), h(this, "responseInterceptor"), h(this, "fetch"), h(this, "ejectInterceptor"), h(this, "url"), h(this, "parameters"), this.baseURL = 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 = false, this.url = "", this.parameters = {};
406
- }
407
- /**
408
- *
409
- * @param url string
410
- * @param params ISbStoriesParams
411
- * @returns Promise<ISbResponse | Error>
412
- */
413
- get(e, t) {
414
- return this.url = e, this.parameters = t, this._methodHandler("get");
415
- }
416
- post(e, t) {
417
- return this.url = e, this.parameters = t, this._methodHandler("post");
418
- }
419
- put(e, t) {
420
- return this.url = e, this.parameters = t, this._methodHandler("put");
421
- }
422
- delete(e, t) {
423
- return this.url = e, this.parameters = t, this._methodHandler("delete");
424
- }
425
- async _responseHandler(e) {
426
- const t = [], s = {
427
- data: {},
428
- headers: {},
429
- status: 0,
430
- statusText: ""
431
- };
432
- e.status !== 204 && await e.json().then((r) => {
433
- s.data = r;
434
- });
435
- for (const r of e.headers.entries())
436
- t[r[0]] = r[1];
437
- return s.headers = { ...t }, s.status = e.status, s.statusText = e.statusText, s;
438
- }
439
- async _methodHandler(e) {
440
- let t = `${this.baseURL}${this.url}`, s = null;
441
- if (e === "get") {
442
- const a = new k();
443
- t = `${this.baseURL}${this.url}?${a.stringify(
444
- this.parameters
445
- )}`;
446
- } else
447
- s = JSON.stringify(this.parameters);
448
- const r = new URL(t), o = new AbortController(), { signal: i } = o;
449
- let c;
450
- this.timeout && (c = setTimeout(() => o.abort(), this.timeout));
451
- try {
452
- const a = await this.fetch(`${r}`, {
453
- method: e,
454
- headers: this.headers,
455
- body: s,
456
- signal: i
457
- });
458
- this.timeout && clearTimeout(c);
459
- const l = await this._responseHandler(a);
460
- return this.responseInterceptor && !this.ejectInterceptor ? this._statusHandler(this.responseInterceptor(l)) : this._statusHandler(l);
461
- } catch (a) {
462
- return {
463
- message: a
464
- };
465
- }
466
- }
467
- eject() {
468
- this.ejectInterceptor = true;
469
- }
470
- _statusHandler(e) {
471
- const t = /20[0-6]/g;
472
- return new Promise((s, r) => {
473
- if (t.test(`${e.status}`))
474
- return s(e);
475
- const o = {
476
- message: new Error(e.statusText),
477
- status: e.status,
478
- response: Array.isArray(e.data) ? e.data[0] : e.data.error || e.data.slug
479
- };
480
- r(o);
481
- });
482
- }
483
- }
484
- const N = "SB-Agent", y = {
485
- defaultAgentName: "SB-JS-CLIENT",
486
- defaultAgentVersion: "SB-Agent-Version",
487
- packageVersion: "2.2.3"
488
- };
489
- let g = {};
490
- const _ = {};
491
- class ce {
492
- /**
493
- *
494
- * @param config ISbConfig interface
495
- * @param endpoint string, optional
496
- */
497
- constructor(e, t) {
498
- h(this, "client"), h(this, "maxRetries"), h(this, "throttle"), h(this, "accessToken"), h(this, "cache"), h(this, "helpers"), h(this, "resolveCounter"), h(this, "relations"), h(this, "links"), h(this, "richTextResolver"), h(this, "resolveNestedRelations");
499
- let s = e.endpoint || t;
500
- if (!s) {
501
- const i = new k().getRegionURL, c = e.https === false ? "http" : "https";
502
- e.oauthToken ? s = `${c}://${i(e.region)}/v1` : s = `${c}://${i(e.region)}/v2`;
503
- }
504
- const r = new Headers();
505
- if (r.set("Content-Type", "application/json"), r.set("Accept", "application/json"), e.headers)
506
- for (const i in e.headers)
507
- r.set(i, e.headers[i]);
508
- r.has(N) || (r.set(N, y.defaultAgentName), r.set(y.defaultAgentVersion, y.packageVersion));
509
- let o = 5;
510
- e.oauthToken && (r.set("Authorization", e.oauthToken), o = 3), e.rateLimit && (o = e.rateLimit), e.richTextSchema ? this.richTextResolver = new b(e.richTextSchema) : this.richTextResolver = new b(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries || 5, this.throttle = H(this.throttledRequest, o, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new k(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || true, this.client = new le({
511
- baseURL: s,
512
- timeout: e.timeout || 0,
513
- headers: r,
514
- responseInterceptor: e.responseInterceptor,
515
- fetch: e.fetch
516
- });
517
- }
518
- setComponentResolver(e) {
519
- this.richTextResolver.addNode("blok", (t) => {
520
- let s = "";
521
- return t.attrs.body && t.attrs.body.forEach((r) => {
522
- s += e(r.component, r);
523
- }), {
524
- html: s
525
- };
526
- });
527
- }
528
- parseParams(e) {
529
- return e.version || (e.version = "published"), e.token || (e.token = this.getToken()), e.cv || (e.cv = _[e.token]), Array.isArray(e.resolve_relations) && (e.resolve_relations = e.resolve_relations.join(",")), e;
530
- }
531
- factoryParamOptions(e, t) {
532
- return this.helpers.isCDNUrl(e) ? this.parseParams(t) : t;
533
- }
534
- makeRequest(e, t, s, r) {
535
- const o = this.factoryParamOptions(
536
- e,
537
- this.helpers.getOptionsPage(t, s, r)
538
- );
539
- return this.cacheResponse(e, o);
540
- }
541
- get(e, t) {
542
- t || (t = {});
543
- const s = `/${e}`, r = this.factoryParamOptions(s, t);
544
- return this.cacheResponse(s, r);
545
- }
546
- async getAll(e, t, s) {
547
- const r = (t == null ? void 0 : t.per_page) || 25, o = `/${e}`, i = o.split("/"), c = s || i[i.length - 1], a = 1, l = await this.makeRequest(o, t, r, a), u = l.total ? Math.ceil(l.total / r) : 1, d = await this.helpers.asyncMap(
548
- this.helpers.range(a, u),
549
- (m) => this.makeRequest(o, t, r, m + 1)
550
- );
551
- return this.helpers.flatMap(
552
- [l, ...d],
553
- (m) => Object.values(m.data[c])
554
- );
555
- }
556
- post(e, t) {
557
- const s = `/${e}`;
558
- return Promise.resolve(this.throttle("post", s, t));
559
- }
560
- put(e, t) {
561
- const s = `/${e}`;
562
- return Promise.resolve(this.throttle("put", s, t));
563
- }
564
- delete(e, t) {
565
- const s = `/${e}`;
566
- return Promise.resolve(this.throttle("delete", s, t));
567
- }
568
- getStories(e) {
569
- return this.get("cdn/stories", e);
570
- }
571
- getStory(e, t) {
572
- return this.get(`cdn/stories/${e}`, t);
573
- }
574
- getToken() {
575
- return this.accessToken;
576
- }
577
- ejectInterceptor() {
578
- this.client.eject();
579
- }
580
- _cleanCopy(e) {
581
- return JSON.parse(JSON.stringify(e));
582
- }
583
- _insertLinks(e, t, s) {
584
- const r = e[t];
585
- 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]));
586
- }
587
- _insertRelations(e, t, s, r) {
588
- if (s.indexOf(`${e.component}.${t}`) > -1) {
589
- if (typeof e[t] == "string")
590
- this.relations[r][e[t]] && (e[t] = this._cleanCopy(
591
- this.relations[r][e[t]]
592
- ));
593
- else if (e[t] && e[t].constructor === Array) {
594
- const o = [];
595
- e[t].forEach((i) => {
596
- this.relations[r][i] && o.push(this._cleanCopy(this.relations[r][i]));
597
- }), e[t] = o;
598
- }
599
- }
600
- }
601
- iterateTree(e, t, s) {
602
- const r = (o) => {
603
- if (o != null) {
604
- if (o.constructor === Array)
605
- for (let i = 0; i < o.length; i++)
606
- r(o[i]);
607
- else if (o.constructor === Object) {
608
- if (o._stopResolving)
609
- return;
610
- for (const i in o)
611
- (o.component && o._uid || o.type === "link") && (this._insertRelations(
612
- o,
613
- i,
614
- t,
615
- s
616
- ), this._insertLinks(
617
- o,
618
- i,
619
- s
620
- )), r(o[i]);
621
- }
622
- }
623
- };
624
- r(e.content);
625
- }
626
- async resolveLinks(e, t, s) {
627
- let r = [];
628
- if (e.link_uuids) {
629
- const o = e.link_uuids.length, i = [], c = 50;
630
- for (let a = 0; a < o; a += c) {
631
- const l = Math.min(o, a + c);
632
- i.push(e.link_uuids.slice(a, l));
633
- }
634
- for (let a = 0; a < i.length; a++)
635
- (await this.getStories({
636
- per_page: c,
637
- language: t.language,
638
- version: t.version,
639
- by_uuids: i[a].join(",")
640
- })).data.stories.forEach(
641
- (l) => {
642
- r.push(l);
643
- }
644
- );
645
- } else
646
- r = e.links;
647
- r.forEach((o) => {
648
- this.links[s][o.uuid] = {
649
- ...o,
650
- _stopResolving: true
651
- };
652
- });
653
- }
654
- async resolveRelations(e, t, s) {
655
- let r = [];
656
- if (e.rel_uuids) {
657
- const o = e.rel_uuids.length, i = [], c = 50;
658
- for (let a = 0; a < o; a += c) {
659
- const l = Math.min(o, a + c);
660
- i.push(e.rel_uuids.slice(a, l));
661
- }
662
- for (let a = 0; a < i.length; a++)
663
- (await this.getStories({
664
- per_page: c,
665
- language: t.language,
666
- version: t.version,
667
- by_uuids: i[a].join(",")
668
- })).data.stories.forEach((l) => {
669
- r.push(l);
670
- });
671
- } else
672
- r = e.rels;
673
- r && r.length > 0 && r.forEach((o) => {
674
- this.relations[s][o.uuid] = {
675
- ...o,
676
- _stopResolving: true
677
- };
678
- });
679
- }
680
- async resolveStories(e, t, s) {
681
- var r, o;
682
- let i = [];
683
- 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"].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)
684
- for (const c in this.relations[s])
685
- this.iterateTree(
686
- this.relations[s][c],
687
- i,
688
- s
689
- );
690
- e.story ? this.iterateTree(e.story, i, s) : e.stories.forEach((c) => {
691
- this.iterateTree(c, i, s);
692
- }), delete this.links[s], delete this.relations[s];
693
- }
694
- async cacheResponse(e, t, s) {
695
- const r = this.helpers.stringify({ url: e, params: t }), o = this.cacheProvider();
696
- if (this.cache.clear === "auto" && t.version === "draft" && await this.flushCache(), t.version === "published" && e != "/cdn/spaces/me") {
697
- const i = await o.get(r);
698
- if (i)
699
- return Promise.resolve(i);
700
- }
701
- return new Promise((i, c) => {
702
- try {
703
- (async () => {
704
- var a;
705
- try {
706
- const l = await this.throttle("get", e, t);
707
- let u = { data: l.data, headers: l.headers };
708
- if ((a = l.headers) != null && a["per-page"] && (u = Object.assign({}, u, {
709
- perPage: l.headers["per-page"] ? parseInt(l.headers["per-page"]) : 0,
710
- total: l.headers["per-page"] ? parseInt(l.headers.total) : 0
711
- })), l.status != 200)
712
- return c(l);
713
- if (u.data.story || u.data.stories) {
714
- const d = this.resolveCounter = ++this.resolveCounter % 1e3;
715
- await this.resolveStories(u.data, t, `${d}`);
716
- }
717
- return t.version === "published" && e != "/cdn/spaces/me" && await o.set(r, u), u.data.cv && t.token && (t.version == "draft" && _[t.token] != u.data.cv && await this.flushCache(), _[t.token] = u.data.cv), i(u);
718
- } catch (l) {
719
- return c(l);
720
- }
721
- })();
722
- } catch {
723
- }
724
- });
725
- }
726
- throttledRequest(e, t, s) {
727
- return this.client[e](t, s);
728
- }
729
- cacheVersions() {
730
- return _;
731
- }
732
- cacheVersion() {
733
- return _[this.accessToken];
734
- }
735
- setCacheVersion(e) {
736
- this.accessToken && (_[this.accessToken] = e);
737
- }
738
- cacheProvider() {
739
- switch (this.cache.type) {
740
- case "memory":
741
- return {
742
- get(e) {
743
- return Promise.resolve(g[e]);
744
- },
745
- getAll() {
746
- return Promise.resolve(g);
747
- },
748
- set(e, t) {
749
- return g[e] = t, Promise.resolve(void 0);
750
- },
751
- flush() {
752
- return g = {}, Promise.resolve(void 0);
753
- }
754
- };
755
- case "custom":
756
- if (this.cache.custom)
757
- return this.cache.custom;
758
- default:
759
- return {
760
- get() {
761
- return Promise.resolve(void 0);
762
- },
763
- getAll() {
764
- return Promise.resolve(void 0);
765
- },
766
- set() {
767
- return Promise.resolve(void 0);
768
- },
769
- flush() {
770
- return Promise.resolve(void 0);
771
- }
772
- };
773
- }
774
- }
775
- async flushCache() {
776
- return await this.cacheProvider().flush(), this;
777
- }
778
- }
779
- const ue = (n = {}) => {
780
- const { apiOptions: e } = n;
781
- if (!e.accessToken) {
782
- console.error(
783
- "You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication"
784
- );
785
- return;
786
- }
787
- return { storyblokApi: new ce(e) };
788
- }, de = (n) => {
789
- if (typeof n != "object" || typeof n._editable > "u")
790
- return {};
791
- const e = JSON.parse(
792
- n._editable.replace(/^<!--#storyblok#/, "").replace(/-->$/, "")
793
- );
794
- return {
795
- "data-blok-c": JSON.stringify(e),
796
- "data-blok-uid": e.id + "-" + e.uid
797
- };
798
- };
799
- let R;
800
- const w = "https://app.storyblok.com/f/storyblok-v2-latest.js", pe = (n, e, t = {}) => {
801
- var c;
802
- const r = !(typeof window > "u") && typeof window.storyblokRegisterEvent < "u", i = +new URL((c = window.location) == null ? void 0 : c.href).searchParams.get(
803
- "_storyblok"
804
- ) === n;
805
- if (!(!r || !i)) {
806
- if (!n) {
807
- console.warn("Story ID is not defined. Please provide a valid ID.");
808
- return;
809
- }
810
- window.storyblokRegisterEvent(() => {
811
- new window.StoryblokBridge(t).on(["input", "published", "change"], (l) => {
812
- l.action === "input" && l.story.id === n ? e(l.story) : (l.action === "change" || l.action === "published") && l.storyId === n && window.location.reload();
813
- });
814
- });
815
- }
816
- }, me = (n = {}) => {
817
- var u, d;
818
- const {
819
- bridge: e,
820
- accessToken: t,
821
- use: s = [],
822
- apiOptions: r = {},
823
- richText: o = {}
824
- } = n;
825
- r.accessToken = r.accessToken || t;
826
- const i = { bridge: e, apiOptions: r };
827
- let c = {};
828
- s.forEach((m) => {
829
- c = { ...c, ...m(i) };
830
- });
831
- const l = !(typeof window > "u") && ((d = (u = window.location) == null ? void 0 : u.search) == null ? void 0 : d.includes("_storyblok_tk"));
832
- return e !== false && l && A(w), R = new b(o.schema), o.resolver && S(R, o.resolver), c;
833
- }, S = (n, e) => {
834
- n.addNode("blok", (t) => {
835
- let s = "";
836
- return t.attrs.body.forEach((r) => {
837
- s += e(r.component, r);
838
- }), {
839
- html: s
840
- };
841
- });
842
- }, he = (n) => {
843
- var e, t;
844
- return !n || ((e = n == null ? void 0 : n.content) == null ? void 0 : e[0].type) !== "blok" && !((t = n == null ? void 0 : n.content) != null && t[0].content);
845
- }, _e = (n, e, t) => {
846
- let s = t || R;
847
- if (!s) {
848
- console.error(
849
- "Please initialize the Storyblok SDK before calling the renderRichText function"
850
- );
851
- return;
852
- }
853
- return he(n) ? "" : (e && (s = new b(e.schema), e.resolver && S(s, e.resolver)), s.render(n));
854
- }, ge = () => A(w);
855
- export {
856
- _e as _,
857
- b,
858
- de as d,
859
- ge as g,
860
- ie as i,
861
- me as m,
862
- pe as p,
863
- ue as u
864
- };