@contentful/experiences-core 0.0.1-alpha.10

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 (37) hide show
  1. package/LICENSE +21 -0
  2. package/dist/communication/sendMessage.d.ts +6 -0
  3. package/dist/constants.d.ts +106 -0
  4. package/dist/constants.js +144 -0
  5. package/dist/constants.js.map +1 -0
  6. package/dist/deep-binding/DeepReference.d.ts +28 -0
  7. package/dist/definitions/components.d.ts +8 -0
  8. package/dist/definitions/styles.d.ts +11 -0
  9. package/dist/entity/EditorEntityStore.d.ts +34 -0
  10. package/dist/entity/EditorModeEntityStore.d.ts +29 -0
  11. package/dist/entity/EntityStore.d.ts +68 -0
  12. package/dist/entity/EntityStoreBase.d.ts +49 -0
  13. package/dist/enums.d.ts +6 -0
  14. package/dist/exports.d.ts +3 -0
  15. package/dist/exports.js +2 -0
  16. package/dist/exports.js.map +1 -0
  17. package/dist/fetchers/createExperience.d.ts +20 -0
  18. package/dist/fetchers/fetchById.d.ts +20 -0
  19. package/dist/fetchers/fetchBySlug.d.ts +20 -0
  20. package/dist/index.d.ts +24 -0
  21. package/dist/index.js +2359 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/registries/designTokenRegistry.d.ts +12 -0
  24. package/dist/types.d.ts +244 -0
  25. package/dist/utils/breakpoints.d.ts +12 -0
  26. package/dist/utils/components.d.ts +4 -0
  27. package/dist/utils/domValues.d.ts +15 -0
  28. package/dist/utils/isLink.d.ts +5 -0
  29. package/dist/utils/isLinkToAsset.d.ts +5 -0
  30. package/dist/utils/pathSchema.d.ts +30 -0
  31. package/dist/utils/styleUtils/stylesUtils.d.ts +20 -0
  32. package/dist/utils/supportedModes.d.ts +5 -0
  33. package/dist/utils/transformers/transformBoundContentValue.d.ts +8 -0
  34. package/dist/utils/typeguards.d.ts +6 -0
  35. package/dist/utils/utils.d.ts +46 -0
  36. package/dist/utils/validations.d.ts +15 -0
  37. package/package.json +75 -0
