Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions actions/lib/validateHtml.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* Validates HTML syntax by checking for balanced opening and closing tags
* @param {string} html - The HTML string to validate
* @returns {Object} - { valid: boolean, reason: string }
*/
function validateHtml(html) {
if (typeof html !== 'string') {
return { valid: false, reason: 'Input must be a string' };
}

if (html.trim() === '') {
return { valid: true, reason: 'Empty string is valid' };
}

const stack = [];
const selfClosingTags = new Set([
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
'link', 'meta', 'param', 'source', 'track', 'wbr'
]);

// Regular expression to match HTML tags
const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g;
let match;
let lineNumber = 1;
let charPosition = 0;

while ((match = tagRegex.exec(html)) !== null) {
const fullTag = match[0];
const tagName = match[1].toLowerCase();
const isClosingTag = fullTag.startsWith('</');
const isSelfClosing = fullTag.endsWith('/>') || selfClosingTags.has(tagName);

// Calculate position for error reporting
const beforeMatch = html.substring(0, match.index);
lineNumber = beforeMatch.split('\n').length;
charPosition = match.index - beforeMatch.lastIndexOf('\n') - 1;

if (isSelfClosing) {
// Self-closing tags don't need to be balanced
continue;
}

if (isClosingTag) {
// Check if we have a matching opening tag
if (stack.length === 0) {
return {
valid: false,
reason: `Unexpected closing tag </${tagName}> at line ${lineNumber}, position ${charPosition}`
};
}

const lastOpenTag = stack.pop();
if (lastOpenTag !== tagName) {
return {
valid: false,
reason: `Mismatched tags: expected </${lastOpenTag}> but found </${tagName}> at line ${lineNumber}, position ${charPosition}`
};
}
} else {
// Opening tag - push onto stack
stack.push(tagName);
}
}

// Check if any opening tags weren't closed
if (stack.length > 0) {
const unclosedTags = stack.reverse().join(', ');
return {
valid: false,
reason: `Unclosed tags: ${unclosedTags}`
};
}

return { valid: true, reason: 'HTML is valid' };
}

