// The one MIME multipart reader for requests and published examples. Dependency-free, side-effect-free and // byte-preserving: a browser bundle imports it, and empty field names and binary uploads must survive reading. export type MultipartPart = { name: string; filename: string | null; type: string | null; body: Uint8Array }; export type MultipartFramedPart = MultipartPart & { headers: Uint8Array; leading: Uint8Array; separator: Uint8Array; trailing: Uint8Array; }; export type MultipartEnvelope = { complete: boolean; preamble: Uint8Array; epilogue: Uint8Array; delimiters: Uint8Array[]; parts: MultipartFramedPart[]; }; /** The boundary named by any multipart media type. */ export function multipartBoundary(contentType: string | null | undefined): string | null { if (!contentType || !/^multipart\//i.test(contentType)) return null; const hit = /\bboundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i.exec(contentType); return hit ? (hit[1] ?? hit[2]!) : null; } type Line = { at: number; end: number; after: number }; function byteLines(bytes: Uint8Array): Line[] { const lines: Line[] = []; for (let at = 0; at < bytes.length;) { let end = at; while (end < bytes.length && bytes[end] !== 13 && bytes[end] !== 10) end++; const after = end === bytes.length ? end : end + (bytes[end] === 13 && bytes[end + 1] === 10 ? 2 : 1); lines.push({ at, end, after }); at = after; } return lines; } /** Used both by the byte reader and by consumers guarding placeholder spans within a part. */ export function multipartDelimiterPattern(boundary: string): string { const literal = boundary.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&'); // Include malformed whitespace-before-close lines in the guard: they cannot be hidden in a value either. return '(?:^|(?<=[\\r\\n]))--' + literal + '(?:--|[ \\t]+--)?[ \\t]*(?=\\r\\n|\\n|\\r|$)'; } /** Infer only a boundary with a corresponding closing line; Content-Type remains authoritative when supplied. */ export function inferMultipartBoundary(bytes: Uint8Array): string | null { const decoder = new TextDecoder(); const lines = byteLines(bytes).map(({ at, end }) => decoder.decode(bytes.subarray(at, end))); for (const line of lines) { if (!line.startsWith('--')) continue; const boundary = line.slice(2).replace(/[ \t]+$/, ''); if (boundary && lines.some((closing) => closing.replace(/[ \t]+$/, '') === '--' + boundary + '--')) return boundary; } return null; } /** Read MIME fields once, unfolding continuations for interpretation while retaining raw bytes in the envelope. */ function mimeHeaders(raw: Uint8Array): Map | undefined { const fields = new Map(); let previous: string | undefined; for (const line of new TextDecoder().decode(raw).split(/\r\n|\n|\r/)) { if (!line) continue; if (/^[ \t]/.test(line)) { if (!previous) return undefined; fields.set(previous, fields.get(previous)! + ' ' + line.trim()); } else { const field = /^([^\s:]+):[ \t]*(.*)$/.exec(line); if (!field) return undefined; previous = field[1]!.toLowerCase(); fields.set(previous, field[2]!.trim()); } } return fields; } /** Raw MIME framing and interpreted parts. A malformed tail ends reading and leaves `complete` false. */ export function multipartEnvelope(bytes: Uint8Array, boundary: string): MultipartEnvelope { const empty = new Uint8Array(); const result: MultipartEnvelope = { complete: false, preamble: bytes.slice(), epilogue: empty, delimiters: [], parts: [] }; const lines = byteLines(bytes); const decoder = new TextDecoder(); const prefix = '--' + boundary; const hits: Array = []; for (const line of lines) { const text = decoder.decode(bytes.subarray(line.at, line.end)); if (!text.startsWith(prefix)) continue; const suffix = text.slice(prefix.length); const closing = /^--[ \t]*$/.test(suffix); const valid = closing || /^[ \t]*$/.test(suffix); if (!valid && !/^[ \t]+--[ \t]*$/.test(suffix)) continue; hits.push({ ...line, closing, valid }); if (closing || !valid) break; } if (!hits.length) return result; result.preamble = bytes.slice(0, hits[0]!.at); result.delimiters = hits.map(({ at, end }) => bytes.slice(at, end)); for (let i = 0; i < hits.length - 1; i++) { const current = hits[i]!; const next = hits[i + 1]!; if (!current.valid || current.closing || current.after === current.end || !next.valid) return result; const headerLines = lines.filter((line) => line.at >= current.after && line.at < next.at); const blank = headerLines.find((line) => line.at === line.end); if (!blank) return result; const previous = headerLines.find((line) => line.after === blank.at); const headersEnd = previous?.end ?? blank.at; const headers = bytes.slice(current.after, headersEnd); const fields = mimeHeaders(headers); if (!fields) return result; const beforeNext = lines.find((line) => line.after === next.at); // The line break immediately before a delimiter belongs to framing, never to the uploaded bytes. const bodyEnd = Math.max(blank.after, beforeNext?.end ?? next.at); const disposition = fields.get('content-disposition') ?? ''; result.parts.push({ name: /\bname="([^"]*)"/i.exec(disposition)?.[1] ?? '', filename: /\bfilename="([^"]*)"/i.exec(disposition)?.[1] ?? null, type: fields.get('content-type')?.trim() ?? null, body: bytes.slice(blank.after, bodyEnd), headers, leading: bytes.slice(current.end, current.after), separator: bytes.slice(headersEnd, blank.after), trailing: bytes.slice(bodyEnd, next.at), }); } const last = hits.at(-1)!; result.complete = last.valid && last.closing; if (result.complete) result.epilogue = bytes.slice(last.end); return result; } /** The request's parts, in order, using the same framing reader as wire comparison. */ export function multipartParts(bytes: Uint8Array, boundary: string): MultipartPart[] { return multipartEnvelope(bytes, boundary).parts.map(({ name, filename, type, body }) => ({ name, filename, type, body })); }