@capillarytech/creatives-library 8.0.290-alpha.3 → 8.0.290

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 (76) hide show
  1. package/constants/unified.js +1 -0
  2. package/initialState.js +2 -0
  3. package/package.json +1 -1
  4. package/utils/common.js +8 -5
  5. package/utils/commonUtils.js +85 -4
  6. package/utils/tagValidations.js +222 -84
  7. package/utils/tests/commonUtil.test.js +124 -147
  8. package/utils/tests/tagValidations.test.js +358 -280
  9. package/v2Components/CommonTestAndPreview/DeliverySettings/DeliverySettings.scss +33 -0
  10. package/v2Components/CommonTestAndPreview/DeliverySettings/ModifyDeliverySettings.js +397 -0
  11. package/v2Components/CommonTestAndPreview/DeliverySettings/ModifyDeliverySettings.scss +35 -0
  12. package/v2Components/CommonTestAndPreview/DeliverySettings/TECH_DETAILING_DELIVERY_SETTINGS.md +725 -0
  13. package/v2Components/CommonTestAndPreview/DeliverySettings/constants.js +92 -0
  14. package/v2Components/CommonTestAndPreview/DeliverySettings/index.js +243 -0
  15. package/v2Components/CommonTestAndPreview/DeliverySettings/messages.js +111 -0
  16. package/v2Components/CommonTestAndPreview/DeliverySettings/utils/parseSenderDetailsResponse.js +91 -0
  17. package/v2Components/CommonTestAndPreview/SendTestMessage.js +33 -1
  18. package/v2Components/CommonTestAndPreview/actions.js +20 -0
  19. package/v2Components/CommonTestAndPreview/constants.js +10 -0
  20. package/v2Components/CommonTestAndPreview/index.js +133 -15
  21. package/v2Components/CommonTestAndPreview/reducer.js +47 -0
  22. package/v2Components/CommonTestAndPreview/sagas.js +60 -0
  23. package/v2Components/CommonTestAndPreview/selectors.js +51 -0
  24. package/v2Components/CommonTestAndPreview/tests/DeliverySettings/ModifyDeliverySettings.test.js +782 -0
  25. package/v2Components/CommonTestAndPreview/tests/DeliverySettings/index.test.js +200 -0
  26. package/v2Components/CommonTestAndPreview/tests/DeliverySettings/utils/parseSenderDetailsResponse.test.js +235 -0
  27. package/v2Components/CommonTestAndPreview/tests/SendTestMessage.test.js +127 -0
  28. package/v2Components/CommonTestAndPreview/tests/actions.test.js +50 -0
  29. package/v2Components/CommonTestAndPreview/tests/constants.test.js +18 -0
  30. package/v2Components/CommonTestAndPreview/tests/index.test.js +214 -1
  31. package/v2Components/CommonTestAndPreview/tests/reducer.test.js +118 -0
  32. package/v2Components/CommonTestAndPreview/tests/sagas.test.js +145 -0
  33. package/v2Components/CommonTestAndPreview/tests/selectors.test.js +146 -0
  34. package/v2Components/ErrorInfoNote/index.js +5 -2
  35. package/v2Components/FormBuilder/index.js +162 -84
  36. package/v2Components/FormBuilder/messages.js +8 -0
  37. package/v2Components/HtmlEditor/HTMLEditor.js +5 -0
  38. package/v2Components/HtmlEditor/__tests__/HTMLEditor.apiErrors.test.js +1 -0
  39. package/v2Components/HtmlEditor/__tests__/HTMLEditor.test.js +15 -0
  40. package/v2Components/HtmlEditor/components/CodeEditorPane/index.js +2 -1
  41. package/v2Components/TestAndPreviewSlidebox/index.js +14 -0
  42. package/v2Containers/Cap/mockData.js +14 -0
  43. package/v2Containers/Cap/reducer.js +55 -3
  44. package/v2Containers/Cap/tests/reducer.test.js +102 -0
  45. package/v2Containers/CreativesContainer/SlideBoxFooter.js +1 -3
  46. package/v2Containers/CreativesContainer/index.js +6 -19
  47. package/v2Containers/Email/index.js +5 -1
  48. package/v2Containers/EmailWrapper/components/EmailHTMLEditor.js +62 -10
  49. package/v2Containers/EmailWrapper/components/__tests__/EmailHTMLEditor.test.js +115 -12
  50. package/v2Containers/FTP/index.js +51 -2
  51. package/v2Containers/FTP/messages.js +4 -0
  52. package/v2Containers/InApp/index.js +96 -1
  53. package/v2Containers/InApp/tests/index.test.js +6 -17
  54. package/v2Containers/InappAdvance/index.js +103 -2
  55. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/content.test.js.snap +24 -3
  56. package/v2Containers/Line/Container/Text/index.js +1 -0
  57. package/v2Containers/MobilePush/Create/index.js +16 -6
  58. package/v2Containers/MobilePush/Edit/index.js +16 -6
  59. package/v2Containers/MobilePushNew/index.js +33 -2
  60. package/v2Containers/Rcs/index.js +37 -12
  61. package/v2Containers/Rcs/tests/__snapshots__/index.test.js.snap +667 -16
  62. package/v2Containers/Sms/Create/index.js +3 -35
  63. package/v2Containers/Sms/Create/messages.js +0 -4
  64. package/v2Containers/Sms/Edit/index.js +3 -33
  65. package/v2Containers/Sms/commonMethods.js +6 -6
  66. package/v2Containers/SmsTrai/Edit/index.js +47 -6
  67. package/v2Containers/SmsTrai/Edit/tests/__snapshots__/index.test.js.snap +147 -6
  68. package/v2Containers/Viber/index.js +1 -0
  69. package/v2Containers/WebPush/Create/hooks/useTagManagement.js +3 -1
  70. package/v2Containers/WebPush/Create/hooks/useTagManagement.test.js +7 -0
  71. package/v2Containers/WebPush/Create/index.js +2 -2
  72. package/v2Containers/WebPush/Create/utils/validation.js +2 -17
  73. package/v2Containers/WebPush/Create/utils/validation.test.js +24 -0
  74. package/v2Containers/Whatsapp/index.js +18 -10
  75. package/v2Containers/Whatsapp/tests/__snapshots__/index.test.js.snap +25849 -3524
  76. package/v2Containers/Zalo/index.js +11 -3