module.exports = { validateHtml }
16 changes: 14 additions & 2 deletions actions/pdp-renderer/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ const { findDescription, prepareBaseTemplate, getPrimaryImage, generatePriceStri
const { generateLdJson } = require('./ldJson');
const { requestSaaS, getProductUrl } = require('../utils');
const { ProductQuery, ProductByUrlKeyQuery } = require('../queries');
const { validateHtml } = require('../lib/validateHtml');

const productTemplateCache = {};

function toTemplateProductData(baseProduct) {
function toTemplateProductData(baseProduct, context) {
const templateProductData = { ...baseProduct };
const primaryImage = getPrimaryImage(baseProduct)?.url;

Expand All @@ -20,6 +21,17 @@ function toTemplateProductData(baseProduct) {
templateProductData.primaryImage = primaryImage;
templateProductData.metaTitle = baseProduct.metaTitle || baseProduct.name || 'Product Details';

const fieldValidations = {
shortDescription: validateHtml(templateProductData.shortDescription),
description: validateHtml(templateProductData.description)
}

Object.entries(fieldValidations).forEach(([field, validation]) => {
if (!validation.valid) {
context.logger.warn(`Validation failed for "${field}" field: ${validation.reason}`);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this log sufficient to inform the user? Hopefully users do not have to experience what I did - tracing backwards from malformed UX through EDS CDN, Azure, and finally realizing it is the data itself that is the problem.

@duynguyen let me know if there's a better way to alert users to bad data.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the log message is good but it will potentially get lost among other logs.
IMO this should be tackled in a generic way, created #197

}
})

return templateProductData;
}

Expand Down Expand Up @@ -65,7 +77,7 @@ async function generateProductHtml(sku, urlKey, context) {
}

// Assign meta tag data for template
const templateProductData = toTemplateProductData(baseProduct);
const templateProductData = toTemplateProductData(baseProduct, context);

// Generate LD-JSON
const ldJson = await generateLdJson(baseProduct, context);
Expand Down
6 changes: 3 additions & 3 deletions actions/queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const CategoriesQuery = `
name
level
urlPath
}
}
}
`;

Expand Down Expand Up @@ -194,7 +194,7 @@ const ProductsQuery = `
items {
productView {
urlKey
sku
sku
}
}
page_info {
Expand All @@ -214,4 +214,4 @@ module.exports = {
CategoriesQuery,
ProductCountQuery,
ProductsQuery
};
};
4 changes: 2 additions & 2 deletions test/mock-responses/mock-product.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"sku": "24-MB03",
"name": "Crown Summit Backpack",
"url": "http://www.aemshop.net/crown-summit-backpack.html",
"description": "<p>The Crown Summit Backpack is equally at home in a gym locker, study cube or a pup tent, so be sure yours is packed with books, a bag lunch, water bottles, yoga block, laptop, or whatever else you want in hand. Rugged enough for day hikes and camping trips, it has two large zippered compartments and padded, adjustable shoulder straps.</p>\r\n<ul>\r\n<li>Top handle.</li>\r\n<li>Grommet holes.</li>\r\n<li>Two-way zippers.</li>\r\n<li>H 20\" x W 14\" x D 12\".</li>\r\n<li>Weight: 2 lbs, 8 oz. Volume: 29 L.</li>\r\n<ul>",
"description": "<p>The Crown Summit Backpack is equally at home in a gym locker, study cube or a pup tent, so be sure yours is packed with books, a bag lunch, water bottles, yoga block, laptop, or whatever else you want in hand. Rugged enough for day hikes and camping trips, it has two large zippered compartments and padded, adjustable shoulder straps.</p>\r\n<ul>\r\n<li>Top handle.</li>\r\n<li>Grommet holes.</li>\r\n<li>Two-way zippers.</li>\r\n<li>H 20\" x W 14\" x D 12\".</li>\r\n<li>Weight: 2 lbs, 8 oz. Volume: 29 L.</li>\r\n</ul>",
"shortDescription": "",
"metaDescription": "",
"metaKeyword": "backpack, hiking, camping",
Expand Down Expand Up @@ -180,4 +180,4 @@
}
]
}
}
}
72 changes: 72 additions & 0 deletions test/mock-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,33 @@ const handlers = {
matcher?.(req);
return HttpResponse.json(mockProduct);
}),

defaultProductInvalidShortDescription: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
// Create a product with invalid HTML in shortDescription
const invalidProduct = {
...mockProduct.data.products[0],
shortDescription: '<div><p>Mismatched tags</div>'
};
return HttpResponse.json({
data: {
products: [invalidProduct]
}
});
}),
defaultProductInvalidDescription: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
// Create a product with invalid HTML in description
const invalidProduct = {
...mockProduct.data.products[0],
description: '<ul><li>List item<li>Another item</ul>'
};
return HttpResponse.json({
data: {
products: [invalidProduct]
}
});
}),
defaultComplexProduct: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
return HttpResponse.json(mockComplexProduct);
Expand All @@ -38,6 +65,51 @@ const handlers = {
matcher?.(req);
return HttpResponse.json(mockProductLs);
}),
defaultProductBadData: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
// Create a product with invalid HTML in multiple fields
const badProduct = {
...mockProduct.data.products[0],
metaDescription: '<span>Unclosed span',
shortDescription: '<div>Unclosed div',
description: '<p>Unclosed paragraph'
};
return HttpResponse.json({
data: {
products: [badProduct]
}
});
}),
defaultProductValidHtml: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
// Create a product with valid HTML in all fields
const validProduct = {
...mockProduct.data.products[0],
metaDescription: '<p>Valid paragraph</p>',
shortDescription: '<div>Valid div</div>',
description: '<ul><li>Valid list item</li></ul>'
};
return HttpResponse.json({
data: {
products: [validProduct]
}
});
}),
defaultProductEmptyHtml: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
// Create a product with empty/undefined HTML fields
const emptyProduct = {
...mockProduct.data.products[0],
metaDescription: '',
shortDescription: undefined,
description: null
};
return HttpResponse.json({
data: {
products: [emptyProduct]
}
});
}),
return404: (matcher) => graphql.query('ProductQuery', (req) => {
matcher?.(req);
return HttpResponse.json({ data: { products: [] }});
Expand Down
Loading