luci-base: luci.js: fix L.Poll.remove()
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / luci.js
1 (function(window, document, undefined) {
2         'use strict';
3
4         /* Object.assign polyfill for IE */
5         if (typeof Object.assign !== 'function') {
6                 Object.defineProperty(Object, 'assign', {
7                         value: function assign(target, varArgs) {
8                                 if (target == null)
9                                         throw new TypeError('Cannot convert undefined or null to object');
10
11                                 var to = Object(target);
12
13                                 for (var index = 1; index < arguments.length; index++)
14                                         if (arguments[index] != null)
15                                                 for (var nextKey in arguments[index])
16                                                         if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
17                                                                 to[nextKey] = arguments[index][nextKey];
18
19                                 return to;
20                         },
21                         writable: true,
22                         configurable: true
23                 });
24         }
25
26         /* Promise.finally polyfill */
27         if (typeof Promise.prototype.finally !== 'function') {
28                 Promise.prototype.finally = function(fn) {
29                         var onFinally = function(cb) {
30                                 return Promise.resolve(fn.call(this)).then(cb);
31                         };
32
33                         return this.then(
34                                 function(result) { return onFinally.call(this, function() { return result }) },
35                                 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
36                         );
37                 };
38         }
39
40         /*
41          * Class declaration and inheritance helper
42          */
43
44         var toCamelCase = function(s) {
45                 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
46         };
47
48         var superContext = null, Class = Object.assign(function() {}, {
49                 extend: function(properties) {
50                         var props = {
51                                 __base__: { value: this.prototype },
52                                 __name__: { value: properties.__name__ || 'anonymous' }
53                         };
54
55                         var ClassConstructor = function() {
56                                 if (!(this instanceof ClassConstructor))
57                                         throw new TypeError('Constructor must not be called without "new"');
58
59                                 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
60                                         if (typeof(this.__init__) != 'function')
61                                                 throw new TypeError('Class __init__ member is not a function');
62
63                                         this.__init__.apply(this, arguments)
64                                 }
65                                 else {
66                                         this.super('__init__', arguments);
67                                 }
68                         };
69
70                         for (var key in properties)
71                                 if (!props[key] && properties.hasOwnProperty(key))
72                                         props[key] = { value: properties[key], writable: true };
73
74                         ClassConstructor.prototype = Object.create(this.prototype, props);
75                         ClassConstructor.prototype.constructor = ClassConstructor;
76                         Object.assign(ClassConstructor, this);
77                         ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
78
79                         return ClassConstructor;
80                 },
81
82                 singleton: function(properties /*, ... */) {
83                         return Class.extend(properties)
84                                 .instantiate(Class.prototype.varargs(arguments, 1));
85                 },
86
87                 instantiate: function(args) {
88                         return new (Function.prototype.bind.apply(this,
89                                 Class.prototype.varargs(args, 0, null)))();
90                 },
91
92                 call: function(self, method) {
93                         if (typeof(this.prototype[method]) != 'function')
94                                 throw new ReferenceError(method + ' is not defined in class');
95
96                         return this.prototype[method].apply(self, self.varargs(arguments, 1));
97                 },
98
99                 isSubclass: function(_class) {
100                         return (_class != null &&
101                                 typeof(_class) == 'function' &&
102                                 _class.prototype instanceof this);
103                 },
104
105                 prototype: {
106                         varargs: function(args, offset /*, ... */) {
107                                 return Array.prototype.slice.call(arguments, 2)
108                                         .concat(Array.prototype.slice.call(args, offset));
109                         },
110
111                         super: function(key, callArgs) {
112                                 for (superContext = Object.getPrototypeOf(superContext ||
113                                                                           Object.getPrototypeOf(this));
114                                      superContext && !superContext.hasOwnProperty(key);
115                                      superContext = Object.getPrototypeOf(superContext)) { }
116
117                                 if (!superContext)
118                                         return null;
119
120                                 var res = superContext[key];
121
122                                 if (arguments.length > 1) {
123                                         if (typeof(res) != 'function')
124                                                 throw new ReferenceError(key + ' is not a function in base class');
125
126                                         if (typeof(callArgs) != 'object')
127                                                 callArgs = this.varargs(arguments, 1);
128
129                                         res = res.apply(this, callArgs);
130                                 }
131
132                                 superContext = null;
133
134                                 return res;
135                         },
136
137                         toString: function() {
138                                 var s = '[' + this.constructor.displayName + ']', f = true;
139                                 for (var k in this) {
140                                         if (this.hasOwnProperty(k)) {
141                                                 s += (f ? ' {\n' : '') + '  ' + k + ': ' + typeof(this[k]) + '\n';
142                                                 f = false;
143                                         }
144                                 }
145                                 return s + (f ? '' : '}');
146                         }
147                 }
148         });
149
150
151         /*
152          * HTTP Request helper
153          */
154
155         var Headers = Class.extend({
156                 __name__: 'LuCI.XHR.Headers',
157                 __init__: function(xhr) {
158                         var hdrs = this.headers = {};
159                         xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
160                                 var m = /^([^:]+):(.*)$/.exec(line);
161                                 if (m != null)
162                                         hdrs[m[1].trim().toLowerCase()] = m[2].trim();
163                         });
164                 },
165
166                 has: function(name) {
167                         return this.headers.hasOwnProperty(String(name).toLowerCase());
168                 },
169
170                 get: function(name) {
171                         var key = String(name).toLowerCase();
172                         return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
173                 }
174         });
175
176         var Response = Class.extend({
177                 __name__: 'LuCI.XHR.Response',
178                 __init__: function(xhr, url, duration, headers, content) {
179                         this.ok = (xhr.status >= 200 && xhr.status <= 299);
180                         this.status = xhr.status;
181                         this.statusText = xhr.statusText;
182                         this.headers = (headers != null) ? headers : new Headers(xhr);
183                         this.duration = duration;
184                         this.url = url;
185                         this.xhr = xhr;
186
187                         if (content != null && typeof(content) == 'object') {
188                                 this.responseJSON = content;
189                                 this.responseText = null;
190                         }
191                         else if (content != null) {
192                                 this.responseJSON = null;
193                                 this.responseText = String(content);
194                         }
195                         else {
196                                 this.responseJSON = null;
197                                 this.responseText = xhr.responseText;
198                         }
199                 },
200
201                 clone: function(content) {
202                         var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
203
204                         copy.ok = this.ok;
205                         copy.status = this.status;
206                         copy.statusText = this.statusText;
207
208                         return copy;
209                 },
210
211                 json: function() {
212                         if (this.responseJSON == null)
213                                 this.responseJSON = JSON.parse(this.responseText);
214
215                         return this.responseJSON;
216                 },
217
218                 text: function() {
219                         if (this.responseText == null && this.responseJSON != null)
220                                 this.responseText = JSON.stringify(this.responseJSON);
221
222                         return this.responseText;
223                 }
224         });
225
226
227         var requestQueue = [];
228
229         function isQueueableRequest(opt) {
230                 if (!classes.rpc)
231                         return false;
232
233                 if (opt.method != 'POST' || typeof(opt.content) != 'object')
234                         return false;
235
236                 if (opt.nobatch === true)
237                         return false;
238
239                 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
240
241                 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
242         }
243
244         function flushRequestQueue() {
245                 if (!requestQueue.length)
246                         return;
247
248                 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
249                     batch = [];
250
251                 for (var i = 0; i < requestQueue.length; i++) {
252                         batch[i] = requestQueue[i];
253                         reqopt.content[i] = batch[i][0].content;
254                 }
255
256                 requestQueue.length = 0;
257
258                 Request.request(rpcBaseURL, reqopt).then(function(reply) {
259                         var json = null, req = null;
260
261                         try { json = reply.json() }
262                         catch(e) { }
263
264                         while ((req = batch.shift()) != null)
265                                 if (Array.isArray(json) && json.length)
266                                         req[2].call(reqopt, reply.clone(json.shift()));
267                                 else
268                                         req[1].call(reqopt, new Error('No related RPC reply'));
269                 }).catch(function(error) {
270                         var req = null;
271
272                         while ((req = batch.shift()) != null)
273                                 req[1].call(reqopt, error);
274                 });
275         }
276
277         var Request = Class.singleton({
278                 __name__: 'LuCI.Request',
279
280                 interceptors: [],
281
282                 expandURL: function(url) {
283                         if (!/^(?:[^/]+:)?\/\//.test(url))
284                                 url = location.protocol + '//' + location.host + url;
285
286                         return url;
287                 },
288
289                 request: function(target, options) {
290                         var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
291                             opt = Object.assign({}, options, state),
292                             content = null,
293                             contenttype = null,
294                             callback = this.handleReadyStateChange;
295
296                         return new Promise(function(resolveFn, rejectFn) {
297                                 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
298                                 opt.method = String(opt.method || 'GET').toUpperCase();
299
300                                 if ('query' in opt) {
301                                         var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
302                                                 if (opt.query[k] != null) {
303                                                         var v = (typeof(opt.query[k]) == 'object')
304                                                                 ? JSON.stringify(opt.query[k])
305                                                                 : String(opt.query[k]);
306
307                                                         return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
308                                                 }
309                                                 else {
310                                                         return encodeURIComponent(k);
311                                                 }
312                                         }).join('&') : '';
313
314                                         if (q !== '') {
315                                                 switch (opt.method) {
316                                                 case 'GET':
317                                                 case 'HEAD':
318                                                 case 'OPTIONS':
319                                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
320                                                         break;
321
322                                                 default:
323                                                         if (content == null) {
324                                                                 content = q;
325                                                                 contenttype = 'application/x-www-form-urlencoded';
326                                                         }
327                                                 }
328                                         }
329                                 }
330
331                                 if (!opt.cache)
332                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
333
334                                 if (isQueueableRequest(opt)) {
335                                         requestQueue.push([opt, rejectFn, resolveFn]);
336                                         requestAnimationFrame(flushRequestQueue);
337                                         return;
338                                 }
339
340                                 if ('username' in opt && 'password' in opt)
341                                         opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
342                                 else
343                                         opt.xhr.open(opt.method, opt.url, true);
344
345                                 opt.xhr.responseType = 'text';
346
347                                 if ('overrideMimeType' in opt.xhr)
348                                         opt.xhr.overrideMimeType('application/octet-stream');
349
350                                 if ('timeout' in opt)
351                                         opt.xhr.timeout = +opt.timeout;
352
353                                 if ('credentials' in opt)
354                                         opt.xhr.withCredentials = !!opt.credentials;
355
356                                 if (opt.content != null) {
357                                         switch (typeof(opt.content)) {
358                                         case 'function':
359                                                 content = opt.content(xhr);
360                                                 break;
361
362                                         case 'object':
363                                                 content = JSON.stringify(opt.content);
364                                                 contenttype = 'application/json';
365                                                 break;
366
367                                         default:
368                                                 content = String(opt.content);
369                                         }
370                                 }
371
372                                 if ('headers' in opt)
373                                         for (var header in opt.headers)
374                                                 if (opt.headers.hasOwnProperty(header)) {
375                                                         if (header.toLowerCase() != 'content-type')
376                                                                 opt.xhr.setRequestHeader(header, opt.headers[header]);
377                                                         else
378                                                                 contenttype = opt.headers[header];
379                                                 }
380
381                                 if (contenttype != null)
382                                         opt.xhr.setRequestHeader('Content-Type', contenttype);
383
384                                 try {
385                                         opt.xhr.send(content);
386                                 }
387                                 catch (e) {
388                                         rejectFn.call(opt, e);
389                                 }
390                         });
391                 },
392
393                 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
394                         var xhr = this.xhr;
395
396                         if (xhr.readyState !== 4)
397                                 return;
398
399                         if (xhr.status === 0 && xhr.statusText === '') {
400                                 rejectFn.call(this, new Error('XHR request aborted by browser'));
401                         }
402                         else {
403                                 var response = new Response(
404                                         xhr, xhr.responseURL || this.url, Date.now() - this.start);
405
406                                 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
407                                         .then(resolveFn.bind(this, response))
408                                         .catch(rejectFn.bind(this));
409                         }
410                 },
411
412                 get: function(url, options) {
413                         return this.request(url, Object.assign({ method: 'GET' }, options));
414                 },
415
416                 post: function(url, data, options) {
417                         return this.request(url, Object.assign({ method: 'POST', content: data }, options));
418                 },
419
420                 addInterceptor: function(interceptorFn) {
421                         if (typeof(interceptorFn) == 'function')
422                                 this.interceptors.push(interceptorFn);
423                         return interceptorFn;
424                 },
425
426                 removeInterceptor: function(interceptorFn) {
427                         var oldlen = this.interceptors.length, i = oldlen;
428                         while (i--)
429                                 if (this.interceptors[i] === interceptorFn)
430                                         this.interceptors.splice(i, 1);
431                         return (this.interceptors.length < oldlen);
432                 },
433
434                 poll: {
435                         add: function(interval, url, options, callback) {
436                                 if (isNaN(interval) || interval <= 0)
437                                         throw new TypeError('Invalid poll interval');
438
439                                 var ival = interval >>> 0,
440                                     opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
441
442                                 return Poll.add(function() {
443                                         return Request.request(url, options).then(function(res) {
444                                                 if (!Poll.active())
445                                                         return;
446
447                                                 try {
448                                                         callback(res, res.json(), res.duration);
449                                                 }
450                                                 catch (err) {
451                                                         callback(res, null, res.duration);
452                                                 }
453                                         });
454                                 }, ival);
455                         },
456
457                         remove: function(entry) { return Poll.remove(entry) },
458                         start: function() { return Poll.start() },
459                         stop: function() { return Poll.stop() },
460                         active: function() { return Poll.active() }
461                 }
462         });
463
464         var Poll = Class.singleton({
465                 __name__: 'LuCI.Poll',
466
467                 queue: [],
468
469                 add: function(fn, interval) {
470                         if (interval == null || interval <= 0)
471                                 interval = window.L ? window.L.env.pollinterval : null;
472
473                         if (isNaN(interval) || typeof(fn) != 'function')
474                                 throw new TypeError('Invalid argument to LuCI.Poll.add()');
475
476                         for (var i = 0; i < this.queue.length; i++)
477                                 if (this.queue[i].fn === fn)
478                                         return false;
479
480                         var e = {
481                                 r: true,
482                                 i: interval >>> 0,
483                                 fn: fn
484                         };
485
486                         this.queue.push(e);
487
488                         if (this.tick != null && !this.active())
489                                 this.start();
490
491                         return true;
492                 },
493
494                 remove: function(fn) {
495                         if (typeof(fn) != 'function')
496                                 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
497
498                         var len = this.queue.length;
499
500                         for (var i = len; i > 0; i--)
501                                 if (this.queue[i-1].fn === fn)
502                                         this.queue.splice(i-1, 1);
503
504                         if (!this.queue.length && this.stop())
505                                 this.tick = 0;
506
507                         return (this.queue.length != len);
508                 },
509
510                 start: function() {
511                         if (this.active())
512                                 return false;
513
514                         this.tick = 0;
515
516                         if (this.queue.length) {
517                                 this.timer = window.setInterval(this.step, 1000);
518                                 this.step();
519                                 document.dispatchEvent(new CustomEvent('poll-start'));
520                         }
521
522                         return true;
523                 },
524
525                 stop: function() {
526                         if (!this.active())
527                                 return false;
528
529                         document.dispatchEvent(new CustomEvent('poll-stop'));
530                         window.clearInterval(this.timer);
531                         delete this.timer;
532                         delete this.tick;
533                         return true;
534                 },
535
536                 step: function() {
537                         for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
538                                 if ((Poll.tick % e.i) != 0)
539                                         continue;
540
541                                 if (!e.r)
542                                         continue;
543
544                                 e.r = false;
545
546                                 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
547                         }
548
549                         Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
550                 },
551
552                 active: function() {
553                         return (this.timer != null);
554                 }
555         });
556
557
558         var dummyElem = null,
559             domParser = null,
560             originalCBIInit = null,
561             rpcBaseURL = null,
562             sysFeatures = null,
563             classes = {};
564
565         var LuCI = Class.extend({
566                 __name__: 'LuCI',
567                 __init__: function(env) {
568
569                         document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
570                                 if (env.base_url == null || env.base_url == '')
571                                         env.base_url = s.getAttribute('src').replace(/\/luci\.js(?:\?v=[^?]+)?$/, '');
572                         });
573
574                         if (env.base_url == null)
575                                 this.error('InternalError', 'Cannot find url of luci.js');
576
577                         Object.assign(this.env, env);
578
579                         document.addEventListener('poll-start', function(ev) {
580                                 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
581                                         e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
582                                 });
583                         });
584
585                         document.addEventListener('poll-stop', function(ev) {
586                                 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
587                                         e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
588                                 });
589                         });
590
591                         var domReady = new Promise(function(resolveFn, rejectFn) {
592                                 document.addEventListener('DOMContentLoaded', resolveFn);
593                         });
594
595                         Promise.all([
596                                 domReady,
597                                 this.require('ui'),
598                                 this.require('rpc'),
599                                 this.require('form'),
600                                 this.probeRPCBaseURL()
601                         ]).then(this.setupDOM.bind(this)).catch(this.error);
602
603                         originalCBIInit = window.cbi_init;
604                         window.cbi_init = function() {};
605                 },
606
607                 raise: function(type, fmt /*, ...*/) {
608                         var e = null,
609                             msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
610                             stack = null;
611
612                         if (type instanceof Error) {
613                                 e = type;
614                                 stack = (e.stack || '').split(/\n/);
615
616                                 if (msg)
617                                         e.message = msg + ': ' + e.message;
618                         }
619                         else {
620                                 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
621                                 e.name = type || 'Error';
622                         }
623
624                         if (window.console && console.debug)
625                                 console.debug(e);
626
627                         throw e;
628                 },
629
630                 error: function(type, fmt /*, ...*/) {
631                         try {
632                                 L.raise.apply(L, Array.prototype.slice.call(arguments));
633                         }
634                         catch (e) {
635                                 var stack = (e.stack || '').split(/\n/).map(function(frame) {
636                                         frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
637                                         return frame ? '  ' + frame : '';
638                                 });
639
640                                 if (!/^  at /.test(stack[0]))
641                                         stack.shift();
642
643                                 if (/\braise /.test(stack[0]))
644                                         stack.shift();
645
646                                 if (/\berror /.test(stack[0]))
647                                         stack.shift();
648
649                                 stack = stack.length ? '\n' + stack.join('\n') : '';
650
651                                 if (L.ui)
652                                         L.ui.showModal(e.name || _('Runtime error'),
653                                                 E('pre', { 'class': 'alert-message error' }, e.message + stack));
654                                 else
655                                         L.dom.content(document.querySelector('#maincontent'),
656                                                 E('pre', { 'class': 'alert-message error' }, e + stack));
657
658                                 throw e;
659                         }
660                 },
661
662                 bind: function(fn, self /*, ... */) {
663                         return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
664                 },
665
666                 /* Class require */
667                 require: function(name, from) {
668                         var L = this, url = null, from = from || [];
669
670                         /* Class already loaded */
671                         if (classes[name] != null) {
672                                 /* Circular dependency */
673                                 if (from.indexOf(name) != -1)
674                                         L.raise('DependencyError',
675                                                 'Circular dependency: class "%s" depends on "%s"',
676                                                 name, from.join('" which depends on "'));
677
678                                 return classes[name];
679                         }
680
681                         url = '%s/%s.js'.format(L.env.base_url, name.replace(/\./g, '/'));
682                         from = [ name ].concat(from);
683
684                         var compileClass = function(res) {
685                                 if (!res.ok)
686                                         L.raise('NetworkError',
687                                                 'HTTP error %d while loading class file "%s"', res.status, url);
688
689                                 var source = res.text(),
690                                     requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
691                                     strictmatch = /^use[ \t]+strict$/,
692                                     depends = [],
693                                     args = '';
694
695                                 /* find require statements in source */
696                                 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
697                                         var chr = source.charCodeAt(i);
698
699                                         if (esc) {
700                                                 esc = false;
701                                         }
702                                         else if (chr == 92) {
703                                                 esc = true;
704                                         }
705                                         else if (chr == quote) {
706                                                 var s = source.substring(off, i),
707                                                     m = requirematch.exec(s);
708
709                                                 if (m) {
710                                                         var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
711                                                         depends.push(L.require(dep, from));
712                                                         args += ', ' + as;
713                                                 }
714                                                 else if (!strictmatch.exec(s)) {
715                                                         break;
716                                                 }
717
718                                                 off = -1;
719                                                 quote = -1;
720                                         }
721                                         else if (quote == -1 && (chr == 34 || chr == 39)) {
722                                                 off = i + 1;
723                                                 quote = chr;
724                                         }
725                                 }
726
727                                 /* load dependencies and instantiate class */
728                                 return Promise.all(depends).then(function(instances) {
729                                         var _factory, _class;
730
731                                         try {
732                                                 _factory = eval(
733                                                         '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
734                                                                 .format(args, source, res.url));
735                                         }
736                                         catch (error) {
737                                                 L.raise('SyntaxError', '%s\n  in %s:%s',
738                                                         error.message, res.url, error.lineNumber || '?');
739                                         }
740
741                                         _factory.displayName = toCamelCase(name + 'ClassFactory');
742                                         _class = _factory.apply(_factory, [window, document, L].concat(instances));
743
744                                         if (!Class.isSubclass(_class))
745                                             L.error('TypeError', '"%s" factory yields invalid constructor', name);
746
747                                         if (_class.displayName == 'AnonymousClass')
748                                                 _class.displayName = toCamelCase(name + 'Class');
749
750                                         var ptr = Object.getPrototypeOf(L),
751                                             parts = name.split(/\./),
752                                             instance = new _class();
753
754                                         for (var i = 0; ptr && i < parts.length - 1; i++)
755                                                 ptr = ptr[parts[i]];
756
757                                         if (ptr)
758                                                 ptr[parts[i]] = instance;
759
760                                         classes[name] = instance;
761
762                                         return instance;
763                                 });
764                         };
765
766                         /* Request class file */
767                         classes[name] = Request.get(url, { cache: true }).then(compileClass);
768
769                         return classes[name];
770                 },
771
772                 /* DOM setup */
773                 probeRPCBaseURL: function() {
774                         if (rpcBaseURL == null) {
775                                 try {
776                                         rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
777                                 }
778                                 catch (e) { }
779                         }
780
781                         if (rpcBaseURL == null) {
782                                 var rpcFallbackURL = this.url('admin/ubus');
783
784                                 rpcBaseURL = Request.get('/ubus/').then(function(res) {
785                                         return (rpcBaseURL = (res.status == 400) ? '/ubus/' : rpcFallbackURL);
786                                 }, function() {
787                                         return (rpcBaseURL = rpcFallbackURL);
788                                 }).then(function(url) {
789                                         try {
790                                                 window.sessionStorage.setItem('rpcBaseURL', url);
791                                         }
792                                         catch (e) { }
793
794                                         return url;
795                                 });
796                         }
797
798                         return Promise.resolve(rpcBaseURL);
799                 },
800
801                 probeSystemFeatures: function() {
802                         if (sysFeatures == null) {
803                                 try {
804                                         sysFeatures = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
805                                 }
806                                 catch (e) {}
807                         }
808
809                         if (!this.isObject(sysFeatures)) {
810                                 sysFeatures = classes.rpc.declare({
811                                         object: 'luci',
812                                         method: 'getFeatures',
813                                         expect: { '': {} }
814                                 })().then(function(features) {
815                                         try {
816                                                 window.sessionStorage.setItem('sysFeatures', JSON.stringify(features));
817                                         }
818                                         catch (e) {}
819
820                                         sysFeatures = features;
821
822                                         return features;
823                                 });
824                         }
825
826                         return Promise.resolve(sysFeatures);
827                 },
828
829                 hasSystemFeature: function() {
830                         var ft = sysFeatures[arguments[0]];
831
832                         if (arguments.length == 2)
833                                 return this.isObject(ft) ? ft[arguments[1]] : null;
834
835                         return (ft != null && ft != false);
836                 },
837
838                 setupDOM: function(res) {
839                         var domEv = res[0],
840                             uiClass = res[1],
841                             rpcClass = res[2],
842                             formClass = res[3],
843                             rpcBaseURL = res[4];
844
845                         rpcClass.setBaseURL(rpcBaseURL);
846
847                         Request.addInterceptor(function(res) {
848                                 if (res.status != 403 || res.headers.get('X-LuCI-Login-Required') != 'yes')
849                                         return;
850
851                                 Poll.stop();
852
853                                 L.ui.showModal(_('Session expired'), [
854                                         E('div', { class: 'alert-message warning' },
855                                                 _('A new login is required since the authentication session expired.')),
856                                         E('div', { class: 'right' },
857                                                 E('div', {
858                                                         class: 'btn primary',
859                                                         click: function() {
860                                                                 var loc = window.location;
861                                                                 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
862                                                         }
863                                                 }, _('To login…')))
864                                 ]);
865
866                                 throw 'Session expired';
867                         });
868
869                         return this.probeSystemFeatures().finally(this.initDOM);
870                 },
871
872                 initDOM: function() {
873                         originalCBIInit();
874                         Poll.start();
875                         document.dispatchEvent(new CustomEvent('luci-loaded'));
876                 },
877
878                 env: {},
879
880                 /* URL construction helpers */
881                 path: function(prefix, parts) {
882                         var url = [ prefix || '' ];
883
884                         for (var i = 0; i < parts.length; i++)
885                                 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
886                                         url.push('/', parts[i]);
887
888                         if (url.length === 1)
889                                 url.push('/');
890
891                         return url.join('');
892                 },
893
894                 url: function() {
895                         return this.path(this.env.scriptname, arguments);
896                 },
897
898                 resource: function() {
899                         return this.path(this.env.resource, arguments);
900                 },
901
902                 location: function() {
903                         return this.path(this.env.scriptname, this.env.requestpath);
904                 },
905
906
907                 /* Data helpers */
908                 isObject: function(val) {
909                         return (val != null && typeof(val) == 'object');
910                 },
911
912                 sortedKeys: function(obj, key, sortmode) {
913                         if (obj == null || typeof(obj) != 'object')
914                                 return [];
915
916                         return Object.keys(obj).map(function(e) {
917                                 var v = (key != null) ? obj[e][key] : e;
918
919                                 switch (sortmode) {
920                                 case 'addr':
921                                         v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
922                                                 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
923                                         break;
924
925                                 case 'num':
926                                         v = (v != null) ? +v : null;
927                                         break;
928                                 }
929
930                                 return [ e, v ];
931                         }).filter(function(e) {
932                                 return (e[1] != null);
933                         }).sort(function(a, b) {
934                                 return (a[1] > b[1]);
935                         }).map(function(e) {
936                                 return e[0];
937                         });
938                 },
939
940                 toArray: function(val) {
941                         if (val == null)
942                                 return [];
943                         else if (Array.isArray(val))
944                                 return val;
945                         else if (typeof(val) == 'object')
946                                 return [ val ];
947
948                         var s = String(val).trim();
949
950                         if (s == '')
951                                 return [];
952
953                         return s.split(/\s+/);
954                 },
955
956
957                 /* HTTP resource fetching */
958                 get: function(url, args, cb) {
959                         return this.poll(null, url, args, cb, false);
960                 },
961
962                 post: function(url, args, cb) {
963                         return this.poll(null, url, args, cb, true);
964                 },
965
966                 poll: function(interval, url, args, cb, post) {
967                         if (interval !== null && interval <= 0)
968                                 interval = this.env.pollinterval;
969
970                         var data = post ? { token: this.env.token } : null,
971                             method = post ? 'POST' : 'GET';
972
973                         if (!/^(?:\/|\S+:\/\/)/.test(url))
974                                 url = this.url(url);
975
976                         if (args != null)
977                                 data = Object.assign(data || {}, args);
978
979                         if (interval !== null)
980                                 return Request.poll.add(interval, url, { method: method, query: data }, cb);
981                         else
982                                 return Request.request(url, { method: method, query: data })
983                                         .then(function(res) {
984                                                 var json = null;
985                                                 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
986                                                         try { json = res.json() } catch(e) {}
987                                                 cb(res.xhr, json, res.duration);
988                                         });
989                 },
990
991                 stop: function(entry) { return Poll.remove(entry) },
992                 halt: function() { return Poll.stop() },
993                 run: function() { return Poll.start() },
994
995                 /* DOM manipulation */
996                 dom: Class.singleton({
997                         __name__: 'LuCI.DOM',
998
999                         elem: function(e) {
1000                                 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
1001                         },
1002
1003                         parse: function(s) {
1004                                 var elem;
1005
1006                                 try {
1007                                         domParser = domParser || new DOMParser();
1008                                         elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1009                                 }
1010                                 catch(e) {}
1011
1012                                 if (!elem) {
1013                                         try {
1014                                                 dummyElem = dummyElem || document.createElement('div');
1015                                                 dummyElem.innerHTML = s;
1016                                                 elem = dummyElem.firstChild;
1017                                         }
1018                                         catch (e) {}
1019                                 }
1020
1021                                 return elem || null;
1022                         },
1023
1024                         matches: function(node, selector) {
1025                                 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
1026                                 return m ? m.call(node, selector) : false;
1027                         },
1028
1029                         parent: function(node, selector) {
1030                                 if (this.elem(node) && node.closest)
1031                                         return node.closest(selector);
1032
1033                                 while (this.elem(node))
1034                                         if (this.matches(node, selector))
1035                                                 return node;
1036                                         else
1037                                                 node = node.parentNode;
1038
1039                                 return null;
1040                         },
1041
1042                         append: function(node, children) {
1043                                 if (!this.elem(node))
1044                                         return null;
1045
1046                                 if (Array.isArray(children)) {
1047                                         for (var i = 0; i < children.length; i++)
1048                                                 if (this.elem(children[i]))
1049                                                         node.appendChild(children[i]);
1050                                                 else if (children !== null && children !== undefined)
1051                                                         node.appendChild(document.createTextNode('' + children[i]));
1052
1053                                         return node.lastChild;
1054                                 }
1055                                 else if (typeof(children) === 'function') {
1056                                         return this.append(node, children(node));
1057                                 }
1058                                 else if (this.elem(children)) {
1059                                         return node.appendChild(children);
1060                                 }
1061                                 else if (children !== null && children !== undefined) {
1062                                         node.innerHTML = '' + children;
1063                                         return node.lastChild;
1064                                 }
1065
1066                                 return null;
1067                         },
1068
1069                         content: function(node, children) {
1070                                 if (!this.elem(node))
1071                                         return null;
1072
1073                                 var dataNodes = node.querySelectorAll('[data-idref]');
1074
1075                                 for (var i = 0; i < dataNodes.length; i++)
1076                                         delete this.registry[dataNodes[i].getAttribute('data-idref')];
1077
1078                                 while (node.firstChild)
1079                                         node.removeChild(node.firstChild);
1080
1081                                 return this.append(node, children);
1082                         },
1083
1084                         attr: function(node, key, val) {
1085                                 if (!this.elem(node))
1086                                         return null;
1087
1088                                 var attr = null;
1089
1090                                 if (typeof(key) === 'object' && key !== null)
1091                                         attr = key;
1092                                 else if (typeof(key) === 'string')
1093                                         attr = {}, attr[key] = val;
1094
1095                                 for (key in attr) {
1096                                         if (!attr.hasOwnProperty(key) || attr[key] == null)
1097                                                 continue;
1098
1099                                         switch (typeof(attr[key])) {
1100                                         case 'function':
1101                                                 node.addEventListener(key, attr[key]);
1102                                                 break;
1103
1104                                         case 'object':
1105                                                 node.setAttribute(key, JSON.stringify(attr[key]));
1106                                                 break;
1107
1108                                         default:
1109                                                 node.setAttribute(key, attr[key]);
1110                                         }
1111                                 }
1112                         },
1113
1114                         create: function() {
1115                                 var html = arguments[0],
1116                                     attr = arguments[1],
1117                                     data = arguments[2],
1118                                     elem;
1119
1120                                 if (!(attr instanceof Object) || Array.isArray(attr))
1121                                         data = attr, attr = null;
1122
1123                                 if (Array.isArray(html)) {
1124                                         elem = document.createDocumentFragment();
1125                                         for (var i = 0; i < html.length; i++)
1126                                                 elem.appendChild(this.create(html[i]));
1127                                 }
1128                                 else if (this.elem(html)) {
1129                                         elem = html;
1130                                 }
1131                                 else if (html.charCodeAt(0) === 60) {
1132                                         elem = this.parse(html);
1133                                 }
1134                                 else {
1135                                         elem = document.createElement(html);
1136                                 }
1137
1138                                 if (!elem)
1139                                         return null;
1140
1141                                 this.attr(elem, attr);
1142                                 this.append(elem, data);
1143
1144                                 return elem;
1145                         },
1146
1147                         registry: {},
1148
1149                         data: function(node, key, val) {
1150                                 var id = node.getAttribute('data-idref');
1151
1152                                 /* clear all data */
1153                                 if (arguments.length > 1 && key == null) {
1154                                         if (id != null) {
1155                                                 node.removeAttribute('data-idref');
1156                                                 val = this.registry[id]
1157                                                 delete this.registry[id];
1158                                                 return val;
1159                                         }
1160
1161                                         return null;
1162                                 }
1163
1164                                 /* clear a key */
1165                                 else if (arguments.length > 2 && key != null && val == null) {
1166                                         if (id != null) {
1167                                                 val = this.registry[id][key];
1168                                                 delete this.registry[id][key];
1169                                                 return val;
1170                                         }
1171
1172                                         return null;
1173                                 }
1174
1175                                 /* set a key */
1176                                 else if (arguments.length > 2 && key != null && val != null) {
1177                                         if (id == null) {
1178                                                 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1179                                                 while (this.registry.hasOwnProperty(id));
1180
1181                                                 node.setAttribute('data-idref', id);
1182                                                 this.registry[id] = {};
1183                                         }
1184
1185                                         return (this.registry[id][key] = val);
1186                                 }
1187
1188                                 /* get all data */
1189                                 else if (arguments.length == 1) {
1190                                         if (id != null)
1191                                                 return this.registry[id];
1192
1193                                         return null;
1194                                 }
1195
1196                                 /* get a key */
1197                                 else if (arguments.length == 2) {
1198                                         if (id != null)
1199                                                 return this.registry[id][key];
1200                                 }
1201
1202                                 return null;
1203                         },
1204
1205                         bindClassInstance: function(node, inst) {
1206                                 if (!(inst instanceof Class))
1207                                         L.error('TypeError', 'Argument must be a class instance');
1208
1209                                 return this.data(node, '_class', inst);
1210                         },
1211
1212                         findClassInstance: function(node) {
1213                                 var inst = null;
1214
1215                                 do {
1216                                         inst = this.data(node, '_class');
1217                                         node = node.parentNode;
1218                                 }
1219                                 while (!(inst instanceof Class) && node != null);
1220
1221                                 return inst;
1222                         },
1223
1224                         callClassMethod: function(node, method /*, ... */) {
1225                                 var inst = this.findClassInstance(node);
1226
1227                                 if (inst == null || typeof(inst[method]) != 'function')
1228                                         return null;
1229
1230                                 return inst[method].apply(inst, inst.varargs(arguments, 2));
1231                         },
1232
1233                         isEmpty: function(node, ignoreFn) {
1234                                 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1235                                         if (!child.classList.contains('hidden') && (!ignoreFn || !ignoreFn(child)))
1236                                                 return false;
1237
1238                                 return true;
1239                         }
1240                 }),
1241
1242                 Poll: Poll,
1243                 Class: Class,
1244                 Request: Request,
1245
1246                 view: Class.extend({
1247                         __name__: 'LuCI.View',
1248
1249                         __init__: function() {
1250                                 var vp = document.getElementById('view');
1251
1252                                 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1253
1254                                 return Promise.resolve(this.load())
1255                                         .then(L.bind(this.render, this))
1256                                         .then(L.bind(function(nodes) {
1257                                                 var vp = document.getElementById('view');
1258
1259                                                 L.dom.content(vp, nodes);
1260                                                 L.dom.append(vp, this.addFooter());
1261                                         }, this)).catch(L.error);
1262                         },
1263
1264                         load: function() {},
1265                         render: function() {},
1266
1267                         handleSave: function(ev) {
1268                                 var tasks = [];
1269
1270                                 document.getElementById('maincontent')
1271                                         .querySelectorAll('.cbi-map').forEach(function(map) {
1272                                                 tasks.push(L.dom.callClassMethod(map, 'save'));
1273                                         });
1274
1275                                 return Promise.all(tasks);
1276                         },
1277
1278                         handleSaveApply: function(ev) {
1279                                 return this.handleSave(ev).then(function() {
1280                                         L.ui.changes.apply(true);
1281                                 });
1282                         },
1283
1284                         handleReset: function(ev) {
1285                                 var tasks = [];
1286
1287                                 document.getElementById('maincontent')
1288                                         .querySelectorAll('.cbi-map').forEach(function(map) {
1289                                                 tasks.push(L.dom.callClassMethod(map, 'reset'));
1290                                         });
1291
1292                                 return Promise.all(tasks);
1293                         },
1294
1295                         addFooter: function() {
1296                                 var footer = E([]),
1297                                     mc = document.getElementById('maincontent');
1298
1299                                 if (mc.querySelector('.cbi-map')) {
1300                                         footer.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
1301                                                 E('input', {
1302                                                         'class': 'cbi-button cbi-button-apply',
1303                                                         'type': 'button',
1304                                                         'value': _('Save & Apply'),
1305                                                         'click': L.bind(this.handleSaveApply, this)
1306                                                 }), ' ',
1307                                                 E('input', {
1308                                                         'class': 'cbi-button cbi-button-save',
1309                                                         'type': 'submit',
1310                                                         'value': _('Save'),
1311                                                         'click': L.bind(this.handleSave, this)
1312                                                 }), ' ',
1313                                                 E('input', {
1314                                                         'class': 'cbi-button cbi-button-reset',
1315                                                         'type': 'button',
1316                                                         'value': _('Reset'),
1317                                                         'click': L.bind(this.handleReset, this)
1318                                                 })
1319                                         ]));
1320                                 }
1321
1322                                 return footer;
1323                         }
1324                 })
1325         });
1326
1327         var XHR = Class.extend({
1328                 __name__: 'LuCI.XHR',
1329                 __init__: function() {
1330                         if (window.console && console.debug)
1331                                 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
1332                 },
1333
1334                 _response: function(cb, res, json, duration) {
1335                         if (this.active)
1336                                 cb(res, json, duration);
1337                         delete this.active;
1338                 },
1339
1340                 get: function(url, data, callback, timeout) {
1341                         this.active = true;
1342                         L.get(url, data, this._response.bind(this, callback), timeout);
1343                 },
1344
1345                 post: function(url, data, callback, timeout) {
1346                         this.active = true;
1347                         L.post(url, data, this._response.bind(this, callback), timeout);
1348                 },
1349
1350                 cancel: function() { delete this.active },
1351                 busy: function() { return (this.active === true) },
1352                 abort: function() {},
1353                 send_form: function() { L.error('InternalError', 'Not implemented') },
1354         });
1355
1356         XHR.get = function() { return window.L.get.apply(window.L, arguments) };
1357         XHR.post = function() { return window.L.post.apply(window.L, arguments) };
1358         XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
1359         XHR.stop = Request.poll.remove.bind(Request.poll);
1360         XHR.halt = Request.poll.stop.bind(Request.poll);
1361         XHR.run = Request.poll.start.bind(Request.poll);
1362         XHR.running = Request.poll.active.bind(Request.poll);
1363
1364         window.XHR = XHR;
1365         window.LuCI = LuCI;
1366 })(window, document);