-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
nightmare.js
481 lines (395 loc) · 11.9 KB
/
nightmare.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/**
* DEBUG=nightmare*
*/
var log = require('debug')('nightmare:log');
var debug = require('debug')('nightmare');
var electronLog = {
stdout: require('debug')('electron:stdout'),
stderr: require('debug')('electron:stderr')
};
/**
* Module dependencies
*/
var default_electron_path = require('electron-prebuilt');
var source = require('function-source');
var proc = require('child_process');
var actions = require('./actions');
var path = require('path');
var sliced = require('sliced');
var child = require('./ipc');
var once = require('once');
var split2 = require('split2');
var noop = function() {};
var keys = Object.keys;
/**
* Export `Nightmare`
*/
module.exports = Nightmare;
/**
* runner script
*/
var runner = path.join(__dirname, 'runner.js');
/**
* Template
*/
var template = require('./javascript');
/**
* Initialize `Nightmare`
*
* @param {Object} options
*/
function Nightmare(options) {
if (!(this instanceof Nightmare)) return new Nightmare(options);
options = options || {};
var electronArgs = {};
var self = this;
self.optionWaitTimeout = options.waitTimeout || 30000;
var electron_path = options.electronPath || default_electron_path
if (options.paths) {
electronArgs.paths = options.paths;
}
if (options.switches) {
electronArgs.switches = options.switches;
}
electronArgs.dock = options.dock || false;
this.proc = proc.spawn(electron_path, [runner].concat(JSON.stringify(electronArgs)), {
stdio: [null, null, null, 'ipc']
});
this.proc.stdout.pipe(split2()).on('data', (data) => {
electronLog.stdout(data);
});
this.proc.stderr.pipe(split2()).on('data', (data) => {
electronLog.stderr(data);
});
this.proc.on('close', function(code) {
var help = {
127: 'command not found - you may not have electron installed correctly',
126: 'permission problem or command is not an executable - you may not have all the necessary dependencies for electron',
1: 'general error - you may need xvfb',
0: 'success!'
};
debug('electron child process exited with code ' + code + ': ' + help[code]);
});
attachToProcess(this);
// initial state
this.state = 'initial';
this.running = false;
this.ending = false;
this.ended = false;
this._queue = [];
this._headers = {};
this.options = options;
// initialize namespaces
Nightmare.namespaces.forEach(function (name) {
if ('function' === typeof this[name]) {
this[name] = this[name]()
}
}, this)
//prepend adding child actions to the queue
Object.keys(Nightmare.childActions).forEach(function(key){
debug('queueing child action addition for "%s"', key);
this.queue(function(done){
this.child.call('action', key, String(Nightmare.childActions[key]), done);
});
}, this);
this.child = child(this.proc);
this.child.once('ready', function() {
self.child.call('browser-initialize', options, function() {
self.state = 'ready';
});
});
// propagate console.log(...) through
this.child.on('log', function() {
log.apply(log, arguments);
});
this.child.on('uncaughtException', function(stack) {
console.error('Nightmare runner error:\n\n%s\n', '\t' + stack.replace(/\n/g, '\n\t'));
endInstance(self);
process.exit(1);
});
this.child.on('page', function(type) {
log.apply(null, ['page-' + type].concat(sliced(arguments, 1)));
});
// proporate events through to debugging
this.child.on('did-finish-load', function () { log('did-finish-load', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-fail-load', function () { log('did-fail-load', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-fail-provisional-load', function () { log('did-fail-provisional-load', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-frame-finish-load', function () { log('did-frame-finish-load', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-start-loading', function () { log('did-start-loading', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-stop-loading', function () { log('did-stop-loading', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-get-response-details', function () { log('did-get-response-details', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('did-get-redirect-request', function () { log('did-get-redirect-request', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('dom-ready', function () { log('dom-ready', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('page-favicon-updated', function () { log('page-favicon-updated', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('new-window', function () { log('new-window', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('will-navigate', function () { log('will-navigate', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('crashed', function () { log('crashed', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('plugin-crashed', function () { log('plugin-crashed', JSON.stringify(Array.prototype.slice.call(arguments))); });
this.child.on('destroyed', function () { log('destroyed', JSON.stringify(Array.prototype.slice.call(arguments))); });
}
function endInstance(instance) {
instance.ended = true;
detachFromProcess(instance);
if (instance.proc.connected) {
instance.child.removeAllListeners();
instance.proc.removeAllListeners();
instance.proc.disconnect();
instance.proc.kill();
}
}
/**
* Attach any instance-specific process-level events.
*/
function attachToProcess(instance) {
instance._endNow = endInstance.bind(null, instance);
process.setMaxListeners(Infinity);
process.on('exit', instance._endNow);
process.on('SIGINT', instance._endNow);
process.on('SIGTERM', instance._endNow);
process.on('SIGQUIT', instance._endNow);
process.on('SIGHUP', instance._endNow);
process.on('SIGBREAK', instance._endNow);
}
function detachFromProcess(instance) {
process.removeListener('exit', instance._endNow);
process.removeListener('SIGINT', instance._endNow);
process.removeListener('SIGTERM', instance._endNow);
process.removeListener('SIGQUIT', instance._endNow);
process.removeListener('SIGHUP', instance._endNow);
process.removeListener('SIGBREAK', instance._endNow);
}
/**
* Namespaces to initialize
*/
Nightmare.namespaces = [];
/**
* Child actions to create
*/
Nightmare.childActions = {};
/**
* Version
*/
Nightmare.version = require(path.resolve(__dirname, '..', 'package.json')).version;
/**
* ready
*/
Nightmare.prototype.ready = function(fn) {
var self = this;
if (this.state == 'ready') return fn();
this.child.once('ready', function(versions){
self.engineVersions = versions;
return fn();
});
return this;
};
/**
* Override headers for all HTTP requests
*/
Nightmare.prototype.header = function(header, value) {
if (header && typeof value !== 'undefined') {
this._headers[header] = value;
} else {
this._headers = header || {};
}
return this;
};
/**
* Go to a `url`
*/
Nightmare.prototype.goto = function(url, headers) {
debug('queueing action "goto" for %s', url);
var child = this.child;
headers = headers || {};
for (var key in this._headers) {
headers[key] = headers[key] || this._headers[key];
}
this.queue(function(fn) {
child.call('goto', url, headers, fn);
});
return this;
};
/**
* run
*/
Nightmare.prototype.run = function(fn) {
debug('running')
var ready = [this.ready.bind(this)];
var steps = [ready].concat(this.queue());
this.running = true;
this._queue = [];
var self = this;
// kick us off
next();
// next function
function next (err, res) {
var item = steps.shift();
// Immediately halt execution if an error has been thrown, or we have no more queued up steps.
if (err || !item) return done.apply(self, arguments);
var args = item[1] || [];
var method = item[0];
args.push(once(after));
method.apply(self, args);
}
function after (err, res) {
var args = sliced(arguments);
self.child.call('continue', function() {
next.apply(self, args);
});
}
function done () {
self.running = false;
if (self.ending) {
endInstance(self);
}
return fn.apply(self, arguments);
}
return this;
};
/**
* run the code now (do not queue it)
*
* you should not use this, unless you know what you're doing
* it should be used for plugins and custom actions, not for
* normal API usage
*/
Nightmare.prototype.evaluate_now = function(js_fn, done) {
var args = Array.prototype.slice.call(arguments).slice(2);
var argsList = JSON.stringify(args).slice(1,-1);
var source = template.execute({ src: String(js_fn), args: argsList });
this.child.call('javascript', source, done);
return this;
};
/**
* inject javascript
*/
Nightmare.prototype._inject = function(js, done) {
this.child.call('javascript', template.inject({ src: js }), done);
return this;
};
/**
* end
*/
Nightmare.prototype.end = function(done) {
this.ending = true;
if (done && !this.running && !this.ended) {
this.run(done);
}
return this;
};
/**
* on
*/
Nightmare.prototype.on = function(event, handler) {
this.child.on(event, handler);
return this;
};
/**
* once
*/
Nightmare.prototype.once = function(event, handler) {
this.child.once(event, handler);
return this;
};
/**
* removeEventListener
*/
Nightmare.prototype.removeListener = function(event, handler) {
this.child.removeListener(event, handler);
return this;
};
/**
* Queue
*/
Nightmare.prototype.queue = function(done) {
if (!arguments.length) return this._queue;
var args = sliced(arguments);
var fn = args.pop();
this._queue.push([fn, args]);
};
/**
* then
*/
Nightmare.prototype.then = function(fulfill, reject) {
var self = this;
return new Promise(function (success, failure) {
self.run(function(err, result) {
if (err) failure(err);
else success(result);
})
})
.then(fulfill, reject);
};
/**
* catch
*/
Nightmare.prototype.catch = function(reject) {
return this.then(undefined, reject);
};
/**
* use
*/
Nightmare.prototype.use = function(fn) {
fn(this)
return this
};
// wrap all the functions in the queueing function
function queued (name, fn) {
return function action () {
debug('queueing action "' + name + '"');
var args = [].slice.call(arguments);
this._queue.push([fn, args]);
return this;
}
}
/**
* Static: Support attaching custom actions
*
* @param {String} name - method name
* @param {Function|Object} [childfn] - Electron implementation
* @param {Function|Object} parentfn - Nightmare implementation
* @return {Nightmare}
*/
Nightmare.action = function() {
var name = arguments[0], childfn, parentfn;
if(arguments.length === 2) {
parentfn = arguments[1];
} else {
parentfn = arguments[2];
childfn = arguments[1];
}
// support functions and objects
// if it's an object, wrap it's
// properties in the queue function
if(parentfn) {
if (typeof parentfn === 'function') {
Nightmare.prototype[name] = queued(name, parentfn);
} else {
if (!~Nightmare.namespaces.indexOf(name)) {
Nightmare.namespaces.push(name);
}
Nightmare.prototype[name] = function() {
var self = this;
return keys(parentfn).reduce(function (obj, key) {
obj[key] = queued(name, parentfn[key]).bind(self)
return obj;
}, {});
}
}
}
if(childfn) {
if (typeof childfn === 'function') {
Nightmare.childActions[name] = childfn;
} else {
for(var key in childfn){
Nightmare.childActions[name+'.'+key] = childfn;
}
}
}
}
/**
* Attach all the actions.
*/
Object.keys(actions).forEach(function (name) {
var fn = actions[name];
Nightmare.action(name, fn);
});