@@ -43,6 +43,7 @@ export const HOSPITALITY_BASED_SCOPE = 'HOSPITALITY_BASED_SCOPE';
43
43
  export const REGISTRATION_CUSTOM_FIELD = 'Registration custom fields';
44
44
  export const GIFT_CARDS = 'GIFT_CARDS';
45
45
  export const PROMO_ENGINE = 'PROMO_ENGINE';
46
+ export const LIQUID_SUPPORT = 'ENABLE_LIQUID_SUPPORT';
46
47
  export const ENABLE_NEW_MPUSH = 'ENABLE_NEW_MPUSH';
47
48
  export const SUPPORT_CK_EDITOR = 'SUPPORT_CK_EDITOR';
48
49
  export const CUSTOM_TAG = 'CustomTagMessage';
package/initialState.js CHANGED
@@ -14,7 +14,9 @@ export default {
14
14
  metaEntities: {
15
15
  tags: [],
16
16
  layouts: [],
17
+ tagLookupMap: {},
17
18
  },
19
+ liquidTags: [],
18
20
  fetchingLiquidTags: false,
19
21
  fetchingSchema: true,
20
22
  fetchingSchemaError: '',
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capillarytech/creatives-library",
3
3
  "author": "meharaj",
4
- "version": "8.0.290-alpha.3",
4
+ "version": "8.0.290",
5
5
  "description": "Capillary creatives ui",
6
6
  "main": "./index.js",
7
7
  "module": "./index.es.js",
package/utils/common.js CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  BADGES_ISSUE,
23
23
  ENABLE_WECHAT,
24
24
  ENABLE_WEBPUSH,
25
+ LIQUID_SUPPORT,
25
26
  SUPPORT_CK_EDITOR,
26
27
  ENABLE_NEW_MPUSH
27
28
  } from '../constants/unified';
@@ -90,6 +91,12 @@ export const hasPromoFeature = Auth.hasFeatureAccess.bind(
90
91
  null,
91
92
  PROMO_ENGINE,
92
93
  );
