2 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
3 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
4 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
5 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
7 const ESCAPES = new Map([
20 function unescape(c) {
21 if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
22 return String.fromCharCode(parseInt(c.slice(1), 16));
25 return ESCAPES.get(c) || c;
28 function parseArguments(name, args) {
30 const chunks = args.trim().split(/\s*,\s*/g);
33 for (const chunk of chunks) {
35 results.push(Number(chunk));
36 } else if ((matches = chunk.match(STRING_REGEX))) {
37 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
39 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
46 function parseStyle(style) {
47 STYLE_REGEX.lastIndex = 0;
52 while ((matches = STYLE_REGEX.exec(style)) !== null) {
53 const name = matches[1];
56 const args = parseArguments(name, matches[2]);
57 results.push([name].concat(args));
66 function buildStyle(chalk, styles) {
69 for (const layer of styles) {
70 for (const style of layer.styles) {
71 enabled[style[0]] = layer.inverse ? null : style.slice(1);
76 for (const styleName of Object.keys(enabled)) {
77 if (Array.isArray(enabled[styleName])) {
78 if (!(styleName in current)) {
79 throw new Error(`Unknown Chalk style: ${styleName}`);
82 if (enabled[styleName].length > 0) {
83 current = current[styleName].apply(current, enabled[styleName]);
85 current = current[styleName];
93 module.exports = (chalk, tmp) => {
98 // eslint-disable-next-line max-params
99 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
101 chunk.push(unescape(escapeChar));
103 const str = chunk.join('');
105 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
106 styles.push({inverse, styles: parseStyle(style)});
108 if (styles.length === 0) {
109 throw new Error('Found extraneous } in Chalk template literal');
112 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
120 chunks.push(chunk.join(''));
122 if (styles.length > 0) {
123 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
124 throw new Error(errMsg);
127 return chunks.join('');