All files resolvedValues.ts

100% Statements 31/31
100% Branches 22/22
100% Functions 7/7
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63        377x   359x 359x 903x     359x               29x 21x 20x   19x 19x 31x 28x     19x       21x 21x             20x 20x 3x 1x     19x       52x 52x 52x   4x         41x    
export function replaceProtectedTokens(
  value: string,
  resolvedValues: ReadonlyMap<string, string> | undefined,
): string {
  if (!resolvedValues?.size) return value;
 
  let resolved = value;
  for (const [token, plaintext] of resolvedValues) {
    resolved = resolved.replaceAll(token, plaintext);
  }
 
  return resolved;
}
 
export function replaceProtectedBody(
  body: string,
  mimeType: string | undefined,
  resolvedValues: ReadonlyMap<string, string> | undefined,
): string {
  if (!resolvedValues?.size) return body;
  if (!isJSONMimeType(mimeType)) return replaceProtectedTokens(body, resolvedValues);
  if (!isValidJSONBody(body, mimeType)) return body;
 
  let resolved = body;
  for (const [token, plaintext] of resolvedValues) {
    if (!isJSONValue(plaintext)) continue;
    resolved = resolved.replaceAll(JSON.stringify(token), plaintext);
  }
 
  return resolved;
}
 
function isJSONMimeType(mimeType: string | undefined): boolean {
  const base = baseMimeType(mimeType);
  return base === "application/json"
    || base.endsWith("+json")
    || base === "application/x-ndjson"
    || base === "application/ndjson";
}
 
function isValidJSONBody(body: string, mimeType: string | undefined): boolean {
  const base = baseMimeType(mimeType);
  if (base === "application/x-ndjson" || base === "application/ndjson") {
    const documents = body.split(/\r?\n/).filter((line) => line.trim() !== "");
    return documents.length > 0 && documents.every(isJSONValue);
  }
 
  return isJSONValue(body);
}
 
function isJSONValue(value: string): boolean {
  try {
    JSON.parse(value);
    return true;
  } catch {
    return false;
  }
}
 
function baseMimeType(mimeType: string | undefined): string {
  return mimeType?.split(";", 1)[0].trim().toLowerCase() ?? "";
}