From 7bfec7f549f49233a26d8e3519ef195e7c897469 Mon Sep 17 00:00:00 2001 From: Sri Manaswi Chirumamilla Date: Thu, 28 May 2026 22:49:38 -0700 Subject: [PATCH] feat: add computeTTL and sanitizeValue utilities --- lib/utils.js | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/utils.js b/lib/utils.js index bf4ad04..d7019bd 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -117,8 +117,40 @@ function formatAjvErrors (errors) { return stringErrors } +/** + * Computes the TTL in seconds from an expiry date or a number of seconds. + * Returns undefined if no expiry is provided. + * + * @private + * @param {Date|number} expiry a Date object or seconds from now + * @returns {number|undefined} TTL in seconds + */ +function computeTTL (expiry) { + if (expiry === undefined || expiry === null) return undefined + if (expiry instanceof Date) { + return Math.floor((expiry.getTime() - Date.now()) / 1000) + } + return expiry +} + +/** + * Truncates a value to the max allowed byte size for state storage. + * + * @private + * @param {string} value the value to sanitize + * @param {number} maxBytes max allowed size in bytes + * @returns {string} the value, truncated if necessary + */ +function sanitizeValue (value, maxBytes) { + const encoded = Buffer.from(value) + if (encoded.length <= maxBytes) return value + return encoded.slice(0, maxBytes).toString() +} + module.exports = { withHiddenFields, isInternalToAdobeRuntime, - formatAjvErrors + formatAjvErrors, + computeTTL, + sanitizeValue }