Skip to content

Commit c5d73ca

Browse files
authoredNov 28, 2023
fix: correctly handle data URL with hashes. (#2475)
* fix: correctly handle data URL with hashes. * fix: lint * test: better name * suggestion change * perf: avoid substring * fixup * test: better
1 parent 0437f69 commit c5d73ca

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed
 

‎lib/fetch/dataURL.js

+5-8
Original file line numberDiff line numberDiff line change
@@ -119,17 +119,14 @@ function dataURLProcessor (dataURL) {
119119
* @param {boolean} excludeFragment
120120
*/
121121
function URLSerializer (url, excludeFragment = false) {
122-
const href = url.href
123-
124122
if (!excludeFragment) {
125-
return href
123+
return url.href
126124
}
127125

128-
const hash = href.lastIndexOf('#')
129-
if (hash === -1) {
130-
return href
131-
}
132-
return href.slice(0, hash)
126+
const href = url.href
127+
const hashLength = url.hash.length
128+
129+
return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
133130
}
134131

135132
// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points

‎test/fetch/data-uri.js

+21
Original file line numberDiff line numberDiff line change
@@ -191,3 +191,24 @@ test('https://domain.com/?', (t) => {
191191
const serialized = URLSerializer(new URL(domain))
192192
t.equal(serialized, domain)
193193
})
194+
195+
// https://github.com/nodejs/undici/issues/2474
196+
test('hash url', (t) => {
197+
t.plan(1)
198+
const domain = 'https://domain.com/#a#b'
199+
const url = new URL(domain)
200+
const serialized = URLSerializer(url, true)
201+
t.equal(serialized, url.href.substring(0, url.href.length - url.hash.length))
202+
})
203+
204+
// https://github.com/nodejs/undici/issues/2474
205+
test('data url that includes the hash', async (t) => {
206+
t.plan(1)
207+
const dataURL = 'data:,node#js#'
208+
try {
209+
const res = await fetch(dataURL)
210+
t.equal(await res.text(), 'node')
211+
} catch (error) {
212+
t.fail(`failed to fetch ${dataURL}`)
213+
}
214+
})

0 commit comments

Comments
 (0)
Please sign in to comment.