This repository has been archived by the owner on Dec 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 107
/
catalog.js
262 lines (227 loc) · 8 KB
/
catalog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
const assert = require('assert');
const debug = require('./debug');
const File = require('fs');
const Path = require('path');
const Matcher = require('./matcher');
const jsStringEscape = require('js-string-escape');
const NEW_RESPONSE_FORMAT = /HTTP\/(\d\.\d)\s+(\d{3})\s*(.*)/;
const OLD_RESPONSE_FORMAT = /(\d{3})\s+HTTP\/(\d\.\d)/;
function mkpathSync(pathname) {
if (File.existsSync(pathname))
return;
const parent = Path.dirname(pathname);
if (File.existsSync(parent))
File.mkdirSync(pathname);
else {
mkpathSync(parent);
File.mkdirSync(pathname);
}
}
// Parse headers from headerLines. Optional argument `only` is an array of
// regular expressions; only headers matching one of these expressions are
// parsed. Returns a object with name/value pairs.
function parseHeaders(filename, headerLines, only = null) {
const headers = Object.create(null);
for (let line of headerLines) {
if (line === '')
continue;
let [name, value] = line.match(/^(.*?)\:\s+(.*)$/).slice(1);
if (only && !match(name, only))
continue;
const key = (name || '').toLowerCase();
value = (value || '').trim().replace(/^"(.*)"$/, '$1');
if (Array.isArray(headers[key]))
headers[key].push(value);
else if (headers[key])
headers[key] = [headers[key], value];
else
headers[key] = value;
}
return headers;
}
function parseRequest(filename, request, requestHeaders) {
function parseRegexp(rawRegexp) {
const [ inRegexp, flags ] = rawRegexp.match(/^\/(.+)\/(i|m|g)?$/).slice(1);
return new RegExp(inRegexp, flags || '');
}
assert(request, `${filename} missing request section`);
const [ methodAndPath, ...headerLines ] = request.split(/\n/);
let method;
let path;
let rawRegexp;
let regexp;
if (/\sREGEXP\s/.test(methodAndPath)) {
[ method, rawRegexp ] = methodAndPath.split(' REGEXP ');
regexp = parseRegexp(rawRegexp);
} else
[ method, path ] = methodAndPath.split(/\s/);
assert(method && (path || regexp), `${filename}: first line must be <method> <path>`);
assert(/^[a-zA-Z]+$/.test(method), `${filename}: method not valid`);
const headers = parseHeaders(filename, headerLines, requestHeaders);
let body = headers.body;
delete headers.body;
if (body && /^REGEXP\s+/.test(body)) {
rawRegexp = body.split(/REGEXP\s+/)[1];
body = parseRegexp(rawRegexp);
}
const url = path || regexp;
return { url, method, headers, body };
}
function parseResponse(filename, response, body) {
if (response) {
const [ statusLine, ...headerLines ] = response.split(/\n/);
const { version, statusCode, statusMessage } = statusComponents(statusLine)
const headers = parseHeaders(filename, headerLines);
const rawHeaders = headerLines.reduce(function(raw, header) {
const [name, value] = header.split(/:\s+/);
raw.push(name);
raw.push(value);
return raw;
}, []);
return { statusCode, statusMessage, version, headers, rawHeaders, body, trailers: {}, rawTrailers: [] };
}
}
function statusComponents(statusLine) {
let response = {};
if ( isResponseFormatNew(statusLine) ) {
const formattedStatus = statusLine.match(NEW_RESPONSE_FORMAT);
response.version = formattedStatus[1];
response.statusCode = parseInt(formattedStatus[2], 10);
response.statusMessage = formattedStatus[3].trim();
} else {
const formattedStatus = statusLine.match(OLD_RESPONSE_FORMAT);
response.version = formattedStatus[2];
response.statusCode = parseInt(formattedStatus[0], 10);
}
return response;
}
function isResponseFormatNew(statusLine) {
return /^HTTP/.test(statusLine)
}
function readAndInitialParseFile(filename) {
const buffer = File.readFileSync(filename);
const parts = buffer.toString('utf8').split('\n\n');
if (parts.length > 2) {
const parts0 = new Buffer(parts[0], 'utf8');
const parts1 = new Buffer(parts[1], 'utf8');
const body = buffer.slice(parts0.length + parts1.length + 4);
return [ parts[0], parts[1], body ];
} else
return [ parts[0], parts[1], '' ];
}
// Write headers to the File object. Optional argument `only` is an array of
// regular expressions; only headers matching one of these expressions are
// written.
function writeHeaders(file, headers, only = null) {
for (let name in headers) {
let value = headers[name];
if (only && !match(name, only))
continue;
if (Array.isArray(value))
for (let item of value)
file.write(`${name}: ${item}\n`);
else
file.write(`${name}: ${value}\n`);
}
}
// Returns true if header name matches one of the regular expressions.
function match(name, regexps){
for (let regexp of regexps)
if (regexp.test(name))
return true;
return false;
}
module.exports = class Catalog {
constructor(settings) {
this.settings = settings;
// We use this to cache host/host:port mapped to array of matchers.
this.matchers = {};
this._basedir = Path.resolve('fixtures');
}
getFixturesDir() {
return this._basedir;
}
setFixturesDir(dir) {
this._basedir = Path.resolve(dir);
this.matchers = {};
}
find(host) {
// Return result from cache.
const matchers = this.matchers[host];
if (matchers)
return matchers;
// Start by looking for directory and loading each of the files.
// Look for host-port (windows friendly) or host:port (legacy)
let pathname = `${this.getFixturesDir()}/${host.replace(':', '-')}`;
if (!File.existsSync(pathname))
pathname = `${this.getFixturesDir()}/${host}`;
if (!File.existsSync(pathname))
return null;
const newMatchers = this.matchers[host] || [];
this.matchers[host] = newMatchers;
const stat = File.statSync(pathname);
if (stat.isDirectory()) {
let files = File.readdirSync(pathname);
// remove dot files from the list
files = files.filter(f => !/^\./.test(f));
for (let file of files) {
let mapping = this._read(`${pathname}/${file}`);
newMatchers.push(Matcher.fromMapping(host, mapping));
}
} else {
const mapping = this._read(pathname);
newMatchers.push(Matcher.fromMapping(host, mapping));
}
return newMatchers;
}
save(host, request, response, callback) {
const matcher = Matcher.fromMapping(host, { request, response });
const matchers = this.matchers[host] || [];
matchers.push(matcher);
const requestHeaders = this.settings.headers;
const uid = `${Date.now()}${Math.floor(Math.random() * 100000)}`;
const tmpfile = `${this.getFixturesDir()}/node-replay.${uid}`;
const pathname = `${this.getFixturesDir()}/${host.replace(':', '-')}`;
debug(`Creating ${pathname}`);
try {
mkpathSync(pathname);
} catch (error) {
setImmediate(function() {
callback(error);
});
return;
}
const filename = `${pathname}/${uid}`;
try {
const file = File.createWriteStream(tmpfile, { encoding: 'utf-8' });
file.write(`${request.method.toUpperCase()} ${request.url.path || '/'}\n`);
writeHeaders(file, request.headers, requestHeaders);
if (request.body) {
let body = '';
for (let chunks of request.body)
body += chunks[0];
writeHeaders(file, { body: jsStringEscape(body) });
}
file.write('\n');
// Response part
file.write(`HTTP/${response.version || '1.1'} ${response.statusCode || 200} ${response.statusMessage}\n`);
writeHeaders(file, response.headers);
file.write('\n');
for (let part of response.body)
file.write(part[0], part[1]);
file.end(function() {
File.rename(tmpfile, filename, callback);
});
} catch (error) {
callback(error);
}
}
_read(filename) {
const [request, response, part] = readAndInitialParseFile(filename);
const body = [[part, undefined]];
return {
request: parseRequest(filename, request, this.settings.headers),
response: parseResponse(filename, response, body)
};
}
};