94
+
95
+ export const hasLiquidSupportFeature = Auth.hasFeatureAccess.bind(
96
+ null,
97
+ LIQUID_SUPPORT,
98
+ );
99
+
93
100
  export const hasSupportCKEditor = Auth.hasFeatureAccess.bind(
94
101
  null,
95
102
  SUPPORT_CK_EDITOR,
@@ -125,11 +132,7 @@ export const hasCustomerBarcodeFeatureEnabled = Auth.hasFeatureAccess.bind(
125
132
  ENABLE_CUSTOMER_BARCODE_TAG,
126
133
  );
127
134
 
128
- // Note: The "EMAIL_UNSUBSCRIBE_TAG_MANDATORY" feature flag determines if the Unsubscribe tag in email is optional.
129
- // When this flag is enabled for an org, the Unsubscribe tag is NOT mandatory in the email flow.
130
- // This is as per the requirement in the tech doc:
131
- // https://capillarytech.atlassian.net/wiki/spaces/CAM/pages/3941662838/Remove+mandate+for+Unsubscribe+tag+in+email+flow
132
- export const isEmailUnsubscribeTagOptional = Auth.hasFeatureAccess.bind(
135
+ export const isEmailUnsubscribeTagMandatory = Auth.hasFeatureAccess.bind(
133
136
  null,
134
137
  EMAIL_UNSUBSCRIBE_TAG_MANDATORY,
135
138
  );
@@ -16,6 +16,7 @@ import {
16
16
  IOS,
17
17
  } from "../v2Containers/CreativesContainer/constants";
18
18
  import { GLOBAL_CONVERT_OPTIONS } from "../v2Components/FormBuilder/constants";
19
+ import { checkSupport, extractNames, skipTags as defaultSkipTags, isInsideLiquidBlock } from "./tagValidations";
19
20
  import { SMS_TRAI_VAR } from '../v2Containers/SmsTrai/Edit/constants';
20
21
  export const apiMessageFormatHandler = (id, fallback) => (
21
22
  <FormattedMessage id={id} defaultMessage={fallback} />
@@ -140,7 +141,12 @@ export const validateLiquidTemplateContent = async (
140
141
  messages,
141
142
  onError = () => {},
142
143
  onSuccess = () => {},
144
+ tagLookupMap,
145
+ eventContextTags,
146
+ isLiquidFlow,
147
+ forwardedTags = {},
143
148
  tabType,
149
+ skipTags = defaultSkipTags,
144
150
  } = options;
145
151
  const emptyBodyError = formatMessage(messages?.emailBodyEmptyError);
146
152
  const somethingWrongMsg = formatMessage(messages?.somethingWentWrong);
@@ -198,6 +204,81 @@ export const validateLiquidTemplateContent = async (
198
204
  });
199
205
  return false;
200
206
  }
207
+ // Extract and validate tags
208
+ const extractedLiquidTags = extractNames(result?.data || []);
209
+ // Get supported tags
210
+ const supportedLiquidTags = checkSupport(
211
+ result,
212
+ tagLookupMap,
213
+ eventContextTags,
214
+ isLiquidFlow,
215
+ forwardedTags
216
+ );
217
+ // Helper function to check if a tag appears only inside {% %} blocks
218
+ const isTagOnlyInsideLiquidBlocks = (tagName) => {
219
+ // Escape special regex characters in tag name, including dots
220
+ // Dots need to be escaped to match literally (item.name should match item.name, not item or name)
221
+ const escapedTagName = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
222
+
223
+ // First, check if tag appears in {% %} syntax itself (like "order.items" in "{% for item in order.items %}")
224
+ // This is a tag used in Liquid logic, not output, so it should always be skipped
225
+ // Match the tag name as a whole (with dots escaped), optionally surrounded by word boundaries or non-word chars
226
+ // For tags with dots, we match them directly; for simple tags, we use word boundaries
227
+ const hasDot = tagName.includes('.');
228
+ const liquidSyntaxPattern = hasDot
229
+ ? `{%[^%]*${escapedTagName}[^%]*%}`
230
+ : `{%[^%]*\\b${escapedTagName}\\b[^%]*%}`;
231
+ const liquidSyntaxRegex = new RegExp(liquidSyntaxPattern, 'g');
232
+ const liquidSyntaxMatches = Array.from(content.matchAll(liquidSyntaxRegex));
233
+
234
+ // Find all occurrences of {{tagName}} in the content (output tags)
235
+ // Match patterns like: {{tagName}}, {{ tagName }}, {{tagName }}, {{ tagName}}
236
+ // Use non-word-boundary approach for tags with dots (item.name should match item.name, not item or name separately)
237
+ const outputTagRegex = new RegExp(`\\{\\{\\s*${escapedTagName}\\s*\\}\\}`, 'g');
238
+ const outputTagMatches = Array.from(content.matchAll(outputTagRegex));
239
+ const outputTagPositions = outputTagMatches.map((match) => match.index);
240
+
241
+ // If tag appears in {% %} syntax, skip validation
242
+ if (liquidSyntaxMatches.length > 0) {
243
+ return true;
244
+ }
245
+
246
+ // If no output tag matches found, don't skip validation
247
+ // The tag was extracted by the API, so it exists somewhere and should be validated
248
+ if (outputTagPositions.length === 0) {
249
+ return false;
250
+ }
251
+
252
+ // Check if all output tag occurrences are inside {% %} blocks
253
+ // We check the position of {{ to see if it's inside a block
254
+ // Only skip validation if ALL occurrences are inside blocks
255
+ return outputTagPositions.every((tagIndex) => {
256
+ if (tagIndex === undefined || tagIndex === null) {
257
+ return false;
258
+ }
259
+ return isInsideLiquidBlock(content, tagIndex);
260
+ });
261
+ };
262
+
263
+ // Find unsupported tags, excluding those that are only inside {% %} blocks
264
+ const unsupportedLiquidTags = extractedLiquidTags?.filter(
265
+ (tag) => !supportedLiquidTags?.includes(tag)
266
+ && !skipTags(tag)
267
+ && !isTagOnlyInsideLiquidBlocks(tag)
268
+ );
269
+ // Handle unsupported tags
270
+ if (unsupportedLiquidTags?.length > 0) {
271
+ const errorMsg = formatMessage(messages.unsupportedTagsValidationError, {
272
+ unsupportedTags: unsupportedLiquidTags.join(", "),
273
+ });
274
+ onError({
275
+ standardErrors: [],
276
+ liquidErrors: [errorMsg],
277
+ tabType,
278
+ });
279
+ return false;
280
+ }
281
+ // All validations passed
201
282
  onSuccess(content, tabType);
202
283
  return true;
203
284
  };
