import { isIterator, isToken, needsEncoding } from "./_util.ts";
export function formatMediaType( type: string, param?: Record<string, string> | Iterable<[string, string]>,): string { let b = ""; const [major, sub] = type.split("/"); if (!sub) { if (!isToken(type)) { return ""; } b += type.toLowerCase(); } else { if (!isToken(major) || !isToken(sub)) { return ""; } b += `${major.toLowerCase()}/${sub.toLowerCase()}`; }
if (param) { param = isIterator(param) ? Object.fromEntries(param) : param; const attrs = Object.keys(param); attrs.sort();
for (const attribute of attrs) { if (!isToken(attribute)) { return ""; } const value = param[attribute]; b += `; ${attribute.toLowerCase()}`;
const needEnc = needsEncoding(value); if (needEnc) { b += "*"; } b += "=";
if (needEnc) { b += `utf-8''${encodeURIComponent(value)}`; continue; }
if (isToken(value)) { b += value; continue; } b += `"${value.replace(/["\\]/gi, (m) => `\\${m}`)}"`; } } return b;}