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

[TypeScript] insomnia-cookies #5

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions packages/insomnia-cookies/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
src/tough-cookie.d.ts
node_modules
dist
20 changes: 20 additions & 0 deletions packages/insomnia-cookies/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

// @ts-check
/** @type { import('@jest/types').Config.InitialOptions } */
module.exports = {
globals: {
'ts-jest': {
isolatedModules: true,
},
},
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: ['.+\\.test\\.ts$'],
collectCoverage: false,
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
coverageReporters: ['text-summary', 'lcov'],
};
4,875 changes: 4,875 additions & 0 deletions packages/insomnia-cookies/package-lock.json

Large diffs are not rendered by default.

20 changes: 18 additions & 2 deletions packages/insomnia-cookies/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,25 @@
"author": "Gregory Schier <greg.schier@konghq.com>",
"description": "Cookie utilities",
"license": "MIT",
"main": "index.js",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"package.json",
"READEME.md"
dimitropoulos marked this conversation as resolved.
Show resolved Hide resolved
],
"scripts": {
"test": "jest --silent"
"bootstrap": "npm run build",
"lint": "eslint . --ext .js,.ts,.tsx",
"clean": "tsc --build tsconfig.build.json --clean",
"postclean": "rimraf dist",
"build": "tsc --build tsconfig.build.json",
"test": "jest"
},
"devDependencies": {
"jest": "^26.6.3",
"ts-jest": "^26.5.3",
"typescript": "^4.2.3"
},
"dependencies": {
"tough-cookie": "^2.3.3"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { CookieJar } = require('tough-cookie');
const { jarFromCookies, cookiesFromJar } = require('..');
import { CookieJar, Cookie, CookieSerialized } from 'tough-cookie';
import { jarFromCookies, cookiesFromJar } from './cookies';

describe('jarFromCookies()', () => {
it('returns valid cookies', done => {
Expand All @@ -8,7 +8,7 @@ describe('jarFromCookies()', () => {
key: 'foo',
value: 'bar',
domain: 'google.com',
},
} as Cookie,
]);

jar.store.getAllCookies((err, cookies) => {
Expand All @@ -23,6 +23,7 @@ describe('jarFromCookies()', () => {
});

it('handles malformed JSON', () => {
// @ts-expect-error this test is verifying that an invalid input is handled appropriately
const jar = jarFromCookies('not a jar');
expect(jar.constructor.name).toBe('CookieJar');
});
Expand All @@ -31,7 +32,7 @@ describe('jarFromCookies()', () => {
describe('cookiesFromJar()', () => {
it('returns valid jar', async () => {
const d = new Date();
const initialCookies = [
const initialCookies: CookieSerialized[] = [
{
key: 'bar',
value: 'baz',
Expand All @@ -41,7 +42,7 @@ describe('cookiesFromJar()', () => {
{
// This one will fail to parse, and be skipped
bad: 'cookie',
},
} as CookieSerialized,
];

const jar = CookieJar.fromJSON({ cookies: initialCookies });
Expand All @@ -58,12 +59,12 @@ describe('cookiesFromJar()', () => {
it('handles bad jar', async () => {
const jar = CookieJar.fromJSON({ cookies: [] });

// MemoryStore never actually throws errors, so lets mock the
// function to force it to this time.
// MemoryStore never actually throws errors, so lets mock the function to force it to this time.
// @ts-expect-error intentionally invalid value
jar.store.getAllCookies = cb => cb(new Error('Dummy Error'));
const cookies = await cookiesFromJar(jar);

// Cookies failed to p
// Cookies failed to parse
expect(cookies.length).toBe(0);
});
});
Original file line number Diff line number Diff line change
@@ -1,40 +1,36 @@
const { CookieJar, Cookie } = require('tough-cookie');
import { CookieJar, Cookie, CookieJSON } from 'tough-cookie';

/**
* Get a list of cookie objects from a request.jar()
*
* @param jar
*/
module.exports.cookiesFromJar = function(jar) {
export const cookiesFromJar = (cookieJar: CookieJar): Promise<CookieJSON[]> => {
return new Promise(resolve => {
jar.store.getAllCookies((err, cookies) => {
cookieJar.store.getAllCookies((err, cookies) => {
if (err) {
console.warn('Failed to get cookies form jar', err);
resolve([]);
} else {
// NOTE: Perform toJSON so we have a plain JS object instead of Cookie instance
resolve(cookies.map(c => c.toJSON()));
resolve(cookies.map(cookie => cookie.toJSON()));
}
});
});
};

/**
* Get a request.jar() from a list of cookie objects
*
* @param cookies
*/
module.exports.jarFromCookies = function(cookies) {
let jar;
export const jarFromCookies = (cookies: Cookie[]) => {
let jar: CookieJar;

try {
// For some reason, fromJSON modifies `cookies`. Create a copy first
// just to be sure
// For some reason, fromJSON modifies `cookies`.
// Create a copy first just to be sure.
const copy = JSON.stringify({ cookies });
jar = CookieJar.fromJSON(copy);
} catch (e) {
console.log('[cookies] Failed to initialize cookie jar', e);
jar = new CookieJar();
jar = new CookieJar() as CookieJar;
}

jar.rejectPublicSuffixes = false;
Expand All @@ -43,18 +39,21 @@ module.exports.jarFromCookies = function(cookies) {
return jar;
};

module.exports.cookieToString = function(cookie) {
export const cookieToString = (cookie: Parameters<typeof Cookie.fromJSON>[0] | Cookie) => {
// Cookie can either be a plain JS object or Cookie instance
if (!(cookie instanceof Cookie)) {
cookie = Cookie.fromJSON(cookie);
}
cookie = Cookie.fromJSON(cookie) as Cookie;

if (cookie === null) {
throw new Error('asdf');
dimitropoulos marked this conversation as resolved.
Show resolved Hide resolved
}
}
let str = cookie.toString();

// tough-cookie toString() doesn't put domain on all the time.
// This hack adds when tough-cookie won't
if (cookie.domain && cookie.hostOnly) {
str += '; Domain=' + cookie.domain;
if ((cookie as Cookie).domain && (cookie as Cookie).hostOnly) {
str += `; Domain=${(cookie as Cookie).domain}`;
}

return str;
Expand Down
1 change: 1 addition & 0 deletions packages/insomnia-cookies/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { cookiesFromJar, jarFromCookies, cookieToString } from './cookies';
Loading