import chalk from 'chalk'; import fs from 'node:fs'; import path from 'node:path'; import { documentsToRender } from '../actions/render'; import { TopLevelDirectoryName } from '../domain/file-names'; import { RootConfigWrite } from '../domain/root-config'; import { generateDocument } from './generate-document'; import { getErrorMessage } from './get-error-message'; import { validateDocument } from './validate-document'; const maxDocumentSizeString = '6291556 bytes (6MB)'; export const validateDocuments = async (params: { apiKey: string; productModuleConfig: RootConfigWrite }) => { const { apiKey, productModuleConfig } = params; for await (const documentToRender of documentsToRender) { const [fileName, extension] = documentToRender.split('.'); const pathToFile = path.join('./', TopLevelDirectoryName.Documents, `${fileName}.${extension}`); const { host } = productModuleConfig; if (fs.existsSync(pathToFile)) { const content = fs.readFileSync(pathToFile, { encoding: 'utf-8' }); const validationResult = await validateDocument({ apiKey, content, host, }); if (validationResult.result === 'error') { console.log(`\nThere was an error validating ${chalk.yellow(documentToRender)}`); throw new Error(validationResult.message); } try { await generateDocument({ apiKey, host, merge: false, content, mergeVars: {} }); } catch (error) { const errorMessage = getErrorMessage(error); if (errorMessage.includes('entity_too_large_error')) { throw new Error( `The document ${documentToRender} is too large. Please ensure the size of the rendered document is less than ${maxDocumentSizeString}.`, ); } if (errorMessage.includes('request_timeout_error')) { throw new Error( `Validation of document ${documentToRender} timed out. If the problem persists, please ensure the rendered document is less than ${maxDocumentSizeString}.`, ); } // Preserve the underlying error so the user can act on it. Without this, every // platform-side failure (template syntax error, missing merge var, 5xx, etc.) // collapses into the same opaque "Error validating document X" line. throw new Error( [ `Error validating document ${chalk.yellow(documentToRender)}`, `File: ${chalk.yellow(pathToFile)}`, '', 'Underlying error:', errorMessage .split('\n') .map((line) => ` ${line}`) .join('\n'), '', `Tip: open ${chalk.yellow(pathToFile)} and check for unmatched template tags, malformed HTML, or merge-var references that the renderer cannot resolve.`, ].join('\n'), ); } } } };