-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
executable file
·875 lines (781 loc) · 30.4 KB
/
index.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
#!/usr/bin/env node
/* eslint-disable func-names */
/* eslint-disable func-name-matching */
/* eslint-disable camelcase */
/* eslint prefer-rest-params: "warn" */
/* eslint prefer-destructuring: "warn" */
/* eslint node/no-deprecated-api: "warn" */
const log = require('yalm');
const config = require('./config.js');
const pkg = require('./package.json');
/* istanbul ignore next */
log.setLevel(['debug', 'info', 'warn', 'error'].indexOf(config.verbosity) === -1 ? 'info' : config.verbosity);
log.info(pkg.name + ' ' + pkg.version + ' starting');
log.debug('loaded config: ', config);
const modules = {
fs: require('fs'),
path: require('path'),
vm: require('vm'),
/* eslint-disable no-restricted-modules */
domain: require('domain'),
mqtt: require('mqtt'),
watch: require('watch'),
'node-schedule': require('node-schedule'),
suncalc: require('suncalc')
};
const domain = modules.domain;
const vm = modules.vm;
const fs = modules.fs;
const path = modules.path;
const watch = modules.watch;
const scheduler = modules['node-schedule'];
const suncalc = modules.suncalc;
const sandboxModules = [];
const status = {};
const scripts = {};
const subscriptions = [];
const _global = {};
// Sun scheduling
const sunEvents = [];
let sunTimes = [{}, /* today */ {}, /* tomorrow */ {}];
function calculateSunTimes() {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 0, 0, 0, 0);
const yesterday = new Date(today.getTime() - 86400000); // (24 * 60 * 60 * 1000));
const tomorrow = new Date(today.getTime() + 86400000); // (24 * 60 * 60 * 1000));
sunTimes = [
suncalc.getTimes(yesterday, config.latitude, config.longitude),
suncalc.getTimes(today, config.latitude, config.longitude),
suncalc.getTimes(tomorrow, config.latitude, config.longitude)
];
}
calculateSunTimes();
scheduler.scheduleJob('0 0 * * *', () => {
// Re-calculate every day
calculateSunTimes();
// Schedule events for this day
sunEvents.forEach(event => {
sunScheduleEvent(event);
});
log.info('re-scheduled', sunEvents.length, 'sun events');
});
function sunScheduleEvent(obj, shift) {
// Shift = -1 -> yesterday
// shift = 0 -> today
// shift = 1 -> tomorrow
let event = sunTimes[1 + (shift || 0)][obj.pattern];
const now = new Date();
if (event.toString() !== 'Invalid Date') {
// Event will occur today
if (obj.options.shift) {
event = new Date(event.getTime() + ((parseFloat(obj.options.shift) || 0) * 1000));
}
if ((event.getDate() !== now.getDate()) && (typeof shift === 'undefined')) {
// Event shifted to previous or next day
sunScheduleEvent(obj, (event < now) ? 1 : -1);
return;
}
if ((now.getTime() - event.getTime()) < 1000) {
// Event is less than 1s in the past or occurs later this day
if (obj.options.random) {
event = new Date(
event.getTime() +
(Math.floor((parseFloat(obj.options.random) || 0) * Math.random()) * 1000)
);
}
if ((event.getTime() - now.getTime()) < 1000) {
// Event is less than 1s in the future or already in the past
// (options.random may have shifted us further to the past)
// call the callback immediately!
obj.domain.bind(obj.callback)();
} else {
// Schedule the event!
scheduler.scheduleJob(event, obj.domain.bind(obj.callback));
}
}
}
}
// MQTT
const mqtt = modules.mqtt.connect(config.url, {will: {topic: config.name + '/connected', payload: '0', retain: true}});
mqtt.publish(config.name + '/connected', '2', {retain: true});
let firstConnect = true;
let startTimeout;
let connected;
mqtt.on('connect', () => {
connected = true;
log.info('mqtt connected ' + config.url);
log.debug('mqtt subscribe #');
mqtt.subscribe('#');
if (firstConnect) {
// Wait until retained topics are received before we load the scripts (timeout is prolonged on incoming retained messages)
startTimeout = setTimeout(start, 500);
}
});
mqtt.on('close', () => {
if (connected) {
firstConnect = false;
connected = false;
log.info('mqtt closed ' + config.url);
}
});
/* istanbul ignore next */
mqtt.on('error', () => {
log.error('mqtt error ' + config.url);
});
mqtt.on('message', (topic, payload, msg) => {
if (firstConnect && msg.retain) {
// Retained message received - prolong the timeout
clearTimeout(startTimeout);
startTimeout = setTimeout(start, 500);
}
payload = payload.toString();
let state;
const val = payload;
if (val === 'true') {
// Payload was the string "true" - treat it as bool true
state = {val: true};
} else if (val === 'false') {
// Payload was the string "false" - treat it as bool false
state = {val: false};
} else if (isNaN(val)) {
try {
state = JSON.parse(payload);
if ((typeof state === 'object') && (Array.isArray(state))) {
state = {val: state};
} else if (!state || typeof state.val === 'undefined') {
state = {val: state};
}
} catch (err) {
state = {val};
}
} else {
// Payload seems to be type number
state = {val: parseFloat(val)};
}
const topicArr = topic.split('/');
let oldState;
if (topicArr[0] === config.variablePrefix && topicArr[1] === 'set' && !config.disableVariables) {
topicArr[1] = 'status';
topic = topicArr.join('/');
oldState = status[topic] || {};
const ts = (new Date()).getTime();
state.ts = ts;
state.lc = state.val === oldState.val ? oldState.lc : ts;
status[topic] = state;
mqtt.publish(topic, JSON.stringify(state), {retain: true});
} else {
/* istanbul ignore next */
if (!state) {
log.error('invalid state', topic, payload);
process.exit();
}
if (!state.ts) {
state.ts = new Date().getTime();
}
oldState = status[topic] || {};
if (oldState.val !== state.val) {
state.lc = state.ts;
}
status[topic] = state;
stateChange(topic, state, oldState, msg);
}
});
function stateChange(topic, state, oldState, msg) {
subscriptions.forEach(subs => {
const options = subs.options || {};
let delay;
const match = mqttWildcards(topic, subs.topic);
if (match && typeof options.condition === 'function') {
if (!options.condition(topic.replace(/^([^/]+)\/status\/(.+)/, '$1//$2'), state.val, state, oldState, msg)) {
return;
}
}
if (match && typeof subs.callback === 'function') {
if (msg.retain && !options.retain) {
return;
}
if (options.change && (state.val === oldState.val)) {
return;
}
delay = 0;
if (options.shift) {
delay += ((parseFloat(options.shift) || 0) * 1000);
}
if (options.random) {
delay += ((parseFloat(options.random) || 0) * Math.random() * 1000);
}
delay = Math.floor(delay);
setTimeout(() => {
/**
* @callback subscribeCallback
* @param {string} topic - the topic that triggered this callback. +/status/# will be replaced by +//#
* @param {mixed} val - the val property of the new state
* @param {object} obj - new state - the whole state object (e.g. {"val": true, "ts": 12346345, "lc": 12346345} )
* @param {object} objPrev - previous state - the whole state object
* @param {object} msg - the mqtt message as received from MQTT.js
*/
subs.callback(topic.replace(/^([^/]+)\/status\/(.+)/, '$1//$2'), state.val, state, oldState, msg);
}, delay);
}
});
}
function mqttWildcards(topic, subscription) {
return topic.match(new RegExp('^' + subscription.replace(/#$/, '.*').replace(/\+/g, '[^/]+') + '$'));
}
function createScript(source, name) {
log.debug(name, 'compiling');
try {
return new vm.Script(source, {filename: name});
} catch (err) {
log.error(name, err.name + ':', err.message);
return false;
}
}
function runScript(script, name) {
const scriptDir = path.dirname(path.resolve(name));
log.debug(name, 'creating domain');
const scriptDomain = domain.create();
log.debug(name, 'creating sandbox');
const Sandbox = {
global: _global,
setTimeout,
setInterval,
clearTimeout,
clearInterval,
Buffer,
require(md) {
if (modules[md]) {
return modules[md];
}
try {
let tmp;
if (md.match(/^\.\//) || md.match(/^\.\.\//)) {
tmp = './' + path.relative(__dirname, path.join(scriptDir, md));
} else {
tmp = md;
if (fs.existsSync(path.join(scriptDir, 'node_modules', md, 'package.json'))) {
tmp = './' + path.relative(__dirname, path.join(scriptDir, 'node_modules', md));
tmp = path.resolve(tmp);
}
}
Sandbox.log.debug('require', tmp);
modules[md] = require(tmp);
return modules[md];
} catch (err) {
const lines = err.stack.split('\n');
const stack = [];
lines.forEach(line => {
if (!line.match(/module\.js:/) && !line.match(/index\.js:307/)) {
stack.push(line);
}
});
log.error(name + ': ' + stack);
}
},
/**
* @class log
* @classdesc Log to stdout/stderr. Messages are prefixed with a timestamp and the calling scripts path.
*/
log: {
/**
* Log a debug message
* @memberof log
* @method debug
* @param {...*}
*/
debug() {
const args = Array.prototype.slice.call(arguments);
args.unshift(name + ':');
log.debug.apply(log, args);
},
/**
* Log an info message
* @memberof log
* @method info
* @param {...*}
*/
info() {
const args = Array.prototype.slice.call(arguments);
args.unshift(name + ':');
log.info.apply(log, args);
},
/**
* Log a warning message
* @memberof log
* @method warn
* @param {...*}
*/
warn() {
const args = Array.prototype.slice.call(arguments);
args.unshift(name + ':');
log.warn.apply(log, args);
},
/**
* Log an error message
* @memberof log
* @method error
* @param {...*}
*/
error() {
const args = Array.prototype.slice.call(arguments);
args.unshift(name + ':');
log.error.apply(log, args);
}
},
/**
* Subscribe to MQTT topic(s)
* @method subscribe
* @param {(string|string[])} topic - topic or array of topics to subscribe
* @param {Object|string|function} [options] - Options object or as shorthand to options.condition a function or string
* @param {number} [options.shift] - delay execution in seconds. Has to be positive
* @param {number} [options.random] - random delay execution in seconds. Has to be positive
* @param {boolean} [options.change] - if set to true callback is only called if val changed
* @param {boolean} [options.retain] - if set to true callback is also called on retained messages
* @param {(string|function)} [options.condition] - conditional function or condition string
* @param {subscribeCallback} callback
*/
subscribe: function Sandbox_subscribe(topic, /* optional */ options, callback) {
if (typeof topic === 'undefined') {
throw (new TypeError('argument topic missing'));
}
if (arguments.length === 2) {
if (typeof arguments[1] !== 'function') {
throw new TypeError('callback is not a function');
}
callback = arguments[1];
options = {};
} else if (arguments.length === 3) {
if (typeof arguments[2] !== 'function') {
throw new TypeError('callback is not a function');
}
options = arguments[1] || {};
if (typeof options === 'string' || typeof options === 'function') {
options = {condition: options};
}
callback = arguments[2];
} else if (arguments.length > 3) {
throw (new Error('wrong number of arguments'));
}
if (typeof topic === 'string') {
topic = topic.replace(/^\$/, config.variablePrefix + '/status/');
topic = topic.replace(/^([^/]+)\/\//, '$1/status/');
if (typeof options.condition === 'string') {
if (options.condition.indexOf('\n') !== -1) {
throw new Error('options.condition string must be one-line javascript');
}
/* eslint-disable no-new-func */
options.condition = new Function('topic', 'val', 'obj', 'objPrev', 'msg', 'return ' + options.condition + ';');
}
if (typeof options.condition === 'function') {
options.condition = scriptDomain.bind(options.condition);
}
subscriptions.push({topic, options, callback: (typeof callback === 'function') && scriptDomain.bind(callback)});
if (options.retain && status[topic] && typeof callback === 'function') {
callback(topic.replace(/^([^/]+)\/status\/(.+)/, '$1//$2'), status[topic].val, status[topic]);
} else if (options.retain && (/\/\+\//.test(topic) || /\+$/.test(topic) || /\+/.test(topic) || topic.endsWith('#')) && typeof callback === 'function') {
for (const t in status) {
if (mqttWildcards(t, topic)) {
callback(t.replace(/^([^/]+)\/status\/(.+)/, '$1//$2'), status[t].val, status[t]);
}
}
}
} else if (typeof topic === 'object' && topic.length > 0) {
topic = Array.prototype.slice.call(topic);
topic.forEach(tp => {
Sandbox.subscribe(tp, options, callback);
});
}
},
/**
* Schedule recurring and one-shot events
* @method schedule
* @param {(string|Date|Object|mixed[])} pattern - pattern or array of patterns. May be cron style string, Date object or node-schedule object literal. See {@link https://github.com/tejasmanohar/node-schedule/wiki}
* @param {Object} [options]
* @param {number} [options.random] - random delay execution in seconds. Has to be positive
* @param {function} callback - is called with no arguments
* @example // every full Hour.
* schedule('0 * * * *', callback);
*
* // Monday till friday, random between 7:30am an 8:00am
* schedule('30 7 * * 1-5', {random: 30 * 60}, callback);
*
* // once on 21. December 2018 at 5:30am
* schedule(new Date(2018, 12, 21, 5, 30, 0), callback);
*
* // every Sunday at 2:30pm
* schedule({hour: 14, minute: 30, dayOfWeek: 0}, callback);
* @see {@link sunSchedule} for scheduling based on sun position.
*/
schedule: function Sandbox_schedule(pattern, /* optional */ options, callback) {
if (arguments.length === 2) {
if (typeof arguments[1] !== 'function') {
throw new TypeError('callback is not a function');
}
callback = arguments[1];
options = {};
} else if (arguments.length === 3) {
if (typeof arguments[2] !== 'function') {
throw new TypeError('callback is not a function');
}
options = arguments[1] || {};
callback = arguments[2];
} else {
throw (new Error('wrong number of arguments'));
}
if (typeof pattern === 'object' && pattern.length > 0) {
pattern = Array.prototype.slice.call(pattern);
pattern.forEach(pt => {
Sandbox.schedule(pt, options, callback);
});
return;
}
if (options.random) {
scheduler.scheduleJob(pattern, () => {
setTimeout(scriptDomain.bind(callback), (parseFloat(options.random) || 0) * 1000 * Math.random());
});
} else {
scheduler.scheduleJob(pattern, scriptDomain.bind(callback));
}
},
/**
* Schedule a recurring event based on sun position
* @method sunSchedule
* @param {string|string[]} pattern - a suncalc event or an array of suncalc events. See {@link https://github.com/mourner/suncalc}
* @param {Object} [options]
* @param {number} [options.shift] - delay execution in seconds. Allowed Range: -86400...86400 (+/- 24h)
* @param {number} [options.random] - random delay execution in seconds.
* @param {function} callback - is called with no arguments
* @example // Call callback 15 minutes before sunrise
* sunSchedule('sunrise', {shift: -900}, callback);
*
* // Call callback random 0-15 minutes after sunset
* sunSchedule('sunset', {random: 900}, callback);
* @see {@link schedule} for time based scheduling.
*/
sunSchedule: function Sandbox_sunSchedule(pattern, /* optional */ options, callback) {
if (arguments.length === 2) {
if (typeof arguments[1] !== 'function') {
throw new TypeError('callback is not a function');
}
callback = arguments[1];
options = {};
} else if (arguments.length === 3) {
if (typeof arguments[2] !== 'function') {
throw new TypeError('callback is not a function');
}
options = arguments[1] || {};
callback = arguments[2];
} else {
throw new Error('wrong number of arguments');
}
if ((typeof options.shift !== 'undefined') && (options.shift < -86400 || options.shift > 86400)) {
throw new Error('options.shift out of range');
}
if (typeof pattern === 'object' && pattern.length > 0) {
pattern = Array.prototype.slice.call(pattern);
pattern.forEach(pt => {
Sandbox.sunSchedule(pt, options, callback);
});
return;
}
const event = sunTimes[0][pattern];
if (typeof event === 'undefined') {
throw new TypeError('unknown suncalc event ' + pattern);
}
const obj = {
pattern,
options,
callback,
context: Sandbox,
domain: scriptDomain
};
sunEvents.push(obj);
sunScheduleEvent(obj);
},
/**
* Publish a MQTT message
* @method publish
* @param {(string|string[])} topic - topic or array of topics to publish to
* @param {(string|Object)} payload - the payload string. If an object is given it will be JSON.stringified
* @param {Object} [options] - the options to publish with
* @param {number} [options.qos=0] - QoS Level
* @param {boolean} [options.retain=false] - retain flag
*/
publish: function Sandbox_publish(topic, payload, options) {
if (typeof topic === 'object' && topic.length > 0) {
topic = Array.prototype.slice.call(topic);
topic.forEach(tp => {
Sandbox.publish(tp, payload, options);
});
return;
}
topic = topic.replace(/^([^/]+)\/\/(.+)$/, '$1/set/$2');
if (typeof payload === 'object') {
payload = JSON.stringify(payload);
} else {
payload = String(payload);
}
mqtt.publish(topic, payload, options);
},
/**
* Set a value on one or more topics
* @method setValue
* @param {(string|string[])} topic - topic or array of topics to set value on
* @param {mixed} val
*/
setValue: function Sandbox_setValue(topic, val, publishUnchanged) {
if (typeof topic === 'object' && topic.length > 0) {
topic = Array.prototype.slice.call(topic);
topic.forEach(tp => {
Sandbox.setValue(tp, val);
});
return;
}
let changed;
topic = topic.replace(/^\$/, config.variablePrefix + '//');
const tmp = topic.split('/');
if (tmp[0] === config.variablePrefix && !config.disableVariables) {
// Variable
tmp[1] = 'status';
topic = tmp.join('/');
const oldState = status[topic] || {};
const ts = (new Date()).getTime();
if (typeof val === 'object') {
val.ts = ts;
} else {
val = {val, ts};
}
if (val.val !== oldState.val) {
val.lc = ts;
changed = true;
}
status[topic] = val;
stateChange(topic, val, oldState, {});
if (changed || publishUnchanged) {
Sandbox.publish(topic, val, {retain: true});
}
/* istanbul ignore next */ // TODO tests!
} else if (tmp[0] === config.variablePrefix && config.disableVariables) {
/* istanbul ignore next */
tmp[1] = 'status';
topic = tmp.join('/');
/* istanbul ignore next */
if (!status[topic] || (status[topic].val !== val)) {
/* istanbul ignore next */
tmp[1] = 'set';
topic = tmp.join('/');
Sandbox.publish(topic, val, {retain: false}); // TODO really retain false?!
}
} else {
topic = topic.replace(/^([^/]+)\/\/(.+)$/, '$1/set/$2');
Sandbox.publish(topic, val, {retain: false});
}
},
/**
* @method getValue
* @param {string} topic
* @returns {mixed} the topics value
*/
getValue: function Sandbox_getValue(topic) {
topic = topic.replace(/^\$/, config.variablePrefix + '/status/');
topic = topic.replace(/^([^/]+)\/\/(.+)$/, '$1/status/$2');
return status[topic] && status[topic].val;
},
/**
* Get a specific property of a topic
* @method getProp
* @param {string} topic
* @param {...string} [property] - the property to retrieve. May be repeated for nested properties. If omitted the whole topic object is returned.
* @returns {mixed} the topics properties value
* @example // returns the timestamp of a given topic
* getProp('hm//Bewegungsmelder Keller/MOTION', 'ts');
*/
getProp: function Sandbox_getProp(topic /* , optional property, optional nested property, ... */) {
topic = topic.replace(/^([^/]+)\/\/(.+)$/, '$1/status/$2');
if (arguments.length > 1) {
let tmp = status[topic];
if (typeof tmp === 'undefined') {
return;
}
for (let i = 1; i < arguments.length; i++) {
if (typeof tmp[arguments[i]] === 'undefined') {
return;
}
tmp = tmp[arguments[i]];
}
return tmp;
}
return status[topic];
}
};
Sandbox.console = {
log: Sandbox.log.info,
error: Sandbox.log.error
};
sandboxModules.forEach(md => {
md(Sandbox);
});
log.debug(name, 'contextifying sandbox');
const context = vm.createContext(Sandbox);
scriptDomain.on('error', e => {
/* istanbul ignore if */
if (!e.stack) {
log.error([name + ' unkown exception']);
return;
}
const lines = e.stack.split('\n');
const stack = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].match(/at ContextifyScript.Script.runInContext/)) {
break;
}
stack.push(lines[i]);
}
log.error([name + ' ' + stack.join('\n')]);
});
scriptDomain.run(() => {
log.debug(name, 'running');
script.runInContext(context);
});
}
function loadScript(file) {
/* istanbul ignore if */
if (scripts[file]) {
log.error(file, 'already loaded?!');
return;
}
log.info(file, 'loading');
fs.readFile(file, (err, src) => {
/* istanbul ignore if */
if (err && err.code === 'ENOENT') {
log.error(file, 'not found');
} else if (err) {
/* istanbul ignore next */
log.error(file, err);
} else {
if (file.match(/\.coffee$/)) {
if (!modules['coffee-compiler']) {
log.info('loading coffee-compiler');
modules['coffee-compiler'] = require('coffee-compiler');
}
log.debug(file, 'transpiling');
modules['coffee-compiler'].fromSource(src.toString(), {sourceMap: false, bare: true}, (err, js) => {
/* istanbul ignore if */
if (err) {
log.error(file, 'transpile failed', err.message);
return;
}
scripts[file] = createScript(js, file);
});
} else if (file.match(/\.js$/)) {
// Javascript
scripts[file] = createScript(src, file);
}
if (scripts[file]) {
runScript(scripts[file], file);
}
}
});
}
function loadSandbox(callback) {
const dir = path.join(__dirname, 'sandbox');
fs.readdir(dir, (err, data) => {
/* istanbul ignore if */
if (err) {
if (err.errno === 34) {
log.error('directory ' + path.resolve(dir) + ' not found');
} else {
log.error('readdir', dir, err);
}
} else {
data.sort().forEach(file => {
if (file.match(/\.js$/)) {
sandboxModules.push(require(path.join(dir, file)));
}
});
if (!config.disableWatch) {
watch.watchTree(dir, {
filter(path) {
return path.match(/\.js$/);
}
}, (f, curr, prev) => {
if (typeof f === 'object' && prev === null && curr === null) {
log.debug('watch', dir, 'initialized');
} else {
watch.unwatchTree(dir);
log.info(f, 'change detected. exiting.');
process.exit(0);
}
});
}
callback();
}
});
}
function loadDir(dir) {
fs.readdir(dir, (err, data) => {
/* istanbul ignore if */
if (err) {
if (err.errno === 34) {
log.error('directory ' + path.resolve(dir) + ' not found');
} else {
log.error('readdir', dir, err);
}
} else {
data.sort().forEach(file => {
if (file.match(/\.(js|coffee)$/)) {
loadScript(path.join(dir, file));
}
});
if (!config.disableWatch) {
watch.watchTree(dir, {
filter(path) {
return path.match(/\.(js|coffee)$/);
}
}, (f, curr, prev) => {
if (typeof f === 'object' && prev === null && curr === null) {
log.debug('watch', dir, 'initialized');
} else {
watch.unwatchTree(dir);
log.info(f, 'change detected. exiting.');
process.exit(0);
}
});
}
}
});
}
function start() {
/* istanbul ignore if */
if (config.file) {
if (typeof config.file === 'string') {
loadScript(config.file);
} else {
config.file.forEach(file => {
loadScript(file);
});
}
}
loadSandbox(() => {
if (config.dir) {
/* istanbul ignore else */
if (typeof config.dir === 'string') {
loadDir(config.dir);
} else {
config.dir.forEach(dir => {
loadDir(dir);
});
}
}
});
}
/* istanbul ignore next */
process.on('SIGINT', () => {
log.info('got SIGINT. exiting.');
process.exit(0);
});
/* istanbul ignore next */
process.on('SIGTERM', () => {
log.info('got SIGTERM. exiting.');
process.exit(0);
});