From eff5e3e85fdc04446f0a813611616a0a593b8ed1 Mon Sep 17 00:00:00 2001 From: Yagiz Nizipli Date: Wed, 22 Feb 2023 09:20:13 -0500 Subject: [PATCH] perf: optimize happy path (#1955) * perf: do not call url.format if not needed * perf: return early on parseURL * perf: remove the usage of url.format from serializer --- lib/core/util.js | 6 ++++++ lib/fetch/dataURL.js | 13 +++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/core/util.js b/lib/core/util.js index 334bc26c776..75e632118a7 100644 --- a/lib/core/util.js +++ b/lib/core/util.js @@ -46,6 +46,12 @@ function buildURL (url, queryParams) { function parseURL (url) { if (typeof url === 'string') { url = new URL(url) + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('invalid protocol') + } + + return url } if (!url || typeof url !== 'object') { diff --git a/lib/fetch/dataURL.js b/lib/fetch/dataURL.js index 0d4a46956db..beefad15482 100644 --- a/lib/fetch/dataURL.js +++ b/lib/fetch/dataURL.js @@ -1,6 +1,5 @@ const assert = require('assert') const { atob } = require('buffer') -const { format } = require('url') const { isValidHTTPToken, isomorphicDecode } = require('./util') const encoder = new TextEncoder() @@ -118,7 +117,17 @@ function dataURLProcessor (dataURL) { * @param {boolean} excludeFragment */ function URLSerializer (url, excludeFragment = false) { - return format(url, { fragment: !excludeFragment }) + const href = url.href + + if (!excludeFragment) { + return href + } + + const hash = href.lastIndexOf('#') + if (hash === -1) { + return href + } + return href.slice(0, hash) } // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points