From 719539c2abfd7e14fb338b8d32e627fd2d7170f6 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Wed, 26 Jun 2024 21:58:57 +0300 Subject: [PATCH] Improve types and sanitation of macro values --- public/scripts/macros.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/public/scripts/macros.js b/public/scripts/macros.js index 0465eda2c..992150894 100644 --- a/public/scripts/macros.js +++ b/public/scripts/macros.js @@ -13,17 +13,22 @@ Handlebars.registerHelper('helperMissing', function () { return substituteParams(`{{${macroName}}}`); }); +/** + * @typedef {Object} EnvObject + * @typedef {(nonce: string) => string} MacroFunction + */ + export class MacrosParser { /** * A map of registered macros. - * @type {Map string)>} + * @type {Map} */ static #macros = new Map(); /** * Registers a global macro that can be used anywhere where substitution is allowed. * @param {string} key Macro name (key) - * @param {string|((nonce: string) => string)} value A string or a function that returns a string + * @param {string|MacroFunction} value A string or a function that returns a string */ static registerMacro(key, value) { if (typeof key !== 'string') { @@ -55,7 +60,7 @@ export class MacrosParser { /** * Populate the env object with macro values from the current context. - * @param {Object} env Env object for the current evaluation context + * @param {EnvObject} env Env object for the current evaluation context * @returns {void} */ static populateEnv(env) { @@ -88,6 +93,20 @@ export class MacrosParser { return ''; } + if (value instanceof Promise) { + console.warn('Promises are not supported as macro values'); + return ''; + } + + if (typeof value === 'function') { + console.warn('Functions are not supported as macro values'); + return ''; + } + + if (value instanceof Date) { + return value.toISOString(); + } + if (typeof value === 'object') { return JSON.stringify(value); } @@ -367,7 +386,7 @@ function timeDiffReplace(input) { /** * Substitutes {{macro}} parameters in a string. * @param {string} content - The string to substitute parameters in. - * @param {Object} env - Map of macro names to the values they'll be substituted with. If the param + * @param {EnvObject} env - Map of macro names to the values they'll be substituted with. If the param * values are functions, those functions will be called and their return values are used. * @returns {string} The string with substituted parameters. */