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

[RFC] Record / Replay modes #7

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
22 changes: 12 additions & 10 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const App = () => {
<ChakraProvider>
<MSWToolbar
worker={worker}
apiUrl="http://www.example.com"
apiUrl="https://pokeapi.co"
isEnabled={true}
actions={
<HStack spacing={2}>
Expand All @@ -36,16 +36,18 @@ const App = () => {
prefix={APP_NAME}
>
<Button
onClick={() =>
fetch('http://www.example.com').then(async (res) => {
if (res.ok) {
const content = await res.json();
alert(
`Here is the mocked response!: ${JSON.stringify(content)}`
);
onClick={() => {
fetch('https://pokeapi.co/api/v2/pokemon/ditto').then(
async (res) => {
if (res.ok) {
const content = await res.json();
alert(
`Here is the mocked response!: ${JSON.stringify(content)}`
);
}
}
})
}
);
}}
mt={50}
>
Make a request
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
],
"devDependencies": {
"@size-limit/preset-small-lib": "^5.0.4",
"@types/har-format": "^1.2.7",
"@types/react": "^17.0.24",
"@types/react-dom": "^17.0.9",
"husky": "^7.0.0",
Expand All @@ -66,5 +67,9 @@
"tsdx": "^0.14.1",
"tslib": "^2.3.1",
"typescript": "^4.4.3"
},
"dependencies": {
"headers-utils": "^3.0.2",
"set-cookie-parser": "^2.4.8"
}
}
62 changes: 43 additions & 19 deletions src/component/MSWToolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import * as React from 'react';
import { rest } from 'msw';
import {
SetupWorkerApi,
MockedRequest,
ResponseComposition,
RestContext,
} from 'msw';
import { SetupWorkerApi } from 'msw';
import { usePrevious } from './hooks';
import styles from './styles.module.css';
import { WorkerMode } from '../types';
import { get, modes, set } from '../helpers';
import { MSWToolbarProps } from '..';
import { buildHandlersForTrackedRequests, get, modes, set } from '../helpers';
import { MSWToolbarProps, TrackedRequest } from '..';

/**
* This is a simple toolbar that allows you to toggle MSW handlers in local development as well as easily invalidate all of the caches.
Expand All @@ -35,6 +30,7 @@ export const MSWToolbar = ({
}

const workerRef = React.useRef<SetupWorkerApi>();
const trackedRequestsRef = React.useRef<TrackedRequest>(new Map());

const [isReady, setIsReady] = React.useState(isEnabled ? false : true);

Expand Down Expand Up @@ -83,22 +79,50 @@ export const MSWToolbar = ({
set(prefix, 'mode', mode);

switch (mode) {
case 'record':
// Passing empty handlers will cause everything to run as a bypass
workerRef.current?.use(...[]);
workerRef.current?.events.on('request:start', request => {
trackedRequestsRef.current.set(request.id, {
time: Number(new Date()),
request,
response: null,
});
});

workerRef.current?.events.on('response:bypass', async (res, reqId) => {
const existingRequestEntry = trackedRequestsRef.current.get(reqId);
if (existingRequestEntry) {
trackedRequestsRef.current.set(reqId, {
...existingRequestEntry,
time: existingRequestEntry.time - Number(new Date()),
response: res.clone(),
});
}
});

return;
case 'replay':
workerRef.current?.events.removeAllListeners();
buildHandlersForTrackedRequests(trackedRequestsRef.current).then(
handlers => {
workerRef.current?.resetHandlers(...handlers);
}
);

return;
case 'normal':
workerRef.current?.events.removeAllListeners();
workerRef.current?.resetHandlers();
return;
case 'error':
workerRef.current?.use(
...['get', 'post', 'put', 'patch', 'delete'].map(method =>
(rest as any)[method as any](
`${apiUrl}/*`,
(
_req: MockedRequest<any>,
res: ResponseComposition<any>,
_ctx: RestContext
) => {
return res.networkError('Fake error');
}
)
...(['get', 'post', 'put', 'patch', 'delete'] as Array<
keyof typeof rest
>).map(method =>
rest[method](`${apiUrl}/*`, (_req, res, _ctx) => {
return res.networkError('Fake error');
})
)
);
return;
Expand Down
162 changes: 162 additions & 0 deletions src/helpers/har.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { MockedRequest, RequestHandler } from 'msw';
import setCookie from 'set-cookie-parser';
import { Entry, Header as HARHeader, Cookie as HARCookie } from 'har-format';
import { HeadersObject, headersToObject } from 'headers-utils/lib';
import { TrackedRequest } from '..';
import { fromTraffic } from './source';

const normalizeValueAsString = (value: string | string[]): string => {
return Array.isArray(value) ? value.join(', ') : value;
};

function buildHARHeaders(headers: HeadersObject): HARHeader[] {
const result = Object.keys(headers).map(name => ({
name,
value: normalizeValueAsString(headers[name]),
}));

return result;
}

function buildHARCookies(cookies: Record<string, string>): HARCookie[] {
return Object.keys(cookies).map(name => ({
name,
value: cookies[name],
}));
}

function buildResponseCookies(headers: HeadersObject) {
const cookies: HARCookie[] = [];

const setCookies = headers['set-cookie'];

if (setCookies) {
for (const headerValue of setCookies) {
let parsed: setCookie.Cookie[];
try {
parsed = setCookie.parse(headerValue);
} catch (err) {
return;
}
for (const cookie of parsed) {
const { name, value, path, domain, expires, httpOnly, secure } = cookie;
const harCookie: HARCookie = {
name,
value,
httpOnly: httpOnly ?? false,
secure: secure ?? false,
path,
domain,
expires: expires?.toISOString(),
};

cookies.push(harCookie);
}
}
}

return cookies;
}

const convertCapturedLifecycleToHAR = async (
time: number,
request: MockedRequest,
res: Response
) => {
const response = res.clone();
let entry: Entry = {
time,
startedDateTime: new Date().toISOString(),
cache: {
beforeRequest: null,
afterRequest: null,
},
timings: {
blocked: -1,
dns: -1,
connect: -1,
send: 0,
wait: 0,
receive: 0,
ssl: -1,
},
request: {
httpVersion: 'HTTP/1.1', // TODO: Can we capture this?
method: request.method,
url: request.url.href,
cookies: buildHARCookies(request.cookies),
headers: request.headers as any,
queryString: [...(request.url.searchParams as any)].map(
([name, value]) => ({
name,
value,
})
),
headersSize: -1,
bodySize: -1,
},
} as any;

const text = await response.text();
const bodySize = Buffer.byteLength(text);

const headers = headersToObject(response.headers);

entry.response = {
status: response.status,
statusText: response.statusText,
// httpVersion,
cookies: buildResponseCookies(headers),
headers: buildHARHeaders(headers),
content: {
mimeType: headers['content-type'],
text,
size: bodySize,
},
redirectURL: headers['location'] || '',
headersSize: -1,
bodySize: -1,
} as any;

entry.response.content.text = text;
entry.response.content.size = bodySize;

return entry;
};

function createHarLog(entries: Entry[] = []) {
return {
log: {
version: '1.1',
creator: {
version: '1',
name: 'msw-toolbar',
},
entries,
},
};
}

async function buildHandlersForTrackedRequests(
trackedRequests: TrackedRequest
): Promise<RequestHandler[]> {
let entries = [];
for (const [, { request, response, time }] of trackedRequests.entries()) {
if (!response) continue;
const harEntry = await convertCapturedLifecycleToHAR(
time,
request,
response
);
entries.push(harEntry);
}
const harLog = createHarLog(entries);

return fromTraffic(harLog);
}

export {
convertCapturedLifecycleToHAR,
createHarLog,
buildHandlersForTrackedRequests,
};
1 change: 1 addition & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './settings';
export * from './har';
2 changes: 1 addition & 1 deletion src/helpers/settings.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Setting } from '..';
import { WorkerMode, WorkerStatus } from '../types';

export const modes: WorkerMode[] = ['normal', 'error'];
export const modes: WorkerMode[] = ['normal', 'error', 'record', 'replay'];

type SettingValueMap = {
mode: WorkerMode;
Expand Down
Loading