2026-03-18 15:09:51 +01:00

38 lines
1.6 KiB
JavaScript

/**
* Recontextualize text or response object by replacing placeholders with original values.
* @param {string} text - String that may contain placeholders (e.g. PII_0, PII_1)
* @param {Array<{ placeholder: string, value: string }>} mapping - From anonymize()
* @returns {string}
*/
function recontextualizeText(text, mapping) {
if (text === null || text === undefined || typeof text !== "string") return text;
let out = text;
for (const m of mapping) {
const re = new RegExp(escapeRegex(m.placeholder), "g");
out = out.replace(re, m.value);
}
return out;
}
/**
* Recontextualize full response object (4 fields).
* @param {object} response - { answer, nextActionsTable, membersInfoSheet, synthesisRecommendation }
* @param {Array<{ placeholder: string, value: string }>} mapping
* @returns {object}
*/
function recontextualizeResponse(response, mapping) {
if (!response || !mapping || mapping.length === 0) return response;
const out = { ...response };
if (typeof out.answer === "string") out.answer = recontextualizeText(out.answer, mapping);
if (typeof out.nextActionsTable === "string") out.nextActionsTable = recontextualizeText(out.nextActionsTable, mapping);
if (typeof out.membersInfoSheet === "string") out.membersInfoSheet = recontextualizeText(out.membersInfoSheet, mapping);
if (typeof out.synthesisRecommendation === "string") out.synthesisRecommendation = recontextualizeText(out.synthesisRecommendation, mapping);
return out;
}
function escapeRegex(s) {
return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
module.exports = { recontextualizeText, recontextualizeResponse };