import type Token from 'markdown-it/lib/token'; import type {MarkdownItPluginCb, MarkdownItPluginOpts} from '../typings'; import type {ImageOptions, StateCore} from '../../typings'; import type {IDGenerator} from '../utils'; import type {PluginConfig} from '../../svgo'; import {join, sep} from 'path'; import {bold} from 'chalk'; import {readFileSync} from 'fs'; import {isFileExists, resolveRelativePath} from '../../utilsFS'; import {filterTokens, getSrcTokenAttr, isExternalHref} from '../../utils'; import {generateID as globalGenerateID} from '../utils'; import {optimize} from '../../svgo'; import {getLogger} from '../../log'; const SVG_ENTITY_LIMIT_HINT = 'To inline this SVG, set svgMaxEntityCount in Transform or content.svgMaxEntityCount / --svg-max-entity-count in CLI.'; function isSvgEntityLimitError(error: unknown): error is Error { return ( error instanceof Error && error.name === 'SvgoParserError' && error.message.includes('Parsed entity count exceeds max entity count') ); } const sanitizeAttribute = (value: string): string => value.replace(/(\d*[%a-z]{0,5}).*/gi, '$1'); const sanitizeHTMLAttr = (value: string): string => { return value .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); }; interface ImageOpts extends MarkdownItPluginOpts { assetsPublicPath: string; inlineSvg?: boolean; } function replaceImageSrc( state: StateCore, currentPath: string, path: string, imgSrc: string, {assetsPublicPath = sep, root = '', log}: ImageOpts, ) { if (isFileExists(path)) { state.md.assets?.push(imgSrc); } else { log.error(`Asset not found: ${bold(imgSrc)} in ${bold(currentPath)}`); } const relativeToRoot = path.replace(root + sep, ''); const publicSrc = join(assetsPublicPath, relativeToRoot); // Normalize path separators to forward slashes for cross-platform compatibility return publicSrc.replace(/\\/g, '/'); } interface InlineOptions { enabled: boolean; maxFileSize: number; } interface SVGOpts extends MarkdownItPluginOpts { notFoundCb: (s: string) => void; imageOpts: ImageOptions; svgInline: InlineOptions; } function getSvgContent(file: string, from: string, {rawContent, notFoundCb, log, root = ''}: Opts) { try { const content = rawContent(file); if (!content || typeof content !== 'string') { return null; } return content; } catch { const path = file.replace(root, ''); // Normalize path separators to forward slashes for cross-platform compatibility const normalizedPath = path.replace(/\\/g, '/'); log.error(`SVG ${normalizedPath} from ${from} not found`); try { if (notFoundCb) { notFoundCb(normalizedPath); } } catch { // notFoundCb may throw in some backends (e.g. memcache) // to signal that the file needs to be fetched } return null; } } type Opts = SVGOpts & ImageOpts & { rawContent: (path: string) => string; calcPath: (root: string, path: string) => string; replaceImageSrc: ( state: StateCore, currentPath: string, path: string, imgSrc: string, opts: ImageOpts, ) => string; file: string; }; function shouldBeInlined(token: Token, opts: InlineOptions) { if (!token.attrGet('src')?.endsWith('.svg')) { return false; } const forceInlineSvg = token.attrGet('inline') === 'true'; const shouldInlineSvg = forceInlineSvg || (token.attrGet('inline') !== 'false' && opts.enabled !== false); return shouldInlineSvg; } function isGalleryValid(value: string): boolean { return value === 'true' || value === 'false'; } function resolveGallerySrcAttr( key: string, value: string, state: StateCore, from: string, calcPath: (root: string, path: string) => string, replaceImage: typeof replaceImageSrc, opts: ImageOpts, ): [string, string] | null { if (key !== 'gallery-src' && key !== 'data-gallery-src') { return null; } if (!value) { return null; } const galleryFile = calcPath(from, value); const processedSrc = replaceImage(state, from, galleryFile, value, opts); return ['data-gallery-src', processedSrc]; } function collectDataAttrs( image: Token, state: StateCore, from: string, calcPath: (root: string, path: string) => string, replaceImage: typeof replaceImageSrc, opts: ImageOpts, ): Record { const result: Record = {}; if (!image.attrs) { return result; } for (const [key, value] of image.attrs) { if (key === 'gallery' && isGalleryValid(value)) { result['data-gallery'] = value; continue; } if (key === 'gallery-id' && value !== '') { result['data-gallery-id'] = value; continue; } const gallerySrc = resolveGallerySrcAttr( key, value, state, from, calcPath, replaceImage, opts, ); if (gallerySrc) { result[gallerySrc[0]] = gallerySrc[1]; continue; } if ( key.startsWith('data-') && key !== 'data-gallery-src' && (key !== 'data-gallery-id' || value !== '') && (key !== 'data-gallery' || isGalleryValid(value)) ) { result[key] = value; } } image.attrs = image.attrs.filter( ([key, value]) => key !== 'gallery' && key !== 'gallery-id' && key !== 'gallery-src' && (key !== 'data-gallery' || isGalleryValid(value)) && (key !== 'data-gallery-id' || value !== '') && (key !== 'data-gallery-src' || value !== ''), ); if (result['data-gallery-id']) { result['data-gallery'] = 'true'; } return result; } const getRawFile = (path: string) => { return readFileSync(path, 'utf8').toString(); }; const index: MarkdownItPluginCb = (md, opts) => { const { rawContent = getRawFile, calcPath = resolveRelativePath, replaceImageSrc: replaceImage = replaceImageSrc, } = opts; // TODO:goldserg need remove support opts.inlineSvg if (opts.inlineSvg !== undefined) { opts.svgInline = { ...opts.svgInline, enabled: opts.inlineSvg, }; } md.assets = []; function processImageToken( image: Token, tokenIndex: number, childrenTokens: Token[], state: StateCore, ): void { if (image.attrGet('yfm_patched')) { return; } const imgSrc = getSrcTokenAttr(image); if (isExternalHref(imgSrc)) { return; } const from = state.env.path || opts.path; const dataAttrs = collectDataAttrs(image, state, from, calcPath, replaceImage, opts); const forceInlineSvg = image.attrGet('inline') === 'true'; const imageOpts = { width: image.attrGet('width'), height: image.attrGet('height'), title: image.attrGet('title'), dataAttrs, }; const file = calcPath(from, imgSrc); if (shouldBeInlined(image, opts.svgInline)) { const svgContent = getSvgContent(file, from, {...opts, rawContent}); if (svgContent) { if (svgContent.length > opts.svgInline.maxFileSize && !forceInlineSvg) { image.attrSet( 'YFM011', `Svg size: ${svgContent.length}; Config size: ${opts.svgInline.maxFileSize}; Src: ${bold(file)}`, ); } else { const inlinedSvg = replaceSvgContent( svgContent, { ...imageOpts, svgMaxEntityCount: opts.svgMaxEntityCount, path: file, log: opts.log, }, opts.generateID, ); if (inlinedSvg) { const svgToken = new state.Token('image_svg', '', 0); svgToken.attrSet('content', inlinedSvg); childrenTokens[tokenIndex] = svgToken; } } } } if (childrenTokens[tokenIndex].type === 'image') { image.attrSet('src', replaceImage(state, from, file, imgSrc, opts)); image.attrSet('yfm_patched', '1'); for (const [key, value] of Object.entries(dataAttrs)) { image.attrSet(key, value); } } } const plugin = (state: StateCore) => { filterTokens(state.tokens, 'inline', (inline, {commented}) => { if (commented || !inline.children) { return; } const childrenTokens = inline.children; filterTokens(childrenTokens, 'image', (image, {commented, index}) => { if (!commented) { processImageToken(image, index, childrenTokens, state); } }); }); }; try { md.core.ruler.before('includes', 'images', plugin); } catch { md.core.ruler.push('images', plugin); } md.renderer.rules.image_svg = (tokens, index) => { const token = tokens[index]; return token.attrGet('content') || ''; }; }; function applyDataAttrs(svgRoot: string, dataAttrs: Record): string { let result = svgRoot; for (const [key, value] of Object.entries(dataAttrs)) { if (!result.includes(`${key}=`)) { result = `${result} ${key}="${sanitizeHTMLAttr(value)}"`; } } return result; } const removeProcessingInstructions: PluginConfig = { name: 'removeProcessingInstructions', fn: () => { return { instruction: { enter: (node, parent) => { const start = parent.children.indexOf(node); parent.children.splice(start, 1); }, }, }; }, }; /** * Return inline SVG, or an empty string when the original image must be kept. * @param {string | null} content Source SVG. * @param {ImageOptions} options Image, parser and diagnostic options. * @param {IDGenerator} generateID Generator used for SVG identifier prefixes. * @returns {string} Inline markup, or an empty result for the image fallback. */ function replaceSvgContent( content: string | null, options: ImageOptions, generateID: IDGenerator = globalGenerateID, ) { if (!content) { return ''; } // monoline content = content.replace(/>\r?\n<').replace(/\r?\n/g, ' '); let optimized; try { optimized = optimize(content, { ...(options.svgMaxEntityCount === undefined ? {} : {maxEntityCount: options.svgMaxEntityCount}), plugins: [ 'removeDoctype', {name: 'removeComments', params: {preservePatterns: []}}, removeProcessingInstructions, { name: 'prefixIds', params: { prefix: generateID('svg'), prefixClassNames: false, }, }, ], }); } catch (error) { if (!isSvgEntityLimitError(error)) { throw error; } getLogger(options.log).warn( `SVG entity limit reached: ${options.path ?? ''}. Keeping the image reference. ${SVG_ENTITY_LIMIT_HINT}`, ); return ''; } content = optimized.data; // width, height let svgRoot = content.replace(/.*?]*)>.*/g, '$1'); const {width, height} = svgRoot .match(/(?:width="(.*?)")|(?:height="(.*?)")/g) ?.reduce((acc: {[key: string]: string}, val) => { const [key, value] = val.split('='); acc[key] = value; return acc; }, {}) || {width: undefined, height: undefined}; if (!width && options.width) { const sanitizedWidth = sanitizeAttribute(options.width.toString()); svgRoot = `${svgRoot} width="${sanitizedWidth}"`; } if (!height && options.height) { const sanitizedHeight = sanitizeAttribute(options.height.toString()); svgRoot = `${svgRoot} height="${sanitizedHeight}"`; } if ((!width && options.width) || (!height && options.height)) { content = content.replace(/]*)>/, ``); } if (options.dataAttrs) { svgRoot = applyDataAttrs(svgRoot, options.dataAttrs); content = content.replace(/]*)>/, ``); } // title const hasTitle = /.*?<\/title>/i.test(content); if (!hasTitle && options.title) { // Insert title tag after the opening svg tag content = content.replace(/(<svg[^>]*>)/, `$1<title>${options.title}`); } return escapeMarkdownCharsInSvgTextNodes(content); } // Asterisks in SVG text nodes break markdown emphasis parsing when SVG is embedded in .md // (e.g. merge-svg): SAI_POLICER_STAT_* opens until the next * in *_PPS. function escapeMarkdownCharsInSvgTextNodes(content: string): string { return content.replace(/]*)>([^<]*)<\/text>/gi, (_match, attrs, text) => { const escaped = text.replace(/\*/g, '*'); return `${escaped}`; }); } // Create an object that is the index function with an additional replaceSvgContent property const imagesPlugin: typeof index & { replaceSvgContent: typeof replaceSvgContent; } = Object.assign(index, { replaceSvgContent, }); export = imagesPlugin;