@@ -215,8 +296,8 @@ export const _validatePlatformSpecificContent = async (
215
296
  ...commonVltcOptions // Other options like getLiquidTags, formatMessage, messages, currentTab, etc.
216
297
  } = options;
217
298
 
218
- let isAndroidValid = true;
219
- let isIosValid = true;
299
+ let isAndroidValid = false;
300
+ let isIosValid = false;
220
301
 
221
302
  // This aggregator is passed to validateLiquidTemplateContent.
222
303
  // It accumulates errors in the new structure and calls the parentOnError
@@ -284,8 +365,8 @@ export const _validatePlatformSpecificContent = async (
284
365
  /**
285
366
  * Validate Mobile Push content for both Android and iOS tabs
286
367
  * @param {object} formData - Form data containing Android and iOS content
287
- * @param {object} options - Options for validation (currentTab, onError, onSuccess, getLiquidTags, formatMessage, messages, singleTab).
288
- * @returns {Promise<boolean>} - Promise that resolves to true when validation succeeds, false otherwise
368
+ * @param {object} options - Options for validation
369
+ * @returns {Promise} - Promise that resolves when validation completes
289
370
  */
290
371
  export const validateMobilePushContent = async (formData, options) => {
291
372
  const {
@@ -13,121 +13,259 @@ import { ENTRY_TRIGGER_TAG_REGEX, SKIP_TAGS_REGEX_GROUPS } from '../constants/un
13
13
  const DEFAULT = 'default';
14
14
  const SUBTAGS = 'subtags';
15
15
 
16
- /** Whitespace-tolerant check for {{ unsubscribe }}-style tag in content. */
17
- const UNSUBSCRIBE_TAG_REGEX = /\{\{\s*unsubscribe\s*\}\}/;
18
- export const hasUnsubscribeTag = (content) =>
19
- typeof content === 'string' && UNSUBSCRIBE_TAG_REGEX.test(content);
20
-
21
16
  /**
22
- * Shared core for tag validation. Used by validateTags (tagValidations) and FormBuilder.validateTags.
23
- * @param {Object} params
24
- * @param {string} params.contentForBraceCheck - String to run validateIfTagClosed on.
25
- * @param {string} params.contentForUnsubscribeScan - String to scan for {{...}} unsubscribe variants.
26
- * @param {Array} [params.tags] - Tag definitions (for definition-based missing tags).
27
- * @param {string} [params.currentModule] - Module context (e.g. 'default', 'outbound').
28
- * @param {boolean} [params.isFullMode] - If true, skip unsubscribe checks.
29
- * @param {Array} [params.initialMissingTags=null] - If set, use instead of computing from definitions.
30
- * @param {function} [params.skipTagsFn=skipTags] - skipTags implementation.
31
- * @param {boolean} [params.includeIsContentEmpty=false] - If true, response includes isContentEmpty: false.
32
- * @returns {{ valid: boolean, missingTags: string[], isBraceError: boolean }}
17
+ * Checks if the response object of Tags supports the Tags added in the Add Labels Section
18
+ * @param {Object} response - The response object to check.
19
+ * @param {Object} tagObject - The tagLookupMap.
33
20
  */
34
- export const validateTagsCore = ({
35
- contentForBraceCheck,
36
- contentForUnsubscribeScan,
37
- tags,
38
- currentModule,
39
- isFullMode,
40
- initialMissingTags = null,
41
- skipTagsFn = skipTags,
42
- includeIsContentEmpty = false,
43
- }) => {
44
- const response = {
45
- valid: true,
46
- missingTags: [],
47
- isBraceError: false,
48
- ...(includeIsContentEmpty && { isContentEmpty: false }),
21
+ export const checkSupport = (response = {}, tagObject = {}, eventContextTags = [], isLiquidFlow = false, forwardedTags = {}) => {
22
+ const supportedList = [];
23
+ // Verifies the presence of the tag in the 'Add Labels' section.
24
+ // Incase of journey event context the tags won't be available in the tagObject(tagLookupMap).
25
+ //Here forwardedTags only use in case of loyalty module
26
+ const mappedForwardedTags = handleForwardedTags(forwardedTags);
27
+ const checkNameInTagObjectOrEventContext = (name) => !!tagObject[name] || eventContextTags?.some((tag) => tag?.tagName === name) || mappedForwardedTags.includes(name);
28
+
29
+ // Verify if childTag is a valid sub-tag of parentTag from the 'Add Labels' section or if it's unsupported.
30
+ const checkSubtags = (parentTag, childName) => {
31
+ // For event context tags the parentTag will be the event context tag name and subtags will be the child attributes for leaderboards
32
+ if (checkNameInTagObjectOrEventContext(parentTag) && isLiquidFlow && eventContextTags?.length) {
33
+ const childNameAfterDot = childName?.split(".")?.[1];
34
+ if (eventContextTags?.some((tag) => tag?.subTags?.includes(childNameAfterDot))) {
35
+ supportedList.push(childName);
36
+ }
37
+ }
38
+ if (!tagObject?.[parentTag] && !mappedForwardedTags.includes(parentTag)) return false;
39
+ let updatedChildName = childName;
40
+ let updatedWithoutDotChildName = childName;
41
+ if (childName?.includes(".")) {
42
+ updatedChildName = `.${childName?.split(".")?.[1]}`;
43
+ updatedWithoutDotChildName = childName?.split(".")?.[1];
44
+ }
45
+ if (tagObject?.[parentTag]) {
46
+ const subTags = tagObject?.[parentTag]?.definition?.subtags;
47
+ return subTags?.includes(updatedChildName);
48
+ }
49
+ return mappedForwardedTags.includes(updatedChildName) || mappedForwardedTags.includes(updatedWithoutDotChildName) || mappedForwardedTags.includes(childName);
49
50
  };
50
51
 
51
- if (tags && tags.length && !isFullMode) {
52
- if (initialMissingTags == null) {
53
- // Definition-based: same as original tagValidations (when caller does not pass initialMissingTags)
54
- lodashForEach(tags, ({
55
- definition: {
56
- supportedModules,
57
- value,
58
- },
59
- }) => {
60
- if (value === 'unsubscribe') {
61
- lodashForEach(supportedModules, (module) => {
62
- if (module.mandatory && (currentModule === module.context)) {
63
- if (!hasUnsubscribeTag(contentForUnsubscribeScan)) {
64
- response.missingTags.push(value);
65
- }
66
- }
67
- });
68
- }
52
+ //Recursively checks if the childTag is actually a Sub-tag of the ParentTag
53
+ const processChildren = (parentTag = "", children = []) => {
54
+ for (const child of children) {
55
+ if (checkSubtags(parentTag, child?.name)) {
56
+ supportedList.push(child?.name);
57
+ }
58
+ if (child?.children?.length) {
59
+ processChildren(child?.name, child?.children);
60
+ }
61
+ }
62
+ };
63
+
64
+ //Checks if the tag is present in the Add Label Section
65
+ for (const item of response?.data || []) {
66
+ if (checkNameInTagObjectOrEventContext(item?.name)) {
67
+ supportedList?.push(item?.name);
68
+ }
69
+ //Repeat the process for subtags
70
+ if (item?.children?.length) {
71
+ processChildren(item?.name, item?.children);
72
+ }
73
+ }
74
+
75
+
76
+ return supportedList;
77
+ };
78
+
79
+ const handleForwardedTags = (forwardedTags) => {
80
+ const result = [];
81
+ Object.keys(forwardedTags).forEach((key) => {
82
+ result.push(key); // Add the main key to the result array
83
+
84
+ // Check if there are subtags for the current key
85
+ if (forwardedTags[key].subtags) {
86
+ // If subtags exist, add all subtag keys to the result array
87
+ Object.keys(forwardedTags[key].subtags).forEach((subkey) => {
88
+ result.push(subkey);
69
89
  });
70
- } else {
71
- response.missingTags = [...initialMissingTags];
72
90
  }
91
+ });
92
+ return result;
93
+ };
73
94
 
74
- const regex = /{{([^}]+)}}/g;
75
- let match = regex.exec(contentForUnsubscribeScan);
76
- while (match !== null) {
77
- const tagValue = match[1].trim();
78
- const ifSkipped = skipTagsFn(tagValue);
79
- if (ifSkipped && tagValue.indexOf('unsubscribe') !== -1) {
80
- const missingTagIndex = response.missingTags.indexOf('unsubscribe');
81
- if (missingTagIndex !== -1) {
82
- response.missingTags.splice(missingTagIndex, 1);
83
- }
84
- }
85
- match = regex.exec(contentForUnsubscribeScan);
95
+ /**
96
+ * Extracts the names from the given data.
97
+ * @param {Array} data - The data to extract names from.
98
+ * @returns {Array} - The extracted names.
99
+ */
100
+ export function extractNames(data) {
101
+ const names = [];
102
+
103
+ function traverse(node) {
104
+ if (node?.name) {
105
+ names.push(node?.name);
86
106
  }
87
107
 
88
- if (response.missingTags.length > 0) {
89
- response.valid = false;
108
+ if (node?.children?.length > 0) {
109
+ node?.children?.forEach((child) => traverse(child));
90
110
  }
91
111
  }
92
112
 
93
- response.isBraceError = !validateIfTagClosed(contentForBraceCheck);
94
- if (response.isBraceError) {
95
- response.valid = false;
96
- } else if (response.missingTags.length > 0) {
97
- response.valid = false;
113
+ data?.forEach((item) => traverse(item));
114
+
115
+ return names;
116
+ }
117
+
118
+ // Helper to check if a tag is inside a {% ... %} block
119
+ // Handles all Liquid block types: {% %}, {%- -%}, {%- %}, {% -%}
120
+ // Content inside {% %} blocks can contain any dynamic tags and should not be validated
121
+ export const isInsideLiquidBlock = (content, tagIndex) => {
122
+ if (!content || tagIndex < 0 || tagIndex >= content.length) {
123
+ return false;
124
+ }
125
+
126
+ // Check if tagIndex is at the start of a {% block
127
+ // Need to check a few characters ahead to catch {% patterns
128
+ const checkWindow = content.substring(Math.max(0, tagIndex - 1), Math.min(content.length, tagIndex + 3));
129
+ if (/{%-?/.test(checkWindow) && content.substring(tagIndex, tagIndex + 2) === '{%') {
130
+ return true;
98
131
  }
99
- return response;
132
+
133
+ // Check content up to tagIndex to see if we're inside any {% %} block
134
+ // We need to properly handle Liquid tags:
135
+ // - Block opening tags: {% for %}, {% if %}, {% unless %}, {% case %}, {% capture %}, etc.
136
+ // These OPEN a block that needs to be closed with an "end" tag
137
+ // - Block closing tags: {% endfor %}, {% endif %}, {% endunless %}, etc.
138
+ // These CLOSE a block opened by a corresponding opening tag
139
+ // - Self-contained tags: {% assign %}, {% comment %}, etc.
140
+ // These are blocks themselves (from {% to %})
141
+ const contentBeforeTag = content.substring(0, tagIndex);
142
+
143
+ // Regex to match Liquid block opening tags (for, if, unless, case, capture, tablerow, raw, comment)
144
+ // These tags OPEN a block that needs to be closed with an "end" tag
145
+ const blockOpeningTags = ['for', 'if', 'unless', 'case', 'capture', 'tablerow', 'raw', 'comment'];
146
+ const blockOpeningPattern = blockOpeningTags.map(tag => `\\b${tag}\\b`).join('|');
147
+ const blockOpeningRegex = new RegExp(`{%-?\\s*(${blockOpeningPattern})[^%]*%}`, 'gi');
148
+
149
+ // Regex to match Liquid block closing tags (endfor, endif, endunless, endcase, endcapture, etc.)
150
+ const blockClosingTags = ['endfor', 'endif', 'endunless', 'endcase', 'endcapture', 'endtablerow', 'endraw', 'endcomment'];
151
+ const blockClosingPattern = blockClosingTags.map(tag => `\\b${tag}\\b`).join('|');
152
+ const blockClosingRegex = new RegExp(`{%-?\\s*(${blockClosingPattern})[^%]*%}`, 'gi');
153
+
154
+ // Find all block opening tags before tagIndex
155
+ const blockOpenings = Array.from(contentBeforeTag.matchAll(blockOpeningRegex), (match) => match.index);
156
+
157
+ // Find all block closing tags before tagIndex
158
+ const blockClosings = Array.from(contentBeforeTag.matchAll(blockClosingRegex), (match) => match.index);
159
+
160
+ // Count unmatched opening blocks (for, if, etc.)
161
+ const openBlockCount = blockOpenings.length - blockClosings.length;
162
+
163
+ // Also check for self-contained tags (assign, etc.) that create blocks from {% to %}
164
+ // These are any {% %} tags that are not block-opening or block-closing tags
165
+ const allBlockStarts = /{%-?/g;
166
+ const allBlockEnds = /-?%}/g;
167
+ const allStarts = Array.from(contentBeforeTag.matchAll(allBlockStarts), (match) => match.index);
168
+ const allEnds = Array.from(contentBeforeTag.matchAll(allBlockEnds), (match) => match.index);
169
+
170
+ // Check if we're inside a self-contained tag (more {% than %} before tagIndex, excluding block tags)
171
+ const selfContainedCount = allStarts.length - allEnds.length;
172
+
173
+ // We're inside a block if:
174
+ // 1. We're inside an unclosed block-opening tag (for, if, etc.), OR
175
+ // 2. We're inside a self-contained tag (assign, etc.)
176
+ return openBlockCount > 0 || selfContainedCount > 0;
100
177
  };
101
178
 
102
179
  /**
103
180
  * Validates the tags based on the provided parameters.
104
181
  * @param {Object} params - The parameters for tag validation.
105
- * @param {string} params.content - Content to validate.
106
- * @param {Array} [params.tagsParam] - Tag definitions.
107
- * @param {Object} [params.location] - Location with query.module.
108
- * @param {string} [params.tagModule] - Override for current module context.
109
- * @param {boolean} [params.isFullMode] - If true, skip unsubscribe checks.
110
- * @returns {{ valid: boolean, missingTags: string[], isBraceError: boolean }}
111
182
  */
112
183
  export const validateTags = ({
113
184
  content,
114
185
  tagsParam,
186
+ injectedTagsParams,
115
187
  location,
116
188
  tagModule,
189
+ eventContextTags,
117
190
  isFullMode,
118
191
  }) => {
119
192
  const tags = tagsParam;
193
+ const injectedTags = transformInjectedTags(injectedTagsParams);
120
194
  let currentModule = location?.query?.module ? location?.query?.module : DEFAULT;
121
195
  if (tagModule) {
122
196
  currentModule = tagModule;
123
197
  }
124
- return validateTagsCore({
125
- contentForBraceCheck: content,
126
- contentForUnsubscribeScan: content,
127
- tags,
128
- currentModule,
129
- isFullMode,
130
- });
198
+ const response = {
199
+ valid: true,
200
+ missingTags: [],
201
+ unsupportedTags: [],
202
+ isBraceError: false,
203
+ };
204
+ // Mandatory-tags check: only when we have a tags list and are in library mode
205
+ if (tags && tags.length && !isFullMode) {
206
+ lodashForEach(tags, ({
207
+ definition: {
208
+ supportedModules,
209
+ value,
210
+ },
211
+ }) => {
212
+ lodashForEach(supportedModules, (module) => {
213
+ if (module.mandatory && (currentModule === module.context)) {
214
+ if (content.indexOf(`{{${value}}}`) === -1) {
215
+ response.valid = false;
216
+ response.missingTags.push(value);
217
+ }
218
+ }
219
+ });
220
+ });
221
+ }
222
+ // In library mode, always scan content for {{...}} and flag unsupported tags (even when tags list is empty)
223
+ if (!isFullMode && content) {
224
+ const regex = /{{[(A-Z\w+(\s\w+)*$\(\)@!#$%^&*~.,/\\]+}}/g;
225
+ let match = regex.exec(content);
226
+ while (match !== null) {
227
+ const tagValue = match[0].substring(indexOfEnd(match[0], '{{'), match[0].indexOf('}}'));
228
+ const tagIndex = match?.index;
229
+ match = regex.exec(content);
230
+ let ifSupported = false;
231
+ lodashForEach(tags || [], (tag) => {
232
+ if (tag?.definition?.value === tagValue) {
233
+ ifSupported = true;
234
+ }
235
+ });
236
+ const ifSkipped = skipTags(tagValue);
237
+ if (ifSkipped) {
238
+ ifSupported = true;
239
+ const isUnsubscribeSkipped = tagValue.indexOf("unsubscribe") !== -1;
240
+ if (isUnsubscribeSkipped) {
241
+ const missingTagIndex = response.missingTags.indexOf("unsubscribe");
242
+ if (missingTagIndex !== -1) {
243
+ response.missingTags.splice(missingTagIndex, 1);
244
+ }
245
+ }
246
+ }
247
+ // Journey Event Context Tags support
248
+ eventContextTags?.forEach((tag) => {
249
+ if (tagValue === tag?.tagName) {
250
+ ifSupported = true;
251
+ }
252
+ });
253
+ ifSupported = ifSupported || checkIfSupportedTag(tagValue, injectedTags);
254
+ // Only add to unsupportedTags if not inside a {% ... %} block and does not contain a dot
255
+ if (!ifSupported && !isInsideLiquidBlock(content, tagIndex) && tagValue?.indexOf('.') === -1) {
256
+ response.unsupportedTags.push(tagValue);
257
+ response.valid = false;
258
+ }
259
+ if (response.unsupportedTags.length === 0 && response.missingTags.length === 0) {
260
+ response.valid = true;
261
+ }
262
+ }
263
+ }
264
+ response.isBraceError = !validateIfTagClosed(content);
265
+ // response should not be valid if there is unbalanced bracket error, as
266
+ // validations (eg button) are handled on valid property coming from the response.
267
+ response.isBraceError ? response.valid = false : response.valid = true;
268
+ return response;
131
269
  };
132
270
 
133
271
  /**