-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlocal.js
6344 lines (5726 loc) · 198 KB
/
local.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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Worker API whitelisting code
// ============================
var whitelist = [ // a list of global objects which are allowed in the worker
'null', 'self', 'console', 'atob', 'btoa',
'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval',
'Proxy',
'importScripts', 'navigator',
'postMessage', 'addEventListener', 'removeEventListener',
'onmessage', 'onerror', 'onclose',
'dispatchEvent'
];
var blacklist = [ // a list of global objects which are not allowed in the worker, and which dont enumerate on `self` for some reason
'XMLHttpRequest', 'WebSocket', 'EventSource',
'Worker'
];
var whitelistAPIs_src = [ // nullifies all toplevel variables except those listed above in `whitelist`
'(function() {',
'var nulleds=[];',
'var whitelist = ["'+whitelist.join('", "')+'"];',
'for (var k in self) {',
'if (whitelist.indexOf(k) === -1) {',
'Object.defineProperty(self, k, { value: null, configurable: false, writable: false });',
'nulleds.push(k);',
'}',
'}',
'var blacklist = ["'+blacklist.join('", "')+'"];',
'blacklist.forEach(function(k) {',
'Object.defineProperty(self, k, { value: null, configurable: false, writable: false });',
'nulleds.push(k);',
'});',
'if (typeof console != "undefined") { console.log("Nullified: "+nulleds.join(", ")); }',
'})();\n'
].join('');
var importScriptsPatch_src = [ // patches importScripts() to allow relative paths despite the use of blob uris
'(function() {',
'var orgImportScripts = importScripts;',
'function joinRelPath(base, relpath) {',
'if (relpath.charAt(0) == \'/\') {',
'return "{{HOST}}" + relpath;',
'}',
'// totally relative, oh god',
'// (thanks to geoff parker for this)',
'var hostpath = "{{HOST_DIR_PATH}}";',
'var hostpathParts = hostpath.split(\'/\');',
'var relpathParts = relpath.split(\'/\');',
'for (var i=0, ii=relpathParts.length; i < ii; i++) {',
'if (relpathParts[i] == \'.\')',
'continue; // noop',
'if (relpathParts[i] == \'..\')',
'hostpathParts.pop();',
'else',
'hostpathParts.push(relpathParts[i]);',
'}',
'return "{{HOST}}/" + hostpathParts.join(\'/\');',
'}',
'var isImportingAllowed = true;',
'setTimeout(function() { isImportingAllowed = false; },0);', // disable after initial run
'importScripts = function() {',
'if (!isImportingAllowed) { throw "Local.js - Imports disabled after initial load to prevent data-leaking"; }',
'return orgImportScripts.apply(null, Array.prototype.map.call(arguments, function(v, i) {',
'return (v.indexOf(\'/\') < v.indexOf(/[.:]/) || v.charAt(0) == \'/\' || v.charAt(0) == \'.\') ? joinRelPath(\'{{HOST_DIR_URL}}\',v) : v;',
'}));',
'};',
'})();\n'
].join('\n');
module.exports = {
logAllExceptions: false,
workerBootstrapScript: whitelistAPIs_src+importScriptsPatch_src
};
},{}],2:[function(require,module,exports){
module.exports = {
// Local status codes
// ==================
// used to specify client operation states
// link query failed to match
LINK_NOT_FOUND: 1
};
},{}],3:[function(require,module,exports){
var util = require('./util');
module.exports = {
Request: require('./web/request.js'),
Response: require('./web/response.js'),
Server: require('./web/server.js'),
Relay: require('./web/relay.js'),
BridgeServer: require('./web/bridge-server.js'),
WorkerBridgeServer: require('./web/worker-bridge-server.js'),
RTCBridgeServer: require('./web/rtc-bridge-server.js'),
UriTemplate: require('./web/uri-template.js'),
util: util,
schemes: require('./web/schemes.js'),
httpHeaders: require('./web/http-headers.js'),
contentTypes: require('./web/content-types.js'),
worker: require('./worker'),
};
util.mixin.call(module.exports, require('./constants.js'));
util.mixin.call(module.exports, require('./config.js'));
util.mixin.call(module.exports, require('./promises.js'));
util.mixin.call(module.exports, require('./spawners.js'));
util.mixin.call(module.exports, require('./request-event.js'));
util.mixin.call(module.exports, require('./web/helpers.js'));
util.mixin.call(module.exports, require('./web/httpl.js'));
util.mixin.call(module.exports, require('./web/dispatch.js'));
util.mixin.call(module.exports, require('./web/subscribe.js'));
util.mixin.call(module.exports, require('./web/agent.js'));
if (typeof window != 'undefined') window.local = module.exports;
else if (typeof self != 'undefined') self.local = module.exports;
else local = module.exports;
// Local Registry Host
local.addServer('hosts', function(req, res) {
var localHosts = local.getServers();
if (!(req.method == 'HEAD' || req.method == 'GET'))
return res.writeHead(405, 'bad method').end();
if (req.method == 'GET' && !local.preferredType(req, 'application/json'))
return res.writeHead(406, 'bad accept - only provides application/json').end();
var responses_ = [];
var domains = [], links = [];
links.push({ href: '/', rel: 'self service via', id: 'hosts', title: 'Page Hosts' });
for (var domain in localHosts) {
if (domain == 'hosts')
continue;
domains.push(domain);
responses_.push(local.dispatch({ method: 'HEAD', url: 'local://'+domain, timeout: 500 }));
}
local.promise.bundle(responses_).then(function(ress) {
ress.forEach(function(res, i) {
var selfLink = local.queryLinks(res, { rel: 'self' })[0];
if (!selfLink) {
selfLink = { rel: 'service', id: domains[i], href: 'local://'+domains[i] };
}
selfLink.rel = (selfLink.rel) ? selfLink.rel.replace(/(^|\b)(self|up|via)(\b|$)/gi, '') : 'service';
links.push(selfLink);
});
res.setHeader('link', links);
if (req.method == 'HEAD')
return res.writeHead(204, 'ok, no content').end();
res.writeHead(200, 'ok', { 'content-type': 'application/json' });
res.end({ host_names: domains });
});
});
},{"./config.js":1,"./constants.js":2,"./promises.js":4,"./request-event.js":5,"./spawners.js":6,"./util":9,"./web/agent.js":10,"./web/bridge-server.js":11,"./web/content-types.js":12,"./web/dispatch.js":13,"./web/helpers.js":14,"./web/http-headers.js":15,"./web/httpl.js":16,"./web/relay.js":17,"./web/request.js":18,"./web/response.js":19,"./web/rtc-bridge-server.js":20,"./web/schemes.js":21,"./web/server.js":22,"./web/subscribe.js":23,"./web/uri-template.js":24,"./web/worker-bridge-server.js":25,"./worker":27}],4:[function(require,module,exports){
var localConfig = require('./config.js');
var util = require('./util');
function isPromiselike(p) {
return (p && typeof p.then == 'function');
}
// Promise
// =======
// EXPORTED
// Monadic function chaining around asynchronously-fulfilled values
// - conformant with the promises/a+ spec
// - better to use the `promise` function to construct
function Promise(value) {
this.succeedCBs = []; // used to notify about fulfillments
this.failCBs = []; // used to notify about rejections
this.__hasValue = false;
this.__hasFailed = false;
this.value = undefined;
if (value)
this.fulfill(value);
}
Promise.prototype.isUnfulfilled = function() { return !this.__hasValue; };
Promise.prototype.isRejected = function() { return this.__hasFailed; };
Promise.prototype.isFulfilled = function() { return (this.__hasValue && !this.__hasFailed); };
// helper function to execute `then` behavior
function execCallback(parentPromise, targetPromise, fn) {
if (fn === null) {
if (parentPromise.isRejected())
targetPromise.reject(parentPromise.value);
else
targetPromise.fulfill(parentPromise.value);
} else {
var newValue;
try { newValue = fn(parentPromise.value); }
catch (e) {
if (localConfig.logAllExceptions || e instanceof Error) {
if (console.error)
console.error(e, e.stack);
else console.log("Promise exception thrown", e, e.stack);
}
return targetPromise.reject(e);
}
if (isPromiselike(newValue))
promise(newValue).chain(targetPromise);
else
targetPromise.fulfill(newValue);
}
}
// add a 'succeed' and an 'fail' function to the sequence
Promise.prototype.then = function(succeedFn, failFn) {
succeedFn = (succeedFn && typeof succeedFn == 'function') ? succeedFn : null;
failFn = (failFn && typeof failFn == 'function') ? failFn : null;
var p = promise();
if (this.isUnfulfilled()) {
this.succeedCBs.push({ p:p, fn:succeedFn });
this.failCBs.push({ p:p, fn:failFn });
} else {
var self = this;
util.nextTick(function() {
if (self.isFulfilled())
execCallback(self, p, succeedFn);
else
execCallback(self, p, failFn);
});
}
return p;
};
// add a non-error function to the sequence
// - will be skipped if in 'error' mode
Promise.prototype.succeed = function(fn) {
if (this.isRejected()) {
return this;
} else {
var args = Array.prototype.slice.call(arguments, 1);
return this.then(function(v) {
return fn.apply(null, [v].concat(args));
});
}
};
// add an error function to the sequence
// - will be skipped if in 'non-error' mode
Promise.prototype.fail = function(fn) {
if (this.isFulfilled()) {
return this;
} else {
var args = Array.prototype.slice.call(arguments, 1);
return this.then(null, function(v) {
return fn.apply(null, [v].concat(args));
});
}
};
// add a function to the success and error paths of the sequence
Promise.prototype.always = function(fn) {
return this.then(fn, fn);
};
// sets the promise value, enters 'succeed' mode, and executes any queued `then` functions
Promise.prototype.fulfill = function(value) {
if (this.isUnfulfilled()) {
this.value = value;
this.__hasValue = true;
for (var i=0; i < this.succeedCBs.length; i++) {
var cb = this.succeedCBs[i];
execCallback(this, cb.p, cb.fn);
}
this.succeedCBs.length = 0;
this.failCBs.length = 0;
}
return this;
};
// sets the promise value, enters 'error' mode, and executes any queued `then` functions
Promise.prototype.reject = function(err) {
if (this.isUnfulfilled()) {
this.value = err;
this.__hasValue = true;
this.__hasFailed = true;
for (var i=0; i < this.failCBs.length; i++) {
var cb = this.failCBs[i];
execCallback(this, cb.p, cb.fn);
}
this.succeedCBs.length = 0;
this.failCBs.length = 0;
}
return this;
};
// releases all of the remaining references in the prototype chain
// - to be used in situations where promise handling will not continue, and memory needs to be freed
Promise.prototype.cancel = function() {
// propagate the command to promises later in the chain
var i;
for (i=0; i < this.succeedCBs.length; i++) {
this.succeedCBs[i].p.cancel();
}
for (i=0; i < this.failCBs.length; i++) {
this.failCBs[i].p.cancel();
}
// free up memory
this.succeedCBs.length = 0;
this.failCBs.length = 0;
return this;
};
// sets up the given promise to fulfill/reject upon the method-owner's fulfill/reject
Promise.prototype.chain = function(otherPromise) {
this.then(
function(v) {
promise(otherPromise).fulfill(v);
return v;
},
function(err) {
promise(otherPromise).reject(err);
return err;
}
);
return otherPromise;
};
// provides a node-style function for fulfilling/rejecting based on the (err, result) pattern
Promise.prototype.cb = function(err, value) {
if (err)
this.reject(err);
else
this.fulfill((typeof value == 'undefined') ? null : value);
};
// bundles an array of promises into a single promise that requires none to succeed for a pass
// - `shouldFulfillCB` is called with (results, fails) to determine whether to fulfill or reject
function bundle(ps, shouldFulfillCB) {
if (!Array.isArray(ps)) ps = [ps];
var p = promise(), nPromises = ps.length, nFinished = 0;
if (nPromises === 0) {
p.fulfill([]);
return p;
}
var results = []; results.length = nPromises;
var fails = [];
var addResult = function(v, index, isfail) {
results[index] = v;
if (isfail) fails.push(index);
if ((++nFinished) == nPromises) {
if (!shouldFulfillCB) p.fulfill(results);
else if (shouldFulfillCB(results, fails)) p.fulfill(results);
else p.reject(results);
}
};
for (var i=0; i < nPromises; i++)
promise(ps[i]).succeed(addResult, i, false).fail(addResult, i, true);
return p;
}
// bundles an array of promises into a single promise that requires all to succeed for a pass
function all(ps) {
return bundle(ps, function(results, fails) {
return fails.length === 0;
});
}
// bundles an array of promises into a single promise that requires one to succeed for a pass
function any(ps) {
return bundle(ps, function(results, fails) {
return fails.length < results.length;
});
}
// promise creator
// - behaves like a guard, ensuring `v` is a promise
// - if multiple arguments are given, will provide a promise that encompasses all of them
// - containing promise always succeeds
function promise(v) {
if (arguments.length > 1)
return bundle(Array.prototype.slice.call(arguments));
if (v instanceof Promise)
return v;
if (isPromiselike(v)) {
var p = promise();
v.then(function(v2) { p.fulfill(v2); }, function(v2) { p.reject(v2); });
return p;
}
return new Promise(v);
}
module.exports = {
Promise: Promise,
promise: promise,
isPromiselike: isPromiselike
};
promise.bundle = bundle;
promise.all = all;
promise.any = any;
},{"./config.js":1,"./util":9}],5:[function(require,module,exports){
// Standard DOM Events
// ===================
var util = require('./util');
// bindRequestEvents()
// ===================
// EXPORTED
// Converts 'click' and 'submit' events into custom 'request' events
// - within the container, all 'click' and 'submit' events will be consumed
// - 'request' events will be dispatched by the original dispatching element
// Parameters:
// - `container` must be a valid DOM element
// - `options` may disable event listeners by setting `links` or `forms` to false
function bindRequestEvents(container, options) {
container.__localEventHandlers = [];
options = options || {};
var handler;
if (options.links !== false) {
// anchor-click handler
handler = { name: 'click', handleEvent: Local__clickHandler, container: container };
container.addEventListener('click', handler, false);
container.__localEventHandlers.push(handler);
}
if (options.forms !== false) {
// submitter tracking
handler = { name: 'click', handleEvent: Local__submitterTracker, container: container };
container.addEventListener('click', handler, true); // must be on capture to happen in time
container.__localEventHandlers.push(handler);
// submit handler
handler = { name: 'submit', handleEvent: Local__submitHandler, container: container };
container.addEventListener('submit', handler, false);
container.__localEventHandlers.push(handler);
}
}
// unbindRequestEvents()
// =====================
// EXPORTED
// Stops listening to 'click' and 'submit' events
function unbindRequestEvents(container) {
if (container.__localEventHandlers) {
container.__localEventHandlers.forEach(function(handler) {
container.removeEventListener(handler.name, handler);
});
delete container.__localEventHandlers;
}
}
// INTERNAL
// transforms click events into request events
function Local__clickHandler(e) {
if (e.button !== 0) { return; } // handle left-click only
var request = util.extractRequest.fromAnchor(e.orgtarget || e.target);
if (request && ['_top','_blank'].indexOf(request.target) !== -1) { return; }
if (request) {
e.preventDefault();
e.stopPropagation();
util.dispatchRequestEvent(e.target, request);
return false;
}
}
// INTERNAL
// marks the submitting element (on click capture-phase) so the submit handler knows who triggered it
function Local__submitterTracker(e) {
if (e.button !== 0) { return; } // handle left-click only
util.trackFormSubmitter(e.target);
}
// INTERNAL
// transforms submit events into request events
function Local__submitHandler(e) {
var request = util.extractRequest(e.target, this.container);
if (request && ['_top','_blank'].indexOf(request.target) !== -1) { return; }
if (request) {
e.preventDefault();
e.stopPropagation();
util.finishPayloadFileReads(request).then(function() {
util.dispatchRequestEvent(e.target, request);
});
return false;
}
}
module.exports = {
bindRequestEvents: bindRequestEvents,
unbindRequestEvents: unbindRequestEvents
};
},{"./util":9}],6:[function(require,module,exports){
// Helpers to create servers
// -
var helpers = require('./web/helpers.js');
var httpl = require('./web/httpl.js');
var WorkerBridgeServer = require('./web/worker-bridge-server.js');
var Relay = require('./web/relay.js');
// EXPORTED
// Creates a Web Worker and a bridge server to the worker
// eg `local.spawnWorkerServer('http://foo.com/myworker.js', localServerFn)
// - `src`: optional string, the URI to load into the worker. If null, must give `config.domain` with a source-path
// - `config`: optional object, additional config options to pass to the worker
// - `config.domain`: optional string, overrides the automatic domain generation
// - `config.temp`: boolean, should the workerserver be destroyed after it handles it's requests?
// - `config.shared`: boolean, should the workerserver be shared?
// - `config.namespace`: optional string, what should the shared worker be named?
// - defaults to `config.src` if undefined
// - `serverFn`: optional function, a response generator for requests from the worker
function spawnWorkerServer(src, config, serverFn) {
if (typeof config == 'function') { serverFn = config; config = null; }
if (!config) { config = {}; }
config.src = src;
config.serverFn = serverFn;
// Create the domain
var domain = config.domain;
if (!domain) {
if (local.isAbsUri(src)) {
var urld = helpers.parseUri(src);
domain = urld.authority + '(' + urld.path.slice(1) + ')';
} else {
var src_parts = src.split(/[\?#]/);
domain = window.location.host + '(' + src_parts[0].slice(1) + ')';
}
}
// Create the server
if (httpl.getServer(domain)) throw "Worker already exists";
var server = new WorkerBridgeServer(config);
httpl.addServer(domain, server);
return server;
}
// EXPORTED
// Opens a stream to a peer relay
// - `providerUrl`: optional string, the relay provider
// - `config.app`: optional string, the app to join as (defaults to window.location.host)
// - `serverFn`: optional function, a response generator for requests from connected peers
function joinRelay(providerUrl, config, serverFn) {
if (typeof config == 'function') { serverFn = config; config = null; }
if (!config) config = {};
config.provider = providerUrl;
config.serverFn = serverFn;
return new Relay(config);
}
module.exports = {
spawnWorkerServer: spawnWorkerServer,
joinRelay: joinRelay
};
},{"./web/helpers.js":14,"./web/httpl.js":16,"./web/relay.js":17,"./web/worker-bridge-server.js":25}],7:[function(require,module,exports){
// Helpers
// =======
if (typeof CustomEvent === 'undefined') {
// CustomEvent shim (safari)
// thanks to netoneko https://github.com/maker/ratchet/issues/101
CustomEvent = function(type, eventInitDict) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent(type, eventInitDict['bubbles'], eventInitDict['cancelable'], eventInitDict['detail']);
return event;
};
}
// EXPORTED
// searches up the node tree for an element
function findParentNode(node, test) {
while (node) {
if (test(node)) { return node; }
node = node.parentNode;
}
return null;
}
findParentNode.byTag = function(node, tagName) {
return findParentNode(node, function(elem) {
return elem.tagName == tagName;
});
};
findParentNode.byTagOrAlias = function(node, tagName) {
return findParentNode(node, function(elem) {
return elem.tagName == tagName || (elem.dataset && elem.dataset.localAlias && elem.dataset.localAlias.toUpperCase() == tagName);
});
};
findParentNode.byClass = function(node, className) {
return findParentNode(node, function(elem) {
return elem.classList && elem.classList.contains(className);
});
};
findParentNode.byElement = function(node, element) {
return findParentNode(node, function(elem) {
return elem === element;
});
};
findParentNode.thatisFormRelated = function(node) {
return findParentNode(node, function(elem) {
return !!elem.form;
});
};
// combines parameters as objects
// - precedence is rightmost
// reduceObjects({a:1}, {a:2}, {a:3}) => {a:3}
function reduceObjects() {
var objs = Array.prototype.slice.call(arguments);
var acc = {}, obj;
while (objs.length) {
obj = objs.shift();
if (!obj) { continue; }
for (var k in obj) {
if (typeof obj[k] == 'undefined' || obj[k] === null) { continue; }
if (typeof obj[k] == 'object' && !Array.isArray(obj[k])) {
acc[k] = reduceObjects(acc[k], obj[k]);
} else {
acc[k] = obj[k];
}
}
}
return acc;
}
// EXPORTED
// dispatches a request event, stopping the given event
function dispatchRequestEvent(targetElem, request) {
var re = new CustomEvent('request', { bubbles:true, cancelable:true, detail:request });
targetElem.dispatchEvent(re);
}
// EXPORTED
// submit helper, makes it possible to find the button which triggered the submit
function trackFormSubmitter(node) {
var elem = findParentNode.thatisFormRelated(node);
if (elem) {
for (var i=0; i < elem.form.length; i++) {
elem.form[i].setAttribute('submitter', null);
}
elem.setAttribute('submitter', '1');
}
}
// EXPORTED
// extracts request from any given element
function extractRequest(targetElem, containerElem) {
var requests = { form:{}, elem:{} };
var form = null;
// find parent form
if (targetElem.tagName === 'FORM') {
form = targetElem;
} else {
// :TODO: targetElem.form may be a simpler alternative
var formId = targetElem.getAttribute('form');
if (formId) {
form = containerElem.querySelector('#'+formId);
}
if (!form) {
form = findParentNode.byTag(targetElem, 'FORM');
}
}
// extract payload
var payload = extractRequestPayload(targetElem, form);
// extract form headers
if (form) {
requests.form = extractRequest.fromForm(form, targetElem);
}
// extract element headers
if (targetElem.tagName === 'A') {
requests.elem = extractRequest.fromAnchor(targetElem);
} else if (['FORM','FIELDSET'].indexOf(targetElem.tagName) === -1) {
requests.elem = extractRequest.fromFormElement(targetElem);
}
// combine then all, with precedence given to rightmost objects in param list
var req = reduceObjects(requests.form, requests.elem);
var payloadWrapper = {};
payloadWrapper[/GET/i.test(req.method) ? 'query' : 'body'] = payload;
return reduceObjects(req, payloadWrapper);
}
// EXPORTED
// extracts request parameters from an anchor tag
extractRequest.fromAnchor = function(node) {
// get the anchor
node = findParentNode.byTagOrAlias(node, 'A');
if (!node || !node.attributes.href || node.attributes.href.value.charAt(0) == '#') { return null; }
// pull out params
var request = {
method: node.getAttribute('method'),
url: node.attributes.href.value,
target: node.getAttribute('target'),
headers: { accept: node.getAttribute('type') }
};
return request;
};
// EXPORTED
// extracts request parameters from a form element (inputs, textareas, etc)
extractRequest.fromFormElement = function(node) {
// :TODO: search parent for the form-related element?
// might obviate the need for submitter-tracking
// pull out params
var request = {
method : node.getAttribute('formmethod'),
url : node.getAttribute('formaction'),
target : node.getAttribute('formtarget'),
headers : {
'content-type' : node.getAttribute('formenctype'),
accept : node.getAttribute('formaccept')
}
};
return request;
};
// EXPORTED
// extracts request parameters from a form
extractRequest.fromForm = function(form, submittingElem) {
// find the submitter, if the submitting element is not form-related
if (submittingElem && !submittingElem.form) {
for (var i=0; i < form.length; i++) {
var elem = form[i];
if (elem.getAttribute('submitter') == '1') {
submittingElem = elem;
elem.setAttribute('submitter', '0');
break;
}
}
}
var requests = { submitter:{}, fieldset:{}, form:{} };
// extract submitting element headers
if (submittingElem) {
requests.submitter = {
method : submittingElem.getAttribute('formmethod'),
url : submittingElem.getAttribute('formaction'),
target : submittingElem.getAttribute('formtarget'),
headers : {
'content-type' : submittingElem.getAttribute('formenctype'),
accept : submittingElem.getAttribute('formaccept')
}
};
// find fieldset(s)
var fieldsetEl = submittingElem;
var fieldsetTest = function(elem) { return elem.tagName == 'FIELDSET' || elem.tagName == 'FORM'; };
while ((fieldsetEl = findParentNode(fieldsetEl.parentNode, fieldsetTest))) {
if (fieldsetEl.tagName == 'FORM') {
break; // Stop at the form
}
// extract fieldset headers
if (fieldsetEl) {
requests.fieldset = reduceObjects(extractRequest.fromFormElement(fieldsetEl), requests.fieldset);
}
}
}
// extract form headers
requests.form = {
method : form.getAttribute('method'),
url : form.getAttribute('action'),
target : form.getAttribute('target'),
headers : {
'content-type' : form.getAttribute('enctype') || form.enctype,
'accept' : form.getAttribute('accept')
}
};
if (form.acceptCharset) { requests.form.headers.accept = form.acceptCharset; }
// combine, with precedence to the submitting element
var request = reduceObjects(requests.form, requests.fieldset, requests.submitter);
// strip the base URI
// :TODO: needed?
/*var base_uri = window.location.href.split('#')[0];
if (target_uri.indexOf(base_uri) != -1) {
target_uri = target_uri.substring(base_uri.length);
if (target_uri.charAt(0) != '/') { target_uri = '/' + target_uri; }
}*/
return request;
};
// EXPORTED
// serializes all form elements beneath and including the given element
// - `targetElem`: container element, will reject the field if not within (optional)
// - `form`: an array of HTMLElements or a form field (they behave the same for iteration)
// - `opts.nofiles`: dont try to read files in file fields? (optional)
function extractRequestPayload(targetElem, form, opts) {
if (!opts) opts = {};
// iterate form elements
var data = {};
if (!opts.nofiles)
data.__fileReads = []; // an array of promises to read <input type=file>s
for (var i=0; i < form.length; i++) {
var elem = form[i];
// skip if it doesnt have a name
if (!elem.name) {
continue;
}
// skip if not a child of the target element
if (targetElem && !findParentNode.byElement(elem, targetElem))
continue;
// pull value if it has one
var isSubmittingElem = elem.getAttribute('submitter') == '1';
if (elem.tagName === 'BUTTON') {
if (isSubmittingElem) {
// don't pull from buttons unless recently clicked
data[elem.name] = elem.value;
}
} else if (elem.tagName === 'INPUT') {
switch (elem.type.toLowerCase()) {
case 'button':
case 'submit':
if (isSubmittingElem) {
// don't pull from buttons unless recently clicked
data[elem.name] = elem.value;
}
break;
case 'checkbox':
if (elem.checked) {
// don't pull from checkboxes unless checked
data[elem.name] = (data[elem.name] || []).concat(elem.value);
}
break;
case 'radio':
if (elem.getAttribute('checked') !== null) {
// don't pull from radios unless selected
data[elem.name] = elem.value;
}
break;
case 'file':
// read the files
if (opts.nofiles)
break;
if (elem.multiple) {
for (var i=0, f; f = elem.files[i]; i++)
readFile(data, elem, elem.files[i], i);
data[elem.name] = [];
data[elem.name].length = i;
} else {
readFile(data, elem, elem.files[0]);
}
break;
default:
data[elem.name] = elem.value;
break;
}
} else
data[elem.name] = elem.value;
}
return data;
}
// INTERNAL
// file read helpers
function readFile(data, elem, file, index) {
if (!file) return; // no value set
var reader = new FileReader();
reader.onloadend = readFileLoadEnd(data, elem, file, index);
reader.readAsDataURL(file);
}
function readFileLoadEnd(data, elem, file, index) {
// ^ this avoids a closure circular reference
var promise = require('../promises.js').promise();
data.__fileReads.push(promise);
return function(e) {
var obj = {
content: e.target.result || null,
name: file.name,
formattr: elem.name,
size: file.size,
type: file.type,
lastModifiedDate: file.lastModifiedDate
};
if (typeof index != 'undefined')
obj.formindex = index;
promise.fulfill(obj);
};
}
function finishPayloadFileReads(request) {
var fileReads = (request.body) ? request.body.__fileReads :
((request.query) ? request.query.__fileReads : []);
return require('../promises.js').promise.bundle(fileReads).then(function(files) {
if (request.body) delete request.body.__fileReads;
if (request.query) delete request.query.__fileReads;
files.forEach(function(file) {
if (typeof file.formindex != 'undefined')
request.body[file.formattr][file.formindex] = file;
else request.body[file.formattr] = file;
});
return request;
});
}
module.exports = {
findParentNode: findParentNode,
trackFormSubmitter: trackFormSubmitter,
dispatchRequestEvent: dispatchRequestEvent,
extractRequest: extractRequest,
extractRequestPayload: extractRequestPayload,
finishPayloadFileReads: finishPayloadFileReads
};
},{"../promises.js":4}],8:[function(require,module,exports){
// EventEmitter
// ============
// EXPORTED
// A minimal event emitter, based on the NodeJS api
// initial code borrowed from https://github.com/tmpvar/node-eventemitter (thanks tmpvar)
function EventEmitter() {
Object.defineProperty(this, '_events', {
value: {},
configurable: false,
enumerable: false,
writable: true
});
Object.defineProperty(this, '_suspensions', {
value: 0,
configurable: false,
enumerable: false,
writable: true
});
Object.defineProperty(this, '_history', {
value: [],
configurable: false,
enumerable: false,
writable: true
});
}
module.exports = EventEmitter;
EventEmitter.prototype.suspendEvents = function() {
this._suspensions++;
};
EventEmitter.prototype.resumeEvents = function() {
this._suspensions--;
if (this._suspensions <= 0)
this.playbackHistory();
};
EventEmitter.prototype.isSuspended = function() { return this._suspensions > 0; };
EventEmitter.prototype.playbackHistory = function() {
var e;
// always check if we're suspended - a handler might resuspend us
while (!this.isSuspended() && (e = this._history.shift()))
this.emit.apply(this, e);
};
EventEmitter.prototype.emit = function(type) {
var args = Array.prototype.slice.call(arguments);
if (this.isSuspended()) {
this._history.push(args);
return;
}
var handlers = this._events[type];
if (!handlers) return false;
args = args.slice(1);
for (var i = 0, l = handlers.length; i < l; i++)
handlers[i].apply(this, args);
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
if (Array.isArray(type)) {
type.forEach(function(t) { this.addListener(t, listener); }, this);
return;
}
if ('function' !== typeof listener) {
throw new Error('addListener only takes instances of Function');
}
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if (!this._events[type]) {
this._events[type] = [listener];
} else {
this._events[type].push(listener);
}
return this;