Skip to content

Commit

Permalink
fix!: Use Headers.prototype.getSetCookie to avoid comma-splitting
Browse files Browse the repository at this point in the history
Since Node.js now has `getSetCookie` available, we can use it instead of
splitting the header on comma, which was very error-prone.

Ref: nodejs/undici#1915

The linked PR was released as Undici v5.19.0, which is first available
in Node.js 18.14.1. Since Node.js 18.14.2 has an even more up-tp-date
version of Undici (5.20.0), I figured it'd be sensible to raise our
requirement to that.

BREAKING CHANGE: Engine version requirement raised to Node `>=18.14.2`.
  • Loading branch information
meyfa committed Mar 24, 2023
1 parent 286ba27 commit ee90121
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 9 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ A stateful HTTP client for NodeJS. Test your routes even when mocking is infeasi

## Usage

This package requires Node version 18 or later because it makes use of native `fetch()`.
This package requires Node version 18.14.2 or later because it makes use of native `fetch()`,
as well as `Headers.prototype.getSetCookie`.

Additionally, it is packaged as an ES module only, so your tests have to be in ESM format, too.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"prepack": "npm run build"
},
"engines": {
"node": ">=18"
"node": ">=18.14.2"
},
"repository": {
"type": "git",
Expand Down
8 changes: 2 additions & 6 deletions src/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ export function cookieMiddleware (store: CookieStore): Middleware {
}

function parseCookies (headers: Headers): Cookie[] {
// Node's Headers implementation returns all Set-Cookie headers joined by ', '
// TODO: Since dates are represented like "Wed, 12-Jul-2023 19:59:03 GMT", this will split too often!
const cookieDefinitions = headers.get('set-cookie')?.trim().split(/\s*,\s*/) ?? []

const cookies = []
for (const cookieDefinition of cookieDefinitions) {
// Note: Headers.prototype.getSetCookie() is available since Node.js 18.14.1, but types aren't updated yet.
for (const cookieDefinition of (headers as any).getSetCookie()) {
// TODO: Handle malformed strings, quoted values, escaping.
// TODO: Parse expiration date and flags.
const key = cookieDefinition.match(/^([^=\s]+)/)?.[1]
Expand All @@ -33,6 +30,5 @@ function parseCookies (headers: Headers): Cookie[] {
cookies.push({ key, value })
}
}

return cookies
}

0 comments on commit ee90121

Please sign in to comment.