package/dist/index.js ADDED
@@ -0,0 +1,2359 @@
1
+ import md5 from 'md5';
2
+ import { BLOCKS } from '@contentful/rich-text-types';
3
+
4
+ const INCOMING_EVENTS = {
5
+ RequestEditorMode: 'requestEditorMode',
6
+ ExperienceUpdated: 'componentTreeUpdated',
7
+ ComponentDraggingChanged: 'componentDraggingChanged',
8
+ ComponentDragCanceled: 'componentDragCanceled',
9
+ ComponentDragStarted: 'componentDragStarted',
10
+ ComponentDragEnded: 'componentDragEnded',
11
+ ComponentMoveEnded: 'componentMoveEnded',
12
+ CanvasResized: 'canvasResized',
13
+ SelectComponent: 'selectComponent',
14
+ HoverComponent: 'hoverComponent',
15
+ UpdatedEntity: 'updatedEntity',
16
+ AssembliesAdded: 'assembliesAdded',
17
+ AssembliesRegistered: 'assembliesRegistered',
18
+ InitEditor: 'initEditor',
19
+ MouseMove: 'mouseMove',
20
+ };
21
+ const CONTENTFUL_COMPONENT_CATEGORY = 'contentful-component';
22
+ const CONTENTFUL_COMPONENTS = {
23
+ section: {
24
+ id: 'contentful-section',
25
+ name: 'Section',
26
+ },
27
+ container: {
28
+ id: 'contentful-container',
29
+ name: 'Container',
30
+ },
31
+ columns: {
32
+ id: 'contentful-columns',
33
+ name: 'Columns',
34
+ },
35
+ singleColumn: {
36
+ id: 'contentful-single-column',
37
+ name: 'Column',
38
+ },
39
+ button: {
40
+ id: 'contentful-button',
41
+ name: 'Button',
42
+ },
43
+ heading: {
44
+ id: 'contentful-heading',
45
+ name: 'Heading',
46
+ },
47
+ image: {
48
+ id: 'contentful-image',
49
+ name: 'Image',
50
+ },
51
+ richText: {
52
+ id: 'contentful-richText',
53
+ name: 'Rich Text',
54
+ },
55
+ text: {
56
+ id: 'contentful-text',
57
+ name: 'Text',
58
+ },
59
+ };
60
+ const ASSEMBLY_DEFAULT_CATEGORY = 'Assemblies';
61
+ const EMPTY_CONTAINER_HEIGHT = '80px';
62
+ const DEFAULT_IMAGE_WIDTH = '500px';
63
+ var PostMessageMethods;
64
+ (function (PostMessageMethods) {
65
+ PostMessageMethods["REQUEST_ENTITIES"] = "REQUEST_ENTITIES";
66
+ PostMessageMethods["REQUESTED_ENTITIES"] = "REQUESTED_ENTITIES";
67
+ })(PostMessageMethods || (PostMessageMethods = {}));
68
+ const SUPPORTED_IMAGE_FORMATS = ['jpg', 'png', 'webp', 'gif', 'avif'];
69
+
70
+ const structureComponents = new Set([
71
+ CONTENTFUL_COMPONENTS.section.id,
72
+ CONTENTFUL_COMPONENTS.columns.id,
73
+ CONTENTFUL_COMPONENTS.container.id,
74
+ CONTENTFUL_COMPONENTS.singleColumn.id,
75
+ ]);
76
+ const isContentfulStructureComponent = (componentId) => structureComponents.has(componentId ?? '');
77
+ const isEmptyStructureWithRelativeHeight = (children, componentId, height) => {
78
+ return (children === 0 &&
79
+ isContentfulStructureComponent(componentId) &&
80
+ !height?.toString().endsWith('px'));
81
+ };
82
+
83
+ const findOutermostCoordinates = (first, second) => {
84
+ return {
85
+ top: Math.min(first.top, second.top),
86
+ right: Math.max(first.right, second.right),
87
+ bottom: Math.max(first.bottom, second.bottom),
88
+ left: Math.min(first.left, second.left),
89
+ };
90
+ };
91
+ const getElementCoordinates = (element) => {
92
+ const rect = element.getBoundingClientRect();
93
+ /**
94
+ * If element does not have children, or element has it's own width or height,
95
+ * return the element's coordinates.
96
+ */
97
+ if (element.children.length === 0 || rect.width !== 0 || rect.height !== 0) {
98
+ return rect;
99
+ }
100
+ const rects = [];
101
+ /**
102
+ * If element has children, or element does not have it's own width and height,
103
+ * we find the cordinates of the children, and assume the outermost coordinates of the children
104
+ * as the coordinate of the element.
105
+ *
106
+ * E.g child1 => {top: 2, bottom: 3, left: 4, right: 6} & child2 => {top: 1, bottom: 8, left: 12, right: 24}
107
+ * The final assumed coordinates of the element would be => { top: 1, right: 24, bottom: 8, left: 4 }
108
+ */
109
+ for (const child of element.children) {
110
+ const childRect = getElementCoordinates(child);
111
+ if (childRect.width !== 0 || childRect.height !== 0) {
112
+ const { top, right, bottom, left } = childRect;
113
+ rects.push({ top, right, bottom, left });
114
+ }
115
+ }
116
+ if (rects.length === 0) {
117
+ return rect;
118
+ }
119
+ const { top, right, bottom, left } = rects.reduce(findOutermostCoordinates);
120
+ return DOMRect.fromRect({
121
+ x: left,
122
+ y: top,
123
+ height: bottom - top,
124
+ width: right - left,
125
+ });
126
+ };
127
+
128
+ class ParseError extends Error {
129
+ constructor(message) {
130
+ super(message);
131
+ }
132
+ }
133
+ const isValidJsonObject = (s) => {
134
+ try {
135
+ const result = JSON.parse(s);
136
+ if ('object' !== typeof result) {
137
+ return false;
138
+ }
139
+ return true;
140
+ }
141
+ catch (e) {
142
+ return false;
143
+ }
144
+ };
145
+ const doesMismatchMessageSchema = (event) => {
146
+ try {
147
+ tryParseMessage(event);
148
+ return false;
149
+ }
150
+ catch (e) {
151
+ if (e instanceof ParseError) {
152
+ return e.message;
153
+ }
154
+ throw e;
155
+ }
156
+ };
157
+ const tryParseMessage = (event) => {
158
+ if (!event.data) {
159
+ throw new ParseError('Field event.data is missing');
160
+ }
161
+ if ('string' !== typeof event.data) {
162
+ throw new ParseError(`Field event.data must be a string, instead of '${typeof event.data}'`);
163
+ }
164
+ if (!isValidJsonObject(event.data)) {
165
+ throw new ParseError('Field event.data must be a valid JSON object serialized as string');
166
+ }
167
+ const eventData = JSON.parse(event.data);
168
+ if (!eventData.source) {
169
+ throw new ParseError(`Field eventData.source must be equal to 'composability-app'`);
170
+ }
171
+ if ('composability-app' !== eventData.source) {
172
+ throw new ParseError(`Field eventData.source must be equal to 'composability-app', instead of '${eventData.source}'`);
173
+ }
174
+ // check eventData.eventType
175
+ const supportedEventTypes = Object.values(INCOMING_EVENTS);
176
+ if (!supportedEventTypes.includes(eventData.eventType)) {
177
+ // Expected message: This message is handled in the EntityStore to store fetched entities
178
+ if (eventData.eventType !== PostMessageMethods.REQUESTED_ENTITIES) {
179
+ throw new ParseError(`Field eventData.eventType must be one of the supported values: [${supportedEventTypes.join(', ')}]`);
180
+ }
181
+ }
182
+ return eventData;
183
+ };
184
+ const validateExperienceBuilderConfig = ({ locale, isEditorMode, }) => {
185
+ if (isEditorMode) {
186
+ return;
187
+ }
188
+ if (!locale) {
189
+ throw new Error('Parameter "locale" is required for experience builder initialization outside of editor mode');
190
+ }
191
+ };
192
+
193
+ const transformFill = (value) => (value === 'fill' ? '100%' : value);
194
+ const transformGridColumn = (span) => {
195
+ if (!span) {
196
+ return {};
197
+ }
198
+ return {
199
+ gridColumn: `span ${span}`,
200
+ };
201
+ };
202
+ const transformBorderStyle = (value) => {
203
+ if (!value)
204
+ return {};
205
+ const parts = value.split(' ');
206
+ // Just accept the passed value
207
+ if (parts.length < 3)
208
+ return { border: value };
209
+ // Replace the second part always with `solid` and set the box sizing accordingly
210
+ const [borderSize, borderStyle, ...borderColorParts] = parts;
211
+ const borderColor = borderColorParts.join(' ');
212
+ return {
213
+ border: `${borderSize} ${borderStyle} ${borderColor}`,
214
+ };
215
+ };
216
+ const transformAlignment = (cfHorizontalAlignment, cfVerticalAlignment, cfFlexDirection = 'column') => cfFlexDirection === 'row'
217
+ ? {
218
+ alignItems: cfHorizontalAlignment,
219
+ justifyContent: cfVerticalAlignment === 'center' ? `safe ${cfVerticalAlignment}` : cfVerticalAlignment,
220
+ }
221
+ : {
222
+ alignItems: cfVerticalAlignment,
223
+ justifyContent: cfHorizontalAlignment === 'center'
224
+ ? `safe ${cfHorizontalAlignment}`
225
+ : cfHorizontalAlignment,
226
+ };
227
+ const transformBackgroundImage = (cfBackgroundImageUrl, cfBackgroundImageOptions) => {
228
+ const matchBackgroundSize = (scaling) => {
229
+ if ('fill' === scaling)
230
+ return 'cover';
231
+ if ('fit' === scaling)
232
+ return 'contain';
233
+ };
234
+ const matchBackgroundPosition = (alignment) => {
235
+ if (!alignment || 'string' !== typeof alignment) {
236
+ return;
237
+ }
238
+ let [horizontalAlignment, verticalAlignment] = alignment.trim().split(/\s+/, 2);
239
+ // Special case for handling single values
240
+ // for backwards compatibility with single values 'right','left', 'center', 'top','bottom'
241
+ if (horizontalAlignment && !verticalAlignment) {
242
+ const singleValue = horizontalAlignment;
243
+ switch (singleValue) {
244
+ case 'left':
245
+ horizontalAlignment = 'left';
246
+ verticalAlignment = 'center';
247
+ break;
248
+ case 'right':
249
+ horizontalAlignment = 'right';
250
+ verticalAlignment = 'center';
251
+ break;
252
+ case 'center':
253
+ horizontalAlignment = 'center';
254
+ verticalAlignment = 'center';
255
+ break;
256
+ case 'top':
257
+ horizontalAlignment = 'center';
258
+ verticalAlignment = 'top';
259
+ break;
260
+ case 'bottom':
261
+ horizontalAlignment = 'center';
262
+ verticalAlignment = 'bottom';
263
+ break;
264
+ // just fall down to the normal validation logic for horiz and vert
265
+ }
266
+ }
267
+ const isHorizontalValid = ['left', 'right', 'center'].includes(horizontalAlignment);
268
+ const isVerticalValid = ['top', 'bottom', 'center'].includes(verticalAlignment);
269
+ horizontalAlignment = isHorizontalValid ? horizontalAlignment : 'left';
270
+ verticalAlignment = isVerticalValid ? verticalAlignment : 'top';
271
+ return `${horizontalAlignment} ${verticalAlignment}`;
272
+ };
273
+ if (!cfBackgroundImageUrl) {
274
+ return;
275
+ }
276
+ let backgroundImage;
277
+ let backgroundImageSet;
278
+ if (typeof cfBackgroundImageUrl === 'string') {
279
+ backgroundImage = `url(${cfBackgroundImageUrl})`;
280
+ }
281
+ else {
282
+ const imgSet = cfBackgroundImageUrl.srcSet?.join(',');
283
+ backgroundImage = `url(${cfBackgroundImageUrl.url})`;
284
+ backgroundImageSet = `image-set(${imgSet})`;
285
+ }
286
+ return {
287
+ backgroundImage,
288
+ backgroundImage2: backgroundImageSet,
289
+ backgroundRepeat: cfBackgroundImageOptions?.scaling === 'tile' ? 'repeat' : 'no-repeat',
290
+ backgroundPosition: matchBackgroundPosition(cfBackgroundImageOptions?.alignment),
291
+ backgroundSize: matchBackgroundSize(cfBackgroundImageOptions?.scaling),
292
+ };
293
+ };
294
+ const transformWidthSizing = ({ value, cfMargin, }) => {
295
+ if (!value || !cfMargin)
296
+ return;
297
+ const transformedValue = transformFill(value);
298
+ const marginValues = cfMargin.split(' ');
299
+ const rightMargin = marginValues[1] || '0px';
300
+ const leftMargin = marginValues[3] || '0px';
301
+ const calcValue = `calc(${transformedValue} - ${leftMargin} - ${rightMargin})`;
302
+ /**
303
+ * We want to check if the calculated value is valid CSS. If this fails,
304
+ * this means the `transformedValue` is not a calculable value (not a px, rem, or %).
305
+ * The value may instead be a string such as `min-content` or `max-content`. In
306
+ * that case we don't want to use calc and instead return the raw value.
307
+ */
308
+ if (typeof window !== 'undefined' && CSS.supports('width', calcValue)) {
309
+ return calcValue;
310
+ }
311
+ return transformedValue;
312
+ };
313
+
314
+ const toCSSAttribute = (key) => {
315
+ let val = key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
316
+ // Remove the number from the end of the key to allow for overrides on style properties
317
+ val = val.replace(/\d+$/, '');
318
+ return val;
319
+ };
320
+ const buildStyleTag = ({ styles, nodeId }) => {
321
+ const stylesStr = Object.entries(styles)
322
+ .filter(([, value]) => value !== undefined)
323
+ .reduce((acc, [key, value]) => `${acc}
324
+ ${toCSSAttribute(key)}: ${value};`, '');
325
+ const className = `cfstyles-${nodeId ? nodeId : md5(stylesStr)}`;
326
+ const styleRule = `.${className}{ ${stylesStr} }`;
327
+ return [className, styleRule];
328
+ };
329
+ const buildCfStyles = ({ cfHorizontalAlignment, cfVerticalAlignment, cfFlexDirection, cfFlexWrap, cfMargin, cfPadding, cfBackgroundColor, cfWidth, cfHeight, cfMaxWidth, cfBorder, cfBorderRadius, cfGap, cfBackgroundImageUrl, cfBackgroundImageOptions, cfFontSize, cfFontWeight, cfImageOptions, cfLineHeight, cfLetterSpacing, cfTextColor, cfTextAlign, cfTextTransform, cfTextBold, cfTextItalic, cfTextUnderline, cfColumnSpan, }) => {
330
+ return {
331
+ margin: cfMargin,
332
+ padding: cfPadding,
333
+ backgroundColor: cfBackgroundColor,
334
+ width: transformWidthSizing({ value: cfWidth || cfImageOptions?.width, cfMargin }),
335
+ height: transformFill(cfHeight || cfImageOptions?.height),
336
+ maxWidth: cfMaxWidth,
337
+ ...transformGridColumn(cfColumnSpan),
338
+ ...transformBorderStyle(cfBorder),
339
+ borderRadius: cfBorderRadius,
340
+ gap: cfGap,
341
+ ...transformAlignment(cfHorizontalAlignment, cfVerticalAlignment, cfFlexDirection),
342
+ flexDirection: cfFlexDirection,
343
+ flexWrap: cfFlexWrap,
344
+ ...transformBackgroundImage(cfBackgroundImageUrl, cfBackgroundImageOptions),
345
+ fontSize: cfFontSize,
346
+ fontWeight: cfTextBold ? 'bold' : cfFontWeight,
347
+ fontStyle: cfTextItalic ? 'italic' : 'normal',
348
+ lineHeight: cfLineHeight,
349
+ letterSpacing: cfLetterSpacing,
350
+ color: cfTextColor,
351
+ textAlign: cfTextAlign,
352
+ textTransform: cfTextTransform,
353
+ textDecoration: cfTextUnderline ? 'underline' : 'none',
354
+ boxSizing: 'border-box',
355
+ objectFit: cfImageOptions?.objectFit,
356
+ objectPosition: cfImageOptions?.objectPosition,
357
+ };
358
+ };
359
+ /**
360
+ * Container/section default behavior:
361
+ * Default height => height: EMPTY_CONTAINER_HEIGHT (120px)
362
+ * If a container component has children => height: 'fit-content'
363
+ */
364
+ const calculateNodeDefaultHeight = ({ blockId, children, value, }) => {
365
+ if (!blockId || !isContentfulStructureComponent(blockId) || value !== 'auto') {
366
+ return value;
367
+ }
368
+ if (children.length) {
369
+ return '100%';
370
+ }
371
+ return EMPTY_CONTAINER_HEIGHT;
372
+ };
373
+
374
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
375
+ function get(obj, path) {
376
+ if (!path.length) {
377
+ return obj;
378
+ }
379
+ try {
380
+ const [currentPath, ...nextPath] = path;
381
+ return get(obj[currentPath], nextPath);
382
+ }
383
+ catch (err) {
384
+ return undefined;
385
+ }
386
+ }
387
+
388
+ const getBoundValue = (entryOrAsset, path) => {
389
+ const value = get(entryOrAsset, path.split('/').slice(2, -1));
390
+ return value && typeof value == 'object' && value.url
391
+ ? value.url
392
+ : value;
393
+ };
394
+
395
+ const transformRichText = (entryOrAsset, path) => {
396
+ const value = getBoundValue(entryOrAsset, path);
397
+ if (typeof value === 'string') {
398
+ return {
399
+ data: {},
400
+ content: [
401
+ {
402
+ nodeType: BLOCKS.PARAGRAPH,
403
+ data: {},
404
+ content: [
405
+ {
406
+ data: {},
407
+ nodeType: 'text',
408
+ value: value,
409
+ marks: [],
410
+ },
411
+ ],
412
+ },
413
+ ],
414
+ nodeType: BLOCKS.DOCUMENT,
415
+ };
416
+ }
417
+ if (typeof value === 'object' && value.nodeType === BLOCKS.DOCUMENT) {
418
+ return value;
419
+ }
420
+ return undefined;
421
+ };
422
+
423
+ function getOptimizedImageUrl(url, width, quality, format) {
424
+ if (url.startsWith('//')) {
425
+ url = 'https:' + url;
426
+ }
427
+ const params = new URLSearchParams();
428
+ if (width) {
429
+ params.append('w', width.toString());
430
+ }
431
+ if (quality && quality > 0 && quality < 100) {
432
+ params.append('q', quality.toString());
433
+ }
434
+ if (format) {
435
+ params.append('fm', format);
436
+ }
437
+ const queryString = params.toString();
438
+ return `${url}${queryString ? '?' + queryString : ''}`;
439
+ }
440
+
441
+ function validateParams(file, quality, format) {
442
+ if (!file.details.image) {
443
+ throw Error('No image in file asset to transform');
444
+ }
445
+ if (quality < 0 || quality > 100) {
446
+ throw Error('Quality must be between 0 and 100');
447
+ }
448
+ if (format && !SUPPORTED_IMAGE_FORMATS.includes(format)) {
449
+ throw Error(`Format must be one of ${SUPPORTED_IMAGE_FORMATS.join(', ')}`);
450
+ }
451
+ return true;
452
+ }
453
+
454
+ const MAX_WIDTH_ALLOWED$1 = 2000;
455
+ const getOptimizedBackgroundImageAsset = (file, widthStyle, quality = '100%', format) => {
456
+ const qualityNumber = Number(quality.replace('%', ''));
457
+ if (!validateParams(file, qualityNumber, format)) ;
458
+ if (!validateParams(file, qualityNumber, format)) ;
459
+ const url = file.url;
460
+ const { width1x, width2x } = getWidths(widthStyle, file);
461
+ const imageUrl1x = getOptimizedImageUrl(url, width1x, qualityNumber, format);
462
+ const imageUrl2x = getOptimizedImageUrl(url, width2x, qualityNumber, format);
463
+ const srcSet = [`url(${imageUrl1x}) 1x`, `url(${imageUrl2x}) 2x`];
464
+ const returnedUrl = getOptimizedImageUrl(url, width2x, qualityNumber, format);
465
+ const optimizedBackgroundImageAsset = {
466
+ url: returnedUrl,
467
+ srcSet,
468
+ file,
469
+ };
470
+ return optimizedBackgroundImageAsset;
471
+ function getWidths(widthStyle, file) {
472
+ let width1x = 0;
473
+ let width2x = 0;
474
+ const intrinsicImageWidth = file.details.image.width;
475
+ if (widthStyle.endsWith('px')) {
476
+ width1x = Math.min(Number(widthStyle.replace('px', '')), intrinsicImageWidth);
477
+ }
478
+ else {
479
+ width1x = Math.min(MAX_WIDTH_ALLOWED$1, intrinsicImageWidth);
480
+ }
481
+ width2x = Math.min(width1x * 2, intrinsicImageWidth);
482
+ return { width1x, width2x };
483
+ }
484
+ };
485
+
486
+ const MAX_WIDTH_ALLOWED = 4000;
487
+ const getOptimizedImageAsset = (file, sizes, quality = '100%', format) => {
488
+ const qualityNumber = Number(quality.replace('%', ''));
489
+ if (!validateParams(file, qualityNumber, format)) ;
490
+ const url = file.url;
491
+ const maxWidth = Math.min(file.details.image.width, MAX_WIDTH_ALLOWED);
492
+ const numOfParts = Math.max(2, Math.ceil(maxWidth / 500));
493
+ const widthParts = Array.from({ length: numOfParts }, (_, index) => Math.ceil((index + 1) * (maxWidth / numOfParts)));
494
+ const srcSet = sizes
495
+ ? widthParts.map((width) => `${getOptimizedImageUrl(url, width, qualityNumber, format)} ${width}w`)
496
+ : [];
497
+ const intrinsicImageWidth = file.details.image.width;
498
+ if (intrinsicImageWidth > MAX_WIDTH_ALLOWED) {
499
+ srcSet.push(`${getOptimizedImageUrl(url, undefined, qualityNumber, format)} ${intrinsicImageWidth}w`);
500
+ }
501
+ const returnedUrl = getOptimizedImageUrl(url, file.details.image.width > 2000 ? 2000 : undefined, qualityNumber, format);
502
+ const optimizedImageAsset = {
503
+ url: returnedUrl,
504
+ srcSet,
505
+ sizes,
506
+ file,
507
+ };
508
+ return optimizedImageAsset;
509
+ };
510
+
511
+ const transformMedia = (asset, variables, resolveDesignValue, variableName, path) => {
512
+ let value;
513
+ //TODO: this will be better served by injectable type transformers instead of if statement
514
+ if (variableName === 'cfImageAsset') {
515
+ const optionsVariableName = 'cfImageOptions';
516
+ const options = resolveDesignValue(variables[optionsVariableName]?.type === 'DesignValue'
517
+ ? variables[optionsVariableName].valuesByBreakpoint
518
+ : {}, optionsVariableName);
519
+ if (!options) {
520
+ console.error(`Error transforming image asset: Required variable [${optionsVariableName}] missing from component definition`);
521
+ return;
522
+ }
523
+ try {
524
+ value = getOptimizedImageAsset(asset.fields.file, options.targetSize, options.quality, options.format);
525
+ return value;
526
+ }
527
+ catch (error) {
528
+ console.error('Error transforming image asset', error);
529
+ }
530
+ return;
531
+ }
532
+ if (variableName === 'cfBackgroundImageUrl') {
533
+ const width = resolveDesignValue(variables['cfWidth']?.type === 'DesignValue' ? variables['cfWidth'].valuesByBreakpoint : {}, 'cfWidth');
534
+ const optionsVariableName = 'cfBackgroundImageOptions';
535
+ const options = resolveDesignValue(variables[optionsVariableName]?.type === 'DesignValue'
536
+ ? variables[optionsVariableName].valuesByBreakpoint
537
+ : {}, optionsVariableName);
538
+ if (!options) {
539
+ console.error(`Error transforming image asset: Required variable [${optionsVariableName}] missing from component definition`);
540
+ return;
541
+ }
542
+ try {
543
+ value = getOptimizedBackgroundImageAsset(asset.fields.file, width, options.quality, options.format);
544
+ return value;
545
+ }
546
+ catch (error) {
547
+ console.error('Error transforming image asset', error);
548
+ }
549
+ return;
550
+ }
551
+ // return getBoundValue(asset, entityStore, binding, path);
552
+ return getBoundValue(asset, path);
553
+ };
554
+
555
+ const transformBoundContentValue = (variables, entityStore, binding, resolveDesignValue, variableName, variableDefinition, path) => {
556
+ const entityOrAsset = entityStore.getEntryOrAsset(binding, path);
557
+ if (!entityOrAsset)
558
+ return;
559
+ switch (variableDefinition.type) {
560
+ case 'Media':
561
+ return transformMedia(entityOrAsset, variables, resolveDesignValue, variableName, path);
562
+ case 'RichText':
563
+ return transformRichText(entityOrAsset, path);
564
+ default:
565
+ return getBoundValue(entityOrAsset, path);
566
+ }
567
+ };
568
+
569
+ const getDataFromTree = (tree) => {
570
+ let dataSource = {};
571
+ let unboundValues = {};
572
+ const queue = [...tree.root.children];
573
+ while (queue.length) {
574
+ const node = queue.shift();
575
+ if (!node) {
576
+ continue;
577
+ }
578
+ dataSource = { ...dataSource, ...node.data.dataSource };
579
+ unboundValues = { ...unboundValues, ...node.data.unboundValues };
580
+ if (node.children.length) {
581
+ queue.push(...node.children);
582
+ }
583
+ }
584
+ return {
585
+ dataSource,
586
+ unboundValues,
587
+ };
588
+ };
589
+ /**
590
+ * Gets calculates the index to drop the dragged component based on the mouse position
591
+ * @returns {InsertionData} a object containing a node that will become a parent for dragged component and index at which it must be inserted
592
+ */
593
+ const getInsertionData = ({ dropReceiverParentNode, dropReceiverNode, flexDirection, isMouseAtTopBorder, isMouseAtBottomBorder, isMouseInLeftHalf, isMouseInUpperHalf, isOverTopIndicator, isOverBottomIndicator, }) => {
594
+ const APPEND_INSIDE = dropReceiverNode.children.length;
595
+ const PREPEND_INSIDE = 0;
596
+ if (isMouseAtTopBorder || isMouseAtBottomBorder) {
597
+ const indexOfSectionInParentChildren = dropReceiverParentNode.children.findIndex((n) => n.data.id === dropReceiverNode.data.id);
598
+ const APPEND_OUTSIDE = indexOfSectionInParentChildren + 1;
599
+ const PREPEND_OUTSIDE = indexOfSectionInParentChildren;
600
+ return {
601
+ // when the mouse is around the border we want to drop the new component as a new section onto the root node
602
+ node: dropReceiverParentNode,
603
+ index: isMouseAtBottomBorder ? APPEND_OUTSIDE : PREPEND_OUTSIDE,
604
+ };
605
+ }
606
+ // if over one of the section indicators
607
+ if (isOverTopIndicator || isOverBottomIndicator) {
608
+ const indexOfSectionInParentChildren = dropReceiverParentNode.children.findIndex((n) => n.data.id === dropReceiverNode.data.id);
609
+ const APPEND_OUTSIDE = indexOfSectionInParentChildren + 1;
610
+ const PREPEND_OUTSIDE = indexOfSectionInParentChildren;
611
+ return {
612
+ // when the mouse is around the border we want to drop the new component as a new section onto the root node
613
+ node: dropReceiverParentNode,
614
+ index: isOverBottomIndicator ? APPEND_OUTSIDE : PREPEND_OUTSIDE,
615
+ };
616
+ }
617
+ if (flexDirection === undefined || flexDirection === 'row') {
618
+ return {
619
+ node: dropReceiverNode,
620
+ index: isMouseInLeftHalf ? PREPEND_INSIDE : APPEND_INSIDE,
621
+ };
622
+ }
623
+ else {
624
+ return {
625
+ node: dropReceiverNode,
626
+ index: isMouseInUpperHalf ? PREPEND_INSIDE : APPEND_INSIDE,
627
+ };
628
+ }
629
+ };
630
+ const generateRandomId = (letterCount) => {
631
+ const LETTERS = 'abcdefghijklmnopqvwxyzABCDEFGHIJKLMNOPQVWXYZ';
632
+ const NUMS = '0123456789';
633
+ const ALNUM = NUMS + LETTERS;
634
+ const times = (n, callback) => Array.from({ length: n }, callback);
635
+ const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
636
+ return times(letterCount, () => ALNUM[random(0, ALNUM.length - 1)]).join('');
637
+ };
638
+ const checkIsAssemblyNode = ({ componentId, usedComponents, }) => {
639
+ if (!usedComponents?.length)
640
+ return false;
641
+ return usedComponents.some((usedComponent) => usedComponent.sys.id === componentId);
642
+ };
643
+ /** @deprecated use `checkIsAssemblyNode` instead. Will be removed with SDK v5. */
644
+ const checkIsAssembly = checkIsAssemblyNode;
645
+ /**
646
+ * This check assumes that the entry is already ensured to be an experience, i.e. the
647
+ * content type of the entry is an experience type with the necessary annotations.
648
+ **/
649
+ const checkIsAssemblyEntry = (entry) => {
650
+ return Boolean(entry.fields?.componentSettings);
651
+ };
652
+ const checkIsAssemblyDefinition = (component) => component?.category === ASSEMBLY_DEFAULT_CATEGORY;
653
+
654
+ const isExperienceEntry = (entry) => {
655
+ return (entry?.sys?.type === 'Entry' &&
656
+ !!entry.fields?.title &&
657
+ !!entry.fields?.slug &&
658
+ !!entry.fields?.componentTree &&
659
+ Array.isArray(entry.fields.componentTree.breakpoints) &&
660
+ Array.isArray(entry.fields.componentTree.children) &&
661
+ typeof entry.fields.componentTree.schemaVersion === 'string');
662
+ };
663
+
664
+ const supportedModes = ['delivery', 'preview', 'editor'];
665
+
666
+ const builtInStyles = {
667
+ cfVerticalAlignment: {
668
+ validations: {
669
+ in: [
670
+ {
671
+ value: 'start',
672
+ displayName: 'Align left',
673
+ },
674
+ {
675
+ value: 'center',
676
+ displayName: 'Align center',
677
+ },
678
+ {
679
+ value: 'end',
680
+ displayName: 'Align right',
681
+ },
682
+ ],
683
+ },
684
+ type: 'Text',
685
+ group: 'style',
686
+ description: 'The horizontal alignment of the section',
687
+ defaultValue: 'center',
688
+ displayName: 'Vertical alignment',
689
+ },
690
+ cfHorizontalAlignment: {
691
+ validations: {
692
+ in: [
693
+ {
694
+ value: 'start',
695
+ displayName: 'Align top',
696
+ },
697
+ {
698
+ value: 'center',
699
+ displayName: 'Align center',
700
+ },
701
+ {
702
+ value: 'end',
703
+ displayName: 'Align bottom',
704
+ },
705
+ ],
706
+ },
707
+ type: 'Text',
708
+ group: 'style',
709
+ description: 'The horizontal alignment of the section',
710
+ defaultValue: 'center',
711
+ displayName: 'Horizontal alignment',
712
+ },
713
+ cfMargin: {
714
+ displayName: 'Margin',
715
+ type: 'Text',
716
+ group: 'style',
717
+ description: 'The margin of the section',
718
+ defaultValue: '0 0 0 0',
719
+ },
720
+ cfPadding: {
721
+ displayName: 'Padding',
722
+ type: 'Text',
723
+ group: 'style',
724
+ description: 'The padding of the section',
725
+ defaultValue: '0 0 0 0',
726
+ },
727
+ cfBackgroundColor: {
728
+ displayName: 'Background color',
729
+ type: 'Text',
730
+ group: 'style',
731
+ description: 'The background color of the section',
732
+ defaultValue: 'rgba(255, 255, 255, 0)',
733
+ },
734
+ cfWidth: {
735
+ displayName: 'Width',
736
+ type: 'Text',
737
+ group: 'style',
738
+ description: 'The width of the section',
739
+ defaultValue: 'fill',
740
+ },
741
+ cfHeight: {
742
+ displayName: 'Height',
743
+ type: 'Text',
744
+ group: 'style',
745
+ description: 'The height of the section',
746
+ defaultValue: 'fit-content',
747
+ },
748
+ cfMaxWidth: {
749
+ displayName: 'Max width',
750
+ type: 'Text',
751
+ group: 'style',
752
+ description: 'The max-width of the section',
753
+ defaultValue: 'none',
754
+ },
755
+ cfFlexDirection: {
756
+ displayName: 'Direction',
757
+ type: 'Text',
758
+ group: 'style',
759
+ description: 'The orientation of the section',
760
+ defaultValue: 'column',
761
+ },
762
+ cfFlexWrap: {
763
+ displayName: 'Wrap objects',
764
+ type: 'Text',
765
+ group: 'style',
766
+ description: 'Wrap objects',
767
+ defaultValue: 'nowrap',
768
+ },
769
+ cfBorder: {
770
+ displayName: 'Border',
771
+ type: 'Text',
772
+ group: 'style',
773
+ description: 'The border of the section',
774
+ defaultValue: '0px solid rgba(0, 0, 0, 0)',
775
+ },
776
+ cfBorderRadius: {
777
+ displayName: 'Border Radius',
778
+ type: 'Text',
779
+ group: 'style',
780
+ description: 'The border radius of the section',
781
+ defaultValue: '0px',
782
+ },
783
+ cfGap: {
784
+ displayName: 'Gap',
785
+ type: 'Text',
786
+ group: 'style',
787
+ description: 'The spacing between the elements of the section',
788
+ defaultValue: '0px',
789
+ },
790
+ cfHyperlink: {
791
+ displayName: 'Hyperlink',
792
+ type: 'Text',
793
+ defaultValue: '',
794
+ validations: {
795
+ format: 'URL',
796
+ },
797
+ description: 'hyperlink for section or container',
798
+ },
799
+ cfOpenInNewTab: {
800
+ displayName: 'Hyperlink behaviour',
801
+ type: 'Boolean',
802
+ defaultValue: false,
803
+ description: 'To open hyperlink in new Tab or not',
804
+ },
805
+ };
806
+ const optionalBuiltInStyles = {
807
+ cfFontSize: {
808
+ displayName: 'Font Size',
809
+ type: 'Text',
810
+ group: 'style',
811
+ description: 'The font size of the element',
812
+ defaultValue: '16px',
813
+ },
814
+ cfFontWeight: {
815
+ validations: {
816
+ in: [
817
+ {
818
+ value: '400',
819
+ displayName: 'Normal',
820
+ },
821
+ {
822
+ value: '500',
823
+ displayName: 'Medium',
824
+ },
825
+ {
826
+ value: '600',
827
+ displayName: 'Semi Bold',
828
+ },
829
+ ],
830
+ },
831
+ displayName: 'Font Weight',
832
+ type: 'Text',
833
+ group: 'style',
834
+ description: 'The font weight of the element',
835
+ defaultValue: '400',
836
+ },
837
+ cfImageAsset: {
838
+ displayName: 'Image',
839
+ type: 'Media',
840
+ description: 'Image to display',
841
+ },
842
+ cfImageOptions: {
843
+ displayName: 'Image options',
844
+ type: 'Object',
845
+ group: 'style',
846
+ defaultValue: {
847
+ width: DEFAULT_IMAGE_WIDTH,
848
+ height: '100%',
849
+ targetSize: DEFAULT_IMAGE_WIDTH,
850
+ },
851
+ },
852
+ cfBackgroundImageUrl: {
853
+ displayName: 'Background image',
854
+ type: 'Media',
855
+ description: 'Background image for component',
856
+ },
857
+ cfBackgroundImageOptions: {
858
+ displayName: 'Background image options',
859
+ type: 'Object',
860
+ group: 'style',
861
+ defaultValue: {
862
+ scaling: 'fill',
863
+ alignment: 'left top',
864
+ targetSize: '2000px',
865
+ },
866
+ },
867
+ cfLineHeight: {
868
+ displayName: 'Line Height',
869
+ type: 'Text',
870
+ group: 'style',
871
+ description: 'The line height of the element',
872
+ defaultValue: '20px',
873
+ },
874
+ cfLetterSpacing: {
875
+ displayName: 'Letter Spacing',
876
+ type: 'Text',
877
+ group: 'style',
878
+ description: 'The letter spacing of the element',
879
+ defaultValue: '0px',
880
+ },
881
+ cfTextColor: {
882
+ displayName: 'Text Color',
883
+ type: 'Text',
884
+ group: 'style',
885
+ description: 'The text color of the element',
886
+ defaultValue: 'rgba(0, 0, 0, 1)',
887
+ },
888
+ cfTextAlign: {
889
+ validations: {
890
+ in: [
891
+ {
892
+ value: 'left',
893
+ displayName: 'Align left',
894
+ },
895
+ {
896
+ value: 'center',
897
+ displayName: 'Align center',
898
+ },
899
+ {
900
+ value: 'right',
901
+ displayName: 'Align right',
902
+ },
903
+ ],
904
+ },
905
+ displayName: 'Text Align',
906
+ type: 'Text',
907
+ group: 'style',
908
+ description: 'The text alignment of the element',
909
+ defaultValue: 'left',
910
+ },
911
+ cfTextTransform: {
912
+ validations: {
913
+ in: [
914
+ {
915
+ value: 'none',
916
+ displayName: 'Normal',
917
+ },
918
+ {
919
+ value: 'capitalize',
920
+ displayName: 'Capitalize',
921
+ },
922
+ {
923
+ value: 'uppercase',
924
+ displayName: 'Uppercase',
925
+ },
926
+ {
927
+ value: 'lowercase',
928
+ displayName: 'Lowercase',
929
+ },
930
+ ],
931
+ },
932
+ displayName: 'Text Transform',
933
+ type: 'Text',
934
+ group: 'style',
935
+ description: 'The text transform of the element',
936
+ defaultValue: 'none',
937
+ },
938
+ cfTextBold: {
939
+ displayName: 'Bold',
940
+ type: 'Boolean',
941
+ group: 'style',
942
+ description: 'The text bold of the element',
943
+ defaultValue: false,
944
+ },
945
+ cfTextItalic: {
946
+ displayName: 'Italic',
947
+ type: 'Boolean',
948
+ group: 'style',
949
+ description: 'The text italic of the element',
950
+ defaultValue: false,
951
+ },
952
+ cfTextUnderline: {
953
+ displayName: 'Underline',
954
+ type: 'Boolean',
955
+ group: 'style',
956
+ description: 'The text underline of the element',
957
+ defaultValue: false,
958
+ },
959
+ };
960
+ const sectionBuiltInStyles = {
961
+ ...builtInStyles,
962
+ cfBackgroundImageUrl: optionalBuiltInStyles.cfBackgroundImageUrl,
963
+ cfBackgroundImageOptions: optionalBuiltInStyles.cfBackgroundImageOptions,
964
+ };
965
+ const containerBuiltInStyles = {
966
+ ...builtInStyles,
967
+ cfBackgroundImageUrl: optionalBuiltInStyles.cfBackgroundImageUrl,
968
+ cfBackgroundImageOptions: optionalBuiltInStyles.cfBackgroundImageOptions,
969
+ cfMaxWidth: {
970
+ displayName: 'Max Width',
971
+ type: 'Text',
972
+ group: 'style',
973
+ description: 'The max-width of the section',
974
+ defaultValue: '1192px',
975
+ },
976
+ };
977
+ const singleColumnBuiltInStyles = {
978
+ cfBackgroundImageUrl: optionalBuiltInStyles.cfBackgroundImageUrl,
979
+ cfBackgroundImageOptions: optionalBuiltInStyles.cfBackgroundImageOptions,
980
+ cfVerticalAlignment: {
981
+ validations: {
982
+ in: [
983
+ {
984
+ value: 'start',
985
+ displayName: 'Align left',
986
+ },
987
+ {
988
+ value: 'center',
989
+ displayName: 'Align center',
990
+ },
991
+ {
992
+ value: 'end',
993
+ displayName: 'Align right',
994
+ },
995
+ ],
996
+ },
997
+ type: 'Text',
998
+ group: 'style',
999
+ description: 'The horizontal alignment of the column',
1000
+ defaultValue: 'center',
1001
+ displayName: 'Vertical alignment',
1002
+ },
1003
+ cfHorizontalAlignment: {
1004
+ validations: {
1005
+ in: [
1006
+ {
1007
+ value: 'start',
1008
+ displayName: 'Align top',
1009
+ },
1010
+ {
1011
+ value: 'center',
1012
+ displayName: 'Align center',
1013
+ },
1014
+ {
1015
+ value: 'end',
1016
+ displayName: 'Align bottom',
1017
+ },
1018
+ ],
1019
+ },
1020
+ type: 'Text',
1021
+ group: 'style',
1022
+ description: 'The horizontal alignment of the column',
1023
+ defaultValue: 'center',
1024
+ displayName: 'Horizontal alignment',
1025
+ },
1026
+ cfPadding: {
1027
+ displayName: 'Padding',
1028
+ type: 'Text',
1029
+ group: 'style',
1030
+ description: 'The padding of the column',
1031
+ defaultValue: '0 0 0 0',
1032
+ },
1033
+ cfBackgroundColor: {
1034
+ displayName: 'Background color',
1035
+ type: 'Text',
1036
+ group: 'style',
1037
+ description: 'The background color of the column',
1038
+ defaultValue: 'rgba(255, 255, 255, 0)',
1039
+ },
1040
+ cfFlexDirection: {
1041
+ displayName: 'Direction',
1042
+ type: 'Text',
1043
+ group: 'style',
1044
+ description: 'The orientation of the column',
1045
+ defaultValue: 'column',
1046
+ },
1047
+ cfFlexWrap: {
1048
+ displayName: 'Wrap objects',
1049
+ type: 'Text',
1050
+ group: 'style',
1051
+ description: 'Wrap objects',
1052
+ defaultValue: 'nowrap',
1053
+ },
1054
+ cfBorder: {
1055
+ displayName: 'Border',
1056
+ type: 'Text',
1057
+ group: 'style',
1058
+ description: 'The border of the column',
1059
+ defaultValue: '0px solid rgba(0, 0, 0, 0)',
1060
+ },
1061
+ cfBorderRadius: {
1062
+ displayName: 'Border Radius',
1063
+ type: 'Text',
1064
+ group: 'style',
1065
+ description: 'The border radius of the column',
1066
+ defaultValue: '0px',
1067
+ },
1068
+ cfGap: {
1069
+ displayName: 'Gap',
1070
+ type: 'Text',
1071
+ group: 'style',
1072
+ description: 'The spacing between the elements of the column',
1073
+ defaultValue: '0px',
1074
+ },
1075
+ cfColumnSpan: {
1076
+ type: 'Text',
1077
+ defaultValue: '6',
1078
+ group: 'style',
1079
+ },
1080
+ cfColumnSpanLock: {
1081
+ type: 'Boolean',
1082
+ defaultValue: false,
1083
+ group: 'style',
1084
+ },
1085
+ };
1086
+ const columnsBuiltInStyles = {
1087
+ cfBackgroundImageUrl: optionalBuiltInStyles.cfBackgroundImageUrl,
1088
+ cfBackgroundImageOptions: optionalBuiltInStyles.cfBackgroundImageOptions,
1089
+ cfMargin: {
1090
+ displayName: 'Margin',
1091
+ type: 'Text',
1092
+ group: 'style',
1093
+ description: 'The margin of the columns',
1094
+ defaultValue: '0 0 0 0',
1095
+ },
1096
+ cfWidth: {
1097
+ displayName: 'Width',
1098
+ type: 'Text',
1099
+ group: 'style',
1100
+ description: 'The width of the columns',
1101
+ defaultValue: 'fill',
1102
+ },
1103
+ cfMaxWidth: {
1104
+ displayName: 'Max width',
1105
+ type: 'Text',
1106
+ group: 'style',
1107
+ description: 'The max-width of the columns',
1108
+ defaultValue: '1192px',
1109
+ },
1110
+ cfPadding: {
1111
+ displayName: 'Padding',
1112
+ type: 'Text',
1113
+ group: 'style',
1114
+ description: 'The padding of the columns',
1115
+ defaultValue: '10px 10px 10px 10px',
1116
+ },
1117
+ cfBackgroundColor: {
1118
+ displayName: 'Background color',
1119
+ type: 'Text',
1120
+ group: 'style',
1121
+ description: 'The background color of the columns',
1122
+ defaultValue: 'rgba(255, 255, 255, 0)',
1123
+ },
1124
+ cfBorder: {
1125
+ displayName: 'Border',
1126
+ type: 'Text',
1127
+ group: 'style',
1128
+ description: 'The border of the columns',
1129
+ defaultValue: '0px solid rgba(0, 0, 0, 0)',
1130
+ },
1131
+ cfBorderRadius: {
1132
+ displayName: 'Border Radius',
1133
+ type: 'Text',
1134
+ group: 'style',
1135
+ description: 'The border radius of the columns',
1136
+ defaultValue: '0px',
1137
+ },
1138
+ cfGap: {
1139
+ displayName: 'Gap',
1140
+ type: 'Text',
1141
+ group: 'style',
1142
+ description: 'The spacing between the elements of the columns',
1143
+ defaultValue: '10px 10px',
1144
+ },
1145
+ cfColumns: {
1146
+ type: 'Text',
1147
+ defaultValue: '[6,6]',
1148
+ group: 'style',
1149
+ },
1150
+ cfWrapColumns: {
1151
+ type: 'Boolean',
1152
+ defaultValue: false,
1153
+ group: 'style',
1154
+ },
1155
+ cfWrapColumnsCount: {
1156
+ type: 'Text',
1157
+ defaultValue: '2',
1158
+ group: 'style',
1159
+ },
1160
+ };
1161
+
1162
+ const designTokensRegistry = {};
1163
+ /**
1164
+ * Register design tokens styling
1165
+ * @param designTokenDefinition - {[key:string]: Record<string, string>}
1166
+ * @returns void
1167
+ */
1168
+ const defineDesignTokens = (designTokenDefinition) => {
1169
+ Object.assign(designTokensRegistry, designTokenDefinition);
1170
+ };
1171
+ const templateStringRegex = /\${(.+?)}/g;
1172
+ const getDesignTokenRegistration = (breakpointValue, variableName) => {
1173
+ if (!breakpointValue)
1174
+ return breakpointValue;
1175
+ let resolvedValue = '';
1176
+ for (const part of breakpointValue.split(' ')) {
1177
+ const tokenValue = templateStringRegex.test(part)
1178
+ ? resolveSimpleDesignToken(part, variableName)
1179
+ : part;
1180
+ resolvedValue += `${tokenValue} `;
1181
+ }
1182
+ // Not trimming would end up with a trailing space that breaks the check in `calculateNodeDefaultHeight`
1183
+ return resolvedValue.trim();
1184
+ };
1185
+ const resolveSimpleDesignToken = (templateString, variableName) => {
1186
+ const nonTemplateValue = templateString.replace(templateStringRegex, '$1');
1187
+ const [tokenCategory, tokenName] = nonTemplateValue.split('.');
1188
+ const tokenValues = designTokensRegistry[tokenCategory];
1189
+ if (tokenValues && tokenValues[tokenName]) {
1190
+ if (variableName === 'cfBorder') {
1191
+ const { width, style, color } = tokenValues[tokenName];
1192
+ return `${width} ${style} ${color}`;
1193
+ }
1194
+ return tokenValues[tokenName];
1195
+ }
1196
+ if (builtInStyles[variableName]) {
1197
+ return builtInStyles[variableName].defaultValue;
1198
+ }
1199
+ if (optionalBuiltInStyles[variableName]) {
1200
+ return optionalBuiltInStyles[variableName].defaultValue;
1201
+ }
1202
+ return '0px';
1203
+ };
1204
+
1205
+ const MEDIA_QUERY_REGEXP = /(<|>)(\d{1,})(px|cm|mm|in|pt|pc)$/;
1206
+ const toCSSMediaQuery = ({ query }) => {
1207
+ if (query === '*')
1208
+ return undefined;
1209
+ const match = query.match(MEDIA_QUERY_REGEXP);
1210
+ if (!match)
1211
+ return undefined;
1212
+ const [, operator, value, unit] = match;
1213
+ if (operator === '<') {
1214
+ const maxScreenWidth = Number(value) - 1;
1215
+ return `(max-width: ${maxScreenWidth}${unit})`;
1216
+ }
1217
+ else if (operator === '>') {
1218
+ const minScreenWidth = Number(value) + 1;
1219
+ return `(min-width: ${minScreenWidth}${unit})`;
1220
+ }
1221
+ return undefined;
1222
+ };
1223
+ // Remove this helper when upgrading to TypeScript 5.0 - https://github.com/microsoft/TypeScript/issues/48829
1224
+ const findLast = (array, predicate) => {
1225
+ return array.reverse().find(predicate);
1226
+ };
1227
+ // Initialise media query matchers. This won't include the always matching fallback breakpoint.
1228
+ const mediaQueryMatcher = (breakpoints) => {
1229
+ const mediaQueryMatches = {};
1230
+ const mediaQueryMatchers = breakpoints
1231
+ .map((breakpoint) => {
1232
+ const cssMediaQuery = toCSSMediaQuery(breakpoint);
1233
+ if (!cssMediaQuery)
1234
+ return undefined;
1235
+ if (typeof window === 'undefined')
1236
+ return undefined;
1237
+ const mediaQueryMatcher = window.matchMedia(cssMediaQuery);
1238
+ mediaQueryMatches[breakpoint.id] = mediaQueryMatcher.matches;
1239
+ return { id: breakpoint.id, signal: mediaQueryMatcher };
1240
+ })
1241
+ .filter((matcher) => !!matcher);
1242
+ return [mediaQueryMatchers, mediaQueryMatches];
1243
+ };
1244
+ const getActiveBreakpointIndex = (breakpoints, mediaQueryMatches, fallbackBreakpointIndex) => {
1245
+ // The breakpoints are ordered (desktop-first: descending by screen width)
1246
+ const breakpointsWithMatches = breakpoints.map(({ id }, index) => ({
1247
+ id,
1248
+ index,
1249
+ // The fallback breakpoint with wildcard query will always match
1250
+ isMatch: mediaQueryMatches[id] ?? index === fallbackBreakpointIndex,
1251
+ }));
1252
+ // Find the last breakpoint in the list that matches (desktop-first: the narrowest one)
1253
+ const mostSpecificIndex = findLast(breakpointsWithMatches, ({ isMatch }) => isMatch)?.index;
1254
+ return mostSpecificIndex ?? fallbackBreakpointIndex;
1255
+ };
1256
+ const getFallbackBreakpointIndex = (breakpoints) => {
1257
+ // We assume that there will be a single breakpoint which uses the wildcard query.
1258
+ // If there is none, we just take the first one in the list.
1259
+ return Math.max(breakpoints.findIndex(({ query }) => query === '*'), 0);
1260
+ };
1261
+ const builtInStylesWithDesignTokens = [
1262
+ 'cfMargin',
1263
+ 'cfPadding',
1264
+ 'cfGap',
1265
+ 'cfWidth',
1266
+ 'cfHeight',
1267
+ 'cfBackgroundColor',
1268
+ 'cfBorder',
1269
+ 'cfBorderRadius',
1270
+ 'cfFontSize',
1271
+ 'cfLineHeight',
1272
+ 'cfLetterSpacing',
1273
+ 'cfTextColor',
1274
+ ];
1275
+ const getValueForBreakpoint = (valuesByBreakpoint, breakpoints, activeBreakpointIndex, variableName) => {
1276
+ const eventuallyResolveDesignTokens = (value) => {
1277
+ // For some built-in design propertier, we support design tokens
1278
+ if (builtInStylesWithDesignTokens.includes(variableName)) {
1279
+ return getDesignTokenRegistration(value, variableName);
1280
+ }
1281
+ // For all other properties, we just return the breakpoint-specific value
1282
+ return value;
1283
+ };
1284
+ if (valuesByBreakpoint instanceof Object) {
1285
+ // Assume that the values are sorted by media query to apply the cascading CSS logic
1286
+ for (let index = activeBreakpointIndex; index >= 0; index--) {
1287
+ const breakpointId = breakpoints[index].id;
1288
+ if (valuesByBreakpoint[breakpointId]) {
1289
+ // If the value is defined, we use it and stop the breakpoints cascade
1290
+ return eventuallyResolveDesignTokens(valuesByBreakpoint[breakpointId]);
1291
+ }
1292
+ }
1293
+ // If no breakpoint matched, we search and apply the fallback breakpoint
1294
+ const fallbackBreakpointIndex = getFallbackBreakpointIndex(breakpoints);
1295
+ const fallbackBreakpointId = breakpoints[fallbackBreakpointIndex].id;
1296
+ return eventuallyResolveDesignTokens(valuesByBreakpoint[fallbackBreakpointId]);
1297
+ }
1298
+ else {
1299
+ // Old design properties did not support breakpoints, keep for backward compatibility
1300
+ return valuesByBreakpoint;
1301
+ }
1302
+ };
1303
+
1304
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1305
+ const isLinkToAsset = (variable) => {
1306
+ if (!variable)
1307
+ return false;
1308
+ if (typeof variable !== 'object')
1309
+ return false;
1310
+ return (variable.sys?.linkType === 'Asset' &&
1311
+ typeof variable.sys?.id === 'string' &&
1312
+ !!variable.sys?.id &&
1313
+ variable.sys?.type === 'Link');
1314
+ };
1315
+
1316
+ const isLink = (maybeLink) => {
1317
+ if (maybeLink === null)
1318
+ return false;
1319
+ if (typeof maybeLink !== 'object')
1320
+ return false;
1321
+ const link = maybeLink;
1322
+ return Boolean(link.sys?.id) && link.sys?.type === 'Link';
1323
+ };
1324
+
1325
+ /**
1326
+ * This module encapsulates format of the path to a deep reference.
1327
+ */
1328
+ const parseDataSourcePathIntoFieldset = (path) => {
1329
+ const parsedPath = parseDeepPath(path);
1330
+ if (null === parsedPath) {
1331
+ throw new Error(`Cannot parse path '${path}' as deep path`);
1332
+ }
1333
+ return parsedPath.fields.map((field) => [null, field, '~locale']);
1334
+ };
1335
+ /**
1336
+ * Parse path into components, supports L1 references (one reference follow) atm.
1337
+ * @param path from data source. eg. `/uuid123/fields/image/~locale/fields/file/~locale`
1338
+ * eg. `/uuid123/fields/file/~locale/fields/title/~locale`
1339
+ * @returns
1340
+ */
1341
+ const parseDataSourcePathWithL1DeepBindings = (path) => {
1342
+ const parsedPath = parseDeepPath(path);
1343
+ if (null === parsedPath) {
1344
+ throw new Error(`Cannot parse path '${path}' as deep path`);
1345
+ }
1346
+ return {
1347
+ key: parsedPath.key,
1348
+ field: parsedPath.fields[0],
1349
+ referentField: parsedPath.fields[1],
1350
+ };
1351
+ };
1352
+ /**
1353
+ * Detects if paths is valid deep-path, like:
1354
+ * - /gV6yKXp61hfYrR7rEyKxY/fields/mainStory/~locale/fields/cover/~locale/fields/title/~locale
1355
+ * or regular, like:
1356
+ * - /6J8eA60yXwdm5eyUh9fX6/fields/mainStory/~locale
1357
+ * @returns
1358
+ */
1359
+ const isDeepPath = (deepPathCandidate) => {
1360
+ const deepPathParsed = parseDeepPath(deepPathCandidate);
1361
+ if (!deepPathParsed) {
1362
+ return false;
1363
+ }
1364
+ return deepPathParsed.fields.length > 1;
1365
+ };
1366
+ const parseDeepPath = (deepPathCandidate) => {
1367
+ // ALGORITHM:
1368
+ // We start with deep path in form:
1369
+ // /uuid123/fields/mainStory/~locale/fields/cover/~locale/fields/title/~locale
1370
+ // First turn string into array of segments
1371
+ // ['', 'uuid123', 'fields', 'mainStory', '~locale', 'fields', 'cover', '~locale', 'fields', 'title', '~locale']
1372
+ // Then group segments into intermediate represenatation - chunks, where each non-initial chunk starts with 'fields'
1373
+ // [
1374
+ // [ "", "uuid123" ],
1375
+ // [ "fields", "mainStory", "~locale" ],
1376
+ // [ "fields", "cover", "~locale" ],
1377
+ // [ "fields", "title", "~locale" ]
1378
+ // ]
1379
+ // Then check "initial" chunk for corretness
1380
+ // Then check all "field-leading" chunks for correctness
1381
+ const isValidInitialChunk = (initialChunk) => {
1382
+ // must have start with '' and have at least 2 segments, second non-empty
1383
+ // eg. /-_432uuid123123
1384
+ return /^\/([^/^~]+)$/.test(initialChunk.join('/'));
1385
+ };
1386
+ const isValidFieldChunk = (fieldChunk) => {
1387
+ // must start with 'fields' and have at least 3 segments, second non-empty and last segment must be '~locale'
1388
+ // eg. fields/-32234mainStory/~locale
1389
+ return /^fields\/[^/^~]+\/~locale$/.test(fieldChunk.join('/'));
1390
+ };
1391
+ const deepPathSegments = deepPathCandidate.split('/');
1392
+ const chunks = chunkSegments(deepPathSegments, { startNextChunkOnElementEqualTo: 'fields' });
1393
+ if (chunks.length <= 1) {
1394
+ return null; // malformed path, even regular paths have at least 2 chunks
1395
+ }
1396
+ else if (chunks.length === 2) {
1397
+ return null; // deep paths have at least 3 chunks
1398
+ }
1399
+ // With 3+ chunks we can now check for deep path correctness
1400
+ const [initialChunk, ...fieldChunks] = chunks;
1401
+ if (!isValidInitialChunk(initialChunk)) {
1402
+ return null;
1403
+ }
1404
+ if (!fieldChunks.every(isValidFieldChunk)) {
1405
+ return null;
1406
+ }
1407
+ return {
1408
+ key: initialChunk[1], // pick uuid from initial chunk ['','uuid123'],
1409
+ fields: fieldChunks.map((fieldChunk) => fieldChunk[1]), // pick only fieldName eg. from ['fields','mainStory', '~locale'] we pick `mainStory`
1410
+ };
1411
+ };
1412
+ const chunkSegments = (segments, { startNextChunkOnElementEqualTo }) => {
1413
+ const chunks = [];
1414
+ let currentChunk = [];
1415
+ const isSegmentBeginningOfChunk = (segment) => segment === startNextChunkOnElementEqualTo;
1416
+ const excludeEmptyChunks = (chunk) => chunk.length > 0;
1417
+ for (let i = 0; i < segments.length; i++) {
1418
+ const isInitialElement = i === 0;
1419
+ const segment = segments[i];
1420
+ if (isInitialElement) {
1421
+ currentChunk = [segment];
1422
+ }
1423
+ else if (isSegmentBeginningOfChunk(segment)) {
1424
+ chunks.push(currentChunk);
1425
+ currentChunk = [segment];
1426
+ }
1427
+ else {
1428
+ currentChunk.push(segment);
1429
+ }
1430
+ }
1431
+ chunks.push(currentChunk);
1432
+ return chunks.filter(excludeEmptyChunks);
1433
+ };
1434
+
1435
+ const sectionDefinition = {
1436
+ id: CONTENTFUL_COMPONENTS.section.id,
1437
+ name: CONTENTFUL_COMPONENTS.section.name,
1438
+ category: CONTENTFUL_COMPONENT_CATEGORY,
1439
+ children: true,
1440
+ variables: sectionBuiltInStyles,
1441
+ tooltip: {
1442
+ description: 'Create a new full width section of your experience by dragging this component onto the canvas. Other components and patterns can be added into a section.',
1443
+ },
1444
+ };
1445
+ const containerDefinition = {
1446
+ id: CONTENTFUL_COMPONENTS.container.id,
1447
+ name: CONTENTFUL_COMPONENTS.container.name,
1448
+ category: CONTENTFUL_COMPONENT_CATEGORY,
1449
+ children: true,
1450
+ variables: containerBuiltInStyles,
1451
+ tooltip: {
1452
+ description: 'Create a new area or pattern within your page layout by dragging a container onto the canvas. Other components and patterns can be added into a container.',
1453
+ },
1454
+ };
1455
+ const columnsDefinition = {
1456
+ id: CONTENTFUL_COMPONENTS.columns.id,
1457
+ name: CONTENTFUL_COMPONENTS.columns.name,
1458
+ category: CONTENTFUL_COMPONENT_CATEGORY,
1459
+ children: true,
1460
+ variables: columnsBuiltInStyles,
1461
+ tooltip: {
1462
+ description: 'Add columns to a container to create your desired layout and ensure that the experience is responsive across different screen sizes.',
1463
+ },
1464
+ };
1465
+ const singleColumnDefinition = {
1466
+ id: CONTENTFUL_COMPONENTS.singleColumn.id,
1467
+ name: CONTENTFUL_COMPONENTS.singleColumn.name,
1468
+ category: CONTENTFUL_COMPONENT_CATEGORY,
1469
+ children: true,
1470
+ variables: singleColumnBuiltInStyles,
1471
+ };
1472
+
1473
+ const sendMessage = (eventType, data) => {
1474
+ if (typeof window === 'undefined') {
1475
+ return;
1476
+ }
1477
+ console.debug(`[experiences-sdk-react::sendMessage] Sending message [${eventType}]`, {
1478
+ source: 'customer-app',
1479
+ eventType,
1480
+ payload: data,
1481
+ });
1482
+ window.parent?.postMessage({
1483
+ source: 'customer-app',
1484
+ eventType,
1485
+ payload: data,
1486
+ }, '*');
1487
+ };
1488
+
1489
+ /**
1490
+ * Base Store for entities
1491
+ * Can be extended for the different loading behaviours (editor, production, ..)
1492
+ */
1493
+ class EntityStoreBase {
1494
+ constructor({ entities, locale }) {
1495
+ this.entryMap = new Map();
1496
+ this.assetMap = new Map();
1497
+ this.locale = locale;
1498
+ for (const entity of entities) {
1499
+ this.addEntity(entity);
1500
+ }
1501
+ }
1502
+ get entities() {
1503
+ return [...this.entryMap.values(), ...this.assetMap.values()];
1504
+ }
1505
+ updateEntity(entity) {
1506
+ this.addEntity(entity);
1507
+ }
1508
+ getEntryOrAsset(linkOrEntryOrAsset, path) {
1509
+ if (isDeepPath(path)) {
1510
+ return this.getDeepEntry(linkOrEntryOrAsset, path);
1511
+ }
1512
+ let entity;
1513
+ if (isLink(linkOrEntryOrAsset)) {
1514
+ const resolvedEntity = linkOrEntryOrAsset.sys.linkType === 'Entry'
1515
+ ? this.entryMap.get(linkOrEntryOrAsset.sys.id)
1516
+ : this.assetMap.get(linkOrEntryOrAsset.sys.id);
1517
+ if (!resolvedEntity || resolvedEntity.sys.type !== linkOrEntryOrAsset.sys.linkType) {
1518
+ console.warn(`Experience references unresolved entity: ${JSON.stringify(linkOrEntryOrAsset)}`);
1519
+ return;
1520
+ }
1521
+ entity = resolvedEntity;
1522
+ }
1523
+ else {
1524
+ // We already have the complete entity in preview & delivery (resolved by the CMA client)
1525
+ entity = linkOrEntryOrAsset;
1526
+ }
1527
+ return entity;
1528
+ }
1529
+ /**
1530
+ * @deprecated in the base class this should be simply an abstract method
1531
+ * @param entityLink
1532
+ * @param path
1533
+ * @returns
1534
+ */
1535
+ getValue(entityLink, path) {
1536
+ const entity = this.getEntity(entityLink.sys.linkType, entityLink.sys.id);
1537
+ if (!entity) {
1538
+ // TODO: move to `debug` utils once it is extracted
1539
+ console.warn(`Unresolved entity reference: ${entityLink.sys.linkType} with ID ${entityLink.sys.id}`);
1540
+ return;
1541
+ }
1542
+ return get(entity, path);
1543
+ }
1544
+ getEntityFromLink(link) {
1545
+ const resolvedEntity = link.sys.linkType === 'Entry'
1546
+ ? this.entryMap.get(link.sys.id)
1547
+ : this.assetMap.get(link.sys.id);
1548
+ if (!resolvedEntity || resolvedEntity.sys.type !== link.sys.linkType) {
1549
+ console.warn(`Experience references unresolved entity: ${JSON.stringify(link)}`);
1550
+ return;
1551
+ }
1552
+ return resolvedEntity;
1553
+ }
1554
+ getEntitiesFromMap(type, ids) {
1555
+ const resolved = [];
1556
+ const missing = [];
1557
+ for (const id of ids) {
1558
+ const entity = this.getEntity(type, id);
1559
+ if (entity) {
1560
+ resolved.push(entity);
1561
+ }
1562
+ else {
1563
+ missing.push(id);
1564
+ }
1565
+ }
1566
+ return {
1567
+ resolved,
1568
+ missing,
1569
+ };
1570
+ }
1571
+ addEntity(entity) {
1572
+ if (this.isAsset(entity)) {
1573
+ this.assetMap.set(entity.sys.id, entity);
1574
+ }
1575
+ else {
1576
+ this.entryMap.set(entity.sys.id, entity);
1577
+ }
1578
+ }
1579
+ async fetchAsset(id) {
1580
+ const { resolved, missing } = this.getEntitiesFromMap('Asset', [id]);
1581
+ if (missing.length) {
1582
+ // TODO: move to `debug` utils once it is extracted
1583
+ console.warn(`Asset "${id}" is not in the store`);
1584
+ return;
1585
+ }
1586
+ return resolved[0];
1587
+ }
1588
+ async fetchAssets(ids) {
1589
+ const { resolved, missing } = this.getEntitiesFromMap('Asset', ids);
1590
+ if (missing.length) {
1591
+ throw new Error(`Missing assets in the store (${missing.join(',')})`);
1592
+ }
1593
+ return resolved;
1594
+ }
1595
+ async fetchEntry(id) {
1596
+ const { resolved, missing } = this.getEntitiesFromMap('Entry', [id]);
1597
+ if (missing.length) {
1598
+ // TODO: move to `debug` utils once it is extracted
1599
+ console.warn(`Entry "${id}" is not in the store`);
1600
+ return;
1601
+ }
1602
+ return resolved[0];
1603
+ }
1604
+ async fetchEntries(ids) {
1605
+ const { resolved, missing } = this.getEntitiesFromMap('Entry', ids);
1606
+ if (missing.length) {
1607
+ throw new Error(`Missing assets in the store (${missing.join(',')})`);
1608
+ }
1609
+ return resolved;
1610
+ }
1611
+ getDeepEntry(linkOrEntryOrAsset, path) {
1612
+ const resolveFieldset = (unresolvedFieldset, headEntry) => {
1613
+ const resolvedFieldset = [];
1614
+ let entityToResolveFieldsFrom = headEntry;
1615
+ for (let i = 0; i < unresolvedFieldset.length; i++) {
1616
+ const isLeaf = i === unresolvedFieldset.length - 1; // with last row, we are not expecting a link, but a value
1617
+ const row = unresolvedFieldset[i];
1618
+ const [, field, _localeQualifier] = row;
1619
+ if (!entityToResolveFieldsFrom) {
1620
+ throw new Error(`Logic Error: Cannot resolve field ${field} of a fieldset as there is no entity to resolve it from.`);
1621
+ }
1622
+ if (isLeaf) {
1623
+ resolvedFieldset.push([entityToResolveFieldsFrom, field, _localeQualifier]);
1624
+ break;
1625
+ }
1626
+ const fieldValue = get(entityToResolveFieldsFrom, ['fields', field]);
1627
+ if (undefined === fieldValue) {
1628
+ return {
1629
+ resolvedFieldset,
1630
+ isFullyResolved: false,
1631
+ reason: `Cannot resolve field Link<${entityToResolveFieldsFrom.sys.type}>(sys.id=${entityToResolveFieldsFrom.sys.id}).fields[${field}] as field value is not defined`,
1632
+ };
1633
+ }
1634
+ else if (isLink(fieldValue)) {
1635
+ const entity = this.getEntityFromLink(fieldValue);
1636
+ if (entity === undefined) {
1637
+ return {
1638
+ resolvedFieldset,
1639
+ isFullyResolved: false,
1640
+ reason: `Field reference Link (sys.id=${fieldValue.sys.id}) not found in the EntityStore, waiting...`,
1641
+ };
1642
+ }
1643
+ resolvedFieldset.push([entityToResolveFieldsFrom, field, _localeQualifier]);
1644
+ entityToResolveFieldsFrom = entity; // we move up
1645
+ }
1646
+ else {
1647
+ // TODO: Eg. when someone changed the schema and the field is not a link anymore, what should we return then?
1648
+ throw new Error(`LogicError: Invalid value of a field we consider a reference field. Cannot resolve field ${field} of a fieldset as it is not a link, neither undefined.`);
1649
+ }
1650
+ }
1651
+ return {
1652
+ resolvedFieldset,
1653
+ isFullyResolved: true,
1654
+ };
1655
+ };
1656
+ const headEntity = isLink(linkOrEntryOrAsset)
1657
+ ? this.getEntityFromLink(linkOrEntryOrAsset)
1658
+ : linkOrEntryOrAsset;
1659
+ if (undefined === headEntity) {
1660
+ return;
1661
+ }
1662
+ const unresolvedFieldset = parseDataSourcePathIntoFieldset(path);
1663
+ // The purpose here is to take this intermediate representation of the deep-path
1664
+ // and to follow the links to the leaf-entity and field
1665
+ // in case we can't follow till the end, we should signal that there was null-reference in the path
1666
+ const { resolvedFieldset, isFullyResolved, reason } = resolveFieldset(unresolvedFieldset, headEntity);
1667
+ if (!isFullyResolved) {
1668
+ reason &&
1669
+ console.debug(`[exp-builder.sdk::EntityStoreBased::getValueDeep()] Deep path wasn't resolved till leaf node, falling back to undefined, because: ${reason}`);
1670
+ return;
1671
+ }
1672
+ const [leafEntity] = resolvedFieldset[resolvedFieldset.length - 1];
1673
+ return leafEntity;
1674
+ }
1675
+ isAsset(entity) {
1676
+ return entity.sys.type === 'Asset';
1677
+ }
1678
+ getEntity(type, id) {
1679
+ if (type === 'Asset') {
1680
+ return this.assetMap.get(id);
1681
+ }
1682
+ return this.entryMap.get(id);
1683
+ }
1684
+ toJSON() {
1685
+ return {
1686
+ entryMap: Object.fromEntries(this.entryMap),
1687
+ assetMap: Object.fromEntries(this.assetMap),
1688
+ locale: this.locale,
1689
+ };
1690
+ }
1691
+ }
1692
+
1693
+ /**
1694
+ * EntityStore which resolves entries and assets from the editor
1695
+ * over the sendMessage and subscribe functions.
1696
+ */
1697
+ class EditorEntityStore extends EntityStoreBase {
1698
+ constructor({ entities, locale, sendMessage, subscribe, timeoutDuration = 3000, }) {
1699
+ super({ entities, locale });
1700
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1701
+ this.requestCache = new Map();
1702
+ this.cacheIdSeperator = ',';
1703
+ this.sendMessage = sendMessage;
1704
+ this.subscribe = subscribe;
1705
+ this.timeoutDuration = timeoutDuration;
1706
+ }
1707
+ cleanupPromise(referenceId) {
1708
+ setTimeout(() => {
1709
+ this.requestCache.delete(referenceId);
1710
+ }, 300);
1711
+ }
1712
+ getCacheId(id) {
1713
+ return id.length === 1 ? id[0] : id.join(this.cacheIdSeperator);
1714
+ }
1715
+ async fetchEntity(type, ids, skipCache = false) {
1716
+ let missing;
1717
+ if (!skipCache) {
1718
+ const { missing: missingFromCache, resolved } = this.getEntitiesFromMap(type, ids);
1719
+ if (missingFromCache.length === 0) {
1720
+ // everything is already in cache
1721
+ return resolved;
1722
+ }
1723
+ missing = missingFromCache;
1724
+ }
1725
+ else {
1726
+ missing = [...ids];
1727
+ }
1728
+ const cacheId = this.getCacheId(missing);
1729
+ const openRequest = this.requestCache.get(cacheId);
1730
+ if (openRequest) {
1731
+ return openRequest;
1732
+ }
1733
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1734
+ const newPromise = new Promise((resolve, reject) => {
1735
+ const unsubscribe = this.subscribe(PostMessageMethods.REQUESTED_ENTITIES, (message) => {
1736
+ const messageIds = [
1737
+ ...message.entities.map((entity) => entity.sys.id),
1738
+ ...(message.missingEntityIds ?? []),
1739
+ ];
1740
+ if (missing.every((id) => messageIds.find((entityId) => entityId === id))) {
1741
+ clearTimeout(timeout);
1742
+ resolve(message.entities);
1743
+ this.cleanupPromise(cacheId);
1744
+ ids.forEach((id) => this.cleanupPromise(id));
1745
+ unsubscribe();
1746
+ }
1747
+ else {
1748
+ console.warn('Unexpected entities received in REQUESTED_ENTITIES. Ignoring this response.');
1749
+ }
1750
+ });
1751
+ const timeout = setTimeout(() => {
1752
+ reject(new Error(`Request for entities timed out ${this.timeoutDuration}ms} for ${cacheId}`));
1753
+ this.cleanupPromise(cacheId);
1754
+ ids.forEach((id) => this.cleanupPromise(id));
1755
+ unsubscribe();
1756
+ }, this.timeoutDuration);
1757
+ this.sendMessage(PostMessageMethods.REQUEST_ENTITIES, {
1758
+ entityIds: missing,
1759
+ entityType: type,
1760
+ locale: this.locale,
1761
+ });
1762
+ });
1763
+ this.requestCache.set(cacheId, newPromise);
1764
+ ids.forEach((cid) => {
1765
+ this.requestCache.set(cid, newPromise);
1766
+ });
1767
+ const result = (await newPromise);
1768
+ result.forEach((value) => {
1769
+ this.addEntity(value);
1770
+ });
1771
+ return this.getEntitiesFromMap(type, ids).resolved;
1772
+ }
1773
+ async fetchAsset(id, skipCache = false) {
1774
+ try {
1775
+ return (await this.fetchAssets([id], skipCache))[0];
1776
+ }
1777
+ catch (err) {
1778
+ // TODO: move to debug utils once it is extracted
1779
+ console.warn(`Failed to request asset ${id}`);
1780
+ return undefined;
1781
+ }
1782
+ }
1783
+ fetchAssets(ids, skipCache = false) {
1784
+ return this.fetchEntity('Asset', ids, skipCache);
1785
+ }
1786
+ async fetchEntry(id, skipCache = false) {
1787
+ try {
1788
+ return (await this.fetchEntries([id], skipCache))[0];
1789
+ }
1790
+ catch (err) {
1791
+ // TODO: move to debug utils once it is extracted
1792
+ console.warn(`Failed to request entry ${id}`, err);
1793
+ return undefined;
1794
+ }
1795
+ }
1796
+ fetchEntries(ids, skipCache = false) {
1797
+ return this.fetchEntity('Entry', ids, skipCache);
1798
+ }
1799
+ }
1800
+
1801
+ function transformAssetFileToUrl(fieldValue) {
1802
+ return fieldValue && typeof fieldValue == 'object' && fieldValue.url
1803
+ ? fieldValue.url
1804
+ : fieldValue;
1805
+ }
1806
+
1807
+ // The default of 3s in the EditorEntityStore is sometimes timing out and
1808
+ // leads to not rendering bound content and assemblies.
1809
+ const REQUEST_TIMEOUT = 10000;
1810
+ class EditorModeEntityStore extends EditorEntityStore {
1811
+ constructor({ entities, locale }) {
1812
+ console.debug(`[experiences-sdk-react] Initializing editor entity store with ${entities.length} entities for locale ${locale}.`, { entities });
1813
+ const subscribe = (method, cb) => {
1814
+ const handleMessage = (event) => {
1815
+ const data = JSON.parse(event.data);
1816
+ if (typeof data !== 'object' || !data)
1817
+ return;
1818
+ if (data.source !== 'composability-app')
1819
+ return;
1820
+ if (data.eventType === method) {
1821
+ cb(data.payload);
1822
+ }
1823
+ };
1824
+ if (typeof window !== 'undefined') {
1825
+ window.addEventListener('message', handleMessage);
1826
+ }
1827
+ return () => {
1828
+ if (typeof window !== 'undefined') {
1829
+ window.removeEventListener('message', handleMessage);
1830
+ }
1831
+ };
1832
+ };
1833
+ super({ entities, sendMessage, subscribe, locale, timeoutDuration: REQUEST_TIMEOUT });
1834
+ this.locale = locale;
1835
+ }
1836
+ /**
1837
+ * This function collects and returns the list of requested entries and assets. Additionally, it checks
1838
+ * upfront whether any async fetching logic is actually happening. If not, it returns a plain `false` value, so we
1839
+ * can detect this early and avoid unnecessary re-renders.
1840
+ * @param entityLinks
1841
+ * @returns false if no async fetching is happening, otherwise a promise that resolves when all entities are fetched
1842
+ */
1843
+ async fetchEntities({ missingEntryIds, missingAssetIds, skipCache = false, }) {
1844
+ // Entries and assets will be stored in entryMap and assetMap
1845
+ await Promise.all([
1846
+ this.fetchEntries(missingEntryIds, skipCache),
1847
+ this.fetchAssets(missingAssetIds, skipCache),
1848
+ ]);
1849
+ }
1850
+ getMissingEntityIds(entityLinks) {
1851
+ const entryLinks = entityLinks.filter((link) => link.sys?.linkType === 'Entry');
1852
+ const assetLinks = entityLinks.filter((link) => link.sys?.linkType === 'Asset');
1853
+ const uniqueEntryIds = [...new Set(entryLinks.map((link) => link.sys.id))];
1854
+ const uniqueAssetIds = [...new Set(assetLinks.map((link) => link.sys.id))];
1855
+ const { missing: missingEntryIds } = this.getEntitiesFromMap('Entry', uniqueEntryIds);
1856
+ const { missing: missingAssetIds } = this.getEntitiesFromMap('Asset', uniqueAssetIds);
1857
+ return { missingEntryIds, missingAssetIds };
1858
+ }
1859
+ getValue(entityLinkOrEntity, path) {
1860
+ const entity = this.getEntryOrAsset(entityLinkOrEntity, path.join('/'));
1861
+ if (!entity) {
1862
+ return;
1863
+ }
1864
+ const fieldValue = get(entity, path);
1865
+ // walk around to render asset files
1866
+ return fieldValue && typeof fieldValue == 'object' && fieldValue.url
1867
+ ? fieldValue.url
1868
+ : fieldValue;
1869
+ }
1870
+ }
1871
+
1872
+ class EntityStore extends EntityStoreBase {
1873
+ constructor(options) {
1874
+ if (typeof options === 'string') {
1875
+ const data = JSON.parse(options);
1876
+ const { _experienceEntry, _unboundValues, locale, entryMap, assetMap } = data.entityStore;
1877
+ super({
1878
+ entities: [
1879
+ ...Object.values(entryMap),
1880
+ ...Object.values(assetMap),
1881
+ ],
1882
+ locale,
1883
+ });
1884
+ this._experienceEntry = _experienceEntry;
1885
+ this._unboundValues = _unboundValues;
1886
+ }
1887
+ else {
1888
+ const { experienceEntry, entities, locale } = options;
1889
+ super({ entities, locale });
1890
+ if (isExperienceEntry(experienceEntry)) {
1891
+ this._experienceEntry = experienceEntry.fields;
1892
+ this._unboundValues = experienceEntry.fields.unboundValues;
1893
+ }
1894
+ else {
1895
+ throw new Error('Provided entry is not experience entry');
1896
+ }
1897
+ }
1898
+ }
1899
+ getCurrentLocale() {
1900
+ return this.locale;
1901
+ }
1902
+ get experienceEntryFields() {
1903
+ return this._experienceEntry;
1904
+ }
1905
+ get schemaVersion() {
1906
+ return this._experienceEntry?.componentTree.schemaVersion;
1907
+ }
1908
+ get breakpoints() {
1909
+ return this._experienceEntry?.componentTree.breakpoints ?? [];
1910
+ }
1911
+ get dataSource() {
1912
+ return this._experienceEntry?.dataSource ?? {};
1913
+ }
1914
+ get unboundValues() {
1915
+ return this._unboundValues ?? {};
1916
+ }
1917
+ get usedComponents() {
1918
+ return this._experienceEntry?.usedComponents ?? [];
1919
+ }
1920
+ /**
1921
+ * Extend the existing set of unbound values with the ones from the assembly definition.
1922
+ * When creating a new assembly out of a container, the unbound value keys are copied and
1923
+ * thus the existing and the added ones have colliding keys. In the case of overlapping value
1924
+ * keys, the ones from the experience overrule the ones from the assembly definition as
1925
+ * the latter one is certainly just a default value while the other one is from the actual instance.
1926
+ * @param unboundValues set of unbound values defined in the assembly definition
1927
+ */
1928
+ addAssemblyUnboundValues(unboundValues) {
1929
+ this._unboundValues = { ...unboundValues, ...(this._unboundValues ?? {}) };
1930
+ }
1931
+ getValue(entityLinkOrEntity, path) {
1932
+ const entity = isLink(entityLinkOrEntity)
1933
+ ? this.getEntityFromLink(entityLinkOrEntity)
1934
+ : entityLinkOrEntity;
1935
+ if (entity === undefined) {
1936
+ return;
1937
+ }
1938
+ const fieldValue = get(entity, path);
1939
+ return transformAssetFileToUrl(fieldValue);
1940
+ }
1941
+ toJSON() {
1942
+ return {
1943
+ _experienceEntry: this._experienceEntry,
1944
+ _unboundValues: this._unboundValues,
1945
+ ...super.toJSON(),
1946
+ };
1947
+ }
1948
+ }
1949
+
1950
+ var VisualEditorMode;
1951
+ (function (VisualEditorMode) {
1952
+ VisualEditorMode["LazyLoad"] = "lazyLoad";
1953
+ VisualEditorMode["InjectScript"] = "injectScript";
1954
+ })(VisualEditorMode || (VisualEditorMode = {}));
1955
+
1956
+ function createExperience(options) {
1957
+ if (typeof options === 'string') {
1958
+ const entityStore = new EntityStore(options);
1959
+ return {
1960
+ entityStore,
1961
+ };
1962
+ }
1963
+ else {
1964
+ const { experienceEntry, referencedAssets, referencedEntries, locale } = options;
1965
+ if (!isExperienceEntry(experienceEntry)) {
1966
+ throw new Error('Provided entry is not experience entry');
1967
+ }
1968
+ const entityStore = new EntityStore({
1969
+ experienceEntry,
1970
+ entities: [...referencedEntries, ...referencedAssets],
1971
+ locale,
1972
+ });
1973
+ return {
1974
+ entityStore,
1975
+ };
1976
+ }
1977
+ }
1978
+
1979
+ const fetchExperienceEntry = async ({ client, experienceTypeId, locale, identifier, }) => {
1980
+ if (!client) {
1981
+ throw new Error('Failed to fetch experience entities. Required "client" parameter was not provided');
1982
+ }
1983
+ if (!locale) {
1984
+ throw new Error('Failed to fetch experience entities. Required "locale" parameter was not provided');
1985
+ }
1986
+ if (!experienceTypeId) {
1987
+ throw new Error('Failed to fetch experience entities. Required "experienceTypeId" parameter was not provided');
1988
+ }
1989
+ if (!identifier.slug && !identifier.id) {
1990
+ throw new Error(`Failed to fetch experience entities. At least one identifier must be provided. Received: ${JSON.stringify(identifier)}`);
1991
+ }
1992
+ const filter = identifier.slug ? { 'fields.slug': identifier.slug } : { 'sys.id': identifier.id };
1993
+ const entries = await client.getEntries({
1994
+ content_type: experienceTypeId,
1995
+ locale,
1996
+ ...filter,
1997
+ });
1998
+ if (entries.items.length > 1) {
1999
+ throw new Error(`More than one experience with identifier: ${JSON.stringify(identifier)} was found`);
2000
+ }
2001
+ return entries.items[0];
2002
+ };
2003
+
2004
+ function treeVisit(initialNode, onNode) {
2005
+ // returns last used index
2006
+ const _treeVisit = (currentNode, currentIndex, currentDepth) => {
2007
+ // Copy children in case of onNode removing it as we pass the node by reference
2008
+ const children = [...currentNode.children];
2009
+ onNode(currentNode, currentIndex, currentDepth);
2010
+ let nextAvailableIndex = currentIndex + 1;
2011
+ const lastUsedIndex = currentIndex;
2012
+ for (const child of children) {
2013
+ const lastUsedIndex = _treeVisit(child, nextAvailableIndex, currentDepth + 1);
2014
+ nextAvailableIndex = lastUsedIndex + 1;
2015
+ }
2016
+ return lastUsedIndex;
2017
+ };
2018
+ _treeVisit(initialNode, 0, 0);
2019
+ }
2020
+
2021
+ class DeepReference {
2022
+ constructor({ path, dataSource }) {
2023
+ const { key, field, referentField } = parseDataSourcePathWithL1DeepBindings(path);
2024
+ this.originalPath = path;
2025
+ this.entityId = dataSource[key].sys.id;
2026
+ this.entityLink = dataSource[key];
2027
+ this.field = field;
2028
+ this.referentField = referentField;
2029
+ }
2030
+ get headEntityId() {
2031
+ return this.entityId;
2032
+ }
2033
+ /**
2034
+ * Extracts referent from the path, using EntityStore as source of
2035
+ * entities during the resolution path.
2036
+ * TODO: should it be called `extractLeafReferent` ? or `followToLeafReferent`
2037
+ */
2038
+ extractReferent(entityStore) {
2039
+ const headEntity = entityStore.getEntityFromLink(this.entityLink);
2040
+ const maybeReferentLink = headEntity.fields[this.field];
2041
+ if (undefined === maybeReferentLink) {
2042
+ // field references nothing (or even field doesn't exist)
2043
+ return undefined;
2044
+ }
2045
+ if (!isLink(maybeReferentLink)) {
2046
+ // Scenario of "impostor referent", where one of the deepPath's segments is not a Link but some other type
2047
+ // Under normal circumstance we expect field to be a Link, but it could be an "impostor"
2048
+ // eg. `Text` or `Number` or anything like that; could be due to CT changes or manual path creation via CMA
2049
+ return undefined;
2050
+ }
2051
+ return maybeReferentLink;
2052
+ }
2053
+ static from(opt) {
2054
+ return new DeepReference(opt);
2055
+ }
2056
+ }
2057
+ function gatherDeepReferencesFromExperienceEntry(experienceEntry) {
2058
+ const deepReferences = [];
2059
+ const dataSource = experienceEntry.fields.dataSource;
2060
+ const { children } = experienceEntry.fields.componentTree;
2061
+ treeVisit({
2062
+ definitionId: 'root',
2063
+ variables: {},
2064
+ children,
2065
+ }, (node) => {
2066
+ if (!node.variables)
2067
+ return;
2068
+ for (const [, variableMapping] of Object.entries(node.variables)) {
2069
+ if (variableMapping.type !== 'BoundValue')
2070
+ continue;
2071
+ if (!isDeepPath(variableMapping.path))
2072
+ continue;
2073
+ deepReferences.push(DeepReference.from({
2074
+ path: variableMapping.path,
2075
+ dataSource,
2076
+ }));
2077
+ }
2078
+ });
2079
+ return deepReferences;
2080
+ }
2081
+ function gatherDeepReferencesFromTree(startingNode, dataSource) {
2082
+ const deepReferences = [];
2083
+ treeVisit(startingNode, (node) => {
2084
+ if (!node.data.props)
2085
+ return;
2086
+ for (const [, variableMapping] of Object.entries(node.data.props)) {
2087
+ if (variableMapping.type !== 'BoundValue')
2088
+ continue;
2089
+ if (!isDeepPath(variableMapping.path))
2090
+ continue;
2091
+ deepReferences.push(DeepReference.from({
2092
+ path: variableMapping.path,
2093
+ dataSource,
2094
+ }));
2095
+ }
2096
+ });
2097
+ return deepReferences;
2098
+ }
2099
+
2100
+ /**
2101
+ * Traverses deep-references and extracts referents from valid deep-paths.
2102
+ * The referents are received from the CDA/CPA response `.includes` field.
2103
+ *
2104
+ * In case deep-paths not resolving till the end, eg.:
2105
+ * - non-link referents: are ignored
2106
+ * - unset references: are ignored
2107
+ *
2108
+ * Errors are thrown in case of deep-paths being correct,
2109
+ * but referents not found. Because if we don't throw now, the EntityStore will
2110
+ * be missing entities and upon rendering will not be able to render bindings.
2111
+ */
2112
+ function gatherAutoFetchedReferentsFromIncludes(deepReferences, entriesResponse) {
2113
+ const autoFetchedReferentEntries = [];
2114
+ const autoFetchedReferentAssets = [];
2115
+ for (const reference of deepReferences) {
2116
+ const headEntry = entriesResponse.items.find((entry) => entry.sys.id === reference.headEntityId);
2117
+ if (!headEntry) {
2118
+ throw new Error(`LogicError: When resolving deep-references could not find headEntry (id=${reference.entityId})`);
2119
+ }
2120
+ const linkToReferent = headEntry.fields[reference.field];
2121
+ if (undefined === linkToReferent) {
2122
+ console.debug(`[experiences-sdk-react::gatherAutoFetchedReferentsFromIncludes] Empty reference in headEntity. Probably reference is simply not set.`);
2123
+ continue;
2124
+ }
2125
+ if (!isLink(linkToReferent)) {
2126
+ console.debug(`[experiences-sdk-react::gatherAutoFetchedReferentsFromIncludes] Non-link value in headEntity. Probably broken path '${reference.originalPath}'`);
2127
+ continue;
2128
+ }
2129
+ if (linkToReferent.sys.linkType === 'Entry') {
2130
+ const referentEntry = entriesResponse.includes?.Entry?.find((entry) => entry.sys.id === linkToReferent.sys.id);
2131
+ if (!referentEntry) {
2132
+ throw new Error(`Logic Error: L2-referent Entry was not found within .includes (${JSON.stringify({
2133
+ linkToReferent,
2134
+ })})`);
2135
+ }
2136
+ autoFetchedReferentEntries.push(referentEntry);
2137
+ }
2138
+ else if (linkToReferent.sys.linkType === 'Asset') {
2139
+ const referentAsset = entriesResponse.includes?.Asset?.find((entry) => entry.sys.id === linkToReferent.sys.id);
2140
+ if (!referentAsset) {
2141
+ throw new Error(`Logic Error: L2-referent Asset was not found within includes (${JSON.stringify({
2142
+ linkToReferent,
2143
+ })})`);
2144
+ }
2145
+ autoFetchedReferentAssets.push(referentAsset);
2146
+ }
2147
+ else {
2148
+ console.debug(`[experiences-sdk-react::gatherAutoFetchedReferentsFromIncludes] Unhandled linkType :${JSON.stringify(linkToReferent)}`);
2149
+ }
2150
+ } // for (reference of deepReferences)
2151
+ return { autoFetchedReferentAssets, autoFetchedReferentEntries };
2152
+ }
2153
+
2154
+ const MIN_FETCH_LIMIT = 1;
2155
+ const fetchEntities = async ({ entityType, client, query, }) => {
2156
+ if (entityType === 'Asset') {
2157
+ return client.getAssets({ ...query });
2158
+ }
2159
+ return client.withoutLinkResolution.getEntries({ ...query });
2160
+ };
2161
+ const fetchAllEntities = async ({ client, entityType, ids, locale, skip = 0, limit = 100, responseItems = [], }) => {
2162
+ try {
2163
+ if (!ids.length || !client) {
2164
+ return {
2165
+ items: [],
2166
+ };
2167
+ }
2168
+ const query = { 'sys.id[in]': ids, locale, limit, skip };
2169
+ const response = await fetchEntities({ entityType, client, query });
2170
+ if (!response) {
2171
+ return {
2172
+ items: responseItems,
2173
+ };
2174
+ }
2175
+ responseItems.push(...response.items);
2176
+ if (skip + limit < response.total) {
2177
+ await fetchAllEntities({
2178
+ client,
2179
+ entityType,
2180
+ ids,
2181
+ locale,
2182
+ skip: skip + limit,
2183
+ limit,
2184
+ responseItems,
2185
+ });
2186
+ }
2187
+ return {
2188
+ items: responseItems,
2189
+ };
2190
+ }
2191
+ catch (error) {
2192
+ if (error instanceof Error &&
2193
+ error.message.includes('size too big') &&
2194
+ limit > MIN_FETCH_LIMIT) {
2195
+ const newLimit = Math.max(MIN_FETCH_LIMIT, Math.floor(limit / 2));
2196
+ return fetchAllEntities({
2197
+ client,
2198
+ entityType,
2199
+ ids,
2200
+ locale,
2201
+ skip,
2202
+ limit: newLimit,
2203
+ responseItems,
2204
+ });
2205
+ }
2206
+ return error;
2207
+ }
2208
+ };
2209
+
2210
+ const fetchReferencedEntities = async ({ client, experienceEntry, locale, }) => {
2211
+ if (!client) {
2212
+ throw new Error('Failed to fetch experience entities. Required "client" parameter was not provided');
2213
+ }
2214
+ if (!locale) {
2215
+ throw new Error('Failed to fetch experience entities. Required "locale" parameter was not provided');
2216
+ }
2217
+ if (!isExperienceEntry(experienceEntry)) {
2218
+ throw new Error('Failed to fetch experience entities. Provided "experienceEntry" does not match experience entry schema');
2219
+ }
2220
+ const deepReferences = gatherDeepReferencesFromExperienceEntry(experienceEntry);
2221
+ const entryIds = [];
2222
+ const assetIds = [];
2223
+ for (const dataBinding of Object.values(experienceEntry.fields.dataSource)) {
2224
+ if (!('sys' in dataBinding)) {
2225
+ continue;
2226
+ }
2227
+ if (dataBinding.sys.linkType === 'Entry') {
2228
+ entryIds.push(dataBinding.sys.id);
2229
+ }
2230
+ if (dataBinding.sys.linkType === 'Asset') {
2231
+ assetIds.push(dataBinding.sys.id);
2232
+ }
2233
+ }
2234
+ const [entriesResponse, assetsResponse] = (await Promise.all([
2235
+ fetchAllEntities({ client, entityType: 'Entry', ids: entryIds, locale }),
2236
+ fetchAllEntities({ client, entityType: 'Asset', ids: assetIds, locale }),
2237
+ ]));
2238
+ const { autoFetchedReferentAssets, autoFetchedReferentEntries } = gatherAutoFetchedReferentsFromIncludes(deepReferences, entriesResponse);
2239
+ // Using client getEntries resolves all linked entry references, so we do not need to resolve entries in usedComponents
2240
+ const allResolvedEntries = [
2241
+ ...(entriesResponse?.items ?? []),
2242
+ ...(experienceEntry.fields.usedComponents || []),
2243
+ ...autoFetchedReferentEntries,
2244
+ ];
2245
+ const allResolvedAssets = [
2246
+ ...(assetsResponse.items ?? []),
2247
+ ...autoFetchedReferentAssets,
2248
+ ];
2249
+ return {
2250
+ entries: allResolvedEntries,
2251
+ assets: allResolvedAssets,
2252
+ };
2253
+ };
2254
+
2255
+ const errorMessagesWhileFetching$1 = {
2256
+ experience: 'Failed to fetch experience',
2257
+ experienceReferences: 'Failed to fetch entities, referenced in experience',
2258
+ };
2259
+ const handleError$1 = (generalMessage, error) => {
2260
+ const message = error instanceof Error ? error.message : `Unknown error: ${error}`;
2261
+ throw Error(message);
2262
+ };
2263
+ /**
2264
+ * Fetch experience entry using slug as the identifier
2265
+ * @param {string} experienceTypeId - id of the content type associated with the experience
2266
+ * @param {string} slug - slug of the experience (defined in entry settings)
2267
+ * @param {string} localeCode - locale code to fetch the experience. Falls back to the currently active locale in the state
2268
+ */
2269
+ // Promise<Experience<EntityStore> | undefined> =>
2270
+ async function fetchBySlug({ client, experienceTypeId, slug, localeCode, }) {
2271
+ let experienceEntry = undefined;
2272
+ try {
2273
+ experienceEntry = await fetchExperienceEntry({
2274
+ client,
2275
+ experienceTypeId,
2276
+ locale: localeCode,
2277
+ identifier: {
2278
+ slug,
2279
+ },
2280
+ });
2281
+ if (!experienceEntry) {
2282
+ throw new Error(`No experience entry with slug: ${slug} exists`);
2283
+ }
2284
+ try {
2285
+ const { entries, assets } = await fetchReferencedEntities({
2286
+ client,
2287
+ experienceEntry,
2288
+ locale: localeCode,
2289
+ });
2290
+ const experience = createExperience({
2291
+ experienceEntry,
2292
+ referencedAssets: assets,
2293
+ referencedEntries: entries,
2294
+ locale: localeCode,
2295
+ });
2296
+ return experience;
2297
+ }
2298
+ catch (error) {
2299
+ handleError$1(errorMessagesWhileFetching$1.experienceReferences, error);
2300
+ }
2301
+ }
2302
+ catch (error) {
2303
+ handleError$1(errorMessagesWhileFetching$1.experience, error);
2304
+ }
2305
+ }
2306
+
2307
+ const errorMessagesWhileFetching = {
2308
+ experience: 'Failed to fetch experience',
2309
+ experienceReferences: 'Failed to fetch entities, referenced in experience',
2310
+ };
2311
+ const handleError = (generalMessage, error) => {
2312
+ const message = error instanceof Error ? error.message : `Unknown error: ${error}`;
2313
+ throw Error(message);
2314
+ };
2315
+ /**
2316
+ * Fetch experience entry using slug as the identifier
2317
+ * @param {string} experienceTypeId - id of the content type associated with the experience
2318
+ * @param {string} slug - slug of the experience (defined in entry settings)
2319
+ * @param {string} localeCode - locale code to fetch the experience. Falls back to the currently active locale in the state
2320
+ */
2321
+ async function fetchById({ client, experienceTypeId, id, localeCode, }) {
2322
+ let experienceEntry = undefined;
2323
+ try {
2324
+ experienceEntry = await fetchExperienceEntry({
2325
+ client,
2326
+ experienceTypeId,
2327
+ locale: localeCode,
2328
+ identifier: {
2329
+ id,
2330
+ },
2331
+ });
2332
+ if (!experienceEntry) {
2333
+ throw new Error(`No experience entry with id: ${id} exists`);
2334
+ }
2335
+ try {
2336
+ const { entries, assets } = await fetchReferencedEntities({
2337
+ client,
2338
+ experienceEntry,
2339
+ locale: localeCode,
2340
+ });
2341
+ const experience = createExperience({
2342
+ experienceEntry,
2343
+ referencedAssets: assets,
2344
+ referencedEntries: entries,
2345
+ locale: localeCode,
2346
+ });
2347
+ return experience;
2348
+ }
2349
+ catch (error) {
2350
+ handleError(errorMessagesWhileFetching.experienceReferences, error);
2351
+ }
2352
+ }
2353
+ catch (error) {
2354
+ handleError(errorMessagesWhileFetching.experience, error);
2355
+ }
2356
+ }
2357
+
2358
+ export { DeepReference, EditorModeEntityStore, EntityStore, EntityStoreBase, MEDIA_QUERY_REGEXP, VisualEditorMode, buildCfStyles, buildStyleTag, builtInStyles, calculateNodeDefaultHeight, checkIsAssembly, checkIsAssemblyDefinition, checkIsAssemblyEntry, checkIsAssemblyNode, columnsBuiltInStyles, columnsDefinition, containerBuiltInStyles, containerDefinition, createExperience, defineDesignTokens, designTokensRegistry, doesMismatchMessageSchema, fetchById, fetchBySlug, findOutermostCoordinates, gatherDeepReferencesFromExperienceEntry, gatherDeepReferencesFromTree, generateRandomId, getActiveBreakpointIndex, getDataFromTree, getDesignTokenRegistration, getElementCoordinates, getFallbackBreakpointIndex, getInsertionData, getValueForBreakpoint, isContentfulStructureComponent, isDeepPath, isEmptyStructureWithRelativeHeight, isExperienceEntry, isLink, isLinkToAsset, mediaQueryMatcher, optionalBuiltInStyles, parseDataSourcePathIntoFieldset, parseDataSourcePathWithL1DeepBindings, sectionBuiltInStyles, sectionDefinition, sendMessage, singleColumnBuiltInStyles, singleColumnDefinition, supportedModes, transformBoundContentValue, tryParseMessage, validateExperienceBuilderConfig };
2359
+ //# sourceMappingURL=index.js.map