From 593801e265e7609ac0bd695fcb450e479d5db776 Mon Sep 17 00:00:00 2001 From: Andreu Botella Date: Sun, 20 Mar 2022 14:31:12 +0100 Subject: cleanup(web, fetch): dedupe minesniff / "extract a MIME type" algorithm (#14044) Closes #14002 --- ext/web/01_mimesniff.js | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- ext/web/internal.d.ts | 3 +++ 2 files changed, 51 insertions(+), 1 deletion(-) (limited to 'ext/web') diff --git a/ext/web/01_mimesniff.js b/ext/web/01_mimesniff.js index c6ac7c66c..d2c784d6e 100644 --- a/ext/web/01_mimesniff.js +++ b/ext/web/01_mimesniff.js @@ -12,6 +12,7 @@ const { ArrayPrototypeIncludes, Map, + MapPrototypeGet, MapPrototypeHas, MapPrototypeSet, RegExpPrototypeTest, @@ -207,5 +208,51 @@ return serialization; } - window.__bootstrap.mimesniff = { parseMimeType, essence, serializeMimeType }; + /** + * Part of the Fetch spec's "extract a MIME type" algorithm + * (https://fetch.spec.whatwg.org/#concept-header-extract-mime-type). + * @param {string[] | null} headerValues The result of getting, decoding and + * splitting the "Content-Type" header. + * @returns {MimeType | null} + */ + function extractMimeType(headerValues) { + if (headerValues === null) return null; + + let charset = null; + let essence_ = null; + let mimeType = null; + for (const value of headerValues) { + const temporaryMimeType = parseMimeType(value); + if ( + temporaryMimeType === null || + essence(temporaryMimeType) == "*/*" + ) { + continue; + } + mimeType = temporaryMimeType; + if (essence(mimeType) !== essence_) { + charset = null; + const newCharset = MapPrototypeGet(mimeType.parameters, "charset"); + if (newCharset !== undefined) { + charset = newCharset; + } + essence_ = essence(mimeType); + } else { + if ( + !MapPrototypeHas(mimeType.parameters, "charset") && + charset !== null + ) { + MapPrototypeSet(mimeType.parameters, "charset", charset); + } + } + } + return mimeType; + } + + window.__bootstrap.mimesniff = { + parseMimeType, + essence, + serializeMimeType, + extractMimeType, + }; })(this); diff --git a/ext/web/internal.d.ts b/ext/web/internal.d.ts index 41d4c9b32..8e580495b 100644 --- a/ext/web/internal.d.ts +++ b/ext/web/internal.d.ts @@ -60,6 +60,9 @@ declare namespace globalThis { declare function parseMimeType(input: string): MimeType | null; declare function essence(mimeType: MimeType): string; declare function serializeMimeType(mimeType: MimeType): string; + declare function extractMimeType( + headerValues: string[] | null, + ): MimeType | null; } declare var eventTarget: { -- cgit v1.2.3