Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support usage in cloudflare workers #27

Merged
merged 7 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node_version: [14, 16]
node_version: [18, 20]
steps:
- uses: actions/checkout@v3

Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"lib"
],
"engines": {
"node": ">=14"
"node": ">=18"
},
"devDependencies": {
"@commitlint/cli": "^16.0.3",
Expand All @@ -41,6 +41,7 @@
"commitizen": "^4.2.4",
"cz-conventional-changelog": "^3.3.0",
"jest": "^26.6.3",
"jest-environment-miniflare": "^2.14.1",
mattcosta7 marked this conversation as resolved.
Show resolved Hide resolved
"rimraf": "^3.0.2",
"set-cookie-parser": "^2.4.6",
"simple-git-hooks": "^2.7.0",
Expand All @@ -50,4 +51,4 @@
"typescript": "^4.0.5",
"whatwg-fetch": "^3.5.0"
}
}
}
53 changes: 33 additions & 20 deletions src/store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Cookie, parse as parseCookie } from 'set-cookie-parser'

interface RequestLike {
credentials: Request['credentials']
credentials?: Request['credentials']
url: string
}

Expand Down Expand Up @@ -49,8 +49,14 @@ class CookieStore {
* Respects the `request.credentials` policy.
*/
add(request: RequestLike, response: ResponseLike): void {
if (request.credentials === 'omit') {
return
try {
if (request.credentials === 'omit') {
return
}
} catch {
// Ignore errors thrown by `request.credentials` access, such as those in cloudflare workers
mattcosta7 marked this conversation as resolved.
Show resolved Hide resolved
// We can't just check that `credentials` is in request, because it is in cloudflare workers test environment
// however access throws an error
}

const requestUrl = new URL(request.url)
Expand Down Expand Up @@ -89,28 +95,35 @@ class CookieStore {
const originCookies =
this.store.get(requestUrl.origin) || new Map<string, Cookie>()

switch (request.credentials) {
case 'include': {
// Support running this method in Node.js.
if (typeof document === 'undefined') {
return originCookies
}
try {
switch (request.credentials) {
case 'include': {
// Support running this method in Node.js.
if (typeof document === 'undefined') {
return originCookies
}

const documentCookies = parseCookie(document.cookie)
const documentCookies = parseCookie(document.cookie)

documentCookies.forEach((cookie) => {
originCookies.set(cookie.name, cookie)
})
documentCookies.forEach((cookie) => {
originCookies.set(cookie.name, cookie)
})

return originCookies
}
return originCookies
}

case 'same-origin': {
return originCookies
}
case 'same-origin': {
return originCookies
}

default:
return new Map()
default:
return new Map()
}
} catch {
// Ignore errors thrown by `request.credentials` access, such as those in cloudflare workers
// We can't just check that `credentials` is in request, because it is in cloudflare workers test environment
// however access throws an error
return originCookies
mattcosta7 marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
90 changes: 90 additions & 0 deletions test/get.worker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* @jest-environment miniflare
*/
import { store } from '../src'

afterEach(() => {
store.clear()
})

it('stores cookies for the given request', () => {
const req = new Request('https://mswjs.io')
const res = new Response(null, {
headers: new Headers({ 'Set-Cookie': 'cookieName=abc-123' }),
})

store.add(req, res)

const allCookies = Array.from(store.getAll().entries())
expect(allCookies).toEqual([
[
'https://mswjs.io',
new Map([['cookieName', { name: 'cookieName', value: 'abc-123' }]]),
],
])
})

it('returns cookies for the requests with credentials "include"', () => {
const req = new Request('https://mswjs.io', {
credentials: 'include',
})
const res = new Response(null, {
headers: new Headers({ 'Set-Cookie': 'secret=abc-123' }),
})
store.add(req, res)

const cookies = store.get(req)
expect(cookies).toEqual(
new Map([
[
'secret',
{
name: 'secret',
value: 'abc-123',
maxAge: undefined,
expires: undefined,
},
],
]),
)
})

it('returns cookies for the requests with credentials "same-origin"', () => {
const req = new Request('https://mswjs.io', {
credentials: 'same-origin',
})
const res = new Response(null, {
headers: new Headers({ 'Set-Cookie': 'secret=abc-123' }),
})

store.add(req, res)
store.add(
{
url: 'https://test.io',
credentials: 'include',
},
new Response(null, {
headers: new Headers({ 'Set-Cookie': 'anotherCookie=yes' }),
}),
)

const cookies = store.get(req)
expect(cookies).toEqual(
new Map([['secret', { name: 'secret', value: 'abc-123' }]]),
)
})

it('returns cookies for the requests with credentials "omit"', () => {
const req = new Request('https://mswjs.io', {
credentials: 'omit',
})
const res = new Response(null, {
headers: new Headers({ 'Set-Cookie': 'secret=abc-123' }),
})
store.add(req, res)

const cookies = store.get(req)
expect(cookies).toEqual(
new Map([['secret', { name: 'secret', value: 'abc-123' }]]),
)
})
19 changes: 11 additions & 8 deletions test/invalid-store.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* @jest-environment jsdom
*/
import { mocked } from 'ts-jest/utils'
import { store, PERSISTENCY_KEY } from '../src'

afterEach(() => {
Expand All @@ -10,17 +11,19 @@ afterEach(() => {
it('should reset the store if contains an invalid value', () => {
jest.spyOn(global.console, 'warn').mockImplementation(() => {})
localStorage.setItem(PERSISTENCY_KEY, 'not valid json')

const mockConsole = mocked(global.console.warn)
expect(() => store.hydrate()).not.toThrow()
expect(localStorage.getItem(PERSISTENCY_KEY)).toBeNull()
expect(console.warn).toHaveBeenCalledWith(`
const errorMessage = mockConsole.mock.calls[0][0]
expect(errorMessage).toContain(`
[virtual-cookie] Failed to parse a stored cookie from the localStorage (key \"MSW_COOKIE_STORE\").

Stored value:
not valid json

Thrown exception:
SyntaxError: Unexpected token o in JSON at position 1

Invalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`)
not valid json`)
// not asserting on the entire error message because it's different in different node versions
expect(errorMessage).toContain(`Thrown exception:
SyntaxError: Unexpected token`)
expect(errorMessage).toContain(
`Invalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`,
)
mattcosta7 marked this conversation as resolved.
Show resolved Hide resolved
})
Loading
Loading