jam/build/jamsh/jamsh

9671 lines
2.4 MiB
Plaintext
Raw Normal View History

2024-08-27 00:12:14 +02:00
#!/usr/bin/env jx
var CoreModule={};CoreModule['crypto']='crypto';CoreModule['util']='util';CoreModule['http']='http';CoreModule['fs']='fs';CoreModule['stream']='stream';CoreModule['url']='url';CoreModule['os']='os';CoreModule['net']='net';CoreModule['zlib']='zlib';CoreModule['path']='path';CoreModule['dgram']='dgram';CoreModule['child_process']='child_process';CoreModule['events']='events';CoreModule['string_decoder']='string_decoder';CoreModule['assert']='assert';CoreModule['buffer']='buffer';var BundleModuleCode=[];var BundleObjectCode=[];var BundleModules=[];function _isdir(path){var stats=Fs.statSync(path);return stats&&stats.isDirectory()};function _search(index,file){if(PATH.length==index)return file;var path=PATH[index];if(Fs.existsSync(path+"/"+file+".js"))return path+"/"+file+".js";else if(Fs.existsSync(path+"/"+file)&&!_isdir(path+"/"+fil))return path+"/"+file;else return _search(index+1,file);}
var Fs=require("fs");if(typeof __dirname=='undefined')__dirname='';if(typeof __filename=='undefined')__filename='/home/sbosse/proj/jam/js/top/jamsh.js';if(typeof global=='undefined')global={};PATH=[process.cwd(),".","/home/sbosse/proj/jam/js"];function search(index,file){if(file.indexOf("/")==-1)return file;if(PATH.length==index)return file;var path=PATH[index];if(Fs.existsSync(path+"/"+file+".js"))return path+"/"+file+".js";else if(Fs.existsSync(path+"/"+file))return path+"/"+file;else return search(index+1,file);}
function Require(modupath){var file,filepath;if(BundleModules[modupath])return BundleModules[modupath];var exports={};var module={exports:exports};if(CoreModule[modupath]!=undefined)modupath=CoreModule[modupath];if(modupath=='')return undefined;if(BundleModuleCode[modupath])BundleModuleCode[modupath](module,exports);else if(BundleObjectCode[modupath])BundleObjectCode[modupath](module,exports);else{try{file=search(0,modupath);module=require(file)}
catch(e){var more="";if((e.name==="SyntaxError"||e.name==="TypeError")&&file){var src=Fs.readFileSync(file,"utf8");var Esprima=Require("parser/esprima");try{var ast=Esprima.parse(src,{tolerant:true,loc:true});if(ast.errors&&ast.errors.length>0)more=", "+ast.errors[0];}catch(e){if(e.lineNumber)more=", in line "+e.lineNumber;}}
console.log("Require import of "+file+" failed: "+e+more);throw e;}}
BundleModules[modupath]=module.exports||module;return module.exports||module;};FilesEmbedded=global.FilesEmbedded={};FileEmbedd=global.FileEmbedd=function(path,format){};FileEmbedded=global.FileEmbedded=function(path,format){return FilesEmbedded[path](format);};global.TARGET='node';BundleModuleCode['com/io']=function(module,exports){var util=Require('util');var os=Require('os');var child=Require('child_process');var GetEnv=Require('os/getenv');var Base64=Require('os/base64');var Fs=Require('fs');Require('os/polyfill')
var stderr_fun=function(str){process.stderr.write(str);};var stdout_fun=function(str){process.stdout.write(str);};var tracefile=undefined;var tracing=false;var timestamp=false;global.open=function(name,context,as){var module=Require(name);if(!context)context=global;for(var p in module){context[p]=module[p];};if(as)context[as]=module;}
global.print=console.log;var NL='\n';global.checkOptions=function(options,defaultOptions){return Object.assign({},defaultOptions||{},options)};global.checkOption=function(option,defaultOption){return option==undefined?defaultOption:option};var io={options:{columns:undefined,rows:undefined,log:console.log.bind(console),err:console.err,warn:console.warn,},close:function(fd){Fs.closeSync(fd);},Date:function()
{var now=new Date();var year=""+now.getFullYear();var month="0"+(now.getMonth()+1);month=month.substring(month.length-2);var date="0"+now.getDate();date=date.substring(date.length-2);return year+"-"+month+"-"+date;},debug:function(msg){io.options.err('Debug: '+msg);},exists:function(path){return Fs.existsSync(path);},error:undefined,err:function(msg){io.options.err('Error: '+msg);throw Error(msg);},exit:function(n){process.exit(n);},fail:function(msg){io.options.err('Fatal Error: '+msg);process.exit(0);},file_exists:function(path){return Fs.existsSync(path);},file_search:function(name){if(io.file_exists(name))return name;else if(typeof PATH!=='undefined'){for(var p in PATH){if(io.file_exists(PATH[p]+'/'+name))return(PATH[p]+'/'+name);}
return undefined;}else return undefined;},file_size:function(path){var stat=Fs.statSync(path);if(stat!=undefined)
return stat.size;else
return-1;},file_time:function(path,timekind){var stat=Fs.statSync(path);if(stat!=undefined)
switch(timekind){case'a':return stat.atime.getTime()/1000;case'c':return stat.ctime.getTime()/1000;case'm':return stat.mtime.getTime()/1000;default:return stat.mtime.getTime()/1000;}
else
return-1;},getargs:function(){return process.argv;},getenv:function(name,def){return GetEnv(name,def);},inspect:util.inspect,log:function(condmsg){if(condmsg==true)return;if(!timestamp)console.warn(condmsg);else{var date=new Date();var time=Math.floor(date.getTime());console.warn('['+process.pid+':'+time+']'+condmsg);}},mem:function(){var mem=process.memoryUsage();return{data:(mem.rss/1024)|0,heap:(mem.heapUsed/1024)|0};},open:function(path,mode){return Fs.openSync(path,mode);},out:function(msg){io.options.log(msg)},printstack:function(e,where){if(!e.stack)e=new Error(e);if(!e.stack)e.stack='empty stack';var stack=e.stack.replace(/^\s+at\s+/gm,'').replace(/^Object.<anonymous>\s*\(/gm,'{anonymous}()@').split('\n');if(where==undefined)io.out(e);else io.out(where+': '+e);io.out('Stack Trace');io.out('--------------------------------');for(var i in stack){if(i>0){var line=stack[i];if(line.indexOf('Module.',0)>=0)break;io.out(' at '+line);}}
io.out('--------------------------------');},read:function(fd,len,foff){},read_file:function(path){try{return Fs.readFileSync(path,'utf8');}catch(e){io.error=e;return undefined;}},read_file_bin:function(path){try{return Fs.readFileSync(path);}catch(e){io.error=e;return undefined;}},read_line:function(fd){},read_buf:function(fd,buf,boff,len,foff){return Fs.readSync(fd,buf,boff,len,foff);},sprintstack:function(e){var str='';if(e==_||!e.stack)e=new Error(e);if(!e.stack)e.stack='empty stack';var stack=e.stack.replace(/^\s+at\s+/gm,'').replace(/^Object.<anonymous>\s*\(/gm,'{anonymous}()@').replace(/^Object.eval\s*\(/gm,'').split('\n');for(var i in stack){if(i>0){var line=stack[i];if(line.indexOf('Module.',0)>=0)break;if(str!='')str+='\n';str+=' at '+line;}}
return str;},stacktrace:function(){var e=new Error('dummy');if(!e.stack)e.stack='empty stack';var stack=e.stack.replace(/^[^\(]+?[\n$]/gm,'').replace(/^\s+at\s+/gm,'').replace(/^Object.<anonymous>\s*\(/gm,'{anonymous}()@').split('\n');io.out('Stack Trace');io.out('--------------------------------');for(var i in stack){if(i>0){var line=stack[i];if(line.indexOf('Module.',0)>=0)break;io.out(' at '+line);}}
io.out('--------------------------------');},set_stderr:function(fun){stderr_fun=fun;},set_stdout:function(fun){stdout_fun=fun;},stderr:function(msg){stderr_fun(msg);},sleep:function(delay){var start=new Date().getTime();while(new Date().getTime()<start+delay);},stdout:function(msg){stdout_fun(msg);},sync:function(fd){Fs.fsyncSync(fd);},date:function(){var date=Date();return date.split(' ').slice(1,5).join(' ');},time:function(){var date=new Date();return Math.floor(date.getTime());},Time:function()
{var now=new Date();var hour="0"+now.getHours();hour=hour.substring(hour.length-2);var minute="0"+now.getMinutes();minute=minute.substring(minute.length-2);var second="0"+now.getSeconds();second=second.substring(second.length-2);var milli="0"+Math.floor(now.getMilliseconds()/10);milli=milli.substring(milli.length-2);return hour+":"+minute+":"+second+':'+milli;},trace:function(condmsg){if(condmsg!=true&&tracefile!=undefined){var date=new Date();var time=Math.floor(date.getTime());Fs.writeSync(tracefile,'['+time+'] '+condmsg+'\n');}},tracing:tracing,trace_open:function(path){tracefile=Fs.openSync(path,'w+');if(tracefile!=undefined)io.tracing=false;},warn:function(msg){if(!timestamp)io.options.warn('Warning: '+msg);else{var date=new Date();var time=Math.floor(date.getTime());console.warn('['+process.pid+':'+time+'] Warning: '+msg);}},workdir:function(){return io.getenv('PWD',io.getenv('CWD',''));},write:function(fd,data,foff){return Fs.writeSync(fd,data,foff);},write_buf:function(fd,buf,bpos,blen,foff){return Fs.writeSync(fd,buf,bpos,blen,foff);},write_file:function(path,str){try{Fs.writeFileSync(path,str,'utf8');return str.length;}catch(e){return-1;}},write_file_bin:function(path,buf){try{Fs.writeFileSync(path,buf,'binary');return buf.length;}catch(e){io.error=e;return-1;}},write_line:function(fd,str){return Fs.writeSync(fd,str+NL);},fork:child.fork,exec:child.exec,execSync:child.execSync,spawn:child.spawn,hostname:os.hostname};module.exports=io;};BundleModuleCode['os/getenv']=function(module,exports){var util=require("util");var fallbacksDisabled=false;function _value(varName,fallback){var value=process.env[varName];if(value===undefined){if(fallback===undefined){throw new Error('GetEnv.Nonexistent: '+varName+' does not exist '+'and no fallback value provided.');}
if(fallbacksDisabled){throw new Error('GetEnv.DisabledFallbacks: '+varName+' relying on fallback '+'when fallbacks have been disabled');}
return''+fallback;}
return value;}
var convert={string:function(value){return''+value;},int:function(value){var isInt=value.match(/^-?\d+$/);if(!isInt){throw new Error('GetEnv.NoInteger: '+value+' is not an integer.');}
return+value;},float:function(value){var isInfinity=(+value===Infinity||+value===-Infinity);if(isInfinity){throw new Error('GetEnv.Infinity: '+value+' is set to +/-Infinity.');}
var isFloat=!(isNaN(value)||value==='');if(!isFloat){throw new Error('GetEnv.NoFloat: '+value+' is not a number.');}
return+value;},bool:function(value){var isBool=(value==='true'||value==='false');if(!isBool){throw new Error('GetEnv.NoBoolean: '+value+' is not a boolean.');}
return(value==='true');}};function converter(type){return function(varName,fallback){if(typeof varName=='string'){var value=_value(varName,fallback);return convert[type](value);}else{return getenv.multi(varName);}};};var getenv=converter('string');Object.keys(convert).forEach(function(type){getenv[type]=converter(type);});getenv.array=function array(varName,type,fallback){type=type||'string';if(Object.keys(convert).indexOf(type)===-1){throw new Error('GetEnv.ArrayUndefinedType: Unknown array type '+type);}
var value=_value(varName,fallback);return value.split(/\s*,\s*/).map(convert[type]);};getenv.multi=function multi(spec){var key,value;var result={};for(var key in spec){var value=spec[key];if(util.isArray(value)){switch(value.length){case 1:case 2:result[key]=getenv(value[0],value[1]);break;case 3:result[key]=getenv[value[2]](value[0],value[1]);break;default:throw('getenv.multi(): invalid spec');break;}}else{result[key]=getenv(value);}}
return result;};getenv.disableFallbacks=function(){fallbacksDisabled=true;};getenv.enableFallbacks=function(){fallbacksDisabled=false;};module.exports=getenv;};BundleModuleCode['os/base64']=function(module,exports){var keyStr="ABCDEFGHIJKLMNOP"+"QRSTUVWXYZabcdef"+"ghijklmnopqrstuv"+"wxyz0123456789+/"+"=";var Base64={encode:function(input){input=escape(input);var output="";var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;do{chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
keyStr.charAt(enc1)+
keyStr.charAt(enc2)+
keyStr.charAt(enc3)+
keyStr.charAt(enc4);chr1=chr2=chr3="";enc1=enc2=enc3=enc4="";}while(i<input.length);return output;},encodeBuf:function(input){var output="";var NaN=output.charCodeAt(2);var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;var len=input.length;do{chr1=input.readUInt8(i++);chr2=(i<len)?input.readUInt8(i++):NaN;chr3=(i<len)?input.readUInt8(i++):NaN;enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
keyStr.charAt(enc1)+
keyStr.charAt(enc2)+
keyStr.charAt(enc3)+
keyStr.charAt(enc4);chr1=chr2=chr3="";enc1=enc2=enc3=enc4="";}while(i<len);return output;},decode:function(input){var output="";var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}
chr1=chr2=chr3="";enc1=enc2=enc3=enc4="";}while(i<input.length);return unescape(output);},decodeBuf:function(input){var len=input.length;var buf=new Buffer(len);var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;var buflen=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");buf.fill(0);do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;buf.writeUInt8(chr1,buflen);buflen++;if(enc3!=64){buf.writeUInt8(chr2,buflen);buflen++;}
if(enc4!=64){buf.writeUInt8(chr3,buflen);buflen++;}
chr1=chr2=chr3="";enc1=enc2=enc3=enc4="";}while(i<input.length);return buf.slice(0,buflen);}};module.exports=Base64;};BundleModuleCode['os/polyfill']=function(module,exports){Object.addProperty=function(obj,name,fun){if(obj.prototype[name])return;obj.prototype[name]=fun;Object.defineProperty(obj.prototype,name,{enumerable:false});};Object.updateProperty=function(obj,name,fun){obj.prototype[name]=fun;Object.defineProperty(obj.prototype,name,{enumerable:false});};if(typeof Object.assign!='function'){Object.defineProperty(Object,"assign",{value:function assign(target,varArgs){'use strict';if(target==null){throw new TypeError('Cannot convert undefined or null to object');}
var to=Object(target);for(var index=1;index<arguments.length;index++){var nextSource=arguments[index];if(nextSource!=null){for(var nextKey in nextSource){if(Object.prototype.hasOwnProperty.call(nextSource,nextKey)){to[nextKey]=nextSource[nextKey];}}}}
return to;},writable:true,configurable:true});}
if(!Array.prototype.find){Object.addProperty(Array,'find',function(predicate){if(this==null){throw new TypeError('"this" is null or not defined');}
var o=Object(this);var len=o.length>>>0;if(typeof predicate!=='function'){throw new TypeError('predicate must be a function');}
var thisArg=arguments[1];var k=0;while(k<len){var kValue=o[k];if(predicate.call(thisArg,kValue,k,o)){return kValue;}
k++;}
return undefined;});}
if(!String.prototype.contains){Object.addProperty(String,'contains',function(el){return this.indexOf(el)!=-1})}
checkOptions=function(options,defaultOptions){return Object.assign({},defaultOptions||{},options)};checkOption=function(option,defaultOption){return option==undefined?defaultOption:option};};BundleModuleCode['com/path']=function(module,exports){var Fs=Require('fs');var _process=process||{};(function(){"use strict";var isWindows=_process.platform==='win32';var util=Require('util');if(!util.deprecate)util.deprecate=function(f,w){return f;};function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==='.'){parts.splice(i,1);}else if(last==='..'){parts.splice(i,1);up++;}else if(up){parts.splice(i,1);up--;}}
if(allowAboveRoot){for(;up--;up){parts.unshift('..');}}
return parts;}
if(isWindows){var splitDeviceRe=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var splitTailRe=/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;var splitPath=function(filename){var result=splitDeviceRe.exec(filename),device=(result[1]||'')+(result[2]||''),tail=result[3]||'';var result2=splitTailRe.exec(tail),dir=result2[1],basename=result2[2],ext=result2[3];return[device,dir,basename,ext];};var normalizeUNCRoot=function(device){return'\\\\'+device.replace(/^[\\\/]+/,'').replace(/[\\\/]+/g,'\\');};exports.resolve=function(){var resolvedDevice='',resolvedTail='',resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1;i--){var path;if(i>=0){path=arguments[i];}else if(!resolvedDevice){path=_process.cwd();}else{path=_process.env['='+resolvedDevice];if(!path||path.substr(0,3).toLowerCase()!==resolvedDevice.toLowerCase()+'\\'){path=resolvedDevice+'\\';}}
if(!util.isString(path)){throw new TypeError('Arguments to path.resolve must be strings');}else if(!path){continue;}
var result=splitDeviceRe.exec(path),device=result[1]||'',isUnc=device&&device.charAt(1)!==':',isAbsolute=exports.isAbsolute(path),tail=result[3];if(device&&resolvedDevice&&device.toLowerCase()!==resolvedDevice.toLowerCase()){continue;}
if(!resolvedDevice){resolvedDevice=device;}
if(!resolvedAbsolute){resolvedTail=tail+'\\'+resolvedTail;resolvedAbsolute=isAbsolute;}
if(resolvedDevice&&resolvedAbsolute){break;}}
if(isUnc){resolvedDevice=normalizeUNCRoot(resolvedDevice);}
function f(p){return!!p;}
resolvedTail=normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f),!resolvedAbsolute).join('\\');return(resolvedDevice+(resolvedAbsolute?'\\':'')+resolvedTail)||'.';};exports.normalize=function(path){var result=splitDeviceRe.exec(path),device=result[1]||'',isUnc=device&&device.charAt(1)!==':',isAbsolute=exports.isAbsolute(path),tail=result[3],trailingSlash=/[\\\/]$/.test(tail);if(device&&device.charAt(1)===':'){device=device[0].toLowerCase()+device.substr(1);}
tail=normalizeArray(tail.split(/[\\\/]+/).filter(function(p){return!!p;}),!isAbsolute).join('\\');if(!tail&&!isAbsolute){tail='.';}
if(tail&&trailingSlash){tail+='\\';}
if(isUnc){device=normalizeUNCRoot(device);}
return device+(isAbsolute?'\\':'')+tail;};exports.isAbsolute=function(path){var result=splitDeviceRe.exec(path),device=result[1]||'',isUnc=!!device&&device.charAt(1)!==':';return!!result[2]||isUnc;};exports.join=function(){function f(p){if(!util.isString(p)){throw new TypeError('Arguments to path.join must be strings');}
return p;}
var paths=Array.prototype.filter.call(arguments,f);var joined=paths.join('\\');if(!/^[\\\/]{2}[^\\\/]/.test(paths[0])){joined=joined.replace(/^[\\\/]{2,}/,'\\');}
return exports.normalize(joined);};exports.relative=function(from,to){from=exports.resolve(from);to=exports.resolve(to);var lowerFrom=from.toLowerCase();var lowerTo=to.toLowerCase();function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=='')break;}
var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=='')break;}
if(start>end)return[];return arr.slice(start,end+1);}
var toParts=trim(to.split('\\'));var lowerFromParts=trim(lowerFrom.split('\\'));var lowerToParts=trim(lowerTo.split('\\'));var length=Math.min(lowerFromParts.length,lowerToParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(lowerFromParts[i]!==lowerToParts[i]){samePartsLength=i;break;}}
if(samePartsLength==0){return to;}
var outputParts=[];for(var i=samePartsLength;i<lowerFromParts.length;i++){outputParts.push('..');}
outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join('\\');};exports.sep='\\';exports.delimiter=';';}else{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1);};exports.resolve=function(){var resolvedPath='',resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=(i>=0)?arguments[i]:_process.cwd();if(!util.isString(path)){throw new TypeError('Arguments to path.resolve must be strings');}else if(!path){continue;}
resolvedPath=path+'/'+resolvedPath;resolvedAbsolute=path.charAt(0)==='/';}
resolvedPath=normalizeArray(resolvedPath.split('/').filter(function(p){return!!p;}),!resolvedAbsolute).join('/');return((resolvedAbsolute?'/':'')+resolvedPath)||'.';};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=path[path.length-1]==='/',segments=path.split('/'),nonEmptySegments=[];for(var i=0;i<segments.length;i++){if(segments[i]){nonEmptySegments.push(segments[i]);}}
path=normalizeArray(nonEmptySegments,!isAbsolute).join('/');if(!path&&!isAbsolute){path='.';}
if(path&&trailingSlash){path+='/';}
return(isAbsolute?'/':'')+path;};exports.isAbsolute=function(path){return path.charAt(0)==='/';};exports.join=function(){var path='';for(var i=0;i<arguments.length;i++){var segment=arguments[i];if(!util.isString(segment)){throw new TypeError('Arguments to path.join must be strings');}
if(segment){if(!path){path+=segment;}else{path+='/'+segment;}}}
return exports.normalize(path);};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=='')break;}
var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=='')break;}
if(start>end)return[];return arr.slice(start,end+1);}
var fromParts=trim(from.split('/'));var toParts=trim(to.split('/'));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break;}}
var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push('..');}
outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join('/');};exports.sep='/';exports.delimiter=':';}
exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return'.';}
if(dir){dir=dir.substr(0,dir.length-1);}
return root+dir;};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length);}
return f;};exports.extname=function(path){return splitPath(path)[3];};exports.exists=util.deprecate(function(path,callback){if(Fs)Fs.exists(path,callback);else callback(false);},'path.exists is now called `fs.exists`.');exports.existsSync=util.deprecate(function(path){if(Fs)return Fs.existsSync(path);else return false;},'path.existsSync is now called `fs.existsSync`.');if(isWindows){exports._makeLong=function(path){if(!util.isString(path))
return path;if(!path){return'';}
var resolvedPath=exports.resolve(path);if(/^[a-zA-Z]\:\\/.test(resolvedPath)){return'\\\\?\\'+resolvedPath;}else if(/^\\\\[^?.]/.test(resolvedPath)){return'\\\\?\\UNC\\'+resolvedPath.substring(2);}
return path;};}else{exports._makeLong=function(path){return path;};}}());};BundleModuleCode['com/sprintf']=function(module,exports){(function(window){var re={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/}
function sprintf(){var key=arguments[0],cache=sprintf.cache
if(!(cache[key]&&cache.hasOwnProperty(key))){cache[key]=sprintf.parse(key)}
return sprintf.format.call(null,cache[key],arguments)}
sprintf.format=function(parse_tree,argv){var cursor=1,tree_length=parse_tree.length,node_type="",arg,output=[],i,k,match,pad,pad_character,pad_length,is_positive=true,sign=""
for(i=0;i<tree_length;i++){node_type=get_type(parse_tree[i])
if(node_type==="string"){output[output.length]=parse_tree[i]}
else if(node_type==="array"){match=parse_tree[i]
if(match[2]){arg=argv[cursor]
for(k=0;k<match[2].length;k++){if(!arg.hasOwnProperty(match[2][k])){throw new Error(sprintf("[sprintf] property '%s' does not exist",match[2][k]))}
arg=arg[match[2][k]]}}
else if(match[1]){arg=argv[match[1]]}
else{arg=argv[cursor++]}
if(get_type(arg)=="function"){arg=arg()}
if(re.not_string.test(match[8])&&re.not_json.test(match[8])&&(get_type(arg)!="number"&&isNaN(arg))){throw new TypeError(sprintf("[sprintf] expecting number but found %s",get_type(arg)))}
if(re.number.test(match[8])){is_positive=arg>=0}
switch(match[8]){case"b":arg=arg.toString(2)
break
case"c":arg=String.fromCharCode(arg)
break
case"d":case"i":arg=parseInt(arg,10)
break
case"j":arg=JSON.stringify(arg,null,match[6]?parseInt(match[6]):0)
break
case"e":arg=match[7]?arg.toExponential(match[7]):arg.toExponential()
break
case"f":arg=match[7]?parseFloat(arg).toFixed(match[7]):parseFloat(arg)
break
case"g":arg=match[7]?parseFloat(arg).toPrecision(match[7]):parseFloat(arg)
break
case"o":arg=arg.toString(8)
break
case"s":arg=((arg=String(arg))&&match[7]?arg.substring(0,match[7]):arg)
break
case"u":arg=arg>>>0
break
case"x":arg=arg.toString(16)
break
case"X":arg=arg.toString(16).toUpperCase()
break}
if(re.json.test(match[8])){output[output.length]=arg}
else{if(re.number.test(match[8])&&(!is_positive||match[3])){sign=is_positive?"+":"-"
arg=arg.toString().replace(re.sign,"")}
else{sign=""}
pad_character=match[4]?match[4]==="0"?"0":match[4].charAt(1):" "
pad_length=match[6]-(sign+arg).length
pad=match[6]?(pad_length>0?str_repeat(pad_character,pad_length):""):""
output[output.length]=match[5]?sign+arg+pad:(pad_character==="0"?sign+pad+arg:pad+sign+arg)}}}
return output.join("")}
sprintf.cache={}
sprintf.parse=function(fmt){var _fmt=fmt,match=[],parse_tree=[],arg_names=0
while(_fmt){if((match=re.text.exec(_fmt))!==null){parse_tree[parse_tree.length]=match[0]}
else if((match=re.modulo.exec(_fmt))!==null){parse_tree[parse_tree.length]="%"}
else if((match=re.placeholder.exec(_fmt))!==null){if(match[2]){arg_names|=1
var field_list=[],replacement_field=match[2],field_match=[]
if((field_match=re.key.exec(replacement_field))!==null){field_list[field_list.length]=field_match[1]
while((replacement_field=replacement_field.substring(field_match[0].length))!==""){if((field_match=re.key_access.exec(replacement_field))!==null){field_list[field_list.length]=field_match[1]}
else if((field_match=re.index_access.exec(replacement_field))!==null){field_list[field_list.length]=field_match[1]}
else{throw new SyntaxError("[sprintf] failed to parse named argument key")}}}
else{throw new SyntaxError("[sprintf] failed to parse named argument key")}
match[2]=field_list}
else{arg_names|=2}
if(arg_names===3){throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported")}
parse_tree[parse_tree.length]=match}
else{throw new SyntaxError("[sprintf] unexpected placeholder")}
try{_fmt=_fmt.substring(match[0].length)}catch(e){throw new SyntaxError("[sprintf] unexpected fromat")}}
return parse_tree}
var vsprintf=function(fmt,argv,_argv){_argv=(argv||[]).slice(0)
_argv.splice(0,0,fmt)
return sprintf.apply(null,_argv)}
function get_type(variable){return Object.prototype.toString.call(variable).slice(8,-1).toLowerCase()}
function str_repeat(input,multiplier){return Array(multiplier+1).join(input)}
if(typeof exports!=="undefined"){exports.sprintf=sprintf
exports.vsprintf=vsprintf}
else{window.sprintf=sprintf
window.vsprintf=vsprintf
if(typeof define==="function"&&define.amd){define(function(){return{sprintf:sprintf,vsprintf:vsprintf}})}}})(typeof window==="undefined"?this:window);};BundleModuleCode['/home/sbosse/proj/jam/js/top/jamsh.js']=function(module,exports){process.noDeprecation=true
var Comp=Require('com/compat');var Io=Require('com/io');var doc=Require('doc/doc');var table=Require('doc/table');var readline=Require('com/readline');var readlineSync=Require('term/readlineSync');var renderer=doc.Renderer({lazy:true});var http=Require('http');var httpserv=Require('http/https');try{var https=require('https');}catch(e){};if(!https.request)https=undefined;var geoip=Require('geoip/geoip');var util=Require('util')
var sip=Require('top/rendezvous');var db=Require('db/db');var JamShell=Require('shell/shell');var nlp=Require('nlp/nlp');var ml=Require('ml/ml')
var nn=Require('nn/nn')
var csp=Require('csp/csp')
var sat=Require('logic/sat')
var logic=Require('logic/prolog')
var csv=Require('parser/papaparse');var ampCOM=Require('jam/ampCOM');var numerics=Require('numerics/numerics')
var osutils=Require('os/osutils');var UI=Require('ui/app/app');var Des48=Require('dos/des48');var p;var options={args:[],echo:true,modules:{csp:csp,csv:csv,db:db,des48:Des48,doc:doc,geoip:geoip,http:http,httpserv:httpserv,https:https,logic:logic,ml:ml,nlp:nlp,nn:nn,numerics:numerics,os:osutils,readline:readline,readlineSync:readlineSync,sat:sat,sip:sip,table:table,UI:UI,},extensions:{url2addr:ampCOM.url2addr,sleep:process.watchdog&&process.watchdog.sleep?function(milli){process.watchdog.sleep(milli)}:undefined},nameopts:{length:8,memorable:true,lowercase:true},Nameopts:{length:8,memorable:true,uppercase:true},output:null,renderer:renderer,server:false,verbose:0,}
process.on('uncaughtException',function(err){console.error(err.stack);console.log("jamsh not exiting...");});if((p=process.argv.indexOf('--'))>0){options.args=process.argv.slice(p+1,process.argv.length);process.argv=process.argv.slice(0,p);}
if(process.argv[1].match(/jamsh$/)||process.argv[1].match(/jamsh\.debug$/)){var ind;if(process.argv.indexOf('-h')>0)return print('usage: jamsh [-v -s] [script] [-e "shell commands"]');if((ind=process.argv.indexOf('-e'))>0){options.server=true;options.output=console.log;options.exec=process.argv[ind+1];}else if(process.argv.length>2){var script=process.argv.filter(function(arg,ind){return ind>1&&arg.indexOf(':')==-1&&arg.indexOf('-')!=0;});if(script.length==1){options.script=script[0];options.output=console.log;options.server=true;}}
process.argv.forEach(function(arg){switch(arg){case'-v':options.verbose++;break;case'-s':options.server=false;break;}})
if(!options.server&&options.verbose==0)options.verbose=1;JamShell(options).init();}};BundleModuleCode['com/compat']=function(module,exports){var Io=Require('com/io');var Path=Require('com/path');var Sprintf=Require('com/sprintf');global.any=undefined;global._=undefined;global.none=null;global.empty=null;global.NL='\n';global.int=function(v){return v|0};global.div=function(a,b){return a/b|0};if(!Object.prototype.forEach){Object.defineProperties(Object.prototype,{'forEach':{value:function(callback){if(this==null){throw new TypeError('Not an object');}
var obj=this;for(var key in obj){if(obj.hasOwnProperty(key)){callback.call(obj,obj[key],key,obj);}}},writable:true}});}
function inherit(child,parent){for(var p in parent.prototype){if(p=='__proto__')continue;child.prototype[p]=parent.prototype[p];}}
function inheritPrototype(child,parent){var __proto__=child.__proto__;child.prototype.__proto__=parent.prototype;if(!__proto__)for(var p in parent.prototype){if(p=='__proto__')continue;child.prototype[p]=parent.prototype[p];}}
function instanceOf(obj,cla){var p=obj.__proto__;if(obj instanceof cla)return true;while(p){if(p===cla.prototype)return true;p=p.__proto__}
return false;}
function defineGetter(cla,prop,fun){Object.defineProperty(cla.prototype,prop,{configurable:true,get:fun});}
function defineSetter(cla,prop,fun){Object.defineProperty(cla.prototype,prop,{configurable:true,set:fun});}
Object.addProperty=function(obj,name,fun){if(obj.prototype[name])return;obj.prototype[name]=fun;Object.defineProperty(obj.prototype,name,{enumerable:false});};Object.updateProperty=function(obj,name,fun){obj.prototype[name]=fun;Object.defineProperty(obj.prototype,name,{enumerable:false});};Object.addProperty(Array,'contains',function(el){return this.indexOf(el)!=-1});Object.addProperty(Array,'last',function(){return this[this.length-1]});global.inherit=inherit;global.inheritPrototype=inheritPrototype;global.instanceOf=instanceOf;global.defineGetter=defineGetter;global.defineSetter=defineSetter;var assert=function(condmsg){if(condmsg!=true){Io.out('** Assertion failed: '+condmsg+' **');Io.stacktrace();throw Error(condmsg);}};global.assert=assert;function forof(obj,f){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=obj[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){element=_step.value;f(element);}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}}
global.forof=forof;var obj={compact:function(o){var a;if(obj.isArray(o)){if(o.length==1&&obj.isObject(o[0]))return obj.compact(o[0]);else return o;}else if(obj.isObject(o))for(a in o){var elem=o[a];o[a]=obj.compact(elem);}
return o;},copy:function(o){if(o===null||typeof o!=='object'){return o;}
var temp=(o instanceof Array)?[]:{};for(var key in o){temp[key]=obj.copy(o[key]);}
return temp;},equal:function(o1,o2){if(!o1||!o2)return false;for(var i in o1)if(o1[i]!=o2[i])return false;for(var i in o2)if(o1[i]!=o2[i])return false;return true;},extend:function(o1,o2){for(var i in o2)o1[i]=o2[i];return o1;},find:function(obj,fun){var p;for(p in obj){if(fun(obj[p],p))return obj[p];}},hasProperty:function(o,p){return o[p]!=undefined||(p in o);},head:function(o){for(var p in o)return p;return undefined;},inherit:function(dst,src){for(var i in src){if(typeof dst[i]=='object'&&typeof src[i]=='object')
inherit(dst[i],src[i]);else if(typeof dst[i]=='undefined')
dst[i]=src[i];}
return dst;},isArray:function(o){if(o==_||o==null)return false;else return typeof o=="array"||(typeof o=="object"&&o.constructor===Array);},isMatrix:function(o){if(o==_||o==null)return false;else return obj.isArray(o)&&obj.isArray(o[0]);},isEmpty:function(o){for(var prop in o){if(o[prop]!=undefined)return false;}
return true;},isError:function(o){return o instanceof Error},isFunction:function(o){return typeof o=="function";},isObj:function(o){return typeof o=="object";},isObject:function(o){return typeof o=="object";},isRegex:function(o){return o instanceof RegExp;},isString:function(o){return typeof o=="string"||(typeof o=="object"&&o.constructor===String);},isNumber:function(o){return typeof o=="number"||(typeof o=="object"&&o.constructor===Number);},iter:function(obj,fun){var p;for(p in obj){fun(obj[p],p)}}};var array={and:function(array,fun){var res=true;var i=0;var len=array.length;for(i=0;i<len;i++){var element=array[i];res=res&&fun(element,i)}
return res;},append:function(array,element){array.push(element);return array;},call:function(array,args){var i=0;var len=array.length;for(i=0;i<len;i++){var element=array[i];element()}},check:function(array,fun){var i,exist;exist=false;loop:for(i in array){var element=array[i];if(fun(element,i)){exist=true;break loop;}}
return exist;},concat:function(array,array2){for(var i in array2){array.push(array2[i]);}
return array;},conjunction:function(set1,set2,fun){return array.union(set1,set2,fun);},contains:function(array,elements,fun){var i=array.length;if(!fun)fun=function(o1,o2){return o1===o2};if(obj.isArray(elements)){while(i--){var j=elements.length;while(j--){if(fun(array[i],elements[j])){return true;}}}}
else while(i--){if(fun(array[i],elements)){return true;}}
return false;},copy:function(src,dst){var i;if(dst){for(i in src)dst[i]=src[i];}else return src.slice();},create:function(length,init){var arr=[],i=length;while(i--){arr[i]=init;}
return arr;},create_matrix:function(rows,cols,init){var m=[];var r=[];var i,j;for(i=0;i<rows;i++){r=[];for(j=0;j<cols;j++)r.push(init);m.push(r);}
return m;},disjunction:function(set1,set2,fun){return array.merge(set1,set2);},empty:function(array){return(array==undefined||array.length==0)},equal:function(a1,a2){if(a1.length!=a2.length)return false;for(var i in a1)if(a1[i]!=a2[i])return false;return true;},exclusive:function(set1,set2,fun){var i,j,found,res=[];for(i in set1){found=false;loop1:for(j in set2){if(fun!=undefined&&fun(set1[i],set2[j])){found=true;break loop1;}
else if(fun==undefined&&set1[i]==set2[j]){found=true;break loop1;};}
if(!found)res.push(set1[i]);}
for(i in set2){found=false;loop2:for(j in set1){if(fun!=undefined&&fun(set2[i],set1[j])){found=true;break loop2;}
else if(fun==undefined&&set2[i]==set1[j]){found=true;break loop2;};}
if(!found)res.push(set2[i]);}
return res;},find:function(array,fun){var i;for(i in array){if(fun(array[i],i))return array[i];}
return none;},findmap:function(array,fun){var i,found;for(i in array){found=fun(array[i],i);if(found)return found;}
return none;},filter:function(array,fun){if(array.filter)return array.filter(fun);else{var res=[],len=array.length,element,i;for(i=0;i<len;i++){element=array[i];if(fun(element,i))res.push(element);}
return res;}},filtermap:function(array,fun){var res=[],len=array.length,element,mapped,i;for(i=0;i<len;i++){element=array[i];mapped=fun(element,i);if(mapped!=undefined)res.push(mapped);}
return res;},flatten:function(array){var res=[];var len=array.length;var i;for(i=0;i<len;i++){var element=array[i];if(!obj.isArray(element))res.push(element);else{var j;var len2=element.length;for(j=0;j<len2;j++){var element2=element[j];res.push(element2);}}}
return res;},head:function(array){return array[0];},init:function(length,fun){var arr=[],i=length;while(i--){arr[i]=fun(i);}
return arr;},iter:function(array,fun){array.forEach(fun);},iter2:function(array1,array2,fun){var i=0;assert((array1.length==array2.length)||('Array.iter2: arrays of different lengths'));array1.forEach(function(e1,i){fun(e1,array2[i],i)});},iter_break:function(array,fun){var i=0;var len=array.length;for(i=0;i<len;i++){var element=array[i];if(fun(element,i))return;}},iter_rev:function(array,fun){var i;var len=array.length;for(i=len-1;i>=0;i--){fun(array[i],i)}},last:function(array){var len=array.length;if(len==0)return none;else return array[len-1];},length:function(array){return array.length;},map2:function(array1,array2,fun){var i=0;assert((array1.length==array2.length)||('Array.map2: arrays of different lengths'));var len=array1.length;var res=[];for(i=0;i<len;i++){res.push(fun(array1[i],array2[i],i));}
return res;},map:function(array,fun){var i=0;var len=array.length;var res=[];for(i=0;i<len;i++){var element=array[i];res.push(fun(element,i));}
return res;},match:function(array,fun_hdtl,fun_empty){if(array.length==0){if(fun_empty)fun_empty();}else if(array.length>1){var hd=this.head(array);var tl=this.tail(array);fun_hdtl(hd,tl);}else fun_hdtl(this.head(array),[]);},match2:function(array,fun_hd1hd2,fun_hdtl,fun_empty){if(array.length==0&&fun_empty)
fun_empty();else if(array.length==2){var hd1=this.head(array);var hd2=this.second(array);fun_hd1hd2(hd1,hd2);}
else if(array.length>1&&fun_hdtl){var hd=this.head(array);var tl=this.tail(array);fun_hdtl(hd,tl);}else if(fun_hdtl)fun_hdtl(this.head(array),[]);},max:function(array,fun){var res,max,num;for(var i in array){if(fun)num=fun(array[i]);else num=array[i];if(max==undefined){max=num;res=array[i]}
else if(num>max){max=num;res=array[i]}}
return res;},min:function(array,fun){var res,min,num;for(var i in array){if(fun)num=fun(array[i]);else num=array[i];if(min==undefined){min=num;res=array[i]}
else if(num<min){min=num;res=array[i]}}
return res;},member:function(array,element){var i,exist;var len=array.length;exist=false;loop:for(i=0;i<len;i++){var _element=array[i];if(_element==element){exist=true;break loop;}}
return exist;},merge:function(array1,array2,array3,array4){var arraynew=array1.slice();arraynew=arraynew.concat(array2);if(array3!=undefined)arraynew=arraynew.concat(array3);if(array4!=undefined)arraynew=arraynew.concat(array4);return arraynew;},next:function(array,val){var i;var len=array.length;if(obj.isString(val))
for(i=0;i<len;i++){if(string.equal(array[i],val)){if(i==len-1)return array[0];else return array[i+1];}}
else
for(i=0;i<len;i++){if(array[i]==val){if(i==len-1)return array[0];else return array[i+1];}}
return none;},or:function(array,fun){var res=false;var i=0;var len=array.length;for(i=0;i<len;i++){var element=array[i];res=res||fun(element,i)}
return res;},pluck:function(collection,key){return collection.map(function(object){return object==null?undefined:object[key];});},pop:function(array){var element=array[0];array.shift();return element;},print:function(array){var i;var len=array.length;var str='[';for(i=0;i<len;i++){var cell=array[i];str=str+cell;}
return str+']';},push:function(array,element){array.unshift(element);},range:function(a,b){var i;var array=[];for(i=a;i<=b;i++)array.push(i);return array;},remove:function(array,begin,end){var i,a;if(end==undefined)end=begin+1;if(begin<0||end>=array.length)return[];a=array.slice(0,begin);for(i=end;i<array.length;i++)a.push(array[i]);return a;},second:function(array){return array[1];},sort:function(array,fun){var array2=array.slice();array2.sort(fun);return array2;},split:function(array,pos,len){if(pos==0)return array.slice((len||1));else{var a1=array.slice(0,pos);var a2=array.slice(pos+(len||1));return a1.concat(a2);}},sum:function(array,fun){var res=0;for(var i in array){var num=0;if(fun)num=fun(array[i]);else num=array[i];if(!obj.isNumber(num))return undefined;res+=num;}
return res;},tail:function(array,top){var array2=array.slice();array2.shift();if(top)for(;top>1;top--)array2.shift();return array2;},union:function(set1,set2,fun){var i,j,res=[];for(i in set1){for(j in set2){if(fun!=undefined&&fun(set1[i],set2[j]))res.push(set1[i]);else if(fun==undefined&&set1[i]==set2[j])res.push(set1[i]);}}
return res;},unique:function(array){var length=array?array.length:0;function baseUniq(array){var index=-1,length=array.length,seen,result=[];seen=result;outer:while(++index<length){var value=array[index];var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===value){continue outer;}}
result.push(value);}
return result;}
if(!length){return[];}
return baseUniq(array);},without:function(){var array,values=[];for(var i in arguments){if(i==0)array=arguments[0];else values.push(arguments[i]);}
return array.filter(function(e){return values.indexOf(e)==-1;});},zero:function(array){for(var i in array)if(!!array[i])return false;return true;},};var string={contains:function(template,pattern){return template.indexOf(pattern)>-1;},copy:function(src){var i;var dst='';for(i=0;i<src.length;i++)dst=dst+src.charAt(i);return dst;},create:function(size)
{var i;var s='';var init=' ';for(i=0;i<size;i++)s=s+init;return s;},endsWith:function(str,tail){return str.indexOf(tail)==(str.length-tail.length);},empty:function(str){return this.equal(str,'');},equal:function(str1,str2){var i;var eq=true;if(str1.length!=str2.length)return false;for(i=0;i<str1.length;i++){if(string.get(str1,i)!=string.get(str2,i))eq=false;}
return eq;},find:function(search,str){return str.indexOf(search);},format_hex:function(n,len){switch(len){case 2:return(((n>>4)&0xf).toString(16))+
((n&0xf).toString(16));case 4:return(((n>>12)&0xf).toString(16)+
((n>>8)&0xf).toString(16)+
((n>>4)&0xf).toString(16)+
(n&0xf).toString(16));case 6:return(((n>>20)&0xf).toString(16)+
((n>>16)&0xf).toString(16)+
((n>>12)&0xf).toString(16)+
((n>>8)&0xf).toString(16)+
((n>>4)&0xf).toString(16)+
(n&0xf).toString(16));case 8:return(((n>>28)&0xf).toString(16)+
((n>>24)&0xf).toString(16)+
((n>>20)&0xf).toString(16)+
((n>>16)&0xf).toString(16)+
((n>>12)&0xf).toString(16)+
((n>>8)&0xf).toString(16)+
((n>>4)&0xf).toString(16)+
(n&0xf).toString(16));default:return'format_hex??';}},get:function(str,index){assert((str!=undefined&&index<str.length&&index>=0)||('string.get ('+str.length+')'));return str.charAt(index);},isBoolean:function(str){return(str=='true'||str=='false')},isNumeric:function(str){return!isNaN(parseFloat(str))&&isFinite(str);},isText:function(s){var is_text=true;string.iter(s,function(ch,i){string.match(ch,[['a','z',function(){}],['A','Z',function(){}],['0','9',function(){if(i==0)is_text=false;}],function(){is_text=false;}]);});return is_text;},iter:function(str,fun){var i;var len=str.length;for(i=0;i<len;i++){var c=str.charAt(i);fun(c,i);}},length:function(str){if(str!=undefined)return str.length;else return 0;},lowercase:function(str){return str.toLowerCase();},make:function(size,init)
{var i;var s='';for(i=0;i<size;i++)s=s+init;return s;},map:function(str,mapping){var i;var map;for(i in mapping){map=mapping[i];if(obj.isFunction(map))return map(str);else if(this.equal(str,map[0]))return map[1];}},match:function(str,cases){var i,j;var cas,cex,cv;for(i in cases){cas=cases[i];if(obj.isArray(cas)){switch(cas.length){case 2:cex=cas[0];if(!obj.isArray(cex)){if(this.equal(str,cex)){cas[1]();return;}}else{for(j in cex){cv=cex[j];if(this.equal(str,cv)){cas[1]();return;}}}
break;case 3:try{j=pervasives.int_of_char(str);if(j>=pervasives.int_of_char(cas[0])&&j<=pervasives.int_of_char(cas[1])){cas[2](str);return;}}catch(e){return};break;case 1:cas[0](str);return;default:throw'String.match #args';}}else if(obj.isFunction(cas)){cas(str);return;}}},pad:function(str,pre,post,char){var len=str.length;if(pre>0&&post==0)return string.make(len-pre,char||' ')+str;else if(post>0&&pre==0)return str+string.make(post-len,char||' ');else return string.make(len-pre/2,char||' ')+str+string.make(len-post/2,char||' ');},parse_hex:function(str,pos,len){return parseInt(this.sub(str,pos,len),16);},postfix:function(str,point){var n=str.indexOf(point||'.');if(n<=0)return str;else return str.substr(n+1);},prefix:function(str,point){var n=str.indexOf(point||'.');if(n<=0)return str;else return str.substr(0,n);},replace_first:function(pat,repl,str){return str.replace(pat,repl);},replace_all:function(pat,repl,str){return str.replace('/'+pat+'/g',repl);},set:function(str,index,char){assert((str!=undefined&&index<str.length&&index>=0)||'string.get');return str.substr(0,index)+char+str.substr(index+1)},split:function(delim,str){return str.split(delim);},startsWith:function(str,head){return!str.indexOf(head);},sub:function(str,off,len){if(len)
return str.substr(off,len);else
return str.substr(off);},trim:function(str,pref,post){if(str.length==0||pref>str.length||post>str.length||pref<0||post<0||(pref==0&&post==0))return str;return str.substr(pref,str.length-pref-post);},uppercase:function(str){return str.toUpperCase();},Uppercase:function(str){var len=str.length;if(len>1){var head=str.substr(0,1);var tail=str.substr(1,len-1);return head.toUpperCase()+tail.toLowerCase()}if(len==1)return str.toUpperCase();else return'';}};var rnd=Math.random;var seeder=function(s){var m_w=s;var m_z=987654321;var mask=0xffffffff;return function(){m_z=(36969*(m_z&65535)+(m_z>>16))&mask;m_w=(18000*(m_w&65535)+(m_w>>16))&mask;var result=((m_z<<16)+m_w)&mask;result/=4294967296;return result+0.5;}}
var random={float:function(max){return rnd()*max},int:function(max){return Math.floor(rnd()*max+0)},interval:function(min,max){return Math.round(min+rnd()*(max-min))},range:function(min,max){return min+rnd()*(max-min)},seed:function(s){rnd=seeder(s);}};var printf={align:function(str,indent,width,tab){var lines=string.split('\n',str);var form='';var sp=printf.spaces(indent);var spbreak=sp;array.iter(lines,function(line){var rest;function breakit(spbreak,str){if(width<(str.length+spbreak.length)){return spbreak+string.sub(str,0,width-spbreak.length)+'\n'+
breakit(spbreak,string.sub(str,width-spbreak.length,str.length-width+spbreak.length));}else return spbreak+str+'\n';}
if(width&&width<(line.length+indent)){if(tab){var pos=string.find(tab,line);if(pos>0&&pos<width)spbreak=printf.spaces(pos+indent+1);else spbreak=sp;}
form=form+sp+string.sub(line,0,width-indent)+'\n';rest=string.sub(line,width-indent,line.length-width+indent);form=form+breakit(spbreak,rest);}
else
form=form+sp+line+'\n';});return form;},list:function(array,fun,sep){var i,str='';if(sep==undefined)sep=',';if(fun==undefined)fun=function(s){return s;};if(!obj.isArray(array))array=[array];for(i in array){if(str==='')str=fun(array[i]);else str=str+sep+fun(array[i]);}
return str;},spaces:function(n){return string.make(n,' ');},sprintf2:function(args){var str='';array.iter(args,function(fmtarg){var len,n,fs;if(obj.isArray(fmtarg)){if(fmtarg.length==2){var fmt=fmtarg[0];var arg=fmtarg[1];var fc='';var fn=0;string.iter(fmt,function(c){if(c=='s'||c=='d'||c=='f'||c=='x'){fc=c;}else if(c!='%'){fn=fn*10;n=parseInt(c);if(!isNaN(n))fn=fn+n;}});if(fc=='s'&&obj.isString(arg)){str=str+arg;if(fn!=0){len=arg.length;if(len<fn)str=str+string.create(fn-len);}}else if(fc=='d'&&obj.isNumber(arg)){fs=pervasives.string_of_int(arg);if(fn!=0){len=fs.length;if(len<fn){str=str+string.create(fn-len);}}
str=str+fs;}else if(fc=='x'&&obj.isNumber(arg)){fs=string.format_hex(arg,fn||8);str=str+fs;}}}else if(obj.isString(fmtarg)){str=str+fmtarg;}});return str;},sprintf:Sprintf.sprintf};var filename={basename:function(path){return Path.basename(path);},dirname:function(path){return Path.dirname(path);},extname:function(path){return Path.extname(path)},is_relative:function(path){return!(path.length>0&&path[0]=='/');},join:function(pathl,absolute){var path=(absolute?'/':'');array.iter(pathl,function(name,index){if(index>0){path=path+'/'+name;}
else{path=path+name;}});return path;},normalize:function(path){return Path.normalize(path)},path_absolute:function(path){if(this.is_relative(path)){var workdir=Io.workdir();return this.path_normalize(workdir+'/'+path);}else return this.path_normalize(path);},path_normalize:function(path){var i;if(string.equal(path,''))path='/';var relpath=!(string.get(path,0)=='/');var pathlist=path.split('/');var pathlist2=pathlist.filter(function(s){return(!string.equal(s,'')&&!string.equal(s,'.'))});var pathlist3=[];array.iter(pathlist2,function(pe){if(!string.equal(pe,'..')){array.push(pathlist3,pe)}else{if(pathlist3.length==0)return'';else
pathlist3=array.tail(pathlist3);}});var path2='';i=0;array.iter(pathlist3,function(pe){var sep;if(i==0)sep='';else sep='/';path2=pe+sep+path2;i++;});if(relpath)return path2;else return'/'+path2;},removeext:function(path){return path.substr(0,path.lastIndexOf('.'));}};var pervasives={assert:assert,char_of_int:function(i){return String.fromCharCode(i)},div:function(a,b){return a/b|0;},failwith:function(msg){Io.err(msg);},float_of_string:function(s){var num=parseFloat(s);if(isNaN(num))throw'NaN';else return num;},int_of_char:function(c){return c.charCodeAt()},int_of_float:function(f){return f|0;},int_of_string:function(s){var num=parseInt(s);if(isNaN(num))throw'NaN';else return num;},map:function(value,mapping){function eq(v1,v2){if(v1==v2)return true;if(obj.isString(v1)&&obj.isString(v2))return string.equal(v1,v2);return false;}
if(!array.empty(mapping)){var hd=array.head(mapping);var tl=array.tail(mapping);if(eq(hd[0],value))return hd[1];else return pervasives.map(value,tl);}else return undefined;},match:function(matcher,expr,cases){var ret=undefined;array.iter_break(cases,function(match){var quit,succ,pat,fun;if(match.length==2){pat=match[0];fun=match[1];succ=matcher(expr,pat);if(succ)ret=fun(succ);quit=succ!=undefined;}else if(match.length==1){fun=match[0];ret=fun();quit=true;}
return quit;});return ret;},mtime:function(){var time=new Date();return time.getTime();},min:function(a,b){return(a<b)?a:b},max:function(a,b){return(a>b)?a:b},string_of_float:function(f){return f.toString()},string_of_int:function(i){return i.toString()},string_of_int64:function(i){return i.toString()},time:function(){var time=new Date();return(time.getTime()/1000)|0;}};var bit={get:function(v,b){return(v>>b)&&1;},isSet:function(v,b){return((v>>b)&&1)==1;},set:function(v,b){return v&(1<<b);}};var args={parse:function(argv,map,offset){var shift=undefined,in_shift=0,shift_args=[],names,mapfun,numarg,len=argv.length;if(offset==undefined)offset=1;argv.forEach(function(val,index){var last=index==(len-1);if(index>=offset){if(in_shift==0){array.check(map,function(onemap){assert(onemap!=undefined||'map');if(onemap.length==3){names=onemap[0];numarg=onemap[1];mapfun=onemap[2];if(!obj.isArray(names))names=[names];var found=array.find(names,function(name){if(string.equal(val,name))return name;else _;});if(found){if(numarg==0)mapfun(found);else{in_shift=numarg;shift_args=[];shift=mapfun;}
return true;}}else if(obj.isFunction(onemap)){onemap(val);return true;}else if(onemap.length==1){mapfun=onemap[0];mapfun(val);return true;}
return false;});}else{shift_args.push(val);if(in_shift!='*')in_shift--;if(in_shift==0&&shift!=undefined){numarg=shift_args.length;switch(numarg){case 0:shift(val);break;case 1:shift(shift_args[0],val);break;case 2:shift(shift_args[0],shift_args[1],val);break;case 3:shift(shift_args[0],shift_args[1],shift_args[2],val);break;default:break;}
shift=undefined;}else if(in_shift=='*'&&last)shift(shift_args);}}});}};var hashtbl={add:function(hash,key,data){hash[key]=data;},create:function(initial){return[];},empty:function(hash){for(var key in hash)return false;return true;},find:function(hash,key){return hash[key];},invalidate:function(hash,key){hash[key]=undefined;},iter:function(hash,fun){for(var key in hash){if(hash[key]!=undefined)fun(key,hash[key]);}},mem:function(hash,key){return hash[key]!=undefined;},remove:function(hash,key){if(!hash.hasOwnProperty(key))
return;if(isNaN(parseInt(key))||!(hash instanceof Array))
delete hash[key];else
hash.splice(key,1)}};var types=[];function register_type(name){var typoff=1000+types.length*1000;if(array.member(types,name))throw('[COMP] register_type: type '+name+' exists already.');types.push(name);return typoff;}
module.exports={args:args,assert:assert,array:array,bit:bit,copy:obj.copy,div:pervasives.div,filename:filename,hashtbl:hashtbl,isNodeJS:function(){return(typeof global!=="undefined"&&{}.toString.call(global)=='[object global]');},obj:obj,pervasives:pervasives,printf:printf,random:random,string:string,isArray:obj.isArray,isString:obj.isString,isNumber:obj.isNumber,register_type:register_type,Tuple:function(tag,val1,val2,val3){if(val3)return{t:tag,v1:val1,v2:val2,v3:val3};else if(val2)return{t:tag,v1:val1,v2:val2};else if(val1)return{t:tag,v1:val1};else return{t:tag};}};};BundleModuleCode['doc/doc']=function(module,exports){var Marked=Require('doc/marked');var Colors=Require('doc/colors');var List=Require('doc/list');var Table=Require('doc/cli-table');var NL='\n';function id(x){return x}
var css={bold:Colors.black.bold,italic:Colors.underline,h1:Colors.bold,h2:Colors.blue.bold,h3:Colors.red.bold,ol:{label:['1','a','i'],},ul:{label:['*','-','+'],},}
function incr(label,start){switch(label){case'1':return start.toString();}
return label;}
function B(text){return css.bold(text)}
function I(text){return css.italic(text)}
function P(text){return text+'\n'}
function H(text,level){var color,escapedText=text.toLowerCase().replace(/[^\w]+/g,'-');switch(level){case 1:color=css.h1;break;case 2:color=css.h2;break;case 3:color=css.h3;break;default:color=id;}
return color(text+'\n');};function CD(text){return text+'\n';}
function DL(body){var item;list=new List({type:'dl',tab:2});while(this._data.stack.length&&this._data.stack[0].dt!=undefined){item=this._data.stack.shift();list.unshift({dt:css.bold(item.dt),dd:item.dd});}
return list.toString()+NL;}
function DT(body){this._data.stack.unshift({dt:body});}
function DD(body){if(this._data.stack.length&&this._data.stack[0].dt!=undefined)
this._data.stack[0].dd=body;}
function L(body,ordered,start){var list,label;if(ordered)label=incr(css.ol.label[this._data.olist],start);else label=css.ul.label[this._data.ulist];list=new List({type:label});if(ordered)this._data.olist++;else this._data.ulist++;while(this._data.stack.length&&this._data.stack[0].item!=undefined){list.unshift(this._data.stack.shift().item);}
if(ordered)this._data.olist--;else this._data.ulist--;return list.toString()+NL;}
function LI(text){this._data.stack.unshift({item:text});}
function text(text){return text.replace(/&quot;/g,'"').replace(/&gt;/g,'>').replace(/&lt;/g,'<');}
function Renderer(options){var marked=Marked(),renderer=new marked.Renderer();renderer.heading=H.bind(renderer);renderer.list=L.bind(renderer);renderer.listitem=LI.bind(renderer);renderer.paragraph=P.bind(renderer);renderer.strong=B.bind(renderer);renderer.em=I.bind(renderer);renderer._data={stack:[],ulist:0,olist:0};renderer.dt=DT.bind(renderer);renderer.dd=DD.bind(renderer);renderer.dl=DL.bind(renderer);renderer.code=CD.bind(renderer);renderer.text=text;marked.setOptions({renderer:renderer,highlight:function(code){return require('highlight.js').highlightAuto(code).value;},pedantic:false,gfm:true,tables:true,breaks:false,sanitize:false,smartLists:true,smartypants:false,xhtml:false});if(options.lazy)return function(text){try{return marked(text)}catch(e){return text}};else return marked;}
module.exports={Colors:Colors,List:List,Marked:Marked,Renderer:Renderer,Table:Table}};BundleModuleCode['doc/marked']=function(module,exports){module.exports=function(){'use strict';var block={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:noop,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,nptable:noop,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:'^ {0,3}(?:'
+'<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)'
+'|comment[^\\n]*(\\n+|$)'
+'|<\\?[\\s\\S]*?\\?>\\n*'
+'|<![A-Z][\\s\\S]*?>\\n*'
+'|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*'
+'|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)'
+'|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)'
+'|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)'
+')',def:/^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,dl:/^ *(dt)\n: *(dd)/,table:noop,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)+)/,text:/^[^\n]+/};block._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;block._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;block.def=edit(block.def).replace('label',block._label).replace('title',block._title).getRegex();block.bullet=/(?:[*+-]|\d+\.)/;block.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;block.item=edit(block.item,'gm').replace(/bull/g,block.bullet).getRegex();block.list=edit(block.list).replace(/bull/g,block.bullet).replace('hr','\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def','\\n+(?='+block.def.source+')').getRegex();block._tag='address|article|aside|base|basefont|blockquote|body|caption'
+'|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
+'|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
+'|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
+'|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
+'|track|ul';block._comment=/<!--(?!-?>)[\s\S]*?-->/;block.html=edit(block.html,'i').replace('comment',block._comment).replace('tag',block._tag).replace('attribute',/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();block.paragraph=edit(block.paragraph).replace('hr',block.hr).replace('heading',block.heading).replace('lheading',block.lheading).replace('tag',block._tag).getRegex();block.blockquote=edit(block.blockquote).replace('paragraph',block.paragraph).getRegex();block.dl=edit(block.dl).replace('dt',block.text).replace('dd',block.text).getRegex();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\n? *\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=edit(block.paragraph).replace('(?!','(?!'
+block.gfm.fences.source.replace('\\1','\\2')+'|'
+block.list.source.replace('\\1','\\3')+'|').getRegex();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});block.pedantic=merge({},block.normal,{html:edit('^ *(?:comment *(?:\\n|\\s*$)'
+'|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)'
+'|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment',block._comment).replace(/tag/g,'(?!(?:'
+'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
+'|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
+'\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.pedantic){this.rules=block.pedantic;}else if(this.options.gfm){if(this.options.tables){this.rules=block.tables;}else{this.rules=block.gfm;}}}
Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src);};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,'\n').replace(/\t/g,' ').replace(/\u00a0/g,' ').replace(/\u2424/g,'\n');return this.token(src,true);};Lexer.prototype.token=function(src,top){src=src.replace(/^ +$/gm,'');var next,loose,cap,bull,b,item,space,i,tag,l,isordered;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:'space'});}}
if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,'');this.tokens.push({type:'code',text:!this.options.pedantic?cap.replace(/\n+$/,''):cap});continue;}
if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'code',lang:cap[2],text:cap[3]||''});continue;}
if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'heading',depth:cap[1].length,text:cap[2]});continue;}
if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:'table',header:splitCells(cap[1].replace(/^ *| *\| *$/g,'')),align:cap[2].replace(/^ *|\| *$/g,'').split(/ *\| */),cells:cap[3].replace(/\n$/,'').split('\n')};for(i=0;i<item.align.length;i++){if(/^ *-+: *$/.test(item.align[i])){item.align[i]='right';}else if(/^ *:-+: *$/.test(item.align[i])){item.align[i]='center';}else if(/^ *:-+ *$/.test(item.align[i])){item.align[i]='left';}else{item.align[i]=null;}}
for(i=0;i<item.cells.length;i++){item.cells[i]=splitCells(item.cells[i]);}
this.tokens.push(item);continue;}
if(cap=this.rules.hr.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'hr'});continue;}
if(cap=this.rules.blockquote.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'blockquote_start'});cap=cap[0].replace(/^ *> ?/gm,'');this.token(cap,top);this.tokens.push({type:'blockquote_end'});continue;}
if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];isordered=bull.length>1;this.tokens.push({type:'list_start',ordered:isordered,start:isordered?+bull:''});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i<l;i++){item=cap[i];space=item.length;item=item.replace(/^ *([*+-]|\d+\.) +/,'');if(~item.indexOf('\n ')){space-=item.length;item=!this.options.pedantic?item.replace(new RegExp('^ {1,'+space+'}','gm'),''):item.replace(/^ {1,4}/gm,'');}
if(this.options.smartLists&&i!==l-1){b=block.bullet.exec(cap[i+1])[0];if(bull!==b&&!(bull.length>1&&b.length>1)){src=cap.slice(i+1).join('\n')+src;i=l-1;}}
loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==='\n';if(!loose)loose=next;}
this.tokens.push({type:loose?'loose_item_start':'list_item_start'});this.token(item,false);this.tokens.push({type:'list_item_end'});}
this.tokens.push({type:'list_end'});continue;}
if(cap=this.rules.dl.exec(src)){this.tokens.push({type:'dl_start',});this.tokens.push({type:'dt_start',});this.tokens.push({type:'text',text:cap[1]});this.tokens.push({type:'dt_end',});this.tokens.push({type:'dd_start',});this.tokens.push({type:'text',text:cap[2]});this.tokens.push({type:'dd_end',});src=src.substring(cap[0].length);this.tokens.push({type:'dl_end'});continue;}
if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?'paragraph':'html',pre:!this.options.sanitizer&&(cap[1]==='pre'||cap[1]==='script'||cap[1]==='style'),text:cap[0]});continue;}
if(top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);if(cap[3])cap[3]=cap[3].substring(1,cap[3].length-1);tag=cap[1].toLowerCase().replace(/\s+/g,' ');if(!this.tokens.links[tag]){this.tokens.links[tag]={href:cap[2],title:cap[3]};}
continue;}
if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:'table',header:splitCells(cap[1].replace(/^ *| *\| *$/g,'')),align:cap[2].replace(/^ *|\| *$/g,'').split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,'').split('\n')};for(i=0;i<item.align.length;i++){if(/^ *-+: *$/.test(item.align[i])){item.align[i]='right';}else if(/^ *:-+: *$/.test(item.align[i])){item.align[i]='center';}else if(/^ *:-+ *$/.test(item.align[i])){item.align[i]='left';}else{item.align[i]=null;}}
for(i=0;i<item.cells.length;i++){item.cells[i]=splitCells(item.cells[i].replace(/^ *\| *| *\| *$/g,''));}
this.tokens.push(item);continue;}
if(cap=this.rules.lheading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'heading',depth:cap[2]==='='?1:2,text:cap[1]});continue;}
if(top&&(cap=this.rules.paragraph.exec(src))){src=src.substring(cap[0].length);this.tokens.push({type:'paragraph',text:cap[1].charAt(cap[1].length-1)==='\n'?cap[1].slice(0,-1):cap[1]});continue;}
if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:'text',text:cap[0]});continue;}
if(src){throw new Error('Infinite loop on byte: '+src.charCodeAt(0));}}
return this.tokens;};var inline={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:noop,tag:'^comment'
+'|^</[a-zA-Z][\\w:-]*\\s*>'
+'|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>'
+'|^<\\?[\\s\\S]*?\\?>'
+'|^<![a-zA-Z]+\\s[\\s\\S]*?>'
+'|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',link:/^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__[^\s_\*]__|^\*\*[^\s]\*\*|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)|^__([^\s])__(?!_)|^\*\*([^\s])\*\*(?!\*)/,em:/^_[^\s_\*]_|^\*[^\s_\*]\*|^_([^\s][\s\S]*?[^\s_])_(?!_)|^_([^\s_][\s\S]*?[^\s])_(?!_)|^\*([^\s][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*][\s\S]*?[^\s])\*(?!\*)|^_([^\s_])_(?!_)|^\*([^\s*])\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`]?)\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\<!\[`*]|\b_| {2,}\n|$)/};inline._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;inline._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;inline._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;inline.autolink=edit(inline.autolink).replace('scheme',inline._scheme).replace('email',inline._email).getRegex();inline._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;inline.tag=edit(inline.tag).replace('comment',block._comment).replace('attribute',inline._attribute).getRegex();inline._label=/(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?/;inline._href=/\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f()\\]*\)|[^\s\x00-\x1f()\\])*?)/;inline._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;inline.link=edit(inline.link).replace('label',inline._label).replace('href',inline._href).replace('title',inline._title).getRegex();inline.reflink=edit(inline.reflink).replace('label',inline._label).getRegex();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:edit(/^!?\[(label)\]\((.*?)\)/).replace('label',inline._label).getRegex(),reflink:edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label',inline._label).getRegex()});inline.gfm=merge({},inline.normal,{escape:edit(inline.escape).replace('])','~|])').getRegex(),url:edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace('email',inline._email).getRegex(),_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:edit(inline.text).replace(']|','~]|').replace('|','|https?://|ftp://|www\\.|[a-zA-Z0-9.!#$%&\'*+/=?^_`{\\|}~-]+@|').getRegex()});inline.breaks=merge({},inline.gfm,{br:edit(inline.br).replace('{2,}','*').getRegex(),text:edit(inline.gfm.text).replace('{2,}','*').getRegex()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer();this.renderer.options=this.options;if(!this.links){throw new Error('Tokens array requires a `links` property.');}
if(this.options.pedantic){this.rules=inline.pedantic;}else if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks;}else{this.rules=inline.gfm;}}}
InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src);};InlineLexer.prototype.output=function(src){var out='',link,text,href,title,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue;}
if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==='@'){text=escape(this.mangle(cap[1]));href='mailto:'+text;}else{text=escape(cap[1]);href=text;}
out+=this.renderer.link(href,null,text);continue;}
if(!this.inLink&&(cap=this.rules.url.exec(src))){cap[0]=this.rules._backpedal.exec(cap[0])[0];src=src.substring(cap[0].length);if(cap[2]==='@'){text=escape(cap[0]);href='mailto:'+text;}else{text=escape(cap[0]);if(cap[1]==='www.'){href='http://'+text;}else{href=text;}}
out+=this.renderer.link(href,null,text);continue;}
if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^<a /i.test(cap[0])){this.inLink=true;}else if(this.inLink&&/^<\/a>/i.test(cap[0])){this.inLink=false;}
src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0]
continue;}
if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;href=cap[2];if(this.options.pedantic){link=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);if(link){href=link[1];title=link[3];}else{title='';}}else{title=cap[3]?cap[3].slice(1,-1):'';}
href=href.trim().replace(/^<([\s\S]*)>$/,'$1');out+=this.outputLink(cap,{href:InlineLexer.escapes(href),title:InlineLexer.escapes(title)});this.inLink=false;continue;}
if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g,' ');link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue;}
this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue;}
if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[4]||cap[3]||cap[2]||cap[1]));continue;}
if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[6]||cap[5]||cap[4]||cap[3]||cap[2]||cap[1]));continue;}
if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2].trim(),true));continue;}
if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue;}
if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue;}
if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue;}
if(src){throw new Error('Infinite loop on byte: '+src.charCodeAt(0));}}
return out;};InlineLexer.escapes=function(text){return text?text.replace(InlineLexer.rules._escapes,'$1'):text;}
InlineLexer.prototype.outputLink=function(cap,link){var href=link.href,title=link.title?escape(link.title):null;return cap[0].charAt(0)!=='!'?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]));};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,'\u2014').replace(/--/g,'\u2013').replace(/(^|[-\u2014/(\[{"\s])'/g,'$1\u2018').replace(/'/g,'\u2019').replace(/(^|[-\u2014/(\[{\u2018\s])"/g,'$1\u201c').replace(/"/g,'\u201d').replace(/\.{3}/g,'\u2026');};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out='',l=text.length,i=0,ch;for(;i<l;i++){ch=text.charCodeAt(i);if(Math.random()>0.5){ch='x'+ch.toString(16);}
out+='&#'+ch+';';}
return out;};function Renderer(options){this.options=options||marked.defaults;}
Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out;}}
if(!lang){return'<pre><code>'
+(escaped?code:escape(code,true))
+'\n</code></pre>';}
return'<pre><code class="'
+this.options.langPrefix
+escape(lang,true)
+'">'
+(escaped?code:escape(code,true))
+'\n</code></pre>\n';};Renderer.prototype.blockquote=function(quote){return'<blockquote>\n'+quote+'</blockquote>\n';};Renderer.prototype.html=function(html){return html;};Renderer.prototype.heading=function(text,level,raw){if(this.options.headerIds){return'<h'
+level
+' id="'
+this.options.headerPrefix
+raw.toLowerCase().replace(/[^\w]+/g,'-')
+'">'
+text
+'</h'
+level
+'>\n';}
return'<h'+level+'>'+text+'</h'+level+'>\n';};Renderer.prototype.hr=function(){return this.options.xhtml?'<hr/>\n':'<hr>\n';};Renderer.prototype.list=function(body,ordered,start){var type=ordered?'ol':'ul',startatt=(ordered&&start!==1)?(' start="'+start+'"'):'';return'<'+type+startatt+'>\n'+body+'</'+type+'>\n';};Renderer.prototype.listitem=function(text){return'<li>'+text+'</li>\n';};Renderer.prototype.dl=function(body){return'<dl>\n'+body+'</dl>\n';};Renderer.prototype.dt=function(body){return'<dt>'+body+'</dt>\n';};Renderer.prototype.dd=function(body){return'<dd>'+body+'</dd>\n';};Renderer.prototype.paragraph=function(text){return'<p>'+text+'</p>\n';};Renderer.prototype.table=function(header,body){return'<table>\n'
+'<thead>\n'
+header
+'</thead>\n'
+'<tbody>\n'
+body
+'</tbody>\n'
+'</table>\n';};Renderer.prototype.tablerow=function(content){return'<tr>\n'+content+'</tr>\n';};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?'th':'td';var tag=flags.align?'<'+type+' style="text-align:'+flags.align+'">':'<'+type+'>';return tag+content+'</'+type+'>\n';};Renderer.prototype.strong=function(text){return'<strong>'+text+'</strong>';};Renderer.prototype.em=function(text){return'<em>'+text+'</em>';};Renderer.prototype.codespan=function(text){return'<code>'+text+'</code>';};Renderer.prototype.br=function(){return this.options.xhtml?'<br/>':'<br>';};Renderer.prototype.del=function(text){return'<del>'+text+'</del>';};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,'').toLowerCase();}catch(e){return text;}
if(prot.indexOf('javascript:')===0||prot.indexOf('vbscript:')===0||prot.indexOf('data:')===0){return text;}}
if(this.options.baseUrl&&!originIndependentUrl.test(href)){href=resolveUrl(this.options.baseUrl,href);}
try{href=encodeURI(href).replace(/%25/g,'%');}catch(e){return text;}
var out='<a href="'+escape(href)+'"';if(title){out+=' title="'+title+'"';}
out+='>'+text+'</a>';return out;};Renderer.prototype.image=function(href,title,text){if(this.options.baseUrl&&!originIndependentUrl.test(href)){href=resolveUrl(this.options.baseUrl,href);}
var out='<img src="'+href+'" alt="'+text+'"';if(title){out+=' title="'+title+'"';}
out+=this.options.xhtml?'/>':'>';return out;};Renderer.prototype.text=function(text){return text;};function TextRenderer(){}
TextRenderer.prototype.strong=TextRenderer.prototype.em=TextRenderer.prototype.codespan=TextRenderer.prototype.del=TextRenderer.prototype.text=function(text){return text;}
TextRenderer.prototype.link=TextRenderer.prototype.image=function(href,title,text){return''+text;}
TextRenderer.prototype.br=function(){return'';}
function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer();this.renderer=this.options.renderer;this.renderer.options=this.options;}
Parser.parse=function(src,options){var parser=new Parser(options);return parser.parse(src);};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options);this.inlineText=new InlineLexer(src.links,merge({},this.options,{renderer:new TextRenderer()}));this.tokens=src.reverse();var out='';while(this.next()){out+=this.tok();}
return out;};Parser.prototype.next=function(){return this.token=this.tokens.pop();};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0;};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==='text'){body+='\n'+this.next().text;}
return this.inline.output(body);};Parser.prototype.tok=function(){switch(this.token.type){case'space':{return'';}
case'hr':{return this.renderer.hr();}
case'heading':{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,unescape(this.inlineText.output(this.token.text)));}
case'code':{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);}
case'table':{var header='',body='',i,row,cell,j;cell='';for(i=0;i<this.token.header.length;i++){cell+=this.renderer.tablecell(this.inline.output(this.token.header[i]),{header:true,align:this.token.align[i]});}
header+=this.renderer.tablerow(cell);for(i=0;i<this.token.cells.length;i++){row=this.token.cells[i];cell='';for(j=0;j<row.length;j++){cell+=this.renderer.tablecell(this.inline.output(row[j]),{header:false,align:this.token.align[j]});}
body+=this.renderer.tablerow(cell);}
return this.renderer.table(header,body);}
case'blockquote_start':{body='';while(this.next().type!=='blockquote_end'){body+=this.tok();}
return this.renderer.blockquote(body);}
case'list_start':{body='';var ordered=this.token.ordered,start=this.token.start;while(this.next().type!=='list_end'){body+=this.tok();}
return this.renderer.list(body,ordered,start);}
case'list_item_start':{body='';while(this.next().type!=='list_item_end'){body+=this.token.type==='text'?this.parseText():this.tok();}
return this.renderer.listitem(body);}
case'loose_item_start':{body='';while(this.next().type!=='list_item_end'){body+=this.tok();}
return this.renderer.listitem(body);}
case'dl_start':{body='';while(this.next().type!=='dl_end'){body+=this.tok();}
return this.renderer.dl(body);}
case'dt_start':{body='';while(this.next().type!=='dt_end'){body+=this.parseText();}
return this.renderer.dt(body);}
case'dd_start':{body='';while(this.next().type!=='dd_end'){body+=this.parseText();}
return this.renderer.dd(body);}
case'html':{return this.renderer.html(this.token.text);}
case'paragraph':{return this.renderer.paragraph(this.inline.output(this.token.text));}
case'text':{return this.renderer.paragraph(this.parseText());}}};function escape(html,encode){return html.replace(!encode?/&(?!#?\w+;)/g:/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}
function unescape(html){return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,function(_,n){n=n.toLowerCase();if(n==='colon')return':';if(n.charAt(0)==='#'){return n.charAt(1)==='x'?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1));}
return'';});}
function edit(regex,opt){regex=regex.source||regex;opt=opt||'';return{replace:function(name,val){val=val.source||val;val=val.replace(/(^|[^\[])\^/g,'$1');regex=regex.replace(name,val);return this;},getRegex:function(){return new RegExp(regex,opt);}};}
function resolveUrl(base,href){if(!baseUrls[' '+base]){if(/^[^:]+:\/*[^/]*$/.test(base)){baseUrls[' '+base]=base+'/';}else{baseUrls[' '+base]=base.replace(/[^/]*$/,'');}}
base=baseUrls[' '+base];if(href.slice(0,2)==='//'){return base.replace(/:[\s\S]*/,':')+href;}else if(href.charAt(0)==='/'){return base.replace(/(:\/*[^/]*)[\s\S]*/,'$1')+href;}else{return base+href;}}
var baseUrls={};var originIndependentUrl=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function noop(){}
noop.exec=noop;function merge(obj){var i=1,target,key;for(;i<arguments.length;i++){target=arguments[i];for(key in target){if(Object.prototype.hasOwnProperty.call(target,key)){obj[key]=target[key];}}}
return obj;}
function splitCells(tableRow){var cells=tableRow.replace(/([^\\])\|/g,'$1 |').split(/ +\| */),i=0;for(;i<cells.length;i++){cells[i]=cells[i].replace(/\\\|/g,'|');}
return cells;}
function marked(src,opt,callback){if(typeof src==='undefined'||src===null){throw new Error('marked(): input parameter is undefined or null');}
if(typeof src!=='string'){throw new Error('marked(): input parameter is of type '
+Object.prototype.toString.call(src)+', string expected');}
if(callback||typeof opt==='function'){if(!callback){callback=opt;opt=null;}
opt=merge({},marked.defaults,opt||{});var highlight=opt.highlight,tokens,pending,i=0;try{tokens=Lexer.lex(src,opt)}catch(e){return callback(e);}
pending=tokens.length;var done=function(err){if(err){opt.highlight=highlight;return callback(err);}
var out;try{out=Parser.parse(tokens,opt);}catch(e){err=e;}
opt.highlight=highlight;return err?callback(err):callback(null,out);};if(!highlight||highlight.length<3){return done();}
delete opt.highlight;if(!pending)return done();for(;i<tokens.length;i++){(function(token){if(token.type!=='code'){return--pending||done();}
return highlight(token.text,token.lang,function(err,code){if(err)return done(err);if(code==null||code===token.text){return--pending||done();}
token.text=code;token.escaped=true;--pending||done();});})(tokens[i]);}
return;}
try{if(opt)opt=merge({},marked.defaults,opt);return Parser.parse(Lexer.lex(src,opt),opt);}catch(e){e.message+='\nPlease report this to https://github.com/markedjs/marked.';if((opt||marked.defaults).silent){return'<p>An error occurred:</p><pre>'
+escape(e.message+'',true)
+'</pre>';}
throw e;}}
marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked;};marked.getDefaults=function(){return{baseUrl:null,breaks:false,gfm:true,headerIds:true,headerPrefix:'',highlight:null,langPrefix:'lang-',mangle:true,pedantic:false,renderer:new Renderer(),sanitize:false,sanitizer:null,silent:false,smartLists:false,smartypants:false,tables:true,xhtml:false};}
marked.defaults=marked.getDefaults();marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.TextRenderer=TextRenderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;return marked;}};BundleModuleCode['doc/colors']=function(module,exports){var colors={};module['exports']=colors;colors.themes={};var ansiStyles=colors.styles=Require('doc/styles');var defineProps=Object.defineProperties;colors.supportsColor=Require('doc/system/supports-colors').supportsColor;if(typeof colors.enabled==="undefined"){colors.enabled=colors.supportsColor()!==false;}
colors.stripColors=colors.strip=function(str){return(""+str).replace(/\x1B\[\d+m/g,'');};var stylize=colors.stylize=function stylize(str,style){if(!colors.enabled){return str+'';}
return ansiStyles[style].open+str+ansiStyles[style].close;}
var matchOperatorsRe=/[|\\{}()[\]^$+*?.]/g;var escapeStringRegexp=function(str){if(typeof str!=='string'){throw new TypeError('Expected a string');}
return str.replace(matchOperatorsRe,'\\$&');}
function build(_styles){var builder=function builder(){return applyStyle.apply(builder,arguments);};builder._styles=_styles;builder.__proto__=proto;return builder;}
var styles=(function(){var ret={};ansiStyles.grey=ansiStyles.gray;Object.keys(ansiStyles).forEach(function(key){ansiStyles[key].closeRe=new RegExp(escapeStringRegexp(ansiStyles[key].close),'g');ret[key]={get:function(){return build(this._styles.concat(key));}};});return ret;})();var proto=defineProps(function colors(){},styles);function applyStyle(){var args=arguments;var argsLen=args.length;var str=argsLen!==0&&String(arguments[0]);if(argsLen>1){for(var a=1;a<argsLen;a++){str+=' '+args[a];}}
if(!colors.enabled||!str){return str;}
var nestedStyles=this._styles;var i=nestedStyles.length;while(i--){var code=ansiStyles[nestedStyles[i]];str=code.open+str.replace(code.closeRe,code.open)+code.close;}
return str;}
colors.setTheme=function(theme){if(typeof theme==='string'){console.log('colors.setTheme now only accepts an object, not a string. '+'If you are trying to set a theme from a file, it is now your (the caller\'s) responsibility to require the file. '+'The old syntax looked like colors.setTheme(__dirname + \'/../themes/generic-logging.js\'); '+'The new syntax looks like colors.setTheme(require(__dirname + \'/../themes/generic-logging.js\'));');return;}
for(var style in theme){(function(style){colors[style]=function(str){if(typeof theme[style]==='object'){var out=str;for(var i in theme[style]){out=colors[theme[style][i]](out);}
return out;}
return colors[theme[style]](str);};})(style)}}
function init(){var ret={};Object.keys(styles).forEach(function(name){ret[name]={get:function(){return build([name]);}};});return ret;}
var sequencer=function sequencer(map,str){var exploded=str.split(""),i=0;exploded=exploded.map(map);return exploded.join("");};colors.trap=Require('doc/custom/trap');colors.zalgo=Require('doc/custom/zalgo');colors.maps={};colors.maps.america=(function(){return function(letter,i,exploded){if(letter===" ")return letter;switch(i%3){case 0:return colors.red(letter);case 1:return colors.white(letter)
case 2:return colors.blue(letter)}}})();colors.maps.zebra=function(letter,i,exploded){return i%2===0?letter:colors.inverse(letter);}
colors.maps.rainbow=(function(){var rainbowColors=['red','yellow','green','blue','magenta'];return function(letter,i,exploded){if(letter===" "){return letter;}else{return colors[rainbowColors[i++%rainbowColors.length]](letter);}};})();colors.maps.random=(function(){var available=['underline','inverse','grey','yellow','red','green','blue','white','cyan','magenta'];return function(letter,i,exploded){return letter===" "?letter:colors[available[Math.round(Math.random()*(available.length-1))]](letter);};})();for(var map in colors.maps){(function(map){colors[map]=function(str){return sequencer(colors.maps[map],str);}})(map)}
defineProps(colors,init());};BundleModuleCode['doc/styles']=function(module,exports){var styles={};module['exports']=styles;var codes={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(codes).forEach(function(key){var val=codes[key];var style=styles[key]=[];style.open='\u001b['+val[0]+'m';style.close='\u001b['+val[1]+'m';});};BundleModuleCode['doc/system/supports-colors']=function(module,exports){'use strict';var os=Require('os');var hasFlag=Require('doc/system/has-flag.js');var env=process.env;var forceColor=void 0;if(hasFlag('no-color')||hasFlag('no-colors')||hasFlag('color=false')){forceColor=false;}else if(hasFlag('color')||hasFlag('colors')||hasFlag('color=true')||hasFlag('color=always')){forceColor=true;}
if('FORCE_COLOR'in env){forceColor=env.FORCE_COLOR.length===0||parseInt(env.FORCE_COLOR,10)!==0;}
function translateLevel(level){if(level===0){return false;}
return{level:level,hasBasic:true,has256:level>=2,has16m:level>=3};}
function supportsColor(stream){if(forceColor===false){return 0;}
if(hasFlag('color=16m')||hasFlag('color=full')||hasFlag('color=truecolor')){return 3;}
if(hasFlag('color=256')){return 2;}
if(stream&&!stream.isTTY&&forceColor!==true){return 0;}
var min=forceColor?1:0;if(process.platform==='win32'){var osRelease=os.release().split('.');if(Number(process.versions.node.split('.')[0])>=8&&Number(osRelease[0])>=10&&Number(osRelease[2])>=10586){return Number(osRelease[2])>=14931?3:2;}
return 1;}
if('CI'in env){if(['TRAVIS','CIRCLECI','APPVEYOR','GITLAB_CI'].some(function(sign){return sign in env;})||env.CI_NAME==='codeship'){return 1;}
return min;}
if('TEAMCITY_VERSION'in env){return(/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0);}
if('TERM_PROGRAM'in env){var version=parseInt((env.TERM_PROGRAM_VERSION||'').split('.')[0],10);switch(env.TERM_PROGRAM){case'iTerm.app':return version>=3?3:2;case'Hyper':return 3;case'Apple_Terminal':return 2;}}
if(/-256(color)?$/i.test(env.TERM)){return 2;}
if(/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)){return 1;}
if('COLORTERM'in env){return 1;}
if(env.TERM==='dumb'){return min;}
return min;}
function getSupportLevel(stream){var level=supportsColor(stream);return translateLevel(level);}
module.exports={supportsColor:getSupportLevel,stdout:getSupportLevel(process.stdout),stderr:getSupportLevel(process.stderr)};};BundleModuleCode['doc/system/has-flag.js']=function(module,exports){'use strict';module.exports=function(flag,argv){argv=argv||process.argv;var terminatorPos=argv.indexOf('--');var prefix=/^-{1,2}/.test(flag)?'':'--';var pos=argv.indexOf(prefix+flag);return pos!==-1&&(terminatorPos===-1?true:pos<terminatorPos);};};BundleModuleCode['doc/custom/trap']=function(module,exports){module['exports']=function runTheTrap(text,options){var result="";text=text||"Run the trap, drop the bass";text=text.split('');var trap={a:["\u0040","\u0104","\u023a","\u0245","\u0394","\u039b","\u0414"],b:["\u00df","\u0181","\u0243","\u026e","\u03b2","\u0e3f"],c:["\u00a9","\u023b","\u03fe"],d:["\u00d0","\u018a","\u0500","\u0501","\u0502","\u0503"],e:["\u00cb","\u0115","\u018e","\u0258","\u03a3","\u03be","\u04bc","\u0a6c"],f:["\u04fa"],g:["\u0262"],h:["\u0126","\u0195","\u04a2","\u04ba","\u04c7","\u050a"],i:["\u0f0f"],j:["\u0134"],k:["\u0138","\u04a0","\u04c3","\u051e"],l:["\u0139"],m:["\u028d","\u04cd","\u04ce","\u0520","\u0521","\u0d69"],n:["\u00d1","\u014b","\u019d","\u0376","\u03a0","\u048a"],o:["\u00d8","\u00f5","\u00f8","\u01fe","\u0298","\u047a","\u05dd","\u06dd","\u0e4f"],p:["\u01f7","\u048e"],q:["\u09cd"],r:["\u00ae","\u01a6","\u0210","\u024c","\u0280","\u042f"],s:["\u00a7","\u03de","\u03df","\u03e8"],t:["\u0141","\u0166","\u0373"],u:["\u01b1","\u054d"],v:["\u05d8"],w:["\u0428","\u0460","\u047c","\u0d70"],x:["\u04b2","\u04fe","\u04fc","\u04fd"],y:["\u00a5","\u04b0","\u04cb"],z:["\u01b5","\u0240"]}
text.forEach(function(c){c=c.toLowerCase();var chars=trap[c]||[" "];var rand=Math.floor(Math.random()*chars.length);if(typeof trap[c]!=="undefined"){result+=trap[c][rand];}else{result+=c;}});return result;}};BundleModuleCode['doc/custom/zalgo']=function(module,exports){module['exports']=function zalgo(text,options){text=text||" he is here ";var soul={"up":['̍','̎','̄','̅','̿','̑','̆','̐','͒','͗','͑','̇','̈','̊','͂','̓','̈','͊','͋','͌','̃','̂','̌','͐','̀','́','̋','̏','̒','̓','̔','̽','̉','ͣ','ͤ','ͥ','ͦ','ͧ','ͨ','ͩ','ͪ','ͫ','ͬ','ͭ','ͮ','ͯ','̾','͛','͆','̚'],"down":['̖','̗','̘','̙','̜','̝','̞','̟','̠','̤','̥','̦','̩','̪','̫','̬','̭','̮','̯','̰','̱','̲','̳','̹','̺','̻','̼','ͅ','͇','͈','͉','͍','͎','͓','͔','͕','͖','͙','͚','̣'],"mid":['̕','̛','̀','́','͘','̡','̢','̧','̨','̴','̵','̶','͜','͝','͞','͟','͠','͢','̸','̷','͡',' ҉']},all=[].concat(soul.up,soul.down,soul.mid),zalgo={};function randomNumber(range){var r=Math.floor(Math.random()*range);return r;}
function is_char(character){var bool=false;all.filter(function(i){bool=(i===character);});return bool;}
function heComes(text,options){var result='',counts,l;options=options||{};options["up"]=typeof options["up"]!=='undefined'?options["up"]:true;options["mid"]=typeof options["mid"]!=='undefined'?options["mid"]:true;options["down"]=typeof options["down"]!=='undefined'?options["down"]:true;options["size"]=typeof options["size"]!=='undefined'?options["size"]:"maxi";text=text.split('');for(l in text){if(is_char(l)){continue;}
result=result+text[l];counts={"up":0,"down":0,"mid":0};switch(options.size){case'mini':counts.up=randomNumber(8);counts.mid=randomNumber(2);counts.down=randomNumber(8);break;case'maxi':counts.up=randomNumber(16)+3;counts.mid=randomNumber(4)+1;counts.down=randomNumber(64)+3;break;default:counts.up=randomNumber(8)+1;counts.mid=randomNumber(6)/2;counts.down=randomNumber(8)+1;break;}
var arr=["up","mid","down"];for(var d in arr){var index=arr[d];for(var i=0;i<=counts[index];i++){if(options[index]){result=result+soul[index][randomNumber(soul[index].length)];}}}}
return result;}
return heComes(text,options);}};BundleModuleCode['doc/list']=function(module,exports){var NL='\n',SP=' ';function spaces(n){var s='';while(n)s+=SP,n--;return s;}
function List(options){this.type=options.type||'*';this.margin=options.margin||{left:0,right:0,top:0,bottom:0};this.width=options.width||80;this.tab=options.tab||2;this.tab2=options.tab||4;}
List.prototype.__proto__=Array.prototype;List.prototype.render
List.prototype.toString=function(){var i,self=this,ret='',line='',lines=[],label,tokens,textwidth=this.width-this.margin.left-this.margin.right-this.tab;for(i=0;i<this.margin.top;i++)lines.push([]);this.forEach(function(item,index){label=self.type;line=spaces(self.margin.left);switch(label){case'*':case'+':case'-':line+=label+SP;break;case' ':break;case'1':line+=(index+1).toString()+'.'+SP;break;case'2':line+=(index+2).toString()+'.'+SP;break;case'3':line+=(index+3).toString()+'.'+SP;break;case'4':line+=(index+4).toString()+'.'+SP;break;case'5':line+=(index+5).toString()+'.'+SP;break;case'6':line+=(index+6).toString()+'.'+SP;break;case'7':line+=(index+7).toString()+'.'+SP;break;case'8':line+=(index+8).toString()+'.'+SP;break;case'9':line+=(index+9).toString()+'.'+SP;break;case'dl':line+=item.dt+NL;label=undefined;item=item.dd;break;default:break;}
line+=label?spaces(self.tab-label.length-1):spaces(self.tab);if(item.length<textwidth){line+=item;lines.push(line);}else{tokens=item.split(SP);tokens.forEach(function(token){if((line.length+token.length+1)<textwidth)
line+=(token+SP);else{lines.push(line);line=spaces(self.margin.left+self.tab)+token+SP;}});lines.push(line);}});for(i=0;i<this.margin.bottom;i++)lines.push([]);return lines.join(NL);}
module.exports=List;};BundleModuleCode['doc/cli-table']=function(module,exports){var colors=Require('doc/colors'),utils=Require('doc/cli-utils'),repeat=utils.repeat,truncate=utils.truncate,pad=utils.pad;function Table(options){this.options=utils.options({chars:{'top':'─','top-mid':'┬','top-left':'┌','top-right':'┐','bottom':'─','bottom-mid':'┴','bottom-left':'└','bottom-right':'┘','left':'│','left-mid':'├','mid':'─','mid-mid':'┼','right':'│','right-mid':'┤','middle':'│'},truncate:'…',colWidths:[],colAligns:[],style:{'padding-left':1,'padding-right':1,head:['red'],border:['grey'],compact:false},head:[]},options);};Table.prototype.__proto__=Array.prototype;Object.defineProperty(Table.prototype,'width',{get:function(){var str=this.toString().split("\n");if(str.length)return str[0].length;return 0;}});Table.prototype.render
Table.prototype.toString=function(){var ret='',options=this.options,style=options.style,head=options.head,chars=options.chars,truncater=options.truncate,colWidths=options.colWidths||new Array(this.head.length),totalWidth=0;if(!head.length&&!this.length)return'';if(!colWidths.length){var all_rows=this.slice(0);if(head.length){all_rows=all_rows.concat([head])};all_rows.forEach(function(cells){if(typeof cells==='object'&&cells.length){extractColumnWidths(cells);}else{var header_cell=Object.keys(cells)[0],value_cell=cells[header_cell];colWidths[0]=Math.max(colWidths[0]||0,get_width(header_cell)||0);if(typeof value_cell==='object'&&value_cell.length){extractColumnWidths(value_cell,1);}else{colWidths[1]=Math.max(colWidths[1]||0,get_width(value_cell)||0);}}});};totalWidth=(colWidths.length==1?colWidths[0]:colWidths.reduce(function(a,b){return a+b}))+colWidths.length+1;function extractColumnWidths(arr,offset){var offset=offset||0;arr.forEach(function(cell,i){colWidths[i+offset]=Math.max(colWidths[i+offset]||0,get_width(cell)||0);});};function get_width(obj){return typeof obj=='object'&&obj&&obj.width!=undefined?obj.width:((typeof obj=='object'&&obj!==null?utils.strlen(obj.text):utils.strlen(obj))+(style['padding-left']||0)+(style['padding-right']||0))}
function line(line,left,right,intersection){var width=0,line=left
+repeat(line,totalWidth-2)
+right;colWidths.forEach(function(w,i){if(i==colWidths.length-1)return;width+=w+1;line=line.substr(0,width)+intersection+line.substr(width+1);});return applyStyles(options.style.border,line);};function lineTop(){var l=line(chars.top,chars['top-left']||chars.top,chars['top-right']||chars.top,chars['top-mid']);if(l)
ret+=l+"\n";};function generateRow(items,style){var cells=[],max_height=0;if(!Array.isArray(items)&&typeof items==="object"){var key=Object.keys(items)[0],value=items[key],first_cell_head=true;if(Array.isArray(value)){items=value;items.unshift(key);}else{items=[key,value];}}
items.forEach(function(item,i){var contents=(item==null?'':item).toString().split("\n").reduce(function(memo,l){memo.push(string(l,i));return memo;},[])
var height=contents.length;if(height>max_height){max_height=height};cells.push({contents:contents,height:height});});var lines=new Array(max_height);cells.forEach(function(cell,i){cell.contents.forEach(function(line,j){if(!lines[j]){lines[j]=[]};if(style||(first_cell_head&&i===0&&options.style.head)){line=applyStyles(options.style.head,line)}
lines[j].push(line);});for(var j=cell.height,l=max_height;j<l;j++){if(!lines[j]){lines[j]=[]};lines[j].push(string('',i));}});var ret="";lines.forEach(function(line,index){if(ret.length>0){ret+="\n"+applyStyles(options.style.border,chars.left);}
ret+=line.join(applyStyles(options.style.border,chars.middle))+applyStyles(options.style.border,chars.right);});return applyStyles(options.style.border,chars.left)+ret;};function applyStyles(styles,subject){if(!subject)
return'';styles.forEach(function(style){subject=colors[style](subject);});return subject;};function string(str,index){var str=String(typeof str=='object'&&str.text?str.text:str),length=utils.strlen(str),width=colWidths[index]
-(style['padding-left']||0)
-(style['padding-right']||0),align=options.colAligns[index]||'left';return repeat(' ',style['padding-left']||0)
+(length==width?str:(length<width?pad(str,(width+(str.length-length)),' ',align=='left'?'right':(align=='middle'?'both':'left')):(truncater?truncate(str,width,truncater):str)))
+repeat(' ',style['padding-right']||0);};if(head.length){lineTop();ret+=generateRow(head,style.head)+"\n"}
if(this.length)
this.forEach(function(cells,i){if(!head.length&&i==0)
lineTop();else{if(!style.compact||i<(!!head.length)?1:0||cells.length==0){var l=line(chars.mid,chars['left-mid'],chars['right-mid'],chars['mid-mid']);if(l)
ret+=l+"\n"}}
if(cells.hasOwnProperty("length")&&!cells.length){return}else{ret+=generateRow(cells)+"\n";};});var l=line(chars.bottom,chars['bottom-left']||chars.bottom,chars['bottom-right']||chars.bottom,chars['bottom-mid']);if(l)
ret+=l;else
ret=ret.slice(0,-1);return ret;};module.exports=Table;module.exports.version='0.0.1';};BundleModuleCode['doc/cli-utils']=function(module,exports){exports.repeat=function(str,times){return Array(times+1).join(str);};exports.pad=function(str,len,pad,dir){if(len+1>=str.length)
switch(dir){case'left':str=Array(len+1-str.length).join(pad)+str;break;case'both':var right=Math.ceil((padlen=len-str.length)/2);var left=padlen-right;str=Array(left+1).join(pad)+str+Array(right+1).join(pad);break;default:str=str+Array(len+1-str.length).join(pad);};return str;};exports.truncate=function(str,length,chr){chr=chr||'…';return str.length>=length?str.substr(0,length-chr.length)+chr:str;};function options(defaults,opts){for(var p in opts){if(opts[p]&&opts[p].constructor&&opts[p].constructor===Object){defaults[p]=defaults[p]||{};options(defaults[p],opts[p]);}else{defaults[p]=opts[p];}}
return defaults;};exports.options=options;exports.strlen=function(str){var code=/\u001b\[(?:\d*;){0,5}\d*m/g;var stripped=(""+(str!=null?str:'')).replace(code,'');var split=stripped.split("\n");return split.reduce(function(memo,s){return(s.length>memo)?s.length:memo},0);}};BundleModuleCode['doc/table']=function(module,exports){var doc=Require('doc/doc');var com=Require('com/compat');function Table(data,options){var totalWidth=(process.stdout.columns)-2;if(com.obj.isArray(options))options={head:options};options=options||{};var head=options.head,table;if(com.obj.isMatrix(data)){}else if(com.obj.isArray(data)&&com.obj.isObject(data[0])){options.head=true;head=Object.keys(data[0]);data=data.map(function(row){return head.map(function(key){return row[key]})});}else return new Error('Table: Inavlid data');if(!options.colWidths){totalWidth-=((head||data[0]).length-1);options.colWidths=(head||data[0]).map(function(x,i){return Math.max(4,Math.floor(totalWidth/(head||data[0]).length));});}
if(head)
table=new doc.Table({head:head,colWidths:options.colWidths,});else
table=new doc.Table({colWidths:options.colWidths,});data.forEach(function(row,rowi){table.push(row);});print(table.toString());}
module.exports=Table;};BundleModuleCode['com/readline']=function(module,exports){var kHistorySize=30;var util=Require('util');var Buffer=Require('buffer').Buffer;var inherits=Require('util').inherits;var EventEmitter=Require('events').EventEmitter;var StringDecoder=Require('string_decoder').StringDecoder;EventEmitter._listenerCount=EventEmitter._listenerCount||function(ee,event){var listeners=ee&&ee._events&&ee._events[event]
if(Array.isArray(listeners)){return listeners.length}else if(typeof listeners==='function'){return 1}else{return 0}}
exports.createInterface=function(input,output,completer,terminal){var rl;if(arguments.length===1){rl=new Interface(input);}else{rl=new Interface(input,output,completer,terminal);}
return rl;};function Interface(input,output,completer,terminal){if(!(this instanceof Interface)){return new Interface(input,output,completer,terminal);}
this._sawReturn=false;EventEmitter.call(this);if(arguments.length===1){output=input.output;completer=input.completer;terminal=input.terminal;input=input.input;}
completer=completer||function(){return[];};if(!util.isFunction(completer)){throw new TypeError('Argument \'completer\' must be a function');}
if(util.isUndefined(terminal)&&!util.isNullOrUndefined(output)){terminal=!!output.isTTY;}
var self=this;this.output=output;this.input=input;this.completer=completer.length===2?completer:function(v,callback){callback(null,completer(v));};this.setPrompt('> ');this.terminal=!!terminal;function ondata(data){self._normalWrite(data);}
function onend(){if(util.isString(self._line_buffer)&&self._line_buffer.length>0){self.emit('line',self._line_buffer);}
self.close();}
function ontermend(){if(util.isString(self.line)&&self.line.length>0){self.emit('line',self.line);}
self.close();}
function onkeypress(s,key){self._ttyWrite(s,key);}
function onresize(){self._refreshLine();}
if(!this.terminal){input.on('data',ondata);input.on('end',onend);self.once('close',function(){input.removeListener('data',ondata);input.removeListener('end',onend);});this._decoder=new StringDecoder('utf8');}else{exports.emitKeypressEvents(input);input.on('keypress',onkeypress);input.on('end',ontermend);this.line='';this._setRawMode(true);this.terminal=true;this.cursor=0;this.history=[];this.historyIndex=-1;if(!util.isNullOrUndefined(output))
output.on('resize',onresize);self.once('close',function(){input.removeListener('keypress',onkeypress);input.removeListener('end',ontermend);if(!util.isNullOrUndefined(output)){output.removeListener('resize',onresize);}});}
input.resume();}
inherits(Interface,EventEmitter);Object.defineProperty(Interface.prototype,'columns',{get:function(){var columns=Infinity;if(this.output&&this.output.columns)
columns=this.output.columns;return columns;}});Interface.prototype.setPrompt=function(prompt){this._prompt=prompt;};Interface.prototype._setRawMode=function(mode){if(util.isFunction(this.input.setRawMode)){return this.input.setRawMode(mode);}};Interface.prototype.prompt=function(preserveCursor){if(this.paused)this.resume();if(this.terminal){if(!preserveCursor)this.cursor=0;this._refreshLine();}else{this._writeToOutput(this._prompt);}};Interface.prototype.question=function(query,cb){if(util.isFunction(cb)){if(this._questionCallback){this.prompt();}else{this._oldPrompt=this._prompt;this.setPrompt(query);this._questionCallback=cb;this.prompt();}}};Interface.prototype._onLine=function(line){if(this._questionCallback){var cb=this._questionCallback;this._questionCallback=null;this.setPrompt(this._oldPrompt);cb(line);}else{this.emit('line',line);}};Interface.prototype._writeToOutput=function _writeToOutput(stringToWrite){if(!util.isString(stringToWrite))
throw new TypeError('stringToWrite must be a string');if(!util.isNullOrUndefined(this.output))
this.output.write(stringToWrite);};Interface.prototype._addHistory=function(){if(this.line.length===0)return'';if(this.history.length===0||this.history[0]!==this.line){this.history.unshift(this.line);if(this.history.length>kHistorySize)this.history.pop();}
this.historyIndex=-1;return this.history[0];};Interface.prototype._refreshLine=function(){var line=this._prompt+this.line;var dispPos=this._getDisplayPos(line);var lineCols=dispPos.cols;var lineRows=dispPos.rows;var cursorPos=this._getCursorPos();var prevRows=this.prevRows||0;if(prevRows>0){exports.moveCursor(this.output,0,-prevRows);}
exports.cursorTo(this.output,0);exports.clearScreenDown(this.output);this._writeToOutput(line);if(lineCols===0){this._writeToOutput(' ');}
exports.cursorTo(this.output,cursorPos.cols);var diff=lineRows-cursorPos.rows;if(diff>0){exports.moveCursor(this.output,0,-diff);}
this.prevRows=cursorPos.rows;};Interface.prototype.close=function(){if(this.closed)return;this.pause();if(this.terminal){this._setRawMode(false);}
this.closed=true;this.emit('close');};Interface.prototype.pause=function(){if(this.paused)return;this.input.pause();this.paused=true;this.emit('pause');return this;};Interface.prototype.resume=function(){if(!this.paused)return;this.input.resume();this.paused=false;this.emit('resume');return this;};Interface.prototype.write=function(d,key){if(this.paused)this.resume();this.terminal?this._ttyWrite(d,key):this._normalWrite(d);};var lineEnding=/\r?\n|\r(?!\n)/;Interface.prototype._normalWrite=function(b){if(util.isUndefined(b)){return;}
var string=this._decoder.write(b);if(this._sawReturn){string=string.replace(/^\n/,'');this._sawReturn=false;}
var newPartContainsEnding=lineEnding.test(string);if(this._line_buffer){string=this._line_buffer+string;this._line_buffer=null;}
if(newPartContainsEnding){this._sawReturn=/\r$/.test(string);var lines=string.split(lineEnding);string=lines.pop();this._line_buffer=string;lines.forEach(function(line){this._onLine(line);},this);}else if(string){this._line_buffer=string;}};Interface.prototype._insertString=function(c){if(this.cursor<this.line.length){var beg=this.line.slice(0,this.cursor);var end=this.line.slice(this.cursor,this.line.length);this.line=beg+c+end;this.cursor+=c.length;this._refreshLine();}else{this.line+=c;this.cursor+=c.length;if(this._getCursorPos().cols===0){this._refreshLine();}else{this._writeToOutput(c);}
this._moveCursor(0);}};Interface.prototype._tabComplete=function(){var self=this;self.pause();self.completer(self.line.slice(0,self.cursor),function(err,rv){self.resume();if(err){return;}
var completions=rv[0],completeOn=rv[1];if(completions&&completions.length){if(completions.length===1){self._insertString(completions[0].slice(completeOn.length));}else{self._writeToOutput('\r\n');var width=completions.reduce(function(a,b){return a.length>b.length?a:b;}).length+2;var maxColumns=Math.floor(self.columns/width)||1;var group=[],c;for(var i=0,compLen=completions.length;i<compLen;i++){c=completions[i];if(c===''){handleGroup(self,group,width,maxColumns);group=[];}else{group.push(c);}}
handleGroup(self,group,width,maxColumns);var f=completions.filter(function(e){if(e)return e;});var prefix=commonPrefix(f);if(prefix.length>completeOn.length){self._insertString(prefix.slice(completeOn.length));}}
self._refreshLine();}});};function handleGroup(self,group,width,maxColumns){if(group.length==0){return;}
var minRows=Math.ceil(group.length/maxColumns);for(var row=0;row<minRows;row++){for(var col=0;col<maxColumns;col++){var idx=row*maxColumns+col;if(idx>=group.length){break;}
var item=group[idx];self._writeToOutput(item);if(col<maxColumns-1){for(var s=0,itemLen=item.length;s<width-itemLen;s++){self._writeToOutput(' ');}}}
self._writeToOutput('\r\n');}
self._writeToOutput('\r\n');}
function commonPrefix(strings){if(!strings||strings.length==0){return'';}
var sorted=strings.slice().sort();var min=sorted[0];var max=sorted[sorted.length-1];for(var i=0,len=min.length;i<len;i++){if(min[i]!=max[i]){return min.slice(0,i);}}
return min;}
Interface.prototype._wordLeft=function(){if(this.cursor>0){var leading=this.line.slice(0,this.cursor);var match=leading.match(/([^\w\s]+|\w+|)\s*$/);this._moveCursor(-match[0].length);}};Interface.prototype._wordRight=function(){if(this.cursor<this.line.length){var trailing=this.line.slice(this.cursor);var match=trailing.match(/^(\s+|\W+|\w+)\s*/);this._moveCursor(match[0].length);}};Interface.prototype._deleteLeft=function(){if(this.cursor>0&&this.line.length>0){this.line=this.line.slice(0,this.cursor-1)+
this.line.slice(this.cursor,this.line.length);this.cursor--;this._refreshLine();}};Interface.prototype._deleteRight=function(){this.line=this.line.slice(0,this.cursor)+
this.line.slice(this.cursor+1,this.line.length);this._refreshLine();};Interface.prototype._deleteWordLeft=function(){if(this.cursor>0){var leading=this.line.slice(0,this.cursor);var match=leading.match(/([^\w\s]+|\w+|)\s*$/);leading=leading.slice(0,leading.length-match[0].length);this.line=leading+this.line.slice(this.cursor,this.line.length);this.cursor=leading.length;this._refreshLine();}};Interface.prototype._deleteWordRight=function(){if(this.cursor<this.line.length){var trailing=this.line.slice(this.cursor);var match=trailing.match(/^(\s+|\W+|\w+)\s*/);this.line=this.line.slice(0,this.cursor)+
trailing.slice(match[0].length);this._refreshLine();}};Interface.prototype._deleteLineLeft=function(){this.line=this.line.slice(this.cursor);this.cursor=0;this._refreshLine();};Interface.prototype._deleteLineRight=function(){this.line=this.line.slice(0,this.cursor);this._refreshLine();};Interface.prototype.clearLine=function(){this._moveCursor(+Infinity);this._writeToOutput('\r\n');this.line='';this.cursor=0;this.prevRows=0;};Interface.prototype.getLine=function(){return this.line;};Interface.prototype.insertOutput=function(msg){this._moveCursor(+Infinity);this._writeToOutput('\r');this._writeToOutput(msg+'\n');this._writeToOutput(this._prompt+this.line);};Interface.prototype._line=function(){var line=this._addHistory();this.clearLine();this._onLine(line);};Interface.prototype._historyNext=function(){if(this.historyIndex>0){this.historyIndex--;this.line=this.history[this.historyIndex];this.cursor=this.line.length;this._refreshLine();}else if(this.historyIndex===0){this.historyIndex=-1;this.cursor=0;this.line='';this._refreshLine();}};Interface.prototype._historyPrev=function(){if(this.historyIndex+1<this.history.length){this.historyIndex++;this.line=this.history[this.historyIndex];this.cursor=this.line.length;this._refreshLine();}};Interface.prototype._getDisplayPos=function(str){var offset=0;var col=this.columns;var row=0;var code;str=stripVTControlCharacters(str);for(var i=0,len=str.length;i<len;i++){code=codePointAt(str,i);if(code>=0x10000){i++;}
if(code===0x0a){offset=0;row+=1;continue;}
if(isFullWidthCodePoint(code)){if((offset+1)%col===0){offset++;}
offset+=2;}else{offset++;}}
var cols=offset%col;var rows=row+(offset-cols)/col;return{cols:cols,rows:rows};};Interface.prototype._getCursorPos=function(){var columns=this.columns;var strBeforeCursor=this._prompt+this.line.substring(0,this.cursor);var dispPos=this._getDisplayPos(stripVTControlCharacters(strBeforeCursor));var cols=dispPos.cols;var rows=dispPos.rows;if(cols+1===columns&&this.cursor<this.line.length&&isFullWidthCodePoint(codePointAt(this.line,this.cursor))){rows++;cols=0;}
return{cols:cols,rows:rows};};Interface.prototype._moveCursor=function(dx){var oldcursor=this.cursor;var oldPos=this._getCursorPos();this.cursor+=dx;if(this.cursor<0)this.cursor=0;else if(this.cursor>this.line.length)this.cursor=this.line.length;var newPos=this._getCursorPos();if(oldPos.rows===newPos.rows){var diffCursor=this.cursor-oldcursor;var diffWidth;if(diffCursor<0){diffWidth=-getStringWidth(this.line.substring(this.cursor,oldcursor));}else if(diffCursor>0){diffWidth=getStringWidth(this.line.substring(this.cursor,oldcursor));}
exports.moveCursor(this.output,diffWidth,0);this.prevRows=newPos.rows;}else{this._refreshLine();}};Interface.prototype._ttyWrite=function(s,key){key=key||{};if(key.name=='escape')return;if(key.ctrl&&key.shift){switch(key.name){case'backspace':this._deleteLineLeft();break;case'delete':this._deleteLineRight();break;}}else if(key.ctrl){switch(key.name){case'c':if(EventEmitter.listenerCount(this,'SIGINT')>0){this.emit('SIGINT');}else{this.close();}
break;case'h':this._deleteLeft();break;case'd':if(this.cursor===0&&this.line.length===0){this.close();}else if(this.cursor<this.line.length){this._deleteRight();}
break;case'u':this.cursor=0;this.line='';this._refreshLine();break;case'k':this._deleteLineRight();break;case'a':this._moveCursor(-Infinity);break;case'e':this._moveCursor(+Infinity);break;case'b':this._moveCursor(-1);break;case'f':this._moveCursor(+1);break;case'l':exports.cursorTo(this.output,0,0);exports.clearScreenDown(this.output);this._refreshLine();break;case'n':this._historyNext();break;case'p':this._historyPrev();break;case'z':if(process.platform=='win32')break;if(EventEmitter.listenerCount(this,'SIGTSTP')>0){this.emit('SIGTSTP');}else{process.once('SIGCONT',(function(self){return function(){if(!self.paused){self.pause();self.emit('SIGCONT');}
self._setRawMode(true);self._refreshLine();};})(this));this._setRawMode(false);process.kill(process.pid,'SIGTSTP');}
break;case'w':case'backspace':this._deleteWordLeft();break;case'delete':this._deleteWordRight();break;case'left':this._wordLeft();break;case'right':this._wordRight();break;}}else if(key.meta){switch(key.name){case'b':this._wordLeft();break;case'f':this._wordRight();break;case'd':case'delete':this._deleteWordRight();break;case'backspace':this._deleteWordLeft();break;}}else{if(this._sawReturn&&key.name!=='enter')
this._sawReturn=false;switch(key.name){case'return':this._sawReturn=true;this._line();break;case'enter':if(this._sawReturn)
this._sawReturn=false;else
this._line();break;case'backspace':this._deleteLeft();break;case'delete':this._deleteRight();break;case'tab':this._tabComplete();break;case'left':this._moveCursor(-1);break;case'right':this._moveCursor(+1);break;case'home':this._moveCursor(-Infinity);break;case'end':this._moveCursor(+Infinity);break;case'up':this._historyPrev();break;case'down':this._historyNext();break;default:if(util.isBuffer(s))
s=s.toString('utf-8');if(s){var lines=s.split(/\r\n|\n|\r/);for(var i=0,len=lines.length;i<len;i++){if(i>0){this._line();}
this._insertString(lines[i]);}}}}};exports.Interface=Interface;function emitKeypressEvents(stream){if(stream._keypressDecoder)return;var StringDecoder=Require('string_decoder').StringDecoder;stream._keypressDecoder=new StringDecoder('utf8');function onData(b){if(EventEmitter.listenerCount(stream,'keypress')>0){var r=stream._keypressDecoder.write(b);if(r)emitKeys(stream,r);}else{stream.removeListener('data',onData);stream.on('newListener',onNewListener);}}
function onNewListener(event){if(event=='keypress'){stream.on('data',onData);stream.removeListener('newListener',onNewListener);}}
if(EventEmitter.listenerCount(stream,'keypress')>0){stream.on('data',onData);}else{stream.on('newListener',onNewListener);}}
exports.emitKeypressEvents=emitKeypressEvents;var metaKeyCodeReAnywhere=/(?:\x1b)([a-zA-Z0-9])/;var metaKeyCodeRe=new RegExp('^'+metaKeyCodeReAnywhere.source+'$');var functionKeyCodeReAnywhere=new RegExp('(?:\x1b+)(O|N|\\[|\\[\\[)(?:'+['(\\d+)(?:;(\\d+))?([~^$])','(?:M([@ #!a`])(.)(.))','(?:1;)?(\\d+)?([a-zA-Z])'].join('|')+')');var functionKeyCodeRe=new RegExp('^'+functionKeyCodeReAnywhere.source);var escapeCodeReAnywhere=new RegExp([functionKeyCodeReAnywhere.source,metaKeyCodeReAnywhere.source,/\x1b./.source].join('|'));function emitKeys(stream,s){if(util.isBuffer(s)){if(s[0]>127&&util.isUndefined(s[1])){s[0]-=128;s='\x1b'+s.toString(stream.encoding||'utf-8');}else{s=s.toString(stream.encoding||'utf-8');}}
var buffer=[];var match;while(match=escapeCodeReAnywhere.exec(s)){buffer=buffer.concat(s.slice(0,match.index).split(''));buffer.push(match[0]);s=s.slice(match.index+match[0].length);}
buffer=buffer.concat(s.split(''));buffer.forEach(function(s){var ch,key={sequence:s,name:undefined,ctrl:false,meta:false,shift:false},parts;if(s==='\r'){key.name='return';}else if(s==='\n'){key.name='enter';}else if(s==='\t'){key.name='tab';}else if(s==='\b'||s==='\x7f'||s==='\x1b\x7f'||s==='\x1b\b'){key.name='backspace';key.meta=(s.charAt(0)==='\x1b');}else if(s==='\x1b'||s==='\x1b\x1b'){key.name='escape';key.meta=(s.length===2);}else if(s===' '||s==='\x1b '){key.name='space';key.meta=(s.length===2);}else if(s.length===1&&s<='\x1a'){key.name=String.fromCharCode(s.charCodeAt(0)+'a'.charCodeAt(0)-1);key.ctrl=true;}else if(s.length===1&&s>='a'&&s<='z'){key.name=s;}else if(s.length===1&&s>='A'&&s<='Z'){key.name=s.toLowerCase();key.shift=true;}else if(parts=metaKeyCodeRe.exec(s)){key.name=parts[1].toLowerCase();key.meta=true;key.shift=/^[A-Z]$/.test(parts[1]);}else if(parts=functionKeyCodeRe.exec(s)){var code=(parts[1]||'')+(parts[2]||'')+
(parts[4]||'')+(parts[9]||''),modifier=(parts[3]||parts[8]||1)-1;key.ctrl=!!(modifier&4);key.meta=!!(modifier&10);key.shift=!!(modifier&1);key.code=code;switch(code){case'OP':key.name='f1';break;case'OQ':key.name='f2';break;case'OR':key.name='f3';break;case'OS':key.name='f4';break;case'[11~':key.name='f1';break;case'[12~':key.name='f2';break;case'[13~':key.name='f3';break;case'[14~':key.name='f4';break;case'[[A':key.name='f1';break;case'[[B':key.name='f2';break;case'[[C':key.name='f3';break;case'[[D':key.name='f4';break;case'[[E':key.name='f5';break;case'[15~':key.name='f5';break;case'[17~':key.name='f6';break;case'[18~':key.name='f7';break;case'[19~':key.name='f8';break;case'[20~':key.name='f9';break;case'[21~':key.name='f10';break;case'[23~':key.name='f11';break;case'[24~':key.name='f12';break;case'[A':key.name='up';break;case'[B':key.name='down';break;case'[C':key.name='right';break;case'[D':key.name='left';break;case'[E':key.name='clear';break;case'[F':key.name='end';break;case'[H':key.name='home';break;case'OA':key.name='up';break;case'OB':key.name='down';break;case'OC':key.name='right';break;case'OD':key.name='left';break;case'OE':key.name='clear';break;case'OF':key.name='end';break;case'OH':key.name='home';break;case'[1~':key.name='home';break;case'[2~':key.name='insert';break;case'[3~':key.name='delete';break;case'[4~':key.name='end';break;case'[5~':key.name='pageup';break;case'[6~':key.name='pagedown';break;case'[[5~':key.name='pageup';break;case'[[6~':key.name='pagedown';break;case'[7~':key.name='home';break;case'[8~':key.name='end';break;case'[a':key.name='up';key.shift=true;break;case'[b':key.name='down';key.shift=true;break;case'[c':key.name='right';key.shift=true;break;case'[d':key.name='left';key.shift=true;break;case'[e':key.name='clear';key.shift=true;break;case'[2$':key.name='insert';key.shift=true;break;case'[3$':key.name='delete';key.shift=true;break;case'[5$':key.name='pageup';key.shift=true;break;case'[6$':key.name='pagedown';key.shift=true;break;case'[7$':key.name='home';key.shift=true;break;case'[8$':key.name='end';key.shift=true;break;case'Oa':key.name='up';key.ctrl=true;break;case'Ob':key.name='down';key.ctrl=true;break;case'Oc':key.name='right';key.ctrl=true;break;case'Od':key.name='left';key.ctrl=true;break;case'Oe':key.name='clear';key.ctrl=true;break;case'[2^':key.name='insert';key.ctrl=true;break;case'[3^':key.name='delete';key.ctrl=true;break;case'[5^':key.name='pageup';key.ctrl=true;break;case'[6^':key.name='pagedown';key.ctrl=true;break;case'[7^':key.name='home';key.ctrl=true;break;case'[8^':key.name='end';key.ctrl=true;break;case'[Z':key.name='tab';key.shift=true;break;default:key.name='undefined';break;}}
if(util.isUndefined(key.name)){key=undefined;}
if(s.length===1){ch=s;}
if(key||ch){stream.emit('keypress',ch,key);}});}
function cursorTo(stream,x,y){if(util.isNullOrUndefined(stream))
return;if(!util.isNumber(x)&&!util.isNumber(y))
return;if(!util.isNumber(x))
throw new Error("Can't set cursor row without also setting it's column");if(!util.isNumber(y)){stream.write('\x1b['+(x+1)+'G');}else{stream.write('\x1b['+(y+1)+';'+(x+1)+'H');}}
exports.cursorTo=cursorTo;function moveCursor(stream,dx,dy){if(util.isNullOrUndefined(stream))
return;if(dx<0){stream.write('\x1b['+(-dx)+'D');}else if(dx>0){stream.write('\x1b['+dx+'C');}
if(dy<0){stream.write('\x1b['+(-dy)+'A');}else if(dy>0){stream.write('\x1b['+dy+'B');}}
exports.moveCursor=moveCursor;function clearLine(stream,dir){if(util.isNullOrUndefined(stream))
return;if(dir<0){stream.write('\x1b[1K');}else if(dir>0){stream.write('\x1b[0K');}else{stream.write('\x1b[2K');}}
exports.clearLine=clearLine;function clearScreenDown(stream){if(util.isNullOrUndefined(stream))
return;stream.write('\x1b[0J');}
exports.clearScreenDown=clearScreenDown;function getStringWidth(str){var width=0;str=stripVTControlCharacters(str);for(var i=0,len=str.length;i<len;i++){var code=codePointAt(str,i);if(code>=0x10000){i++;}
if(isFullWidthCodePoint(code)){width+=2;}else{width++;}}
return width;}
exports.getStringWidth=getStringWidth;function isFullWidthCodePoint(code){if(isNaN(code)){return false;}
if(code>=0x1100&&(code<=0x115f||0x2329===code||0x232a===code||(0x2e80<=code&&code<=0x3247&&code!==0x303f)||0x3250<=code&&code<=0x4dbf||0x4e00<=code&&code<=0xa4c6||0xa960<=code&&code<=0xa97c||0xac00<=code&&code<=0xd7a3||0xf900<=code&&code<=0xfaff||0xfe10<=code&&code<=0xfe19||0xfe30<=code&&code<=0xfe6b||0xff01<=code&&code<=0xff60||0xffe0<=code&&code<=0xffe6||0x1b000<=code&&code<=0x1b001||0x1f200<=code&&code<=0x1f251||0x20000<=code&&code<=0x3fffd)){return true;}
return false;}
exports.isFullWidthCodePoint=isFullWidthCodePoint;function codePointAt(str,index){var code=str.charCodeAt(index);var low;if(0xd800<=code&&code<=0xdbff){low=str.charCodeAt(index+1);if(!isNaN(low)){code=0x10000+(code-0xd800)*0x400+(low-0xdc00);}}
return code;}
exports.codePointAt=codePointAt;function stripVTControlCharacters(str){str=str.replace(new RegExp(functionKeyCodeReAnywhere.source,'g'),'');return str.replace(new RegExp(metaKeyCodeReAnywhere.source,'g'),'');}
exports.stripVTControlCharacters=stripVTControlCharacters;};BundleModuleCode['term/readlineSync']=function(module,exports){'use strict';var
IS_WIN=process.platform==='win32',ALGORITHM_CIPHER='aes-256-cbc',ALGORITHM_HASH='sha256',DEFAULT_ERR_MSG='The current environment doesn\'t support interactive reading from TTY.',fs=require('fs'),TTY=process.binding('tty_wrap').TTY,childProc=require('child_process'),pathUtil=require('path'),defaultOptions={prompt:'> ',hideEchoBack:false,mask:'*',limit:[],limitMessage:'Input another, please.$<( [)limit(])>',defaultInput:'',trueValue:[],falseValue:[],caseSensitive:false,keepWhitespace:false,encoding:'utf8',bufferSize:1024,print:void 0,history:true,cd:false,phContent:void 0,preCheck:void 0},fdR='none',fdW,ttyR,isRawMode=false,extHostPath,extHostArgs,tempdir,salt=0,lastInput='',inputHistory=[],rawInput,_DBG_useExt=false,_DBG_checkOptions=false,_DBG_checkMethod=false;function getHostArgs(options){function encodeArg(arg){return arg.replace(/[^\w\u0080-\uFFFF]/g,function(chr){return'#'+chr.charCodeAt(0)+';';});}
return extHostArgs.concat((function(conf){var args=[];Object.keys(conf).forEach(function(optionName){if(conf[optionName]==='boolean'){if(options[optionName]){args.push('--'+optionName);}}else if(conf[optionName]==='string'){if(options[optionName]){args.push('--'+optionName,encodeArg(options[optionName]));}}});return args;})({display:'string',displayOnly:'boolean',keyIn:'boolean',hideEchoBack:'boolean',mask:'string',limit:'string',caseSensitive:'boolean'}));}
function _execFileSync(options,execOptions){function getTempfile(name){var filepath,suffix='',fd;tempdir=tempdir||require('os').tmpdir();while(true){filepath=pathUtil.join(tempdir,name+suffix);try{fd=fs.openSync(filepath,'wx');}catch(e){if(e.code==='EEXIST'){suffix++;continue;}else{throw e;}}
fs.closeSync(fd);break;}
return filepath;}
var hostArgs,shellPath,shellArgs,res={},exitCode,extMessage,pathStdout=getTempfile('readline-sync.stdout'),pathStderr=getTempfile('readline-sync.stderr'),pathExit=getTempfile('readline-sync.exit'),pathDone=getTempfile('readline-sync.done'),crypto=require('crypto'),shasum,decipher,password;shasum=crypto.createHash(ALGORITHM_HASH);shasum.update(''+process.pid+(salt++)+Math.random());password=shasum.digest('hex');decipher=crypto.createDecipher(ALGORITHM_CIPHER,password);hostArgs=getHostArgs(options);if(IS_WIN){shellPath=process.env.ComSpec||'cmd.exe';process.env.Q='"';shellArgs=['/V:ON','/S','/C','(%Q%'+shellPath+'%Q% /V:ON /S /C %Q%'+'%Q%'+extHostPath+'%Q%'+
hostArgs.map(function(arg){return' %Q%'+arg+'%Q%';}).join('')+' & (echo !ERRORLEVEL!)>%Q%'+pathExit+'%Q%%Q%) 2>%Q%'+pathStderr+'%Q%'+' |%Q%'+process.execPath+'%Q% %Q%'+__dirname+'\\encrypt.js%Q%'+' %Q%'+ALGORITHM_CIPHER+'%Q% %Q%'+password+'%Q%'+' >%Q%'+pathStdout+'%Q%'+' & (echo 1)>%Q%'+pathDone+'%Q%'];}else{shellPath='/bin/sh';shellArgs=['-c','("'+extHostPath+'"'+
hostArgs.map(function(arg){return" '"+arg.replace(/'/g,"'\\''")+"'";}).join('')+'; echo $?>"'+pathExit+'") 2>"'+pathStderr+'"'+' |"'+process.execPath+'" "'+__dirname+'/encrypt.js"'+' "'+ALGORITHM_CIPHER+'" "'+password+'"'+' >"'+pathStdout+'"'+'; echo 1 >"'+pathDone+'"'];}
if(_DBG_checkMethod){_DBG_checkMethod('_execFileSync',hostArgs);}
try{childProc.spawn(shellPath,shellArgs,execOptions);}catch(e){res.error=new Error(e.message);res.error.method='_execFileSync - spawn';res.error.program=shellPath;res.error.args=shellArgs;}
while(fs.readFileSync(pathDone,{encoding:options.encoding}).trim()!=='1'){}
if((exitCode=fs.readFileSync(pathExit,{encoding:options.encoding}).trim())==='0'){res.input=decipher.update(fs.readFileSync(pathStdout,{encoding:'binary'}),'hex',options.encoding)+
decipher.final(options.encoding);}else{extMessage=fs.readFileSync(pathStderr,{encoding:options.encoding}).trim();res.error=new Error(DEFAULT_ERR_MSG+(extMessage?'\n'+extMessage:''));res.error.method='_execFileSync';res.error.program=shellPath;res.error.args=shellArgs;res.error.extMessage=extMessage;res.error.exitCode=+exitCode;}
fs.unlinkSync(pathStdout);fs.unlinkSync(pathStderr);fs.unlinkSync(pathExit);fs.unlinkSync(pathDone);return res;}
function readlineExt(options){var hostArgs,res={},extMessage,execOptions={env:process.env,encoding:options.encoding};if(!extHostPath){if(IS_WIN){if(process.env.PSModulePath){extHostPath='powershell.exe';extHostArgs=['-ExecutionPolicy','Bypass','-File',__dirname+'\\read.ps1'];}else{extHostPath='cscript.exe';extHostArgs=['//nologo',__dirname+'\\read.cs.js'];}}else{extHostPath='/bin/sh';extHostArgs=[__dirname+'/read.sh'];}}
if(IS_WIN&&!process.env.PSModulePath){execOptions.stdio=[process.stdin];}
if(childProc.execFileSync){hostArgs=getHostArgs(options);if(_DBG_checkMethod){_DBG_checkMethod('execFileSync',hostArgs);}
try{res.input=childProc.execFileSync(extHostPath,hostArgs,execOptions);}catch(e){extMessage=e.stderr?(e.stderr+'').trim():'';res.error=new Error(DEFAULT_ERR_MSG+(extMessage?'\n'+extMessage:''));res.error.method='execFileSync';res.error.program=extHostPath;res.error.args=hostArgs;res.error.extMessage=extMessage;res.error.exitCode=e.status;res.error.code=e.code;res.error.signal=e.signal;}}else{res=_execFileSync(options,execOptions);}
if(!res.error){res.input=res.input.replace(/^\s*'|'\s*$/g,'');options.display='';}
return res;}
function _readlineSync(options){var input='',displaySave=options.display,silent=!options.display&&options.keyIn&&options.hideEchoBack&&!options.mask;function tryExt(){var res=readlineExt(options);if(res.error){throw res.error;}
return res.input;}
if(_DBG_checkOptions){_DBG_checkOptions(options);}
(function(){var fsB,constants,verNum;function getFsB(){if(!fsB){fsB=process.binding('fs');constants=process.binding('constants');}
return fsB;}
if(typeof fdR!=='string'){return;}
fdR=null;if(IS_WIN){verNum=(function(ver){var nums=ver.replace(/^\D+/,'').split('.');var verNum=0;if((nums[0]=+nums[0])){verNum+=nums[0]*10000;}
if((nums[1]=+nums[1])){verNum+=nums[1]*100;}
if((nums[2]=+nums[2])){verNum+=nums[2];}
return verNum;})(process.version);if(!(verNum>=20302&&verNum<40204||verNum>=50000&&verNum<50100||verNum>=50600&&verNum<60200)&&process.stdin.isTTY){process.stdin.pause();fdR=process.stdin.fd;ttyR=process.stdin._handle;}else{try{fdR=getFsB().open('CONIN$',constants.O_RDWR,parseInt('0666',8));ttyR=new TTY(fdR,true);}catch(e){}}
if(process.stdout.isTTY){fdW=process.stdout.fd;}else{try{fdW=fs.openSync('\\\\.\\CON','w');}catch(e){}
if(typeof fdW!=='number'){try{fdW=getFsB().open('CONOUT$',constants.O_RDWR,parseInt('0666',8));}catch(e){}}}}else{if(process.stdin.isTTY){process.stdin.pause();try{fdR=fs.openSync('/dev/tty','r');ttyR=process.stdin._handle;}catch(e){}}else{try{fdR=fs.openSync('/dev/tty','r');ttyR=new TTY(fdR,false);}catch(e){}}
if(process.stdout.isTTY){fdW=process.stdout.fd;}else{try{fdW=fs.openSync('/dev/tty','w');}catch(e){}}}})();(function(){var atEol,limit,isCooked=!options.hideEchoBack&&!options.keyIn,buffer,reqSize,readSize,chunk,line;rawInput='';function setRawMode(mode){if(mode===isRawMode){return true;}
if(ttyR.setRawMode(mode)!==0){return false;}
isRawMode=mode;return true;}
if(_DBG_useExt||!ttyR||typeof fdW!=='number'&&(options.display||!isCooked)){input=tryExt();return;}
if(options.display){fs.writeSync(fdW,options.display);options.display='';}
if(options.displayOnly){return;}
if(!setRawMode(!isCooked)){input=tryExt();return;}
reqSize=options.keyIn?1:options.bufferSize;buffer=Buffer.allocUnsafe&&Buffer.alloc?Buffer.alloc(reqSize):new Buffer(reqSize);if(options.keyIn&&options.limit){limit=new RegExp('[^'+options.limit+']','g'+(options.caseSensitive?'':'i'));}
while(true){readSize=0;try{readSize=fs.readSync(fdR,buffer,0,reqSize);}catch(e){if(e.code!=='EOF'){setRawMode(false);input+=tryExt();return;}}
if(readSize>0){chunk=buffer.toString(options.encoding,0,readSize);rawInput+=chunk;}else{chunk='\n';rawInput+=String.fromCharCode(0);}
if(chunk&&typeof(line=(chunk.match(/^(.*?)[\r\n]/)||[])[1])==='string'){chunk=line;atEol=true;}
if(chunk){chunk=chunk.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,'');}
if(chunk&&limit){chunk=chunk.replace(limit,'');}
if(chunk){if(!isCooked){if(!options.hideEchoBack){fs.writeSync(fdW,chunk);}else if(options.mask){fs.writeSync(fdW,(new Array(chunk.length+1)).join(options.mask));}}
input+=chunk;}
if(!options.keyIn&&atEol||options.keyIn&&input.length>=reqSize){break;}}
if(!isCooked&&!silent){fs.writeSync(fdW,'\n');}
setRawMode(false);})();if(options.print&&!silent){options.print(displaySave+(options.displayOnly?'':(options.hideEchoBack?(new Array(input.length+1)).join(options.mask):input)+'\n'),options.encoding);}
return options.displayOnly?'':(lastInput=options.keepWhitespace||options.keyIn?input:input.trim());}
function flattenArray(array,validator){var flatArray=[];function _flattenArray(array){if(array==null){return;}else if(Array.isArray(array)){array.forEach(_flattenArray);}else if(!validator||validator(array)){flatArray.push(array);}}
_flattenArray(array);return flatArray;}
function escapePattern(pattern){return pattern.replace(/[\x00-\x7f]/g,function(s){return'\\x'+('00'+s.charCodeAt().toString(16)).substr(-2);});}
function margeOptions(){var optionsList=Array.prototype.slice.call(arguments),optionNames,fromDefault;if(optionsList.length&&typeof optionsList[0]==='boolean'){fromDefault=optionsList.shift();if(fromDefault){optionNames=Object.keys(defaultOptions);optionsList.unshift(defaultOptions);}}
return optionsList.reduce(function(options,optionsPart){if(optionsPart==null){return options;}
if(optionsPart.hasOwnProperty('noEchoBack')&&!optionsPart.hasOwnProperty('hideEchoBack')){optionsPart.hideEchoBack=optionsPart.noEchoBack;delete optionsPart.noEchoBack;}
if(optionsPart.hasOwnProperty('noTrim')&&!optionsPart.hasOwnProperty('keepWhitespace')){optionsPart.keepWhitespace=optionsPart.noTrim;delete optionsPart.noTrim;}
if(!fromDefault){optionNames=Object.keys(optionsPart);}
optionNames.forEach(function(optionName){var value;if(!optionsPart.hasOwnProperty(optionName)){return;}
value=optionsPart[optionName];switch(optionName){case'mask':case'limitMessage':case'defaultInput':case'encoding':value=value!=null?value+'':'';if(value&&optionName!=='limitMessage'){value=value.replace(/[\r\n]/g,'');}
options[optionName]=value;break;case'bufferSize':if(!isNaN(value=parseInt(value,10))&&typeof value==='number'){options[optionName]=value;}
break;case'displayOnly':case'keyIn':case'hideEchoBack':case'caseSensitive':case'keepWhitespace':case'history':case'cd':options[optionName]=!!value;break;case'limit':case'trueValue':case'falseValue':options[optionName]=flattenArray(value,function(value){var type=typeof value;return type==='string'||type==='number'||type==='function'||value instanceof RegExp;}).map(function(value){return typeof value==='string'?value.replace(/[\r\n]/g,''):value;});break;case'print':case'phContent':case'preCheck':options[optionName]=typeof value==='function'?value:void 0;break;case'prompt':case'display':options[optionName]=value!=null?value:'';break;}});return options;},{});}
function isMatched(res,comps,caseSensitive){return comps.some(function(comp){var type=typeof comp;return type==='string'?(caseSensitive?res===comp:res.toLowerCase()===comp.toLowerCase()):type==='number'?parseFloat(res)===comp:type==='function'?comp(res):comp instanceof RegExp?comp.test(res):false;});}
function replaceHomePath(path,expand){var homePath=pathUtil.normalize(IS_WIN?(process.env.HOMEDRIVE||'')+(process.env.HOMEPATH||''):process.env.HOME||'').replace(/[\/\\]+$/,'');path=pathUtil.normalize(path);return expand?path.replace(/^~(?=\/|\\|$)/,homePath):path.replace(new RegExp('^'+escapePattern(homePath)+'(?=\\/|\\\\|$)',IS_WIN?'i':''),'~');}
function replacePlaceholder(text,generator){var PTN_INNER='(?:\\(([\\s\\S]*?)\\))?(\\w+|.-.)(?:\\(([\\s\\S]*?)\\))?',rePlaceholder=new RegExp('(\\$)?(\\$<'+PTN_INNER+'>)','g'),rePlaceholderCompat=new RegExp('(\\$)?(\\$\\{'+PTN_INNER+'\\})','g');function getPlaceholderText(s,escape,placeholder,pre,param,post){var text;return escape||typeof(text=generator(param))!=='string'?placeholder:text?(pre||'')+text+(post||''):'';}
return text.replace(rePlaceholder,getPlaceholderText).replace(rePlaceholderCompat,getPlaceholderText);}
function array2charlist(array,caseSensitive,collectSymbols){var values,group=[],groupClass=-1,charCode=0,symbols='',suppressed;function addGroup(groups,group){if(group.length>3){groups.push(group[0]+'...'+group[group.length-1]);suppressed=true;}else if(group.length){groups=groups.concat(group);}
return groups;}
values=array.reduce(function(chars,value){return chars.concat((value+'').split(''));},[]).reduce(function(groups,curChar){var curGroupClass,curCharCode;if(!caseSensitive){curChar=curChar.toLowerCase();}
curGroupClass=/^\d$/.test(curChar)?1:/^[A-Z]$/.test(curChar)?2:/^[a-z]$/.test(curChar)?3:0;if(collectSymbols&&curGroupClass===0){symbols+=curChar;}else{curCharCode=curChar.charCodeAt(0);if(curGroupClass&&curGroupClass===groupClass&&curCharCode===charCode+1){group.push(curChar);}else{groups=addGroup(groups,group);group=[curChar];groupClass=curGroupClass;}
charCode=curCharCode;}
return groups;},[]);values=addGroup(values,group);if(symbols){values.push(symbols);suppressed=true;}
return{values:values,suppressed:suppressed};}
function joinChunks(chunks,suppressed){return chunks.join(chunks.length>2?', ':suppressed?' / ':'/');}
function getPhContent(param,options){var text,values,resCharlist={},arg;if(options.phContent){text=options.phContent(param,options);}
if(typeof text!=='string'){switch(param){case'hideEchoBack':case'mask':case'defaultInput':case'caseSensitive':case'keepWhitespace':case'encoding':case'bufferSize':case'history':case'cd':text=!options.hasOwnProperty(param)?'':typeof options[param]==='boolean'?(options[param]?'on':'off'):options[param]+'';break;case'limit':case'trueValue':case'falseValue':values=options[options.hasOwnProperty(param+'Src')?param+'Src':param];if(options.keyIn){resCharlist=array2charlist(values,options.caseSensitive);values=resCharlist.values;}else{values=values.filter(function(value){var type=typeof value;return type==='string'||type==='number';});}
text=joinChunks(values,resCharlist.suppressed);break;case'limitCount':case'limitCountNotZero':text=options[options.hasOwnProperty('limitSrc')?'limitSrc':'limit'].length;text=text||param!=='limitCountNotZero'?text+'':'';break;case'lastInput':text=lastInput;break;case'cwd':case'CWD':case'cwdHome':text=process.cwd();if(param==='CWD'){text=pathUtil.basename(text);}else if(param==='cwdHome'){text=replaceHomePath(text);}
break;case'date':case'time':case'localeDate':case'localeTime':text=(new Date())['to'+
param.replace(/^./,function(str){return str.toUpperCase();})+'String']();break;default:if(typeof(arg=(param.match(/^history_m(\d+)$/)||[])[1])==='string'){text=inputHistory[inputHistory.length-arg]||'';}}}
return text;}
function getPhCharlist(param){var matches=/^(.)-(.)$/.exec(param),text='',from,to,code,step;if(!matches){return null;}
from=matches[1].charCodeAt(0);to=matches[2].charCodeAt(0);step=from<to?1:-1;for(code=from;code!==to+step;code+=step){text+=String.fromCharCode(code);}
return text;}
function parseCl(cl){var reToken=new RegExp(/(\s*)(?:("|')(.*?)(?:\2|$)|(\S+))/g),matches,taken='',args=[],part;cl=cl.trim();while((matches=reToken.exec(cl))){part=matches[3]||matches[4]||'';if(matches[1]){args.push(taken);taken='';}
taken+=part;}
if(taken){args.push(taken);}
return args;}
function toBool(res,options){return((options.trueValue.length&&isMatched(res,options.trueValue,options.caseSensitive))?true:(options.falseValue.length&&isMatched(res,options.falseValue,options.caseSensitive))?false:res);}
function getValidLine(options){var res,forceNext,limitMessage,matches,histInput,args,resCheck;function _getPhContent(param){return getPhContent(param,options);}
function addDisplay(text){options.display+=(/[^\r\n]$/.test(options.display)?'\n':'')+text;}
options.limitSrc=options.limit;options.displaySrc=options.display;options.limit='';options.display=replacePlaceholder(options.display+'',_getPhContent);while(true){res=_readlineSync(options);forceNext=false;limitMessage='';if(options.defaultInput&&!res){res=options.defaultInput;}
if(options.history){if((matches=/^\s*\!(?:\!|-1)(:p)?\s*$/.exec(res))){histInput=inputHistory[0]||'';if(matches[1]){forceNext=true;}else{res=histInput;}
addDisplay(histInput+'\n');if(!forceNext){options.displayOnly=true;_readlineSync(options);options.displayOnly=false;}}else if(res&&res!==inputHistory[inputHistory.length-1]){inputHistory=[res];}}
if(!forceNext&&options.cd&&res){args=parseCl(res);switch(args[0].toLowerCase()){case'cd':if(args[1]){try{process.chdir(replaceHomePath(args[1],true));}catch(e){addDisplay(e+'');}}
forceNext=true;break;case'pwd':addDisplay(process.cwd());forceNext=true;break;}}
if(!forceNext&&options.preCheck){resCheck=options.preCheck(res,options);res=resCheck.res;if(resCheck.forceNext){forceNext=true;}}
if(!forceNext){if(!options.limitSrc.length||isMatched(res,options.limitSrc,options.caseSensitive)){break;}
if(options.limitMessage){limitMessage=replacePlaceholder(options.limitMessage,_getPhContent);}}
addDisplay((limitMessage?limitMessage+'\n':'')+
replacePlaceholder(options.displaySrc+'',_getPhContent));}
return toBool(res,options);}
exports._DBG_set_useExt=function(val){_DBG_useExt=val;};exports._DBG_set_checkOptions=function(val){_DBG_checkOptions=val;};exports._DBG_set_checkMethod=function(val){_DBG_checkMethod=val;};exports._DBG_clearHistory=function(){lastInput='';inputHistory=[];};exports.setDefaultOptions=function(options){defaultOptions=margeOptions(true,options);return margeOptions(true);};exports.question=function(query,options){return getValidLine(margeOptions(margeOptions(true,options),{display:query}));};exports.prompt=function(options){var readOptions=margeOptions(true,options);readOptions.display=readOptions.prompt;return getValidLine(readOptions);};exports.keyIn=function(query,options){var readOptions=margeOptions(margeOptions(true,options),{display:query,keyIn:true,keepWhitespace:true});readOptions.limitSrc=readOptions.limit.filter(function(value){var type=typeof value;return type==='string'||type==='number';}).map(function(text){return replacePlaceholder(text+'',getPhCharlist);});readOptions.limit=escapePattern(readOptions.limitSrc.join(''));['trueValue','falseValue'].forEach(function(optionName){readOptions[optionName]=readOptions[optionName].reduce(function(comps,comp){var type=typeof comp;if(type==='string'||type==='number'){comps=comps.concat((comp+'').split(''));}else{comps.push(comp);}
return comps;},[]);});readOptions.display=replacePlaceholder(readOptions.display+'',function(param){return getPhContent(param,readOptions);});return toBool(_readlineSync(readOptions),readOptions);};exports.questionEMail=function(query,options){if(query==null){query='Input e-mail address: ';}
return exports.question(query,margeOptions({hideEchoBack:false,limit:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,limitMessage:'Input valid e-mail address, please.',trueValue:null,falseValue:null},options,{keepWhitespace:false,cd:false}));};exports.questionNewPassword=function(query,options){var resCharlist,min,max,readOptions=margeOptions({hideEchoBack:true,mask:'*',limitMessage:'It can include: $<charlist>\n'+'And the length must be: $<length>',trueValue:null,falseValue:null,caseSensitive:true},options,{history:false,cd:false,phContent:function(param){return param==='charlist'?resCharlist.text:param==='length'?min+'...'+max:null;}}),charlist,confirmMessage,unmatchMessage,limit,limitMessage,res1,res2;options=options||{};charlist=replacePlaceholder(options.charlist?options.charlist+'':'$<!-~>',getPhCharlist);if(isNaN(min=parseInt(options.min,10))||typeof min!=='number'){min=12;}
if(isNaN(max=parseInt(options.max,10))||typeof max!=='number'){max=24;}
limit=new RegExp('^['+escapePattern(charlist)+']{'+min+','+max+'}$');resCharlist=array2charlist([charlist],readOptions.caseSensitive,true);resCharlist.text=joinChunks(resCharlist.values,resCharlist.suppressed);confirmMessage=options.confirmMessage!=null?options.confirmMessage:'Reinput a same one to confirm it: ';unmatchMessage=options.unmatchMessage!=null?options.unmatchMessage:'It differs from first one.'+' Hit only the Enter key if you want to retry from first one.';if(query==null){query='Input new password: ';}
limitMessage=readOptions.limitMessage;while(!res2){readOptions.limit=limit;readOptions.limitMessage=limitMessage;res1=exports.question(query,readOptions);readOptions.limit=[res1,''];readOptions.limitMessage=unmatchMessage;res2=exports.question(confirmMessage,readOptions);}
return res1;};function _questionNum(query,options,parser){var validValue;function getValidValue(value){validValue=parser(value);return!isNaN(validValue)&&typeof validValue==='number';}
exports.question(query,margeOptions({limitMessage:'Input valid number, please.'},options,{limit:getValidValue,cd:false}));return validValue;}
exports.questionInt=function(query,options){return _questionNum(query,options,function(value){return parseInt(value,10);});};exports.questionFloat=function(query,options){return _questionNum(query,options,parseFloat);};exports.questionPath=function(query,options){var validPath,error='',readOptions=margeOptions({hideEchoBack:false,limitMessage:'$<error(\n)>Input valid path, please.'+'$<( Min:)min>$<( Max:)max>',history:true,cd:true},options,{keepWhitespace:false,limit:function(value){var exists,stat,res;value=replaceHomePath(value,true);error='';function mkdirParents(dirPath){dirPath.split(/\/|\\/).reduce(function(parents,dir){var path=pathUtil.resolve((parents+=dir+pathUtil.sep));if(!fs.existsSync(path)){fs.mkdirSync(path);}else if(!fs.statSync(path).isDirectory()){throw new Error('Non directory already exists: '+path);}
return parents;},'');}
try{exists=fs.existsSync(value);validPath=exists?fs.realpathSync(value):pathUtil.resolve(value);if(!options.hasOwnProperty('exists')&&!exists||typeof options.exists==='boolean'&&options.exists!==exists){error=(exists?'Already exists':'No such file or directory')+': '+validPath;return false;}
if(!exists&&options.create){if(options.isDirectory){mkdirParents(validPath);}else{mkdirParents(pathUtil.dirname(validPath));fs.closeSync(fs.openSync(validPath,'w'));}
validPath=fs.realpathSync(validPath);}
if(exists&&(options.min||options.max||options.isFile||options.isDirectory)){stat=fs.statSync(validPath);if(options.isFile&&!stat.isFile()){error='Not file: '+validPath;return false;}else if(options.isDirectory&&!stat.isDirectory()){error='Not directory: '+validPath;return false;}else if(options.min&&stat.size<+options.min||options.max&&stat.size>+options.max){error='Size '+stat.size+' is out of range: '+validPath;return false;}}
if(typeof options.validate==='function'&&(res=options.validate(validPath))!==true){if(typeof res==='string'){error=res;}
return false;}}catch(e){error=e+'';return false;}
return true;},phContent:function(param){return param==='error'?error:param!=='min'&&param!=='max'?null:options.hasOwnProperty(param)?options[param]+'':'';}});options=options||{};if(query==null){query='Input path (you can "cd" and "pwd"): ';}
exports.question(query,readOptions);return validPath;};function getClHandler(commandHandler,options){var clHandler={},hIndex={};if(typeof commandHandler==='object'){Object.keys(commandHandler).forEach(function(cmd){if(typeof commandHandler[cmd]==='function'){hIndex[options.caseSensitive?cmd:cmd.toLowerCase()]=commandHandler[cmd];}});clHandler.preCheck=function(res){var cmdKey;clHandler.args=parseCl(res);cmdKey=clHandler.args[0]||'';if(!options.caseSensitive){cmdKey=cmdKey.toLowerCase();}
clHandler.hRes=cmdKey!=='_'&&hIndex.hasOwnProperty(cmdKey)?hIndex[cmdKey].apply(res,clHandler.args.slice(1)):hIndex.hasOwnProperty('_')?hIndex._.apply(res,clHandler.args):null;return{res:res,forceNext:false};};if(!hIndex.hasOwnProperty('_')){clHandler.limit=function(){var cmdKey=clHandler.args[0]||'';if(!options.caseSensitive){cmdKey=cmdKey.toLowerCase();}
return hIndex.hasOwnProperty(cmdKey);};}}else{clHandler.preCheck=function(res){clHandler.args=parseCl(res);clHandler.hRes=typeof commandHandler==='function'?commandHandler.apply(res,clHandler.args):true;return{res:res,forceNext:false};};}
return clHandler;}
exports.promptCL=function(commandHandler,options){var readOptions=margeOptions({hideEchoBack:false,limitMessage:'Requested command is not available.',caseSensitive:false,history:true},options),clHandler=getClHandler(commandHandler,readOptions);readOptions.limit=clHandler.limit;readOptions.preCheck=clHandler.preCheck;exports.prompt(readOptions);return clHandler.args;};exports.promptLoop=function(inputHandler,options){var readOptions=margeOptions({hideEchoBack:false,trueValue:null,falseValue:null,caseSensitive:false,history:true},options);while(true){if(inputHandler(exports.prompt(readOptions))){break;}}
return;};exports.promptCLLoop=function(commandHandler,options){var readOptions=margeOptions({hideEchoBack:false,limitMessage:'Requested command is not available.',caseSensitive:false,history:true},options),clHandler=getClHandler(commandHandler,readOptions);readOptions.limit=clHandler.limit;readOptions.preCheck=clHandler.preCheck;while(true){exports.prompt(readOptions);if(clHandler.hRes){break;}}
return;};exports.promptSimShell=function(options){return exports.prompt(margeOptions({hideEchoBack:false,history:true},options,{prompt:(function(){return IS_WIN?'$<cwd>>':(process.env.USER||'')+
(process.env.HOSTNAME?'@'+process.env.HOSTNAME.replace(/\..*$/,''):'')+':$<cwdHome>$ ';})()}));};function _keyInYN(query,options,limit){var res;if(query==null){query='Are you sure? ';}
if((!options||options.guide!==false)&&(query+='')){query=query.replace(/\s*:?\s*$/,'')+' [y/n]: ';}
res=exports.keyIn(query,margeOptions(options,{hideEchoBack:false,limit:limit,trueValue:'y',falseValue:'n',caseSensitive:false}));return typeof res==='boolean'?res:'';}
exports.keyInYN=function(query,options){return _keyInYN(query,options);};exports.keyInYNStrict=function(query,options){return _keyInYN(query,options,'yn');};exports.keyInPause=function(query,options){if(query==null){query='Continue...';}
if((!options||options.guide!==false)&&(query+='')){query=query.replace(/\s+$/,'')+' (Hit any key)';}
exports.keyIn(query,margeOptions({limit:null},options,{hideEchoBack:true,mask:''}));return;};exports.keyInSelect=function(items,query,options){var readOptions=margeOptions({hideEchoBack:false},options,{trueValue:null,falseValue:null,caseSensitive:false,phContent:function(param){return param==='itemsCount'?items.length+'':param==='firstItem'?(items[0]+'').trim():param==='lastItem'?(items[items.length-1]+'').trim():null;}}),keylist='',key2i={},charCode=49,display='\n';if(!Array.isArray(items)||!items.length||items.length>35){throw'`items` must be Array (max length: 35).';}
items.forEach(function(item,i){var key=String.fromCharCode(charCode);keylist+=key;key2i[key]=i;display+='['+key+'] '+(item+'').trim()+'\n';charCode=charCode===57?97:charCode+1;});if(!options||options.cancel!==false){keylist+='0';key2i['0']=-1;display+='[0] '+
(options&&options.cancel!=null&&typeof options.cancel!=='boolean'?(options.cancel+'').trim():'CANCEL')+'\n';}
readOptions.limit=keylist;display+='\n';if(query==null){query='Choose one from list: ';}
if((query+='')){if(!options||options.guide!==false){query=query.replace(/\s*:?\s*$/,'')+' [$<limit>]: ';}
display+=query;}
return key2i[exports.keyIn(display,readOptions).toLowerCase()];};exports.getRawInput=function(){return rawInput;};function _setOption(optionName,args){var options;if(args.length){options={};options[optionName]=args[0];}
return exports.setDefaultOptions(options)[optionName];}
exports.setPrint=function(){return _setOption('print',arguments);};exports.setPrompt=function(){return _setOption('prompt',arguments);};exports.setEncoding=function(){return _setOption('encoding',arguments);};exports.setMask=function(){return _setOption('mask',arguments);};exports.setBufferSize=function(){return _setOption('bufferSize',arguments);};};BundleModuleCode['http/https']=function(module,exports){"use strict";var log=0;var Io=Require('com/io');var util=Require('util');var http=Require('http');var https;try{https=require('https');}catch(e){}
var fs=Require('fs');var Comp=Require('com/compat');var Perv=Comp.pervasives;var String=Comp.string;var Array=Comp.array;var Filename=Comp.filename;var trace=Io.tracing;var div=Perv.div;var isNode=Comp.isNodeJS();var HTTPSrv=function(options){if(!(this instanceof HTTPSrv))return new HTTPSrv(options);this.srv_ip=options.ip;this.srv_ipport=options.ipport;this.dir=options.dir;this.proto=options.proto||'http';this.https=undefined;this.verbose=options.verbose||0;this.index=options.index||'index.html';this.log=options.log||Io.log;this.options=options;};HTTPSrv.prototype.init=function(){var self=this,stat='';this.dir=Filename.path_absolute(this.dir);function handler(request,response){response.origin=request.headers.origin;var path=String.prefix(request.url,'?');String.match(request.method,[['GET',function(){if(self.verbose>2)self.log('[HTTP] Get: '+path);var data='';try{path=self.dir+'/'+Filename.path_normalize(path=='/'?self.index:path);data=Io.read_file_bin(path);stat='OK';}catch(e){data='File server: failed to read file '+path+' , '+util.inspect(e);stat=data;}
if(data==undefined){stat='Failed: no data read.';if(self.verbose>1)self.log('[HTTP] : Failed to get data for file '+path);data='Error: Not found: '+path;}
if(self.verbose>2)self.log('[HTTP] Get: '+request.url+' -> '+stat+' ['+(data?data.length:0)+']');if(data!=undefined){if(response.origin!=undefined)
response.writeHead(200,{'Access-Control-Allow-Origin':response.origin,'Access-Control-Allow-Credentials':'true',});else
response.writeHead(200,{'Access-Control-Allow-Origin':'*'});response.write(data);response.end();}}]])};if(this.proto=='http')this.https=http.createServer(handler);else if(this.proto=='https'&&https){var _options={key:"-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCj1c0IRFOg2FZt\ncDtVgdQetk0RtOmU5ukMs09xw+irPHZeHmtu0gWy11yCHfqHwaqsrYdmnC1EAJsr\nlyBgdoiOn2MJNxW52/x7/I1ZVUke6p4OPyhNGaQHcCPmp/dBzMH9yY6K/HHPDqR/\ncDR1ait3ttpsvMxFT0baHZsxm/bajKUETSkGOW5gugq32egyjAKfHYSbbSY2zm8R\n3g1kluYKGvhjt/SvTPjcGYiTMwkyKBTuvpfZqxRArkaMlQdKKKBT+X3cY47ZD4I3\n0Hy8kirTeLvPf91THeI8pcTVU8a6qPryttOB9cRruzYJF4Z0sdnAzTPmVugPjRqn\n6BFPb0v1AgMBAAECggEASTMAHV5xwt6FlvXa/LQ58tLekjezWRzmKQ+AQkMWlFM6\nS4jp1SSu+R2xrkz4n2kO+YG6ikTjEIv4yDwIcjDjiF18ISTkZxr7ruXCvZQWTGLk\n5VagifoXyF75G1gWZ+a1Ec/ZCQ4LR0iyhGG8fm1GKIGhC4468giejltF+J9HZpNT\nJTcOZ/d5+WtwFa67o1vEqp8tIZ6bA6as9Jp4brmWifXSNZpGh3oIa6eQcVAl9b32\nxnh9F1oBwAz5D5TbHZ7RfiRsoUKeEprsJ8XEfVwO5R8xd7IMc5eXqDcZIZHJEWeV\nRqY0GOGRCdBWZydrHnyIpkCcJ9TytN4nx3OD0BsCYQKBgQDRrXDM88lVWW3htatu\nZiEZQIVkJ3Lj/S9/YByeU22UBUr7UZfWAQWEF7nhDnoa3NeQULMekgeH8O4Yd7Qd\nsGHm9DwiqPiyw2MRUU2eM074GiDpgy1K+oP669YHSMe+Vq5TnW1deNDuPYm4R85V\nGqG0rpG5yN6FojMmQsn+0qTxDQKBgQDIB7E8AMLFV7g1e8mor4uMa68GyScl1bFK\ngQ3Yoq+yLUV0zziFIcR9IwGxopC81QN4qXynb1JnlQyTASEPxJT558wFIUqRwnND\nxbwfwcNL5KVN7F1yTn55mmKHuxYGURs3Au8ErwQ+cdDu3bFsQxk8eBEob3OEzAd1\nxEW1yAh8iQKBgGaU4y3yS1rtULvvhHqTjrfrABe60RPHp7g6jmXLTT3wxPllttIl\nV8yDSxZXXdfMmc3qHWfka7jPX70quz0XMR6r+MvAPURAITS0wTOXyJfLOLTlz3/y\nRiW5wdF4gviVMd6Ik5v6YsVb6Af3YXPzfo+GJJdvNabNbxbV8DsyVS31AoGAGaTy\n0fB/B/HRCfpOxjOLPntnuwT64dzdl+GntshUohEvwGP4qQjFOg3M38sppyvgAA4q\njwS0mdb//7C7XlwjhU50V4wHFVzKjjvBfIjI0ugDUVQmPstVZ52lWCViE3k+dfUI\nU59keeT5lkYRwwFvMNNrz7VKKBJIOo7pKP72J5ECgYAygg6zNNUzrcUuuZHSpyEM\nx5uy5nmoD81RwlGS0N8m5SwN8jW+c7C7ROUdGakXV69zubMXzAsz4xMJTTSQBep2\nsNTNjlV71UikZhhx/spLZqaLb0ZIgCxj4dfNZS3XRh7Wi1bYuf2III+SUf4zitG0\nuGKHIqJgcSumSzjYGiMSAA==\n-----END PRIVATE KEY-----\n",cert:"-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIJAKMxU7sE4FnyMA0GCSqGSIb3DQEBCwUAMCcxCzAJBgNV\nBAYTAlVTMRgwFgYDVQQDDA9FeGFtcGxlLVJvb3QtQ0EwHhcNMjIwNjA1MTEzMDMy\nWhcNMjUwMzI1MTEzMDMyWjAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPRXhhbXBs\nZS1Sb290LUNBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo9XNCERT\noNhWbXA7VYHUHrZNEbTplObpDLNPccPoqzx2Xh5rbtIFstdcgh36h8GqrK2HZpwt\nRACbK5cgYHaIjp9jCTcVudv8e/yNWVVJHuqeDj8oTRmkB3Aj5qf3QczB/cmOivxx\nzw6kf3A0dWord7babLzMRU9G2h2bMZv22oylBE0pBjluYLoKt9noMowCnx2Em20m\nNs5vEd4NZJbmChr4Y7f0r0z43BmIkzMJMigU7r6X2asUQK5GjJUHSiigU/l93GOO\n2Q+CN9B8vJIq03i7z3/dUx3iPKXE1VPGuqj68rbTgfXEa7s2CReGdLHZwM0z5lbo\nD40ap+gRT29L9QIDAQABo1AwTjAdBgNVHQ4EFgQU763HyX73limLTXAwJ4SwpVGv\nD/AwHwYDVR0jBBgwFoAU763HyX73limLTXAwJ4SwpVGvD/AwDAYDVR0TBAUwAwEB\n/zANBgkqhkiG9w0BAQsFAAOCAQEAaO662eNFN2wWtMsUrITX8pwUAJRKxkFvxEQI\nt0HgtfxxvZeTgYjLeTv5U0Jmv8K+6QnNnFIfoc9CD0fFaETw9Z6a+mzliMnHwzZ2\ndI+3eahIcRZ86VuvwisJsDzpW1931Jz+/arIEZprTTSfCPkJs9U790W4wfA6/7Cc\nyZ57EWiug8sP/0NcgofKNNCiixlnlNhXJIOh7/7gXw+zJVdyoKUHMJMoii1UElzN\nVTm6YKSTiuOc+rOIbC4Aw5gQqRDtUqbf/Vcr2IEdOqlL7r4vW9urH+/p3sLVF20C\n8ssjea8dmHcrb5Omu0tUMbhzMM1/eHZS3iwcauu2VWzBDOOjeQ==\n-----END CERTIFICATE-----\n"}
if(fs.existsSync(this.options.key)){console.log('Loading '+_this.options.key);_options.key=fs.readFileSync(this.options.key,'utf8')};if(fs.existsSync(this.options.cert)){console.log('Loading '+this.options.cert);_options.cert=fs.readFileSync(this.options,'utf8')};this.https=https.createServer(_options,handler);}else throw"ENOTSUPPORTED";this.https.on("connection",function(socket){socket.setNoDelay(true);});this.log('[HTTP] servicing directory: '+this.dir);};HTTPSrv.prototype.start=function(){var self=this;if(self.verbose)Io.out('[HTTP] Starting ..');this.https.listen(this.srv_ipport,function(){self.log('[HTTP] listen: listening on *:'+self.srv_ipport);});};HTTPSrv.prototype.stop=function(){if(this.https)this.https.close();}
module.exports={HTTPSrv:HTTPSrv}};BundleModuleCode['geoip/geoip']=function(module,exports){var fs=require("fs");var sat=Require('dos/ext/satelize');var out=function(msg){console.log('[GEOIP] '+msg)};var geoip=module.exports={dir:process.cwd()||__dirname,ipblocks:[],locations:[],midpoints:[],numblocks:0,ready:0,verbose:0,config:function(a,v){geoip[a]=v},init:function(cb){out('Loading '+geoip.dir+"/GeoLiteCity-Blocks.csv ..");var block=fs.createReadStream(geoip.dir+"/GeoLiteCity-Blocks.csv");out('Loading '+geoip.dir+"/GeoLiteCity-Location.csv ..");var location=fs.createReadStream(geoip.dir+"/GeoLiteCity-Location.csv");var buffer1="",buffer2="";block.addListener("data",function(data){buffer1+=data.toString().replace(/"/g,"");});block.addListener("end",function(){var entries=buffer1.split("\n");out('Compiling GeoLiteCity-Blocks ..');for(var i=0;i<entries.length;i++){if(i<2)continue;var entry=entries[i].split(",");if(parseInt(entry[0]))geoip.ipblocks.push({a:parseInt(entry[0]),b:parseInt(entry[1]),i:parseInt(entry[2])});}
geoip.ipblocks.sort(function(a,b){return a.a-b.a;});geoip.numblocks=geoip.ipblocks.length;geoip.midpoints=[];var n=Math.floor(geoip.numblocks/2);while(n>=1){n=Math.floor(n/1.5);geoip.midpoints.push(n);}
geoip.ready++;if(cb&&geoip.ready==2)cb();});location.addListener("data",function(data){buffer2+=data.toString().replace(/"/g,"");});location.addListener("end",function(){var entries=buffer2.split("\n");var locid=0;out('Compiling GeoLiteCity-Location ..');for(var i=0;i<entries.length;i++){if(i<2)continue;var entry=entries[i].split(",");locid=parseInt(entry[0]);geoip.locations[locid]={cn:entry[1],re:entry[2],ci:entry[3],pc:entry[4],la:entry[5],lo:entry[6]};}
geoip.ready++;if(cb&&geoip.ready==2)cb();});},load:function(cb){out('Loading '+geoip.dir+"/GeoLiteCity-Blocks.json ..");var block=fs.createReadStream(geoip.dir+"/GeoLiteCity-Blocks.json");out('Loading '+geoip.dir+"/GeoLiteCity-Location.json ..");var location=fs.createReadStream(geoip.dir+"/GeoLiteCity-Location.json");var buffer1="",buffer2="";block.on('error',function(e){out(e);cb(e);});location.on('error',function(e){out(e);cb(e);});block.addListener("data",function(data){buffer1+=data.toString();});block.addListener("end",function(){out('Parsing GeoLiteCity-Blocks ..');geoip.ipblocks=JSON.parse(buffer1);out('Parsing GeoLiteCity-Blocks done.');geoip.ipblocks.sort(function(a,b){return a.a-b.a;});geoip.numblocks=geoip.ipblocks.length;var n=Math.floor(geoip.numblocks/2);geoip.midpoints=[];while(n>=1){n=Math.floor(n/1.5);geoip.midpoints.push(n);}
geoip.ready++;if(cb&&geoip.ready==2)cb();});location.addListener("data",function(data){buffer2+=data.toString();});location.addListener("end",function(){out('Parsing GeoLiteCity-Location ..');geoip.locations=JSON.parse(buffer2);out('Parsing GeoLiteCity-Location done.');geoip.ready++;if(cb&&geoip.ready==2)cb();});},lookup:function(ip){if(geoip.ready<2){return{error:"GeoIP not ready"};}
var ipl=iplong(ip);if(ipl==0){return{error:"Invalid ip address "+ip+" -> "+ipl+" as integer"};}
var found=find(ipl);if(found){var loc=geoip.locations[found.i];return{status:"success",country:getCountryName(loc.cn),countryCode:loc.cn,city:loc.ci,region:loc.re,zip:loc.pc,lon:loc.lo,lat:loc.la,}}else return none;},proxy:function(options){options=options||{http:9999};var http=require('http');var https;try{https=require('https')}catch(e){}
if(options.http){var httpSrv=http.createServer(function(request,response){var url=request.url,body,header,sep,query,now,remote=request.connection.remoteAddress;if(request.url.length)
query=parseQueryString(request.remote||request.url);else
query={}
if(url.match(/\/json\/([0-9\.]+)/))query.ip=url.match(/\/json\/([0-9\.]+)/)[1];if(geoip.verbose>0)print(url,query,remote);switch(request.method){case'GET':sat.satelize({ip:query.ip||remote},function(err,info){if(err){return reply(response,JSON.stringify({error:err}))}else{if(request.headers&&request.headers.host)info.proxy=request.headers.host;return reply(response,JSON.stringify(info))}})
break;}});httpSrv.on("connection",function(socket){});httpSrv.on("error",function(err){out(err)});httpSrv.listen(options.http,function(err){out('HTTP server started on port '+options.http);});};if(options.https&&https&&options.pem){var httpsSrv=https.createServer(options.pem,function(request,response){var url=request.url,body,header,sep,query,now,remote=request.connection.remoteAddress;if(request.url.length)
query=parseQueryString(request.remote||request.url);else
query={}
if(url.match(/\/json\/([0-9\.]+)/))query.ip=url.match(/\/json\/([0-9\.]+)/)[1];if(geoip.verbose>0)print(url,query,remote);switch(request.method){case'GET':sat.satelize({ip:query.ip||remote},function(err,info){if(err){return reply(response,JSON.stringify({error:err}))}else{if(request.headers&&request.headers.host)info.proxy=request.headers.host;return reply(response,JSON.stringify(info))}})
break;}});httpsSrv.on("connection",function(socket){});httpsSrv.on("error",function(err){out(err)});httpsSrv.listen(options.https,function(err){out('HTTPS server started on port '+options.https);});};},server:function(options){options=options||{http:{address:'localhost',port:9999}};var http=require('http');var https;try{https=require('https')}catch(e){}
geoip.load(function(err){if(err)return;if(options.http){var httpSrv=http.createServer(function(request,response){var url=request.url,body,header,sep,query,now,remote=request.connection.remoteAddress;if(request.url.length)
query=parseQueryString(request.remote||request.url);else
query={}
if(url.match(/\/json\/([0-9\.]+)/))query.ip=url.match(/\/json\/([0-9\.]+)/)[1];if(geoip.verbose>0)print(url,query,remote);switch(request.method){case'GET':reply(response,JSON.stringify(geoip.lookup(query.ip||remote)))
break;}})
httpSrv.on("connection",function(socket){});httpSrv.on("error",function(err){out(err)});httpSrv.listen(options.http.port,function(err){out('HTTP server started on port '+options.http.port);});}
if(options.https&&https&&options.pem){var httpsSrv=https.createServer(options.pem,function(request,response){var url=request.url,body,header,sep,query,now,remote=request.connection.remoteAddress;if(request.url.length)
query=parseQueryString(request.remote||request.url);else
query={}
if(url.match(/\/json\/([0-9\.]+)/))query.ip=url.match(/\/json\/([0-9\.]+)/)[1];if(geoip.verbose>0)print(url,query,remote);switch(request.method){case'GET':reply(response,JSON.stringify(geoip.lookup(query.ip||remote)))
break;}})
httpsSrv.on("connection",function(socket){});httpsSrv.on("error",function(err){out(err)});httpsSrv.listen(options.http.port,function(err){out('HTTPS server started on port '+options.http.port);});}});},save:function(){out('Saving '+geoip.dir+"/GeoLiteCity-Blocks.json ..");var jsblocks=JSON.stringify(geoip.ipblocks);fs.writeFileSync(geoip.dir+"/GeoLiteCity-Blocks.json",jsblocks,'utf8');out('Saving '+geoip.dir+"/GeoLiteCity-Location.json ..");var jslocations=JSON.stringify(geoip.locations);fs.writeFileSync(geoip.dir+"/GeoLiteCity-Location.json",jslocations,'utf8');},};function iplong(ip){if(!ip){return 0;}
ip=ip.toString();if(isNaN(ip)&&ip.indexOf(".")==-1){return 0;}
if(ip.indexOf(".")==-1){try{ip=parseFloat(ip);return ip<0||ip>4294967296?0:ip;}
catch(s){}}
var parts=ip.split(".");if(parts.length!=4){return 0;}
var ipl=0;for(var i=0;i<4;i++){parts[i]=parseInt(parts[i],10);if(parts[i]<0||parts[i]>255){return 0;}
ipl+=parts[3-i]*(Math.pow(256,i));}
return ipl>4294967296?0:ipl;}
function find(ipl){var mpi=0;var n=geoip.midpoints[0];var step;var current;var next;var prev;var nn;var pn;while(true){step=geoip.midpoints[mpi];mpi++;current=geoip.ipblocks[n];nn=n+1;pn=n-1;next=nn<geoip.numblocks?geoip.ipblocks[nn]:null;prev=pn>-1?geoip.ipblocks[pn]:null;if(step>0){if(!next||next.a<ipl){n+=step;}else{n-=step;}
continue;}
var cd=Math.abs(ipl-current.a);var nd=next&&next.a<ipl?ipl-next.a:1000000000;var pd=prev&&prev.a<ipl?ipl-prev.a:1000000000;if(cd<nd&&cd<pd){return current;}
if(nd<cd&&nd<pd){return next;}
return prev;}
return none;}
var isoCountries={'AF':'Afghanistan','AX':'Aland Islands','AL':'Albania','DZ':'Algeria','AS':'American Samoa','AD':'Andorra','AO':'Angola','AI':'Anguilla','AQ':'Antarctica','AG':'Antigua And Barbuda','AR':'Argentina','AM':'Armenia','AW':'Aruba','AU':'Australia','AT':'Austria','AZ':'Azerbaijan','BS':'Bahamas','BH':'Bahrain','BD':'Bangladesh','BB':'Barbados','BY':'Belarus','BE':'Belgium','BZ':'Belize','BJ':'Benin','BM':'Bermuda','BT':'Bhutan','BO':'Bolivia','BA':'Bosnia And Herzegovina','BW':'Botswana','BV':'Bouvet Island','BR':'Brazil','IO':'British Indian Ocean Territory','BN':'Brunei Darussalam','BG':'Bulgaria','BF':'Burkina Faso','BI':'Burundi','KH':'Cambodia','CM':'Cameroon','CA':'Canada','CV':'Cape Verde','KY':'Cayman Islands','CF':'Central African Republic','TD':'Chad','CL':'Chile','CN':'China','CX':'Christmas Island','CC':'Cocos (Keeling) Islands','CO':'Colombia','KM':'Comoros','CG':'Congo','CD':'Congo, Democratic Republic','CK':'Cook Islands','CR':'Costa Rica','CI':'Cote D\'Ivoire','HR':'Croatia','CU':'Cuba','CY':'Cyprus','CZ':'Czech Republic','DK':'Denmark','DJ':'Djibouti','DM':'Dominica','DO':'Dominican Republic','EC':'Ecuador','EG':'Egypt','SV':'El Salvador','GQ':'Equatorial Guinea','ER':'Eritrea','EE':'Estonia','ET':'Ethiopia','FK':'Falkland Islands (Malvinas)','FO':'Faroe Islands','FJ':'Fiji','FI':'Finland','FR':'France','GF':'French Guiana','PF':'French Polynesia','TF':'French Southern Territories','GA':'Gabon','GM':'Gambia','GE':'Georgia','DE':'Germany','GH':'Ghana','GI':'Gibraltar','GR':'Greece','GL':'Greenland','GD':'Grenada','GP':'Guadeloupe','GU':'Guam','GT':'Guatemala','GG':'Guernsey','GN':'Guinea','GW':'Guinea-Bissau','GY':'Guyana','HT':'Haiti','HM':'Heard Island & Mcdonald Islands','VA':'Holy See (Vatican City State)','HN':'Honduras','HK':'Hong Kong','HU':'Hungary','IS':'Iceland','IN':'India','ID':'Indonesia','IR':'Iran, Islamic Republic Of','IQ':'Iraq','IE':'Ireland','IM':'Isle Of Man','IL':'Israel','IT':'Italy','JM':'Jamaica','JP':'Japan','JE':'Jersey','JO':'Jordan','KZ':'Kazakhstan','KE':'Kenya','KI':'Kiribati','KR':'Korea','KW':'Kuwait','KG':'Kyrgyzstan','LA':'Lao People\'s Democratic Republic','LV':'Latvia','LB':'Lebanon','LS':'Lesotho','LR':'Liberia','LY':'Libyan Arab Jamahiriya','LI':'Liechtenstein','LT':'Lithuania','LU':'Luxembourg','MO':'Macao','MK':'Macedonia','MG':'Madagascar','MW':'Malawi','MY':'Malaysia','MV':'Maldives','ML':'Mali','MT':'Malta','MH':'Marshall Islands','MQ':'Martinique','MR':'Mauritania','MU':'Mauritius','YT':'Mayotte','MX':'Mexico','FM':'Micronesia, Federated States Of','MD':'Moldova','MC':'Monaco','MN':'Mongolia','ME':'Montenegro','MS':'Montserrat','MA':'Morocco','MZ':'Mozambique','MM':'Myanmar','NA':'Namibia','NR':'Nauru','NP':'Nepal','NL':'Netherlands','AN':'Netherlands Antilles','NC':'New Caledonia','NZ':'New Zealand','NI':'Nicaragua','NE':'Niger','NG':'Nigeria','NU':'Niue','NF':'Norfolk Island','MP':'Northern Mariana Islands','NO':'Norway','OM':'Oman','PK':'Pakistan','PW':'Palau','PS':'Palestinian Territory, Occupied','PA':'Panama','PG':'Papua New Guinea','PY':'Paraguay','PE':'Peru','PH':'Philippines','PN':'Pitcairn','PL':'Poland','PT':'Portugal','PR':'Puerto Rico','QA':'Qatar','RE':'Reunion','RO':'Romania','RU':'Russian Federation','RW':'Rwanda','BL':'Saint Barthelemy','SH':'Saint Helena','KN':'Saint Kitts And Nevis','LC':'Saint Lucia','MF':'Saint Martin','PM':'Saint Pierre And Miquelon','VC':'Saint Vincent And Grenadines','WS':'Samoa','SM':'San Marino','ST':'Sao Tome And Principe','SA':'Saudi Arabia','SN':'Senegal','RS':'Serbia','SC':'Seychelles','SL':'Sierra Leone','SG':'Singapore','SK':'Slovakia','SI':'Slovenia','SB':'Solomon Islands','SO':'Somalia','ZA':'South Africa','GS':'South Georgia And Sandwich Isl.','ES':'Spain','LK':'Sri Lanka','SD':'Sudan','SR':'Suriname','SJ':'Svalbard And Jan Mayen','SZ':'Swaziland','SE':'Sweden','CH':'Switzerland','SY':'Syrian Arab Republic','TW':'Taiwan','TJ':'Tajikistan','TZ':'Tanzania','TH':'Thailand','TL':'Timor-Leste','TG':'Togo','TK':'Tokelau','TO':'Tonga','TT':'Trinidad And Tobago','TN':'Tunisia','TR':'Turkey','TM':'Turkmeni
function parseQueryString(url){var queryString=url.substring(url.indexOf('?')+1);if(queryString==url)return[];var params={},queries,temp,i,l;queries=queryString.split("&");for(i=0,l=queries.length;i<l;i++){temp=queries[i].split('=');if(temp[1]==undefined)temp[1]='true';params[temp[0]]=temp[1].replace('%20',' ');}
return params;}
function reply(response,body,mimetype){header={'Access-Control-Allow-Origin':'*','Access-Control-Allow-Credentials':'true','Content-Type':mimetype||'text/plain'};response.writeHead(200,header);response.write(body);response.end();}};BundleModuleCode['dos/ext/satelize']=function(module,exports){var http=Require("http"),serviceHost="ip-api.com",servicePort=80,servicePath="/json",serviceJSONP="";function Satelize(options){this.init()}
Satelize.prototype.init=function(options){return this}
Satelize.prototype.satelize=function(a,b){var c=(a.ip?"/"+a.ip:"")+(a.JSONP?serviceJSONP:""),d=a.timeout||1e3,h=a.url||a.host||serviceHost,p=a.port||servicePort,e,f;if(!http)return b('ENOTSUPPORTED',null);if(!http.xhr&&http.request){e={hostname:h,path:servicePath+c,method:"GET",port:p};f=http.request(e,function(a){a.setEncoding("utf8");var c="";a.on("data",function(a){c+=a}),a.on("end",function(){try{return b(null,JSON.parse(c));}catch(err){b(err.toString()+', '+e.hostname+':'+e.port);}})});return f.on("error",function(a){return b(a)}),f.setTimeout(d,function(){return b(new Error("timeout"))}),f.end(),this;}else{e={uri:a.url?a.url:(a.proto?a.proto:'http')+'://'+h+':'+p+servicePath+c,method:"GET",headers:{}};console.log(e);http.request(e,function(err,xhr,body){if(err)return b(err);else try{b(null,JSON.parse(body));}catch(err){b(err.toString()+', '+e.uri)}})
return this;}}
var sat=new Satelize
module.exports=sat;};BundleModuleCode['top/rendezvous']=function(module,exports){global.config={simulation:false,nonetwork:false};var Comp=Require('com/compat');var Io=Require('com/io');var Chan=Require('jam/chan');var Amp=Require('jam/amp');var Buf=Require('dos/buf');var Net=Require('dos/network');var sprintf=Comp.printf.sprintf;var ipnet=Require('net');var dgram=Require('dgram');var sprintf=Comp.printf.sprintf;var onexit=false;var start=false;var options={connport:Net.uniqport(),http:{address:'134.102.50.219',port:80},ip:{address:'0.0.0.0',port:10001},verbose:1,CACHETMO:60000,MAXTOKENS:4,TIMER:200,TRIES:3,version:'1.2.2'}
var usage=function(exit){out('Usage: rendezvous [-h] [verbose:#] [port:#]');if(exit)onexit=true,start=false;}
if(process.argv[1].indexOf('ampbroker')!=-1||process.argv[1].indexOf('rendezvous')!=-1)
start=true,process.argv.forEach(function(arg){var tokens=arg.split(':');if(arg=='-h'||arg=='-help')usage(true);if(tokens.length!=2)return;switch(tokens[0]){case'verbose':options.verbose=Number(tokens[1]);break;case'port':options.ip.port=Number(tokens[1]);break;}});function getNetworkIP(callback){var socket=ipnet.createConnection(options.http.port,options.http.address);socket.on('connect',function(){callback(undefined,socket.address().address);socket.end();});socket.on('error',function(e){callback(e,'error');});}
function timestamp(){return Date.now();}
function Broker(_options){var self=this;if(!(this instanceof Broker))return new Broker(_options);this.options=options;for(var p in _options)if(_options[p]!=undefined)options[p]=_options[p];this.out=function(msg){console.log('[RED '+Chan.addr2url(options.ip)+' '+Io.Time()+'] '+msg)};this.udp=dgram.createSocket('udp4');this.clients={};function doUntil(interval,fn,cond,arg){if(cond())return;fn(arg);return setTimeout(function(){doUntil(interval,fn,cond,arg);},interval);}
function eq(client1,client2){var p;if(!client1||!client2||client1.name!=client2.name)return false;for(p in client1.connections){if(client1.connections[p].address!=client2.connections[p].address||client1.connections[p].port!=client2.connections[p].port)return false;}
return true;}
function store(name,client){client.time=timestamp()
if(!self.clients[name]||!eq(client,self.clients[name][0]))self.clients[name]=[client];else if(self.clients[name].length<options.MAXTOKENS){self.clients[name].push(client);self.clients[name].forEach(function(client){client.time=timestamp()});}}
function lookup(pat,from,all){var isRegex=pat.indexOf('*')!=-1;if(!isRegex){if(!self.clients[pat])return all?[]:undefined;return all?self.clients[pat]:self.clients[pat].pop();}else{}}
function search(pat){var isRegex=pat.indexOf('*')!=-1,regex,result=[];if(!isRegex){return self.clients[pat]&&self.clients[pat].length?[self.clients[pat][0]]:[];}else{regex=RegExp(pat.replace(/\//g,'\\/').replace(/\*/g,'.+'));for(var p in self.clients){if(self.clients[p]&&self.clients[p].length&&regex.test(p))result.push(p);}
return result;}}
function send(host,port,msg,cb){var buf=Buf.Buffer();var data=JSON.stringify(msg);Buf.buf_put_int16(buf,Amp.AMMessageType.AMMCONTROL);Buf.buf_put_port(buf,options.connport);Buf.buf_put_string(buf,data);self.udp.send(buf.data,0,Buf.length(buf),port,host,function(err,bytes){if(err){udp.close();self.out(sprintf('# stopped due to error: %s',err));process.exit(-1);}else{if(options.verbose>1)self.out('# sent '+msg.type+' to '+host+':'+port);if(cb)cb();}});}
this.udp.on('listening',function(){var address=self.udp.address();if(options.verbose)self.out(sprintf('# listening [%s:%s]',address.address,address.port));});this.udp.on('message',function(message,rinfo){var buf=Buf.Buffer(),reply,port,data,msg,obj,i,j,newreg=false;Buf.buf_init(buf);Buf.buf_of_str(buf,message);msgtyp=Buf.buf_get_int16(buf);if(msgtyp!=Amp.AMMessageType.AMMCONTROL){if(options.verbose)
self.out(sprintf('# Invalid message from %s:%s',rinfo.address,rinfo.port));return;}
port=Buf.buf_get_port(buf);data=Buf.buf_get_string(buf);try{msg=JSON.parse(data);}catch(e){self.out(sprintf('! Couldn\'t parse data (%s):\n%s',e,data));return;}
switch(msg.type){case'lookup':reply=search(msg.data);console.log(msg.data,reply)
send(rinfo.address,rinfo.port,{type:'lookup',from:'BROKER',data:reply,path:msg.data});break;case'register':obj={name:msg.name,connections:{local:msg.linfo,public:rinfo},};for(p in msg){switch(p){case'name':case'linfo':case'type':continue;default:obj[p]=msg[p];}}
store(msg.name,obj);if(self.clients[msg.name].length==1)newreg=1;if(options.verbose&&newreg)
self.out(sprintf('# Client registered: P %s@[%s:%s | L %s:%s]',msg.name,rinfo.address,rinfo.port,msg.linfo.address,msg.linfo.port));send(rinfo.address,rinfo.port,{type:'registered',from:'BROKER'});break;case'pair':var couple=[lookup(msg.from,rinfo),lookup(msg.to,rinfo)],counter=options.TRIES;if(options.verbose>1)
self.out(sprintf('# Pair request: %s@[%s:%s] to %s [%b,%b]',msg.from,rinfo.address,rinfo.port,msg.to,couple[0]!=undefined,couple[1]!=undefined));else if(options.verbose&&couple[0]!=undefined&&couple[1]!=undefined)
self.out(sprintf('# Pairing %s@[%s:%d] and %s@[%s:%d]',msg.from,couple[0].connections.public.address,couple[0].connections.public.port,msg.to,couple[1].connections.public.address,couple[1].connections.public.port));for(i=0;i<couple.length;i++){if(!couple[i]){for(j=0;j<couple.length;j++){if(couple[j])store(couple[j].name,couple[j]);}
return self.out('Client '+(i+1)+' unknown! '+(i==0?msg.from:msg.to));}}
doUntil(options.TIMER,function(){for(var i=0;i<couple.length;i++){send(couple[i].connections.public.address,couple[i].connections.public.port,{type:'pairing',client:couple[(i+1)%couple.length],});}
counter--;},function(){return counter==0});break;};});}
Broker.prototype.init=function(){var self=this;this.gc=setInterval(function(){var time=timestamp();for(var p in self.clients){if(self.clients[p])self.clients[p]=self.clients[p].filter(function(conn){return time>conn.time+self.options.CACHETMO;});}},this.options.CACHETMO);}
Broker.prototype.start=function(){var self=this;getNetworkIP(function(err,addr){if(!err){self.options.ip.address=addr;self.out('# got IP '+addr);}});this.udp.bind(options.ip.port,options.ip.address);}
Broker.prototype.stop=function(){if(this.gc)clearInterval(this.gc),this.gc=undefined;}
if(start){var bs=new Broker(options);bs.start()}
module.exports={Broker:Broker};};BundleModuleCode['jam/chan']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var Amp=Require('jam/amp');var Sec=Require('jam/security');var options={debug:{},verbose:1,version:'1.15.6'}
module.exports.options=options;var SLINK={INIT:'INIT',INITED:'INITED',RUNNING:'RUNNING'}
var virtual=function(node1,node2,dir,options){var self=this;this.node1=node1;this.node2=node2;this.dir=dir;this.buffer1=[];this.buffer2=[];this.count1={rcv:0,snd:0};this.count2={rcv:0,snd:0};this.compress=options.compress;this.handler1=[];this.handler2=[];this.link1={control:function(msg,to,callback){},on:function(event,callback){var data;self.handler1[event]=callback;if(event=='agent'&&self.buffer2.length>0){data=Comp.array.pop(self.buffer2);if(self.compress)data=Lz.decompress(data);callback(data);}},send:function(msg){var data;if(msg.agent){data=msg.agent;if(self.compress)data=Lz.compress(data);if(self.handler2.agent)self.handler2.agent(self.compress?Lz.decompress(data):data);else self.buffer1.push(data);if(data.length)self.count1.snd+=data.length;else self.count1.snd++;}else if(msg.signal){data=msg.signal;if(data.length)self.count1.snd+=data.length;else self.count1.snd++;if(self.handler2.signal)self.handler2.signal(data);}},count:function(){return self.count1.snd},status:function(){return true},virtual:true}
this.link2={control:function(msg,to,callback){},on:function(event,callback){var data;self.handler2[event]=callback;if(event=='agent'&&self.buffer1.length>0){data=Comp.array.pop(self.buffer1);if(self.compress)data=Lz.decompress(data);callback(data);}},send:function(msg){var data;if(msg.agent){data=msg.agent;if(self.compress)data=Lz.compress(data);if(self.handler1.agent)self.handler1.agent(self.compress?Lz.decompress(data):data);else self.buffer2.push(data);if(data.length)self.count2.snd+=data.length;else self.count2.snd++;}else if(msg.signal){data=msg.signal;if(data.length)self.count2.snd+=data.length;else self.count2.snd++;if(self.handler1.signal)self.handler1.signal(data);}},count:function(){return self.count2.snd},status:function(){return true},virtual:true}};virtual.prototype.init=function(){};virtual.prototype.start=function(){};virtual.prototype.stop=function(){};var Virtual=function(node1,node2,dir,options){var obj=new virtual(node1,node2,dir,options);return obj;}
module.exports.Virtual=Virtual;module.exports.current=function(module){current=module.current;Aios=module;Amp.current(module);};if(global.config.nonetwork)return;var physical=function(node,dir,options){var self=this;options=checkOptions(options,{});this.options=options;this.ip=none;if(options.rcv)this.ip=url2addr(options.rcv);else this.ip={address:Amp.options.localhost,port:undefined};if(options.proto&&this.ip)this.ip.proto=options.proto;this.node=node;this.dir=dir;this.count=0;this.broker=options.broker;this.mode=this.options.compress?Amp.AMMode.AMO_COMPRESS:0;this.state=SLINK.INIT;this.linked=0;this.events=[];this.callbacks=[];this.out=function(msg,async){async?Aios.logAsync(msg):Aios.log(msg)};if(this.ip.parameter&&this.ip.parameter.secure){this.options.secure=Sec.Port.ofString(this.ip.parameter.secure);delete this.ip.parameter;this.dir.ip=addr2url(this.ip);}
this.amp=Amp.Amp({broker:options.broker?url2addr(options.broker,this.ip.address):undefined,dir:this.dir,keepAlive:options.keepAlive,mode:this.options.mode,multicast:this.options.multicast,name:this.options.name,node:node,nodeid:this.options.nodeid,oneway:this.options.oneway,proto:this.options.proto,pem:this.options.pem,rcv:this.ip,secure:this.options.secure,snd:options.snd?url2addr(options.snd):undefined,sharedSocket:options.sharedSocket,sock:options.sock,verbose:options.verbose,});this.link={control:function(msg,to,callback){var buf,data,addr=to?url2addr(to):{};buf=Buf.Buffer();msg.tid=Comp.random.int(65536/2);self.callbacks[msg.tid]=callback;Buf.buf_put_int16(buf,msg.tid);Buf.buf_put_string(buf,JSON.stringify(msg.args||{}));self.amp.request(msg.cmd,buf,self.amp.mode&Amp.AMMode.AMO_MULTICAST?addr:undefined);},on:function(event,callback){self.events[event]=callback;},send:function(msg,to){var buf,data,addr=to?url2addr(to):{};if(msg.agent){data=msg.agent;buf=Buf.Buffer();if(self.mode&Amp.AMMode.AMO_COMPRESS)data=Lz.compress(data);Buf.buf_put_string(buf,data);self.amp.request(Command.PS_MIGRATE,buf,self.amp.mode&Amp.AMMode.AMO_MULTICAST?addr:undefined);}else if(msg.signal){data=msg.signal;buf=Buf.Buffer();if(self.mode&Amp.AMMode.AMO_COMPRESS)data=Lz.compress(data);Buf.buf_put_string(buf,data);self.amp.request(Command.PS_SIGNAL,buf,self.amp.mode&Amp.AMMode.AMO_MULTICAST?addr:undefined);}},count:function(){return self.amp.count.rcv+self.amp.count.snd},status:function(to){if(self.amp){switch(to){case'%':return self.amp.status(to);break;default:if(to)to=url2addr(to);return to?self.amp.status(to.address,to.port):self.amp.status();}}},stats:function(){return{transferred:(self.amp.count.rcv+self.amp.count.snd),linked:self.linked}},ip:this.ip,mode:this.amp.mode}
this.link.connect=function(to,key){url2addr(to,self.ip.address,function(addr){self.amp.link(addr,true,key);})};this.link.disconnect=function(to){var tokens;if(!to){if(self.amp.snd&&self.amp.snd.address&&self.amp.snd.port)
self.amp.unlink(self.amp.snd);}else{var addr=url2addr(to,self.ip.address);self.amp.unlink(addr);}};this.link.init=function(cb){if(self.state!=SLINK.INIT)return cb?cb():null;self.state=SLINK.INITED;return self.amp.init(cb);}
this.link.start=function(cb){if(self.state!=SLINK.INITED)return cb?cb():null;self.state=SLINK.RUNNING;return self.amp.start(cb);}
this.link.stop=function(cb){if(self.state!=SLINK.RUNNING)return cb?cb():null;self.state=SLINK.INITED;return self.amp.stop(cb);}
if(this.broker)this.link.lookup=function(path,callback){if(self.amp.lookup)self.amp.lookup(path,callback);else if(callback)callback([]);}
this.amp.on('route+',function(url,node,remote){if(remote)self.ip.public=remote;if(self.router)self.router.add(url,self.link,node);self.emit('link+',url,node);Aios.emit('link+',url,node);self.linked++;});this.amp.on('route-',function(url){if(self.router)self.router.delete(url,self.link);self.emit('link-',url);Aios.emit('link-',url);self.linked--;});this.amp.on('error',function(err,arg){self.emit('error',err,arg);});if(options.on){for(var p in options.on)this.on(p,options.on[p]);}
this.amp.receiver(function(handler){var code,name,env,agentid,stat,obj,buf,status,tid;if(!handler)return;if(self.options.verbose>2){self.out('AMP: got request: '+Io.inspect(handler),true);};switch(handler.cmd){case Command.PS_MIGRATE:code=Buf.buf_get_string(handler.buf);if(self.mode&Amp.AMMode.AMO_COMPRESS)code=Lz.decompress(code);if(self.events.agent)self.events.agent(code,false,handler.remote);break;case Command.PS_CREATE:code=Buf.buf_get_string(handler.buf);if(self.mode&Amp.AMMode.AMO_COMPRESS)code=Lz.decompress(code);if(self.events.agent)self.events.agent(code,true);break;case Command.PS_WRITE:name=Buf.buf_get_string(handler.buf);code=Buf.buf_get_string(handler.buf);env=Buf.buf_get_string(handler.buf);if(self.mode&Amp.AMMode.AMO_COMPRESS)code=Lz.decompress(code);obj={};try{eval("env = "+env)}catch(e){};obj[name]={fun:code,env:env}
if(self.events['class'])self.events['class'](obj);break;case Command.PS_SIGNAL:code=Buf.buf_get_string(handler.buf);if(self.mode&Amp.AMMode.AMO_COMPRESS)code=Lz.decompress(code);if(self.events.signal)self.events.signal(code,handler.remote);break;case Command.PS_STUN:code=Buf.buf_get_string(handler.buf);break;case Command.STD_STATUS:tid=Buf.buf_get_int16(handler.buf);code=Buf.buf_get_string(handler.buf);code=JSON.parse(code);status={};if(typeof code=='string'){switch(code){case'node':case'links':case'ports':case'agents':status=self.node.std_status(code);break;}}
buf=Buf.Buffer();Buf.buf_put_int16(buf,tid);Buf.buf_put_string(buf,JSON.stringify(status));self.amp.reply(Command.STD_MONITOR,buf,self.amp.mode&Amp.AMMode.AMO_MULTICAST?handler.remote:undefined);break;case Command.STD_INFO:tid=Buf.buf_get_int16(handler.buf);code=JSON.parse(Buf.buf_get_string(handler.buf));status={};if(typeof code=='string'){switch(code){case'node':status=self.node.std_info();break;}}else if(typeof code=='object'){if(code.node){if(code.node==self.node.id)status=self.node.std_info();else{var to=COM.lookupNode(self.node,code.node);console.log(to);}}
if(code.agent){status=self.node.std_info(code);}}
buf=Buf.Buffer();Buf.buf_put_int16(buf,tid);Buf.buf_put_string(buf,JSON.stringify(status));self.amp.reply(Command.STD_MONITOR,buf,self.amp.mode&Amp.AMMode.AMO_MULTICAST?handler.remote:undefined);break;case Command.STD_MONITOR:tid=Buf.buf_get_int16(handler.buf);code=Buf.buf_get_string(handler.buf);code=JSON.parse(code);if(self.callbacks[tid]){self.callbacks[tid](code);delete self.callbacks[tid];}
break;}});};physical.prototype.emit=function(event,arg,aux1,aux2){if(this.events[event])this.events[event](arg,aux1,aux2)};physical.prototype.on=function(event,handler){this.events[event]=handler};physical.prototype.init=function(callback){return this.link.init(callback)};physical.prototype.start=function(callback){return this.link.start(callback)};physical.prototype.stop=function(){return this.link.stop()};var Physical=function(node,dir,options){var obj=new physical(node,dir,options);return obj;}
module.exports.Physical=Physical;var url2addr=Amp.url2addr;var addr2url=Amp.addr2url;var resolve=Amp.resolve;function addrequal(addr1,addr2){return ipequal(addr1.address,addr2.address)&&addr1.port==addr2.port;}
function ipequal(ip1,ip2){if(ip1==undefined||ip2==undefined)return false;else if((Comp.string.equal(ip1,'localhost')||Comp.string.equal(ip1,'127.0.0.1'))&&(Comp.string.equal(ip2,'localhost')||Comp.string.equal(ip2,'127.0.0.1')))return true;else return ip1==ip2;}
function iprouter(){this.routingTable={};this.nodeTable={};this.links=[];}
iprouter.prototype.add=function(to,link,node){to=resolve(to);if(options.verbose)Aios.logAsync('[IP] iprouter: add route '+addr2url(link.ip)+' -> '+to+(node?'#'+node:''));this.routingTable[to]=link;this.nodeTable[to]=node;}
iprouter.prototype.addLink=function(link){if(!link.ip)link.ip='*';if(options.verbose)Aios.logAsync('[IP] iprouter: add link '+addr2url(link.ip));this.links.push(link);}
iprouter.prototype.connect=function(to,key){var link,p,addr;to=resolve(to);addr=url2addr(to);for(p in this.links){if(this.links[p].status(to))return;if(!(this.links[p].mode&Amp.AMMode.AMO_MULTICAST)&&this.links[p].status())continue;if(addr.proto&&this.links[p].ip&&this.links[p].ip.proto!=addr.proto)continue;link=this.links[p];break;}
if(link&&link.connect){link.connect(to,key);}}
iprouter.prototype.count=function(dest){var res=0;for(var i in this.links){res+=this.links[i].count();}
return res;}
iprouter.prototype.delete=function(to){to=resolve(to);if(this.routingTable[to]){if(options.verbose)Aios.logAsync('[IP] iprouter: remove route '+addr2url(this.routingTable[to].ip)+' -> '+to);delete this.routingTable[to];delete this.nodeTable[to];}}
iprouter.prototype.disconnect=function(to){to=resolve(to);if(this.routingTable[to]&&this.routingTable[to].status(to)){this.routingTable[to].disconnect(to);}}
iprouter.prototype.lookup=function(nodeid,callback){var p,result=[],n=0;if(nodeid.indexOf('*')!=-1){for(p in this.links){if(this.links[p].lookup){n++;this.links[p].lookup(nodeid,function(_result){if(_result&&_result.length)result=result.concat(_result);n--;if(n==0)callback(result);});}}}else for(p in this.nodeTable){if(this.nodeTable[p]==nodeid&&this.routingTable[p])return p;}}
iprouter.prototype.ip=function(){for(var i in this.links){if(this.links[i].ip)return this.links[i].ip;}}
iprouter.prototype.reverse=function(ip){return this.nodeTable[ip];}
iprouter.prototype.send=function(msg){msg.to=resolve(msg.to);if(this.routingTable[msg.to]){this.routingTable[msg.to].send(msg,msg.to);}else{}}
iprouter.prototype.start=function(callback){var cbl=CBL(callback||function(){});this.links.forEach(function(link){cbl.push(function(next){link.start(next)});});cbl.start();}
iprouter.prototype.stats=function(){return{links:Object.keys(this.routingTable).length}}
iprouter.prototype.status=function(dest){var res,p;if(dest==undefined){for(p in this.routingTable){if(this.routingTable[p])return true}}else if(dest=='*'){res=[];for(p in this.routingTable){if(this.routingTable[p])res.push(p)}
return res;}else if(dest=='%'){res=[];for(p in this.nodeTable){if(this.nodeTable[p]&&this.routingTable[p])res.push(this.nodeTable[p]);}
return res;}else{dest=resolve(dest);if(this.routingTable[dest])
return this.routingTable[dest].status(dest);else
return false;}
return false;}
iprouter.prototype.stop=function(callback){var cbl=CBL(callback||function(){});this.links.forEach(function(link){cbl.push(function(next){link.stop(next)});});cbl.start();}
module.exports.iprouter=iprouter;module.exports.Command=Command
module.exports.Status=Status
module.exports.url2addr=url2addr;module.exports.addr2url=addr2url;};BundleModuleCode['os/lz-string']=function(module,exports){var LZString=(function(){var f=String.fromCharCode;var keyStrBase64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var keyStrUriSafe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";var baseReverseDic={};function getBaseValue(alphabet,character){if(!baseReverseDic[alphabet]){baseReverseDic[alphabet]={};for(var i=0;i<alphabet.length;i++){baseReverseDic[alphabet][alphabet.charAt(i)]=i;}}
return baseReverseDic[alphabet][character];}
var LZString={compressToBase64:function(input){if(input==null)return"";var res=LZString._compress(input,6,function(a){return keyStrBase64.charAt(a);});switch(res.length%4){default:case 0:return res;case 1:return res+"===";case 2:return res+"==";case 3:return res+"=";}},decompressFromBase64:function(input){if(input==null)return"";if(input=="")return null;return LZString._decompress(input.length,32,function(index){return getBaseValue(keyStrBase64,input.charAt(index));});},compressToUTF16:function(input){if(input==null)return"";return LZString._compress(input,15,function(a){return f(a+32);})+" ";},decompressFromUTF16:function(compressed){if(compressed==null)return"";if(compressed=="")return null;return LZString._decompress(compressed.length,16384,function(index){return compressed.charCodeAt(index)-32;});},compressToUint8Array:function(uncompressed){var compressed=LZString.compress(uncompressed);var buf=new Uint8Array(compressed.length*2);for(var i=0,TotalLen=compressed.length;i<TotalLen;i++){var current_value=compressed.charCodeAt(i);buf[i*2]=current_value>>>8;buf[i*2+1]=current_value%256;}
return buf;},decompressFromUint8Array:function(compressed){if(compressed===null||compressed===undefined){return LZString.decompress(compressed);}else{var buf=new Array(compressed.length/2);for(var i=0,TotalLen=buf.length;i<TotalLen;i++){buf[i]=compressed[i*2]*256+compressed[i*2+1];}
var result=[];buf.forEach(function(c){result.push(f(c));});return LZString.decompress(result.join(''));}},compressToEncodedURIComponent:function(input){if(input==null)return"";return LZString._compress(input,6,function(a){return keyStrUriSafe.charAt(a);});},decompressFromEncodedURIComponent:function(input){if(input==null)return"";if(input=="")return null;input=input.replace(/ /g,"+");return LZString._decompress(input.length,32,function(index){return getBaseValue(keyStrUriSafe,input.charAt(index));});},compress:function(uncompressed){return LZString._compress(uncompressed,16,function(a){return f(a);});},_compress:function(uncompressed,bitsPerChar,getCharFromInt){if(uncompressed==null)return"";var i,value,context_dictionary={},context_dictionaryToCreate={},context_c="",context_wc="",context_w="",context_enlargeIn=2,context_dictSize=3,context_numBits=2,context_data=[],context_data_val=0,context_data_position=0,ii;for(ii=0;ii<uncompressed.length;ii+=1){context_c=uncompressed.charAt(ii);if(!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)){context_dictionary[context_c]=context_dictSize++;context_dictionaryToCreate[context_c]=true;}
context_wc=context_w+context_c;if(Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)){context_w=context_wc;}else{if(Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)){if(context_w.charCodeAt(0)<256){for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}}
value=context_w.charCodeAt(0);for(i=0;i<8;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}}else{value=1;for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1)|value;if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=0;}
value=context_w.charCodeAt(0);for(i=0;i<16;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}}
context_enlargeIn--;if(context_enlargeIn==0){context_enlargeIn=Math.pow(2,context_numBits);context_numBits++;}
delete context_dictionaryToCreate[context_w];}else{value=context_dictionary[context_w];for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}}
context_enlargeIn--;if(context_enlargeIn==0){context_enlargeIn=Math.pow(2,context_numBits);context_numBits++;}
context_dictionary[context_wc]=context_dictSize++;context_w=String(context_c);}}
if(context_w!==""){if(Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)){if(context_w.charCodeAt(0)<256){for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}}
value=context_w.charCodeAt(0);for(i=0;i<8;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}}else{value=1;for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1)|value;if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=0;}
value=context_w.charCodeAt(0);for(i=0;i<16;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}}
context_enlargeIn--;if(context_enlargeIn==0){context_enlargeIn=Math.pow(2,context_numBits);context_numBits++;}
delete context_dictionaryToCreate[context_w];}else{value=context_dictionary[context_w];for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}}
context_enlargeIn--;if(context_enlargeIn==0){context_enlargeIn=Math.pow(2,context_numBits);context_numBits++;}}
value=2;for(i=0;i<context_numBits;i++){context_data_val=(context_data_val<<1)|(value&1);if(context_data_position==bitsPerChar-1){context_data_position=0;context_data.push(getCharFromInt(context_data_val));context_data_val=0;}else{context_data_position++;}
value=value>>1;}
while(true){context_data_val=(context_data_val<<1);if(context_data_position==bitsPerChar-1){context_data.push(getCharFromInt(context_data_val));break;}
else context_data_position++;}
return context_data.join('');},decompress:function(compressed){if(compressed==null)return"";if(compressed=="")return null;return LZString._decompress(compressed.length,32768,function(index){return compressed.charCodeAt(index);});},_decompress:function(length,resetValue,getNextValue){var dictionary=[],next,enlargeIn=4,dictSize=4,numBits=3,entry="",result=[],i,w,bits,resb,maxpower,power,c,data={val:getNextValue(0),position:resetValue,index:1};for(i=0;i<3;i+=1){dictionary[i]=i;}
bits=0;maxpower=Math.pow(2,2);power=1;while(power!=maxpower){resb=data.val&data.position;data.position>>=1;if(data.position==0){data.position=resetValue;data.val=getNextValue(data.index++);}
bits|=(resb>0?1:0)*power;power<<=1;}
switch(next=bits){case 0:bits=0;maxpower=Math.pow(2,8);power=1;while(power!=maxpower){resb=data.val&data.position;data.position>>=1;if(data.position==0){data.position=resetValue;data.val=getNextValue(data.index++);}
bits|=(resb>0?1:0)*power;power<<=1;}
c=f(bits);break;case 1:bits=0;maxpower=Math.pow(2,16);power=1;while(power!=maxpower){resb=data.val&data.position;data.position>>=1;if(data.position==0){data.position=resetValue;data.val=getNextValue(data.index++);}
bits|=(resb>0?1:0)*power;power<<=1;}
c=f(bits);break;case 2:return"";}
dictionary[3]=c;w=c;result.push(c);while(true){if(data.index>length){return"";}
bits=0;maxpower=Math.pow(2,numBits);power=1;while(power!=maxpower){resb=data.val&data.position;data.position>>=1;if(data.position==0){data.position=resetValue;data.val=getNextValue(data.index++);}
bits|=(resb>0?1:0)*power;power<<=1;}
switch(c=bits){case 0:bits=0;maxpower=Math.pow(2,8);power=1;while(power!=maxpower){resb=data.val&data.position;data.position>>=1;if(data.position==0){data.position=resetValue;data.val=getNextValue(data.index++);}
bits|=(resb>0?1:0)*power;power<<=1;}
dictionary[dictSize++]=f(bits);c=dictSize-1;enlargeIn--;break;case 1:bits=0;maxpower=Math.pow(2,16);power=1;while(power!=maxpower){resb=data.val&data.position;data.position>>=1;if(data.position==0){data.position=resetValue;data.val=getNextValue(data.index++);}
bits|=(resb>0?1:0)*power;power<<=1;}
dictionary[dictSize++]=f(bits);c=dictSize-1;enlargeIn--;break;case 2:return result.join('');}
if(enlargeIn==0){enlargeIn=Math.pow(2,numBits);numBits++;}
if(dictionary[c]){entry=dictionary[c];}else{if(c===dictSize){entry=w+w.charAt(0);}else{return null;}}
result.push(entry);dictionary[dictSize++]=w+entry.charAt(0);enlargeIn--;w=entry;if(enlargeIn==0){enlargeIn=Math.pow(2,numBits);numBits++;}}}};return LZString;})();if(typeof define==='function'&&define.amd){define(function(){return LZString;});}else if(typeof module!=='undefined'&&module!=null){module.exports=LZString}};BundleModuleCode['dos/buf']=function(module,exports){"use strict";var log=0;var util=Require('util');var Io=Require('com/io');var Comp=Require('com/compat');var String=Comp.string;var Array=Comp.array;var Perv=Comp.pervasives;var des48=Require('dos/des48');var Rand=Comp.random;var Net=Require('dos/network');var Status=Net.Status;var Fs=Require('fs');var SIZEOF_INT16=2;var SIZEOF_INT32=4;var PORT_SIZE=6;var PRIV_SIZE=PORT_SIZE+SIZEOF_INT32;var CAP_SIZE=PORT_SIZE+PRIV_SIZE;var buffer=function(data){var size;this.pos=0;if(Comp.isNumber(data)){this.data=new Buffer(data);}else if(Comp.isString(data)){this.data=new Buffer('');buf_of_hex(this,data)}else if(Comp.isArray(data)){this.data=new Buffer(data);}else if(typeof data=="object"&&data.constructor===Buffer){this.data=data;}else this.data=new Buffer('');};function buf_extend(buf,off){if(buf.data.length<(buf.pos+off)){buf.data=Buffer.concat([buf.data,new Buffer(off-(buf.data.length-buf.pos))]);}}
function buf_expand(buf,size){if(buf.data.length<size){buf.data=Buffer.concat([buf.data,new Buffer(size-buf.data.length)]);}}
function buf_shrink(buf,size){if(buf.data.length>size){buf.data=Buffer.slice(buf.data,size);}}
function buf_put_string(buf,str){buf_extend(buf,str.length+1);for(var i=0;i<str.length;i++){buf.data[buf.pos]=Perv.int_of_char(String.get(str,i));buf.pos++;}
buf.data[buf.pos]=0;buf.pos++;}
function buf_get_string(buf){var str='';var end=buf.data.length;var finished=false;while(!finished&&buf.pos<end){if(buf.data[buf.pos]==0)finished=true;else{str=str+Perv.char_of_int(buf.data[buf.pos]);buf.pos++;}}
buf.pos++;return str;}
function buf_to_hex(buf){return buf.data.toString('hex');}
function buf_of_hex(buf,str){buf.pos=0;buf.data=new Buffer(str,'hex');}
function buf_to_str(buf){var str=buf.data.toString('binary');return str;}
function buf_of_str(buf,str){buf.pos=0;buf.data=new Buffer(str,'binary');return buf;}
function buf_put_bytes(buf,str){buf_extend(buf,str.length);for(var i=0;i<str.length;i++){var n=Perv.int_of_char(String.get(str,i));buf.data[buf.pos]=n;buf.pos++;}}
function buf_get_bytes(buf,size){var i=0;var str='';var end=buf.data.length;var finished=false;while(!finished&&buf.pos<end){if(i==size)finished=true;else{str=str+Perv.char_of_int(buf.data[buf.pos]);buf.pos++;i++;}}
return str;}
function buf_put_int16(buf,n){buf_extend(buf,2);buf.data[buf.pos]=n&0xff;buf.data[buf.pos+1]=(n>>8)&0xff;buf.pos=buf.pos+2;}
function buf_get_int16(buf){var n=0;var end=buf.data.length;if(buf.pos+2<=end){n=buf.data[buf.pos];n=n|(buf.data[buf.pos+1]<<8);buf.pos=buf.pos+2;if(n&0x8000)return(n-0x10000);else return(n);}else throw Status.BUF_OVERFLOW;}
function buf_put_int32(buf,n){buf_extend(buf,4);buf.data[buf.pos]=n&0xff;buf.data[buf.pos+1]=(n>>8)&0xff;buf.data[buf.pos+2]=(n>>16)&0xff;buf.data[buf.pos+3]=(n>>24)&0xff;buf.pos=buf.pos+4;}
function buf_get_int32(buf){var n=0;var end=buf.data.length;if(buf.pos+4<=end){n=buf.data[buf.pos];n=n|(buf.data[buf.pos+1]<<8);n=n|(buf.data[buf.pos+2]<<16);n=n|(buf.data[buf.pos+3]<<24);buf.pos=buf.pos+4;return(n);}else throw Status.BUF_OVERFLOW;}
function buf_put_port(buf,port){buf_extend(buf,Net.PORT_SIZE);for(var i=0;i<Net.PORT_SIZE;i++){var n=Perv.int_of_char(String.get(port,i));buf.data[buf.pos]=n;buf.pos++;}}
function buf_get_port(buf){var port='';var end=buf.data.length;if(buf.pos+Net.PORT_SIZE<=end){for(var i=0;i<Net.PORT_SIZE;i++){port=port+Perv.char_of_int(buf.data[buf.pos]);buf.pos++;}
return port;}else throw Status.BUF_OVERFLOW;}
function buf_put_priv(buf,priv){buf_extend(buf,Net.PRIV_SIZE);buf.data[buf.pos]=priv.prv_obj&0xff;buf.data[buf.pos+1]=(priv.prv_obj>>8)&0xff;buf.data[buf.pos+2]=(priv.prv_obj>>16)&0xff;buf.data[buf.pos+3]=priv.prv_rights&0xff;buf.pos=buf.pos+4;buf_put_port(buf,priv.prv_rand);}
function buf_get_priv(buf,priv){var n;var end=buf.data.length;if(buf.pos+(Net.PRIV_SIZE)<=end){if(priv==undefined)priv=Net.Private();n=buf.data[buf.pos];n=n|(buf.data[buf.pos+1]<<8);n=n|(buf.data[buf.pos+2]<<16);priv.prv_obj=n;priv.prv_rights=buf.data[buf.pos+3];buf.pos=buf.pos+4;priv.prv_rand=buf_get_port(buf);return priv;}else throw Status.BUF_OVERFLOW;}
function buf_put_cap(buf,cap){buf_put_port(buf,cap.cap_port);buf_put_priv(buf,cap.cap_priv);}
function buf_get_cap(buf,cap){var end=buf.data.length;if(buf.pos+(Net.CAP_SIZE)<=end){if(cap==undefined)cap=Net.Capability();cap.cap_port=buf_get_port(buf);buf_get_priv(buf,cap.cap_priv);return cap;}else throw Status.BUF_OVERFLOW;}
function buf_put_hdr(buf,hdr){buf_put_port(buf,hdr.h_port);buf_put_priv(buf,hdr.h_priv);buf_put_int32(buf,hdr.h_command);buf_put_int32(buf,hdr.h_status);}
function buf_get_hdr(buf,hdr){if(hdr==undefined)hdr=Net.Header();hdr.h_port=buf_get_port(buf);buf_get_priv(buf,hdr.h_priv);hdr.h_command=buf_get_int32(buf);hdr.h_status=buf_get_int32(buf);return hdr;}
function buf_put_buf(buf,bufsrc,srcoff,len){if(srcoff==undefined)srcoff=0;if(len==undefined)len=bufsrc.data.length;buf_extend(buf,len);for(var i=0;i<len;i++){buf.data[buf.pos]=bufsrc.data[srcoff+i];buf.pos++;}}
function buf_get_buf(buf,bufdst,dstoff,len){buf_extend(bufdst,dstoff+len);for(var i=0;i<len;i++){bufdst.data[dstoff+i]=buf.data[buf.pos];buf.pos++;}}
function buf_pad(buf,size,byte){if(buf.data.length<size)buf_extend(buf,size-buf.data.length);if(byte!=undefined){while(buf.pos<size){buf.data[buf.pos]=byte;buf.pos++;}}else buf.pos=size-1;}
function buf_set_pos(buf,off){if(off>=buf.data.length)buf_expand(buf,off+1);buf.pos=off;}
function buf_write(fd,buf,off,len){var n;if(off==undefined)n=Io.write_buf(fd,buf.data,0,buf.data.length);else{if(len==undefined)len=buf.data.length;n=Io.write_buf(fd,buf.data,0,len,off);}
return n;}
function buf_read(fd,buf,off,len){var n;buf_expand(buf,len);n=Io.read_buf(fd,buf.data,0,len,off);buf.pos=0;return n;}
function buf_print(buf){var str='[';for(var i=0;i<buf.data.length;i++){if(i>0)str=str+','+buf.data[i];else str=str+buf.data[i];}
return str+']'+buf.pos+':'+buf.data.length;}
function buf_set(buf,off,byte){if(off>=buf.data.length)buf_expand(buf,off+1);buf.data[off]=byte;}
function buf_get(buf,off){return buf.data[off];}
function buf_init(buf){buf.data=new Buffer('');buf.pos=0;}
function buf_copy(dst,src){dst.data=new Buffer(src.data);dst.pos=0;}
function buf_blit(dst,dstoff,src,srcoff,len){buf_expand(dst,dstoff+len);src.data.copy(dst.data,dstoff,srcoff,srcoff+len);dst.pos=0;}
module.exports={SIZEOF_INT16:SIZEOF_INT16,SIZEOF_INT32:SIZEOF_INT32,PORT_SIZE:PORT_SIZE,PRIV_SIZE:PRIV_SIZE,CAP_SIZE:CAP_SIZE,Buffer:function Buffer(data){var obj=new buffer(data);Object.preventExtensions(obj);return obj;},buf_put_string:buf_put_string,buf_put_int16:buf_put_int16,buf_put_int32:buf_put_int32,buf_put_port:buf_put_port,buf_put_priv:buf_put_priv,buf_put_cap:buf_put_cap,buf_put_hdr:buf_put_hdr,buf_put_buf:buf_put_buf,buf_put_bytes:buf_put_bytes,buf_get_string:buf_get_string,buf_get_int16:buf_get_int16,buf_get_int32:buf_get_int32,buf_get_port:buf_get_port,buf_get_priv:buf_get_priv,buf_get_cap:buf_get_cap,buf_get_hdr:buf_get_hdr,buf_get_buf:buf_get_buf,buf_get_bytes:buf_get_bytes,buf_pad:buf_pad,buf_set:buf_set,buf_get:buf_get,buf_set_pos:buf_set_pos,buf_init:buf_init,buf_blit:buf_blit,buf_copy:buf_copy,buf_extend:buf_extend,buf_expand:buf_expand,buf_shrink:buf_shrink,buf_read:buf_read,buf_write:buf_write,buf_print:buf_print,buf_to_hex:buf_to_hex,buf_of_hex:buf_of_hex,buf_to_str:buf_to_str,buf_of_str:buf_of_str,length:function(buf){if(buf.data==undefined)return 0;else return buf.data.length;}};};BundleModuleCode['dos/des48']=function(module,exports){var util=Require('util');var Io=Require('com/io');var Comp=Require('com/compat');var Array=Comp.array;var assert=Comp.assert;const des_HBS=24;const des_BS=des_HBS*2;var des_IP=[23,27,34,44,37,17,12,42,3,32,41,29,20,2,1,10,0,28,40,6,7,11,16,8,25,30,14,26,47,38,19,43,18,5,35,39,36,21,4,45,24,22,13,33,31,9,15,46];var des_FP=[16,14,13,8,38,33,19,20,23,45,15,21,6,42,26,46,22,5,32,30,12,37,41,0,40,24,27,1,17,11,25,44,9,43,2,34,36,4,29,35,18,10,7,31,3,39,47,28];var des_PC1_C=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36];var des_PC1_D=[63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4];var des_shifts=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];var des_PC2_C=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2];var des_PC2_D=[41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32];var des_C=Array.create(56,0);var des_D_get=function(i){return des_C[i+28]};var des_D_set=function(i,sval){des_C[i+28]=sval};var des_KS=Array.create_matrix(16,48,0);var des_OWsetkey=function(key){var ks=[];var t=0;var i,j,k;for(i=0;i<28;i++){var index1=des_PC1_C[i]-1;var index2=des_PC1_D[i]-1;des_C[i]=key[index1];des_D_set(i,key[index2]);}
for(i=0;i<16;i++){ks=des_KS[i];for(k=0;k<des_shifts[i];k++){t=des_C[0];for(j=0;j<27;j++){des_C[j]=des_C[j+1];}
des_C[27]=t;t=des_D_get(0);for(j=0;j<27;j++){des_D_set(j,des_D_get(j+1));}
des_D_set(27,t);}
for(j=0;j<24;j++){ks[j]=des_C[des_PC2_C[j]-1];ks[j+24]=des_D_get(des_PC2_D[j]-28-1);}}
return{C:des_C,KS:des_KS}};var des_E=[22,15,12,3,8,2,23,16,14,13,9,10,0,1,21,19,18,6,11,7,17,4,20,5,5,17,11,13,12,14,8,7,19,22,18,9,3,4,1,6,16,2,20,15,10,23,0,21];var des_S=[[14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13],[15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9],[10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12],[7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14],[2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3],[12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13],[4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12],[13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11]];var des_P=[3,13,9,12,8,20,21,7,5,23,16,1,14,18,4,15,22,10,2,0,11,19,17,6];var des_L=Array.create(des_BS,0);var des_R_get=function(i){return des_L[(i+des_HBS)]};var des_R_set=function(i,sval){des_L[i+des_HBS]=sval};var des_tempL=Array.create(des_HBS,0);var des_f=Array.create(32,0);var des_preS=Array.create(48,0);var des_OWcrypt48=function(block){var ks=[];var t1=0;var t2=0;var i,j,k;for(j=0;j<=(des_BS-1);j++){des_L[j]=block[des_IP[j]];}
for(i=0;i<=15;i++){ks=des_KS[i];for(j=0;j<(des_HBS-1);j++){des_tempL[j]=des_R_get(j);}
for(j=0;j<=47;j++){des_preS[j]=(des_R_get(des_E[j]))^ks[j];}
t1=0;t2=0;for(j=0;j<=7;j++){var sind2=((des_preS[t1+0]<<5)&0xff)+
((des_preS[t1+1]<<3)&0xff)+
((des_preS[t1+2]<<2)&0xff)+
((des_preS[t1+3]<<1)&0xff)+
((des_preS[t1+4]<<0)&0xff)+
((des_preS[t1+5]<<4)&0xff);k=des_S[j][sind2];des_f[t2+0]=(k>>3)&0x1;des_f[t2+1]=(k>>2)&0x1;des_f[t2+2]=(k>>1)&0x1;des_f[t2+3]=(k>>0)&0x1;t1=t1+6;t2=t2+4;}
for(j=0;j<des_HBS;j++){des_R_set(j,(des_L[j]^des_f[des_P[j]]));}
for(j=0;j<des_HBS;j++){des_L[j]=des_tempL[j];}}
for(j=0;j<des_HBS;j++){t1=des_L[j];des_L[j]=des_R_get(j);des_R_set(j,t1);}
for(j=0;j<des_BS;j++){block[j]=des_L[des_FP[j]];}
return block;};module.exports={des_OWsetkey:des_OWsetkey,des_OWcrypt48:des_OWcrypt48};};BundleModuleCode['dos/network']=function(module,exports){"use strict";var log=0;var util=Require('util');var Io=Require('com/io');var Comp=Require('com/compat');var String=Comp.string;var Array=Comp.array;var Perv=Comp.pervasives;var Des48=Require('dos/des48');var Base64=Require('os/base64');var Rand=Comp.random;var Fs=Require('fs');function pad(str,size){while(str.length<(size||2)){str="0"+str;}
return str;}
var STD_FIRST_COM=1000;var STD_LAST_COM=1999;var STD_FIRST_ERR=(-STD_FIRST_COM);var STD_LAST_ERR=(-STD_LAST_COM);var AFS_FIRST_COM=2000;var AFS_LAST_COM=2099;var AFS_FIRST_ERR=(-AFS_FIRST_COM);var AFS_LAST_ERR=(-AFS_LAST_COM);var AFS_REQBUFSZ=1024*32;var DNS_FIRST_COM=2100;var DNS_LAST_COM=2199;var DNS_FIRST_ERR=(-DNS_FIRST_COM);var DNS_LAST_ERR=(-DNS_LAST_COM);var DNS_MAXCOLUMNS=4;var PS_FIRST_COM=2200;var PS_LAST_COM=2299;var PS_FIRST_ERR=(-PS_FIRST_COM);var PS_LAST_ERR=(-PS_LAST_COM);var BR_FIRST_COM=2300;var BR_LAST_COM=2399;var BR_FIRST_ERR=(-BR_FIRST_COM);var BR_LAST_ERR=(-BR_LAST_COM);var Status={STD_OK:0,STD_CAPBAD:STD_FIRST_ERR,STD_COMBAD:(STD_FIRST_ERR-1),STD_ARGBAD:(STD_FIRST_ERR-2),STD_NOTNOW:(STD_FIRST_ERR-3),STD_NOSPACE:(STD_FIRST_ERR-4),STD_DENIED:(STD_FIRST_ERR-5),STD_NOMEM:(STD_FIRST_ERR-6),STD_EXISTS:(STD_FIRST_ERR-7),STD_NOTFOUND:(STD_FIRST_ERR-8),STD_SYSERR:(STD_FIRST_ERR-9),STD_INTR:(STD_FIRST_ERR-10),STD_OVERFLOW:(STD_FIRST_ERR-11),STD_WRITEPROT:(STD_FIRST_ERR-12),STD_NOMEDIUM:(STD_FIRST_ERR-13),STD_IOERR:(STD_FIRST_ERR-14),STD_WRONGSRV:(STD_FIRST_ERR-15),STD_OBJBAD:(STD_FIRST_ERR-16),STD_UNKNOWN:(STD_FIRST_ERR-17),DNS_UNAVAIL:(DNS_FIRST_ERR-1),DNS_NOTEMPTY:(DNS_FIRST_ERR-2),DNS_UNREACH:(DNS_FIRST_ERR-3),DNS_CLASH:(DNS_FIRST_ERR-4),RPC_FAILURE:-1,BUF_OVERFLOW:-2,print:function(stat){switch(stat){case Status.STD_OK:return'STD_OK';case Status.STD_CAPBAD:return'STD_CAPBAD';case Status.STD_COMBAD:return'STD_COMBAD';case Status.STD_ARGBAD:return'STD_ARGBAD';case Status.STD_NOTNOW:return'STD_NOTNOW';case Status.STD_NOSPACE:return'STD_NOSPACE';case Status.STD_DENIED:return'STD_DENIED';case Status.STD_NOMEM:return'STD_NOMEM';case Status.STD_EXISTS:return'STD_EXISTS';case Status.STD_NOTFOUND:return'STD_NOTFOUND';case Status.STD_SYSERR:return'STD_SYSERR';case Status.STD_INTR:return'STD_INTR';case Status.STD_OVERFLOW:return'STD_OVERFLOW';case Status.STD_WRITEPROT:return'STD_WRITEPROT';case Status.STD_NOMEDIUM:return'STD_NOMEDIUM';case Status.STD_IOERR:return'STD_IOERR';case Status.STD_WRONGSRV:return'STD_WRONGSRV';case Status.STD_OBJBAD:return'STD_OBJBAD';case Status.STD_UNKNOWN:return'STD_UNKNOWN';case Status.DNS_UNAVAIL:return'DNS_UNAVAIL';case Status.DNS_NOTEMPTY:return'DNS_NOTEMPTY';case Status.DNS_UNREACH:return'DNS_UNREACH';case Status.DNS_CLASH:return'DNS_CLASH';case Status.RPC_FAILURE:return'RPC_FAILURE';case Status.BUF_OVERFLOW:return'BUF_OVERFLOW';default:return'"'+stat+'"';}}};var Command={STD_MONITOR:STD_FIRST_COM,STD_AGE:(STD_FIRST_COM+1),STD_COPY:(STD_FIRST_COM+2),STD_DESTROY:(STD_FIRST_COM+3),STD_INFO:(STD_FIRST_COM+4),STD_RESTRICT:(STD_FIRST_COM+5),STD_STATUS:(STD_FIRST_COM+6),STD_TOUCH:(STD_FIRST_COM+7),STD_GETPARAMS:(STD_FIRST_COM+8),STD_SETPARAMS:(STD_FIRST_COM+9),STD_NTOUCH:(STD_FIRST_COM+10),STD_EXIT:(STD_FIRST_COM+11),STD_RIGHTS:(STD_FIRST_COM+12),STD_EXEC:(STD_FIRST_COM+13),STD_LOCATION:(STD_FIRST_COM+20),STD_LABEL:(STD_FIRST_COM+21),AFS_CREATE:(AFS_FIRST_COM+1),AFS_DELETE:(AFS_FIRST_COM+2),AFS_FSCK:(AFS_FIRST_COM+3),AFS_INSERT:(AFS_FIRST_COM+4),AFS_MODIFY:(AFS_FIRST_COM+5),AFS_READ:(AFS_FIRST_COM+6),AFS_SIZE:(AFS_FIRST_COM+7),AFS_DISK_COMPACT:(AFS_FIRST_COM+8),AFS_SYNC:(AFS_FIRST_COM+9),AFS_DESTROY:(AFS_FIRST_COM+10),DNS_CREATE:(DNS_FIRST_COM),DNS_DISCARD:(DNS_FIRST_COM+1),DNS_LIST:(DNS_FIRST_COM+2),DNS_APPEND:(DNS_FIRST_COM+3),DNS_CHMOD:(DNS_FIRST_COM+4),DNS_DELETE:(DNS_FIRST_COM+5),DNS_LOOKUP:(DNS_FIRST_COM+6),DNS_SETLOOKUP:(DNS_FIRST_COM+7),DNS_INSTALL:(DNS_FIRST_COM+8),DNS_REPLACE:(DNS_FIRST_COM+10),DNS_GETMASKS:(DNS_FIRST_COM+11),DNS_GETSEQNR:(DNS_FIRST_COM+12),DNS_RENAME:(DNS_FIRST_COM+13),DNS_GETROOT:(DNS_FIRST_COM+14),DNS_GETDEFAFS:(DNS_FIRST_COM+15),PS_STUN:(PS_FIRST_COM),PS_MIGRATE:(PS_FIRST_COM+1),PS_EXEC:(PS_FIRST_COM+2),PS_WRITE:(PS_FIRST_COM+4),PS_READ:(PS_FIRST_COM+5),PS_CREATE:(PS_FIRST_COM+6),PS_FORK:(PS_FIRST_COM+7),PS_SIGNAL:(PS_FIRST_COM+8),BR_CONNECT:(BR_FIRST_COM),BR_DISCONN:(BR_FIRST_COM+1),print:function(cmd){switch(cmd){case Command.STD_MONITOR:return'STD_MONITOR';case Command.STD_AGE:return'STD_AGE';case Command.STD_COPY:return'STD_COPY';case Command.STD_DESTR
return port;};var privat=function(obj,rights,rand){if(obj==undefined){this.prv_obj=0;this.prv_rights=0;this.prv_rand=port();}else{this.prv_obj=obj;this.prv_rights=rights;this.prv_rand=rand;}};var capability=function(cap_port,cap_priv){if(cap_port==undefined){this.cap_port=port();this.cap_priv=new privat();}else{this.cap_port=cap_port;if(cap_priv==undefined)
this.cap_priv=new privat();else
this.cap_priv=cap_priv;}};var header=function(h_port,h_priv,h_command,h_status){if(h_port==undefined){this.h_port=port();this.h_priv=new privat();this.h_command=undefined;this.h_status=undefined;}else{this.h_port=h_port;this.h_priv=h_priv;this.h_command=h_command;this.h_status=h_status;}};function Private(obj,rights,rand){var _obj=new privat(obj,rights,rand);Object.preventExtensions(_obj);return _obj;}
function Capability(cap_port,cap_priv){var obj=new capability(cap_port,cap_priv);Object.preventExtensions(obj);return obj;}
function Header(h_port,h_priv,h_command,h_status){var obj=new header(h_port,h_priv,h_command,h_status);Object.preventExtensions(obj);return obj;}
var uniqports=[];var Net={PORT_SIZE:PORT_SIZE,PRIV_SIZE:PRIV_SIZE,AFS_REQBUFSZ:AFS_REQBUFSZ,CAP_SIZE:CAP_SIZE,DNS_MAXCOLUMNS:DNS_MAXCOLUMNS,TIMEOUT:5000,DEF_RPC_MAX_HOP:DEF_RPC_MAX_HOP,Status:Status,Command:Command,Rights:Rights,Private:Private,Capability:Capability,Header:Header,Port:port,nilport:port(),nilpriv:Private(0,0,this.nilport),nilcap:Capability(this.nilport,this.nilpriv),get_portbyte:function(port,i){return Perv.int_of_char(String.get(port,i))},set_portbyte:function(port,i,byte){return String.set(port,i,(Perv.char_of_int(byte)));},key:function(cap){return cap.cap_port+
cap.cap_priv.prv_obj+
cap.cap_priv.prv_rights+
cap.cap_priv.prv_rand;},one_way:function(port){var key=Array.create(64,0);var block=Array.create(48,0);var pubport=String.make(PORT_SIZE,'\0');var i,j,k;j=0;for(i=0;i<64;i++){if((i&7)>5)
key[i]=0;else{if((this.get_portbyte(port,(j>>3))&(1<<(j&7)))!=0)
key[i]=1;else
key[i]=0;j++;}}
Des48.des_OWsetkey(key);block=Des48.des_OWcrypt48(block);var pb=0;for(i=0;i<PORT_SIZE;i++){var pbyte=0;for(j=0;j<8;j++){pbyte=pbyte|(block[pb]<<j);pb++;}
pubport=this.set_portbyte(pubport,i,pbyte);}
return pubport;},rights_req:function(rights,required){var all=true;Array.iter(required,function(rq){if(rq&rights==0)all=false;});return all;},port_cmp:function(port1,port2){var i;var eq=true;for(i=0;i<PORT_SIZE;i++){if(String.get(port1,i)!=String.get(port2,i))eq=false;}
return eq;},port_copy:function(port){return String.copy(port);},port_name:function(name){var p=String.make(PORT_SIZE,'\0');var i;var n=name.length;for(i=0;i<n;i++){var k=i%PORT_SIZE;p=String.set(p,k,Perv.char_of_int((Perv.int_of_char(String.get(p,k))+
Perv.int_of_char(String.get(name,i)))&0xff));}
return p;},port_to_str:function(port,compact){var i,str='';if(port){for(i=0;i<PORT_SIZE;i++){var num=Perv.int_of_char(String.get(port,i));if(!compact&&i>0)str=str+':';str=str+pad(num.toString(16).toUpperCase(),2);}}else str='undefined';return str;},port_of_str:function(str,compact){var tokens=str.split(':'),i,port='';for(i=0;i<PORT_SIZE;i++){var num='0x'+tokens[i];port=port+Perv.char_of_int(parseInt(num,16));}
return port;},port_of_param:function(str){if(str==undefined||String.equal(str,'undefined'))return undefined;var tokens=str.split(':');var i;var port='';for(i=0;i<PORT_SIZE;i++){var num='0x'+tokens[i];port=port+Perv.char_of_int(parseInt(num,16));}
return port;},prv2pub:function(port){var putport;if(priv2pub_cache[port]==undefined){putport=this.one_way(port);priv2pub_cache[port]=putport;}else putport=priv2pub_cache[port];return putport;},prv_decode:function(prv,rand){if(prv.prv_rights==Rights.PRV_ALL_RIGHTS)
return this.port_cmp(prv.prv_rand,rand);else{var tmp_port=this.port_copy(rand),pt0=this.get_portbyte(tmp_port,0),pr0=prv.prv_rights;tmp_port=this.set_portbyte(tmp_port,0,(pt0^pr0));tmp_port=this.one_way(tmp_port);return this.port_cmp(prv.prv_rand,tmp_port)}},prv_encode:function(obj,rights,rand){var tmp_port=this.port_copy(rand);var r1=rights;var rmask=Rights.PRV_ALL_RIGHTS;if(rights==Rights.PRV_ALL_RIGHTS)
return this.Private(obj,r1&rmask,tmp_port);else{var pt0=this.get_portbyte(tmp_port,0);tmp_port=this.set_portbyte(tmp_port,0,pt0^r1);tmp_port=this.one_way(tmp_port);return this.Private(obj,r1&rmask,tmp_port)}},prv_number:function(prv){return prv.prv_obj;},prv_rights:function(prv){return prv.prv_rights&Rights.PRV_ALL_RIGHTS;},prv_rights_check:function(prv,rand,required){if(!Net.prv_decode(prv,rand))return false;return(prv.prv_rights&required)==required;},restrict:function(priv,mask,random){var pr=this.prv_encode(priv.prv_obj,priv.prv_rights&mask,random);return pr;},uniqport:function(){var port=String.create(PORT_SIZE);var exists=true;while(exists){var i;for(i=0;i<=(PORT_SIZE-1);i++){port=String.set(port,i,(Perv.char_of_int(Rand.int(256))));}
if(uniqports[port]==undefined)
{uniqports[port]=port;exists=false;}}
return port;},cap_to_file:function(cap,path){try{Fs.writeFileSync(path,this.Print.capability(cap));}catch(e){}},cap_of_file:function(path){try{var cap=undefined;var data=Fs.readFileSync(path);var cp=this.Parse.capability(data.toString(),0);cap=cp.cap;return cap;}catch(e){return undefined;}},Position:function(x,y){this.x=x;this.y=y;},Copy:{port:function(src){return String.copy(src);},private:function(src,dst){if(dst!=undefined){dst.prv_obj=src.prv_obj;dst.prv_rights=src.prv_rights;dst.prv_rand=this.port(src.prv_rand);return dst;}else{var dstnew=Private();dstnew.prv_obj=src.prv_obj;dstnew.prv_rights=src.prv_rights;dstnew.prv_rand=this.port(src.prv_rand);return dstnew;}},capability:function(src,dst){if(dst!=undefined){dst.cap_port=this.port(src.cap_port);this.private(src.cap_priv,dst.cap_priv);return dst;}
else{var dstnew=Capability();dstnew.cap_port=this.port(src.cap_port);this.private(src.cap_priv,dstnew.cap_priv);return dstnew;}},header:function(src,dst){dst.h_port=this.port(src.h_port);dst.h_status=src.h_status;dst.h_command=src.h_command;if(src.h_priv!=undefined){if(dst.h_priv==undefined){var obj=new privat();Object.preventExtensions(obj);dst.h_priv=obj;}
this.private(src.h_priv,dst.h_priv);}else dst.h_priv=undefined;}},Equal:{port:function(port1,port2){if(port1==undefined||port2==undefined)return(port1==port2);else return String.equal(port1,port2);},private:function(prv1,prv2){return(prv1==undefined&&prv2==undefined)||(prv1.prv_obj==prv2.prv_obj&&prv1.prv_rights==prv2.prv_rights&&this.port(prv1.prv_rand,prv2.prv_rand))},capability:function(cap1,cap2){return(cap1==undefined&&cap2==undefined)||(this.private(cap1.cap_priv,cap2.cap_priv)&&this.port(cap1.cap_port,cap2.cap_port))},header:function(hdr1,hdr2){return(hdr1==undefined&&hdr2==undefined)||(this.private(hdr1.h_priv,hdr1.h_priv)&&this.port(hdr1.h_port,hdr2.h_port)&&hdr1.h_status==hdr2.h_status&&hdr1.h_command==hdr2.h_command)}},Parse:{port:function(str,pos){var port='';var len=str.length;if(pos==undefined)pos=0;if(len<(pos+17))return undefined;if(str[pos]=='[')pos++;for(var i=0;i<6;i++){var sv='0x'+str[pos]+str[pos+1];port=port+Perv.char_of_int(Perv.int_of_string(sv));pos=pos+2;if(str[pos]==':')pos++;}
if(str[pos]==']')pos++;return{port:port,pos:pos};},private:function(str,pos){var priv=Private();var sv;var len=str.length;if(pos==undefined)pos=0;if(len<(pos+25))return undefined;if(str[pos]=='(')pos++;sv='';while(str[pos]!='('){sv=sv+str[pos];pos++;}
priv.prv_obj=Perv.int_of_string(sv);sv='';if(str[pos]=='(')pos++;while(str[pos]!=')'){sv=sv+str[pos];pos++;}
priv.prv_rights=Perv.int_of_string('0x'+sv);if(str[pos]==')')pos++;var pp=this.port(str,pos);if(pp==undefined)return undefined;priv.prv_rand=pp.port;pos=pp.pos;return{priv:priv,pos:pos};},capability:function(str,pos){var cap=Capability();if(pos==undefined)pos=0;var pp=this.port(str,pos);if(pp==undefined)return undefined;cap.cap_port=pp.port;pos=pp.pos;pp=this.private(str,pos);if(pp==undefined)return undefined;cap.cap_priv=pp.priv;pos=pp.pos;return{cap:cap,pos:pos};}},Print:{capability:function(cap){var str='';if(cap==undefined)return'undefined';if(cap.cap_port!=undefined)str='['+this.port(cap.cap_port)+']';else str='[]';if(cap.cap_priv!=undefined)str=str+'('+this.private(cap.cap_priv)+')';else str=str+'()';return str;},command:Command.print,header:function(hdr){var str='';if(hdr==undefined)return'undefined';if(hdr.h_port!=undefined)str='['+this.port(hdr.h_port)+']';else str='[]';if(hdr.h_command!=undefined)str=str+': '+Command.print(hdr.h_command);if(hdr.h_priv!=undefined)str=str+'('+this.private(hdr.h_priv)+')';else str=str+'()';if(hdr.h_status!=undefined)str=str+' ?'+Status.print(hdr.h_status);return str;},port:function(port){var i;var str='';if(port!=undefined){for(i=0;i<PORT_SIZE;i++){var num=Perv.int_of_char(String.get(port,i));if(i>0)str=str+':';str=str+pad(num.toString(16).toUpperCase(),2);}}else str='undefined';return str;},private:function(priv){var str='';if(priv==undefined)return'undefined';str=priv.prv_obj;str=str+'('+String.format_hex(priv.prv_rights,2).toUpperCase()+')[';str=str+this.port(priv.prv_rand)+']';return str;},status:Status.print}};module.exports=Net;};BundleModuleCode['com/cbl']=function(module,exports){function CBL(callback){if(!(this instanceof CBL))return new CBL(callback);this.schedules=[];this.callback=callback;}
CBL.prototype.next=function(status){var f=this.schedules.shift();if(f){f(this.next.bind(this),status);}else if(this.callback)this.callback(status);}
CBL.prototype.push=function(f){this.schedules.push(f);}
CBL.prototype.start=function(){this.next();}
CBL.prototype.top=function(f){this.schedules.unshift(f);}
module.exports=CBL;};BundleModuleCode['jam/amp']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,getNetworkIP=COM.getNetworkIP,doUntilAck=COM.doUntilAck;options.localhost='localhost';options.version='1.11.1',options.AMC_MAXLIVE=5,options.TIMER=500,options.TRIES=10;options.REGTMO=1000;options.pem={};var ampMAN=Require('jam/ampMAN');var ampRPC=Require('jam/ampRPC');if(global.TARGET!='browser'){var ampUDP=Require('jam/ampUDP');var ampTCP=Require('jam/ampTCP');var ampStream=Require('jam/ampStream');}
var ampHTTP=Require('jam/ampHTTP');var ampHTTPS=Require('jam/ampHTTPS');var Amp=function(options){var obj;switch(options.proto){case'stream':obj=new amp.stream(options);break;case'http':obj=new amp.http(options);break;case'https':obj=new amp.https(options);break;case'tcp':obj=new amp.tcp(options);break;case'udp':default:obj=new amp.udp(options);}
return obj;}
module.exports.current=function(module){current=module.current;Aios=module;if(ampMAN)ampMAN.current(module);if(ampUDP)ampUDP.current(module);if(ampHTTP)ampHTTP.current(module);if(ampHTTPS)ampHTTPS.current(module);if(ampTCP)ampTCP.current(module);if(ampStream)ampStream.current(module);if(ampRPC)ampRPC.current(module);};module.exports.Amp=Amp;module.exports.AMMessageType=AMMessageType;module.exports.AMState=AMState;module.exports.AMMode=AMMode;module.exports.Com=COM;module.exports.Rpc=ampRPC;module.exports.url2addr=url2addr;module.exports.addr2url=addr2url;module.exports.resolve=resolve;module.exports.Command=Command
module.exports.Status=Status
module.exports.options=options;};BundleModuleCode['jam/ampCOM']=function(module,exports){var options={debug:{},magic:0x6dab,peekIP:'134.102.22.124',localhost:'localhost',}
var Comp=Require('com/compat');var Dns=Require('dns');var AMMode={AMO_UNICAST:1,AMO_MULTICAST:2,AMO_STATIC:4,AMO_BUFFER:8,AMO_OBJECT:16,AMO_COMPRESS:32,AMO_SERVER:64,AMO_CLIENT:128,AMO_ONEWAY:256,print:function(m){var s='',sep='';if(m&AMMode.AMO_UNICAST)s+=(sep+'UNI'),sep='|';if(m&AMMode.AMO_MULTICAST)s+=(sep+'MUL'),sep='|';if(m&AMMode.AMO_STATIC)s+=(sep+'STA'),sep='|';if(m&AMMode.AMO_BUFFER)s+=(sep+'BUF'),sep='|';if(m&AMMode.AMO_OBJECT)s+=(sep+'OBJ'),sep='|';if(m&AMMode.AMO_COMPRESS)s+=(sep+'ZIP'),sep='|';if(m&AMMode.AMO_CLIENT)s+=(sep+'CLI'),sep='|';if(m&AMMode.AMO_SERVER)s+=(sep+'SRV'),sep='|';if(m&AMMode.AMO_ONEWAY)s+=(sep+'ONE'),sep='|';return s;}}
var AMMessageType={AMMACK:0,AMMPING:1,AMMPONG:2,AMMLINK:3,AMMUNLINK:4,AMMRPCHEAD:6,AMMRPCDATA:7,AMMCONTROL:8,AMMRPC:9,AMMCOLLECT:10,AMMRPCHEADDATA:11,AMMSCAN:12,AMMINFO:13,print:function(op){switch(op){case AMMessageType.AMMACK:return"AMMACK";case AMMessageType.AMMPING:return"AMMPING";case AMMessageType.AMMPONG:return"AMMPONG";case AMMessageType.AMMLINK:return"AMMLINK";case AMMessageType.AMMUNLINK:return"AMMUNLINK";case AMMessageType.AMMRPCHEAD:return"AMMRPCHEAD";case AMMessageType.AMMRPCHEADDATA:return"AMMRPCHEADDATA";case AMMessageType.AMMRPCDATA:return"AMMRPCDATA";case AMMessageType.AMMRPC:return"AMMRPC";case AMMessageType.AMMCOLLECT:return"AMMCOLLECT";case AMMessageType.AMMCONTROL:return"AMMCONTROL";case AMMessageType.AMMSCAN:return"AMMSCAN";case AMMessageType.AMMINFO:return"AMMINFO";default:return"Chan.AMMessageType?";}}};var AMState={AMS_NOTINIT:1,AMS_INIT:2,AMS_READY:3,AMS_NEGOTIATE:4,AMS_CONNECTED:5,AMS_AWAIT:6,AMS_NOTCONNECTED:10,AMS_RENDEZVOUS:7,AMS_REGISTERED:8,AMS_PAIRING:9,AMS_PAIRED:10,print:function(op){switch(op){case AMState.AMS_NOTINIT:return"AMS_NOTINIT";case AMState.AMS_INIT:return"AMS_INIT";case AMState.AMS_READY:return"AMS_READY";case AMState.AMS_NEGOTIATE:return"AMS_NEGOTIATE";case AMState.AMS_CONNECTED:return"AMS_CONNECTED";case AMState.AMS_AWAIT:return"AMS_AWAIT";case AMState.AMS_NOTCONNECTED:return"AMS_NOTCONNECTED";case AMState.AMS_RENDEZVOUS:return"AMS_RENDEZVOUS";case AMState.AMS_REGISTERED:return"AMS_REGISTERED";case AMState.AMS_PAIRING:return"AMS_PAIRING";case AMState.AMS_PAIRED:return"AMS_PAIRED";default:return"Chan.AMState?";}}};var STD_FIRST_COM=1000;var STD_LAST_COM=1999;var STD_FIRST_ERR=(-STD_FIRST_COM);var STD_LAST_ERR=(-STD_LAST_COM);var PS_FIRST_COM=2200;var PS_LAST_COM=2299;var PS_FIRST_ERR=(-PS_FIRST_COM);var PS_LAST_ERR=(-PS_LAST_COM);var Command={STD_MONITOR:STD_FIRST_COM,STD_AGE:(STD_FIRST_COM+1),STD_COPY:(STD_FIRST_COM+2),STD_DESTROY:(STD_FIRST_COM+3),STD_INFO:(STD_FIRST_COM+4),STD_RESTRICT:(STD_FIRST_COM+5),STD_STATUS:(STD_FIRST_COM+6),STD_TOUCH:(STD_FIRST_COM+7),STD_GETPARAMS:(STD_FIRST_COM+8),STD_SETPARAMS:(STD_FIRST_COM+9),STD_NTOUCH:(STD_FIRST_COM+10),STD_EXIT:(STD_FIRST_COM+11),STD_RIGHTS:(STD_FIRST_COM+12),STD_EXEC:(STD_FIRST_COM+13),STD_LOCATION:(STD_FIRST_COM+20),STD_LABEL:(STD_FIRST_COM+21),PS_STUN:(PS_FIRST_COM),PS_MIGRATE:(PS_FIRST_COM+1),PS_EXEC:(PS_FIRST_COM+2),PS_WRITE:(PS_FIRST_COM+4),PS_READ:(PS_FIRST_COM+5),PS_CREATE:(PS_FIRST_COM+6),PS_FORK:(PS_FIRST_COM+7),PS_SIGNAL:(PS_FIRST_COM+8),};var Status={STD_OK:0,STD_CAPBAD:STD_FIRST_ERR,STD_COMBAD:(STD_FIRST_ERR-1),STD_ARGBAD:(STD_FIRST_ERR-2),STD_NOTNOW:(STD_FIRST_ERR-3),STD_NOSPACE:(STD_FIRST_ERR-4),STD_DENIED:(STD_FIRST_ERR-5),STD_NOMEM:(STD_FIRST_ERR-6),STD_EXISTS:(STD_FIRST_ERR-7),STD_NOTFOUND:(STD_FIRST_ERR-8),STD_SYSERR:(STD_FIRST_ERR-9),STD_INTR:(STD_FIRST_ERR-10),STD_OVERFLOW:(STD_FIRST_ERR-11),STD_WRITEPROT:(STD_FIRST_ERR-12),STD_NOMEDIUM:(STD_FIRST_ERR-13),STD_IOERR:(STD_FIRST_ERR-14),STD_WRONGSRV:(STD_FIRST_ERR-15),STD_OBJBAD:(STD_FIRST_ERR-16),STD_UNKNOWN:(STD_FIRST_ERR-17),RPC_FAILURE:-1,BUF_OVERFLOW:-2,}
var amp={AMMessageType:AMMessageType,AMState:AMState};function lookupNode(node,destnode){var chan,url;if(node.connections.ip&&node.connections.ip.lookup){url=node.connections.ip.lookup(destnode);if(url)return{chan:node.connections.ip,url:url,link:node.connections.ip.routingTable[url]};}}
function isLocal(addr){return addr=='localhost'||addr=='127.0.0.1'}
function isIpAddr(addr){return(/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(addr))}
function parseUrl(url){if(!isNaN(Number(url))||url=='*')return{proto:undefined,address:undefined,port:url,param:undefined,value:undefined}
var tokens=url.match(/((http|https|udp|tcp):\/\/)?([a-zA-Z0-9_\.\-]+):(\[?[a-zA-Z0-9]+\]?|\*)(\?([a-zA-z0-9]+)=([a-zA-Z0-9:]+))?/)
if(!tokens)
tokens=url.match(/((http|https|udp|tcp):\/\/)?([a-zA-Z0-9_\.\-]+)/);return{proto:tokens[2],address:tokens[3],port:tokens[4],param:tokens[6],value:tokens[7]}}
function url2addr(url,defaultIP,callback){var addr={address:defaultIP||options.localhost,port:undefined},parts=parseUrl(url);if(parts.proto)addr.proto=parts.proto;if(parts.address)addr.address=parts.address;if(parts.port&&parts.port!='*')
addr.port=!isNaN(Number(parts.port))?Number(parts.port):parts.port;if(parts.param){addr.parameter={};addr.parameter[parts.param]=parts.value;}
if(!isLocal(parts.address)&&!isIpAddr(parts.address)){if(Dns)
Dns.lookup(parts.address,function(err,_addr){if(!err)addr.address=_addr;if(callback)callback(addr);});else if(callback)callback(addr);return addr;}
if(callback)callback(addr);else return addr;};function params(po){var s='?',sep='';for(var p in po){s+=(sep+p+'='+po[p]);sep='&';}
return s;}
function addr2url(addr,noproto){return(!noproto&&addr.proto?(addr.proto+'://'):'')+
(isLocal(addr.address)?options.localhost:addr.address)+':'+
(addr.port?addr.port:'*')+
(!noproto&&addr.parameter?params(addr.parameter):'')};function obj2url(obj){if(!obj)return'*';if(obj.name&&!obj.address)return obj.name+':*';if(!obj.address)return'*';return(isLocal(obj.address)?options.localhost:obj.address)+':'+(obj.port?obj.port:'*')};function addrequal(addr1,addr2){return ipequal(addr1.address,addr2.address)&&addr1.port==addr2.port;}
function addrempty(addr){return!(addr&&addr.address&&addr.port);}
function resolve(url){return addr2url(url2addr(url))}
function ipequal(ip1,ip2){if(ip1==undefined||ip2==undefined)return false;else if((Comp.string.equal(ip1,'localhost')||Comp.string.equal(ip1,'127.0.0.1'))&&(Comp.string.equal(ip2,'localhost')||Comp.string.equal(ip2,'127.0.0.1')))return true;else return ip1==ip2;}
var ipnet=Require('net');var myip;function getNetworkInterfaces(){var results=null;try{var networkInterfaces=require('os').networkInterfaces;var nets=networkInterfaces();for(var name of Object.keys(nets)){for(var net of nets[name]){if(net.family==='IPv4'&&!net.internal){results=results||{};if(!results[name]){results[name]=[];}
results[name].push(net.address);}}}}catch(e){};return results}
function getNetworkIP(server,callback){var socket;try{if(typeof process!='undefined'&&process.env&&process.env['HOSTIP'])
return callback(undefined,process.env['HOSTIP']);}catch(e){}
if(!ipnet)return callback('Not supported','error');if(myip)return callback(undefined,myip);if(!server)server={address:options.peekIP,port:80};socket=ipnet.createConnection(server.port,server.address);socket.on('connect',function(){myip=socket.address().address;callback(undefined,socket.address().address);socket.end();});socket.on('error',function(e){var results=getNetworkInterfaces();if(!results)
return callback(e,'error');else{for(var i in results)return callback(undefined,results[i]);}});}
function doUntilAck(interval,fn,ack,arg){if(ack())return;fn(arg);return setTimeout(function(){doUntilAck(interval,fn,ack,arg);},interval);}
module.exports={AMMode:AMMode,AMMessageType:AMMessageType,AMState:AMState,doUntilAck:doUntilAck,getNetworkIP:getNetworkIP,amp:amp,options:options,addrempty:addrempty,addrequal:addrequal,addr2url:addr2url,ipequal:ipequal,isLocal:isLocal,lookupNode:lookupNode,obj2url:obj2url,resolve:resolve,url2addr:url2addr,Command:Command,Status:Status,}};BundleModuleCode['jam/ampMAN']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Sec=Require('jam/security');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,addrempty=COM.addrempty,getNetworkIP=COM.getNetworkIP;function msgData(msg){return msg.data&&msg.data.data?msg.data.data:msg.data;}
module.exports.current=function(module){current=module.current;Aios=module;};amp.man=function(options){}
amp.man.prototype.LOG=function(op,msg){if(!this.logging)return;switch(op){case'print':for(var i in this.logs){Aios.log(this.logs[i].op,this.logs[i].time,this.logs[i].msg,AMState.print(this.logs[i].state));}
this.logs=[];break;case'enable':this.logging=true;break;case'disable':this.logging=false;break;default:var date=new Date();var time=Math.floor(date.getTime());this.logs.push({op:op,time:time,msg:msg,state:(this.url&&this.links[this.url].state)});}}
amp.man.prototype.addTransaction=function(remote,tid,data){if(this.mode&AMMode.AMO_MULTICAST)
this.transactions[remote.address+remote.port+tid]=data;else
this.transactions[tid]=data;}
amp.man.prototype.deleteTransaction=function(remote,tid){if(this.mode&AMMode.AMO_MULTICAST)
delete this.transactions[remote.address+remote.port+tid];else
delete this.transactions[tid];}
amp.man.prototype.findTransaction=function(remote,tid){if(this.mode&AMMode.AMO_MULTICAST)
return this.transactions[remote.address+remote.port+tid];else
return this.transactions[tid];}
amp.man.prototype.checkState=function(state,addr){switch(state){case AMState.AMS_CONNECTED:if(this.mode&AMMode.AMO_ONEWAY)return true;if(this.mode&AMMode.AMO_MULTICAST)return this.links[addr2url(addr,true)];if(this.url&&this.links[this.url].state==AMState.AMS_CONNECTED)return true;break;}
return false;}
amp.man.prototype.config=function(options){for(var p in options)this[p]=options[p];}
amp.man.prototype.emit=function(event,arg,aux,aux2){if(this.events[event])this.events[event](arg,aux,aux2);}
amp.man.prototype.handle=function(msg,remote,response){var handler,thisnum,ipport,cmsg,url,ack,info;if(this.verbose>1)this.out('handle '+AMMessageType.print(msg.type)+' from '+addr2url(remote),true);switch(msg.type){case AMMessageType.AMMRPCHEAD:case AMMessageType.AMMRPCHEADDATA:if(!this.checkState(AMState.AMS_CONNECTED,remote))return;handler={};handler.tid=msg.tid;handler.remote=remote;handler.cmd=msg.cmd;handler.size=msg.size;handler.frags=msg.frags;if(msg.size<0)this.err('Got invalid message (size<0) from '+addr2url(remote));if(handler.size>0&&handler.frags>0){handler.buf=Buf.Buffer();dlist=Comp.array.range(0,handler.frags-1);this.addTransaction(remote,handler.tid,[handler,dlist,1000]);}else if(handler.size>0){handler.buf=msg.data;this.callback(handler);}else{handler.buf=Buf.Buffer();this.callback(handler);}
break;case AMMessageType.AMMRPCDATA:if(!this.checkState(AMState.AMS_CONNECTED,remote))return;thisnum=msg.off/this.dlimit;transaction=this.findTransaction(remote,msg.tid);if(transaction!=undefined){handler=transaction[0];if(this.verbose>1)
this.out('receiver: adding data num='+
thisnum+' off='+msg.off+' size='+msg.size+' dlist='+transaction[1],true);Buf.buf_get_buf(msg.data,handler.buf,msg.off,msg.size);transaction[1]=Comp.array.filter(transaction[1],function(num){return(num!=thisnum)});if(Comp.array.empty(transaction[1])){if(this.verbose>2)this.out('[AMP] receiver: finalize '+addr2url(remote),true);this.callback(handler);this.deleteTransaction(remote,msg.tid);}}
break;case AMMessageType.AMMRPC:if(!this.checkState(AMState.AMS_CONNECTED,remote))return;handler={};handler.tid=msg.tid;handler.remote=remote;handler.cmd=msg.cmd;handler.size=msg.size;handler.frags=msg.frags;handler.buf=Buf.Buffer(msgData(msg));this.callback(handler);if(this.ack&&response)this.ack(response);break;case AMMessageType.AMMPING:url=addr2url(remote,true);ipport=remote.port;if(this.mode&AMMode.AMO_MULTICAST){if(!this.links[url]||this.links[url].state!=AMState.AMS_CONNECTED)return;}else if(this.url){if(this.links[this.url].state!=AMState.AMS_CONNECTED)return;}
this.pong({address:remote.address,port:ipport},response);break;case AMMessageType.AMMPONG:ipport=remote.port;if(this.mode&AMMode.AMO_MULTICAST){url=addr2url(remote,true);if(this.links[url]&&this.links[url].state==AMState.AMS_CONNECTED){this.links[url].live=options.AMC_MAXLIVE;}}else if(this.url&&this.links[this.url].state==AMState.AMS_CONNECTED){this.links[this.url].live=options.AMC_MAXLIVE;}
if(this.ack&&response)this.ack(response);break;case AMMessageType.AMMACK:if(msg.status=="ELINKED"){if(this.mode&AMMode.AMO_MULTICAST){url=addr2url(remote,true);if(!this.links[url]||this.links[url].state==AMState.AMS_NOTCONNECTED){if(!this.links[url])this.links[url]={};this.links[url].snd=remote;this.links[url].live=options.AMC_MAXLIVE;this.links[url].port=msg.port;this.links[url].ipport=remote.port;this.links[url].state=AMState.AMS_CONNECTED;this.links[url].node=msg.node;this.emit('route+',url,msg.node);this.watchdog(true);if(this.verbose)
this.out('Linked with ad-hoc '+this.proto+' '+url+', AMP '+
Net.Print.port(msg.port)+', Node '+msg.node,true);}}}
break;case AMMessageType.AMMLINK:ipport=remote.port;url=addr2url(remote,true);if(this.secure&&(!msg.secure||!Sec.Port.equal(this.secure,msg.secure)))return;if(this.mode&AMMode.AMO_MULTICAST){if(!this.links[url]||this.links[url].state==AMState.AMS_NOTCONNECTED){if(!this.links[url])this.links[url]={};this.links[url].snd=remote;this.links[url].live=options.AMC_MAXLIVE;this.links[url].port=msg.port;this.links[url].ipport=remote.port;this.link(this.links[url].snd,false,none,response);this.links[url].state=AMState.AMS_CONNECTED;this.links[url].node=msg.node;this.emit('route+',url,msg.node,msg.remote);this.watchdog(true);if(this.verbose)
this.out('Linked with ad-hoc '+this.proto+' '+url+', AMP '+
Net.Print.port(msg.port)+', Node '+msg.node,true);}else if(this.links[url].state==AMState.AMS_CONNECTED){ack="ELINKED";}}else{if(this.links[url]&&!addrempty(this.links[url].snd)&&this.links[url].state==AMState.AMS_NOTCONNECTED&&ipequal(this.links[url].snd.address,remote.address)&&this.links[url].snd.port==ipport)
{this.links[url].snd=remote;this.links[url].port=msg.port;this.links[url].ipport=remote.port;this.links[url].node=msg.node;this.links[url].live=options.AMC_MAXLIVE;this.link(this.links[url].snd);this.links[url].state=AMState.AMS_CONNECTED;this.emit('route+',url,msg.node,msg.remote);this.watchdog(true);if(this.verbose)
this.out('Linked with preferred '+this.proto+' '+url+', '+
Net.Print.port(msg.port),true);}else if((!this.links[url]&&!this.url)||(this.links[url]&&this.links[url].state==AMState.AMS_NOTCONNECTED)||(this.broker&&this.url&&this.links[this.url].state==AMState.AMS_NOTCONNECTED)){if(!this.links[url])this.links[url]={};this.links[url].snd=remote;this.links[url].live=options.AMC_MAXLIVE;this.links[url].port=msg.port;this.links[url].ipport=remote.port;this.links[url].node=msg.node;this.link(this.links[url].snd,false,none,response);this.links[url].state=AMState.AMS_CONNECTED;this.url=url;this.emit('route+',url,msg.node);this.watchdog(true);if(this.verbose)
this.out('Linked with ad-hoc '+this.proto+' '+url+', '+
Net.Print.port(msg.port),true);}}
if(ack&&this.ack&&response)this.ack(response,ack);break;case AMMessageType.AMMUNLINK:ipport=remote.port;if(this.mode&AMMode.AMO_MULTICAST){url=addr2url(remote,true);if(this.links[url]&&!addrempty(this.links[url].snd)&&ipequal(this.links[url].snd.address,remote.address)&&this.links[url].snd.port==ipport&&this.links[url].state==AMState.AMS_CONNECTED){this.links[url].state=AMState.AMS_NOTCONNECTED;if(this.verbose)
this.out('Unlinked '+url+', '+
Net.Print.port(msg.port),true);this.emit('route-',url);if(!this.links[url].snd.connect)this.links[url].snd={};if(this.cleanup)this.cleanup(url);}}else{if(this.url&&!addrempty(this.links[this.url].snd)&&ipequal(this.links[this.url].snd.address,remote.address)&&this.links[this.url].snd.port==ipport&&this.links[this.url].state==AMState.AMS_CONNECTED)
{this.links[this.url].state=AMState.AMS_NOTCONNECTED;addr=this.links[this.url].snd;if(this.verbose)
this.out('Unlinked '+this.url+', '+
Net.Print.port(msg.port),true);this.emit('route-',addr2url(addr));if(!this.links[this.url].snd.connect)this.links[this.url].snd=null;if(this.cleanup)this.cleanup(url);}}
if(this.ack&&response)this.ack(response);break;case AMMessageType.AMMCONTROL:cmsg=JSON.parse(msgData(msg));if(this.verbose>1)this.out('# got message '+msgData(msg),true);this.LOG('rcv',cmsg);if(this.control&&this.links['*'])
this.control(this.links['*'],cmsg,remote);break;case AMMessageType.AMMSCAN:url=addr2url(remote,true);ipport=remote.port;info={world:(current.world&&current.world.id),stats:(current.world&&current.world.info()),};this.scan({address:remote.address,port:ipport,info:info},response);break;default:this.out('handle: Unknown message type '+msg.type,true);}}
amp.man.prototype.on=function(event,handler){this.events[event]=handler;}
amp.man.prototype.status=function(ip,ipport){var p,url,sl=[];if(ip=='%'){for(p in this.links)if(this.links[p]&&this.links[p].state==AMState.AMS_CONNECTED)
sl.push(this.links[p].node);return sl;}
if(this.mode&AMMode.AMO_MULTICAST){if(!ip){for(p in this.links)if(this.links[p]&&this.links[p].state==AMState.AMS_CONNECTED)return true;return false;}else{url=addr2url({address:ip,port:ipport});if(!this.links[url])return false;return this.links[url].state==AMState.AMS_CONNECTED;}}
if(!ip&&this.url)return this.links[this.url].state==AMState.AMS_CONNECTED||(this.mode&AMMode.AMO_ONEWAY)==AMMode.AMO_ONEWAY;return(this.url&&ipequal(this.links[this.url].snd.address,ip)&&this.links[this.url].snd.port==ipport);}};BundleModuleCode['jam/security']=function(module,exports){var Io=Require('com/io');var Des48=Require('dos/des48');var Base64=Require('os/base64');var Comp=Require('com/compat');var String=Comp.string;var Array=Comp.array;var Perv=Comp.pervasives;var current=none;var Aios=none;var Rnd=Require('com/pwgen');var PORT_SIZE=6;var PRIV_SIZE=4+PORT_SIZE;var CAP_SIZE=16;var PRV_ALL_RIGHTS=0xff;var priv2pub_cache=[];var uniquePorts={};var Rights={HOST_INFO:0x01,HOST_READ:0x02,HOST_WRITE:0x04,HOST_EXEC:0x08,PSR_READ:0x01,PSR_WRITE:0x02,PSR_CREATE:0x04,PSR_DELETE:0x08,PSR_EXEC:0x10,PSR_KILL:0x20,PSR_ALL:0xff,NEG_SCHED:0x08,NEG_CPU:0x10,NEG_RES:0x20,NEG_LIFE:0x40,NEG_LEVEL:0x80,PRV_ALL_RIGHTS:0xff};var Port=function(port_vals){if(port_vals==undefined)port_vals=[0,0,0,0,0,0];var port='';for(var i=0;i<PORT_SIZE;i++){port=port+Perv.char_of_int(port_vals[i]);}
return port;};var Private=function(obj,rights,rand){if(obj==undefined){return{prv_obj:0,prv_rights:0,prv_rand:Port()}}else{return{prv_obj:obj,prv_rights:rights,prv_rand:rand}}}
var Capability=function(cap_port,cap_priv){if(cap_port==undefined){return{cap_port:Port(),cap_priv:Private()}}else{return{cap_port:cap_port,cap_priv:cap_priv?cap_priv:Private()}}}
function cap_parse(str,offset){var cap=Capability(),pos=0;if(offset!=undefined)pos=offset;var pp=port_parse(str,pos);if(pp==undefined)return undefined;cap.cap_port=pp.port;pos=pp.pos;pp=prv_parse(str,pos);if(pp==undefined)return undefined;cap.cap_priv=pp.priv;pos=pp.pos;return{cap:cap,pos:pos};}
function cap_of_string(str){var pp=cap_parse(str,0);return pp?pp.cap:undefined}
function cap_to_string(cap){var str='';if(cap==undefined)return'undefined';if(cap.cap_port!=undefined)str='['+port_to_string(cap.cap_port)+']';else str='[]';if(cap.cap_priv!=undefined)str=str+'('+prv_to_string(cap.cap_priv)+')';else str=str+'()';return str;}
function get_portbyte(port,i){return Perv.int_of_char(String.get(port,i))}
function set_portbyte(port,i,byte){return String.set(port,i,(Perv.char_of_int(byte)));}
function one_way(port){var key=Array.create(64,0);var block=Array.create(48,0);var pubport=String.make(PORT_SIZE,'\0');var i,j,k;j=0;for(i=0;i<64;i++){if((i&7)>5)
key[i]=0;else{if((get_portbyte(port,(j>>3))&(1<<(j&7)))!=0)
key[i]=1;else
key[i]=0;j++;}}
Des48.des_OWsetkey(key);block=Des48.des_OWcrypt48(block);var pb=0;for(i=0;i<PORT_SIZE;i++){var pbyte=0;for(j=0;j<8;j++){pbyte=pbyte|(block[pb]<<j);pb++;}
pubport=set_portbyte(pubport,i,pbyte);}
return pubport;}
function pad(str,size){while(str.length<(size||2)){str="0"+str;}
return str;}
function port_cmp(port1,port2){if(port1==undefined||port2==undefined)return(port1==port2);else return String.equal(port1,port2);}
function port_copy(port){return String.copy(port);}
function port_of_string(str,compact){var tokens=str.split(':'),i,port='';for(i=0;i<PORT_SIZE;i++){var num='0x'+tokens[i];port=port+Perv.char_of_int(parseInt(num,16));}
return port;}
function port_parse(str,pos){var port='';var len=str.length;if(pos==undefined)pos=0;if(len<(pos+17))return undefined;if(str[pos]=='[')pos++;for(var i=0;i<6;i++){var sv='0x'+str[pos]+str[pos+1];port=port+Perv.char_of_int(Perv.int_of_string(sv));pos=pos+2;if(str[pos]==':')pos++;}
if(str[pos]==']')pos++;return{port:port,pos:pos};}
function port_to_string(port,compact){var i,str='';if(port){for(i=0;i<PORT_SIZE;i++){var num=Perv.int_of_char(String.get(port,i));if(!compact&&i>0)str=str+':';str=str+pad(num.toString(16).toUpperCase(),2);}}else str='undefined';return str;}
function prv2pub(port){var putport;if(priv2pub_cache[port]==undefined){putport=one_way(port);priv2pub_cache[port]=putport;}else putport=priv2pub_cache[port];return putport;}
function prv_cmp(prv1,prv2){return(prv1==undefined&&prv2==undefined)||(prv1.prv_obj==prv2.prv_obj&&prv1.prv_rights==prv2.prv_rights&&port_cmp(prv1.prv_rand,prv2.prv_rand))}
function prv_decode(prv,rand){if(prv.prv_rights==PRV_ALL_RIGHTS)
return port_cmp(prv.prv_rand,rand);else{var tmp_port=port_copy(rand),pt0=get_portbyte(tmp_port,0),pr0=prv.prv_rights;tmp_port=set_portbyte(tmp_port,0,(pt0^pr0));tmp_port=one_way(tmp_port);return port_cmp(prv.prv_rand,tmp_port)}}
function prv_encode(obj,rights,rand){var tmp_port=port_copy(rand),r1=rights,rmask=PRV_ALL_RIGHTS;if(rights==PRV_ALL_RIGHTS)
return Private(obj,r1&rmask,tmp_port);else{var pt0=get_portbyte(tmp_port,0);tmp_port=set_portbyte(tmp_port,0,pt0^r1);tmp_port=one_way(tmp_port);return Private(obj,r1&rmask,tmp_port)}}
function prv_of_string(str){var pp=prv_parse(str,0);return pp?pp.priv:undefined}
function prv_number(prv){return prv.prv_obj;}
function prv_parse(str,offset){var priv=Private();var sv;var len=str.length,pos=offset;if(str[pos]=='(')pos++;sv='';while(str[pos]!='('){sv=sv+str[pos];pos++;}
priv.prv_obj=Perv.int_of_string(sv);sv='';if(str[pos]=='(')pos++;while(str[pos]!=')'){sv=sv+str[pos];pos++;}
priv.prv_rights=Perv.int_of_string('0x'+sv);if(str[pos]==')')pos++;var pp=port_parse(str,pos);if(pp==undefined)return undefined;priv.prv_rand=pp.port;pos=pp.pos;return{priv:priv,pos:pos};}
function prv_to_string(priv){var str='';if(priv==undefined)return'undefined';str=priv.prv_obj;str=str+'('+String.format_hex(priv.prv_rights,2).toUpperCase()+')[';str=str+port_to_string(priv.prv_rand)+']';return str;}
function prv_restrict(priv,mask,random){var pr=prv_encode(priv.prv_obj,priv.prv_rights&mask,random);return pr;}
function prv_rights(prv){return prv.prv_rights&Rights.PRV_ALL_RIGHTS;}
function prv_rights_check(prv,rand,required){if(!prv_decode(prv,rand))return false;return(prv.prv_rights&required)==required;}
function uniqport(){var port=String.create(PORT_SIZE);var i,values;do{values=Rnd.generate({number:true,length:PORT_SIZE});for(i=0;i<=(PORT_SIZE-1);i++)
port=String.set(port,i,(Perv.char_of_int(values[i])));if(uniquePorts[port])uniquePorts[port]++;else uniquePorts[port]=1;}while(uniquePorts[port]>1);return port;}
Port.equal=port_cmp
Port.toString=port_to_string
Port.ofString=port_of_string
Port.prv2pub=prv2pub
Port.random=uniqport
Port.unique=uniqport
Private.decode=prv_decode
Private.encode=prv_encode
Private.equal=prv_cmp
Private.number=prv_number
Private.ofString=prv_of_string
Private.restrict=prv_restrict
Private.rights=prv_rights
Private.rights_check=prv_rights_check
Private.toString=prv_to_string
Capability.toString=cap_to_string
Capability.ofString=cap_of_string
var Security={current:function(module){current=module.current;Aios=module;},PORT_SIZE:PORT_SIZE,PRIV_SIZE:PRIV_SIZE,Rights:Rights,Private:Private,Capability:Capability,Port:Port,nilport:Port(),nilpriv:Private(0,0,Port()),nilcap:Capability(Port(),Private(0,0,Port())),one_way:one_way,prv2pub:prv2pub,}
module.exports=Security;};BundleModuleCode['com/pwgen']=function(module,exports){var Crypto=Require('os/crypto.rand');module.exports.generate=function(options){function numgen(options){var arr=new Uint8Array(options.length||8);getRandomValues(arr);return arr;}
function pwgen(options){var localName,consonant,letter,vowel,pattern=options.pattern,char="",n,i,validChars=[],prefix=options.prefix;letter=/[a-zA-Z]$/;vowel=/[aeiouAEIOU]$/;consonant=/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]$/;if(options.length==null){options.length=10;}
if(pattern==null){pattern=/\w/;}
if(prefix==null){prefix='';}
if(!options.memorable){for(i=33;126>i;i+=1){char=String.fromCharCode(i);if(char.match(pattern)){validChars.push(char);}}
if(!validChars.length){throw new Error("Could not find characters that match the "+"password pattern "+pattern+". Patterns must match individual "+"characters, not the password as a whole.");}}
while(prefix.length<options.length){if(options.memorable){if(prefix.match(consonant)){pattern=vowel;}else{pattern=consonant;}
n=Crypto.randomByte(33,126);char=String.fromCharCode(n);}else{char=validChars[rand(0,validChars.length)];}
if(options.lowercase)char=char.toLowerCase();else if(options.uppercase)char=char.toUpperCase();if(char.match(pattern)){prefix=""+prefix+char;}}
return prefix;};function rand(min,max){var key,value,arr=new Uint8Array(max);getRandomValues(arr);for(key in arr){if(arr.hasOwnProperty(key)){value=arr[key];if(value>min&&value<max){return value;}}}
return rand(min,max);}
function getRandomValues(buf){var bytes=Crypto.randomBytes(buf.length);buf.set(bytes);}
if(options.number)
return numgen(options)
else
return pwgen(options);};};BundleModuleCode['os/crypto.rand']=function(module,exports){var crypto=global.crypto||global.msCrypto;if(!crypto&&typeof require!='undefined')try{crypto=global.crypto=require('require')}catch(e){};var twister;var MersenneTwister=function(seed){if(seed==undefined){seed=new Date().getTime();seed*=Math.random()*91713;seed|=0;}
this.N=624;this.M=397;this.MATRIX_A=0x9908b0df;this.UPPER_MASK=0x80000000;this.LOWER_MASK=0x7fffffff;this.mt=new Array(this.N);this.mti=this.N+1;if(seed.constructor==Array){this.init_by_array(seed,seed.length);}
else{this.init_seed(seed);}}
MersenneTwister.prototype.init_seed=function(s){this.mt[0]=s>>>0;for(this.mti=1;this.mti<this.N;this.mti++){var s=this.mt[this.mti-1]^(this.mt[this.mti-1]>>>30);this.mt[this.mti]=(((((s&0xffff0000)>>>16)*1812433253)<<16)+(s&0x0000ffff)*1812433253)
+this.mti;this.mt[this.mti]>>>=0;}}
MersenneTwister.prototype.init_by_array=function(init_key,key_length){var i,j,k;this.init_seed(19650218);i=1;j=0;k=(this.N>key_length?this.N:key_length);for(;k;k--){var s=this.mt[i-1]^(this.mt[i-1]>>>30)
this.mt[i]=(this.mt[i]^(((((s&0xffff0000)>>>16)*1664525)<<16)+((s&0x0000ffff)*1664525)))
+init_key[j]+j;this.mt[i]>>>=0;i++;j++;if(i>=this.N){this.mt[0]=this.mt[this.N-1];i=1;}
if(j>=key_length)j=0;}
for(k=this.N-1;k;k--){var s=this.mt[i-1]^(this.mt[i-1]>>>30);this.mt[i]=(this.mt[i]^(((((s&0xffff0000)>>>16)*1566083941)<<16)+(s&0x0000ffff)*1566083941))
-i;this.mt[i]>>>=0;i++;if(i>=this.N){this.mt[0]=this.mt[this.N-1];i=1;}}
this.mt[0]=0x80000000;}
MersenneTwister.prototype.random_int=function(){var y;var mag01=new Array(0x0,this.MATRIX_A);if(this.mti>=this.N){var kk;if(this.mti==this.N+1)
this.init_seed(5489);for(kk=0;kk<this.N-this.M;kk++){y=(this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);this.mt[kk]=this.mt[kk+this.M]^(y>>>1)^mag01[y&0x1];}
for(;kk<this.N-1;kk++){y=(this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);this.mt[kk]=this.mt[kk+(this.M-this.N)]^(y>>>1)^mag01[y&0x1];}
y=(this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);this.mt[this.N-1]=this.mt[this.M-1]^(y>>>1)^mag01[y&0x1];this.mti=0;}
y=this.mt[this.mti++];y^=(y>>>11);y^=(y<<7)&0x9d2c5680;y^=(y<<15)&0xefc60000;y^=(y>>>18);return y>>>0;}
MersenneTwister.prototype.random_int31=function(){return(this.random_int()>>>1);}
MersenneTwister.prototype.random_incl=function(){return this.random_int()*(1.0/4294967295.0);}
MersenneTwister.prototype.random=function(){return this.random_int()*(1.0/4294967296.0);}
MersenneTwister.prototype.random_excl=function(){return(this.random_int()+0.5)*(1.0/4294967296.0);}
MersenneTwister.prototype.random_long=function(){var a=this.random_int()>>>5,b=this.random_int()>>>6;return(a*67108864.0+b)*(1.0/9007199254740992.0);}
function polyfill(){twister=new MersenneTwister();if(!crypto)crypto=global.crypto={};crypto.getRandomValues=function getRandomValues(abv){var l=abv.length
while(l--){abv[l]=Math.floor(twister.random()*256)}
return abv}
if(!global.Uint8Array&&!Uint8Array)throw new Error('crypto.rand: No Uint8Array found!');if(!global.Uint8Array)global.Uint8Array=Uint8Array;}
function randomByte(min,max){if(!twister)twister=new MersenneTwister();return Math.floor(twister.random()*(max-min))+min;}
function randomBytes(size,cb){if(size>65536)throw new Error('requested too many random bytes')
if(!crypto||!crypto.getRandomValues)polyfill();var rawBytes=new global.Uint8Array(size);if(size>0){crypto.getRandomValues(rawBytes);}
var bytes=new Buffer(rawBytes);if(typeof cb==='function'){cb(null,bytes)}
return bytes}
module.exports={randomByte:randomByte,randomBytes:randomBytes}};BundleModuleCode['jam/ampRPC']=function(module,exports){var Buf=Require('dos/buf');var Net=Require('dos/network');var Command=Net.Command;var Status=Net.Status;var COM=Require('jam/ampCOM');var current=none;var Aios=none;var Std={info:function(node,obj,callback){var node0=current.node;var to=COM.lookupNode(node0,node);if(to){to.link.control({cmd:COM.Command.STD_INFO,args:obj,},to.url,function(reply){callback(reply)})}},status:function(node,obj,callback){var node0=current.node;var to=COM.lookupNode(node0,node);if(to){to.link.control({cmd:COM.Command.STD_STATUS,args:obj,},to.url,function(reply){callback(reply)})}},}
var Run={stun:function(node,agent){},}
module.exports={current:function(module){current=module.current;Aios=module;},Run:Run,Std:Std};};BundleModuleCode['jam/ampUDP']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Sec=Require('jam/security');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,obj2url=COM.obj2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,doUntilAck=COM.doUntilAck,getNetworkIP=COM.getNetworkIP,magic=COM.options.magic;module.exports.current=function(module){current=module.current;Aios=module;};var dgram=Require('dgram');amp.udp=function(options){var self=this;options=checkOptions(options,{});this.proto='udp';this.options=options;if(options.oneway&&options.multicast)this.err('Invalid: Both ONEWAY and MULTICAST modes enabled!');this.verbose=checkOption(options.verbose,0);if(!options.rcv)options.rcv=url2addr('localhost:*');this.dir=options.dir;this.rcv=options.rcv;this.broker=options.broker;this.node=options.node;this.port=options.port||Net.uniqport();this.secure=this.options.secure;if(this.broker&&!this.broker.port)
Io.err('['+Io.Time()+' AMP] No broker port specified!');this.out=function(msg){Aios.print('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.err=function(msg){Aios.print('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] Error: '+msg);throw'AMP';}
this.links={};if(options.snd){url=addr2url(options.snd,true);this.links[url]={snd:options.snd,tries:0,state:this.broker?AMState.AMS_AWAIT:AMState.AMS_NOTCONNECTED,live:COM.AMC_MAXLIVE};if(this.verbose>0)this.out('Added destiantion route '+url+', '+Io.inspect(this.links[url]));if(!options.multicast)this.url=url;}
if(this.broker){url='*';this.links[url]={tries:0,state:AMState.AMS_RENDEZVOUS,live:COM.options.AMC_MAXLIVE,queue:{pairing:[],lookup:[]}};if(this.verbose>0)this.out('Added default registration route '+url);}
this.rcv.name=options.name;this.mode=options.multicast?AMMode.AMO_MULTICAST:AMMode.AMO_UNICAST;if(options.oneway)this.mode|=AMMode.AMO_ONEWAY;this.sock=dgram.createSocket("udp4");this.dlimit=options.dlimit||512;this.count={rcv:0,snd:0,lnk:0,png:0};this.timer=undefined;this.inwatchdog=false;this.events=[];this.transactions=Comp.hashtbl.create();this.logs=[];this.logging=options.logging||false;if(this.logging){setInterval(function(){self.LOG('print')},5000);}};amp.udp.prototype.LOG=amp.man.prototype.LOG;amp.udp.prototype.addTransaction=amp.man.prototype.addTransaction;amp.udp.prototype.checkState=amp.man.prototype.checkState;amp.udp.prototype.deleteTransaction=amp.man.prototype.deleteTransaction;amp.udp.prototype.emit=amp.man.prototype.emit;amp.udp.prototype.findTransaction=amp.man.prototype.findTransaction;amp.udp.prototype.handle=amp.man.prototype.handle;amp.udp.prototype.on=amp.man.prototype.on;amp.udp.prototype.status=amp.man.prototype.status;amp.udp.prototype.control=function(link,msg,remote){var self=this;switch(msg.type){case'lookup':if(link.queue.lookup[msg.path]){link.queue.lookup[msg.path](msg.data);delete link.queue.lookup[msg.path];}
break;case'registered':if(link.state==AMState.AMS_RENDEZVOUS){link.state=AMState.AMS_REGISTERED;if(this.verbose)self.out('Registered on broker with name '+this.rcv.name);}
break;case'pairing':if(link.state==AMState.AMS_REGISTERED){var punch={type:'punch',from:this.rcv.name,to:msg.client.name},counter=options.TRIES;link.state=AMState.AMS_PAIRING;for(var con in msg.client.connections){doUntilAck(options.TIMER,function(i){counter--;self.send(punch,msg.client.connections[i]);},function(){return counter==0||link.state!=AMState.AMS_PAIRING;},con);}}
break;case'ack':if(link.state==AMState.AMS_PAIRING){if(this.verbose)self.out('Paired with '+msg.from+'('+addr2url(remote)+')');self.links.forEach(function(link2,url){if(url=='*')return;if(link2&&link2.state==AMState.AMS_AWAIT&&link2.snd.name==link.snd.name){var newurl=addr2url(remote,true);self.links[url]=undefined;self.links[newurl]=link2;link2.state=AMState.AMS_NOTCONNECTED;link2.snd.address=remote.address;link2.snd.port=remote.port;if(self.mode&AMMode.AMO_UNICAST)self.url=newurl,self;}});link.state=AMState.AMS_RENDEZVOUS;if(link.queue.pairing.length)
link.snd={name:link.queue.pairing.shift().snd.name};else
link.snd=undefined;self.watchdog(true);}
break;case'punch':if(msg.to==this.rcv.name){this.send({type:'ack',from:this.rcv.name},remote);}
break;}}
amp.udp.prototype.init=function(callback){if(callback)callback();};amp.udp.prototype.link=function(snd,connect,key){var self=this,url,buf=Buf.Buffer(),sock=this.sock;if(this.verbose>1)this.out('amp.link: to '+(snd&&snd.address)+':'+((snd&&snd.port)||'*'));snd=this.updateLinkTable(snd||(this.url&&this.links[this.url].snd),connect,key);if(snd&&snd.parameter&&snd.parameter.secure)key=snd.parameter.secure;if(!snd)return this.watchdog(true);Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMLINK);Buf.buf_put_port(buf,this.port);Buf.buf_put_string(buf,this.node?this.node.id:'*');Buf.buf_put_string(buf,key?key:'');this.count.snd+=Buf.length(buf);this.count.lnk++;sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){sock.close();self.emit('error',err);}});};amp.udp.prototype.lookup=function(path,callback){var link=this.links['*'];if(!link&&callback)return callback([]);if(callback)link.queue.lookup[path]=callback;this.send({type:'lookup',name:this.rcv.name,linfo:this.rcv,data:path},this.broker,function(){});}
amp.udp.prototype.lookupLinkTable=function(snd){if(this.url)return this.links[this.url];if(!snd)return;var url=obj2url(snd);return this.links[url];}
amp.udp.prototype.pairing=function(link){if(!this.links['*'].snd){this.links['*'].snd={name:link.snd.name};this.watchdog(true);}else{this.links['*'].queue.pairing.push(link);}}
amp.udp.prototype.ping=function(snd){var self=this,buf=Buf.Buffer(),sock=this.sock;Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMPING);Buf.buf_put_port(buf,this.port);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('amp.udp.ping: no destinataion set (snd==null)');if(this.verbose>1)this.out('amp.ping: to '+addr2url(snd));this.count.snd+=Buf.length(buf);this.count.png++;sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){sock.close();self.emit('error',err);}});};amp.udp.prototype.pong=function(snd){var self=this,buf=Buf.Buffer(),sock=this.sock;Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMPONG);Buf.buf_put_port(buf,this.port);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('amp.udp.pong: no destinataion set (snd==null)');if(this.verbose>1)this.out('amp.pong: to '+addr2url(snd));this.count.snd+=Buf.length(buf);this.count.png++;sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){sock.close();self.emit('error',err);}});};amp.udp.prototype.receiver=function(callback,rcv){var self=this;if(rcv==undefined||rcv.address==undefined)rcv={},rcv.address=this.rcv.address;if(rcv.port==undefined)rcv.port=this.rcv.port;if(callback)this.callback=callback;var buf=Buf.Buffer();var sock=this.sock;sock.on('listening',function(){var address=sock.address();if(!rcv.port)self.rcv.port=rcv.port=address.port;if(self.verbose>1)self.out('UDP receiver listening on '+addr2url(rcv));if(self.dir.ip=='*')self.dir=Aios.DIR.IP(self.rcv.port);getNetworkIP(undefined,function(err,ip){if(!err)self.rcv.address=ip;if(self.verbose)self.out('IP port '+addr2url(self.rcv)+' (proto '+self.options.proto+')');if(err)return self.out("! Unable to obtain network connection information: "+err);});});sock.on('error',function(err){Io.out('[AMP] UDP error: '+err);self.sock.close();});sock.on('message',function(message,remote){var handler,dfrags,dlist,msgtyp,tid,ipport,discard,off,size,thisnum,transaction,more,port,addr,url,data,msg;remote.address=remote.address.replace(/^::ffff:/,'')
Buf.buf_init(buf);Buf.buf_of_str(buf,message);self.count.rcv+=message.length;msg={};if(message.length>=10){msg.magic=Buf.buf_get_int16(buf);if(msg.magic!=magic)return;msg.type=Buf.buf_get_int16(buf);discard=false;if(self.verbose>1){url=addr2url(remote,true);self.out('receiver: Receiving Message from '+url+' ['+message.length+'] '+
AMMessageType.print(msg.type)+' in state '+
(self.mode&AMMode.AMO_MULTICAST?(self.links[url]&&AMState.print(self.links[url].state)):(self.links[self.url]&&AMState.print(self.links[self.url].state))));}
switch(msg.type){case AMMessageType.AMMRPCHEAD:if(!self.checkState(AMState.AMS_CONNECTED,remote))return;msg.tid=Buf.buf_get_int16(buf);msg.port=Buf.buf_get_port(buf);msg.cmd=Buf.buf_get_int16(buf);msg.size=Buf.buf_get_int32(buf);msg.frags=Buf.buf_get_int16(buf);msg.data=Buf.Buffer();self.handle(msg,remote);break;case AMMessageType.AMMRPCDATA:if(!self.checkState(AMState.AMS_CONNECTED,remote))return;msg.tid=Buf.buf_get_int16(buf);msg.port=Buf.buf_get_port(buf);msg.off=Buf.buf_get_int32(buf);msg.size=Buf.buf_get_int16(buf);msg.more=Buf.buf_get_int16(buf);msg.data=buf;self.handle(msg,remote);break;case AMMessageType.AMMPING:msg.port=Buf.buf_get_port(buf);self.handle(msg,remote);break;case AMMessageType.AMMPONG:msg.port=Buf.buf_get_port(buf);self.handle(msg,remote);break;case AMMessageType.AMMLINK:msg.port=Buf.buf_get_port(buf);msg.node=Buf.buf_get_string(buf);msg.secure=Buf.buf_get_string(buf);if(msg.secure!='')msg.secure=Sec.Port.ofString(msg.secure);self.handle(msg,remote);break;case AMMessageType.AMMUNLINK:msg.port=Buf.buf_get_port(buf);self.handle(msg,remote);break;case AMMessageType.AMMCONTROL:msg.port=Buf.buf_get_port(buf);msg.data=Buf.buf_get_string(buf);self.handle(msg,remote);break;}}});};amp.udp.prototype.request=function(cmd,msg,snd){var self=this,buf=Buf.Buffer(),sock=this.sock,size=msg.data.length,frags=div((size+self.dlimit-1),self.dlimit),tid=msg.tid||Comp.random.int(65536/2);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('amp.udp.request: no destinataion set(snd==null)');Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMRPCHEAD);Buf.buf_put_int16(buf,tid);Buf.buf_put_port(buf,this.port);Buf.buf_put_int16(buf,cmd);Buf.buf_put_int32(buf,size);Buf.buf_put_int16(buf,frags);if(self.verbose>1)self.out('Send AMMRPCHEAD tid='+tid+' @'+Comp.pervasives.mtime());this.count.snd+=Buf.length(buf);sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(self.verbose>1)self.out('Send AMMRPCHEAD tid='+tid+'. Done @'+Comp.pervasives.mtime());if(err){if(self.verbose>1)self.out('AMMRPCHEAD Error: '+err);sock.close();if(callback)callback(Status.STD_IOERR,err);}else{if(size>0){var dsend=function(n,off){var fsize,more;if(frags==1)fsize=size;else if(n<frags)fsize=self.dlimit;else fsize=size-off;if(n==frags)more=0;else more=1;Buf.buf_init(buf);Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMRPCDATA);Buf.buf_put_int16(buf,tid);Buf.buf_put_port(buf,self.port);Buf.buf_put_int32(buf,off);Buf.buf_put_int16(buf,fsize);Buf.buf_put_int16(buf,more);Buf.buf_put_buf(buf,msg,off,fsize);if(self.verbose>1)self.out('Send AMMRPCDATA tid='+tid+'. Start #'+n+'/'+frags+' @'+Comp.pervasives.mtime());self.count.snd+=Buf.length(buf);sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(self.verbose>1)self.out('Send AMMRPCDATA tid='+tid+'. Done #'+n+'/'+frags+' @'+Comp.pervasives.mtime());if(err){if(self.verbose>1)self.out('AMMRPCDATA Error: '+err);sock.close();self.emit('error',err);}
else if(n<frags)dsend(n+1,off+fsize);});};dsend(1,0);}}});};amp.udp.prototype.reply=function(cmd,msg,snd){this.request(cmd,msg,snd);}
amp.udp.prototype.scan=function(snd,response,callback){var self=this,msg={magic:magic};msg.type=response?AMMessageType.AMMACK:AMMessageType.AMMSCAN;if(this.verbose>1)this.out('amp.scan: to '+addr2url(snd));}
amp.udp.prototype.send=function(msg,snd){var buf=Buf.Buffer(),sock=this.sock,data=JSON.stringify(msg);this.LOG('snd',msg);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('amp.udp.send: no destinataion set (snd==null)');if(this.verbose>1)this.out('amp.send: to '+addr2url(snd)+': '+data);Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMCONTROL);Buf.buf_put_port(buf,this.port);Buf.buf_put_string(buf,data);this.count.snd+=Buf.length(buf);sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err)self.emit('error',err);});};amp.udp.prototype.start=function(callback){var self=this,link,startwatch=false
s=this.secure?' (security port '+Sec.Port.toString(this.secure)+')':'';if(this.verbose>0)this.out('Starting '+(this.rcv.name?(this.rcv.name+' '):'')+addr2url(this.rcv)+
(this.mode&AMMode.AMO_UNICAST&&this.url?(' -> '+this.url):'')+' ['+AMMode.print(this.mode)+'] (proto '+this.proto+')'+s);if(this.mode&AMMode.AMO_UNICAST){if(this.url){link=this.links[this.url];link.state=this.broker?AMState.AMS_AWAIT:AMState.AMS_NOTCONNECTED;if(link.snd&&!(this.mode&AMMode.AMO_ONEWAY))
startwatch=true;if(link.snd&&(this.mode&AMMode.AMO_ONEWAY))
this.emit('route+',addr2url(link.snd,true));if(this.broker)this.pairing(link);}}
if(this.broker){startwatch=true;}
if(startwatch)this.watchdog(true);if(!this.sock){this.sock=dgram.createSocket("udp4");this.receiver();}
this.sock.bind(this.rcv.port,undefined,function(arg){if(callback)callback();});}
amp.udp.prototype.stop=function(callback){if(this.mode&AMMode.AMO_MULTICAST)
for(var p in this.links){if(this.links[p]){this.unlink(this.links[p].snd);this.links[p].state=AMState.AMS_NOTCONNECTED;}}
else
this.links.state=AMState.AMS_NOTCONNECTED;if(this.timer)clearTimeout(this.timer),this.timer=undefined;if(this.sock)this.sock.close(),this.sock=undefined;if(callback)callback();}
amp.udp.prototype.unlink=function(snd){var self=this,buf=Buf.Buffer(),url=snd?addr2url(snd,true):null,sock=this.sock;if(!this.links[url||this.url]||this.links[url||this.url].state!=AMState.AMS_CONNECTED)return;this.emit('route-',addr2url(snd,true));if(this.mode&AMMode.AMO_ONEWAY)return;Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMUNLINK);Buf.buf_put_port(buf,this.port);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;url=this.url;}
if(snd==undefined)this.err('amp.udp.unlink: no destination (snd==null)');if(this.verbose>1)this.out('amp.unlink: to '+addr2url(snd));this.count.snd+=Buf.length(buf);sock.send(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){sock.close();self.emit('error',err)}});this.links[url].state=AMState.AMS_NOTCONNECTED;if(!this.links[url].snd.connect)this.links[url].snd={};if(this.broker){this.links[url]=undefined;if(this.url)this.url=undefined;}
if(this.verbose)this.out('Unlinked '+addr2url(snd));};amp.udp.prototype.updateLinkTable=function(snd,connect){var link;if(!snd)this.err('amp.udp.link: no destinataion set (snd==null)');url=addr2url(snd,true);if(this.broker&&!snd.port&&!this.links[url]){link=this.links[url]={state:AMState.AMS_AWAIT,tries:0,connect:connect,live:options.AMC_MAXLIVE,snd:{name:snd.address}};if(connect)link.snd.connect=true;if(this.mode&AMMode.AMO_UNICAST)this.url=url;this.pairing(link);return;}else if(this.mode&AMMode.AMO_UNICAST){if(!this.links[url])link=this.links[url]={state:AMState.AMS_NOTCONNECTED};else link=this.links[url];if(snd!=undefined&&snd.address!=undefined&&snd.port!=undefined&&!link.snd)
link.snd=snd;if(snd!=undefined&&snd.address!=undefined&&snd.port!=undefined&&snd.port!='*'&&link.snd.address==undefined)
link.snd.address=snd.address;if(snd!=undefined&&snd.port!=undefined&&link.snd.port==undefined)
link.snd.port=snd.port;if(connect)link.snd.connect=true;if((link.state&&link.state!=AMState.AMS_NOTCONNECTED&&link.state!=AMState.AMS_PAIRED)||this.mode&AMMode.AMO_ONEWAY)return;if(typeof link.snd.port=='string')return;if(snd==undefined||snd.address==undefined)snd={},snd.address=link.snd.address;if(snd.port==undefined)snd.port=link.snd.port;this.url=url;}else{if(!this.links[url]||!this.links[url].snd.address)
link=this.links[url]={snd:snd,state:AMState.AMS_NOTCONNECTED,tries:0,connect:connect,live:options.AMC_MAXLIVE};if(!this.inwatchdog&&connect){this.watchdog(true);return;}}
return snd;}
amp.udp.prototype.watchdog=function(run,immed){var self=this;if(this.timer)clearTimeout(self.timer),this.timer=undefined;if(run)this.timer=setTimeout(function(){var con,to,tokens;if(!self.timer||!self.sock||self.inwatchdog)return;self.timer=undefined;self.inwatchdog=true;function handle(obj,url){if(self.verbose>1)self.out('Watchdog: handle link '+
url+(obj.snd?('('+obj2url(obj.snd)+')'):'')+' in state '+AMState.print(obj.state)+'['+obj.live+'] '+
(obj.tries!=undefined?('[#'+obj.tries+']'):''));switch(obj.state){case AMState.AMS_CONNECTED:if(obj.live==0){if(self.verbose>0)
self.out('Endpoint '+addr2url(obj.snd)+' not responding, propably dead. Unlinking...');if(self.mode&AMMode.AMO_MULTICAST)self.unlink(obj.snd);else self.unlink();obj.state=AMState.AMS_NOTCONNECTED;if(!obj.snd.connect)obj.snd={};if(self.broker){self.watchdog(true);if(self.links['*']){self.links['*'].state=AMState.AMS_RENDEZVOUS;}}}else{obj.tries=0;obj.live--;self.watchdog(true);if(self.mode&AMMode.AMO_MULTICAST)self.ping(obj.snd);else self.ping();}
break;case AMState.AMS_NOTCONNECTED:if(!obj.snd)return;if(obj.snd.port&&typeof obj.snd.port=='string'){tokens=obj.snd.port.split('-');if(tokens.length==2)obj.range=[Number(tokens[0]),Number(tokens[1])];}
if(obj.range){obj.snd.port=Comp.random.interval(obj.range[0],obj.range[1]);if(self.verbose>0)
self.out('Trying link to '+addr2url(obj.snd));if(self.mode&AMMode.AMO_MULTICAST)self.link(obj.snd);else self.link();obj.tries++;if(obj.tries<options.TRIES)self.watchdog(true);else{obj.snd={},obj.tries=0,obj.range=undefined;}}else if(obj.snd.port&&typeof obj.snd.port=='number'){if(self.verbose>0&&obj.tries==0)
self.out('Trying link to '+addr2url(obj.snd));if(self.mode&AMMode.AMO_MULTICAST)self.link(obj.snd);else self.link();obj.tries++;if(obj.tries<options.TRIES)self.watchdog(true);else{self.out('Giving up to link '+addr2url(obj.snd));self.emit('error','link',addr2url(obj.snd,true));obj.snd={},obj.tries=0;}}
break;case AMState.AMS_RENDEZVOUS:obj.next=Aios.time()+options.REGTMO;obj.interval=options.REGTMO;self.send({type:'register',name:self.rcv.name,linfo:self.rcv},self.broker,function(){});self.watchdog(true);break;case AMState.AMS_REGISTERED:if(obj.snd&&obj.snd.name&&obj.tries<options.TRIES){obj.tries++;self.send({type:'pair',from:self.rcv.name,to:obj.snd.name},self.broker,function(){});}else if(options.REGTMO&&Aios.time()>obj.next){obj.interval*=2;obj.interval=Math.min(obj.interval,options.REGTMO*8);obj.next=Aios.time()+obj.interval;self.send({type:'register',name:self.rcv.name,linfo:self.rcv},self.broker,function(){});}
self.watchdog(true);break;}}
for(var p in self.links)if(self.links[p])handle(self.links[p],p);self.inwatchdog=false;},immed?0:options.TIMER);};};BundleModuleCode['jam/ampTCP']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Sec=Require('jam/security');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,obj2url=COM.obj2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,doUntilAck=COM.doUntilAck,getNetworkIP=COM.getNetworkIP,magic=COM.options.magic;module.exports.current=function(module){current=module.current;Aios=module;};var net=require('net');var dgram=Require('dgram');amp.tcp=function(options){var self=this;options=checkOptions(options,{});this.options=options;this.proto='tcp';if(options.oneway&&options.multicast)this.err('Invalid: Both ONEWAY and MULTICAST modes enabled!');this.verbose=checkOption(options.verbose,0);if(!options.rcv)options.rcv=url2addr('localhost:*');if(this.verbose>2)console.log(options);this.dir=options.dir;this.rcv=options.rcv;this.broker=options.broker;this.node=options.node;this.port=options.port||Net.uniqport();this.secure=this.options.secure;this.client={};this.keepAlive=checkOption(options.keepAlive,false);this.sharedSocket=checkOption(options.sharedSocket,false);if(this.broker&&!this.broker.port)
Io.err('[AMP] No broker port specified!');this.out=function(msg){Aios.print('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.err=function(msg){Aios.print('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] Error: '+msg);throw'AMP';}
this.links={};if(options.snd){url=addr2url(options.snd,true);this.links[url]={snd:options.snd,tries:0,state:this.broker?AMState.AMS_AWAIT:AMState.AMS_NOTCONNECTED,live:COM.AMC_MAXLIVE};if(this.verbose>0)this.out('Added destiantion route '+url+', '+Io.inspect(this.links[url]));if(!options.multicast)this.url=url;}
if(this.broker){url='*';this.links[url]={tries:0,state:AMState.AMS_RENDEZVOUS,live:COM.options.AMC_MAXLIVE,queue:{pairing:[],lookup:[]}};if(this.verbose>0)this.out('Added default registration route '+url);}
this.rcv.name=options.name;this.mode=options.multicast?AMMode.AMO_MULTICAST:AMMode.AMO_UNICAST;if(options.oneway)this.mode|=AMMode.AMO_ONEWAY;this.sock=undefined;this.count={rcv:0,snd:0,lnk:0,png:0};this.timer=undefined;this.inwatchdog=false;this.events=[];this.transactions=Comp.hashtbl.create();this.logs=[];this.logging=options.logging||false;if(this.logging){setInterval(function(){self.LOG('print')},5000);}};amp.tcp.prototype.LOG=amp.man.prototype.LOG;amp.tcp.prototype.addTransaction=amp.man.prototype.addTransaction;amp.tcp.prototype.checkState=amp.man.prototype.checkState;amp.tcp.prototype.deleteTransaction=amp.man.prototype.deleteTransaction;amp.tcp.prototype.emit=amp.man.prototype.emit;amp.tcp.prototype.findTransaction=amp.man.prototype.findTransaction;amp.tcp.prototype.handle=amp.man.prototype.handle;amp.tcp.prototype.on=amp.man.prototype.on;amp.tcp.prototype.status=amp.man.prototype.status;amp.tcp.prototype.init=function(callback){if(callback)callback();};amp.tcp.prototype.link=function(snd,connect,key){var self=this,url=addr2url(snd,true),buf=Buf.Buffer();if(this.verbose>1)this.out('amp.link: to '+(snd&&snd.address)+':'+((snd&&snd.port)||'*'));snd=this.updateLinkTable(snd||(this.url&&this.links[this.url].snd),connect,key);if(snd&&snd.parameter&&snd.parameter.secure)key=snd.parameter.secure;if(!snd)return this.watchdog(true);if((this.keepAlive||this.sharedSocket)&&(!this.client[url]||!this.client[url].socket)){if(!this.client[url])this.client[url]={busy:false,id:Math.random(),connected:false,queue:[]}
if(!this.client[url].socket){if(self.verbose>1)console.log('amp.link Creating keepAlive socket for client '+url);this.client[url].socket=new net.Socket();this.client[url].connected=false;this.client[url].socket.on('close',function(){console.log('close',url);delete self.client[url];});this.client[url].socket.on('error',function(err){if(self.verbose>1)console.log('error',url,err)
delete self.client[url];});}
if(this.sharedSocket&&!this.rcv.port){if(self.verbose>1)console.log('amp.link Creating sharedSocket receiver for client '+url);this.receiverSocket(this.client[url].socket);if(!this.inwatchdog){this.watchdog(true);}}
this.client[url].busy=true;console.log('Connecting to client '+url);this.client[url].socket.connect(snd.port,snd.address,function(){var rcv=self.sharedSocket?self.client[url].socket.address():self.rcv;if(self.verbose>1)console.log('amp.link.connect:',url,rcv)
self.client[url].rcv=rcv;self.client[url].busy=false;send(self.client[url].rcv.port);});this.client[url].connected=true;return;}
function send(rcvport){if(self.verbose>1)self.out('amp.link.send: '+url+' rcvport='+rcvport);Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMLINK);Buf.buf_put_port(buf,self.port);Buf.buf_put_string(buf,self.node?self.node.id:'*');Buf.buf_put_string(buf,key?key:'');Buf.buf_put_int32(buf,rcvport);self.count.snd+=Buf.length(buf);self.count.lnk++;self.write(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){self.emit('error',err);}});}
send(this.sharedSocket&&this.client[url]&&this.client[url].rcv?this.client[url].rcv.port:this.rcv.port);};amp.tcp.prototype.lookup=function(path,callback){var link=this.links['*'];if(!link&&callback)return callback([]);if(callback)link.queue.lookup[path]=callback;this.send({type:'lookup',name:this.rcv.name,linfo:this.rcv,data:path},this.broker,function(){});}
amp.tcp.prototype.lookupLinkTable=function(snd){if(this.url)return this.links[this.url];if(!snd)return;var url=obj2url(snd);return this.links[url];}
amp.tcp.prototype.ping=function(snd){var self=this,buf=Buf.Buffer();Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMPING);Buf.buf_put_port(buf,this.port);if(!this.sharedSocket)
Buf.buf_put_int32(buf,this.rcv.port);else
Buf.buf_put_int32(buf,this.client[url]&&this.client[url].rcv?this.client[url].rcv.port:this.rcv.port);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('ping: snd=null');if(this.verbose>1)this.out('amp.ping: to '+addr2url(snd));this.count.snd+=Buf.length(buf);this.count.png++;this.write(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){self.emit('error',err);}});};amp.tcp.prototype.pong=function(snd){var self=this,buf=Buf.Buffer();Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMPONG);Buf.buf_put_port(buf,this.port);if(!this.sharedSocket)
Buf.buf_put_int32(buf,this.rcv.port);else
Buf.buf_put_int32(buf,this.client[url]&&this.client[url].rcv?this.client[url].rcv.port:this.rcv.port);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('pong: snd=null');if(this.verbose>1)this.out('amp.pong: to '+addr2url(snd));this.count.snd+=Buf.length(buf);this.count.png++;this.write(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){self.emit('error',err);}});};amp.tcp.prototype.receiverHandler=function handler(message,remote){var self=this,handler,dfrags,dlist,msgtyp,tid,ipport,discard,off,size,thisnum,transaction,more,port,addr,url,data,msg,url0=addr2url(remote,true);var buf=Buf.Buffer();Buf.buf_init(buf);Buf.buf_of_str(buf,message);self.count.rcv+=message.length;msg={};if(message.length>=10){msg.magic=Buf.buf_get_int16(buf);if(msg.magic!=magic)return;msg.type=Buf.buf_get_int16(buf);discard=false;if(self.verbose>1){url=addr2url(remote,true);self.out('receiver: Receiving Message from '+url+' ['+message.length+'] '+
AMMessageType.print(msg.type));}
switch(msg.type){case AMMessageType.AMMRPCHEADDATA:msg.tid=Buf.buf_get_int16(buf);msg.port=Buf.buf_get_port(buf);msg.sndport=Buf.buf_get_int32(buf);remote.port=msg.sndport;url=addr2url(remote,true);if(self.verbose>1)self.out('receiver: Receiving Message in state '+
(self.mode&AMMode.AMO_MULTICAST?(self.links[url]&&AMState.print(self.links[url].state)):(self.links[self.url]&&AMState.print(self.links[self.url].state))));if(!self.checkState(AMState.AMS_CONNECTED,remote))return;msg.cmd=Buf.buf_get_int16(buf);msg.size=Buf.buf_get_int32(buf);msg.data=buf;msg.frags=0;msg.more=false;self.handle(msg,remote);break;case AMMessageType.AMMPING:msg.port=Buf.buf_get_port(buf);msg.sndport=Buf.buf_get_int32(buf);remote.port=msg.sndport;url=addr2url(remote,true);if(self.verbose>1)self.out('receiver: Receiving Message in state '+
(self.mode&AMMode.AMO_MULTICAST?(self.links[url]&&AMState.print(self.links[url].state)):(self.links[self.url]&&AMState.print(self.links[self.url].state))));self.handle(msg,remote);break;case AMMessageType.AMMPONG:msg.port=Buf.buf_get_port(buf);msg.sndport=Buf.buf_get_int32(buf);remote.port=msg.sndport;url=addr2url(remote,true);if(self.verbose>1)self.out('receiver: Receiving Message in state '+
(self.mode&AMMode.AMO_MULTICAST?(self.links[url]&&AMState.print(self.links[url].state)):(self.links[self.url]&&AMState.print(self.links[self.url].state))));self.handle(msg,remote);break;case AMMessageType.AMMLINK:msg.port=Buf.buf_get_port(buf);msg.node=Buf.buf_get_string(buf);msg.secure=Buf.buf_get_string(buf);if(msg.secure!='')msg.secure=Sec.Port.ofString(msg.secure);msg.sndport=Buf.buf_get_int32(buf);var oldport=remote.port;remote.port=msg.sndport;url=addr2url(remote,true);if(remote.port!=oldport){if(self.verbose>1)console.log('LINK NAT fix',remote.port,oldport,url,url0,typeof self.client[url0])
if(self.client[url0]){self.client[url]={address:remote.address,port:remote.port,busy:self.client[url0].busy,connected:self.client[url0].connected,queue:self.client[url0].queue,socket:self.client[url0].socket};}}
if(self.verbose>1)self.out('receiver: Receiving Message in state '+
(self.mode&AMMode.AMO_MULTICAST?(self.links[url]&&AMState.print(self.links[url].state)):(self.links[self.url]&&AMState.print(self.links[self.url].state))));self.handle(msg,remote);break;case AMMessageType.AMMUNLINK:msg.port=Buf.buf_get_port(buf);msg.sndport=Buf.buf_get_int32(buf);remote.port=msg.sndport;url=addr2url(remote,true);self.handle(msg,remote);break;case AMMessageType.AMMCONTROL:msg.port=Buf.buf_get_port(buf);msg.data=Buf.buf_get_string(buf);self.handle(msg,remote);break;}}};amp.tcp.prototype.receiverSocket=function(sock){var self=this,chunks,remote,expect=0,url;sock.on('data',function(data){var pending;if(!remote){remote={address:sock.remoteAddress.replace(/^::ffff:/,''),port:sock.remotePort};url=addr2url(remote);if(self.sharedSocket&&!self.client[url]){self.client[url]={busy:false,connected:true,socket:sock,queue:[]};}}
if(self.keepAlive||self.sharedSocket){do{if(pending){data=pending;pending=null};if(data.length==0)process.exit();if(data.length==4){expect=data.readInt32LE(0);return;}
else if(expect==0){if(data.length<4)return console.log('uff',data.length);var dataLength=data.slice(0,4);data=data.slice(4);expect=dataLength.readInt32LE(0);}
if(expect){if(chunks&&(data.length+chunks.length)>expect||data.length>expect){var diff=(data.length+(chunks?chunks.length:0))-expect,need=expect-(chunks?chunks.length:0);pending=data.slice(need);data=data.slice(0,need);}}
if(!chunks)chunks=data;else chunks=Buffer.concat([chunks,data]);if(expect&&chunks.length==expect){self.receiverHandler(Buffer(chunks),remote);expect=0;chunks=null;}}while(pending&&pending.length)}else{if(!chunks)chunks=data;else chunks=Buffer.concat([chunks,data]);}});sock.on('end',function(){if(chunks)self.receiverHandler(Buffer(chunks),remote);});if(!this.sharedSocket){sock.on('close',function(data){if(self.sharedSocket&&self.client[url])delete self.client[url];});sock.on('error',function(data){if(self.sharedSocket&&self.client[url])delete self.client[url];});}}
amp.tcp.prototype.receiver=function(callback,rcv){var self=this;if(rcv==undefined||rcv.address==undefined)rcv={},rcv.address=this.rcv.address;if(rcv.port==undefined)rcv.port=this.rcv.port;if(callback)this.callback=callback;if(this.sharedSocket&&rcv.port==undefined){if(this.verbose)this.out('IP port * (proto '+this.options.proto+') SS');return;}
this.sock=net.createServer({keepAlive:this.keepAlive,noDelay:true},this.receiverSocket.bind(this));this.sock.on('listening',function(){var address=self.sock.address();if(!rcv.port)self.rcv.port=rcv.port=address.port;if(self.verbose>1)self.out('TCP receiver listening on '+addr2url(rcv));if(self.dir.ip=='*')self.dir=Aios.DIR.IP(self.rcv.port);getNetworkIP(undefined,function(err,ip){if(!err)self.rcv.address=ip;if(self.verbose)self.out('IP port '+addr2url(self.rcv)+' (proto '+self.options.proto+') '+
(self.keepAlive?'KA ':'')+
(self.sharedSocket?'SS':''));if(err)return self.out("! Unable to obtain network connection information: "+err);});});this.sock.on('error',function(err){Io.out('[AMP] TCP error: '+err);self.sock.close();});};amp.tcp.prototype.request=function(cmd,msg,snd){var self=this,buf=Buf.Buffer(),size=msg.data.length,url=snd?addr2url(snd,true):'',tid=msg.tid||Comp.random.int(65536/2);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('request: request=null');Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMRPCHEADDATA);Buf.buf_put_int16(buf,tid);Buf.buf_put_port(buf,this.port);if(!this.sharedSocket)
Buf.buf_put_int32(buf,this.rcv.port);else
Buf.buf_put_int32(buf,this.client[url]&&this.client[url].rcv?this.client[url].rcv.port:this.rcv.port);Buf.buf_put_int16(buf,cmd);Buf.buf_put_int32(buf,size);Buf.buf_put_buf(buf,msg,0,size);if(self.verbose>1)self.out('Send AMMRPCHEAD tid='+tid+' @'+Comp.pervasives.mtime());this.count.snd+=Buf.length(buf);this.write(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(self.verbose>1)self.out('Send AMMRPCHEADDATA tid='+tid+'. Done @'+Comp.pervasives.mtime());if(err){if(self.verbose>1)self.out('AMMRPCHEADDATA Error: '+err);if(callback)callback(Status.STD_IOERR,err);}});};amp.tcp.prototype.reply=function(cmd,msg,snd){this.request(cmd,msg,snd);}
amp.tcp.prototype.send=function(msg,snd){var buf=Buf.Buffer(),data=JSON.stringify(msg);this.LOG('snd',msg);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;}
if(snd==undefined)this.err('send: snd=null');if(this.verbose>1)this.out('amp.send: to '+addr2url(snd)+': '+data);Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMCONTROL);Buf.buf_put_port(buf,this.port);Buf.buf_put_string(buf,data);this.count.snd+=Buf.length(buf);this.write(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err)self.emit('error',err);});};amp.tcp.prototype.start=function(callback){var self=this,link,startwatch=false,s=this.secure?' (security port '+Sec.Port.toString(this.secure)+')':'';if(this.verbose>0)this.out('Starting '+(this.rcv.name?(this.rcv.name+' '):'')+addr2url(this.rcv)+
(this.mode&AMMode.AMO_UNICAST&&this.url?(' -> '+this.url):'')+' ['+AMMode.print(this.mode)+'] (proto '+this.proto+') '+s);if(this.mode&AMMode.AMO_UNICAST){if(this.url){link=this.links[this.url];link.state=this.broker?AMState.AMS_AWAIT:AMState.AMS_NOTCONNECTED;if(link.snd&&!(this.mode&AMMode.AMO_ONEWAY))
startwatch=true;if(link.snd&&(this.mode&AMMode.AMO_ONEWAY))
this.emit('route+',addr2url(link.snd,true));if(this.broker)this.pairing(link);}}
if(startwatch)this.watchdog(true);if(!this.sock&&!this.sharedSocket&&this.rcv.port){this.receiver();}
if(this.sock){this.sock.listen(this.rcv.port,undefined);}
if(callback)callback();}
amp.tcp.prototype.stop=function(callback){if(this.mode&AMMode.AMO_MULTICAST)
for(var p in this.links){if(this.links[p]){this.unlink(this.links[p].snd);this.links[p].state=AMState.AMS_NOTCONNECTED;}}
else
this.links.state=AMState.AMS_NOTCONNECTED;if(this.timer)clearTimeout(this.timer),this.timer=undefined;if(this.sock)this.sock.close(),this.sock=undefined;for(var p in this.client){if(this.client[p]&&this.client[p].socket){this.client[p].socket.destroy();delete this.client[p];}}
if(callback)callback();}
amp.tcp.prototype.unlink=function(snd){var self=this,buf=Buf.Buffer(),url=snd?addr2url(snd,true):null;if(!this.links[url||this.url]||this.links[url||this.url].state!=AMState.AMS_CONNECTED)return;this.emit('route-',addr2url(snd,true));if(this.mode&AMMode.AMO_ONEWAY)return;Buf.buf_put_int16(buf,magic);Buf.buf_put_int16(buf,AMMessageType.AMMUNLINK);Buf.buf_put_port(buf,this.port);if(!this.sharedSocket)
Buf.buf_put_int32(buf,this.rcv.port);else
Buf.buf_put_int32(buf,this.client[url]&&this.client[url].rcv?this.client[url].rcv.port:this.rcv.port);if(this.mode&AMMode.AMO_UNICAST){if(snd==undefined||snd.address==undefined)snd={},snd.address=this.links[this.url].snd.address;if(snd.port==undefined)snd.port=this.links[this.url].snd.port;url=this.url;}
if(snd==undefined)this.err('unlink: no destination');if(this.verbose>1)this.out('amp.unlink: to '+addr2url(snd));this.count.snd+=Buf.length(buf);this.write(buf.data,0,Buf.length(buf),snd.port,snd.address,function(err){if(err){self.emit('error',err)}});this.links[url].state=AMState.AMS_NOTCONNECTED;if(!this.links[url].snd.connect)this.links[url].snd={};if(this.broker){this.links[url]=undefined;if(this.url)this.url=undefined;}
if(this.client[url]){this.client[url].socket.destroy();delete this.client[url]};if(this.verbose)this.out('Unlinked '+url);};amp.tcp.prototype.updateLinkTable=function(snd,connect){var link;if(!snd)this.err('link: no destinataion set');url=addr2url(snd,true);if(this.broker&&!snd.port&&!this.links[url]){link=this.links[url]={state:AMState.AMS_AWAIT,tries:0,connect:connect,live:options.AMC_MAXLIVE,snd:{name:snd.address}};if(connect)link.snd.connect=true;if(this.mode&AMMode.AMO_UNICAST)this.url=url;this.pairing(link);return;}else if(this.mode&AMMode.AMO_UNICAST){if(!this.links[url])link=this.links[url]={state:AMState.AMS_NOTCONNECTED};else link=this.links[url];if(snd!=undefined&&snd.address!=undefined&&snd.port!=undefined&&!link.snd)
link.snd=snd;if(snd!=undefined&&snd.address!=undefined&&snd.port!=undefined&&snd.port!='*'&&link.snd.address==undefined)
link.snd.address=snd.address;if(snd!=undefined&&snd.port!=undefined&&link.snd.port==undefined)
link.snd.port=snd.port;if(connect)link.snd.connect=true;if((link.state&&link.state!=AMState.AMS_NOTCONNECTED&&link.state!=AMState.AMS_PAIRED)||this.mode&AMMode.AMO_ONEWAY)return;if(typeof link.snd.port=='string')return;if(snd==undefined||snd.address==undefined)snd={},snd.address=link.snd.address;if(snd.port==undefined)snd.port=link.snd.port;this.url=url;}else{url=addr2url(snd,true);if(!this.links[url]||!this.links[url].snd.address)
this.links[url]={snd:snd,state:AMState.AMS_NOTCONNECTED,tries:0,connect:connect,live:options.AMC_MAXLIVE};if(!this.inwatchdog&&connect&&!this.sharedSocket){this.watchdog(true);return;}}
return snd;}
amp.tcp.prototype.watchdog=function(run,immed){var self=this;if(this.timer)clearTimeout(self.timer),this.timer=undefined;if(this.verbose>1)this.out('Starting watchdog run='+run+' immed='+immed);if(run)this.timer=setTimeout(function(){var con,to,tokens;if(!self.timer||(!self.sock&&!self.sharedSocket)||self.inwatchdog)return;self.timer=undefined;self.inwatchdog=true;function handle(obj,url){if(self.verbose>1)self.out('Watchdog: handle link '+
url+(obj.snd?('('+obj2url(obj.snd)+')'):'')+' in state '+AMState.print(obj.state)+
(obj.tries!=undefined?('[#'+obj.tries+']'):''));switch(obj.state){case AMState.AMS_CONNECTED:if(obj.live==0){if(self.verbose>0)
self.out('(TCP) Endpoint '+addr2url(obj.snd)+' not responding, propably dead. Unlinking...');if(self.mode&AMMode.AMO_MULTICAST)self.unlink(obj.snd);else self.unlink();obj.state=AMState.AMS_NOTCONNECTED;if(!obj.snd.connect)obj.snd={};if(self.broker){self.watchdog(true);if(self.links['*']){self.links['*'].state=AMState.AMS_RENDEZVOUS;}}}else{obj.tries=0;obj.live--;self.watchdog(true);if(self.mode&AMMode.AMO_MULTICAST)self.ping(obj.snd);else self.ping();}
break;case AMState.AMS_NOTCONNECTED:if(!obj.snd)return;if(obj.snd.port&&typeof obj.snd.port=='string'){tokens=obj.snd.port.split('-');if(tokens.length==2)obj.range=[Number(tokens[0]),Number(tokens[1])];}
if(obj.range){obj.snd.port=Comp.random.interval(obj.range[0],obj.range[1]);if(self.verbose>0)
self.out('Trying link to '+addr2url(obj.snd));if(self.mode&AMMode.AMO_MULTICAST)self.link(obj.snd);else self.link();obj.tries++;if(obj.tries<options.TRIES)self.watchdog(true);else{obj.snd={},obj.tries=0,obj.range=undefined;}}else if(obj.snd.port&&typeof obj.snd.port=='number'){if(self.verbose>0&&obj.tries==0)
self.out('(TCP) Trying link to '+addr2url(obj.snd));if(self.mode&AMMode.AMO_MULTICAST)self.link(obj.snd);else self.link();obj.tries++;if(obj.tries<options.TRIES)self.watchdog(true);else{self.out('(TCP) Giving up to link '+addr2url(obj.snd));self.emit('error','link',addr2url(obj.snd,true));obj.snd={},obj.tries=0;}}
break;case AMState.AMS_RENDEZVOUS:obj.next=Aios.time()+options.REGTMO;obj.interval=options.REGTMO;self.send({type:'register',name:self.rcv.name,linfo:self.rcv},self.broker,function(){});self.watchdog(true);break;case AMState.AMS_REGISTERED:if(obj.snd&&obj.snd.name&&obj.tries<options.TRIES){obj.tries++;self.send({type:'pair',from:self.rcv.name,to:obj.snd.name},self.broker,function(){});}else if(options.REGTMO&&Aios.time()>obj.next){obj.interval*=2;obj.interval=Math.min(obj.interval,options.REGTMO*8);obj.next=Aios.time()+obj.interval;self.send({type:'register',name:self.rcv.name,linfo:self.rcv},self.broker,function(){});}
self.watchdog(true);break;}}
for(var p in self.links)if(self.links[p])handle(self.links[p],p);self.inwatchdog=false;},immed?0:options.TIMER);};amp.tcp.prototype.write=function(data,off,len,port,address,cb){var self=this,url=addr2url({address:address,port:port});if(off!=0)this.err('tpc.socket.write: buffer offset <> 0');if(this.keepAlive||this.sharedSocket){if(!this.client[url])return;if(this.client[url].busy){this.client[address+':'+port].queue.push([data,off,len,port,address,cb]);return;}
this.client[url].busy=true;function send(){if(!self.client[url])return;var dataLength=Buffer(4);dataLength.writeInt32LE(data.length,0);try{self.client[url].socket.write(dataLength,function(){if(!self.client[url])return;self.client[url].socket.write(data,function(){if(!self.client[url])return;if(cb)cb();self.client[url].busy=false;if(self.client[url].queue.length){self.client[url].socket.write.apply(self,self.client[url].shift());}})});}catch(e){if(self.verbose)self.out(url+': '+e);delete self.client[url];}}
if(!this.client[url].connected){console.log('write.connect',url);this.client[url].busy=true;this.client[url].socket.connect(port,address,function(){self.client[url].busy=false;send();});this.client[url].connected=true;}else{send();}}else{var client=new net.Socket();client.on('error',function(e){if(cb)cb(e.toString())})
client.connect(port,address,function(){client.write(data,function(){client.destroy();if(cb)cb();});});}}};BundleModuleCode['jam/ampStream']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,getNetworkIP=COM.getNetworkIP;module.exports.current=function(module){current=module.current;Aios=module;};amp.stream=function(options){var self=this;options=checkOptions(options,{});this.options=options;this.verbose=checkOption(options.verbose,0);this.dir=options.dir;this.mode=AMMode.AMO_UNICAST|AMMode.AMO_STATIC|(options.mode=='object'?AMMode.AMO_OBJECT:AMMode.AMO_BUFFER);this.port=options.port||Net.uniqport();this.id=Net.Print.port(this.port);this.links={state:AMState.AMS_NOTCONNECTED};this.sock=options.sock;this.dlimit=options.dlimit||512;this.out=function(msg){Aios.print('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.state=AMState.AMS_INIT;this.events=[];this.logs=[];this.logging=options.logging||false;if(this.logging){setInterval(function(){self.LOG('print')},5000);}
if(this.mode&AMMode.AMO_OBJECT)
this.receiver=this.receiverObj,this.request=this.requestObj;};amp.stream.prototype.LOG=amp.udp.prototype.LOG;amp.stream.prototype.emit=amp.udp.prototype.emit;amp.stream.prototype.init=amp.udp.prototype.init;amp.stream.prototype.on=amp.udp.prototype.on;amp.stream.prototype.receiver=function(callback,rcv){var self=this;if(rcv==undefined||rcv.address==undefined)rcv={},rcv.address=this.rcv.address;if(rcv.port==undefined)rcv,port=this.rcv.port;var cache=Comp.hashtbl.create();var buf=Buf.Buffer();var sock=this.sock;sock.on('message',function(message,remote){var handler,dfrags,dlist,msgtyp,tid,ipport,discard,off,size,thisnum,transaction,more,port,ip,data,msg;handler={};Buf.buf_init(buf);Buf.buf_of_str(buf,message);self.count.rcv+=message.length;if(message.length>=12){msgtyp=Buf.buf_get_int16(buf);discard=false;if(self.verbose>1)
self.out('receiver: Receiving Message ['+message.length+'] '+AMMessageType.print(msgtyp));switch(msgtyp){case AMMessageType.AMMRPCHEAD:tid=Buf.buf_get_int16(buf);port=Buf.buf_get_port(buf);handler.tid=tid;handler.remote=remote.address+':'+Buf.buf_get_int16(buf);handler.cmd=Buf.buf_get_int16(buf);handler.size=Buf.buf_get_int16(buf);handler.frags=Buf.buf_get_int16(buf);handler.buf=Buf.Buffer();if(handler.size>0){dlist=Comp.array.range(0,handler.frags-1);Comp.hashtbl.add(cache,handler.tid,[handler,dlist,1000]);}else{callback(handler);}
break;case AMMessageType.AMMRPCDATA:tid=Buf.buf_get_int16(buf);port=Buf.buf_get_port(buf);off=Buf.buf_get_int32(buf);size=Buf.buf_get_int16(buf);more=Buf.buf_get_int16(buf);thisnum=off/self.dlimit;transaction=Comp.hashtbl.find(cache,tid);if(transaction!=undefined){handler=transaction[0];if(self.verbose>1)
self.out('receiver: adding data num='+
thisnum+' off='+off+' size='+size+' dlist='+transaction[1]);Buf.buf_get_buf(buf,handler.buf,off,size);transaction[1]=Comp.array.filter(transaction[1],function(num){return(num!=thisnum)});if(Comp.array.empty(transaction[1])){if(self.verbose>1)self.out('[AMP] receiver: finalize '+addr2url(remote));callback(handler);Comp.hashtbl.remove(cache,tid);}
handler=undefined;}
break;}}});};amp.stream.prototype.receiverObj=function(callback,rcv){this.sock.on('message',function(obj){var handler={cmd:obj.cmd,buf:Buf.Buffer(obj.msg)};self.count.rcv+=obj.msg.length;if(callback)callback(handler);});}
amp.stream.prototype.request=amp.udp.prototype.request;amp.stream.prototype.requestObj=function(cmd,msg,callback){this.count.snd+=msg.data.length;this.sock.send({cmd:cmd,msg:msg.data});if(callback)callback()}
amp.stream.prototype.start=function(callback){if(this.verbose)this.out('Stream link '+Aios.DIR.print(this.dir)+' started.');this.links.state=AMState.AMS_CONNECTED;if(callback)callback()};amp.stream.prototype.stop=function(callback){if(callback)callback()};amp.stream.prototype.status=amp.udp.prototype.status;};BundleModuleCode['jam/ampHTTP']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var Bas64=Require('os/base64');var Sec=Require('jam/security')
var JSONfn=Require('jam/jsonfn')
var options={version:"1.14.7"}
var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,isLocal=COM.isLocal,getNetworkIP=COM.getNetworkIP
magic=COM.options.magic;var debug=false;module.exports.current=function(module){current=module.current;Aios=module;};function parseQueryString(url){var queryString=url.substring(url.indexOf('?')+1);if(queryString==url)return[];var params={},queries,temp,i,l;queries=queryString.split("&");for(i=0,l=queries.length;i<l;i++){temp=queries[i].split('=');if(temp[1]==undefined)temp[1]='true';params[temp[0]]=temp[1].replace('%20',' ');}
return params;}
function formatQueryString(msg){var path='/?';path+="magic="+msg.magic;path+="&type="+AMMessageType.print(msg.type);if(msg.cmd)path+='&cmd='+msg.cmd;if(msg.tid)path+='&tid='+msg.tid;if(msg.port)path+='&port='+Net.port_to_str(msg.port);if(msg.timeout)path+='&timeout='+msg.timeout;if(msg.node)path+='&node='+msg.node.replace(' ','%20');if(msg.index)path+='&index='+msg.index;if(msg.secure)path+='&secure='+(msg.secure.length==8?Net.port_to_str(msg.secure):msg.secure);return path;}
function msg2JSON(msg){if(msg.port)msg.port=Net.port_to_str(msg.port);if(msg.msg&&msg.msg.length)Comp.array.iter(msg.msg,function(msg){if(msg.port)msg.port=Net.port_to_str(msg.port);});return JSONfn.stringify(msg);}
function JSON2msg(data){var msg=JSONfn.parse(data);if(msg.port)msg.port=Net.port_of_str(msg.port);if(msg.msg&&msg.msg.length)Comp.array.iter(msg.msg,function(msg){if(msg.port)msg.port=Net.port_of_str(msg.port);});return msg;}
function getData(data){if(data==undefined)return undefined;else if(data.val!='')return data.val;else return data.children.toString();}
function is_error(data,err){if(data==undefined)return true;if(err==undefined)
return(data.length>0&&Comp.string.get(data,0)=='E');else
return(Comp.string.equal(data,err));};var http=Require('http');amp.http=function(options){var self=this;this.proto='http';this.options=checkOptions(options,{});this.verbose=checkOption(this.options.verbose,0);this.dir=options.dir;this.rcv=options.rcv;this.mode=AMMode.AMO_MULTICAST;this.node=options.node;if(options.nodeid)this.node={id:options.nodeid};if(options.rcv&&options.rcv.address!='*'&&options.rcv.port)this.mode|=AMMode.AMO_SERVER;else this.mode|=AMMode.AMO_CLIENT;this.options.keepalive=checkOption(options.keepAlive,true);this.secure=this.options.secure;this.port=options.port||Net.uniqport();this.id=Net.Print.port(this.port);this.out=function(msg,async){(async?Aios.logAsync:Aios.log)
('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.debug=function(msg){Aios.logAsync
('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.err=function(msg,async){(async?Aios.logAsync:Aios.log)
('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] Error: '+msg);throw'AMP';}
this.events=[];this.links={};this.count={rcv:0,snd:0,lnk:0,png:0};if(options.snd){url=addr2url(options.snd,true);this.links[url]={snd:options.snd,tries:0,state:AMState.AMS_NOTCONNECTED,live:options.AMC_MAXLIVE};}
this.collector=undefined;this.logs=[];this.logging=options.logging||false;if(this.logging){setInterval(function(){self.LOG('print')},5000);}
this.index=0;};amp.http.prototype.LOG=amp.man.prototype.LOG;amp.http.prototype.checkState=amp.man.prototype.checkState;amp.http.prototype.config=amp.man.prototype.config;amp.http.prototype.emit=amp.man.prototype.emit;amp.http.prototype.on=amp.man.prototype.on;amp.http.prototype.handle=amp.man.prototype.handle;amp.http.prototype.status=amp.man.prototype.status;amp.http.prototype.ack=function(snd,status){this.response(snd,{type:AMMessageType.AMMACK,status:status||"EOK",port:this.port,node:this.node?this.node.id:'*'});}
amp.http.prototype.cleanup=function(url,keep){var obj=this.links[url];if(!obj)return;obj.state=AMState.AMS_NOTCONNECTED
if(obj.collect)clearTimeout(obj.collect),obj.collect=undefined;if(obj.collecting)this.response(obj.collecting,{status:'ENOENTRY'}),obj.collecting=undefined;if(!keep){obj.snd={};this.links[url]=undefined;}}
amp.http.prototype.collect=function(snd){var self=this,url=addr2url(snd,true),msg={type:AMMessageType.AMMCOLLECT,port:this.port,index:this.index++,magic:magic};if(this.links[url]&&this.links[url].state==AMState.AMS_CONNECTED)
this.send(snd,msg,function(reply){var err=is_error(reply);if(err)return;if(reply.msg)Comp.array.iter(reply.msg,function(msg){self.handle(msg,snd);});if(!self.links[url])return;self.links[url].collect=setTimeout(function(){self.collect(snd);},0);});}
amp.http.prototype.collecting=function(msg,remote,response){var url;if(this.verbose>2)this.debug('handle AMMCOLLECT from '+addr2url(remote));url=addr2url(remote,true);if(this.links[url]&&this.links[url].msgqueue&&this.links[url].msgqueue.length){this.response(response,{msg:this.links[url].msgqueue});this.links[url].msgqueue=[];}
else if(this.links[url])this.links[url].collecting=response;else this.response(response,{status:'ENOENTRY'});}
amp.http.prototype.get=function(snd,path,callback){var body,req,self=this;if(this.verbose>2)this.debug('get '+addr2url(snd)+path);this.count.snd=this.count.snd+path.length;if(!http.xhr){req=http.request({host:snd.address,port:snd.port,path:path,method:'GET',keepAlive:this.options.keepalive,headers:{}},function(res){if(self.verbose>2)self.debug('got '+addr2url(snd)+path);if(res.setEncoding!=null)res.setEncoding('utf8');body='';res.on('data',function(chunk){body=body+chunk;});res.once('end',function(){self.count.rcv+=body.length;if(callback)callback(body);});});req.once('error',function(err){if(self.verbose)self.out('Warning: request to '+addr2url(snd)+' '+path+' failed: '+err,true);self.emit('error',err);if(callback)callback();});req.end();}else{http.request({host:snd.address,port:snd.port,path:path,proto:'http',keepAlive:this.options.keepalive,method:'GET',headers:{}},function(err,xhr,body){if(err){if(self.verbose)self.out('Warning: request to '+addr2url(snd)+' '+path+' failed: '+err,true);self.emit('error',err);if(callback)callback();}else{self.count.rcv+=body.length;if(callback)callback(body);}});}};amp.http.prototype.init=function(callback){if(callback)callback();};amp.http.prototype.link=function(snd,connect,key,response){var self=this,msg,url;if(this.verbose>1)this.out('amp.link: to '+addr2url(snd),true);if(!snd)this.err(true,'link: no destinataion set in MULTICAST mode');if(snd.parameter&&snd.parameter.secure)key=snd.parameter.secure;url=addr2url(snd,true);if(!this.links[url]||!this.links[url].snd.address){if(connect)snd.connect=true;this.links[url]={snd:snd,state:AMState.AMS_NOTCONNECTED,tries:0,connect:connect,live:options.AMC_MAXLIVE};}
if(!this.inwatchdog&&connect)
return this.watchdog(true);msg={type:AMMessageType.AMMLINK,port:this.port,node:this.node?this.node.id:'*',index:this.index++,magic:magic,remote:snd.address,};if(key)msg.secure=key;this.count.lnk++;if(response)
this.response(response,msg);else this.send(snd,msg,function(reply){if(is_error(reply))return;if((self.mode&AMMode.AMO_CLIENT)&&!self.links[url].collect){self.links[url].collect=setTimeout(function(){self.collect(snd);},0);}
self.handle(reply,snd);});};amp.http.prototype.ping=function(snd,response){var self=this,msg={};msg.type=AMMessageType.AMMPING;msg.port=this.port;msg.index=this.index++;msg.magic=magic;if(this.verbose>1)this.debug('amp.ping'+(response?'in response':'')+': to '+addr2url(snd));this.count.png++;if(response)
this.response(response,msg);else this.send(snd,msg,function(reply){if(is_error(reply))return;self.handle(reply,snd);});}
amp.http.prototype.pong=function(snd,response){var self=this,msg={};msg.type=AMMessageType.AMMPONG;msg.port=this.port;msg.index=this.index++;msg.magic=magic;if(this.verbose>1)this.debug('amp.pong '+(response?'in response':'')+': to '+addr2url(snd));this.count.png++;if(response)
this.response(response,msg);else this.send(snd,msg,function(reply){if(is_error(reply)){self.emit('error',reply);}});}
amp.http.prototype.put=function(snd,path,data){var self=this,req,body;this.count.snd=this.count.snd+path.length+data.length;if(!http.xhr){req=http.request({host:snd.address,port:snd.port,path:path,method:'POST',keepAlive:this.options.keepalive,headers:{'Content-Type':'application/x-www-form-urlencoded','Content-Length':data.length}},function(res){if(res.setEncoding!=null)res.setEncoding('utf8');res.once('data',function(chunk){});});req.once('error',function(err){self.out('Warning: request to '+addr2url(snd)+' failed: '+err,true);self.emit('error',err);});req.write(data);req.end();}else{http.request({host:snd.address,port:snd.port,path:path,method:'POST',body:data,keepAlive:this.options.keepalive,headers:{'Content-Type':'application/x-www-form-urlencoded','Content-Length':data.length}},function(err,xhr,body){if(err){if(self.verbose)self.out('Warning: request to '+addr2url(snd)+' failed: '+err,true);self.emit('error',err);}})}};amp.http.prototype.receiver=function(callback,rcv){var self=this;if(callback)this.callback=callback;if(this.mode&AMMode.AMO_SERVER){if(rcv==undefined||rcv.address==undefined)rcv={},rcv.address=this.rcv.address;if(rcv.port==undefined)rcv.port=this.rcv.port;this.server=http.createServer(function(request,response){if(parseQueryString(request.url).length==0)return response.end('EINVALID');var i,body,msg=parseQueryString(request.url),remote={address:request.connection.remoteAddress.replace(/^::ffff:/,'').replace(/^::1/,'localhost'),port:'['+msg.port.replace(/:/g,'')+']'};if(self.verbose>2)
console.log(request.method,request.url,msg,addr2url(remote),url2addr(addr2url(remote)));if(msg.magic!=magic)return;self.count.rcv+=1;msg.type=AMMessageType[msg.type];if(msg.secure)msg.secure=Net.port_of_str(msg.secure);if(debug)console.log(Io.Time(),msg)
response.origin=request.headers.origin||request.headers.Origin;Comp.string.match(request.method,[['GET',function(){if(msg.type==AMMessageType.AMMCOLLECT)
self.collecting(msg,remote,response);else
self.handle(msg,remote,response);}],['POST',function(){body='';request.on('data',function(chunk){body=body+chunk;});request.on('end',function(){msg.data=Buffer(body,'hex');self.count.rcv+=msg.data.length;if(msg.cmd)msg.cmd=Number(msg.cmd);self.handle(msg,remote,response);});}]])});this.server.on("connection",function(socket){socket.setNoDelay(true);});this.server.on("error",function(err){self.out('Warning: receiver failed: '+err,true);if(err)self.err(true,err);});this.server.listen(rcv.port,function(err){if(!err)getNetworkIP(undefined,function(err,ip){if(!err)self.rcv.address=isLocal(ip)?options.localhost:ip;if(self.verbose)self.out('IP port '+addr2url(self.rcv)+' (proto '+self.options.proto+')',true);if(err)return self.out("! Unable to obtain network connection information: "+err,true);});if(callback)callback(err);});}
if(this.mode&AMMode.AMO_CLIENT){if(callback)this.callback=callback;}}
amp.http.prototype.reply=function(cmd,msg,snd){this.request(cmd,msg,snd);}
amp.http.prototype.response=function(response,msg){var data=msg2JSON(msg),header;if(response.origin!=undefined)
header={'Access-Control-Allow-Origin':response.origin,'Access-Control-Allow-Credentials':'true','Content-Type':'text/plain'};else
header={'Content-Type':'text/plain'};if(this.options.keepalive)header["Connection"]="keep-alive";response.writeHead(200,header);response.write(data);if(debug)console.log(Io.Time(),msg)
response.end();}
amp.http.prototype.request=function(cmd,msg,snd){var self=this,req={},size=msg.data.length,tid=msg.tid||Comp.random.int(65536/2);if(snd==undefined)this.err(true,'request: snd=null');req.type=AMMessageType.AMMRPC;req.tid=tid;req.port=this.port;req.cmd=cmd;req.size=size;req.magic=magic;req.data=msg.data;this.send(snd,req);}
amp.http.prototype.scan=function(snd,response,callback){var self=this,msg={};msg.type=response?AMMessageType.AMMACK:AMMessageType.AMMSCAN;msg.port=this.port;msg.magic=magic;if(response)msg.info=snd.info;if(this.verbose>1&&snd)this.debug('amp.scan: to '+addr2url(snd));if(response)
this.response(response,msg);else
this.send(snd,msg,function(reply){callback(reply)});}
amp.http.prototype.send=function(snd,msg,callback){var path,url,body,self=this;path=formatQueryString(msg);if(typeof snd.port=='string'){url=addr2url(snd,true);if(this.links[url]){if(!this.links[url].msgqueue)this.links[url].msgqueue=[];if(this.links[url].collecting){if(this.verbose>1)this.debug('REPLY msg '+AMMessageType.print(msg.type)+' to '+url);this.response(this.links[url].collecting,{msg:[msg]});this.links[url].collecting=undefined;}else{if(this.verbose>1)this.debug('QUEUE msg '+AMMessageType.print(msg.type)+' for '+url);this.links[url].msgqueue.push(msg);}}}else if(msg.data!=undefined){body=msg.data.toString('hex');this.put(snd,path,body,function(body){if(is_error(body))self.emit('error',body);else if(!is_status(body))self.emit('error','EINVALID');});}else{this.get(snd,path,function(body){var xml,i,reply;if(!body||is_error(body)){self.emit('error','EINVALID');}else{reply=JSON2msg(body);}
if(callback)callback(reply);});}}
amp.http.prototype.start=function(callback){var self=this,s=this.secure?' (security port '+Sec.Port.toString(this.secure)+')':'';if(this.verbose>0&&this.mode&AMMode.AMO_SERVER)
this.out('Starting '+addr2url(this.rcv)+' ['+AMMode.print(this.mode)+'] (proto '+this.proto+')'+s);if(this.verbose>0&&this.mode&AMMode.AMO_CLIENT)
this.out('Starting ['+AMMode.print(this.mode)+'] (proto http)');this.watchdog(true);if(!this.server&&this.mode&AMMode.AMO_SERVER){this.receiver();}
if(callback)callback();}
amp.http.prototype.stop=function(callback){if(this.links)for(var p in this.links){if(this.links[p]){if(this.links[p].collect)clearTimeout(this.links[p].collect),this.links[p].collect=undefined;this.unlink(this.links[p].snd);if(this.links[p])this.links[p].state=AMState.AMS_NOTCONNECTED;}}
if(this.verbose>0&&this.mode&AMMode.AMO_SERVER)
this.out('Stopping '+addr2url(this.rcv)+' ['+AMMode.print(this.mode)+'] (proto '+this.proto+')'+s);if(this.verbose>0&&this.mode&AMMode.AMO_CLIENT)
this.out('Stopping ['+AMMode.print(this.mode)+'] (proto http)');if(this.timer)clearTimeout(this.timer),this.timer=undefined;if(this.server)this.server.close(),this.server=undefined;if(callback)callback();}
amp.http.prototype.unlink=function(snd){var self=this,msg,url=snd?addr2url(snd,true):null;if(this.mode&AMMode.AMO_MULTICAST){if(!this.links[url]||this.links[url].state!=AMState.AMS_CONNECTED)return;}else{if(this.links.state!=AMState.AMS_CONNECTED)return;}
msg={type:AMMessageType.AMMUNLINK,port:this.port,node:this.node?this.node.id:'*',index:this.index++,magic:magic};this.send(snd,msg,function(reply){if(reply){}});this.emit('route-',addr2url(snd,true));if(this.mode&AMMode.AMO_MULTICAST){this.links[url].state=AMState.AMS_NOTCONNECTED;if(!this.links[url].snd.connect)this.links[url].snd={};}else{this.links.state=AMState.AMS_NOTCONNECTED;if(!this.links.snd.connect)this.links.snd={};}
this.cleanup(url);}
amp.http.prototype.watchdog=function(run,immedOrDelay){var self=this;if(this.timer)clearTimeout(self.timer),this.timer=undefined;if(run)self.timer=setTimeout(function(){if(!self.timer||self.inwatchdog)return;self.timer=undefined;self.inwatchdog=true;function handle(obj,url){if(self.verbose>1)self.debug('Watchdog: handle link ('+url+') '+
(obj.snd?addr2url(obj.snd):'')+' in state '+
AMState.print(obj.state)+' live '+obj.live,true);switch(obj.state){case AMState.AMS_CONNECTED:if(obj.live==0){if(self.verbose>0)
self.out('Endpoint '+addr2url(obj.snd)+' not responding, propably dead. Unlinking...',true);obj.state=AMState.AMS_NOTCONNECTED;self.emit('route-',addr2url(obj.snd,true));self.cleanup(url,obj.snd.connect);if(obj.snd.connect)self.watchdog(true,2000);}else{obj.tries=0;obj.live--;self.watchdog(true);if(self.mode&AMMode.AMO_MULTICAST)self.ping(obj.snd);else self.ping();}
break;case AMState.AMS_NOTCONNECTED:case AMState.AMS_PAIRED:if(obj.snd.port&&typeof obj.snd.port=='number'){if(self.verbose>0&&obj.tries==0)
self.out('Trying link to '+addr2url(obj.snd),true);self.link(obj.snd);obj.tries++;if(obj.tries<options.TRIES)self.watchdog(true);else{self.out('Giving up to link '+addr2url(obj.snd),true);self.emit('error','link',addr2url(obj.snd));obj.snd={},obj.tries=0;}}
break;case AMState.AMS_RENDEZVOUS:obj.send({type:'register',name:self.rcv.name,linfo:self.rcv},self.broker,function(){});self.watchdog(true);break;case AMState.AMS_REGISTERED:if(obj.tries<options.TRIES&&obj.snd.name){obj.tries++;self.send({type:'pair',from:self.rcv.name,to:obj.snd.name},self.broker,function(){});}
if(obj.tries<options.TRIES)self.watchdog(true);break;}}
for(var p in self.links)if(self.links[p])handle(self.links[p],p);self.inwatchdog=false;},immedOrDelay==true?0:immedOrDelay||options.TIMER);};};BundleModuleCode['jam/jsonfn']=function(module,exports){var current=null;function typedarrayTObase64(ta,ftyp){var b,i;if(ta.buffer instanceof ArrayBuffer){b=Buffer(ta.buffer);if(b.length>0)return b.toString('base64');}
switch(ftyp){case Float32Array:b=Buffer(ta.length*4);for(i=0;i<ta.length;i++)b.writeFloatLE(ta[i],i*4);return b.toString('base64');case Float64Array:b=Buffer(ta.length*8);for(i=0;i<ta.length;i++)b.writeDoubleLE(ta[i],i*8);return b.toString('base64');case Int16Array:b=Buffer(ta.length*2);for(i=0;i<ta.length;i++)b.writeInt16LE(ta[i],i*2);return b.toString('base64');case Int32Array:b=Buffer(ta.length*4);for(i=0;i<ta.length;i++)b.writeInt32LE(ta[i],i*4);return b.toString('base64');}
return ta.toString();}
function base64TOtypedarray(buff,ftyp){var i,ta;if(buff.buffer instanceof ArrayBuffer){switch(ftyp){case Float32Array:return new Float32Array((new Uint8Array(buff)).buffer);case Float64Array:return new Float64Array((new Uint8Array(buff)).buffer);case Int16Array:return new Int16Array((new Uint8Array(buff)).buffer);case Int32Array:return new Int32Array((new Uint8Array(buff)).buffer);}}else if(typeof Uint8Array.from!='undefined'){switch(ftyp){case Float32Array:return new Float32Array(Uint8Array.from(buff).buffer);case Float64Array:return new Float64Array(Uint8Array.from(buff).buffer);case Int16Array:return new Int16Array(Uint8Array.from(buff).buffer);case Int32Array:return new Int32Array(Uint8Array.from(buff).buffer);}}else{switch(ftyp){case Float32Array:ta=new Float32Array(buff.length/4);for(i=0;i<ta.length;i++)
ta[i]=buff.readFloatLE(i*4);return ta;case Float64Array:ta=new Float64Array(buff.length/8);for(i=0;i<ta.length;i++)
ta[i]=buff.readDoubleLE(i*8);return ta;case Int16Array:ta=new Int16Array(buff.length/2);for(i=0;i<ta.length;i++)
ta[i]=buff.readInt16LE(i*2);return ta;case Int32Array:ta=new Int32Array(buff.length/4);for(i=0;i<ta.length;i++)
ta[i]=buff.readInt32LE(i*4);return ta;}}}
(function(exports){function stringify(obj){return JSON.stringify(obj,function(key,value){if(value instanceof Function||typeof value=='function')
return'_PxEnUf_'+Buffer(value.toString(true)).toString('base64');if(value instanceof Buffer)
return'_PxEfUb_'+value.toString('base64');if(typeof Float64Array!='undefined'&&value instanceof Float64Array)
return'_PxE6Lf_'+typedarrayTObase64(value,Float64Array);if(typeof Float32Array!='undefined'&&value instanceof Float32Array)
return'_PxE3Lf_'+typedarrayTObase64(value,Float32Array);if(typeof Int16Array!='undefined'&&value instanceof Int16Array)
return'_PxE1Ni_'+typedarrayTObase64(value,Int16Array);if(typeof Int32Array!='undefined'&&value instanceof Int32Array)
return'_PxE3Ni_'+typedarrayTObase64(value,Int32Array);if(value instanceof RegExp)
return'_PxEgEr_'+value;return value;});};function parse(str,mask){var code;try{with(mask||{}){code=JSON.parse(str,function(key,value){var prefix;try{if(typeof value!='string'){return value;}
if(value.length<8){return value;}
prefix=value.substring(0,8);if(prefix==='_PxEnUf_'){var code=value.slice(8);if(code.indexOf('function')==0)
return eval('('+code+')');else
return eval('('+Buffer(code,'base64').toString()+')');}
if(prefix==='_PxEfUb_')
return Buffer(value.slice(8),'base64');if(prefix==='_PxE6Lf_')
return base64TOtypedarray(Buffer(value.slice(8),'base64'),Float64Array);if(prefix==='_PxE3Lf_')
return base64TOtypedarray(Buffer(value.slice(8),'base64'),Float32Array);if(prefix==='_PxE1Ni_')
return base64TOtypedarray(Buffer(value.slice(8),'base64'),Int16Array);if(prefix==='_PxE3Ni_')
return base64TOtypedarray(Buffer(value.slice(8),'base64'),Int32Array);if(prefix==='_PxEgEr_')
return eval(value.slice(8));return value;}catch(e){throw{error:e,value:value};}});};}catch(e){throw e.error||e;}
return code;};exports.clone=function(obj,date2obj){return exports.parse(exports.stringify(obj),date2obj);};exports.current=function(module){current=module.current;};exports.serialize=stringify;exports.stringify=stringify;exports.deserialize=parse;exports.parse=parse;if(typeof Buffer!='undefined'&&Buffer.prototype.toJSON)delete Buffer.prototype.toJSON;if(typeof buffer=='object'&&buffer.Buffer)delete buffer.Buffer.prototype.toJSON;}(typeof exports==='undefined'?(window.JSONfn={}):exports));};BundleModuleCode['jam/ampHTTPS']=function(module,exports){var Io=Require('com/io');var Lz=Require('os/lz-string');var Comp=Require('com/compat');var Buf=Require('dos/buf');var Net=Require('dos/network');var Command=Net.Command;var Status=Net.Status;var current=none;var Aios=none;var CBL=Require('com/cbl');var Bas64=Require('os/base64');var Sec=Require('jam/security')
var JSONfn=Require('jam/jsonfn')
var options={version:"1.14.7",}
var COM=Require('jam/ampCOM'),AMMode=COM.AMMode,AMMessageType=COM.AMMessageType,AMState=COM.AMState,amp=COM.amp,options=COM.options,url2addr=COM.url2addr,addr2url=COM.addr2url,addrequal=COM.addrequal,resolve=COM.resolve,ipequal=COM.ipequal,isLocal=COM.isLocal,getNetworkIP=COM.getNetworkIP,pem=COM.options.pem,magic=COM.options.magic;var debug=false;module.exports.current=function(module){current=module.current;Aios=module;};function parseQueryString(url){var queryString=url.substring(url.indexOf('?')+1);if(queryString==url)return[];var params={},queries,temp,i,l;queries=queryString.split("&");for(i=0,l=queries.length;i<l;i++){temp=queries[i].split('=');if(temp[1]==undefined)temp[1]='true';params[temp[0]]=temp[1].replace('%20',' ');}
return params;}
function formatQueryString(msg){var path='/?';path+="magic="+msg.magic;path+="&type="+AMMessageType.print(msg.type);if(msg.cmd)path+='&cmd='+msg.cmd;if(msg.tid)path+='&tid='+msg.tid;if(msg.port)path+='&port='+Net.port_to_str(msg.port);if(msg.timeout)path+='&timeout='+msg.timeout;if(msg.node)path+='&node='+msg.node.replace(' ','%20');if(msg.index)path+='&index='+msg.index;if(msg.secure)path+='&secure='+(msg.secure.length==8?Net.port_to_str(msg.secure):msg.secure);return path;}
function msg2JSON(msg){if(msg.port)msg.port=Net.port_to_str(msg.port);if(msg.msg&&msg.msg.length)Comp.array.iter(msg.msg,function(msg){if(msg.port)msg.port=Net.port_to_str(msg.port);});return JSONfn.stringify(msg);}
function JSON2msg(data){var msg=JSONfn.parse(data);if(msg.port)msg.port=Net.port_of_str(msg.port);if(msg.msg&&msg.msg.length)Comp.array.iter(msg.msg,function(msg){if(msg.port)msg.port=Net.port_of_str(msg.port);});return msg;}
function getData(data){if(data==undefined)return undefined;else if(data.val!='')return data.val;else return data.children.toString();}
function is_error(data,err){if(data==undefined)return true;if(err==undefined)
return(data.length>0&&Comp.string.get(data,0)=='E');else
return(Comp.string.equal(data,err));};var https;var http=Require('http');amp.https=function(options){var self=this;this.proto='http';this.options=checkOptions(options,{});this.verbose=checkOption(this.options.verbose,0);if(global.TARGET!='browser'&&!https)try{https=require('https');}catch(e){throw'amp.https: no https/crypto support ('+e+')';}
this.dir=options.dir;this.rcv=options.rcv;this.mode=AMMode.AMO_MULTICAST;this.node=options.node;if(options.rcv&&options.rcv.address!='*'&&options.rcv.port)this.mode|=AMMode.AMO_SERVER;else this.mode|=AMMode.AMO_CLIENT;if(!options.pem)this.options.pem=pem;if((this.mode&AMMode.AMO_CLIENT)==0&&(!this.options.pem||!this.options.pem.key||!this.options.pem.cert))
throw"amp.https: no pem certificate and key provided like pem:{key,cert}";this.options.keepalive=checkOption(options.keepAlive,true);this.secure=this.options.secure;this.port=options.port||Net.uniqport();this.id=Net.Print.port(this.port);this.out=function(msg,async){(async?Aios.logAsync:Aios.log)
('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.debug=function(msg){Aios.logAsync
('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] '+msg);}
this.err=function(msg,async){(async?Aios.logAsync:Aios.log)
('[AMP '+Net.Print.port(self.port)+
(self.dir?(' '+Aios.DIR.print(self.dir)):'')+'] Error: '+msg);throw'AMP';}
this.events=[];this.links={};this.count={rcv:0,snd:0,lnk:0,png:0};if(options.snd){url=addr2url(options.snd,true);this.links[url]={snd:options.snd,tries:0,state:AMState.AMS_NOTCONNECTED,live:options.AMC_MAXLIVE};}
this.collector=undefined;this.logs=[];this.logging=options.logging||false;if(this.logging){setInterval(function(){self.LOG('print')},5000);}
this.index=0;};amp.https.prototype.LOG=amp.man.prototype.LOG;amp.https.prototype.checkState=amp.man.prototype.checkState;amp.https.prototype.config=amp.man.prototype.config;amp.https.prototype.emit=amp.man.prototype.emit;amp.https.prototype.on=amp.man.prototype.on;amp.https.prototype.handle=amp.man.prototype.handle;amp.https.prototype.status=amp.man.prototype.status;amp.https.prototype.ack=function(snd,status){this.response(snd,{type:AMMessageType.AMMACK,status:status||"EOK",port:this.port,node:this.node?this.node.id:'*'});}
amp.https.prototype.cleanup=function(url,keep){var obj=this.links[url];if(!obj)return;obj.state=AMState.AMS_NOTCONNECTED
if(obj.collect)clearTimeout(obj.collect),obj.collect=undefined;if(obj.collecting)this.response(obj.collecting,{status:'ENOENTRY'}),obj.collecting=undefined;if(!keep){obj.snd={};this.links[url]=undefined;}}
amp.https.prototype.collect=function(snd){var self=this,url=addr2url(snd,true),msg={type:AMMessageType.AMMCOLLECT,port:this.port,index:this.index++,magic:magic};if(this.links[url]&&this.links[url].state==AMState.AMS_CONNECTED)
this.send(snd,msg,function(reply){var err=is_error(reply);if(err)return;if(reply.msg)Comp.array.iter(reply.msg,function(msg){self.handle(msg,snd);});if(!self.links[url])return;self.links[url].collect=setTimeout(function(){self.collect(snd);},0);});}
amp.https.prototype.collecting=function(msg,remote,response){var url;if(this.verbose>2)this.debug('handle AMMCOLLECT from '+addr2url(remote));url=addr2url(remote,true);if(this.links[url]&&this.links[url].msgqueue&&this.links[url].msgqueue.length){this.response(response,{msg:this.links[url].msgqueue});this.links[url].msgqueue=[];}
else if(this.links[url])this.links[url].collecting=response;else this.response(response,{status:'ENOENTRY'});}
amp.https.prototype.get=function(snd,path,callback){var body,req,self=this;if(this.verbose>2)this.debug('get '+addr2url(snd)+path);this.count.snd=this.count.snd+path.length;if(https){req=https.request({host:snd.address,port:snd.port,path:path,method:'GET',keepAlive:this.options.keepalive,headers:{}},function(res){if(self.verbose>2)self.debug('got '+addr2url(snd)+path);if(res.setEncoding!=null)res.setEncoding('utf8');body='';res.on('data',function(chunk){body=body+chunk;});res.once('end',function(){self.count.rcv+=body.length;if(callback)callback(body);});});req.once('error',function(err){if(self.verbose)self.out('Warning: request to '+addr2url(snd)+' '+path+' failed: '+err,true);self.emit('error',err);if(callback)callback();});req.end();}else{http.request({host:snd.address,port:snd.port,path:path,proto:'https',method:'GET',headers:{}},function(err,xhr,body){if(err){if(self.verbose)self.out('Warning: request to '+addr2url(snd)+' '+path+' failed: '+err,true);self.emit('error',err);if(callback)callback();}else{self.count.rcv+=body.length;if(callback)callback(body);}});}};amp.https.prototype.init=function(callback){if(callback)callback();};amp.https.prototype.link=function(snd,connect,key,response){var self=this,msg,url;if(this.verbose>1)this.debug('amp.link: to '+addr2url(snd));if(!snd)this.err('link: no destinataion set in MULTICAST mode');if(snd.parameter&&snd.parameter.secure)key=snd.parameter.secure;url=addr2url(snd,true);if(!this.links[url]||!this.links[url].snd.address){if(connect)snd.connect=true;this.links[url]={snd:snd,state:AMState.AMS_NOTCONNECTED,tries:0,connect:connect,live:options.AMC_MAXLIVE};}
if(!this.inwatchdog&&connect)
return this.watchdog(true);msg={type:AMMessageType.AMMLINK,port:this.port,node:this.node?this.node.id:'*',index:this.index++,magic:magic,remote:snd.address,};if(key)msg.secure=key;this.count.lnk++;if(response)
this.response(response,msg);else this.send(snd,msg,function(reply){if(is_error(reply))return;if((self.mode&AMMode.AMO_CLIENT)&&!self.links[url].collect){self.links[url].collect=setTimeout(function(){self.collect(snd);},0);}
self.handle(reply,snd);});};amp.https.prototype.ping=function(snd,response){var self=this,msg={};msg.type=AMMessageType.AMMPING;msg.port=this.port;msg.index=this.index++;msg.magic=magic;if(this.verbose>1)this.debug('amp.ping'+(response?'in response':'')+': to '+addr2url(snd));this.count.png++;if(response)
this.response(response,msg);else this.send(snd,msg,function(reply){if(is_error(reply))return;self.handle(reply,snd);});}
amp.https.prototype.pong=function(snd,response){var self=this,msg={};msg.type=AMMessageType.AMMPONG;msg.port=this.port;msg.index=this.index++;msg.magic=magic;if(this.verbose>1)this.debug('amp.pong '+(response?'in response':'')+': to '+addr2url(snd));this.count.png++;if(response)
this.response(response,msg);else this.send(snd,msg,function(reply){if(is_error(reply)){self.emit('error',reply);}});}
amp.https.prototype.put=function(snd,path,data){var self=this,req,body;this.count.snd=this.count.snd+path.length+data.length;if(https){req=https.request({host:snd.address,port:snd.port,path:path,method:'POST',keepAlive:this.options.keepalive,headers:{'Content-Type':'application/x-www-form-urlencoded','Content-Length':data.length}},function(res){if(res.setEncoding!=null)res.setEncoding('utf8');res.once('data',function(chunk){});});req.once('error',function(err){self.out('Warning: request to '+addr2url(snd)+' failed: '+err,true);self.emit('error',err);});req.write(data);req.end();}else{http.request({host:snd.address,port:snd.port,path:path,proto:'https',method:'POST',body:data,keepAlive:this.options.keepalive,headers:{'Content-Type':'application/x-www-form-urlencoded','Content-Length':data.length}},function(err,xhr,body){if(err){if(self.verbose)self.out('Warning: request to '+addr2url(snd)+' failed: '+err,true);self.emit('error',err);}})}};amp.https.prototype.receiver=function(callback,rcv){var self=this;if(callback)this.callback=callback;if(this.mode&AMMode.AMO_SERVER){if(rcv==undefined||rcv.address==undefined)rcv={},rcv.address=this.rcv.address;if(rcv.port==undefined)rcv.port=this.rcv.port;var _options={key:this.options.pem.key,cert:this.options.pem.cert,};this.server=https.createServer(_options,function(request,response){if(parseQueryString(request.url).length==0)return response.end('EINVALID');var i,body,msg=parseQueryString(request.url),remote={address:request.connection.remoteAddress.replace(/^::ffff:/,'').replace(/^::1/,'localhost'),port:'['+msg.port.replace(/:/g,'')+']'};if(self.verbose>2)
console.log(request.method,request.url,msg,addr2url(remote),url2addr(addr2url(remote)));if(msg.magic!=magic)return;self.count.rcv+=msg.length;msg.type=AMMessageType[msg.type];if(msg.secure)msg.secure=Net.port_of_str(msg.secure);if(debug)console.log(Io.Time(),msg)
response.origin=request.headers.origin||request.headers.Origin;Comp.string.match(request.method,[['GET',function(){if(msg.type==AMMessageType.AMMCOLLECT)
self.collecting(msg,remote,response);else
self.handle(msg,remote,response);}],['POST',function(){body='';request.on('data',function(chunk){body=body+chunk;});request.on('end',function(){msg.data=Buffer(body,'hex');self.count.rcv+=msg.data.length;if(msg.cmd)msg.cmd=Number(msg.cmd);self.handle(msg,remote,response);});}]])});this.server.on("connection",function(socket){socket.setNoDelay(true);});this.server.on("error",function(err){self.out('Warning: receiver failed: '+err,true);if(err)self.err(err);});this.server.listen(rcv.port,function(err){if(!err)getNetworkIP(undefined,function(err,ip){if(!err)self.rcv.address=isLocal(ip)?options.localhost:ip;if(self.verbose)self.out('IP port '+addr2url(self.rcv)+' (proto '+self.options.proto+')',true);if(err)return self.out("! Unable to obtain network connection information: "+err,true);});if(callback)callback(err);});}
if(this.mode&AMMode.AMO_CLIENT){if(callback)this.callback=callback;}}
amp.http.prototype.reply=function(cmd,msg,snd){this.request(cmd,msg,snd);}
amp.https.prototype.response=function(response,msg){var data=msg2JSON(msg),header;if(response.origin!=undefined)
header={'Access-Control-Allow-Origin':response.origin,'Access-Control-Allow-Credentials':'true','Content-Type':'text/plain'};else
header={'Content-Type':'text/plain'};if(this.options.keepalive)header["Connection"]="keep-alive";response.writeHead(200,header);response.write(data);if(debug)console.log(Io.Time(),msg)
response.end();}
amp.https.prototype.request=function(cmd,msg,snd){var self=this,req={},size=msg.data.length,tid=msg.tid||Comp.random.int(65536/2);if(snd==undefined)this.err('request: snd=null');req.type=AMMessageType.AMMRPC;req.tid=tid;req.port=this.port;req.cmd=cmd;req.size=size;req.magic=magic;req.data=msg.data;this.send(snd,req);}
amp.https.prototype.scan=function(snd,response,callback){var self=this,msg={};msg.type=response?AMMessageType.AMMACK:AMMessageType.AMMSCAN;msg.port=this.port;msg.magic=magic;if(response)msg.info=snd.info;if(this.verbose>1&&snd)this.debug('amp.scan: to '+addr2url(snd)+' '+(response?'R':''));if(response)
this.response(response,msg);else
this.send(snd,msg,function(reply){callback(reply)});}
amp.https.prototype.send=function(snd,msg,callback){var path,url,body,self=this;path=formatQueryString(msg);if(typeof snd.port=='string'){url=addr2url(snd,true);if(this.links[url]){if(!this.links[url].msgqueue)this.links[url].msgqueue=[];if(this.links[url].collecting){if(this.verbose>1)this.debug('REPLY msg '+AMMessageType.print(msg.type)+' to '+url);this.response(this.links[url].collecting,{msg:[msg]});this.links[url].collecting=undefined;}else{if(this.verbose>1)this.debug('QUEUE msg '+AMMessageType.print(msg.type)+' for '+url);this.links[url].msgqueue.push(msg);}}}else if(msg.data!=undefined){body=msg.data.toString('hex');this.put(snd,path,body,function(body){if(is_error(body))self.emit('error',body);else if(!is_status(body))self.emit('error','EINVALID');});}else{this.get(snd,path,function(body){var xml,i,reply;if(!body||is_error(body)){self.emit('error','EINVALID');}else{reply=JSON2msg(body);}
if(callback)callback(reply);});}}
amp.https.prototype.start=function(callback){var self=this,s=this.secure?' (security port '+Sec.Port.toString(this.secure)+')':'';if(this.verbose>0&&this.mode&AMMode.AMO_SERVER)
this.out('Starting '+addr2url(this.rcv)+' ['+AMMode.print(this.mode)+'] (proto '+this.proto+')'+s);if(this.verbose>0&&this.mode&AMMode.AMO_CLIENT)
this.out('Starting ['+AMMode.print(this.mode)+'] (proto http)');this.watchdog(true);if(!this.server&&this.mode&AMMode.AMO_SERVER){this.receiver();}
if(callback)callback();}
amp.https.prototype.stop=function(callback){if(this.verbose>0&&this.mode&AMMode.AMO_SERVER)
this.out('Stopping '+addr2url(this.rcv)+' ['+AMMode.print(this.mode)+'] (proto '+this.proto+')'+s);if(this.verbose>0&&this.mode&AMMode.AMO_CLIENT)
this.out('Stopping ['+AMMode.print(this.mode)+'] (proto http)');if(this.links)for(var p in this.links){if(this.links[p]){this.unlink(this.links[p].snd);this.links[p].state=AMState.AMS_NOTCONNECTED;if(this.links[p].collect)clearTimeout(this.links[p].collect),this.links[p].collect=undefined;}}
if(this.timer)clearTimeout(this.timer),this.timer=undefined;if(this.server)this.server.close(),this.server=undefined;if(callback)callback();}
amp.https.prototype.unlink=function(snd){var self=this,msg,url=snd?addr2url(snd,true):null;if(this.mode&AMMode.AMO_MULTICAST){if(!this.links[url]||this.links[url].state!=AMState.AMS_CONNECTED)return;}else{if(this.links.state!=AMState.AMS_CONNECTED)return;}
msg={type:AMMessageType.AMMUNLINK,port:this.port,node:this.node?this.node.id:'*',index:this.index++,magic:magic};this.send(snd,msg,function(reply){if(reply){}});this.emit('route-',addr2url(snd,true));if(this.mode&AMMode.AMO_MULTICAST){this.links[url].state=AMState.AMS_NOTCONNECTED;if(!this.links[url].snd.connect)this.links[url].snd={};}else{this.links.state=AMState.AMS_NOTCONNECTED;if(!this.links.snd.connect)this.links.snd={};}
this.cleanup(url);}
amp.https.prototype.watchdog=function(run,immedOrDelay){var self=this;if(this.timer)clearTimeout(self.timer),this.timer=undefined;if(run)self.timer=setTimeout(function(){if(!self.timer||self.inwatchdog)return;self.timer=undefined;self.inwatchdog=true;function handle(obj,url){if(self.verbose>1)self.debug('Watchdog: handle link ('+url+') '+
(obj.snd?addr2url(obj.snd):'')+' in state '+
AMState.print(obj.state)+' live '+obj.live);switch(obj.state){case AMState.AMS_CONNECTED:if(obj.live==0){if(self.verbose>0)
self.out('Endpoint '+addr2url(obj.snd)+' not responding, propably dead. Unlinking...',true);obj.state=AMState.AMS_NOTCONNECTED;self.emit('route-',addr2url(obj.snd,true));self.cleanup(url,obj.snd.connect);if(obj.snd.connect)self.watchdog(true,2000);}else{obj.tries=0;obj.live--;self.watchdog(true);if(self.mode&AMMode.AMO_MULTICAST)self.ping(obj.snd);else self.ping();}
break;case AMState.AMS_NOTCONNECTED:case AMState.AMS_PAIRED:if(obj.snd.port&&typeof obj.snd.port=='number'){if(self.verbose>0&&obj.tries==0)
self.out('Trying link to '+addr2url(obj.snd),true);self.link(obj.snd);obj.tries++;if(obj.tries<options.TRIES)self.watchdog(true);else{self.out('Giving up to link '+addr2url(obj.snd),true);self.emit('error','link',addr2url(obj.snd));obj.snd={},obj.tries=0;}}
break;case AMState.AMS_RENDEZVOUS:obj.send({type:'register',name:self.rcv.name,linfo:self.rcv},self.broker,function(){});self.watchdog(true);break;case AMState.AMS_REGISTERED:if(obj.tries<options.TRIES&&obj.snd.name){obj.tries++;self.send({type:'pair',from:self.rcv.name,to:obj.snd.name},self.broker,function(){});}
if(obj.tries<options.TRIES)self.watchdog(true);break;}}
for(var p in self.links)if(self.links[p])handle(self.links[p],p);self.inwatchdog=false;},immedOrDelay==true?0:immedOrDelay||options.TIMER);};};BundleModuleCode['db/db']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var Fs=Require('fs');var current={};var Aios=none;var NL='\n';var options={version:'1.6.3'}
function await(){if(jxcore)jxcore.utils.jump();}
function wakeup(){if(jxcore)jxcore.utils.continue();}
function exists(path){try{var fd=Fs.openSync(path,'r');Fs.close(fd);return true;}catch(e){return false}}
var Buffer=require('buffer').Buffer;function tryReadSync(fd,buffer,pos,len){var threw=true;var bytesRead;try{bytesRead=Fs.readSync(fd,buffer,pos,len);threw=false;}finally{if(threw)fs.closeSync(fd);}
return bytesRead;}
function readFileSync(path,encoding){var fd=Fs.openSync(path,'r',666),bytesRead,buffer,pos=0,buffers=[];do{buffer=Buffer(8192);bytesRead=tryReadSync(fd,buffer,0,8192);if(bytesRead!==0){buffers.push(buffer.slice(0,bytesRead));}
pos+=bytesRead;}while(bytesRead!==0);Fs.closeSync(fd);buffer=Buffer.concat(buffers,pos);if(encoding)buffer=buffer.toString(encoding);return buffer;}
function sleep(time){var stop=new Date().getTime();while(new Date().getTime()<stop+time){;}}
function writeSync(path,str){var n=0;var fd=Fs.openSync(path,'r+');n=Fs.writeSync(fd,str);Fs.closeSync(fd);return n;}
var sqlc=function(path,chan){this.path=path;this.input=none;this.output=none;this.chan=chan;this.id='SQLC';this.log=function(msg){((Aios&&Aios.print)||Io.log)('[SQLC] '+msg);}
this.todo=[];}
sqlc.prototype.args=function(msg){var args=Comp.string.split(',',msg);return Comp.array.filtermap(args,function(arg){if(arg=='')return none;else if(Comp.string.get(arg,0)=="'")return Comp.string.trim(arg,1,1);else return arg;});};sqlc.prototype.createMatrix=function(matname,header,callback){var repl,intf='',line='',sep='',self=this;if(!this.connected)return callback?callback(false):false;if(header.length==0)return false;Comp.array.iter(header,function(col,i){intf+=(sep+'c'+(i+1)+(Comp.obj.isNumber(col)?' integer':' varchar(32)'));sep=',';});sep='';function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
return this.seq([['exec','drop table if exists '+matname,done],['exec','create table '+matname+' ('+intf+')',done]],callback);}
sqlc.prototype.createTable=function(tabname,header,callback){var repl,intf='',sep='',self=this;if(!this.connected)return callback?callback(false):false;Comp.obj.iter(header,function(attr,key){intf+=(sep+key+(Comp.obj.isNumber(attr)?' integer':' varchar(32)'));sep=',';});function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
return this.seq([['exec','drop table if exists '+tabname,done],['exec','create table '+tabname+' ('+intf+')',done],],callback);}
sqlc.prototype.end=function(msg){return msg.indexOf('END')==0}
sqlc.prototype.err=function(msg){if(!msg)return false;if(Comp.obj.isObject(msg))return msg.errno!=undefined;if(Comp.obj.isString(msg))return msg.indexOf('ERR')==0||msg.indexOf('Error')==0;return false;}
sqlc.prototype.exec=function(cmd,callback){var n,str='',fd;if(!this.connected)return callback?callback(none):none;n=Fs.writeSync(this.input,cmd+NL);if(n<=0){if(callback){callback(none);return;}
else return none;}
str=readFileSync(this.output,'utf8');if(callback)callback(str?Comp.array.filter(Comp.string.split('\n',str),function(line){return line!=''}):none);else return str?Comp.array.filter(Comp.string.split('\n',str),function(line){return line!=''}):none;};sqlc.prototype.get=function(fmt,callback){var row,self=this,repl;if(!this.connected)return callback?callback(none):none;function done(_repl){repl=_repl?_repl[0]:none;if(!repl||self.err(repl)){current.error=repl;row=none;return 0;}
else return 1;}
this.seq([['exec','get row',function(_repl){var cols,i,p;if(!row)row=[];if(done(_repl)&&!self.end(repl)){repl=Comp.string.replace_all('\n','',repl);cols=Comp.string.split(',',repl);if(fmt){i=0;row=[];for(p in fmt){switch(fmt[p]){case'string':row.push(cols[i]);break;case'number':row.push(Number(cols[i]));break;default:row.push(cols[i]);}
i++;}}else row=cols;}
return 1;}]],callback?function(res){if(res)callback(row);else callback(none);}:wakeup);if(callback)return;else if(row)return row;else{await();return row}}
sqlc.prototype.getError=function(){var err=current.error;current.error=undefined;return current.error||'OK'}
sqlc.prototype.init=function(callback){var path_in=Comp.printf.sprintf("%sI%s%d",this.path,this.chan<10?'0':'',this.chan),path_out=Comp.printf.sprintf("%sO%s%d",this.path,this.chan<10?'0':'',this.chan),stat,repl,self=this;this.id=Comp.printf.sprintf("[SQLC%s%d]",this.chan<10?'0':'',this.chan);this.log(Comp.printf.sprintf("%s Connecting to server channel %s...",this.id,path_in));if(!exists(path_in)||!exists(path_out)){this.log(Comp.printf.sprintf("%s Connecting to server channel %s failed: %s",this.id,path_in,'No such file(s)'));if(callback){callback(false);return;}
else return false;}
try{this.input=Fs.openSync(path_in,'r+');}catch(e){this.log(Comp.printf.sprintf("%s Connecting to server channel %s failed: %s",this.id,path_in,e));if(callback){callback(false);return;}else return false;}
this.output=path_out;this.connected=true;return this.seq([['set','nl',function(repl){return(repl&&!self.err(repl[0]))}],['set','csv',function(repl){return(repl&&!self.err(repl[0]))}]],callback);}
sqlc.prototype.insert=function(tbl,row,callback){var repl,line='',sep='',self=this;if(!this.connected)return callback?callback(false):false;if(Comp.obj.isArray(row))
Comp.array.iter(row,function(col,i){line+=sep+(Comp.obj.isNumber(col)?int(col):"'"+col+"'");sep=',';});else if(Comp.obj.isObject(row))
Comp.obj.iter(row,function(attr,key){line+=sep+(Comp.obj.isNumber(attr)?int(attr):"'"+attr+"'");sep=',';});else
throw'sql.insert: row neither array nor object!';function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
return this.seq([['exec','insert into '+tbl+' values ('+line+')',done]],callback);}
sqlc.prototype.insertMatrix=function(matname,row,callback){var repl,line='',sep='',self=this;if(this.connected)return callback?callback(false):false;Comp.array.iter(row,function(col,i){line+=sep+(Comp.obj.isNumber(col)?int(col):"'"+col+"'");sep=',';});function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
return this.seq([['exec','insert into '+matname+' values ('+line+')',done]],callback);}
sqlc.prototype.insertTable=sqlc.prototype.insert;sqlc.prototype.readMatrix=function(matname,callback){var mat,repl,cols,self=this;if(!this.connected)return callback?callback(none):none;function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;mat=none;return 0;}
else return 1;}
function doneSelect(_repl,_rows){repl=_repl[0];if(_rows){mat=_rows;return 2};if(!repl||self.err(repl)){current.error=repl;tbl=none;return 0;}
else return 1;}
this.seq([['exec','select * from '+matname,doneSelect],['exec','get row',function(_repl){if(done(_repl)){if(!mat)mat=[];if(rows){print('done');mat=rows;return true};if(!self.end(repl)){cols=_;if(typeof repl=='string'){repl=Comp.string.replace_all('\n','',repl);var cols=Comp.array.map(Comp.string.split(',',repl),function(col){return Number(col);});}else if(Comp.obj.isArray(repl)){cols=repl;}
mat.push(cols);return-1;}else return 1;}else return 0;}]],callback?function(res){if(res)callback(mat);else callback(none);}:wakeup);if(callback)return;else if(mat)return mat;else{await();return mat};}
sqlc.prototype.readTable=function(tblname,callback){var tbl,intf=[],repl,cols,self=this;if(!this.connected)return callback?callback(none):none;function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;tbl=none;return false;}
else return true;}
function doneSelect(_repl,_rows){repl=_repl[0];if(_rows){tbl=_rows;return 2};if(!repl||self.err(repl)){current.error=repl;tbl=none;return 0;}
else return 1;}
this.seq([['get',"select * from sqlite_master where type='table' and name='"+tblname+"'",function(_repl){var tokens;if(done(_repl)){if(repl.sql){tokens=repl.sql.match(/\((.+)\)/)[1].split(',');tokens.forEach(function(token){var cols=token.split(' ');if(cols.length==2){intf.push({tag:cols[0],type:self.sqlType2native(cols[1])});}else intf.push(null);});return!Comp.obj.isEmpty(intf)?1:0;}}else return 0;}],['exec','select * from '+tblname,doneSelect],['exec','get row',function(_repl){var o={};if(!tbl)tbl=[];if(done(_repl)){if(!self.end(repl)){cols=_;if(typeof repl=='string'){repl=Comp.string.replace_all('\n','',repl);repl.split(',').forEach(function(e,i){var io=intf[i];if(io)o[io.tag]=io.type=='number'?Number(e):e;});}else if(Comp.obj.isArray(repl)){repl.forEach(function(e,i){var io=intf[i];if(io)o(io.tag)=io.type=='number'?Number(e):e;});}
tbl.push(o);return-1;}else return 1;}else return 0;}]],callback?function(res){if(res)callback(tbl);else callback(none);}:wakeup);if(callback)return;else if(tbl)return tbl;else{await();return tbl}}
sqlc.prototype.select=function(tbl,vars,cond,callback){var self=this,repl,stat;function done(_repl){repl=_repl?_repl[0]:none;if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
if(vars==undefined)vars='*';stat=this.seq([['exec',Comp.printf.sprintf('select %s from %s%s',Comp.obj.isArray(vars)?Comp.printf.list(vars):vars,tbl,cond?(' '+cond):''),done]],callback?callback:wakeup);if(!callback)await();return stat;}
sqlc.prototype.seq=function(todo,callback){var l=todo,self=this,status,res,next;if(callback){function Todo(){if(self.todo.length>0){var f=Comp.array.head(self.todo);self.error=undefined;f(_,function(){self.todo=Comp.array.tail(self.todo);Todo();});}}
next=function(loop,finalize){if(l.length==0&&!loop){callback(status);if(finalize)finalize()}
else{var hd;if(!loop){hd=Comp.array.head(l);l=Comp.array.tail(l);}else hd=loop;switch(hd[0]){case'set':self.set(hd[1],function(repl){status=hd[2](repl);if(status==1)next(_,finalize);else callback(status);});break;case'exec':self.exec(hd[1],function(repl){status=hd[2](repl);if(status==1)next(_,finalize);else if(status==-1)next(hd,finalize);else callback(status);});break;}}}
self.todo.push(next);if(self.todo.length==1)Todo();return;}else{next=function(loop){if(l.length==0&&!loop)return status;else{if(!loop){hd=Comp.array.head(l);l=Comp.array.tail(l);}else hd=loop;switch(hd[0]){case'set':status=self.set(hd[1]);if(status==1)next();else return status;break;case'exec':res=self.exec(hd[1]);status=hd[2](res);if(status==1)next();else if(status==-1)next(hd);else return status;break;}}}
return next();}};sqlc.prototype.set=function(flag,callback){var n,fd,str='';if(!this.connected)return callback?callback(false):false;n=Fs.writeSync(this.input,'set '+flag);if(n<=0){if(callback){callback(none);return;}
else return none;}
str=readFileSync(this.output,'utf8');if(callback)callback(str?Comp.array.filter(Comp.string.split('\n',str),function(line){return line!=''}):none);else return str?Comp.array.filter(Comp.string.split('\n',str),function(line){return line!=''}):none;};sqlc.prototype.sqlType2native=function(str){if(str=='integer')return'number';if(str.indexOf('varchar')==0)return'string';}
sqlc.prototype.writeMatrix=function(matname,matrix,callback){var repl,line='',self=this,intf='',sep='',i=0,row;if(!this.connected)return callback?callback(false):false;if(matrix.length==0)return false;Comp.array.iter(matrix[0],function(col,i){intf+=sep+'c'+(i+1)+(Comp.obj.isNumber(col)?' integer':' varchar(32)');sep=',';});row=matrix[0];Comp.array.iter(row,function(col,i){line+=sep+(Comp.obj.isNumber(col)?int(col):"'"+col+"'");sep=',';});function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
seq=[['exec','drop table if exists '+matname,done],['exec','create table '+matname+' ('+intf+')',done]];for(i=0;i<matrix.length;i++){row=matrix[i];line='',sep='';Comp.array.iter(row,function(col,i){line+=sep+(Comp.obj.isNumber(col)?int(col):"'"+col+"'");sep=',';});seq.push(['exec','insert into '+matname+' values ('+line+')',done]);}
return this.seq(seq,callback);}
sqlc.prototype.writeTable=function(tblname,tbl,callback){var repl,line='',self=this,intf='',sep='',i=0,row;if(!this.connected)return callback?callback(false):false;if(matrix.length==0)return false;Comp.obj.iter(tbl[0],function(attr,key){intf+=sep+key+(Comp.obj.isNumber(attr)?' integer':' varchar(32)');sep=',';});row=matrix[0];Comp.obj.iter(row,function(attr,key){line+=sep+(Comp.obj.isNumber(attr)?int(attr):"'"+attr+"'");sep=',';});function done(_repl){repl=_repl[0];if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
seq=[['exec','drop table if exists '+tblname,done],['exec','create table '+tblname+' ('+intf+')',done]];for(i=0;i<matrix.length;i++){row=tbl[i];line='',sep='';Comp.array.iter(row,function(col,i){line+=sep+(Comp.obj.isNumber(col)?int(col):"'"+col+"'");sep=',';});seq.push(['exec','insert into '+tblname+' values ('+line+')',done]);}
return this.seq(seq,callback);}
sqlc.prototype.setLog=function(f){this.log=f;}
var Sqlc=function(path,chan){var obj=new sqlc(path,chan);return obj;};var sqld=function(file,options){this.file=file||':memory:';this.options=options||{};this.id='SQLD';this.todo=[];this.log=function(msg){((Aios&&Aios.print)||Io.log)('[SQLD] '+msg);}
try{this.sqlite3=require('sqlite3');}catch(e){throw e;}
if(this.options.mode=='r+')
this.mode=this.sqlite3.OPEN_READWRITE;else if(this.options.mode=='w+')
this.mode=this.sqlite3.OPEN_READWRITE|this.sqlite3.OPEN_CREATE;else
this.mode=this.sqlite3.OPEN_READONLY}
sqld.prototype.createTable=sqlc.prototype.createTable;sqld.prototype.end=sqlc.prototype.end;sqld.prototype.err=sqlc.prototype.err;sqld.prototype.getError=sqlc.prototype.getError;sqld.prototype.init=function(){this.db=new this.sqlite3.Database(this.file,this.mode);this.db.serialize();this.log('Opened DB '+this.file+' in mode '+(this.mode&this.sqlite3.OPEN_READWRITE?'RW':'R')+
(this.mode&this.sqlite3.OPEN_CREATE?'C':''));this.connected=true;}
sqld.prototype.insertMatrix=sqlc.prototype.insertMatrix;sqld.prototype.insertTable=sqlc.prototype.insert;sqld.prototype.readMatrix=sqlc.prototype.readMatrix;sqld.prototype.readTable=sqlc.prototype.readTable;sqld.prototype.seq=function(todo,callback){var l=todo,self=this,status,res,row,rows,cols,next;if(callback){function Todo(){if(self.todo.length>0){var f=Comp.array.head(self.todo);f(_,function(){self.todo=Comp.array.tail(self.todo);Todo();});}}
next=function(loop,finalize){var p;if(l.length==0&&!loop){callback(status);if(finalize)finalize()}
else{var hd;if(!loop){hd=l.shift();}else hd=loop;switch(hd[0]){case'exec':if(hd[1]=='get row'){if(rows&&rows.length){row=rows.shift();cols=[];for(p in row)cols.push(row[p]);status=hd[2]([cols.join(',')]);}else status=hd[2](['END']);if(status==1)next(_,finalize);else if(status==-1)next(hd,finalize);else callback(status);}else if(hd[1].indexOf('select')==0){self.db.all(hd[1],[],function(repl,_rows){rows=_rows;if(repl!=null&&!Comp.obj.isArray(repl))repl=[repl];if(repl==null)repl=['OK'];status=hd[2](repl,_rows);if(status==1)next(_,finalize);else if(status==-1)next(hd,finalize);else if(status==2){l=[];next(_,finalize)}
else callback(status);});}else{self.db.run(hd[1],[],function(repl){rows=_rows;if(repl!=null&&!Comp.obj.isArray(repl))repl=[repl];if(repl==null)repl=['OK'];status=hd[2](repl);if(status==1)next(_,finalize);else if(status==-1)next(hd,finalize);else if(status==2){l=[];next(_,finalize)}
else callback(status);});}
break;case'get':self.db.get(hd[1],function(err,table){var repl;if(err)repl=[err];else repl=[table];status=hd[2](repl);if(status==1)next(_,finalize);else if(status==-1)next(hd,finalize);else callback(status);});break;}}}
self.todo.push(next);if(self.todo.length==1)Todo();return;}else{next=function(loop){if(l.length==0&&!loop)return status;else{if(!loop){hd=l.shift();}else hd=loop;switch(hd[0]){case'exec':res='OK';self.db.run(hd[1],function(err){if(err)self.log(err)});status=hd[2](res);if(status==1)return next();else if(status==-1)return next(hd);else if(status==2){l=[];next()}
else return status;break;}}}
return next();}};sqld.prototype.select=function(tbl,vars,cond,callback){var self=this,repl,stat,rows;function done(_repl,_rows){repl=_repl?_repl[0]:none;rows=_rows;if(!repl||self.err(repl)){current.error=repl;return 0;}
else return 1;}
if(vars==undefined)vars='*';stat=this.seq([['exec',Comp.printf.sprintf('select %s from %s%s',Comp.obj.isArray(vars)?Comp.printf.list(vars):vars,tbl,cond?(' '+cond):''),done]],callback?callback:wakeup);if(!callback)await();return rows||stat;}
sqld.prototype.sqlType2native=sqlc.prototype.sqlType2native;sqld.prototype.writeMatrix=sqlc.prototype.writeMatrix;var Sqld=function(file,options){var obj=new sqld(file,options);return obj;};module.exports={current:function(module){current=module.current;Aios=module;},Sqlc:Sqlc,Sqld:Sqld};};BundleModuleCode['shell/shell']=function(module,exports){Require('os/polyfill');var JamLib=Require('top/jamlib');var util=Require('util');var Comp=Require('com/compat');var Io=Require('com/io');var Sat=Require('dos/ext/satelize');var Cluster=Require('shell/cluster');var Sec=Require('jam/security');var Rpc=Require('rpc/rpc');var Esprima=Require("parser/esprima");var Json=Require('jam/jsonfn');var options={verbose:JamLib.environment.verbose||1,version:'1.36.1',}
Cluster.current(JamLib.Aios);if(typeof print=='undefined')print=console.log;DIR=JamLib.Aios.DIR;var NET=Require('jam/ampCOM'),url2addr=NET.url2addr,addr2url=NET.addr2url;function format(line){var msg;switch(typeof line){case'boolean':msg=line.toString();break;case'string':msg=line;break;case'number':msg=line.toString();break;case'function':msg=line.toString();break;case'object':msg=Io.inspect(line);break;default:msg='';}
return msg;}
function Shell(_options){if(!(this instanceof Shell))return new Shell(_options);this.options=Comp.obj.extend(options,_options);this.modules=options.modules||{};this.events={};this.env={};this.modules.forEach(function(mod,name){switch(name){case'des48':JamLib.Aios[name]=mod;break;case'ml':case'nn':case'csp':case'sat':case'numerics':mod.current(JamLib.Aios);JamLib.Aios[name]=mod.agent;JamLib.Aios.aios1[name]=mod.agent;JamLib.Aios.aios2[name]=mod.agent;JamLib.Aios.aios3[name]=mod.agent;break;case'nlp':case'logic':JamLib.Aios[name]=mod;JamLib.Aios.aios1[name]=mod;JamLib.Aios.aios2[name]=mod;JamLib.Aios.aios3[name]=mod;break;}})
if(!this.options.renderer){if(this.modules.doc)this.options.renderer=this.modules.doc.Renderer({lazy:true});else
this.options.renderer=function(text){return text.replace(/\n:/g,'\n ');}}}
Shell.prototype.cmd=function(){return this.env}
Shell.prototype.emit=function(ev,arg1,arg2,arg3,arg4){if(this.events[ev])this.events[ev](arg1,arg2,arg3,arg4);}
Shell.prototype.help=function(){return this.options.renderer(['# Usage',' jamsh [-v] [script.js] [-- <script args>]','# Shell Commands','The following shell commands are avaiable:','','add({x,y})\n: Add a new logical (virtual) node','agent(id,proc?:boolean)\n: Returns the agent object (or process)','agents\n: Get all agents (id list) of current node','args\n: Script arguments','ask(question:string,choices: string [])\n: Ask a question and read answer. Available only in script mode.','array(n,init)\n: Creates initialised array','assign(src,dst)\n: Copy elements of objects','broker(ip)\n: Start a UDP rendezvous broker server','Capability\n: Create a security capability object','clock(ms)\n: Returns system time (ms or hh:mm:ss format)','cluster(desc)\n:Create a worker process cluster','config(options)\n: Configure JAM. Options: _print_, _printAgent_,_TSTMO_','configs\n: Get configuration of JAM AIOS','connect({x,y},{x,y})\n: Connect two logical nodes (DIR.NORTH...)','connect({to:dir)\n: Connect to physical node','connected(to:dir)\n: Check connection between two nodes','compile(function)\n: Compile an agent class constructor function','concat(a,b)->c\n: Concatenate two values','contains(a,v)->boolean\n: Check if array or object contains a value or oen in an array of values','copy(o)\n: Returns copy of record or array','create(ac:string|function,args:*[]|{},level?:number,node?)\n: Create an agent from class @ac with given arguments @args and @level','csp?\n: Constraint Solving Programming','csv?\n: CSV file reader and writer (read,write)','des48?\n: DES48 Encryption','disconnect({x,y},{x,y})\n: Disconnect two logical nodes','disconnect({to:dir)\n: Diconnect remote endpoint','env\n: Shell environment including command line arguments a:v','empty(a)->boolean\n: Test empty string, array, or object','exec(cnd:string)\n: Execute a jam shell command','exit\n: Exit shell','extend(level:number|number[],name:string,function,argn?:number|number[])\n: Extend AIOS','filter(a,f)->b\n: Filter array or object','http.get(url:string,path:string,callback?:function)\n: Serve HTTP get request','http.put(url:string,path:string,data,callback?:function)\n: Serve HTTP put request','http.GET(url:string,params:{},callback?:function)\n: Serve HTTP JSON get request','http.PUT(url:string,params:{},data,data,callback?:function)\n: Serve HTTP JSON put request','http.server(ip:string,dir:string,index?:string)\n: Create and start a HTTP file server','info(kind:"node"|"version"|"host",id?:string)->info {}\n: Return information (node)','inp(pattern:[],all?:boolean)\n: Read and remove (a) tuple(s) from the tuple space','Json\n:JSON+ serializer','kill(id:string|number)\n: Kill an agent (id="*": kill all) or a task (started by later)','last(object|array)\n: Return last element of array, string, or object','later(ms:number,callback:function(id,counter)->booleabn)\n: Execute a function later. If fucntion returns true, next cycle is started.','load(path:string,mimetype?)\n: Load a JSON or CSV file (autodetect) or custom','lookup(pattern:string,callback:function (string [])\n: Ask broker for registered nodes','locate(callback?:function)\n: Try to estimate node location (geo,IP,..)','log(msg)\n: Agent logger function','logic??\n: Generic predicate (pro)logic framework module','mark(tuple:[],millisec)\n: Store a tuple with timeout in the tuple space','merge\n: Add a column (array) to a matrix (array array)','ml?\n: Generic machine Learning framework module','name("node"|"world")\n: Return name of current node or wolrd','nlp?\n: Natural language processing framework module','node\n: Get or set current vJAM node (default: root) either by index or id name','nodes\n: Get all vJAM nodes','numerics?\n: Numerics module (fft, vector, matrix, ..)','nn?\n: Neural Network framework module','neg(v)->v\n: Negate number, array or object of numebrs','object(s)\n: Convert string to object','ofJSON(s)\n: Convert JSON to object including functions','on(event:string,handler:function)\n: Install an event handler. Events: "agent+","agent-","signal+","signal","link+","link-","exit"','ope
Shell.prototype.init=function(callback){var self=this;if(!this.options.server&&this.modules.readline){this.rl=this.modules.readline.createInterface({input:process.stdin,output:process.stdout,completer:function(cmdline){var args=Array.filter(String.split(' ',cmdline),function(str){return str!='';});var completed=cmdline;var choices=[];return[choices,completed];}});this.rl.on('line',function(line){self.cmdline=line;self.process(line)
self.rl.prompt();});this.rl.on('close',function(){});if(this.modules.doc)
this.output(this.modules.doc.Colors.bold('JAM Shell. Version '+this.options.version+' (C) Dr. Stefan Bosse'));else
this.output('JAM Shell. Version '+this.options.version+' (C) Dr. Stefan Bosse');this.rl.setPrompt('> ');this.rl.prompt();}else if(this.options.verbose)this.output('JAM Shell. Version '+this.options.version+' (c) Dr. Stefan Bosse');this.jam=JamLib.Jam({print:this.output.bind(this),printAgent:this.outputAgent.bind(this),printAsync:this.outputAsync.bind(this),nameopts:this.options.nameopts,Nameopts:this.options.Nameopts,verbose:this.options.verbose,type:this.options.type||'shell'});this.jam.init();function error(msg){self.output('Error: '+msg);}
self.log=self.output;this.tasks=[];this.env={Aios:this.jam.Aios,DIR:this.jam.Aios.DIR,add:this.jam.addNode.bind(this.jam),agent:function(id,proc){var node=self.jam.world.nodes[self.jam.getCurrentNode()];if(node){return proc?node.getAgentProcess(id):node.getAgent(id);}},get agents(){var node=self.jam.world.nodes[self.jam.getCurrentNode()];if(node){return node.processes.table.map(function(pro){return pro.agent.id});}},angle:JamLib.Aios.aios0.angle,args:options.args,array:JamLib.Aios.aios0.array,assign:JamLib.Aios.aios0.assign,broker:function(ip){if(!self.modules.sip)return;if(self.broker)self.broker.stop();if(!ip)ip='localhost';var ipport=10001,tokens=ip.toString().split(':');if(tokens.length==2)ip=tokens[0],ipport=Number(tokens[1]);self.broker=sip.Broker({ip:{address:ip,port:ipport},log:self.output.bind(self)});self.broker.init();self.broker.start();},Capability:JamLib.Aios.Sec.Capability,clock:this.jam.clock.bind(this.jam),cluster:function(options){return new Cluster(options,self.env);},compile:function(constr,name,options){try{if(typeof name=='object')
return self.jam.compileClass(undefined,constr,name)
else
return self.jam.compileClass(name,constr,options||{verbose:self.options.verbose})}catch(e){error(e)}},config:function(options){JamLib.Aios.config(options);},get configs(){return JamLib.Aios.configGet();},connect:function(n1,n2){if(n1&&n2)
return self.jam.connectNodes([n1,n2])
else
return self.jam.connectTo(n1)},connected:this.jam.connected.bind(this.jam),concat:JamLib.Aios.aios0.concat,contains:JamLib.Aios.aios0.contains,copy:JamLib.Aios.aios0.copy,create:this.jam.createAgent.bind(this.jam),csp:JamLib.Aios.csp,get current(){return JamLib.Aios.current},delta:JamLib.Aios.aios0.delta,des48:JamLib.Aios.des48,disconnect:function(n1,n2){if(n1&&n2){}
else
return self.jam.disconnect(n1)},distance:JamLib.Aios.aios0.distance,env:this.jam.environment,empty:JamLib.Aios.aios0.empty,extend:this.jam.extend.bind(this.jam),exec:this.process.bind(this),get exit(){process.exit()},get help(){return self.help()},filter:function(a,f){var res=[],len,len2,i,j,found;if(Comp.obj.isArray(a)&&Comp.obj.isFunction(f)){res=[];len=a.length;for(i=0;i<len;i++){var element=a[i];if(f(element,i))res.push(element);}
return res;}else if(Comp.obj.isArray(a)&&Comp.obj.isArray(f)){res=[];len=a.length;len2=f.length;for(i=0;i<len;i++){var element=a[i];found=false;for(j=0;j<len2;j++)if(element==f[j]){found=true;break;}
if(!found)res.push(element);}
return res;}else return undefined;},flatten:JamLib.Aios.aios0.flatten,geoip:self.modules.geoip,Json:Json,ignore:function(){},info:this.jam.info.bind(this.jam),inspect:util.inspect,inp:this.jam.inp.bind(this.jam),kill:function(id){if(typeof id=='string')self.jam.kill(id);else if(typeof id=='number'&&id>=0){if(self.tasks[id])clearInterval(self.tasks[id]);self.tasks[id]=null;}},last:JamLib.Aios.aios0.last,later:function(timeout,callback){var counter=0,id=self.tasks.length;var timer=setInterval(function(){try{var res=callback(id,counter);}catch(e){error(e);res=0;}
counter++;if(!res){clearInterval(timer);self.tasks[id]=null;}},timeout)
self.tasks[id]=timer;return id;},load:function(file,mimetype){var obj,text=Io.read_file(file);if(!text)return;if(!mimetype&&file.match(/\.js$/))mimetype='JS';if(!mimetype&&file.match(/\.json$/))mimetype='JSON';switch(mimetype&&mimetype.replace(/application\//,'')){case'text':return text;};var scanner=text.replace(/\/\/[^\n]*/g,'');if(scanner.match(/^\s*{/)||scanner.match(/^\s*\[\s*{/)||scanner.match(/^\s*\[\s*\[/)||scanner.match(/^\s*\[\s*\{/)){switch(mimetype&&mimetype.replace(/application\//,'')){case'JS':case'JSOB':eval('"use strict"; obj = '+text);break;case'JSON':default:obj=self.env.ofJSON(text);};}else if(self.env.csv&&self.env.csv.detect(text))
obj=self.env.csv.read(text,false,true);return obj;},locate:this.jam.locate.bind(this.jam),lookup:this.jam.lookup.bind(this.jam),log:this.jam.log.bind(this.jam),logic:JamLib.Aios.logic,map:function(a,f){var res,i,p;if(Comp.obj.isArray(a)&&Comp.obj.isFunction(f)){res=[];for(i in a){v=f(a[i],i);if(v!=undefined)res.push(v);}
return res;}else if(Comp.obj.isObject(a)&&Comp.obj.isFunction(f)){res={};for(p in a){v=f(a[p],p);if(v!=undefined)res[p]=v;}
return res;}else return undefined;},mark:this.jam.mark.bind(this.jam),merge:function(a,b){if(Comp.obj.isMatrix(a)&&Comp.obj.isArray(b)){a=a.map(function(row,i){var _row=row.slice();_row.push(b[i]);return _row})}
return a},ml:JamLib.Aios.ml,name:function(of,arg){switch(of){case'node':return self.jam.getNodeName(arg);case'world':return self.jam.world.id;}},neg:JamLib.Aios.aios0.neg,get node(){return self.jam.getCurrentNode(true)},set node(n){return self.jam.setCurrentNode(n)},get nodes(){return self.jam.world.nodes.map(function(node){return node.id})},nlp:JamLib.Aios.nlp,nn:JamLib.Aios.nn,numerics:JamLib.Aios.numerics,object:JamLib.Aios.aios0.object,ofJSON:function(s){return self.jam.Aios.Code.Jsonf.parse(s,{})},on:function(ev,handler){switch(ev){case'exit':process.on('exit',handler);process.on('SIGINT',function(){process.exit()});break;default:self.jam.on(ev,handler);}},open:function(file,verbose){if(verbose==undefined)verbose=1;return self.jam.readClass(file,{verbose:verbose})},os:self.modules.os,out:this.jam.out.bind(this.jam),pluck:function(table,column){var res=[];for(var i in table){res.push(table[i][column]);}
return res;},port:function(dir,options,node){if(typeof options=='string')options={proto:options};else options=options||{};if(options.verbose==undefined)options.verbose=self.options.verbose;if(options.multicast==undefined)options.multicast=!options.broker;if(options.secure&&options.secure.length!=Sec.PORT_SIZE)options.secure=Sec.Port.ofString(options.secure);var port=self.jam.createPort(dir,options,node);self.emit('port',dir,options);return port;},Port:JamLib.Aios.Sec.Port,print:function(){if(arguments.length>1)
self.outputPrint(Array.prototype.slice.call(arguments).map(Io.inspect).join(' '));else
self.outputPrint(arguments[0])},Private:JamLib.Aios.Sec.Private,provider:function(provider){self.jam.world.nodes[0].ts.register(provider)},random:JamLib.Aios.aios.random,rd:this.jam.rd.bind(this.jam),reduce:JamLib.Aios.aios0.reduce,reverse:JamLib.Aios.aios0.reverse,Rights:JamLib.Aios.Sec.Rights,rm:this.jam.rm.bind(this.jam),Rpc:Rpc,sat:JamLib.Aios.sat,save:function(file,o,csv){if(csv&&self.env.csv){self.env.csv.write(file,o[0],o.slice(1));}else Io.write_file(file,self.env.toJSON(o))},schedule:this.jam.schedule.bind(this.jam),script:function(file){var text=Io.read_file(file);if(typeof text!='string')text=text.toString();self.process(text);},select:function(data,a,b){if(b==undefined){return data.map(function(object){return object[a];});}else{return data.map(function(object){return object.slice(a,b+1);});}},setlog:function(attr,on){self.jam.Aios.config(on?{'log+':attr}:{'log-':attr})},signal:this.jam.signal.bind(this.jam),start:this.jam.start.bind(this.jam),start0:this.jam.start0.bind(this.jam),stats:this.jam.stats.bind(this.jam),Std:JamLib.Aios.Amp.Rpc.Std,step:this.jam.step.bind(this.jam),stop:this.jam.stop.bind(this.jam),time:this.jam.time.bind(this.jam),Time:Io.Time,test:this.jam.test.bind(this.jam),toJSON:function(o){return self.jam.Aios.Code.Jsonf.stringify(o)},ts:this.jam.ts.bind(this.jam),uniqid:function(options){return self.jam.Aios.aidgen(options)},UI:self.modules.UI,url:{toAddr:self.jam.Aios.Amp.url2addr,fromAddr:self.jam.Aios.Amp.addr2url,},utime:function(){hr=process.hrtime();return hr[0]*1E9+hr[1]},verbose:function(l){self.jam.Aios.config({verbose:l});self.options.verbose=l;},versions:function(){return{shell:options.version,lib:JamLib.options.version,aios:JamLib.Aios.options.version}},without:JamLib.Aios.aios0.without,get world(){return self.jam.world},}
if(this.options.extensions){for(var p in this.options.extensions)this.env[p]=this.options.extensions[p];}
if(this.modules.table)this.env.Table=this.modules.table;if(this.modules.http)this.env.http={get:function(url,path,callback){var snd=url2addr(url),proto=snd.proto||'http';if(proto=='https'&&!self.modules.https)throw('http.get: unsupported HTTPS');if(!snd.port)snd.port=proto=='http'?80:443;if(!path)path='';else if(path.charAt(0)!='/')path='/'+path;if(!self.modules.http.xhr){req=(proto=='https'?self.modules.https.request:self.modules.http.request)({host:snd.address,port:snd.port,path:path,method:'GET',keepAlive:true,headers:{'User-Agent':'Mozilla/5.0 (X11; SunOS i86pc; rv:45.0) Gecko/20100101 Firefox/45.0',}},function(res){if(res.setEncoding!=null)res.setEncoding('utf8');var body='';res.on('data',function(chunk){body=body+chunk;});res.once('end',function(){if(callback)callback(body);});});req.once('error',function(err){print('Warning: request to '+addr2url(snd)+' failed: '+err);if(callback)callback(null,err);});req.end();}else{self.modules.http.request({host:snd.address,port:snd.port,path:path,proto:proto,method:'GET',keepAlive:true,headers:{}},function(err,xhr,body){if(err){print('Warning: request to '+addr2url(snd)+' failed: '+err);if(callback)return callback(null,err);}
if(callback)callback(body);});}},GET:function(url,params,callback){var tokens=url.match(/(http[s]*)?([:\/\/]*)?([^\/]+)\/?(.+)?/);if(!tokens)throw"http.GET: Invalid URL";var proto=tokens[1]||'http',ip=tokens[3],path=tokens[4]||'',sep='';if(params){path+='?';Object.keys(params).forEach(function(param){path+=(sep+param+'='+escape(params[param]));sep='&';});}
return self.env.http.get(proto+'://'+ip,path,function(result,err){if(err||Comp.obj.isError(result)){if(callback)callback(err||result);return;}
try{result=JSON.parse(result);callback(result);}catch(e){if(e.toString().indexOf('SyntaxError')!=-1&&callback)
callback(e.toString()+'\n'+result);else callback(e);}});},put:function(url,path,data,callback){var snd=url2addr(url),proto=snd.proto||'http';if(proto=='https'&&!self.modules.https)throw('http.put: unsupported HTTPS');if(!snd.port)snd.port=80;if(!path)path='';else if(path.charAt(0)!='/')path='/'+path;if(!self.modules.http.xhr){req=(proto=='https'?self.modules.https.request:self.modules.http.request)({host:snd.address,port:snd.port,path:path,method:'POST',keepAlive:self.env.http.options.keepalive,headers:{'User-Agent':'Mozilla/5.0 (X11; SunOS i86pc; rv:45.0) Gecko/20100101 Firefox/45.0','Content-Type':'application/x-www-form-urlencoded','Content-Length':data.length}},function(res){if(res.setEncoding!=null)res.setEncoding('utf8');var body='';res.on('data',function(chunk){body=body+chunk;});res.once('end',function(){if(callback)callback(body);});});req.once('error',function(err){print('Warning: request to '+addr2url(snd)+' failed: '+err);if(callback)callback(err);});req.write(data);req.end();}else{self.modules.http.request({host:snd.address,port:snd.port,path:path,method:'POST',body:data,keepAlive:self.env.http.options.keepalive,headers:{'Content-Type':'application/x-www-form-urlencoded','Content-Length':data.length}},function(err,xhr,body){if(err){print('Warning: request to '+addr2url(snd)+' failed: '+err);if(callback)callback(err);return;}
if(callback)callback(body);})}},POST:function(url,data,callback,params){var tokens=url.match(/(http[s]*)?([:\/\/]*)?([^\/]+)\/?(.+)?/);if(!tokens)throw"http.GET: Invalid URL";var proto=tokens[1]||'http',ip=tokens[3],path=tokens[4]||'',sep='';if(params){path+='?';Object.keys(params).forEach(function(param){path+=(sep+param+'='+escape(params[param]));sep='&';});}
try{data=JSON.stringify(data);}catch(e){if(callback)callback(e);return;}
return self.env.http.put(proto+'://'+ip,path,data,function(result,err){if(err||Comp.obj.isError(result)){if(callback)callback(err||result);return;}
try{result=JSON.parse(result);if(callback)callback(result);}catch(e){if(e.toString().indexOf('SyntaxError')!=-1&&callback)
callback(e.toString()+'\n'+result);else if(callback)callback(e);}});},options:{keepalive:true,}}
if(this.modules.httpserv){if(!this.env.http)this.env.http={};this.env.http.server=function(ip,dir,index){if(!self.modules.httpserv)return;if(!dir)return;if(ip==undefined)ip="localhost:8080";if(self.httpSrv)self.httpSrv.stop();var ipport=8080,tokens=ip.toString().split(':');if(tokens.length==2)ip=tokens[0],ipport=Number(tokens[1]);else if(typeof ip=='number')ipport=ip;self.httpSrv=self.modules.httpserv.HTTPSrv({ip:ip,ipport:ipport,dir:dir,index:index,log:self.output.bind(self)});self.httpSrv.init();self.httpSrv.start();}
if(self.modules.https){if(!this.env.https)this.env.https={};this.env.https.server=function(ip,dir,index){if(!self.modules.httpserv)return;if(!dir)return;if(ip==undefined)ip="localhost:8080";if(self.httpSrv)self.httpSrv.stop();var ipport=8080,tokens=ip.toString().split(':');if(tokens.length==2)ip=tokens[0],ipport=Number(tokens[1]);else if(typeof ip=='number')ipport=ip;self.httpSrv=self.modules.httpserv.HTTPSrv({ip:ip,ipport:ipport,proto:'https',dir:dir,index:index,log:self.output.bind(self)});self.httpSrv.init();self.httpSrv.start();}}}
if(this.modules.nlp)this.env.nlp=this.modules.nlp;if(this.modules.sql)this.env.sql=function(filename,options){return self.modules.sql.Sqld(filename,options);}
if(this.modules.csv){this.env.csv={detect:function(text){return self.modules.csv.detect(text);},read:function(file,convert,isString){var data,text;if(self.options.verbose)self.log('CSV: Reading from '+(isString?'string':file));try{text=isString?file:Io.read_file(file);if(!text)throw'CSV File read error: '+file;if(self.options.verbose)self.log('CSV: Parsing '+(isString?'string':file));self.modules.csv.parse(text,{skipEmptyLines:true,dynamicTyping:true,complete:function(results){if(self.options.verbose)
self.log('CSV parsed with DEL="'+results.meta.delimiter+'" TRUNC='+results.meta.truncated+' ABORT='+results.meta.aborted);data=results.data;if(convert){header=data.shift();data=data.map(function(row){var r={};header.forEach(function(col,i){r[col]=row[i]});return r;})}}});if(data&&data[0].length==1)data=data.map(function(row){return row[0]});return data;}catch(e){return e;}},write:function(file,header,data,sep){var d1=false,fd,i,convert=!Comp.obj.isArray(data[0])&&Comp.obj.isObj(data[0]);if(!sep)sep=',';d1=typeof data[0]!='object';if(!header||header.length==0){if(!convert)
header=d1?['0']:data[0].map(function(x,i){return String(i)});else{header=[];for(var p in data[0]){header.push(p);}}}
try{if(self.options.verbose)self.log('CSV: Wrting to '+file);fd=Io.open(file,'w+');Io.write_line(fd,header.join(sep));if(!d1)
for(i in data){if(!convert)
Io.write_line(fd,data[i].join(sep));else
Io.write_line(fd,header.map(function(col){return data[i][col]}).join(sep));}
else
for(i in data){if(!convert)
Io.write_line(fd,data[i]);else
Io.write_line(fd,data[i][header[0]]);};Io.close(fd);return data.length}catch(e){return e;}}}}
if(!this.rl&&this.modules.readlineSync){this.env.ask=function(msg,choices){var answer;while(choices.indexOf(answer)==-1)
answer=self.modules.readlineSync.question(msg+'? ['+choices.join(',')+'] ');return answer;}}
if(this.options.script)this.env.script(this.options.script);if(this.options.exec)this.process(this.options.exec);return this;}
Shell.prototype.on=function(event,handler){var self=this;if(this.events[event]){var funorig=events[event];this.events[event]=function(){funorig.apply(this,arguments);handler.apply(this,arguments);};}else{this.events[event]=handler;this.jam.Aios.on(event,function(arg1,arg2,arg3,arg4){self.emit(event,arg1,arg2,arg3,arg4)});}}
Shell.prototype.output=function(line){var msg=format(line);if(this.options.output&&msg.length)this.options.output(msg);if(this.rl&&msg.length)this.rl.insertOutput(msg);if(msg.length)this.emit('output',msg);}
Shell.prototype.outputAgent=function(line){var msg=format(line);if(this.options.outputAgent&&msg.length)this.options.outputAgent(msg);else if(this.options.output&&msg.length)this.options.output(msg);if(this.rl&&msg.length)this.rl.insertOutput(msg);if(msg.length)this.emit('output',msg);}
Shell.prototype.outputPrint=function(line){var msg=format(line);if(this.options.outputPrint&&msg.length)this.options.outputPrint(msg);else if(this.options.output&&msg.length)this.options.output(msg);if(this.rl&&msg.length)this.rl.insertOutput(msg);if(msg.length)this.emit('output',msg);}
Shell.prototype.outputAsync=function(line){var msg=format(line);if(this.options.outputAsync&&msg.length)this.options.outputAsync(msg);else if(this.options.output&&msg.length)this.options.output(msg);if(this.rl&&msg.length)this.rl.insertOutput(msg);if(msg.length)this.emit('output',msg);}
Shell.prototype.process=function(line){var self=this;with(this.env){try{if(line.match(/;[ \n]*$/))
eval(line);else
self.output(eval(line));}catch(e){var more='';if(e.name==="SyntaxError"||e.name==="TypeError"){try{var ast=Esprima.parse(line,{tolerant:true,loc:true});if(ast.errors&&ast.errors.length>0)more=", "+ast.errors[0];}catch(_e){e=_e;}
self.output(e.toString()+more)}else if(e.stack){var line=e.stack.toString().match(/<anonymous>:([0-9]+):([0-9]+)\)/)
self.output(e.toString()+(line?', at line '+line[1]:''));}else{self.output(e.toString())}
if(self.options.verbose>1)self.output(Io.sprintstack(e));}}}
module.exports=Shell;};BundleModuleCode['top/jamlib']=function(module,exports){var onexit=false;var start=false;var options={geo:undefined,verbose:0,version:'1.35.1'};global.config={simulation:false,nonetwork:false};var Io=Require('com/io');var Comp=Require('com/compat');var Aios=Require('jam/aios');var Esprima=Require('parser/esprima');var Json=Require('jam/jsonfn');var fs=Require('fs');var Sat=Require('dos/ext/satelize');var GPS5=Require('geoip/gps5');var GeoLoc5=Require('geoip/geoloc5');var CBL=Require('com/cbl');var platform=Require('os/platform');var DIR=Aios.DIR;var environment=process.env;process.argv.slice(2).forEach(function(arg){var tokens=arg.match(/([a-zA-Z]+):(['"0-9a-zA-Z_:\->\.\{\},;]+)/);if(tokens&&tokens.length==3)environment[tokens[1]]=tokens[2];});function locationEvalError(e){return(e.lineNumber?(' at line '+e.lineNumber+
(e.columnNumber?(' column '+e.columnNumber):'')):'')}
if(typeof setImmediate=='undefined'){function setImmediate(callback){return setTimeout(callback,0)};}
DIR.North=function(ip){return{tag:DIR.NORTH,ip:ip}}
DIR.South=function(ip){return{tag:DIR.SOUTH,ip:ip}}
DIR.West=function(ip){return{tag:DIR.WEST,ip:ip}}
DIR.East=function(ip){return{tag:DIR.EAST,ip:ip}}
DIR.Up=function(ip){return{tag:DIR.UP,ip:ip}}
DIR.Down=function(ip){return{tag:DIR.DOWN,ip:ip}}
var jam=function(options){var self=this,p,conn,node;this.options=options||{};this.environment=environment;if(this.setup)this.setup();if(this.options.world&&!this.options.id)this.options.id=this.options.world;if(!this.options.id)this.options.id=Aios.aidgen();if(!this.options.log)this.options.log={};if(!this.options.logJam)this.options.logJam={pid:false,host:false,time:false};this.verbose=this.options.verbose||0;this.Aios=Aios;this.DIR=Aios.aios.DIR;Aios.options.verbose=this.verbose;if(options.scheduler)Aios.current.scheduler=scheduler;if(options.nolimits||options.nowatch||options.checkpoint)
Aios.config({nolimits:options.nolimits,nowatch:options.nowatch,checkpoint:options.checkpoint});if(this.options.print)Aios.print=Aios.printAgent=this.options.print;if(this.options.print2)Aios.printAgent=this.options.print2;if(this.options.printAgent)Aios.printAgent=this.options.printAgent;if(this.options.printAsync)Aios.printAsync=this.options.printAsync;this.log=function(msg){var s='[JAM',sep=' ';if(self.options.logJam.pid&&process)s+=(' '+process.pid),sep=':';if(self.options.logJam.world&&Aios.current.world)s+=(sep+Aios.current.world.id),sep=':';if(self.options.logJam.node&&Aios.current.node)s+=(sep+Aios.current.node.id),sep=':';if(self.options.logJam.time)s+=(sep+Aios.time());Aios.print(s+'] '+msg);};this.err=function(msg,err){self.log('Error: '+msg);throw(err||'JAMLIB');}
this.warn=function(msg){self.log('Warning: '+msg);}
this.error=undefined;this.world=Aios.World.World([],{id:this.options.world||this.options.id.toUpperCase(),classes:options.classes||[],scheduler:options.scheduler,verbose:options.verbose});if(this.verbose)this.log('Created world '+this.world.id+'.');this.node=none;this.run=false;this.ticks=0;this.steps=0;this.loop=none;this.looping=none;Aios.config({fastcopy:this.options.fastcopy,verbose:this.options.verbose});if(this.options.log)
for(p in this.options.log)Aios.config(this.options.log[p]?{"log+":p}:{"log-":p});this.process=Aios.Proc.Proc();this.process.agent={id:'jamlib'};this.events={};}
var JamAnal=Require('jam/analyzer');JamAnal.current(Aios);jam.prototype.analyzeSyntax=JamAnal.jamc.prototype.analyze;jam.prototype.syntax=JamAnal.jamc.prototype.syntax;jam.prototype.addClass=function(name,constructor,env){this.world.addClass(name,constructor,env);if(this.verbose)this.log('Agent class '+name+' added to world library.');};jam.prototype.addNode=function(nodeDesc){var node,x,y;x=nodeDesc.x;y=nodeDesc.y;if(Comp.array.find(this.world.nodes,function(node){return node.position.x==x&&node.position.y==y;})){this.err('addNodes: Node at positition ('+x+','+y+') exists already.');return;}
node=Aios.Node.Node({id:nodeDesc.id||Aios.aidgen(),position:{x:x,y:y}},true);if(this.verbose)this.log('Created node '+node.id+' ('+x+','+y+').');this.world.addNode(node);return node.id;}
jam.prototype.addNodes=function(nodes){var n,node,x,y,nodeids=[];for(n in nodes){nodeids.push(this.addNode(nodes[n]));}
return nodeids;}
jam.prototype.analyze=function(ac,options){var source,name,syntax,content,report,interface;if(Comp.obj.isString(ac)){}else if(Comp.obj.isObject(ac)){}else if(Comp.obj.isFunction(ac)){source=ac.toString();if(!options.classname){name=source.match(/^ *function *([^\s\(]*)\(/);if(name&&name[1]!='')options.classname=name[1];}
content='var ac ='+source;syntax=Esprima.parse(content,{tolerant:true,loc:true});try{interface=this.analyzeSyntax(syntax,{classname:options.classname||'anonymous',level:options.level==undefined?2:options.level,verbose:options.verbose,err:function(msg){throw msg},out:function(msg){if(!report)report=msg;else report=report+'\n'+msg;},warn:function(msg){if(!report)report=msg;else report=report+'\n'+msg;}});return{report:report||'OK',interface:interface};}catch(e){return{report:e,interface:interface};}}}
jam.prototype.clock=Aios.clock;jam.prototype.compileClass=function(name,constructor,options){var ac,p,verbose,content,syntax,report,text,env={ac:undefined},self=this,ac;if(typeof name=='function')constructor=name,name=undefined,options=constructor;if(typeof options=='object')verbose=options.verbose||0;else if(options!=undefined)verbose=options;else verbose=this.verbose;if(typeof constructor=='function')text=constructor.toString();else text=constructor;if(!name){name=text.match(/[\s]*function[\s]*([A-Za-z0-9_]+)[\s]*\(/);if(!name)throw('compileClass: No class name provided and no name found in constructor '+
text.substring(0,80));name=name[1];}
content='var ac = '+text;try{syntax=Esprima.parse(content,{tolerant:true,loc:true})}
catch(e){throw'compileClass('+name+'): Parsing failed with '+e}
report=this.analyzeSyntax(syntax,{classname:name,level:2,verbose:verbose||0,err:function(msg){self.log(msg)},out:function(msg){self.log(msg)},warn:function(msg){self.log(msg)}});if(report.errors.length){throw'compileClass('+name+'): failed with '+report.errors.join('; ')};for(p in report.activities)env[p]=p;try{with(env){eval(content)}}
catch(e){throw('compileClass('+name+'): failed with '+e+locationEvalError(e))};ac=env.ac;env.ac=undefined;this.addClass(name,ac,env);return name;}
jam.prototype.connectNodes=function(connections){var c,node1,node2,x1,y1,x2,y2,dir;if(connections[0].x!=undefined&&connections[0].y!=undefined){if(connections.length!=2)throw'INVALID';connections=[{x1:connections[0].x,x2:connections[1].x,y1:connections[0].y,y2:connections[1].y}];}
for(c in connections){x1=connections[c].x1;y1=connections[c].y1;x2=connections[c].x2;y2=connections[c].y2;if(this.verbose)this.log('Connecting ('+x1+','+y1+') -> ('+x2+','+y2+')');node1=Comp.array.find(this.world.nodes,function(node){return node.position.x==x1&&node.position.y==y1;});node2=Comp.array.find(this.world.nodes,function(node){return node.position.x==x2&&node.position.y==y2;});if(!node1)this.err('connectNodes: Node at positition ('+x1+','+y1+') does not exist.');if(!node2)this.err('connectNodes: Node at positition ('+x2+','+y2+') does not exist.');if((x2-x1)==0){if((y2-y1)>0)dir=Aios.DIR.SOUTH;else dir=Aios.DIR.NORTH;}else if((x2-x1)>0)dir=Aios.DIR.EAST;else dir=Aios.DIR.WEST;this.world.connect(dir,node1,node2);this.world.connect(Aios.DIR.opposite(dir),node2,node1);}}
jam.prototype.connectTo=function(to,nodeid){var node=this.getNode(nodeid),tokens=(typeof to=='string')?to.split('->'):null,dir;if(!node)return;if(to.tag)dir=to;else if(tokens.length==2){dir=Aios.DIR.from(tokens[0]);if(dir)dir.ip=tokens[1];}else dir={tag:'DIR.IP',ip:to};if(dir)this.world.connectTo(dir,node);}
jam.prototype.connected=function(dir,nodeid){var node=this.getNode(nodeid);if(!node)return;return this.world.connected(dir,node);}
jam.prototype.createAgent=function(ac,args,level,className,parent){var node=this.world.nodes[this.node],process=none,sac;if(level==undefined)level=Aios.options.LEVEL;if(!className&&typeof ac=='string')className=ac;if(!className&&typeof ac=='function')className=Aios.Code.className(ac);if(Comp.obj.isFunction(ac)||Comp.obj.isObject(ac)){process=Aios.Code.createOn(node,ac,args,level,className);if(process&&!process.agent.parent)process.agent.parent=parent;if(process)return process.agent.id;}else{if(this.world.classes[ac])
process=Aios.Code.createOn(node,this.world.classes[ac][level],args,level,className);else{this.error='createAgent: Cannot find agent class '+ac;this.log(this.error);return;}
if(process){if(!process.agent.parent)process.agent.parent=parent;process.agent.ac=ac;return process.agent.id;}else return none;}}
jam.prototype.createAgentOn=function(node,ac,args,level,className,parent){var res,_currentNode=this.node,found=this.getNode(node);if(found){this.setCurrentNode();res=this.createAgent(ac,args,level,className,parent);this.setCurrentNode(_currentNode);}
return res;}
jam.prototype.createPort=function(dir,options,nodeid){if(!options)options={};var multicast=options.multicast;switch(dir.tag){case Aios.DIR.NORTH:case Aios.DIR.SOUTH:case Aios.DIR.WEST:case Aios.DIR.EAST:case Aios.DIR.UP:case Aios.DIR.DOWN:multicast=false;break;}
if(dir.ip&&typeof dir.ip=='string'&&dir.ip.indexOf('//')>0){var addr=Aios.Amp.url2addr(dir.ip);if(!options.proto&&addr.proto)options.proto=addr.proto;dir.ip=Aios.Amp.addr2url(addr);}
if(options.from==undefined&&dir.ip)options.from=dir.ip.toString();var chan=this.world.connectPhy(dir,this.getNode(nodeid),{broker:options.broker,keepAlive:options.keepAlive,multicast:multicast,name:options.name,on:options.on,oneway:options.oneway,pem:options.pem,proto:options.proto||'udp',rcv:options.from,secure:options.secure,sharedSocket:options.sharedSocket,snd:options.to,verbose:(options.verbose!=undefined?options.verbose:this.verbose)});chan.init();chan.start();return chan;}
jam.prototype.disconnect=function(to,nodeid){var node=this.getNode(nodeid);if(node){this.world.disconnect(to,node);}}
jam.prototype.emit=function(){Aios.emit.apply(this,arguments);}
jam.prototype.execute=function(data,file){if(!data&&file&&fs)
try{data=fs.readFileSync(file,'utf8');}catch(e){this.log('Error: Reading file '+file+' failed: '+e);return undefined;}
if(data)return this.world.nodes[this.node].receive(data,true);}
jam.prototype.executeOn=function(data,node,file){node=this.getNode(node);if(!node)return;if(!data&&file&&fs)
try{data=fs.readFileSync(file,'utf8');}catch(e){this.log('Error: Reading file '+file+' failed: '+e);return undefined;}
if(data)return node.receive(data,true);}
jam.prototype.extend=function(level,name,funcOrObj,argn){var self=this;if(Comp.obj.isArray(level)){Comp.array.iter(level,function(l){self.extend(l,name,funcOrObj,argn)});return;}
function range(n){var l=[];for(var i=0;i<n+1;i++)l.push(i);return l;}
switch(level){case 0:if(Aios.aios0[name])throw Error('JAM: Cannot extend AIOS(0) with '+name+', existst already!');Aios.aios0[name]=funcOrObj;break;case 1:if(Aios.aios1[name])throw Error('JAM: Cannot extend AIOS(1) with '+name+', existst already!');Aios.aios1[name]=funcOrObj;break;case 2:if(Aios.aios2[name])throw Error('JAM: Cannot extend AIOS(2) with '+name+', existst already!');Aios.aios2[name]=funcOrObj;break;case 3:if(Aios.aios3[name])throw Error('JAM: Cannot extend AIOS(3) with '+name+', existst already!');Aios.aios3[name]=funcOrObj;break;default:throw Error('JAM: Extend: Invalid privilige level argument ([0,1,2,3])');}
if(!JamAnal.corefuncs[name]){if(typeof funcOrObj=='function')
JamAnal.corefuncs[name]={argn:Comp.obj.isArray(argn)?argn:argn!=undefined?range(argn):range(funcOrObj.length)};else{var obj={};Object.keys(funcOrObj).forEach(function(attr){obj[attr]={argn:range(funcOrObj[attr].length)};});JamAnal.corefuncs[name]={obj:obj};}}}
jam.prototype.getCurrentNode=function(asname){if(!asname)return this.node;else return this.world.nodes[this.node].id;}
jam.prototype.getNode=function(id){var node;if(id==undefined)return this.world.nodes[this.node];if(typeof id=='number')
node=this.world.nodes[id];else if(typeof id=='string'){loop:for(var i in this.world.nodes){if(this.world.nodes[i]&&this.world.nodes[i].id==id){node=this.world.nodes[i];break loop;}}}else if(id.x!=undefined&&id.y!=undefined){loop:for(var i in this.world.nodes){if(this.world.nodes[i]&&Comp.obj.equal(this.world.nodes[i].position,id)){node=this.world.nodes[i];break loop;}}}
return node;}
jam.prototype.getNodeName=function(nodeNumberorPosition){var node=this.getNode(nodeNumberorPosition);if(node)return node.id;}
jam.prototype.getProcess=function(agent){if(!agent)
return Aios.current.process;else{var node=this.getNode();if(node)return node.getAgentProcess(agent);}}
jam.prototype.getWorldName=function(){return this.world.id;}
jam.prototype.info=function(kind,id){switch(kind){case'node':var node=this.getNode(id);if(!node)return;return{id:node.id,position:node.position,location:node.location,type:node.type}
break;case'agent':var agent=this.getProcess(id);if(!agent)return;var code=Aios.Code.print(agent.agent,true);return{id:id,pid:agent.pid,level:agent.level,blocked:agent.blocked,suspended:agent.suspended,resources:agent.resources,code:code}
break;case'agent-data':var agent=this.getProcess(id);if(!agent)return;else return agent.agent;break;case'version':return Aios.options.version;case'host':return{type:global.TARGET,watchdog:Aios.watchdog?true:false,protect:Aios.watchdog&&Aios.watchdog.protect?true:false,jsonify:Aios.options.json,minify:!Aios.Code.options.compactit,};case'platform':return platform;}}
jam.prototype.init=function(callback){var i=0,j=0,n,p,id,node,connect=[],chan,dir,dirs,pos,self=this;this.node=0;if(!this.options.network){if(this.options.position)i=this.options.position.x,j=this.options.position.y;if(!this.getNode({x:i,y:j})){node=Aios.Node.Node({id:this.options.id,position:{x:i,y:j},TMO:this.options.TMO,type:this.options.type},true);if(this.verbose)this.log('Created '+(i==0&&j==0?'root ':'')+'node '+node.id+' ('+i+','+j+').');this.world.addNode(node);}
this.register(node);}else if(!this.options.network.cluster){if(this.options.network.rows&&this.options.network.columns){for(j=0;j<this.options.network.rows;j++)
for(i=0;i<this.options.network.columns;i++){node=Aios.Node.Node({id:Aios.aidgen(),position:{x:i,y:j},TMO:this.options.TMO},true);if(this.verbose)this.log('Created node '+node.id+' at ('+i+','+j+').');if(i==0&&j==0){this.register(node);}
this.world.addNode(node);}
for(j=0;j<this.options.network.rows;j++)
for(i=0;i<this.options.network.columns;i++){if(i+1<this.options.network.columns)connect.push({x1:i,y1:j,x2:i+1,y2:j});if(j+1<this.options.network.rows)connect.push({x1:i,y1:j,x2:i,y2:j+1});}
if(this.options.network.connect)connect=connect.filter(this.options.network.connect);this.connectNodes(connect);}}else if(this.options.network.cluster&&this.options.fork){dirs=[DIR.ORIGIN,DIR.EAST,DIR.SOUTH,DIR.SE,DIR.WEST,DIR.SW,DIR.NORTH,DIR.NW,DIR.NE];pos={x:[0,1,0,1,-1,-1,0,-1,1],y:[0,0,1,1,0,1,-1,-1,-1]};this.cluster=[];this.master=true;for(j=0;j<this.options.network.rows;j++)
for(i=0;i<this.options.network.columns;i++){id=Aios.aidgen();if(i==0&&j==0){dir=undefined;node=Aios.Node.Node({id:id,position:{x:i,y:j},TMO:this.options.TMO},true);if(this.verbose)this.log('Created root node '+node.id+' at ('+i+','+j+').');this.register(node);this.world.addNode(node);this.setCurrentNode(id);}else{n=i+j*this.options.network.columns;dir=dirs[n];if(this.verbose)this.log('Started cluster node '+id+' at ('+i+','+j+'). with link '+DIR.print(dir));this.cluster[id]=this.options.fork(process.argv[1],['autosetup:'+JSON.stringify({id:id,world:this.world.id,cluster:true,network:null,position:{x:pos.x[n],y:pos.y[n]},dir:dir,connections:{stream:{dir:DIR.opposite(dir)}}})]);this.cluster[id].dir=dir;}}
for(p in this.cluster){chan=this.world.connectPhy(this.cluster[p].dir,this.getNode(),{proto:'stream',sock:this.cluster[p],mode:'object',verbose:this.verbose});chan.init();}}
if(this.options.provider)this.world.nodes[this.node].ts.register(function(pat){return self.options.provider(pat);});if(this.options.consumer)this.world.nodes[this.node].ts.register(function(tuple){return self.options.consumer(tuple);},true);if(this.options.connections){for(p in this.options.connections){conn=this.options.connections[p];if(!conn)continue;if(p=='ip'||conn.proto){n=1;switch(p){case'ip':dir=this.DIR.IP(this.options.connections.ip.from||'*');n=(conn.range&&conn.range.length==2&&(conn.range[1]-conn.range[0]+1))||conn.num||1;break;case'north':dir=this.DIR.NORTH;break;case'south':dir=this.DIR.SOUTH;break;case'west':dir=this.DIR.WEST;break;case'east':dir=this.DIR.EAST;break;case'up':dir=this.DIR.UP;break;case'down':dir=this.DIR.DOWN;break;}
function makeAddr(ip,i){if(!conn.range)return ip;else return ip+':'+(conn.range[0]+i);}
for(i=0;i<n;i++){chan=this.world.connectPhy(dir,this.getNode(),{broker:conn.broker,multicast:conn.multicast,name:conn.name,on:conn.on,oneway:conn.oneway,proto:conn.proto||'udp',rcv:makeAddr(conn.from,i),snd:conn.to,verbose:this.verbose});chan.init();}}else if(conn.send){node=this.world.nodes[this.node];function makeconn(p,conn){var link={_handler:[],emit:function(event,msg){if(link._handler[event])link._handler[event](msg);},on:function(event,callback){link._handler[event]=callback;},send:function(data,dest,context){var res;self.world.nodes[self.node].connections[p]._count+=data.length;res=conn.send(data,dest);if(!res){context.error='Migration to destination '+dest+' failed';throw'MOVE';};context.process.finalize();},status:conn.status?conn.status:(function(){return true}),count:conn.count?conn.count:function(){return link._count},_count:0};if(conn.register)conn.register(link);return link;}
node.connections[p]=makeconn(p,conn);node.connections[p].on('agent',node.receive.bind(node));node.connections[p].on('signal',node.handle.bind(node));}else if(p=='stream'){chan=this.world.connectPhy(conn.dir,this.getNode(),{proto:'stream',sock:process,mode:'object',verbose:this.verbose});chan.init();}}}
if(callback)callback();}
jam.prototype.inp=function(pat,all){return this.world.nodes[this.node].ts.extern.inp(pat,all);}
jam.prototype.kill=function(id,node){if(id=='*'){this.world.nodes[this.node].processes.table.forEach(function(p){if(p)Aios.kill(p.agent.id);});}else
return Aios.kill(id);}
jam.prototype.locate=function(nodeid,cb,options){if(typeof nodeid=='function'){options=cb;cb=nodeid;nodeid=0};if(typeof nodeid=='object'){options=nodeid;cb=null;nodeid=0};var node=this.getNode(nodeid);if(!node)return;return GeoLoc5.locate(function(location,errors){node.location=node.location||{};Object.assign(node.location,location);if(cb)cb(location,errors);},options);}
jam.prototype.lookup=function(dir,callback,nodeid){var node=this.getNode(nodeid);if(!node)return;return this.world.lookup(dir,callback,node);}
jam.prototype.mark=function(tuple,tmo){return this.world.nodes[this.node].ts.extern.mark(tuple,tmo);}
jam.prototype.migrate=function(data){return this.world.nodes[this.node].receive(data,false);}
jam.prototype.on=function(event,handler){Aios.on(event,handler);}
jam.prototype.off=function(ev){Aios.off(event);}
jam.prototype.open=function(file,options){var self=this,res,text,name,ast=null;if(!options)options={};name=options.classname||'<unknown>';if(options.verbose>0)this.log('Reading agent class template '+name+' from '+file);function parseModel(text){var modu={},more,module={exports:{}},name=text.match(/[\s]*function[\s]*([a-z0-9]+)[\s]*\(/);if(name)name=name[1];function open(filename){var text;try{text=fs?fs.readFileSync(filename,'utf8'):null;return parseModel(text);}catch(e){self.log('Error: Opening of '+(fs?file:'text')+' failed: '+e);}}
try{with(module){eval('res = '+text)};if(name){modu[name]=res;return modu}
else if(module.exports)return module.exports;else return res;}catch(e){try{ast=Esprima.parse(text,{tolerant:true,loc:true});if(ast.errors&&ast.errors.length>0)more=', '+ast.errors[0];}catch(e){if(e.lineNumber)more=', in line '+e.lineNumber;}
self.log(e.name+(e.message?': '+e.message:'')+(more?more:''));}}
try{text=fs?fs.readFileSync(file,'utf8'):file;return parseModel(text);}catch(e){this.log('Error: Opening of '+(fs?file:'text')+' failed: '+e);}};jam.prototype.out=function(tuple){return this.world.nodes[this.node].ts.extern.out(tuple);}
jam.prototype.rd=function(pat,all){return this.world.nodes[this.node].ts.extern.rd(pat,all);}
if(fs)jam.prototype.readClass=function(file,options){var self=this,ac,name,env,interface,text,modu,path,p,m,regex1,ast=null,fileText=null,off=null;this.error=_;function errLoc(ast){var err;if(ast&&ast.errors&&ast.errors.length){err=ast.errors[0];if(err.lineNumber!=undefined)return'line '+err.lineNumber;}
return'unknown'}
try{if(!options)options={};if(options.verbose>0)this.log('Looking up agent class template(s) from '+file);if(Comp.obj.isEmpty(modu)){if(options.verbose>0)this.log('Reading agent class template(s) from file '+file);if(Comp.string.get(file,0)!='/')
path=(process.cwd?process.cwd()+'/':'./')+file;else
path=file;fileText=fs.readFileSync(path,'utf8');ast=Esprima.parse(fileText,{tolerant:true,loc:true});if(require.cache)delete require.cache[file];modu=require(path);if(Comp.obj.isEmpty(modu)){modu={};if(!fileText)throw'No such file!';name=fileText.match(/[\s]*function[\s]*([a-z0-9]+)[\s]*\(/);if(!name)throw('Export interface of module is empty and file contains no valid function definition!');name=name[1];eval('(function () {'+fileText+' modu["'+name+'"]='+name+'})()');}}
if(!modu||Comp.obj.isEmpty(modu))throw'Empty module.';for(m in modu){ac=modu[m];env={};if(fileText)off=this.syntax.find(fileText,'VariableDeclarator',m);if(off&&off.loc)this.syntax.offset=off.loc.start.line-1;content='var ac = '+ac;syntax=Esprima.parse(content,{tolerant:true,loc:true});interface=this.analyzeSyntax(syntax,{classname:m,level:2,verbose:options.verbose||0,err:options.error||function(msg){throw(msg)},out:function(msg){self.log(msg)},warn:function(msg){self.log(msg)}});for(var p in interface.activities)env[p]=p;with(env){eval(content)};if(options.verbose>0)this.log('Adding agent class constructor '+m+' ('+(typeof ac)+').');this.addClass(m,ac,env);this.syntax.offset=0;}
this.error=undefined;return true;}catch(e){this.error='Compiling agent class file "'+file+'" failed: '+e+
(ast&&ast.errors.length?', in '+errLoc(ast):'');if(options.error)
options.error(e+(ast&&ast.errors.length?', in '+errLoc(ast):''));else{this.log(this.error);}
return false;}};jam.prototype.register=function(node){this.on('agent',function(msg){node.receive(msg)});this.on('signal',function(msg){node.handle(msg)});}
jam.prototype.removeNode=function(nodeid){this.world.removeNode(nodeid);}
jam.prototype.rm=function(pat,all){return this.world.nodes[this.node].ts.extern.rm(pat,all);}
jam.prototype.saveSnapshotOn=function(aid,node,file,kill){var snapshot,pro;node=this.getNode(node);if(!node)return;pro=node.getAgentProcess(aid);if(!pro)return;snapshot=Aios.Code.ofCode(pro,false);if(kill)Aios.killOn(aid,node);if(!file)return snapshot;else if(fs)return fs.writeFileSync(file,snapshot,'utf8');}
jam.prototype.saveSnapshot=function(aid,file,kill){return this.saveSnapshotOn(aid,_,file,kill);}
jam.prototype.schedule=function(){if(this.loop){clearTimeout(this.loop);setImmediate(this.looping);}else if(!this.run)setImmediate(this.looping);}
jam.prototype.security=Aios.Sec;jam.prototype.setCurrentNode=function(n){if(typeof n=='number'){if(n>=0&&n<this.world.nodes.length)this.node=n;}else if(typeof n=='string'){this.node=this.world.nodes.indexOf(this.world.getNode(n))}
current.node=this.world.nodes[this.node];}
jam.prototype.signal=function(to,sig,arg,broadcast){var node=this.getNode(),_process=Aios.current.process;Aios.current.process=this.process;if(!broadcast)
Aios.aios.send(to,sig,arg);else
Aios.aios.broadcast(to,sig,arg);Aios.current.process=_process;this.schedule();}
jam.prototype.start0=function(callback){if(this.run)return;var self=this,cbl=CBL(callback);this.world.nodes.forEach(function(node){node.connections.forEach(function(chan,kind){if(!chan)return;if(chan.start)cbl.push(function(next){chan.start(next)});});});cbl.start();Aios.on('schedule',function(){self.schedule();});this.world.start();if(this.verbose)this.log('Starting JAM .. ');return;}
jam.prototype.start=function(callback){if(this.run)return;var self=this,current=Aios.current,cbl=CBL(callback);this.world.nodes.forEach(function(node){node.connections.forEach(function(chan,kind){if(!chan)return;if(chan.start)cbl.push(function(next){chan.start(next)});});});cbl.start();Aios.on('schedule',function(){self.schedule();});function loop(){var loop=function(){var nexttime,curtime;if(self.verbose>3)self.log('loop: Entering scheduler #'+self.ticks);self.ticks++;nexttime=Aios.scheduler();curtime=Aios.time();if(self.verbose>3)self.log('loop: Scheduler returned nexttime='+nexttime+' ('+(nexttime>0?nexttime-curtime:0)+')');if(!self.run)return;if(nexttime>0)
self.loop=setTimeout(loop,nexttime-curtime);else if(nexttime==0)
self.loop=setTimeout(loop,1000);else setImmediate(loop);};self.loop=setTimeout(loop,1);};this.looping=loop;Aios.config({iterations:100});this.run=true;this.world.start();if(this.verbose)this.log('Starting JAM loop .. ');if(!this.options.scheduler)loop();}
jam.prototype.stats=function(kind,id){var p,n,sys,conn,pro,agent,state,stats,allstats={},signals,node;switch(kind){case'process':case'agent':for(n in this.world.nodes){stats={};node=this.world.nodes[n];for(p in node.processes.table){if(node.processes.table[p]){pro=node.processes.table[p];if(pro.signals.length==0)signals=[];else signals=pro.signals.map(function(sig){return sig[0]});agent=pro.agent;if(pro.suspended)state='SUSPENDED';else if(pro.blocked)state='BLOCKED';else if(pro.dead)state='DEAD';else if(pro.kill)state='KILL';else if(pro.move)state='MOVE';else state='READY';stats[agent.id]={pid:pro.pid,gid:pro.gid,state:state,parent:pro.agent.parent,class:pro.agent.ac,next:agent.next,resources:Comp.obj.copy(pro.resources)};if(signals.length)stats[agent.id].signals=signals;}}
allstats[node.id]=stats;}
break;case'node':return Comp.obj.copy(this.getNode(id).stats);break;case'conn':for(n in this.world.nodes){stats={};node=this.world.nodes[n];for(p in node.connections){conn=node.connections[p];if(conn){stats[p]={count:conn.count(),conn:conn.status('%')};}}
allstats[node.id]=stats;}
break;case'vm':if(process&&process.memoryUsage){sys=process.memoryUsage();for(p in sys)sys[p]=(sys[p]/1024)|0;sys.v8=process.versions&&process.versions.v8;sys.node=process.versions&&process.versions.node;sys.arch=process.arch;sys.platform=process.platform;sys.watchdog=Aios.watchdog?(Aios.watchdog.checkPoint?'semi':'full'):'none';return sys;}
break;}
if(this.world.nodes.length==1)return stats;else return allstats;}
jam.prototype.step=function(steps,callback){var self=this,sync=callback===true,milliTime=function(){return Math.ceil(Date.now())},current=Aios.current,curtime=Aios.time(),lasttime=curtime;function loop(){var loop=function(){var nexttime,curtime;if(self.verbose>1)self.log('loop: Entering scheduler #'+self.ticks);self.ticks++,self.steps--;self.time=curtime=Aios.time();nexttime=Aios.scheduler();curtime=Aios.time();if(self.verbose>3)self.log('loop: Scheduler returned nexttime='+nexttime+' ('+(nexttime>0?nexttime-curtime:0)+')');if(sync){self.time=curtime;return;}
if(self.steps==0||!self.run){self.loop=none;self.run=false;self.time=curtime;if(callback)callback();return;}
if(nexttime>0)
self.loop=setTimeout(loop,nexttime-curtime);else if(nexttime<0)self.loop=setImmediate(loop);else{self.loop=none;self.run=false;self.time=curtime;if(callback)callback();}};if(sync)loop();else self.loop=setTimeout(loop,1);};this.looping=loop;Aios.config({iterations:1});this.steps=steps;this.run=true;if(this.time>0)current.world.lag=current.world.lag+(curtime-this.time);this.time=curtime;if(!this.options.scheduler){if(sync){this.run=true;for(var step=0;step<steps;step++)loop();this.run=false;}else
loop();}}
jam.prototype.stop=function(callback){if(!this.run)return;this.run=false,cbl=CBL(callback);this.log('Stopping JAM ..');Aios.off('schedule');if(this.loop)
clearTimeout(this.loop);this.world.nodes.forEach(function(node){node.connections.forEach(function(chan,kind){if(!chan)return;if(chan.stop)cbl.push(function(next){chan.stop(next)});});});cbl.start();}
jam.prototype.test=function(pat){return this.world.nodes[this.node].ts.extern.exists(pat);}
jam.prototype.ts=function(pat,callback){return this.world.nodes[this.node].ts.extern.ts(pat,callback);}
jam.prototype.time=function(){return Aios.time();}
jam.prototype.version=function(){return options.version;}
var Jam=function(options){var obj=new jam(options);return obj;};if(environment.autosetup){try{var _options=JSON.parse(environment.autosetup);jam.prototype.setup=function(){for(var p in _options)this.options[p]=_options[p];}}catch(e){console.log('['+process.pid+'] JAM auto setup failed: '+e);}}
module.exports={Aios:Aios,Comp:Comp,Esprima:Esprima,Io:Io,Jam:Jam,Json:Json,environment:environment,options:options}};BundleModuleCode['jam/aios']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var Name=Require('com/pwgen');var Conf=Require('jam/conf');var Code=Require('jam/code');var Sig=Require('jam/sig');var Node=Require('jam/node');var Proc=Require('jam/proc');var Sec=Require('jam/security');var Ts=Require('jam/ts');var World=Require('jam/world');var Chan=Require('jam/chan');var Mobi=Require('jam/mobi');var Simu=global.config.simulation?Require(global.config.simulation):none;var Json=Require('jam/jsonfn');var watchdog=Require('jam/watchdog');var util=Require('util');var Amp=Require('jam/amp')
var aiosExceptions=['CREATE','MOVE','SIGNAL','SCHEDULE','WATCHDOG','KILL'];var aiosErrors=['SCHEDULE','CPU','EOL','EOM','EOT','EOA','EOR',];var aiosEvents=['agent','agent+','agent-','signal','signal+','node+','node-'];var options={version:"1.67.2",debug:{},fastcopy:false,json:false,log:{node:false,agent:true,parent:false,pid:false,host:false,time:false,Time:true,date:false,class:false},nameopts:{length:8,memorable:true,lowercase:true},nolimits:false,nostats:false,useproc:false,verbose:0,LIFETIME:Infinity,TIMESCHED:200,TIMEPOOL:5000,MEMPOOL:50000,TSPOOL:1000,TSTMO:0,AGENTPOOL:20,MINCOST:0.1,RUNTIME:1000,AGENTSIZE:60000,AGENTSIZEMAX:256000,IDLETIME:0,LEVEL:1,security:{}};var timer,ticks=0,iterations=0,events={};var current={process:none,world:none,node:none,network:none,error:none,scheduler:none};function clock(what){if(what==undefined)return Io.Time();else if(what=='date')return Io.Date();else return Io.time();}
function format(msg,cls){switch(cls){case'aios':return('['+(options.log.host?('#'+process.pid+'.'):'')+
(options.log.world&&current.world?(current.world.id+'.'):'')+
(options.log.node&&current.node?(current.node.id+'.'):'')+
(options.log.pid&&current.process?('('+current.process.pid+')'):'')+
(options.log.date?('@'+Io.date()):(options.log.time?('@'+Io.time()):(options.log.Time?('@'+Io.Time()):'')))+'] '+msg);case'agent':return('['+(options.log.host?('#'+process.pid+'.'):'')+
(options.log.world&&current.world?(current.world.id+'.'):'')+
(options.log.node&&current.node?(current.node.id+'.'):'')+
(options.log.class&&current.process?(current.process.agent.ac+'.'):'')+
(options.log.agent&&current.process?(current.process.agent.id):'')+
(options.log.parent&&current.process?('<'+current.process.agent.parent):'')+
(options.log.pid&&current.process?('('+current.process.pid+')'):'')+
(options.log.date?('@'+Io.date()):(options.log.time?('@'+Io.time()):(options.log.Time?('@'+Io.Time()):'')))+'] '+msg);default:return('['+
(options.log.date?('@'+Io.date()):(options.log.time?('@'+Io.time()):(options.log.Time?('@'+Io.Time()):'')))+'] '+msg)}}
var logAgent=function(){var msg='';arguments.forEach(function(arg,i){if(typeof arg=='string'||typeof arg==Number)msg+=(i>0?', '+arg:arg);else msg+=(i>0?' '+Io.inspect(arg):Io.inspect(arg));});(Aios.printAgent||Aios.print)(format(msg,'agent'))}
var logAIOS=function(){var msg='';arguments.forEach(function(arg,i){if(typeof arg=='string'||typeof arg==Number)msg+=(i>0?', '+arg:arg);else msg+=(i>0?' '+Io.inspect(arg):Io.inspect(arg));});if(current.process)(Aios.printAgent||Aios.print)(format(msg,'aios'));else(Aios.printAgent||Aios.print)(format(msg));}
var logAIOSasync=function(){var msg='';arguments.forEach(function(arg,i){if(typeof arg=='string'||typeof arg==Number)msg+=(i>0?', '+arg:arg);else msg+=(i>0?' '+Io.inspect(arg):Io.inspect(arg));});if(current.process)(Aios.printAsync||Aios.print)(Aios.printAgent||Aios.print)(format(msg,'aios'));else(Aios.printAsync||Aios.print)(format(msg));}
var log=function(){var msg='',pref='';arguments.forEach(function(arg,i){if(typeof arg=='string'||typeof arg==Number)msg+=(i>0?', '+arg:arg);else msg+=(i>0?', '+Io.inspect(arg):Io.inspect(arg));});if(options.log.host&&typeof process!='undefined')pref='#'+process.pid+': ';if(options.log.date)pref=pref+Io.date()+' ';else if(options.log.time)pref=pref+Io.time()+' ';else if(options.log.Time)pref=pref+Io.Time()+' ';if(msg[0]=='[')Aios.print(pref+msg);else Aios.print('[AIOS'+pref+'] '+msg);}
var logAsync=function(){var msg='',pref='';arguments.forEach(function(arg,i){if(typeof arg=='string'||typeof arg==Number)msg+=(i>0?', '+arg:arg);else msg+=(i>0?', '+Io.inspect(arg):Io.inspect(arg));});if(options.log.host&&typeof process!='undefined')pref='#'+process.pid+': ';if(options.log.date)pref=pref+Io.date()+' ';else if(options.log.time)pref=pref+Io.time()+' ';else if(options.log.Time)pref=pref+Io.Time()+' ';if(msg[0]=='[')(Aios.printAsync||Aios.print)(pref+msg);else(Aios.printAsync||Aios.print)('[AIOS'+pref+'] '+msg);}
var eval0=eval;var aios0={abs:Math.abs,add:function(a,b){var res,i;if(Comp.obj.isNumber(a)&&Comp.obj.isNumber(b))return a+b;if(Comp.obj.isArray(a)&&Comp.obj.isArray(b)){if(a.length!=b.length)return none;res=Comp.array.copy(a);for(i in a){res[i]=aios0.add(a[i],b[i]);}
return res;}
if(Comp.obj.isArray(a)&&Comp.obj.isFunction(b)){res=Comp.array.copy(a);for(i in a){res[i]=aios0.add(a[i],b.call(current.process.agent,a[i]));}
return res;}
if(Comp.obj.isObj(a)&&Comp.obj.isObj(b)){res={};for(i in a){res[i]=aios0.add(a[i],b[i]);}
return res;}
return none;},angle:function(p1,p2){var angle,v1,v2;if(Comp.obj.isArray(p1))v1=p1;else if(Comp.obj.isObj(p1))v1=[p1.x,p1.y];if(Comp.obj.isArray(p2))v2=p2;else if(Comp.obj.isObj(p2))v2=[p2.x,p2.y];if(p2==undefined){v2=v1;v1=[0,0]};angle=Math.atan2(v2[1]-v1[1],v2[0]-v1[0]);return 180*angle/Math.PI;},array:function(cols,init){if(init==undefined)init=0;var row=[];for(var j=0;j<cols;j++)row.push(typeof init=='function'?init(j):init);return row;},assign:function(src,dst){for(var p in src)dst[p]=src[p]
return dst;},Capability:Sec.Capability,clock:clock,concat:function(a,b,unique){var res,i;if(Comp.obj.isArray(a)&&Comp.obj.isArray(b)){if(!unique)return a.concat(b);res=a.slice();for(var i in b){if(res.indexOf(b[i])==-1)res.push(b[i]);}
return res;}else if(Comp.obj.isObj(a)&&Comp.obj.isObj(b)){res={};for(i in a){res[i]=a[i];}
for(i in b){res[i]=b[i];}
return res;}else if(Comp.obj.isString(a)&&Comp.obj.isString(b)){return a+b;}else
return undefined;},contains:function(o,e){if(Comp.obj.isArray(o))
return Comp.array.contains(o,e);else if(Comp.obj.isObj(o)&&(Comp.obj.isString(e)||Comp.obj.isNumber(e)))
return o[e]!=undefined;else if(Comp.obj.isString(o)&&Comp.obj.isString(e))
return o.indexOf(e)!=-1},copy:function(o){var _o,p;if(Comp.obj.isArray(o)){if(typeof o[0]!='object')return o.slice();else return o.map(function(e){if(typeof e=='object')return aios0.copy(e);else return e;});}else if(Comp.obj.isObject(o)){_o={};for(p in o)_o[p]=(typeof o[p]=='object'?aios0.copy(o[p]):o[p]);return _o;}
else if(Comp.obj.isString(o))
return o.slice();else return o;},delta:function(o1,o2){var res;if(Comp.obj.isArray(o1)&&Comp.obj.isArray(o2)){if(o1.length!=o2.length)return;res=[];for(var i in o1)res[i]=o1[i]-o2[i];}else if(Comp.obj.isObject(o1)&&Comp.obj.isObject(o2)){res={};for(var p in o1)res[p]=o1[p]-o2[p];}
return res;},distance:function(p1,p2){var y=0;if(p2)for(var p in p1)if(typeof p1[p]=='number'&&typeof p2[p]=='number')y+=Math.pow(p1[p]-p2[p],2);else for(var p in p1)if(typeof p1[p]=='number')y+=Math.pow(p1[p],2);return Math.sqrt(y)},div:div,dump:function(x){if(x=='res')x=Comp.obj.copy(current.process.resources);if(x=='?')x=this;logAgent(util.inspect(x));},empty:function(o){if(Comp.obj.isArray(o)||Comp.obj.isString(o))return o.length==0;else if(Comp.obj.isObj(o))return Comp.obj.isEmpty(o);else return false;},equal:function(a,b){var i;if(Comp.obj.isNumber(a)&&Comp.obj.isNumber(b))return a==b;else if(Comp.obj.isArray(a)&&Comp.obj.isArray(b)){if(a.length!=b.length)return false;for(i in a){if(!aios0.equal(a[i],b[i]))return false;}
return true;}
else if(Comp.obj.isObj(a)&&Comp.obj.isObj(b)){for(i in a){if(!aios0.equal(a[i],b[i]))return false;}
return true;}
else if(Comp.obj.isString(a)&&Comp.obj.isString(b))
return(a.length==b.length&&a==b)
return false;},filter:function(a,f){var element,res=[],len,len2,i,j,found;if(Comp.obj.isArray(a)&&Comp.obj.isFunction(f)){res=[];len=a.length;for(i=0;i<len;i++){element=a[i];if(f.call(current.process.agent,element,i))res.push(element);}
return res;}else if(Comp.obj.isArray(a)&&Comp.obj.isArray(f)){res=[];len=a.length;len2=f.length;for(i=0;i<len;i++){element=a[i];found=false;for(j=0;j<len2;j++)if(element==f[j]){found=true;break;}
if(!found)res.push(element);}
return res;}else return undefined;},flatten:function(a,level){if(Comp.obj.isMatrix(a)){return a.reduce(function(flat,toFlatten){return flat.concat(Array.isArray(toFlatten)&&level>1?aios0.flatten(toFlatten,level-1):toFlatten);},[]);}else if(Comp.obj.isObj(a)){function flo(o){var o2={},o3;for(var p in o){if(typeof o[p]=='object'){o3=flo(o[p]);for(var p2 in o3){o2[p+p2]=o3[p2];}}else o2[p]=o[p];}
return o2;}
return flo(a);}
return a;},head:function(a){if(Comp.obj.isArray(a))
return Comp.array.head(a);else return undefined;},id:aidgen,info:function(kind){switch(kind){case'node':return{id:current.node.id,position:current.node.position,location:current.node.location,type:current.node.type,};case'version':return options.version;case'host':return{type:global.TARGET};}},int:int,isin:function(o,v){var p;if(Comp.obj.isArray(o)){for(p in o)if(aios0.equal(o[p],v))return true;return false;}else if(Comp.obj.isObj(o)){for(p in o)if(aios0.equal(o[p],v))return true;return false;}else if(Comp.obj.isString(o)){return o.indexOf(v)!=-1}},iter:function(obj,fun){var p;if(Comp.obj.isArray(obj))
for(p in obj)fun.call(current.process.agent,obj[p],Number(p));else
for(p in obj)fun.call(current.process.agent,obj[p],p)},keys:Object.keys,kill:function(){kill(current.process.agent.id)},last:function(o){if(o==undefined)return;else if(Comp.obj.isArray(o)||Comp.obj.isString(o))
return o[o.length-1];else if(Comp.obj.isObj(o)){var p,l;for(p in o)if(o[p]!=undefined)l=o[p];return l;}},length:function(o){if(o==undefined)return 0;else if(Comp.obj.isObj(o)){var p,l=0;for(p in o)if(o[p]!=undefined)l++;return l;}else return o.length},log:function(){logAgent.apply(_,arguments)},map:function(a,f){var res,i,p;if(Comp.obj.isArray(a)&&Comp.obj.isFunction(f)){res=[];for(i in a){v=f.call(current.process.agent,a[i],i);if(v!=undefined)res.push(v);}
return res;}else if(Comp.obj.isObject(a)&&Comp.obj.isFunction(f)){res={};for(p in a){v=f.call(current.process.agent,a[p],p);if(v!=undefined)res[p]=v;}
return res;}else return undefined;},matrix:function(x,y,init){var row=[];var mat=[];for(var j=0;j<y;j++){row=[];for(var i=0;i<x;i++)
row.push(init||0)
mat.push(row)}
return mat;},max:function(a,b){if(Comp.obj.isArray(a)){var f=function(x){return x},v,vi;if(Comp.obj.isFunction(b))f=b;Comp.array.iter(a,function(a0,i){a0=f(a0);if(v==undefined||a0>v){v=a0;vi=i};});if(vi!=undefined)return a[vi];}else return Math.max(a,b);},me:function(){return current.process.agent.id;},min:function(a,b){if(Comp.obj.isArray(a)){var f=function(x){return x},v,vi;if(Comp.obj.isFunction(b))f=b;Comp.array.iter(a,function(a0,i){a0=f(a0);if(v==undefined||a0<v){v=a0;vi=i};});if(vi!=undefined)return a[vi];}else return Math.min(a,b);},myClass:function(){return current.process.agent.ac;},myLevel:function(){return current.process.level;},myNode:function(){return current.node.id;},myParent:function(){return current.process.agent.parent;},myPosition:function(){return current.node.location||current.node.position;},neg:function(v){var p;if(Comp.obj.isNumber(v))return-v;if(Comp.obj.isArray(v))return v.map(function(e){return aios0.neg(e)});if(Comp.obj.isObj(v)){var o=v,_o={};for(p in o)_o[p]=typeof o[p]=='number'?-o[p]:o[p];return _o;}},negotiate:function(res,val,cap){return negotiate(0,res,val,cap)},next:function(){},object:function(str){var myobj={data:null};with({myobj:myobj,str:str}){myobj.data=eval0('var _o='+str+';_o')};return myobj.data;},pluck:function(table,column){var res=[];for(var i in table){res.push(table[i][column]);}
return res;},privilege:function(){return 0},Port:Sec.Port,Private:Sec.Private,random:function(a,b,frac){var r,n,p,i,keys,k;if(Comp.obj.isArray(a)){n=a.length;if(n>0)
return a[Comp.random.int(n)];else
return none;}else if(Comp.obj.isObj(a)){keys=Object.keys(a);n=keys.length;if(n>0)
return a[keys[Comp.random.int(n)]];else
return none;}else if(b==undefined){b=a;a=0};if(!frac||frac==1)
return Comp.random.interval(a,b);else{r=Comp.random.range(a,b);return((r/frac)|0)*frac;}},reduce:function(a,f){if(Comp.obj.isArray(a)){return a.reduce(function(a,b){return current.process?f.call(current.process.agent,a,b):f(a,b);});}},reverse:function(a){if(Comp.obj.isArray(a))
return a.slice().reverse();else if(Comp.obj.isString(a))
return a.split("").reverse().join("")},sleep:Sig.agent.sleep,sort:function(a,f){if(Comp.obj.isArray(a)&&Comp.obj.isFunction(f)){return Comp.array.sort(a,function(x,y){return f.call(current.process.agent,x,y);});}else return undefined;},sum:function(o,f){if(Comp.obj.isArray(o))return Comp.array.sum(o,f);else if(Comp.obj.isObject(o)){var s=0,p;if(!f)f=function(x){return x};for(p in o)s+=f(o[p]);return s;}},string:function(o){if(Comp.obj.isString(o))return o;else return o.toString()},tail:function(a){if(Comp.obj.isArray(a))
return Comp.array.tail(a);else return undefined;},time:function(){return time()-current.world.lag},without:function(a,b){if(Comp.obj.isArray(a)&&(Comp.obj.isArray(b)))
return a.filter(function(v){return!aios0.contains(b,v);});else if(Comp.obj.isArray(a))
return a.filter(function(v){return!aios0.equal(b,v);});},zero:function(a){var i;if(Comp.obj.isNumber(a))return a==0;if(Comp.obj.isArray(a)){for(i in a){if(!aios0.zero(a[i]))return false;}
return true;}
if(Comp.obj.isObj(a)){for(i in a){if(!aios0.zero(a[i]))return false;}
return true;}
return false;},Vector:function(x,y,z){var o={};if(x!=_)o['x']=x;if(y!=_)o['y']=y;if(z!=_)o['z']=z;return o},B:B,CP:CP,I:I,L:L,RT:RT,Math:Math}
var aios1={abs:aios0.abs,act:Conf.agent.act,add:aios0.add,angle:aios0.angle,alt:Ts.agent.alt,array:aios0.array,assign:aios0.assign,broadcast:Sig.agent.broadcast,Capability:Sec.Capability,clock:clock,collect:Ts.agent.collect,concat:aios0.concat,contains:aios0.contains,copy:aios0.copy,copyto:Ts.agent.copyto,create:function(ac,args,level){if(level==undefined||level>1)level=1;if(args==undefined)args={};var process=none,code;if(!Comp.obj.isArray(args)&&!Comp.obj.isObject(args)){current.error='Invalid argument: Agent argument is neither array nor object';throw'CREATE';};current.process.resources.agents++;if(typeof ac=='object'){process=Code.createFromOn(current.node,current.process,ac,level);}else if(current.world.classes[ac]&&current.world.classes[ac][level])
process=Code.createOn(current.node,current.world.classes[ac][level],args,level,ac);else if(current.process.agent.subclass&&current.process.agent.subclass[ac]){process=Code.createOn(current.node,current.process.agent.subclass[ac],args,level,ac);}else{current.error='Invalid argument: Unknown agent class '+ac;throw'CREATE';}
if(process){if(current.process!=none&&process.gid==none){process.gid=current.process.pid;if(!process.agent.parent)
process.agent.parent=current.process.agent.id;}
return process.agent.id;}else return none;},delta:aios0.delta,distance:aios0.distance,div:aios0.div,dump:aios0.dump,empty:aios0.empty,evaluate:Ts.agent.evaluate,equal:aios0.equal,exists:Ts.agent.exists,Export:function(name,code){current.node.export(name,code)},filter:aios0.filter,flatten:aios0.flatten,fork:function(parameter){var process=current.process.fork(parameter,undefined,options.fastcopy);return process.agent.id},head:aios0.head,id:aidgen,Import:function(name){return current.node.import(name)},info:aios0.info,inp:Ts.agent.inp,int:aios0.int,isin:aios0.isin,iter:aios0.iter,keys:Object.keys,kill:function(aid){if(aid==undefined)kill(current.process.agent.id);else kill(aid)},last:aios0.last,length:aios0.length,link:function(dir){return current.world.connected(dir,current.node)},listen:Ts.agent.listen,log:aios0.log,me:aios0.me,mark:Ts.agent.mark,map:aios0.map,max:aios0.max,matrix:aios0.matrix,moveto:Mobi.agent.move,min:aios0.min,myClass:aios0.myClass,myNode:aios0.myNode,myLevel:aios0.myLevel,myParent:aios0.myParent,myPosition:aios0.myPosition,neg:aios0.neg,negotiate:function(res,val,cap){return negotiate(1,res,val,cap)},object:aios0.object,opposite:Mobi.agent.opposite,out:Ts.agent.out,pluck:aios0.pluck,Port:Sec.Port,position:function(){return current.node.position},Private:Sec.Private,privilege:function(){return 1},random:aios0.random,rd:Ts.agent.rd,reduce:aios0.reduce,reverse:aios0.reverse,rm:Ts.agent.rm,security:Sec,send:Sig.agent.send,sendto:Sig.agent.sendto,sleep:Sig.agent.sleep,sort:aios0.sort,store:Ts.agent.store,string:aios0.string,sum:aios0.sum,tail:aios0.tail,test:Ts.agent.exists,time:aios0.time,timer:Sig.agent.timer,trans:Conf.agent.trans,try_alt:Ts.agent.try.alt,try_inp:Ts.agent.try.inp,try_rd:Ts.agent.try.rd,ts:Ts.agent.ts,wakeup:Sig.agent.wakeup,without:aios0.without,zero:aios0.zero,B:B,CP:CP,I:I,L:L,RT:RT,Vector:aios0.Vector,DIR:Mobi.agent.DIR,Math:Math};var aios2={abs:aios0.abs,add:aios0.add,act:Conf.agent.act,angle:aios0.angle,alt:Ts.agent.alt,array:aios0.array,assign:aios0.assign,broadcast:Sig.agent.broadcast,Capability:Sec.Capability,clock:clock,collect:Ts.agent.collect,concat:aios0.concat,contains:aios0.contains,copy:aios0.copy,copyto:Ts.agent.copyto,create:function(ac,args,level){var process=none;if(level==undefined||level>2)level=2;if(args==undefined)args={};if(!Comp.obj.isArray(args)&&!Comp.obj.isObject(args)){current.error='Invalid argument: Agent arguments is neither array nor object';throw'CREATE';};current.process.resources.agents++;if(typeof ac=='object'){process=Code.createFromOn(current.node,current.process,ac,level);}else if(current.world.classes[ac]&&current.world.classes[ac][level])
process=Code.createOn(current.node,current.world.classes[ac][level],args,level,ac);else if(current.process.agent.subclass&&current.process.agent.subclass[ac]){process=Code.createOn(current.node,current.process.agent.subclass[ac],args,level,ac);}else{current.error='Invalid argument: Unknown agent class '+ac;throw'CREATE';}
if(process){process.agent.ac=ac;if(current.process!=none&&process.gid==none){process.gid=current.process.pid;if(process.agent.parent==_||process.agent.parent==none)
process.agent.parent=current.process.agent.id;}
return process.agent.id;}else return none;},delta:aios0.delta,distance:aios0.distance,div:aios0.div,dump:aios0.dump,empty:aios0.empty,evaluate:Ts.agent.evaluate,equal:aios0.equal,exists:Ts.agent.exists,Export:function(name,code){current.node.export(name,code)},filter:aios0.filter,flatten:aios0.flatten,fork:function(parameter){var process=current.process.fork(parameter);return process.agent.id},head:aios0.head,id:aidgen,Import:function(name){return current.node.import(name)},info:aios0.info,inp:Ts.agent.inp,int:aios0.int,isin:aios0.isin,iter:aios0.iter,keys:Object.keys,kill:function(aid){if(aid==undefined)kill(current.process.agent.id);else kill(aid)},last:aios0.last,length:aios0.length,link:function(dir){return current.world.connected(dir,current.node)},listen:Ts.agent.listen,log:aios0.log,max:aios0.max,me:aios0.me,min:aios0.min,myClass:aios0.myClass,myNode:aios0.myNode,myLevel:aios0.myLevel,myParent:aios0.myParent,myPosition:aios0.myPosition,mark:Ts.agent.mark,map:aios0.map,matrix:aios0.matrix,moveto:Mobi.agent.move,neg:aios0.neg,negotiate:function(res,val,cap){return negotiate(2,res,val,cap)},object:aios0.object,opposite:Mobi.agent.opposite,out:Ts.agent.out,random:aios0.random,reduce:aios0.reduce,rd:Ts.agent.rd,reverse:aios0.reverse,rm:Ts.agent.rm,pluck:aios0.pluck,Port:Sec.Port,position:function(){return current.node.position},Private:Sec.Private,privilege:function(){return 2},security:Sec,send:Sig.agent.send,sendto:Sig.agent.sendto,sleep:Sig.agent.sleep,sort:aios0.sort,store:Ts.agent.store,string:aios0.string,sum:aios0.sum,tail:aios0.tail,test:Ts.agent.exists,time:aios0.time,timer:Sig.agent.timer,trans:Conf.agent.trans,try_alt:Ts.agent.try.alt,try_inp:Ts.agent.try.inp,try_rd:Ts.agent.try.rd,ts:Ts.agent.ts,wakeup:Sig.agent.wakeup,without:aios0.without,zero:aios0.zero,B:B,CP:CP,I:I,L:L,RT:RT,Vector:aios0.Vector,DIR:Mobi.agent.DIR,Math:Math,};var aios3={abs:aios0.abs,act:Conf.agent.act,add:aios0.add,angle:aios0.angle,alt:Ts.agent.alt,array:aios0.array,assign:aios0.assign,broadcast:Sig.agent.broadcast,Capability:Sec.Capability,clock:clock,collect:Ts.agent.collect,connectTo:function(dir,options){var node=current.node,world=current.world;if(!dir||!dir.tag)throw('CONNECT');world.connectTo(dir,node,options);},concat:aios0.concat,contains:aios0.contains,copy:aios0.copy,copyto:Ts.agent.copyto,create:function(ac,args,level){var process=none;if(level==undefined)level=3;if(args==undefined)args={};if(!Comp.obj.isArray(args)&&!Comp.obj.isObject(args)){current.error='Invalid argument: Agent arguments is neither array nor object';throw'CREATE';};current.process.resources.agents++;if(typeof ac=='object'){process=Code.createFromOn(current.node,current.process,ac,level);}else if(current.world.classes[ac]&&current.world.classes[ac][level])
process=Code.createOn(current.node,current.world.classes[ac][level],args,level,ac);else if(current.process.agent.subclass&&current.process.agent.subclass[ac]){process=Code.createOn(current.node,current.process.agent.subclass[ac],args,level,ac);}else{current.error='Invalid argument: Unknown agent class '+ac;throw'CREATE';}
if(process){process.agent.ac=ac;if(current.process!=none&&process.gid==none){process.gid=current.process.pid;if(process.agent.parent==_||process.agent.parent==none)
process.agent.parent=current.process.agent.id;}
return process.agent.id;}else return none;},delta:aios0.delta,distance:aios0.distance,div:aios0.div,dump:aios0.dump,empty:aios0.empty,equal:aios0.equal,evaluate:Ts.agent.evaluate,exists:Ts.agent.exists,Export:aios2.Export,filter:aios0.filter,flatten:aios0.flatten,fork:aios2.fork,head:aios0.head,id:aidgen,Import:aios2.Import,info:aios0.info,inp:Ts.agent.inp,int:aios0.int,isin:aios0.isin,iter:aios0.iter,keys:Object.keys,kill:aios2.kill,last:aios0.last,length:aios0.length,link:aios2.link,listen:Ts.agent.listen,log:aios0.log,max:aios0.max,me:aios0.me,min:aios0.min,myClass:aios0.myClass,myLevel:aios0.myLevel,myNode:aios0.myNode,myParent:aios0.myParent,myPosition:aios0.myPosition,mark:Ts.agent.mark,map:aios0.map,matrix:aios0.matrix,moveto:function(){current.error='ENOTSUPPORTED';throw'MOVE';},neg:aios0.neg,negotiate:function(res,val,cap){return negotiate(3,res,val,cap)},object:aios0.object,opposite:Mobi.agent.opposite,out:Ts.agent.out,pluck:aios0.pluck,Port:Sec.Port,position:function(){return current.node.position},Private:Sec.Private,privilege:function(){return 3},reduce:aios0.reduce,random:aios0.random,rd:Ts.agent.rd,reverse:aios0.reverse,rm:Ts.agent.rm,send:Sig.agent.send,sendto:Sig.agent.sendto,sleep:aios0.sleep,sort:aios0.sort,store:Ts.agent.store,string:aios0.string,sum:aios0.sum,tail:aios0.tail,test:Ts.agent.exists,time:aios0.time,timer:Sig.agent.timer,trans:Conf.agent.trans,try_alt:Ts.agent.try.alt,try_inp:Ts.agent.try.inp,try_rd:Ts.agent.try.rd,ts:Ts.agent.ts,wakeup:Sig.agent.wakeup,without:aios0.without,zero:aios0.zero,B:B,CP:CP,I:I,L:L,RT:RT,Vector:aios0.Vector,DIR:Mobi.agent.DIR,Math:Math,IOB:function(block){var proc=current.process;setImmediate(function(){var index=0;function next(to){var _proc=current.process,_node=current.node;if(to==none){proc.mask.next=undefined;proc.wakeup();return;}
index=index+to;try{current.process=proc;current.node=proc.node;block[index].call(proc.agent);}catch(e){logAgent('Caught IOB error: '+e);}
current.process=_proc;current.node=_node;}
proc.mask.next=next;next(0);});proc.suspend();}};var aios=aios1;function B(block){if(current.process.schedule.length==0)
current.process.schedule=block;else
current.process.schedule=Comp.array.concat(block,current.process.schedule);}
function CB(process,cb,args){if(args)
Comp.array.push(process.schedule,function(){cb.apply(this,args)});else
Comp.array.push(process.schedule,cb);}
function CP(){if(current.process.runtime&&(current.process.runtime+current.world.lag-Date.now())<0)throw"SCHEDULE";return true;}
function RT(e){if(['WATCHDOG','SCHEDULE'].indexOf(e.toString())!=-1)throw(e);}
function I(obj,next,block,finalize){var index=0;var length=obj.length;var iterator=[function(){next(obj[index]);if(index<length){B(block.slice());index++;}},function(){if(index<length)B(iterator.slice());else if(finalize)finalize.call(this);}];B(iterator.slice());}
function L(init,cond,next,block,finalize){var loop=[function(){if(cond.call(this))B(block.slice());},next,function(){if(cond.call(this))B(loop.slice());}];B(loop.slice());B([init]);}
function aidgen(_options){return Name.generate(_options||options.nameopts);}
function config(settings){for(var p in settings){switch(p){case'iterations':iterations=settings[p];break;case'fastcopy':options.fastcopy=settings[p];break;case'verbose':options.verbose=settings[p];break;case'log+':options.log[settings[p]]=true;break;case'log-':options.log[settings[p]]=false;break;case'log':for(var l in settings[p])options.log[l]=settings[p][l];break;case'nolimits':if(settings[p])
Aios.watchdog=undefined,options.nolimits=true,Aios.Code.inject.cp=undefined,Aios.Code.inject.rt=undefined;break;case'nowatch':if(settings[p])
Aios.watchdog=undefined,Aios.Code.inject.cp=undefined,Aios.Code.inject.rt=undefined;break;case'checkpoint':if(settings[p])
Aios.watchdog=undefined,Aios.Code.inject.cp='CP',Aios.Code.inject.rt='RT';break;case'security':for(var q in settings[p]){var port=Sec.Port.ofString(q),random=Sec.Port.ofString(settings[p][q]);options.security[port]=random;}
break;case'print':Aios.print=settings[p];break;case'printAgent':Aios.printAgent=settings[p];break;case'printAsync':Aios.printAsync=settings[p];break;case'LEVEL':options.LEVEL=settings[p];break;case'LIFETIME':options.LIFETIME=settings[p];break;case'TIMESCHED':options.TIMESCHED=settings[p];break;case'TIMEPOOL':options.TIMEPOOL=settings[p];break;case'MEMPOOL':options.MEMPOOL=settings[p];break;case'TSPOOL':options.TSPOOL=settings[p];break;case'AGENTPOOL':options.AGENTPOOL=settings[p];break;case'MINCOST':options.MINCOST=settings[p];break;case'RUNTIME':options.RUNTIME=settings[p];break;case'IDLETIME':options.IDLETIME=settings[p];break;case'TSTMO':options.TSTMO=Aios.Ts.options.timeout=settings[p];break;case'time':time=settings[p];Aios.time=aios0.time=aios1.time=aios2.time=aios3.time=time;Aios.CP=aios0.CP=aios1.CP=aios2.CP=aios3.CP=function(){if(current.process.runtime&&(current.process.runtime+current.world.lag-time())<0)throw"SCHEDULE";return true;};break;}}}
function configGet(){return{LEVEL:options.LEVEL,LIFETIME:options.LIFETIME,TIMESCHED:options.TIMESCHED,TIMEPOOL:options.TIMEPOOL,TSPOOL:options.TSPOOL,AGENTPOOL:options.AGENTPOOL,MEMPOOL:options.MEMPOOL,MINCOST:options.MINCOST,RUNTIME:options.RUNTIME,IDLETIME:options.IDLETIME,TSTMO:Aios.Ts.options.timeout,security:Object.keys(options.security).map(function(port){return{port:Sec.Port.toString(port),random:Sec.Port.toString(options.security[port])}}),checkpoint:{cp:Aios.Code.inject.cp,rt:Aios.Code.inject.rt,watchdog:Aios.watchdog?true:fals},nolimits:options.nolimits,iterations:iterations,fastcopy:options.fastcopy,verbose:options.verbose,log:options.log,}}
function dump(e){var e=e||(new Error('dummy'));var stack=e.stack.replace(/^[^\(]+?[\n$]/gm,'').replace(/^\s+at\s+/gm,'').replace(/^Object.<anonymous>\s*\(/gm,'{anonymous}()@').split('\n');log(e);log('Stack Trace');log('--------------------------------');for(var i in stack){if(i>0){var line=stack[i];if(line.indexOf('Module.',0)>=0)break;log(line);}}
log('--------------------------------');};function emit(){if(events[arguments[0]])
events[arguments[0]](arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]);}
function errorLocation(process,err){try{var stack=err.stack.split('\n');for(var i in stack){var line=stack[i];if(line.indexOf('at act.')>=0||line.indexOf('at F.act.')>=0){return line.replace(/\([^\)]+\)/,'').replace(/\)/,'');}
else if(line.indexOf('at trans.')>=0||line.indexOf('at F.trans.')>=0){return line.replace(/\([^\)]+\)/,'').replace(/\)/,'');}}
return'';}catch(e){return'';}}
function exec_block_fun(next){var fun=next[0]||next,argn=next.length-1;switch(argn){case 0:case-1:fun();break;case 1:fun(next[1]);break;case 2:fun(next[1],next[2]);break;case 3:fun(next[1],next[2],next[3]);break;case 4:fun(next[1],next[2],next[3],next[4]);break;case 5:fun(next[1],next[2],next[3],next[4],next[5]);break;case 6:fun(next[1],next[2],next[3],next[4],next[5],next[6]);break;case 7:fun(next[1],next[2],next[3],next[4],next[5],next[6],next[7]);break;case 8:fun(next[1],next[2],next[3],next[4],next[5],next[6],next[7],next[8]);break;case 9:fun(next[1],next[2],next[3],next[4],next[5],next[6],next[7],next[8],next[9]);break;default:Io.err('Aios.exec_block_fun: more than 9 function arguments');}}
function fork(parameters){return current.process.fork(parameters);}
function kill(agent){var process;if(!agent){process=current.process;}else{process=current.node.processes.process(agent);}
if(options.debug.kill)console.log('Aios.kill',agent,process!=null);if(process){process.kill=true;current.node.unregister(process);return true;}else if(current.node.processes.gone[agent]){Sig.agent.send(agent,'PROC.KILL',9,current.process.agent.id);}else return false;}
function killOn(agent,node){var process;process=node.processes.process(agent);if(process){process.kill=true;node.unregister(process);};}
function lock(){Object.preventExtensions(global);}
function loop(services){var nexttime=scheduler(services);if(nexttime>0){if(options.verbose>3)log('[LOOP '+current.node.id+'] next schedule on '+nexttime);timer=setTimeout(function(){loop(services)},nexttime-time());}}
function min0(a,b){return a==0?b:(b==0?a:Comp.pervasives.min(a,b))};function handleException(process,exc,arg1,arg2,arg3,arg4){var agent=process.agent;if(Aios.watchdog&&Aios.watchdog.protect){try{Aios.watchdog.protect(function(){agent.on[exc].call(agent,arg1,arg2,arg3,arg4)})}catch(e){if(options.verbose)logAIOS('Agent '+agent.id+' ['+agent.ac+'] failed handling '+exc+'('+arg1+')');process.kill=true
return false;};}else
try{agent.on[exc].call(agent,arg1,arg2,arg3,arg4)}catch(e){if(options.verbose)logAIOS('Agent '+agent.id+' ['+agent.ac+'] failed handling '+exc+'('+arg1+')');process.kill=true
return false;}
return true;}
function negotiate(level,resource,value,cap){var obj,security=options.security;function checkRights(r){return(level>1||(cap&&security[cap.cap_port]&&Sec.Private.rights_check(cap.cap_priv,security[cap.cap_port],r)))}
switch(resource){case'LIFE':case'LIFETIME':if(!checkRights(Sec.Rights.NEG_LIFE))return false;current.process.resources.LIFE=value;break;case'CPU':case'TIMEPOOL':if(!checkRights(Sec.Rights.NEG_CPU))return false;current.process.resources.CPU=value;break;case'SCHED':case'SCHEDULE':case'TIMESCHED':if(!checkRights(Sec.Rights.NEG_SCHED))return false;current.process.resources.SCHED=value;break;case'MEM':case'MEMORY':case'MEMPOOL':if(!checkRights(Sec.Rights.NEG_RES))return false;current.process.resources.MEM=value;break;case'TS':case'TSPOOL':if(!checkRights(Sec.Rights.NEG_RES))return false;current.process.resources.TS=value;break;case'AGENT':case'AGENTPPOL':if(!checkRights(Sec.Rights.NEG_RES))return false;current.process.resources.AGENT=value;break;case'LEVEL':if(!checkRights(Sec.Rights.NEG_LEVEL))return false;switch(value){case 1:case 2:current.process.upgrade(value);break;}
break;case'?':obj=Comp.obj.copy(current.process.resources);Comp.obj.extend(obj,{SCHED:current.process.resources.SCHED||options.TIMESCHED,CPU:current.process.resources.CPU||options.TIMEPOOL,MEM:current.process.resources.MEM||options.MEMPOOL,TS:current.process.resources.TS||options.TSPOOL,AGENT:current.process.resources.AGENT||options.AGENTPOOL,});return obj;break;default:return false;}
return true;}
function off(event){events[event]=undefined;}
function on(event,fun){if(events[event]){var funorig=events[event];events[event]=function(){funorig.apply(this,arguments);fun.apply(this,arguments);};}else
events[event]=fun;}
function out(str){log(str)};function resource(r0){var r;if(!options.useproc)return 0;r=process.memoryUsage();if(r0==undefined)
return{r:r.rss-r.heapTotal,h:r.heapUsed};else return int((Math.max(0,r.rss-r.heapTotal-r0.r)+Math.max(0,r.heapUsed-r0.h))/1024);}
var SA={NOOP:0,BLOCK:1,NORES:2,SIG:3,TRANS:4,SCHED:5,ACT:6,print:function(op){switch(op){case SA.NOOP:return'NOOP';case SA.BLOCK:return'BLOCK';case SA.NORES:return'NORES';case SA.SIG:return'SIG';case SA.TRANS:return'TRANS';case SA.SCHED:return'SCHED';case SA.ACT:return'ACT';}}}
function schedule(process){var exec,sig,start,delta,next,_current,node=current.node,agent=process.agent,action='',op=SA.NOOP,handled,exception,curtime,r0;ticks++;assert((process.agent!=undefined&&process.id=='agent')||('Aios.schedule: not an agent process: '+process.id));curtime=time();if(!options.nolimits&&!process.kill&&(process.resources.start+(process.resources.LIFE||options.LIFETIME))<(curtime-current.world.lag))op=SA.NORES;else if(process.blocked||(process.suspended==true&&process.block.length==0&&process.signals.length==0)||process.dead==true||(agent.next==none&&process.signals.length==0&&process.schedule.length==0))op=SA.NOOP;else if(!process.blocked&&process.block.length>0)op=SA.BLOCK;else if(!options.nolimits&&(process.resources.consumed>(process.resources.CPU||options.TIMEPOOL)||process.resources.memory>(process.resources.MEM||options.MEMPOOL)))
op=SA.NORES;else if(process.priority<Proc.PRIO.HIGH&&process.signals.length>0)op=SA.SIG;else if(!process.suspended&&process.transition)op=SA.TRANS;else if(!process.suspended&&process.schedule.length>0)op=SA.SCHED;else if(!process.suspended)op=SA.ACT;else if(process.signals.length>0)op=SA.SIG;if(options.verbose>3)print('[SCH] '+time()+' '+process.agent.id+' : '+
SA.print(op)+' [susp='+process.suspended+',trans='+process.transition+',tmo='+process.timeout+']');if(op==SA.NOOP)return 0;start=curtime;if(Aios.watchdog)Aios.watchdog.start(process.resources.SCHED||options.TIMESCHED);else if(!options.nolimits)
process.runtime=start-current.world.lag+(process.resources.SCHED||options.TIMESCHED);if(!options.nolimits)
r0=resource();current.process=process;current.error=none;if(current.scheduler)_current=current.scheduler.SetCurrent(process);try{switch(op){case SA.BLOCK:schedule_block(process);break;case SA.NORES:throw'EOL';break;case SA.SIG:if(!process.suspended&&!process.transition)process.priority++;action='signal';sig=Comp.array.pop(process.signals);try{agent.on[sig[0]].call(agent,sig[1],sig[2],sig[3]);if(process.suspended&&process.transition)process.suspended=false;}catch(e){if(!agent.on[sig[0]])
logAIOS('Signal handler '+sig[0]+' in agent '+agent.id+' ['+agent.ac+'] not defined, ignoring signal.');else
logAIOS('Signal handler '+sig[0]+' in agent '+agent.id+' ['+agent.ac+'] failed: '+e+
(current.error?' / '+current.error:'')+', in: \n'+Code.print(agent.on[sig[0]])+
+errorLocation(process,e))
current.error=none;process.kill=true;};Aios.emit('signal+',process,node,sig[0],sig[1],sig[2]);break;case SA.TRANS:try{action='transition';if(!agent.trans[agent.next])throw"NOTDEFINED";next=(typeof agent.trans[agent.next]=='function')?agent.trans[agent.next].call(agent):agent.trans[agent.next];if(next){agent.next=next;process.suspended=false;process.transition=false;}else{process.suspended=true;}}catch(e){if(agent.trans[agent.next]==undefined)
logAIOS('Transition table entry '+agent.next+' not defined in agent '+agent.id+' ['+agent.ac+'].');else
logAIOS('Agent '+agent.id+' ['+agent.ac+'] in transition '+agent.next+' failed:\n'+e+(current.error?' / '+current.error:'')+
+errorLocation(process,e));process.kill=true;current.error=none;}
break;case SA.SCHED:action='block';exec=Comp.array.pop(process.schedule);Aios.watchdog&&Aios.watchdog.protect?Aios.watchdog.protect(exec.bind(agent)):exec.call(agent);if(!process.kill&&!process.suspended&&process.schedule.length==0){if(process.notransition){process.notransition=false;}else{next=(typeof agent.trans[agent.next]=='function')?agent.trans[agent.next].call(agent):agent.trans[agent.next];if(!next)process.suspend(0,true);else agent.next=next;}}
break;case SA.ACT:if(process.priority==Proc.PRIO.HIGH)process.priority--;action='activity';if(agent.next==none)throw'KILL';Aios.watchdog&&Aios.watchdog.protect?Aios.watchdog.protect(agent.act[agent.next].bind(agent)):agent.act[agent.next].call(agent);if(!process.kill&&!process.suspended&&process.schedule.length==0){action='transition';if(!agent.trans[agent.next])throw"NOTDEFINED";next=(typeof agent.trans[agent.next]=='function')?agent.trans[agent.next].call(agent):agent.trans[agent.next];if(!next)process.suspend(0,true);else agent.next=next;}
break;}}catch(e){if(Aios.watchdog)Aios.watchdog.stop();curtime=time()-current.world.lag;exception=true;switch(e){case'SCHEDULE':case'WATCHDOG':e='SCHEDULE';if(Aios.watchdog)Aios.watchdog.start(options.TIMESCHED/10);else process.runtime=curtime+options.TIMESCHED/10;handleException(process,'error',e,options.TIMESCHED,agent.next);break;case'EOL':if(Aios.watchdog)Aios.watchdog.start(options.TIMESCHED/10);else
process.runtime=curtime+options.TIMESCHED/10;if(process.resources.consumed>=(process.resources.CPU||options.TIMEPOOL)){handleException(process,'error','CPU',e,process.resources.consumed,agent.next);if(process.resources.consumed>=(process.resources.CPU||options.TIMEPOOL))
process.kill=true;}else if(process.resources.memory>=(process.resources.MEM||options.MEMPOOL)){handleException(process,'error','EOM',process.resources.memory,agent.next);if(process.resources.memory>=(process.resources.MEM||options.MEMPOOL))
process.kill=true;}else if(process.resources.tuples>=(process.resources.TS||options.TSPOOL)){handleException(process,'error','EOT',process.resources.memory,agent.next);if(process.resources.tuples>=(process.resources.TS||options.TSPOOL))
process.kill=true;}else if((process.resources.start+(process.resources.LIFE||options.LIFETIME))<curtime){handleException(process,'error','EOL',process.resources.memory,agent.next);if((process.resources.start+(process.resources.LIFE||options.LIFETIME))<curtime)
process.kill=true;}else{handleException(process,'error','EOR',0,agent.next);process.kill=true;}
break;case'KILL':if(Aios.watchdog)Aios.watchdog.start(options.TIMESCHED/10);else process.runtime=curtime+options.TIMESCHED/10;handleException(process,'exit');process.kill=true;break;case'NOTDEFINED':if(agent.act[agent.next]==undefined&&options.verbose)
logAIOS('Activity '+agent.next+' not defined in agent '+
agent.id+' ['+agent.ac+'].');else if(agent.trans[agent.next]==undefined&&options.verbose)
logAIOS('Transition table entry '+agent.next+' not defined in agent '+agent.id+' ['+agent.ac+'].');process.kill=true;current.error=none;break;default:handled=handleException(process,aiosExceptions.indexOf(e.toString())!=-1?e:'error',e,current.error,agent.next);if(!handled&&options.verbose)
logAIOS('Agent '+agent.id+' ['+agent.ac+'] in '+(action=='block'?'block in':action)+' '+
(action=='signal'?sig[0]:agent.next)+' failed: Error '+e+(current.error?('; '+current.error):'')+
(options.verbose>1?(', in code: \n'+(action=='activity'?Code.print(agent.act[agent.next]):(action=='transition'?Code.print(agent.trans[agent.next]):(agent.on&&sig&&agent.on[sig[0]])?Code.print(agent.on[sig[0]]):'none'))+
errorLocation(process,e)):''));if(options.verbose>2&&['CREATE','MOVE','SIGNAL'].indexOf(e)==-1)Io.printstack(e);if(!handled)process.kill=true;else{action='transition';if(!agent.trans[agent.next])throw"NOTDEFINED";next=(typeof agent.trans[agent.next]=='function')?agent.trans[agent.next].call(agent):agent.trans[agent.next];if(!next)process.suspend(0,true);else agent.next=next;}
current.error=none;}}
if(Aios.watchdog)Aios.watchdog.stop();else process.runtime=0;if(!options.nostats){delta=(time()-start)||options.MINCOST;process.resources.consumed+=delta;process.resources.memory+=resource(r0);current.node.stats.cpu+=delta;}
if(options.verbose&&exception&&process.kill)logAIOS('Killed agent '+agent.id);if(current.scheduler)current.scheduler.SetCurrent(_current);current.process=none;if(options.verbose>3)print(time()+' <- '+process.print());return 1;}
function schedule_block(process){var next;if(!process.blocked){next=process.block[0];process.block.splice(0,1);while(!Comp.array.empty(process.block)&&next.handler!=undefined){next=process.block[0];process.block.splice(0,1);}
if(next.handler==undefined){try{exec_block_fun(next)}catch(e){while(next.handler==undefined&&!Comp.array.empty(process.block)){next=process.block[0];process.block.splice(0,1);}
if(next.handler!=undefined){try{exec_block_fun([next.handler,e])}
catch(e){Io.out('Aios.schedule_block [Internal B], in agent context '+
process.agent.id+', got exception in exception handler: '+e);Io.out(Json.stringify(next).replace(/\\n/g,'\n'));};}else{logAIOS('Agent '+process.agent.id+' ['+process.agent.ac+'] in activity '+
process.agent.next+' failed:\n'+e+(current.error?' / '+current.error:', in: \n'+
Code.print(process.agent.act[process.agent.next]))+'');process.kill=true;current.error=none;}}}}}
var scheduled=0;function scheduler(services){var run=1,nexttime=0,n=0,curtime,process,env,node,pro,timeout=time()+options.RUNTIME;scheduled=0;while(run&&(iterations==0||n<iterations)&&time()<timeout){run=0;n++;if(services)services();nexttime=options.IDLETIME?Sig.agent.timeout(options.IDLETIME):0;for(env in current.world.nodes){node=current.world.nodes[env];if(!node)continue;current.node=node;curtime=time()-current.world.lag;if(node.timers.length>0){remove=false;Comp.array.iter(node.timers,function(timer,i){if(timer&&timer[1]<=curtime){var process=timer[0],agent=process.agent,suspended=process.suspended,timeout=process.timeout;process.signals.push([timer[2],timer[3],agent.id]);run+=schedule(process);curtime=time()-current.world.lag;if(timer[4]>0){timer[1]=curtime+timer[4];}else{remove=true;node.timers[i]=undefined;}
process.timeout=timeout;}else if(timer)nexttime=min0(nexttime,timer[1]);});if(remove)
node.timers=Comp.array.filter(node.timers,function(timer){return timer!=undefined;});}
curtime=time()-current.world.lag;node.service(curtime);for(pro in node.processes.table){if(node.processes.table[pro]){curtime=time()-current.world.lag;process=node.processes.table[pro];if(process.suspended&&process.timeout&&process.timeout<=curtime){process.wakeup();}
run+=schedule(process);if(node.processes.table[pro]&&node.processes.table[pro].kill)
node.unregister(node.processes.table[pro]);if(node.processes.table[pro]&&process.suspended&&process.timeout>0)
nexttime=min0(nexttime,process.timeout);}}}
scheduled+=run;}
if(scheduled>0)return-scheduled;else if(nexttime>0)return nexttime;else return 0;}
var time=function(){return Math.ceil(Date.now())};var Aios={aidgen:aidgen,aios:aios1,aios0:aios0,aios1:aios1,aios2:aios2,aios3:aios3,aiosEvents:aiosEvents,Amp:Amp,callback:undefined,clock:clock,collect:Ts.agent.collect,config:config,configGet:configGet,current:current,emit:emit,err:function(msg){if(options.verbose)log('Error: '+msg)},fork:fork,kill:kill,killOn:killOn,lock:lock,loop:loop,log:log,logAgent:logAgent,logAIOS:logAIOS,logAIOSasync:logAIOSasync,logAsync:logAsync,off:off,on:on,options:options,print:Io.out,printAgent:undefined,printAsync:undefined,schedule:schedule,scheduled:scheduled,scheduler:scheduler,ticks:function(v){if(v!=undefined)ticks=v;else return ticks},time:time,timeout:function(tmo){return tmo>0?Aios.time()-current.world.lag+tmo:0},Chan:Chan,Code:Code,Json:Json,Mobi:Mobi,Name:Name,Node:Node,Proc:Proc,Sec:Sec,Sig:Sig,Simu:Simu,Ts:Ts,World:World,CB:CB,CP:CP,RT:RT,B:B,DIR:Mobi.DIR,I:I,L:L,warn:function(msg){if(options.verbose>1)log('Warning: '+msg)},watchdog:undefined,version:options.version}
if(watchdog&&watchdog.start)Aios.watchdog=watchdog;if(watchdog&&watchdog.init)watchdog.init('WATCHDOG');if(watchdog&&watchdog.checkPoint){aios0.CP=watchdog.checkPoint;aios1.CP=watchdog.checkPoint;aios2.CP=watchdog.checkPoint;aios3.CP=watchdog.checkPoint;Aios.CP=watchdog.checkPoint;}
Conf.current(Aios);Code.current(Aios);Sig.current(Aios);Sec.current(Aios);Ts.current(Aios);Proc.current(Aios);Node.current(Aios);World.current(Aios);Mobi.current(Aios);if(Simu)Simu.current(Aios);Chan.current(Aios);Json.current(Aios);module.exports=Aios;};BundleModuleCode['jam/conf']=function(module,exports){var Json=Require('jam/jsonfn');var Comp=Require('com/compat');var current=none;var Aios=none;var act={add:function(act,code){if(typeof code=='function')current.process.agent.act[act]=code;else if(typeof code=='string'){with(current.process.mask){current.process.agent.act[act]=eval(code);}}
current.process.mask[act]=act;},delete:function(act){if(Comp.obj.isArray(act))return Comp.array.map(act,function(a){var f=current.process.agent.act[a];current.process.agent.act[a]=undefined;return f;});else{var f=current.process.agent.act[act];current.process.agent.act[act]=undefined;return f;}},update:function(act,code){if(typeof code=='function')current.process.agent.act[act]=code;else if(typeof code=='string')current.process.agent.act[act]=Json.parse(code,current.process.mask);}};var __eval=eval;function sandBoxCode(mask,code){var __code;with(mask){__code=__eval('__code='+code);}
return __code;}
var trans={add:function(from,cond,data){if(current.process.agent.trans[from]){function wrap(s){return s[0]=='"'||s[0]=="'"?s:'"'+s+'"'};var old=current.process.agent.trans[from];if(typeof old!='function')old='function () { return'+wrap(old)+'}';else old=old.toString();if(typeof cond!='function')cond='function () { return'+wrap(cond)+'}';else cond=cond.toString();if(data)data=JSON.stringify(data);else data='null';var merged='function () { var next = ('+cond+').call(this,'+data+'); if (next) return next; else return ('+old+').call(this) }';var code=sandBoxCode(current.process.mask,merged);current.process.agent.trans[from]=code;}else current.process.agent.trans[from]=cond;},delete:function(trans){if(Comp.obj.isArray(trans))Comp.array.iter(trans,function(t){var f=current.process.agent.trans[t];current.process.agent.trans[t]=undefined;return f});else{var f=current.process.agent.trans[trans];current.process.agent.trans[trans]=undefined;return f;}},update:function(from,cond){current.process.agent.trans[from]=cond;}}
module.exports={agent:{act:act,trans:trans},current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['jam/code']=function(module,exports){var options={debug:{},compactit:false,version:'1.12.1'}
var minify=Require('com/minify');var Esprima=Require('parser/esprima');try{var M=process.binding('minify');Function.prototype._toString=Function.prototype.toString;Function.prototype.toString=function(compact){return compact?M.minify(this._toString()):this._toString();}
options.minifier=true;options.minifyC=true;minify=M.minify;}catch(e){Function.prototype._toString=Function.prototype.toString;Function.prototype.toString=function(compact){return compact?minify(this._toString()):this._toString();}
options.minifier=true;};var Io=Require('com/io');var Json=Require('jam/jsonfn');var Comp=Require('com/compat');var sandbox=Require('jam/sandbox')();var current=none;var Aios=none;var util=Require('util');function _testac(p1,p2){this.x=p1;this.y=p2;this.z=0;this.act={init:function(){this.z=this.x;this.x++;}}}
var _testobj=new _testac(1,2);options.compactit=Json.stringify(_testobj).length>93;var inject={cp:undefined,rt:undefined};function construct(constructor,argArray){var inst=Object.create(constructor.prototype);constructor.apply(inst,argArray);return inst;}
function copyProcess(process){var _process,_agent,agent=process.agent,mask=process.mask;process.node.stats.fastcopy++;agent.process={};for(var p in process){switch(p){case'schedule':if(process.schedule.length>0)
agent.process[p]=process.schedule;break;case'blocked':if(agent.process.suspended==true)
agent.process[p]=true;break;case'gid':case'pid':break;case'back':case'dir':agent.process[p]=process[p];break;}}
if(Comp.obj.isEmpty(agent.process))agent['process']=undefined;agent['self']=undefined;_agent=Comp.obj.copy(agent);if(!_agent.process)
_process=Aios.Proc.Proc({mask:mask,agent:_agent});else{_process=Aios.Proc.Proc(agent.process);_process.init({timeout:0,schedule:[],blocked:false,mask:mask,agent:_agent});_agent['process']=undefined;}
agent['self']=agent;return _process;}
function className(f){var name=f.toString().match(/[\s]*function[\s]*([a-z0-9]+)[\s]*\(/);return name?name[1]:"unknown"}
function create(constructor,args,level,className){return createOn(current.node,constructor,args,level,className);}
function createOn(node,constructor,args,level,className){if(!constructor.fun&&!Comp.obj.isFunction(constructor)){Aios.err('Code.create: No valid constructor function specified.');return;}
var code,agent0,agent,process,_process;_process=current.process;current.process={timeout:0};if(level==undefined)level=Aios.options.LEVEL;try{if(!constructor.fun)
constructor=makeSandbox(constructor,level);if(!(args instanceof Array))args=[args];agent0=construct(constructor.fun,args);if(!agent0){Aios.err('Code.createOn ('+className+'): Agent constructor failed.');current.process=_process;return null;}
process=makeProcess(agent0,constructor.mask);process.resources.memory=constructor.size||0;current.process=_process;}catch(e){current.process=_process;Aios.err('Code.createOn ('+className+'): '+e);return;}
agent=process.agent;if(!Comp.obj.isArray(args)&&Comp.obj.isObject(args))
for(var p in args){if(Comp.obj.hasProperty(agent,p))agent[p]=args[p];}
if(!agent['next']||!agent['trans']||!agent['act']){Aios.err('Code.createOn: Missing next/trans/act attribute in agent constructor '+className);return none;}
process.level=level;agent['self']=agent;if(className)agent['ac']=className;node.register(process);node.stats.create++;return process;}
function createFromOn(node,_process,subclass,level){var code,process;code=forkCode(_process,subclass);process=toCode(code,level);process.agent.id=Aios.aidgen();process.init({gid:_process.pid});node.register(process);var agent_=process.agent;if(!subclass.next)try{agent_.next=(typeof agent_.trans[agent_.next]=='function')?agent_.trans[agent_.next].call(agent_):agent_.trans[agent_.next];}catch(e){process.kill=true;};return process;}
function createAndReturn(constructor,ac,args,level){if(!(args instanceof Array))args=[args];var process,agent,code=ofCode({agent:construct(constructor,args)},true);if(level==undefined)level=Aios.options.LEVEL;process=toCode(code,level);agent=process.agent;agent.id=Aios.aidgen();agent.ac=ac;return{code:ofCode(process,false),process:process};}
function forkCode(process,subclass){var code='',p;var agent,self;var agent;if(!subclass){agent=process.agent;self=agent.self;agent['process']=undefined;agent['self']=undefined;}else if(typeof subclass=='object'){var agent={act:{},trans:{},next:process.agent.next}
console.log(subclass)
for(p in subclass){var o=subclass[p];switch(p){case'act':if(Comp.obj.isArray(o)){for(var q in o){var v=o[q];if(process.agent.act[v])
agent.act[v]=process.agent.act[v];}}else if(Comp.obj.isObject(o)){for(var q in o){agent.act[q]=o[q];}}
break;case'trans':if(Comp.obj.isObject(o)){for(var q in o){agent.trans[q]=o[q];}}
break;case'on':agent.on={};if(Comp.obj.isArray(o)){for(var q in o){var v=o[q];if(process.agent.on[v])
agent.on[v]=process.agent.on[v];}}else if(Comp.obj.isObject(o)){for(var q in o){agent.on[q]=o[q];}}
break;case'var':if(Comp.obj.isArray(o)){for(var q in o){var v=o[q];agent[v]=process.agent[v];}}
break;default:agent[p]=o;break;}}
for(var p in agent.act){if(!agent.trans[p]&&process.agent.trans[p])
agent.trans[p]=process.agent.trans[p];}}else throw"forkCode: invalid subclass"
code=Aios.options.json?Json.stringify(agent):toString(agent);if(!subclass){agent.process=process;agent.self=self;}
if(inject.cp||inject.rt)
code=removeInjection(code);return code;}
function ofCode(process,clean){var code='',p;var agent=process.agent;agent.process={};for(var p in process){switch(p){case'schedule':if(process.schedule.length>0)
agent.process[p]=process.schedule;break;case'blocked':if(agent.process.suspended==true)
agent.process[p]=true;break;case'gid':case'pid':break;case'back':case'dir':agent.process[p]=process[p];break;}}
if(Comp.obj.isEmpty(agent.process))agent['process']=undefined;agent['self']=undefined;try{code=Aios.options.json?Json.stringify(agent):toString(agent);}catch(e){throw'Code.ofCode: Code-Text serialization failed ('+e.toString()+')';}
if(clean&&!options.compactit)return code;if(!clean&&(inject.cp||inject.rt))
code=removeInjection(code);if(options.compactit)code=minimize(code);return code;}
function ofObject(agent){var process;if(!agent.process)
process=Aios.Proc.Proc({mask:agent.mask,agent:agent});else{process=Aios.Proc.Proc(agent.process);process.init({timeout:0,schedule:[],blocked:false,mask:agent.mask,agent:agent});agent['process']=undefined;}
agent['mask']=undefined;process.node.stats.fastcopy++;return process;}
function _ofString(source,mask){var code;try{with(mask){eval('"use strict"; code = '+source);}}catch(e){console.log(e)};return code;}
function ofString(source,mask){var self={},temp;function evalCode(){var code;try{with(mask){eval('"use strict"; code = '+source);}}catch(e){console.log(e)};return code;}
temp=evalCode.call(self);self=Object.assign(self,temp);return self;}
function parseString(source,mask){var self={},temp;function evalCode(){var code;try{code=Json.parse(source,mask);}catch(e){console.log(e)};return code;}
temp=evalCode.call(self);self=Object.assign(self,temp);return self;}
function makeProcess(agent,mask){var process;if(mask)for(var p in agent.act){mask[p]=p;}
if(!agent.process)
process=Aios.Proc.Proc({mask:mask,agent:agent});else{process=Aios.Proc.Proc(agent.process);process.init({timeout:0,schedule:[],blocked:false,mask:mask,agent:agent});agent['process']=undefined;}
agent['self']=agent;return process;}
function makeSandbox(constructor,level,env){var _process,sac,aios;switch(level){case 0:aios=Aios.aios0;break;case 1:aios=Aios.aios1;break;case 2:aios=Aios.aios2;break;case 3:aios=Aios.aios3;break;default:aios=Aios.aios0;break;}
_process=current.process;current.process={timeout:0};sac=sandbox(constructor,aios,inject,env);current.process=_process;return sac;}
function minimize(code){return minify(code)}
function print(agent,compact){var process=agent.process;var self=agent.self;agent['process']=undefined;agent['self']=undefined;var text=Aios.options.json?Json.stringify(agent):toString(agent);agent.process=process;agent.self=self;if(!text)return'undefined';var regex4=/\\n/g;if(inject.cp||inject.rt)
text=removeInjection(text);if(compact&&options.compactit)
text=minimize(text);return text.replace(regex4,'\n');}
function removeInjection(text){if(inject.cp){var regex1=/CP\(\);/g;var regex2=/\(\(([^\)]+)\)\s&&\sCP\(\)\)/g;var regex3=/,CP\(\)/g;text=text.replace(regex1,"").replace(regex2,"($1)").replace(regex3,"");}
if(inject.rt){var regex4=/RT\(\);/g;text=text.replace(regex4,"");}
return text;}
function size(agent){var text='',p;var process=agent.process;var self=agent.self;agent['process']=undefined;agent['self']=undefined;text=Aios.options.json?Json.stringify(agent):toString(agent);agent.process=process;agent.self=self;if(inject.cp||inject.rt){text=removeInjection(text);}
return text.length;}
function test(what){switch(what){case'minify':if(minify.test)minify.test();break;}}
function toCode(text,level){var agent,process,p,aios,next;switch(level){case undefined:case 0:aios=Aios.aios0;break;case 1:aios=Aios.aios1;break;case 2:aios=Aios.aios2;break;case 3:aios=Aios.aios3;break;default:aios=Aios.aios0;break;}
if(inject.cp){var regex1=/while[\s]*\(([^\'")]+)\)/g;var regex2=/for[\s]*\(([^\)'"]+)\)/g;var regex3=/function([^\{'"]+)\{/g;text=text.replace(regex1,"while (($1) && CP())").replace(regex2,"for ($1,CP())").replace(regex3,"function $1{CP();");}
if(inject.rt){var regex4=/catch[\s]*\([\s]*([a-zA-Z0-9_]+)[\s]*\)[\s]*\{/g;text=text.replace(regex4,'catch ($1) {'+inject.rt+'($1);');}
var mask={current:undefined,require:undefined};for(p in this)
mask[p]=undefined;for(p in global)
mask[p]=undefined;for(p in aios){mask[p]=aios[p];}
var isjson=Comp.string.startsWith(text,'{"');try{agent=isjson?parseString(text,mask):ofString(text,mask);}
catch(e){if(Aios.options.verbose)Aios.log('Aios.code.toCode: '+e+(current.error?(',\nin: '+current.error):''));return null;}
if(!agent){var more;try{var ast=Esprima.parse('code='+text,{tolerant:true,loc:true});if(ast.errors&&ast.errors.length>0)console.log(ast.errors[0]);}catch(e){console.log(e);}
__LASTCODE=text;return Aios.log('Aios.code.toCode: Invalid agent code received (invalid source text?) See __LASTCODE');}
for(var p in agent.act){mask[p]=p;}
if(!agent.process)
process=Aios.Proc.Proc({mask:mask,agent:agent});else{process=Aios.Proc.Proc(agent.process);process.init({timeout:0,schedule:[],blocked:false,mask:mask,agent:agent});agent['process']=undefined;}
process.level=level;process.resources.memory=text.length;agent['self']=agent;return process;}
function toObject(process){var _process,_agent,agent=process.agent,mask=process.mask;agent.process={};for(var p in process){switch(p){case'schedule':if(process.schedule.length>0)
agent.process[p]=process.schedule;break;case'blocked':if(agent.process.suspended==true)
agent.process[p]=true;break;case'gid':case'pid':break;case'back':case'dir':agent.process[p]=process[p];break;}}
if(Comp.obj.isEmpty(agent.process))agent['process']=undefined;agent['self']=undefined;_agent=Comp.obj.copy(agent);_agent.mask=mask;agent['self']=agent;return _agent;}
function toString(o){var p,i,s='',sep;if(Comp.obj.isArray(o)){s='[';sep='';for(p in o){s=s+sep+toString(o[p]);sep=',';}
s+=']';}else if(o instanceof Buffer){s='[';sep='';for(i=0;i<o.length;i++){s=s+sep+toString(o[i]);sep=',';}
s+=']';}else if(typeof o=='object'){s='{';sep='';for(p in o){if(o[p]==undefined)continue;s=s+sep+"'"+p+"'"+':'+toString(o[p]);sep=',';}
s+='}';}else if(typeof o=='string')
s="'"+o.toString()+"'";else if(typeof o=='function')
s=o.toString(true);else if(o!=undefined)
s=o.toString();else s='undefined';return s;}
module.exports={className:className,copyProcess:copyProcess,create:create,createAndReturn:createAndReturn,createFromOn:createFromOn,createOn:createOn,forkCode:forkCode,ofCode:ofCode,ofObject:ofObject,ofString:ofString,inject:inject,Jsonf:Json,makeProcess:makeProcess,makeSandbox:makeSandbox,minimize:minimize,print:print,size:size,test:test,toCode:toCode,toObject:toObject,toString:toString,options:options,current:function(module){current=module.current;Aios=module;inject.cp=(Aios.watchdog&&!Aios.watchdog.checkPoint)?undefined:'CP';inject.rt=(Aios.watchdog&&Aios.watchdog.protect)?undefined:'RT';if(inject.cp||inject.rt)options.inject=inject;if(Aios.watchdog&&Aios.watchdog.protect)options.watchdog='native';else options.watchdog=false;}}};BundleModuleCode['com/minify']=function(module,exports){var EOF=null;var theA;var theB;var theLookahead=EOF;var theX=EOF;var theY=EOF;var theInbuf=null;var theOutbuf=null;var theInbufIndex=0;var theOutbufIndex=0;function isAlphanum(c)
{return((c>='a'&&c<='z')||(c>='0'&&c<='9')||(c>='A'&&c<='Z')||c=='_'||c=='$'||c=='\\'||c>String.fromCharCode(126));}
function get(){var c=theLookahead;theLookahead=EOF;if(c==EOF){c=theInbuf[theInbufIndex++];}
if(c>=' '||c=='\n'||c==EOF){return c;}
if(c=='\r'){return'\n';}
return' ';}
function put(c){theOutbuf+=c;}
function peek()
{theLookahead=get();return theLookahead;}
function error(msg){throw msg}
function next()
{var c=get();if(c=='/'){switch(peek()){case'/':for(;;){c=get();if(c<='\n'){break;}}
break;case'*':get();while(c!=' '){switch(get()){case'*':if(peek()=='/'){get();c=' ';}
break;case EOF:error("Unterminated comment.");}}
break;}}
theY=theX;theX=c;return c;}
function action(d)
{switch(d){case 1:put(theA);if((theY=='\n'||theY==' ')&&(theA=='+'||theA=='-'||theA=='*'||theA=='/')&&(theB=='+'||theB=='-'||theB=='*'||theB=='/')){put(theY);}
case 2:theA=theB;if(theA=='\''||theA=='"'||theA=='`'){for(;;){put(theA);theA=get();if(theA==theB){break;}
if(theA=='\\'){put(theA);theA=get();}
if(theA==EOF){error("Unterminated string literal.");}}}
case 3:theB=next();if(theB=='/'&&(theA=='('||theA==','||theA=='='||theA==':'||theA=='['||theA=='!'||theA=='&'||theA=='|'||theA=='?'||theA=='+'||theA=='-'||theA=='~'||theA=='*'||theA=='/'||theA=='{'||theA=='\n')){put(theA);if(theA=='/'||theA=='*'){put(' ');}
put(theB);for(;;){theA=get();if(theA=='['){for(;;){put(theA);theA=get();if(theA==']'){break;}
if(theA=='\\'){put(theA);theA=get();}
if(theA==EOF){error("Unterminated set in Regular Expression literal.");}}}else if(theA=='/'){switch(peek()){case'/':case'*':error("Unterminated set in Regular Expression literal.");break;case'\n':put(theA);theA='\n';}
break;}else if(theA=='\\'){put(theA);theA=get();}
if(theA==EOF){error("Unterminated Regular Expression literal.");}
put(theA);}
theB=next();}}}
function minify(text){theA=0;theB=0;theLookahead=EOF;theX=EOF;theY=EOF;theInbuf=text;theInbufIndex=0;theOutbuf='';if(peek()==0xEF){get();get();get();}
theA=get();action(3);while(theA!=EOF){switch(theA){case' ':action(isAlphanum(theB)?1:2);break;case'\n':switch(theB){case'{':case'[':case'(':case'+':case'-':case'!':case'~':action(1);break;case' ':action(3);break;default:action(isAlphanum(theB)?1:2);}
break;default:switch(theB){case' ':action(isAlphanum(theA)?1:3);break;case'\n':switch(theA){case'}':case']':case')':case'+':case'-':case'"':case'\'':case'`':action(1);break;default:action(isAlphanum(theA)?1:3);}
break;default:action(1);break;}}}
return theOutbuf;}
function minimize0(code){var regex4=/\/\*([\S\s]*?)\*\//g;var regex5=/([^\\}])\\n/g;var regex6=/\/\/[^\n]+/g;var regex7=/[ ]*([{},; ]|else)[ ]*\n[\n]*/g;var regex8=/([^\'"]+)|([\'"](?:[^\'"\\]|\\.)+[\'"])/g;var regex9=/ [ ]+/g;var regex10=/}\s+(?!else|finally|catch)([a-zA-Z_]+)/g;var regex11=/\)\s+([a-zA-Z_]+)/g;code=code.replace(regex4,"").replace(regex5,'$1\n').replace(regex5,'$1\n').replace(regex6,"").replace(regex7,"$1").replace(regex8,function($0,$1,$2){if($1){return $1.replace(regex9,' ').replace(regex10,'};$1').replace(regex11,')\n$1');}else{return $2;}});return code;}
function test(){var n=1E4;var text=minify.toString();var t0=Date.now()
for(var i=0;i<n;i++){minify(text);}
var t1=Date.now();console.log('minify: '+((t1-t0)/n/text.length*1000)+' us/char');var t0=Date.now()
for(var i=0;i<n;i++){minimize0(text);}
var t1=Date.now();console.log('minimize0: '+((t1-t0)/n/text.length*1000)+' us/char');try{var M=process.binding('minify');var t0=Date.now()
for(var i=0;i<n;i++){M.minify(text);}
var t1=Date.now();console.log('minifyC: '+((t1-t0)/n/text.length*1000)+' us/char');}catch(e){}}
minify.test=test;module.exports=minify;};BundleModuleCode['parser/esprima']=function(module,exports){(function(root,factory){'use strict';if(typeof define==='function'&&define.amd){define(['exports'],factory);}else if(typeof exports!=='undefined'){factory(exports);}else{factory((root.esprima={}));}}(this,function(exports){'use strict';var Token,TokenName,FnExprTokens,Syntax,PlaceHolders,Messages,Regex,source,strict,index,lineNumber,lineStart,hasLineTerminator,lastIndex,lastLineNumber,lastLineStart,startIndex,startLineNumber,startLineStart,scanning,length,lookahead,state,extra,isBindingElement,isAssignmentTarget,firstCoverInitializedNameError;Token={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8,RegularExpression:9,Template:10};TokenName={};TokenName[Token.BooleanLiteral]='Boolean';TokenName[Token.EOF]='<end>';TokenName[Token.Identifier]='Identifier';TokenName[Token.Keyword]='Keyword';TokenName[Token.NullLiteral]='Null';TokenName[Token.NumericLiteral]='Numeric';TokenName[Token.Punctuator]='Punctuator';TokenName[Token.StringLiteral]='String';TokenName[Token.RegularExpression]='RegularExpression';TokenName[Token.Template]='Template';FnExprTokens=['(','{','[','in','typeof','instanceof','new','return','case','delete','throw','void','=','+=','-=','*=','/=','%=','<<=','>>=','>>>=','&=','|=','^=',',','+','-','*','/','%','++','--','<<','>>','>>>','&','|','^','!','~','&&','||','?',':','===','==','>=','<=','<','>','!=','!=='];Syntax={AssignmentExpression:'AssignmentExpression',AssignmentPattern:'AssignmentPattern',ArrayExpression:'ArrayExpression',ArrayPattern:'ArrayPattern',ArrowFunctionExpression:'ArrowFunctionExpression',BlockStatement:'BlockStatement',BinaryExpression:'BinaryExpression',BreakStatement:'BreakStatement',CallExpression:'CallExpression',CatchClause:'CatchClause',ClassBody:'ClassBody',ClassDeclaration:'ClassDeclaration',ClassExpression:'ClassExpression',ConditionalExpression:'ConditionalExpression',ContinueStatement:'ContinueStatement',DoWhileStatement:'DoWhileStatement',DebuggerStatement:'DebuggerStatement',EmptyStatement:'EmptyStatement',ExportAllDeclaration:'ExportAllDeclaration',ExportDefaultDeclaration:'ExportDefaultDeclaration',ExportNamedDeclaration:'ExportNamedDeclaration',ExportSpecifier:'ExportSpecifier',ExpressionStatement:'ExpressionStatement',ForStatement:'ForStatement',ForOfStatement:'ForOfStatement',ForInStatement:'ForInStatement',FunctionDeclaration:'FunctionDeclaration',FunctionExpression:'FunctionExpression',Identifier:'Identifier',IfStatement:'IfStatement',ImportDeclaration:'ImportDeclaration',ImportDefaultSpecifier:'ImportDefaultSpecifier',ImportNamespaceSpecifier:'ImportNamespaceSpecifier',ImportSpecifier:'ImportSpecifier',Literal:'Literal',LabeledStatement:'LabeledStatement',LogicalExpression:'LogicalExpression',MemberExpression:'MemberExpression',MetaProperty:'MetaProperty',MethodDefinition:'MethodDefinition',NewExpression:'NewExpression',ObjectExpression:'ObjectExpression',ObjectPattern:'ObjectPattern',Program:'Program',Property:'Property',RestElement:'RestElement',ReturnStatement:'ReturnStatement',SequenceExpression:'SequenceExpression',SpreadElement:'SpreadElement',Super:'Super',SwitchCase:'SwitchCase',SwitchStatement:'SwitchStatement',TaggedTemplateExpression:'TaggedTemplateExpression',TemplateElement:'TemplateElement',TemplateLiteral:'TemplateLiteral',ThisExpression:'ThisExpression',ThrowStatement:'ThrowStatement',TryStatement:'TryStatement',UnaryExpression:'UnaryExpression',UpdateExpression:'UpdateExpression',VariableDeclaration:'VariableDeclaration',VariableDeclarator:'VariableDeclarator',WhileStatement:'WhileStatement',WithStatement:'WithStatement',YieldExpression:'YieldExpression'};PlaceHolders={ArrowParameterPlaceHolder:'ArrowParameterPlaceHolder'};Messages={UnexpectedToken:'Unexpected token %0',UnexpectedNumber:'Unexpected number',UnexpectedString:'Unexpected string',UnexpectedIdentifier:'Unexpected identifier',UnexpectedReserved:'Unexpected reserved word',UnexpectedTemplate:'Unexpected quasi %0',UnexpectedEOS:'Unexpected e
function isDecimalDigit(ch){return(ch>=0x30&&ch<=0x39);}
function isHexDigit(ch){return'0123456789abcdefABCDEF'.indexOf(ch)>=0;}
function isOctalDigit(ch){return'01234567'.indexOf(ch)>=0;}
function octalToDecimal(ch){var octal=(ch!=='0'),code='01234567'.indexOf(ch);if(index<length&&isOctalDigit(source[index])){octal=true;code=code*8+'01234567'.indexOf(source[index++]);if('0123'.indexOf(ch)>=0&&index<length&&isOctalDigit(source[index])){code=code*8+'01234567'.indexOf(source[index++]);}}
return{code:code,octal:octal};}
function isWhiteSpace(ch){return(ch===0x20)||(ch===0x09)||(ch===0x0B)||(ch===0x0C)||(ch===0xA0)||(ch>=0x1680&&[0x1680,0x180E,0x2000,0x2001,0x2002,0x2003,0x2004,0x2005,0x2006,0x2007,0x2008,0x2009,0x200A,0x202F,0x205F,0x3000,0xFEFF].indexOf(ch)>=0);}
function isLineTerminator(ch){return(ch===0x0A)||(ch===0x0D)||(ch===0x2028)||(ch===0x2029);}
function fromCodePoint(cp){return(cp<0x10000)?String.fromCharCode(cp):String.fromCharCode(0xD800+((cp-0x10000)>>10))+
String.fromCharCode(0xDC00+((cp-0x10000)&1023));}
function isIdentifierStart(ch){return(ch===0x24)||(ch===0x5F)||(ch>=0x41&&ch<=0x5A)||(ch>=0x61&&ch<=0x7A)||(ch===0x5C)||((ch>=0x80)&&Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));}
function isIdentifierPart(ch){return(ch===0x24)||(ch===0x5F)||(ch>=0x41&&ch<=0x5A)||(ch>=0x61&&ch<=0x7A)||(ch>=0x30&&ch<=0x39)||(ch===0x5C)||((ch>=0x80)&&Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));}
function isFutureReservedWord(id){switch(id){case'enum':case'export':case'import':case'super':return true;default:return false;}}
function isStrictModeReservedWord(id){switch(id){case'implements':case'interface':case'package':case'private':case'protected':case'public':case'static':case'yield':case'let':return true;default:return false;}}
function isRestrictedWord(id){return id==='eval'||id==='arguments';}
function isKeyword(id){switch(id.length){case 2:return(id==='if')||(id==='in')||(id==='do');case 3:return(id==='var')||(id==='for')||(id==='new')||(id==='try')||(id==='let');case 4:return(id==='this')||(id==='else')||(id==='case')||(id==='void')||(id==='with')||(id==='enum');case 5:return(id==='while')||(id==='break')||(id==='catch')||(id==='throw')||(id==='const')||(id==='yield')||(id==='class')||(id==='super');case 6:return(id==='return')||(id==='typeof')||(id==='delete')||(id==='switch')||(id==='export')||(id==='import');case 7:return(id==='default')||(id==='finally')||(id==='extends');case 8:return(id==='function')||(id==='continue')||(id==='debugger');case 10:return(id==='instanceof');default:return false;}}
function addComment(type,value,start,end,loc){var comment;assert(typeof start==='number','Comment must have valid position');state.lastCommentStart=start;comment={type:type,value:value};if(extra.range){comment.range=[start,end];}
if(extra.loc){comment.loc=loc;}
extra.comments.push(comment);if(extra.attachComment){extra.leadingComments.push(comment);extra.trailingComments.push(comment);}
if(extra.tokenize){comment.type=comment.type+'Comment';if(extra.delegate){comment=extra.delegate(comment);}
extra.tokens.push(comment);}}
function skipSingleLineComment(offset){var start,loc,ch,comment;start=index-offset;loc={start:{line:lineNumber,column:index-lineStart-offset}};while(index<length){ch=source.charCodeAt(index);++index;if(isLineTerminator(ch)){hasLineTerminator=true;if(extra.comments){comment=source.slice(start+offset,index-1);loc.end={line:lineNumber,column:index-lineStart-1};addComment('Line',comment,start,index-1,loc);}
if(ch===13&&source.charCodeAt(index)===10){++index;}
++lineNumber;lineStart=index;return;}}
if(extra.comments){comment=source.slice(start+offset,index);loc.end={line:lineNumber,column:index-lineStart};addComment('Line',comment,start,index,loc);}}
function skipMultiLineComment(){var start,loc,ch,comment;if(extra.comments){start=index-2;loc={start:{line:lineNumber,column:index-lineStart-2}};}
while(index<length){ch=source.charCodeAt(index);if(isLineTerminator(ch)){if(ch===0x0D&&source.charCodeAt(index+1)===0x0A){++index;}
hasLineTerminator=true;++lineNumber;++index;lineStart=index;}else if(ch===0x2A){if(source.charCodeAt(index+1)===0x2F){++index;++index;if(extra.comments){comment=source.slice(start+2,index-2);loc.end={line:lineNumber,column:index-lineStart};addComment('Block',comment,start,index,loc);}
return;}
++index;}else{++index;}}
if(extra.comments){loc.end={line:lineNumber,column:index-lineStart};comment=source.slice(start+2,index);addComment('Block',comment,start,index,loc);}
tolerateUnexpectedToken();}
function skipComment(){var ch,start;hasLineTerminator=false;start=(index===0);while(index<length){ch=source.charCodeAt(index);if(isWhiteSpace(ch)){++index;}else if(isLineTerminator(ch)){hasLineTerminator=true;++index;if(ch===0x0D&&source.charCodeAt(index)===0x0A){++index;}
++lineNumber;lineStart=index;start=true;}else if(ch===0x2F){ch=source.charCodeAt(index+1);if(ch===0x2F){++index;++index;skipSingleLineComment(2);start=true;}else if(ch===0x2A){++index;++index;skipMultiLineComment();}else{break;}}else if(start&&ch===0x2D){if((source.charCodeAt(index+1)===0x2D)&&(source.charCodeAt(index+2)===0x3E)){index+=3;skipSingleLineComment(3);}else{break;}}else if(ch===0x3C){if(source.slice(index+1,index+4)==='!--'){++index;++index;++index;++index;skipSingleLineComment(4);}else{break;}}else{break;}}}
function scanHexEscape(prefix){var i,len,ch,code=0;len=(prefix==='u')?4:2;for(i=0;i<len;++i){if(index<length&&isHexDigit(source[index])){ch=source[index++];code=code*16+'0123456789abcdef'.indexOf(ch.toLowerCase());}else{return'';}}
return String.fromCharCode(code);}
function scanUnicodeCodePointEscape(){var ch,code;ch=source[index];code=0;if(ch==='}'){throwUnexpectedToken();}
while(index<length){ch=source[index++];if(!isHexDigit(ch)){break;}
code=code*16+'0123456789abcdef'.indexOf(ch.toLowerCase());}
if(code>0x10FFFF||ch!=='}'){throwUnexpectedToken();}
return fromCodePoint(code);}
function codePointAt(i){var cp,first,second;cp=source.charCodeAt(i);if(cp>=0xD800&&cp<=0xDBFF){second=source.charCodeAt(i+1);if(second>=0xDC00&&second<=0xDFFF){first=cp;cp=(first-0xD800)*0x400+second-0xDC00+0x10000;}}
return cp;}
function getComplexIdentifier(){var cp,ch,id;cp=codePointAt(index);id=fromCodePoint(cp);index+=id.length;if(cp===0x5C){if(source.charCodeAt(index)!==0x75){throwUnexpectedToken();}
++index;if(source[index]==='{'){++index;ch=scanUnicodeCodePointEscape();}else{ch=scanHexEscape('u');cp=ch.charCodeAt(0);if(!ch||ch==='\\'||!isIdentifierStart(cp)){throwUnexpectedToken();}}
id=ch;}
while(index<length){cp=codePointAt(index);if(!isIdentifierPart(cp)){break;}
ch=fromCodePoint(cp);id+=ch;index+=ch.length;if(cp===0x5C){id=id.substr(0,id.length-1);if(source.charCodeAt(index)!==0x75){throwUnexpectedToken();}
++index;if(source[index]==='{'){++index;ch=scanUnicodeCodePointEscape();}else{ch=scanHexEscape('u');cp=ch.charCodeAt(0);if(!ch||ch==='\\'||!isIdentifierPart(cp)){throwUnexpectedToken();}}
id+=ch;}}
return id;}
function getIdentifier(){var start,ch;start=index++;while(index<length){ch=source.charCodeAt(index);if(ch===0x5C){index=start;return getComplexIdentifier();}else if(ch>=0xD800&&ch<0xDFFF){index=start;return getComplexIdentifier();}
if(isIdentifierPart(ch)){++index;}else{break;}}
return source.slice(start,index);}
function scanIdentifier(){var start,id,type;start=index;id=(source.charCodeAt(index)===0x5C)?getComplexIdentifier():getIdentifier();if(id.length===1){type=Token.Identifier;}else if(isKeyword(id)){type=Token.Keyword;}else if(id==='null'){type=Token.NullLiteral;}else if(id==='true'||id==='false'){type=Token.BooleanLiteral;}else{type=Token.Identifier;}
return{type:type,value:id,lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
function scanPunctuator(){var token,str;token={type:Token.Punctuator,value:'',lineNumber:lineNumber,lineStart:lineStart,start:index,end:index};str=source[index];switch(str){case'(':if(extra.tokenize){extra.openParenToken=extra.tokenValues.length;}
++index;break;case'{':if(extra.tokenize){extra.openCurlyToken=extra.tokenValues.length;}
state.curlyStack.push('{');++index;break;case'.':++index;if(source[index]==='.'&&source[index+1]==='.'){index+=2;str='...';}
break;case'}':++index;state.curlyStack.pop();break;case')':case';':case',':case'[':case']':case':':case'?':case'~':++index;break;default:str=source.substr(index,4);if(str==='>>>='){index+=4;}else{str=str.substr(0,3);if(str==='==='||str==='!=='||str==='>>>'||str==='<<='||str==='>>='){index+=3;}else{str=str.substr(0,2);if(str==='&&'||str==='||'||str==='=='||str==='!='||str==='+='||str==='-='||str==='*='||str==='/='||str==='++'||str==='--'||str==='<<'||str==='>>'||str==='&='||str==='|='||str==='^='||str==='%='||str==='<='||str==='>='||str==='=>'){index+=2;}else{str=source[index];if('<>=!+-*%&|^/'.indexOf(str)>=0){++index;}}}}}
if(index===token.start){throwUnexpectedToken();}
token.end=index;token.value=str;return token;}
function scanHexLiteral(start){var number='';while(index<length){if(!isHexDigit(source[index])){break;}
number+=source[index++];}
if(number.length===0){throwUnexpectedToken();}
if(isIdentifierStart(source.charCodeAt(index))){throwUnexpectedToken();}
return{type:Token.NumericLiteral,value:parseInt('0x'+number,16),lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
function scanBinaryLiteral(start){var ch,number;number='';while(index<length){ch=source[index];if(ch!=='0'&&ch!=='1'){break;}
number+=source[index++];}
if(number.length===0){throwUnexpectedToken();}
if(index<length){ch=source.charCodeAt(index);if(isIdentifierStart(ch)||isDecimalDigit(ch)){throwUnexpectedToken();}}
return{type:Token.NumericLiteral,value:parseInt(number,2),lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
function scanOctalLiteral(prefix,start){var number,octal;if(isOctalDigit(prefix)){octal=true;number='0'+source[index++];}else{octal=false;++index;number='';}
while(index<length){if(!isOctalDigit(source[index])){break;}
number+=source[index++];}
if(!octal&&number.length===0){throwUnexpectedToken();}
if(isIdentifierStart(source.charCodeAt(index))||isDecimalDigit(source.charCodeAt(index))){throwUnexpectedToken();}
return{type:Token.NumericLiteral,value:parseInt(number,8),octal:octal,lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
function isImplicitOctalLiteral(){var i,ch;for(i=index+1;i<length;++i){ch=source[i];if(ch==='8'||ch==='9'){return false;}
if(!isOctalDigit(ch)){return true;}}
return true;}
function scanNumericLiteral(){var number,start,ch;ch=source[index];assert(isDecimalDigit(ch.charCodeAt(0))||(ch==='.'),'Numeric literal must start with a decimal digit or a decimal point');start=index;number='';if(ch!=='.'){number=source[index++];ch=source[index];if(number==='0'){if(ch==='x'||ch==='X'){++index;return scanHexLiteral(start);}
if(ch==='b'||ch==='B'){++index;return scanBinaryLiteral(start);}
if(ch==='o'||ch==='O'){return scanOctalLiteral(ch,start);}
if(isOctalDigit(ch)){if(isImplicitOctalLiteral()){return scanOctalLiteral(ch,start);}}}
while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++];}
ch=source[index];}
if(ch==='.'){number+=source[index++];while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++];}
ch=source[index];}
if(ch==='e'||ch==='E'){number+=source[index++];ch=source[index];if(ch==='+'||ch==='-'){number+=source[index++];}
if(isDecimalDigit(source.charCodeAt(index))){while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++];}}else{throwUnexpectedToken();}}
if(isIdentifierStart(source.charCodeAt(index))){throwUnexpectedToken();}
return{type:Token.NumericLiteral,value:parseFloat(number),lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
function scanStringLiteral(){var str='',quote,start,ch,unescaped,octToDec,octal=false;quote=source[index];assert((quote==='\''||quote==='"'),'String literal must starts with a quote');start=index;++index;while(index<length){ch=source[index++];if(ch===quote){quote='';break;}else if(ch==='\\'){ch=source[index++];if(!ch||!isLineTerminator(ch.charCodeAt(0))){switch(ch){case'u':case'x':if(source[index]==='{'){++index;str+=scanUnicodeCodePointEscape();}else{unescaped=scanHexEscape(ch);if(!unescaped){throw throwUnexpectedToken();}
str+=unescaped;}
break;case'n':str+='\n';break;case'r':str+='\r';break;case't':str+='\t';break;case'b':str+='\b';break;case'f':str+='\f';break;case'v':str+='\x0B';break;case'8':case'9':str+=ch;tolerateUnexpectedToken();break;default:if(isOctalDigit(ch)){octToDec=octalToDecimal(ch);octal=octToDec.octal||octal;str+=String.fromCharCode(octToDec.code);}else{str+=ch;}
break;}}else{++lineNumber;if(ch==='\r'&&source[index]==='\n'){++index;}
lineStart=index;}}else if(isLineTerminator(ch.charCodeAt(0))){break;}else{str+=ch;}}
if(quote!==''){throwUnexpectedToken();}
return{type:Token.StringLiteral,value:str,octal:octal,lineNumber:startLineNumber,lineStart:startLineStart,start:start,end:index};}
function scanTemplate(){var cooked='',ch,start,rawOffset,terminated,head,tail,restore,unescaped;terminated=false;tail=false;start=index;head=(source[index]==='`');rawOffset=2;++index;while(index<length){ch=source[index++];if(ch==='`'){rawOffset=1;tail=true;terminated=true;break;}else if(ch==='$'){if(source[index]==='{'){state.curlyStack.push('${');++index;terminated=true;break;}
cooked+=ch;}else if(ch==='\\'){ch=source[index++];if(!isLineTerminator(ch.charCodeAt(0))){switch(ch){case'n':cooked+='\n';break;case'r':cooked+='\r';break;case't':cooked+='\t';break;case'u':case'x':if(source[index]==='{'){++index;cooked+=scanUnicodeCodePointEscape();}else{restore=index;unescaped=scanHexEscape(ch);if(unescaped){cooked+=unescaped;}else{index=restore;cooked+=ch;}}
break;case'b':cooked+='\b';break;case'f':cooked+='\f';break;case'v':cooked+='\v';break;default:if(ch==='0'){if(isDecimalDigit(source.charCodeAt(index))){throwError(Messages.TemplateOctalLiteral);}
cooked+='\0';}else if(isOctalDigit(ch)){throwError(Messages.TemplateOctalLiteral);}else{cooked+=ch;}
break;}}else{++lineNumber;if(ch==='\r'&&source[index]==='\n'){++index;}
lineStart=index;}}else if(isLineTerminator(ch.charCodeAt(0))){++lineNumber;if(ch==='\r'&&source[index]==='\n'){++index;}
lineStart=index;cooked+='\n';}else{cooked+=ch;}}
if(!terminated){throwUnexpectedToken();}
if(!head){state.curlyStack.pop();}
return{type:Token.Template,value:{cooked:cooked,raw:source.slice(start+1,index-rawOffset)},head:head,tail:tail,lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
function testRegExp(pattern,flags){var astralSubstitute='\uFFFF',tmp=pattern;if(flags.indexOf('u')>=0){tmp=tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,function($0,$1,$2){var codePoint=parseInt($1||$2,16);if(codePoint>0x10FFFF){throwUnexpectedToken(null,Messages.InvalidRegExp);}
if(codePoint<=0xFFFF){return String.fromCharCode(codePoint);}
return astralSubstitute;}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,astralSubstitute);}
try{RegExp(tmp);}catch(e){throwUnexpectedToken(null,Messages.InvalidRegExp);}
try{return new RegExp(pattern,flags);}catch(exception){return null;}}
function scanRegExpBody(){var ch,str,classMarker,terminated,body;ch=source[index];assert(ch==='/','Regular expression literal must start with a slash');str=source[index++];classMarker=false;terminated=false;while(index<length){ch=source[index++];str+=ch;if(ch==='\\'){ch=source[index++];if(isLineTerminator(ch.charCodeAt(0))){throwUnexpectedToken(null,Messages.UnterminatedRegExp);}
str+=ch;}else if(isLineTerminator(ch.charCodeAt(0))){throwUnexpectedToken(null,Messages.UnterminatedRegExp);}else if(classMarker){if(ch===']'){classMarker=false;}}else{if(ch==='/'){terminated=true;break;}else if(ch==='['){classMarker=true;}}}
if(!terminated){throwUnexpectedToken(null,Messages.UnterminatedRegExp);}
body=str.substr(1,str.length-2);return{value:body,literal:str};}
function scanRegExpFlags(){var ch,str,flags,restore;str='';flags='';while(index<length){ch=source[index];if(!isIdentifierPart(ch.charCodeAt(0))){break;}
++index;if(ch==='\\'&&index<length){ch=source[index];if(ch==='u'){++index;restore=index;ch=scanHexEscape('u');if(ch){flags+=ch;for(str+='\\u';restore<index;++restore){str+=source[restore];}}else{index=restore;flags+='u';str+='\\u';}
tolerateUnexpectedToken();}else{str+='\\';tolerateUnexpectedToken();}}else{flags+=ch;str+=ch;}}
return{value:flags,literal:str};}
function scanRegExp(){var start,body,flags,value;scanning=true;lookahead=null;skipComment();start=index;body=scanRegExpBody();flags=scanRegExpFlags();value=testRegExp(body.value,flags.value);scanning=false;if(extra.tokenize){return{type:Token.RegularExpression,value:value,regex:{pattern:body.value,flags:flags.value},lineNumber:lineNumber,lineStart:lineStart,start:start,end:index};}
return{literal:body.literal+flags.literal,value:value,regex:{pattern:body.value,flags:flags.value},start:start,end:index};}
function collectRegex(){var pos,loc,regex,token;skipComment();pos=index;loc={start:{line:lineNumber,column:index-lineStart}};regex=scanRegExp();loc.end={line:lineNumber,column:index-lineStart};if(!extra.tokenize){if(extra.tokens.length>0){token=extra.tokens[extra.tokens.length-1];if(token.range[0]===pos&&token.type==='Punctuator'){if(token.value==='/'||token.value==='/='){extra.tokens.pop();}}}
extra.tokens.push({type:'RegularExpression',value:regex.literal,regex:regex.regex,range:[pos,index],loc:loc});}
return regex;}
function isIdentifierName(token){return token.type===Token.Identifier||token.type===Token.Keyword||token.type===Token.BooleanLiteral||token.type===Token.NullLiteral;}
function advanceSlash(){var regex,previous,check;function testKeyword(value){return value&&(value.length>1)&&(value[0]>='a')&&(value[0]<='z');}
previous=extra.tokenValues[extra.tokens.length-1];regex=(previous!==null);switch(previous){case'this':case']':regex=false;break;case')':check=extra.tokenValues[extra.openParenToken-1];regex=(check==='if'||check==='while'||check==='for'||check==='with');break;case'}':regex=false;if(testKeyword(extra.tokenValues[extra.openCurlyToken-3])){check=extra.tokenValues[extra.openCurlyToken-4];regex=check?(FnExprTokens.indexOf(check)<0):false;}else if(testKeyword(extra.tokenValues[extra.openCurlyToken-4])){check=extra.tokenValues[extra.openCurlyToken-5];regex=check?(FnExprTokens.indexOf(check)<0):true;}}
return regex?collectRegex():scanPunctuator();}
function advance(){var cp,token;if(index>=length){return{type:Token.EOF,lineNumber:lineNumber,lineStart:lineStart,start:index,end:index};}
cp=source.charCodeAt(index);if(isIdentifierStart(cp)){token=scanIdentifier();if(strict&&isStrictModeReservedWord(token.value)){token.type=Token.Keyword;}
return token;}
if(cp===0x28||cp===0x29||cp===0x3B){return scanPunctuator();}
if(cp===0x27||cp===0x22){return scanStringLiteral();}
if(cp===0x2E){if(isDecimalDigit(source.charCodeAt(index+1))){return scanNumericLiteral();}
return scanPunctuator();}
if(isDecimalDigit(cp)){return scanNumericLiteral();}
if(extra.tokenize&&cp===0x2F){return advanceSlash();}
if(cp===0x60||(cp===0x7D&&state.curlyStack[state.curlyStack.length-1]==='${')){return scanTemplate();}
if(cp>=0xD800&&cp<0xDFFF){cp=codePointAt(index);if(isIdentifierStart(cp)){return scanIdentifier();}}
return scanPunctuator();}
function collectToken(){var loc,token,value,entry;loc={start:{line:lineNumber,column:index-lineStart}};token=advance();loc.end={line:lineNumber,column:index-lineStart};if(token.type!==Token.EOF){value=source.slice(token.start,token.end);entry={type:TokenName[token.type],value:value,range:[token.start,token.end],loc:loc};if(token.regex){entry.regex={pattern:token.regex.pattern,flags:token.regex.flags};}
if(extra.tokenValues){extra.tokenValues.push((entry.type==='Punctuator'||entry.type==='Keyword')?entry.value:null);}
if(extra.tokenize){if(!extra.range){delete entry.range;}
if(!extra.loc){delete entry.loc;}
if(extra.delegate){entry=extra.delegate(entry);}}
extra.tokens.push(entry);}
return token;}
function lex(){var token;scanning=true;lastIndex=index;lastLineNumber=lineNumber;lastLineStart=lineStart;skipComment();token=lookahead;startIndex=index;startLineNumber=lineNumber;startLineStart=lineStart;lookahead=(typeof extra.tokens!=='undefined')?collectToken():advance();scanning=false;return token;}
function peek(){scanning=true;skipComment();lastIndex=index;lastLineNumber=lineNumber;lastLineStart=lineStart;startIndex=index;startLineNumber=lineNumber;startLineStart=lineStart;lookahead=(typeof extra.tokens!=='undefined')?collectToken():advance();scanning=false;}
function Position(){this.line=startLineNumber;this.column=startIndex-startLineStart;}
function SourceLocation(){this.start=new Position();this.end=null;}
function WrappingSourceLocation(startToken){this.start={line:startToken.lineNumber,column:startToken.start-startToken.lineStart};this.end=null;}
function Node(){if(extra.range){this.range=[startIndex,0];}
if(extra.loc){this.loc=new SourceLocation();}}
function WrappingNode(startToken){if(extra.range){this.range=[startToken.start,0];}
if(extra.loc){this.loc=new WrappingSourceLocation(startToken);}}
WrappingNode.prototype=Node.prototype={processComment:function(){var lastChild,innerComments,leadingComments,trailingComments,bottomRight=extra.bottomRightStack,i,comment,last=bottomRight[bottomRight.length-1];if(this.type===Syntax.Program){if(this.body.length>0){return;}}
if(this.type===Syntax.BlockStatement&&this.body.length===0){innerComments=[];for(i=extra.leadingComments.length-1;i>=0;--i){comment=extra.leadingComments[i];if(this.range[1]>=comment.range[1]){innerComments.unshift(comment);extra.leadingComments.splice(i,1);extra.trailingComments.splice(i,1);}}
if(innerComments.length){this.innerComments=innerComments;return;}}
if(extra.trailingComments.length>0){trailingComments=[];for(i=extra.trailingComments.length-1;i>=0;--i){comment=extra.trailingComments[i];if(comment.range[0]>=this.range[1]){trailingComments.unshift(comment);extra.trailingComments.splice(i,1);}}
extra.trailingComments=[];}else{if(last&&last.trailingComments&&last.trailingComments[0].range[0]>=this.range[1]){trailingComments=last.trailingComments;delete last.trailingComments;}}
while(last&&last.range[0]>=this.range[0]){lastChild=bottomRight.pop();last=bottomRight[bottomRight.length-1];}
if(lastChild){if(lastChild.leadingComments){leadingComments=[];for(i=lastChild.leadingComments.length-1;i>=0;--i){comment=lastChild.leadingComments[i];if(comment.range[1]<=this.range[0]){leadingComments.unshift(comment);lastChild.leadingComments.splice(i,1);}}
if(!lastChild.leadingComments.length){lastChild.leadingComments=undefined;}}}else if(extra.leadingComments.length>0){leadingComments=[];for(i=extra.leadingComments.length-1;i>=0;--i){comment=extra.leadingComments[i];if(comment.range[1]<=this.range[0]){leadingComments.unshift(comment);extra.leadingComments.splice(i,1);}}}
if(leadingComments&&leadingComments.length>0){this.leadingComments=leadingComments;}
if(trailingComments&&trailingComments.length>0){this.trailingComments=trailingComments;}
bottomRight.push(this);},finish:function(){if(extra.range){this.range[1]=lastIndex;}
if(extra.loc){this.loc.end={line:lastLineNumber,column:lastIndex-lastLineStart};if(extra.source){this.loc.source=extra.source;}}
if(extra.attachComment){this.processComment();}},finishArrayExpression:function(elements){this.type=Syntax.ArrayExpression;this.elements=elements;this.finish();return this;},finishArrayPattern:function(elements){this.type=Syntax.ArrayPattern;this.elements=elements;this.finish();return this;},finishArrowFunctionExpression:function(params,defaults,body,expression){this.type=Syntax.ArrowFunctionExpression;this.id=null;this.params=params;this.defaults=defaults;this.body=body;this.generator=false;this.expression=expression;this.finish();return this;},finishAssignmentExpression:function(operator,left,right){this.type=Syntax.AssignmentExpression;this.operator=operator;this.left=left;this.right=right;this.finish();return this;},finishAssignmentPattern:function(left,right){this.type=Syntax.AssignmentPattern;this.left=left;this.right=right;this.finish();return this;},finishBinaryExpression:function(operator,left,right){this.type=(operator==='||'||operator==='&&')?Syntax.LogicalExpression:Syntax.BinaryExpression;this.operator=operator;this.left=left;this.right=right;this.finish();return this;},finishBlockStatement:function(body){this.type=Syntax.BlockStatement;this.body=body;this.finish();return this;},finishBreakStatement:function(label){this.type=Syntax.BreakStatement;this.label=label;this.finish();return this;},finishCallExpression:function(callee,args){this.type=Syntax.CallExpression;this.callee=callee;this.arguments=args;this.finish();return this;},finishCatchClause:function(param,body){this.type=Syntax.CatchClause;this.param=param;this.body=body;this.finish();return this;},finishClassBody:function(body){this.type=Syntax.ClassBody;this.body=body;this.finish();return this;},finishClassDeclaration:function(id,superClass,body){this.type=Syntax.ClassDeclaration;this.id=id;this.superClass=superClass;this.body=body;this.finish();return this;},finishClassExpression:function(id,superClass,body){this.type=Syntax.ClassExpression;this.id=id;this.superClass=superClass;this.body=body;this.finish();return this;},finishConditionalExpression:function(test,consequent,alternate){this.type=Syntax.ConditionalExpression;this.test=test;this.consequent=consequent;this.alternate=alternate;this.finish();return this;},finishContinueStatement:function(label){this.type=Syntax.ContinueStatement;this.label=label;this.finish();return this;},finishDebuggerStatement:function(){this.type=Syntax.DebuggerStatement;this.finish();return this;},finishDoWhileStatement:function(body,test){this.type=Syntax.DoWhileStatement;this.body=body;this.test=test;this.finish();return this;},finishEmptyStatement:function(){this.type=Syntax.EmptyStatement;this.finish();return this;},finishExpressionStatement:function(expression){this.type=Syntax.ExpressionStatement;this.expression=expression;this.finish();return this;},finishForStatement:function(init,test,update,body){this.type=Syntax.ForStatement;this.init=init;this.test=test;this.update=update;this.body=body;this.finish();return this;},finishForOfStatement:function(left,right,body){this.type=Syntax.ForOfStatement;this.left=left;this.right=right;this.body=body;this.finish();return this;},finishForInStatement:function(left,right,body){this.type=Syntax.ForInStatement;this.left=left;this.right=right;this.body=body;this.each=false;this.finish();return this;},finishFunctionDeclaration:function(id,params,defaults,body,generator){this.type=Syntax.FunctionDeclaration;this.id=id;this.params=params;this.defaults=defaults;this.body=body;this.generator=generator;this.expression=false;this.finish();return this;},finishFunctionExpression:function(id,params,defaults,body,generator){this.type=Syntax.FunctionExpression;this.id=id;this.params=params;this.defaults=defaults;this.body=body;this.generator=generator;this.expression=false;this.finish();return this;},finishIdentifier:function(name){this.type=Syntax.Identifier;this.name=name;this.finish();return this;},finishIfStatement:function(test,consequent,alternate){this.type=Syntax.IfStatement;this.test=test;this.consequent=consequent;this.alternate=alternate;this.finish();return this;},finishLab
this.finish();return this;},finishMemberExpression:function(accessor,object,property){this.type=Syntax.MemberExpression;this.computed=accessor==='[';this.object=object;this.property=property;this.finish();return this;},finishMetaProperty:function(meta,property){this.type=Syntax.MetaProperty;this.meta=meta;this.property=property;this.finish();return this;},finishNewExpression:function(callee,args){this.type=Syntax.NewExpression;this.callee=callee;this.arguments=args;this.finish();return this;},finishObjectExpression:function(properties){this.type=Syntax.ObjectExpression;this.properties=properties;this.finish();return this;},finishObjectPattern:function(properties){this.type=Syntax.ObjectPattern;this.properties=properties;this.finish();return this;},finishPostfixExpression:function(operator,argument){this.type=Syntax.UpdateExpression;this.operator=operator;this.argument=argument;this.prefix=false;this.finish();return this;},finishProgram:function(body,sourceType){this.type=Syntax.Program;this.body=body;this.sourceType=sourceType;this.finish();return this;},finishProperty:function(kind,key,computed,value,method,shorthand){this.type=Syntax.Property;this.key=key;this.computed=computed;this.value=value;this.kind=kind;this.method=method;this.shorthand=shorthand;this.finish();return this;},finishRestElement:function(argument){this.type=Syntax.RestElement;this.argument=argument;this.finish();return this;},finishReturnStatement:function(argument){this.type=Syntax.ReturnStatement;this.argument=argument;this.finish();return this;},finishSequenceExpression:function(expressions){this.type=Syntax.SequenceExpression;this.expressions=expressions;this.finish();return this;},finishSpreadElement:function(argument){this.type=Syntax.SpreadElement;this.argument=argument;this.finish();return this;},finishSwitchCase:function(test,consequent){this.type=Syntax.SwitchCase;this.test=test;this.consequent=consequent;this.finish();return this;},finishSuper:function(){this.type=Syntax.Super;this.finish();return this;},finishSwitchStatement:function(discriminant,cases){this.type=Syntax.SwitchStatement;this.discriminant=discriminant;this.cases=cases;this.finish();return this;},finishTaggedTemplateExpression:function(tag,quasi){this.type=Syntax.TaggedTemplateExpression;this.tag=tag;this.quasi=quasi;this.finish();return this;},finishTemplateElement:function(value,tail){this.type=Syntax.TemplateElement;this.value=value;this.tail=tail;this.finish();return this;},finishTemplateLiteral:function(quasis,expressions){this.type=Syntax.TemplateLiteral;this.quasis=quasis;this.expressions=expressions;this.finish();return this;},finishThisExpression:function(){this.type=Syntax.ThisExpression;this.finish();return this;},finishThrowStatement:function(argument){this.type=Syntax.ThrowStatement;this.argument=argument;this.finish();return this;},finishTryStatement:function(block,handler,finalizer){this.type=Syntax.TryStatement;this.block=block;this.guardedHandlers=[];this.handlers=handler?[handler]:[];this.handler=handler;this.finalizer=finalizer;this.finish();return this;},finishUnaryExpression:function(operator,argument){this.type=(operator==='++'||operator==='--')?Syntax.UpdateExpression:Syntax.UnaryExpression;this.operator=operator;this.argument=argument;this.prefix=true;this.finish();return this;},finishVariableDeclaration:function(declarations){this.type=Syntax.VariableDeclaration;this.declarations=declarations;this.kind='var';this.finish();return this;},finishLexicalDeclaration:function(declarations,kind){this.type=Syntax.VariableDeclaration;this.declarations=declarations;this.kind=kind;this.finish();return this;},finishVariableDeclarator:function(id,init){this.type=Syntax.VariableDeclarator;this.id=id;this.init=init;this.finish();return this;},finishWhileStatement:function(test,body){this.type=Syntax.WhileStatement;this.test=test;this.body=body;this.finish();return this;},finishWithStatement:function(object,body){this.type=Syntax.WithStatement;this.object=object;this.body=body;this.finish();return this;},finishExportSpecifier:function(local,exported){this.type=Synta
extra.errors.push(error);}
function constructError(msg,column){var error=new Error(msg);try{throw error;}catch(base){if(Object.create&&Object.defineProperty){error=Object.create(base);Object.defineProperty(error,'column',{value:column});}}finally{return error;}}
function createError(line,pos,description){var msg,column,error;column=pos-(scanning?lineStart:lastLineStart)+1;msg='Line '+line+' Column '+column+': '+description;error=constructError(msg,column);error.lineNumber=line;error.description=description;error.index=pos;return error;}
function throwError(messageFormat){var args,msg;args=Array.prototype.slice.call(arguments,1);msg=messageFormat.replace(/%(\d)/g,function(whole,idx){assert(idx<args.length,'Message reference must be in range');return args[idx];});throw createError(lastLineNumber,lastIndex,msg);}
function tolerateError(messageFormat){var args,msg,error;args=Array.prototype.slice.call(arguments,1);msg=messageFormat.replace(/%(\d)/g,function(whole,idx){assert(idx<args.length,'Message reference must be in range');return args[idx];});error=createError(lineNumber,lastIndex,msg);if(extra.errors){recordError(error);}else{throw error;}}
function unexpectedTokenError(token,message){var value,msg=message||Messages.UnexpectedToken;if(token){if(!message){msg=(token.type===Token.EOF)?Messages.UnexpectedEOS:(token.type===Token.Identifier)?Messages.UnexpectedIdentifier:(token.type===Token.NumericLiteral)?Messages.UnexpectedNumber:(token.type===Token.StringLiteral)?Messages.UnexpectedString:(token.type===Token.Template)?Messages.UnexpectedTemplate:Messages.UnexpectedToken;if(token.type===Token.Keyword){if(isFutureReservedWord(token.value)){msg=Messages.UnexpectedReserved;}else if(strict&&isStrictModeReservedWord(token.value)){msg=Messages.StrictReservedWord;}}}
value=(token.type===Token.Template)?token.value.raw:token.value;}else{value='ILLEGAL';}
msg=msg.replace('%0',value);return(token&&typeof token.lineNumber==='number')?createError(token.lineNumber,token.start,msg):createError(scanning?lineNumber:lastLineNumber,scanning?index:lastIndex,msg);}
function throwUnexpectedToken(token,message){throw unexpectedTokenError(token,message);}
function tolerateUnexpectedToken(token,message){var error=unexpectedTokenError(token,message);if(extra.errors){recordError(error);}else{throw error;}}
function expect(value){var token=lex();if(token.type!==Token.Punctuator||token.value!==value){throwUnexpectedToken(token);}}
function expectCommaSeparator(){var token;if(extra.errors){token=lookahead;if(token.type===Token.Punctuator&&token.value===','){lex();}else if(token.type===Token.Punctuator&&token.value===';'){lex();tolerateUnexpectedToken(token);}else{tolerateUnexpectedToken(token,Messages.UnexpectedToken);}}else{expect(',');}}
function expectKeyword(keyword){var token=lex();if(token.type!==Token.Keyword||token.value!==keyword){throwUnexpectedToken(token);}}
function match(value){return lookahead.type===Token.Punctuator&&lookahead.value===value;}
function matchKeyword(keyword){return lookahead.type===Token.Keyword&&lookahead.value===keyword;}
function matchContextualKeyword(keyword){return lookahead.type===Token.Identifier&&lookahead.value===keyword;}
function matchAssign(){var op;if(lookahead.type!==Token.Punctuator){return false;}
op=lookahead.value;return op==='='||op==='*='||op==='/='||op==='%='||op==='+='||op==='-='||op==='<<='||op==='>>='||op==='>>>='||op==='&='||op==='^='||op==='|=';}
function consumeSemicolon(){if(source.charCodeAt(startIndex)===0x3B||match(';')){lex();return;}
if(hasLineTerminator){return;}
lastIndex=startIndex;lastLineNumber=startLineNumber;lastLineStart=startLineStart;if(lookahead.type!==Token.EOF&&!match('}')){throwUnexpectedToken(lookahead);}}
function isolateCoverGrammar(parser){var oldIsBindingElement=isBindingElement,oldIsAssignmentTarget=isAssignmentTarget,oldFirstCoverInitializedNameError=firstCoverInitializedNameError,result;isBindingElement=true;isAssignmentTarget=true;firstCoverInitializedNameError=null;result=parser();if(firstCoverInitializedNameError!==null){throwUnexpectedToken(firstCoverInitializedNameError);}
isBindingElement=oldIsBindingElement;isAssignmentTarget=oldIsAssignmentTarget;firstCoverInitializedNameError=oldFirstCoverInitializedNameError;return result;}
function inheritCoverGrammar(parser){var oldIsBindingElement=isBindingElement,oldIsAssignmentTarget=isAssignmentTarget,oldFirstCoverInitializedNameError=firstCoverInitializedNameError,result;isBindingElement=true;isAssignmentTarget=true;firstCoverInitializedNameError=null;result=parser();isBindingElement=isBindingElement&&oldIsBindingElement;isAssignmentTarget=isAssignmentTarget&&oldIsAssignmentTarget;firstCoverInitializedNameError=oldFirstCoverInitializedNameError||firstCoverInitializedNameError;return result;}
function parseArrayPattern(params,kind){var node=new Node(),elements=[],rest,restNode;expect('[');while(!match(']')){if(match(',')){lex();elements.push(null);}else{if(match('...')){restNode=new Node();lex();params.push(lookahead);rest=parseVariableIdentifier(kind);elements.push(restNode.finishRestElement(rest));break;}else{elements.push(parsePatternWithDefault(params,kind));}
if(!match(']')){expect(',');}}}
expect(']');return node.finishArrayPattern(elements);}
function parsePropertyPattern(params,kind){var node=new Node(),key,keyToken,computed=match('['),init;if(lookahead.type===Token.Identifier){keyToken=lookahead;key=parseVariableIdentifier();if(match('=')){params.push(keyToken);lex();init=parseAssignmentExpression();return node.finishProperty('init',key,false,new WrappingNode(keyToken).finishAssignmentPattern(key,init),false,false);}else if(!match(':')){params.push(keyToken);return node.finishProperty('init',key,false,key,false,true);}}else{key=parseObjectPropertyKey();}
expect(':');init=parsePatternWithDefault(params,kind);return node.finishProperty('init',key,computed,init,false,false);}
function parseObjectPattern(params,kind){var node=new Node(),properties=[];expect('{');while(!match('}')){properties.push(parsePropertyPattern(params,kind));if(!match('}')){expect(',');}}
lex();return node.finishObjectPattern(properties);}
function parsePattern(params,kind){if(match('[')){return parseArrayPattern(params,kind);}else if(match('{')){return parseObjectPattern(params,kind);}else if(matchKeyword('let')){if(kind==='const'||kind==='let'){tolerateUnexpectedToken(lookahead,Messages.UnexpectedToken);}}
params.push(lookahead);return parseVariableIdentifier(kind);}
function parsePatternWithDefault(params,kind){var startToken=lookahead,pattern,previousAllowYield,right;pattern=parsePattern(params,kind);if(match('=')){lex();previousAllowYield=state.allowYield;state.allowYield=true;right=isolateCoverGrammar(parseAssignmentExpression);state.allowYield=previousAllowYield;pattern=new WrappingNode(startToken).finishAssignmentPattern(pattern,right);}
return pattern;}
function parseArrayInitializer(){var elements=[],node=new Node(),restSpread;expect('[');while(!match(']')){if(match(',')){lex();elements.push(null);}else if(match('...')){restSpread=new Node();lex();restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));if(!match(']')){isAssignmentTarget=isBindingElement=false;expect(',');}
elements.push(restSpread);}else{elements.push(inheritCoverGrammar(parseAssignmentExpression));if(!match(']')){expect(',');}}}
lex();return node.finishArrayExpression(elements);}
function parsePropertyFunction(node,paramInfo,isGenerator){var previousStrict,body;isAssignmentTarget=isBindingElement=false;previousStrict=strict;body=isolateCoverGrammar(parseFunctionSourceElements);if(strict&&paramInfo.firstRestricted){tolerateUnexpectedToken(paramInfo.firstRestricted,paramInfo.message);}
if(strict&&paramInfo.stricted){tolerateUnexpectedToken(paramInfo.stricted,paramInfo.message);}
strict=previousStrict;return node.finishFunctionExpression(null,paramInfo.params,paramInfo.defaults,body,isGenerator);}
function parsePropertyMethodFunction(){var params,method,node=new Node(),previousAllowYield=state.allowYield;state.allowYield=false;params=parseParams();state.allowYield=previousAllowYield;state.allowYield=false;method=parsePropertyFunction(node,params,false);state.allowYield=previousAllowYield;return method;}
function parseObjectPropertyKey(){var token,node=new Node(),expr;token=lex();switch(token.type){case Token.StringLiteral:case Token.NumericLiteral:if(strict&&token.octal){tolerateUnexpectedToken(token,Messages.StrictOctalLiteral);}
return node.finishLiteral(token);case Token.Identifier:case Token.BooleanLiteral:case Token.NullLiteral:case Token.Keyword:return node.finishIdentifier(token.value);case Token.Punctuator:if(token.value==='['){expr=isolateCoverGrammar(parseAssignmentExpression);expect(']');return expr;}
break;}
throwUnexpectedToken(token);}
function lookaheadPropertyName(){switch(lookahead.type){case Token.Identifier:case Token.StringLiteral:case Token.BooleanLiteral:case Token.NullLiteral:case Token.NumericLiteral:case Token.Keyword:return true;case Token.Punctuator:return lookahead.value==='[';}
return false;}
function tryParseMethodDefinition(token,key,computed,node){var value,options,methodNode,params,previousAllowYield=state.allowYield;if(token.type===Token.Identifier){if(token.value==='get'&&lookaheadPropertyName()){computed=match('[');key=parseObjectPropertyKey();methodNode=new Node();expect('(');expect(')');state.allowYield=false;value=parsePropertyFunction(methodNode,{params:[],defaults:[],stricted:null,firstRestricted:null,message:null},false);state.allowYield=previousAllowYield;return node.finishProperty('get',key,computed,value,false,false);}else if(token.value==='set'&&lookaheadPropertyName()){computed=match('[');key=parseObjectPropertyKey();methodNode=new Node();expect('(');options={params:[],defaultCount:0,defaults:[],firstRestricted:null,paramSet:{}};if(match(')')){tolerateUnexpectedToken(lookahead);}else{state.allowYield=false;parseParam(options);state.allowYield=previousAllowYield;if(options.defaultCount===0){options.defaults=[];}}
expect(')');state.allowYield=false;value=parsePropertyFunction(methodNode,options,false);state.allowYield=previousAllowYield;return node.finishProperty('set',key,computed,value,false,false);}}else if(token.type===Token.Punctuator&&token.value==='*'&&lookaheadPropertyName()){computed=match('[');key=parseObjectPropertyKey();methodNode=new Node();state.allowYield=true;params=parseParams();state.allowYield=previousAllowYield;state.allowYield=false;value=parsePropertyFunction(methodNode,params,true);state.allowYield=previousAllowYield;return node.finishProperty('init',key,computed,value,true,false);}
if(key&&match('(')){value=parsePropertyMethodFunction();return node.finishProperty('init',key,computed,value,true,false);}
return null;}
function parseObjectProperty(hasProto){var token=lookahead,node=new Node(),computed,key,maybeMethod,proto,value;computed=match('[');if(match('*')){lex();}else{key=parseObjectPropertyKey();}
maybeMethod=tryParseMethodDefinition(token,key,computed,node);if(maybeMethod){return maybeMethod;}
if(!key){throwUnexpectedToken(lookahead);}
if(!computed){proto=(key.type===Syntax.Identifier&&key.name==='__proto__')||(key.type===Syntax.Literal&&key.value==='__proto__');if(hasProto.value&&proto){tolerateError(Messages.DuplicateProtoProperty);}
hasProto.value|=proto;}
if(match(':')){lex();value=inheritCoverGrammar(parseAssignmentExpression);return node.finishProperty('init',key,computed,value,false,false);}
if(token.type===Token.Identifier){if(match('=')){firstCoverInitializedNameError=lookahead;lex();value=isolateCoverGrammar(parseAssignmentExpression);return node.finishProperty('init',key,computed,new WrappingNode(token).finishAssignmentPattern(key,value),false,true);}
return node.finishProperty('init',key,computed,key,false,true);}
throwUnexpectedToken(lookahead);}
function parseObjectInitializer(){var properties=[],hasProto={value:false},node=new Node();expect('{');while(!match('}')){properties.push(parseObjectProperty(hasProto));if(!match('}')){expectCommaSeparator();}}
expect('}');return node.finishObjectExpression(properties);}
function reinterpretExpressionAsPattern(expr){var i;switch(expr.type){case Syntax.Identifier:case Syntax.MemberExpression:case Syntax.RestElement:case Syntax.AssignmentPattern:break;case Syntax.SpreadElement:expr.type=Syntax.RestElement;reinterpretExpressionAsPattern(expr.argument);break;case Syntax.ArrayExpression:expr.type=Syntax.ArrayPattern;for(i=0;i<expr.elements.length;i++){if(expr.elements[i]!==null){reinterpretExpressionAsPattern(expr.elements[i]);}}
break;case Syntax.ObjectExpression:expr.type=Syntax.ObjectPattern;for(i=0;i<expr.properties.length;i++){reinterpretExpressionAsPattern(expr.properties[i].value);}
break;case Syntax.AssignmentExpression:expr.type=Syntax.AssignmentPattern;reinterpretExpressionAsPattern(expr.left);break;default:break;}}
function parseTemplateElement(option){var node,token;if(lookahead.type!==Token.Template||(option.head&&!lookahead.head)){throwUnexpectedToken();}
node=new Node();token=lex();return node.finishTemplateElement({raw:token.value.raw,cooked:token.value.cooked},token.tail);}
function parseTemplateLiteral(){var quasi,quasis,expressions,node=new Node();quasi=parseTemplateElement({head:true});quasis=[quasi];expressions=[];while(!quasi.tail){expressions.push(parseExpression());quasi=parseTemplateElement({head:false});quasis.push(quasi);}
return node.finishTemplateLiteral(quasis,expressions);}
function parseGroupExpression(){var expr,expressions,startToken,i,params=[];expect('(');if(match(')')){lex();if(!match('=>')){expect('=>');}
return{type:PlaceHolders.ArrowParameterPlaceHolder,params:[],rawParams:[]};}
startToken=lookahead;if(match('...')){expr=parseRestElement(params);expect(')');if(!match('=>')){expect('=>');}
return{type:PlaceHolders.ArrowParameterPlaceHolder,params:[expr]};}
isBindingElement=true;expr=inheritCoverGrammar(parseAssignmentExpression);if(match(',')){isAssignmentTarget=false;expressions=[expr];while(startIndex<length){if(!match(',')){break;}
lex();if(match('...')){if(!isBindingElement){throwUnexpectedToken(lookahead);}
expressions.push(parseRestElement(params));expect(')');if(!match('=>')){expect('=>');}
isBindingElement=false;for(i=0;i<expressions.length;i++){reinterpretExpressionAsPattern(expressions[i]);}
return{type:PlaceHolders.ArrowParameterPlaceHolder,params:expressions};}
expressions.push(inheritCoverGrammar(parseAssignmentExpression));}
expr=new WrappingNode(startToken).finishSequenceExpression(expressions);}
expect(')');if(match('=>')){if(expr.type===Syntax.Identifier&&expr.name==='yield'){return{type:PlaceHolders.ArrowParameterPlaceHolder,params:[expr]};}
if(!isBindingElement){throwUnexpectedToken(lookahead);}
if(expr.type===Syntax.SequenceExpression){for(i=0;i<expr.expressions.length;i++){reinterpretExpressionAsPattern(expr.expressions[i]);}}else{reinterpretExpressionAsPattern(expr);}
expr={type:PlaceHolders.ArrowParameterPlaceHolder,params:expr.type===Syntax.SequenceExpression?expr.expressions:[expr]};}
isBindingElement=false;return expr;}
function parsePrimaryExpression(){var type,token,expr,node;if(match('(')){isBindingElement=false;return inheritCoverGrammar(parseGroupExpression);}
if(match('[')){return inheritCoverGrammar(parseArrayInitializer);}
if(match('{')){return inheritCoverGrammar(parseObjectInitializer);}
type=lookahead.type;node=new Node();if(type===Token.Identifier){if(state.sourceType==='module'&&lookahead.value==='await'){tolerateUnexpectedToken(lookahead);}
expr=node.finishIdentifier(lex().value);}else if(type===Token.StringLiteral||type===Token.NumericLiteral){isAssignmentTarget=isBindingElement=false;if(strict&&lookahead.octal){tolerateUnexpectedToken(lookahead,Messages.StrictOctalLiteral);}
expr=node.finishLiteral(lex());}else if(type===Token.Keyword){if(!strict&&state.allowYield&&matchKeyword('yield')){return parseNonComputedProperty();}
isAssignmentTarget=isBindingElement=false;if(matchKeyword('function')){return parseFunctionExpression();}
if(matchKeyword('this')){lex();return node.finishThisExpression();}
if(matchKeyword('class')){return parseClassExpression();}
if(!strict&&matchKeyword('let')){return node.finishIdentifier(lex().value);}
throwUnexpectedToken(lex());}else if(type===Token.BooleanLiteral){isAssignmentTarget=isBindingElement=false;token=lex();token.value=(token.value==='true');expr=node.finishLiteral(token);}else if(type===Token.NullLiteral){isAssignmentTarget=isBindingElement=false;token=lex();token.value=null;expr=node.finishLiteral(token);}else if(match('/')||match('/=')){isAssignmentTarget=isBindingElement=false;index=startIndex;if(typeof extra.tokens!=='undefined'){token=collectRegex();}else{token=scanRegExp();}
lex();expr=node.finishLiteral(token);}else if(type===Token.Template){expr=parseTemplateLiteral();}else{throwUnexpectedToken(lex());}
return expr;}
function parseArguments(){var args=[],expr;expect('(');if(!match(')')){while(startIndex<length){if(match('...')){expr=new Node();lex();expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));}else{expr=isolateCoverGrammar(parseAssignmentExpression);}
args.push(expr);if(match(')')){break;}
expectCommaSeparator();}}
expect(')');return args;}
function parseNonComputedProperty(){var token,node=new Node();token=lex();if(!isIdentifierName(token)){throwUnexpectedToken(token);}
return node.finishIdentifier(token.value);}
function parseNonComputedMember(){expect('.');return parseNonComputedProperty();}
function parseComputedMember(){var expr;expect('[');expr=isolateCoverGrammar(parseExpression);expect(']');return expr;}
function parseNewExpression(){var callee,args,node=new Node();expectKeyword('new');if(match('.')){lex();if(lookahead.type===Token.Identifier&&lookahead.value==='target'){if(state.inFunctionBody){lex();return node.finishMetaProperty('new','target');}}
throwUnexpectedToken(lookahead);}
callee=isolateCoverGrammar(parseLeftHandSideExpression);args=match('(')?parseArguments():[];isAssignmentTarget=isBindingElement=false;return node.finishNewExpression(callee,args);}
function parseLeftHandSideExpressionAllowCall(){var quasi,expr,args,property,startToken,previousAllowIn=state.allowIn;startToken=lookahead;state.allowIn=true;if(matchKeyword('super')&&state.inFunctionBody){expr=new Node();lex();expr=expr.finishSuper();if(!match('(')&&!match('.')&&!match('[')){throwUnexpectedToken(lookahead);}}else{expr=inheritCoverGrammar(matchKeyword('new')?parseNewExpression:parsePrimaryExpression);}
for(;;){if(match('.')){isBindingElement=false;isAssignmentTarget=true;property=parseNonComputedMember();expr=new WrappingNode(startToken).finishMemberExpression('.',expr,property);}else if(match('(')){isBindingElement=false;isAssignmentTarget=false;args=parseArguments();expr=new WrappingNode(startToken).finishCallExpression(expr,args);}else if(match('[')){isBindingElement=false;isAssignmentTarget=true;property=parseComputedMember();expr=new WrappingNode(startToken).finishMemberExpression('[',expr,property);}else if(lookahead.type===Token.Template&&lookahead.head){quasi=parseTemplateLiteral();expr=new WrappingNode(startToken).finishTaggedTemplateExpression(expr,quasi);}else{break;}}
state.allowIn=previousAllowIn;return expr;}
function parseLeftHandSideExpression(){var quasi,expr,property,startToken;assert(state.allowIn,'callee of new expression always allow in keyword.');startToken=lookahead;if(matchKeyword('super')&&state.inFunctionBody){expr=new Node();lex();expr=expr.finishSuper();if(!match('[')&&!match('.')){throwUnexpectedToken(lookahead);}}else{expr=inheritCoverGrammar(matchKeyword('new')?parseNewExpression:parsePrimaryExpression);}
for(;;){if(match('[')){isBindingElement=false;isAssignmentTarget=true;property=parseComputedMember();expr=new WrappingNode(startToken).finishMemberExpression('[',expr,property);}else if(match('.')){isBindingElement=false;isAssignmentTarget=true;property=parseNonComputedMember();expr=new WrappingNode(startToken).finishMemberExpression('.',expr,property);}else if(lookahead.type===Token.Template&&lookahead.head){quasi=parseTemplateLiteral();expr=new WrappingNode(startToken).finishTaggedTemplateExpression(expr,quasi);}else{break;}}
return expr;}
function parsePostfixExpression(){var expr,token,startToken=lookahead;expr=inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);if(!hasLineTerminator&&lookahead.type===Token.Punctuator){if(match('++')||match('--')){if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){tolerateError(Messages.StrictLHSPostfix);}
if(!isAssignmentTarget){tolerateError(Messages.InvalidLHSInAssignment);}
isAssignmentTarget=isBindingElement=false;token=lex();expr=new WrappingNode(startToken).finishPostfixExpression(token.value,expr);}}
return expr;}
function parseUnaryExpression(){var token,expr,startToken;if(lookahead.type!==Token.Punctuator&&lookahead.type!==Token.Keyword){expr=parsePostfixExpression();}else if(match('++')||match('--')){startToken=lookahead;token=lex();expr=inheritCoverGrammar(parseUnaryExpression);if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){tolerateError(Messages.StrictLHSPrefix);}
if(!isAssignmentTarget){tolerateError(Messages.InvalidLHSInAssignment);}
expr=new WrappingNode(startToken).finishUnaryExpression(token.value,expr);isAssignmentTarget=isBindingElement=false;}else if(match('+')||match('-')||match('~')||match('!')){startToken=lookahead;token=lex();expr=inheritCoverGrammar(parseUnaryExpression);expr=new WrappingNode(startToken).finishUnaryExpression(token.value,expr);isAssignmentTarget=isBindingElement=false;}else if(matchKeyword('delete')||matchKeyword('void')||matchKeyword('typeof')){startToken=lookahead;token=lex();expr=inheritCoverGrammar(parseUnaryExpression);expr=new WrappingNode(startToken).finishUnaryExpression(token.value,expr);if(strict&&expr.operator==='delete'&&expr.argument.type===Syntax.Identifier){tolerateError(Messages.StrictDelete);}
isAssignmentTarget=isBindingElement=false;}else{expr=parsePostfixExpression();}
return expr;}
function binaryPrecedence(token,allowIn){var prec=0;if(token.type!==Token.Punctuator&&token.type!==Token.Keyword){return 0;}
switch(token.value){case'||':prec=1;break;case'&&':prec=2;break;case'|':prec=3;break;case'^':prec=4;break;case'&':prec=5;break;case'==':case'!=':case'===':case'!==':prec=6;break;case'<':case'>':case'<=':case'>=':case'instanceof':prec=7;break;case'in':prec=allowIn?7:0;break;case'<<':case'>>':case'>>>':prec=8;break;case'+':case'-':prec=9;break;case'*':case'/':case'%':prec=11;break;default:break;}
return prec;}
function parseBinaryExpression(){var marker,markers,expr,token,prec,stack,right,operator,left,i;marker=lookahead;left=inheritCoverGrammar(parseUnaryExpression);token=lookahead;prec=binaryPrecedence(token,state.allowIn);if(prec===0){return left;}
isAssignmentTarget=isBindingElement=false;token.prec=prec;lex();markers=[marker,lookahead];right=isolateCoverGrammar(parseUnaryExpression);stack=[left,token,right];while((prec=binaryPrecedence(lookahead,state.allowIn))>0){while((stack.length>2)&&(prec<=stack[stack.length-2].prec)){right=stack.pop();operator=stack.pop().value;left=stack.pop();markers.pop();expr=new WrappingNode(markers[markers.length-1]).finishBinaryExpression(operator,left,right);stack.push(expr);}
token=lex();token.prec=prec;stack.push(token);markers.push(lookahead);expr=isolateCoverGrammar(parseUnaryExpression);stack.push(expr);}
i=stack.length-1;expr=stack[i];markers.pop();while(i>1){expr=new WrappingNode(markers.pop()).finishBinaryExpression(stack[i-1].value,stack[i-2],expr);i-=2;}
return expr;}
function parseConditionalExpression(){var expr,previousAllowIn,consequent,alternate,startToken;startToken=lookahead;expr=inheritCoverGrammar(parseBinaryExpression);if(match('?')){lex();previousAllowIn=state.allowIn;state.allowIn=true;consequent=isolateCoverGrammar(parseAssignmentExpression);state.allowIn=previousAllowIn;expect(':');alternate=isolateCoverGrammar(parseAssignmentExpression);expr=new WrappingNode(startToken).finishConditionalExpression(expr,consequent,alternate);isAssignmentTarget=isBindingElement=false;}
return expr;}
function parseConciseBody(){if(match('{')){return parseFunctionSourceElements();}
return isolateCoverGrammar(parseAssignmentExpression);}
function checkPatternParam(options,param){var i;switch(param.type){case Syntax.Identifier:validateParam(options,param,param.name);break;case Syntax.RestElement:checkPatternParam(options,param.argument);break;case Syntax.AssignmentPattern:checkPatternParam(options,param.left);break;case Syntax.ArrayPattern:for(i=0;i<param.elements.length;i++){if(param.elements[i]!==null){checkPatternParam(options,param.elements[i]);}}
break;case Syntax.YieldExpression:break;default:assert(param.type===Syntax.ObjectPattern,'Invalid type');for(i=0;i<param.properties.length;i++){checkPatternParam(options,param.properties[i].value);}
break;}}
function reinterpretAsCoverFormalsList(expr){var i,len,param,params,defaults,defaultCount,options,token;defaults=[];defaultCount=0;params=[expr];switch(expr.type){case Syntax.Identifier:break;case PlaceHolders.ArrowParameterPlaceHolder:params=expr.params;break;default:return null;}
options={paramSet:{}};for(i=0,len=params.length;i<len;i+=1){param=params[i];switch(param.type){case Syntax.AssignmentPattern:params[i]=param.left;if(param.right.type===Syntax.YieldExpression){if(param.right.argument){throwUnexpectedToken(lookahead);}
param.right.type=Syntax.Identifier;param.right.name='yield';delete param.right.argument;delete param.right.delegate;}
defaults.push(param.right);++defaultCount;checkPatternParam(options,param.left);break;default:checkPatternParam(options,param);params[i]=param;defaults.push(null);break;}}
if(strict||!state.allowYield){for(i=0,len=params.length;i<len;i+=1){param=params[i];if(param.type===Syntax.YieldExpression){throwUnexpectedToken(lookahead);}}}
if(options.message===Messages.StrictParamDupe){token=strict?options.stricted:options.firstRestricted;throwUnexpectedToken(token,options.message);}
if(defaultCount===0){defaults=[];}
return{params:params,defaults:defaults,stricted:options.stricted,firstRestricted:options.firstRestricted,message:options.message};}
function parseArrowFunctionExpression(options,node){var previousStrict,previousAllowYield,body;if(hasLineTerminator){tolerateUnexpectedToken(lookahead);}
expect('=>');previousStrict=strict;previousAllowYield=state.allowYield;state.allowYield=true;body=parseConciseBody();if(strict&&options.firstRestricted){throwUnexpectedToken(options.firstRestricted,options.message);}
if(strict&&options.stricted){tolerateUnexpectedToken(options.stricted,options.message);}
strict=previousStrict;state.allowYield=previousAllowYield;return node.finishArrowFunctionExpression(options.params,options.defaults,body,body.type!==Syntax.BlockStatement);}
function parseYieldExpression(){var argument,expr,delegate,previousAllowYield;argument=null;expr=new Node();expectKeyword('yield');if(!hasLineTerminator){previousAllowYield=state.allowYield;state.allowYield=false;delegate=match('*');if(delegate){lex();argument=parseAssignmentExpression();}else{if(!match(';')&&!match('}')&&!match(')')&&lookahead.type!==Token.EOF){argument=parseAssignmentExpression();}}
state.allowYield=previousAllowYield;}
return expr.finishYieldExpression(argument,delegate);}
function parseAssignmentExpression(){var token,expr,right,list,startToken;startToken=lookahead;token=lookahead;if(!state.allowYield&&matchKeyword('yield')){return parseYieldExpression();}
expr=parseConditionalExpression();if(expr.type===PlaceHolders.ArrowParameterPlaceHolder||match('=>')){isAssignmentTarget=isBindingElement=false;list=reinterpretAsCoverFormalsList(expr);if(list){firstCoverInitializedNameError=null;return parseArrowFunctionExpression(list,new WrappingNode(startToken));}
return expr;}
if(matchAssign()){if(!isAssignmentTarget){tolerateError(Messages.InvalidLHSInAssignment);}
if(strict&&expr.type===Syntax.Identifier){if(isRestrictedWord(expr.name)){tolerateUnexpectedToken(token,Messages.StrictLHSAssignment);}
if(isStrictModeReservedWord(expr.name)){tolerateUnexpectedToken(token,Messages.StrictReservedWord);}}
if(!match('=')){isAssignmentTarget=isBindingElement=false;}else{reinterpretExpressionAsPattern(expr);}
token=lex();right=isolateCoverGrammar(parseAssignmentExpression);expr=new WrappingNode(startToken).finishAssignmentExpression(token.value,expr,right);firstCoverInitializedNameError=null;}
return expr;}
function parseExpression(){var expr,startToken=lookahead,expressions;expr=isolateCoverGrammar(parseAssignmentExpression);if(match(',')){expressions=[expr];while(startIndex<length){if(!match(',')){break;}
lex();expressions.push(isolateCoverGrammar(parseAssignmentExpression));}
expr=new WrappingNode(startToken).finishSequenceExpression(expressions);}
return expr;}
function parseStatementListItem(){if(lookahead.type===Token.Keyword){switch(lookahead.value){case'export':if(state.sourceType!=='module'){tolerateUnexpectedToken(lookahead,Messages.IllegalExportDeclaration);}
return parseExportDeclaration();case'import':if(state.sourceType!=='module'){tolerateUnexpectedToken(lookahead,Messages.IllegalImportDeclaration);}
return parseImportDeclaration();case'const':return parseLexicalDeclaration({inFor:false});case'function':return parseFunctionDeclaration(new Node());case'class':return parseClassDeclaration();}}
if(matchKeyword('let')&&isLexicalDeclaration()){return parseLexicalDeclaration({inFor:false});}
return parseStatement();}
function parseStatementList(){var list=[];while(startIndex<length){if(match('}')){break;}
list.push(parseStatementListItem());}
return list;}
function parseBlock(){var block,node=new Node();expect('{');block=parseStatementList();expect('}');return node.finishBlockStatement(block);}
function parseVariableIdentifier(kind){var token,node=new Node();token=lex();if(token.type===Token.Keyword&&token.value==='yield'){if(strict){tolerateUnexpectedToken(token,Messages.StrictReservedWord);}if(!state.allowYield){throwUnexpectedToken(token);}}else if(token.type!==Token.Identifier){if(strict&&token.type===Token.Keyword&&isStrictModeReservedWord(token.value)){tolerateUnexpectedToken(token,Messages.StrictReservedWord);}else{if(strict||token.value!=='let'||kind!=='var'){throwUnexpectedToken(token);}}}else if(state.sourceType==='module'&&token.type===Token.Identifier&&token.value==='await'){tolerateUnexpectedToken(token);}
return node.finishIdentifier(token.value);}
function parseVariableDeclaration(options){var init=null,id,node=new Node(),params=[];id=parsePattern(params,'var');if(strict&&isRestrictedWord(id.name)){tolerateError(Messages.StrictVarName);}
if(match('=')){lex();init=isolateCoverGrammar(parseAssignmentExpression);}else if(id.type!==Syntax.Identifier&&!options.inFor){expect('=');}
return node.finishVariableDeclarator(id,init);}
function parseVariableDeclarationList(options){var list=[];do{list.push(parseVariableDeclaration({inFor:options.inFor}));if(!match(',')){break;}
lex();}while(startIndex<length);return list;}
function parseVariableStatement(node){var declarations;expectKeyword('var');declarations=parseVariableDeclarationList({inFor:false});consumeSemicolon();return node.finishVariableDeclaration(declarations);}
function parseLexicalBinding(kind,options){var init=null,id,node=new Node(),params=[];id=parsePattern(params,kind);if(strict&&id.type===Syntax.Identifier&&isRestrictedWord(id.name)){tolerateError(Messages.StrictVarName);}
if(kind==='const'){if(!matchKeyword('in')&&!matchContextualKeyword('of')){expect('=');init=isolateCoverGrammar(parseAssignmentExpression);}}else if((!options.inFor&&id.type!==Syntax.Identifier)||match('=')){expect('=');init=isolateCoverGrammar(parseAssignmentExpression);}
return node.finishVariableDeclarator(id,init);}
function parseBindingList(kind,options){var list=[];do{list.push(parseLexicalBinding(kind,options));if(!match(',')){break;}
lex();}while(startIndex<length);return list;}
function tokenizerState(){return{index:index,lineNumber:lineNumber,lineStart:lineStart,hasLineTerminator:hasLineTerminator,lastIndex:lastIndex,lastLineNumber:lastLineNumber,lastLineStart:lastLineStart,startIndex:startIndex,startLineNumber:startLineNumber,startLineStart:startLineStart,lookahead:lookahead,tokenCount:extra.tokens?extra.tokens.length:0};}
function resetTokenizerState(ts){index=ts.index;lineNumber=ts.lineNumber;lineStart=ts.lineStart;hasLineTerminator=ts.hasLineTerminator;lastIndex=ts.lastIndex;lastLineNumber=ts.lastLineNumber;lastLineStart=ts.lastLineStart;startIndex=ts.startIndex;startLineNumber=ts.startLineNumber;startLineStart=ts.startLineStart;lookahead=ts.lookahead;if(extra.tokens){extra.tokens.splice(ts.tokenCount,extra.tokens.length);}}
function isLexicalDeclaration(){var lexical,ts;ts=tokenizerState();lex();lexical=(lookahead.type===Token.Identifier)||match('[')||match('{')||matchKeyword('let')||matchKeyword('yield');resetTokenizerState(ts);return lexical;}
function parseLexicalDeclaration(options){var kind,declarations,node=new Node();kind=lex().value;assert(kind==='let'||kind==='const','Lexical declaration must be either let or const');declarations=parseBindingList(kind,options);consumeSemicolon();return node.finishLexicalDeclaration(declarations,kind);}
function parseRestElement(params){var param,node=new Node();lex();if(match('{')){throwError(Messages.ObjectPatternAsRestParameter);}
params.push(lookahead);param=parseVariableIdentifier();if(match('=')){throwError(Messages.DefaultRestParameter);}
if(!match(')')){throwError(Messages.ParameterAfterRestParameter);}
return node.finishRestElement(param);}
function parseEmptyStatement(node){expect(';');return node.finishEmptyStatement();}
function parseExpressionStatement(node){var expr=parseExpression();consumeSemicolon();return node.finishExpressionStatement(expr);}
function parseIfStatement(node){var test,consequent,alternate;expectKeyword('if');expect('(');test=parseExpression();expect(')');consequent=parseStatement();if(matchKeyword('else')){lex();alternate=parseStatement();}else{alternate=null;}
return node.finishIfStatement(test,consequent,alternate);}
function parseDoWhileStatement(node){var body,test,oldInIteration;expectKeyword('do');oldInIteration=state.inIteration;state.inIteration=true;body=parseStatement();state.inIteration=oldInIteration;expectKeyword('while');expect('(');test=parseExpression();expect(')');if(match(';')){lex();}
return node.finishDoWhileStatement(body,test);}
function parseWhileStatement(node){var test,body,oldInIteration;expectKeyword('while');expect('(');test=parseExpression();expect(')');oldInIteration=state.inIteration;state.inIteration=true;body=parseStatement();state.inIteration=oldInIteration;return node.finishWhileStatement(test,body);}
function parseForStatement(node){var init,forIn,initSeq,initStartToken,test,update,left,right,kind,declarations,body,oldInIteration,previousAllowIn=state.allowIn;init=test=update=null;forIn=true;expectKeyword('for');expect('(');if(match(';')){lex();}else{if(matchKeyword('var')){init=new Node();lex();state.allowIn=false;declarations=parseVariableDeclarationList({inFor:true});state.allowIn=previousAllowIn;if(declarations.length===1&&matchKeyword('in')){init=init.finishVariableDeclaration(declarations);lex();left=init;right=parseExpression();init=null;}else if(declarations.length===1&&declarations[0].init===null&&matchContextualKeyword('of')){init=init.finishVariableDeclaration(declarations);lex();left=init;right=parseAssignmentExpression();init=null;forIn=false;}else{init=init.finishVariableDeclaration(declarations);expect(';');}}else if(matchKeyword('const')||matchKeyword('let')){init=new Node();kind=lex().value;if(!strict&&lookahead.value==='in'){init=init.finishIdentifier(kind);lex();left=init;right=parseExpression();init=null;}else{state.allowIn=false;declarations=parseBindingList(kind,{inFor:true});state.allowIn=previousAllowIn;if(declarations.length===1&&declarations[0].init===null&&matchKeyword('in')){init=init.finishLexicalDeclaration(declarations,kind);lex();left=init;right=parseExpression();init=null;}else if(declarations.length===1&&declarations[0].init===null&&matchContextualKeyword('of')){init=init.finishLexicalDeclaration(declarations,kind);lex();left=init;right=parseAssignmentExpression();init=null;forIn=false;}else{consumeSemicolon();init=init.finishLexicalDeclaration(declarations,kind);}}}else{initStartToken=lookahead;state.allowIn=false;init=inheritCoverGrammar(parseAssignmentExpression);state.allowIn=previousAllowIn;if(matchKeyword('in')){if(!isAssignmentTarget){tolerateError(Messages.InvalidLHSInForIn);}
lex();reinterpretExpressionAsPattern(init);left=init;right=parseExpression();init=null;}else if(matchContextualKeyword('of')){if(!isAssignmentTarget){tolerateError(Messages.InvalidLHSInForLoop);}
lex();reinterpretExpressionAsPattern(init);left=init;right=parseAssignmentExpression();init=null;forIn=false;}else{if(match(',')){initSeq=[init];while(match(',')){lex();initSeq.push(isolateCoverGrammar(parseAssignmentExpression));}
init=new WrappingNode(initStartToken).finishSequenceExpression(initSeq);}
expect(';');}}}
if(typeof left==='undefined'){if(!match(';')){test=parseExpression();}
expect(';');if(!match(')')){update=parseExpression();}}
expect(')');oldInIteration=state.inIteration;state.inIteration=true;body=isolateCoverGrammar(parseStatement);state.inIteration=oldInIteration;return(typeof left==='undefined')?node.finishForStatement(init,test,update,body):forIn?node.finishForInStatement(left,right,body):node.finishForOfStatement(left,right,body);}
function parseContinueStatement(node){var label=null,key;expectKeyword('continue');if(source.charCodeAt(startIndex)===0x3B){lex();if(!state.inIteration){throwError(Messages.IllegalContinue);}
return node.finishContinueStatement(null);}
if(hasLineTerminator){if(!state.inIteration){throwError(Messages.IllegalContinue);}
return node.finishContinueStatement(null);}
if(lookahead.type===Token.Identifier){label=parseVariableIdentifier();key='$'+label.name;if(!Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError(Messages.UnknownLabel,label.name);}}
consumeSemicolon();if(label===null&&!state.inIteration){throwError(Messages.IllegalContinue);}
return node.finishContinueStatement(label);}
function parseBreakStatement(node){var label=null,key;expectKeyword('break');if(source.charCodeAt(lastIndex)===0x3B){lex();if(!(state.inIteration||state.inSwitch)){throwError(Messages.IllegalBreak);}
return node.finishBreakStatement(null);}
if(hasLineTerminator){if(!(state.inIteration||state.inSwitch)){throwError(Messages.IllegalBreak);}}else if(lookahead.type===Token.Identifier){label=parseVariableIdentifier();key='$'+label.name;if(!Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError(Messages.UnknownLabel,label.name);}}
consumeSemicolon();if(label===null&&!(state.inIteration||state.inSwitch)){throwError(Messages.IllegalBreak);}
return node.finishBreakStatement(label);}
function parseReturnStatement(node){var argument=null;expectKeyword('return');if(!state.inFunctionBody){tolerateError(Messages.IllegalReturn);}
if(source.charCodeAt(lastIndex)===0x20){if(isIdentifierStart(source.charCodeAt(lastIndex+1))){argument=parseExpression();consumeSemicolon();return node.finishReturnStatement(argument);}}
if(hasLineTerminator){return node.finishReturnStatement(null);}
if(!match(';')){if(!match('}')&&lookahead.type!==Token.EOF){argument=parseExpression();}}
consumeSemicolon();return node.finishReturnStatement(argument);}
function parseWithStatement(node){var object,body;if(strict){tolerateError(Messages.StrictModeWith);}
expectKeyword('with');expect('(');object=parseExpression();expect(')');body=parseStatement();return node.finishWithStatement(object,body);}
function parseSwitchCase(){var test,consequent=[],statement,node=new Node();if(matchKeyword('default')){lex();test=null;}else{expectKeyword('case');test=parseExpression();}
expect(':');while(startIndex<length){if(match('}')||matchKeyword('default')||matchKeyword('case')){break;}
statement=parseStatementListItem();consequent.push(statement);}
return node.finishSwitchCase(test,consequent);}
function parseSwitchStatement(node){var discriminant,cases,clause,oldInSwitch,defaultFound;expectKeyword('switch');expect('(');discriminant=parseExpression();expect(')');expect('{');cases=[];if(match('}')){lex();return node.finishSwitchStatement(discriminant,cases);}
oldInSwitch=state.inSwitch;state.inSwitch=true;defaultFound=false;while(startIndex<length){if(match('}')){break;}
clause=parseSwitchCase();if(clause.test===null){if(defaultFound){throwError(Messages.MultipleDefaultsInSwitch);}
defaultFound=true;}
cases.push(clause);}
state.inSwitch=oldInSwitch;expect('}');return node.finishSwitchStatement(discriminant,cases);}
function parseThrowStatement(node){var argument;expectKeyword('throw');if(hasLineTerminator){throwError(Messages.NewlineAfterThrow);}
argument=parseExpression();consumeSemicolon();return node.finishThrowStatement(argument);}
function parseCatchClause(){var param,params=[],paramMap={},key,i,body,node=new Node();expectKeyword('catch');expect('(');if(match(')')){throwUnexpectedToken(lookahead);}
param=parsePattern(params);for(i=0;i<params.length;i++){key='$'+params[i].value;if(Object.prototype.hasOwnProperty.call(paramMap,key)){tolerateError(Messages.DuplicateBinding,params[i].value);}
paramMap[key]=true;}
if(strict&&isRestrictedWord(param.name)){tolerateError(Messages.StrictCatchVariable);}
expect(')');body=parseBlock();return node.finishCatchClause(param,body);}
function parseTryStatement(node){var block,handler=null,finalizer=null;expectKeyword('try');block=parseBlock();if(matchKeyword('catch')){handler=parseCatchClause();}
if(matchKeyword('finally')){lex();finalizer=parseBlock();}
if(!handler&&!finalizer){throwError(Messages.NoCatchOrFinally);}
return node.finishTryStatement(block,handler,finalizer);}
function parseDebuggerStatement(node){expectKeyword('debugger');consumeSemicolon();return node.finishDebuggerStatement();}
function parseStatement(){var type=lookahead.type,expr,labeledBody,key,node;if(type===Token.EOF){throwUnexpectedToken(lookahead);}
if(type===Token.Punctuator&&lookahead.value==='{'){return parseBlock();}
isAssignmentTarget=isBindingElement=true;node=new Node();if(type===Token.Punctuator){switch(lookahead.value){case';':return parseEmptyStatement(node);case'(':return parseExpressionStatement(node);default:break;}}else if(type===Token.Keyword){switch(lookahead.value){case'break':return parseBreakStatement(node);case'continue':return parseContinueStatement(node);case'debugger':return parseDebuggerStatement(node);case'do':return parseDoWhileStatement(node);case'for':return parseForStatement(node);case'function':return parseFunctionDeclaration(node);case'if':return parseIfStatement(node);case'return':return parseReturnStatement(node);case'switch':return parseSwitchStatement(node);case'throw':return parseThrowStatement(node);case'try':return parseTryStatement(node);case'var':return parseVariableStatement(node);case'while':return parseWhileStatement(node);case'with':return parseWithStatement(node);default:break;}}
expr=parseExpression();if((expr.type===Syntax.Identifier)&&match(':')){lex();key='$'+expr.name;if(Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError(Messages.Redeclaration,'Label',expr.name);}
state.labelSet[key]=true;labeledBody=parseStatement();delete state.labelSet[key];return node.finishLabeledStatement(expr,labeledBody);}
consumeSemicolon();return node.finishExpressionStatement(expr);}
function parseFunctionSourceElements(){var statement,body=[],token,directive,firstRestricted,oldLabelSet,oldInIteration,oldInSwitch,oldInFunctionBody,oldParenthesisCount,node=new Node();expect('{');while(startIndex<length){if(lookahead.type!==Token.StringLiteral){break;}
token=lookahead;statement=parseStatementListItem();body.push(statement);if(statement.expression.type!==Syntax.Literal){break;}
directive=source.slice(token.start+1,token.end-1);if(directive==='use strict'){strict=true;if(firstRestricted){tolerateUnexpectedToken(firstRestricted,Messages.StrictOctalLiteral);}}else{if(!firstRestricted&&token.octal){firstRestricted=token;}}}
oldLabelSet=state.labelSet;oldInIteration=state.inIteration;oldInSwitch=state.inSwitch;oldInFunctionBody=state.inFunctionBody;oldParenthesisCount=state.parenthesizedCount;state.labelSet={};state.inIteration=false;state.inSwitch=false;state.inFunctionBody=true;state.parenthesizedCount=0;while(startIndex<length){if(match('}')){break;}
body.push(parseStatementListItem());}
expect('}');state.labelSet=oldLabelSet;state.inIteration=oldInIteration;state.inSwitch=oldInSwitch;state.inFunctionBody=oldInFunctionBody;state.parenthesizedCount=oldParenthesisCount;return node.finishBlockStatement(body);}
function validateParam(options,param,name){var key='$'+name;if(strict){if(isRestrictedWord(name)){options.stricted=param;options.message=Messages.StrictParamName;}
if(Object.prototype.hasOwnProperty.call(options.paramSet,key)){options.stricted=param;options.message=Messages.StrictParamDupe;}}else if(!options.firstRestricted){if(isRestrictedWord(name)){options.firstRestricted=param;options.message=Messages.StrictParamName;}else if(isStrictModeReservedWord(name)){options.firstRestricted=param;options.message=Messages.StrictReservedWord;}else if(Object.prototype.hasOwnProperty.call(options.paramSet,key)){options.stricted=param;options.message=Messages.StrictParamDupe;}}
options.paramSet[key]=true;}
function parseParam(options){var token,param,params=[],i,def;token=lookahead;if(token.value==='...'){param=parseRestElement(params);validateParam(options,param.argument,param.argument.name);options.params.push(param);options.defaults.push(null);return false;}
param=parsePatternWithDefault(params);for(i=0;i<params.length;i++){validateParam(options,params[i],params[i].value);}
if(param.type===Syntax.AssignmentPattern){def=param.right;param=param.left;++options.defaultCount;}
options.params.push(param);options.defaults.push(def);return!match(')');}
function parseParams(firstRestricted){var options;options={params:[],defaultCount:0,defaults:[],firstRestricted:firstRestricted};expect('(');if(!match(')')){options.paramSet={};while(startIndex<length){if(!parseParam(options)){break;}
expect(',');}}
expect(')');if(options.defaultCount===0){options.defaults=[];}
return{params:options.params,defaults:options.defaults,stricted:options.stricted,firstRestricted:options.firstRestricted,message:options.message};}
function parseFunctionDeclaration(node,identifierIsOptional){var id=null,params=[],defaults=[],body,token,stricted,tmp,firstRestricted,message,previousStrict,isGenerator,previousAllowYield;previousAllowYield=state.allowYield;expectKeyword('function');isGenerator=match('*');if(isGenerator){lex();}
if(!identifierIsOptional||!match('(')){token=lookahead;id=parseVariableIdentifier();if(strict){if(isRestrictedWord(token.value)){tolerateUnexpectedToken(token,Messages.StrictFunctionName);}}else{if(isRestrictedWord(token.value)){firstRestricted=token;message=Messages.StrictFunctionName;}else if(isStrictModeReservedWord(token.value)){firstRestricted=token;message=Messages.StrictReservedWord;}}}
state.allowYield=!isGenerator;tmp=parseParams(firstRestricted);params=tmp.params;defaults=tmp.defaults;stricted=tmp.stricted;firstRestricted=tmp.firstRestricted;if(tmp.message){message=tmp.message;}
previousStrict=strict;body=parseFunctionSourceElements();if(strict&&firstRestricted){throwUnexpectedToken(firstRestricted,message);}
if(strict&&stricted){tolerateUnexpectedToken(stricted,message);}
strict=previousStrict;state.allowYield=previousAllowYield;return node.finishFunctionDeclaration(id,params,defaults,body,isGenerator);}
function parseFunctionExpression(){var token,id=null,stricted,firstRestricted,message,tmp,params=[],defaults=[],body,previousStrict,node=new Node(),isGenerator,previousAllowYield;previousAllowYield=state.allowYield;expectKeyword('function');isGenerator=match('*');if(isGenerator){lex();}
state.allowYield=!isGenerator;if(!match('(')){token=lookahead;id=(!strict&&!isGenerator&&matchKeyword('yield'))?parseNonComputedProperty():parseVariableIdentifier();if(strict){if(isRestrictedWord(token.value)){tolerateUnexpectedToken(token,Messages.StrictFunctionName);}}else{if(isRestrictedWord(token.value)){firstRestricted=token;message=Messages.StrictFunctionName;}else if(isStrictModeReservedWord(token.value)){firstRestricted=token;message=Messages.StrictReservedWord;}}}
tmp=parseParams(firstRestricted);params=tmp.params;defaults=tmp.defaults;stricted=tmp.stricted;firstRestricted=tmp.firstRestricted;if(tmp.message){message=tmp.message;}
previousStrict=strict;body=parseFunctionSourceElements();if(strict&&firstRestricted){throwUnexpectedToken(firstRestricted,message);}
if(strict&&stricted){tolerateUnexpectedToken(stricted,message);}
strict=previousStrict;state.allowYield=previousAllowYield;return node.finishFunctionExpression(id,params,defaults,body,isGenerator);}
function parseClassBody(){var classBody,token,isStatic,hasConstructor=false,body,method,computed,key;classBody=new Node();expect('{');body=[];while(!match('}')){if(match(';')){lex();}else{method=new Node();token=lookahead;isStatic=false;computed=match('[');if(match('*')){lex();}else{key=parseObjectPropertyKey();if(key.name==='static'&&(lookaheadPropertyName()||match('*'))){token=lookahead;isStatic=true;computed=match('[');if(match('*')){lex();}else{key=parseObjectPropertyKey();}}}
method=tryParseMethodDefinition(token,key,computed,method);if(method){method['static']=isStatic;if(method.kind==='init'){method.kind='method';}
if(!isStatic){if(!method.computed&&(method.key.name||method.key.value.toString())==='constructor'){if(method.kind!=='method'||!method.method||method.value.generator){throwUnexpectedToken(token,Messages.ConstructorSpecialMethod);}
if(hasConstructor){throwUnexpectedToken(token,Messages.DuplicateConstructor);}else{hasConstructor=true;}
method.kind='constructor';}}else{if(!method.computed&&(method.key.name||method.key.value.toString())==='prototype'){throwUnexpectedToken(token,Messages.StaticPrototype);}}
method.type=Syntax.MethodDefinition;delete method.method;delete method.shorthand;body.push(method);}else{throwUnexpectedToken(lookahead);}}}
lex();return classBody.finishClassBody(body);}
function parseClassDeclaration(identifierIsOptional){var id=null,superClass=null,classNode=new Node(),classBody,previousStrict=strict;strict=true;expectKeyword('class');if(!identifierIsOptional||lookahead.type===Token.Identifier){id=parseVariableIdentifier();}
if(matchKeyword('extends')){lex();superClass=isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);}
classBody=parseClassBody();strict=previousStrict;return classNode.finishClassDeclaration(id,superClass,classBody);}
function parseClassExpression(){var id=null,superClass=null,classNode=new Node(),classBody,previousStrict=strict;strict=true;expectKeyword('class');if(lookahead.type===Token.Identifier){id=parseVariableIdentifier();}
if(matchKeyword('extends')){lex();superClass=isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);}
classBody=parseClassBody();strict=previousStrict;return classNode.finishClassExpression(id,superClass,classBody);}
function parseModuleSpecifier(){var node=new Node();if(lookahead.type!==Token.StringLiteral){throwError(Messages.InvalidModuleSpecifier);}
return node.finishLiteral(lex());}
function parseExportSpecifier(){var exported,local,node=new Node(),def;if(matchKeyword('default')){def=new Node();lex();local=def.finishIdentifier('default');}else{local=parseVariableIdentifier();}
if(matchContextualKeyword('as')){lex();exported=parseNonComputedProperty();}
return node.finishExportSpecifier(local,exported);}
function parseExportNamedDeclaration(node){var declaration=null,isExportFromIdentifier,src=null,specifiers=[];if(lookahead.type===Token.Keyword){switch(lookahead.value){case'let':case'const':declaration=parseLexicalDeclaration({inFor:false});return node.finishExportNamedDeclaration(declaration,specifiers,null);case'var':case'class':case'function':declaration=parseStatementListItem();return node.finishExportNamedDeclaration(declaration,specifiers,null);}}
expect('{');while(!match('}')){isExportFromIdentifier=isExportFromIdentifier||matchKeyword('default');specifiers.push(parseExportSpecifier());if(!match('}')){expect(',');if(match('}')){break;}}}
expect('}');if(matchContextualKeyword('from')){lex();src=parseModuleSpecifier();consumeSemicolon();}else if(isExportFromIdentifier){throwError(lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value);}else{consumeSemicolon();}
return node.finishExportNamedDeclaration(declaration,specifiers,src);}
function parseExportDefaultDeclaration(node){var declaration=null,expression=null;expectKeyword('default');if(matchKeyword('function')){declaration=parseFunctionDeclaration(new Node(),true);return node.finishExportDefaultDeclaration(declaration);}
if(matchKeyword('class')){declaration=parseClassDeclaration(true);return node.finishExportDefaultDeclaration(declaration);}
if(matchContextualKeyword('from')){throwError(Messages.UnexpectedToken,lookahead.value);}
if(match('{')){expression=parseObjectInitializer();}else if(match('[')){expression=parseArrayInitializer();}else{expression=parseAssignmentExpression();}
consumeSemicolon();return node.finishExportDefaultDeclaration(expression);}
function parseExportAllDeclaration(node){var src;expect('*');if(!matchContextualKeyword('from')){throwError(lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value);}
lex();src=parseModuleSpecifier();consumeSemicolon();return node.finishExportAllDeclaration(src);}
function parseExportDeclaration(){var node=new Node();if(state.inFunctionBody){throwError(Messages.IllegalExportDeclaration);}
expectKeyword('export');if(matchKeyword('default')){return parseExportDefaultDeclaration(node);}
if(match('*')){return parseExportAllDeclaration(node);}
return parseExportNamedDeclaration(node);}
function parseImportSpecifier(){var local,imported,node=new Node();imported=parseNonComputedProperty();if(matchContextualKeyword('as')){lex();local=parseVariableIdentifier();}
return node.finishImportSpecifier(local,imported);}
function parseNamedImports(){var specifiers=[];expect('{');while(!match('}')){specifiers.push(parseImportSpecifier());if(!match('}')){expect(',');if(match('}')){break;}}}
expect('}');return specifiers;}
function parseImportDefaultSpecifier(){var local,node=new Node();local=parseNonComputedProperty();return node.finishImportDefaultSpecifier(local);}
function parseImportNamespaceSpecifier(){var local,node=new Node();expect('*');if(!matchContextualKeyword('as')){throwError(Messages.NoAsAfterImportNamespace);}
lex();local=parseNonComputedProperty();return node.finishImportNamespaceSpecifier(local);}
function parseImportDeclaration(){var specifiers=[],src,node=new Node();if(state.inFunctionBody){throwError(Messages.IllegalImportDeclaration);}
expectKeyword('import');if(lookahead.type===Token.StringLiteral){src=parseModuleSpecifier();}else{if(match('{')){specifiers=specifiers.concat(parseNamedImports());}else if(match('*')){specifiers.push(parseImportNamespaceSpecifier());}else if(isIdentifierName(lookahead)&&!matchKeyword('default')){specifiers.push(parseImportDefaultSpecifier());if(match(',')){lex();if(match('*')){specifiers.push(parseImportNamespaceSpecifier());}else if(match('{')){specifiers=specifiers.concat(parseNamedImports());}else{throwUnexpectedToken(lookahead);}}}else{throwUnexpectedToken(lex());}
if(!matchContextualKeyword('from')){throwError(lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value);}
lex();src=parseModuleSpecifier();}
consumeSemicolon();return node.finishImportDeclaration(specifiers,src);}
function parseScriptBody(){var statement,body=[],token,directive,firstRestricted;while(startIndex<length){token=lookahead;if(token.type!==Token.StringLiteral){break;}
statement=parseStatementListItem();body.push(statement);if(statement.expression.type!==Syntax.Literal){break;}
directive=source.slice(token.start+1,token.end-1);if(directive==='use strict'){strict=true;if(firstRestricted){tolerateUnexpectedToken(firstRestricted,Messages.StrictOctalLiteral);}}else{if(!firstRestricted&&token.octal){firstRestricted=token;}}}
while(startIndex<length){statement=parseStatementListItem();if(typeof statement==='undefined'){break;}
body.push(statement);}
return body;}
function parseProgram(){var body,node;peek();node=new Node();body=parseScriptBody();return node.finishProgram(body,state.sourceType);}
function filterTokenLocation(){var i,entry,token,tokens=[];for(i=0;i<extra.tokens.length;++i){entry=extra.tokens[i];token={type:entry.type,value:entry.value};if(entry.regex){token.regex={pattern:entry.regex.pattern,flags:entry.regex.flags};}
if(extra.range){token.range=entry.range;}
if(extra.loc){token.loc=entry.loc;}
tokens.push(token);}
extra.tokens=tokens;}
function tokenize(code,options,delegate){var toString,tokens;toString=String;if(typeof code!=='string'&&!(code instanceof String)){code=toString(code);}
source=code;index=0;lineNumber=(source.length>0)?1:0;lineStart=0;startIndex=index;startLineNumber=lineNumber;startLineStart=lineStart;length=source.length;lookahead=null;state={allowIn:true,allowYield:true,labelSet:{},inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1,curlyStack:[]};extra={};options=options||{};options.tokens=true;extra.tokens=[];extra.tokenValues=[];extra.tokenize=true;extra.delegate=delegate;extra.openParenToken=-1;extra.openCurlyToken=-1;extra.range=(typeof options.range==='boolean')&&options.range;extra.loc=(typeof options.loc==='boolean')&&options.loc;if(typeof options.comment==='boolean'&&options.comment){extra.comments=[];}
if(typeof options.tolerant==='boolean'&&options.tolerant){extra.errors=[];}
try{peek();if(lookahead.type===Token.EOF){return extra.tokens;}
lex();while(lookahead.type!==Token.EOF){try{lex();}catch(lexError){if(extra.errors){recordError(lexError);break;}else{throw lexError;}}}
tokens=extra.tokens;if(typeof extra.errors!=='undefined'){tokens.errors=extra.errors;}}catch(e){throw e;}finally{extra={};}
return tokens;}
function parse(code,options){var program,toString;toString=String;if(typeof code!=='string'&&!(code instanceof String)){code=toString(code);}
source=code;index=0;lineNumber=(source.length>0)?1:0;lineStart=0;startIndex=index;startLineNumber=lineNumber;startLineStart=lineStart;length=source.length;lookahead=null;state={allowIn:true,allowYield:true,labelSet:{},inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1,curlyStack:[],sourceType:'script'};strict=false;extra={};if(typeof options!=='undefined'){extra.range=(typeof options.range==='boolean')&&options.range;extra.loc=(typeof options.loc==='boolean')&&options.loc;extra.attachComment=(typeof options.attachComment==='boolean')&&options.attachComment;if(extra.loc&&options.source!==null&&options.source!==undefined){extra.source=toString(options.source);}
if(typeof options.tokens==='boolean'&&options.tokens){extra.tokens=[];}
if(typeof options.comment==='boolean'&&options.comment){extra.comments=[];}
if(typeof options.tolerant==='boolean'&&options.tolerant){extra.errors=[];}
if(extra.attachComment){extra.range=true;extra.comments=[];extra.bottomRightStack=[];extra.trailingComments=[];extra.leadingComments=[];}
if(options.sourceType==='module'){state.sourceType=options.sourceType;strict=true;}}
try{program=parseProgram();if(typeof extra.comments!=='undefined'){program.comments=extra.comments;}
if(typeof extra.tokens!=='undefined'){filterTokenLocation();program.tokens=extra.tokens;}
if(typeof extra.errors!=='undefined'){program.errors=extra.errors;}}catch(e){throw e;}finally{extra={};}
return program;}
exports.version='2.7.0';exports.tokenize=tokenize;exports.parse=parse;exports.Syntax=(function(){var name,types={};if(typeof Object.create==='function'){types=Object.create(null);}
for(name in Syntax){if(Syntax.hasOwnProperty(name)){types[name]=Syntax[name];}}
if(typeof Object.freeze==='function'){Object.freeze(types);}
return types;}());}));};BundleModuleCode['jam/sandbox']=function(module,exports){var Json=Require('jam/jsonfn');function sandbox(f,modules,inject,env)
{var p,F,mask,source;mask={mask:undefined,modules:undefined,require:undefined,cp:undefined,f:undefined};for(p in this)
mask[p]=undefined;for(p in modules)
mask[p]=modules[p];if(env)for(p in env)
mask[p]=env[p];if(typeof f=='function')source=f.toString(true);else source=f;if(inject.cp){var regex1=/while[\s]*\(([^\)]+)\)/g;var regex2=/for[\s]*\(([^\)]+)\)/g;var regex3=/function([^\{]+)\{/g;source=source.replace(regex1,"while (($1) && "+inject.cp+"())").replace(regex2,"for ($1,"+inject.cp+"())").replace(regex3,"function $1{"+inject.cp+"();");}
if(inject.rt){var regex4=/catch[\s]*\([\s]*([a-zA-Z0-9_]+)[\s]*\)[\s]*\{/g;source=source.replace(regex4,'catch ($1) {'+inject.rt+'($1);');}
function evalInContext(context,js){return eval('with(context) { "use strict"; F='+js+' }');}
mask.eval=undefined;evalInContext(mask,source);return{fun:F,mask:mask,size:source.length};}
function Sandbox(f,modules,inject,env){var p,mask={},_mask='process';for(p in global){if(p.indexOf('Array')>0)continue;_mask=_mask+','+p;}
for(p in modules)
mask[p]=modules[p];if(env)for(p in env)
mask[p]=env[p];if(typeof f=='function')source=f.toString(true);else source=f;if(inject.cp){var regex1=/while[\s]*\(([^\)]+)\)/g;var regex2=/for[\s]*\(([^\)]+)\)/g;var regex3=/function([^\{]+)\{/g;source=source.replace(regex1,"while (($1) && "+inject.cp+"())").replace(regex2,"for ($1,"+inject.cp+"())").replace(regex3,"function $1{"+inject.cp+"();");}
if(inject.rt){var regex4=/catch[\s]*\([\s]*([a-zA-Z0-9_]+)[\s]*\)[\s]*\{/g;source=source.replace(regex4,'catch ($1) {'+inject.rt+'($1);');}
mask.eval=undefined;_mask+=',eval'
mask.require=undefined;_mask+=',require'
var F=new Function(_mask,'"use strict"; with(this) { f=('+source+').bind(this)} return f').bind(mask);return{fun:F(),mask:mask,_mask:_mask};}
function sandboxObject(obj,mask){var objS;if(typeof obj=='object')obj=Json.stringify(obj);return Json.parse(obj,mask);}
module.exports={sandbox:sandbox,sandboxObject:sandboxObject,Sandbox:Sandbox}
module.exports=function(){return sandbox}};BundleModuleCode['jam/sig']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var options={debug:{},version:'1.5.3'}
function lookup(node,destnode){var chan,url;if(node.connections.ip&&node.connections.ip.lookup){url=node.connections.ip.lookup(destnode);if(url)return{chan:node.connections.ip,url:url};}
if(node.connections.path&&node.connections.path._connected){if(node.connections.path._connected.indexOf(destnode)!=-1){return{chan:node.connections.path,url:Aios.DIR.NODE(destnode)}}}}
var sig={broadcast:function(ac,range,sig,arg){var delivered=0;if(!Comp.obj.isString(ac)){current.error='broadcast, invalid class '+ac;throw'SIGNAL'};if(!Comp.obj.isString(sig)&&!Comp.obj.isNumber(sig)){current.error='broadcast, invalid signal '+sig;throw'SIGNAL'};if(range!=0){current.error='broadcast, invalid range '+range;throw'SIGNAL'};for(var p in current.node.processes.table){var proc=current.node.processes.table[p];if(proc&&proc.agent.ac==ac&&proc.agent.on[sig]){proc.signals.push([sig,arg,current.process.agent.id]);delivered++;}}
return delivered;},send:function(to,sig,arg,from,hop){var p,node,delivered,curtime;var pid=current.node.processes.lookup(to);if(options.debug.send)console.log('sig.send',to,sig,arg,from,hop,pid);if(!Comp.obj.isString(sig)&&!Comp.obj.isNumber(sig)){current.error='send, invalid signal';throw'SIGNAL'};current.node.stats.signal++;if(pid!=none){switch(sig){case'PROC.KILL':Aios.kill(to);return true;}
current.node.processes.table[pid].signals.push([sig,arg,from||current.process.agent.id]);return true;}else{if(current.node.processes.gone[to]){if(options.debug.send)print('sig.send',to,sig,arg,from,hop,current.node.processes.gone[to].dir);curtime=Aios.time()-current.world.lag;current.node.processes.gone[to].timeout=curtime+current.node.TMO*10;return route(current.node.processes.gone[to].dir,to,sig,arg,from||current.process.agent.id);}
if(hop>2)return true;if(current.node.parent){return current.node.parent.handle({to:to,sig:sig,arg:arg,from:from,hop:hop?hop+1:1})}else if(current.node.children){delivered=false;for(p in current.node.children){node=current.node.children[p];delivered=node.handle({to:to,sig:sig,arg:arg,from:from,hop:hop?hop+1:1});if(delivered)break;}
if(delivered)return true;}
if(current.node.signals[to]){curtime=Aios.time()-current.world.lag;current.node.signals[to].timeout=curtime+current.node.TMO*10;return route(current.node.signals[to].dir,to,sig,arg,from||current.process.agent.id);}}
return false;},sendto:function(to,sig,arg,from,node){var delivered=0,i;if(!Comp.obj.isString(sig)&&!Comp.obj.isNumber(sig)){current.error='sendto, invalid signal '+sig;throw'SIGNAL'};if((to.tag||to).indexOf('DIR')!=0){current.error='sendto, invalid destination '+to;throw'SIGNAL'};if(to==Aios.DIR.ORIGIN||(to.delta&&Comp.array.zero(to.delta)||to.node==current.node.id)){if(sig=='TS.SIG'){for(i in arg){Aios.Ts.agent.out(arg[i]);}}else for(var p in current.node.processes.table){var proc=current.node.processes.table[p];if(proc&&proc.agent.on&&proc.agent.on[sig]){proc.signals.push([sig,arg,from||current.process.agent.id,node]);delivered++;}}
return delivered;}else{return route(to,none,sig,arg,current.process.agent.id,node||current.node.id);}},sleep:function(tmo){current.process.suspend(tmo?Aios.time()-current.world.lag+tmo:0);},timer:{add:function(tmo,sig,arg,repeat){if(!Comp.obj.isNumber(tmo)){current.error='timer, invalid timeout '+tmo;throw'SIGNAL'};if(!Comp.obj.isString(sig)){current.error='timer, invalid signal '+sig;throw'SIGNAL'};current.node.timers.push([current.process,(Aios.time()-current.world.lag+tmo),sig,arg,repeat?tmo:0]);return sig;},delete:function(sig){current.node.timers=current.node.timers.filter(function(t){return t[2]!=sig});}},timeout:function(tmo){return Aios.time()-current.world.lag+tmo},wakeup:function(process){if(!process)current.process.wakeup();else process.wakeup();}}
function route(dir,to,sig,arg,from,node){var node1=current.node,chan=none,dest,stat,alive=function(){return 1},sigobj={sig:sig,to:to||dir,from:from,arg:arg,back:Aios.DIR.opposite(dir,true),node:node},msg;switch(dir.tag||dir){case Aios.DIR.NORTH:chan=node1.connections.north;break;case Aios.DIR.SOUTH:chan=node1.connections.south;break;case Aios.DIR.WEST:chan=node1.connections.west;break;case Aios.DIR.EAST:chan=node1.connections.east;break;case Aios.DIR.UP:chan=node1.connections.up;break;case Aios.DIR.DOWN:chan=node1.connections.down;break;case Aios.DIR.NW:chan=node1.connections.nw;break;case Aios.DIR.NE:chan=node1.connections.ne;break;case Aios.DIR.SE:chan=node1.connections.se;break;case Aios.DIR.SW:chan=node1.connections.sw;break;case'DIR.IP':chan=node1.connections.ip;dest=dir.ip;break;case'DIR.DELTA':sigobj.to=Comp.obj.copy(sigobj.to);if(dir.delta[0]>0&&node1.connections.east&&node1.connections.east.status())
sigobj.to.delta[0]--,chan=node1.connections.east;else if(dir.delta[0]<0&&node1.connections.west&&node1.connections.west.status())
sigobj.to.delta[0]++,chan=node1.connections.west;else if(dir.delta[1]>0&&node1.connections.south&&node1.connections.south.status())
sigobj.to.delta[1]--,chan=node1.connections.south;else if(dir.delta[1]<0&&node1.connections.north&&node1.connections.north.status())
sigobj.to.delta[1]++,chan=node1.connections.north;else if(dir.delta[2]>0&&node1.connections.up&&node1.connections.up.status())
sigobj.to.delta[2]--,chan=node1.connections.up;else if(dir.delta[2]<0&&node1.connections.down&&node1.connections.down.status())
sigobj.to.delta[2]++,chan=node1.connections.down;break;case'DIR.PATH':chan=node1.connections.path;dest=dir.path;break;case'DIR.CAP':if(!current.network){current.error='No connection to server '+dir.cap;return false;};chan=node1.connections.dos;dest=Net.Parse.capability(dir.cap).cap;break;case'DIR.NODE':if(node1.connections.range&&node1.connections.range[dir.node]&&node1.connections.range[dir.node].status())
chan=node1.connections.range[dir.node],dest=dir.node;else{dest=lookup(node1,dir.node);if(dest)chan=dest.chan,dest=dest.url;}
break;default:return false;}
switch(dir.tag||dir){case Aios.DIR.NORTH:case Aios.DIR.SOUTH:case Aios.DIR.WEST:case Aios.DIR.EAST:case Aios.DIR.UP:case Aios.DIR.DOWN:case Aios.DIR.NW:case Aios.DIR.NE:case Aios.DIR.SE:case Aios.DIR.SW:sigobj.to=Aios.DIR.ORIGIN;break;}
if(options.debug.route)console.log('sig.route',node1.id,dir,sigobj,chan!=null);if(chan==none||!chan.status(dest)){current.error='No connection to direction '+dir;return false;};node1.stats.signal++;if(Aios.options.fastcopy&&chan.virtual)msg=sigobj;else msg=Aios.Code.toString(sigobj);chan.send({signal:msg,to:dest});return true;}
module.exports={agent:sig,options:options,route:route,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['jam/node']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var Security=Require('jam/security');var current=none;var Aios=none;var options={debug:{},verbose:0,version:'1.13.2'}
function aid(process){return process.agent.id+':'+process.pid}
function min0(a,b){return a==0?b:(b==0?a:Comp.pervasives.min(a,b))};var node=function(options){var self=this;options=checkOptions(options,{});this.options=options;this.id=checkOption(this.options.id,Aios.aidgen());this.position=checkOption(this.options.position,Aios.DIR.ORIGIN);this.type=checkOption(this.options.type,'generic');this.verbose=checkOption(this.options.verbose,0);this.defaultLevel=checkOption(this.options.defaultLevel,Aios.options.LEVEL);this.processes={free:none,max:checkOption(this.options.maxpro,100),table:[],hash:[],top:0,used:0,gone:[]};this.processes.lookup=function(aid){if(self.processes.hash[aid]!=undefined)
return self.processes.hash[aid];else
return none;};this.processes.process=function(aid){if(self.processes.hash[aid]!=_)
return self.processes.table[self.processes.hash[aid]];else
return none;};this.signals=[];this.timers=[];this.connections={north:none,south:none,west:none,east:none};this.ts=Aios.Ts.create({maxn:checkOption(this.options.maxts,8),id:this.id,node:self});this.random={};this.port=Security.Port.unique();this.random[this.port]=Security.Port.unique();this.library={};this.location=null;this.position=options.position;this.stats={cpu:0,create:0,fastcopy:0,fork:0,handled:0,migrate:0,received:0,signal:0,error:0,tsout:0,tsin:0,agents:0,}
this.TMO=checkOption(this.options.TMO,100000);this.timeout=0;Aios.emit('node+',self);};node.prototype.destroy=function(){var p,pro,_node=current.node,self=this;this.connections={};if(this.verbose>2)console.log('node.destroy',this)
current.node=this;for(p in this.processes.table){pro=this.processes.table[p];if(!pro)continue;pro.kill=true;this.unregister(pro);}
this.processes.gone=[];this.ts=none;current.node=_node;if(this.parent){this.parent.children=this.parent.children.filter(function(node){return node!=self});}
if(this.children){this.children.forEach(function(node){node.parent=null;})}
Aios.emit('node-',self);}
node.prototype.export=function(name,code){if(!this.library[name])
this.library[name]=Aios.Code.toString(code);}
node.prototype.getAgent=function(id,ac){var pros=this.getAgentProcess(id,ac);if(pros&&Comp.obj.isArray(pros))
return Comp.array.map(pros,function(pro){return pro.agent});else if(pros)return pros.agent;};node.prototype.getAgentProcess=function(id,ac){var matches=Comp.obj.isRegex(id)?[]:undefined,table=this.processes.table,p;if(!matches&&this.processes.hash[id]!=undefined){p=table[this.processes.hash[id]];if(!ac||p.agent.ac==ac)return p;}
if(typeof id=='number')return table[id];for(var p in table){if(!table[p])continue;if(!matches&&table[p].agent.id==id&&(!ac||table[p].agent.ac==ac))
return table[p];if(matches&&id.test(table[p].agent.id)&&(!ac||table[p].agent.ac==ac))
matches.push(table[p]);}
return matches;};node.prototype.handle=function(msg){var delivered,tmo,curtime=Aios.time()-current.world.lag,_node=current.node,self=this,sigobj=(typeof msg=='string')?Aios.Code.ofString(msg,{}):msg;if(options.debug.handle)console.log('node.handle',this.id,sigobj);if(!sigobj)return;current.node=this;delivered=(Aios.Mobi.DIR.isDir(sigobj.to)?Aios.Sig.agent.sendto:Aios.Sig.agent.send)
(sigobj.to,sigobj.sig,sigobj.arg,sigobj.from,sigobj.to?sigobj.node:sigobj.hop);if(delivered&&sigobj.back){tmo=curtime+this.TMO;this.signals[sigobj.from]={dir:sigobj.back,timeout:tmo};this.timeout=min0(this.timeout,tmo);};this.stats.handled++;current.node=_node;Aios.emit('schedule',self);return delivered;}
node.prototype.import=function(name){var code;if(this.library[name])code=Aios.Code.ofString(this.library[name],current.process.mask);return code;}
node.prototype.info=function(){var self=this,p,obj={};ovj.stats=this.stats;obj.id=this.id;obj.position=this.position;obj.agents={};var update=function(obj){var p;for(p in obj){if(p!='_update')delete obj[p];}
for(p in self.processes.hash){if(self.processes.hash[p]!=_)
obj[p]=self.processes.table[self.processes.hash[p]];};}
obj.agents._update=update;update(obj.agents);obj.signals=this.signals;obj.timers=this.timers;obj.ts=this.ts;obj.connections=this.connections;return obj;}
node.prototype.print=function(summary){var i,blocked,pending,total,ghost=0;var str='==== NODE '+this.id+' ===='+NL;str+='SYSTIME='+Aios.time()+NL;str+='PROCESS TABLE >>'+NL;if(summary){blocked=0;pending=0;total=0;ghost=0;for(i in this.processes.table){if(this.processes.table[i]!=_){total++;if(this.processes.table[i].blocked)blocked++;if(this.processes.table[i].signals.length>0)pending++;if(this.processes.table[i].agent.next==undefined)ghost++;};}
str+=' TOTAL='+total+' BLOCKED='+blocked+' DYING='+ghost+' SIGPEND='+pending+NL;}else{for(i in this.processes.table){if(this.processes.table[i]!=_){str+=' ['+aid(this.processes.table[i])+'] '+'NEXT='+this.processes.table[i].agent.next+' '+
this.processes.table[i].print();};}}
if(this.timers.length>0){str+='TIMER TABLE >>'+NL;for(i in this.timers){str+=' ['+aid(this.timers[i][0])+'] TMO='+this.timers[i][1]+' SIG='+this.timers[i][2]+NL;}}
str+='TUPLE SPACES >>'+NL;if(summary)str+=' '+this.ts.print(summary);else str+=this.ts.print(summary);return str;}
node.prototype.receive=function(msg,start,from){var _process=current.process,_node=current.node,self=this,process,agent;if(options.debug.receive)console.log('node.receive (start='+start+',length='+msg.length+'):\n<'+msg+'>');if(typeof msg!=='object')process=Aios.Code.toCode(msg,this.defaultLevel);else process=Aios.Code.ofObject(msg);if(!process)return;agent=process.agent;agent['self']=agent;this.register(process);this.stats.received++;if(process.dir||process.delta){return;};if((!process.back||process.back.tag=='DIR.IP')&&from&&from.address&&from.port)
process.back=Aios.DIR.IP(from.address+':'+from.port);if(process.back&&process.agent.parent){tmo=Aios.time()-current.world.lag+this.TMO;this.signals[process.agent.parent]={dir:process.back,timeout:tmo};this.timeout=min0(this.timeout,tmo);}
if(process.schedule.length==0){current.node=this;current.process=process;try{if(!start)
agent.next=(typeof agent.trans[agent.next]=='function')?agent.trans[agent.next].call(agent):agent.trans[agent.next];if(process.blocked)throw'BLOCKING';}catch(e){Aios.aios.log('Node.receive: Agent '+agent.id+' ['+agent.ac+'] in transition '+agent.next+' failed:\n'+e+(current.error?' / '+current.error:', in: \n'+Aios.Code.print(agent.trans[agent.next]))+'\nat:\n'+Io.sprintstack(e));this.unregister(process);};current.node=_node;current.process=_process;}}
node.prototype.register=function(process){var i,p,self=this,agent=process.agent;if(this.processes.free==none){loop:for(i in this.processes.table){if(this.processes.table[i]==_){this.processes.free=i;break loop};}}
if(this.processes.free!=none){this.processes.table[this.processes.free]=process;process.pid=this.processes.free;process.agent=agent;this.processes.free=none;}else{this.processes.table[this.processes.top]=process;process.agent=agent;process.pid=this.processes.top;this.processes.top++;}
if(agent.id==undefined)agent.id=Aios.aidgen();this.processes.hash[agent.id]=process.pid;this.processes.used++;this.stats.agents++;if(this.processes.gone[process.agent.id])
this.processes.gone[process.agent.id]=undefined;process.node=this;Aios.emit('agent+',{agent:agent,proc:process,node:self},self);Aios.emit('schedule',self);}
node.prototype.service=function(curtime){var nexttime=0,p,pro,sig;this.ts.service(curtime);if(curtime<this.timeout)return;for(p in this.processes.gone){pro=this.processes.gone[p];if(pro==undefined)continue;if(pro.timeout<curtime){this.processes.gone[p]=undefined;}
else
nexttime=min0(nexttime,pro.timeout);}
for(p in this.signals){sig=this.signals[p];if(sig==undefined)continue;if(sig.timeout<curtime){this.signals[p]=undefined;}
else
nexttime=min0(nexttime,sig.timeout);}
this.timeout=nexttime;}
node.prototype.std_info=function(what){if(what==undefined)return{defaultLevel:this.defaultLevel,id:this.id,location:this.location,position:this.position,type:this.type,}
if(what.agent){}}
node.prototype.std_status=function(what){var data,self=this;if(!what||what=='node')return this.stats;if(what=='agents')return Comp.array.filtermap(this.processes.table,function(pro,index){if(pro)return{index:index,agent:pro.agent.id,blocked:pro.blocked,suspended:pro.suspended,signals:pro.signals.length,next:pro.agent.next,}})
if(what=='links'){data={}
for(var p in this.connections){if(!this.connections[p])continue;if(p=='ip')data.ip=Comp.array.map(this.connections[p].links,function(link){return{ip:link.ip,stats:link.stats(),status:link.status('%'),}})}
return data;}}
node.prototype.unregister=function(process){var i,p,remove,self=this,tmo,agent=process.agent,curtime=Aios.time()-current.world.lag;remove=false;Comp.array.iter(this.timers,function(timer,i){if(timer&&timer[0].pid==process.pid){self.timers[i]=_;remove=true;}});if(remove)
this.timers=Comp.array.filter(this.timers,function(timer){return timer!=undefined;});this.processes.table[process.pid]=_;delete this.processes.hash[agent.id];if(this.processes.free==none)this.processes.free=process.pid;this.ts.cleanup(process);process.pid=none;process.signals=[];process.dead=true;this.processes.used--;this.stats.agents--;if(process.move){tmo=curtime+this.TMO;this.processes.gone[process.agent.id]={dir:process.move,timeout:tmo};this.timeout=min0(this.timeout,tmo);}
Aios.emit('agent-',{agent:agent,node:self,proc:process},self);}
var Node=function(options,setcurrent){var obj=new node(options);if(setcurrent)current.node=obj;return obj;}
module.exports={isNode:function(o){return o instanceof Node},Node:Node,options:options,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['jam/proc']=function(module,exports){var Comp=Require('com/compat');var current=none;var Aios=none;var options={debug:{},version:'1.7.2'}
var PRIO={LOW:0,NORMAL:1,HIGH:2}
var proc=function(properties){this.agent={};this.block=[];this.blocked=false;this.timeout=0;this.runtime=0;this.resources={start:Aios.clock('ms'),consumed:0,memory:0,tuples:0,agents:0,}
this.level=undefined;this.priority=PRIO.NORMAL;this.schedule=[];this.suspended=false;this.suspendedIn=undefined;this.error=none;this.pid=none;this.gid=none;this.id='agent';this.mask={};this.signals=[];this.move=none;this.kill=false;this.dead=false;this.transition=false;this.notransition=false;for(var p in properties){if(properties[p]!=undefined)this[p]=properties[p];}
this.shape=undefined;if(current.world)this.parent=current.world.context;this.node=current.node;}
proc.prototype.callback=function(cb,args){var _process=current.process,_node=current.node,res;current.node=this.node;current.process=this;try{res=cb.apply(this.agent,args||[]);}catch(e){Aios.aios.log('Caught callback error: '+e);}
current.process=_process;current.node=_node;return res;}
proc.prototype.exec=function(){var _process=current.process,_node=current.node,res;current.node=this.node;res=Aios.schedule(this);current.process=_process;current.node=_node;return res;}
proc.prototype.finalize=function(){this.kill=true;this.suspended=false;current.node.unregister(this);}
proc.prototype.fork=function(parameters,level,dirty){var code,_process=current.process,agent=current.process.agent,process_,agent_,p;parameters=parameters||{};current.process.resources.agents++;if(dirty&&level!=undefined)dirty=false;if(level==undefined)level=current.process.mask.privilege();else level=Math.min(current.process.mask.privilege(),level);if(!dirty){code=Aios.Code.forkCode(current.process);process_=Aios.Code.toCode(code,level);}else{process_=Aios.Code.copyProcess(current.process);}
agent_=process_.agent
agent_.id=Aios.aidgen();agent_.parent=current.process.agent.id;process_.init({gid:current.process.pid});current.process=process_;current.node.register(process_);for(p in agent){if(agent[p]===null)agent_[p]=null;}
for(p in parameters){if(Comp.obj.hasProperty(agent_,p))agent_[p]=parameters[p];}
if(!parameters.next)try{agent_.next=(typeof agent_.trans[agent_.next]=='function')?agent_.trans[agent_.next].call(agent_):agent_.trans[agent_.next];}catch(e){process_.kill=true;};this.node.stats.fork++;current.process=_process;return process_;}
proc.prototype.init=function(properties){for(var p in properties){if(this[p]!=undefined)this[p]=properties[p];}}
proc.prototype.print=function(){var str='',agent=this.agent;str='PID='+this.pid+
(this.gid?' GID='+this.gid:'')+
(this.timeout?(' TMO='+this.timeout):'')+
(this.blocked?' BLOCKED':'')+
(this.suspended?' SUSP':'')+
(this.kill?' KILL':'')+
(this.dead?' DEAD':'');if(this.schedule.length>0)str+=' SCHEDULE='+this.schedule.length;if(this.block.length>0)str+=' BLOCK='+this.block.length;if(this.signals.length>0)str+=' SIGNALS('+this.signals.length+'):'+
Comp.printf.list(this.signals,function(s){return s[0]});if(this.transition)str+=' TRANS';if(this.consumed|0)str+=' CONS='+(this.consumed|0);if(agent)str+=' AGENT '+agent.id+' next='+agent.next;return str;}
proc.prototype.suspend=function(timeout,transition,suspendedIn){if(!this.kill&&!this.dead){this.suspended=true;if(timeout!=undefined)this.timeout=timeout;if(transition)this.transition=true;this.suspendedIn=suspendedIn;}}
proc.prototype.update=function(properties){for(var p in properties){this[p]=properties[p];}}
proc.prototype.upgrade=function(level){var aios;switch(level){case undefined:case 0:aios=Aios.aios0;break;case 1:aios=Aios.aios1;break;case 2:aios=Aios.aios2;break;case 3:aios=Aios.aios3;break;default:aios=Aios.aios0;break;}
for(p in aios){this.mask[p]=aios[p];}}
proc.prototype.wakeup=function(immediate){this.suspended=false;this.timeout=0;if(!this.kill&&!this.dead&&(immediate||this.schedule.length==0)){var _process=current.process,_node=current.node;current.node=this.node;if(this.suspendedIn=='ts')this.node.ts.cleanup(this,true);this.suspendedIn=undefined;this.transition=this.schedule.length==0;Aios.schedule(this);current.process=_process;current.node=_node;}else Aios.scheduled++;}
function Proc(properties){var obj=new proc(properties);return obj;}
module.exports={agent:{fork:function fork(parameters){return current.process.fork(parameters);}},isProc:function(o){return o instanceof Proc},Proc:Proc,PRIO:PRIO,current:function(module){current=module.current;Aios=module;},options:options}};BundleModuleCode['jam/ts']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var verbose=false;var options={debug:{},version:'1.11.2',timeout:0,}
function aid(process){return process.agent.id+':'+process.pid}
function log(tsi,process,msg){if(verbose&&process)Aios.aios.log('[TS'+(tsi.i)+':'+current.node.ts.id+'] Ag '
+aid(process)+' '+msg);else if(verbose)Io.log('[TS'+(tsi.i)+':'+current.node.ts.id+'] SYS'+msg);}
function min0(a,b){return a==0?b:(b==0?a:Comp.pervasives.min(a,b))};var addwaiter=function(tsi,waiter){var index,key;if(tsi.waiters.free.length==0){index=tsi.waiters.length;tsi.waiters.push(waiter);}else{index=tsi.waiters.free[0];tsi.waiters[index]=waiter;tsi.waiters.free.shift();}
if(typeof(key=waiter.pat[0])=='string')switch(waiter.op){case'listen':tsi.waiters.hash[key]=index;break;}}
var checkwaiter=function(tsi,tuple,callback){var res,consumed=false,i,waiter;function cb(waiter,res){Aios.CB(waiter.pro,function(){waiter.cb.call(waiter.pro.agent,res)});}
for(i=0;i<tsi.waiters.length;i++){if(!tsi.waiters[i])continue;waiter=tsi.waiters[i];if(!consumed)switch(waiter.op){case'rd':case'rd-all':res=match(tuple,waiter.pat);log(tsi,current.process,' rd waiter? '+res);if(res!=none){cb(waiter,(waiter.op=='rd'?res:[res])),waiter.pro.wakeup();removewaiter(tsi,i);}
break;case'in':case'in-all':res=match(tuple,waiter.pat);log(tsi,current.process,' in waiter? '+res);if(res!=none){cb(waiter,(waiter.op=='in'?res:[res])),waiter.pro.wakeup();consumed=true;removewaiter(tsi,i);}
break;case'listen':res=match(tuple,waiter.pat);log(tsi,current.process,' listen waiter? '+res);if(res!=none){res=waiter.pro.callback(waiter.cb,[res]);if(callback)callback.apply(current.process.agent,[res]);consumed=true;}
break;}else break;}
if(!consumed&&current.node.ts.consumers.length>0){consumed=Comp.array.findmap(current.node.ts.consumers,function(consumer){return consumer(tuple);});}
return consumed;}
var findwaiter=function(tsi,waiter){var i;for(i=0;i<tsi.waiters.length;i++){if(!tsi.waiters[i])continue;if(tsi.waiters[i].pro.pid!=waiter.pro.pid)continue;if(equal(tsi.waiters[i].pat,waiter.pat))return i;}
return;}
var removewaiter=function(tsi,index){var waiter=tsi.waiters[index],_tsi,_index;tsi.waiters[index]=undefined;tsi.waiters.free.push(index);if(waiter.prev){waiter.prev.next=undefined;_tsi=current.node.ts.db[waiter.prev.pat.length];_index=findwaiter(_tsi,waiter.prev);if(_index!=undefined)removewaiter(_tsi,_index);};if(waiter.next){waiter.next.prev=undefined;_tsi=current.node.ts.db[waiter.next.pat.length];_index=findwaiter(_tsi,waiter.next);if(_index!=undefined)removewaiter(_tsi,_index);};}
var count=function(tsi){var data=tsi.data,i,n=0;for(i in data){if(data[i]!=undefined)n++};return n;}
var lookup=function(pat,all){var tsi,nary=pat.length,res=none;if(nary>current.node.ts.n||nary==0)return;tsi=current.node.ts.db[nary];if(!all&&Comp.isString(pat[0])&&tsi.hash[pat[0]]!=undefined){res=match(tsi.data[tsi.hash[pat[0]]],pat);}
if(res==none){res=(all?Comp.array.filtermap:Comp.array.findmap)(tsi.data,function(tuple){if(tuple==_)return none;else return match(tuple,pat);});if(res&&res.length==0)res=none;if(res==none&&current.node.ts.providers.length>0){res=Comp.array.findmap(current.node.ts.providers,function(provider){return provider(pat);});}}
return res;}
var lookupIndex=function(pat,all){var tsi,nary=pat.length,res=none;if(nary>current.node.ts.n||nary==0)return;tsi=current.node.ts.db[nary];if(!all&&Comp.isString(pat[0])&&tsi.hash[pat[0]]!=undefined){res=match(tsi.data[tsi.hash[pat[0]]],pat);if(res!=none)return tsi.hash[pat[0]];}
if(res==none){res=(all?Comp.array.filtermap:Comp.array.findmap)(tsi.data,function(tuple,index){if(tuple==_)return none;else return match(tuple,pat)?index:none;});if(res&&res.length==0)res=none;}
return res;}
var equal=function(x,y){var i;if(x==y)return true;if(Comp.obj.isArray(x)&&Comp.obj.isArray(y)){if(x.length!=y.length)return false;for(i in x){if(x[i]!=y[i])return false;}
return true;}
return false;}
var match1=function(x,y){if(y==any)return true;if(x==y)return true;if((x instanceof Array)&&(y instanceof Array))return match(x,y)!=none;if(y instanceof RegExp&&typeof x=='string'&&y.test(x))return true;return false;}
var match=function(tuple,templ){var i;if(tuple.length!=templ.length)return none;for(i in tuple){if(!match1(tuple[i],templ[i]))return none;};return tuple;}
var remove=function(pat,all){var tsi,nary=pat.length,res=none,removed=false,hashed=_;if(nary>current.node.ts.n||nary==0)return;tsi=current.node.ts.db[nary];if(!all&&Comp.isString(pat[0]))hashed=tsi.hash[pat[0]];if(hashed!=_){res=match(tsi.data[hashed],pat);if(res){removed=true;tsi.data[hashed]=_;tsi.tmo[hashed]=0;if(tsi.free==none)tsi.free=hashed;delete tsi.hash[pat[0]];}}
if(res==none||removed==false){res=(all?Comp.array.filtermap:Comp.array.findmap)(tsi.data,function(tuple,i){if(tuple==_)return none;var res_=match(tuple,pat);if(res_!=none){if(Comp.isString(pat[0])&&tsi.hash[pat[0]]==i){delete tsi.hash[pat[0]];}
tsi.data[i]=_;tsi.tmo[i]=0;if(tsi.free==none)tsi.free=i;return res_;}else return none;});if(res&&res.length==0)res=none;}
return res;}
var ts={alt:function(pats,callback,all,tmo){var tsi,nary,res,i,p,pat,waiters=none,last=none;for(i in pats){pat=pats[i];nary=pat.length;if(nary>current.node.ts.n||nary==0)return none;res=remove(pat,all);if(res&&res.length)current.node.stats.tsin+=(all?res.length:1);if(res&&callback){callback.call(current.process.agent,res);return;}
else if(res)return res;}
if(callback&&tmo==0)return callback();if(tmo==0)return;for(i in pats){pat=pats[i];nary=pat.length;if(callback&&(tmo==undefined||tmo>0)){if(waiters==none)
waiters={pat:pat,pro:current.process,cb:callback,op:'in'+(all?'-all':''),tmo:tmo>0?Aios.time()-current.world.lag+tmo:0},last=waiters;else{last.next={pat:pat,pro:current.process,cb:callback,op:'in'+(all?'-all':''),tmo:tmo>0?Aios.time()-current.world.lag+tmo:0,prev:last},last=last.next;}}}
if(waiters!=none){p=waiters;while(p){tsi=current.node.ts.db[p.pat.length];addwaiter(tsi,p);p=p.next;}
log(tsi,current.process,' +waiter');current.process.suspend(tmo>0?Aios.time()-current.world.lag+tmo:0,_,'ts');}},collect:function(to,pat){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0)return none;tsi=current.node.ts.db[nary];res=remove(pat,true);if(res.length>0){current.node.stats.tsin+=res.length;Aios.Sig.agent.sendto(to,'TS.SIG',res);}
return res.length;},copyto:function(to,pat){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0)return 0;tsi=current.node.ts.db[nary];res=lookup(pat,true);if(res.length>0){Aios.Sig.agent.sendto(to,'TS.SIG',res);}
return res.length;},evaluate:function(pat,callback,tmo){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0)return none;tsi=current.node.ts.db[nary];consumed=checkwaiter(tsi,pat,callback);if(!consumed&&callback)callback.call(current.process.agent,null);},exists:function(pat){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0)return none;tsi=current.node.ts.db[nary];res=lookup(pat);return res!=none;},inp:function(pat,callback,all,tmo){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0||typeof pat!='object')throw'TS';tsi=current.node.ts.db[nary];res=remove(pat,all);log(tsi,current.process,' in? '+res+' []='+count(tsi));if(res&&res.length)current.node.stats.tsin+=(all?res.length:1);if(res==none&&callback&&(tmo==undefined||tmo>0)){addwaiter(tsi,{pat:pat,pro:current.process,cb:callback,op:'in'+(all?'-all':''),tmo:tmo>0?Aios.time()-current.world.lag+tmo:0});log(tsi,current.process,' +waiter');current.process.suspend(tmo>0?Aios.time()-current.world.lag+tmo:0,_,'ts');return none;}else if(callback)callback.call(current.process.agent,res);else return res;},listen:function(pat,callback){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0||typeof pat!='object')throw'TS';tsi=current.node.ts.db[nary];addwaiter(tsi,{pat:pat,pro:current.process,cb:callback,op:'listen',tmo:0});},mark:function(tuple,tmo){var p,tsi,nary=tuple.length,consumed=false;if(nary>current.node.ts.n||nary==0||typeof tuple!='object')throw'TS';if(current.process&&(current.process.resources.tuples+1)>(current.process.resources.TS||Aios.options.TSPOOL))throw'EOL';tuple=Comp.copy(tuple);tsi=current.node.ts.db[nary];current.node.stats.tsout++;consumed=checkwaiter(tsi,tuple);if(!consumed){if(tsi.free==none){loop:for(var i in tsi.data){if(tsi.data[i]==_){tsi.free=i;break loop}}}
if(options.timeout)tmo=min0(options.timeout,tmo);tmo=Aios.time()-current.world.lag+tmo;if(tsi.free!=none){tsi.data[tsi.free]=tuple;tsi.tmo[tsi.free]=tmo;current.node.ts.timeout=min0(current.node.ts.timeout,tsi.tmo[tsi.free]);if(Comp.obj.isString(tuple[0]))
tsi.hash[tuple[0]]=tsi.free;tsi.free=none;}else{tsi.data.push(tuple);tsi.tmo.push(tmo);if(Comp.obj.isString(tuple[0]))
tsi.hash[tuple[0]]=tsi.data.length-1;}}else current.node.stats.tsin++;},out:function(tuple){var tsi,tmo=0,nary=tuple.length,consumed=false,res;if(nary>current.node.ts.n||nary==0||typeof tuple!='object')throw'TS';if(current.process&&(current.process.resources.tuples+1)>(current.process.resources.TS||Aios.options.TSPOOL))throw'EOL';tsi=current.node.ts.db[nary];tuple=Comp.copy(tuple);current.node.stats.tsout++;consumed=checkwaiter(tsi,tuple);if(!consumed){if(tsi.free==none){loop:for(var i in tsi.data){if(tsi.data[i]==_){tsi.free=i;break loop}}}
if(options.timeout)tmo=Aios.time()-current.world.lag+options.timeout;if(tmo)current.node.ts.timeout=min0(current.node.ts.timeout,tmo);if(tsi.free!=none){tsi.data[tsi.free]=tuple;tsi.tmo[tsi.free]=tmo;if(Comp.obj.isString(tuple[0]))
tsi.hash[tuple[0]]=tsi.free;tsi.free=none;}
else{tsi.data.push(tuple);tsi.tmo.push(tmo);if(Comp.obj.isString(tuple[0]))
tsi.hash[tuple[0]]=tsi.data.length-1;}}else current.node.stats.tsin++;log(tsi,current.process,' out '+tuple+' ['+nary+'] consumed='+consumed+' []='+count(tsi));},rd:function(pat,callback,all,tmo){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0||typeof pat!='object')throw'TS';tsi=current.node.ts.db[nary];res=lookup(pat,all);if(res==none&&callback&&(tmo==_||tmo>0)){addwaiter(tsi,{pat:pat,pro:current.process,cb:callback,op:'rd'+(all?'-all':''),tmo:tmo>0?Aios.time()-current.world.lag+tmo:0});current.process.suspend(tmo>0?Aios.time()-current.world.lag+tmo:0,_,'ts');return none;}else if(callback)callback.call(current.process.agent,res);else return res;},rm:function(pat,all){var tsi,nary=pat.length,res;if(nary>current.node.ts.n||nary==0||typeof pat!='object')throw'TS';tsi=current.node.ts.db[nary];res=remove(pat,all);if(res&&res.length)current.node.stats.tsin+=(all?res.length:1);return(res!=none);},store:function(to,tuple){Aios.Sig.agent.sendto(to,'TS.SIG',[tuple]);return 1;},ts:function(pat,callbackOrTimeout){var tsi,nary=pat.length,index,res,ret,tmo;if(nary>current.node.ts.n||nary==0||!Comp.obj.isArray(pat))throw'TS';tsi=current.node.ts.db[nary];index=lookupIndex(pat,false);if(index!=none)res=tsi.data[index];else return;log(tsi,current.process,' test? '+res+' []='+count(tsi));if(typeof callbackOrTimeout=='function'){if(current.process)
ret=callbackOrTimeout.call(current.process.agent,res);else
ret=callbackOrTimeout(res);if(ret&&ret.length==res.length)Comp.array.copy(ret,res);res=ret;}else if(typeof callbackOrTimeout=='number'){tmo=min0(options.timeout,callbackOrTimeout);tmo=Aios.time()-current.world.lag+tmo;tsi.tmo[index]=Math.max(tmo,tsi.tmo[index]);}
return res;},try:{alt:function(tmo,pats,callback,all){if(typeof callback=='boolean'){all=callback;callback=null;}
return ts.alt(pats,callback,all,tmo);},evaluate:function(tmo,pat,callback){return ts.evaluate(pat,callback,tmo);},inp:function(tmo,pat,callback,all){if(typeof callback=='boolean'){all=callback;callback=null;}
return ts.inp(pat,callback,all,tmo);},rd:function(tmo,pat,callback,all){if(typeof callback=='boolean'){all=callback;callback=null;}
return ts.rd(pat,callback,all,tmo);}}}
ts.alt.try=ts.try.alt
ts.evaluate.try=ts.try.evaluate
ts.inp.try=ts.try.inp
ts.rd.try=ts.try.rd
var tsd=function(options){var self=this;if(!options)options={};this.n=options.maxn||8;this.id=options.id||'TS';this.timeout=0;this.db=Comp.array.init(this.n+1,function(i){var tsi;if(i==0)return none;tsi={i:i,hash:[],free:none,data:[],tmo:[],waiters:[]};tsi.waiters.free=[];tsi.waiters.hash={};return tsi;});this.providers=[];this.consumers=[];this.node=options.node;this.extern={exists:function(pat,callback){var res,_node=current.node;current.node=self.node||_node;res=ts.exists(pat,callback);current.node=_node;return res;},inp:function(pat,all){var res,tsi,nary=pat.length,_node=current.node;current.node=self.node||_node;if(nary>current.node.ts.n||nary==0)return none;tsi=current.node.ts.db[nary];res=remove(pat,all);if(res&&res.length)current.node.stats.tsin+=(all?res.length:1);current.node=_node;return res;},mark:function(pat,tmo){var res,_node=current.node,_proc=current.process;current.node=self.node||_node;current.process=null;res=ts.mark(pat,tmo);current.node=_node;current.process=_proc;return res;},out:function(pat){var res,_node=current.node,_proc=current.process;current.node=self.node||_node;current.process=null;res=ts.out(pat)
current.node=_node;current.process=_proc;return res;},rd:function(pat,all){var res,tsi,nary=pat.length,_node=current.node;current.node=self.node||_node;if(nary>current.node.ts.n||nary==0)return none;tsi=current.node.ts.db[nary];res=lookup(pat,all);if(res&&res.length)current.node.stats.tsin+=(all?res.length:1);current.node=_node;return res;},rm:function(pat,all){var res,_node=current.node;current.node=self.node||_node;res=ts.rm(pat,all);current.node=_node;return res;},ts:function(pat,callback){var res,_node=current.node;current.node=self.node||_node;res=ts.ts(pat,callback);current.node=_node;return res;},}}
var create=function(options){return new tsd(options);}
tsd.prototype.checkwaiter=function(tuple){var tsi,nary=tuple.length;if(nary>this.n||nary==0)return none;tsi=current.node.ts.db[nary];return checkwaiter(tsi,tuple);}
tsd.prototype.cleanup=function(process,doCallback){var i,j,tsi,p,waiter,node=process.node;function cb(waiter){Aios.CB(waiter.pro,function(){waiter.cb.call(waiter.pro.agent,null)});}
for(i in node.ts.db){if(i==0)continue;tsi=node.ts.db[i];for(j=0;j<tsi.waiters.length;j++){if(!tsi.waiters[j])continue;waiter=tsi.waiters[j];if(waiter.pro.pid==process.pid){if(doCallback&&waiter.cb)cb(waiter);removewaiter(tsi,j);}}}}
tsd.prototype.register=function(func,consumer){if(consumer)this.consumers.push(func)
else this.providers.push(func);};tsd.prototype.print=function(summary){var i,tsi,num,str='',sep='';if(summary){str+='[';for(i in current.node.ts.db){if(i==0)continue;tsi=current.node.ts.db[i];num=count(tsi);if(num>0){str+=sep+'TS'+(int(i)+1)+'='+num;sep=' ';}}
str+=']'+NL;}
else for(i in current.node.ts.db){if(i==0)continue;tsi=current.node.ts.db[i];str+='['+Comp.printf.sprintf('%2d',tsi.i)+' free='+(tsi.free?Comp.printf.sprintf('%4d',tsi.free):'none')+' data='+Comp.printf.sprintf('%4d(%4d)',count(tsi),tsi.data.length)+' waiters='+Comp.printf.sprintf('%4d',tsi.waiters.length)+']'+NL;}
return str;}
tsd.prototype.service=function(curtime){var i,hashed,tsi,nexttime=0;for(i in this.db){tsi=this.db[i];hashed;if(tsi==_)continue;Comp.array.iter(tsi.tmo,function(tmo,i){var tuple=tsi.data[i];if(tuple&&tmo){if(tmo<curtime){if(Comp.isString(tuple[0]))hashed=tsi.hash[tuple[0]];if(hashed!=_&&hashed==i)delete tsi.hash[tuple[0]];tsi.data[i]=_;tsi.tmo[i]=0;if(tsi.free==none)tsi.free=i;}else nexttime=min0(nexttime,tmo);}});}
this.timeout=nexttime;}
module.exports={agent:ts,count:count,create:create,current:function(module){current=module.current;Aios=module;},match:match,options:options}};BundleModuleCode['jam/world']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var options={debug:{},version:'1.11.3',verbose:0,}
var world=function(nodes,options){var main=this;options=checkOptions(options,{});this.options=options;this.nodes=nodes||[];this.verbose=checkOption(this.options.verbose,0);this.hash={};this.id=checkOption(this.options.id,Aios.aidgen().toUpperCase());this.classes=checkOption(this.options.classes,[]);this.lag=0;this.scheduler=this.options.scheduler;this.log=Aios.log;this.out=function(msg){main.log('[JAW '+this.id+'] '+msg)};this.thread=function(arg){var thr=this;var dying=false;this.nexttime=0;this.number=arg;this.curtime=0;this.init=function(){main.out('JAM World is starting ..');};this.run=function(){thr.nexttime=Aios.scheduler();thr.curtime=Aios.time();if(main.verbose>3)main.out(' .. nexttime = '+thr.nexttime+' ('+(thr.nexttime>0?thr.nexttime-thr.curtime:0)+')');};this.sleep=function(){var delta;thr.curtime=Aios.time();delta=thr.nexttime>0?thr.nexttime-thr.curtime:1000;if(main.verbose>3)main.out(' .. sleeping for '+delta+' ms');main.scheduler.Delay(delta);};this.transitions=function(){var trans;trans=[[undefined,this.init,function(thr){return true}],[this.init,this.run,function(thr){return true}],[this.run,this.run,function(thr){return thr.nexttime<0;}],[this.run,this.sleep,function(thr){return!dying;}],[this.run,this.terminate,function(thr){return dying}],[this.sleep,this.run,function(thr){return true;}]];return trans;};this.context=main.scheduler.TaskContext('JAM World'+main.id,thr);}};world.prototype.addClass=function(name,constructor,env){this.classes[name]=[Aios.Code.makeSandbox(constructor,0,env),Aios.Code.makeSandbox(constructor,1,env),Aios.Code.makeSandbox(constructor,2,env),Aios.Code.makeSandbox(constructor,3,env)];}
world.prototype.addNode=function(node){this.nodes.push(node);if(node.id)this.hash[node.id]=node;if(options.verbose)Io.out('World.addNode <'+node.id+'>');};world.prototype.connect=function(dir,node1,node2,options){if(!options)options={};var chan=Aios.Chan.Virtual(node1,node2,dir,options);switch(dir){case Aios.DIR.NORTH:node1.connections.north=chan.link1;node2.connections.south=chan.link2;break;case Aios.DIR.SOUTH:node1.connections.south=chan.link1;node2.connections.north=chan.link2;break;case Aios.DIR.WEST:node1.connections.west=chan.link1;node2.connections.east=chan.link2;break;case Aios.DIR.EAST:node1.connections.east=chan.link1;node2.connections.west=chan.link2;break;case Aios.DIR.NE:node1.connections.ne=chan.link1;node2.connections.sw=chan.link2;break;case Aios.DIR.NW:node1.connections.nw=chan.link1;node2.connections.se=chan.link2;break;case Aios.DIR.SE:node1.connections.se=chan.link1;node2.connections.nw=chan.link2;break;case Aios.DIR.SW:node1.connections.sw=chan.link1;node2.connections.ne=chan.link2;break;case Aios.DIR.UP:node1.connections.up=chan.link1;node2.connections.down=chan.link2;break;case Aios.DIR.DOWN:node1.connections.down=chan.link1;node2.connections.up=chan.link2;break;default:if(current)current.error='EINVALID';throw'CONNECT';}
chan.link2.on('agent',node1.receive.bind(node2));chan.link1.on('agent',node2.receive.bind(node1));chan.link2.on('signal',node1.handle.bind(node2));chan.link1.on('signal',node2.handle.bind(node1));chan.link1.end=node2.id;chan.link2.end=node1.id;return chan;};world.prototype.connectPhy=function(dir,node,options){var self=this,chan,name=Aios.DIR.to(dir);if(!options)options={};chan=Aios.Chan.Physical(node,dir,options);switch(dir.tag||dir){case'DIR.IP':if(!node.connections.ip)node.connections.ip=new Aios.Chan.iprouter();node.connections.ip.addLink(chan.link);chan.router=node.connections.ip;break;default:if(!name){if(current)current.error='ENOCHANNEL';throw'CONNECT';}
node.connections[name]=chan.link;}
chan.link.on('agent',node.receive.bind(node));chan.link.on('signal',node.handle.bind(node));chan.link.on('class',function(obj){for(var p in obj)self.addClass(p,obj[p].fun,obj[p].env)});return chan;};world.prototype.connectTo=function(dir,node,options){var chan,tokens,to=dir.ip,name=Aios.DIR.to(dir);if(!node)node=current.node;chan=node.connections[name];if(chan&&(chan.status(to)||!chan.connect))chan=undefined;if(chan)chan.connect(to,options);}
world.prototype.connected=function(dir,node){var name=Aios.DIR.to(dir),list;chan=node.connections[name];switch(dir.tag||dir){case Aios.DIR.tag.PATH:return chan&&chan.status(dir.path);break;case Aios.DIR.tag.IP:return chan&&chan.status(dir.ip);break;case Aios.DIR.tag.NODE:if(dir.node=='*'){list=[];if(node.connections.ip)list=list.concat(node.connections.ip.status('%'));return list;}else if(typeof dir.node=='string'){if(node.connections.ip&&node.connections.ip.lookup){found=node.connections.ip.lookup(dir.node);return found?Aios.DIR.IP(found):none;}}
break;case Aios.DIR.tag.DELTA:if(dir.delta[0]==1)chan=node.connections.east;else if(dir.delta[0]==-1)chan=node.connections.west;else if(dir.delta[1]==1)chan=node.connections.north;else if(dir.delta[1]==-1)chan=node.connections.south;else if(dir.delta[2]==1)chan=node.connections.up;else if(dir.delta[2]==-1)chan=node.connections.down;return chan&&chan.status();break;default:return(chan&&chan.status(dir.ip||dir.node||dir.path))||false;}}
world.prototype.disconnect=function(dir,node){var chan;switch(dir.tag||dir){case'DIR.IP':if(node.connections.ip&&node.connections.ip.status(dir.ip)&&node.connections.ip.disconnect)
node.connections.ip.disconnect(dir.ip);break;}}
world.prototype.getAgent=function(id,ac){var res=this.getAgentProcess(id,ac);if(res&&Comp.obj.isArray(res))return res.map(function(ap){return ap.agent});if(res)return res.agent;return;};world.prototype.getAgentProcess=function(id,ac){var matches=Comp.obj.isRegex(id)?[]:undefined;for(var n in this.nodes){var table=this.nodes[n].processes.table;for(var p in table){if(!table[p])continue;if(!matches&&table[p].agent.id==id&&(!ac||table[p].agent.ac==ac))
return table[p];if(matches&&id.test(table[p].agent.id)&&(!ac||table[p].agent.ac==ac))
matches.push(table[p]);}}
return matches;};world.prototype.getNode=function(nodeid){if(Comp.obj.isRegex(nodeid)){var res=[];for(var n in this.nodes){if(nodeid.test(this.nodes[n].id))res.push(this.nodes[n]);}
return res;}else{if(!this.hash[nodeid]&&options.verbose)Io.out('World.getNode: not found <'+nodeid+'>');return this.hash[nodeid];}};world.prototype.info=function(){var obj={},stat;obj.agents=0;obj.transferred=0;obj.links=0;obj.ports=0;for(var n in this.nodes){obj.agents+=this.nodes[n].processes.used;for(var l in this.nodes[n].connections){if(this.nodes[n].connections[l]){obj.ports++;obj.transferred+=this.nodes[n].connections[l].count();if(this.nodes[n].connections[l].stats){stat=this.nodes[n].connections[l].stats();obj.links+=(stat.links||0);}}}}
return obj;}
world.prototype.init=function(){}
world.prototype.lookup=function(dir,callback,node){switch(dir.tag||dir){case Aios.DIR.tag.PATH:if(node.connections.ip&&node.connections.ip.lookup)return node.connections.ip.lookup(dir.path,callback);break;default:if(callback)callback();}}
world.prototype.print=function(summary){var str='**** WORLD '+this.id+' ****'+NL;var res=Io.mem();str+='DATA='+int(res.data/1024)+' MB HEAP='+int(res.heap/1024)+' MB'+NL;for(var n in this.nodes){str+=this.nodes[n].print(summary);}
return str;}
world.prototype.removeNode=function(nodeid){var c,c2,conn,thenode,chan,node2;this.nodes=Comp.array.filter(this.nodes,function(node){if(node.id==nodeid)thenode=node;return node.id!=nodeid;});this.hash[nodeid]=undefined;if(thenode)for(c in thenode.connections){conn=thenode.connections[c];if(conn&&conn.end){node2=this.getNode(conn.end);if(node2)for(c2 in node2.connections){if(node2.connections[c2]&&node2.connections[c2].end==nodeid)
node2.connections[c2]=undefined;}}}
if(options.verbose)Io.out('World.removeNode <'+nodeid+'>');};world.prototype.start=function(){var self=this;if(this.scheduler){proc=new this.thread(0);this.context=proc.context;this.scheduler.Add(proc.context);}
this.gc=setInterval(function(){var node,n,p;if(self.verbose>3)self.out('GC');for(n in self.nodes){node=self.nodes[n];for(p in node.processes.gone){if(node.processes.gone[p]){node.processes.gone[p].tmo-=500;if(node.processes.gone[p].tmo<=0)node.processes.gone[p]=undefined;}}}},500);}
world.prototype.stop=function(){}
var World=function(nodes,options){var obj=new world(nodes,options);current.world=obj;return obj;}
module.exports={options:options,World:World,current:function(module){current=module.current;Aios=module}}};BundleModuleCode['jam/mobi']=function(module,exports){var Comp=Require('com/compat');var Net;var options={debug:{},version:'1.10.2'}
function addr2url(addr){return typeof addr=='number'?String(addr):(addr.proto?addr.proto+'://':'')+addr.address+':'+addr.port;}
if(global.config.dos)Net=Require('dos/network');var current=none;var Aios=none;var DIRS=['NORTH','SOUTH','WEST','EAST','LEFT','RIGHT','UP','DOWN','ORIGIN','NW','NE','SW','SE','DELTA','RANGE','NODE','IP','PATH','CAP'];var DIR={NORTH:'DIR.NORTH',SOUTH:'DIR.SOUTH',WEST:'DIR.WEST',EAST:'DIR.EAST',LEFT:'DIR.LEFT',RIGHT:'DIR.RIGHT',UP:'DIR.UP',DOWN:'DIR.DOWN',ORIGIN:'DIR.ORIGIN',NW:'DIR.NW',NE:'DIR.NE',SW:'DIR.SW',SE:'DIR.SE',BACKWARD:'DIR.BACKWARD',FORWARD:'DIR.FORWARD',OPPOSITE:'DIR.OPPOSITE',DELTA:function(addr){return{tag:"DIR.DELTA",delta:addr}},RANGE:function(r){return{tag:"DIR.RANGE",radius:r}},NODE:function(node){return{tag:"DIR.NODE",node:node}},IP:function(addr){return{tag:"DIR.IP",ip:addr}},PATH:function(path){return{tag:"DIR.PATH",path:path}},CAP:function(cap){return{tag:"DIR.CAP",cap:cap}}}
DIR.tag={NORTH:'DIR.NORTH',SOUTH:'DIR.SOUTH',WEST:'DIR.WEST',EAST:'DIR.EAST',LEFT:'DIR.LEFT',RIGHT:'DIR.RIGHT',UP:'DIR.UP',DOWN:'DIR.DOWN',ORIGIN:'DIR.ORIGIN',NW:'DIR.NW',NE:'DIR.NE',SW:'DIR.SW',SE:'DIR.SE',BACKWARD:'DIR.BACKWARD',FORWARD:'DIR.FORWARD',OPPOSITE:'DIR.OPPOSITE',DELTA:'DIR.DELTA',RANGE:'DIR.RANGE',NODE:'DIR.NODE',IP:'DIR.IP',PATH:'DIR.PATH',CAP:'DIR.CAP',}
function opposite(dir,next){var chan;switch(dir.tag||dir){case DIR.NORTH:return DIR.SOUTH;case DIR.SOUTH:return DIR.NORTH;case DIR.WEST:return DIR.EAST;case DIR.EAST:return DIR.WEST;case DIR.LEFT:return DIR.RIGHT;case DIR.RIGHT:return DIR.LEFT;case DIR.UP:return DIR.DOWN;case DIR.DOWN:return DIR.UP;case DIR.NW:return DIR.SE;case DIR.NE:return DIR.SW;case DIR.SE:return DIR.NW;case DIR.SW:return DIR.NE;case DIR.BACKWARD:return DIR.FORWARD;case DIR.FORWARD:return DIR.BACKWARD;case DIR.OPPOSITE:return DIR.OPPOSITE;case DIR.tag.DELTA:if(!next)return DIR.DELTA(dir.delta.map(function(v){return-v}));else return;case DIR.tag.IP:if(current.process&&current.process.back&&current.process.back.tag==DIR.tag.IP)return current.process.back;else return none;case DIR.tag.NODE:if(current.process&&current.process.back){switch(current.process.back.tag){case DIR.tag.IP:if(current.node&&current.node.connections.ip&&current.node.connections.ip.reverse)
return DIR.NODE(current.node.connections.ip.reverse(current.process.back.ip));else
return current.process.back;case DIR.tag.NODE:return current.process.back;default:return none;}}else return none;case'DIR.PATH':return none;case'DIR.CAP':return none;default:return none;}};DIR.from=function(name){var Dir=name.toUpperCase();if(DIRS.indexOf(Dir)==-1)return;return{tag:'DIR.'+Dir}}
DIR.to=function(dir){if((dir.tag||dir).substr(0,4)!='DIR.')return;return(dir.tag||dir).substr(4).toLowerCase();}
DIR.isDir=function(o){return(o.tag||o).indexOf('DIR')==0;}
DIR.opposite=opposite;DIR.print=function(dir){if(!dir)return'undefined';var name=(dir.tag||dir).substring(4);switch(dir.tag||dir){case'DIR.DELTA':return name+'('+Comp.printf.list(dir.delta)+')';case'DIR.RANGE':return name+'('+dir.radius+')';case'DIR.NODE':return name+'('+dir.node+')';case'DIR.IP':return name+'('+(dir.ip==undefined?'*':dir.ip)+')';case'DIR.PATH':return name+'('+dir.path+')';case'DIR.CAP':return name+'('+dir.cao+')';default:if(!dir.ip)return name
else return name+'('+addr2url(dir.ip)+')';}};DIR.toString=function(dir){function format(ip){if(ip==undefined)return'';if(typeof ip=='number')return ip;if(typeof ip=='string')return'"'+ip+'"';}
switch(dir.tag){case DIR.NORTH:return'DIR.North('+format(dir.ip)+')';case DIR.SOUTH:return'DIR.South('+format(dir.ip)+')';case DIR.WEST:return'DIR.West('+format(dir.ip)+')';case DIR.EAST:return'DIR.East('+format(dir.ip)+')';case DIR.tag.IP:return'DIR.IP('+format(dir.ip)+')';}
return dir;}
function lookup(node,destnode){var chan,path;if(node.connections.ip&&node.connections.ip.lookup){path=node.connections.ip.lookup(destnode);if(path)return{chan:node.connections.ip,dest:path};}}
function move(dir){var node1=current.node,chan=none,dest,stat,path,alive=function(){return 1},nokill=false,name=DIR.to(dir),msg;switch(dir.tag||dir){case'DIR.IP':chan=node1.connections.ip;dest=dir.ip;break;case'DIR.DELTA':current.process.dir=Comp.obj.copy(dir);if(dir.delta[0]>0&&node1.connections.east&&node1.connections.east.status())
current.process.dir.delta[0]--,chan=node1.connections.east;else if(dir.delta[0]<0&&node1.connections.west&&node1.connections.west.status())
current.process.dir.delta[0]++,chan=node1.connections.west;else if(dir.delta[1]>0&&node1.connections.south&&node1.connections.south.status())
current.process.dir.delta[1]--,chan=node1.connections.south;else if(dir.delta[1]<0&&node1.connections.north&&node1.connections.north.status())
current.process.dir.delta[1]++,chan=node1.connections.north;else if(dir.delta[2]>0&&node1.connections.up&&node1.connections.up.status())
current.process.dir.delta[2]--,chan=node1.connections.up;else if(dir.delta[2]<0&&node1.connections.down&&node1.connections.down.status())
current.process.dir.delta[2]++,chan=node1.connections.down;break;case'DIR.NODE':if(node1.connections.range&&node1.connections.range[dir.node]&&node1.connections.range[dir.node].status())
chan=node1.connections.range[dir.node],dest=dir.node;else{dest=lookup(node1,dir.node);if(dest)chan=dest.chan,dest=dest.dest;}
break;case'DIR.PATH':if(Comp.obj.isArray(dir.path)){path=Comp.array.pop(dir.path);}else path=dir.path;chan=node1.connections.path;dest=path;nokill=true;break;case'DIR.CAP':if(!current.network){current.error='No connection to server '+dir.cap;throw'MOVE'};chan=node1.connections.dos;dest=Net.Parse.capability(dir.cap).cap;nokill=true;break;default:if(!name){current.error='ENOCHANNEL';throw'MOVE';}
chan=node1.connections[name];}
if(chan==none||!chan.status(dest)){current.error='No connection to direction '+DIR.print(dir);throw'MOVE'};if(!current.process.back)current.process.back=Aios.DIR.opposite(dir);node1.stats.migrate++;if(Aios.options.fastcopy&&chan.virtual)msg=Aios.Code.toObject(current.process);else msg=Aios.Code.ofCode(current.process,false);current.process.move=dir;if(options.debug.move)console.log(dest,msg);chan.send({agent:msg,to:dest,context:current.process});if(!nokill)current.process.kill=true;else current.process.suspended=true;}
module.exports={agent:{move:move,opposite:opposite,DIR:DIR},current:function(module){current=module.current;Aios=module;},DIR:DIR,DIRS:DIRS,options:options}};BundleModuleCode['jam/watchdog']=function(module,exports){var version='1.2.2'
if(typeof process!='undefined'&&process.env&&!process.env.BOOTSTRAP)PATH.push('/opt/jam');function search(index,module){if(PATH.length==index)return module;var path=PATH[index];if(Fs.existsSync(path+'/'+module))return path+'/'+module;else return search(index+1,module);}
try{var watchdog;var Fs=Require('fs');try{watchdog=process&&process.binding&&process.binding&&process.binding('watchdog')}catch(e){};if(!watchdog)watchdog=process&&process.watchdog;if(!watchdog&&process&&process.startWatchdog)watchdog={start:process.startWatchdog,stop:process.stopWatchdog,init:process.initWatchdog,tick:process.tick};if(!watchdog){try{watchdog=require(search(0,'watchdog.node'))}catch(e){}}
if(!watchdog&&process&&process.version&&Fs){var nativePath,platformVersion;if(process.version.match(/^v0.12/))platformVersion="0.12";else if(process.version.match(/^v3/))platformVersion="3.x";else if(process.version.match(/^v4/))platformVersion="4.x";else if(process.version.match(/^v5/))platformVersion="5.x";else if(process.version.match(/^v6/))platformVersion="6.x";else if(process.version.match(/^v7/))platformVersion="7.x";else if(process.version.match(/^v8/))platformVersion="8.x";else if(process.version.match(/^v9/))platformVersion="9.x";if(platformVersion&&process.platform&&process.arch)
nativePath='native/'+process.platform+'/'+platformVersion+'/'+process.arch+'/watchdog.node';if(PATH)
if(nativePath){var _watchdog=require(search(0,nativePath));watchdog={start:_watchdog.start,stop:_watchdog.clear,protect:_watchdog.protect,init:function(){},}}}}catch(e){}
if(watchdog){module.exports={start:watchdog.start||watchdog.startWatchdog,stop:watchdog.stop||watchdog.stopWatchdog,init:watchdog.init||watchdog.initWatchdog,checkPoint:watchdog.checkPoint,tick:watchdog.tick,protect:watchdog.protect,version:version}}else module=undefined;};BundleModuleCode['geoip/gps5']=function(module,exports){var serviceHost="location.services.mozilla.com",servicePath="/v1/geolocate?key=test";function geolocate(cb){var https;if(typeof require=='function')try{https=require('https');}catch(e){}
if(!https)return cb(new Error('ENETWORK'));var req=https.request({hostname:serviceHost,port:443,path:servicePath,method:'GET'},function(res){res.on('data',function(d){try{var json=JSON.parse(d);cb(json)}catch(e){cb(e)};});})
req.on('error',function(e){console.error(e);cb(e);});req.end();}
module.exports={geolocate:geolocate};};BundleModuleCode['geoip/geoloc5']=function(module,exports){var Options={locate:{primary:{http:'ag-0.de:9999',https:'ag-0.de:9998',timeout:1000},secondary:{http:'ip-api.com:80',https:'ip-api.com:80',path:'/json',timeout:2000},},locate5:{secondary:{https:'location.services.mozilla.com:443',path:'/v1/geolocate?key=test'},},reverse:{primary:{https:'api.opencagedata.com',path:'/geocode/v1/json?q=LAT+LON&key=8e7c3730678842468d6acf450ecbca16'},secondary:{https:'nominatim.openstreetmap.org',path:'/reverse/?format=json&lat=LAT&lon=LON'},},verbose:0}
var http=Require("http"),https;function ip(url){return url.split(':')[0]}
function port(url){return url.split(':')[1]}
function stage1(cb,options,location){var e,r;if(!http.xhr&&http.request){e={hostname:ip(options.http),path:options.path||'',method:"GET",port:port(options.http)};if(Options.verbose)console.log('locate.stage1',e);r=http.request(e,function(a){a.setEncoding("utf8");var c="";a.on("data",function(a){c+=a}),a.on("end",function(){try{var info=JSON.parse(c);if(Options.verbose)console.log('locate.stage1.res',info);Object.assign(location,{ip:info.query,gps:{lat:info.lat,lon:info.lon},geo:{city:info.city,country:info.country,countryCode:info.countryCode,region:info.region,zip:info.zip}})
return cb(location);}catch(err){return cb(err);}})});r.on("error",function(a){if(Options.verbose)console.log('locate.stage1.err',a);return cb(a);})
r.setTimeout(options.timeout,function(){if(Options.verbose)console.log('locate.stage1.err',"ETIMEOUT");return cb(new Error("ETIMEOUT"));})
r.end();}else{var proto=document.URL.indexOf('https')==0?'https':'http';e={uri:proto+'://'+options[proto]+'/'+options.path,method:"GET",headers:{}};if(Options.verbose)console.log('stage1',e);http.request(e,function(err,xhr,body){if(err){if(Options.verbose)console.log('locate.stage1.err',err);return cb(err);}
try{var info=JSON.parse(body);if(Options.verbose)console.log('locate.stage1.res',info);Object.assign(location,{ip:info.query,gps:{lat:info.lat,lon:info.lon},geo:{city:info.city,country:info.country,countryCode:info.countryCode,region:info.region,zip:info.zip}})
return cb(location);}catch(err){if(Options.verbose)console.log('locate.stage1.err',err);return cb(err);}})}}
function stage2(cb,options,location){if(!https||!https.request)return cb(new Error('ENETWORK'));if(!https.xhr&&https.request){var e={hostname:ip(options.https),port:port(options.https),path:options.path,method:'GET'}
if(Options.verbose)console.log('locate.stage2',e);var req=https.request(e,function(res){res.on('data',function(d){try{var pos=JSON.parse(d);if(Options.verbose)console.log('locate.stage3.res',pos);location.gps5={lat:pos.location.lat,lon:pos.location.lng}
cb(location)}catch(e){if(Options.verbose)console.log('locate.stage2.err',e);cb(e)};});})
req.on('error',function(e){cb(e);});req.end();}else{e={uri:'https://'+options.https+'/'+options.path,method:"GET",headers:{}};if(Options.verbose)console.log('locate.stage2',e);https.request(e,function(err,xhr,body){if(err){if(Options.verbose)console.log('locate.stage2.err',err);return cb(err);}
try{var pos=JSON.parse(body);if(Options.verbose)console.log('locate.stage2.res',pos);location.gps5={lat:pos.location.lat,lon:pos.location.lng}
return cb(location);}catch(err){if(Options.verbose)console.log('locate.stage2.err',err);return cb(err);}})}}
function stage3(cb,options,location){if(!https||!https.request)return cb(new Error('ENETWORK'));options.path=options.path.replace(/LAT/,location.gps5.lat).replace(/LON/,location.gps5.lon);if(!https.xhr&&https.request){var e={hostname:ip(options.https),port:port(options.https),path:options.path,method:'GET'}
if(Options.verbose)console.log('locate.stage3',e);var req=https.request(e,function(res){res.on('data',function(d){try{var res=JSON.parse(d);var loc;if(Options.verbose)console.log('locate.stage3.res',res);if(res.address)loc=res.address;else if(res.results&&res.results[0])loc=res.results[0].components;location.geo5={city:loc.city,zip:loc.postcode,street:loc.road,number:loc.house_number,country:loc.country}
cb(location)}catch(e){if(Options.verbose)console.log('locate.stage3.err',e);cb(e)};});})
req.on('error',function(e){if(Options.verbose)console.log('locate.stage3.err',e);cb(e);});req.end();}else{e={uri:'https://'+options.https+'/'+options.path,method:"GET",headers:{}};if(Options.verbose)console.log('locate.stage3',e);https.request(e,function(err,xhr,body){if(err){if(Options.verbose)console.log('locate.stage3.err',err);return cb(err);}
try{var res=JSON.parse(body);var loc;if(Options.verbose)console.log('locate.stage3.res',res);if(res.address)loc=res.address;else if(res.results&&res.results[0])loc=res.results[0].components;location.geo5={city:loc.city,zip:loc.postcode,street:loc.road,number:loc.house_number,country:loc.country}
return cb(location);}catch(err){if(Options.verbose)console.log('locate.stage3.err',err);return cb(err);}})}}
var todo={stage1A:function(cb,errors,location){stage1(function(res){if(res instanceof Error){errors.push({url:Options.locate.primary,error:res});todo.stage1B(cb,errors,location);}else{todo.stage2A(cb,errors,location);}},Options.locate.primary,location);},stage1B:function(cb,errors,location){stage1(function(res){if(res instanceof Error){errors.push({url:Options.locate.secondary,error:res});todo.stage2A(cb,errors,location);}else{todo.stage2A(cb,errors,location);}},Options.locate.secondary,location);},stage2A:function(cb,errors,location){stage2(function(res){if(res instanceof Error){errors.push({url:Options.locate5.secondary,error:res});todo.finalize(cb,errors,location);}else{todo.stage2B(cb,errors,location);}},Options.locate5.secondary,location);},stage2B:function(cb,errors,location){stage3(function(res){if(res instanceof Error){errors.push({url:Options.reverse.primary,x:1,error:res});todo.finalize(cb,errors,location);}else{todo.finalize(cb,errors,location);}},Options.reverse.primary,location);},finalize:function(cb,errors,location){cb(location,errors);}}
function locate(cb,options){var e;if(options)Options=Object.assign(Options,options);if(typeof require=='function'&&!https)try{https=require('https');}catch(e){}else if(http.xhr)https=http;if(!http)return cb(new Error('ENOTSUPPORTED'));todo.stage1A(cb,[],{});return;}
module.exports={locate:locate,options:Options};};BundleModuleCode['os/platform']=function(module,exports){if(global.TARGET=='browser'){var objectTypes={'function':true,'object':true};var root=(objectTypes[typeof window]&&window)||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=='object'&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal;}
var maxSafeInteger=Math.pow(2,53)-1;var reOpera=/\bOpera/;var thisBinding=this;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var toString=objectProto.toString;function capitalize(string){string=String(string);return string.charAt(0).toUpperCase()+string.slice(1);}
function cleanupOS(os,pattern,label){var data={'10.0':'10','6.4':'10 Technical Preview','6.3':'8.1','6.2':'8','6.1':'Server 2008 R2 / 7','6.0':'Server 2008 / Vista','5.2':'Server 2003 / XP 64-bit','5.1':'XP','5.01':'2000 SP1','5.0':'2000','4.0':'NT','4.90':'ME'};if(pattern&&label&&/^Win/i.test(os)&&!/^Windows Phone /i.test(os)&&(data=data[/[\d.]+$/.exec(os)])){os='Windows '+data;}
os=String(os);if(pattern&&label){os=os.replace(RegExp(pattern,'i'),label);}
os=format(os.replace(/ ce$/i,' CE').replace(/\bhpw/i,'web').replace(/\bMacintosh\b/,'Mac OS').replace(/_PowerPC\b/i,' OS').replace(/\b(OS X) [^ \d]+/i,'$1').replace(/\bMac (OS X)\b/,'$1').replace(/\/(\d)/,' $1').replace(/_/g,'.').replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,'').replace(/\bx86\.64\b/gi,'x86_64').replace(/\b(Windows Phone) OS\b/,'$1').replace(/\b(Chrome OS \w+) [\d.]+\b/,'$1').split(' on ')[0]);return os;}
function each(object,callback){var index=-1,length=object?object.length:0;if(typeof length=='number'&&length>-1&&length<=maxSafeInteger){while(++index<length){callback(object[index],index,object);}}else{forOwn(object,callback);}}
function format(string){string=trim(string);return/^(?:webOS|i(?:OS|P))/.test(string)?string:capitalize(string);}
function forOwn(object,callback){for(var key in object){if(hasOwnProperty.call(object,key)){callback(object[key],key,object);}}}
function getClassOf(value){return value==null?capitalize(value):toString.call(value).slice(8,-1);}
function isHostType(object,property){var type=object!=null?typeof object[property]:'number';return!/^(?:boolean|number|string|undefined)$/.test(type)&&(type=='object'?!!object[property]:true);}
function qualify(string){return String(string).replace(/([ -])(?!$)/g,'$1?');}
function reduce(array,callback){var accumulator=null;each(array,function(value,index){accumulator=callback(accumulator,value,index,array);});return accumulator;}
function trim(string){return String(string).replace(/^ +| +$/g,'');}
function parse(ua){var context=root;var isCustomContext=ua&&typeof ua=='object'&&getClassOf(ua)!='String';if(isCustomContext){context=ua;ua=null;}
var nav=context.navigator||{};var userAgent=nav.userAgent||'';ua||(ua=userAgent);var isModuleScope=isCustomContext||thisBinding==oldRoot;var likeChrome=isCustomContext?!!nav.likeChrome:/\bChrome\b/.test(ua)&&!/internal|\n/i.test(toString.toString());var objectClass='Object',airRuntimeClass=isCustomContext?objectClass:'ScriptBridgingProxyObject',enviroClass=isCustomContext?objectClass:'Environment',javaClass=(isCustomContext&&context.java)?'JavaPackage':getClassOf(context.java),phantomClass=isCustomContext?objectClass:'RuntimeObject';var java=/\bJava/.test(javaClass)&&context.java;var rhino=java&&getClassOf(context.environment)==enviroClass;var alpha=java?'a':'\u03b1';var beta=java?'b':'\u03b2';var doc=context.document||{};var opera=context.operamini||context.opera;var operaClass=reOpera.test(operaClass=(isCustomContext&&opera)?opera['[[Class]]']:getClassOf(opera))?operaClass:(opera=null);var data;var arch=ua;var description=[];var prerelease=null;var useFeatures=ua==userAgent;var version=useFeatures&&opera&&typeof opera.version=='function'&&opera.version();var isSpecialCasedOS;var layout=getLayout([{'label':'EdgeHTML','pattern':'(?:Edge|EdgA|EdgiOS)'},'Trident',{'label':'WebKit','pattern':'AppleWebKit'},'iCab','Presto','NetFront','Tasman','KHTML','Gecko']);var name=getName(['Adobe AIR','Arora','Avant Browser','Breach','Camino','Electron','Epiphany','Fennec','Flock','Galeon','GreenBrowser','iCab','Iceweasel','K-Meleon','Konqueror','Lunascape','Maxthon',{'label':'Microsoft Edge','pattern':'(?:Edge|Edg|EdgA|EdgiOS)'},'Midori','Nook Browser','PaleMoon','PhantomJS','Raven','Rekonq','RockMelt',{'label':'Samsung Internet','pattern':'SamsungBrowser'},'SeaMonkey',{'label':'Silk','pattern':'(?:Cloud9|Silk-Accelerated)'},'Sleipnir','SlimBrowser',{'label':'SRWare Iron','pattern':'Iron'},'Sunrise','Swiftfox','Waterfox','WebPositive','Opera Mini',{'label':'Opera Mini','pattern':'OPiOS'},'Opera',{'label':'Opera','pattern':'OPR'},'Chrome',{'label':'Chrome Mobile','pattern':'(?:CriOS|CrMo)'},{'label':'Firefox','pattern':'(?:Firefox|Minefield)'},{'label':'Firefox for iOS','pattern':'FxiOS'},{'label':'IE','pattern':'IEMobile'},{'label':'IE','pattern':'MSIE'},'Safari']);var product=getProduct([{'label':'BlackBerry','pattern':'BB10'},'BlackBerry',{'label':'Galaxy S','pattern':'GT-I9000'},{'label':'Galaxy S2','pattern':'GT-I9100'},{'label':'Galaxy S3','pattern':'GT-I9300'},{'label':'Galaxy S4','pattern':'GT-I9500'},{'label':'Galaxy S5','pattern':'SM-G900'},{'label':'Galaxy S6','pattern':'SM-G920'},{'label':'Galaxy S6 Edge','pattern':'SM-G925'},{'label':'Galaxy S7','pattern':'SM-G930'},{'label':'Galaxy S7 Edge','pattern':'SM-G935'},'Google TV','Lumia','iPad','iPod','iPhone','Kindle',{'label':'Kindle Fire','pattern':'(?:Cloud9|Silk-Accelerated)'},'Nexus','Nook','PlayBook','PlayStation Vita','PlayStation','TouchPad','Transformer',{'label':'Wii U','pattern':'WiiU'},'Wii','Xbox One',{'label':'Xbox 360','pattern':'Xbox'},'Xoom']);var manufacturer=getManufacturer({'Apple':{'iPad':1,'iPhone':1,'iPod':1},'Archos':{},'Amazon':{'Kindle':1,'Kindle Fire':1},'Asus':{'Transformer':1},'Barnes & Noble':{'Nook':1},'BlackBerry':{'PlayBook':1},'Google':{'Google TV':1,'Nexus':1},'HP':{'TouchPad':1},'HTC':{},'LG':{},'Microsoft':{'Xbox':1,'Xbox One':1},'Motorola':{'Xoom':1},'Nintendo':{'Wii U':1,'Wii':1},'Nokia':{'Lumia':1},'Samsung':{'Galaxy S':1,'Galaxy S2':1,'Galaxy S3':1,'Galaxy S4':1},'Sony':{'PlayStation':1,'PlayStation Vita':1}});var os=getOS(['Windows Phone','Android','CentOS',{'label':'Chrome OS','pattern':'CrOS'},'Debian','Fedora','FreeBSD','Gentoo','Haiku','Kubuntu','Linux Mint','OpenBSD','Red Hat','SuSE','Ubuntu','Xubuntu','Cygwin','Symbian OS','hpwOS','webOS ','webOS','Tablet OS','Tizen','Linux','Mac OS X','Macintosh','Mac','Windows 98;','Windows ','SunOS',]);function getLayout(guesses){return reduce(guesses,function(result,guess){return result||RegExp('\\b'+(guess.pattern||qualify(guess))+'\\b','i').exec(ua)&&(guess.label||guess);});}
function getManufacturer(guesses){return reduce(guesses,function(result,value,key){return result||(value[product]||value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)]||RegExp('\\b'+qualify(key)+'(?:\\b|\\w*\\d)','i').exec(ua))&&key;});}
function getName(guesses){return reduce(guesses,function(result,guess){return result||RegExp('\\b'+(guess.pattern||qualify(guess))+'\\b','i').exec(ua)&&(guess.label||guess);});}
function getOS(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);if(!result&&(result=RegExp('\\b'+pattern+'(?:/[\\d.]+|[ \\w.]*)','i').exec(ua))){result=cleanupOS(result,pattern,guess.label||guess);}
return result;});}
function getProduct(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);if(!result&&(result=RegExp('\\b'+pattern+' *\\d+[.\\w_]*','i').exec(ua)||RegExp('\\b'+pattern+' *\\w+-[\\w]*','i').exec(ua)||RegExp('\\b'+pattern+'(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)','i').exec(ua))){if((result=String((guess.label&&!RegExp(pattern,'i').test(guess.label))?guess.label:result).split('/'))[1]&&!/[\d.]+/.test(result[0])){result[0]+=' '+result[1];}
guess=guess.label||guess;result=format(result[0].replace(RegExp(pattern,'i'),guess).replace(RegExp('; *(?:'+guess+'[_-])?','i'),' ').replace(RegExp('('+guess+')[-_.]?(\\w)','i'),'$1 $2'));}
return result;});}
function getVersion(patterns){return reduce(patterns,function(result,pattern){return result||(RegExp(pattern+'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)','i').exec(ua)||0)[1]||null;});}
function toStringPlatform(){return this.description||'';}
layout&&(layout=[layout]);if(manufacturer&&!product){product=getProduct([manufacturer]);}
if((data=/\bGoogle TV\b/.exec(product))){product=data[0];}
if(/\bSimulator\b/i.test(ua)){product=(product?product+' ':'')+'Simulator';}
if(name=='Opera Mini'&&/\bOPiOS\b/.test(ua)){description.push('running in Turbo/Uncompressed mode');}
if(name=='IE'&&/\blike iPhone OS\b/.test(ua)){data=parse(ua.replace(/like iPhone OS/,''));manufacturer=data.manufacturer;product=data.product;}
else if(/^iP/.test(product)){name||(name='Safari');os='iOS'+((data=/ OS ([\d_]+)/i.exec(ua))?' '+data[1].replace(/_/g,'.'):'');}
else if(name=='Konqueror'&&!/buntu/i.test(os)){os='Kubuntu';}
else if((manufacturer&&manufacturer!='Google'&&((/Chrome/.test(name)&&!/\bMobile Safari\b/i.test(ua))||/\bVita\b/.test(product)))||(/\bAndroid\b/.test(os)&&/^Chrome/.test(name)&&/\bVersion\//i.test(ua))){name='Android Browser';os=/\bAndroid\b/.test(os)?os:'Android';}
else if(name=='Silk'){if(!/\bMobi/i.test(ua)){os='Android';description.unshift('desktop mode');}
if(/Accelerated *= *true/i.test(ua)){description.unshift('accelerated');}}
else if(name=='PaleMoon'&&(data=/\bFirefox\/([\d.]+)\b/.exec(ua))){description.push('identifying as Firefox '+data[1]);}
else if(name=='Firefox'&&(data=/\b(Mobile|Tablet|TV)\b/i.exec(ua))){os||(os='Firefox OS');product||(product=data[1]);}
else if(!name||(data=!/\bMinefield\b/i.test(ua)&&/\b(?:Firefox|Safari)\b/.exec(name))){if(name&&!product&&/[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data+'/')+8))){name=null;}
if((data=product||manufacturer||os)&&(product||manufacturer||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))){name=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os)?os:data)+' Browser';}}
else if(name=='Electron'&&(data=(/\bChrome\/([\d.]+)\b/.exec(ua)||0)[1])){description.push('Chromium '+data);}
if(!version){version=getVersion(['(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$))','Version',qualify(name),'(?:Firefox|Minefield|NetFront)']);}
if((data=layout=='iCab'&&parseFloat(version)>3&&'WebKit'||/\bOpera\b/.test(name)&&(/\bOPR\b/.test(ua)?'Blink':'Presto')||/\b(?:Midori|Nook|Safari)\b/i.test(ua)&&!/^(?:Trident|EdgeHTML)$/.test(layout)&&'WebKit'||!layout&&/\bMSIE\b/i.test(ua)&&(os=='Mac OS'?'Tasman':'Trident')||layout=='WebKit'&&/\bPlayStation\b(?! Vita\b)/i.test(name)&&'NetFront')){layout=[data];}
if(name=='IE'&&(data=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua)||0)[1])){name+=' Mobile';os='Windows Phone '+(/\+$/.test(data)?data:data+'.x');description.unshift('desktop mode');}
else if(/\bWPDesktop\b/i.test(ua)){name='IE Mobile';os='Windows Phone 8.x';description.unshift('desktop mode');version||(version=(/\brv:([\d.]+)/.exec(ua)||0)[1]);}
else if(name!='IE'&&layout=='Trident'&&(data=/\brv:([\d.]+)/.exec(ua))){if(name){description.push('identifying as '+name+(version?' '+version:''));}
name='IE';version=data[1];}
if(useFeatures){if(isHostType(context,'global')){if(java){data=java.lang.System;arch=data.getProperty('os.arch');os=os||data.getProperty('os.name')+' '+data.getProperty('os.version');}
if(rhino){try{version=context.require('ringo/engine').version.join('.');name='RingoJS';}catch(e){if((data=context.system)&&data.global.system==context.system){name='Narwhal';os||(os=data[0].os||null);}}
if(!name){name='Rhino';}}
else if(typeof context.process=='object'&&!context.process.browser&&(data=context.process)){if(typeof data.versions=='object'){if(typeof data.versions.electron=='string'){description.push('Node '+data.versions.node);name='Electron';version=data.versions.electron;}else if(typeof data.versions.nw=='string'){description.push('Chromium '+version,'Node '+data.versions.node);name='NW.js';version=data.versions.nw;}}
if(!name){name='Node.js';arch=data.arch;os=data.platform;version=/[\d.]+/.exec(data.version);version=version?version[0]:null;}}}
else if(getClassOf((data=context.runtime))==airRuntimeClass){name='Adobe AIR';os=data.flash.system.Capabilities.os;}
else if(getClassOf((data=context.phantom))==phantomClass){name='PhantomJS';version=(data=data.version||null)&&(data.major+'.'+data.minor+'.'+data.patch);}
else if(typeof doc.documentMode=='number'&&(data=/\bTrident\/(\d+)/i.exec(ua))){version=[version,doc.documentMode];if((data=+data[1]+4)!=version[1]){description.push('IE '+version[1]+' mode');layout&&(layout[1]='');version[1]=data;}
version=name=='IE'?String(version[1].toFixed(1)):version[0];}
else if(typeof doc.documentMode=='number'&&/^(?:Chrome|Firefox)\b/.test(name)){description.push('masking as '+name+' '+version);name='IE';version='11.0';layout=['Trident'];os='Windows';}
os=os&&format(os);}
if(version&&(data=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version)||/(?:alpha|beta)(?: ?\d)?/i.exec(ua+';'+(useFeatures&&nav.appMinorVersion))||/\bMinefield\b/i.test(ua)&&'a')){prerelease=/b/i.test(data)?'beta':'alpha';version=version.replace(RegExp(data+'\\+?$'),'')+
(prerelease=='beta'?beta:alpha)+(/\d+\+?/.exec(data)||'');}
if(name=='Fennec'||name=='Firefox'&&/\b(?:Android|Firefox OS)\b/.test(os)){name='Firefox Mobile';}
else if(name=='Maxthon'&&version){version=version.replace(/\.[\d.]+/,'.x');}
else if(/\bXbox\b/i.test(product)){if(product=='Xbox 360'){os=null;}
if(product=='Xbox 360'&&/\bIEMobile\b/.test(ua)){description.unshift('mobile mode');}}
else if((/^(?:Chrome|IE|Opera)$/.test(name)||name&&!product&&!/Browser|Mobi/.test(name))&&(os=='Windows CE'||/Mobi/i.test(ua))){name+=' Mobile';}
else if(name=='IE'&&useFeatures){try{if(context.external===null){description.unshift('platform preview');}}catch(e){description.unshift('embedded');}}
else if((/\bBlackBerry\b/.test(product)||/\bBB10\b/.test(ua))&&(data=(RegExp(product.replace(/ +/g,' *')+'/([.\\d]+)','i').exec(ua)||0)[1]||version)){data=[data,/BB10/.test(ua)];os=(data[1]?(product=null,manufacturer='BlackBerry'):'Device Software')+' '+data[0];version=null;}
else if(this!=forOwn&&product!='Wii'&&((useFeatures&&opera)||(/Opera/.test(name)&&/\b(?:MSIE|Firefox)\b/i.test(ua))||(name=='Firefox'&&/\bOS X (?:\d+\.){2,}/.test(os))||(name=='IE'&&((os&&!/^Win/.test(os)&&version>5.5)||/\bWindows XP\b/.test(os)&&version>8||version==8&&!/\bTrident\b/.test(ua))))&&!reOpera.test((data=parse.call(forOwn,ua.replace(reOpera,'')+';')))&&data.name){data='ing as '+data.name+((data=data.version)?' '+data:'');if(reOpera.test(name)){if(/\bIE\b/.test(data)&&os=='Mac OS'){os=null;}
data='identify'+data;}
else{data='mask'+data;if(operaClass){name=format(operaClass.replace(/([a-z])([A-Z])/g,'$1 $2'));}else{name='Opera';}
if(/\bIE\b/.test(data)){os=null;}
if(!useFeatures){version=null;}}
layout=['Presto'];description.push(data);}
if((data=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua)||0)[1])){data=[parseFloat(data.replace(/\.(\d)$/,'.0$1')),data];if(name=='Safari'&&data[1].slice(-1)=='+'){name='WebKit Nightly';prerelease='alpha';version=data[1].slice(0,-1);}
else if(version==data[1]||version==(data[2]=(/\bSafari\/([\d.]+\+?)/i.exec(ua)||0)[1])){version=null;}
data[1]=(/\bChrome\/([\d.]+)/i.exec(ua)||0)[1];if(data[0]==537.36&&data[2]==537.36&&parseFloat(data[1])>=28&&layout=='WebKit'){layout=['Blink'];}
if(!useFeatures||(!likeChrome&&!data[1])){layout&&(layout[1]='like Safari');data=(data=data[0],data<400?1:data<500?2:data<526?3:data<533?4:data<534?'4+':data<535?5:data<537?6:data<538?7:data<601?8:'8');}else{layout&&(layout[1]='like Chrome');data=data[1]||(data=data[0],data<530?1:data<532?2:data<532.05?3:data<533?4:data<534.03?5:data<534.07?6:data<534.10?7:data<534.13?8:data<534.16?9:data<534.24?10:data<534.30?11:data<535.01?12:data<535.02?'13+':data<535.07?15:data<535.11?16:data<535.19?17:data<536.05?18:data<536.10?19:data<537.01?20:data<537.11?'21+':data<537.13?23:data<537.18?24:data<537.24?25:data<537.36?26:layout!='Blink'?'27':'28');}
layout&&(layout[1]+=' '+(data+=typeof data=='number'?'.x':/[.+]/.test(data)?'':'+'));if(name=='Safari'&&(!version||parseInt(version)>45)){version=data;}}
if(name=='Opera'&&(data=/\bzbov|zvav$/.exec(os))){name+=' ';description.unshift('desktop mode');if(data=='zvav'){name+='Mini';version=null;}else{name+='Mobile';}
os=os.replace(RegExp(' *'+data+'$'),'');}
else if(name=='Safari'&&/\bChrome\b/.exec(layout&&layout[1])){description.unshift('desktop mode');name='Chrome Mobile';version=null;if(/\bOS X\b/.test(os)){manufacturer='Apple';os='iOS 4.3+';}else{os=null;}}
if(version&&version.indexOf((data=/[\d.]+$/.exec(os)))==0&&ua.indexOf('/'+data+'-')>-1){os=trim(os.replace(data,''));}
if(layout&&!/\b(?:Avant|Nook)\b/.test(name)&&(/Browser|Lunascape|Maxthon/.test(name)||name!='Safari'&&/^iOS/.test(os)&&/\bSafari\b/.test(layout[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|Web)/.test(name)&&layout[1])){(data=layout[layout.length-1])&&description.push(data);}
if(description.length){description=['('+description.join('; ')+')'];}
if(manufacturer&&product&&product.indexOf(manufacturer)<0){description.push('on '+manufacturer);}
if(product){description.push((/^on /.test(description[description.length-1])?'':'on ')+product);}
if(os){data=/ ([\d.+]+)$/.exec(os);isSpecialCasedOS=data&&os.charAt(os.length-data[0].length-1)=='/';os={'architecture':32,'family':(data&&!isSpecialCasedOS)?os.replace(data[0],''):os,'version':data?data[1]:null,'toString':function(){var version=this.version;return this.family+((version&&!isSpecialCasedOS)?' '+version:'')+(this.architecture==64?' 64-bit':'');}};}
if((data=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch))&&!/\bi686\b/i.test(arch)){if(os){os.architecture=64;os.family=os.family.replace(RegExp(' *'+data),'');}
if(name&&(/\bWOW64\b/i.test(ua)||(useFeatures&&/\w(?:86|32)$/.test(nav.cpuClass||nav.platform)&&!/\bWin64; x64\b/i.test(ua)))){description.unshift('32-bit');}}
else if(os&&/^OS X/.test(os.family)&&name=='Chrome'&&parseFloat(version)>=39){os.architecture=64;}
ua||(ua=null);var platform={};platform.description=ua;platform.engine=layout&&layout[0];platform.manufacturer=manufacturer;platform.name=name;platform.prerelease=prerelease;platform.product=product;platform.ua=ua;platform.version=name&&version;platform.os=os||{'architecture':null,'family':null,'version':null,'toString':function(){return'null';}};platform.parse=parse;platform.toString=toStringPlatform;if(platform.version){description.unshift(version);}
if(platform.name){description.unshift(name);}
if(os&&name&&!(os==String(os).split(' ')[0]&&(os==name.split(' ')[0]||product))){description.push(product?'('+os+')':'on '+os);}
if(description.length){platform.description=description.join(' ');}
function popupsAllowed(){var allowed=false;if(!window.open)return;var w=window.open("about:blank","","directories=no,height=1,width=1,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,left=0,top=0,location=no");if(w){allowed=true;w.close();}
return allowed;}
function isTouch(){try{document.createEvent("TouchEvent");return true;}
catch(e){return("ontouchstart"in window)?true:false;}}
function isMobile(){try{if(typeof navigator=='undefined')return false;if(typeof sessionStorage!='undefined'&&sessionStorage.desktop)
return false;else if(typeof localStorage!='undefined'&&localStorage.mobile)
return true;var mobile=['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile'];for(var i in mobile)if(navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase())>0)return true;}catch(e){}
return false;}
global.jsVersion=1.0;function _detectJsVersion(){if(!document.write)return;document.write('<script language="JavaScript1.0">');document.write('jsVersion=1.0;');document.write('<\/script>');document.write('<script language="JavaScript1.1">');document.write('jsVersion=1.1;');document.write('<\/script>');document.write('<script language="JavaScript1.2">');document.write('jsVersion=1.2;');document.write('<\/script>');document.write('<script language="JavaScript1.3">');document.write('jsVersion=1.3;');document.write('<\/script>');document.write('<script language="JavaScript1.4">');document.write('jsVersion=1.4;');document.write('<\/script>');document.write('<script language="JavaScript1.5">');document.write('jsVersion=1.5;');document.write('<\/script>');document.write('<script language="JavaScript1.6">');document.write('jsVersion=1.6;');document.write('<\/script>');document.write('<script language="JavaScript1.7">');document.write('jsVersion=1.7;');document.write('<\/script>');document.write('<script language="JavaScript1.8">');document.write('jsVersion=1.8;');document.write('<\/script>');document.write('<script language="JavaScript2.0">');document.write('jsVersion=2.0;');document.write('<\/script>');}
function detectJsVersion(){_detectJsVersion();}
detectJsVersion();platform.jsVersion=function(){return jsVersion};if(typeof navigator!='undefined')
platform.hasWebRTC=(navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia)?1:undefined;platform.touch=isTouch();platform.mobile=isMobile();platform.geoloc=(typeof navigator!='undefined'&&navigator.geolocation&&typeof navigator.geolocation.getCurrentPosition=='function')?true:false;return platform;}
var platform=parse();}else{var platform={}}
module.exports=platform;};BundleModuleCode['jam/analyzer']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var Aios=none;var current=none;var util=Require('util');var options={version:'1.7.1',}
var out=function(msg){Io.out('[AJS] '+msg)};var corefuncs={act:{obj:{add:{argn:2},delete:{argn:1},update:{argn:2}}},add:{argn:2},angle:{argn:[1,2]},alt:{argn:[2,3],obj:{try:{argn:[2,3,4]}}},collect:{argn:2},concat:{argn:2},connectTo:{argn:1},copyto:{argn:2},delta:{argn:2},distance:{argn:[1,2]},empty:{argn:1},equal:{argn:2},Export:{argn:2},exists:{argn:1},filter:{argn:2,this:[1]},head:{argn:1},iter:{argn:2,this:[1]},Import:{argn:1},inp:{argn:[2,3],this:[1],obj:{try:{argn:[2,3,4]}}},kill:{argn:[0,1]},last:{argn:1},length:{argn:1},log:{argn:[1,2,3,4,5,6,7,8,9,10]},mark:{argn:2},map:{argn:2,this:[1]},matrix:{argn:[2,3]},max:{argn:[1,2]},me:{argn:0},min:{argn:[1,2]},myClass:{argn:0},myNode:{argn:0},myParent:{argn:0},myPosition:{argn:0},Number:{argn:1},object:{argn:1},out:{argn:1},opposite:{argn:1},privilege:{argn:0},random:{argn:[1,2,3]},reduce:{argn:2,this:[1]},reverse:{argn:1,this:[1]},rd:{argn:[2,3],this:[1],obj:{try:{argn:[2,3,4]}}},rm:{argn:[1,2]},send:{argn:[2,3]},sendto:{argn:[2,3]},sort:{argn:2,this:[1]},sleep:{argn:[0,1]},store:{argn:2},string:{argn:1},sum:{argn:[1,2]},tail:{argn:1},time:{argn:0},timer:{obj:{add:{argn:[2,3]},delete:{argn:1},update:{argn:2}}},try_alt:{argn:[2,3,4],this:[2]},try_inp:{argn:[2,3,4],this:[2]},try_rd:{argn:[2,3,4],this:[2]},ts:{argn:2},zero:{argn:1},B:{argn:[1,2],this:[0,1]},I:{argn:[3,4],this:[1,2,3]},L:{argn:[4,5],this:[1,2,3,4]},Vector:{argn:[1,2,3]}};function check_args(arguments,corefun){var len=arguments?arguments.length:0,passed=false;if(Comp.obj.isArray(corefun.argn))Comp.array.iter(corefun.argn,function(n){if(n==len)passed=true;});else passed=(len==corefun.argn);return passed;}
var jamc=function(options){};var properties={indexOf:'string.indexOf',push:'array.push',shift:'array.shift'}
var literals={none:'Literal',undefined:'Literal'}
literals['_']='Literal';var syntax={find:function(root,typ,name){if(root.type==typ&&root.id&&root.id.type=='Identifier'&&root.id.name==name)return root;switch(root.type){case'Program':return Comp.array.findmap(root.body,function(el){return syntax.find(el,typ,name)});break;case'VariableDeclaration':return Comp.array.findmap(root.declarations,function(el){return syntax.find(el,typ,name)});break;}
return null;},location:function(elem,short){var str='';if(elem.loc){if(elem.loc.start)str='line '+(elem.loc.start.line+syntax.offset)+', position '+elem.loc.start.column;if(elem.loc.end)str+=' to line '+(elem.loc.end.line+syntax.offset)+', position '+elem.loc.end.column;return str;}else return"unknown location";},name:function(elem){switch(elem.type){case'ThisExpression':return'this';case'Identifier':return elem.name;case'MemberExpression':return syntax.name(elem.object)+'.'+syntax.name(elem.property);default:return elem.toString();}},offset:0}
jamc.prototype.syntax=syntax;jamc.prototype.analyze=function(syntax,_options){var self=this,classname=_options.classname,level=_options.level,ep,elem,cp,declarator,ac,val,syms={id:{type:'Literal'},ac:{type:'Literal'}},nextVal,transObj,actObj,subclassObj,transitions={},activities={},subclasses,aios,options={},errors=[],verbose=_options.verbose||0,err=function(msg){errors.push(msg);(_options.err||this.err||Io.err)(msg)},out=_options.out||this.out||Io.out,warn=_options.warn||this.warn||Io.warn;switch(level){case 0:aios=Aios.aios0;break;case 1:aios=Aios.aios1;break;case 2:aios=Aios.aios2;break;case 3:aios=Aios.aios3;break;}
function unwrap(elem){switch(elem.type){case'BlockStatement':if(elem.body.length==1)return elem.body[0];else return elem;break;default:return elem;}}
function isThisExpr(elem){switch(elem.type){case'MemberExpression':return isThisExpr(elem.object);case'ThisExpression':return true;}
return false;}
function isEmpty(o){if(!o)return true;for(var p in o){if(o[p]!=undefined)return false;};return true;}
function iterMemberExpression(elem,options){var part,corefun,obj;switch(elem.type){case'Identifier':if(!aios[elem.name]&&!corefuncs[elem.name])
err('['+classname+'] Call of undefined function: '+
elem.name+', in level '+level+' ,at '+self.syntax.location(elem));else if(corefuncs[elem.name]){corefun=corefuncs[elem.name];if(!check_args(options.arguments,corefun)){err('['+classname+']: Call of AIOS function '+elem.name+' with invalid number of arguments, '+'(expecting '+(corefun.argn.toString())+' argument(s), got '+options.arguments.length+'), in level '+level+' ,at '+self.syntax.location(elem));}
return aios[elem.name];}else return aios[elem.name];break;case'MemberExpression':switch(elem.object.type){case'ThisExpression':if(!syms[elem.property.name]||syms[elem.property.name].context!='ThisExpression')
err("['+classname+'] Undefined 'this' reference: "+
elem.property.name+', at '+self.syntax.location(elem));if(syms[elem.property.name].type=='ObjectExpression'){var Osyms={};Comp.array.iter(syms[elem.property.name].properties,function(p){Osyms[p.key.name]=p.type;});if(!isEmpty(Osyms))
return Osyms;else
return none;}else return none;break;case'Identifier':if(!aios[elem.object.name]&&!corefuncs[elem.object.name]&&!options.syms[elem.object.name]){err('['+classname+'] Access of undefined object variable: '+
elem.object.name+', in level '+level+' ,at '+self.syntax.location(elem));}
if(properties[elem.property.name])return undefined;if(elem.computed)return undefined;if(corefuncs[elem.object.name]){obj=corefuncs[elem.object.name].obj||corefuncs[elem.object.name];if(!obj[elem.property.name]){err('['+classname+'] Access of unknown AIOS(corefuncs) object attribute: '+
elem.object.name+'.'+elem.property.name+', in level '+level+' ,at '+self.syntax.location(elem));}
return obj[elem.property.name];}else if(aios[elem.object.name]){obj=aios[elem.object.name].obj||aios[elem.object.name];if(!obj[elem.property.name])
err('['+classname+'] Access of unknown AIOS object attribute: '+
elem.object.name+'.'+elem.property.name+', in level '+level+' ,at '+self.syntax.location(elem));return obj[elem.property.name];}
else if(options.syms[elem.object.name]){return none;}
return;break;case'MemberExpression':part=iterMemberExpression(elem.object,options);if(part&&part.obj)part=part.obj;if(!elem.computed&&part&&!part[elem.property.name]&&!properties[elem.property.name]){err('['+classname+'] Access of unknown object attribute: '+
self.syntax.name(elem)+' ('+elem.property.name+'), in level '+
level+' ,at '+self.syntax.location(elem));}
if(elem.computed)check(elem.property,{reference:true,syms:options.syms});if(part&&(typeof part[elem.property.name]=='object')&&!isEmpty(part[elem.property.name]))
return part[elem.property.name];else
return none;break;}
break;}
return;}
function addDeclaration(elem,options){var ep,el;switch(elem.type){case'VariableDeclaration':for(ep in elem.declarations){el=elem.declarations[ep];if(!options.shadow[el.id.name])options.shadow[el.id.name]=options.syms[el.id.name];if(el.type=='VariableDeclarator'){if(el.id.type=='Identifier'){options.syms[el.id.name]=el;}}}
break;case'FunctionDeclaration':if(!options.shadow[elem.id.name])options.shadow[elem.id.name]=options.syms[elem.id.name];options.syms[elem.id.name]=elem;break;case'ForStatement':addDeclaration(elem.init,options);break;}}
function check(elem,options){var ep,el,name,thismaybe,shadow,locshadow;if(options.left&&options.this){switch(elem.type){case'Identifier':err('['+classname+'] Assignment may not contain free variables: var '+
elem.name+', at '+self.syntax.location(elem));break;case'MemberExpression':if(elem.object.type!='ThisExpression')
err('['+classname+'] Assignment may not contain non-this MemberExpression on left side: '+
self.syntax.name(elem.object)+', at '+self.syntax.location(elem));switch(elem.property.type){case'Identifier':if(syms[elem.property.name])
err('['+classname+'] Found duplicate property definition: '+
elem.property.name+' ('+syms[elem.property.name].type+'), at '+self.syntax.location(elem));else{syms[elem.property.name]=options.target;syms[elem.property.name].context=elem.object.type;}
switch(elem.property.name){case'act':actObj=options.target;break;case'trans':transObj=options.target;break;case'subclass':subclassObj=options.target;break;}
break;}
break;}}
else if(options.right&&options.this){switch(elem.type){case'Literal':case'Identifier':switch(options.target.property.name){case'next':val=elem.value||elem.name;if(!Comp.obj.isString(val))
err('['+classname+'] Invalid next property, expected string, got '+
val+', at '+self.syntax.location(elem));nextVal=val;break;}
break;case'ObjectExpression':switch(options.target.property.name){case'trans':for(ep in elem.properties){el=elem.properties[ep];if(el.type=='Property'){transitions[el.key.name]=el.value;}}
break;case'act':for(ep in elem.properties){el=elem.properties[ep];if(el.type=='Property'){if(aios[el.key.name])
err('['+classname+'] Activity name '+el.key.name+' shadows AIOS function or object, at '+self.syntax.location(elem));activities[el.key.name]=el.value;}}
break;case'subclass':subclasses={};for(ep in elem.properties){el=elem.properties[ep];if(el.type=='Property'){subclasses[el.key.name]=el.value;}}
break;}
break;case'FunctionExpression':locshadow={};for(ep in elem.params){param=elem.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type'+param.type+', expected Identifier'+', at '+self.syntax.location(elem));locshadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(elem.body,{funbody:true,this:true,syms:options.syms});for(ep in locshadow){options.syms[ep]=locshadow[ep];}
break;}}
else if(options.funbody&&options.this){elem=unwrap(elem);switch(elem.type){case'BlockStatement':if(options.shadow)shadow=options.shadow;options.shadow={};if(!options.syms)options.syms={};Comp.array.iter(elem.body,function(el){addDeclaration(el,options);});Comp.array.iter(elem.body,function(el){check(el,options)});if(options.syms)for(ep in options.shadow){options.syms[ep]=options.shadow[ep];}
options.shadow=shadow;break;case'ExpressionStatement':switch(elem.expression.type){case'AssignmentExpression':switch(elem.expression.left.type){case'MemberExpression':if(isThisExpr(elem.expression.left.object))
check(elem.expression.left,{this:true});break;case'Identifier':check(elem.expression.left,{reference:true,syms:options.syms});break;}
check(elem.expression.right,{reference:true,syms:options.syms});break;case'CallExpression':thismaybe=[];if(elem.expression.callee.object&&isThisExpr(elem.expression.callee.object)){check(elem.expression.callee,{this:true,funcall:true,arguments:elem.expression.arguments});}else{if(corefuncs[elem.expression.callee.name]&&corefuncs[elem.expression.callee.name].this)
{thismaybe=corefuncs[elem.expression.callee.name].this;}
if(options.syms[elem.expression.callee.name]){if(options.syms[elem.expression.callee.name].type!='FunctionDeclaration')
err('['+classname+'] Not a function:'+elem.expression.callee.name+', at '+self.syntax.location(elem));}else
check(elem.expression.callee,{funcall:true,external:true,syms:options.syms,arguments:elem.expression.arguments});}
Comp.array.iter(elem.expression.arguments,function(el,i){var ep,param,shadow;if(!Comp.array.member(thismaybe,i)){check(el,{reference:true,syms:options.syms});}else{switch(el.type){case'ArrayExpression':Comp.array.iter(el.elements,function(el_block,block_i){if(el_block.type!='FunctionExpression')
err('['+classname+'] Invalid argument '+(i+1)+' of AIOS core function '+
elem.expression.callee.name+': Expeceted FunctionExpression array, but got '+
el_block.type+' element (array index '+(block_i+1)+')'+', at '+self.syntax.location(elem));check(el_block.body,{funbody:true,this:true,syms:options.syms});});break;case'FunctionExpression':shadow={};for(ep in el.params){param=el.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type'+param.type+', expected Identifier'+', at '+self.syntax.location(elem));if(options.syms[param.name])shadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(el.body,{funbody:true,this:true,syms:options.syms});for(ep in shadow){options.syms[ep]=shadow[ep];}
break;case'ArrowFunctionExpression':shadow={};for(ep in el.params){param=el.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type'+param.type+', expected Identifier'+', at '+self.syntax.location(elem));if(options.syms[param.name])shadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(el.body,{funbody:true,this:true,syms:options.syms});for(ep in shadow){options.syms[ep]=shadow[ep];}
break;case'CallExpression':break;case'Identifier':break;default:err('['+classname+'] Invalid argument '+(i+1)+' of AIOS core function '+
elem.expression.callee.name+': Expeceted FunctionExpression, ArrowFunctionExpression, ArrayExpression, or Identifier, but got '+
el.type+', at '+self.syntax.location(elem));}}});break;case'UpdateExpression':check(elem.expression.argument,{reference:true,syms:options.syms});break;}
break;case'VariableDeclaration':if(!options.shadow)options.shadow={};for(ep in elem.declarations){el=elem.declarations[ep];if(!options.shadow[el.id.name])options.shadow[el.id.name]=options.syms[el.id.name];if(el.type=='VariableDeclarator'){if(el.id.type=='Identifier'){options.syms[el.id.name]=el;}}}
break;case'IfStatement':check(elem.consequent,options);if(elem.alternate)check(elem.alternate,options);check(elem.test,{reference:true,syms:options.syms});break;case'ForStatement':check(elem.body,options);check(elem.init,{reference:true,syms:options.syms});check(elem.test,{reference:true,syms:options.syms});check(elem.update,{reference:true,syms:options.syms});break;case'WhileStatement':check(elem.body,options);check(elem.test,{reference:true,syms:options.syms});break;case'ReturnStatement':if(elem.argument)
check(elem.argument,{reference:true,syms:options.syms});break;case'FunctionDeclaration':if(!options.shadow[elem.id.name])options.shadow[elem.id.name]=options.syms[elem.id.name];options.syms[elem.id.name]=elem;locshadow={};for(ep in elem.params){param=elem.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type'+param.type+', expected Identifier'+', at '+self.syntax.location(elem));locshadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(elem.body,{funbody:true,syms:options.syms});for(ep in locshadow){options.syms[ep]=locshadow[ep];}
break;}}
else if(options.funbody){elem=unwrap(elem);switch(elem.type){case'BlockStatement':if(options.shadow)shadow=options.shadow;options.shadow={};if(!options.syms)options.syms={};Comp.array.iter(elem.body,function(el){addDeclaration(el,options);});Comp.array.iter(elem.body,function(el){check(el,options)});if(options.syms)for(ep in options.shadow){options.syms[ep]=options.shadow[ep];}
options.shadow=shadow;break;case'ExpressionStatement':switch(elem.expression.type){case'AssignmentExpression':switch(elem.expression.left.type){case'MemberExpression':if(elem.expression.left.object&&isThisExpr(elem.expression.left.object))
check(elem.expression.left,{syms:options.syms});break;case'Identifier':check(elem.expression.left,{reference:true,syms:options.syms});break;}
check(elem.expression.right,{reference:true,syms:options.syms});break;case'CallExpression':thismaybe=[];if(elem.expression.callee.object&&isThisExpr(elem.expression.callee.object)){check(elem.expression.callee,{this:true,funcall:true,arguments:elem.expression.arguments});}else{if(corefuncs[elem.expression.callee.name]&&corefuncs[elem.expression.callee.name].this)
{thismaybe=corefuncs[elem.expression.callee.name].this;}
if(options.syms[elem.expression.callee.name]){if(options.syms[elem.expression.callee.name].type!='FunctionDeclaration')
err('['+classname+'] Not a function:'+elem.expression.callee.name+', at '+self.syntax.location(elem));}else
check(elem.expression.callee,{funcall:true,external:true,syms:options.syms,arguments:elem.expression.arguments});}
Comp.array.iter(elem.expression.arguments,function(el,i){var ep,param,shadow;if(!Comp.array.member(thismaybe,i)){check(el,{reference:true,syms:options.syms});}else{switch(el.type){case'ArrayExpression':Comp.array.iter(el.elements,function(el_block,block_i){if(el_block.type!='FunctionExpression')
err('['+classname+'] Invalid argument '+(i+1)+' of AIOS core function '+
elem.expression.callee.name+': Expeceted FunctionExpression array, but got '+
el_block.type+' element (array index '+(block_i+1)+')'+', at '+self.syntax.location(elem));check(el_block.body,{funbody:true,this:true,syms:options.syms});});break;case'FunctionExpression':shadow={};for(ep in el.params){param=el.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type'+param.type+', expected Identifier'+', at '+self.syntax.location(elem));if(options.syms[param.name])shadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(el.body,{funbody:true,this:true,syms:options.syms});for(ep in shadow){options.syms[ep]=shadow[ep];}
break;case'ArrowFunctionExpression':shadow={};for(ep in el.params){param=el.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type'+param.type+', expected Identifier'+', at '+self.syntax.location(elem));if(options.syms[param.name])shadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(el.body,{funbody:true,this:true,syms:options.syms});for(ep in shadow){options.syms[ep]=shadow[ep];}
break;case'CallExpression':break;case'Identifier':break;default:err('['+classname+'] Invalid argument '+(i+1)+' of AIOS core function '+
elem.expression.callee.name+': Expeceted FunctionExpression, ArrowFunctionExpression, ArrayExpression, or Identifier, but got '+
el.type+', at '+self.syntax.location(elem));}}});break;case'UpdateExpression':check(elem.expression.argument,{reference:true,syms:options.syms});break;}
break;case'VariableDeclaration':for(ep in elem.declarations){el=elem.declarations[ep];if(!options.shadow[el.id.name])options.shadow[el.id.name]=options.syms[el.id.name];if(el.type=='VariableDeclarator'){if(el.id.type=='Identifier'){options.syms[el.id.name]=el;}}}
break;case'IfStatement':check(elem.consequent,options);if(elem.alternate)check(elem.alternate,options);check(elem.test,{reference:true,syms:options.syms});break;case'ForStatement':check(elem.body,options);check(elem.init,{reference:true,syms:options.syms});check(elem.test,{reference:true,syms:options.syms});check(elem.update,{reference:true,syms:options.syms});break;case'WhileStatement':check(elem.body,options);check(elem.test,{reference:true,syms:options.syms});break;case'ReturnStatement':if(elem.argument)
check(elem.argument,{reference:true,syms:options.syms});break;case'FunctionDeclaration':if(!options.shadow[elem.id.name])options.shadow[elem.id.name]=options.syms[elem.id.name];options.syms[elem.id.name]=elem;locshadow={};for(ep in elem.params){param=elem.params[ep];if(param.type!='Identifier')
err('['+classname+'] Invalid function parameter type '+param.type+', expected Identifier'+', at '+self.syntax.location(elem));locshadow[param.name]=options.syms[param.name];options.syms[param.name]=param.type;}
check(elem.body,{funbody:true,syms:options.syms});for(ep in locshadow){options.syms[ep]=locshadow[ep];}
break;}}
else if(options.this){switch(elem.object.type){case'MemberExpression':check(elem.object,{this:true});break;case'ThisExpression':if(!syms[elem.property.name])
err('['+classname+"] Undefined 'this' reference: "+
elem.property.name+', at '+self.syntax.location(elem));if(options.funcall&&syms[elem.property.name].type!='FunctionExpression')
err('['+classname+"] Not a function: this."+
elem.property.name+', at '+self.syntax.location(elem));}}
else if(options.reference){switch(elem.type){case'Identifier':if(!options.syms[elem.name]&&!literals[elem.name]&&!aios[elem.name]&&!activities[elem.name])
err('['+classname+'] Undefined variable reference: '+
elem.name+', at '+self.syntax.location(elem));break;case'BinaryExpression':check(elem.left,options);check(elem.right,options);break;case'AssignmentExpression':switch(elem.left.type){case'MemberExpression':if(elem.left.object&&isThisExpr(elem.left.object))
check(elem.left,{this:true});break;case'Identifier':check(elem.left,{reference:true,syms:options.syms});break;}
check(elem.right,options);break;case'UpdateExpression':check(elem.argument,options);break;case'MemberExpression':switch(elem.object.type){case'ThisExpression':check(elem,{this:true,syms:options.syms});break;case'Identifier':check(elem.object,{reference:true,syms:options.syms});if(elem.computed)switch(elem.property.type){case'Identifier':check(elem.property,{reference:true,syms:options.syms});break;}
break;case'MemberExpression':iterMemberExpression(elem,options);}
break;case'ArrayExpression':Comp.array.iter(elem.elements,function(el2,i){if(el2)check(el2,{reference:true,syms:options.syms});});break;case'CallExpression':if(elem.callee.object&&isThisExpr(elem.callee.object)){check(elem.callee,{this:true,funobj:true,arguments:elem.arguments});}else{if(options.syms[elem.callee.name]){if(options.syms[elem.callee.name].type!='FunctionDeclaration')
err('['+classname+'] Not a function:'+elem.callee.name+', at '+self.syntax.location(elem));}else
check(elem.callee,{funcall:true,external:true,syms:options.syms,arguments:elem.arguments});}
Comp.array.iter(elem.arguments,function(el){check(el,{reference:true,syms:options.syms,arguments:elem.arguments})});break;}}
else if(options.funcall&&options.external){switch(elem.type){case'Identifier':case'MemberExpression':iterMemberExpression(elem,options);break;}}
else if(options.trans){switch(elem.type){case'BlockStatement':Comp.array.iter(elem.body,function(el){check(el,options)});break;case'IfStatement':check(elem.consequent,options);if(elem.alternate)check(elem.alternate,options);break;case'ReturnStatement':options.ret++;if(elem.argument)
check(elem.argument,options);else
if(verbose)warn('['+classname+'] Returns undefined in transition '+
options.trans+', at '+self.syntax.location(elem)+'.');break;case'Literal':if(!activities[elem.value])
err('['+classname+'] Returns unknown activity reference '+
elem.value+' in transition '+options.trans+', at '+self.syntax.location(elem)+'.');break;case'Identifier':if(!activities[elem.name])
err('['+classname+'] Returns unknown activity reference '+
elem.name+' in transition '+options.trans+', at '+self.syntax.location(elem)+'.');break;}}}
if(verbose)out('Analyzing agent class "'+classname+'" ..');if(syntax.type!='Program')
err('Syntax is not a program: '+syntax.type);loop1:for(ep in syntax.body){var elem=syntax.body[ep];if(elem.type!='VariableDeclaration')
err('Body element is not a variable declaration: '+elem.type);for(cp in elem.declarations){var declarator=elem.declarations[cp];if(declarator.type!='VariableDeclarator'){err('VariableDeclaration element is not a variable declarator: '+declarator.type);}
if(declarator.id.name!='ac')
err('['+classname+'] Entry not found, expected ac, got: '+declarator.id.name);else{ac=declarator;break loop1;};}}
if(!ac)
err('No agent class template found.');if(!ac.init||ac.init.type!='FunctionExpression')
err('['+classname+'] Entry is invalid, expected function, got: '+ac.init.type);if(ac.init.type!='FunctionExpression')
err('['+classname+'] Entry is invalid, expected function, got: '+ac.init.type);if(ac.init.body.type!='BlockStatement')
err('['+classname+'] Entry is invalid, expected function body, got: '+ac.init.body.type);loop2:for(ep in ac.init.body.body){var elem=ac.init.body.body[ep];switch(elem.type){case'VariableDeclaration':err('['+classname+'] May not contain free variable declarations: '+
Comp.printf.list(Comp.array.map(elem.declarations,function(decl){if(decl.type!='VariableDeclarator')return'?';else return'var '+self.syntax.name(decl.id)}))+', at '+self.syntax.location(elem));break;case'ExpressionStatement':switch(elem.expression.type){case'AssignmentExpression':check(elem.expression.left,{left:true,this:true,target:elem.expression.right});check(elem.expression.right,{right:true,this:true,target:elem.expression.left,syms:syms});break;case'MemberExpression':if(elem.expression.object&&elem.expression.object.type=='ThisExpression')
check(elem.expression,{left:true,this:true,target:{type:'undefined'}});break;}
break;default:err('['+classname+'] Invalid top-level '+elem.type+', at '+self.syntax.location(elem));break;}}
if(!syms['act']||syms['act'].type!='ObjectExpression')
err('['+classname+'] Found no or no valid activity section, expecting this.act={..}.');if(!syms['trans']||syms['trans'].type!='ObjectExpression')
err('['+classname+'] Found no or no valid transition section, expecting this.trans={..}.');if(syms['on']&&syms['on'].type!='ObjectExpression')
err('['+classname+'] Found invalid handler section, expecting this.on={..}.');if(!syms['on']&&verbose)
warn('['+classname+'] Found no handler section, expecting this.on={..}.');if(!nextVal)
err('['+classname+'] Found no next attribute, expecting this.next="<nextact>".');if(!activities[nextVal])
err('['+classname+'] Found invalid next attribute pointing to undefined activity '+nextVal+'.');loop3A:for(ep in activities){var elem=activities[ep];if(!transitions[ep]&&verbose)warn('['+classname+'] No transition entry found for activity '+ep);switch(elem.type){case'FunctionExpression':options={funbody:true,this:true,syms:{}};check(elem.body,options);elem.syms=syms;break;case'ArrowFunctionExpression':options={funbody:true,this:true,syms:{}};check(elem.body,options);elem.syms=syms;break;default:err('['+classname+'] Found invalid activity entry, expecting FunctionExpression or ArrowFunctionExpression, got '+
elem.type+', at '+self.syntax.location(elem));}}
loop3B:for(ep in transitions){var elem=transitions[ep],opt;if(!activities[ep])
err('['+classname+'] Transition entry found referencing unknown activity: '+
ep+', at '+self.syntax.location(elem));switch(elem.type){case'Identifier':if(!activities[elem.name])
err('['+classname+'] Unknown transition found: '+
elem.name+', at '+self.syntax.location(elem));break;case'Literal':if(!activities[elem.value])
err('['+classname+'] Unknown transition found: '+
elem.value+', at '+self.syntax.location(elem));break;case'FunctionExpression':opt={trans:ep,ret:0};check(elem.body,opt);if(opt.ret==0&&verbose)
warn('['+classname+'] Missing return (undefined) in transition '+
opt.trans+', at '+self.syntax.location(elem)+'.');break;case'ArrowFunctionExpression':opt={trans:ep,ret:0};check(elem.body,opt);if(opt.ret==0&&verbose)
warn('['+classname+'] Missing return (undefined) in transition '+
opt.trans+', at '+self.syntax.location(elem)+'.');break;default:err('['+classname+'] Found invalid transition entry, expecting FunctionExpression or ArrowFunctionExpression, Identifier, or String Literal, got '+
elem.type+', at '+self.syntax.location(elem));}}
if(verbose)out(classname+' passed check.');if(verbose){out(classname+' has the following top-level object properties:');for(ep in syms){var sym=syms[ep];if(!sym)continue;out(' '+ep+' : '+sym.type);}
out(classname+' has the following activities:');for(ep in activities){var elem=activities[ep];out(' '+ep);}
out(classname+' next activity: '+nextVal);out(classname+' has the following transition entries:');for(ep in transitions){var elem=transitions[ep];out(' '+ep);}
if(subclasses){out(classname+' has the following subclass entries:');for(ep in subclasses){var elem=subclasses[ep];out(' '+ep);}}}
if(verbose>1){out(classname+' has the following top-level symbols:');for(ep in syms){if(!syms[ep])continue;out(' '+ep+':'+(verbose>2?Io.inspect(syms[ep]):syms[ep].type));}}
return{activities:activities,transitions:transitions,subclasses:subclasses,symbols:syms,errors:errors}}
module.exports={corefuncs:corefuncs,extend:function(funcs){var p;for(p in funcs){corefuncs[p]=funcs[p];}},jamc:jamc,options:options,current:function(module){current=module.current;Aios=module;}};};BundleModuleCode['shell/cluster']=function(module,exports){var Comp=Require('com/compat');var CP=Require('child_process')
var osutils=Require('os/osutils');var program=process.argv[1];var Aios=none;var PS={START:'PS.START',STOP:'PS.STOP',RUN:'PS.RUN',RESTART:'PS.RESTART',DEAD:'PS.DEAD',EXIT:'PS.EXIT',DEAF:'PS.DEAF',}
function Cluster(options,shell){var i,j,n,m,self=this,poll;function pos2index(col,row){return row*self.grid.cols+col;}
function pos2ip(col,row,dir){var off=0;switch(dir){case DIR.NORTH:off=0;break;case DIR.WEST:off=1;break;case DIR.EAST:off=2;break;case DIR.SOUTH:off=3;break;}
return self.options.port0+row*self.grid.cols*4+col*4+off;}
function addr(port){return'localhost:'+port;}
function ports(col,row){var port;if(options.port1&&options.proto){port=options.port1+pos2index(col,row)*(options.portn||options.proto.length)-1;return options.proto.map(function(proto){port++;return DIR.IP(proto+'://'+addr(port)+
(options.secure?'?secure='+options.secure:''));})}else return[];}
this.cluster=options.cluster;this.options=options;this.logging=options.logging;if((options.poll==true||typeof options.poll=='number')&&options.port1&&options.proto&&options.proto.contains('http')){this.log('Creating AMP HTTP scanner on port '+(options.port0||(options.port1-1)));this.probe=shell.port(DIR.IP(options.port0||(options.port1-1)),{proto:'http',});poll=function poll(pro){var port=(options.port1+options.proto.indexOf('http'))+pro.index*(options.portn||options.proto.length)
self.probe.amp.scan({address:'localhost',port:port,proto:'http'},null,function(reply){pro.poll={time:shell.time(),state:reply!=undefined,info:reply&&reply.info,port:(reply&&reply.port?shell.Port.toString(reply.port):null)};})}
this.polltimer=setInterval(self.poll.bind(self),options.poll);}else if(typeof options.poll=='function')poll=options.poll;if(!this.cluster&&this.options.rows&&this.options.cols){this.cluster=[];this.grid={rows:this.options.rows,cols:this.options.cols}
for(j=0;j<this.grid.rows;j++)
for(i=0;i<this.grid.cols;i++)
this.cluster.push({id:'node('+i+','+j+')',poll:poll,todo:this.options.todo||'',ports:ports(i,j)})}else if(this.cluster){n=m=int(Math.log2(this.cluster.length));while(n*m<this.cluster.length)n++;this.grid={rows:n,cols:m}}else return;if(this.options.verbose)this.log('Grid: '+this.grid.rows+','+this.grid.cols);this.cluster.forEach(function(node,i){var row=int(i/self.grid.cols),col=i-row*self.grid.cols,ports,connects,ip;node.position=[col,row];if(!self.options.connect||!self.options.port0)return;ip=pos2ip(col,row);if(!node.ports)node.ports=[];if(!node.connect)node.connect=[];if(row==0){if(col==0)ports=[DIR.East(ip+2),DIR.South(ip+3)];else if(col<(self.grid.cols-1))ports=[DIR.West(ip+1),DIR.East(ip+2),DIR.South(ip+3)];else ports=[DIR.West(ip+1),DIR.South(ip+3)]}else if(row<(self.grid.rows-1)){if(col==0)ports=[DIR.North(ip),DIR.East(ip+2),DIR.South(ip+3)];else if(col<(self.grid.cols-1))ports=[DIR.North(ip),DIR.West(ip+1),DIR.East(ip+2),DIR.South(ip+3)];else ports=[DIR.North(ip),DIR.West(ip+1),DIR.South(ip+3)]}else{if(col==0)ports=[DIR.North(ip),DIR.East(ip+2),];else if(col<(self.grid.cols-1))ports=[DIR.North(ip),DIR.West(ip+1),DIR.East(ip+2),];else ports=[DIR.North(ip),DIR.West(ip+1),]}
self.log('Creating cluster interconnect AMP UDP ports for node '+i+': '+
ports.map(function(p){return DIR.print(p)}).join(' '));node.ports=node.ports.concat(ports);if(row==0){if(col==0){connects=[DIR.East(addr(pos2ip(col+1,row,DIR.WEST))),DIR.South(addr(pos2ip(col,row+1,DIR.NORTH)))]}else if(col<(self.grid.cols-1))connects=[DIR.East(addr(pos2ip(col+1,row,DIR.WEST))),DIR.South(addr(pos2ip(col,row+1,DIR.NORTH)))];else connects=[DIR.South(addr(pos2ip(col,row+1,DIR.NORTH)))]}else if(row<(self.grid.rows-1)){if(col==0){connects=[DIR.East(addr(pos2ip(col+1,row,DIR.WEST))),DIR.South(addr(pos2ip(col,row+1,DIR.NORTH)))]}else if(col<(self.grid.cols-1))connects=[DIR.East(addr(pos2ip(col+1,row,DIR.WEST))),DIR.South(addr(pos2ip(col,row+1,DIR.NORTH)))];else connects=[DIR.South(addr(pos2ip(col,row+1,DIR.NORTH)))]}else{if(col==0){connects=[DIR.East(addr(pos2ip(col+1,row,DIR.WEST))),]}else if(col<(self.grid.cols-1))ports=[DIR.East(localhost+':'+pos2ip(col+1,row))];else connects=[]}
node.connect=node.connect.concat(connects);});}
Cluster.prototype.log=function(msg,pid){console.log('[CLU'+(pid||process.pid)+' '+Aios.clock()+'] '+msg);}
Cluster.prototype.newVM=function(index,todo){var argv=[],desc=this.cluster[index],self=this;if(this.options.verbose)argv.push('-v');if(this.options.verbose>1)argv.push('-v');if(todo&&todo[todo.length-1]!=';')todo+=';';if(desc.ports)todo+=desc.ports.map(function(port,index){if(port.port!=undefined||port.proto!=undefined||port.address!=undefined)
return('var p'+index+'='+'port(DIR.IP('+port.port+'),{proto:"'+port.proto+'"'+
(port.secure?',secure:"'+port.secure+'"':'')+'})');if(port.tag)
return('var p'+index+'=port('+Aios.DIR.toString(port)+')');}).join(';');if(desc.connect)todo=todo+';'+desc.connect.map(function(port,index){return'var t'+index+'=setTimeout(function () { connect('+Aios.DIR.toString(port)+')},500)';}).join(';');todo=['config({print:process.send.bind(process),printAgent:process.send.bind(process),printAsync:process.send.bind(process)})',''].join(';')+todo;argv=argv.concat(['-e',todo]);if(this.options.verbose>1)this.log(argv);var pro=CP.fork(program,argv);pro.on('exit',function(code,signal){if(self.options.verbose)self.log('Process #'+pro.pid+' got signal '+code);pro.exited={code:code,signal:signal};});pro.on('message',function(msg){if(self.logging)self.logging(msg,index);else self.log(msg,pro.pid);});if(this.options.verbose)this.log('Started worker #'+pro.pid+': '+todo);else this.log('Started worker #'+pro.pid);pro.argv=argv;pro.todo=todo;pro.state=PS.START;pro.index=index;pro.cluster=desc;pro.load=0;pro.mem=0;return pro;}
Cluster.prototype.check=function(index){var self=this,stats=[];this.childs.forEach(function(pro,_index){if(index!=undefined&&_index!=index)return;if(pro.state!=PS.DEAD)
pro.state=pro.exited?PS.STOP:PS.RUN;stats.push({pid:pro.pid,state:pro.state,poll:pro.poll,load:pro.load,mem:pro.mem})
osutils.getProcess(pro.pid,function(res){if(res){pro.load=Math.floor(res.cpu)/100;pro.mem=Math.floor(res.mem);}});})
return stats;}
Cluster.prototype.poll=function(index){var self=this;this.childs.forEach(function(pro,_index){if(index!=undefined&&_index!=index)return;if(pro.cluster.poll)pro.cluster.poll(pro);})}
Cluster.prototype.restart=function(index){var self=this;this.childs=this.childs.map(function(pro,_index){if(index!=undefined&&_index!=index)return pro;if(self.options.verbose)self.log('Restarting worker #'+index);if(pro.state==PS.RUN)pro.kill();return self.newVM(_index,self.cluster[_index].todo);})}
Cluster.prototype.report=function(index){var desc=this.cluster;function pn(proto){switch(proto){case'http':return'h';case'https':return'hs';case'udp':return'u';case'tcp':return't';}}
function ports(index){if(desc[index].ports){var ports=desc[index].ports.filter(function(p){return p.tag==DIR.tag.IP||p.port;});return ports.map(function(port){if(port.proto)return pn(port.proto)+port.port+(port.secure?'S':'P');if(port.ip)return port.ip.replace(/localhost|ttp|dp|cp|:|\//g,'').replace(/\?[^$]+$/,'')+
(port.ip.match(/\?secure=/)?'S':'P')}).join(',');}else return'-';}
var table='';var stats=this.check();table='| Node | Ports | PID | Status | CPU% | Memory MB | Agents | Links |\n'+'|:---|:---|:---|:---|:---|:---|:---|:---|\n';table=table+stats.map(function(row,index){if(!row||row.state!=Cluster.PS.RUN||!row.poll||!row.poll.state||!row.poll.info)
return'| - | '+ports(index)+' | - | '+row.state+' | - | - | - | - |';else
return'| '+row.poll.info.world+' | '+ports(index)+' | '+
row.pid+' | '+row.state+' | '+row.load+' | '+row.mem+' | '+
row.poll.info.stats.agents+' | '+
row.poll.info.stats.links+' |';}).join('\n')
return table;}
Cluster.prototype.start=function(index){this.childs=[];for(var pi=0;pi<this.cluster.length;pi++){if(index!=undefined&&index!=pi)continue;this.childs.push(this.newVM(pi,this.cluster[pi].todo));}}
Cluster.prototype.stop=function(index){var self=this;this.childs.forEach(function(pro,_index){if(index!=undefined&&_index!=index)return;if(pro.state==PS.DEAD)return;self.log('Stopping worker #'+_index);pro.state=PS.DEAD;pro.kill();})}
Cluster.PS=PS;Cluster.current=function(module){Aios=module};module.exports=Cluster;};BundleModuleCode['os/osutils']=function(module,exports){var _os=require('os');var _proc=require('child_process')
var _fs=require('fs')
exports.platform=function(){return process.platform;}
exports.cpuCount=function(){return _os.cpus().length;}
exports.sysUptime=function(){return _os.uptime();}
exports.processUptime=function(){return process.uptime();}
exports.freemem=function(){return _os.freemem()/(1024*1024);}
exports.totalmem=function(){return _os.totalmem()/(1024*1024);}
exports.freememPercentage=function(){return _os.freemem()/_os.totalmem();}
exports.freeCommand=function(callback){require('child_process').exec('free -m',function(error,stdout,stderr){var lines=stdout.split("\n");var str_mem_info=lines[1].replace(/[\s\n\r]+/g,' ');var mem_info=str_mem_info.split(' ')
total_mem=parseFloat(mem_info[1])
free_mem=parseFloat(mem_info[3])
buffers_mem=parseFloat(mem_info[5])
cached_mem=parseFloat(mem_info[6])
used_mem=total_mem-(free_mem+buffers_mem+cached_mem)
callback(used_mem-2);});}
exports.harddrive=function(callback){require('child_process').exec('df -k',function(error,stdout,stderr){var total=0;var used=0;var free=0;var lines=stdout.split("\n");var str_disk_info=lines[1].replace(/[\s\n\r]+/g,' ');var disk_info=str_disk_info.split(' ');total=Math.ceil((disk_info[1]*1024)/Math.pow(1024,2));used=Math.ceil(disk_info[2]*1024/Math.pow(1024,2));free=Math.ceil(disk_info[3]*1024/Math.pow(1024,2));callback(total,free,used);});}
exports.getProcesses=function(nProcess,callback){if(typeof nProcess==='function'){callback=nProcess;nProcess=0}
if(nProcess>0)
command='ps -eo pid,pcpu,pmem,time,args | sort -k 2 -r | head -n'+(nProcess+1)
else
command='ps -eo pid,pcpu,pmem,time,args | sort -k 2 -r | head -n'+10
_proc.exec(command,function(error,stdout,stderr){var that=this
var lines=stdout.split("\n");lines.shift()
lines.pop()
var result=[];lines.forEach(function(_item,_i){var _str=_item.replace(/[\s\n\r]+/g,' ');_str=_str.split(' ')
result.push({cpu:Number(_str[2]),mem:Number(_str[3]),time:_str[4],pro:_str[5],args:_str.slice(6,_str.length)});});callback(result);});}
exports.getProcess=function(pid,callback){if(typeof pid==='function'){callback=pid;pid=process.pid}
command='ps -eo pid,pcpu,rss,time,args'
_proc.exec(command,function(error,stdout,stderr){var that=this
var lines=stdout.split("\n");lines.shift()
lines.pop()
var result;lines.forEach(function(_item,_i){var _str=_item.trim().replace(/[\s\n\r]+/g,' ');_str=_str.split(' ')
if(Number(_str[0])==pid)
result={cpu:Number(_str[1]),mem:Math.floor(Number(_str[2])/1024),time:_str[3],pro:_str[4],args:_str.slice(5,_str.length)};});callback(result);});}
exports.allLoadavg=function(){var loads=_os.loadavg();return loads[0].toFixed(4)+','+loads[1].toFixed(4)+','+loads[2].toFixed(4);}
exports.loadavg=function(_time){if(_time===undefined||(_time!==5&&_time!==15))_time=1;var loads=_os.loadavg();var v=0;if(_time==1)v=loads[0];if(_time==5)v=loads[1];if(_time==15)v=loads[2];return v;}
exports.cpuFree=function(callback){getCPUUsage(callback,true);}
exports.cpuUsage=function(callback){getCPUUsage(callback,false);}
if(process.platform=='linux')
exports.load=function(pid,callback,time){var t0,t1;if(typeof pid=='function'){time=callback;callback=pid;pid=process.pid;}
getUsage(pid,function(t){t0=t;if(!time)callback(t);})
if(time)setTimeout(function(){getUsage(pid,function(t){t1=t;callback((t1-t0)/time*1000);})},time);}
function getCPUUsage(callback,free){var stats1=getCPUInfo();var startIdle=stats1.idle;var startTotal=stats1.total;setTimeout(function(){var stats2=getCPUInfo();var endIdle=stats2.idle;var endTotal=stats2.total;var idle=endIdle-startIdle;var total=endTotal-startTotal;var perc=idle/total;if(free===true)
callback(perc);else
callback((1-perc));},1000);}
function getCPUInfo(callback){var cpus=_os.cpus();var user=0;var nice=0;var sys=0;var idle=0;var irq=0;var total=0;for(var cpu in cpus){if(!cpus.hasOwnProperty(cpu))continue;user+=cpus[cpu].times.user;nice+=cpus[cpu].times.nice;sys+=cpus[cpu].times.sys;irq+=cpus[cpu].times.irq;idle+=cpus[cpu].times.idle;}
var total=user+nice+sys+idle+irq;return{'idle':idle,'total':total};}
function getUsage(pid,cb){print(pid)
_fs.readFile("/proc/"+pid+"/stat",function(err,data){var elems=data.toString().split(' ');var utime=parseInt(elems[13]);var stime=parseInt(elems[14]);cb(utime+stime);});}};BundleModuleCode['rpc/rpc']=function(module,exports){var udprpc=Require('rpc/udp_rpc');var version="1.1.3"
function rpc(proto,port,arrayOfNamedFunctions,options){options=options||{}
switch(proto.toUpperCase()){case'UDP':return new udprpc(options.dgramType||'udp4',port,arrayOfNamedFunctions,options);}}
var clientCache=[];function getreq(url,requestCallback,options){var proto=url.match(/^([a-zA-Z]+):/),port=url.match(/([0-9]+)$/);proto=(proto&&proto[1])||'udp';port=(port&&port[1]);if(!port)throw Error('getreq: invalid port');var myport=rpc(proto,port,[function request(source,data,callback){callback(requestCallback(data,source))}],options)
return myport;}
function trans(url,data,replyCallback,options){var proto=url.match(/^([a-zA-Z]+):/),destination=url.replace(/^([a-zA-Z]+):\/\//,''),port=url.match(/([0-9]+)$/);proto=(proto&&proto[1])||'udp';port=(port&&port[1]);if(!port)throw Error('getreq: invalid port');if(clientCache[url]){if(clientCache[url].state!='listening'){clientCache[url].queue.push([destination,data,replyCallback]);}else
clientCache[url].request(destination,data,replyCallback||function(){});clientCache[url].timestamp=Date.now();}else{var myport=clientCache[url]=rpc(proto,0,[function request(source,data,callback){}],options);clientCache[url].timestamp=Date.now();clientCache[url].queue=[];clientCache[url].queue.push([destination,data,replyCallback]);myport.on('init',function(){while(clientCache[url].queue.length){var next=clientCache[url].queue.shift();myport.request(next[0],next[1],next[2]||function(){});}});}}
module.exports={clientCache:clientCache,rpc:rpc,getreq:getreq,trans:trans,version:version}};BundleModuleCode['rpc/udp_rpc']=function(module,exports){'use strict';var dgram=require('dgram');var crypto=Require('os/crypto.rand');var util=require('util');var events=require('events');var async=Require('rpc/async');var version="1.1.3";var flags={lastPacket:128};function bufXor(buf){var out=0;for(var i=0;i<buf.length;i++){out=out^buf.readUInt8(i,true);}
return out;}
function uniqId(usedList){var id=0;do{id=(Math.random()*(Math.pow(2,8)-1))&127;}while(typeof usedList[id]!='undefined')
return id;}
function execRpc(method,address){if(!method||!address){throw new Error("Did not receive a valid RPC request!");}
var rpcParams=Array.prototype.slice.call(arguments,2);var callback=rpcParams.length>1?rpcParams.pop():undefined;var addrArray=address.split(":");var messageId=this.genId();var payload=new Buffer(JSON.stringify([method,messageId,].concat(rpcParams)));this.emit('execRpc',method,address,rpcParams,callback);var self=this;this.messages[messageId]={callTs:new Date(),callback:callback,method:method,ip:addrArray[0],port:addrArray[1],rpcParams:rpcParams};sendMessage.call(this,address,payload,function allSent(err){self.emit('sentRpc',method,address,rpcParams,callback,err);if(err instanceof Error){delete self.messages[messageId];callback(err)}else{}});}
function sendMessage(address,payload,callback){var addrArray=address.split(":");if(!this.packets[address]){this.packets[address]={};}
var currFlags=uniqId(this.packets[address]);var totXor=bufXor(payload);var payloads=[];if(payload.length>494){var i=0;for(i=0;i<payload.length;i+=494){var newPayload=new Buffer(494);payload.copy(newPayload,0,i,i+493);payloads.push(newPayload);}
if(i<payload.length){var newPayload=new Buffer(payload.length-i);payload.copy(newPayload,0,i,payload.length-1);payloads.push(newPayload);}}else{payloads.push(payload);}
var self=this;async.forEach(payloads,function sendPayload(payload,callback){var message=new Buffer(payload.length+6);var packetNumber=payloads.indexOf(payload);currFlags&=127;message.writeUInt32BE(packetNumber,1,true);var curXor=bufXor(payload);if(packetNumber==payloads.length-1){currFlags|=flags.lastPacket;message.writeUInt8(totXor,5,true);}else{message.writeUInt8(curXor,5,true);}
message.writeUInt8(currFlags,0,true);payload.copy(message,6);self.stats.send++;self.stats.sendData+=message.length;self.dgram.send(message,0,message.length,addrArray[1],addrArray[0],function(err){if(err instanceof Error){return callback(err);}
return callback();});},callback);}
function receiveRpc(message,info){this.emit('receivedPacket',message,info);var header={flagid:message.readUInt8(0,true),packetNumber:message.readUInt32BE(1,true),xor:message.readUInt8(5,true)};var body=message.slice(6);this.stats.recv++;this.stats.recvData+=message.length;var source=info.address+":"+info.port;if(!this.packets[source]){this.packets[source]={};}
if(!this.packets[source][header.flagid]){this.packets[source][header.flagid]=[];}
this.packets[source][header.flagid].push({header:header,body:body});attemptProcessing.call(this,source,header.flagid);}
function attemptProcessing(source,id){var packetArray=this.packets[source][id];var integerSum=0;var totalMessageLen=0;var lastPacket=false;for(var i=0;i<packetArray.length;i++){integerSum+=packetArray[i].header.packetNumber+1;totalMessageLen+=packetArray[i].body.length;if(!!(packetArray[i].header.flagid&flags.lastPacket)){lastPacket=true;}}
if(!lastPacket||integerSum!=(packetArray.length*(packetArray.length+1)/2)){return;}
packetArray=packetArray.sort(function(a,b){return a.header.packetNumber-b.header.packetNumber;});var fullMessage=new Buffer(totalMessageLen);for(var i=0,j=0;i<packetArray.length;j+=packetArray[i].body.length,i++){packetArray[i].body.copy(fullMessage,0,j);}
delete this.packets[source][id];processMessage.call(this,fullMessage,source);}
function processMessage(message,source){var sourceArr=source.split(':');try{var messageArr=JSON.parse(message.toString('utf8'));}catch(e){console.log(e)}
if(!this.oneway&&typeof this.messages[messageArr[0]]=='object'&&sourceArr[1]==this.messages[messageArr[0]].port){this.emit('receivedRpcResponse',message,source);this.messages[messageArr[0]].callback.apply(this,messageArr.slice(1));delete this.messages[messageArr[0]];}else if(typeof this.methods[messageArr[0]]=='function'){this.emit('receivedRpcRequest',message,source);var messageId=messageArr[1];var params=messageArr.slice(2);params.unshift(source);var self=this;if(!this.oneway)params.push(function rpcCallback(){var payload=new Buffer(JSON.stringify([messageId].concat((Array.prototype.slice.call(arguments,0)))));sendMessage.call(self,source,payload,function(err){if(err instanceof Error){throw err;}});});this.methods[messageArr[0]].apply(this,params);}else{console.log('receivedUnknownMessage',messageArr)
this.emit('receivedUnknownMessage',message,source);}}
function udpRpc(ipType,srvPort,methods,oneway){var options={};events.EventEmitter.call(this);if(typeof oneway=='object'){options=oneway;oneway=options.oneway;}
this.methods={};this.messages={};this.packets={};this.state='starting';this.stats={recv:0,send:0,recvData:0,sendData:0,}
for(var i in methods){Object.defineProperty(this,methods[i].name,{enumerable:true,configurable:false,writable:false,value:execRpc.bind(this,methods[i].name)});Object.defineProperty(this.methods,methods[i].name,{enumerable:true,configurable:false,writable:false,value:methods[i]});}
this.genId=function(){var id="";do{try{id=crypto.randomBytes(3).toString('base64');}catch(e){id=new Buffer(Math.random()*(Math.pow(2,24)-1)).toString('base64');}}while(typeof this.messages[id]!='undefined')
return id;};this.srvPort=srvPort;this.address=undefined;var self=this;process.nextTick(function(){self.dgram=dgram.createSocket(ipType);self.dgram.on('listening',function udpRpcStart(){self.address=self.dgram.address();self.state='listening';if(options.verbose)console.log('udpRpc: listening on',self.address);self.emit('init');});self.dgram.on('message',receiveRpc.bind(self));self.dgram.bind(srvPort);});this.die=function die(){this.dgram.close();this.emit('death');delete this;};this.oneway=oneway||false;return this;}
util.inherits(udpRpc,events.EventEmitter);exports=module.exports=udpRpc;};BundleModuleCode['rpc/async']=function(module,exports){(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define(['exports'],factory):(factory((global.async=global.async||{})));}(this,(function(exports){'use strict';function slice(arrayLike,start){start=start|0;var newLen=Math.max(arrayLike.length-start,0);var newArr=Array(newLen);for(var idx=0;idx<newLen;idx++){newArr[idx]=arrayLike[start+idx];}
return newArr;}
var apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs));};};var initialParams=function(fn){return function(){var args=slice(arguments);var callback=args.pop();fn.call(this,args,callback);};};function isObject(value){var type=typeof value;return value!=null&&(type=='object'||type=='function');}
var hasSetImmediate=typeof setImmediate==='function'&&setImmediate;var hasNextTick=typeof process==='object'&&typeof process.nextTick==='function';function fallback(fn){setTimeout(fn,0);}
function wrap(defer){return function(fn){var args=slice(arguments,1);defer(function(){fn.apply(null,args);});};}
var _defer;if(hasSetImmediate){_defer=setImmediate;}else if(hasNextTick){_defer=process.nextTick;}else{_defer=fallback;}
var setImmediate$1=wrap(_defer);function asyncify(func){return initialParams(function(args,callback){var result;try{result=func.apply(this,args);}catch(e){return callback(e);}
if(isObject(result)&&typeof result.then==='function'){result.then(function(value){invokeCallback(callback,null,value);},function(err){invokeCallback(callback,err.message?err:new Error(err));});}else{callback(null,result);}});}
function invokeCallback(callback,error,value){try{callback(error,value);}catch(e){setImmediate$1(rethrow,e);}}
function rethrow(error){throw error;}
var supportsSymbol=typeof Symbol==='function';function isAsync(fn){return supportsSymbol&&fn[Symbol.toStringTag]==='AsyncFunction';}
function wrapAsync(asyncFn){return isAsync(asyncFn)?asyncify(asyncFn):asyncFn;}
function applyEach$1(eachfn){return function(fns){var args=slice(arguments,1);var go=initialParams(function(args,callback){var that=this;return eachfn(fns,function(fn,cb){wrapAsync(fn).apply(that,args.concat(cb));},callback);});if(args.length){return go.apply(this,args);}
else{return go;}};}
var freeGlobal=typeof global=='object'&&global&&global.Object===Object&&global;var freeSelf=typeof self=='object'&&self&&self.Object===Object&&self;var root=freeGlobal||freeSelf||Function('return this')();var Symbol$1=root.Symbol;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var nativeObjectToString=objectProto.toString;var symToStringTag$1=Symbol$1?Symbol$1.toStringTag:undefined;function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag$1),tag=value[symToStringTag$1];try{value[symToStringTag$1]=undefined;var unmasked=true;}catch(e){}
var result=nativeObjectToString.call(value);if(unmasked){if(isOwn){value[symToStringTag$1]=tag;}else{delete value[symToStringTag$1];}}
return result;}
var objectProto$1=Object.prototype;var nativeObjectToString$1=objectProto$1.toString;function objectToString(value){return nativeObjectToString$1.call(value);}
var nullTag='[object Null]';var undefinedTag='[object Undefined]';var symToStringTag=Symbol$1?Symbol$1.toStringTag:undefined;function baseGetTag(value){if(value==null){return value===undefined?undefinedTag:nullTag;}
return(symToStringTag&&symToStringTag in Object(value))?getRawTag(value):objectToString(value);}
var asyncTag='[object AsyncFunction]';var funcTag='[object Function]';var genTag='[object GeneratorFunction]';var proxyTag='[object Proxy]';function isFunction(value){if(!isObject(value)){return false;}
var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}
var MAX_SAFE_INTEGER=9007199254740991;function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}
function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}
var breakLoop={};function noop(){}
function once(fn){return function(){if(fn===null)return;var callFn=fn;fn=null;callFn.apply(this,arguments);};}
var iteratorSymbol=typeof Symbol==='function'&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]();};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index);}
return result;}
function isObjectLike(value){return value!=null&&typeof value=='object';}
var argsTag='[object Arguments]';function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag;}
var objectProto$3=Object.prototype;var hasOwnProperty$2=objectProto$3.hasOwnProperty;var propertyIsEnumerable=objectProto$3.propertyIsEnumerable;var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};var isArray=Array.isArray;function stubFalse(){return false;}
var freeExports=typeof exports=='object'&&exports&&!exports.nodeType&&exports;var freeModule=freeExports&&typeof module=='object'&&module&&!module.nodeType&&module;var moduleExports=freeModule&&freeModule.exports===freeExports;var Buffer=moduleExports?root.Buffer:undefined;var nativeIsBuffer=Buffer?Buffer.isBuffer:undefined;var isBuffer=nativeIsBuffer||stubFalse;var MAX_SAFE_INTEGER$1=9007199254740991;var reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(value,length){var type=typeof value;length=length==null?MAX_SAFE_INTEGER$1:length;return!!length&&(type=='number'||(type!='symbol'&&reIsUint.test(value)))&&(value>-1&&value%1==0&&value<length);}
var argsTag$1='[object Arguments]';var arrayTag='[object Array]';var boolTag='[object Boolean]';var dateTag='[object Date]';var errorTag='[object Error]';var funcTag$1='[object Function]';var mapTag='[object Map]';var numberTag='[object Number]';var objectTag='[object Object]';var regexpTag='[object RegExp]';var setTag='[object Set]';var stringTag='[object String]';var weakMapTag='[object WeakMap]';var arrayBufferTag='[object ArrayBuffer]';var dataViewTag='[object DataView]';var float32Tag='[object Float32Array]';var float64Tag='[object Float64Array]';var int8Tag='[object Int8Array]';var int16Tag='[object Int16Array]';var int32Tag='[object Int32Array]';var uint8Tag='[object Uint8Array]';var uint8ClampedTag='[object Uint8ClampedArray]';var uint16Tag='[object Uint16Array]';var uint32Tag='[object Uint32Array]';var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)];}
function baseUnary(func){return function(value){return func(value);};}
var freeExports$1=typeof exports=='object'&&exports&&!exports.nodeType&&exports;var freeModule$1=freeExports$1&&typeof module=='object'&&module&&!module.nodeType&&module;var moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1;var freeProcess=moduleExports$1&&freeGlobal.process;var nodeUtil=(function(){try{var types=freeModule$1&&freeModule$1.require&&freeModule$1.require('util').types;if(types){return types;}
return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}());var nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;var objectProto$2=Object.prototype;var hasOwnProperty$1=objectProto$2.hasOwnProperty;function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value){if((inherited||hasOwnProperty$1.call(value,key))&&!(skipIndexes&&(key=='length'||(isBuff&&(key=='offset'||key=='parent'))||(isType&&(key=='buffer'||key=='byteLength'||key=='byteOffset'))||isIndex(key,length)))){result.push(key);}}
return result;}
var objectProto$5=Object.prototype;function isPrototype(value){var Ctor=value&&value.constructor,proto=(typeof Ctor=='function'&&Ctor.prototype)||objectProto$5;return value===proto;}
function overArg(func,transform){return function(arg){return func(transform(arg));};}
var nativeKeys=overArg(Object.keys,Object);var objectProto$4=Object.prototype;var hasOwnProperty$3=objectProto$4.hasOwnProperty;function baseKeys(object){if(!isPrototype(object)){return nativeKeys(object);}
var result=[];for(var key in Object(object)){if(hasOwnProperty$3.call(object,key)&&key!='constructor'){result.push(key);}}
return result;}
function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}
function createArrayIterator(coll){var i=-1;var len=coll.length;return function next(){return++i<len?{value:coll[i],key:i}:null;}}
function createES2015Iterator(iterator){var i=-1;return function next(){var item=iterator.next();if(item.done)
return null;i++;return{value:item.value,key:i};}}
function createObjectIterator(obj){var okeys=keys(obj);var i=-1;var len=okeys.length;return function next(){var key=okeys[++i];return i<len?{value:obj[key],key:key}:null;};}
function iterator(coll){if(isArrayLike(coll)){return createArrayIterator(coll);}
var iterator=getIterator(coll);return iterator?createES2015Iterator(iterator):createObjectIterator(coll);}
function onlyOnce(fn){return function(){if(fn===null)throw new Error("Callback was already called.");var callFn=fn;fn=null;callFn.apply(this,arguments);};}
function _eachOfLimit(limit){return function(obj,iteratee,callback){callback=once(callback||noop);if(limit<=0||!obj){return callback(null);}
var nextElem=iterator(obj);var done=false;var running=0;var looping=false;function iterateeCallback(err,value){running-=1;if(err){done=true;callback(err);}
else if(value===breakLoop||(done&&running<=0)){done=true;return callback(null);}
else if(!looping){replenish();}}
function replenish(){looping=true;while(running<limit&&!done){var elem=nextElem();if(elem===null){done=true;if(running<=0){callback(null);}
return;}
running+=1;iteratee(elem.value,elem.key,onlyOnce(iterateeCallback));}
looping=false;}
replenish();};}
function eachOfLimit(coll,limit,iteratee,callback){_eachOfLimit(limit)(coll,wrapAsync(iteratee),callback);}
function doLimit(fn,limit){return function(iterable,iteratee,callback){return fn(iterable,limit,iteratee,callback);};}
function eachOfArrayLike(coll,iteratee,callback){callback=once(callback||noop);var index=0,completed=0,length=coll.length;if(length===0){callback(null);}
function iteratorCallback(err,value){if(err){callback(err);}else if((++completed===length)||value===breakLoop){callback(null);}}
for(;index<length;index++){iteratee(coll[index],index,onlyOnce(iteratorCallback));}}
var eachOfGeneric=doLimit(eachOfLimit,Infinity);var eachOf=function(coll,iteratee,callback){var eachOfImplementation=isArrayLike(coll)?eachOfArrayLike:eachOfGeneric;eachOfImplementation(coll,wrapAsync(iteratee),callback);};function doParallel(fn){return function(obj,iteratee,callback){return fn(eachOf,obj,wrapAsync(iteratee),callback);};}
function _asyncMap(eachfn,arr,iteratee,callback){callback=callback||noop;arr=arr||[];var results=[];var counter=0;var _iteratee=wrapAsync(iteratee);eachfn(arr,function(value,_,callback){var index=counter++;_iteratee(value,function(err,v){results[index]=v;callback(err);});},function(err){callback(err,results);});}
var map=doParallel(_asyncMap);var applyEach=applyEach$1(map);function doParallelLimit(fn){return function(obj,limit,iteratee,callback){return fn(_eachOfLimit(limit),obj,wrapAsync(iteratee),callback);};}
var mapLimit=doParallelLimit(_asyncMap);var mapSeries=doLimit(mapLimit,1);var applyEachSeries=applyEach$1(mapSeries);function arrayEach(array,iteratee){var index=-1,length=array==null?0:array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break;}}
return array;}
function createBaseFor(fromRight){return function(object,iteratee,keysFunc){var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;while(length--){var key=props[fromRight?length:++index];if(iteratee(iterable[key],key,iterable)===false){break;}}
return object;};}
var baseFor=createBaseFor();function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}
function baseFindIndex(array,predicate,fromIndex,fromRight){var length=array.length,index=fromIndex+(fromRight?1:-1);while((fromRight?index--:++index<length)){if(predicate(array[index],index,array)){return index;}}
return-1;}
function baseIsNaN(value){return value!==value;}
function strictIndexOf(array,value,fromIndex){var index=fromIndex-1,length=array.length;while(++index<length){if(array[index]===value){return index;}}
return-1;}
function baseIndexOf(array,value,fromIndex){return value===value?strictIndexOf(array,value,fromIndex):baseFindIndex(array,baseIsNaN,fromIndex);}
var auto=function(tasks,concurrency,callback){if(typeof concurrency==='function'){callback=concurrency;concurrency=null;}
callback=once(callback||noop);var keys$$1=keys(tasks);var numTasks=keys$$1.length;if(!numTasks){return callback(null);}
if(!concurrency){concurrency=numTasks;}
var results={};var runningTasks=0;var hasError=false;var listeners=Object.create(null);var readyTasks=[];var readyToCheck=[];var uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task)){enqueueTask(key,[task]);readyToCheck.push(key);return;}
var dependencies=task.slice(0,task.length-1);var remainingDependencies=dependencies.length;if(remainingDependencies===0){enqueueTask(key,task);readyToCheck.push(key);return;}
uncheckedDependencies[key]=remainingDependencies;arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName]){throw new Error('async.auto task `'+key+'` has a non-existent dependency `'+
dependencyName+'` in '+
dependencies.join(', '));}
addListener(dependencyName,function(){remainingDependencies--;if(remainingDependencies===0){enqueueTask(key,task);}});});});checkForDeadlocks();processQueue();function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task);});}
function processQueue(){if(readyTasks.length===0&&runningTasks===0){return callback(null,results);}
while(readyTasks.length&&runningTasks<concurrency){var run=readyTasks.shift();run();}}
function addListener(taskName,fn){var taskListeners=listeners[taskName];if(!taskListeners){taskListeners=listeners[taskName]=[];}
taskListeners.push(fn);}
function taskComplete(taskName){var taskListeners=listeners[taskName]||[];arrayEach(taskListeners,function(fn){fn();});processQueue();}
function runTask(key,task){if(hasError)return;var taskCallback=onlyOnce(function(err,result){runningTasks--;if(arguments.length>2){result=slice(arguments,1);}
if(err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val;});safeResults[key]=result;hasError=true;listeners=Object.create(null);callback(err,safeResults);}else{results[key]=result;taskComplete(key);}});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);if(task.length>1){taskFn(results,taskCallback);}else{taskFn(taskCallback);}}
function checkForDeadlocks(){var currentTask;var counter=0;while(readyToCheck.length){currentTask=readyToCheck.pop();counter++;arrayEach(getDependents(currentTask),function(dependent){if(--uncheckedDependencies[dependent]===0){readyToCheck.push(dependent);}});}
if(counter!==numTasks){throw new Error('async.auto cannot execute tasks due to a recursive dependency');}}
function getDependents(taskName){var result=[];baseForOwn(tasks,function(task,key){if(isArray(task)&&baseIndexOf(task,taskName,0)>=0){result.push(key);}});return result;}};function arrayMap(array,iteratee){var index=-1,length=array==null?0:array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array);}
return result;}
var symbolTag='[object Symbol]';function isSymbol(value){return typeof value=='symbol'||(isObjectLike(value)&&baseGetTag(value)==symbolTag);}
var INFINITY=1/0;var symbolProto=Symbol$1?Symbol$1.prototype:undefined;var symbolToString=symbolProto?symbolProto.toString:undefined;function baseToString(value){if(typeof value=='string'){return value;}
if(isArray(value)){return arrayMap(value,baseToString)+'';}
if(isSymbol(value)){return symbolToString?symbolToString.call(value):'';}
var result=(value+'');return(result=='0'&&(1/value)==-INFINITY)?'-0':result;}
function baseSlice(array,start,end){var index=-1,length=array.length;if(start<0){start=-start>length?0:(length+start);}
end=end>length?length:end;if(end<0){end+=length;}
length=start>end?0:((end-start)>>>0);start>>>=0;var result=Array(length);while(++index<length){result[index]=array[index+start];}
return result;}
function castSlice(array,start,end){var length=array.length;end=end===undefined?length:end;return(!start&&end>=length)?array:baseSlice(array,start,end);}
function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}
return index;}
function charsStartIndex(strSymbols,chrSymbols){var index=-1,length=strSymbols.length;while(++index<length&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}
return index;}
function asciiToArray(string){return string.split('');}
var rsAstralRange='\\ud800-\\udfff';var rsComboMarksRange='\\u0300-\\u036f';var reComboHalfMarksRange='\\ufe20-\\ufe2f';var rsComboSymbolsRange='\\u20d0-\\u20ff';var rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange;var rsVarRange='\\ufe0e\\ufe0f';var rsZWJ='\\u200d';var reHasUnicode=RegExp('['+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+']');function hasUnicode(string){return reHasUnicode.test(string);}
var rsAstralRange$1='\\ud800-\\udfff';var rsComboMarksRange$1='\\u0300-\\u036f';var reComboHalfMarksRange$1='\\ufe20-\\ufe2f';var rsComboSymbolsRange$1='\\u20d0-\\u20ff';var rsComboRange$1=rsComboMarksRange$1+reComboHalfMarksRange$1+rsComboSymbolsRange$1;var rsVarRange$1='\\ufe0e\\ufe0f';var rsAstral='['+rsAstralRange$1+']';var rsCombo='['+rsComboRange$1+']';var rsFitz='\\ud83c[\\udffb-\\udfff]';var rsModifier='(?:'+rsCombo+'|'+rsFitz+')';var rsNonAstral='[^'+rsAstralRange$1+']';var rsRegional='(?:\\ud83c[\\udde6-\\uddff]){2}';var rsSurrPair='[\\ud800-\\udbff][\\udc00-\\udfff]';var rsZWJ$1='\\u200d';var reOptMod=rsModifier+'?';var rsOptVar='['+rsVarRange$1+']?';var rsOptJoin='(?:'+rsZWJ$1+'(?:'+[rsNonAstral,rsRegional,rsSurrPair].join('|')+')'+rsOptVar+reOptMod+')*';var rsSeq=rsOptVar+reOptMod+rsOptJoin;var rsSymbol='(?:'+[rsNonAstral+rsCombo+'?',rsCombo,rsRegional,rsSurrPair,rsAstral].join('|')+')';var reUnicode=RegExp(rsFitz+'(?='+rsFitz+')|'+rsSymbol+rsSeq,'g');function unicodeToArray(string){return string.match(reUnicode)||[];}
function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string);}
function toString(value){return value==null?'':baseToString(value);}
var reTrim=/^\s+|\s+$/g;function trim(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return string.replace(reTrim,'');}
if(!string||!(chars=baseToString(chars))){return string;}
var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join('');}
var FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;var FN_ARG_SPLIT=/,/;var FN_ARG=/(=.+)?(\s*)$/;var STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function parseParams(func){func=func.toString().replace(STRIP_COMMENTS,'');func=func.match(FN_ARGS)[2].replace(' ','');func=func?func.split(FN_ARG_SPLIT):[];func=func.map(function(arg){return trim(arg.replace(FN_ARG,''));});return func;}
function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){var params;var fnIsAsync=isAsync(taskFn);var hasNoDeps=(!fnIsAsync&&taskFn.length===1)||(fnIsAsync&&taskFn.length===0);if(isArray(taskFn)){params=taskFn.slice(0,-1);taskFn=taskFn[taskFn.length-1];newTasks[key]=params.concat(params.length>0?newTask:taskFn);}else if(hasNoDeps){newTasks[key]=taskFn;}else{params=parseParams(taskFn);if(taskFn.length===0&&!fnIsAsync&&params.length===0){throw new Error("autoInject task functions require explicit parameters.");}
if(!fnIsAsync)params.pop();newTasks[key]=params.concat(newTask);}
function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name];});newArgs.push(taskCb);wrapAsync(taskFn).apply(null,newArgs);}});auto(newTasks,callback);}
function DLL(){this.head=this.tail=null;this.length=0;}
function setInitial(dll,node){dll.length=1;dll.head=dll.tail=node;}
DLL.prototype.removeLink=function(node){if(node.prev)node.prev.next=node.next;else this.head=node.next;if(node.next)node.next.prev=node.prev;else this.tail=node.prev;node.prev=node.next=null;this.length-=1;return node;};DLL.prototype.empty=function(){while(this.head)this.shift();return this;};DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node;newNode.next=node.next;if(node.next)node.next.prev=newNode;else this.tail=newNode;node.next=newNode;this.length+=1;};DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev;newNode.next=node;if(node.prev)node.prev.next=newNode;else this.head=newNode;node.prev=newNode;this.length+=1;};DLL.prototype.unshift=function(node){if(this.head)this.insertBefore(this.head,node);else setInitial(this,node);};DLL.prototype.push=function(node){if(this.tail)this.insertAfter(this.tail,node);else setInitial(this,node);};DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head);};DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail);};DLL.prototype.toArray=function(){var arr=Array(this.length);var curr=this.head;for(var idx=0;idx<this.length;idx++){arr[idx]=curr.data;curr=curr.next;}
return arr;};DLL.prototype.remove=function(testFn){var curr=this.head;while(!!curr){var next=curr.next;if(testFn(curr)){this.removeLink(curr);}
curr=next;}
return this;};function queue(worker,concurrency,payload){if(concurrency==null){concurrency=1;}
else if(concurrency===0){throw new Error('Concurrency must not be zero');}
var _worker=wrapAsync(worker);var numRunning=0;var workersList=[];var processingScheduled=false;function _insert(data,insertAtFront,callback){if(callback!=null&&typeof callback!=='function'){throw new Error('task callback must be a function');}
q.started=true;if(!isArray(data)){data=[data];}
if(data.length===0&&q.idle()){return setImmediate$1(function(){q.drain();});}
for(var i=0,l=data.length;i<l;i++){var item={data:data[i],callback:callback||noop};if(insertAtFront){q._tasks.unshift(item);}else{q._tasks.push(item);}}
if(!processingScheduled){processingScheduled=true;setImmediate$1(function(){processingScheduled=false;q.process();});}}
function _next(tasks){return function(err){numRunning-=1;for(var i=0,l=tasks.length;i<l;i++){var task=tasks[i];var index=baseIndexOf(workersList,task,0);if(index===0){workersList.shift();}else if(index>0){workersList.splice(index,1);}
task.callback.apply(task,arguments);if(err!=null){q.error(err,task.data);}}
if(numRunning<=(q.concurrency-q.buffer)){q.unsaturated();}
if(q.idle()){q.drain();}
q.process();};}
var isProcessing=false;var q={_tasks:new DLL(),concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:false,paused:false,push:function(data,callback){_insert(data,false,callback);},kill:function(){q.drain=noop;q._tasks.empty();},unshift:function(data,callback){_insert(data,true,callback);},remove:function(testFn){q._tasks.remove(testFn);},process:function(){if(isProcessing){return;}
isProcessing=true;while(!q.paused&&numRunning<q.concurrency&&q._tasks.length){var tasks=[],data=[];var l=q._tasks.length;if(q.payload)l=Math.min(l,q.payload);for(var i=0;i<l;i++){var node=q._tasks.shift();tasks.push(node);workersList.push(node);data.push(node.data);}
numRunning+=1;if(q._tasks.length===0){q.empty();}
if(numRunning===q.concurrency){q.saturated();}
var cb=onlyOnce(_next(tasks));_worker(data,cb);}
isProcessing=false;},length:function(){return q._tasks.length;},running:function(){return numRunning;},workersList:function(){return workersList;},idle:function(){return q._tasks.length+numRunning===0;},pause:function(){q.paused=true;},resume:function(){if(q.paused===false){return;}
q.paused=false;setImmediate$1(q.process);}};return q;}
function cargo(worker,payload){return queue(worker,1,payload);}
var eachOfSeries=doLimit(eachOfLimit,1);function reduce(coll,memo,iteratee,callback){callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOfSeries(coll,function(x,i,callback){_iteratee(memo,x,function(err,v){memo=v;callback(err);});},function(err){callback(err,memo);});}
function seq(){var _functions=arrayMap(arguments,wrapAsync);return function(){var args=slice(arguments);var that=this;var cb=args[args.length-1];if(typeof cb=='function'){args.pop();}else{cb=noop;}
reduce(_functions,args,function(newargs,fn,cb){fn.apply(that,newargs.concat(function(err){var nextargs=slice(arguments,1);cb(err,nextargs);}));},function(err,results){cb.apply(that,[err].concat(results));});};}
var compose=function(){return seq.apply(null,slice(arguments).reverse());};var _concat=Array.prototype.concat;var concatLimit=function(coll,limit,iteratee,callback){callback=callback||noop;var _iteratee=wrapAsync(iteratee);mapLimit(coll,limit,function(val,callback){_iteratee(val,function(err){if(err)return callback(err);return callback(null,slice(arguments,1));});},function(err,mapResults){var result=[];for(var i=0;i<mapResults.length;i++){if(mapResults[i]){result=_concat.apply(result,mapResults[i]);}}
return callback(err,result);});};var concat=doLimit(concatLimit,Infinity);var concatSeries=doLimit(concatLimit,1);var constant=function(){var values=slice(arguments);var args=[null].concat(values);return function(){var callback=arguments[arguments.length-1];return callback.apply(this,args);};};function identity(value){return value;}
function _createTester(check,getResult){return function(eachfn,arr,iteratee,cb){cb=cb||noop;var testPassed=false;var testResult;eachfn(arr,function(value,_,callback){iteratee(value,function(err,result){if(err){callback(err);}else if(check(result)&&!testResult){testPassed=true;testResult=getResult(true,value);callback(null,breakLoop);}else{callback();}});},function(err){if(err){cb(err);}else{cb(null,testPassed?testResult:getResult(false));}});};}
function _findGetResult(v,x){return x;}
var detect=doParallel(_createTester(identity,_findGetResult));var detectLimit=doParallelLimit(_createTester(identity,_findGetResult));var detectSeries=doLimit(detectLimit,1);function consoleFunc(name){return function(fn){var args=slice(arguments,1);args.push(function(err){var args=slice(arguments,1);if(typeof console==='object'){if(err){if(console.error){console.error(err);}}else if(console[name]){arrayEach(args,function(x){console[name](x);});}}});wrapAsync(fn).apply(null,args);};}
var dir=consoleFunc('dir');function doDuring(fn,test,callback){callback=onlyOnce(callback||noop);var _fn=wrapAsync(fn);var _test=wrapAsync(test);function next(err){if(err)return callback(err);var args=slice(arguments,1);args.push(check);_test.apply(this,args);}
function check(err,truth){if(err)return callback(err);if(!truth)return callback(null);_fn(next);}
check(null,true);}
function doWhilst(iteratee,test,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);var next=function(err){if(err)return callback(err);var args=slice(arguments,1);if(test.apply(this,args))return _iteratee(next);callback.apply(null,[null].concat(args));};_iteratee(next);}
function doUntil(iteratee,test,callback){doWhilst(iteratee,function(){return!test.apply(this,arguments);},callback);}
function during(test,fn,callback){callback=onlyOnce(callback||noop);var _fn=wrapAsync(fn);var _test=wrapAsync(test);function next(err){if(err)return callback(err);_test(check);}
function check(err,truth){if(err)return callback(err);if(!truth)return callback(null);_fn(next);}
_test(check);}
function _withoutIndex(iteratee){return function(value,index,callback){return iteratee(value,callback);};}
function eachLimit(coll,iteratee,callback){eachOf(coll,_withoutIndex(wrapAsync(iteratee)),callback);}
function eachLimit$1(coll,limit,iteratee,callback){_eachOfLimit(limit)(coll,_withoutIndex(wrapAsync(iteratee)),callback);}
var eachSeries=doLimit(eachLimit$1,1);function ensureAsync(fn){if(isAsync(fn))return fn;return initialParams(function(args,callback){var sync=true;args.push(function(){var innerArgs=arguments;if(sync){setImmediate$1(function(){callback.apply(null,innerArgs);});}else{callback.apply(null,innerArgs);}});fn.apply(this,args);sync=false;});}
function notId(v){return!v;}
var every=doParallel(_createTester(notId,notId));var everyLimit=doParallelLimit(_createTester(notId,notId));var everySeries=doLimit(everyLimit,1);function baseProperty(key){return function(object){return object==null?undefined:object[key];};}
function filterArray(eachfn,arr,iteratee,callback){var truthValues=new Array(arr.length);eachfn(arr,function(x,index,callback){iteratee(x,function(err,v){truthValues[index]=!!v;callback(err);});},function(err){if(err)return callback(err);var results=[];for(var i=0;i<arr.length;i++){if(truthValues[i])results.push(arr[i]);}
callback(null,results);});}
function filterGeneric(eachfn,coll,iteratee,callback){var results=[];eachfn(coll,function(x,index,callback){iteratee(x,function(err,v){if(err){callback(err);}else{if(v){results.push({index:index,value:x});}
callback();}});},function(err){if(err){callback(err);}else{callback(null,arrayMap(results.sort(function(a,b){return a.index-b.index;}),baseProperty('value')));}});}
function _filter(eachfn,coll,iteratee,callback){var filter=isArrayLike(coll)?filterArray:filterGeneric;filter(eachfn,coll,wrapAsync(iteratee),callback||noop);}
var filter=doParallel(_filter);var filterLimit=doParallelLimit(_filter);var filterSeries=doLimit(filterLimit,1);function forever(fn,errback){var done=onlyOnce(errback||noop);var task=wrapAsync(ensureAsync(fn));function next(err){if(err)return done(err);task(next);}
next();}
var groupByLimit=function(coll,limit,iteratee,callback){callback=callback||noop;var _iteratee=wrapAsync(iteratee);mapLimit(coll,limit,function(val,callback){_iteratee(val,function(err,key){if(err)return callback(err);return callback(null,{key:key,val:val});});},function(err,mapResults){var result={};var hasOwnProperty=Object.prototype.hasOwnProperty;for(var i=0;i<mapResults.length;i++){if(mapResults[i]){var key=mapResults[i].key;var val=mapResults[i].val;if(hasOwnProperty.call(result,key)){result[key].push(val);}else{result[key]=[val];}}}
return callback(err,result);});};var groupBy=doLimit(groupByLimit,Infinity);var groupBySeries=doLimit(groupByLimit,1);var log=consoleFunc('log');function mapValuesLimit(obj,limit,iteratee,callback){callback=once(callback||noop);var newObj={};var _iteratee=wrapAsync(iteratee);eachOfLimit(obj,limit,function(val,key,next){_iteratee(val,key,function(err,result){if(err)return next(err);newObj[key]=result;next();});},function(err){callback(err,newObj);});}
var mapValues=doLimit(mapValuesLimit,Infinity);var mapValuesSeries=doLimit(mapValuesLimit,1);function has(obj,key){return key in obj;}
function memoize(fn,hasher){var memo=Object.create(null);var queues=Object.create(null);hasher=hasher||identity;var _fn=wrapAsync(fn);var memoized=initialParams(function memoized(args,callback){var key=hasher.apply(null,args);if(has(memo,key)){setImmediate$1(function(){callback.apply(null,memo[key]);});}else if(has(queues,key)){queues[key].push(callback);}else{queues[key]=[callback];_fn.apply(null,args.concat(function(){var args=slice(arguments);memo[key]=args;var q=queues[key];delete queues[key];for(var i=0,l=q.length;i<l;i++){q[i].apply(null,args);}}));}});memoized.memo=memo;memoized.unmemoized=fn;return memoized;}
var _defer$1;if(hasNextTick){_defer$1=process.nextTick;}else if(hasSetImmediate){_defer$1=setImmediate;}else{_defer$1=fallback;}
var nextTick=wrap(_defer$1);function _parallel(eachfn,tasks,callback){callback=callback||noop;var results=isArrayLike(tasks)?[]:{};eachfn(tasks,function(task,key,callback){wrapAsync(task)(function(err,result){if(arguments.length>2){result=slice(arguments,1);}
results[key]=result;callback(err);});},function(err){callback(err,results);});}
function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback);}
function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback);}
var queue$1=function(worker,concurrency){var _worker=wrapAsync(worker);return queue(function(items,cb){_worker(items[0],cb);},concurrency,1);};var priorityQueue=function(worker,concurrency){var q=queue$1(worker,concurrency);q.push=function(data,priority,callback){if(callback==null)callback=noop;if(typeof callback!=='function'){throw new Error('task callback must be a function');}
q.started=true;if(!isArray(data)){data=[data];}
if(data.length===0){return setImmediate$1(function(){q.drain();});}
priority=priority||0;var nextNode=q._tasks.head;while(nextNode&&priority>=nextNode.priority){nextNode=nextNode.next;}
for(var i=0,l=data.length;i<l;i++){var item={data:data[i],priority:priority,callback:callback};if(nextNode){q._tasks.insertBefore(nextNode,item);}else{q._tasks.push(item);}}
setImmediate$1(q.process);};delete q.unshift;return q;};function race(tasks,callback){callback=once(callback||noop);if(!isArray(tasks))return callback(new TypeError('First argument to race must be an array of functions'));if(!tasks.length)return callback();for(var i=0,l=tasks.length;i<l;i++){wrapAsync(tasks[i])(callback);}}
function reduceRight(array,memo,iteratee,callback){var reversed=slice(array).reverse();reduce(reversed,memo,iteratee,callback);}
function reflect(fn){var _fn=wrapAsync(fn);return initialParams(function reflectOn(args,reflectCallback){args.push(function callback(error,cbArg){if(error){reflectCallback(null,{error:error});}else{var value;if(arguments.length<=2){value=cbArg;}else{value=slice(arguments,1);}
reflectCallback(null,{value:value});}});return _fn.apply(this,args);});}
function reflectAll(tasks){var results;if(isArray(tasks)){results=arrayMap(tasks,reflect);}else{results={};baseForOwn(tasks,function(task,key){results[key]=reflect.call(this,task);});}
return results;}
function reject$1(eachfn,arr,iteratee,callback){_filter(eachfn,arr,function(value,cb){iteratee(value,function(err,v){cb(err,!v);});},callback);}
var reject=doParallel(reject$1);var rejectLimit=doParallelLimit(reject$1);var rejectSeries=doLimit(rejectLimit,1);function constant$1(value){return function(){return value;};}
function retry(opts,task,callback){var DEFAULT_TIMES=5;var DEFAULT_INTERVAL=0;var options={times:DEFAULT_TIMES,intervalFunc:constant$1(DEFAULT_INTERVAL)};function parseTimes(acc,t){if(typeof t==='object'){acc.times=+t.times||DEFAULT_TIMES;acc.intervalFunc=typeof t.interval==='function'?t.interval:constant$1(+t.interval||DEFAULT_INTERVAL);acc.errorFilter=t.errorFilter;}else if(typeof t==='number'||typeof t==='string'){acc.times=+t||DEFAULT_TIMES;}else{throw new Error("Invalid arguments for async.retry");}}
if(arguments.length<3&&typeof opts==='function'){callback=task||noop;task=opts;}else{parseTimes(options,opts);callback=callback||noop;}
if(typeof task!=='function'){throw new Error("Invalid arguments for async.retry");}
var _task=wrapAsync(task);var attempt=1;function retryAttempt(){_task(function(err){if(err&&attempt++<options.times&&(typeof options.errorFilter!='function'||options.errorFilter(err))){setTimeout(retryAttempt,options.intervalFunc(attempt));}else{callback.apply(null,arguments);}});}
retryAttempt();}
var retryable=function(opts,task){if(!task){task=opts;opts=null;}
var _task=wrapAsync(task);return initialParams(function(args,callback){function taskFn(cb){_task.apply(null,args.concat(cb));}
if(opts)retry(opts,taskFn,callback);else retry(taskFn,callback);});};function series(tasks,callback){_parallel(eachOfSeries,tasks,callback);}
var some=doParallel(_createTester(Boolean,identity));var someLimit=doParallelLimit(_createTester(Boolean,identity));var someSeries=doLimit(someLimit,1);function sortBy(coll,iteratee,callback){var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){if(err)return callback(err);callback(null,{value:x,criteria:criteria});});},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty('value')));});function comparator(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0;}}
function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){var timedOut=false;var timer;function timeoutCallback(){var name=asyncFn.name||'anonymous';var error=new Error('Callback function "'+name+'" timed out.');error.code='ETIMEDOUT';if(info){error.info=info;}
timedOut=true;callback(error);}
args.push(function(){if(!timedOut){callback.apply(null,arguments);clearTimeout(timer);}});timer=setTimeout(timeoutCallback,milliseconds);fn.apply(null,args);});}
var nativeCeil=Math.ceil;var nativeMax=Math.max;function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step;}
return result;}
function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback);}
var times=doLimit(timeLimit,Infinity);var timesSeries=doLimit(timeLimit,1);function transform(coll,accumulator,iteratee,callback){if(arguments.length<=3){callback=iteratee;iteratee=accumulator;accumulator=isArray(coll)?[]:{};}
callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb);},function(err){callback(err,accumulator);});}
function tryEach(tasks,callback){var error=null;var result;callback=callback||noop;eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){if(arguments.length>2){result=slice(arguments,1);}else{result=res;}
error=err;callback(!err);});},function(){callback(error,result);});}
function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments);};}
function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args));};_iteratee(next);}
function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments);},iteratee,callback);}
var waterfall=function(tasks,callback){callback=once(callback||noop);if(!isArray(tasks))return callback(new Error('First argument to waterfall must be an array of functions'));if(!tasks.length)return callback();var taskIndex=0;function nextTask(args){var task=wrapAsync(tasks[taskIndex++]);args.push(onlyOnce(next));task.apply(null,args);}
function next(err){if(err||taskIndex===tasks.length){return callback.apply(null,arguments);}
nextTask(slice(arguments,1));}
nextTask([]);};var index={apply:apply,applyEach:applyEach,applyEachSeries:applyEachSeries,asyncify:asyncify,auto:auto,autoInject:autoInject,cargo:cargo,compose:compose,concat:concat,concatLimit:concatLimit,concatSeries:concatSeries,constant:constant,detect:detect,detectLimit:detectLimit,detectSeries:detectSeries,dir:dir,doDuring:doDuring,doUntil:doUntil,doWhilst:doWhilst,during:during,each:eachLimit,eachLimit:eachLimit$1,eachOf:eachOf,eachOfLimit:eachOfLimit,eachOfSeries:eachOfSeries,eachSeries:eachSeries,ensureAsync:ensureAsync,every:every,everyLimit:everyLimit,everySeries:everySeries,filter:filter,filterLimit:filterLimit,filterSeries:filterSeries,forever:forever,groupBy:groupBy,groupByLimit:groupByLimit,groupBySeries:groupBySeries,log:log,map:map,mapLimit:mapLimit,mapSeries:mapSeries,mapValues:mapValues,mapValuesLimit:mapValuesLimit,mapValuesSeries:mapValuesSeries,memoize:memoize,nextTick:nextTick,parallel:parallelLimit,parallelLimit:parallelLimit$1,priorityQueue:priorityQueue,queue:queue$1,race:race,reduce:reduce,reduceRight:reduceRight,reflect:reflect,reflectAll:reflectAll,reject:reject,rejectLimit:rejectLimit,rejectSeries:rejectSeries,retry:retry,retryable:retryable,seq:seq,series:series,setImmediate:setImmediate$1,some:some,someLimit:someLimit,someSeries:someSeries,sortBy:sortBy,timeout:timeout,times:times,timesLimit:timeLimit,timesSeries:timesSeries,transform:transform,tryEach:tryEach,unmemoize:unmemoize,until:until,waterfall:waterfall,whilst:whilst,all:every,allLimit:everyLimit,allSeries:everySeries,any:some,anyLimit:someLimit,anySeries:someSeries,find:detect,findLimit:detectLimit,findSeries:detectSeries,forEach:eachLimit,forEachSeries:eachSeries,forEachLimit:eachLimit$1,forEachOf:eachOf,forEachOfSeries:eachOfSeries,forEachOfLimit:eachOfLimit,inject:reduce,foldl:reduce,foldr:reduceRight,select:filter,selectLimit:filterLimit,selectSeries:filterSeries,wrapSync:asyncify};exports['default']=index;exports.apply=apply;exports.applyEach=applyEach;exports.applyEachSeries=applyEachSeries;exports.asyncify=asyncify;exports.auto=auto;exports.autoInject=autoInject;exports.cargo=cargo;exports.compose=compose;exports.concat=concat;exports.concatLimit=concatLimit;exports.concatSeries=concatSeries;exports.constant=constant;exports.detect=detect;exports.detectLimit=detectLimit;exports.detectSeries=detectSeries;exports.dir=dir;exports.doDuring=doDuring;exports.doUntil=doUntil;exports.doWhilst=doWhilst;exports.during=during;exports.each=eachLimit;exports.eachLimit=eachLimit$1;exports.eachOf=eachOf;exports.eachOfLimit=eachOfLimit;exports.eachOfSeries=eachOfSeries;exports.eachSeries=eachSeries;exports.ensureAsync=ensureAsync;exports.every=every;exports.everyLimit=everyLimit;exports.everySeries=everySeries;exports.filter=filter;exports.filterLimit=filterLimit;exports.filterSeries=filterSeries;exports.forever=forever;exports.groupBy=groupBy;exports.groupByLimit=groupByLimit;exports.groupBySeries=groupBySeries;exports.log=log;exports.map=map;exports.mapLimit=mapLimit;exports.mapSeries=mapSeries;exports.mapValues=mapValues;exports.mapValuesLimit=mapValuesLimit;exports.mapValuesSeries=mapValuesSeries;exports.memoize=memoize;exports.nextTick=nextTick;exports.parallel=parallelLimit;exports.parallelLimit=parallelLimit$1;exports.priorityQueue=priorityQueue;exports.queue=queue$1;exports.race=race;exports.reduce=reduce;exports.reduceRight=reduceRight;exports.reflect=reflect;exports.reflectAll=reflectAll;exports.reject=reject;exports.rejectLimit=rejectLimit;exports.rejectSeries=rejectSeries;exports.retry=retry;exports.retryable=retryable;exports.seq=seq;exports.series=series;exports.setImmediate=setImmediate$1;exports.some=some;exports.someLimit=someLimit;exports.someSeries=someSeries;exports.sortBy=sortBy;exports.timeout=timeout;exports.times=times;exports.timesLimit=timeLimit;exports.timesSeries=timesSeries;exports.transform=transform;exports.tryEach=tryEach;exports.unmemoize=unmemoize;exports.until=until;exports.waterfall=waterfall;exports.whilst=whilst;exports.all=every;exports.allLimit=everyLimit;exports.allSeries=everySeries;exports.any=so
var list=Object(this);var length=list.length>>>0;var thisArg=arguments[1];for(var i=0;i<length;i++){if(callback.call(thisArg,list[i],i,list)){return i;}}
return-1;});(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.nlp=factory());}(this,(function(){'use strict';function similar_text(first,second,percent){if(first===null||second===null||typeof first==='undefined'||typeof second==='undefined'){return 0;}
first+='';second+='';var pos1=0,pos2=0,max=0,firstLength=first.length,secondLength=second.length,p,q,l,sum;max=0;for(p=0;p<firstLength;p++){for(q=0;q<secondLength;q++){for(l=0;(p+l<firstLength)&&(q+l<secondLength)&&(first.charAt(p+l)===second.charAt(q+l));l++);if(l>max){max=l;pos1=p;pos2=q;}}}
sum=max;if(sum){if(pos1&&pos2){sum+=similar_text(first.substr(0,pos2),second.substr(0,pos2));}
if((pos1+max<firstLength)&&(pos2+max<secondLength)){sum+=similar_text(first.substr(pos1+max,firstLength-pos1-max),second.substr(pos2+max,secondLength-pos2-max));}}
if(!percent){return sum;}else{return(sum*200)/(firstLength+secondLength);}}
function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function(obj){return typeof obj;};}else{_typeof=function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}
return _typeof(obj);}
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}
function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}
function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}
subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}
function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}
function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}
function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}
function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
function _possibleConstructorReturn(self,call){if(call&&(typeof call==="object"||typeof call==="function")){return call;}
return _assertThisInitialized(self);}
function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}
return _possibleConstructorReturn(this,result);};}
function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}
function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}
function _iterableToArrayLimit(arr,i){if(typeof Symbol==="undefined"||!(Symbol.iterator in Object(arr)))return;var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}
return _arr;}
function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}
function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2;}
function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}
var chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split('');function makeId(str){str=str||'_';var text=str+'-';for(var i=0;i<7;i++){text+=chars[Math.floor(Math.random()*chars.length)];}
return text;}
var _id=makeId;var compact={'!':'¡','?':'¿Ɂ','"':'“”"❝❞',"'":'‘‛❛❜','-':'—–',a:'ªÀÁÂÃÄÅàáâãäåĀāĂ㥹ǍǎǞǟǠǡǺǻȀȁȂȃȦȧȺΆΑΔΛάαλАадѦѧӐӑӒӓƛɅæ',b:'ßþƀƁƂƃƄƅɃΒβϐϦБВЪЬвъьѢѣҌҍ',c:'¢©ÇçĆćĈĉĊċČčƆƇƈȻȼͻͼͽϲϹϽϾСсєҀҁҪҫ',d:'ÐĎďĐđƉƊȡƋƌǷ',e:'ÈÉÊËèéêëĒēĔĕĖėĘęĚěƎƏƐǝȄȅȆȇȨȩɆɇΈΕΞΣέεξϱϵ϶ЀЁЕЭеѐёҼҽҾҿӖӗӘәӚӛӬӭ',f:'ƑƒϜϝӺӻҒғſ',g:'ĜĝĞğĠġĢģƓǤǥǦǧǴǵ',h:'ĤĥĦħƕǶȞȟΉΗЂЊЋНнђћҢңҤҥҺһӉӊ',I:'ÌÍÎÏ',i:'ìíîïĨĩĪīĬĭĮįİıƖƗȈȉȊȋΊΐΪίιϊІЇії',j:'ĴĵǰȷɈɉϳЈј',k:'ĶķĸƘƙǨǩΚκЌЖКжкќҚқҜҝҞҟҠҡ',l:'ĹĺĻļĽľĿŀŁłƚƪǀǏǐȴȽΙӀӏ',m:'ΜϺϻМмӍӎ',n:'ÑñŃńŅņŇňʼnŊŋƝƞǸǹȠȵΝΠήηϞЍИЙЛПийлпѝҊҋӅӆӢӣӤӥπ',o:'ÒÓÔÕÖØðòóôõöøŌōŎŏŐőƟƠơǑǒǪǫǬǭǾǿȌȍȎȏȪȫȬȭȮȯȰȱΌΘΟθοσόϕϘϙϬϭϴОФоѲѳӦӧӨөӪӫ',p:'ƤƿΡρϷϸϼРрҎҏÞ',q:'Ɋɋ',r:'ŔŕŖŗŘřƦȐȑȒȓɌɍЃГЯгяѓҐґ',s:'ŚśŜŝŞşŠšƧƨȘșȿЅѕ',t:'ŢţŤťŦŧƫƬƭƮȚțȶȾΓΤτϮТт',u:'µÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųƯưƱƲǓǔǕǖǗǘǙǚǛǜȔȕȖȗɄΰμυϋύ',v:'νѴѵѶѷ',w:'ŴŵƜωώϖϢϣШЩшщѡѿ',x:'×ΧχϗϰХхҲҳӼӽӾӿ',y:'ÝýÿŶŷŸƳƴȲȳɎɏΎΥΫγψϒϓϔЎУучўѰѱҮүҰұӮӯӰӱӲӳ',z:'ŹźŻżŽžƩƵƶȤȥɀΖζ'};var unicode={};Object.keys(compact).forEach(function(k){compact[k].split('').forEach(function(s){unicode[s]=k;});});var killUnicode=function killUnicode(str){var chars=str.split('');chars.forEach(function(s,i){if(unicode[s]){chars[i]=unicode[s];}});return chars.join('');};var unicode_1=killUnicode;var periodAcronym=/([A-Z]\.)+[A-Z]?,?$/;var oneLetterAcronym=/^[A-Z]\.,?$/;var noPeriodAcronym=/[A-Z]{2,}('s|,)?$/;var lowerCaseAcronym=/([a-z]\.){2,}[a-z]\.?$/;var isAcronym=function isAcronym(str){if(periodAcronym.test(str)===true){return true;}
if(lowerCaseAcronym.test(str)===true){return true;}
if(oneLetterAcronym.test(str)===true){return true;}
if(noPeriodAcronym.test(str)===true){return true;}
return false;};var isAcronym_1=isAcronym;var hasSlash=/[a-z\u00C0-\u00FF] ?\/ ?[a-z\u00C0-\u00FF]/;var clean=function clean(str){str=str||'';str=str.toLowerCase();str=str.trim();var original=str;str=unicode_1(str);if(hasSlash.test(str)===true){str=str.replace(/\/.*/,'');}
str=str.replace(/^[#@]/,'');str=str.replace(/[,;.!?]+$/,'');str=str.replace(/[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]+/g,"'");str=str.replace(/[\u0022\u00AB\u00BB\u201C\u201D\u201E\u201F\u2033\u2034\u2036\u2037\u2E42\u301D\u301E\u301F\uFF02]+/g,'"');str=str.replace(/\u2026/g,'...');str=str.replace(/\u2013/g,'-');str=str.replace(/([aeiou][ktrp])in$/,'$1ing');if(/^(re|un)-?[^aeiou]./.test(str)===true){str=str.replace('-','');}
if(/^[:;]/.test(str)===false){str=str.replace(/\.{3,}$/g,'');str=str.replace(/[",\.!:;\?\)]+$/g,'');str=str.replace(/^['"\(]+/g,'');}
str=str.trim();if(str===''){str=original;}
if(isAcronym_1(str)){str=str.replace(/\./g,'');}
str=str.replace(/([0-9]),([0-9])/g,'$1$2');return str;};var clean_1=clean;var reduced=function reduced(str){str=str.replace(/[']s$/,'');str=str.replace(/s[']$/,'s');return str;};var reduce=reduced;var startings=/^[ \n\t\.'\[\](){}⟨⟩:,،、‒–—―…!.‹›«»‐\-?;\/⁄·&*•^†‡°¡¿※№÷׺ª%‰+=‱¶′″‴§~|‖¦©℗®℠™¤₳฿\u0022|\uFF02|\u0027|\u201C|\u2018|\u201F|\u201B|\u201E|\u2E42|\u201A|\u00AB|\u2039|\u2035|\u2036|\u2037|\u301D|\u0060|\u301F]+/;var endings=/[ \n\t\.'\[\](){}⟨⟩:,،、‒–—―…!.‹›«»‐\-?;\/⁄·&*@•^†‡°¡¿※#№÷׺ª‰+=‱¶′″‴§~|‖¦©℗®℠™¤₳฿\u0022|\uFF02|\u0027|\u201D|\u2019|\u201D|\u2019|\u201D|\u201D|\u2019|\u00BB|\u203A|\u2032|\u2033|\u2034|\u301E|\u00B4|\u301E]+$/;var hasSlash$1=/\//;var hasApostrophe=/[']/;var hasAcronym=/^[a-z]\.([a-z]\.)+/i;var minusNumber=/^[-+\.][0-9]/;var parseTerm=function parseTerm(str){var original=str;var pre='';var post='';str=str.replace(startings,function(found){pre=found;if((pre==='-'||pre==='+'||pre==='.')&&minusNumber.test(str)){pre='';return found;}
return'';});str=str.replace(endings,function(found){post=found;if(hasApostrophe.test(found)&&/[sn][']$/.test(original)&&hasApostrophe.test(pre)===false){post=post.replace(hasApostrophe,'');return"'";}
if(hasAcronym.test(str)===true){post=post.replace(/\./,'');return'.';}
return'';});if(str===''){original=original.replace(/ *$/,function(after){post=after||'';return'';});str=original;pre='';post=post;}
var clean=clean_1(str);var parsed={text:str,clean:clean,reduced:reduce(clean),pre:pre,post:post};if(hasSlash$1.test(str)){str.split(hasSlash$1).forEach(function(word){parsed.alias=parsed.alias||{};parsed.alias[word.trim()]=true;});}
return parsed;};var parse=parseTerm;function createCommonjsModule(fn,basedir,module){return module={path:basedir,exports:{},require:function(path,base){return commonjsRequire(path,(base===undefined||base===null)?module.path:base);}},fn(module,module.exports),module.exports;}
function commonjsRequire(){throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');}
var _01Case=createCommonjsModule(function(module,exports){var titleCase=/^[A-Z][a-z'\u00C0-\u00FF]/;var upperCase=/^[A-Z]+s?$/;exports.toUpperCase=function(){this.text=this.text.toUpperCase();return this;};exports.toLowerCase=function(){this.text=this.text.toLowerCase();return this;};exports.toTitleCase=function(){this.text=this.text.replace(/^ *[a-z\u00C0-\u00FF]/,function(x){return x.toUpperCase();});return this;};exports.isUpperCase=function(){return upperCase.test(this.text);};exports.isTitleCase=function(){return titleCase.test(this.text);};exports.titleCase=exports.isTitleCase;});var _02Punctuation=createCommonjsModule(function(module,exports){var startQuote=/(\u0022|\uFF02|\u0027|\u201C|\u2018|\u201F|\u201B|\u201E|\u2E42|\u201A|\u00AB|\u2039|\u2035|\u2036|\u2037|\u301D|\u0060|\u301F)/;var endQuote=/(\u0022|\uFF02|\u0027|\u201D|\u2019|\u201D|\u2019|\u201D|\u201D|\u2019|\u00BB|\u203A|\u2032|\u2033|\u2034|\u301E|\u00B4|\u301E)/;exports.hasPost=function(punct){return this.post.indexOf(punct)!==-1;};exports.hasPre=function(punct){return this.pre.indexOf(punct)!==-1;};exports.hasQuote=function(){return startQuote.test(this.pre)||endQuote.test(this.post);};exports.hasQuotation=exports.hasQuote;exports.hasComma=function(){return this.hasPost(',');};exports.hasPeriod=function(){return this.hasPost('.')===true&&this.hasPost('...')===false;};exports.hasExclamation=function(){return this.hasPost('!');};exports.hasQuestionMark=function(){return this.hasPost('?')||this.hasPost('¿');};exports.hasEllipses=function(){return this.hasPost('..')||this.hasPost('…')||this.hasPre('..')||this.hasPre('…');};exports.hasSemicolon=function(){return this.hasPost(';');};exports.hasSlash=function(){var slash=/\//;return slash.test(this.text);};exports.hasHyphen=function(){var hyphen=/(-||—)/;return hyphen.test(this.post)||hyphen.test(this.pre);};exports.hasDash=function(){var hyphen=/ (-||—) /;return hyphen.test(this.post)||hyphen.test(this.pre);};exports.hasContraction=function(){return Boolean(this.implicit);};exports.addPunctuation=function(punct){if(punct===','||punct===';'){this.post=this.post.replace(punct,'');}
this.post=punct+this.post;return this;};});var wrapMatch=function wrapMatch(){};var doesMatch=function doesMatch(t,reg,index,length){if(reg.id===t.id){return true;}
if(reg.anything===true){return true;}
if(reg.start===true&&index!==0){return false;}
if(reg.end===true&&index!==length-1){return false;}
if(reg.word!==undefined){if(t.implicit!==null&&t.implicit===reg.word){return true;}
if(t.alias!==undefined&&t.alias.hasOwnProperty(reg.word)){return true;}
if(reg.soft===true&&reg.word===t.root){return true;}
return reg.word===t.clean||reg.word===t.text||reg.word===t.reduced;}
if(reg.tag!==undefined){return t.tags[reg.tag]===true;}
if(reg.method!==undefined){if(typeof t[reg.method]==='function'&&t[reg.method]()===true){return true;}
return false;}
if(reg.regex!==undefined){return reg.regex.test(t.clean);}
if(reg.oneOf!==undefined){return reg.oneOf.hasOwnProperty(t.reduced)||reg.oneOf.hasOwnProperty(t.text);}
if(reg.choices!==undefined){if(reg.operator==='and'){return reg.choices.every(function(r){return wrapMatch(t,r,index,length);});}
return reg.choices.some(function(r){return wrapMatch(t,r,index,length);});}
return false;};wrapMatch=function wrapMatch(t,reg,index,length){var result=doesMatch(t,reg,index,length);if(reg.negative===true){return!result;}
return result;};var _doesMatch=wrapMatch;var boring={};var doesMatch_1=function doesMatch_1(reg,index,length){return _doesMatch(this,reg,index,length);};var isAcronym_1$1=function isAcronym_1$1(){return isAcronym_1(this.text);};var isImplicit=function isImplicit(){return this.text===''&&Boolean(this.implicit);};var isKnown=function isKnown(){return Object.keys(this.tags).some(function(t){return boring[t]!==true;});};var setRoot=function setRoot(world){var transform=world.transforms;var str=this.implicit||this.clean;if(this.tags.Plural){str=transform.toSingular(str,world);}
if(this.tags.Verb&&!this.tags.Negative&&!this.tags.Infinitive){var tense=null;if(this.tags.PastTense){tense='PastTense';}else if(this.tags.Gerund){tense='Gerund';}else if(this.tags.PresentTense){tense='PresentTense';}else if(this.tags.Participle){tense='Participle';}else if(this.tags.Actor){tense='Actor';}
str=transform.toInfinitive(str,world,tense);}
this.root=str;};var _03Misc={doesMatch:doesMatch_1,isAcronym:isAcronym_1$1,isImplicit:isImplicit,isKnown:isKnown,setRoot:setRoot};var hasSpace=/[\s-]/;var isUpperCase=/^[A-Z-]+$/;var textOut=function textOut(options,showPre,showPost){options=options||{};var word=this.text;var before=this.pre;var after=this.post;if(options.reduced===true){word=this.reduced||'';}
if(options.root===true){word=this.root||'';}
if(options.implicit===true&&this.implicit){word=this.implicit||'';}
if(options.normal===true){word=this.clean||this.text||'';}
if(options.root===true){word=this.root||this.reduced||'';}
if(options.unicode===true){word=unicode_1(word);}
if(options.titlecase===true){if(this.tags.ProperNoun&&!this.titleCase());else if(this.tags.Acronym){word=word.toUpperCase();}else if(isUpperCase.test(word)&&!this.tags.Acronym){word=word.toLowerCase();}}
if(options.lowercase===true){word=word.toLowerCase();}
if(options.acronyms===true&&this.tags.Acronym){word=word.replace(/\./g,'');}
if(options.whitespace===true||options.root===true){before='';after=' ';if((hasSpace.test(this.post)===false||options.last)&&!this.implicit){after='';}}
if(options.punctuation===true&&!options.root){if(this.hasPost('.')===true){after='.'+after;}else if(this.hasPost('?')===true){after='?'+after;}else if(this.hasPost('!')===true){after='!'+after;}else if(this.hasPost(',')===true){after=','+after;}else if(this.hasEllipses()===true){after='...'+after;}}
if(showPre!==true){before='';}
if(showPost!==true){after='';}
if(options.abbreviations===true&&this.tags.Abbreviation){after=after.replace(/^\./,'');}
return before+word+after;};var _04Text={textOut:textOut};var boringTags={Auxiliary:1,Possessive:1};var rankTags=function rankTags(term,world){var tags=Object.keys(term.tags);var tagSet=world.tags;tags=tags.sort(function(a,b){if(boringTags[b]||!tagSet[b]){return-1;}
if(!tagSet[b]){return 1;}
if(!tagSet[a]){return 0;}
if(tagSet[a].lineage.length>tagSet[b].lineage.length){return 1;}
if(tagSet[a].isA.length>tagSet[b].isA.length){return-1;}
return 0;});return tags;};var _bestTag=rankTags;var jsonDefault={text:true,tags:true,implicit:true,whitespace:true,clean:false,id:false,index:false,offset:false,bestTag:false};var json=function json(options,world){options=options||{};options=Object.assign({},jsonDefault,options);var result={};if(options.text){result.text=this.text;}
if(options.normal){result.normal=this.normal;}
if(options.tags){result.tags=Object.keys(this.tags);}
if(options.clean){result.clean=this.clean;}
if(options.id||options.offset){result.id=this.id;}
if(options.implicit&&this.implicit!==null){result.implicit=this.implicit;}
if(options.whitespace){result.pre=this.pre;result.post=this.post;}
if(options.bestTag){result.bestTag=_bestTag(this,world)[0];}
return result;};var _05Json={json:json};var methods=Object.assign({},_01Case,_02Punctuation,_03Misc,_04Text,_05Json);function isClientSide(){return typeof window!=='undefined'&&window.document;}
var padEnd=function padEnd(str,width){str=str.toString();while(str.length<width){str+=' ';}
return str;};var logTag=function logTag(t,tag,reason){if(isClientSide()){console.log('%c'+padEnd(t.clean,3)+' + '+tag+' ','color: #6accb2;');return;}
var log='\x1b[33m'+padEnd(t.clean,15)+'\x1b[0m + \x1b[32m'+tag+'\x1b[0m ';if(reason){log=padEnd(log,35)+' '+reason+'';}
console.log(log);};var logUntag=function logUntag(t,tag,reason){if(isClientSide()){console.log('%c'+padEnd(t.clean,3)+' - '+tag+' ','color: #AB5850;');return;}
var log='\x1b[33m'+padEnd(t.clean,3)+' \x1b[31m - #'+tag+'\x1b[0m ';if(reason){log=padEnd(log,35)+' '+reason;}
console.log(log);};var isArray=function isArray(arr){return Object.prototype.toString.call(arr)==='[object Array]';};var titleCase=function titleCase(str){return str.charAt(0).toUpperCase()+str.substr(1);};var fns={logTag:logTag,logUntag:logUntag,isArray:isArray,titleCase:titleCase};var addTag=function addTag(t,tag,reason,world){var tagset=world.tags;if(tag===''||tag==='.'||tag==='-'){return;}
if(tag[0]==='#'){tag=tag.replace(/^#/,'');}
tag=fns.titleCase(tag);if(t.tags[tag]===true){return;}
var isVerbose=world.isVerbose();if(isVerbose===true){fns.logTag(t,tag,reason);}
t.tags[tag]=true;if(tagset.hasOwnProperty(tag)===true){tagset[tag].isA.forEach(function(down){t.tags[down]=true;if(isVerbose===true){fns.logTag(t,'→ '+down);}});t.unTag(tagset[tag].notA,'←',world);}};var addTags=function addTags(term,tags,reason,world){if(typeof tags!=='string'){for(var i=0;i<tags.length;i++){addTag(term,tags[i],reason,world);}}else{addTag(term,tags,reason,world);}};var add=addTags;var lowerCase=/^[a-z]/;var titleCase$1=function titleCase(str){return str.charAt(0).toUpperCase()+str.substr(1);};var unTag=function unTag(t,tag,reason,world){var isVerbose=world.isVerbose();if(tag==='*'){t.tags={};return t;}
tag=tag.replace(/^#/,'');if(lowerCase.test(tag)===true){tag=titleCase$1(tag);}
if(t.tags[tag]===true){delete t.tags[tag];if(isVerbose===true){fns.logUntag(t,tag,reason);}}
var tagset=world.tags;if(tagset[tag]){var lineage=tagset[tag].lineage;for(var i=0;i<lineage.length;i++){if(t.tags[lineage[i]]===true){delete t.tags[lineage[i]];if(isVerbose===true){fns.logUntag(t,' - '+lineage[i]);}}}}
return t;};var untagAll=function untagAll(term,tags,reason,world){if(typeof tags!=='string'&&tags){for(var i=0;i<tags.length;i++){unTag(term,tags[i],reason,world);}
return;}
unTag(term,tags,reason,world);};var unTag_1=untagAll;var canBe=function canBe(term,tag,world){var tagset=world.tags;if(tag[0]==='#'){tag=tag.replace(/^#/,'');}
if(tagset[tag]===undefined){return true;}
var enemies=tagset[tag].notA||[];for(var i=0;i<enemies.length;i++){if(term.tags[enemies[i]]===true){return false;}}
if(tagset[tag].isA!==undefined){return canBe(term,tagset[tag].isA,world);}
return true;};var canBe_1=canBe;var tag_1=function tag_1(tags,reason,world){add(this,tags,reason,world);return this;};var tagSafe=function tagSafe(tags,reason,world){if(canBe_1(this,tags,world)){add(this,tags,reason,world);}
return this;};var unTag_1$1=function unTag_1$1(tags,reason,world){unTag_1(this,tags,reason,world);return this;};var canBe_1$1=function canBe_1$1(tags,world){return canBe_1(this,tags,world);};var tag={tag:tag_1,tagSafe:tagSafe,unTag:unTag_1$1,canBe:canBe_1$1};var Term=function(){function Term(){var text=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';_classCallCheck(this,Term);text=String(text);var obj=parse(text);this.text=obj.text||'';this.clean=obj.clean;this.reduced=obj.reduced;this.root=null;this.implicit=null;this.pre=obj.pre||'';this.post=obj.post||'';this.tags={};this.prev=null;this.next=null;this.id=_id(obj.clean);this.isA='Term';if(obj.alias){this.alias=obj.alias;}}
_createClass(Term,[{key:"set",value:function set(str){var obj=parse(str);this.text=obj.text;this.clean=obj.clean;return this;}}]);return Term;}();Term.prototype.clone=function(){var term=new Term(this.text);term.pre=this.pre;term.post=this.post;term.clean=this.clean;term.reduced=this.reduced;term.root=this.root;term.implicit=this.implicit;term.tags=Object.assign({},this.tags);return term;};Object.assign(Term.prototype,methods);Object.assign(Term.prototype,tag);var Term_1=Term;var terms=function terms(n){if(this.length===0){return[];}
if(this.cache.terms){if(n!==undefined){return this.cache.terms[n];}
return this.cache.terms;}
var terms=[this.pool.get(this.start)];for(var i=0;i<this.length-1;i+=1){var id=terms[terms.length-1].next;if(id===null){console.error("Compromise error: Linked list broken in phrase '"+this.start+"'");break;}
var term=this.pool.get(id);terms.push(term);if(n!==undefined&&n===i){return terms[n];}}
if(n===undefined){this.cache.terms=terms;}
if(n!==undefined){return terms[n];}
return terms;};var clone=function clone(isShallow){var _this=this;if(isShallow){var p=this.buildFrom(this.start,this.length);p.cache=this.cache;return p;}
var terms=this.terms();var newTerms=terms.map(function(t){return t.clone();});newTerms.forEach(function(t,i){_this.pool.add(t);if(newTerms[i+1]){t.next=newTerms[i+1].id;}
if(newTerms[i-1]){t.prev=newTerms[i-1].id;}});return this.buildFrom(newTerms[0].id,newTerms.length);};var lastTerm=function lastTerm(){var terms=this.terms();return terms[terms.length-1];};var hasId=function hasId(wantId){if(this.length===0||!wantId){return false;}
if(this.start===wantId){return true;}
if(this.cache.terms){var _terms=this.cache.terms;for(var i=0;i<_terms.length;i++){if(_terms[i].id===wantId){return true;}}
return false;}
var lastId=this.start;for(var _i=0;_i<this.length-1;_i+=1){var term=this.pool.get(lastId);if(term===undefined){console.error("Compromise error: Linked list broken. Missing term '".concat(lastId,"' in phrase '").concat(this.start,"'\n"));return false;}
if(term.next===wantId){return true;}
lastId=term.next;}
return false;};var wordCount=function wordCount(){return this.terms().filter(function(t){return t.text!=='';}).length;};var fullSentence=function fullSentence(){var t=this.terms(0);while(t.prev){t=this.pool.get(t.prev);}
var start=t.id;var len=1;while(t.next){t=this.pool.get(t.next);len+=1;}
return this.buildFrom(start,len);};var _01Utils={terms:terms,clone:clone,lastTerm:lastTerm,hasId:hasId,wordCount:wordCount,fullSentence:fullSentence};var trimEnd=function trimEnd(str){return str.replace(/ +$/,'');};var text=function text(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var isFirst=arguments.length>1?arguments[1]:undefined;var isLast=arguments.length>2?arguments[2]:undefined;if(typeof options==='string'){if(options==='normal'){options={whitespace:true,unicode:true,lowercase:true,punctuation:true,acronyms:true,abbreviations:true,implicit:true,normal:true};}else if(options==='clean'){options={titlecase:false,lowercase:true,punctuation:true,whitespace:true,unicode:true,implicit:true};}else if(options==='reduced'){options={titlecase:false,lowercase:true,punctuation:false,whitespace:true,unicode:true,implicit:true,reduced:true};}else if(options==='root'){options={titlecase:false,lowercase:true,punctuation:true,whitespace:true,unicode:true,implicit:true,root:true};}else{options={};}}
var terms=this.terms();var isFull=false;if(terms[0]&&terms[0].prev===null&&terms[terms.length-1].next===null){isFull=true;}
var text=terms.reduce(function(str,t,i){options.last=isLast&&i===terms.length-1;var showPre=true;var showPost=true;if(isFull===false){if(i===0&&isFirst){showPre=false;}
if(i===terms.length-1&&isLast){showPost=false;}}
var txt=t.textOut(options,showPre,showPost);return str+txt;},'');if(isFull===true&&isLast){text=trimEnd(text);}
if(options.trim===true){text=text.trim();}
return text;};var _02Text={text:text};var trim=function trim(){var terms=this.terms();if(terms.length>0){terms[0].pre=terms[0].pre.replace(/^\s+/,'');var lastTerm=terms[terms.length-1];lastTerm.post=lastTerm.post.replace(/\s+$/,'');}
return this;};var _03Change={trim:trim};var endOfSentence=/[.?!]\s*$/;var combinePost=function combinePost(before,after){if(endOfSentence.test(after)){var whitespace=before.match(/\s*$/);return after+whitespace;}
return before;};var addWhitespace=function addWhitespace(beforeTerms,newTerms){newTerms[0].pre=beforeTerms[0].pre;var lastTerm=beforeTerms[beforeTerms.length-1];var newTerm=newTerms[newTerms.length-1];newTerm.post=combinePost(lastTerm.post,newTerm.post);lastTerm.post='';if(lastTerm.post===''){lastTerm.post+=' ';}};var stitchIn=function stitchIn(beforeTerms,newTerms,pool){var lastBefore=beforeTerms[beforeTerms.length-1];var lastNew=newTerms[newTerms.length-1];var afterId=lastBefore.next;lastBefore.next=newTerms[0].id;lastNew.next=afterId;if(afterId){var afterTerm=pool.get(afterId);afterTerm.prev=lastNew.id;}
var beforeId=beforeTerms[0].id;if(beforeId){var newTerm=newTerms[0];newTerm.prev=beforeId;}};var unique=function unique(list){return list.filter(function(o,i){return list.indexOf(o)===i;});};var appendPhrase=function appendPhrase(before,newPhrase,doc){var beforeTerms=before.terms();var newTerms=newPhrase.terms();addWhitespace(beforeTerms,newTerms);stitchIn(beforeTerms,newTerms,before.pool);var toStretch=[before];var hasId=before.start;var docs=[doc];docs=docs.concat(doc.parents());docs.forEach(function(parent){var shouldChange=parent.list.filter(function(p){return p.hasId(hasId);});toStretch=toStretch.concat(shouldChange);});toStretch=unique(toStretch);toStretch.forEach(function(p){p.length+=newPhrase.length;});before.cache={};return before;};var append=appendPhrase;var hasSpace$1=/ /;var addWhitespace$1=function addWhitespace(newTerms){var lastTerm=newTerms[newTerms.length-1];if(hasSpace$1.test(lastTerm.post)===false){lastTerm.post+=' ';}
return;};var stitchIn$1=function stitchIn(main,newPhrase,newTerms){var lastTerm=newTerms[newTerms.length-1];lastTerm.next=main.start;var pool=main.pool;var start=pool.get(main.start);if(start.prev){var before=pool.get(start.prev);before.next=newPhrase.start;}
newTerms[0].prev=main.terms(0).prev;main.terms(0).prev=lastTerm.id;};var unique$1=function unique(list){return list.filter(function(o,i){return list.indexOf(o)===i;});};var joinPhrase=function joinPhrase(original,newPhrase,doc){var starterId=original.start;var newTerms=newPhrase.terms();addWhitespace$1(newTerms);stitchIn$1(original,newPhrase,newTerms);var toStretch=[original];var docs=[doc];docs=docs.concat(doc.parents());docs.forEach(function(d){var shouldChange=d.list.filter(function(p){return p.hasId(starterId)||p.hasId(newPhrase.start);});toStretch=toStretch.concat(shouldChange);});toStretch=unique$1(toStretch);toStretch.forEach(function(p){p.length+=newPhrase.length;if(p.start===starterId){p.start=newPhrase.start;}
p.cache={};});return original;};var prepend=joinPhrase;var shrinkAll=function shrinkAll(doc,id,deleteLength,after){var arr=doc.parents();arr.push(doc);arr.forEach(function(d){var phrase=d.list.find(function(p){return p.hasId(id);});if(!phrase){return;}
phrase.length-=deleteLength;if(phrase.start===id){phrase.start=after.id;}
phrase.cache={};});doc.list=doc.list.filter(function(p){if(!p.start||!p.length){return false;}
return true;});};var deletePhrase=function deletePhrase(phrase,doc){var pool=doc.pool();var terms=phrase.terms();var prev=pool.get(terms[0].prev)||{};var after=pool.get(terms[terms.length-1].next)||{};if(terms[0].implicit&&prev.implicit){prev.set(prev.implicit);prev.post+=' ';}
shrinkAll(doc,phrase.start,phrase.length,after);if(prev){prev.next=after.id;}
if(after){after.prev=prev.id;}};var _delete=deletePhrase;var append_1=function append_1(newPhrase,doc){append(this,newPhrase,doc);return this;};var prepend_1=function prepend_1(newPhrase,doc){prepend(this,newPhrase,doc);return this;};var _delete$1=function _delete$1(doc){_delete(this,doc);return this;};var replace=function replace(newPhrase,doc){var firstLength=this.length;append(this,newPhrase,doc);var tmp=this.buildFrom(this.start,this.length);tmp.length=firstLength;_delete(tmp,doc);};var splitOn=function splitOn(p){var terms=this.terms();var result={before:null,match:null,after:null};var index=terms.findIndex(function(t){return t.id===p.start;});if(index===-1){return result;}
var start=terms.slice(0,index);if(start.length>0){result.before=this.buildFrom(start[0].id,start.length);}
var match=terms.slice(index,index+p.length);if(match.length>0){result.match=this.buildFrom(match[0].id,match.length);}
var end=terms.slice(index+p.length,terms.length);if(end.length>0){result.after=this.buildFrom(end[0].id,end.length,this.pool);}
return result;};var _04Insert={append:append_1,prepend:prepend_1,"delete":_delete$1,replace:replace,splitOn:splitOn};var json$1=function json(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var world=arguments.length>1?arguments[1]:undefined;var res={};if(options.text){res.text=this.text();}
if(options.normal){res.normal=this.text('normal');}
if(options.clean){res.clean=this.text('clean');}
if(options.reduced){res.reduced=this.text('reduced');}
if(options.root){res.root=this.text('root');}
if(options.trim){if(res.text){res.text=res.text.trim();}
if(res.normal){res.normal=res.normal.trim();}
if(res.reduced){res.reduced=res.reduced.trim();}}
if(options.terms){if(options.terms===true){options.terms={};}
res.terms=this.terms().map(function(t){return t.json(options.terms,world);});}
return res;};var _05Json$1={json:json$1};var lookAhead=function lookAhead(regs){if(!regs){regs='.*';}
var pool=this.pool;var terms=[];var getAfter=function getAfter(id){var term=pool.get(id);if(!term){return;}
terms.push(term);if(term.prev){getAfter(term.next);}};var all=this.terms();var lastTerm=all[all.length-1];getAfter(lastTerm.next);if(terms.length===0){return[];}
var p=this.buildFrom(terms[0].id,terms.length);return p.match(regs);};var lookBehind=function lookBehind(regs){if(!regs){regs='.*';}
var pool=this.pool;var terms=[];var getBefore=function getBefore(id){var term=pool.get(id);if(!term){return;}
terms.push(term);if(term.prev){getBefore(term.prev);}};var term=pool.get(this.start);getBefore(term.prev);if(terms.length===0){return[];}
var p=this.buildFrom(terms[terms.length-1].id,terms.length);return p.match(regs);};var _06Lookahead={lookAhead:lookAhead,lookBehind:lookBehind};var methods$1=Object.assign({},_01Utils,_02Text,_03Change,_04Insert,_05Json$1,_06Lookahead);var failFast=function failFast(p,regs){if(regs.length===0){return true;}
for(var i=0;i<regs.length;i+=1){var reg=regs[i];if(reg.optional!==true&&reg.negative!==true){if(reg.start===true&&i>0){return true;}}
if(reg.anything===true&&reg.negative===true){return true;}}
return false;};var _02FailFast=failFast;var getGreedy=function getGreedy(terms,t,reg,until,index,length){var start=t;for(;t<terms.length;t+=1){if(until&&terms[t].doesMatch(until,index+t,length)){return t;}
var count=t-start+1;if(reg.max!==undefined&&count===reg.max){return t;}
if(terms[t].doesMatch(reg,index+t,length)===false){if(reg.min!==undefined&&count<reg.min){return null;}
return t;}}
return t;};var greedyTo=function greedyTo(terms,t,nextReg,index,length){if(!nextReg){return terms.length;}
for(;t<terms.length;t+=1){if(terms[t].doesMatch(nextReg,index+t,length)===true){return t;}}
return null;};var getOrCreateGroup=function getOrCreateGroup(namedGroups,namedGroupId,terms,startIndex,group){var g=namedGroups[namedGroupId];if(g){return g;}
var id=terms[startIndex].id;namedGroups[namedGroupId]={group:String(group),start:id,length:0};return namedGroups[namedGroupId];};var tryHere=function tryHere(terms,regs,index,length){var namedGroups={};var previousGroupId=null;var t=0;for(var r=0;r<regs.length;r+=1){var reg=regs[r];var isNamedGroup=typeof reg.named==='string'||typeof reg.named==='number';var namedGroupId=null;if(isNamedGroup){var prev=regs[r-1];if(prev&&prev.named===reg.named&&previousGroupId){namedGroupId=previousGroupId;}else{namedGroupId=_id(reg.named);previousGroupId=namedGroupId;}}
if(!terms[t]){var hasNeeds=regs.slice(r).some(function(remain){return!remain.optional;});if(hasNeeds===false){break;}
return[false,null];}
if(reg.anything===true&&reg.greedy===true){var skipto=greedyTo(terms,t,regs[r+1],reg,index);if(reg.min!==undefined&&skipto-t<reg.min){return[false,null];}
if(reg.max!==undefined&&skipto-t>reg.max){t=t+reg.max;continue;}
if(skipto===null){return[false,null];}
if(isNamedGroup){var g=getOrCreateGroup(namedGroups,namedGroupId,terms,t,reg.named);g.length=skipto-t;}
t=skipto;continue;}
if(reg.anything===true||reg.end===true&&reg.greedy===true&&index+t<length-1&&terms[t].doesMatch(Object.assign({},reg,{end:false}),index+t,length)===true||terms[t].doesMatch(reg,index+t,length)===true){var startAt=t;if(reg.optional&&regs[r+1]){if(terms[t].doesMatch(regs[r+1],index+t,length)===true){if(!terms[t+1]||terms[t+1].doesMatch(regs[r+1],index+t,length)===false){r+=1;}}}
t+=1;if(reg.end===true){if(t!==terms.length&&reg.greedy!==true){return[false,null];}}
if(reg.greedy===true){t=getGreedy(terms,t,Object.assign({},reg,{start:false,end:false}),regs[r+1],index,length);if(t===null){return[false,null];}
if(reg.min&&reg.min>t){return[false,null];}
if(reg.end===true&&index+t!==length){return[false,null];}}
if(isNamedGroup){var _g=getOrCreateGroup(namedGroups,namedGroupId,terms,startAt,reg.named);if(t>1&&reg.greedy){_g.length+=t-startAt;}else{_g.length++;}}
continue;}
if(reg.optional===true){continue;}
if(terms[t].isImplicit()&&regs[r-1]&&terms[t+1]){if(terms[t+1].doesMatch(reg,index+t,length)){t+=2;continue;}}
return[false,null];}
return[terms.slice(0,t),namedGroups];};var _03TryMatch=tryHere;var postProcess=function postProcess(terms,regs,matches){if(!matches||matches.length===0){return matches;}
var atEnd=regs.some(function(r){return r.end;});if(atEnd){var lastTerm=terms[terms.length-1];matches=matches.filter(function(_ref){var arr=_ref.match;return arr.indexOf(lastTerm)!==-1;});}
return matches;};var _04PostProcess=postProcess;var hasMinMax=/\{([0-9]+,?[0-9]*)\}/;var andSign=/&&/;var captureName=new RegExp(/^<(\S+)>/);var titleCase$2=function titleCase(str){return str.charAt(0).toUpperCase()+str.substr(1);};var end=function end(str){return str[str.length-1];};var start=function start(str){return str[0];};var stripStart=function stripStart(str){return str.substr(1);};var stripEnd=function stripEnd(str){return str.substr(0,str.length-1);};var stripBoth=function stripBoth(str){str=stripStart(str);str=stripEnd(str);return str;};var parseToken=function parseToken(w){var obj={};for(var i=0;i<2;i+=1){if(end(w)==='$'){obj.end=true;w=stripEnd(w);}
if(start(w)==='^'){obj.start=true;w=stripStart(w);}
if(start(w)==='['||end(w)===']'){obj.named=true;if(start(w)==='['){obj.groupType=end(w)===']'?'single':'start';}else{obj.groupType='end';}
w=w.replace(/^\[/,'');w=w.replace(/\]$/,'');if(start(w)==='<'){var res=captureName.exec(w);if(res.length>=2){obj.named=res[1];w=w.replace(res[0],'');}}}
if(end(w)==='+'){obj.greedy=true;w=stripEnd(w);}
if(w!=='*'&&end(w)==='*'&&w!=='\\*'){obj.greedy=true;w=stripEnd(w);}
if(end(w)==='?'){obj.optional=true;w=stripEnd(w);}
if(start(w)==='!'){obj.negative=true;w=stripStart(w);}
if(start(w)==='('&&end(w)===')'){if(andSign.test(w)){obj.choices=w.split(andSign);obj.operator='and';}else{obj.choices=w.split('|');obj.operator='or';}
obj.choices[0]=stripStart(obj.choices[0]);var last=obj.choices.length-1;obj.choices[last]=stripEnd(obj.choices[last]);obj.choices=obj.choices.map(function(s){return s.trim();});obj.choices=obj.choices.filter(function(s){return s;});obj.choices=obj.choices.map(parseToken);w='';}
if(start(w)==='/'&&end(w)==='/'){w=stripBoth(w);obj.regex=new RegExp(w);return obj;}
if(start(w)==='~'&&end(w)==='~'){w=stripBoth(w);obj.soft=true;obj.word=w;return obj;}}
if(hasMinMax.test(w)===true){w=w.replace(hasMinMax,function(a,b){var arr=b.split(/,/g);if(arr.length===1){obj.min=Number(arr[0]);obj.max=Number(arr[0]);}else{obj.min=Number(arr[0]);obj.max=Number(arr[1]||999);}
obj.greedy=true;return'';});}
if(start(w)==='#'){obj.tag=stripStart(w);obj.tag=titleCase$2(obj.tag);return obj;}
if(start(w)==='@'){obj.method=stripStart(w);return obj;}
if(w==='.'){obj.anything=true;return obj;}
if(w==='*'){obj.anything=true;obj.greedy=true;obj.optional=true;return obj;}
if(w){w=w.replace('\\*','*');w=w.replace('\\.','.');obj.word=w.toLowerCase();}
return obj;};var parseToken_1=parseToken;var isNamed=function isNamed(capture){return typeof capture==='string'||typeof capture==='number';};var fillGroups=function fillGroups(tokens){var convert=false;var index=-1;var current;for(var i=0;i<tokens.length;i++){var n=tokens[i];if(n.groupType==='single'&&n.named===true){index+=1;n.named=index;continue;}
if(n.groupType==='start'){convert=true;if(isNamed(n.named)){current=n.named;}else{index+=1;current=index;}}
if(convert){n.named=current;}
if(n.groupType==='end'){convert=false;}}
return tokens;};var useOneOf=function useOneOf(tokens){return tokens.map(function(token){if(token.choices!==undefined){var shouldPack=token.choices.every(function(c){return c.optional!==true&&c.negative!==true&&c.word!==undefined;});if(shouldPack===true){var oneOf={};token.choices.forEach(function(c){return oneOf[c.word]=true;});token.oneOf=oneOf;delete token.choices;}}
return token;});};var postProcess$1=function postProcess(tokens){var count=tokens.filter(function(t){return t.groupType;}).length;if(count>0){tokens=fillGroups(tokens);}
tokens=useOneOf(tokens);return tokens;};var postProcess_1=postProcess$1;var isArray$1=function isArray(arr){return Object.prototype.toString.call(arr)==='[object Array]';};var byParentheses=function byParentheses(str){var arr=str.split(/([\^\[\!]*(?:<\S+>)?\(.*?\)[?+*]*\]?\$?)/);arr=arr.map(function(s){return s.trim();});return arr;};var byWords=function byWords(arr){var words=[];arr.forEach(function(a){if(/^[[^_/]?\(/.test(a[0])){words.push(a);return;}
var list=a.split(' ');list=list.filter(function(w){return w;});words=words.concat(list);});return words;};var byArray=function byArray(arr){return[{choices:arr.map(function(s){return{word:s};})}];};var fromDoc=function fromDoc(doc){if(!doc||!doc.list||!doc.list[0]){return[];}
var ids=[];doc.list.forEach(function(p){p.terms().forEach(function(t){ids.push({id:t.id});});});return[{choices:ids,greedy:true}];};var syntax=function syntax(input){if(input===null||input===undefined||input===''){return[];}
if(_typeof(input)==='object'){if(isArray$1(input)){if(input.length===0||!input[0]){return[];}
if(_typeof(input[0])==='object'){return input;}
if(typeof input[0]==='string'){return byArray(input);}}
if(input&&input.isA==='Doc'){return fromDoc(input);}
return[];}
if(typeof input==='number'){input=String(input);}
var tokens=byParentheses(input);tokens=byWords(tokens);tokens=tokens.map(parseToken_1);tokens=postProcess_1(tokens);return tokens;};var syntax_1=syntax;var matchAll=function matchAll(p,regs){var matchOne=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(typeof regs==='string'){regs=syntax_1(regs);}
if(_02FailFast(p,regs)===true){return[];}
var minLength=regs.filter(function(r){return r.optional!==true;}).length;var terms=p.terms();var matches=[];if(regs[0].start===true){var _tryMatch=_03TryMatch(terms,regs,0,terms.length),_tryMatch2=_slicedToArray(_tryMatch,2),match=_tryMatch2[0],groups=_tryMatch2[1];if(match!==false&&match.length>0){match=match.filter(function(m){return m;});matches.push({match:match,groups:groups});}
return _04PostProcess(terms,regs,matches);}
for(var i=0;i<terms.length;i+=1){if(i+minLength>terms.length){break;}
var _tryMatch3=_03TryMatch(terms.slice(i),regs,i,terms.length),_tryMatch4=_slicedToArray(_tryMatch3,2),_match=_tryMatch4[0],_groups=_tryMatch4[1];if(_match!==false&&_match.length>0){i+=_match.length-1;_match=_match.filter(function(m){return m;});matches.push({match:_match,groups:_groups});if(matchOne===true){return _04PostProcess(terms,regs,matches);}}}
return _04PostProcess(terms,regs,matches);};var _01MatchAll=matchAll;var notMatch=function notMatch(p,regs){var found={};var arr=_01MatchAll(p,regs);arr.forEach(function(_ref){var ts=_ref.match;ts.forEach(function(t){found[t.id]=true;});});var terms=p.terms();var result=[];var current=[];terms.forEach(function(t){if(found[t.id]===true){if(current.length>0){result.push(current);current=[];}
return;}
current.push(t);});if(current.length>0){result.push(current);}
return result;};var not=notMatch;var match_1=function match_1(regs){var _this=this;var justOne=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var matches=_01MatchAll(this,regs,justOne);matches=matches.map(function(_ref){var match=_ref.match,groups=_ref.groups;var p=_this.buildFrom(match[0].id,match.length,groups);p.cache.terms=match;return p;});return matches;};var has=function has(regs){var matches=_01MatchAll(this,regs,true);return matches.length>0;};var not$1=function not$1(regs){var _this2=this;var matches=not(this,regs);matches=matches.map(function(list){return _this2.buildFrom(list[0].id,list.length);});return matches;};var canBe$1=function canBe(tag,world){var _this3=this;var results=[];var terms=this.terms();var previous=false;for(var i=0;i<terms.length;i+=1){var can=terms[i].canBe(tag,world);if(can===true){if(previous===true){results[results.length-1].push(terms[i]);}else{results.push([terms[i]]);}
previous=can;}}
results=results.filter(function(a){return a.length>0;}).map(function(arr){return _this3.buildFrom(arr[0].id,arr.length);});return results;};var match={match:match_1,has:has,not:not$1,canBe:canBe$1};var Phrase=function Phrase(id,length,pool){_classCallCheck(this,Phrase);this.start=id;this.length=length;this.isA='Phrase';Object.defineProperty(this,'pool',{enumerable:false,writable:true,value:pool});Object.defineProperty(this,'cache',{enumerable:false,writable:true,value:{}});Object.defineProperty(this,'groups',{enumerable:false,writable:true,value:{}});};Phrase.prototype.buildFrom=function(id,length,groups){var p=new Phrase(id,length,this.pool);if(groups&&Object.keys(groups).length>0){p.groups=groups;}else{p.groups=this.groups;}
return p;};Object.assign(Phrase.prototype,match);Object.assign(Phrase.prototype,methods$1);var aliases={term:'terms'};Object.keys(aliases).forEach(function(k){return Phrase.prototype[k]=Phrase.prototype[aliases[k]];});var Phrase_1=Phrase;var Pool=function(){function Pool(){var words=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,Pool);Object.defineProperty(this,'words',{enumerable:false,value:words});}
_createClass(Pool,[{key:"add",value:function add(term){this.words[term.id]=term;return this;}},{key:"get",value:function get(id){return this.words[id];}},{key:"remove",value:function remove(id){delete this.words[id];}},{key:"merge",value:function merge(pool){Object.assign(this.words,pool.words);return this;}},{key:"stats",value:function stats(){return{words:Object.keys(this.words).length};}}]);return Pool;}();Pool.prototype.clone=function(){var _this=this;var keys=Object.keys(this.words);var words=keys.reduce(function(h,k){var t=_this.words[k].clone();h[t.id]=t;return h;},{});return new Pool(words);};var Pool_1=Pool;var linkTerms=function linkTerms(terms){terms.forEach(function(term,i){if(i>0){term.prev=terms[i-1].id;}
if(terms[i+1]){term.next=terms[i+1].id;}});};var _linkTerms=linkTerms;var initSplit=/(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g;var hasSomething=/\S/;var isAcronym$1=/[ .][A-Z]\.? *$/i;var hasEllipse=/(?:\u2026|\.{2,}) *$/;var newLine=/((?:\r?\n|\r)+)/;var hasLetter=/[a-z0-9\u00C0-\u00FF\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]/i;var startWhitespace=/^\s+/;var naiive_split=function naiive_split(text){var all=[];var lines=text.split(newLine);for(var i=0;i<lines.length;i++){var arr=lines[i].split(initSplit);for(var o=0;o<arr.length;o++){all.push(arr[o]);}}
return all;};var isSentence=function isSentence(str,abbrevs){if(isAcronym$1.test(str)===true){return false;}
if(hasEllipse.test(str)===true){return false;}
if(hasLetter.test(str)===false){return false;}
var txt=str.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/,'');var words=txt.split(' ');var lastWord=words[words.length-1].toLowerCase();if(abbrevs.hasOwnProperty(lastWord)){return false;}
return true;};var splitSentences=function splitSentences(text,world){var abbrevs=world.cache.abbreviations;text=text||'';text=String(text);var sentences=[];var chunks=[];if(!text||typeof text!=='string'||hasSomething.test(text)===false){return sentences;}
text=text.replace('\xa0',' ');var splits=naiive_split(text);for(var i=0;i<splits.length;i++){var s=splits[i];if(s===undefined||s===''){continue;}
if(hasSomething.test(s)===false){if(chunks[chunks.length-1]){chunks[chunks.length-1]+=s;continue;}else if(splits[i+1]){splits[i+1]=s+splits[i+1];continue;}}
chunks.push(s);}
for(var _i=0;_i<chunks.length;_i++){var c=chunks[_i];if(chunks[_i+1]&&isSentence(c,abbrevs)===false){chunks[_i+1]=c+(chunks[_i+1]||'');}else if(c&&c.length>0){sentences.push(c);chunks[_i]='';}}
if(sentences.length===0){return[text];}
for(var _i2=1;_i2<sentences.length;_i2+=1){var ws=sentences[_i2].match(startWhitespace);if(ws!==null){sentences[_i2-1]+=ws[0];sentences[_i2]=sentences[_i2].replace(startWhitespace,'');}}
return sentences;};var _01Sentences=splitSentences;var wordlike=/\S/;var isBoundary=/^[!?.]+$/;var naiiveSplit=/(\S+)/;var isSlash=/[a-z] ?\/ ?[a-z]*$/;var notWord={'.':true,'-':true,'':true,'—':true,'--':true,'...':true};var hasHyphen=function hasHyphen(str){if(/^(re|un)-?[^aeiou]./.test(str)===true){return false;}
var reg=/^([a-z\u00C0-\u00FF`"'/]+)(-||—)([a-z0-9\u00C0-\u00FF].*)/i;if(reg.test(str)===true){return true;}
return false;};var combineSlashes=function combineSlashes(arr){for(var i=1;i<arr.length-1;i++){if(isSlash.test(arr[i])){arr[i-1]+=arr[i]+arr[i+1];arr[i]=null;arr[i+1]=null;}}
return arr;};var splitHyphens=function splitHyphens(word){var arr=[];var hyphens=word.split(/[-–—]/);var whichDash='-';var found=word.match(/[-–—]/);if(found&&found[0]){whichDash=found;}
for(var o=0;o<hyphens.length;o++){if(o===hyphens.length-1){arr.push(hyphens[o]);}else{arr.push(hyphens[o]+whichDash);}}
return arr;};var isArray$2=function isArray(arr){return Object.prototype.toString.call(arr)==='[object Array]';};var splitWords=function splitWords(str){var result=[];var arr=[];str=str||'';if(typeof str==='number'){str=String(str);}
if(isArray$2(str)){return str;}
var words=str.split(naiiveSplit);for(var i=0;i<words.length;i++){if(hasHyphen(words[i])===true){arr=arr.concat(splitHyphens(words[i]));continue;}
arr.push(words[i]);}
var carry='';for(var _i=0;_i<arr.length;_i++){var word=arr[_i];if(wordlike.test(word)===true&&notWord.hasOwnProperty(word)===false&&isBoundary.test(word)===false){if(result.length>0){result[result.length-1]+=carry;result.push(word);}else{result.push(carry+word);}
carry='';}else{carry+=word;}}
if(carry){if(result.length===0){result[0]='';}
result[result.length-1]+=carry;}
result=combineSlashes(result);result=result.filter(function(s){return s;});return result;};var _02Words=splitWords;var isArray$3=function isArray(arr){return Object.prototype.toString.call(arr)==='[object Array]';};var fromText=function fromText(){var text=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var world=arguments.length>1?arguments[1]:undefined;var pool=arguments.length>2?arguments[2]:undefined;var sentences=null;if(typeof text!=='string'){if(typeof text==='number'){text=String(text);}else if(isArray$3(text)){sentences=text;}}
sentences=sentences||_01Sentences(text,world);sentences=sentences.map(function(str){return _02Words(str);});pool=pool||new Pool_1();var phrases=sentences.map(function(terms){terms=terms.map(function(str){var term=new Term_1(str);pool.add(term);return term;});_linkTerms(terms);var p=new Phrase_1(terms[0].id,terms.length,pool);p.cache.terms=terms;return p;});return phrases;};var _01Tokenizer=fromText;var fromJSON=function fromJSON(json,world){var pool=new Pool_1();var phrases=json.map(function(p,k){var terms=p.terms.map(function(o,i){var term=new Term_1(o.text);term.pre=o.pre!==undefined?o.pre:'';if(o.post===undefined){o.post=' ';if(i>=p.terms.length-1){o.post='. ';if(k>=p.terms.length-1){o.post='.';}}}
term.post=o.post!==undefined?o.post:' ';if(o.tags){o.tags.forEach(function(tag){return term.tag(tag,'',world);});}
pool.add(term);return term;});_linkTerms(terms);return new Phrase_1(terms[0].id,terms.length,pool);});return phrases;};var fromJSON_1=fromJSON;var _version='13.5.0X003';var _data={"Comparative":"true¦better","Superlative":"true¦earlier","PresentTense":"true¦is,sounds","Value":"true¦a few","Noun":"true¦a5b4c2f1here,ie,lit,m0no doubt,pd,tce;a,d;t,y;a,ca,o0;l,rp;a,l;d,l,rc","Copula":"true¦a1is,w0;as,ere;m,re","PastTense":"true¦be3came,d2had,lied,meant,sa2taken,w0;as,e0;nt,re;id;en,gan","Condition":"true¦if,lest,unless","Gerund":"true¦accord0be0develop0go0result0stain0;ing","Negative":"true¦n0;ever,o0;!n,t","QuestionWord":"true¦how3wh0;at,e1ich,o0y;!m,se;n,re; come,'s","Plural":"true¦records","Conjunction":"true¦&,aEbAcuz,how8in caDno7o6p4supposing,t1vers5wh0yet;eth8ile;h0o;eref9o0;!uC;l0rovided that;us;r,therwi6; matt1r;!ev0;er;e0ut;cau1f0;ore;se;lthou1nd,s 0;far as,if;gh","Pronoun":"true¦'em,elle,h4i3me,ourselves,she5th1us,we,you0;!rself;e0ou;m,y;!l,t;e0im;!'s","Singular":"true¦0:0Z;1:12;a0Yb0Mc0Dd06e04fZgUhQiPjel0kitty,lOmKnJoIpEquestion mark,rCs7t4u2womY;nc0Ts 2;doll0Fst0H; rex,a3h2ic,ragedy,v show;ere,i1;l0x return;i5ky,omeone,t2uper bowl,yst0Y;ep3ri1u2;de0Rff;faOmoO;st0Nze;al0i1o2;om,se;a4i0Kl06r3u2;dMrpoE;erogaWobl0P;rt,te0J;bjTceHthers;othi1umb0F;a4ee05o2;del,m2nopo0th0D;!my;n,yf0;i0unch;ci1nsect;ead start,o2;l0me3u2;se;! run;adf0entlem5irlZlaci04od,rand3u2;l0y; slam,fa2mo2;th01;an;a5ella,ly,ol0r3un2;di1;iTo2;ntiWsN;mi0thV;conomy,gg,ner5veWx2;ampQecu7;ad7e4innSo2ragonf0ude;cumentFg2i0l0or;gy;ath,t2;ec2;tive;!dy;a8eili1h6i4o2redit card;ttage,u2;riJsin;ty,vil w2;ar;andeliGocol2;ate;n2rD;ary;aAel0lesHo6r4u2;n2tterf0;ti1;eakfast,o2;!th8;dy,tt4y2;!fri2;end;le;nki1r2;ri2;er;d4l0noma0u2;nt;ly; homin4verti2;si1;ng;em","Actor":"true¦aJbGcFdCengineIfAgardenIh9instructPjournalLlawyIm8nurse,opeOp5r3s1t0;echnCherapK;ailNcientJoldiGu0;pervKrgeon;e0oofE;ceptionGsearC;hotographClumbColi1r0sychologF;actitionBogrammB;cem6t5;echanic,inist9us4;airdress8ousekeep8;arm7ire0;fight6m2;eputy,iet0;ici0;an;arpent2lerk;ricklay1ut0;ch0;er;ccoun6d2ge7r0ssis6ttenda7;chitect,t0;ist;minist1v0;is1;rat0;or;ta0;nt","Honorific":"true¦a03b00cSdReQfiLgKhon,jr,king,lJmEoDp8queen,r4s0taoiseach,vice7;e1fc,gt,ir,r,u0;ltTpt,rg;c0nDrgeaL;ond liJretary;abbi,e0;ar1pAs,v0;!erend; admirY;astPhd,r0vt;esideEi1of0;!essN;me mini5nce0;!ss;fficOp,rd;a3essrs,i2lle,me,r1s0;!tr;!s;stK;gistrate,j,r6yF;i3lb,t;en,ov;eld mar3rst l0;ady,i0;eutena0;nt;shG;sq,xcellency;et,oct6r,utchess;apt6hance4mdr,o0pl;lonel,m2ngress0unci3;m0wom0;an;dr,mand5;ll0;or;!ain;ldg,rig0;!adi0;er;d0sst,tty,yatullah;j,m0v;!ir0;al","SportsTeam":"true¦0:1A;1:1H;2:1G;a1Eb16c0Td0Kfc dallas,g0Ihouston 0Hindiana0Gjacksonville jagua0k0El0Bm01newToQpJqueens parkIreal salt lake,sAt5utah jazz,vancouver whitecaps,w3yW;ashington 3est ham0Rh10;natio1Oredski2wizar0W;ampa bay 6e5o3;ronto 3ttenham hotspur;blue ja0Mrapto0;nnessee tita2xasC;buccanee0ra0K;a7eattle 5heffield0Kporting kansas0Wt3;. louis 3oke0V;c1Frams;marine0s3;eah15ounG;cramento Rn 3;antonio spu0diego 3francisco gJjose earthquak1;char08paA; ran07;a8h5ittsburgh 4ortland t3;imbe0rail blaze0;pirat1steele0;il3oenix su2;adelphia 3li1;eagl1philNunE;dr1;akland 3klahoma city thunder,rlando magic;athle0Mrai3;de0; 3castle01;england 7orleans 6york 3;city fc,g4je0FknXme0Fred bul0Yy3;anke1;ian0D;pelica2sain0C;patrio0Brevolut3;ion;anchester Be9i3ontreal impact;ami 7lwaukee b6nnesota 3;t4u0Fvi3;kings;imberwolv1wi2;rewe0uc0K;dolphi2heat,marli2;mphis grizz3ts;li1;cXu08;a4eicesterVos angeles 3;clippe0dodDla9; galaxy,ke0;ansas city 3nE;chiefs,roya0E; pace0polis colU;astr06dynamo,rockeTtexa2;olden state warrio0reen bay pac3;ke0;.c.Aallas 7e3i05od5;nver 5troit 3;lio2pisto2ti3;ge0;broncZnuggeM;cowbo4maver3;ic00;ys; uQ;arCelKh8incinnati 6leveland 5ol3;orado r3umbus crew sc;api5ocki1;brow2cavalie0india2;bengaWre3;ds;arlotte horAicago 3;b4cubs,fire,wh3;iteB;ea0ulR;diff3olina panthe0; c3;ity;altimore 9lackburn rove0oston 5rooklyn 3uffalo bilN;ne3;ts;cel4red3; sox;tics;rs;oriol1rave2;rizona Ast8tlanta 3;brav1falco2h4u3;nited;aw9;ns;es;on villa,r3;os;c5di3;amondbac3;k
if(colorMap[k]){tags[k].color=colorMap[k];return;}
tags[k].isA.some(function(t){if(colorMap[t]){tags[k].color=colorMap[t];return true;}
return false;});});return tags;};var _color=addColors;var unique$2=function unique(arr){return arr.filter(function(v,i,a){return a.indexOf(v)===i;});};var inferIsA=function inferIsA(tags){Object.keys(tags).forEach(function(k){var tag=tags[k];var len=tag.isA.length;for(var i=0;i<len;i++){var down=tag.isA[i];if(tags[down]){tag.isA=tag.isA.concat(tags[down].isA);}}
tag.isA=unique$2(tag.isA);});return tags;};var _isA=inferIsA;var unique$3=function unique(arr){return arr.filter(function(v,i,a){return a.indexOf(v)===i;});};var inferNotA=function inferNotA(tags){var keys=Object.keys(tags);keys.forEach(function(k){var tag=tags[k];tag.notA=tag.notA||[];tag.isA.forEach(function(down){if(tags[down]&&tags[down].notA){var notA=typeof tags[down].notA==='string'?[tags[down].isA]:tags[down].notA||[];tag.notA=tag.notA.concat(notA);}});for(var i=0;i<keys.length;i++){var key=keys[i];if(tags[key].notA.indexOf(k)!==-1){tag.notA.push(key);}}
tag.notA=unique$3(tag.notA);});return tags;};var _notA=inferNotA;var inferLineage=function inferLineage(tags){var keys=Object.keys(tags);keys.forEach(function(k){var tag=tags[k];tag.lineage=[];for(var i=0;i<keys.length;i++){if(tags[keys[i]].isA.indexOf(k)!==-1){tag.lineage.push(keys[i]);}}});return tags;};var _lineage=inferLineage;var validate=function validate(tags){Object.keys(tags).forEach(function(k){var tag=tags[k];tag.isA=tag.isA||[];if(typeof tag.isA==='string'){tag.isA=[tag.isA];}
tag.notA=tag.notA||[];if(typeof tag.notA==='string'){tag.notA=[tag.notA];}});return tags;};var inferTags=function inferTags(tags){tags=validate(tags);tags=_isA(tags);tags=_notA(tags);tags=_color(tags);tags=_lineage(tags);return tags;};var inference=inferTags;var addIn=function addIn(obj,tags){Object.keys(obj).forEach(function(k){tags[k]=obj[k];});};var build=function build(){var tags={};addIn(nouns,tags);addIn(verbs,tags);addIn(values,tags);addIn(misc,tags);tags=inference(tags);return tags;};var tags=build();var seq="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",cache=seq.split("").reduce(function(n,o,e){return n[o]=e,n;},{}),toAlphaCode=function toAlphaCode(n){if(void 0!==seq[n])return seq[n];var o=1,e=36,t="";for(;n>=e;n-=e,o++,e*=36){}
for(;o--;){var _o=n%36;t=String.fromCharCode((_o<10?48:55)+_o)+t,n=(n-_o)/36;}
return t;},fromAlphaCode=function fromAlphaCode(n){if(void 0!==cache[n])return cache[n];var o=0,e=1,t=36,r=1;for(;e<n.length;o+=t,e++,t*=36){}
for(var _e=n.length-1;_e>=0;_e--,r*=36){var _t=n.charCodeAt(_e)-48;_t>10&&(_t-=7),o+=_t*r;}
return o;};var encoding={toAlphaCode:toAlphaCode,fromAlphaCode:fromAlphaCode},symbols=function symbols(n){var o=new RegExp("([0-9A-Z]+):([0-9A-Z]+)");for(var e=0;e<n.nodes.length;e++){var t=o.exec(n.nodes[e]);if(!t){n.symCount=e;break;}
n.syms[encoding.fromAlphaCode(t[1])]=encoding.fromAlphaCode(t[2]);}
n.nodes=n.nodes.slice(n.symCount,n.nodes.length);};var indexFromRef=function indexFromRef(n,o,e){var t=encoding.fromAlphaCode(o);return t<n.symCount?n.syms[t]:e+t+1-n.symCount;},toArray=function toArray(n){var o=[],e=function e(t,r){var s=n.nodes[t];"!"===s[0]&&(o.push(r),s=s.slice(1));var c=s.split(/([A-Z0-9,]+)/g);for(var _s=0;_s<c.length;_s+=2){var u=c[_s],i=c[_s+1];if(!u)continue;var l=r+u;if(","===i||void 0===i){o.push(l);continue;}
var f=indexFromRef(n,i,t);e(f,l);}};return e(0,""),o;},unpack=function unpack(n){var o={nodes:n.split(";"),syms:[],symCount:0};return n.match(":")&&symbols(o),toArray(o);};var unpack_1=unpack,unpack_1$1=function unpack_1$1(n){var o=n.split("|").reduce(function(n,o){var e=o.split("¦");return n[e[0]]=e[1],n;},{}),e={};return Object.keys(o).forEach(function(n){var t=unpack_1(o[n]);"true"===n&&(n=!0);for(var _o2=0;_o2<t.length;_o2++){var r=t[_o2];!0===e.hasOwnProperty(r)?!1===Array.isArray(e[r])?e[r]=[e[r],n]:e[r].push(n):e[r]=n;}}),e;};var efrtUnpack_min=unpack_1$1;var addWord=function addWord(word,tag,lex){if(lex[word]!==undefined&&typeof lex[word]!='function'){if(typeof lex[word]==='string'){lex[word]=[lex[word]];}
if(typeof tag==='string'){lex[word].push(tag);}else{lex[word]=lex[word].concat(tag);}}else{lex[word]=tag;}};var addMore=function addMore(word,tag,world){var lexicon=world.words;var transform=world.transforms;var words=word.split(' ');if(words.length>1){world.hasCompound[words[0]]=true;}
if(tag==='Singular'){var plural=transform.toPlural(word,world);lexicon[plural]=lexicon[plural]||'Plural';}
if(tag==='Infinitive'){var conj=transform.conjugate(word,world);var tags=Object.keys(conj);for(var i=0;i<tags.length;i++){var w=conj[tags[i]];lexicon[w]=lexicon[w]||tags[i];}}
if(tag==='Comparable'){var _conj=transform.adjectives(word);var _tags=Object.keys(_conj);for(var _i=0;_i<_tags.length;_i++){var _w=_conj[_tags[_i]];lexicon[_w]=lexicon[_w]||_tags[_i];}}
if(tag==='PhrasalVerb'){addWord(word,'Infinitive',lexicon);var _conj2=transform.conjugate(words[0],world);var _tags2=Object.keys(_conj2);for(var _i2=0;_i2<_tags2.length;_i2++){world.hasCompound[_conj2[_tags2[_i2]]]=true;var _w2=_conj2[_tags2[_i2]]+' '+words[1];addWord(_w2,_tags2[_i2],lexicon);addWord(_w2,'PhrasalVerb',lexicon);}}
if(tag==='Demonym'){var _plural=transform.toPlural(word,world);lexicon[_plural]=lexicon[_plural]||['Demonym','Plural'];}};var addWords={addWord:addWord,addMore:addMore};var addIrregulars=function addIrregulars(world){var nouns=world.irregulars.nouns;var words=Object.keys(nouns);for(var i=0;i<words.length;i++){var w=words[i];world.words[w]='Singular';world.words[nouns[w]]='Plural';}
var verbs=world.irregulars.verbs;var keys=Object.keys(verbs);var _loop=function _loop(_i){var inf=keys[_i];world.words[inf]=world.words[inf]||'Infinitive';var forms=world.transforms.conjugate(inf,world);forms=Object.assign(forms,verbs[inf]);Object.keys(forms).forEach(function(tag){world.words[forms[tag]]=world.words[forms[tag]]||tag;});};for(var _i=0;_i<keys.length;_i++){_loop(_i);}};var addIrregulars_1=addIrregulars;var misc$1={'20th century fox':'Organization','7 eleven':'Organization','7-eleven':'Organization',g8:'Organization','motel 6':'Organization',vh1:'Organization',q1:'Date',q2:'Date',q3:'Date',q4:'Date'};var plurals={addendum:'addenda',alga:'algae',alumna:'alumnae',alumnus:'alumni',analysis:'analyses',antenna:'antennae',appendix:'appendices',avocado:'avocados',axis:'axes',bacillus:'bacilli',barracks:'barracks',beau:'beaux',bus:'buses',cactus:'cacti',chateau:'chateaux',child:'children',circus:'circuses',clothes:'clothes',corpus:'corpora',criterion:'criteria',curriculum:'curricula',database:'databases',deer:'deer',diagnosis:'diagnoses',echo:'echoes',embargo:'embargoes',epoch:'epochs',foot:'feet',formula:'formulae',fungus:'fungi',genus:'genera',goose:'geese',halo:'halos',hippopotamus:'hippopotami',index:'indices',larva:'larvae',leaf:'leaves',libretto:'libretti',loaf:'loaves',man:'men',matrix:'matrices',memorandum:'memoranda',modulus:'moduli',mosquito:'mosquitoes',mouse:'mice',move:'moves',nebula:'nebulae',nucleus:'nuclei',octopus:'octopi',opus:'opera',ovum:'ova',ox:'oxen',parenthesis:'parentheses',person:'people',phenomenon:'phenomena',prognosis:'prognoses',quiz:'quizzes',radius:'radii',referendum:'referenda',rodeo:'rodeos',sex:'sexes',shoe:'shoes',sombrero:'sombreros',stimulus:'stimuli',stomach:'stomachs',syllabus:'syllabi',synopsis:'synopses',tableau:'tableaux',thesis:'theses',thief:'thieves',tooth:'teeth',tornado:'tornados',tuxedo:'tuxedos',vertebra:'vertebrae'};var mapping={g:'Gerund',prt:'Participle',perf:'PerfectTense',pst:'PastTense',fut:'FuturePerfect',pres:'PresentTense',pluperf:'Pluperfect',a:'Actor'};var conjugations={act:{a:'_or'},ache:{pst:'ached',g:'aching'},age:{g:'ageing',pst:'aged',pres:'ages'},aim:{a:'_er',g:'_ing',pst:'_ed'},arise:{prt:'_n',pst:'arose'},babysit:{a:'_ter',pst:'babysat'},ban:{a:'',g:'_ning',pst:'_ned'},be:{a:'',g:'am',prt:'been',pst:'was',pres:'is'},beat:{a:'_er',g:'_ing',prt:'_en'},become:{prt:'_'},begin:{g:'_ning',prt:'begun',pst:'began'},being:{g:'are',pst:'were',pres:'are'},bend:{prt:'bent'},bet:{a:'_ter',prt:'_'},bind:{pst:'bound'},bite:{g:'biting',prt:'bitten',pst:'bit'},bleed:{prt:'bled',pst:'bled'},blow:{prt:'_n',pst:'blew'},boil:{a:'_er'},brake:{prt:'broken'},"break":{pst:'broke'},breed:{pst:'bred'},bring:{prt:'brought',pst:'brought'},broadcast:{pst:'_'},budget:{pst:'_ed'},build:{prt:'built',pst:'built'},burn:{prt:'_ed'},burst:{prt:'_'},buy:{prt:'bought',pst:'bought'},can:{a:'',fut:'_',g:'',pst:'could',perf:'could',pluperf:'could',pres:'_'},"catch":{pst:'caught'},choose:{g:'choosing',prt:'chosen',pst:'chose'},cling:{prt:'clung'},come:{prt:'_',pst:'came',g:'coming'},compete:{a:'competitor',g:'competing',pst:'_d'},cost:{pst:'_'},creep:{prt:'crept'},cut:{prt:'_'},deal:{prt:'_t',pst:'_t'},develop:{a:'_er',g:'_ing',pst:'_ed'},die:{g:'dying',pst:'_d'},dig:{g:'_ging',prt:'dug',pst:'dug'},dive:{prt:'_d'},"do":{pst:'did',pres:'_es'},draw:{prt:'_n',pst:'drew'},dream:{prt:'_t'},drink:{prt:'drunk',pst:'drank'},drive:{g:'driving',prt:'_n',pst:'drove'},drop:{g:'_ping',pst:'_ped'},eat:{a:'_er',g:'_ing',prt:'_en',pst:'ate'},edit:{pst:'_ed',g:'_ing'},egg:{pst:'_ed'},fall:{prt:'_en',pst:'fell'},feed:{prt:'fed',pst:'fed'},feel:{a:'_er',pst:'felt'},fight:{prt:'fought',pst:'fought'},find:{pst:'found'},flee:{g:'_ing',prt:'fled'},fling:{prt:'flung'},fly:{prt:'flown',pst:'flew'},forbid:{pst:'forbade'},forget:{g:'_ing',prt:'forgotten',pst:'forgot'},forgive:{g:'forgiving',prt:'_n',pst:'forgave'},free:{a:'',g:'_ing'},freeze:{g:'freezing',prt:'frozen',pst:'froze'},get:{pst:'got',prt:'gotten'},give:{g:'giving',prt:'_n',pst:'gave'},go:{prt:'_ne',pst:'went',pres:'goes'},grow:{prt:'_n'},hang:{prt:'hung
var conjugations_1=conjugations;var endsWith={b:[{reg:/([^aeiou][aeiou])b$/i,repl:{pr:'$1bs',pa:'$1bbed',gr:'$1bbing'}}],d:[{reg:/(end)$/i,repl:{pr:'$1s',pa:'ent',gr:'$1ing',ar:'$1er'}},{reg:/(eed)$/i,repl:{pr:'$1s',pa:'$1ed',gr:'$1ing',ar:'$1er'}},{reg:/(ed)$/i,repl:{pr:'$1s',pa:'$1ded',ar:'$1der',gr:'$1ding'}},{reg:/([^aeiou][ou])d$/i,repl:{pr:'$1ds',pa:'$1dded',gr:'$1dding'}}],e:[{reg:/(eave)$/i,repl:{pr:'$1s',pa:'$1d',gr:'eaving',ar:'$1r'}},{reg:/(ide)$/i,repl:{pr:'$1s',pa:'ode',gr:'iding',ar:'ider'}},{reg:/(t|sh?)(ake)$/i,repl:{pr:'$1$2s',pa:'$1ook',gr:'$1aking',ar:'$1$2r'}},{reg:/w(ake)$/i,repl:{pr:'w$1s',pa:'woke',gr:'waking',ar:'w$1r'}},{reg:/m(ake)$/i,repl:{pr:'m$1s',pa:'made',gr:'making',ar:'m$1r'}},{reg:/(a[tg]|i[zn]|ur|nc|gl|is)e$/i,repl:{pr:'$1es',pa:'$1ed',gr:'$1ing'}},{reg:/([bd]l)e$/i,repl:{pr:'$1es',pa:'$1ed',gr:'$1ing'}},{reg:/(om)e$/i,repl:{pr:'$1es',pa:'ame',gr:'$1ing'}}],g:[{reg:/([^aeiou][ou])g$/i,repl:{pr:'$1gs',pa:'$1gged',gr:'$1gging'}}],h:[{reg:/(..)([cs]h)$/i,repl:{pr:'$1$2es',pa:'$1$2ed',gr:'$1$2ing'}}],k:[{reg:/(ink)$/i,repl:{pr:'$1s',pa:'unk',gr:'$1ing',ar:'$1er'}}],m:[{reg:/([^aeiou][aeiou])m$/i,repl:{pr:'$1ms',pa:'$1mmed',gr:'$1mming'}}],n:[{reg:/(en)$/i,repl:{pr:'$1s',pa:'$1ed',gr:'$1ing'}}],p:[{reg:/(e)(ep)$/i,repl:{pr:'$1$2s',pa:'$1pt',gr:'$1$2ing',ar:'$1$2er'}},{reg:/([^aeiou][aeiou])p$/i,repl:{pr:'$1ps',pa:'$1pped',gr:'$1pping'}},{reg:/([aeiu])p$/i,repl:{pr:'$1ps',pa:'$1p',gr:'$1pping'}}],r:[{reg:/([td]er)$/i,repl:{pr:'$1s',pa:'$1ed',gr:'$1ing'}},{reg:/(er)$/i,repl:{pr:'$1s',pa:'$1ed',gr:'$1ing'}}],s:[{reg:/(ish|tch|ess)$/i,repl:{pr:'$1es',pa:'$1ed',gr:'$1ing'}}],t:[{reg:/(ion|end|e[nc]t)$/i,repl:{pr:'$1s',pa:'$1ed',gr:'$1ing'}},{reg:/(.eat)$/i,repl:{pr:'$1s',pa:'$1ed',gr:'$1ing'}},{reg:/([aeiu])t$/i,repl:{pr:'$1ts',pa:'$1t',gr:'$1tting'}},{reg:/([^aeiou][aeiou])t$/i,repl:{pr:'$1ts',pa:'$1tted',gr:'$1tting'}}],w:[{reg:/(..)(ow)$/i,repl:{pr:'$1$2s',pa:'$1ew',gr:'$1$2ing',prt:'$1$2n'}}],y:[{reg:/([i|f|rr])y$/i,repl:{pr:'$1ies',pa:'$1ied',gr:'$1ying'}}],z:[{reg:/([aeiou]zz)$/i,repl:{pr:'$1es',pa:'$1ed',gr:'$1ing'}}]};var suffixes=endsWith;var posMap={pr:'PresentTense',pa:'PastTense',gr:'Gerund',prt:'Participle',ar:'Actor'};var doTransform=function doTransform(str,obj){var found={};var keys=Object.keys(obj.repl);for(var i=0;i<keys.length;i+=1){var pos=keys[i];found[posMap[pos]]=str.replace(obj.reg,obj.repl[pos]);}
return found;};var checkSuffix=function checkSuffix(){var str=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var c=str[str.length-1];if(suffixes.hasOwnProperty(c)===true){for(var r=0;r<suffixes[c].length;r+=1){var reg=suffixes[c][r].reg;if(reg.test(str)===true){return doTransform(str,suffixes[c][r]);}}}
return{};};var _01Suffixes=checkSuffix;var hasY=/[bcdfghjklmnpqrstvwxz]y$/;var generic={Gerund:function Gerund(inf){if(inf.charAt(inf.length-1)==='e'){return inf.replace(/e$/,'ing');}
return inf+'ing';},PresentTense:function PresentTense(inf){if(inf.charAt(inf.length-1)==='s'){return inf+'es';}
if(hasY.test(inf)===true){return inf.slice(0,-1)+'ies';}
return inf+'s';},PastTense:function PastTense(inf){if(inf.charAt(inf.length-1)==='e'){return inf+'d';}
if(inf.substr(-2)==='ed'){return inf;}
if(hasY.test(inf)===true){return inf.slice(0,-1)+'ied';}
return inf+'ed';}};var _02Generic=generic;var conjugate=function conjugate(){var inf=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var world=arguments.length>1?arguments[1]:undefined;var found={};if(world&&world.irregulars){if(world.irregulars.verbs.hasOwnProperty(inf)===true){found=Object.assign({},world.irregulars.verbs[inf]);}}
found=Object.assign({},_01Suffixes(inf),found);if(found.Gerund===undefined){found.Gerund=_02Generic.Gerund(inf);}
if(found.PastTense===undefined){found.PastTense=_02Generic.PastTense(inf);}
if(found.PresentTense===undefined){found.PresentTense=_02Generic.PresentTense(inf);}
return found;};var conjugate_1=conjugate;var do_rules=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/oud$/,/...p$/];var dont_rules=[/ary$/];var irregulars={nice:'nicest',late:'latest',hard:'hardest',inner:'innermost',outer:'outermost',far:'furthest',worse:'worst',bad:'worst',good:'best',big:'biggest',large:'largest'};var transforms=[{reg:/y$/i,repl:'iest'},{reg:/([aeiou])t$/i,repl:'$1ttest'},{reg:/([aeou])de$/i,repl:'$1dest'},{reg:/nge$/i,repl:'ngest'},{reg:/([aeiou])te$/i,repl:'$1test'}];var to_superlative=function to_superlative(str){if(irregulars.hasOwnProperty(str)){return irregulars[str];}
for(var i=0;i<transforms.length;i++){if(transforms[i].reg.test(str)){return str.replace(transforms[i].reg,transforms[i].repl);}}
for(var _i=0;_i<dont_rules.length;_i++){if(dont_rules[_i].test(str)===true){return null;}}
for(var _i2=0;_i2<do_rules.length;_i2++){if(do_rules[_i2].test(str)===true){if(str.charAt(str.length-1)==='e'){return str+'st';}
return str+'est';}}
return str+'est';};var toSuperlative=to_superlative;var do_rules$1=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/old$/,/oud$/,/e[ae]p$/];var dont_rules$1=[/ary$/,/ous$/];var irregulars$1={grey:'greyer',gray:'grayer',green:'greener',yellow:'yellower',red:'redder',good:'better',well:'better',bad:'worse',sad:'sadder',big:'bigger'};var transforms$1=[{reg:/y$/i,repl:'ier'},{reg:/([aeiou])t$/i,repl:'$1tter'},{reg:/([aeou])de$/i,repl:'$1der'},{reg:/nge$/i,repl:'nger'}];var to_comparative=function to_comparative(str){if(irregulars$1.hasOwnProperty(str)){return irregulars$1[str];}
for(var i=0;i<transforms$1.length;i++){if(transforms$1[i].reg.test(str)===true){return str.replace(transforms$1[i].reg,transforms$1[i].repl);}}
for(var _i=0;_i<dont_rules$1.length;_i++){if(dont_rules$1[_i].test(str)===true){return null;}}
for(var _i2=0;_i2<do_rules$1.length;_i2++){if(do_rules$1[_i2].test(str)===true){return str+'er';}}
if(/e$/.test(str)===true){return str+'r';}
return str+'er';};var toComparative=to_comparative;var fns$1={toSuperlative:toSuperlative,toComparative:toComparative};var conjugate$1=function conjugate(w){var res={};var sup=fns$1.toSuperlative(w);if(sup){res.Superlative=sup;}
var comp=fns$1.toComparative(w);if(comp){res.Comparative=comp;}
return res;};var adjectives=conjugate$1;var suffixes$1={a:[[/(antenn|formul|nebul|vertebr|vit)a$/i,'$1ae'],[/([ti])a$/i,'$1a']],e:[[/(kn|l|w)ife$/i,'$1ives'],[/(hive)$/i,'$1s'],[/([m|l])ouse$/i,'$1ice'],[/([m|l])ice$/i,'$1ice']],f:[[/^(dwar|handkerchie|hoo|scar|whar)f$/i,'$1ves'],[/^((?:ca|e|ha|(?:our|them|your)?se|she|wo)l|lea|loa|shea|thie)f$/i,'$1ves']],i:[[/(octop|vir)i$/i,'$1i']],m:[[/([ti])um$/i,'$1a']],n:[[/^(oxen)$/i,'$1']],o:[[/(al|ad|at|er|et|ed|ad)o$/i,'$1oes']],s:[[/(ax|test)is$/i,'$1es'],[/(alias|status)$/i,'$1es'],[/sis$/i,'ses'],[/(bu)s$/i,'$1ses'],[/(sis)$/i,'ses'],[/^(?!talis|.*hu)(.*)man$/i,'$1men'],[/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,'$1i']],x:[[/(matr|vert|ind|cort)(ix|ex)$/i,'$1ices'],[/^(ox)$/i,'$1en']],y:[[/([^aeiouy]|qu)y$/i,'$1ies']],z:[[/(quiz)$/i,'$1zes']]};var _rules=suffixes$1;var addE=/(x|ch|sh|s|z)$/;var trySuffix=function trySuffix(str){var c=str[str.length-1];if(_rules.hasOwnProperty(c)===true){for(var i=0;i<_rules[c].length;i+=1){var reg=_rules[c][i][0];if(reg.test(str)===true){return str.replace(reg,_rules[c][i][1]);}}}
return null;};var pluralize=function pluralize(){var str=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var world=arguments.length>1?arguments[1]:undefined;var irregulars=world.irregulars.nouns;if(irregulars.hasOwnProperty(str)){return irregulars[str];}
var plural=trySuffix(str);if(plural!==null){return plural;}
if(addE.test(str)){return str+'es';}
return str+'s';};var toPlural=pluralize;var _rules$1=[[/([^v])ies$/i,'$1y'],[/ises$/i,'isis'],[/(kn|[^o]l|w)ives$/i,'$1ife'],[/^((?:ca|e|ha|(?:our|them|your)?se|she|wo)l|lea|loa|shea|thie)ves$/i,'$1f'],[/^(dwar|handkerchie|hoo|scar|whar)ves$/i,'$1f'],[/(antenn|formul|nebul|vertebr|vit)ae$/i,'$1a'],[/(octop|vir|radi|nucle|fung|cact|stimul)(i)$/i,'$1us'],[/(buffal|tomat|tornad)(oes)$/i,'$1o'],[/(eas)es$/i,'$1e'],[/(..[aeiou]s)es$/i,'$1'],[/(vert|ind|cort)(ices)$/i,'$1ex'],[/(matr|append)(ices)$/i,'$1ix'],[/(x|ch|ss|sh|z|o)es$/i,'$1'],[/men$/i,'man'],[/(n)ews$/i,'$1ews'],[/([ti])a$/i,'$1um'],[/([^aeiouy]|qu)ies$/i,'$1y'],[/(s)eries$/i,'$1eries'],[/(m)ovies$/i,'$1ovie'],[/([m|l])ice$/i,'$1ouse'],[/(cris|ax|test)es$/i,'$1is'],[/(alias|status)es$/i,'$1'],[/(ss)$/i,'$1'],[/(ics)$/i,'$1'],[/s$/i,'']];var invertObj=function invertObj(obj){return Object.keys(obj).reduce(function(h,k){h[obj[k]]=k;return h;},{});};var toSingular=function toSingular(str,world){var irregulars=world.irregulars.nouns;var invert=invertObj(irregulars);if(invert.hasOwnProperty(str)){return invert[str];}
for(var i=0;i<_rules$1.length;i++){if(_rules$1[i][0].test(str)===true){str=str.replace(_rules$1[i][0],_rules$1[i][1]);return str;}}
return str;};var toSingular_1=toSingular;var rules={Participle:[{reg:/own$/i,to:'ow'},{reg:/(.)un([g|k])$/i,to:'$1in$2'}],Actor:[{reg:/(er)er$/i,to:'$1'}],PresentTense:[{reg:/(..)(ies)$/i,to:'$1y'},{reg:/(tch|sh)es$/i,to:'$1'},{reg:/(ss|zz)es$/i,to:'$1'},{reg:/([tzlshicgrvdnkmu])es$/i,to:'$1e'},{reg:/(n[dtk]|c[kt]|[eo]n|i[nl]|er|a[ytrl])s$/i,to:'$1'},{reg:/(ow)s$/i,to:'$1'},{reg:/(op)s$/i,to:'$1'},{reg:/([eirs])ts$/i,to:'$1t'},{reg:/(ll)s$/i,to:'$1'},{reg:/(el)s$/i,to:'$1'},{reg:/(ip)es$/i,to:'$1e'},{reg:/ss$/i,to:'ss'},{reg:/s$/i,to:''}],Gerund:[{reg:/(..)(p|d|t|g){2}ing$/i,to:'$1$2'},{reg:/(ll|ss|zz)ing$/i,to:'$1'},{reg:/([^aeiou])ying$/i,to:'$1y'},{reg:/([^ae]i.)ing$/i,to:'$1e'},{reg:/(ea[dklnrtv])ing$/i,to:'$1'},{reg:/(ch|sh)ing$/i,to:'$1'},{reg:/(z)ing$/i,to:'$1e'},{reg:/(a[gdkvtc])ing$/i,to:'$1e'},{reg:/(u[rtcbn])ing$/i,to:'$1e'},{reg:/([^o]o[bdknprv])ing$/i,to:'$1e'},{reg:/([tbckg]l)ing$/i,to:'$1e'},{reg:/(c|s)ing$/i,to:'$1e'},{reg:/(..)ing$/i,to:'$1'}],PastTense:[{reg:/(ued)$/i,to:'ue'},{reg:/a([^aeiouy])ed$/i,to:'a$1e'},{reg:/([aeiou]zz)ed$/i,to:'$1'},{reg:/(e|i)lled$/i,to:'$1ll'},{reg:/(.)(sh|ch)ed$/i,to:'$1$2'},{reg:/(tl|gl)ed$/i,to:'$1e'},{reg:/(um?pt?)ed$/i,to:'$1'},{reg:/(ss)ed$/i,to:'$1'},{reg:/pped$/i,to:'p'},{reg:/tted$/i,to:'t'},{reg:/(..)gged$/i,to:'$1g'},{reg:/(..)lked$/i,to:'$1lk'},{reg:/([^aeiouy][aeiou])ked$/i,to:'$1ke'},{reg:/(.[aeiou])led$/i,to:'$1l'},{reg:/(..)(h|ion|n[dt]|ai.|[cs]t|pp|all|ss|tt|int|ail|ld|en|oo.|er|k|pp|w|ou.|rt|ght|rm)ed$/i,to:'$1$2'},{reg:/(.ut)ed$/i,to:'$1e'},{reg:/(.pt)ed$/i,to:'$1'},{reg:/(us)ed$/i,to:'$1e'},{reg:/(dd)ed$/i,to:'$1'},{reg:/(..[^aeiouy])ed$/i,to:'$1e'},{reg:/(..)ied$/i,to:'$1y'},{reg:/(.o)ed$/i,to:'$1o'},{reg:/(..i)ed$/i,to:'$1'},{reg:/(.a[^aeiou])ed$/i,to:'$1'},{reg:/([aeiou][^aeiou])ed$/i,to:'$1e'},{reg:/([rl])ew$/i,to:'$1ow'},{reg:/([pl])t$/i,to:'$1t'}]};var _transform=rules;var guessVerb={Gerund:['ing'],Actor:['erer'],Infinitive:['ate','ize','tion','rify','then','ress','ify','age','nce','ect','ise','ine','ish','ace','ash','ure','tch','end','ack','and','ute','ade','ock','ite','ase','ose','use','ive','int','nge','lay','est','ain','ant','ent','eed','er','le','own','unk','ung','en'],PastTense:['ed','lt','nt','pt','ew','ld'],PresentTense:['rks','cks','nks','ngs','mps','tes','zes','ers','les','acks','ends','ands','ocks','lays','eads','lls','els','ils','ows','nds','ays','ams','ars','ops','ffs','als','urs','lds','ews','ips','es','ts','ns']};guessVerb=Object.keys(guessVerb).reduce(function(h,k){guessVerb[k].forEach(function(a){return h[a]=k;});return h;},{});var _guess=guessVerb;var guessTense=function guessTense(str){var three=str.substr(str.length-3);if(_guess.hasOwnProperty(three)===true){return _guess[three];}
var two=str.substr(str.length-2);if(_guess.hasOwnProperty(two)===true){return _guess[two];}
var one=str.substr(str.length-1);if(one==='s'){return'PresentTense';}
return null;};var toInfinitive=function toInfinitive(str,world,tense){if(!str){return'';}
if(world.words.hasOwnProperty(str)===true){var irregs=world.irregulars.verbs;var keys=Object.keys(irregs);for(var i=0;i<keys.length;i++){var forms=Object.keys(irregs[keys[i]]);for(var o=0;o<forms.length;o++){if(str===irregs[keys[i]][forms[o]]){return keys[i];}}}}
tense=tense||guessTense(str);if(tense&&_transform[tense]){for(var _i=0;_i<_transform[tense].length;_i++){var rule=_transform[tense][_i];if(rule.reg.test(str)===true){return str.replace(rule.reg,rule.to);}}}
return str;};var toInfinitive_1=toInfinitive;var irregulars$2={nouns:plurals,verbs:conjugations_1};var transforms$2={conjugate:conjugate_1,adjectives:adjectives,toPlural:toPlural,toSingular:toSingular_1,toInfinitive:toInfinitive_1};var _isVerbose=false;var World=function(){function World(){_classCallCheck(this,World);Object.defineProperty(this,'words',{enumerable:false,value:misc$1,writable:true});Object.defineProperty(this,'hasCompound',{enumerable:false,value:{},writable:true});Object.defineProperty(this,'irregulars',{enumerable:false,value:irregulars$2,writable:true});Object.defineProperty(this,'tags',{enumerable:false,value:Object.assign({},tags),writable:true});Object.defineProperty(this,'transforms',{enumerable:false,value:transforms$2,writable:true});Object.defineProperty(this,'taggers',{enumerable:false,value:[],writable:true});this.unpackWords(_data);this.addIrregulars();Object.defineProperty(this,'cache',{enumerable:false,value:{abbreviations:this.getByTag('Abbreviation')}});}
_createClass(World,[{key:"verbose",value:function verbose(bool){_isVerbose=bool;return this;}},{key:"isVerbose",value:function isVerbose(){return _isVerbose;}},{key:"getByTag",value:function getByTag(tag){var lex=this.words;var res={};var words=Object.keys(lex);for(var i=0;i<words.length;i++){if(typeof lex[words[i]]==='string'){if(lex[words[i]]===tag){res[words[i]]=true;}}else if(lex[words[i]].some(function(t){return t===tag;})){res[words[i]]=true;}}
return res;}},{key:"unpackWords",value:function unpackWords(lex){var tags=Object.keys(lex);for(var i=0;i<tags.length;i++){var words=Object.keys(efrtUnpack_min(lex[tags[i]]));for(var w=0;w<words.length;w++){addWords.addWord(words[w],tags[i],this.words);addWords.addMore(words[w],tags[i],this);}}}},{key:"addWords",value:function addWords$1(obj){var keys=Object.keys(obj);for(var i=0;i<keys.length;i++){var word=keys[i].toLowerCase();addWords.addWord(word,obj[keys[i]],this.words);addWords.addMore(word,obj[keys[i]],this);}}},{key:"addIrregulars",value:function addIrregulars(){addIrregulars_1(this);return this;}},{key:"addTags",value:function addTags(tags){tags=Object.assign({},tags);this.tags=Object.assign(this.tags,tags);this.tags=inference(this.tags);return this;}},{key:"postProcess",value:function postProcess(fn){this.taggers.push(fn);return this;}},{key:"stats",value:function stats(){return{words:Object.keys(this.words).length,plurals:Object.keys(this.irregulars.nouns).length,conjugations:Object.keys(this.irregulars.verbs).length,compounds:Object.keys(this.hasCompound).length,postProcessors:this.taggers.length};}}]);return World;}();var clone$1=function clone(obj){return JSON.parse(JSON.stringify(obj));};World.prototype.clone=function(){var w2=new World();w2.words=Object.assign({},this.words);w2.hasCompound=Object.assign({},this.hasCompound);w2.irregulars=clone$1(this.irregulars);w2.tags=clone$1(this.tags);w2.transforms=this.transforms;w2.taggers=this.taggers;return w2;};var World_1=World;var _01Utils$1=createCommonjsModule(function(module,exports){exports.all=function(){return this.parents()[0]||this;};exports.parent=function(){if(this.from){return this.from;}
return this;};exports.parents=function(n){var arr=[];var addParent=function addParent(doc){if(doc.from){arr.push(doc.from);addParent(doc.from);}};addParent(this);arr=arr.reverse();if(typeof n==='number'){return arr[n];}
return arr;};exports.clone=function(doShallow){var list=this.list.map(function(ts){return ts.clone(doShallow);});var tmp=this.buildFrom(list);return tmp;};exports.wordCount=function(){return this.list.reduce(function(count,p){count+=p.wordCount();return count;},0);};exports.wordcount=exports.wordCount;});var _02Accessors=createCommonjsModule(function(module,exports){exports.first=function(n){if(n===undefined){return this.get(0);}
return this.slice(0,n);};exports.last=function(n){if(n===undefined){return this.get(this.list.length-1);}
var end=this.list.length;return this.slice(end-n,end);};exports.slice=function(start,end){var list=this.list.slice(start,end);return this.buildFrom(list);};exports.eq=function(n){var p=this.list[n];if(p===undefined){return this.buildFrom([]);}
return this.buildFrom([p]);};exports.get=exports.eq;exports.firstTerms=function(){return this.match('^.');};exports.firstTerm=exports.firstTerms;exports.lastTerms=function(){return this.match('.$');};exports.lastTerm=exports.lastTerms;exports.termList=function(num){var arr=[];for(var i=0;i<this.list.length;i++){var terms=this.list[i].terms();for(var o=0;o<terms.length;o++){arr.push(terms[o]);if(num!==undefined&&arr[num]!==undefined){return arr[num];}}}
return arr;};exports.textList=function(num){var arr=[];for(var i=0;i<this.list.length;i++){var terms=this.list[i].terms();for(var o=0;o<terms.length;o++){arr.push(terms[o]);if(num!==undefined&&arr[num]!==undefined){return arr[num];}}}
return arr.map(function(term){return term.text});};var getGroups=function getGroups(doc){var res={};var allGroups={};var _loop=function _loop(i){var phrase=doc.list[i];var groups=Object.keys(phrase.groups).map(function(k){return phrase.groups[k];});for(var j=0;j<groups.length;j++){var _groups$j=groups[j],group=_groups$j.group,start=_groups$j.start,length=_groups$j.length;if(!allGroups[group]){allGroups[group]=[];}
allGroups[group].push(phrase.buildFrom(start,length));}};for(var i=0;i<doc.list.length;i++){_loop(i);}
var keys=Object.keys(allGroups);for(var _i=0;_i<keys.length;_i++){var key=keys[_i];res[key]=doc.buildFrom(allGroups[key]);}
return res;};var getOneName=function getOneName(doc,name){var arr=[];var _loop2=function _loop2(i){var phrase=doc.list[i];var keys=Object.keys(phrase.groups);keys=keys.filter(function(id){return phrase.groups[id].group===name;});keys.forEach(function(id){arr.push(phrase.buildFrom(phrase.groups[id].start,phrase.groups[id].length));});};for(var i=0;i<doc.list.length;i++){_loop2(i);}
return doc.buildFrom(arr);};exports.groups=function(target){if(target===undefined){return getGroups(this);}
if(typeof target==='number'){target=String(target);}
return getOneName(this,target)||this.buildFrom([]);};exports.group=exports.groups;exports.sentences=function(n){var arr=[];this.list.forEach(function(p){arr.push(p.fullSentence());});if(typeof n==='number'){return this.buildFrom([arr[n]]);}
return this.buildFrom(arr);};exports.sentence=exports.sentences;});var cacheRequired=function cacheRequired(reg){var needTags=[];var needWords=[];reg.forEach(function(obj){if(obj.optional===true||obj.negative===true){return;}
if(obj.tag!==undefined){needTags.push(obj.tag);}
if(obj.word!==undefined){needWords.push(obj.word);}});return{tags:needTags,words:needWords};};var failFast$1=function failFast(doc,regs){if(doc._cache&&doc._cache.set===true){var _cacheRequired=cacheRequired(regs),words=_cacheRequired.words,tags=_cacheRequired.tags;for(var i=0;i<words.length;i++){if(doc._cache.words[words[i]]===undefined){return false;}}
for(var _i=0;_i<tags.length;_i++){if(doc._cache.tags[tags[_i]]===undefined){return false;}}}
return true;};var checkCache=failFast$1;var _03Match=createCommonjsModule(function(module,exports){exports.match=function(reg,name){var regs=syntax_1(reg);if(regs.length===0){return this.buildFrom([]);}
if(checkCache(this,regs)===false){return this.buildFrom([]);}
var matches=this.list.reduce(function(arr,p){return arr.concat(p.match(regs));},[]);if(name!==undefined&&name!==null&&name!==''){return this.buildFrom(matches).groups(name);}
return this.buildFrom(matches);};exports.not=function(reg){var regs=syntax_1(reg);if(regs.length===0||checkCache(this,regs)===false){return this;}
var matches=this.list.reduce(function(arr,p){return arr.concat(p.not(regs));},[]);return this.buildFrom(matches);};exports.matchOne=function(reg){var regs=syntax_1(reg);if(checkCache(this,regs)===false){return this.buildFrom([]);}
for(var i=0;i<this.list.length;i++){var match=this.list[i].match(regs,true);return this.buildFrom(match);}
return this.buildFrom([]);};exports["if"]=function(reg){var regs=syntax_1(reg);if(checkCache(this,regs)===false){return this.buildFrom([]);}
var found=this.list.filter(function(p){return p.has(regs)===true;});return this.buildFrom(found);};exports.ifNo=function(reg){var regs=syntax_1(reg);var found=this.list.filter(function(p){return p.has(regs)===false;});return this.buildFrom(found);};exports.has=function(reg,all){if(typeof reg=='object'&&reg.length){for(var i in reg){var check=exports.has.call(this,reg[i]);if(all&&!check)return false;if(!all&&check)return true;}
return all?true:false;}
var regs=syntax_1(reg);if(checkCache(this,regs)===false){return false;}
return this.list.some(function(p){return p.has(regs)===true;});};exports.hasSimilar=function(reg,thres,all){var terms=this.termList();var count=0;thres=thres||90;if(typeof reg=='string')reg=[reg];for(var i in terms){for(var j in reg){var check=similar_text(terms[i].text,reg[j],1)>thres;if(!all&&check)return true;if(check){count++;break}}}
return all?count==res.length:false;}
exports.lookAhead=function(reg){if(!reg){reg='.*';}
var regs=syntax_1(reg);var matches=[];this.list.forEach(function(p){matches=matches.concat(p.lookAhead(regs));});matches=matches.filter(function(p){return p;});return this.buildFrom(matches);};exports.lookAfter=exports.lookAhead;exports.lookBehind=function(reg){if(!reg){reg='.*';}
var regs=syntax_1(reg);var matches=[];this.list.forEach(function(p){matches=matches.concat(p.lookBehind(regs));});matches=matches.filter(function(p){return p;});return this.buildFrom(matches);};exports.lookBefore=exports.lookBehind;exports.before=function(reg){var regs=syntax_1(reg);var phrases=this["if"](regs).list;var befores=phrases.map(function(p){var ids=p.terms().map(function(t){return t.id;});var m=p.match(regs)[0];var index=ids.indexOf(m.start);if(index===0||index===-1){return null;}
return p.buildFrom(p.start,index);});befores=befores.filter(function(p){return p!==null;});return this.buildFrom(befores);};exports.after=function(reg){var regs=syntax_1(reg);var phrases=this["if"](regs).list;var befores=phrases.map(function(p){var terms=p.terms();var ids=terms.map(function(t){return t.id;});var m=p.match(regs)[0];var index=ids.indexOf(m.start);if(index===-1||!terms[index+m.length]){return null;}
var id=terms[index+m.length].id;var len=p.length-index-m.length;return p.buildFrom(id,len);});befores=befores.filter(function(p){return p!==null;});return this.buildFrom(befores);};exports.hasAfter=function(reg){return this.filter(function(doc){return doc.lookAfter(reg).found;});};exports.hasBefore=function(reg){return this.filter(function(doc){return doc.lookBefore(reg).found;});};});var tagTerms=function tagTerms(tag,doc,safe,reason){var tagList=[];if(typeof tag==='string'){tagList=tag.split(' ');}
doc.list.forEach(function(p){var terms=p.terms();if(safe===true){terms=terms.filter(function(t){return t.canBe(tag,doc.world);});}
terms.forEach(function(t,i){if(tagList.length>1){if(tagList[i]&&tagList[i]!=='.'){t.tag(tagList[i],reason,doc.world);}}else{t.tag(tag,reason,doc.world);}});});return;};var _setTag=tagTerms;var tag$1=function tag(tags,why){if(!tags){return this;}
_setTag(tags,this,false,why);return this;};var tagSafe$1=function tagSafe(tags,why){if(!tags){return this;}
_setTag(tags,this,true,why);return this;};var unTag$1=function unTag(tags,why){var _this=this;this.list.forEach(function(p){p.terms().forEach(function(t){return t.unTag(tags,why,_this.world);});});return this;};var canBe$2=function canBe(tag){if(!tag){return this;}
var world=this.world;var matches=this.list.reduce(function(arr,p){return arr.concat(p.canBe(tag,world));},[]);return this.buildFrom(matches);};var _04Tag={tag:tag$1,tagSafe:tagSafe$1,unTag:unTag$1,canBe:canBe$2};var map=function map(fn){var _this=this;if(!fn){return this;}
var list=this.list.map(function(p,i){var doc=_this.buildFrom([p]);doc.from=null;var res=fn(doc,i);if(res&&res.list&&res.list[0]){return res.list[0];}
return res;});list=list.filter(function(x){return x;});if(list.length===0){return this.buildFrom(list);}
if(_typeof(list[0])!=='object'||list[0].isA!=='Phrase'){return list;}
return this.buildFrom(list);};var forEach=function forEach(fn,detachParent){var _this2=this;if(!fn){return this;}
this.list.forEach(function(p,i){var sub=_this2.buildFrom([p]);if(detachParent===true){sub.from=null;}
fn(sub,i);});return this;};var filter=function filter(fn){var _this3=this;if(!fn){return this;}
var list=this.list.filter(function(p,i){var doc=_this3.buildFrom([p]);doc.from=null;return fn(doc,i);});return this.buildFrom(list);};var find=function find(fn){var _this4=this;if(!fn){return this;}
var phrase=this.list.find(function(p,i){var doc=_this4.buildFrom([p]);doc.from=null;return fn(doc,i);});if(phrase){return this.buildFrom([phrase]);}
return undefined;};var some=function some(fn){var _this5=this;if(!fn){return this;}
return this.list.some(function(p,i){var doc=_this5.buildFrom([p]);doc.from=null;return fn(doc,i);});};var random=function random(n){if(!this.found){return this;}
var r=Math.floor(Math.random()*this.list.length);if(n===undefined){var list=[this.list[r]];return this.buildFrom(list);}
if(r+n>this.length){r=this.length-n;r=r<0?0:r;}
return this.slice(r,r+n);};var _05Loops={map:map,forEach:forEach,filter:filter,find:find,some:some,random:random};var tokenize=function tokenize(str){return str.split(/[ -]/g);};var buildTree=function buildTree(termList){var values=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var root={};termList.forEach(function(str,i){var val=true;if(values[i]!==undefined){val=values[i];}
str=(str||'').toLowerCase();str=str.replace(/[,;.!?]+$/,'');var arr=tokenize(str).map(function(s){return s.trim();});root[arr[0]]=root[arr[0]]||{};if(arr.length===1){root[arr[0]].value=val;}else{root[arr[0]].more=root[arr[0]].more||[];root[arr[0]].more.push({rest:arr.slice(1),value:val});}});return root;};var fastLookup=function fastLookup(termList,values,doc){var root=buildTree(termList,values);var found=[];var _loop=function _loop(i){var p=doc.list[i];var terms=p.terms();var words=terms.map(function(t){return t.reduced;});var _loop2=function _loop2(w){if(root[words[w]]!==undefined){if(root[words[w]].more!==undefined){root[words[w]].more.forEach(function(more){if(words[w+more.rest.length]===undefined){return;}
var everyTerm=more.rest.every(function(word,r){return word===words[w+r+1];});if(everyTerm===true){found.push({id:p.terms()[w].id,value:more.value,length:more.rest.length+1});}});}
if(root[words[w]].value!==undefined){found.push({id:p.terms()[w].id,value:root[words[w]].value,length:1});}}};for(var w=0;w<words.length;w++){_loop2(w);}};for(var i=0;i<doc.list.length;i++){_loop(i);}
return found;};var _lookup=fastLookup;var _06Lookup=createCommonjsModule(function(module,exports){var isObject=function isObject(obj){return obj&&Object.prototype.toString.call(obj)==='[object Object]';};exports.lookup=function(arr){var _this=this;var values=[];var isObj=isObject(arr);if(isObj===true){arr=Object.keys(arr).map(function(k){values.push(arr[k]);return k;});}
if(typeof arr==='string'){arr=[arr];}
if(this._cache.set!==true){this.cache();}
var found=_lookup(arr,values,this);var p=this.list[0];if(isObj===true){var byVal={};found.forEach(function(o){byVal[o.value]=byVal[o.value]||[];byVal[o.value].push(p.buildFrom(o.id,o.length));});Object.keys(byVal).forEach(function(k){byVal[k]=_this.buildFrom(byVal[k]);});return byVal;}
found=found.map(function(o){return p.buildFrom(o.id,o.length);});return this.buildFrom(found);};exports.lookUp=exports.lookup;});var cache$1=function cache(options){var _this=this;options=options||{};var words={};var tags={};this._cache.words=words;this._cache.tags=tags;this._cache.set=true;this.list.forEach(function(p,i){p.cache=p.cache||{};var terms=p.terms();terms.forEach(function(t){if(words[t.reduced]&&!words.hasOwnProperty(t.reduced)){return;}
words[t.reduced]=words[t.reduced]||[];words[t.reduced].push(i);Object.keys(t.tags).forEach(function(tag){tags[tag]=tags[tag]||[];tags[tag].push(i);});if(options.root){t.setRoot(_this.world);words[t.root]=true;}});});return this;};var uncache=function uncache(){this._cache={};this.list.forEach(function(p){p.cache={};});this.parents().forEach(function(doc){doc._cache={};doc.list.forEach(function(p){p.cache={};});});return this;};var _07Cache={cache:cache$1,uncache:uncache};var titleCase$3=function titleCase(str){return str.charAt(0).toUpperCase()+str.substr(1);};var replaceWith=function replaceWith(replace){var _this=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!replace){return this["delete"]();}
if(options===true){options={keepTags:true};}
if(options===false){options={keepTags:false};}
options=options||{};this.uncache();this.list.forEach(function(p){var input=replace;if(typeof replace==='function'){input=replace(p);}
var newPhrases;if(input&&_typeof(input)==='object'&&input.isA==='Doc'){newPhrases=input.list;_this.pool().merge(input.pool());}else if(typeof input==='string'){if(options.keepCase!==false&&p.terms(0).isTitleCase()){input=titleCase$3(input);}
newPhrases=_01Tokenizer(input,_this.world,_this.pool());var tmpDoc=_this.buildFrom(newPhrases);tmpDoc.tagger();newPhrases=tmpDoc.list;}else{return;}
if(options.keepTags===true){var oldTags=p.json({terms:{tags:true}}).terms;newPhrases[0].terms().forEach(function(t,i){if(oldTags[i]){t.tagSafe(oldTags[i].tags,'keptTag',_this.world);}});}
p.replace(newPhrases[0],_this);});return this;};var replace$1=function replace(match,_replace,options){if(_replace===undefined){return this.replaceWith(match,options);}
this.match(match).replaceWith(_replace,options);return this;};var _01Replace={replaceWith:replaceWith,replace:replace$1};var _02Insert=createCommonjsModule(function(module,exports){var makeNew=function makeNew(str,doc){var phrase=_01Tokenizer(str,doc.world)[0];var tmpDoc=doc.buildFrom([phrase]);tmpDoc.tagger();doc.list=tmpDoc.list;return doc;};exports.append=function(str){var _this=this;if(!str){return this;}
if(!this.found){return makeNew(str,this);}
this.uncache();this.list.forEach(function(p){var phrase=_01Tokenizer(str,_this.world,_this.pool())[0];var tmpDoc=_this.buildFrom([phrase]);tmpDoc.tagger();p.append(phrase,_this);});return this;};exports.insertAfter=exports.append;exports.insertAt=exports.append;exports.prepend=function(str){var _this2=this;if(!str){return this;}
if(!this.found){return makeNew(str,this);}
this.uncache();this.list.forEach(function(p){var phrase=_01Tokenizer(str,_this2.world,_this2.pool())[0];var tmpDoc=_this2.buildFrom([phrase]);tmpDoc.tagger();p.prepend(phrase,_this2);});return this;};exports.insertBefore=exports.prepend;exports.concat=function(){this.uncache();var list=this.list.slice(0);for(var i=0;i<arguments.length;i++){var arg=arguments[i];if(typeof arg==='string'){var arr=_01Tokenizer(arg,this.world);list=list.concat(arr);}else if(arg.isA==='Doc'){list=list.concat(arg.list);}else if(arg.isA==='Phrase'){list.push(arg);}}
return this.buildFrom(list);};exports["delete"]=function(match){var _this3=this;this.uncache();var toRemove=this;if(match){toRemove=this.match(match);}
toRemove.list.forEach(function(phrase){return phrase["delete"](_this3);});return this;};exports.remove=exports["delete"];});var shouldTrim={clean:true,reduced:true,root:true};var text$1=function text(options){var _this=this;options=options||{};var showFull=false;if(this.parents().length===0){showFull=true;}
if(options==='root'||_typeof(options)==='object'&&options.root){this.list.forEach(function(p){p.terms().forEach(function(t){if(t.root===null){t.setRoot(_this.world);}});});}
var txt=this.list.reduce(function(str,p,i){var trimPre=!showFull&&i===0;var trimPost=!showFull&&i===_this.list.length-1;return str+p.text(options,trimPre,trimPost);},'');if(shouldTrim[options]===true||options.reduced===true||options.clean===true||options.root===true){txt=txt.trim();}
return txt;};var _01Text={text:text$1};var termOffsets=function termOffsets(doc){var elapsed=0;var index=0;var offsets={};doc.termList().forEach(function(term){offsets[term.id]={index:index,start:elapsed+term.pre.length,length:term.text.length};elapsed+=term.pre.length+term.text.length+term.post.length;index+=1;});return offsets;};var calcOffset=function calcOffset(doc,result,options){var offsets=termOffsets(doc.all());if(options.terms.index||options.index){result.forEach(function(o){o.terms.forEach(function(t){t.index=offsets[t.id].index;});o.index=o.terms[0].index;});}
if(options.terms.offset||options.offset){result.forEach(function(o){o.terms.forEach(function(t){t.offset=offsets[t.id]||{};});o.offset={index:o.terms[0].offset.index,start:o.terms[0].offset.start-o.text.indexOf(o.terms[0].text),length:o.text.length};});}};var _offset=calcOffset;var _02Json=createCommonjsModule(function(module,exports){var jsonDefaults={text:true,terms:true,trim:true};var setOptions=function setOptions(options){options=Object.assign({},jsonDefaults,options);if(options.unique){options.reduced=true;}
if(options.offset){options.text=true;if(!options.terms||options.terms===true){options.terms={};}
options.terms.offset=true;}
if(options.index||options.terms.index){options.terms=options.terms===true?{}:options.terms;options.terms.id=true;}
return options;};exports.json=function(){var _this=this;var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(typeof options==='number'&&this.list[options]){return this.list[options].json(jsonDefaults);}
options=setOptions(options);if(options.root===true){this.list.forEach(function(p){p.terms().forEach(function(t){if(t.root===null){t.setRoot(_this.world);}});});}
var result=this.list.map(function(p){return p.json(options,_this.world);});if(options.terms.offset||options.offset||options.terms.index||options.index){_offset(this,result,options);}
if(options.frequency||options.freq||options.count){var obj={};this.list.forEach(function(p){var str=p.text('reduced');obj[str]=obj[str]||0;obj[str]+=1;});this.list.forEach(function(p,i){result[i].count=obj[p.text('reduced')];});}
if(options.unique){var already={};result=result.filter(function(o){if(already[o.reduced]===true){return false;}
already[o.reduced]=true;return true;});}
return result;};exports.data=exports.json;});var _debug=createCommonjsModule(function(module){var reset='\x1b[0m';var padEnd=function padEnd(str,width){str=str.toString();while(str.length<width){str+=' ';}
return str;};function isClientSide(){return typeof window!=='undefined'&&window.document;}
var css={green:'#7f9c6c',red:'#914045',blue:'#6699cc',magenta:'#6D5685',cyan:'#2D85A8',yellow:'#e6d7b3',black:'#303b50'};var logClientSide=function logClientSide(doc){var tagset=doc.world.tags;doc.list.forEach(function(p){console.log('\n%c"'+p.text()+'"','color: #e6d7b3;');var terms=p.terms();terms.forEach(function(t){var tags=Object.keys(t.tags);var text=t.text||'-';if(t.implicit){text='['+t.implicit+']';}
var word="'"+text+"'";word=padEnd(word,8);var found=tags.find(function(tag){return tagset[tag]&&tagset[tag].color;});var color='steelblue';if(tagset[found]){color=tagset[found].color;color=css[color];}
console.log(" ".concat(word," - %c").concat(tags.join(', ')),"color: ".concat(color||'steelblue',";"));});});};var cli={green:function green(str){return'\x1b[32m'+str+reset;},red:function red(str){return'\x1b[31m'+str+reset;},blue:function blue(str){return'\x1b[34m'+str+reset;},magenta:function magenta(str){return'\x1b[35m'+str+reset;},cyan:function cyan(str){return'\x1b[36m'+str+reset;},yellow:function yellow(str){return'\x1b[33m'+str+reset;},black:function black(str){return'\x1b[30m'+str+reset;}};var tagString=function tagString(tags,world){tags=tags.map(function(tag){if(!world.tags.hasOwnProperty(tag)){return tag;}
var c=world.tags[tag].color||'blue';return cli[c](tag);});return tags.join(', ');};var debug=function debug(doc){if(isClientSide()){logClientSide(doc);return doc;}
console.log(cli.blue('====='));doc.list.forEach(function(p){console.log(cli.blue(' -----'));var terms=p.terms();terms.forEach(function(t){var tags=Object.keys(t.tags);var text=t.text||'-';if(t.implicit){text='['+t.implicit+']';}
{text=cli.yellow(text);}
var word="'"+text+"'";word=padEnd(word,18);var str=cli.blue(' ')+word+' - '+tagString(tags,doc.world);console.log(str);});});console.log('');return doc;};module.exports=debug;});var topk=function topk(doc){var list=doc.json({text:false,terms:false,reduced:true});var obj={};list.forEach(function(o){if(!obj[o.reduced]){o.count=0;obj[o.reduced]=o;}
obj[o.reduced].count+=1;});var arr=Object.keys(obj).map(function(k){return obj[k];});arr.sort(function(a,b){if(a.count>b.count){return-1;}else if(a.count<b.count){return 1;}
return 0;});return arr;};var _topk=topk;var debug_1=function debug_1(){_debug(this);return this;};var out=function out(method){if(method==='text'){return this.text();}
if(method==='normal'){return this.text('normal');}
if(method==='json'){return this.json();}
if(method==='offset'||method==='offsets'){return this.json({offset:true});}
if(method==='array'){return this.json({terms:false}).map(function(obj){return obj.text;});}
if(method==='freq'||method==='frequency'){return _topk(this);}
if(method==='terms'){var list=[];this.json({text:false,terms:{text:true}}).forEach(function(obj){var terms=obj.terms.map(function(t){return t.text;});terms=terms.filter(function(t){return t;});list=list.concat(terms);});return list;}
if(method==='tags'){return this.list.map(function(p){return p.terms().reduce(function(h,t){h[t.clean||t.implicit]=Object.keys(t.tags);return h;},{});});}
if(method==='debug'){_debug(this);return this;}
return this.text();};var _03Out={debug:debug_1,out:out};var methods$2={alpha:function alpha(a,b){var left=a.text('clean');var right=b.text('clean');if(left<right){return-1;}
if(left>right){return 1;}
return 0;},length:function length(a,b){var left=a.text().trim().length;var right=b.text().trim().length;if(left<right){return 1;}
if(left>right){return-1;}
return 0;},wordCount:function wordCount(a,b){var left=a.wordCount();var right=b.wordCount();if(left<right){return 1;}
if(left>right){return-1;}
return 0;}};var byFreq=function byFreq(doc){var counts={};var options={"case":true,punctuation:false,whitespace:true,unicode:true};doc.list.forEach(function(p){var str=p.text(options);counts[str]=counts[str]||0;counts[str]+=1;});doc.list.sort(function(a,b){var left=counts[a.text(options)];var right=counts[b.text(options)];if(left<right){return 1;}
if(left>right){return-1;}
return 0;});return doc;};var sortSequential=function sortSequential(doc){var order={};doc.json({terms:{offset:true}}).forEach(function(o){order[o.terms[0].id]=o.terms[0].offset.start;});doc.list=doc.list.sort(function(a,b){if(order[a.start]>order[b.start]){return 1;}else if(order[a.start]<order[b.start]){return-1;}
return 0;});return doc;};methods$2.alphabetical=methods$2.alpha;methods$2.wordcount=methods$2.wordCount;var seqNames={index:true,sequence:true,seq:true,sequential:true,chron:true,chronological:true};var sort=function sort(input){input=input||'alpha';if(input==='freq'||input==='frequency'||input==='topk'){return byFreq(this);}
if(seqNames.hasOwnProperty(input)){return sortSequential(this);}
input=methods$2[input]||input;if(typeof input==='function'){this.list=this.list.sort(input);return this;}
return this;};var reverse=function reverse(){var list=[].concat(this.list);list=list.reverse();return this.buildFrom(list);};var unique$4=function unique(){var list=[].concat(this.list);var obj={};list=list.filter(function(p){var str=p.text('reduced').trim();if(obj.hasOwnProperty(str)===true){return false;}
obj[str]=true;return true;});return this.buildFrom(list);};var _01Sort={sort:sort,reverse:reverse,unique:unique$4};var isPunct=/[\[\]{}⟨⟩:,،、‒–—―…‹›«»‐\-;\/⁄·*\•^†‡°¡¿※№÷׺ª%‰=‱¶§~|‖¦©℗®℠™¤₳฿]/g;var quotes=/['‘’“”"′″‴]+/g;var methods$3={whitespace:function whitespace(doc){var termArr=doc.list.map(function(ts){return ts.terms();});termArr.forEach(function(terms,o){terms.forEach(function(t,i){if(t.hasDash()===true){t.post=' - ';return;}
t.pre=t.pre.replace(/\s/g,'');t.post=t.post.replace(/\s/g,'');if(terms.length-1===i&&!termArr[o+1]){return;}
if(t.implicit&&Boolean(t.text)===true){return;}
if(t.hasHyphen()===true){return;}
t.post+=' ';});});},punctuation:function punctuation(termList){termList.forEach(function(t){if(t.hasHyphen()===true){t.post=' ';}
t.pre=t.pre.replace(isPunct,'');t.post=t.post.replace(isPunct,'');t.post=t.post.replace(/\.\.\./,'');if(/!/.test(t.post)===true){t.post=t.post.replace(/!/g,'');t.post='!'+t.post;}
if(/\?/.test(t.post)===true){t.post=t.post.replace(/[\?!]*/,'');t.post='?'+t.post;}});},unicode:function unicode(termList){termList.forEach(function(t){if(t.isImplicit()===true){return;}
t.text=unicode_1(t.text);});},quotations:function quotations(termList){termList.forEach(function(t){t.post=t.post.replace(quotes,'');t.pre=t.pre.replace(quotes,'');});},adverbs:function adverbs(doc){doc.match('#Adverb').not('(not|nary|seldom|never|barely|almost|basically|so)').remove();},abbreviations:function abbreviations(doc){doc.list.forEach(function(ts){var terms=ts.terms();terms.forEach(function(t,i){if(t.tags.Abbreviation===true&&terms[i+1]){t.post=t.post.replace(/^\./,'');}});});}};var _methods=methods$3;var defaults={whitespace:true,unicode:true,punctuation:true,emoji:true,acronyms:true,abbreviations:true,"case":false,contractions:false,parentheses:false,quotations:false,adverbs:false,possessives:false,verbs:false,nouns:false,honorifics:false};var mapping$1={light:{},medium:{"case":true,contractions:true,parentheses:true,quotations:true,adverbs:true}};mapping$1.heavy=Object.assign({},mapping$1.medium,{possessives:true,verbs:true,nouns:true,honorifics:true});var normalize=function normalize(options){options=options||{};if(typeof options==='string'){options=mapping$1[options]||{};}
options=Object.assign({},defaults,options);this.uncache();var termList=this.termList();if(options["case"]){this.toLowerCase();}
if(options.whitespace){_methods.whitespace(this);}
if(options.unicode){_methods.unicode(termList);}
if(options.punctuation){_methods.punctuation(termList);}
if(options.emoji){this.remove('(#Emoji|#Emoticon)');}
if(options.acronyms){this.acronyms().strip();}
if(options.abbreviations){_methods.abbreviations(this);}
if(options.contraction||options.contractions){this.contractions().expand();}
if(options.parentheses){this.parentheses().unwrap();}
if(options.quotations||options.quotes){_methods.quotations(termList);}
if(options.adverbs){_methods.adverbs(this);}
if(options.possessive||options.possessives){this.possessives().strip();}
if(options.verbs){this.verbs().toInfinitive();}
if(options.nouns||options.plurals){this.nouns().toSingular();}
if(options.honorifics){this.remove('#Honorific');}
return this;};var _02Normalize={normalize:normalize};var _03Split=createCommonjsModule(function(module,exports){exports.splitOn=function(reg){if(!reg){var parent=this.parent();return parent.splitOn(this);}
var regs=syntax_1(reg);var matches=[];this.list.forEach(function(p){var foundEm=p.match(regs);if(foundEm.length===0){matches.push(p);return;}
var carry=p;foundEm.forEach(function(found){var parts=carry.splitOn(found);if(parts.before){matches.push(parts.before);}
if(parts.match){matches.push(parts.match);}
carry=parts.after;});if(carry){matches.push(carry);}});return this.buildFrom(matches);};exports.splitAfter=function(reg){if(!reg){var parent=this.parent();return parent.splitAfter(this);}
var regs=syntax_1(reg);var matches=[];this.list.forEach(function(p){var foundEm=p.match(regs);if(foundEm.length===0){matches.push(p);return;}
var carry=p;foundEm.forEach(function(found){var parts=carry.splitOn(found);if(parts.before&&parts.match){parts.before.length+=parts.match.length;matches.push(parts.before);}else if(parts.match){matches.push(parts.match);}
carry=parts.after;});if(carry){matches.push(carry);}});return this.buildFrom(matches);};exports.split=exports.splitAfter;exports.splitBefore=function(reg){if(!reg){var parent=this.parent();return parent.splitBefore(this);}
var regs=syntax_1(reg);var matches=[];this.list.forEach(function(p){var foundEm=p.match(regs);if(foundEm.length===0){matches.push(p);return;}
var carry=p;foundEm.forEach(function(found){var parts=carry.splitOn(found);if(parts.before){matches.push(parts.before);}
if(parts.match&&parts.after){parts.match.length+=parts.after.length;}
carry=parts.match;});if(carry){matches.push(carry);}});return this.buildFrom(matches);};exports.segment=function(regs,options){regs=regs||{};options=options||{text:true};var doc=this;var keys=Object.keys(regs);keys.forEach(function(k){doc=doc.splitOn(k);});doc.list.forEach(function(p){for(var i=0;i<keys.length;i+=1){if(p.has(keys[i])){p.segment=regs[keys[i]];return;}}});return doc.list.map(function(p){var res=p.json(options);res.segment=p.segment||null;return res;});};});var eachTerm=function eachTerm(doc,fn){var world=doc.world;doc.list.forEach(function(p){p.terms().forEach(function(t){return t[fn](world);});});return doc;};var toLowerCase=function toLowerCase(){return eachTerm(this,'toLowerCase');};var toUpperCase=function toUpperCase(){return eachTerm(this,'toUpperCase');};var toTitleCase=function toTitleCase(){return eachTerm(this,'toTitleCase');};var toCamelCase=function toCamelCase(){this.list.forEach(function(p){var terms=p.terms();terms.forEach(function(t,i){if(i!==0){t.toTitleCase();}
if(i!==terms.length-1){t.post='';}});});return this;};var _04Case={toLowerCase:toLowerCase,toUpperCase:toUpperCase,toTitleCase:toTitleCase,toCamelCase:toCamelCase};var _05Whitespace=createCommonjsModule(function(module,exports){exports.pre=function(str,concat){if(str===undefined){return this.list[0].terms(0).pre;}
this.list.forEach(function(p){var term=p.terms(0);if(concat===true){term.pre+=str;}else{term.pre=str;}});return this;};exports.post=function(str,concat){if(str===undefined){return this.list.map(function(p){var terms=p.terms();var term=terms[terms.length-1];return term.post;});}
this.list.forEach(function(p){var terms=p.terms();var term=terms[terms.length-1];if(concat===true){term.post+=str;}else{term.post=str;}});return this;};exports.trim=function(){this.list=this.list.map(function(p){return p.trim();});return this;};exports.hyphenate=function(){this.list.forEach(function(p){var terms=p.terms();terms.forEach(function(t,i){if(i!==0){t.pre='';}
if(terms[i+1]){t.post='-';}});});return this;};exports.dehyphenate=function(){var hasHyphen=/(-||—)/;this.list.forEach(function(p){var terms=p.terms();terms.forEach(function(t){if(hasHyphen.test(t.post)){t.post=' ';}});});return this;};exports.deHyphenate=exports.dehyphenate;exports.toQuotations=function(start,end){start=start||"\"";end=end||"\"";this.list.forEach(function(p){var terms=p.terms();terms[0].pre=start+terms[0].pre;var last=terms[terms.length-1];last.post=end+last.post;});return this;};exports.toQuotation=exports.toQuotations;exports.toParentheses=function(start,end){start=start||"(";end=end||")";this.list.forEach(function(p){var terms=p.terms();terms[0].pre=start+terms[0].pre;var last=terms[terms.length-1];last.post=end+last.post;});return this;};});var join=function join(str){this.uncache();var main=this.list[0];var before=main.length;var removed={};for(var i=1;i<this.list.length;i++){var p=this.list[i];removed[p.start]=true;var term=main.lastTerm();if(str){term.post+=str;}
term.next=p.start;p.terms(0).prev=term.id;main.length+=p.length;main.cache={};}
var increase=main.length-before;this.parents().forEach(function(doc){doc.list.forEach(function(p){var terms=p.terms();for(var _i=0;_i<terms.length;_i++){if(terms[_i].id===main.start){p.length+=increase;break;}}
p.cache={};});doc.list=doc.list.filter(function(p){return removed[p.start]!==true;});});return this.buildFrom([main]);};var _06Join={join:join};var postPunct=/[,\)"';:\-–—\.…]/;var setContraction=function setContraction(m,suffix){if(!m.found){return;}
var terms=m.termList();for(var i=0;i<terms.length-1;i++){var t=terms[i];if(postPunct.test(t.post)){return;}}
terms.forEach(function(t){t.implicit=t.clean;});terms[0].text+=suffix;terms.slice(1).forEach(function(t){t.text='';});for(var _i=0;_i<terms.length-1;_i++){var _t=terms[_i];_t.post=_t.post.replace(/ /,'');}};var contract=function contract(){var doc=this.not('@hasContraction');var m=doc.match('(we|they|you) are');setContraction(m,"'re");m=doc.match('(he|she|they|it|we|you) will');setContraction(m,"'ll");m=doc.match('(he|she|they|it|we) is');setContraction(m,"'s");m=doc.match('#Person is');setContraction(m,"'s");m=doc.match('#Person would');setContraction(m,"'d");m=doc.match('(is|was|had|would|should|could|do|does|have|has|can) not');setContraction(m,"n't");m=doc.match('(i|we|they) have');setContraction(m,"'ve");m=doc.match('(would|should|could) have');setContraction(m,"'ve");m=doc.match('i am');setContraction(m,"'m");m=doc.match('going to');return this;};var _07Contract={contract:contract};var methods$4=Object.assign({},_01Utils$1,_02Accessors,_03Match,_04Tag,_05Loops,_06Lookup,_07Cache,_01Replace,_02Insert,_01Text,_02Json,_03Out,_01Sort,_02Normalize,_03Split,_04Case,_05Whitespace,_06Join,_07Contract);var methods$5={};var arr=[['terms','.'],['hyphenated','@hasHyphen .'],['adjectives','#Adjective'],['hashTags','#HashTag'],['emails','#Email'],['emoji','#Emoji'],['emoticons','#Emoticon'],['atMentions','#AtMention'],['urls','#Url'],['adverbs','#Adverb'],['pronouns','#Pronoun'],['conjunctions','#Conjunction'],['prepositions','#Preposition']];arr.forEach(function(a){methods$5[a[0]]=function(n){var m=this.match(a[1]);if(typeof n==='number'){m=m.get(n);}
return m;};});methods$5.emojis=methods$5.emoji;methods$5.atmentions=methods$5.atMentions;methods$5.words=methods$5.terms;methods$5.phoneNumbers=function(n){var m=this.splitAfter('@hasComma');m=m.match('#PhoneNumber+');if(typeof n==='number'){m=m.get(n);}
return m;};methods$5.money=function(n){var m=this.match('#Money #Currency?');if(typeof n==='number'){m=m.get(n);}
return m;};methods$5.places=function(n){var keep=this.match('(#City && @hasComma) (#Region|#Country)');var m=this.not(keep).splitAfter('@hasComma');m=m.concat(keep);m.sort('index');m=m.match('#Place+');if(typeof n==='number'){m=m.get(n);}
return m;};methods$5.organizations=function(n){var m=this.clauses();m=m.match('#Organization+');if(typeof n==='number'){m=m.get(n);}
return m;};methods$5.entities=function(n){var r=this.clauses();var yup=r.people();yup=yup.concat(r.places());yup=yup.concat(r.organizations());var ignore=['someone','man','woman','mother','brother','sister','father'];yup=yup.not(ignore);yup.sort('sequence');if(typeof n==='number'){yup=yup.get(n);}
return yup;};methods$5.things=methods$5.entities;methods$5.topics=methods$5.entities;var _simple=methods$5;var underOver=/^(under|over)-?/;var tryMultiple=function tryMultiple(terms,t,world){var lex=world.words;var txt=terms[t].reduced+' '+terms[t+1].reduced;if(lex[txt]!==undefined&&lex.hasOwnProperty(txt)===true){terms[t].tag(lex[txt],'lexicon-two',world);terms[t+1].tag(lex[txt],'lexicon-two',world);return 1;}
if(t+2<terms.length){txt+=' '+terms[t+2].reduced;if(lex[txt]!==undefined&&lex.hasOwnProperty(txt)===true){terms[t].tag(lex[txt],'lexicon-three',world);terms[t+1].tag(lex[txt],'lexicon-three',world);terms[t+2].tag(lex[txt],'lexicon-three',world);return 2;}}
if(t+3<terms.length){txt+=' '+terms[t+3].reduced;if(lex[txt]!==undefined&&lex.hasOwnProperty(txt)===true){terms[t].tag(lex[txt],'lexicon-four',world);terms[t+1].tag(lex[txt],'lexicon-four',world);terms[t+2].tag(lex[txt],'lexicon-four',world);terms[t+3].tag(lex[txt],'lexicon-four',world);return 3;}}
return 0;};var checkLexicon=function checkLexicon(terms,world){var lex=world.words;var hasCompound=world.hasCompound;for(var t=0;t<terms.length;t+=1){var str=terms[t].clean;if(hasCompound[str]===true&&t+1<terms.length){var foundWords=tryMultiple(terms,t,world);if(foundWords>0){t+=foundWords;continue;}}
if(lex[str]!==undefined&&lex.hasOwnProperty(str)===true){terms[t].tag(lex[str],'lexicon',world);continue;}
if(str!==terms[t].reduced&&lex.hasOwnProperty(terms[t].reduced)===true){terms[t].tag(lex[terms[t].reduced],'lexicon',world);continue;}
if(underOver.test(str)===true){var noPrefix=str.replace(underOver,'');if(lex.hasOwnProperty(noPrefix)===true){terms[t].tag(lex[noPrefix],'noprefix-lexicon',world);}}}
return terms;};var _01Lexicon=checkLexicon;var apostrophes=/[\'`´]$/;var perSec=/^(m|k|cm|km|m)\/(s|h|hr)$/;var checkPunctuation=function checkPunctuation(terms,i,world){var term=terms[i];if(apostrophes.test(term.text)){if(!apostrophes.test(term.pre)&&!apostrophes.test(term.post)&&term.clean.length>2){var endChar=term.clean[term.clean.length-2];if(endChar==='s'){term.tag(['Possessive','Noun'],'end-tick',world);return;}
if(endChar==='n'){term.tag(['Gerund'],'chillin',world);}}}
if(perSec.test(term.text)){term.tag('Unit','per-sec',world);}};var _02Punctuation$1=checkPunctuation;var startsWith=[[/^[\w\.]+@[\w\.]+\.[a-z]{2,3}$/,'Email'],[/^#[a-z0-9_\u00C0-\u00FF]{2,}$/,'HashTag'],[/^@\w{2,}$/,'AtMention'],[/^(https?:\/\/|www\.)\w+\.[a-z]{2,3}/,'Url'],[/^[\w./]+\.(com|net|gov|org|ly|edu|info|biz|ru|jp|de|in|uk|br)/,'Url'],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])$/,'Time'],[/^[012]?[0-9](:[0-5][0-9])?(:[0-5][0-9])? ?(am|pm)$/,'Time'],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])? ?(am|pm)?$/,'Time'],[/^[PMCE]ST$/,'Time'],[/^utc ?[+-]?[0-9]+?$/,'Time'],[/^[a-z0-9]*? o\'?clock$/,'Time'],[/^[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,4}$/,'Date'],[/^[0-9]{1,4}\/[0-9]{1,2}\/[0-9]{1,4}$/,'Date'],[/^[0-9]{1,4}-[a-z]{2,9}-[0-9]{1,4}$/i,'Date'],[/^ma?c\'.*/,'LastName'],[/^o\'[drlkn].*/,'LastName'],[/^ma?cd[aeiou]/,'LastName'],[/^(lol)+[sz]$/,'Expression'],[/^woo+a*?h?$/,'Expression'],[/^(un|de|re)\\-[a-z\u00C0-\u00FF]{2}/,'Verb'],[/^[0-9]{1,4}\.[0-9]{1,2}\.[0-9]{1,4}$/,'Date'],[/^[0-9]{3}-[0-9]{4}$/,'PhoneNumber'],[/^(\+?[0-9][ -])?[0-9]{3}[ -]?[0-9]{3}-[0-9]{4}$/,'PhoneNumber'],[/^[-+]?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6][-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(k|m|b|bn)?\+?$/,['Money','Value']],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\+?$/,['Money','Value']],[/^[-+]?[0-9]([0-9,.])+?(usd|eur|jpy|gbp|cad|aud|chf|cny|hkd|nzd|kr|rub)$/i,['Money','Value']],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?\+?$/,['Cardinal','NumericValue']],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(st|nd|rd|th)$/,['Ordinal','NumericValue']],[/^\.[0-9]+\+?$/,['Cardinal','NumericValue']],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?%\+?$/,['Percent','Cardinal','NumericValue']],[/^\.[0-9]+%$/,['Percent','Cardinal','NumericValue']],[/^[0-9]{1,4}\/[0-9]{1,4}$/,'Fraction'],[/^[0-9.]{1,2}[-][0-9]{1,2}$/,['Value','NumberRange']],[/^[0-9.]{1,4}(st|nd|rd|th)?[-][0-9\.]{1,4}(st|nd|rd|th)?$/,'NumberRange'],[/^[0-9.]+([a-z]{1,4})$/,'Value']];var romanNumeral=/^[IVXLCDM]{2,}$/;var romanNumValid=/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/;var checkRegex=function checkRegex(term,world){var str=term.text;for(var r=0;r<startsWith.length;r+=1){if(startsWith[r][0].test(str)===true){term.tagSafe(startsWith[r][1],'prefix #'+r,world);break;}}
if(term.text.length>=2&&romanNumeral.test(str)&&romanNumValid.test(str)){term.tag('RomanNumeral','xvii',world);}};var _03Prefixes=checkRegex;var Adj='Adjective';var Inf='Infinitive';var Pres='PresentTense';var Sing='Singular';var Past='PastTense';var Adverb='Adverb';var Exp='Expression';var Actor='Actor';var Verb='Verb';var Noun='Noun';var Last='LastName';var endsWith$1={a:[[/.[aeiou]na$/,Noun],[/.[oau][wvl]ska$/,Last],[/.[^aeiou]ica$/,Sing],[/^([hyj]a)+$/,Exp]],c:[[/.[^aeiou]ic$/,Adj]],d:[[/[aeiou](pp|ll|ss|ff|gg|tt|rr|bb|nn|mm)ed$/,Past],[/.[aeo]{2}[bdgmnprvz]ed$/,Past],[/.[aeiou][sg]hed$/,Past],[/.[aeiou]red$/,Past],[/.[aeiou]r?ried$/,Past],[/.[bcdgtr]led$/,Past],[/.[aoui]f?led$/,Past],[/.[iao]sed$/,Past],[/[aeiou]n?[cs]ed$/,Past],[/[aeiou][rl]?[mnf]ed$/,Past],[/[aeiou][ns]?c?ked$/,Past],[/[aeiou][nl]?ged$/,Past],[/.[tdbwxz]ed$/,Past],[/[^aeiou][aeiou][tvx]ed$/,Past],[/.[cdlmnprstv]ied$/,Past],[/[^aeiou]ard$/,Sing],[/[aeiou][^aeiou]id$/,Adj],[/.[vrl]id$/,Adj]],e:[[/.[lnr]ize$/,Inf],[/.[^aeiou]ise$/,Inf],[/.[aeiou]te$/,Inf],[/.[^aeiou][ai]ble$/,Adj],[/.[^aeiou]eable$/,Adj],[/.[ts]ive$/,Adj]],h:[[/.[^aeiouf]ish$/,Adj],[/.v[iy]ch$/,Last],[/^ug?h+$/,Exp],[/^uh[ -]?oh$/,Exp]],i:[[/.[oau][wvl]ski$/,Last]],k:[[/^(k){2}$/,Exp]],l:[[/.[gl]ial$/,Adj],[/.[^aeiou]ful$/,Adj],[/.[nrtumcd]al$/,Adj],[/.[^aeiou][ei]al$/,Adj]],m:[[/.[^aeiou]ium$/,Sing],[/[^aeiou]ism$/,Sing],[/^h*u*m+$/,Exp],[/^\d+ ?[ap]m$/,'Date']],n:[[/.[lsrnpb]ian$/,Adj],[/[^aeiou]ician$/,Actor],[/[aeiou][ktrp]in$/,'Gerund']],o:[[/^no+$/,Exp],[/^(yo)+$/,Exp],[/^woo+[pt]?$/,Exp]],r:[[/.[bdfklmst]ler$/,'Noun'],[/.[ilk]er$/,'Comparative'],[/[aeiou][pns]er$/,Sing],[/[^i]fer$/,Inf],[/.[^aeiou][ao]pher$/,Actor]],t:[[/.[di]est$/,'Superlative'],[/.[icldtgrv]ent$/,Adj],[/[aeiou].*ist$/,Adj],[/^[a-z]et$/,Verb]],s:[[/.[rln]ates$/,Pres],[/.[^z]ens$/,Verb],[/.[lstrn]us$/,Sing],[/.[aeiou]sks$/,Pres],[/.[aeiou]kes$/,Pres],[/[aeiou][^aeiou]is$/,Sing],[/[a-z]\'s$/,Noun],[/^yes+$/,Exp]],v:[[/.[^aeiou][ai][kln]ov$/,Last]],y:[[/.[cts]hy$/,Adj],[/.[st]ty$/,Adj],[/.[gk]y$/,Adj],[/.[tnl]ary$/,Adj],[/.[oe]ry$/,Sing],[/[rdntkbhs]ly$/,Adverb],[/...lly$/,Adverb],[/[bszmp]{2}y$/,Adj],[/.(gg|bb|zz)ly$/,Adj],[/.[aeiou]my$/,Adj],[/[ea]{2}zy$/,Adj],[/.[^aeiou]ity$/,Sing]]};var Adj$1='Adjective';var Inf$1='Infinitive';var Pres$1='PresentTense';var Sing$1='Singular';var Past$1='PastTense';var Avb='Adverb';var Plrl='Plural';var Actor$1='Actor';var Vb='Verb';var Noun$1='Noun';var Last$1='LastName';var Modal='Modal';var Place='Place';var suffixMap=[null,null,{ea:Sing$1,ia:Noun$1,ic:Adj$1,ly:Avb,"'n":Vb,"'t":Vb},{oed:Past$1,ued:Past$1,xed:Past$1,' so':Avb,"'ll":Modal,"'re":'Copula',azy:Adj$1,end:Vb,ped:Past$1,ffy:Adj$1,ify:Inf$1,ing:'Gerund',ize:Inf$1,lar:Adj$1,mum:Adj$1,nes:Pres$1,nny:Adj$1,oid:Adj$1,ous:Adj$1,que:Adj$1,rmy:Adj$1,rol:Sing$1,sis:Sing$1,zes:Pres$1},{amed:Past$1,aped:Past$1,ched:Past$1,lked:Past$1,nded:Past$1,cted:Past$1,dged:Past$1,akis:Last$1,cede:Inf$1,chuk:Last$1,czyk:Last$1,ects:Pres$1,ends:Vb,enko:Last$1,ette:Sing$1,fies:Pres$1,fore:Avb,gate:Inf$1,gone:Adj$1,ices:Plrl,ints:Plrl,ines:Plrl,ions:Plrl,less:Avb,llen:Adj$1,made:Adj$1,nsen:Last$1,oses:Pres$1,ould:Modal,some:Adj$1,sson:Last$1,tage:Inf$1,teen:'Value',tion:Sing$1,tive:Adj$1,tors:Noun$1,vice:Sing$1},{tized:Past$1,urned:Past$1,eased:Past$1,ances:Plrl,bound:Adj$1,ettes:Plrl,fully:Avb,ishes:Pres$1,ities:Plrl,marek:Last$1,nssen:Last$1,ology:Noun$1,ports:Plrl,rough:Adj$1,tches:Pres$1,tieth:'Ordinal',tures:Plrl,wards:Avb,where:Avb},{auskas:Last$1,keeper:Actor$1,logist:Actor$1,teenth:'Value'},{opoulos:Last$1,borough:Place,sdottir:Last$1}];var endRegexs=function endRegexs(term,world){var str=term.clean;var _char=str[str.length-1];if(endsWith$1.hasOwnProperty(_char)===true){var regs=endsWith$1[_char];for(var r=0;r<regs.length;r+=1){if(regs[r][0].test(str)===true){term.tagSafe(regs[r][1],"endReg ".concat(_char," #").concat(r),world);break;}}}};var knownSuffixes=function knownSuffixes(term,world){var len=term.clean.length;var max=7;if(len<=max){max=len-1;}
for(var i=max;i>1;i-=1){var str=term.clean.substr(len-i,len);if(suffixMap[str.length].hasOwnProperty(str)===true){var tag=suffixMap[str.length][str];term.tagSafe(tag,'suffix -'+str,world);break;}}};var checkRegex$1=function checkRegex(term,world){knownSuffixes(term,world);endRegexs(term,world);};var _04Suffixes=checkRegex$1;var emoticons={':(':true,':)':true,':P':true,':p':true,':O':true,':3':true,':|':true,':/':true,':\\':true,':$':true,':*':true,':@':true,':-(':true,':-)':true,':-P':true,':-p':true,':-O':true,':-3':true,':-|':true,':-/':true,':-\\':true,':-$':true,':-*':true,':-@':true,':^(':true,':^)':true,':^P':true,':^p':true,':^O':true,':^3':true,':^|':true,':^/':true,':^\\':true,':^$':true,':^*':true,':^@':true,'):':true,'(:':true,'$:':true,'*:':true,')-:':true,'(-:':true,'$-:':true,'*-:':true,')^:':true,'(^:':true,'$^:':true,'*^:':true,'<3':true,'</3':true,'<\\3':true};var emojiReg=/^(\u00a9|\u00ae|[\u2319-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/;var isCommaEmoji=function isCommaEmoji(raw){if(raw.charAt(0)===':'){if(raw.match(/:.?$/)===null){return false;}
if(raw.match(' ')){return false;}
if(raw.length>35){return false;}
return true;}
return false;};var isEmoticon=function isEmoticon(str){str=str.replace(/^[:;]/,':');return emoticons.hasOwnProperty(str);};var tagEmoji=function tagEmoji(term,world){var raw=term.pre+term.text+term.post;raw=raw.trim();raw=raw.replace(/[.!?,]$/,'');if(isCommaEmoji(raw)===true){term.tag('Emoji','comma-emoji',world);term.text=raw;term.pre=term.pre.replace(':','');term.post=term.post.replace(':','');}
if(term.text.match(emojiReg)){term.tag('Emoji','unicode-emoji',world);term.text=raw;}
if(isEmoticon(raw)===true){term.tag('Emoticon','emoticon-emoji',world);term.text=raw;}};var _05Emoji=tagEmoji;var steps={lexicon:_01Lexicon,punctuation:_02Punctuation$1,regex:_03Prefixes,suffix:_04Suffixes,emoji:_05Emoji};var lookups=function lookups(doc,terms){var world=doc.world;steps.lexicon(terms,world);for(var i=0;i<terms.length;i+=1){var term=terms[i];steps.punctuation(terms,i,world);steps.regex(term,world);steps.suffix(term,world);steps.emoji(term,world);}
return doc;};var _01Init=lookups;var afterThisWord={i:'Verb',first:'Noun',it:'Verb',there:'Verb',not:'Verb',because:'Noun',"if":'Noun',but:'Noun',who:'Verb',"this":'Noun',his:'Noun',when:'Noun',you:'Verb',very:'Adjective',old:'Noun',never:'Verb',before:'Noun'};var beforeThisWord={there:'Verb',me:'Verb',man:'Adjective',only:'Verb',him:'Verb',were:'Noun',took:'Noun',himself:'Verb',went:'Noun',who:'Noun',jr:'Person'};var afterThisPOS={Adjective:'Noun',Possessive:'Noun',Determiner:'Noun',Adverb:'Verb',Pronoun:'Verb',Value:'Noun',Ordinal:'Noun',Modal:'Verb',Superlative:'Noun',Demonym:'Noun',Honorific:'Person'};var beforeThisPOS={Copula:'Noun',PastTense:'Noun',Conjunction:'Noun',Modal:'Noun',Pluperfect:'Noun',PerfectTense:'Verb'};var markov={beforeThisWord:beforeThisWord,afterThisWord:afterThisWord,beforeThisPos:beforeThisPOS,afterThisPos:afterThisPOS};var afterKeys=Object.keys(markov.afterThisPos);var beforeKeys=Object.keys(markov.beforeThisPos);var checkNeighbours=function checkNeighbours(terms,world){var _loop=function _loop(i){var term=terms[i];if(term.isKnown()===true){return"continue";}
var lastTerm=terms[i-1];if(lastTerm){if(markov.afterThisWord.hasOwnProperty(lastTerm.clean)===true){var tag=markov.afterThisWord[lastTerm.clean];term.tag(tag,'after-'+lastTerm.clean,world);return"continue";}
var foundTag=afterKeys.find(function(tag){return lastTerm.tags[tag];});if(foundTag!==undefined){var _tag=markov.afterThisPos[foundTag];term.tag(_tag,'after-'+foundTag,world);return"continue";}}
var nextTerm=terms[i+1];if(nextTerm){if(markov.beforeThisWord.hasOwnProperty(nextTerm.clean)===true){var _tag2=markov.beforeThisWord[nextTerm.clean];term.tag(_tag2,'before-'+nextTerm.clean,world);return"continue";}
var _foundTag=beforeKeys.find(function(tag){return nextTerm.tags[tag];});if(_foundTag!==undefined){var _tag3=markov.beforeThisPos[_foundTag];term.tag(_tag3,'before-'+_foundTag,world);return"continue";}}};for(var i=0;i<terms.length;i+=1){var _ret=_loop(i);if(_ret==="continue")continue;}};var _01Neighbours=checkNeighbours;var titleCase$4=/^[A-Z][a-z'\u00C0-\u00FF]/;var hasNumber=/[0-9]/;var checkCase=function checkCase(doc){var world=doc.world;doc.list.forEach(function(p){var terms=p.terms();for(var i=1;i<terms.length;i++){var term=terms[i];if(titleCase$4.test(term.text)===true&&hasNumber.test(term.text)===false){term.tag('ProperNoun','titlecase-noun',world);}}});};var _02Case=checkCase;var hasPrefix=/^(re|un)-?[a-z\u00C0-\u00FF]/;var prefix=/^(re|un)-?/;var checkPrefix=function checkPrefix(terms,world){var lex=world.words;terms.forEach(function(term){if(term.isKnown()===true){return;}
if(hasPrefix.test(term.clean)===true){var stem=term.clean.replace(prefix,'');if(stem&&stem.length>3&&lex[stem]!==undefined&&lex.hasOwnProperty(stem)===true){term.tag(lex[stem],'stem-'+stem,world);}}});};var _03Stem=checkPrefix;var isPlural=[/(^v)ies$/i,/ises$/i,/ives$/i,/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/(buffal|tomat|tornad)oes$/i,/(analy|ba|diagno|parenthe|progno|synop|the)ses$/i,/(vert|ind|cort)ices$/i,/(matr|append)ices$/i,/(x|ch|ss|sh|s|z|o)es$/i,/is$/i,/men$/i,/news$/i,/.tia$/i,/(^f)ves$/i,/(lr)ves$/i,/(^aeiouy|qu)ies$/i,/(m|l)ice$/i,/(cris|ax|test)es$/i,/(alias|status)es$/i,/ics$/i];var isSingular=[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/s[aeiou]+ns$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i];var isPlural_1={isSingular:isSingular,isPlural:isPlural};var noPlurals=['Uncountable','Pronoun','Place','Value','Person','Month','WeekDay','Holiday'];var notPlural=[/ss$/,/sis$/,/[^aeiou][uo]s$/,/'s$/];var notSingular=[/i$/,/ae$/];var checkPlural=function checkPlural(t,world){if(t.tags.Noun&&!t.tags.Acronym){var str=t.clean;if(t.tags.Singular||t.tags.Plural){return;}
if(str.length<=3){t.tag('Singular','short-singular',world);return;}
if(noPlurals.find(function(tag){return t.tags[tag];})){return;}
if(isPlural_1.isPlural.find(function(reg){return reg.test(str);})){t.tag('Plural','plural-rules',world);return;}
if(isPlural_1.isSingular.find(function(reg){return reg.test(str);})){t.tag('Singular','singular-rules',world);return;}
if(/s$/.test(str)===true){if(notPlural.find(function(reg){return reg.test(str);})){return;}
t.tag('Plural','plural-fallback',world);return;}
if(notSingular.find(function(reg){return reg.test(str);})){return;}
t.tag('Singular','singular-fallback',world);}};var _04Plurals=checkPlural;var orgWords=['academy','administration','agence','agences','agencies','agency','airlines','airways','army','assoc','associates','association','assurance','authority','autorite','aviation','bank','banque','board','boys','brands','brewery','brotherhood','brothers','building society','bureau','cafe','caisse','capital','care','cathedral','center','central bank','centre','chemicals','choir','chronicle','church','circus','clinic','clinique','club','co','coalition','coffee','collective','college','commission','committee','communications','community','company','comprehensive','computers','confederation','conference','conseil','consulting','containers','corporation','corps','corp','council','crew','daily news','data','departement','department','department store','departments','design','development','directorate','division','drilling','education','eglise','electric','electricity','energy','ensemble','enterprise','enterprises','entertainment','estate','etat','evening news','faculty','federation','financial','fm','foundation','fund','gas','gazette','girls','government','group','guild','health authority','herald','holdings','hospital','hotel','hotels','inc','industries','institut','institute','institute of technology','institutes','insurance','international','interstate','investment','investments','investors','journal','laboratory','labs','liberation army','limited','local authority','local health authority','machines','magazine','management','marine','marketing','markets','media','memorial','mercantile exchange','ministere','ministry','military','mobile','motor','motors','musee','museum','news','news service','observatory','office','oil','optical','orchestra','organization','partners','partnership',"people's party",'petrol','petroleum','pharmacare','pharmaceutical','pharmaceuticals','pizza','plc','police','polytechnic','post','power','press','productions','quartet','radio','regional authority','regional health authority','reserve','resources','restaurant','restaurants','savings','school','securities','service','services','social club','societe','society','sons','standard','state police','state university','stock exchange','subcommittee','syndicat','systems','telecommunications','telegraph','television','times','tribunal','tv','union','university','utilities','workers'];var organizations=orgWords.reduce(function(h,str){h[str]='Noun';return h;},{});var maybeOrg=function maybeOrg(t){if(!t.tags.Noun){return false;}
if(t.tags.Pronoun||t.tags.Comma||t.tags.Possessive){return false;}
if(t.tags.Organization||t.tags.Acronym||t.tags.Place||t.titleCase()){return true;}
return false;};var tagOrgs=function tagOrgs(terms,world){for(var i=0;i<terms.length;i+=1){var t=terms[i];if(organizations[t.clean]!==undefined&&organizations.hasOwnProperty(t.clean)===true){var lastTerm=terms[i-1];if(lastTerm!==undefined&&maybeOrg(lastTerm)===true){lastTerm.tagSafe('Organization','org-word-1',world);t.tagSafe('Organization','org-word-2',world);continue;}
var nextTerm=terms[i+1];if(nextTerm!==undefined&&nextTerm.clean==='of'){if(terms[i+2]&&maybeOrg(terms[i+2])){t.tagSafe('Organization','org-of-word-1',world);nextTerm.tagSafe('Organization','org-of-word-2',world);terms[i+2].tagSafe('Organization','org-of-word-3',world);continue;}}}}};var _05Organizations=tagOrgs;var oneLetterAcronym$1=/^[A-Z]('s|,)?$/;var periodSeperated=/([A-Z]\.){2}[A-Z]?/i;var oneLetterWord={I:true,A:true};var isAcronym$2=function isAcronym(term,world){var str=term.reduced;if(term.tags.Acronym){return true;}
if(world.words[str]){return false;}
return term.isAcronym();};var checkAcronym=function checkAcronym(terms,world){terms.forEach(function(term){if(term.tags.RomanNumeral===true){return;}
if(periodSeperated.test(term.text)===true){term.tag('Acronym','period-acronym',world);}
if(term.isUpperCase()&&isAcronym$2(term,world)){term.tag('Acronym','acronym-step',world);term.tag('Noun','acronym-infer',world);}else if(!oneLetterWord.hasOwnProperty(term.text)&&oneLetterAcronym$1.test(term.text)){term.tag('Acronym','one-letter-acronym',world);term.tag('Noun','one-letter-infer',world);}
if(term.tags.Organization&&term.text.length<=3){term.tag('Acronym','acronym-org',world);}
if(term.tags.Organization&&term.isUpperCase()&&term.text.length<=6){term.tag('Acronym','acronym-org-case',world);}});};var _06Acronyms=checkAcronym;var step={neighbours:_01Neighbours,"case":_02Case,stem:_03Stem,plural:_04Plurals,organizations:_05Organizations,acronyms:_06Acronyms};var fallbacks=function fallbacks(doc,terms){var world=doc.world;step.neighbours(terms,world);step["case"](doc);step.stem(terms,world);terms.forEach(function(t){if(t.isKnown()===false){t.tag('Noun','noun-fallback',doc.world);}});step.organizations(terms,world);step.acronyms(terms,world);terms.forEach(function(t){step.plural(t,doc.world);});return doc;};var _02Fallbacks=fallbacks;var hasNegative=/n't$/;var irregulars$3={"won't":['will','not'],wont:['will','not'],"can't":['can','not'],cant:['can','not'],cannot:['can','not'],"shan't":['should','not'],dont:['do','not'],dun:['do','not']};var doAint=function doAint(term,phrase){var terms=phrase.terms();var index=terms.indexOf(term);var before=terms.slice(0,index);var noun=before.find(function(t){return t.tags.Noun;});if(noun&&noun.tags.Plural){return['are','not'];}
return['is','not'];};var checkNegative=function checkNegative(term,phrase){if(irregulars$3.hasOwnProperty(term.clean)===true){return irregulars$3[term.clean];}
if(term.clean==="ain't"||term.clean==='aint'){return doAint(term,phrase);}
if(hasNegative.test(term.clean)===true){var main=term.clean.replace(hasNegative,'');return[main,'not'];}
return null;};var _01Negative=checkNegative;var contraction=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z]{1,2})$/i;var easy={ll:'will',ve:'have',re:'are',m:'am',"n't":'not'};var checkApostrophe=function checkApostrophe(term){var parts=term.text.match(contraction);if(parts===null){return null;}
if(easy.hasOwnProperty(parts[2])){return[parts[1],easy[parts[2]]];}
return null;};var _02Simple=checkApostrophe;var irregulars$4={wanna:['want','to'],gonna:['going','to'],im:['i','am'],alot:['a','lot'],ive:['i','have'],imma:['I','will'],"where'd":['where','did'],whered:['where','did'],"when'd":['when','did'],whend:['when','did'],howd:['how','did'],whatd:['what','did'],dunno:['do','not','know'],brb:['be','right','back'],gtg:['got','to','go'],irl:['in','real','life'],tbh:['to','be','honest'],imo:['in','my','opinion'],til:['today','i','learned'],rn:['right','now'],twas:['it','was'],'@':['at']};var checkIrregulars=function checkIrregulars(term){if(irregulars$4.hasOwnProperty(term.clean)){return irregulars$4[term.clean];}
return null;};var _03Irregulars=checkIrregulars;var hasApostropheS=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]s$/i;var banList={that:true,there:true};var isPossessive=function isPossessive(term,pool){if(term.tags.Possessive){return true;}
if(term.tags.Pronoun||term.tags.QuestionWord){return false;}
if(banList.hasOwnProperty(term.reduced)){return false;}
var nextTerm=pool.get(term.next);if(!nextTerm){return true;}
if(nextTerm.tags.Verb){if(nextTerm.tags.Infinitive){return true;}
if(nextTerm.tags.PresentTense){return true;}
return false;}
if(nextTerm.tags.Noun){return true;}
var twoTerm=pool.get(nextTerm.next);if(twoTerm&&twoTerm.tags.Noun&&!twoTerm.tags.Pronoun){return true;}
if(nextTerm.tags.Adjective||nextTerm.tags.Adverb||nextTerm.tags.Verb){return false;}
return false;};var isHas=function isHas(term,phrase){var terms=phrase.terms();var index=terms.indexOf(term);var after=terms.slice(index+1,index+3);return after.find(function(t){return t.tags.PastTense;});};var checkPossessive=function checkPossessive(term,phrase,world){var found=term.text.match(hasApostropheS);if(found!==null){if(isPossessive(term,phrase.pool)===true){term.tag('#Possessive','isPossessive',world);return null;}
if(found!==null){if(isHas(term,phrase)){return[found[1],'has'];}
return[found[1],'is'];}}
return null;};var _04Possessive=checkPossessive;var hasPerfect=/[a-z\u00C0-\u00FF]'d$/;var useDid={how:true,what:true};var checkPerfect=function checkPerfect(term,phrase){if(hasPerfect.test(term.clean)){var root=term.clean.replace(/'d$/,'');var terms=phrase.terms();var index=terms.indexOf(term);var after=terms.slice(index+1,index+4);for(var i=0;i<after.length;i++){var t=after[i];if(t.tags.Verb){if(t.tags.PastTense){return[root,'had'];}
if(useDid[root]===true){return[root,'did'];}
return[root,'would'];}}
return[root,'would'];}
return null;};var _05PerfectTense=checkPerfect;var isRange=/^([0-9]+)[-–—]([0-9]+)$/i;var checkRange=function checkRange(term){if(term.tags.PhoneNumber===true){return null;}
var parts=term.text.match(isRange);if(parts!==null){return[parts[1],'to',parts[2]];}
return null;};var _06Ranges=checkRange;var contraction$1=/^(l|c|d|j|m|n|qu|s|t)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z\u00C0-\u00FF]+)$/i;var french={l:'le',c:'ce',d:'de',j:'je',m:'me',n:'ne',qu:'que',s:'se',t:'tu'};var checkFrench=function checkFrench(term){var parts=term.text.match(contraction$1);if(parts===null||french.hasOwnProperty(parts[1])===false){return null;}
var arr=[french[parts[1]],parts[2]];if(arr[0]&&arr[1]){return arr;}
return null;};var _07French=checkFrench;var isNumber=/^[0-9]+$/;var createPhrase=function createPhrase(found,doc){var phrase=_01Tokenizer(found.join(' '),doc.world,doc.pool())[0];var terms=phrase.terms();_01Lexicon(terms,doc.world);terms.forEach(function(t){t.implicit=t.text;t.text='';t.clean='';t.pre='';t.post='';if(isNumber.test(t.implicit)){t.tags.Number=true;t.tags.Cardinal=true;}});return phrase;};var contractions=function contractions(doc){var world=doc.world;doc.list.forEach(function(p){var terms=p.terms();for(var i=0;i<terms.length;i+=1){var term=terms[i];var found=_01Negative(term,p);found=found||_02Simple(term);found=found||_03Irregulars(term);found=found||_04Possessive(term,p,world);found=found||_05PerfectTense(term,p);found=found||_06Ranges(term);found=found||_07French(term);if(found!==null){var newPhrase=createPhrase(found,doc);if(p.has('#NumberRange')===true){doc.buildFrom([newPhrase]).tag('NumberRange');}
var firstTerm=newPhrase.terms(0);firstTerm.text=term.text;var match=p.buildFrom(term.id,1,doc.pool());match.replace(newPhrase,doc,true);}}});return doc;};var _03Contractions=contractions;var hasWord=function hasWord(doc,word){var arr=doc._cache.words[word]||[];arr=arr.map(function(i){return doc.list[i];});return doc.buildFrom(arr);};var hasTag=function hasTag(doc,tag){var arr=doc._cache.tags[tag]||[];arr=arr.map(function(i){return doc.list[i];});return doc.buildFrom(arr);};var miscCorrection=function miscCorrection(doc){var m=hasWord(doc,'like');m.match('#Adverb like').notIf('(really|generally|typically|usually|sometimes|often) [like]').tag('Adverb','adverb-like');m=hasTag(doc,'Adjective');m.match('#Determiner #Adjective$').notIf('(#Comparative|#Superlative)').terms(1).tag('Noun','the-adj-1');m=hasTag(doc,'FirstName');m.match('#FirstName (#Noun|@titleCase)').ifNo('^#Possessive').ifNo('#Pronoun').ifNo('@hasComma .').lastTerm().tag('#LastName','firstname-noun');m=hasTag(doc,'Value');m=m.match('#Value #PresentTense');if(m.found){if(m.has('(one|1)')===true){m.terms(1).tag('Singular','one-presentTense');}else{m.terms(1).tag('Plural','value-presentTense');}}
doc.match('^(well|so|okay)').tag('Expression','well-');m=hasTag(doc,'Gerund');m.match("(be|been) (#Adverb|not)+? #Gerund").not('#Verb$').tag('Auxiliary','be-walking');doc.match('(try|use|attempt|build|make) #Verb').ifNo('(@hasComma|#Negative|#Copula|will|be)').lastTerm().tag('#Noun','do-verb');m=hasTag(doc,'Possessive');m=m.match('#Possessive [#Infinitive]',0);if(!m.lookBehind('(let|made|make|force|ask)').found){m.tag('Noun','her-match');}
return doc;};var fixMisc=miscCorrection;var unique$5=function unique(arr){var obj={};for(var i=0;i<arr.length;i++){obj[arr[i]]=true;}
return Object.keys(obj);};var _unique=unique$5;var list=[{match:'too much',tag:'Adverb Adjective',reason:'bit-4'},{match:'u r',tag:'Pronoun Copula',reason:'u r'},{match:'#Copula (pretty|dead|full|well) (#Adjective|#Noun)',tag:'#Copula #Adverb #Adjective',reason:'sometimes-adverb'},{match:'[#Gerund] #Adverb? not? #Copula',group:0,tag:'Activity',reason:'gerund-copula'},{match:'[#Gerund] #Modal',group:0,tag:'Activity',reason:'gerund-modal'},{match:'holy (shit|fuck|hell)',tag:'Expression',reason:'swears-expression'},{match:'#Noun #Actor',tag:'Actor',reason:'thing-doer'},{match:'#Conjunction [u]',group:0,tag:'Pronoun',reason:'u-pronoun-2'},{match:'[u] #Verb',group:0,tag:'Pronoun',reason:'u-pronoun-1'},{match:'#Noun [(who|whom)]',group:0,tag:'Determiner',reason:'captain-who'},{match:'that #Noun [#Verb]',group:0,tag:'Determiner',reason:'that-determiner'},{match:'a bit much',tag:'Determiner Adverb Adjective',reason:'bit-3'},{match:'#Verb #Adverb? #Noun [(that|which)]',group:0,tag:'Preposition',reason:'that-prep'},{match:'@hasComma [which] (#Pronoun|#Verb)',group:0,tag:'Preposition',reason:'which-copula'},{match:'just [like]',group:0,tag:'Preposition',reason:'like-preposition'},{match:'#Noun [like] #Noun',group:0,tag:'Preposition',reason:'noun-like'},{match:'#Noun [#Particle]',group:0,tag:'Preposition',reason:'repair-noPhrasal'},{match:'[had] #Noun+ #PastTense',group:0,tag:'Condition',reason:'had-he'},{match:'[were] #Noun+ to #Infinitive',group:0,tag:'Condition',reason:'were-he'},{match:'^how',tag:'QuestionWord',reason:'how-question'},{match:'[how] (#Determiner|#Copula|#Modal|#PastTense)',group:0,tag:'QuestionWord',reason:'how-is'},{match:'^which',tag:'QuestionWord',reason:'which-question'},{match:'[which] . (#Noun)+ #Pronoun',group:0,tag:'QuestionWord',reason:'which-question2'},{match:'[so] #Noun',group:0,tag:'Conjunction',reason:'so-conj'},{match:'[(who|what|where|why|how|when)] #Noun #Copula #Adverb? (#Verb|#Adjective)',group:0,tag:'Conjunction',reason:'how-he-is-x'},{match:'[(who|what|where|why|how|when)] #Noun #Adverb? #Infinitive not? #Gerund',group:0,tag:'Conjunction',reason:'when i go fishing'},{match:'^[(who|what|where|why|how|when)] #Adjective? #Verb #Pronoun',group:0,tag:'Adverb',reason:'where-question'},{match:'the way',tag:'Noun',reason:'fix-1'},];var _01Misc=list;var dates='(april|june|may|jan|august|eve)';var list$1=[{match:'#Holiday (day|eve)',tag:'Holiday',reason:'holiday-day'},{match:'[sun] the #Ordinal',tag:'WeekDay',reason:'sun-the-5th'},{match:'[sun] #Date',group:0,tag:'WeekDay',reason:'sun-feb'},{match:'#Date (on|this|next|last|during)? [sun]',group:0,tag:'WeekDay',reason:'1pm-sun'},{match:"(in|by|before|during|on|until|after|of|within|all) [sat]",group:0,tag:'WeekDay',reason:'sat'},{match:'[sat] #Date',group:0,tag:'WeekDay',reason:'sat-feb'},{match:"#Preposition [(march|may)]",group:0,tag:'Month',reason:'in-month'},{match:"this [(march|may)]",group:0,tag:'Month',reason:'this-month'},{match:"next [(march|may)]",group:0,tag:'Month',reason:'this-month'},{match:"last [(march|may)]",group:0,tag:'Month',reason:'this-month'},{match:"[(march|may)] the? #Value",group:0,tag:'Month',reason:'march-5th'},{match:"#Value of? [(march|may)]",group:0,tag:'Month',reason:'5th-of-march'},{match:"[(march|may)] .? #Date",group:0,tag:'Month',reason:'march-and-feb'},{match:"#Date .? [(march|may)]",group:0,tag:'Month',reason:'feb-and-march'},{match:"#Adverb [(march|may)]",group:0,tag:'Verb',reason:'quickly-march'},{match:"[(march|may)] #Adverb",group:0,tag:'Verb',reason:'march-quickly'},{match:'#Value of #Month',tag:'Date',reason:'value-of-month'},{match:'#Cardinal #Month',tag:'Date',reason:'cardinal-month'},{match:'#Month #Value to #Value',tag:'Date',reason:'value-to-value'},{match:'#Month the #Value',tag:'Date',reason:'month-the-value'},{match:'(#WeekDay|#Month) #Value',tag:'Date',reason:'date-value'},{match:'#Value (#WeekDay|#Month)',tag:'Date',reason:'value-date'},{match:'(#TextValue && #Date) #TextValue',tag:'Date',reason:'textvalue-date'},{match:"in [".concat(dates,"]"),group:0,tag:'Date',reason:'in-june'},{match:"during [".c
if(obj.tag!==undefined){needTags.push(obj.tag);}
if(obj.word!==undefined){needWords.push(obj.word);}});return{tags:_unique(needTags),words:_unique(needWords)};};var allLists=function allLists(m){var more=[];var lists=m.reg.filter(function(r){return r.oneOf!==undefined;});if(lists.length===1){var i=m.reg.findIndex(function(r){return r.oneOf!==undefined;});Object.keys(m.reg[i].oneOf).forEach(function(w){var newM=Object.assign({},m);newM.reg=newM.reg.slice(0);newM.reg[i]=Object.assign({},newM.reg[i]);newM.reg[i].word=w;delete newM.reg[i].operator;delete newM.reg[i].oneOf;newM.reason+='-'+w;more.push(newM);});}
return more;};var all=[];matches.forEach(function(m){m.reg=syntax_1(m.match);var enumerated=allLists(m);if(enumerated.length>0){all=all.concat(enumerated);}else{all.push(m);}});all.forEach(function(m){m.required=cacheRequired$1(m.reg);return m;});var matches_1=all;var hasEvery=function hasEvery(chances){if(chances.length===0){return[];}
var obj={};chances.forEach(function(arr){arr=_unique(arr);for(var i=0;i<arr.length;i++){obj[arr[i]]=obj[arr[i]]||0;obj[arr[i]]+=1;}});var res=Object.keys(obj);res=res.filter(function(k){return obj[k]===chances.length;});res=res.map(function(num){return Number(num);});return res;};var runner=function runner(doc){matches_1.forEach(function(m){var allChances=[];m.required.words.forEach(function(w){allChances.push(doc._cache.words[w]||[]);});m.required.tags.forEach(function(tag){allChances.push(doc._cache.tags[tag]||[]);});var worthIt=hasEvery(allChances);if(worthIt.length===0){return;}
var phrases=worthIt.map(function(index){return doc.list[index];});var tryDoc=doc.buildFrom(phrases);var match=tryDoc.match(m.reg,m.group);if(match.found){if(m.safe===true){match.tagSafe(m.tag,m.reason);}else{match.tag(m.tag,m.reason);}}});};var runner_1=runner;var corrections=function corrections(doc){runner_1(doc);fixMisc(doc);return doc;};var _04Correction=corrections;var tagger=function tagger(doc){var terms=doc.termList();doc=_01Init(doc,terms);doc=_02Fallbacks(doc,terms);doc=_03Contractions(doc);doc.cache();doc=_04Correction(doc);doc.uncache();doc.world.taggers.forEach(function(fn){fn(doc);});return doc;};var _02Tagger=tagger;var addMethod=function addMethod(Doc){var Abbreviations=function(_Doc){_inherits(Abbreviations,_Doc);var _super=_createSuper(Abbreviations);function Abbreviations(){_classCallCheck(this,Abbreviations);return _super.apply(this,arguments);}
_createClass(Abbreviations,[{key:"stripPeriods",value:function stripPeriods(){this.termList().forEach(function(t){if(t.tags.Abbreviation===true&&t.next){t.post=t.post.replace(/^\./,'');}
var str=t.text.replace(/\./,'');t.set(str);});return this;}},{key:"addPeriods",value:function addPeriods(){this.termList().forEach(function(t){t.post=t.post.replace(/^\./,'');t.post='.'+t.post;});return this;}}]);return Abbreviations;}(Doc);Abbreviations.prototype.unwrap=Abbreviations.prototype.stripPeriods;Doc.prototype.abbreviations=function(n){var match=this.match('#Abbreviation');if(typeof n==='number'){match=match.get(n);}
return new Abbreviations(match.list,this,this.world);};return Doc;};var Abbreviations=addMethod;var hasPeriod=/\./;var addMethod$1=function addMethod(Doc){var Acronyms=function(_Doc){_inherits(Acronyms,_Doc);var _super=_createSuper(Acronyms);function Acronyms(){_classCallCheck(this,Acronyms);return _super.apply(this,arguments);}
_createClass(Acronyms,[{key:"stripPeriods",value:function stripPeriods(){this.termList().forEach(function(t){var str=t.text.replace(/\./g,'');t.set(str);});return this;}},{key:"addPeriods",value:function addPeriods(){this.termList().forEach(function(t){var str=t.text.replace(/\./g,'');str=str.split('').join('.');if(hasPeriod.test(t.post)===false){str+='.';}
t.set(str);});return this;}}]);return Acronyms;}(Doc);Acronyms.prototype.unwrap=Acronyms.prototype.stripPeriods;Acronyms.prototype.strip=Acronyms.prototype.stripPeriods;Doc.prototype.acronyms=function(n){var match=this.match('#Acronym');if(typeof n==='number'){match=match.get(n);}
return new Acronyms(match.list,this,this.world);};return Doc;};var Acronyms=addMethod$1;var addMethod$2=function addMethod(Doc){Doc.prototype.clauses=function(n){var commas=this["if"]('@hasComma').notIf('@hasComma @hasComma').notIf('@hasComma . .? (and|or) .').notIf('(#City && @hasComma) #Country').notIf('(#Date && @hasComma) #Year').notIf('@hasComma (too|also)$').match('@hasComma');var found=this.splitAfter(commas);var quotes=found.quotations();found=found.splitOn(quotes);var parentheses=found.parentheses();found=found.splitOn(parentheses);var conjunctions=found["if"]('#Copula #Adjective #Conjunction (#Pronoun|#Determiner) #Verb').match('#Conjunction');found=found.splitBefore(conjunctions);var condition=found["if"]('if .{2,9} then .').match('then');found=found.splitBefore(condition);found=found.splitBefore('as well as .');found=found.splitBefore('such as .');found=found.splitBefore('in addition to .');found=found.splitAfter('@hasSemicolon');found=found.splitAfter('@hasDash');var tooLong=found.filter(function(d){return d.wordCount()>5&&d.match('#Verb+').length>=2;});if(tooLong.found){var m=tooLong.splitAfter('#Noun .* #Verb .* #Noun+');found=found.splitOn(m.eq(0));}
if(typeof n==='number'){found=found.get(n);}
return new Doc(found.list,this,this.world);};return Doc;};var Clauses=addMethod$2;var addMethod$3=function addMethod(Doc){var Contractions=function(_Doc){_inherits(Contractions,_Doc);var _super=_createSuper(Contractions);function Contractions(list,from,world){var _this;_classCallCheck(this,Contractions);_this=_super.call(this,list,from,world);_this.contracted=null;return _this;}
_createClass(Contractions,[{key:"expand",value:function expand(){this.list.forEach(function(p){var terms=p.terms();var isTitlecase=terms[0].isTitleCase();terms.forEach(function(t,i){t.set(t.implicit||t.text);t.implicit=undefined;if(i<terms.length-1&&t.post===''){t.post+=' ';}});if(isTitlecase){terms[0].toTitleCase();}});return this;}}]);return Contractions;}(Doc);Doc.prototype.contractions=function(n){var found=this.match('@hasContraction+');if(typeof n==='number'){found=found.get(n);}
return new Contractions(found.list,this,this.world);};Doc.prototype.expanded=Doc.prototype.isExpanded;Doc.prototype.contracted=Doc.prototype.isContracted;return Doc;};var Contractions=addMethod$3;var addMethod$4=function addMethod(Doc){var parse=function parse(doc){var things=doc.splitAfter('@hasComma').splitOn('(and|or) not?').not('(and|or) not?');var beforeLast=doc.match('[.] (and|or)',0);return{things:things,conjunction:doc.match('(and|or) not?'),beforeLast:beforeLast,hasOxford:beforeLast.has('@hasComma')};};var Lists=function(_Doc){_inherits(Lists,_Doc);var _super=_createSuper(Lists);function Lists(){_classCallCheck(this,Lists);return _super.apply(this,arguments);}
_createClass(Lists,[{key:"conjunctions",value:function conjunctions(){return this.match('(and|or)');}},{key:"parts",value:function parts(){return this.splitAfter('@hasComma').splitOn('(and|or) not?');}},{key:"items",value:function items(){return parse(this).things;}},{key:"add",value:function add(str){this.forEach(function(p){var beforeLast=parse(p).beforeLast;beforeLast.append(str);beforeLast.termList(0).addPunctuation(',');});return this;}},{key:"remove",value:function remove(match){return this.items()["if"](match).remove();}},{key:"hasOxfordComma",value:function hasOxfordComma(){return this.filter(function(doc){return parse(doc).hasOxford;});}},{key:"addOxfordComma",value:function addOxfordComma(){var items=this.items();var needsComma=items.eq(items.length-2);if(needsComma.found&&needsComma.has('@hasComma')===false){needsComma.post(', ');}
return this;}},{key:"removeOxfordComma",value:function removeOxfordComma(){var items=this.items();var needsComma=items.eq(items.length-2);if(needsComma.found&&needsComma.has('@hasComma')===true){needsComma.post(' ');}
return this;}}]);return Lists;}(Doc);Lists.prototype.things=Lists.prototype.items;Doc.prototype.lists=function(n){var m=this["if"]('@hasComma+ .? (and|or) not? .');var nounList=m.match('(#Noun|#Adjective|#Determiner|#Article)+ #Conjunction not? (#Article|#Determiner)? #Adjective? #Noun+')["if"]('#Noun');var adjList=m.match('(#Adjective|#Adverb)+ #Conjunction not? #Adverb? #Adjective+');var verbList=m.match('(#Verb|#Adverb)+ #Conjunction not? #Adverb? #Verb+');var result=nounList.concat(adjList);result=result.concat(verbList);result=result["if"]('@hasComma');if(typeof n==='number'){result=m.get(n);}
return new Lists(result.list,this,this.world);};return Doc;};var Lists=addMethod$4;var noPlural='(#Pronoun|#Place|#Value|#Person|#Uncountable|#Month|#WeekDay|#Holiday|#Possessive)';var hasPlural=function hasPlural(doc){if(doc.has('#Plural')===true){return true;}
if(doc.has(noPlural)===true){return false;}
return true;};var hasPlural_1=hasPlural;var irregulars$5={hour:'an',heir:'an',heirloom:'an',honest:'an',honour:'an',honor:'an',uber:'an'};var an_acronyms={a:true,e:true,f:true,h:true,i:true,l:true,m:true,n:true,o:true,r:true,s:true,x:true};var a_regexs=[/^onc?e/i,/^u[bcfhjkqrstn][aeiou]/i,/^eul/i];var makeArticle=function makeArticle(doc){if(doc.has('#Person')||doc.has('#Place')){return'';}
if(doc.has('#Plural')){return'the';}
var str=doc.text('normal').trim();if(irregulars$5.hasOwnProperty(str)){return irregulars$5[str];}
var firstLetter=str.substr(0,1);if(doc.has('^@isAcronym')&&an_acronyms.hasOwnProperty(firstLetter)){return'an';}
for(var i=0;i<a_regexs.length;i++){if(a_regexs[i].test(str)){return'a';}}
if(/^[aeiou]/i.test(str)){return'an';}
return'a';};var getArticle=makeArticle;var isPlural$1=[/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/men$/i,/.tia$/i,/(m|l)ice$/i];var isSingular$1=[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i];var _rules$2={isSingular:isSingular$1,isPlural:isPlural$1};var endS=/s$/;var isPlural$2=function isPlural(str){if(_rules$2.isSingular.find(function(reg){return reg.test(str);})){return false;}
if(endS.test(str)===true){return true;}
if(_rules$2.isPlural.find(function(reg){return reg.test(str);})){return true;}
return null;};var isPlural_1$1=isPlural$2;var exceptions={he:'his',she:'hers',they:'theirs',we:'ours',i:'mine',you:'yours',her:'hers',their:'theirs',our:'ours',my:'mine',your:'yours'};var toPossessive=function toPossessive(doc){var str=doc.text('text').trim();if(exceptions.hasOwnProperty(str)){doc.replaceWith(exceptions[str],true);doc.tag('Possessive','toPossessive');return;}
if(/s$/.test(str)){str+="'";doc.replaceWith(str,true);doc.tag('Possessive','toPossessive');return;}
str+="'s";doc.replaceWith(str,true);doc.tag('Possessive','toPossessive');return;};var toPossessive_1=toPossessive;var parse$1=function parse(doc){var res={main:doc};if(doc.has('#Noun (of|by|for) .')){var m=doc.splitAfter('[#Noun+]',0);res.main=m.eq(0);res.post=m.eq(1);}
return res;};var parse_1=parse$1;var methods$6={json:function json(options){var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{text:true,normal:true,trim:true,terms:true};var res=[];this.forEach(function(doc){var json=doc.json(options)[0];json.article=getArticle(doc);res.push(json);});if(n!==null){return res[n];}
return res;},adjectives:function adjectives(){var list=this.lookAhead('^(that|who|which)? (was|is|will)? be? #Adverb? #Adjective+');list=list.concat(this.lookBehind('#Adjective+ #Adverb?$'));list=list.match('#Adjective');return list.sort('index');},isPlural:function isPlural(){return this["if"]('#Plural');},hasPlural:function hasPlural(){return this.filter(function(d){return hasPlural_1(d);});},toPlural:function toPlural(agree){var _this=this;var toPlural=this.world.transforms.toPlural;this.forEach(function(doc){if(doc.has('#Plural')||hasPlural_1(doc)===false){return;}
var main=parse_1(doc).main;var str=main.text('reduced');if(!main.has('#Singular')&&isPlural_1$1(str)===true){return;}
str=toPlural(str,_this.world);main.replace(str).tag('#Plural');if(agree){var an=main.lookBefore('(an|a) #Adjective?$').not('#Adjective');if(an.found===true){an.remove();}}});return this;},toSingular:function toSingular(agree){var _this2=this;var toSingular=this.world.transforms.toSingular;this.forEach(function(doc){if(doc.has('^#Singular+$')||hasPlural_1(doc)===false){return;}
var main=parse_1(doc).main;var str=main.text('reduced');if(!main.has('#Plural')&&isPlural_1$1(str)!==true){return;}
str=toSingular(str,_this2.world);main.replace(str).tag('#Singular');if(agree){var start=doc;var adj=doc.lookBefore('#Adjective');if(adj.found){start=adj;}
var article=getArticle(start);start.insertBefore(article);}});return this;},toPossessive:function toPossessive(){this.forEach(function(d){toPossessive_1(d);});return this;}};var methods_1=methods$6;var addMethod$5=function addMethod(Doc){var Nouns=function(_Doc){_inherits(Nouns,_Doc);var _super=_createSuper(Nouns);function Nouns(){_classCallCheck(this,Nouns);return _super.apply(this,arguments);}
return Nouns;}(Doc);Object.assign(Nouns.prototype,methods_1);Doc.prototype.nouns=function(n){var keep=this.match('(#City && @hasComma) (#Region|#Country)');var m=this.not(keep).splitAfter('@hasComma');m=m.concat(keep);m=m.match('#Noun+ (of|by)? the? #Noun+?');m=m.not('#Pronoun');m=m.not('(there|these)');m=m.not('(#Month|#WeekDay)');m=m.not('(my|our|your|their|her|his)');m=m.not('(of|for|by|the)$');if(typeof n==='number'){m=m.get(n);}
return new Nouns(m.list,this,this.world);};return Doc;};var Nouns=addMethod$5;var open=/\(/;var close=/\)/;var addMethod$6=function addMethod(Doc){var Parentheses=function(_Doc){_inherits(Parentheses,_Doc);var _super=_createSuper(Parentheses);function Parentheses(){_classCallCheck(this,Parentheses);return _super.apply(this,arguments);}
_createClass(Parentheses,[{key:"unwrap",value:function unwrap(){this.list.forEach(function(p){var first=p.terms(0);first.pre=first.pre.replace(open,'');var last=p.lastTerm();last.post=last.post.replace(close,'');});return this;}}]);return Parentheses;}(Doc);Doc.prototype.parentheses=function(n){var list=[];this.list.forEach(function(p){var terms=p.terms();for(var i=0;i<terms.length;i+=1){var t=terms[i];if(open.test(t.pre)){for(var o=i;o<terms.length;o+=1){if(close.test(terms[o].post)){var len=o-i+1;list.push(p.buildFrom(t.id,len));i=o;break;}}}}});if(typeof n==='number'){if(list[n]){list=[list[n]];}else{list=[];}
return new Parentheses(list,this,this.world);}
return new Parentheses(list,this,this.world);};return Doc;};var Parentheses=addMethod$6;var addMethod$7=function addMethod(Doc){var Possessives=function(_Doc){_inherits(Possessives,_Doc);var _super=_createSuper(Possessives);function Possessives(list,from,world){var _this;_classCallCheck(this,Possessives);_this=_super.call(this,list,from,world);_this.contracted=null;return _this;}
_createClass(Possessives,[{key:"strip",value:function strip(){this.list.forEach(function(p){var terms=p.terms();terms.forEach(function(t){var str=t.text.replace(/'s$/,'');t.set(str||t.text);});});return this;}}]);return Possessives;}(Doc);Doc.prototype.possessives=function(n){var found=this.match('#Noun+? #Possessive');if(typeof n==='number'){found=found.get(n);}
return new Possessives(found.list,this,this.world);};return Doc;};var Possessives=addMethod$7;var pairs={"\"":"\"","\uFF02":"\uFF02","'":"'","\u201C":"\u201D","\u2018":"\u2019","\u201F":"\u201D","\u201B":"\u2019","\u201E":"\u201D","\u2E42":"\u201D","\u201A":"\u2019","\xAB":"\xBB","\u2039":"\u203A","\u2035":"\u2032","\u2036":"\u2033","\u2037":"\u2034","\u301D":"\u301E","`":"\xB4","\u301F":"\u301E"};var hasOpen=RegExp('('+Object.keys(pairs).join('|')+')');var addMethod$8=function addMethod(Doc){var Quotations=function(_Doc){_inherits(Quotations,_Doc);var _super=_createSuper(Quotations);function Quotations(){_classCallCheck(this,Quotations);return _super.apply(this,arguments);}
_createClass(Quotations,[{key:"unwrap",value:function unwrap(){return this;}}]);return Quotations;}(Doc);Doc.prototype.quotations=function(n){var list=[];this.list.forEach(function(p){var terms=p.terms();for(var i=0;i<terms.length;i+=1){var t=terms[i];if(hasOpen.test(t.pre)){var _char=(t.pre.match(hasOpen)||[])[0];var want=pairs[_char];for(var o=i;o<terms.length;o+=1){if(terms[o].post.indexOf(want)!==-1){var len=o-i+1;list.push(p.buildFrom(t.id,len));i=o;break;}}}}});if(typeof n==='number'){if(list[n]){list=[list[n]];}else{list=[];}
return new Quotations(list,this,this.world);}
return new Quotations(list,this,this.world);};Doc.prototype.quotes=Doc.prototype.quotations;return Doc;};var Quotations=addMethod$8;var toInfinitive$1=function toInfinitive(parsed,world){var verb=parsed.verb;var str=verb.text('normal');if(verb.has('#Infinitive')){return str;}
var tense=null;if(verb.has('#PastTense')){tense='PastTense';}else if(verb.has('#Gerund')){tense='Gerund';}else if(verb.has('#PresentTense')){tense='PresentTense';}else if(verb.has('#Participle')){tense='Participle';}else if(verb.has('#Actor')){tense='Actor';}
return world.transforms.toInfinitive(str,world,tense);};var toInfinitive_1$1=toInfinitive$1;var findNoun=function findNoun(vb){var noun=vb.lookBehind('#Noun+').last();return noun;};var isPlural$3=function isPlural(parsed){var vb=parsed.verb;if(vb.has('(are|were|does)')||parsed.auxiliary.has('(are|were|does)')){return true;}
if(vb.has('(is|am|do|was)')||parsed.auxiliary.has('(is|am|do|was)')){return false;}
var noun=findNoun(vb);if(noun.has('(we|they|you)')){return true;}
if(noun.has('#Plural')){return true;}
if(noun.has('#Singular')){return false;}
return null;};var isPlural_1$2=isPlural$3;var toNegative=function toNegative(parsed,world){var vb=parsed.verb;if(parsed.negative.found){return;}
if(parsed.auxiliary.found){parsed.auxiliary.eq(0).append('not');if(parsed.auxiliary.has('#Modal have not')){parsed.auxiliary.replace('have not','not have');}
return;}
if(vb.has('(#Copula|will|has|had|do)')){vb.append('not');return;}
if(vb.has('#PastTense')){var inf=toInfinitive_1$1(parsed,world);vb.replaceWith(inf,true);vb.prepend('did not');return;}
if(vb.has('#PresentTense')){var _inf=toInfinitive_1$1(parsed,world);vb.replaceWith(_inf,true);if(isPlural_1$2(parsed)){vb.prepend('do not');}else{vb.prepend('does not');}
return;}
if(vb.has('#Gerund')){var _inf2=toInfinitive_1$1(parsed,world);vb.replaceWith(_inf2,true);vb.prepend('not');return;}
if(isPlural_1$2(parsed)){vb.prepend('does not');return;}
vb.prepend('do not');return;};var toNegative_1=toNegative;var parseVerb=function parseVerb(vb){var parsed={adverb:vb.match('#Adverb+'),negative:vb.match('#Negative'),auxiliary:vb.match('#Auxiliary+').not('(#Negative|#Adverb)'),particle:vb.match('#Particle'),verb:vb.match('#Verb+').not('(#Adverb|#Negative|#Auxiliary|#Particle)')};if(!parsed.verb.found){Object.keys(parsed).forEach(function(k){parsed[k]=parsed[k].not('.');});parsed.verb=vb;return parsed;}
if(parsed.adverb&&parsed.adverb.found){var match=parsed.adverb.text('reduced')+'$';if(vb.has(match)){parsed.adverbAfter=true;}}
return parsed;};var parse$2=parseVerb;var toBe=function toBe(parsed){var isI=false;var plural=isPlural_1$2(parsed);var isNegative=parsed.negative.found;if(parsed.verb.lookBehind('(i|we) (#Adverb|#Verb)?$').found){isI=true;}
var obj={PastTense:'was',PresentTense:'is',FutureTense:'will be',Infinitive:'is',Gerund:'being',Actor:'',PerfectTense:'been',Pluperfect:'been'};if(isI===true){obj.PresentTense='am';obj.Infinitive='am';}
if(plural){obj.PastTense='were';obj.PresentTense='are';obj.Infinitive='are';}
if(isNegative){obj.PastTense+=' not';obj.PresentTense+=' not';obj.FutureTense='will not be';obj.Infinitive+=' not';obj.PerfectTense='not '+obj.PerfectTense;obj.Pluperfect='not '+obj.Pluperfect;obj.Gerund='not '+obj.Gerund;}
return obj;};var toBe_1=toBe;var doModal=function doModal(parsed){var str=parsed.verb.text();var res={PastTense:str+' have',PresentTense:str,FutureTense:str,Infinitive:str};return res;};var doModal_1=doModal;var conjugate$2=function conjugate(parsed,world){var verb=parsed.verb;if(verb.has('#Copula')||verb.out('normal')==='be'&&parsed.auxiliary.has('will')){return toBe_1(parsed);}
if(verb.has('#Modal')){return doModal_1(parsed);}
var hasHyphen=parsed.verb.termList(0).hasHyphen();var infinitive=toInfinitive_1$1(parsed,world);if(!infinitive){return{};}
var forms=world.transforms.conjugate(infinitive,world);forms.Infinitive=infinitive;if(parsed.particle.found){var particle=parsed.particle.text();var space=hasHyphen===true?'-':' ';Object.keys(forms).forEach(function(k){return forms[k]+=space+particle;});}
var isNegative=parsed.negative.found;if(isNegative){forms.PastTense='did not '+forms.Infinitive;forms.PresentTense='does not '+forms.Infinitive;forms.Gerund='not '+forms.Gerund;}
if(!forms.FutureTense){if(isNegative){forms.FutureTense='will not '+forms.Infinitive;}else{forms.FutureTense='will '+forms.Infinitive;}}
if(isNegative){forms.Infinitive='not '+forms.Infinitive;}
return forms;};var conjugate_1$1=conjugate$2;var useParticiple=function useParticiple(parsed){if(parsed.auxiliary.has('(could|should|would|may|can|must)')){return true;}
if(parsed.auxiliary.has('am .+? being')){return true;}
if(parsed.auxiliary.has('had .+? been')){return true;}
return false;};var toParticiple=function toParticiple(parsed,world){if(parsed.auxiliary.has('(have|had)')&&parsed.verb.has('#Participle')){return;}
var obj=conjugate_1$1(parsed,world);var str=obj.Participle||obj.PastTense;if(str){parsed.verb.replaceWith(str,false);}
if(parsed.auxiliary.has('am .+? being')){parsed.auxiliary.remove('am');parsed.auxiliary.replace('being','have been');}
if(!parsed.auxiliary.has('have')){parsed.auxiliary.append('have');}
parsed.verb.tag('Participle','toParticiple');parsed.auxiliary.replace('can','could');parsed.auxiliary.replace('be have','have been');parsed.auxiliary.replace('not have','have not');parsed.auxiliary.tag('Auxiliary');};var participle={useParticiple:useParticiple,toParticiple:toParticiple};var _toParticiple=participle.toParticiple,useParticiple$1=participle.useParticiple;var makeNeutral=function makeNeutral(parsed){parsed.auxiliary.remove('(will|are|am|being)');parsed.auxiliary.remove('(did|does)');parsed.auxiliary.remove('(had|has|have)');parsed.particle.remove();parsed.negative.remove();return parsed;};var methods$7={json:function json(options){var _this=this;var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{text:true,normal:true,trim:true,terms:true};var res=[];this.forEach(function(p){var json=p.json(options)[0];var parsed=parse$2(p);json.parts={};Object.keys(parsed).forEach(function(k){if(parsed[k]&&parsed[k].isA==='Doc'){json.parts[k]=parsed[k].text('normal');}else{json.parts[k]=parsed[k];}});json.isNegative=p.has('#Negative');json.conjugations=conjugate_1$1(parsed,_this.world);res.push(json);});if(n!==null){return res[n];}
return res;},adverbs:function adverbs(){var list=[];this.forEach(function(vb){var advb=parse$2(vb).adverb;if(advb.found){list=list.concat(advb.list);}});var m=this.lookBehind('#Adverb+$');if(m.found){list=m.list.concat(list);}
m=this.lookAhead('^#Adverb+');if(m.found){list=list.concat(m.list);}
return this.buildFrom(list);},isPlural:function isPlural(){var _this2=this;var list=[];this.forEach(function(vb){var parsed=parse$2(vb);if(isPlural_1$2(parsed,_this2.world)===true){list.push(vb.list[0]);}});return this.buildFrom(list);},isSingular:function isSingular(){var _this3=this;var list=[];this.forEach(function(vb){var parsed=parse$2(vb);if(isPlural_1$2(parsed,_this3.world)===false){list.push(vb.list[0]);}});return this.buildFrom(list);},conjugate:function conjugate(){var _this4=this;var result=[];this.forEach(function(vb){var parsed=parse$2(vb);var forms=conjugate_1$1(parsed,_this4.world);result.push(forms);});return result;},toPastTense:function toPastTense(){var _this5=this;this.forEach(function(vb){var parsed=parse$2(vb);if(useParticiple$1(parsed)){_toParticiple(parsed,_this5.world);return;}
var str=conjugate_1$1(parsed,_this5.world).PastTense;if(str){parsed=makeNeutral(parsed);parsed.verb.replaceWith(str,false);}});return this;},toPresentTense:function toPresentTense(){var _this6=this;this.forEach(function(vb){var parsed=parse$2(vb);var obj=conjugate_1$1(parsed,_this6.world);var str=obj.PresentTense;if(vb.lookBehind('(i|we) (#Adverb|#Verb)?$').found){str=obj.Infinitive;}
if(str){if(parsed.auxiliary.has('(have|had) been')){parsed.auxiliary.replace('(have|had) been','am being');if(obj.Particle){str=obj.Particle||obj.PastTense;}
return;}
parsed.verb.replaceWith(str,false);parsed.verb.tag('PresentTense');parsed=makeNeutral(parsed);parsed.auxiliary.remove('#Modal');}});return this;},toFutureTense:function toFutureTense(){var _this7=this;this.forEach(function(vb){var parsed=parse$2(vb);if(useParticiple$1(parsed)){return;}
var str=conjugate_1$1(parsed,_this7.world).FutureTense;if(str){parsed=makeNeutral(parsed);parsed.auxiliary.remove('#Modal');parsed.verb.replaceWith(str,false);parsed.verb.tag('FutureTense');}});return this;},toInfinitive:function toInfinitive(){var _this8=this;this.forEach(function(vb){var parsed=parse$2(vb);var str=conjugate_1$1(parsed,_this8.world).Infinitive;if(str){vb.replaceWith(str,false);vb.tag('Infinitive');}});return this;},toGerund:function toGerund(){var _this9=this;this.forEach(function(vb){var parsed=parse$2(vb);var str=conjugate_1$1(parsed,_this9.world).Gerund;if(str){vb.replaceWith(str,false);vb.tag('Gerund');}});return this;},toParticiple:function toParticiple(){var _this10=this;this.forEach(function(vb){var parsed=parse$2(vb);var noAux=!parsed.auxiliary.found;_toParticiple(parsed,_this10.world);if(noAux){parsed.verb.prepend(parsed.auxiliary.text());parsed.auxiliary.remove();}});return this;},isNegative:function isNegative(){return this["if"]('#Negative');},isPositive:function isPositive(){return this.ifNo('#Negative');},toNegative:function toNegative(){var _this11=this;this.list.forEach(function(p){var doc=_this11.buildFrom([p]);var parsed=parse$2(doc);toNegative_1(parsed,doc.world);});return this;},toPositive:function toPositive(){var m=this.match('do not #Verb');if(m.found){m.remove('do not');}
return this.remove('#Negative');}};var addMethod$9=function addMethod(Doc){var Verbs=function(_Doc){_inherits(Verbs,_Doc);var _super=_createSuper(Verbs);function Verbs(){_classCallCheck(this,Verbs);return _super.apply(this,arguments);}
return Verbs;}(Doc);Object.assign(Verbs.prototype,methods$7);Verbs.prototype.negate=Verbs.prototype.toNegative;Doc.prototype.verbs=function(n){var match=this.match('(#Adverb|#Auxiliary|#Verb|#Negative|#Particle)+');match=match.not('^#Adverb+');match=match.not('#Adverb+$');var keep=match.match('(#Adverb && @hasComma) #Adverb');var m=match.not(keep).splitAfter('@hasComma');m=m.concat(keep);m.sort('index');m=m["if"]('#Verb');if(m.has('(is|was)$')){m=m.splitBefore('(is|was)$');}
if(typeof n==='number'){m=m.get(n);}
var vb=new Verbs(m.list,this,this.world);return vb;};return Doc;};var Verbs=addMethod$9;var addMethod$a=function addMethod(Doc){var People=function(_Doc){_inherits(People,_Doc);var _super=_createSuper(People);function People(){_classCallCheck(this,People);return _super.apply(this,arguments);}
return People;}(Doc);Doc.prototype.people=function(n){var match=this.splitAfter('@hasComma');match=match.match('#Person+');if(typeof n==='number'){match=match.get(n);}
return new People(match.list,this,this.world);};return Doc;};var People=addMethod$a;var subclass=[Abbreviations,Acronyms,Clauses,Contractions,Lists,Nouns,Parentheses,Possessives,Quotations,Verbs,People];var extend=function extend(Doc){Object.keys(_simple).forEach(function(k){return Doc.prototype[k]=_simple[k];});subclass.forEach(function(addFn){return addFn(Doc);});return Doc;};var Subset=extend;var methods$8={misc:methods$4,selections:_simple};var Doc=function(){function Doc(list,from,world){var _this=this;_classCallCheck(this,Doc);this.list=list;Object.defineProperty(this,'from',{enumerable:false,value:from,writable:true});if(world===undefined&&from!==undefined){world=from.world;}
Object.defineProperty(this,'world',{enumerable:false,value:world,writable:true});Object.defineProperty(this,'_cache',{enumerable:false,writable:true,value:{}});Object.defineProperty(this,'found',{get:function get(){return _this.list.length>0;}});Object.defineProperty(this,'length',{get:function get(){return _this.list.length;}});Object.defineProperty(this,'isA',{get:function get(){return'Doc';}});}
_createClass(Doc,[{key:"tagger",value:function tagger(){return _02Tagger(this);}},{key:"pool",value:function pool(){if(this.list.length>0){return this.list[0].pool;}
return this.all().list[0].pool;}}]);return Doc;}();Doc.prototype.buildFrom=function(list){list=list.map(function(p){return p.clone(true);});var doc=new Doc(list,this,this.world);return doc;};Doc.prototype.fromText=function(str){var list=_01Tokenizer(str,this.world,this.pool());return this.buildFrom(list);};Object.assign(Doc.prototype,methods$8.misc);Object.assign(Doc.prototype,methods$8.selections);Subset(Doc);var aliases$1={untag:'unTag',and:'match',notIf:'ifNo',only:'if',onlyIf:'if'};Object.keys(aliases$1).forEach(function(k){return Doc.prototype[k]=Doc.prototype[aliases$1[k]];});var Doc_1=Doc;var smallTagger=function smallTagger(doc){var terms=doc.termList();_01Lexicon(terms,doc.world);return doc;};var tiny=smallTagger;function instance(worldInstance){var world=worldInstance;var nlp=function nlp(){var text=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var lexicon=arguments.length>1?arguments[1]:undefined;if(lexicon){world.addWords(lexicon);}
var list=_01Tokenizer(text,world);var doc=new Doc_1(list,null,world);doc.tagger();return doc;};nlp.similar=similar_text;nlp.tokenize=function(){var text=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var lexicon=arguments.length>1?arguments[1]:undefined;var w=world;if(lexicon){w=w.clone();w.words={};w.addWords(lexicon);}
var list=_01Tokenizer(text,w);var doc=new Doc_1(list,null,w);if(lexicon){tiny(doc);}
return doc;};nlp.extend=function(fn){fn(Doc_1,world,this,Phrase_1,Term_1,Pool_1);return this;};nlp.fromJSON=function(json){var list=fromJSON_1(json,world);return new Doc_1(list,null,world);};nlp.clone=function(){return instance(world.clone());};nlp.verbose=function(){var bool=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;world.verbose(bool);return this;};nlp.world=function(){return world;};nlp.parseMatch=function(str){return syntax_1(str);};nlp.version=_version;nlp["import"]=nlp.load;return nlp;}
var src=instance(new World_1());return src;})));};BundleModuleCode['nlp/compromise-adjectives']=function(module,exports){(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.compromiseAdjectives=factory());}(this,(function(){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}
function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}
function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}
subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}
function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}
function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}
function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}
function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
function _possibleConstructorReturn(self,call){if(call&&(typeof call==="object"||typeof call==="function")){return call;}
return _assertThisInitialized(self);}
function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}
return _possibleConstructorReturn(this,result);};}
var not_matches=[/airs$/,/ll$/,/ee.$/,/ile$/,/y$/];var irregulars={bad:'badly',good:'well',icy:'icily',idle:'idly',male:'manly',"public":'publicly',simple:'simply',single:'singly',special:'especially',straight:'straight',vague:'vaguely',whole:'wholly'};var dontChange=['best','early','hard','fast','wrong','well','late','latter','little','long','low'].reduce(function(h,c){h[c]=true;return h;},{});var transforms=[{reg:/al$/i,repl:'ally'},{reg:/ly$/i,repl:'ly'},{reg:/(.{3})y$/i,repl:'$1ily'},{reg:/que$/i,repl:'quely'},{reg:/ue$/i,repl:'uly'},{reg:/ic$/i,repl:'ically'},{reg:/ble$/i,repl:'bly'},{reg:/l$/i,repl:'ly'}];var adj_to_adv=function adj_to_adv(str){if(irregulars.hasOwnProperty(str)===true){return irregulars[str];}
if(dontChange.hasOwnProperty(str)===true){return str;}
for(var i=0;i<not_matches.length;i++){if(not_matches[i].test(str)===true){return null;}}
for(var _i=0;_i<transforms.length;_i++){if(transforms[_i].reg.test(str)===true){return str.replace(transforms[_i].reg,transforms[_i].repl);}}
return str+'ly';};var toAdverb=adj_to_adv;var irregulars$1={clean:'cleanliness',naivety:'naivety',hurt:'hurt'};var transforms$1=[{reg:/y$/,repl:'iness'},{reg:/le$/,repl:'ility'},{reg:/ial$/,repl:'y'},{reg:/al$/,repl:'ality'},{reg:/ting$/,repl:'ting'},{reg:/ring$/,repl:'ring'},{reg:/bing$/,repl:'bingness'},{reg:/sing$/,repl:'se'},{reg:/ing$/,repl:'ment'},{reg:/ess$/,repl:'essness'},{reg:/ous$/,repl:'ousness'}];var to_noun=function to_noun(w){if(irregulars$1.hasOwnProperty(w)){return irregulars$1[w];}
var lastChar=w.charAt(w.length-1);if(lastChar==='w'||lastChar==='s'){return null;}
for(var i=0;i<transforms$1.length;i++){if(transforms$1[i].reg.test(w)===true){return w.replace(transforms$1[i].reg,transforms$1[i].repl);}}
return w+'ness';};var toNoun=to_noun;var dontDo=['c','e','g','l','n','r','w','y'].reduce(function(h,c){h[c]=true;return h;},{});var dontDoTwo={ed:true,nt:true};var banList={random:true,wild:true};var irregulars$2={bored:'bore',red:'redden',sad:'sadden',fat:'fatten',small:'shrink',full:'fill',tired:'tire'};var toVerb=function toVerb(str){if(irregulars$2.hasOwnProperty(str)===true){return irregulars$2[str];}
if(str.length<=3){return null;}
if(banList.hasOwnProperty(str)===true){return null;}
if(dontDo.hasOwnProperty(str[str.length-1])){return null;}
var suffix=str.substr(str.length-2);if(dontDoTwo.hasOwnProperty(suffix)===true){return null;}
if(/e$/.test(str)===true){return str+'n';}
return str+'en';};var toVerb_1=toVerb;var addMethods=function addMethods(Doc){var Adjective=function(_Doc){_inherits(Adjective,_Doc);var _super=_createSuper(Adjective);function Adjective(){_classCallCheck(this,Adjective);return _super.apply(this,arguments);}
_createClass(Adjective,[{key:"json",value:function json(options){var n=null;if(typeof options==='number'){n=options;options=null;}
var res=[];this.forEach(function(doc){var json=doc.json(options)[0];var str=doc.text('reduced');json.toAdverb=toAdverb(str);json.toNoun=toNoun(str);json.toVerb=toVerb_1(str);res.push(json);});if(n!==null){return res[n];}
return res;}},{key:"conjugate",value:function conjugate(n){var transform=this.world.transforms.adjectives;var arr=[];this.forEach(function(doc){var str=doc.text('reduced');var obj=transform(str);obj.Adverb=toAdverb(str);obj.Noun=toNoun(str);obj.Verb=toVerb_1(str);arr.push(obj);});if(typeof n==='number'){return arr[n];}
return arr;}},{key:"toSuperlative",value:function toSuperlative(){var transform=this.world.transforms.adjectives;this.forEach(function(doc){var obj=transform(doc.text('reduced'));doc.replaceWith(obj.Superlative,true);});return this;}},{key:"toComparative",value:function toComparative(){var transform=this.world.transforms.adjectives;this.forEach(function(doc){var obj=transform(doc.text('reduced'));doc.replaceWith(obj.Comparative,true);});return this;}},{key:"toAdverb",value:function toAdverb$1(){this.forEach(function(doc){var adverb=toAdverb(doc.text('reduced'));doc.replaceWith(adverb,true);});return this;}},{key:"toVerb",value:function toVerb(){this.forEach(function(doc){var verb=toVerb_1(doc.text('reduced'));doc.replaceWith(verb,true);});return this;}},{key:"toNoun",value:function toNoun$1(){this.forEach(function(doc){var noun=toNoun(doc.text('reduced'));doc.replaceWith(noun,true);});return this;}}]);return Adjective;}(Doc);Doc.prototype.adjectives=function(n){var m=this.match('#Adjective');if(typeof n==='number'){m=m.get(n);}
return new Adjective(m.list,this,this.world);};};var src=addMethods;return src;})));};BundleModuleCode['nlp/compromise-dates']=function(module,exports){(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.compromiseDates=factory());}(this,(function(){'use strict';function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function(obj){return typeof obj;};}else{_typeof=function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}
return _typeof(obj);}
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}
function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}
function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}
subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}
function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}
function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}
function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}
function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
function _possibleConstructorReturn(self,call){if(call&&(typeof call==="object"||typeof call==="function")){return call;}
return _assertThisInitialized(self);}
function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}
return _possibleConstructorReturn(this,result);};}
var preps='(in|by|before|during|on|until|after|of|within|all)';var thisNext='(last|next|this|previous|current|upcoming|coming)';var sections='(start|end|middle|starting|ending|midpoint|beginning)';var seasons='(spring|summer|winter|fall|autumn)';var tagYear=function tagYear(m,reason){if(m.found!==true){return;}
m.forEach(function(p){var str=p.text('reduced');var num=parseInt(str,10);if(num&&num>1000&&num<3000){p.tag('Year',reason);}});};var tagYearSafe=function tagYearSafe(m,reason){if(m.found!==true){return;}
m.forEach(function(p){var str=p.text('reduced');var num=parseInt(str,10);if(num&&num>1900&&num<2030){p.tag('Year',reason);}});};var tagDates=function tagDates(doc){doc.match('in the (night|evening|morning|afternoon|day|daytime)').tag('Time','in-the-night');doc.match('(#Value|#Time) (am|pm)').tag('Time','value-ampm');doc.match('/^[0-9]{4}-[0-9]{2}$/').tag('Date','2012-06');doc.match('(tue|thu)').tag('WeekDay','misc-weekday');var month=doc["if"]('#Month');if(month.found===true){month.match("#Month #Date+").tag('Date','correction-numberRange');month.match('#Value of #Month').tag('Date','value-of-month');month.match('#Cardinal #Month').tag('Date','cardinal-month');month.match('#Month #Value to #Value').tag('Date','value-to-value');month.match('#Month the #Value').tag('Date','month-the-value');}
var val=doc["if"]('#Value');if(val.found===true){val.match('(#WeekDay|#Month) #Value').ifNo('#Money').tag('Date','date-value');val.match('#Value (#WeekDay|#Month)').ifNo('#Money').tag('Date','value-date');val.match('#TextValue #TextValue')["if"]('#Date').tag('#Date','textvalue-date');val.match('#Value (#WeekDay|#Duration) back').tag('#Date','3-back');var duration=val["if"]('#Duration');if(duration.found===true){duration.match('for #Value #Duration').tag('Date','for-x-duration');duration.match('#Value #Duration #Conjunction').tag('Date','val-duration-conjunction');duration.match("".concat(preps,"? #Value #Duration")).tag('Date','value-duration');duration.match('#Value #Duration old').unTag('Date','val-years-old');}}
var season=doc["if"](seasons);if(season.found===true){season.match("".concat(preps,"? ").concat(thisNext," ").concat(seasons)).tag('Date','thisNext-season');season.match("the? ".concat(sections," of ").concat(seasons)).tag('Date','section-season');season.match("".concat(seasons," ").concat(preps,"? #Cardinal")).tag('Date','season-year');}
var date=doc["if"]('#Date');if(date.found===true){date.match('#Date the? #Ordinal').tag('Date','correction');date.match("".concat(thisNext," #Date")).tag('Date','thisNext');date.match('due? (by|before|after|until) #Date').tag('Date','by');date.match('(last|next|this|previous|current|upcoming|coming|the) #Date').tag('Date','next-feb');date.match("the? ".concat(sections," of #Date")).tag('Date','section-of');date.match('#Ordinal #Duration in #Date').tag('Date','duration-in');date.match('(early|late) (at|in)? the? #Date').tag('Time','early-evening');date.match('#Date (by|before|after|at|@|about) #Cardinal').not('^#Date').tag('Time','date-before-Cardinal');date.match('#Date [(am|pm)]',0).unTag('Verb').unTag('Copula').tag('Time','date-am');date.match('#Date (#Preposition|to) #Date').ifNo('#Duration').tag('Date','date-prep-date');}
var cardinal=doc["if"]('#Cardinal');if(cardinal.found===true){var v=cardinal.match("#Date #Value [#Cardinal]",0);tagYear(v,'date-value-year');v=cardinal.match("#Date [#Cardinal]",0);tagYearSafe(v,'date-year');v=cardinal.match("".concat(sections," of [#Cardinal]"));tagYearSafe(v,'section-year');v=cardinal.match("#Month #Value [#Cardinal]",0);tagYear(v,'month-value-year');v=cardinal.match("#Month #Value to #Value [#Cardinal]",0);tagYear(v,'month-range-year');v=cardinal.match("(in|of|by|during|before|starting|ending|for|year|since) [#Cardinal]",0);tagYear(v,'in-year-1');v=cardinal.match('(q1|q2|q3|q4) [#Cardinal]',0);tagYear(v,'in-year-2');v=cardinal.match('#Ordinal quarter [#Cardinal]',0);tagYear(v,'in-year-3');v=cardinal.match('the year [#Cardinal]',0);tagYear(v,'in-year-4');v=cardinal.match('it (is|was) [#Cardinal]',0);tagYearSafe(v,'in-year-5');cardinal.match("".concat(sections," of #Year")).tag('Date');}
var time=doc["if"]('#Time');if(time.found===true){time.match('(by|before|after|at|@|about) #Time').tag('Time','preposition-time');time.match('#Time [(eastern|pacific|central|mountain)]',0).tag('Date','timezone');time.match('#Time [(est|pst|gmt)]',0).tag('Date','timezone abbr');}
var m=doc.match('^/^20[012][0-9]$/$');tagYearSafe(m,'2020-ish');doc.match('(in|after) /^[0-9]+(min|sec|wk)s?/').tag('Date','shift-units');return doc;};var _00Basic=tagDates;var here='date-values';var values=function values(doc){if(!doc.has('once [a] #Duration')){doc.match('[a] #Duration',0).replaceWith('1').tag('Cardinal',here);}
if(doc.has('#Value')){doc.match('#Month #Value to #Value of? #Year?').tag('Date',here);doc.match('#Value to #Value of? #Month #Year?').tag('Date',here);doc.match('#Value #Duration of #Date').tag('Date',here);doc.match('#Value+ #Duration (after|before|into|later|afterwards|ago)?').tag('Date',here);doc.match('#Value #Date').tag('Date',here);doc.match('#Date #Value').tag('Date',here);doc.match('#Date #Preposition #Value').tag('Date',here);doc.match('#Date (after|before|during|on|in) #Value').tag('Date',here);doc.match('#Value (year|month|week|day) and a half').tag('Date',here);doc.match('#Value and a half (years|months|weeks|days)').tag('Date',here);doc.match('on the #Ordinal').tag('Date',here);}
return doc;};var _01Values=values;var here$1='date-tagger';var dateTagger=function dateTagger(doc){doc.match('(spring|summer|winter|fall|autumn|springtime|wintertime|summertime)').match('#Noun').tag('Season',here$1);doc.match('(q1|q2|q3|q4)').tag('FinancialQuarter',here$1);doc.match('(this|next|last|current) quarter').tag('FinancialQuarter',here$1);doc.match('(this|next|last|current) season').tag('Season',here$1);if(doc.has('#Date')){doc.match('#Date #Preposition #Date').tag('Date',here$1);doc.match('(once|twice) (a|an|each) #Date').tag('Date',here$1);doc.match('(by|until|on|in|at|during|over|every|each|due) the? #Date').tag('Date',here$1);doc.match('#Date+').tag('Date',here$1);doc.match('(by|until|on|in|at|during|over|every|each|due) the? #Date').tag('Date',here$1);doc.match('a #Duration').tag('Date',here$1);doc.match('(between|from) #Date').tag('Date',here$1);doc.match('(to|until|upto) #Date').tag('Date',here$1);doc.match('#Date and #Date').tag('Date',here$1);doc.match('(by|until|after|before|during|on|in|following|since) (next|this|last)? (#Date|#Date)').tag('Date',here$1);doc.match('the? #Date after next one?').tag('Date',here$1);doc.match('(about|approx|approximately|around) #Date').tag('Date',here$1);}
return doc;};var _02Dates=dateTagger;var here$2='section-tagger';var sectionTagger=function sectionTagger(doc){if(doc.has('#Date')){doc.match('this? (last|next|past|this|previous|current|upcoming|coming|the) #Date').tag('Date',here$2);doc.match('(starting|beginning|ending) #Date').tag('Date',here$2);doc.match('the? (start|end|middle|beginning) of (last|next|this|the) (#Date|#Date)').tag('Date',here$2);doc.match('(the|this) #Date').tag('Date',here$2);doc.match('#Date up to #Date').tag('Date',here$2);}
return doc;};var _03Sections=sectionTagger;var here$3='time-tagger';var timeTagger=function timeTagger(doc){doc.match('#Cardinal oclock').tag('Time',here$3);doc.match('/^[0-9]{2}h[0-9]{2}$/').tag('Time',here$3);doc.match('/^[0-9]{2}/[0-9]{2}/').tag('Date',here$3).unTag('Value');doc.match('[#Value] (in|at) the? (morning|evening|night|nighttime)').tag('Time',here$3);if(doc.has('#Cardinal')&&!doc.has('#Month')){doc.match('1? (half|quarter|25|15|10|5) (past|after|to) #Cardinal').tag('Time',here$3);}
if(doc.has('#Date')){doc.match('/^[0-9]{4}[:-][0-9]{2}[:-][0-9]{2}T[0-9]/').tag('Time',here$3);doc.match('#Date [at #Cardinal]',0).notIf('#Year').tag('Time',here$3);doc.match('half an (hour|minute|second)').tag('Date',here$3);doc.match('#Noun (standard|daylight|central|mountain)? time').tag('Timezone',here$3);doc.match('/^utc[+-][0-9]/').tag('Timezone',here$3);doc.match('/^gmt[+-][0-9]/').tag('Timezone',here$3);doc.match('(in|for|by|near|at) #Timezone').tag('Timezone',here$3);doc.match('#Time [(eastern|mountain|pacific|central)]',0).tag('Timezone',here$3);}
return doc;};var _04Time=timeTagger;var here$4='shift-tagger';var shiftTagger=function shiftTagger(doc){if(doc.has('#Date')){doc.match('#Cardinal #Duration (before|after|ago|from|hence|back)').tag('DateShift',here$4);doc.match('in #Cardinal #Duration').tag('DateShift',here$4);doc.match('in a (few|couple) of? #Duration').tag('DateShift',here$4);doc.match('#Cardinal #Duration and? #DateShift').tag('DateShift',here$4);doc.match('#DateShift and #Cardinal #Duration').tag('DateShift',here$4);doc.match('[#Duration (after|before)] #Date',0).tag('DateShift',here$4);doc.match('in half (a|an) #Duration').tag('DateShift',here$4);}
return doc;};var _05Shifts=shiftTagger;var here$5='fix-tagger';var fixUp=function fixUp(doc){if(doc.has('#Date')){var oops=doc.match('#Date+ by #Date+');if(oops.found&&!oops.has('^due')){oops.match('^#Date+').unTag('Date','by-monday');}
var d=doc.match('#Date+');d.match('^day$').unTag('Date','spa-day');d.match('(in|of|by|for)? (#Possessive && #Date)').unTag('Date','tomorrows meeting');var knownDate='(yesterday|today|tomorrow)';if(d.has(knownDate)){d.match("".concat(knownDate," [#Value]$")).unTag('Date','yesterday-7');d.match("^[#Value] ".concat(knownDate,"$"),0).unTag('Date','7 yesterday');d.match("#WeekDay+ ".concat(knownDate,"$")).unTag('Date').lastTerm().tag('Date','fri-yesterday');d.match("(this|last|next) #Date ".concat(knownDate,"$")).unTag('Date').lastTerm().tag('Date','this month yesterday');}
d.match("on #Cardinal$").unTag('Date',here$5);d.match("this tomorrow").terms(0).unTag('Date','this-tomorrow');d.match("(q1|q2|q3|q4) #Year").tag('Date',here$5);d.match("^#Value (this|next|last)").terms(0).unTag('Date',here$5);if(d.has('(last|this|next)')){d.match("(last|this|next) #Duration #Value").terms(2).unTag('Date',here$5);d.match("!#Month #Value (last|this|next) #Date").terms(0).unTag('Date',here$5);}
if(d.has('(#Year|#Time|#TextValue|#NumberRange)')===false){d.match('(#Month|#WeekDay) #Value #Value').terms(2).unTag('Date',here$5);}
if(d.has('^between')&&!d.has('and .')){d.unTag('Date',here$5);}
if(d.has('#Month #Month')&&!d.has('@hasHyphen')&&!d.has('@hasComma')){d.match('#Month').lastTerm().unTag('Date','month-month');}
if(d.has('(minutes|seconds|weeks|hours|days|months)')&&!d.has('#Value #Duration')){d.match('(minutes|seconds|weeks|hours|days|months)').unTag('Date','log-hours');}
if(d.has('about #Holiday')){d.match('about').unTag('#Date','about-thanksgiving');}
d.match('(from|by|before) now').unTag('Time');d.match('#Date+').match('^the').unTag('Date');}
return doc;};var _06Fixup=fixUp;var methods=[_00Basic,_01Values,_02Dates,_03Sections,_04Time,_05Shifts,_06Fixup];var normalize=function normalize(doc){doc.numbers().normalize();return doc;};var tagDate=function tagDate(doc){doc=normalize(doc);methods.forEach(function(fn){return fn(doc);});return doc;};var _01Tagger=tagDate;var _tags={FinancialQuarter:{isA:'Date'},Season:{isA:'Date'},Year:{isA:['Date'],notA:'RomanNumeral'},Duration:{isA:['Date','Noun']},Holiday:{isA:['Date','Noun']},Timezone:{isA:['Date','Noun'],notA:['Adjective','DateShift']},DateShift:{isA:['Date'],notA:['TimeZone','Holiday']}};var commonjsGlobal=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global!=='undefined'?global:typeof self!=='undefined'?self:{};function createCommonjsModule(fn){var module={exports:{}};return fn(module,module.exports),module.exports;}
var spacetime=createCommonjsModule(function(module,exports){(function(global,factory){module.exports=factory();})(commonjsGlobal,function(){function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}
function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}
function _iterableToArrayLimit(arr,i){if(typeof Symbol==="undefined"||!(Symbol.iterator in Object(arr)))return;var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}
return _arr;}
function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}
function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}
return arr2;}
function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}
var MSEC_IN_HOUR=60*60*1000;var toUtc=function toUtc(dstChange,offset,year){var _dstChange$split=dstChange.split('/'),_dstChange$split2=_slicedToArray(_dstChange$split,2),month=_dstChange$split2[0],rest=_dstChange$split2[1];var _rest$split=rest.split(':'),_rest$split2=_slicedToArray(_rest$split,2),day=_rest$split2[0],hour=_rest$split2[1];return Date.UTC(year,month-1,day,hour)-offset*MSEC_IN_HOUR;};var inSummerTime=function inSummerTime(epoch,start,end,summerOffset,winterOffset){var year=new Date(epoch).getUTCFullYear();var startUtc=toUtc(start,winterOffset,year);var endUtc=toUtc(end,summerOffset,year);return epoch>=startUtc&&epoch<endUtc;};var summerTime=inSummerTime;var quickOffset=function quickOffset(s){var zones=s.timezones;var obj=zones[s.tz];if(obj===undefined){console.warn("Warning: couldn't find timezone "+s.tz);return 0;}
if(obj.dst===undefined){return obj.offset;}
var jul=obj.offset;var dec=obj.offset+1;if(obj.hem==='n'){dec=jul-1;}
var split=obj.dst.split('->');var inSummer=summerTime(s.epoch,split[0],split[1],jul,dec);if(inSummer===true){return jul;}
return dec;};var quick=quickOffset;var _build={"9|s":"2/dili,2/jayapura","9|n":"2/chita,2/khandyga,2/pyongyang,2/seoul,2/tokyo,11/palau","9.5|s|04/05:03->10/04:02":"4/adelaide,4/broken_hill,4/south,4/yancowinna","9.5|s":"4/darwin,4/north","8|s|03/08:01->10/04:00":"12/casey","8|s":"2/kuala_lumpur,2/makassar,2/singapore,4/perth,4/west","8|n|03/25:03->09/29:23":"2/ulan_bator","8|n":"2/brunei,2/choibalsan,2/chongqing,2/chungking,2/harbin,2/hong_kong,2/irkutsk,2/kuching,2/macao,2/macau,2/manila,2/shanghai,2/taipei,2/ujung_pandang,2/ulaanbaatar","8.75|s":"4/eucla","7|s":"12/davis,2/jakarta,9/christmas","7|n":"2/bangkok,2/barnaul,2/ho_chi_minh,2/hovd,2/krasnoyarsk,2/novokuznetsk,2/novosibirsk,2/phnom_penh,2/pontianak,2/saigon,2/tomsk,2/vientiane","6|s":"12/vostok","6|n":"2/almaty,2/bishkek,2/dacca,2/dhaka,2/kashgar,2/omsk,2/qyzylorda,2/qostanay,2/thimbu,2/thimphu,2/urumqi,9/chagos","6.5|n":"2/rangoon,2/yangon,9/cocos","5|s":"12/mawson,9/kerguelen","5|n":"2/aqtau,2/aqtobe,2/ashgabat,2/ashkhabad,2/atyrau,2/baku,2/dushanbe,2/karachi,2/oral,2/samarkand,2/tashkent,2/yekaterinburg,9/maldives","5.75|n":"2/kathmandu,2/katmandu","5.5|n":"2/calcutta,2/colombo,2/kolkata","4|s":"9/reunion","4|n":"2/dubai,2/muscat,2/tbilisi,2/yerevan,8/astrakhan,8/samara,8/saratov,8/ulyanovsk,8/volgograd,2/volgograd,9/mahe,9/mauritius","4.5|n|03/21:00->09/20:24":"2/tehran","4.5|n":"2/kabul","3|s":"12/syowa,9/antananarivo","3|n|03/29:03->10/25:04":"2/famagusta,2/nicosia,8/athens,8/bucharest,8/helsinki,8/kiev,8/mariehamn,8/nicosia,8/riga,8/sofia,8/tallinn,8/uzhgorod,8/vilnius,8/zaporozhye","3|n|03/29:02->10/25:03":"8/chisinau,8/tiraspol","3|n|03/29:00->10/24:24":"2/beirut","3|n|03/28:00->10/24:01":"2/gaza,2/hebron","3|n|03/27:02->10/25:02":"2/jerusalem,2/tel_aviv","3|n|03/27:00->10/30:01":"2/amman","3|n|03/27:00->10/29:24":"2/damascus","3|n":"0/addis_ababa,0/asmara,0/asmera,0/dar_es_salaam,0/djibouti,0/juba,0/kampala,0/mogadishu,0/nairobi,2/aden,2/baghdad,2/bahrain,2/istanbul,2/kuwait,2/qatar,2/riyadh,8/istanbul,8/kirov,8/minsk,8/moscow,8/simferopol,9/comoro,9/mayotte","2|s|03/29:02->10/25:02":"12/troll","2|s":"0/gaborone,0/harare,0/johannesburg,0/lubumbashi,0/lusaka,0/maputo,0/maseru,0/mbabane","2|n|03/29:02->10/25:03":"0/ceuta,arctic/longyearbyen,3/jan_mayen,8/amsterdam,8/andorra,8/belgrade,8/berlin,8/bratislava,8/brussels,8/budapest,8/busingen,8/copenhagen,8/gibraltar,8/ljubljana,8/luxembourg,8/madrid,8/malta,8/monaco,8/oslo,8/paris,8/podgorica,8/prague,8/rome,8/san_marino,8/sarajevo,8/skopje,8/stockholm,8/tirane,8/vaduz,8/vatican,8/vienna,8/warsaw,8/zagreb,8/zurich","2|n":"0/blantyre,0/bujumbura,0/cairo,0/khartoum,0/kigali,0/tripoli,8/kaliningrad","1|s|04/02:01->09/03:03":"0/windhoek","1|s":"0/kinshasa,0/luanda","1|n|04/19:03->05/31:02":"0/casablanca,0/el_aaiun","1|n|03/29:01->10/25:02":"3/canary,3/faeroe,3/faroe,3/madeira,8/belfast,8/dublin,8/guernsey,8/isle_of_man,8/jersey,8/lisbon,8/london","1|n":"0/algiers,0/bangui,0/brazzaville,0/douala,0/lagos,0/libreville,0/malabo,0/ndjamena,0/niamey,0/porto-novo,0/tunis","14|n":"11/kiritimati","13|s|04/05:04->09/27:03":"11/apia","13|s|01/15:02->11/05:03":"11/tongatapu","13|n":"11/enderbury,11/fakaofo","12|s|04/05:03->09/27:02":"12/mcmurdo,12/south_pole,11/auckland","12|s|01/12:03->12/20:02":"11/fiji","12|n":"2/anadyr,2/kamchatka,2/srednekolymsk,11/funafuti,11/kwajalein,11/majuro,11/nauru,11/tarawa,11/wake,11/wallis","12.75|s|04/05:03->04/05:02":"11/chatham","11|s|04/05:03->10/04:02":"12/macquarie","11|s":"11/bougainville","11|n":"2/magadan,2/sakhalin,11/efate,11/guadalcanal,11/kosrae,11/noumea,11/pohnpei,11/ponape","11.5|n|04/05:03->10/04:02":"11/norfolk","10|s|04/05:03->10/04:02":"4/act,4/canberra,4/currie,4/hobart,4/melbourne,4/nsw,4/sydney,4/tasmania,4/victoria","10|s":"12/dumontdurville,4/brisbane,4/lindeman,4/queensland","10|n":"2/ust-nera,2/vladivostok,2/yakutsk,11/chuuk,11/guam,11/port_moresby,11/saipan,11/truk,11/yap","10.5|s|04/05:01->10/04:02":"4/lhi,4/lord_howe","0|n|03/29:00->10/25:01":"1/scoresbysund,3/azores","0|n":"0/abidjan,0/accra,0/bamako,0/banjul,0/bissau,0/conakry,0/dakar,0/freetown,0/lome,0/m
function getCjsExportFromNamespace(n){return n&&n['default']||n;}
var data=getCjsExportFromNamespace(_build$1);var all={};Object.keys(data).forEach(function(k){var split=k.split('|');var obj={offset:Number(split[0]),hem:split[1]};if(split[2]){obj.dst=split[2];}
var names=data[k].split(',');names.forEach(function(str){str=str.replace(/(^[0-9]+)\//,function(before,num){num=Number(num);return _prefixes[num]+'/';});all[str]=obj;});});all['utc']={offset:0,hem:'n'};for(var i=-14;i<=14;i+=0.5){var num=i;if(num>0){num='+'+num;}
var name='etc/gmt'+num;all[name]={offset:i* -1,hem:'n'};name='utc/gmt'+num;all[name]={offset:i* -1,hem:'n'};}
var unpack=all;var fallbackTZ='utc';var safeIntl=function safeIntl(){if(typeof Intl==='undefined'||typeof Intl.DateTimeFormat==='undefined'){return null;}
var format=Intl.DateTimeFormat();if(typeof format==='undefined'||typeof format.resolvedOptions==='undefined'){return null;}
var timezone=format.resolvedOptions().timeZone;if(!timezone){return null;}
return timezone.toLowerCase();};var guessTz=function guessTz(){var timezone=safeIntl();if(timezone===null){return fallbackTZ;}
return timezone;};var guessTz_1=guessTz;var isOffset=/(\-?[0-9]+)h(rs)?/i;var isNumber=/(\-?[0-9]+)/;var utcOffset=/utc([\-+]?[0-9]+)/i;var gmtOffset=/gmt([\-+]?[0-9]+)/i;var toIana=function toIana(num){num=Number(num);if(num>=-13&&num<=13){num=num* -1;num=(num>0?'+':'')+num;return'etc/gmt'+num;}
return null;};var parseOffset=function parseOffset(tz){var m=tz.match(isOffset);if(m!==null){return toIana(m[1]);}
m=tz.match(utcOffset);if(m!==null){return toIana(m[1]);}
m=tz.match(gmtOffset);if(m!==null){var num=Number(m[1])* -1;return toIana(num);}
m=tz.match(isNumber);if(m!==null){return toIana(m[1]);}
return null;};var parseOffset_1=parseOffset;var local=guessTz_1();var cities=Object.keys(unpack).reduce(function(h,k){var city=k.split('/')[1]||'';city=city.replace(/_/g,' ');h[city]=k;return h;},{});var normalize=function normalize(tz){tz=tz.replace(/ time/g,'');tz=tz.replace(/ (standard|daylight|summer)/g,'');tz=tz.replace(/\b(east|west|north|south)ern/g,'$1');tz=tz.replace(/\b(africa|america|australia)n/g,'$1');tz=tz.replace(/\beuropean/g,'europe');tz=tz.replace(/\islands/g,'island');return tz;};var lookupTz=function lookupTz(str,zones){if(!str){return local;}
if(typeof str!=='string'){console.error("Timezone must be a string - recieved: '",str,"'\n");}
var tz=str.trim();var split=str.split('/');if(split.length>2&&zones.hasOwnProperty(tz)===false){tz=split[0]+'/'+split[1];}
tz=tz.toLowerCase();if(zones.hasOwnProperty(tz)===true){return tz;}
tz=normalize(tz);if(zones.hasOwnProperty(tz)===true){return tz;}
if(cities.hasOwnProperty(tz)===true){return cities[tz];}
if(/[0-9]/.test(tz)===true){var id=parseOffset_1(tz);if(id){return id;}}
throw new Error("Spacetime: Cannot find timezone named: '"+str+"'. Please enter an IANA timezone id.");};var find=lookupTz;var o={millisecond:1};o.second=1000;o.minute=60000;o.hour=3.6e6;o.day=8.64e7;o.date=o.day;o.month=8.64e7*29.5;o.week=6.048e8;o.year=3.154e10;Object.keys(o).forEach(function(k){o[k+'s']=o[k];});var milliseconds=o;var walk=function walk(s,n,fn,unit,previous){var current=s.d[fn]();if(current===n){return;}
var startUnit=previous===null?null:s.d[previous]();var original=s.epoch;var diff=n-current;s.epoch+=milliseconds[unit]*diff;if(unit==='day'){if(Math.abs(diff)>28&&n<28){s.epoch+=milliseconds.hour;}}
if(previous!==null&&startUnit!==s.d[previous]()){s.epoch=original;}
var halfStep=milliseconds[unit]/2;while(s.d[fn]()<n){s.epoch+=halfStep;}
while(s.d[fn]()>n){s.epoch-=halfStep;}
if(previous!==null&&startUnit!==s.d[previous]()){s.epoch=original;}};var units={year:{valid:function valid(n){return n>-4000&&n<4000;},walkTo:function walkTo(s,n){return walk(s,n,'getFullYear','year',null);}},month:{valid:function valid(n){return n>=0&&n<=11;},walkTo:function walkTo(s,n){var d=s.d;var current=d.getMonth();var original=s.epoch;var startUnit=d.getFullYear();if(current===n){return;}
var diff=n-current;s.epoch+=milliseconds.day*(diff*28);if(startUnit!==s.d.getFullYear()){s.epoch=original;}
while(s.d.getMonth()<n){s.epoch+=milliseconds.day;}
while(s.d.getMonth()>n){s.epoch-=milliseconds.day;}}},date:{valid:function valid(n){return n>0&&n<=31;},walkTo:function walkTo(s,n){return walk(s,n,'getDate','day','getMonth');}},hour:{valid:function valid(n){return n>=0&&n<24;},walkTo:function walkTo(s,n){return walk(s,n,'getHours','hour','getDate');}},minute:{valid:function valid(n){return n>=0&&n<60;},walkTo:function walkTo(s,n){return walk(s,n,'getMinutes','minute','getHours');}},second:{valid:function valid(n){return n>=0&&n<60;},walkTo:function walkTo(s,n){s.epoch=s.seconds(n).epoch;}},millisecond:{valid:function valid(n){return n>=0&&n<1000;},walkTo:function walkTo(s,n){s.epoch=s.milliseconds(n).epoch;}}};var walkTo=function walkTo(s,wants){var keys=Object.keys(units);var old=s.clone();for(var i=0;i<keys.length;i++){var k=keys[i];var n=wants[k];if(n===undefined){n=old[k]();}
if(typeof n==='string'){n=parseInt(n,10);}
if(!units[k].valid(n)){s.epoch=null;if(s.silent===false){console.warn('invalid '+k+': '+n);}
return;}
units[k].walkTo(s,n);}
return;};var walk_1=walkTo;var shortMonths=['jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec'];var longMonths=['january','february','march','april','may','june','july','august','september','october','november','december'];function buildMapping(){var obj={sep:8};for(var i=0;i<shortMonths.length;i++){obj[shortMonths[i]]=i;}
for(var _i=0;_i<longMonths.length;_i++){obj[longMonths[_i]]=_i;}
return obj;}
var months={"short":function _short(){return shortMonths;},"long":function _long(){return longMonths;},mapping:function mapping(){return buildMapping();},set:function set(i18n){shortMonths=i18n["short"]||shortMonths;longMonths=i18n["long"]||longMonths;}};var parseOffset$1=function parseOffset(s,offset){if(!offset){return s;}
if(offset==='Z'||offset==='z'){offset='+0000';}
var num=0;if(/^[\+-]?[0-9]{2}:[0-9]{2}$/.test(offset)){if(/:00/.test(offset)===true){offset=offset.replace(/:00/,'');}
if(/:30/.test(offset)===true){offset=offset.replace(/:30/,'.5');}}
if(/^[\+-]?[0-9]{4}$/.test(offset)){offset=offset.replace(/30$/,'.5');}
num=parseFloat(offset);if(Math.abs(num)>100){num=num/100;}
num*=-1;if(num>=0){num='+'+num;}
var tz='etc/gmt'+num;var zones=s.timezones;if(zones[tz]){s.tz=tz;}
return s;};var parseOffset_1$1=parseOffset$1;var parseTime=function parseTime(s){var str=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';str=str.replace(/^\s+/,'').toLowerCase();var arr=str.match(/([0-9]{1,2}):([0-9]{1,2}):?([0-9]{1,2})?[:\.]?([0-9]{1,4})?/);if(arr!==null){var h=Number(arr[1]);if(h<0||h>24){return s.startOf('day');}
var m=Number(arr[2]);if(arr[2].length<2||m<0||m>59){return s.startOf('day');}
if(arr[4]>999){arr[4]=parseInt("".concat(arr[4]).substring(0,3),10);}
s=s.hour(h);s=s.minute(m);s=s.seconds(arr[3]||0);s=s.millisecond(arr[4]||0);var ampm=str.match(/[\b0-9](am|pm)\b/);if(ampm!==null&&ampm[1]){s=s.ampm(ampm[1]);}
return s;}
arr=str.match(/([0-9]+) ?(am|pm)/);if(arr!==null&&arr[1]){var _h=Number(arr[1]);if(_h>12||_h<1){return s.startOf('day');}
s=s.hour(arr[1]||0);s=s.ampm(arr[2]);s=s.startOf('hour');return s;}
s=s.startOf('day');return s;};var parseTime_1=parseTime;var monthLengths=[31,28,31,30,31,30,31,31,30,31,30,31];var monthLengths_1=monthLengths;var fns=createCommonjsModule(function(module,exports){exports.isLeapYear=function(year){return year%4===0&&year%100!==0||year%400===0;};exports.isDate=function(d){return Object.prototype.toString.call(d)==='[object Date]'&&!isNaN(d.valueOf());};exports.isArray=function(input){return Object.prototype.toString.call(input)==='[object Array]';};exports.isObject=function(input){return Object.prototype.toString.call(input)==='[object Object]';};exports.isBoolean=function(input){return Object.prototype.toString.call(input)==='[object Boolean]';};exports.zeroPad=function(str){var len=arguments.length>1&&arguments[1]!==undefined?arguments[1]:2;var pad='0';str=str+'';return str.length>=len?str:new Array(len-str.length+1).join(pad)+str;};exports.titleCase=function(str){if(!str){return'';}
return str[0].toUpperCase()+str.substr(1);};exports.ordinal=function(i){var j=i%10;var k=i%100;if(j===1&&k!==11){return i+'st';}
if(j===2&&k!==12){return i+'nd';}
if(j===3&&k!==13){return i+'rd';}
return i+'th';};exports.toCardinal=function(str){str=String(str);str=str.replace(/([0-9])(st|nd|rd|th)$/i,'$1');return parseInt(str,10);};exports.normalize=function(){var str=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';str=str.toLowerCase().trim();str=str.replace(/ies$/,'y');str=str.replace(/s$/,'');str=str.replace(/-/g,'');if(str==='day'||str==='days'){return'date';}
if(str==='min'||str==='mins'){return'minute';}
return str;};exports.getEpoch=function(tmp){if(typeof tmp==='number'){return tmp;}
if(exports.isDate(tmp)){return tmp.getTime();}
if(tmp.epoch){return tmp.epoch;}
return null;};exports.beADate=function(d,s){if(exports.isObject(d)===false){return s.clone().set(d);}
return d;};exports.formatTimezone=function(offset){var delimiter=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var sign=offset>0?'+':'-';var absOffset=Math.abs(offset);var hours=exports.zeroPad(parseInt(''+absOffset,10));var minutes=exports.zeroPad(absOffset%1*60);return"".concat(sign).concat(hours).concat(delimiter).concat(minutes);};});var fns_1=fns.isLeapYear;var fns_2=fns.isDate;var fns_3=fns.isArray;var fns_4=fns.isObject;var fns_5=fns.isBoolean;var fns_6=fns.zeroPad;var fns_7=fns.titleCase;var fns_8=fns.ordinal;var fns_9=fns.toCardinal;var fns_10=fns.normalize;var fns_11=fns.getEpoch;var fns_12=fns.beADate;var fns_13=fns.formatTimezone;var isLeapYear=fns.isLeapYear;var hasDate=function hasDate(obj){if(monthLengths_1.hasOwnProperty(obj.month)!==true){return false;}
if(obj.month===1){if(isLeapYear(obj.year)&&obj.date<=29){return true;}else{return obj.date<=28;}}
var max=monthLengths_1[obj.month]||0;if(obj.date<=max){return true;}
return false;};var hasDate_1=hasDate;var months$1=months.mapping();var parseYear=function parseYear(){var str=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var today=arguments.length>1?arguments[1]:undefined;var year=parseInt(str.trim(),10);if(!year&&today){year=today.year;}
year=year||new Date().getFullYear();return year;};var strFmt=[{reg:/^(\-?0?0?[0-9]{3,4})-([0-9]{1,2})-([0-9]{1,2})[T| ]([0-9.:]+)(Z|[0-9\-\+:]+)?$/i,parse:function parse(s,arr,givenTz,options){var month=parseInt(arr[2],10)-1;var obj={year:arr[1],month:month,date:arr[3]};if(hasDate_1(obj)===false){s.epoch=null;return s;}
parseOffset_1$1(s,arr[5]);walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([0-9]{4})[\-\/.]([0-9]{1,2})[\-\/.]([0-9]{1,2}),?( [0-9]{1,2}:[0-9]{2}:?[0-9]{0,2}? ?(am|pm|gmt))?$/i,parse:function parse(s,arr){var obj={year:arr[1],month:parseInt(arr[2],10)-1,date:parseInt(arr[3],10)};if(obj.month>=12){obj.date=parseInt(arr[2],10);obj.month=parseInt(arr[3],10)-1;}
if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([0-9]{1,2})[\-\/.]([0-9]{1,2})[\-\/.]?([0-9]{4})?,?( [0-9]{1,2}:[0-9]{2}:?[0-9]{0,2}? ?(am|pm|gmt))?$/i,parse:function parse(s,arr){var month=parseInt(arr[1],10)-1;var date=parseInt(arr[2],10);if(s.british||month>=12){date=parseInt(arr[1],10);month=parseInt(arr[2],10)-1;}
var year=arr[3]||new Date().getFullYear();var obj={year:year,month:month,date:date};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([0-9]{4})[\-\/]([0-9]{2})$/i,parse:function parse(s,arr,givenTz,options){var month=parseInt(arr[2],10)-1;var obj={year:arr[1],month:month,date:1};if(hasDate_1(obj)===false){s.epoch=null;return s;}
parseOffset_1$1(s,arr[5]);walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([0-9]{1,2})[\-\/]([a-z]+)[\-\/]?([0-9]{4})?$/i,parse:function parse(s,arr){var month=months$1[arr[2].toLowerCase()];var year=parseYear(arr[3],s._today);var obj={year:year,month:month,date:fns.toCardinal(arr[1]||'')};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([a-z]+)[\-\/]([0-9]{1,2})[\-\/]?([0-9]{4})?$/i,parse:function parse(s,arr){var month=months$1[arr[1].toLowerCase()];var year=parseYear(arr[3],s._today);var obj={year:year,month:month,date:fns.toCardinal(arr[2]||'')};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([a-z]+) ([0-9]{1,2}(?:st|nd|rd|th)?),?( [0-9]{4})?( ([0-9:]+( ?am| ?pm| ?gmt)?))?$/i,parse:function parse(s,arr){var month=months$1[arr[1].toLowerCase()];var year=parseYear(arr[3],s._today);var obj={year:year,month:month,date:fns.toCardinal(arr[2]||'')};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([a-z]+) ([0-9]{4})$/i,parse:function parse(s,arr){var month=months$1[arr[1].toLowerCase()];var year=parseYear(arr[2],s._today);var obj={year:year,month:month,date:s._today.date||1};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^([0-9]{1,2}(?:st|nd|rd|th)?) ([a-z]+),?( [0-9]{4})?,? ?([0-9]{1,2}:[0-9]{2}:?[0-9]{0,2}? ?(am|pm|gmt))?$/i,parse:function parse(s,arr){var month=months$1[arr[2].toLowerCase()];if(!month){return null;}
var year=parseYear(arr[3],s._today);var obj={year:year,month:month,date:fns.toCardinal(arr[1])};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s,arr[4]);return s;}},{reg:/^(q[0-9])( of)?( [0-9]{4})?/i,parse:function parse(s,arr){var quarter=arr[1]||'';s=s.quarter(quarter);var year=arr[3]||'';if(year){year=year.trim();s=s.year(year);}
return s;}},{reg:/^(spring|summer|winter|fall|autumn)( of)?( [0-9]{4})?/i,parse:function parse(s,arr){var season=arr[1]||'';s=s.season(season);var year=arr[3]||'';if(year){year=year.trim();s=s.year(year);}
return s;}},{reg:/^[0-9,]+ ?b\.?c\.?$/i,parse:function parse(s,arr){var str=arr[0]||'';str=str.replace(/^([0-9,]+) ?b\.?c\.?$/i,'-$1');str=str.replace(/,/g,'');var year=parseInt(str.trim(),10);var d=new Date();var obj={year:year,month:d.getMonth(),date:d.getDate()};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s);return s;}},{reg:/^[0-9,]+ ?(a\.?d\.?|c\.?e\.?)$/i,parse:function parse(s,arr){var str=arr[0]||'';str=str.replace(/,/g,'');var year=parseInt(str.trim(),10);var d=new Date();var obj={year:year,month:d.getMonth(),date:d.getDate()};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s);return s;}},{reg:/^[0-9]{4}( ?a\.?d\.?)?$/i,parse:function parse(s,arr){var today=s._today;var year=parseYear(arr[0],today);var d=new Date();if(today.month&&!today.date){today.date=1;}
var obj={year:year,month:today.month||d.getMonth(),date:today.date||d.getDate()};if(hasDate_1(obj)===false){s.epoch=null;return s;}
walk_1(s,obj);s=parseTime_1(s);return s;}}];var strParse=strFmt;var getNow=function getNow(s){s.epoch=Date.now();Object.keys(s._today||{}).forEach(function(k){if(typeof s[k]==='function'){s=s[k](s._today[k]);}});return s;};var dates={now:function now(s){return getNow(s);},today:function today(s){return getNow(s);},tonight:function tonight(s){s=getNow(s);s=s.hour(18);return s;},tomorrow:function tomorrow(s){s=getNow(s);s=s.add(1,'day');s=s.startOf('day');return s;},yesterday:function yesterday(s){s=getNow(s);s=s.subtract(1,'day');s=s.startOf('day');return s;},christmas:function christmas(s){var year=getNow(s).year();s=s.set([year,11,25,18,0,0]);return s;},'new years':function newYears(s){var year=getNow(s).year();s=s.set([year,11,31,18,0,0]);return s;}};dates['new years eve']=dates['new years'];var namedDates=dates;var minimumEpoch=2500000000;var defaults={year:new Date().getFullYear(),month:0,date:1};var handleArray=function handleArray(s,arr,today){if(arr.length===0){return s;}
var order=['year','month','date','hour','minute','second','millisecond'];for(var i=0;i<order.length;i++){var num=arr[i]||today[order[i]]||defaults[order[i]]||0;s=s[order[i]](num);}
return s;};var handleObject=function handleObject(s,obj,today){if(Object.keys(obj).length===0){return s;}
obj=Object.assign({},defaults,today,obj);var keys=Object.keys(obj);for(var i=0;i<keys.length;i++){var unit=keys[i];if(s[unit]===undefined||typeof s[unit]!=='function'){continue;}
if(obj[unit]===null||obj[unit]===undefined||obj[unit]===''){continue;}
var num=obj[unit]||today[unit]||defaults[unit]||0;s=s[unit](num);}
return s;};var parseInput=function parseInput(s,input,givenTz){var today=s._today||defaults;if(typeof input==='number'){if(input>0&&input<minimumEpoch&&s.silent===false){console.warn(' - Warning: You are setting the date to January 1970.');console.warn(' - did input seconds instead of milliseconds?');}
s.epoch=input;return s;}
s.epoch=Date.now();if(s._today&&fns.isObject(s._today)&&Object.keys(s._today).length>0){var res=handleObject(s,today,defaults);if(res.isValid()){s.epoch=res.epoch;}}
if(input===null||input===undefined||input===''){return s;}
if(fns.isDate(input)===true){s.epoch=input.getTime();return s;}
if(fns.isArray(input)===true){s=handleArray(s,input,today);return s;}
if(fns.isObject(input)===true){if(input.epoch){s.epoch=input.epoch;s.tz=input.tz;return s;}
s=handleObject(s,input,today);return s;}
if(typeof input!=='string'){return s;}
input=input.replace(/\b(mon|tues|wed|wednes|thu|thurs|fri|sat|satur|sun)(day)?\b/i,'');input=input.replace(/,/g,'');input=input.replace(/ +/g,' ').trim();if(namedDates.hasOwnProperty(input)===true){s=namedDates[input](s);return s;}
for(var i=0;i<strParse.length;i++){var m=input.match(strParse[i].reg);if(m){var _res=strParse[i].parse(s,m,givenTz);if(_res!==null&&_res.isValid()){return _res;}}}
if(s.silent===false){console.warn("Warning: couldn't parse date-string: '"+input+"'");}
s.epoch=null;return s;};var input=parseInput;var shortDays=['sun','mon','tue','wed','thu','fri','sat'];var longDays=['sunday','monday','tuesday','wednesday','thursday','friday','saturday'];var days={"short":function _short2(){return shortDays;},"long":function _long2(){return longDays;},set:function set(i18n){shortDays=i18n["short"]||shortDays;longDays=i18n["long"]||longDays;},aliases:{tues:2,thur:4,thurs:4}};var titleCaseEnabled=true;var caseFormat={useTitleCase:function useTitleCase(){return titleCaseEnabled;},set:function set(useTitleCase){titleCaseEnabled=useTitleCase;}};var isoOffset=function isoOffset(s){var offset=s.timezone().current.offset;return!offset?'Z':fns.formatTimezone(offset,':');};var _offset=isoOffset;var applyCaseFormat=function applyCaseFormat(str){if(caseFormat.useTitleCase()){return fns.titleCase(str);}
return str;};var format={day:function day(s){return applyCaseFormat(s.dayName());},'day-short':function dayShort(s){return applyCaseFormat(days["short"]()[s.day()]);},'day-number':function dayNumber(s){return s.day();},'day-ordinal':function dayOrdinal(s){return fns.ordinal(s.day());},'day-pad':function dayPad(s){return fns.zeroPad(s.day());},date:function date(s){return s.date();},'date-ordinal':function dateOrdinal(s){return fns.ordinal(s.date());},'date-pad':function datePad(s){return fns.zeroPad(s.date());},month:function month(s){return applyCaseFormat(s.monthName());},'month-short':function monthShort(s){return applyCaseFormat(months["short"]()[s.month()]);},'month-number':function monthNumber(s){return s.month();},'month-ordinal':function monthOrdinal(s){return fns.ordinal(s.month());},'month-pad':function monthPad(s){return fns.zeroPad(s.month());},'iso-month':function isoMonth(s){return fns.zeroPad(s.month()+1);},year:function year(s){var year=s.year();if(year>0){return year;}
year=Math.abs(year);return year+' BC';},'year-short':function yearShort(s){var year=s.year();if(year>0){return"'".concat(String(s.year()).substr(2,4));}
year=Math.abs(year);return year+' BC';},'iso-year':function isoYear(s){var year=s.year();var isNegative=year<0;var str=fns.zeroPad(Math.abs(year),4);if(isNegative){str=fns.zeroPad(str,6);str='-'+str;}
return str;},time:function time(s){return s.time();},'time-24':function time24(s){return"".concat(s.hour24(),":").concat(fns.zeroPad(s.minute()));},hour:function hour(s){return s.hour12();},'hour-pad':function hourPad(s){return fns.zeroPad(s.hour12());},'hour-24':function hour24(s){return s.hour24();},'hour-24-pad':function hour24Pad(s){return fns.zeroPad(s.hour24());},minute:function minute(s){return s.minute();},'minute-pad':function minutePad(s){return fns.zeroPad(s.minute());},second:function second(s){return s.second();},'second-pad':function secondPad(s){return fns.zeroPad(s.second());},ampm:function ampm(s){return s.ampm();},quarter:function quarter(s){return'Q'+s.quarter();},season:function season(s){return s.season();},era:function era(s){return s.era();},json:function json(s){return s.json();},timezone:function timezone(s){return s.timezone().name;},offset:function offset(s){return _offset(s);},numeric:function numeric(s){return"".concat(s.year(),"/").concat(fns.zeroPad(s.month()+1),"/").concat(fns.zeroPad(s.date()));},'numeric-us':function numericUs(s){return"".concat(fns.zeroPad(s.month()+1),"/").concat(fns.zeroPad(s.date()),"/").concat(s.year());},'numeric-uk':function numericUk(s){return"".concat(fns.zeroPad(s.date()),"/").concat(fns.zeroPad(s.month()+1),"/").concat(s.year());},'mm/dd':function mmDd(s){return"".concat(fns.zeroPad(s.month()+1),"/").concat(fns.zeroPad(s.date()));},iso:function iso(s){var year=s.format('iso-year');var month=fns.zeroPad(s.month()+1);var date=fns.zeroPad(s.date());var hour=fns.zeroPad(s.h24());var minute=fns.zeroPad(s.minute());var second=fns.zeroPad(s.second());var ms=fns.zeroPad(s.millisecond(),3);var offset=_offset(s);return"".concat(year,"-").concat(month,"-").concat(date,"T").concat(hour,":").concat(minute,":").concat(second,".").concat(ms).concat(offset);},'iso-short':function isoShort(s){var month=fns.zeroPad(s.month()+1);var date=fns.zeroPad(s.date());return"".concat(s.year(),"-").concat(month,"-").concat(date);},'iso-utc':function isoUtc(s){return new Date(s.epoch).toISOString();},nice:function nice(s){return"".concat(months["short"]()[s.month()]," ").concat(fns.ordinal(s.date()),", ").concat(s.time());},'nice-year':function niceYear(s){return"".concat(months["short"]()[s.month()]," ").concat(fns.ordinal(s.date()),", ").concat(s.year());},'nice-day':function niceDay(s){return"".concat(days["short"]()[s.day()]," ").concat(applyCaseFormat(months["short"]()[s.month()])," ").concat(fns.ordinal(s.date()));},'nice-full':function niceFull(s){return"".concat(s.dayName()," ").concat(applyCaseFormat(s.monthName())," ").concat(fns.ordinal(s.date()),", ").concat(s.time());}};var aliases={'day-name':'day','month-name':'month','iso 8601':'iso','time-h24':'time-24','time-12':'time','time-h12':'time',tz:'timezone','day-num':'day-number','month-num':'month-number','month-iso':'iso-month','year-iso':'iso-year','nice-short':'nice',mdy:'numeric-us',dmy:'numeric-uk',ymd:'numeric','yyyy/mm/dd':'numeric','mm/dd/yyyy':'numeric-us','dd/mm/yyyy':'numeric-us','little-endian':'numeric-uk','big-endian':'numeric','day-nice':'nice-day'};Object.keys(aliases).forEach(function(k){return format[k]=format[aliases[k]];});var printFormat=function printFormat(s){var str=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';if(s.isValid()!==true){return'';}
if(format.hasOwnProperty(str)){var out=format[str](s)||'';if(str!=='json'){out=String(out);if(str!=='ampm'){out=applyCaseFormat(out);}}
return out;}
if(str.indexOf('{')!==-1){var sections=/\{(.+?)\}/g;str=str.replace(sections,function(_,fmt){fmt=fmt.toLowerCase().trim();if(format.hasOwnProperty(fmt)){return String(format[fmt](s));}
return'';});return str;}
return s.format('iso-short');};var format_1=printFormat;var pad=fns.zeroPad;var formatTimezone=fns.formatTimezone;var mapping={G:function G(s){return s.era();},GG:function GG(s){return s.era();},GGG:function GGG(s){return s.era();},GGGG:function GGGG(s){return s.era()==='AD'?'Anno Domini':'Before Christ';},y:function y(s){return s.year();},yy:function yy(s){return parseInt(String(s.year()).substr(2,4),10);},yyy:function yyy(s){return s.year();},yyyy:function yyyy(s){return s.year();},yyyyy:function yyyyy(s){return'0'+s.year();},Q:function Q(s){return s.quarter();},QQ:function QQ(s){return s.quarter();},QQQ:function QQQ(s){return s.quarter();},QQQQ:function QQQQ(s){return s.quarter();},M:function M(s){return s.month()+1;},MM:function MM(s){return pad(s.month()+1);},MMM:function MMM(s){return s.format('month-short');},MMMM:function MMMM(s){return s.format('month');},w:function w(s){return s.week();},ww:function ww(s){return pad(s.week());},d:function d(s){return s.date();},dd:function dd(s){return pad(s.date());},D:function D(s){return s.dayOfYear();},DD:function DD(s){return pad(s.dayOfYear());},DDD:function DDD(s){return pad(s.dayOfYear(),3);},E:function E(s){return s.format('day-short');},EE:function EE(s){return s.format('day-short');},EEE:function EEE(s){return s.format('day-short');},EEEE:function EEEE(s){return s.format('day');},EEEEE:function EEEEE(s){return s.format('day')[0];},e:function e(s){return s.day();},ee:function ee(s){return s.day();},eee:function eee(s){return s.format('day-short');},eeee:function eeee(s){return s.format('day');},eeeee:function eeeee(s){return s.format('day')[0];},a:function a(s){return s.ampm().toUpperCase();},aa:function aa(s){return s.ampm().toUpperCase();},aaa:function aaa(s){return s.ampm().toUpperCase();},aaaa:function aaaa(s){return s.ampm().toUpperCase();},h:function h(s){return s.h12();},hh:function hh(s){return pad(s.h12());},H:function H(s){return s.hour();},HH:function HH(s){return pad(s.hour());},m:function m(s){return s.minute();},mm:function mm(s){return pad(s.minute());},s:function s(_s){return _s.second();},ss:function ss(s){return pad(s.second());},A:function A(s){return s.epoch-s.startOf('day').epoch;},z:function z(s){return s.timezone().name;},zz:function zz(s){return s.timezone().name;},zzz:function zzz(s){return s.timezone().name;},zzzz:function zzzz(s){return s.timezone().name;},Z:function Z(s){return formatTimezone(s.timezone().current.offset);},ZZ:function ZZ(s){return formatTimezone(s.timezone().current.offset);},ZZZ:function ZZZ(s){return formatTimezone(s.timezone().current.offset);},ZZZZ:function ZZZZ(s){return formatTimezone(s.timezone().current.offset,':');}};var addAlias=function addAlias(_char,to,n){var name=_char;var toName=to;for(var i=0;i<n;i+=1){mapping[name]=mapping[toName];name+=_char;toName+=to;}};addAlias('q','Q',4);addAlias('L','M',4);addAlias('Y','y',4);addAlias('c','e',4);addAlias('k','H',2);addAlias('K','h',2);addAlias('S','s',2);addAlias('v','z',4);addAlias('V','Z',4);var escapeChars=function escapeChars(arr){for(var i=0;i<arr.length;i+=1){if(arr[i]==="'"){for(var o=i+1;o<arr.length;o+=1){if(arr[o]){arr[i]+=arr[o];}
if(arr[o]==="'"){arr[o]=null;break;}
arr[o]=null;}}}
return arr.filter(function(ch){return ch;});};var combineRepeated=function combineRepeated(arr){for(var i=0;i<arr.length;i+=1){var c=arr[i];for(var o=i+1;o<arr.length;o+=1){if(arr[o]===c){arr[i]+=arr[o];arr[o]=null;}else{break;}}}
arr=arr.filter(function(ch){return ch;});arr=arr.map(function(str){if(str==="''"){str="'";}
return str;});return arr;};var unixFmt=function unixFmt(s,str){var arr=str.split('');arr=escapeChars(arr);arr=combineRepeated(arr);return arr.reduce(function(txt,c){if(mapping[c]!==undefined){txt+=mapping[c](s)||'';}else{if(/^'.{1,}'$/.test(c)){c=c.replace(/'/g,'');}
txt+=c;}
return txt;},'');};var unixFmt_1=unixFmt;var units$1=['year','season','quarter','month','week','day','quarterHour','hour','minute'];var doUnit=function doUnit(s,k){var start=s.clone().startOf(k);var end=s.clone().endOf(k);var duration=end.epoch-start.epoch;var percent=(s.epoch-start.epoch)/duration;return parseFloat(percent.toFixed(2));};var progress=function progress(s,unit){if(unit){unit=fns.normalize(unit);return doUnit(s,unit);}
var obj={};units$1.forEach(function(k){obj[k]=doUnit(s,k);});return obj;};var progress_1=progress;var nearest=function nearest(s,unit){var prog=s.progress();unit=fns.normalize(unit);if(unit==='quarterhour'){unit='quarterHour';}
if(prog[unit]!==undefined){if(prog[unit]>0.5){s=s.add(1,unit);}
s=s.startOf(unit);}else if(s.silent===false){console.warn("no known unit '"+unit+"'");}
return s;};var nearest_1=nearest;var climb=function climb(a,b,unit){var i=0;a=a.clone();while(a.isBefore(b)){a=a.add(1,unit);i+=1;}
if(a.isAfter(b,unit)){i-=1;}
return i;};var diffOne=function diffOne(a,b,unit){if(a.isBefore(b)){return climb(a,b,unit);}else{return climb(b,a,unit)* -1;}};var one=diffOne;var fastYear=function fastYear(a,b){var years=b.year()-a.year();a=a.year(b.year());if(a.isAfter(b)){years-=1;}
return years;};var diff=function diff(a,b){var msDiff=b.epoch-a.epoch;var obj={milliseconds:msDiff,seconds:parseInt(msDiff/1000,10)};obj.minutes=parseInt(obj.seconds/60,10);obj.hours=parseInt(obj.minutes/60,10);var tmp=a.clone();obj.years=fastYear(tmp,b);tmp=a.add(obj.years,'year');obj.months=obj.years*12;tmp=a.add(obj.months,'month');obj.months+=one(tmp,b,'month');obj.weeks=obj.years*52;tmp=a.add(obj.weeks,'week');obj.weeks+=one(tmp,b,'week');obj.days=obj.weeks*7;tmp=a.add(obj.days,'day');obj.days+=one(tmp,b,'day');return obj;};var waterfall=diff;var reverseDiff=function reverseDiff(obj){Object.keys(obj).forEach(function(k){obj[k]*=-1;});return obj;};var main=function main(a,b,unit){b=fns.beADate(b,a);var reversed=false;if(a.isAfter(b)){var tmp=a;a=b;b=tmp;reversed=true;}
var obj=waterfall(a,b);if(reversed){obj=reverseDiff(obj);}
if(unit){unit=fns.normalize(unit);if(/s$/.test(unit)!==true){unit+='s';}
if(unit==='dates'){unit='days';}
return obj[unit];}
return obj;};var diff$1=main;var qualifiers={months:{almost:10,over:4},days:{almost:25,over:10},hours:{almost:20,over:8},minutes:{almost:50,over:20},seconds:{almost:50,over:20}};function getDiff(a,b){var isBefore=a.isBefore(b);var later=isBefore?b:a;var earlier=isBefore?a:b;earlier=earlier.clone();var diff={years:0,months:0,days:0,hours:0,minutes:0,seconds:0};Object.keys(diff).forEach(function(unit){if(earlier.isSame(later,unit)){return;}
var max=earlier.diff(later,unit);earlier=earlier.add(max,unit);diff[unit]=max;});if(isBefore){Object.keys(diff).forEach(function(u){if(diff[u]!==0){diff[u]*=-1;}});}
return diff;}
function pluralize(value,unit){if(value===1){unit=unit.slice(0,-1);}
return value+' '+unit;}
var since=function since(start,end){end=fns.beADate(end,start);var diff=getDiff(start,end);var isNow=Object.keys(diff).every(function(u){return!diff[u];});if(isNow===true){return{diff:diff,rounded:'now',qualified:'now',precise:'now'};}
var rounded;var qualified;var precise;var englishValues=[];Object.keys(diff).forEach(function(unit,i,units){var value=Math.abs(diff[unit]);if(value===0){return;}
var englishValue=pluralize(value,unit);englishValues.push(englishValue);if(!rounded){rounded=qualified=englishValue;if(i>4){return;}
var nextUnit=units[i+1];var nextValue=Math.abs(diff[nextUnit]);if(nextValue>qualifiers[nextUnit].almost){rounded=pluralize(value+1,unit);qualified='almost '+rounded;}else if(nextValue>qualifiers[nextUnit].over)qualified='over '+englishValue;}});precise=englishValues.splice(0,2).join(', ');if(start.isAfter(end)===true){rounded+=' ago';qualified+=' ago';precise+=' ago';}else{rounded='in '+rounded;qualified='in '+qualified;precise='in '+precise;}
return{diff:diff,rounded:rounded,qualified:qualified,precise:precise};};var since_1=since;var seasons={north:[['spring',2,1],['summer',5,1],['fall',8,1],['autumn',8,1],['winter',11,1]],south:[['fall',2,1],['autumn',2,1],['winter',5,1],['spring',8,1],['summer',11,1]]};var quarters=[null,[0,1],[3,1],[6,1],[9,1]];var units$2={minute:function minute(s){walk_1(s,{second:0,millisecond:0});return s;},quarterhour:function quarterhour(s){var minute=s.minutes();if(minute>=45){s=s.minutes(45);}else if(minute>=30){s=s.minutes(30);}else if(minute>=15){s=s.minutes(15);}else{s=s.minutes(0);}
walk_1(s,{second:0,millisecond:0});return s;},hour:function hour(s){walk_1(s,{minute:0,second:0,millisecond:0});return s;},day:function day(s){walk_1(s,{hour:0,minute:0,second:0,millisecond:0});return s;},week:function week(s){var original=s.clone();s=s.day(s._weekStart);if(s.isAfter(original)){s=s.subtract(1,'week');}
walk_1(s,{hour:0,minute:0,second:0,millisecond:0});return s;},month:function month(s){walk_1(s,{date:1,hour:0,minute:0,second:0,millisecond:0});return s;},quarter:function quarter(s){var q=s.quarter();if(quarters[q]){walk_1(s,{month:quarters[q][0],date:quarters[q][1],hour:0,minute:0,second:0,millisecond:0});}
return s;},season:function season(s){var current=s.season();var hem='north';if(s.hemisphere()==='South'){hem='south';}
for(var i=0;i<seasons[hem].length;i++){if(seasons[hem][i][0]===current){var year=s.year();if(current==='winter'&&s.month()<3){year-=1;}
walk_1(s,{year:year,month:seasons[hem][i][1],date:seasons[hem][i][2],hour:0,minute:0,second:0,millisecond:0});return s;}}
return s;},year:function year(s){walk_1(s,{month:0,date:1,hour:0,minute:0,second:0,millisecond:0});return s;},decade:function decade(s){s=s.startOf('year');var year=s.year();var decade=parseInt(year/10,10)*10;s=s.year(decade);return s;},century:function century(s){s=s.startOf('year');var year=s.year();var decade=parseInt(year/100,10)*100;s=s.year(decade);return s;}};units$2.date=units$2.day;var startOf=function startOf(a,unit){var s=a.clone();unit=fns.normalize(unit);if(units$2[unit]){return units$2[unit](s);}
if(unit==='summer'||unit==='winter'){s=s.season(unit);return units$2.season(s);}
return s;};var endOf=function endOf(a,unit){var s=a.clone();unit=fns.normalize(unit);if(units$2[unit]){s=units$2[unit](s);s=s.add(1,unit);s=s.subtract(1,'milliseconds');return s;}
return s;};var startOf_1={startOf:startOf,endOf:endOf};var isDay=function isDay(unit){if(days["short"]().find(function(s){return s===unit;})){return true;}
if(days["long"]().find(function(s){return s===unit;})){return true;}
return false;};var every=function every(start){var unit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var end=arguments.length>2?arguments[2]:undefined;if(!unit||!end){return[];}
unit=fns.normalize(unit);end=start.clone().set(end);if(start.isAfter(end)){var tmp=start;start=end;end=tmp;}
var d=start.clone();if(isDay(unit)){d=d.next(unit);unit='week';}else{d=d.next(unit);}
var result=[];while(d.isBefore(end)){result.push(d);d=d.add(1,unit);}
return result;};var every_1=every;var parseDst=function parseDst(dst){if(!dst){return[];}
return dst.split('->');};var titleCase=function titleCase(str){str=str[0].toUpperCase()+str.substr(1);str=str.replace(/\/gmt/,'/GMT');str=str.replace(/[\/_]([a-z])/gi,function(s){return s.toUpperCase();});return str;};var timezone=function timezone(s){var zones=s.timezones;var tz=s.tz;if(zones.hasOwnProperty(tz)===false){tz=find(s.tz,zones);}
if(tz===null){if(s.silent===false){console.warn("Warn: could not find given or local timezone - '"+s.tz+"'");}
return{current:{epochShift:0}};}
var found=zones[tz];var result={name:titleCase(tz),hasDst:Boolean(found.dst),default_offset:found.offset,hemisphere:found.hem==='s'?'South':'North',current:{}};if(result.hasDst){var arr=parseDst(found.dst);result.change={start:arr[0],back:arr[1]};}
var summer=found.offset;var winter=summer;if(result.hasDst===true){if(result.hemisphere==='North'){winter=summer-1;}else{winter=found.offset+1;}}
if(result.hasDst===false){result.current.offset=summer;result.current.isDST=false;}else if(summerTime(s.epoch,result.change.start,result.change.back,summer,winter)===true){result.current.offset=summer;result.current.isDST=result.hemisphere==='North';}else{result.current.offset=winter;result.current.isDST=result.hemisphere==='South';}
return result;};var timezone_1=timezone;var units$3=['century','decade','year','month','date','day','hour','minute','second','millisecond'];var methods={set:function set(input$1,tz){var s=this.clone();s=input(s,input$1,null);if(tz){this.tz=find(tz);}
return s;},timezone:function timezone(){return timezone_1(this);},isDST:function isDST(){return timezone_1(this).current.isDST;},hasDST:function hasDST(){return timezone_1(this).hasDst;},offset:function offset(){return timezone_1(this).current.offset*60;},hemisphere:function hemisphere(){return timezone_1(this).hemisphere;},format:function format(fmt){return format_1(this,fmt);},unixFmt:function unixFmt(fmt){return unixFmt_1(this,fmt);},startOf:function startOf(unit){return startOf_1.startOf(this,unit);},endOf:function endOf(unit){return startOf_1.endOf(this,unit);},leapYear:function leapYear(){var year=this.year();return fns.isLeapYear(year);},progress:function progress(unit){return progress_1(this,unit);},nearest:function nearest(unit){return nearest_1(this,unit);},diff:function diff(d,unit){return diff$1(this,d,unit);},since:function since(d){if(!d){d=this.clone().set();}
return since_1(this,d);},next:function next(unit){var s=this.add(1,unit);return s.startOf(unit);},last:function last(unit){var s=this.subtract(1,unit);return s.startOf(unit);},isValid:function isValid(){if(!this.epoch&&this.epoch!==0){return false;}
return!isNaN(this.d.getTime());},"goto":function _goto(tz){var s=this.clone();s.tz=find(tz,s.timezones);return s;},every:function every(unit,to){return every_1(this,unit,to);},isAwake:function isAwake(){var hour=this.hour();if(hour<8||hour>22){return false;}
return true;},isAsleep:function isAsleep(){return!this.isAwake();},log:function log(){console.log('');console.log(format_1(this,'nice-short'));return this;},logYear:function logYear(){console.log('');console.log(format_1(this,'full-short'));return this;},json:function json(){var _this=this;return units$3.reduce(function(h,unit){h[unit]=_this[unit]();return h;},{});},debug:function debug(){var tz=this.timezone();var date=this.format('MM')+' '+this.format('date-ordinal')+' '+this.year();date+='\n - '+this.format('time');console.log('\n\n',date+'\n - '+tz.name+' ('+tz.current.offset+')');return this;},from:function from(d){d=this.clone().set(d);return d.since(this);},fromNow:function fromNow(){var d=this.clone().set(Date.now());return d.since(this);},weekStart:function weekStart(input){if(typeof input==='number'){this._weekStart=input;return this;}
if(typeof input==='string'){input=input.toLowerCase().trim();var num=days["short"]().indexOf(input);if(num===-1){num=days["long"]().indexOf(input);}
if(num===-1){num=1;}
this._weekStart=num;}else{console.warn('Spacetime Error: Cannot understand .weekStart() input:',input);}
return this;}};methods.inDST=methods.isDST;methods.round=methods.nearest;methods.each=methods.every;var methods_1=methods;var isLeapYear$1=fns.isLeapYear;var validate=function validate(n){if(typeof n==='string'){n=parseInt(n,10);}
return n;};var order=['year','month','date','hour','minute','second','millisecond'];var confirm=function confirm(s,tmp,unit){var n=order.indexOf(unit);var arr=order.slice(n,order.length);for(var i=0;i<arr.length;i++){var want=tmp[arr[i]]();s[arr[i]](want);}
return s;};var set={milliseconds:function milliseconds(s,n){n=validate(n);var current=s.millisecond();var diff=current-n;return s.epoch-diff;},seconds:function seconds(s,n){n=validate(n);var diff=s.second()-n;var shift=diff*milliseconds.second;return s.epoch-shift;},minutes:function minutes(s,n){n=validate(n);var old=s.clone();var diff=s.minute()-n;var shift=diff*milliseconds.minute;s.epoch-=shift;confirm(s,old,'second');return s.epoch;},hours:function hours(s,n){n=validate(n);if(n>=24){n=24;}else if(n<0){n=0;}
var old=s.clone();var diff=s.hour()-n;var shift=diff*milliseconds.hour;s.epoch-=shift;if(s.date()!==old.date()){s=old.clone();if(diff>1){diff-=1;}
if(diff<1){diff+=1;}
shift=diff*milliseconds.hour;s.epoch-=shift;}
walk_1(s,{hour:n});confirm(s,old,'minute');return s.epoch;},time:function time(s,str){var m=str.match(/([0-9]{1,2})[:h]([0-9]{1,2})(:[0-9]{1,2})? ?(am|pm)?/);if(!m){m=str.match(/([0-9]{1,2}) ?(am|pm)/);if(!m){return s.epoch;}
m.splice(2,0,'0');m.splice(3,0,'');}
var h24=false;var hour=parseInt(m[1],10);var minute=parseInt(m[2],10);if(hour>12){h24=true;}
if(h24===false){if(m[4]==='am'&&hour===12){hour=0;}
if(m[4]==='pm'&&hour<12){hour+=12;}}
m[3]=m[3]||'';m[3]=m[3].replace(/:/,'');var sec=parseInt(m[3],10)||0;s=s.hour(hour);s=s.minute(minute);s=s.second(sec);s=s.millisecond(0);return s.epoch;},date:function date(s,n){n=validate(n);if(n>28){var month=s.month();var max=monthLengths_1[month];if(month===1&&n===29&&isLeapYear$1(s.year())){max=29;}
if(n>max){n=max;}}
if(n<=0){n=1;}
walk_1(s,{date:n});return s.epoch;},month:function month(s,n){if(typeof n==='string'){n=months.mapping()[n.toLowerCase()];}
n=validate(n);if(n>=12){n=11;}
if(n<=0){n=0;}
var date=s.date();if(date>monthLengths_1[n]){date=monthLengths_1[n];}
walk_1(s,{month:n,date:date});return s.epoch;},year:function year(s,n){if(typeof n==='string'&&/^'[0-9]{2}$/.test(n)){n=n.replace(/'/,'').trim();n=Number(n);if(n>30){n=1900+n;}else{n=2000+n;}}
n=validate(n);walk_1(s,{year:n});return s.epoch;},dayOfYear:function dayOfYear(s,n){n=validate(n);var old=s.clone();n-=1;if(n<=0){n=0;}else if(n>=365){n=364;}
s=s.startOf('year');s=s.add(n,'day');confirm(s,old,'hour');return s.epoch;}};var methods$1={millisecond:function millisecond(num){if(num!==undefined){var s=this.clone();s.epoch=set.milliseconds(s,num);return s;}
return this.d.getMilliseconds();},second:function second(num){if(num!==undefined){var s=this.clone();s.epoch=set.seconds(s,num);return s;}
return this.d.getSeconds();},minute:function minute(num){if(num!==undefined){var s=this.clone();s.epoch=set.minutes(s,num);return s;}
return this.d.getMinutes();},hour:function hour(num){var d=this.d;if(num!==undefined){var s=this.clone();s.epoch=set.hours(s,num);return s;}
return d.getHours();},hourFloat:function hourFloat(num){if(num!==undefined){var s=this.clone();var _minute=num%1;_minute=_minute*60;var _hour=parseInt(num,10);s.epoch=set.hours(s,_hour);s.epoch=set.minutes(s,_minute);return s;}
var d=this.d;var hour=d.getHours();var minute=d.getMinutes();minute=minute/60;return hour+minute;},hour12:function hour12(str){var d=this.d;if(str!==undefined){var s=this.clone();str=''+str;var m=str.match(/^([0-9]+)(am|pm)$/);if(m){var hour=parseInt(m[1],10);if(m[2]==='pm'){hour+=12;}
s.epoch=set.hours(s,hour);}
return s;}
var hour12=d.getHours();if(hour12>12){hour12=hour12-12;}
if(hour12===0){hour12=12;}
return hour12;},time:function time(str){if(str!==undefined){var s=this.clone();str=str.toLowerCase().trim();s.epoch=set.time(s,str);return s;}
return"".concat(this.h12(),":").concat(fns.zeroPad(this.minute())).concat(this.ampm());},ampm:function ampm(input){var which='am';var hour=this.hour();if(hour>=12){which='pm';}
if(typeof input!=='string'){return which;}
var s=this.clone();input=input.toLowerCase().trim();if(hour>=12&&input==='am'){hour-=12;return s.hour(hour);}
if(hour<12&&input==='pm'){hour+=12;return s.hour(hour);}
return s;},dayTime:function dayTime(str){if(str!==undefined){var times={morning:'7:00am',breakfast:'7:00am',noon:'12:00am',lunch:'12:00pm',afternoon:'2:00pm',evening:'6:00pm',dinner:'6:00pm',night:'11:00pm',midnight:'23:59pm'};var s=this.clone();str=str||'';str=str.toLowerCase();if(times.hasOwnProperty(str)===true){s=s.time(times[str]);}
return s;}
var h=this.hour();if(h<6){return'night';}
if(h<12){return'morning';}
if(h<17){return'afternoon';}
if(h<22){return'evening';}
return'night';},iso:function iso(num){if(num!==undefined){return this.set(num);}
return this.format('iso');}};var _01Time=methods$1;var methods$2={date:function date(num){if(num!==undefined){var s=this.clone();s.epoch=set.date(s,num);return s;}
return this.d.getDate();},day:function day(input){if(input===undefined){return this.d.getDay();}
var original=this.clone();var want=input;if(typeof input==='string'){input=input.toLowerCase();if(days.aliases.hasOwnProperty(input)){want=days.aliases[input];}else{want=days["short"]().indexOf(input);if(want===-1){want=days["long"]().indexOf(input);}}}
var day=this.d.getDay();var diff=day-want;var s=this.subtract(diff,'days');walk_1(s,{hour:original.hour(),minute:original.minute(),second:original.second()});return s;},dayName:function dayName(input){if(input===undefined){return days["long"]()[this.day()];}
var s=this.clone();s=s.day(input);return s;},month:function month(input){if(input!==undefined){var s=this.clone();s.epoch=set.month(s,input);return s;}
return this.d.getMonth();}};var _02Date=methods$2;var clearMinutes=function clearMinutes(s){s=s.minute(0);s=s.second(0);s=s.millisecond(1);return s;};var methods$3={dayOfYear:function dayOfYear(num){if(num!==undefined){var s=this.clone();s.epoch=set.dayOfYear(s,num);return s;}
var sum=0;var month=this.d.getMonth();var tmp;for(var i=1;i<=month;i++){tmp=new Date();tmp.setDate(1);tmp.setFullYear(this.d.getFullYear());tmp.setHours(1);tmp.setMinutes(1);tmp.setMonth(i);tmp.setHours(-2);sum+=tmp.getDate();}
return sum+this.d.getDate();},week:function week(num){if(num!==undefined){var s=this.clone();s=s.month(0);s=s.date(1);s=s.day('monday');s=clearMinutes(s);if(s.monthName()==='december'&&s.date()>=28){s=s.add(1,'week');}
num-=1;s=s.add(num,'weeks');return s;}
var tmp=this.clone();tmp=tmp.month(0);tmp=tmp.date(1);tmp=clearMinutes(tmp);tmp=tmp.day('monday');if(tmp.monthName()==='december'&&tmp.date()>=28){tmp=tmp.add(1,'week');}
var toAdd=1;if(tmp.date()===1){toAdd=0;}
tmp=tmp.minus(1,'second');var thisOne=this.epoch;if(tmp.epoch>thisOne){return 1;}
var i=0;var skipWeeks=this.month()*4;tmp.epoch+=milliseconds.week*skipWeeks;i+=skipWeeks;for(;i<52;i++){if(tmp.epoch>thisOne){return i+toAdd;}
tmp=tmp.add(1,'week');}
return 52;},monthName:function monthName(input){if(input===undefined){return months["long"]()[this.month()];}
var s=this.clone();s=s.month(input);return s;},quarter:function quarter(num){if(num!==undefined){if(typeof num==='string'){num=num.replace(/^q/i,'');num=parseInt(num,10);}
if(quarters[num]){var s=this.clone();var _month=quarters[num][0];s=s.month(_month);s=s.date(1);s=s.startOf('day');return s;}}
var month=this.d.getMonth();for(var i=1;i<quarters.length;i++){if(month<quarters[i][0]){return i-1;}}
return 4;},season:function season(input){var hem='north';if(this.hemisphere()==='South'){hem='south';}
if(input!==undefined){var s=this.clone();for(var i=0;i<seasons[hem].length;i++){if(input===seasons[hem][i][0]){s=s.month(seasons[hem][i][1]);s=s.date(1);s=s.startOf('day');}}
return s;}
var month=this.d.getMonth();for(var _i=0;_i<seasons[hem].length-1;_i++){if(month>=seasons[hem][_i][1]&&month<seasons[hem][_i+1][1]){return seasons[hem][_i][0];}}
return'winter';},year:function year(num){if(num!==undefined){var s=this.clone();s.epoch=set.year(s,num);return s;}
return this.d.getFullYear();},era:function era(str){if(str!==undefined){var s=this.clone();str=str.toLowerCase();var year=s.d.getFullYear();if(str==='bc'&&year>0){s.epoch=set.year(s,year* -1);}
if(str==='ad'&&year<0){s.epoch=set.year(s,year* -1);}
return s;}
if(this.d.getFullYear()<0){return'BC';}
return'AD';},decade:function decade(input){if(input!==undefined){input=String(input);input=input.replace(/([0-9])'?s$/,'$1');input=input.replace(/([0-9])(th|rd|st|nd)/,'$1');if(!input){console.warn('Spacetime: Invalid decade input');return this;}
if(input.length===2&&/[0-9][0-9]/.test(input)){input='19'+input;}
var year=Number(input);if(isNaN(year)){return this;}
year=Math.floor(year/10)*10;return this.year(year);}
return this.startOf('decade').year();},century:function century(input){if(input!==undefined){if(typeof input==='string'){input=input.replace(/([0-9])(th|rd|st|nd)/,'$1');input=input.replace(/([0-9]+) ?(b\.?c\.?|a\.?d\.?)/i,function(a,b,c){if(c.match(/b\.?c\.?/i)){b='-'+b;}
return b;});input=input.replace(/c$/,'');}
var year=Number(input);if(isNaN(input)){console.warn('Spacetime: Invalid century input');return this;}
if(year===0){year=1;}
if(year>=0){year=(year-1)*100;}else{year=(year+1)*100;}
return this.year(year);}
var num=this.startOf('century').year();num=Math.floor(num/100);if(num<0){return num-1;}
return num+1;},millenium:function millenium(input){if(input!==undefined){if(typeof input==='string'){input=input.replace(/([0-9])(th|rd|st|nd)/,'$1');input=Number(input);if(isNaN(input)){console.warn('Spacetime: Invalid millenium input');return this;}}
if(input>0){input-=1;}
var year=input*1000;if(year===0){year=1;}
return this.year(year);}
var num=Math.floor(this.year()/1000);if(num>=0){num+=1;}
return num;}};var _03Year=methods$3;var methods$4=Object.assign({},_01Time,_02Date,_03Year);methods$4.milliseconds=methods$4.millisecond;methods$4.seconds=methods$4.second;methods$4.minutes=methods$4.minute;methods$4.hours=methods$4.hour;methods$4.hour24=methods$4.hour;methods$4.h12=methods$4.hour12;methods$4.h24=methods$4.hour24;methods$4.days=methods$4.day;var addMethods=function addMethods(Space){Object.keys(methods$4).forEach(function(k){Space.prototype[k]=methods$4[k];});};var query=addMethods;var isLeapYear$2=fns.isLeapYear;var getMonthLength=function getMonthLength(month,year){if(month===1&&isLeapYear$2(year)){return 29;}
return monthLengths_1[month];};var rollMonth=function rollMonth(want,old){if(want.month>0){var years=parseInt(want.month/12,10);want.year=old.year()+years;want.month=want.month%12;}else if(want.month<0){var _years=Math.floor(Math.abs(want.month)/13,10);_years=Math.abs(_years)+1;want.year=old.year()-_years;want.month=want.month%12;want.month=want.month+12;if(want.month===12){want.month=0;}}
return want;};var rollDaysDown=function rollDaysDown(want,old,sum){want.year=old.year();want.month=old.month();var date=old.date();want.date=date-Math.abs(sum);while(want.date<1){want.month-=1;if(want.month<0){want.month=11;want.year-=1;}
var max=getMonthLength(want.month,want.year);want.date+=max;}
return want;};var rollDaysUp=function rollDaysUp(want,old,sum){var year=old.year();var month=old.month();var max=getMonthLength(month,year);while(sum>max){sum-=max;month+=1;if(month>=12){month-=12;year+=1;}
max=getMonthLength(month,year);}
want.month=month;want.date=sum;return want;};var _model={months:rollMonth,days:rollDaysUp,daysBack:rollDaysDown};var order$1=['millisecond','second','minute','hour','date','month'];var keep={second:order$1.slice(0,1),minute:order$1.slice(0,2),quarterhour:order$1.slice(0,2),hour:order$1.slice(0,3),date:order$1.slice(0,4),month:order$1.slice(0,4),quarter:order$1.slice(0,4),season:order$1.slice(0,4),year:order$1,decade:order$1,century:order$1};keep.week=keep.hour;keep.season=keep.date;keep.quarter=keep.date;var dstAwareUnits={year:true,quarter:true,season:true,month:true,week:true,day:true};var keepDate={month:true,quarter:true,season:true,year:true};var addMethods$1=function addMethods(SpaceTime){SpaceTime.prototype.add=function(num,unit){var s=this.clone();if(!unit||num===0){return s;}
var old=this.clone();unit=fns.normalize(unit);if(unit==='fortnight'){num*=2;unit='week';}
if(milliseconds[unit]){s.epoch+=milliseconds[unit]*num;}else if(unit==='week'){s.epoch+=milliseconds.day*(num*7);}else if(unit==='quarter'||unit==='season'){s.epoch+=milliseconds.month*(num*3.1);}else if(unit==='quarterhour'){s.epoch+=milliseconds.minute*15*num;}
var want={};if(keep[unit]){keep[unit].forEach(function(u){want[u]=old[u]();});}
if(dstAwareUnits[unit]){var diff=old.timezone().current.offset-s.timezone().current.offset;s.epoch+=diff*3600*1000;}
if(unit==='month'){want.month=old.month()+num;want=_model.months(want,old);}
if(unit==='week'){var sum=old.date()+num*7;if(sum<=28&&sum>1){want.date=sum;}}
else if(unit==='date'){if(num<0){want=_model.daysBack(want,old,num);}else{var _sum=old.date()+num;want=_model.days(want,old,_sum);}
if(num!==0&&old.isSame(s,'day')){want.date=old.date()+num;}}
else if(unit==='year'){var wantYear=old.year()+num;var haveYear=s.year();if(haveYear<wantYear){s.epoch+=milliseconds.day;}else if(haveYear>wantYear){s.epoch+=milliseconds.day;}}
else if(unit==='decade'){want.year=s.year()+10;}else if(unit==='century'){want.year=s.year()+100;}
if(keepDate[unit]){var max=monthLengths_1[want.month];want.date=old.date();if(want.date>max){want.date=max;}}
walk_1(s,want);return s;};SpaceTime.prototype.subtract=function(num,unit){var s=this.clone();return s.add(num* -1,unit);};SpaceTime.prototype.minus=SpaceTime.prototype.subtract;SpaceTime.prototype.plus=SpaceTime.prototype.add;};var add=addMethods$1;var print={millisecond:function millisecond(s){return s.epoch;},second:function second(s){return[s.year(),s.month(),s.date(),s.hour(),s.minute(),s.second()].join('-');},minute:function minute(s){return[s.year(),s.month(),s.date(),s.hour(),s.minute()].join('-');},hour:function hour(s){return[s.year(),s.month(),s.date(),s.hour()].join('-');},day:function day(s){return[s.year(),s.month(),s.date()].join('-');},week:function week(s){return[s.year(),s.week()].join('-');},month:function month(s){return[s.year(),s.month()].join('-');},quarter:function quarter(s){return[s.year(),s.quarter()].join('-');},year:function year(s){return s.year();}};print.date=print.day;var addMethods$2=function addMethods(SpaceTime){SpaceTime.prototype.isSame=function(b,unit){var tzAware=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var a=this;if(!unit){return null;}
if(typeof b==='string'||typeof b==='number'){b=new SpaceTime(b,this.timezone.name);}
unit=unit.replace(/s$/,'');if(tzAware===true&&a.tz!==b.tz){b=b.clone();b.tz=a.tz;}
if(print[unit]){return print[unit](a)===print[unit](b);}
return null;};};var same=addMethods$2;var addMethods$3=function addMethods(SpaceTime){var methods={isAfter:function isAfter(d){d=fns.beADate(d,this);var epoch=fns.getEpoch(d);if(epoch===null){return null;}
return this.epoch>epoch;},isBefore:function isBefore(d){d=fns.beADate(d,this);var epoch=fns.getEpoch(d);if(epoch===null){return null;}
return this.epoch<epoch;},isEqual:function isEqual(d){d=fns.beADate(d,this);var epoch=fns.getEpoch(d);if(epoch===null){return null;}
return this.epoch===epoch;},isBetween:function isBetween(start,end){var isInclusive=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;start=fns.beADate(start,this);end=fns.beADate(end,this);var startEpoch=fns.getEpoch(start);if(startEpoch===null){return null;}
var endEpoch=fns.getEpoch(end);if(endEpoch===null){return null;}
if(isInclusive){return this.isBetween(start,end)||this.isEqual(start)||this.isEqual(end);}
return startEpoch<this.epoch&&this.epoch<endEpoch;}};Object.keys(methods).forEach(function(k){SpaceTime.prototype[k]=methods[k];});};var compare=addMethods$3;var addMethods$4=function addMethods(SpaceTime){var methods={i18n:function i18n(data){if(fns.isObject(data.days)){days.set(data.days);}
if(fns.isObject(data.months)){months.set(data.months);}
if(fns.isBoolean(data.useTitleCase)){caseFormat.set(data.useTitleCase);}}};Object.keys(methods).forEach(function(k){SpaceTime.prototype[k]=methods[k];});};var i18n=addMethods$4;var timezones=unpack;var SpaceTime=function SpaceTime(input$1,tz){var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};this.epoch=null;this.tz=find(tz,timezones);this.silent=options.silent||true;this.british=options.dmy||options.british;this._weekStart=1;if(options.weekStart!==undefined){this._weekStart=options.weekStart;}
this._today={};if(options.today!==undefined){this._today=options.today;}
Object.defineProperty(this,'d',{get:function get(){var offset=quick(this);var bias=new Date(this.epoch).getTimezoneOffset()||0;var shift=bias+offset*60;shift=shift*60*1000;var epoch=this.epoch+shift;var d=new Date(epoch);return d;}});Object.defineProperty(this,'timezones',{get:function get(){return timezones;},set:function set(obj){timezones=obj;return obj;}});var tmp=input(this,input$1,tz);this.epoch=tmp.epoch;};Object.keys(methods_1).forEach(function(k){SpaceTime.prototype[k]=methods_1[k];});SpaceTime.prototype.clone=function(){return new SpaceTime(this.epoch,this.tz,{silent:this.silent,weekStart:this._weekStart,today:this._today});};SpaceTime.prototype.toLocalDate=function(){return new Date(this.epoch);};query(SpaceTime);add(SpaceTime);same(SpaceTime);compare(SpaceTime);i18n(SpaceTime);var spacetime=SpaceTime;var whereIts=function whereIts(a,b){var start=new spacetime(null);var end=new spacetime(null);start=start.time(a);if(b){end=end.time(b);}else{end=start.add(59,'minutes');}
var startHour=start.hour();var endHour=end.hour();var tzs=Object.keys(start.timezones).filter(function(tz){if(tz.indexOf('/')===-1){return false;}
var m=new spacetime(null,tz);var hour=m.hour();if(hour>=startHour&&hour<=endHour){if(hour===startHour&&m.minute()<start.minute()){return false;}
if(hour===endHour&&m.minute()>end.minute()){return false;}
return true;}
return false;});return tzs;};var whereIts_1=whereIts;var _version='6.12.2';var main$1=function main(input,tz,options){return new spacetime(input,tz,options);};var setToday=function setToday(s){var today=s._today||{};Object.keys(today).forEach(function(k){s=s[k](today[k]);});return s;};main$1.now=function(tz,options){var s=new spacetime(new Date().getTime(),tz,options);s=setToday(s);return s;};main$1.today=function(tz,options){var s=new spacetime(new Date().getTime(),tz,options);s=setToday(s);return s.startOf('day');};main$1.tomorrow=function(tz,options){var s=new spacetime(new Date().getTime(),tz,options);s=setToday(s);return s.add(1,'day').startOf('day');};main$1.yesterday=function(tz,options){var s=new spacetime(new Date().getTime(),tz,options);s=setToday(s);return s.subtract(1,'day').startOf('day');};main$1.extend=function(obj){Object.keys(obj).forEach(function(k){spacetime.prototype[k]=obj[k];});return this;};main$1.whereIts=whereIts_1;main$1.version=_version;main$1.plugin=main$1.extend;var src=main$1;return src;});});var america='America/';var asia='Asia/';var europe='Europe/';var africa='Africa/';var aus='Australia/';var pac='Pacific/';var informal={'british summer time':europe+'London',bst:europe+'London','british time':europe+'London','britain time':europe+'London','irish summer time':europe+'Dublin','irish time':europe+'Dublin',ireland:europe+'Dublin','central european time':europe+'Berlin',cet:europe+'Berlin','central european summer time':europe+'Berlin',cest:europe+'Berlin','central europe':europe+'Berlin','eastern european time':europe+'Riga',eet:europe+'Riga','eastern european summer time':europe+'Riga',eest:europe+'Riga','eastern europe time':europe+'Riga','western european time':europe+'Lisbon','western european summer time':europe+'Lisbon','western europe':europe+'Lisbon','turkey standard time':europe+'Istanbul',trt:europe+'Istanbul','turkish time':europe+'Istanbul',etc:africa+'Freetown',utc:africa+'Freetown','greenwich standard time':africa+'Freetown',gmt:africa+'Freetown','east africa time':africa+'Nairobi','east african time':africa+'Nairobi','eastern africa time':africa+'Nairobi','central africa time':africa+'Khartoum','central african time':africa+'Khartoum','south africa standard time':africa+'Johannesburg',sast:africa+'Johannesburg','southern africa':africa+'Johannesburg','south african':africa+'Johannesburg','west africa standard time':africa+'Lagos','western africa time':africa+'Lagos','west african time':africa+'Lagos','australian central standard time':aus+'Adelaide',acst:aus+'Adelaide','australian central daylight time':aus+'Adelaide',acdt:aus+'Adelaide','australia central':aus+'Adelaide','australian eastern standard time':aus+'Brisbane',aest:aus+'Brisbane','australian eastern daylight time':aus+'Brisbane',aedt:aus+'Brisbane','australia east':aus+'Brisbane','australian western standard time':aus+'Perth',awst:aus+'Perth','australian western daylight time':aus+'Perth',awdt:aus+'Perth','australia west':aus+'Perth','australian central western standard time':aus+'Eucla',acwst:aus+'Eucla','australia central west':aus+'Eucla','lord howe standard time':aus+'Lord_Howe',lhst:aus+'Lord_Howe','lord howe daylight time':aus+'Lord_Howe',lhdt:aus+'Lord_Howe','russian standard time':europe+'Moscow',msk:europe+'Moscow',russian:europe+'Moscow','central standard time':america+'Chicago','central time':america+'Chicago',cst:america+'Havana','central daylight time':america+'Chicago',cdt:america+'Havana','mountain standard time':america+'Denver','mountain time':america+'Denver',mst:america+'Denver','mountain daylight time':america+'Denver',mdt:america+'Denver','atlantic standard time':america+'Halifax','atlantic time':america+'Halifax',ast:asia+'Baghdad','atlantic daylight time':america+'Halifax',adt:america+'Halifax','eastern standard time':america+'New_York','eastern time':america+'New_York',est:america+'New_York','eastern daylight time':america+'New_York',edt:america+'New_York','pacific time':america+'Los_Angeles','pacific standard time':america+'Los_Angeles',pst:america+'Los_Angeles','pacific daylight time':ame
return unit;};var parseShift=function parseShift(doc){var result={};var shift=doc.match('#DateShift+');if(shift.found===false){return result;}
shift.match('#Cardinal #Duration').forEach(function(ts){var num=ts.match('#Cardinal').text('normal');num=parseFloat(num);if(num&&typeof num==='number'){var unit=parseUnit(ts);if(knownUnits[unit]===true){result[unit]=num;}}});if(shift.has('(before|ago|hence|back)$')===true){Object.keys(result).forEach(function(k){return result[k]*=-1;});}
shift.remove('#Cardinal #Duration');var m=shift.match('[<unit>#Duration] [<dir>(after|before)]');if(m.found){var unit=m.groups('unit').text('reduced');var dir=m.groups('dir').text('reduced');if(dir==='after'){result[unit]=1;}else if(dir==='before'){result[unit]=-1;}}
m=shift.match('half (a|an) [#Duration]',0);if(m.found){var _unit=parseUnit(m);result[_unit]=0.5;}
doc.remove('#DateShift');return result;};var _01Shift=parseShift;var oneBased={minute:true};var getCounter=function getCounter(doc){var m=doc.match('[<num>#Value] [<unit>#Duration+] (of|in)');if(m.found){var obj=m.groups();var num=obj.num.text('reduced');var unit=obj.unit.text('reduced');var found={unit:unit,num:Number(num)||0};if(!oneBased[unit]){found.num-=1;}
doc=doc.remove(m);return found;}
m=doc.match('[<dir>(first|initial|last|final)] [<unit>#Duration+] (of|in)');if(m.found){var _obj=m.groups();var dir=_obj.dir.text('reduced');var _unit=_obj.unit.text('reduced');if(dir==='initial'){dir='first';}
if(dir==='final'){dir='last';}
var _found={unit:_unit,dir:dir};doc=doc.remove(m);return _found;}
return{};};var _02Counter=getCounter;var hardCoded={daybreak:'7:00am',breakfast:'8:00am',morning:'9:00am',noon:'12:00pm',midday:'12:00pm',afternoon:'2:00pm',lunchtime:'12:00pm',evening:'6:00pm',dinnertime:'6:00pm',night:'8:00pm',eod:'10:00pm',midnight:'12:00am'};var halfPast=function halfPast(m,s){var hour=m.match('#Cardinal$').text('reduced');var term=m.match('(half|quarter|25|15|10|5)');var mins=term.text('reduced');if(term.has('half')){mins='30';}
if(term.has('quarter')){mins='15';}
var behind=m.has('to');s=s.hour(hour);s=s.startOf('hour');if(hour<6){s=s.ampm('pm');}
if(behind){s=s.subtract(mins,'minutes');}else{s=s.add(mins,'minutes');}
return s;};var parseTime=function parseTime(doc,context){var time=doc.match('(at|by|for|before|this)? #Time+');if(time.found){doc.remove(time);}
time=time.not('^(at|by|for|before|this)');time=time.not('sharp');time=time.not('on the dot');var s=spacetime.now(context.timezone);var now=s.clone();var timeStr=time.text('reduced');if(hardCoded.hasOwnProperty(timeStr)){return hardCoded[timeStr];}
var m=time.match('^#Cardinal oclock (am|pm)?');if(m.found){m=m.not('oclock');s=s.hour(m.text('reduced'));s=s.startOf('hour');if(s.isValid()&&!s.isEqual(now)){return s.time();}}
m=time.match('(half|quarter|25|15|10|5) (past|after|to) #Cardinal');if(m.found){s=halfPast(m,s);if(s.isValid()&&!s.isEqual(now)){return s.time();}}
m=time.match('[<time>#Time] (in|at) the? [<desc>(morning|evening|night|nighttime)]');if(m.found){var _str=m.groups('time').text('reduced');if(/^[0-9]{1,2}$/.test(_str)){s=s.hour(_str);}else{s=s.time(_str);}
if(s.isValid()&&!s.isEqual(now)){var desc=m.groups('desc').text('reduced');if(desc==='evening'||desc==='night'){s=s.ampm('pm');}
return s.time();}}
m=time.match('this? [<desc>(morning|evening|tonight)] at [<time>(#Cardinal|#Time)]');if(m.found){var g=m.groups();var _str2=g.time.text('reduced');if(/^[0-9]{1,2}$/.test(_str2)){s=s.hour(_str2);s=s.startOf('hour');}else{s=s.time(_str2);}
if(s.isValid()&&!s.isEqual(now)){var _desc=g.desc.text('reduced');if(_desc==='morning'){s=s.ampm('am');}
if(_desc==='evening'||_desc==='tonight'){s=s.ampm('pm');}
return s.time();}}
m=time.match('^#Cardinal$');if(m.found){s=s.hour(m.text('reduced'));s=s.startOf('hour');if(s.isValid()&&!s.isEqual(now)){return s.time();}}
var str=time.text('reduced');s=s.time(str);if(s.isValid()&&!s.isEqual(now)){return s.time();}
return null;};var _03Time=parseTime;var parseRelative=function parseRelative(doc){if(doc.has('(next|last|this)$')){return null;}
var rel=null;var m=doc.match('^this? (next|upcoming|coming)');if(m.found){rel='next';doc.remove(m);}
m=doc.match('^this? (last|previous)');if(m.found){rel='last';doc.remove(m);}
m=doc.match('^(this|current)');if(m.found){rel='this';doc.remove(m);}
return rel;};var _04Relative=parseRelative;var parseSection=function parseSection(doc){var m=doc.match('[(start|beginning) of] .',0);if(m.found){doc.remove(m);return'start';}
m=doc.match('[end of] .',0);if(m.found){doc.remove(m);return'end';}
m=doc.match('[(middle|midpoint|center) of] .',0);if(m.found){doc.remove(m);return'middle';}
return null;};var _05Section=parseSection;var isOffset=/(\-?[0-9]+)h(rs)?/i;var isNumber=/(\-?[0-9]+)/;var utcOffset=/utc([\-+]?[0-9]+)/i;var gmtOffset=/gmt([\-+]?[0-9]+)/i;var toIana=function toIana(num){num=Number(num);if(num>-13&&num<13){num=num* -1;num=(num>0?'+':'')+num;return'Etc/GMT'+num;}
return null;};var parseOffset=function parseOffset(tz){var m=tz.match(isOffset);if(m!==null){return toIana(m[1]);}
m=tz.match(utcOffset);if(m!==null){return toIana(m[1]);}
m=tz.match(gmtOffset);if(m!==null){var num=Number(m[1])* -1;return toIana(num);}
m=tz.match(isNumber);if(m!==null){return toIana(m[1]);}
return null;};var parseTimezone=function parseTimezone(doc){var m=doc.match('#Timezone+');m=m.remove('(in|for|by|near|at)');var str=m.text('reduced');doc.remove('#Timezone+');if(_timezones.hasOwnProperty(str)){return _timezones[str];}
var tz=parseOffset(str);if(tz){return tz;}
return null;};var _06Timezone=parseTimezone;var Unit=function(){function Unit(input,unit,context,keepTime){_classCallCheck(this,Unit);this.unit=unit||'day';context=context||{};var today={};if(context.today){today={date:context.today.date(),month:context.today.month(),year:context.today.year()};}
var d=spacetime(input,context.timezone,{today:today});Object.defineProperty(this,'d',{enumerable:false,writable:true,value:d});Object.defineProperty(this,'context',{enumerable:false,writable:true,value:context});}
_createClass(Unit,[{key:"clone",value:function clone(){var d=new Unit(this.d,this.unit,this.context);return d;}},{key:"log",value:function log(){console.log('--');this.d.log();console.log('\n');return this;}},{key:"applyShift",value:function applyShift(){var _this=this;var obj=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};Object.keys(obj).forEach(function(unit){_this.d=_this.d.add(obj[unit],unit);});return this;}},{key:"applyTime",value:function applyTime(str){if(str){this.d=this.d.time(str);}else{this.d=this.d.startOf('day');}
return this;}},{key:"applyRel",value:function applyRel(rel){if(rel==='next'){return this.next();}
if(rel==='last'){return this.last();}
return this;}},{key:"applySection",value:function applySection(section){if(section==='start'){return this.start();}
if(section==='end'){return this.end();}
if(section==='middle'){return this.middle();}
return this;}},{key:"format",value:function format(fmt){return this.d.format(fmt);}},{key:"start",value:function start(){this.d=this.d.startOf(this.unit);return this;}},{key:"end",value:function end(){this.d=this.d.endOf(this.unit);return this;}},{key:"middle",value:function middle(){var diff=this.d.diff(this.d.endOf(this.unit));var minutes=Math.round(diff.minutes/2);this.d=this.d.add(minutes,'minutes');return this;}},{key:"before",value:function before(){this.d=this.d.minus(1,this.unit);this.d=this.d.endOf(this.unit);return this;}},{key:"after",value:function after(){this.d=this.d.add(1,this.unit);this.d=this.d.startOf(this.unit);return this;}},{key:"next",value:function next(){this.d=this.d.add(1,this.unit);this.d=this.d.startOf(this.unit);return this;}},{key:"last",value:function last(){this.d=this.d.minus(1,this.unit);this.d=this.d.startOf(this.unit);return this;}}]);return Unit;}();var Unit_1=Unit;var Day=function(_Unit){_inherits(Day,_Unit);var _super=_createSuper(Day);function Day(input,unit,context){var _this;_classCallCheck(this,Day);_this=_super.call(this,input,unit,context);_this.unit='day';if(_this.d.isValid()){_this.d=_this.d.startOf('day');}
return _this;}
return Day;}(Unit_1);var CalendarDate=function(_Day){_inherits(CalendarDate,_Day);var _super2=_createSuper(CalendarDate);function CalendarDate(input,unit,context){var _this2;_classCallCheck(this,CalendarDate);_this2=_super2.call(this,input,unit,context);_this2.unit='day';if(_this2.d.isValid()){_this2.d=_this2.d.startOf('day');}
return _this2;}
_createClass(CalendarDate,[{key:"next",value:function next(){this.d=this.d.add(1,'year');return this;}},{key:"last",value:function last(){this.d=this.d.minus(1,'year');return this;}}]);return CalendarDate;}(Day);var WeekDay=function(_Day2){_inherits(WeekDay,_Day2);var _super3=_createSuper(WeekDay);function WeekDay(input,unit,context){var _this3;_classCallCheck(this,WeekDay);_this3=_super3.call(this,input,unit,context);_this3.unit='week';if(typeof input==='string'){_this3.d=spacetime(context.today,context.timezone);_this3.d=_this3.d.day(input);if(_this3.d.isBefore(context.today)){_this3.d=_this3.d.add(7,'days');}}else{_this3.d=input;}
_this3.weekDay=_this3.d.dayName();if(_this3.d.isValid()){_this3.d=_this3.d.startOf('day');}
return _this3;}
_createClass(WeekDay,[{key:"clone",value:function clone(){return new WeekDay(this.d,this.unit,this.context);}},{key:"end",value:function end(){this.d=this.d.endOf('day');return this;}},{key:"next",value:function next(){this.d=this.d.add(7,'days');this.d=this.d.day(this.weekDay);return this;}},{key:"last",value:function last(){this.d=this.d.minus(7,'days');this.d=this.d.day(this.weekDay);return this;}}]);return WeekDay;}(Day);var Holiday=function(_CalendarDate){_inherits(Holiday,_CalendarDate);var _super4=_createSuper(Holiday);function Holiday(input,unit,context){var _this4;_classCallCheck(this,Holiday);_this4=_super4.call(this,input,unit,context);_this4.unit='day';if(_this4.d.isValid()){_this4.d=_this4.d.startOf('day');}
return _this4;}
return Holiday;}(CalendarDate);var _day={Day:Day,WeekDay:WeekDay,CalendarDate:CalendarDate,Holiday:Holiday};var AnyMonth=function(_Unit){_inherits(AnyMonth,_Unit);var _super=_createSuper(AnyMonth);function AnyMonth(input,unit,context){var _this;_classCallCheck(this,AnyMonth);_this=_super.call(this,input,unit,context);_this.unit='month';if(_this.d.isValid()){_this.d=_this.d.startOf(_this.unit);}
return _this;}
return AnyMonth;}(Unit_1);var Month=function(_Unit2){_inherits(Month,_Unit2);var _super2=_createSuper(Month);function Month(input,unit,context){var _this2;_classCallCheck(this,Month);_this2=_super2.call(this,input,unit,context);_this2.unit='month';if(_this2.d.isValid()){_this2.d=_this2.d.startOf(_this2.unit);}
return _this2;}
_createClass(Month,[{key:"next",value:function next(){this.d=this.d.add(1,'year');this.d=this.d.startOf('month');return this;}},{key:"last",value:function last(){this.d=this.d.minus(1,'year');this.d=this.d.startOf('month');return this;}}]);return Month;}(Unit_1);var AnyQuarter=function(_Unit3){_inherits(AnyQuarter,_Unit3);var _super3=_createSuper(AnyQuarter);function AnyQuarter(input,unit,context){var _this3;_classCallCheck(this,AnyQuarter);_this3=_super3.call(this,input,unit,context);_this3.unit='quarter';if(_this3.d.isValid()){_this3.d=_this3.d.startOf(_this3.unit);}
return _this3;}
_createClass(AnyQuarter,[{key:"last",value:function last(){console.log(this.d.format());this.d=this.d.minus(1,'quarter');console.log(this.d.format());this.d=this.d.startOf(this.unit);console.log(this.d.format());return this;}}]);return AnyQuarter;}(Unit_1);var Quarter=function(_Unit4){_inherits(Quarter,_Unit4);var _super4=_createSuper(Quarter);function Quarter(input,unit,context){var _this4;_classCallCheck(this,Quarter);_this4=_super4.call(this,input,unit,context);_this4.unit='quarter';if(_this4.d.isValid()){_this4.d=_this4.d.startOf(_this4.unit);}
return _this4;}
_createClass(Quarter,[{key:"next",value:function next(){this.d=this.d.add(1,'year');this.d=this.d.startOf(this.unit);return this;}},{key:"last",value:function last(){this.d=this.d.minus(1,'year');this.d=this.d.startOf(this.unit);return this;}}]);return Quarter;}(Unit_1);var Season=function(_Unit5){_inherits(Season,_Unit5);var _super5=_createSuper(Season);function Season(input,unit,context){var _this5;_classCallCheck(this,Season);_this5=_super5.call(this,input,unit,context);_this5.unit='season';if(_this5.d.isValid()){_this5.d=_this5.d.startOf(_this5.unit);}
return _this5;}
_createClass(Season,[{key:"next",value:function next(){this.d=this.d.add(1,'year');this.d=this.d.startOf(this.unit);return this;}},{key:"last",value:function last(){this.d=this.d.minus(1,'year');this.d=this.d.startOf(this.unit);return this;}}]);return Season;}(Unit_1);var Year=function(_Unit6){_inherits(Year,_Unit6);var _super6=_createSuper(Year);function Year(input,unit,context){var _this6;_classCallCheck(this,Year);_this6=_super6.call(this,input,unit,context);_this6.unit='year';if(_this6.d.isValid()){_this6.d=_this6.d.startOf('year');}
return _this6;}
return Year;}(Unit_1);var _year={AnyMonth:AnyMonth,Month:Month,Quarter:Quarter,AnyQuarter:AnyQuarter,Season:Season,Year:Year};var Week=function(_Unit){_inherits(Week,_Unit);var _super=_createSuper(Week);function Week(input,unit,context){var _this;_classCallCheck(this,Week);_this=_super.call(this,input,unit,context);_this.unit='week';if(_this.d.isValid()){_this.d=_this.d.startOf('week');}
return _this;}
return Week;}(Unit_1);var WeekEnd=function(_Unit2){_inherits(WeekEnd,_Unit2);var _super2=_createSuper(WeekEnd);function WeekEnd(input,unit,context){var _this2;_classCallCheck(this,WeekEnd);_this2=_super2.call(this,input,unit,context);_this2.unit='week';if(_this2.d.isValid()){_this2.d=_this2.d.day('saturday');_this2.d=_this2.d.startOf('day');}
return _this2;}
_createClass(WeekEnd,[{key:"start",value:function start(){this.d=this.d.day('saturday').startOf('day');return this;}},{key:"next",value:function next(){this.d=this.d.add(1,this.unit);this.d=this.d.startOf('weekend');return this;}},{key:"last",value:function last(){this.d=this.d.minus(1,this.unit);this.d=this.d.startOf('weekend');return this;}}]);return WeekEnd;}(Unit_1);var _week={Week:Week,WeekEnd:WeekEnd};var Hour=function(_Unit){_inherits(Hour,_Unit);var _super=_createSuper(Hour);function Hour(input,unit,context){var _this;_classCallCheck(this,Hour);_this=_super.call(this,input,unit,context,true);_this.unit='hour';if(_this.d.isValid()){_this.d=_this.d.startOf('hour');}
return _this;}
return Hour;}(Unit_1);var Minute=function(_Unit2){_inherits(Minute,_Unit2);var _super2=_createSuper(Minute);function Minute(input,unit,context){var _this2;_classCallCheck(this,Minute);_this2=_super2.call(this,input,unit,context,true);_this2.unit='minute';if(_this2.d.isValid()){_this2.d=_this2.d.startOf('minute');}
return _this2;}
return Minute;}(Unit_1);var Moment=function(_Unit3){_inherits(Moment,_Unit3);var _super3=_createSuper(Moment);function Moment(input,unit,context){var _this3;_classCallCheck(this,Moment);_this3=_super3.call(this,input,unit,context,true);_this3.unit='millisecond';return _this3;}
return Moment;}(Unit_1);var _time={Hour:Hour,Minute:Minute,Moment:Moment};var units=Object.assign({Unit:Unit_1},_day,_year,_week,_time);var Day$1=units.Day,Moment$1=units.Moment,Hour$1=units.Hour;var knownWord={today:function today(context){return new Day$1(context.today,null,context);},yesterday:function yesterday(context){return new Day$1(context.today.minus(1,'day'),null,context);},tomorrow:function tomorrow(context){return new Day$1(context.today.plus(1,'day'),null,context);},eom:function eom(context){var d=context.today.endOf('month');d=d.startOf('day');return new Day$1(d,null,context);},eoy:function eoy(context){var d=context.today.endOf('year');d=d.startOf('day');return new Day$1(d,null,context);}};knownWord.tommorrow=knownWord.tomorrow;knownWord.tmrw=knownWord.tomorrow;var today=function today(doc,context,section){var unit=null;if(doc.found===false){if(section.time!==null){unit=new Moment$1(context.today,null,context);}
if(Object.keys(section.shift).length>0){if(section.shift.hour||section.shift.minute){unit=new Moment$1(context.today,null,context);}else{unit=new Day$1(context.today,null,context);}}}
var str=doc.text('reduced');if(knownWord.hasOwnProperty(str)===true){return knownWord[str](context);}
if(str==='next'&&Object.keys(section.shift).length>0){return knownWord.tomorrow(context);}
return unit;};var _01Today=today;var spacetimeHoliday=createCommonjsModule(function(module,exports){(function(global,factory){module.exports=factory(spacetime);})(commonjsGlobal,function(spacetime){function _interopDefaultLegacy(e){return e&&_typeof(e)==='object'&&'default'in e?e:{'default':e};}
var spacetime__default=_interopDefaultLegacy(spacetime);var jan='january';var feb='february';var mar='march';var apr='april';var may='may';var jun='june';var jul='july';var aug='august';var sep='september';var oct='october';var nov='november';var dec='december';var fixedHolidays={'new years eve':[dec,31],'new years':[jan,1],'new years day':[jan,1],'inauguration day':[jan,20],'australia day':[jan,26],'national freedom day':[feb,1],'groundhog day':[feb,2],'rosa parks day':[feb,4],'valentines day':[feb,14],'saint valentines day':[feb,14],'st valentines day ':[feb,14],'saint patricks day':[mar,17],'st patricks day':[mar,17],'april fools':[apr,1],'april fools day':[apr,1],'emancipation day':[apr,16],'tax day':[apr,15],'labour day':[may,1],'cinco de mayo':[may,5],'national nurses day':[may,6],'harvey milk day':[may,22],'victoria day':[may,24],juneteenth:[jun,19],'canada day':[jul,1],'independence day':[jul,4],'independents day':[jul,4],'bastille day':[jul,14],'purple heart day':[aug,7],'womens equality day':[aug,26],'16 de septiembre':[sep,16],'dieciseis de septiembre':[sep,16],'grito de dolores':[sep,16],halloween:[oct,31],'all hallows eve':[oct,31],'day of the dead':[oct,31],'dia de muertos':[oct,31],'veterans day':[nov,11],'st andrews day':[nov,30],'saint andrews day':[nov,30],'all saints day':[nov,1],'all sts day':[nov,1],'armistice day':[nov,11],'rememberance day':[nov,11],'christmas eve':[dec,24],christmas:[dec,25],xmas:[dec,25],'boxing day':[dec,26],'st stephens day':[dec,26],'saint stephens day':[dec,26],epiphany:[jan,6],'orthodox christmas day':[jan,7],'orthodox new year':[jan,14],'assumption of mary':[aug,15],'all souls day':[nov,2],'feast of the immaculate conception':[dec,8],'feast of our lady of guadalupe':[dec,12],kwanzaa:[dec,26],imbolc:[feb,2],beltaine:[may,1],lughnassadh:[aug,1],samhain:[oct,31]};var fixedDates=function fixedDates(str,normal,year,tz){if(fixedHolidays.hasOwnProperty(str)||fixedHolidays.hasOwnProperty(normal)){var arr=fixedHolidays[str]||fixedHolidays[normal]||[];var s=spacetime__default['default'].now(tz);s=s.year(year);s=s.startOf('year');s=s.month(arr[0]);s=s.date(arr[1]);if(s.isValid()){return s;}}
return null;};var _01FixedDates=fixedDates;var jan$1='january';var feb$1='february';var mar$1='march';var may$1='may';var jun$1='june';var sep$1='september';var oct$1='october';var nov$1='november';var mon='monday';var thurs='thursday';var fri='friday';var sun='sunday';var holidays={'martin luther king day':[3,mon,jan$1],'presidents day':[3,mon,feb$1],'commonwealth day':[2,mon,mar$1],'mothers day':[2,sun,may$1],'fathers day':[3,sun,jun$1],'labor day':[1,mon,sep$1],'columbus day':[2,mon,oct$1],'canadian thanksgiving':[2,mon,oct$1],thanksgiving:[4,thurs,nov$1],'black friday':[4,fri,nov$1]};holidays['turday day']=holidays.thanksgiving;holidays['indigenous peoples day']=holidays['columbus day'];holidays['mlk day']=holidays['martin luther king day'];var calendarHolidays=holidays;var fixedDates$1=function fixedDates(str,normal,year,tz){if(calendarHolidays.hasOwnProperty(str)||calendarHolidays.hasOwnProperty(normal)){var arr=calendarHolidays[str]||calendarHolidays[normal]||[];var s=spacetime__default['default'].now(tz);s=s.year(year);s=s.month(arr[2]);s=s.startOf('month');var month=s.month();s=s.day(arr[1]);if(s.month()!==month){s=s.add(1,'week');}
if(arr[0]>1){s=s.add(arr[0]-1,'week');}
if(s.isValid()){return s;}}
return null;};var _02NthWeekday=fixedDates$1;var dates={easter:0,'ash wednesday':-46,'palm sunday':7,'maundy thursday':-3,'good friday':-2,'holy saturday':-1,'easter saturday':-1,'easter monday':1,'ascension day':39,'whit sunday':49,'whit monday':50,'trinity sunday':65,'corpus christi':60,'mardi gras':-47};dates['easter sunday']=dates.easter;dates['pentecost']=dates['whit sunday'];dates['whitsun']=dates['whit sunday'];var easterHolidays=dates;var calcEaster=function calcEaster(year){var f=Math.floor,G=year%19,C=f(year/100),H=(C-f(C/4)-f((8*C+13)/25)+19*G+15)%30,I=H-f(H/28)*(1-f(29/(H+1))*f((21-G)/11)),J=(year+f(year/4)+I+2-C+f(C/4))%7,L=I-J,month=3+f((L+40)/44),date=L+28-31*f(month/4);month=month===4?'April':'March';return month+' '+date;};var calcEaster_1=calcEaster;var easterDates=function easterDates(str,normal,year,tz){if(easterHolidays.hasOwnProperty(str)||easterHolidays.hasOwnProperty(normal)){var days=easterHolidays[str]||easterHolidays[normal]||[];var date=calcEaster_1(year);if(!date){return null;}
var e=spacetime__default['default'](date,tz);e=e.year(year);var s=e.add(days,'day');if(s.isValid()){return s;}}
return null;};var _03EasterDates=easterDates;var exceptions={spring:[2003,2007,2044,2048,2052,2056,2060,2064,2068,2072,2076,2077,2080,2081,2084,2085,2088,2089,2092,2093,2096,2097],summer:[2021,2016,2020,2024,2028,2032,2036,2040,2041,2044,2045,2048,2049,2052,2053,2056,2057,2060,2061,2064,2065,2068,2069,2070,2072,2073,2074,2076,2077,2078,2080,2081,2082,2084,2085,2086,2088,2089,2090,2092,2093,2094,2096,2097,2098,2099],fall:[2002,2003,2004,2006,2007,2010,2011,2014,2015,2018,2019,2022,2023,2026,2027,2031,2035,2039,2043,2047,2051,2055,2059,2092,2096],winter:[2002,2003,2006,2007,2011,2015,2019,2023,2027,2031,2035,2039,2043,2080,2084,2088,2092,2096]};var winter20th=[2080,2084,2088,2092,2096];var calcSeasons=function calcSeasons(year){var res={spring:'March 20 '+year,summer:'June 21 '+year,fall:'Sept 22 '+year,winter:'Dec 21 '+year};if(exceptions.spring.indexOf(year)!==-1){res.spring='March 19 '+year;}
if(exceptions.summer.indexOf(year)!==-1){res.summer='June 20 '+year;}
if(exceptions.fall.indexOf(year)!==-1){res.fall='Sept 21 '+year;}
if(exceptions.winter.indexOf(year)!==-1){res.winter='Dec 22 '+year;}
if(winter20th.indexOf(year)!==-1){res.winter='Dec 20 '+year;}
return res;};var seasons=calcSeasons;var dates$1={'spring equinox':'spring','summer solistice':'summer','fall equinox':'fall','winter solstice':'winter'};dates$1['march equinox']=dates$1['spring equinox'];dates$1['vernal equinox']=dates$1['spring equinox'];dates$1['ostara']=dates$1['spring equinox'];dates$1['june solstice']=dates$1['summer solistice'];dates$1['litha']=dates$1['summer solistice'];dates$1['autumn equinox']=dates$1['fall equinox'];dates$1['autumnal equinox']=dates$1['fall equinox'];dates$1['september equinox']=dates$1['fall equinox'];dates$1['sept equinox']=dates$1['fall equinox'];dates$1['mabon']=dates$1['fall equinox'];dates$1['december solstice']=dates$1['winter solistice'];dates$1['dec solstice']=dates$1['winter solistice'];dates$1['yule']=dates$1['winter solistice'];var astroHolidays=dates$1;var astroDates=function astroDates(str,normal,year,tz){if(astroHolidays.hasOwnProperty(str)||astroHolidays.hasOwnProperty(normal)){var season=astroHolidays[str]||astroHolidays[normal];var seasons$1=seasons(year);if(!season||!seasons$1||!seasons$1[season]){return null;}
var s=spacetime__default['default'](seasons$1[season],tz);if(s.isValid()){return s;}}
return null;};var _04Astronomical=astroDates;var dates$2={'isra and miraj':'april 13','lailat al-qadr':'june 10','eid al-fitr':'june 15','id al-Fitr':'june 15','eid ul-Fitr':'june 15',ramadan:'may 16','eid al-adha':'sep 22',muharram:'sep 12','prophets birthday':'nov 21'};var lunarHolidays=dates$2;var dayDiff=-10.64;var lunarDates=function lunarDates(str,normal,year,tz){if(lunarHolidays.hasOwnProperty(str)||lunarHolidays.hasOwnProperty(normal)){var date=lunarHolidays[str]||lunarHolidays[normal]||[];if(!date){return null;}
var s=spacetime__default['default'](date+' 2018',tz);var diff=year-2018;var toAdd=diff*dayDiff;s=s.add(toAdd,'day');s=s.startOf('day');s=s.year(year);if(s.isValid()){return s;}}
return null;};var _05LunarDates=lunarDates;var nowYear=spacetime__default['default'].now().year();var spacetimeHoliday=function spacetimeHoliday(str,year,tz){year=year||nowYear;str=str||'';str=String(str);str=str.trim().toLowerCase();str=str.replace(/'s/,'s');var normal=str.replace(/ day$/,'');normal=normal.replace(/^the /,'');normal=normal.replace(/^orthodox /,'');var s=_01FixedDates(str,normal,year,tz);if(s!==null){return s;}
s=_02NthWeekday(str,normal,year,tz);if(s!==null){return s;}
s=_03EasterDates(str,normal,year,tz);if(s!==null){return s;}
s=_04Astronomical(str,normal,year,tz);if(s!==null){return s;}
s=_05LunarDates(str,normal,year,tz);if(s!==null){return s;}
return null;};var src=spacetimeHoliday;return src;});});var Holiday$1=units.Holiday;var parseHoliday=function parseHoliday(doc,context){var unit=null;var m=doc.match('[<holiday>#Holiday+] [<year>#Year?]');var year=context.today.year();if(m.groups('year').found){year=Number(m.groups('year').text('reduced'))||year;}
var str=m.groups('holiday').text('reduced');var s=spacetimeHoliday(str,year,context.timezone);if(s!==null){if(s.isBefore(context.today)&&year===context.today.year()){s=spacetimeHoliday(str,year+1,context.timezone);}
unit=new Holiday$1(s,null,context);}
return unit;};var _02Holidays=parseHoliday;var Week$1=units.Week,WeekEnd$1=units.WeekEnd,AnyMonth$1=units.AnyMonth,AnyQuarter$1=units.AnyQuarter,Year$1=units.Year,Season$1=units.Season,WeekDay$1=units.WeekDay,Day$2=units.Day,Hour$2=units.Hour,Minute$1=units.Minute,Moment$2=units.Moment;var mapping={day:Day$2,hour:Hour$2,evening:Hour$2,second:Moment$2,milliscond:Moment$2,instant:Moment$2,minute:Minute$1,week:Week$1,weekend:WeekEnd$1,month:AnyMonth$1,quarter:AnyQuarter$1,year:Year$1,season:Season$1,yr:Year$1,qtr:AnyQuarter$1,wk:Week$1,sec:Moment$2,hr:Hour$2};var matchStr="^(".concat(Object.keys(mapping).join('|'),")$");var nextLast=function nextLast(doc,context){var m=doc.match(matchStr);if(m.found===true){var str=m.text('reduced');if(mapping.hasOwnProperty(str)){var Model=mapping[str];if(!Model){return null;}
var unit=new Model(null,str,context);return unit;}}
m=doc.match('^#WeekDay$');if(m.found===true){var _str=m.text('reduced');var _unit=new WeekDay$1(_str,null,context);return _unit;}
return null;};var _03NextLast=nextLast;var Quarter$1=units.Quarter,Season$2=units.Season,Year$2=units.Year;var fmtToday=function fmtToday(context){return{date:context.today.date(),month:context.today.month(),year:context.today.year()};};var parseYearly=function parseYearly(doc,context){var m=doc.match('(spring|summer|winter|fall|autumn) [<year>#Year?]');if(m.found){var str=doc.text('reduced');var s=spacetime(str,context.timezone,{today:fmtToday(context)});var unit=new Season$2(s,null,context);if(unit.d.isValid()===true){return unit;}}
m=doc.match('[<q>#FinancialQuarter] [<year>#Year?]');if(m.found){var _str=m.groups('q').text('reduced');var _s=spacetime(_str,context.timezone,{today:fmtToday(context)});if(m.groups('year')){var year=Number(m.groups('year').text())||context.today.year();_s=_s.year(year);}
var _unit=new Quarter$1(_s,null,context);if(_unit.d.isValid()===true){return _unit;}}
m=doc.match('[<q>#Value] quarter (of|in)? [<year>#Year?]');if(m.found){var q=m.groups('q').text('reduced');var _s2=spacetime("q".concat(q),context.timezone,{today:fmtToday(context)});if(m.groups('year')){var _year=Number(m.groups('year').text())||context.today.year();_s2=_s2.year(_year);}
var _unit2=new Quarter$1(_s2,null,context);if(_unit2.d.isValid()===true){return _unit2;}}
m=doc.match('^#Year$');if(m.found){var _str2=doc.text('reduced');var _s3=spacetime(null,context.timezone,{today:fmtToday(context)});_s3=_s3.year(_str2);var _unit3=new Year$2(_s3,null,context);if(_unit3.d.isValid()===true){return _unit3;}}
return null;};var _04Yearly=parseYearly;var Day$3=units.Day,CalendarDate$1=units.CalendarDate,Month$1=units.Month,Moment$3=units.Moment;var parseExplicit=function parseExplicit(doc,context){var impliedYear=context.today.year();var m=doc.match('[<date>#Value] of? [<month>#Month] [<year>#Year]');if(!m.found){m=doc.match('[<month>#Month] the? [<date>#Value] [<year>#Year]');}
if(m.found){var obj={month:m.groups('month').text(),date:m.groups('date').text(),year:m.groups('year').text()||impliedYear};var _unit=new CalendarDate$1(obj,null,context);if(_unit.d.isValid()===true){return _unit;}}
m=doc.match('[<month>#Month] of? [<year>#Year]');if(m.found){var _obj={month:m.groups('month').text(),year:m.groups('year').text()||impliedYear};var _unit2=new Month$1(_obj,null,context);if(_unit2.d.isValid()===true){return _unit2;}}
m=doc.match('[<date>#Value] of? [<month>#Month]');if(!m.found){m=doc.match('[<month>#Month] the? [<date>#Value]');}
if(m.found){var _obj2={month:m.groups('month').text(),date:m.groups('date').text(),year:context.today.year()};var _unit3=new CalendarDate$1(_obj2,null,context);if(_unit3.d.month()<context.today.month()){_obj2.year+=1;_unit3=new CalendarDate$1(_obj2,null,context);}
if(_unit3.d.isValid()===true){return _unit3;}}
if(doc.has('#Month')){var _obj3={month:doc.match('#Month').text(),date:1,year:context.today.year()};var _unit4=new Month$1(_obj3,null,context);if(_unit4.d.month()<context.today.month()){_obj3.year+=1;_unit4=new Month$1(_obj3,null,context);}
if(_unit4.d.isValid()===true){return _unit4;}}
m=doc.match('#WeekDay [<date>#Value]');if(m.found){var _obj4={month:context.today.month(),date:m.groups('date').text(),year:context.today.year()};var _unit5=new CalendarDate$1(_obj4,null,context);if(_unit5.d.isValid()===true){return _unit5;}}
m=doc.match('the [<date>#Value]');if(m.found){var _obj5={month:context.today.month(),date:m.groups('date').text(),year:context.today.year()};var _unit6=new CalendarDate$1(_obj5,null,context);if(_unit6.d.isValid()===true){if(_unit6.d.isBefore(context.today)){_unit6.d=_unit6.d.add(1,'month');}
return _unit6;}}
m=doc.match('/[0-9]{4}-[0-9]{2}-[0-9]{2}t[0-9]{2}:/');if(m.found){var _str=doc.text('reduced');var _unit7=new Moment$3(_str,null,context);if(_unit7.d.isValid()===true){return _unit7;}}
var str=doc.text('reduced');var unit=new Day$3(str,null,context);if(unit.d.isValid()===false){return null;}
return unit;};var _05Explicit=parseExplicit;var Quarter$2=units.Quarter,Season$3=units.Season,Week$2=units.Week,Day$4=units.Day,Hour$3=units.Hour,Minute$2=units.Minute,Month$2=units.Month,WeekEnd$2=units.WeekEnd;var units$1={day:Day$4,week:Week$2,weekend:WeekEnd$2,month:Month$2,quarter:Quarter$2,season:Season$3,hour:Hour$3,minute:Minute$2};var applyCounter=function applyCounter(unit){var counter=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var Unit=units$1[counter.unit];if(!Unit){return unit;}
var d=unit.d;if(counter.dir==='first'||counter.num===0){d=unit.start().d;d=d.startOf(counter.unit);}else if(counter.dir==='last'){d=d.endOf(unit.unit);d=d.startOf(counter.unit);}else if(counter.num){d=d.add(counter.num,counter.unit);}
var u=new Unit(d,null,unit.context);if(u.d.isValid()===true){return u;}
return unit;};var addCounter=applyCounter;var tokens={shift:_01Shift,counter:_02Counter,time:_03Time,relative:_04Relative,section:_05Section,timezone:_06Timezone};var parse={today:_01Today,holiday:_02Holidays,nextLast:_03NextLast,yearly:_04Yearly,explicit:_05Explicit};var transform={counter:addCounter};var parseDate=function parseDate(doc,context){doc.match('[^the] !#Value',0).remove();var shift=tokens.shift(doc);var counter=tokens.counter(doc);var tz=tokens.timezone(doc);var time=tokens.time(doc,context);var section=tokens.section(doc,context);var rel=tokens.relative(doc);if(tz){context=Object.assign({},context,{timezone:tz});var iso=context.today.format('iso-short');context.today=context.today["goto"](context.timezone).set(iso);}
var unit=null;unit=unit||parse.today(doc,context,{shift:shift,time:time,rel:rel});unit=unit||parse.holiday(doc,context);unit=unit||parse.nextLast(doc,context);unit=unit||parse.yearly(doc,context);unit=unit||parse.explicit(doc,context);if(!unit){return null;}
if(shift){unit.applyShift(shift);}
if(rel){unit.applyRel(rel);}
if(section){unit.applySection(section);}
if(time){unit.applyTime(time);}
if(counter&&counter.unit){unit=transform.counter(unit,counter);}
return unit;};var parse_1=parseDate;var punt=function punt(unit,context){unit=unit.applyShift(context.punt);return unit;};var ranges=[{match:'between [<start>*] and [<end>*]',parse:function parse(m,context){var start=m.groups('start');start=parse_1(start,context);var end=m.groups('end');end=parse_1(end,context);if(start&&end){return{start:start,end:end.before()};}
return null;}},{match:'[<from>#Month #Value] (to|through|thru) [<to>#Month #Value] [<year>#Year?]',parse:function parse(m,context){var res=m.groups();var start=res.from;if(res.year){start=start.append(res.year);}
start=parse_1(start,context);if(start){var end=res.to;if(res.year){end=end.append(res.year);}
end=parse_1(end,context);if(start.d.isAfter(end.d)){var tmp=start;start=end;end=tmp;}
return{start:start,end:end.end()};}
return null;}},{match:'[<month>#Month] [<from>#Value] (to|through|thru) [<to>#Value] of? [<year>#Year]',parse:function parse(m,context){var _m$groups=m.groups(),month=_m$groups.month,from=_m$groups.from,to=_m$groups.to,year=_m$groups.year;var year2=year.clone();var start=from.prepend(month.text()).append(year.text());start=parse_1(start,context);if(start){var end=to.prepend(month.text()).append(year2);end=parse_1(end,context);return{start:start,end:end.end()};}
return null;}},{match:'[<from>#Value] (to|through|thru) [<to>#Value of? #Month of? #Year]',parse:function parse(m,context){var to=m.groups('to');to=parse_1(to,context);if(to){var fromDate=m.groups('to');var from=to.clone();from.d=from.d.date(fromDate.text('normal'));return{start:from,end:to.end()};}
return null;}},{match:'[<from>#Value] (to|through|thru) [<to>#Value of? #Month]',parse:function parse(m,context){var to=m.groups('to');to=parse_1(to,context);if(to){var fromDate=m.groups('from');var from=to.clone();from.d=from.d.date(fromDate.text('normal'));return{start:from,end:to.end()};}
return null;}},{match:'[<from>#Month #Value] (to|through|thru) [<to>#Value]',parse:function parse(m,context){var from=m.groups('from');from=parse_1(from,context);if(from){var toDate=m.groups('to');var to=from.clone();to.d=to.d.date(toDate.text('normal'));return{start:from,end:to.end()};}
return null;}},{match:'from? [<from>*] (to|until|upto|through|thru) [<to>*]',parse:function parse(m,context){var from=m.groups('from');var to=m.groups('to');from=parse_1(from,context);to=parse_1(to,context);if(from&&to){return{start:from,end:to.end()};}
return null;}},{match:'^due? (by|before) [*]',group:0,parse:function parse(m,context){var unit=parse_1(m,context);if(unit){var start=new Unit_1(context.today,null,context);if(start.d.isAfter(unit.d)){start=unit.clone().applyShift({weeks:-2});}
var end=unit.clone().applyShift({day:-1});return{start:start,end:end.end()};}
return null;}},{match:'^(on|in|at|@) [*]',group:0,parse:function parse(m,context){var unit=parse_1(m,context);if(unit){return{start:unit,end:unit.clone().end()};}
return null;}},{match:'^(after|following) [*]',group:0,parse:function parse(m,context){var unit=parse_1(m,context);if(unit){unit=unit.after();return{start:unit.clone(),end:punt(unit.clone(),context)};}
return null;}},{match:'^(on|during|in|during) [*]',group:0,parse:function parse(m,context){var unit=parse_1(m,context);if(unit){return{start:unit,end:unit.clone().end()};}
return null;}}];var parseRange=function parseRange(doc,context){for(var i=0;i<ranges.length;i+=1){var fmt=ranges[i];var m=doc.match(fmt.match);if(m.found){if(fmt.group!==undefined){m=m.groups(fmt.group);}
var res=fmt.parse(m,context);if(res!==null){return res;}}}
var unit=parse_1(doc,context);if(unit){return{start:unit,end:unit.clone().end()};}
return{start:null,end:null};};var _02Ranges=parseRange;var normalize$1=function normalize(doc){doc=doc.clone();if(!doc.numbers){console.warn("Compromise: compromise-dates cannot find plugin dependency 'compromise-number'");}else{var num=doc.numbers();num.toNumber();num.toCardinal(false);}
doc.contractions().expand();doc.adverbs().remove();doc.replace('week end','weekend').tag('Date');doc.replace('up to','upto').tag('Date');var m=doc.match('in [a few] #Duration');if(m.found){m.groups('0').replaceWith('2');m.tag('DateShift');}
return doc;};var normalize_1=normalize$1;var getDate=function getDate(doc,context){context=context||{};context.timezone=context.timezone||'ETC/UTC';context.today=spacetime(context.today||null,context.timezone);doc=normalize_1(doc);return _02Ranges(doc,context);};var find=getDate;var arr=[['mon','monday'],['tue','tuesday'],['tues','tuesday'],['wed','wednesday'],['thu','thursday'],['thurs','thursday'],['fri','friday'],['sat','saturday'],['sun','sunday'],['jan','january'],['feb','february'],['mar','march'],['apr','april'],['jun','june'],['jul','july'],['aug','august'],['sep','september'],['sept','september'],['oct','october'],['nov','november'],['dec','december']];arr=arr.map(function(a){return{"short":a[0],"long":a[1]};});var _abbrevs=arr;var methods$1={json:function json(options){var _this=this;var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{terms:false};var res=[];var format=options.format||'iso';this.forEach(function(doc){var json=doc.json(options)[0];var obj=find(doc,_this.context);var start=obj.start?obj.start.format(format):null;var end=obj.end?obj.end.format(format):null;json.date={start:start,end:end};if(start&&end){json.date.duration=obj.start.d.diff(obj.end.d);delete json.date.duration.milliseconds;delete json.date.duration.seconds;}
res.push(json);});if(n!==null){return res[n];}
return res;},format:function format(fmt){var _this2=this;this.forEach(function(doc){var obj=find(doc,_this2.context);var str='';if(obj.start){str=obj.start.format(fmt);if(obj.end){var end=obj.start.format(fmt);if(str!==end){str+=' to '+end;}}
doc.replaceWith(str,{keepTags:true,keepCase:false});}});return this;},toLongForm:function toLongForm(){var _this3=this;_abbrevs.forEach(function(a){_this3.replace(a["short"],a["long"],true);});return this;},toShortForm:function toShortForm(){var _this4=this;_abbrevs.forEach(function(a){_this4.replace(a["long"],a["short"],true);});return this;}};var opts={punt:{weeks:2}};var addMethods=function addMethods(Doc,world){world.addTags(_tags);world.addWords(words);world.postProcess(_01Tagger);var Dates=function(_Doc){_inherits(Dates,_Doc);var _super=_createSuper(Dates);function Dates(list,from,w){var _this;_classCallCheck(this,Dates);_this=_super.call(this,list,from,w);_this.context=opts;return _this;}
return Dates;}(Doc);Object.assign(Dates.prototype,methods$1);Doc.prototype.dates=function(n){var context={};if(n&&_typeof(n)==='object'){context=n;n=null;}
context=Object.assign({},context,opts);var dates=this.match('#Date+');if(typeof n==='number'){dates=dates.get(n);}
var d=new Dates(dates.list,this,this.world);if(context.today){context.today=spacetime(context.today,context.timezone);}
d.context=context;return d;};};var src=addMethods;return src;})));};BundleModuleCode['nlp/compromise-numbers']=function(module,exports){(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.compromiseNumbers=factory());}(this,(function(){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}
subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}
function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}
function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}
function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}
function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
function _possibleConstructorReturn(self,call){if(call&&(typeof call==="object"||typeof call==="function")){return call;}
return _assertThisInitialized(self);}
function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}
return _possibleConstructorReturn(this,result);};}
var tens='twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|fourty';var teens='eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen';var findNumbers=function findNumbers(doc,n){var match=doc.match('#Value+');if(match.has('#NumericValue #NumericValue')){if(match.has('#Value @hasComma #Value')){match.splitAfter('@hasComma');}else if(match.has('#NumericValue #Fraction')){match.splitAfter('#NumericValue #Fraction');}else{match=match.splitAfter('#NumericValue');}}
if(match.has('#Value #Value #Value')&&!match.has('#Multiple')){if(match.has('('+tens+') #Cardinal #Cardinal')){match=match.splitAfter('('+tens+') #Cardinal');}}
if(match.has('#Value #Value')){if(match.has('#NumericValue #NumericValue')){match=match.splitOn('#Year');}
if(match.has('('+tens+') ('+teens+')')){match=match.splitAfter('('+tens+')');}
var _double=match.match('#Cardinal #Cardinal');if(_double.found&&!match.has('(point|decimal)')){if(!_double.has('#Cardinal (#Multiple|point|decimal)')){if(!_double.has('('+tens+') #Cardinal')&&!_double.has('#Multiple #Value')){_double.terms().forEach(function(d){match=match.splitOn(d);});}}}
if(match.match('#Ordinal #Ordinal').match('#TextValue').found&&!match.has('#Multiple')){if(!match.has('('+tens+') #Ordinal')){match=match.splitAfter('#Ordinal');}}
if(match.has('#Ordinal #Cardinal')){match=match.splitBefore('#Cardinal+');}
if(match.has('#TextValue #NumericValue')&&!match.has('('+tens+'|#Multiple)')){match=match.splitBefore('#NumericValue+');}}
if(match.has('#NumberRange')){match=match.splitAfter('#NumberRange');}
if(typeof n==='number'){match=match.get(n);}
return match;};var find=findNumbers;var findModifiers=function findModifiers(str){var mults=[{reg:/^(minus|negative)[\s\-]/i,mult:-1},{reg:/^(a\s)?half[\s\-](of\s)?/i,mult:0.5}];for(var i=0;i<mults.length;i++){if(mults[i].reg.test(str)===true){return{amount:mults[i].mult,str:str.replace(mults[i].reg,'')};}}
return{amount:1,str:str};};var findModifiers_1=findModifiers;var data={ones:{zeroth:0,first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9},teens:{tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,ten:10,eleven:11,twelve:12,thirteen:13,fourteen:14,fifteen:15,sixteen:16,seventeen:17,eighteen:18,nineteen:19},tens:{twentieth:20,thirtieth:30,fortieth:40,fourtieth:40,fiftieth:50,sixtieth:60,seventieth:70,eightieth:80,ninetieth:90,twenty:20,thirty:30,forty:40,fourty:40,fifty:50,sixty:60,seventy:70,eighty:80,ninety:90},multiples:{hundredth:100,thousandth:1000,millionth:1e6,billionth:1e9,trillionth:1e12,quadrillionth:1e15,quintillionth:1e18,sextillionth:1e21,septillionth:1e24,hundred:100,thousand:1000,million:1e6,billion:1e9,trillion:1e12,quadrillion:1e15,quintillion:1e18,sextillion:1e21,septillion:1e24,grand:1000}};var isValid=function isValid(w,has){if(data.ones.hasOwnProperty(w)){if(has.ones||has.teens){return false;}}else if(data.teens.hasOwnProperty(w)){if(has.ones||has.teens||has.tens){return false;}}else if(data.tens.hasOwnProperty(w)){if(has.ones||has.teens||has.tens){return false;}}
return true;};var validate=isValid;var parseDecimals=function parseDecimals(arr){var str='0.';for(var i=0;i<arr.length;i++){var w=arr[i];if(data.ones.hasOwnProperty(w)===true){str+=data.ones[w];}else if(data.teens.hasOwnProperty(w)===true){str+=data.teens[w];}else if(data.tens.hasOwnProperty(w)===true){str+=data.tens[w];}else if(/^[0-9]$/.test(w)===true){str+=w;}else{return 0;}}
return parseFloat(str);};var parseDecimals_1=parseDecimals;var parseNumeric=function parseNumeric(str){str=str.replace(/1st$/,'1');str=str.replace(/2nd$/,'2');str=str.replace(/3rd$/,'3');str=str.replace(/([4567890])r?th$/,'$1');str=str.replace(/^[$€¥£¢]/,'');str=str.replace(/[%$€¥£¢]$/,'');str=str.replace(/,/g,'');str=str.replace(/([0-9])([a-z\u00C0-\u00FF]{1,2})$/,'$1');return str;};var parseNumeric_1=parseNumeric;var improperFraction=/^([0-9,\. ]+)\/([0-9,\. ]+)$/;var casualForms={'a couple':2,'a dozen':12,'two dozen':24,zero:0};var section_sum=function section_sum(obj){return Object.keys(obj).reduce(function(sum,k){sum+=obj[k];return sum;},0);};var parse=function parse(str){if(casualForms.hasOwnProperty(str)===true){return casualForms[str];}
if(str==='a'||str==='an'){return 1;}
var modifier=findModifiers_1(str);str=modifier.str;var last_mult=null;var has={};var sum=0;var isNegative=false;var terms=str.split(/[ -]/);for(var i=0;i<terms.length;i++){var w=terms[i];w=parseNumeric_1(w);if(!w||w==='and'){continue;}
if(w==='-'||w==='negative'){isNegative=true;continue;}
if(w.charAt(0)==='-'){isNegative=true;w=w.substr(1);}
if(w==='point'){sum+=section_sum(has);sum+=parseDecimals_1(terms.slice(i+1,terms.length));sum*=modifier.amount;return sum;}
var fm=w.match(improperFraction);if(fm){var num=parseFloat(fm[1].replace(/[, ]/g,''));var denom=parseFloat(fm[2].replace(/[, ]/g,''));if(denom){sum+=num/denom||0;}
continue;}
if(validate(w,has)===false){return null;}
if(/^[0-9\.]+$/.test(w)){has['ones']=parseFloat(w);}else if(data.ones.hasOwnProperty(w)===true){has['ones']=data.ones[w];}else if(data.teens.hasOwnProperty(w)===true){has['teens']=data.teens[w];}else if(data.tens.hasOwnProperty(w)===true){has['tens']=data.tens[w];}else if(data.multiples.hasOwnProperty(w)===true){var mult=data.multiples[w];if(mult===last_mult){return null;}
if(mult===100&&terms[i+1]!==undefined){var w2=terms[i+1];if(data.multiples[w2]){mult*=data.multiples[w2];i+=1;}}
if(last_mult===null||mult<last_mult){sum+=(section_sum(has)||1)*mult;last_mult=mult;has={};}else{sum+=section_sum(has);last_mult=mult;sum=(sum||1)*mult;has={};}}}
sum+=section_sum(has);sum*=modifier.amount;sum*=isNegative?-1:1;if(sum===0&&Object.keys(has).length===0){return null;}
return sum;};var toNumber=parse;var parseNumeric$1=function parseNumeric(str,p){str=str.replace(/,/g,'');var arr=str.split(/^([^0-9]*)([0-9.,]*)([^0-9]*)$/);if(arr&&arr[2]&&p.terms().length<2){var num=parseFloat(arr[2]||str);if(typeof num!=='number'){num=null;}
var suffix=arr[3]||'';if(suffix==='st'||suffix==='nd'||suffix==='rd'||suffix==='th'){suffix='';}
if(suffix==='m'||suffix==='M'){num*=1000000;suffix='';}
if(suffix==='k'||suffix==='k'){num*=1000;suffix='';}
return{prefix:arr[1]||'',num:num,suffix:suffix};}
return null;};var parseNumber=function parseNumber(p){var str=p.text('reduced');var hasComma=/[0-9],[0-9]/.test(p.text('text'));var res=parseNumeric$1(str,p);if(res!==null){res.hasComma=hasComma;return res;}
var num=toNumber(str);return{hasComma:hasComma,prefix:'',num:num,suffix:''};};var parse$1=parseNumber;var agreeUnits=function agreeUnits(agree,val,obj){if(agree===false){return;}
var unit=val.lookAhead('^(#Unit|#Noun)');if(unit.has('(#Address|#Money|#Percent)')||val.has('#Ordinal')){return;}
if(obj.num===1){unit.nouns().toSingular();}else if(unit.has('#Singular')){unit.nouns().toPlural();}};var _agreeUnits=agreeUnits;var numToString=function numToString(n){if(n<1000000){return String(n);}
var str;if(typeof n==='number'){str=n.toFixed(0);}else{str=n;}
if(str.indexOf('e+')===-1){return str;}
return str.replace('.','').split('e+').reduce(function(p,b){return p+Array(b-p.length+2).join(0);});};var _toString=numToString;var tens_mapping=[['ninety',90],['eighty',80],['seventy',70],['sixty',60],['fifty',50],['forty',40],['thirty',30],['twenty',20]];var ones_mapping=['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];var sequence=[[1e24,'septillion'],[1e20,'hundred sextillion'],[1e21,'sextillion'],[1e20,'hundred quintillion'],[1e18,'quintillion'],[1e17,'hundred quadrillion'],[1e15,'quadrillion'],[1e14,'hundred trillion'],[1e12,'trillion'],[1e11,'hundred billion'],[1e9,'billion'],[1e8,'hundred million'],[1e6,'million'],[100000,'hundred thousand'],[1000,'thousand'],[100,'hundred'],[1,'one']];var breakdown_magnitudes=function breakdown_magnitudes(num){var working=num;var have=[];sequence.forEach(function(a){if(num>=a[0]){var howmany=Math.floor(working/a[0]);working-=howmany*a[0];if(howmany){have.push({unit:a[1],count:howmany});}}});return have;};var breakdown_hundred=function breakdown_hundred(num){var arr=[];if(num>100){return arr;}
for(var i=0;i<tens_mapping.length;i++){if(num>=tens_mapping[i][1]){num-=tens_mapping[i][1];arr.push(tens_mapping[i][0]);}}
if(ones_mapping[num]){arr.push(ones_mapping[num]);}
return arr;};var handle_decimal=function handle_decimal(num){var names=['zero','one','two','three','four','five','six','seven','eight','nine'];var arr=[];var str=_toString(num);var decimal=str.match(/\.([0-9]+)/);if(!decimal||!decimal[0]){return arr;}
arr.push('point');var decimals=decimal[0].split('');for(var i=0;i<decimals.length;i++){arr.push(names[decimals[i]]);}
return arr;};var to_text=function to_text(num){if(num===0||num==='0'){return'zero';}
if(num>1e21){num=_toString(num);}
var arr=[];if(num<0){arr.push('minus');num=Math.abs(num);}
var units=breakdown_magnitudes(num);for(var i=0;i<units.length;i++){var unit_name=units[i].unit;if(unit_name==='one'){unit_name='';if(arr.length>1){arr.push('and');}}
arr=arr.concat(breakdown_hundred(units[i].count));arr.push(unit_name);}
arr=arr.concat(handle_decimal(num));arr=arr.filter(function(s){return s;});if(arr.length===0){arr[0]='';}
return arr.join(' ');};var toText=to_text;var numOrdinal=function numOrdinal(num){if(!num&&num!==0){return null;}
var tens=num%100;if(tens>10&&tens<20){return String(num)+'th';}
var mapping={0:'th',1:'st',2:'nd',3:'rd'};var str=_toString(num);var last=str.slice(str.length-1,str.length);if(mapping[last]){str+=mapping[last];}else{str+='th';}
return str;};var numOrdinal_1=numOrdinal;var irregulars={one:'first',two:'second',three:'third',five:'fifth',eight:'eighth',nine:'ninth',twelve:'twelfth',twenty:'twentieth',thirty:'thirtieth',forty:'fortieth',fourty:'fourtieth',fifty:'fiftieth',sixty:'sixtieth',seventy:'seventieth',eighty:'eightieth',ninety:'ninetieth'};var textOrdinal=function textOrdinal(num){var words=toText(num).split(' ');var last=words[words.length-1];if(irregulars.hasOwnProperty(last)){words[words.length-1]=irregulars[last];}else{words[words.length-1]=last.replace(/y$/,'i')+'th';}
return words.join(' ');};var textOrdinal_1=textOrdinal;var prefixes={'¢':'cents',$:'dollars','£':'pounds','¥':'yen','€':'euros','₡':'colón','฿':'baht','₭':'kip','₩':'won','₹':'rupees','₽':'ruble','₺':'liras'};var suffixes={'%':'percent',s:'seconds',cm:'centimetres',km:'kilometres'};var _symbols={prefixes:prefixes,suffixes:suffixes};var prefixes$1=_symbols.prefixes;var suffixes$1=_symbols.suffixes;var isCurrency={usd:true,eur:true,jpy:true,gbp:true,cad:true,aud:true,chf:true,cny:true,hkd:true,nzd:true,kr:true,rub:true};var prefixToText=function prefixToText(obj){if(prefixes$1.hasOwnProperty(obj.prefix)){obj.suffix+=prefixes$1[obj.prefix];obj.prefix='';}
if(suffixes$1.hasOwnProperty(obj.suffix)){obj.suffix=suffixes$1[obj.suffix];}
if(isCurrency.hasOwnProperty(obj.suffix)){obj.suffix=obj.suffix.toUpperCase();}
if(obj.suffix){obj.suffix=' '+obj.suffix;}
return obj;};var makeNumber=function makeNumber(obj,isText,isOrdinal){var num=String(obj.num);if(isText){obj=prefixToText(obj);if(isOrdinal){num=textOrdinal_1(num);return"".concat(obj.prefix||'').concat(num).concat(obj.suffix||'');}
num=toText(num);return"".concat(obj.prefix||'').concat(num).concat(obj.suffix||'');}
if(isOrdinal){num=numOrdinal_1(num);obj=prefixToText(obj);return"".concat(obj.prefix||'').concat(num).concat(obj.suffix||'');}
if(obj.hasComma===true){num=obj.num.toLocaleString();}
num=_toString(num);return"".concat(obj.prefix||'').concat(num).concat(obj.suffix||'');};var makeNumber_1=makeNumber;var methods={json:function json(options){var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{text:true,normal:true,trim:true,terms:true};var res=[];this.forEach(function(doc){var json=doc.json(options)[0];var obj=parse$1(doc);json.prefix=obj.prefix;json.number=obj.num;json.suffix=obj.suffix;json.cardinal=makeNumber_1(obj,false,false);json.ordinal=makeNumber_1(obj,false,true);json.textCardinal=makeNumber_1(obj,true,false);json.textOrdinal=makeNumber_1(obj,true,true);res.push(json);});if(n!==null){return res[n];}
return res;},units:function units(){var m=this.lookAhead('(#Unit|#Noun)+');m=m.splitAfter('@hasComma').first();m=m.not('#Pronoun');return m.first();},isOrdinal:function isOrdinal(){return this["if"]('#Ordinal');},isCardinal:function isCardinal(){return this["if"]('#Cardinal');},toNumber:function toNumber(){this.forEach(function(val){var obj=parse$1(val);if(obj.num===null){return;}
var str=makeNumber_1(obj,false,val.has('#Ordinal'));val.replaceWith(str,true);val.tag('NumericValue');});return this;},toLocaleString:function toLocaleString(){this.forEach(function(val){var obj=parse$1(val);if(obj.num===null){return;}
obj.num=obj.num.toLocaleString();var str=makeNumber_1(obj,false,val.has('#Ordinal'));val.replaceWith(str,true);});return this;},toText:function toText(){this.forEach(function(val){var obj=parse$1(val);if(obj.num===null){return;}
var str=makeNumber_1(obj,true,val.has('#Ordinal'));val.replaceWith(str,true);val.tag('TextValue');});return this;},toCardinal:function toCardinal(agree){var m=this["if"]('#Ordinal');m.forEach(function(val){var obj=parse$1(val);if(obj.num===null){return;}
var str=makeNumber_1(obj,val.has('#TextValue'),false);if(val.has('#NumberRange')){var t=val.termList()[0];if(t.text&&t.post===''){t.post=' ';}}
val.replaceWith(str,true);val.tag('Cardinal');_agreeUnits(agree,val,obj);});return this;},toOrdinal:function toOrdinal(){var _this=this;var m=this["if"]('#Cardinal');m.forEach(function(val){var obj=parse$1(val);if(obj.num===null){return;}
var str=makeNumber_1(obj,val.has('#TextValue'),true);if(val.has('#NumberRange')){var t=val.termList()[0];if(t.text&&t.post===''){t.post=' ';}}
val.replaceWith(str,true);val.tag('Ordinal');var unit=_this.lookAhead('^#Plural');if(unit.found){unit.nouns().toSingular();}});return this;},isEqual:function isEqual(n){return this.filter(function(val){var num=parse$1(val).num;return num===n;});},greaterThan:function greaterThan(n){return this.filter(function(val){var num=parse$1(val).num;return num>n;});},lessThan:function lessThan(n){return this.filter(function(val){var num=parse$1(val).num;return num<n;});},between:function between(min,max){return this.filter(function(val){var num=parse$1(val).num;return num>min&&num<max;});},set:function set(n,agree){if(n===undefined){return this;}
if(typeof n==='string'){n=toNumber(n);}
this.forEach(function(val){var obj=parse$1(val);obj.num=n;if(obj.num===null){return;}
var str=makeNumber_1(obj,val.has('#TextValue'),val.has('#Ordinal'));val=val.not('#Currency');val.replaceWith(str,true);_agreeUnits(agree,val,obj);});return this;},add:function add(n,agree){if(!n){return this;}
if(typeof n==='string'){n=toNumber(n);}
this.forEach(function(val){var obj=parse$1(val);if(obj.num===null){return;}
obj.num+=n;var str=makeNumber_1(obj,val.has('#TextValue'),val.has('#Ordinal'));val=val.not('#Currency');val.replaceWith(str,true);_agreeUnits(agree,val,obj);});return this;},subtract:function subtract(n,agree){return this.add(n* -1,agree);},increment:function increment(agree){this.add(1,agree);return this;},decrement:function decrement(agree){this.add(-1,agree);return this;},romanNumerals:function romanNumerals(n){var m=this.match('#RomanNumeral').numbers();if(typeof n==='number'){m=m.get(n);}
return m;},normalize:function normalize(){var keep={'%':true};this.forEach(function(val){var obj=parse$1(val);if(obj.num!==null&&obj.suffix&&keep[obj.suffix]!==true){var prefix=obj.prefix||'';val=val.replaceWith(prefix+obj.num+' '+obj.suffix);return;}});return this;},get:function get(n){var arr=[];this.forEach(function(doc){arr.push(parse$1(doc).num);});if(n!==undefined){return arr[n];}
return arr;}};methods.toNice=methods.toLocaleString;methods.isBetween=methods.between;methods.minus=methods.subtract;methods.plus=methods.add;methods.equals=methods.isEqual;var methods_1=methods;var currencies=[{dem:'american',name:'dollar',iso:'usd',sub:'cent',sym:['$','US$','U$']},{name:'euro',iso:'eur',sub:'cent',sym:['€']},{dem:'british',name:'pound',iso:'gbp',sub:'penny',alias:{sterling:true},sym:['£']},{name:'renminbi',iso:'cny',sub:'yuán',plural:'yuán',alias:{yuan:true},sym:['元']},{dem:'japanese',name:'yen',iso:'jpy',sub:'sen',sym:['¥','円','圓']},{dem:'swedish',name:'krona',iso:'sek',sub:'öre',alias:{ore:true,kronor:true},sym:['kr']},{dem:'estonian',name:'kroon',iso:'eek',sub:'sent',sym:['kr']},{dem:'norwegian',name:'krone',iso:'nok',sub:'øre',sym:['kr']},{dem:'icelandic',name:'króna',iso:'isk',sym:['kr']},{dem:'danish',name:'krone',iso:'dkk',sub:'øre',sym:['kr.']},{dem:'zambian',name:'kwacha',iso:'zmw',sub:'ngwee',sym:['K']},{dem:'malawian',name:'kwacha',iso:'mwk',sub:'tambala',sym:['K']},{dem:'greek',name:'drachma',iso:'grd',sub:'leptοn',sym:['Δρχ.','Δρ.','₯']},{dem:'eastern caribbean',name:'dollar',iso:'xcd',sub:'cent',sym:['$']},{dem:'finnish',name:'markka',iso:'fim',sub:'penni',sym:['mk']},{dem:'polish',name:'złoty',iso:'pln',sub:'grosz',sym:['zł']},{dem:'slovenian',name:'tolar',iso:'sit',sub:'stotin',sym:[]},{dem:'australian',name:'dollar',iso:'aud',sub:'cent',sym:['$','A$','AU$']},{dem:'deutsche',name:'mark',iso:'dem',sub:'pfennig',sym:['DM']},{dem:'thai',name:'baht',iso:'thb',sub:'satang',sym:['฿']},{dem:'canadian',name:'dollar',iso:'cad',sub:'cent',sym:['$','Can$','C$','CA$','CAD']},{dem:'mexican',name:'peso',iso:'mxn',sub:'centavo',sym:['$','Mex$']},{dem:'spanish',name:'peseta',iso:'esp',sub:'céntimo',sym:['Pta']},{dem:'new zealand',name:'dollar',iso:'nzd',sub:'cent',sym:['$','NZ$']},{dem:'chilean',name:'peso',iso:'clp',sub:'Centavo',sym:['Cifrão','$']},{dem:'nigerian',name:'naira',iso:'ngn',sub:'kobo',sym:['₦']},{dem:'austrian',name:'schilling',iso:'ats',sub:'groschen',sym:['S','öS']},{dem:'guatemalan',name:'quetzal',iso:'gtq',sub:'centavo',sym:['Q']},{dem:'philippine',name:'peso',iso:'php',sub:'sentimo',sym:['₱']},{dem:'hungarian',name:'forint',iso:'huf',sub:'fillér',sym:['Ft']},{dem:'russian',name:'ruble',iso:'rub',sub:'kopeyka',sym:['₽','руб','р.']},{dem:'kuwaiti',name:'dinar',iso:'kwd',sub:'fils',sym:['د.ك','KD']},{dem:'israeli',name:'new shekel',iso:'ils',sub:'agora',sym:['₪']},{dem:'latvian',name:'lats',iso:'lvl',sub:'santīms',sym:['Ls']},{dem:'kazakhstani',name:'tenge',iso:'kzt',sub:'tıyn',sym:['₸']},{dem:'iraqi',name:'dinar',iso:'iqd',sub:'fils',sym:['د.ع']},{dem:'bahamian',name:'dollar',iso:'bsd',sub:'cent',sym:['$','B$']},{dem:'seychellois',name:'rupee',iso:'scr',sub:'cent',sym:['SCR','SR']},{dem:'albanian',name:'lek',iso:'all',sub:'qindarkë',sym:['L']},{dem:'bulgarian',name:'lev',iso:'bgn',sub:'stotinka',sym:['лв.']},{dem:'irish',name:'pound',iso:'iep',sym:['£','IR£']},{name:'cfp franc',iso:'xpf',sym:['f']},{dem:'south african',name:'rand',iso:'zar',sub:'cent',sym:['R']},{dem:'south korean',name:'won',iso:'krw',sub:'jeon',plural:'won',sym:['₩']},{dem:'north korean',name:'won',iso:'kpw',sub:'chon',plural:'won',sym:['₩']},{dem:'portuguese',name:'escudo',iso:'pte',sub:'centavo',sym:[]},{dem:'ghanaian',name:'cedi',iso:'ghs',sub:'pesewa',sym:['GH₵']},{dem:'hong kong',name:'dollar',iso:'hkd',sub:'毫',sym:['$']},{dem:'new taiwan',name:'dollar',iso:'twd',sub:'dime',sym:['NT$']},{dem:'east german',name:'mark',iso:'ddm',sub:'pfennig',sym:['M']},{dem:'namibian',name:'dollar',iso:'nad',sub:'cent',sym:['$']},{dem:'malaysian',name:'ringgit',iso:'myr',sub:'sen',sym:['RM']},{dem:'swiss',name:'franc',iso:'chf',sym:['Rp.']},{dem:'panamanian',name:'balboa',iso:'pab',sub:'centésimo',sym:['B/.']},{dem:'indonesian',name:'rupiah',iso:'idr',sub:'sen',sym:['Rp']},{dem:'brunei',name:'dollar',iso:'bnd',sub:'sen',sym:['$','B$']},{dem:'venezuelan',name:'bolívar',iso:'vef',sub:'céntimo',sym:['Bs.F','Bs.']},{dem:'macedonian',name:'denar',iso:'mkd',sub:'deni
if(str===o.iso){return o;}
if(str===o.sub){return o;}
if(str===o.name){return o;}
if(o.alias&&o.alias[str]===true){return o;}
return false;});};var getBySymbol=function getBySymbol(obj){if(obj.suffix&&symbols.hasOwnProperty(obj.suffix)){return currencies.find(function(o){return o.iso===symbols[obj.suffix];});}
if(obj.prefix&&symbols.hasOwnProperty(obj.prefix)){return currencies.find(function(o){return o.iso===symbols[obj.prefix];});}
return null;};var parseMoney=function parseMoney(doc){var res=parse$1(doc);var found=getBySymbol(res)||getNamedCurrency(doc)||{};var sym='';if(found&&found.sym){sym=found.sym[0];}
return{num:res.num,iso:found.iso,demonym:found.dem,currency:found.name,plural:found.plural,symbol:sym};};var parse$2=parseMoney;var titleCase=function titleCase(){var str=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return str.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase();});};var moneyMethods={currency:function currency(n){var arr=[];this.forEach(function(doc){var found=parse$2(doc);if(found){arr.push(found);}});if(typeof n==='number'){return arr[n];}
return arr;},json:function json(options){var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{text:true,normal:true,trim:true,terms:true};var res=[];this.forEach(function(doc){var json=doc.json(options)[0];var obj=parse$2(doc);json.number=obj.num;if(obj.iso){json.iso=obj.iso.toUpperCase();json.symbol=obj.symbol;json.currency=titleCase(obj.demonym)+' '+titleCase(obj.currency);}
json.textFmt=makeNumber_1(obj,true,false);if(obj.currency){var str=obj.currency;if(obj.num!==1){str=obj.plural||str+'s';}
json.textFmt+=' '+str;}
res.push(json);});if(n!==null){return res[n]||{};}
return res;}};var methods$1=moneyMethods;var endS=/s$/;var slashForm=function slashForm(m){var str=m.text('reduced');var found=str.match(/^([-+]?[0-9]+)\/([-+]?[0-9]+)(st|nd|rd|th)?s?$/);if(found&&found[1]&&found[0]){return{numerator:Number(found[1]),denominator:Number(found[2])};}
return null;};var textForm1=function textForm1(m){var found=m.match('[<num>#Value+] out of every? [<den>#Value+]');if(found.found!==true){return null;}
var _found$groups=found.groups(),num=_found$groups.num,den=_found$groups.den;num=num.numbers().get(0);den=den.numbers().get(0);if(typeof num==='number'&&typeof den==='number'){return{numerator:num,denominator:den};}
return null;};var textForm2=function textForm2(m){var found=m.match('[<num>(#Cardinal|a)+] [<den>#Ordinal+]');if(found.found!==true){return null;}
var _found$groups2=found.groups(),num=_found$groups2.num,den=_found$groups2.den;if(num.has('a')){num=1;}else{num=num.numbers().get(0);}
var str=den.text('reduced');if(endS.test(str)){str=str.replace(endS,'');den.replaceWith(str);}
if(den.has('half')){den=2;}else{den=den.numbers().get(0);}
if(typeof num==='number'&&typeof den==='number'){return{numerator:num,denominator:den};}
return null;};var parseFraction=function parseFraction(m){return slashForm(m)||textForm1(m)||textForm2(m)||null;};var parse$3=parseFraction;var methods$2={json:function json(options){var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{text:true,normal:true,trim:true,terms:true};var res=[];this.forEach(function(m){var json=m.json(options)[0];var found=parse$3(m)||{};json.numerator=found.numerator;json.denominator=found.denominator;res.push(json);});if(n!==null){return res[n]||{};}
return res;},normalize:function normalize(){var _this=this;this.forEach(function(m){var found=parse$3(m);if(found&&typeof found.numerator==='number'&&typeof found.denominator==='number'){var str="".concat(found.numerator,"/").concat(found.denominator);_this.replace(m,str);}});return this;}};var methods_1$1=methods$2;var here='number-tag';var multiples='(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)';var ordinals=['half','third','fourth','quarter','fifth','sixth','seventh','eighth','ninth','tenth','hundredth','thousandth','millionth'];var len=ordinals.length;for(var i=0;i<len;i+=1){ordinals.push(ordinals[i]+'s');}
ordinals="(".concat(ordinals.join('|'),")");var tagger=function tagger(doc){doc.match(multiples).tag('#Multiple',here);doc.match('the [/[0-9]+s$/]').tag('#Plural',here);doc.match('half a? #Value').tag('Value','half-a-value');doc.match('#Value and a (half|quarter)').tag('Value','value-and-a-half');doc.match('#Money and #Money #Currency?').tag('Money','money-and-money');doc.match('#Money').not('#TextValue').match('/\\.[0-9]{3}$/').unTag('#Money','three-decimal money');doc.ifNo('#Value').match('#Currency #Verb').unTag('Currency','no-currency');doc.match('#Value #Currency [and] #Value (cents|ore|centavos|sens)',0).tag('Money',here);var m=doc.match('[<num>#Value] [<currency>(mark|rand|won|rub|ore)]');m.group('num').tag('Money',here);m.group('currency').tag('Currency',here);doc.match('#Cardinal+ out of every? #Cardinal').tag('Fraction',here);m=doc.match("[(#Cardinal|a) ".concat(ordinals,"] of (a|an|the)"),0).tag('Fraction',here);m.match('.$').tag('Ordinal','plural-ordinal');};var tagger_1=tagger;var tags={Fraction:{isA:['Value','NumericValue']},Multiple:{isA:'Value'}};var ambig={mark:true,sucre:true,leone:true,afghani:true,rand:true,"try":true,mop:true,won:true,all:true,rub:true,eek:true,sit:true,bam:true,npr:true,leu:true};var lex={kronor:'Currency'};currencies.forEach(function(o){if(o.iso&&!ambig[o.iso]){lex[o.iso]=['Acronym','Currency'];}
var name=o.name;if(name&&!ambig[name]){lex[name]='Currency';lex[name+'s']='Currency';}
if(o.dem){var dem=o.dem;lex["".concat(dem," ").concat(name)]='Currency';lex["".concat(dem," ").concat(name,"s")]='Currency';}});var lexicon=lex;var plugin=function plugin(Doc,world){world.addWords(lexicon);world.addTags(tags);world.postProcess(tagger_1);var Numbers=function(_Doc){_inherits(Numbers,_Doc);var _super=_createSuper(Numbers);function Numbers(){_classCallCheck(this,Numbers);return _super.apply(this,arguments);}
return Numbers;}(Doc);Object.assign(Numbers.prototype,methods_1);var Money=function(_Numbers){_inherits(Money,_Numbers);var _super2=_createSuper(Money);function Money(){_classCallCheck(this,Money);return _super2.apply(this,arguments);}
return Money;}(Numbers);Object.assign(Money.prototype,methods$1);var Fraction=function(_Numbers2){_inherits(Fraction,_Numbers2);var _super3=_createSuper(Fraction);function Fraction(){_classCallCheck(this,Fraction);return _super3.apply(this,arguments);}
return Fraction;}(Numbers);Object.assign(Fraction.prototype,methods_1$1);var docMethods={numbers:function numbers(n){var m=find(this,n);return new Numbers(m.list,this,this.world);},percentages:function percentages(n){var m=this.match('#Percent+');m=m.concat(this.match('[#Cardinal] percent',0));if(typeof n==='number'){m=m.eq(n);}
return new Numbers(m.list,this,this.world);},fractions:function fractions(n){var m=this.match('#Fraction+');if(typeof n==='number'){m=m.eq(n);}
return new Fraction(m.list,this,this.world);},money:function money(){var m=this.splitOn('(#Money|#Currency)+');m=m["if"]('#Money')["if"]('#Value');return new Money(m.list,this,this.world);}};docMethods.values=docMethods.numbers;docMethods.percents=docMethods.percentages;Object.assign(Doc.prototype,docMethods);return Doc;};var src=plugin;return src;})));};BundleModuleCode['nlp/compromise-sentences']=function(module,exports){(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.compromiseSentences=factory());}(this,(function(){'use strict';function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}
subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}
function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}
function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}
function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}
function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
function _possibleConstructorReturn(self,call){if(call&&(typeof call==="object"||typeof call==="function")){return call;}
return _assertThisInitialized(self);}
function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}
return _possibleConstructorReturn(this,result);};}
var tags={NounPhrase:{notA:['VerbPhrase','AdjectivePhrase'],color:'blue'},VerbPhrase:{notA:['AdjectivePhrase','NounPhrase'],color:'green'},AdjectivePhrase:{notA:['VerbPhrase','NounPhrase'],color:'magenta'},Subordinate:{notA:[]}};var tagger=function tagger(doc){doc.match('#Noun').tag('NounPhrase');doc.match('#Verb').tag('VerbPhrase');doc.match('(this|that|those|these)').tag('NounPhrase');doc.match('#Adjective+ #NounPhrase').tagSafe('NounPhrase');doc.match('#NounPhrase #Adjective+').tagSafe('NounPhrase');doc.match('#Value #NounPhrase').tag('NounPhrase');doc.match('#Determiner #NounPhrase').tag('NounPhrase');doc.match('#Determiner #Adverb+? #Adjective+ #NounPhrase').tag('NounPhrase');doc.match('(many|most|all|one|some|plenty) of #NounPhrase').tag('NounPhrase');doc.match('such a #NounPhrase').tag('NounPhrase');doc.match('#VerbPhrase #Adverb+').tagSafe('VerbPhrase');doc.match('#Adverb+ #VerbPhrase').tagSafe('VerbPhrase');doc.match('#Auxiliary+ #VerbPhrase').tagSafe('VerbPhrase');doc.match('#VerbPhrase no').tagSafe('VerbPhrase');doc.match('not #VerbPhrase').tagSafe('VerbPhrase');doc.match('#VerbPhrase [that]',0).unTag('NounPhrase');doc.match('#VerbPhrase #Conjunction #VerbPhrase').tagSafe('VerbPhrase');doc.match('(who|what|which)').tag('NounPhrase');doc.match('#Adverb+ #Adjective').tagSafe('AdjectivePhrase');doc.match('#Adjective').tagSafe('AdjectivePhrase');doc.match('#Value').tagSafe('NounPhrase');doc.match('#Date').tagSafe('NounPhrase');doc.match('#Date at #Date').tagSafe('NounPhrase');};var tagger_1=tagger;var prepend=function prepend(str){this.forEach(function(doc){var firstTerms=doc.match('^.');firstTerms.not('#ProperNoun').toLowerCase();firstTerms._prepend(str);firstTerms.terms(0).toTitleCase();});return this;};var append_1=function append_1(str){var hasEnd=/[.?!]\s*$/.test(str);this.forEach(function(doc){var end=doc.match('.$');var lastTerm=end.termList(0);var punct=lastTerm.post;if(hasEnd===true){punct='';}
end._append(str+punct);lastTerm.post=' ';});return this;};var append={prepend:prepend,append:append_1};var subordinate="(after|although|as|because|before|if|since|than|that|though|when|whenever|where|whereas|wherever|whether|while|why|unless|until|once)";var relative="(that|which|whichever|who|whoever|whom|whose|whomever)";var mainClause=function mainClause(og){var m=og.clone(true);if(m.length===1){return m;}
m=m["if"]('#Verb');if(m.length===1){return m;}
m=m.ifNo(subordinate);m=m.ifNo('^even (if|though)');m=m.ifNo('^so that');m=m.ifNo('^rather than');m=m.ifNo('^provided that');if(m.length===1){return m;}
m=m.ifNo(relative);if(m.length===1){return m;}
m=m.ifNo('(despite|during|before|through|throughout)');if(m.length===1){return m;}
if(m.length===0){m=og;}
return m.eq(0);};var mainClause_1=mainClause;var parse=function parse(doc){var clauses=doc.clauses();var main=mainClause_1(clauses);var nouns=main.match('#Determiner? (#Noun|#Adjective)+')["if"]('#Noun');var verb=main.verbs().eq(0);return{subject:nouns.eq(0),verb:verb,object:verb.lookAhead('.*')};};var parse_1=parse;var json_1=function json_1(options){var n=null;if(typeof options==='number'){n=options;options=null;}
options=options||{text:true,normal:true,trim:true,terms:true};var res=[];this.forEach(function(doc){var json=doc._json(options)[0];var obj=parse_1(doc);json.subject=obj.subject.json(options)[0];json.verb=obj.verb.json(options)[0];json.object=obj.object.json(options)[0];res.push(json);});if(n!==null){return res[n];}
return res;};var json={json:json_1};var toNegative=function toNegative(){this.forEach(function(doc){var obj=parse_1(doc);var vb=obj.verb.clone();vb=vb.verbs().toNegative();obj.verb.replaceWith(vb,false);});return this;};var toPositive=function toPositive(){this.forEach(function(doc){var obj=parse_1(doc);var vb=obj.verb.clone();vb=vb.verbs().toPositive();obj.verb.replaceWith(vb,false);});return this;};var negative={toNegative:toNegative,toPositive:toPositive};var isQuestion=function isQuestion(doc){var endPunct=doc.post();var clauses=doc.clauses();if(/\?/.test(endPunct)===true){return true;}
if(/\.\.$/.test(doc.out('text'))){return false;}
if(doc.has('^#QuestionWord')&&doc.has('#Comma')){return false;}
if(doc.has('^#QuestionWord')){return true;}
if(doc.has('^(do|does|did|is|was|can|could|will|would|may) #Noun')){return true;}
if(doc.has('^(have|must) you')){return true;}
if(clauses.has('^#QuestionWord')){return true;}
if(clauses.has('(do|does|is|was) #Noun+ #Adverb? (#Adjective|#Infinitive)$')){return true;}
return false;};var isQuestion_1=isQuestion;var isQuestion_1$1=function isQuestion_1$1(){return this.filter(function(d){return isQuestion_1(d);});};var isExclamation=function isExclamation(){return this.filter(function(doc){var term=doc.lastTerm().termList(0);return term.hasPost('!');});};var isStatement=function isStatement(){return this.filter(function(doc){var term=doc.lastTerm().termList(0);return!term.hasPost('?')&&!term.hasPost('!');});};var toExclamation=function toExclamation(){this.post('!');return this;};var toQuestion=function toQuestion(){this.post('?');return this;};var toStatement=function toStatement(){this.post('.');return this;};var questions={isQuestion:isQuestion_1$1,isExclamation:isExclamation,isStatement:isStatement,toExclamation:toExclamation,toQuestion:toQuestion,toStatement:toStatement};var useParticiple=function useParticiple(vb){if(vb.has('(could|should|would|may|can|must)')){return true;}
return false;};var toPastTense=function toPastTense(){this.forEach(function(doc){if(doc.has('#PastTense')){return;}
var obj=parse_1(doc);var vb=obj.verb.clone();if(useParticiple(vb)){vb=vb.verbs().toParticiple();obj.verb.replaceWith(vb,false);}else{vb=vb.verbs().toPastTense();obj.verb.replaceWith(vb,false);}
if(obj.object&&obj.object.found&&obj.object.has('#PresentTense')){var verbs=obj.object.verbs();verbs["if"]('#PresentTense').verbs().toPastTense();}});return this;};var toParticiple=function toParticiple(){this.forEach(function(doc){if(doc.has('has #Participle')){return;}
var obj=parse_1(doc);var vb=obj.verb.clone();vb=vb.verbs().toParticiple();obj.verb.replaceWith(vb,false);if(obj.object&&obj.object.found&&obj.object.has('#PresentTense')){var verbs=obj.object.verbs();verbs["if"]('#PresentTense').verbs().toParticiple();}});return this;};var toPresentTense=function toPresentTense(){this.forEach(function(doc){var obj=parse_1(doc);var isPlural=obj.verb.lookBehind('(i|we) (#Adverb|#Verb)?$').found;var vb=obj.verb.clone();if(isPlural){if(vb.has('(is|was|am|be)')){vb=vb.replace('will? (is|was|am|be)','am');}else{vb=vb.verbs().toInfinitive();}}else{vb=vb.verbs().toPresentTense();}
obj.verb.replaceWith(vb,false);if(obj.object&&obj.object.found&&obj.object.has('#PastTense')){var verbs=obj.object.verbs();verbs["if"]('#PastTense').verbs().toPresentTense();}});return this;};var toFutureTense=function toFutureTense(){this.forEach(function(doc){var obj=parse_1(doc);var vb=obj.verb.clone();vb=vb.verbs().toFutureTense();obj.verb.replaceWith(vb,false);if(obj.object&&obj.object.found&&obj.object.has('(#PastTense|#PresentTense)')){var verbs=obj.object.verbs();verbs["if"]('(#PastTense|#PresentTense)').verbs().toInfinitive();}});return this;};var subjects=function subjects(){return this.map(function(doc){var res=parse_1(doc);return res.subject;});};var isPassive=function isPassive(){return this["if"]('was #Adverb? #PastTense #Adverb? by');};var tense={toPastTense:toPastTense,toParticiple:toParticiple,toPresentTense:toPresentTense,toFutureTense:toFutureTense,subjects:subjects,isPassive:isPassive};var phrases_1=function phrases_1(){var arr=[];this.forEach(function(s){s=s.splitOn('#VerbPhrase+');s=s.splitOn('#NounPhrase+');s=s.splitOn('#AdjectivePhrase+');arr=arr.concat(s.list);});return this.buildFrom(arr);};var phrases={phrases:phrases_1};var methods=Object.assign({},append,json,negative,questions,tense,phrases);var plugin=function plugin(Doc,world){world.addTags(tags);world.postProcess(tagger_1);var Sentences=function(_Doc){_inherits(Sentences,_Doc);var _super=_createSuper(Sentences);function Sentences(list,from,w){_classCallCheck(this,Sentences);list=list.map(function(p){return p.clone(true);});return _super.call(this,list,from,w);}
return Sentences;}(Doc);methods.questions=methods.isQuestion;methods.exclamations=methods.isExclamation;methods.statements=methods.isStatement;methods._prepend=Sentences.prototype.prepend;methods._append=Sentences.prototype.append;methods._json=Sentences.prototype.json;Object.assign(Sentences.prototype,methods);Sentences.prototype.buildFrom=function(list){list=list.map(function(p){return p.clone(true);});var doc=new Sentences(list,this,this.world);return doc;};Sentences.prototype.toDoc=function(){return Doc.prototype.buildFrom(this.list);};Doc.prototype.sentences=function(n){var arr=[];this.list.forEach(function(p){arr.push(p.fullSentence());});var s=new Sentences(arr,this,this.world);if(typeof n==='number'){s=s.get(n);}
return s;};return Doc;};var src=plugin;return src;})));};BundleModuleCode['nlp/efrt']=function(module,exports){(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=global||self,global.efrt=factory());}(this,function(){'use strict';var commonjsGlobal=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global!=='undefined'?global:typeof self!=='undefined'?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports;}
var commonPrefix=function(w1,w2){var len=Math.min(w1.length,w2.length);while(len>0){var prefix=w1.slice(0,len);if(prefix===w2.slice(0,len)){return prefix}
len-=1;}
return''};var unique=function(a){a.sort();for(var i=1;i<a.length;i++){if(a[i-1]===a[i]){a.splice(i,1);}}};var fns={commonPrefix:commonPrefix,unique:unique};var Histogram=function(){this.counts={};};var methods={init:function(sym){if(this.counts[sym]===undefined){this.counts[sym]=0;}},add:function(sym,n){if(n===undefined){n=1;}
this.init(sym);this.counts[sym]+=n;},countOf:function(sym){this.init(sym);return this.counts[sym]},highest:function(top){var sorted=[];var keys=Object.keys(this.counts);for(var i=0;i<keys.length;i++){var sym=keys[i];sorted.push([sym,this.counts[sym]]);}
sorted.sort(function(a,b){return b[1]-a[1]});if(top){sorted=sorted.slice(0,top);}
return sorted}};Object.keys(methods).forEach(function(k){Histogram.prototype[k]=methods[k];});var histogram=Histogram;var BASE=36;var seq='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';var cache=seq.split('').reduce(function(h,c,i){h[c]=i;return h},{});var toAlphaCode=function(n){if(seq[n]!==undefined){return seq[n]}
var places=1;var range=BASE;var s='';for(;n>=range;n-=range,places++,range*=BASE){}
while(places--){var d=n%BASE;s=String.fromCharCode((d<10?48:55)+d)+s;n=(n-d)/BASE;}
return s};var fromAlphaCode=function(s){if(cache[s]!==undefined){return cache[s]}
var n=0;var places=1;var range=BASE;var pow=1;for(;places<s.length;n+=range,places++,range*=BASE){}
for(var i=s.length-1;i>=0;i--,pow*=BASE){var d=s.charCodeAt(i)-48;if(d>10){d-=7;}
n+=d*pow;}
return n};var encoding={toAlphaCode:toAlphaCode,fromAlphaCode:fromAlphaCode};var config={SYM_SEP:'|',NODE_SEP:';',KEY_VAL:':',STRING_SEP:',',TERMINAL_PREFIX:'!',BASE:36};var nodeLine=function(self,node){var line='',sep='';if(self.isTerminal(node)){line+=config.TERMINAL_PREFIX;}
var props=self.nodeProps(node);for(var i=0;i<props.length;i++){var prop=props[i];if(typeof node[prop]==='number'){line+=sep+prop;sep=config.STRING_SEP;continue}
if(self.syms[node[prop]._n]){line+=sep+prop+self.syms[node[prop]._n];sep='';continue}
var ref=encoding.toAlphaCode(node._n-node[prop]._n-1+self.symCount);if(node[prop]._g&&ref.length>=node[prop]._g.length&&node[node[prop]._g]===1){ref=node[prop]._g;line+=sep+prop+ref;sep=config.STRING_SEP;continue}
line+=sep+prop+ref;sep='';}
return line};var analyzeRefs=function(self,node){if(self.visited(node)){return}
var props=self.nodeProps(node,true);for(var i=0;i<props.length;i++){var prop=props[i];var ref=node._n-node[prop]._n-1;if(ref<config.BASE){self.histRel.add(ref);}
self.histAbs.add(node[prop]._n,encoding.toAlphaCode(ref).length-1);analyzeRefs(self,node[prop]);}};var symbolCount=function(self){self.histAbs=self.histAbs.highest(config.BASE);var savings=[];savings[-1]=0;var best=0,sCount=0;var defSize=3+encoding.toAlphaCode(self.nodeCount).length;for(var sym=0;sym<config.BASE;sym++){if(self.histAbs[sym]===undefined){break}
savings[sym]=self.histAbs[sym][1]-
defSize-
self.histRel.countOf(config.BASE-sym-1)+
savings[sym-1];if(savings[sym]>=best){best=savings[sym];sCount=sym+1;}}
return sCount};var numberNodes=function(self,node){if(node._n!==undefined){return}
var props=self.nodeProps(node,true);for(var i=0;i<props.length;i++){numberNodes(self,node[props[i]]);}
node._n=self.pos++;self.nodes.unshift(node);};var pack=function(self){self.nodes=[];self.nodeCount=0;self.syms={};self.symCount=0;self.pos=0;self.optimize();self.histAbs=new histogram();self.histRel=new histogram();numberNodes(self,self.root);self.nodeCount=self.nodes.length;self.prepDFS();analyzeRefs(self,self.root);self.symCount=symbolCount(self);for(var sym=0;sym<self.symCount;sym++){self.syms[self.histAbs[sym][0]]=encoding.toAlphaCode(sym);}
for(var i=0;i<self.nodeCount;i++){self.nodes[i]=nodeLine(self,self.nodes[i]);}
for(var sym=self.symCount-1;sym>=0;sym--){self.nodes.unshift(encoding.toAlphaCode(sym)+
config.KEY_VAL+
encoding.toAlphaCode(self.nodeCount-self.histAbs[sym][0]-1));}
return self.nodes.join(config.NODE_SEP)};var pack_1=pack;var NOT_ALLOWED=new RegExp('[0-9A-Z,;!:|¦]');var methods$1={insertWords:function(words){if(words===undefined){return}
if(typeof words==='string'){words=words.split(/[^a-zA-Z]+/);}
for(var i=0;i<words.length;i++){words[i]=words[i].toLowerCase();}
fns.unique(words);for(var i=0;i<words.length;i++){if(words[i].match(NOT_ALLOWED)===null){this.insert(words[i]);}}},insert:function(word){this._insert(word,this.root);var lastWord=this.lastWord;this.lastWord=word;var prefix=fns.commonPrefix(word,lastWord);if(prefix===lastWord){return}
var freeze=this.uniqueNode(lastWord,word,this.root);if(freeze){this.combineSuffixNode(freeze);}},_insert:function(word,node){var prefix,next;if(word.length===0){return}
var keys=Object.keys(node);for(var i=0;i<keys.length;i++){var prop=keys[i];prefix=fns.commonPrefix(word,prop);if(prefix.length===0){continue}
if(prop===prefix&&typeof node[prop]==='object'){this._insert(word.slice(prefix.length),node[prop]);return}
if(prop===word&&typeof node[prop]==='number'){return}
next={};next[prop.slice(prefix.length)]=node[prop];this.addTerminal(next,word=word.slice(prefix.length));delete node[prop];node[prefix]=next;this.wordCount++;return}
this.addTerminal(node,word);this.wordCount++;},addTerminal:function(node,prop){if(prop.length<=1){node[prop]=1;return}
var next={};node[prop[0]]=next;this.addTerminal(next,prop.slice(1));},nodeProps:function(node,nodesOnly){var props=[];for(var prop in node){if(prop!==''&&prop[0]!=='_'){if(!nodesOnly||typeof node[prop]==='object'){props.push(prop);}}}
props.sort();return props},optimize:function(){this.combineSuffixNode(this.root);this.prepDFS();this.countDegree(this.root);this.prepDFS();this.collapseChains(this.root);},combineSuffixNode:function(node){if(node._c){return node}
var sig=[];if(this.isTerminal(node)){sig.push('!');}
var props=this.nodeProps(node);for(var i=0;i<props.length;i++){var prop=props[i];if(typeof node[prop]==='object'){node[prop]=this.combineSuffixNode(node[prop]);sig.push(prop);sig.push(node[prop]._c);}else{sig.push(prop);}}
sig=sig.join('-');var shared=this.suffixes[sig];if(shared){return shared}
this.suffixes[sig]=node;node._c=this.cNext++;return node},prepDFS:function(){this.vCur++;},visited:function(node){if(node._v===this.vCur){return true}
node._v=this.vCur;return false},countDegree:function(node){if(node._d===undefined){node._d=0;}
node._d++;if(this.visited(node)){return}
var props=this.nodeProps(node,true);for(var i=0;i<props.length;i++){this.countDegree(node[props[i]]);}},collapseChains:function(node){var prop,props,child,i;if(this.visited(node)){return}
props=this.nodeProps(node);for(i=0;i<props.length;i++){prop=props[i];child=node[prop];if(typeof child!=='object'){continue}
this.collapseChains(child);if(child._g!==undefined&&(child._d===1||child._g.length===1)){delete node[prop];prop+=child._g;node[prop]=child[child._g];}}
if(props.length===1&&!this.isTerminal(node)){node._g=prop;}},isTerminal:function(node){return!!node['']},uniqueNode:function(word,other,node){var props=this.nodeProps(node,true);for(var i=0;i<props.length;i++){var prop=props[i];if(prop===word.slice(0,prop.length)){if(prop!==other.slice(0,prop.length)){return node[prop]}
return this.uniqueNode(word.slice(prop.length),other.slice(prop.length),node[prop])}}
return undefined},pack:function(){return pack_1(this)}};var Trie=function(words){this.root={};this.lastWord='';this.suffixes={};this.suffixCounts={};this.cNext=1;this.wordCount=0;this.insertWords(words);this.vCur=0;};Object.keys(methods$1).forEach(function(k){Trie.prototype[k]=methods$1[k];});var trie=Trie;var isArray=function(input){return Object.prototype.toString.call(input)==='[object Array]'};var handleFormats=function(input){if(input===null||input===undefined){return{}}
if(typeof input==='string'){return input.split(/ +/g).reduce(function(h,str){h[str]=true;return h},{})}
if(isArray(input)){return input.reduce(function(h,str){h[str]=true;return h},{})}
return input};var pack$1=function(obj){obj=handleFormats(obj);var flat=Object.keys(obj).reduce(function(h,k){var val=obj[k];if(isArray(val)){for(var i=0;i<val.length;i++){h[val[i]]=h[val[i]]||[];h[val[i]].push(k);}
return h}
if(h.hasOwnProperty(val)===false){Object.defineProperty(h,val,{writable:true,enumerable:true,configurable:true,value:[]});}
h[val].push(k);return h},{});Object.keys(flat).forEach(function(k){var t=new trie(flat[k]);flat[k]=t.pack();});return Object.keys(flat).map(function(k){return k+':'+flat[k]}).join('|')};var pack_1$1=pack$1;var symbols=function(t){var reSymbol=new RegExp('([0-9A-Z]+):([0-9A-Z]+)');for(var i=0;i<t.nodes.length;i++){var m=reSymbol.exec(t.nodes[i]);if(!m){t.symCount=i;break}
t.syms[encoding.fromAlphaCode(m[1])]=encoding.fromAlphaCode(m[2]);}
t.nodes=t.nodes.slice(t.symCount,t.nodes.length);};var indexFromRef=function(trie,ref,index){var dnode=encoding.fromAlphaCode(ref);if(dnode<trie.symCount){return trie.syms[dnode]}
return index+dnode+1-trie.symCount};var toArray=function(trie){var all=[];var crawl=function(index,pref){var node=trie.nodes[index];if(node[0]==='!'){all.push(pref);node=node.slice(1);}
var matches=node.split(/([A-Z0-9,]+)/g);for(var i=0;i<matches.length;i+=2){var str=matches[i];var ref=matches[i+1];if(!str){continue}
var have=pref+str;if(ref===','||ref===undefined){all.push(have);continue}
var newIndex=indexFromRef(trie,ref,index);crawl(newIndex,have);}};crawl(0,'');return all};var unpack=function(str){var trie={nodes:str.split(';'),syms:[],symCount:0};if(str.match(':')){symbols(trie);}
return toArray(trie)};var unpack_1=unpack;var unpack_1$1=function(str){var obj=str.split('|').reduce(function(h,s){var arr=s.split(':');h[arr[0]]=arr[1];return h},{});var all={};Object.keys(obj).forEach(function(cat){var arr=unpack_1(obj[cat]);if(cat==='true'){cat=true;}
for(var i=0;i<arr.length;i++){var k=arr[i];if(all.hasOwnProperty(k)===true){if(Array.isArray(all[k])===false){all[k]=[all[k],cat];}else{all[k].push(cat);}}else{all[k]=cat;}}});return all};var lexer=function(packed){var lex={};var symbols=packed.split(config.SYM_SEP);function lexit(treestr){var levels=treestr.split(';');return function(text){var scannerOff=0,level=0,jump,shift,startOff=0;for(var textOff=0;;){var current=levels[level];if(current[scannerOff]==undefined)return true;if(current[scannerOff]==','&&text[textOff]==undefined)return true;if(current[scannerOff]==',')scannerOff++;if(/[0-9A-Z]/.test(current[scannerOff])){jump=0;var code='';while(/[0-9A-Z]/.test(current[scannerOff])){code+=current[scannerOff++];}
level+=(fromAlphaCode(code)+1);scannerOff=0;startOff=textOff;jump=undefined;continue;}
if(current[scannerOff]=='!'&&text[textOff]==undefined)return true;else if(current[scannerOff]=='!')scannerOff++;if(current[scannerOff]==text[textOff]){textOff++;scannerOff++;}else{while(current[scannerOff]!=undefined&&!(/[0-9A-Z]/.test(current[scannerOff]))&&current[scannerOff]!=',')
scannerOff++;if(current[scannerOff]==',')scannerOff++;else while(current[scannerOff]!=undefined&&(/[0-9A-Z]/.test(current[scannerOff])))scannerOff++;if(current[scannerOff]==undefined)return false;textOff=startOff;}}
return text[textOff]==undefined&&(current[scannerOff]==undefined||current[scannerOff]==','||current[scannerOff]=='!');}}
symbols.forEach(function(line){var tokens=line.split(':');lex[tokens[0]]=lexit(tokens[1]);});return lex;};var src=createCommonjsModule(function(module){var efrt={lexer:lexer,pack:pack_1$1,unpack:unpack_1$1};if(typeof self!=='undefined'){self.efrt=efrt;}else if(typeof window!=='undefined'){window.efrt=efrt;}else if(typeof commonjsGlobal!=='undefined'){commonjsGlobal.efrt=efrt;}
{module.exports=efrt;}});return src;}));};BundleModuleCode['ml/ml']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var ICE=Require('ml/ice');var DTI=Require('ml/dti');var KNN=Require('ml/knn');var KMN=Require('ml/kmeans');var SVM=Require('ml/svm');var MLP=Require('ml/mlp');var ID3=Require('ml/id3');var C45=Require('ml/C45');var TXT=Require('ml/text');var RF=Require('ml/rf');var RL=Require('ml/rl');var STAT=Require('ml/stats');var CNN=Require('ml/cnn');var ANN=Require('ml/ann');var PCA=Require('ml/pca');var current=none;var Aios=none;var options={version:'1.17.1'}
var ML={ANN:'ann',C45:'c45',CNN:'cnn',ICE:'ice',DTI:'dti',ID3:'id3',KMN:'kmeans',KNN:'knn',KNN2:'knn2',MLP:'mlp',RF:'rf',RL:'rl',SLP:'slp',SVM:'svm',TXT:'txt',EUCL:'euclidean',PEAR:'pearson',DPAgent:'DPAgent',TDAgent:'TDAgent',DQNAgent:'DQNAgent',};function log2(n){return Math.log(n)/Math.log(2);}
function obj2Array(row,features){return features.map(function(attr){return row[attr]});}
function objSlice(row,features){var o={};features.forEach(function(attr){o[attr]=row[attr]});return o;}
function relax(mat){if(Comp.obj.isMatrix(mat)&&mat[0].length==1)return mat.map(function(row){return row[0]})
else return mat;}
function wrap(mat){if(!Comp.obj.isMatrix(mat))return mat.map(function(v){return[v]})
else return mat}
function scale(vrow,scala){if(!scala)return vrow;if(typeof vrow=='number'){if(typeof scala.k=='number')
return scala.shift+(vrow-scala.off)*scala.k
else
return scala.shift+(vrow-scala.off[0])*scala.k[0];}
if(typeof scala.k=='number')
return vrow.map(function(col,i){return scala.shift+(col-scala.off)*scala.k})
else
return vrow.map(function(col,i){return scala.shift+(col-scala.off[i])*scala.k[i]})}
function unscale(vrow,scala){if(!scala)return vrow;if(typeof vrow=='number'){if(typeof scala.k=='number')
return(vrow-scala.shift)/scala.k+scala.off
else
return(vrow-scala.shift)/scala.k[0]+scala.off[0]}}
function preprocess(data,need,options){var row,x,y,_data;options=options||{};var scala=options.scale||options.xscale;function array(data){return Comp.obj.isArray(data)?data:[data]}
if(Comp.obj.isArray(data)){row=data[0];switch(need){case'xy':case'xry':if(options.target!=undefined&&options.features!=undefined){if(Comp.obj.isArray(row)&&need=='xy'){if(Number(options.target)==row.length-1){x=data.map(function(row){return scale(row.slice(0,options.target),scala)});y=data.map(function(row){return row[options.target]})}}else if(Comp.obj.isObj(row)){if(typeof options.target=='string'){x=data.map(function(row){return scale(objSlice(row,options.features),scala)});y=data.map(function(row){return row[options.target]});}}}
if(x&&y)return{x:x,y:y}
break;case'a':if(Comp.obj.isArray(data)&&typeof data[0]!='object')return{data:data};if(Comp.obj.isObject(data)&&options.features!=undefined){return{data:data.map(function(row){return scale(objSlice(row,options.features),scala)})};}
break;case'm':if(Comp.obj.isMatrix(data))return{data:data};if(Comp.obj.isObject(row)&&options.features!=undefined){return{data:data.map(function(row){return scale(obj2Array(row,options.features),scala)})};}
break;case'xmy':if(Comp.obj.isObject(row)&&options.features!=undefined&&options.target!=undefined){return{x:data.map(function(row){return scale(obj2Array(row,options.features),scala)}),y:data.map(function(row){return row[options.target]})};}
break;case'io':if(Comp.obj.isArray(row)&&options.target!=undefined){if(Number(options.target)==row.length-1){_data=data.map(function(row){return{input:scale(row.slice(0,options.target),scala),output:array(row[options.target])}});return _data}}else if(Comp.obj.isObject(row)&&options.target!=undefined&&options.features!=undefined){_data=data.map(function(row){return{input:scale(obj2Array(row,options.features),scala),output:array(row[options.target])}});return _data}
break;}}else if(data.x&&data.y){if(Comp.obj.isArray(data.x)&&Comp.obj.isArray(data.y)){row=data.x[0];switch(need){case'io':if(Comp.obj.isArray(row)){_data=data.x.map(function(row,rowi){return{input:scale(row,scala),output:array(data.y[rowi])}});return _data}
if(Comp.obj.isObject(row)&&options.features!=undefined){_data=data.x.map(function(row,rowi){return{input:scale(obj2Array(row,options.features),scala),output:array(data.y[rowi])}});return _data}
break;case'xm':if(Comp.obj.isArray(row))return data.x;break;case'xmy':if(Comp.obj.isArray(row))return{x:data.x,y:data.y};break;case'xmya':if(Comp.obj.isArray(row))return{x:data.x,y:data.y.map(array)};break;case'd':return data.x.map(function(row,rowi){var newrow={};if(options.features&&options.target){options.features.forEach(function(f,coli){newrow[f]=row[coli];});newrow[options.target]=data.y[rowi];}else{row.forEach(function(col,f){newrow[String(f)]=col;});newrow[String(row.length)]=data.y[rowi];}
return newrow;})
break;}}}}
var ml={action:function(model,arg){switch(model.algorithm){case ML.RL:switch(model.kind){case ML.DQNAgent:return model.actions[RL.DQNAgent.code.act(model,arg)];break;case ML.DPAgent:return model.actions[RL.DPAgent.code.act(model,arg)];break;case ML.TDAgent:return model.actions[RL.TDAgent.code.act(model,arg)];break;}
break;}},classify:function(model,samples){var x,solutions,result;switch(model.algorithm){case ML.ANN:if(Comp.obj.isArray(samples))
return samples.map(function(sample){return model.network.activate(sample)});else
return model.network.activate(samples);case ML.CNN:if(Comp.obj.isMatrix(samples))
return samples.map(function(sample){return CNN.predict(model,sample);});else
return CNN.predict(model,samples);break;case ML.C45:if(Comp.obj.isMatrix(samples)){return samples.map(function(sample){return C45.classify(model,sample);});}else if(Comp.obj.isArray(samples)&&!Comp.obj.isObj(samples[0])){return C45.classify(model,samples);}else if(Comp.obj.isArray(samples)&&Comp.obj.isObj(samples[0])){return samples.map(function(sample){return C45.classify(model,sample);});}else if(Comp.obj.isObj(samples)){return C45.classify(model,samples);}
break;case ML.DT:case ML.ICE:if(Comp.obj.isMatrix(samples)||Comp.obj.isArray(samples)&&Comp.obj.isObj(samples[0]))
return samples.map(function(sample){return ICE.predict(model,sample)});else
return ICE.predict(model,samples);case ML.DTI:if(Comp.obj.isMatrix(samples))
return samples.map(function(sample){return DTI.predict(model,sample)});else
return DTI.predict(model,samples);case ML.ID3:if(Comp.obj.isArray(samples))
return samples.map(function(sample){return ID3.predict(model,sample)});else
return ID3.predict(model,samples);case ML.KNN:if(Comp.obj.isMatrix(samples))
return KNN.predict(model,samples);else if(Comp.obj.isArray(samples)&&Comp.obj.isObj(samples[0]))
return KNN.predict(model,samples.map(function(sample){return obj2Array(sample,model.features)}));else if(Comp.obj.isObj(samples))
return KNN.predict(model,obj2Array(samples,model.features));else
return KNN.predict(model,samples);break;case ML.KNN2:if(Comp.obj.isMatrix(samples))
return samples.map(function(sample){return KNN.predict2(model,sample);});else if(Comp.obj.isArray(samples)&&Comp.obj.isObj(samples[0]))
return samples.map(function(sample){return KNN.predict2(model,obj2Array(sample,model.features))})
else if(Comp.obj.isObj(samples))
return KNN.predict2(model,obj2Array(samples,model.features));else
return KNN.predict2(model,samples);break;case ML.KMN:return model.clusters
break;case ML.RF:if(model.labels){if(Comp.obj.isMatrix(samples)){return samples.map(function(sample){return model.rfs.map(function(rf){return RF.code.predictOne(rf,sample);}).map(function(v,i){return{value:model.labels[i],prob:v}})});}else if(Comp.obj.isArray(samples)&&typeof samples[0]=='number'){return model.rfs.map(function(rf){return RF.code.predictOne(rf,samples);}).map(function(v,i){return{value:model.labels[i],prob:v}})}}else{if(Comp.obj.isMatrix(samples)){return samples.map(function(sample){return RF.code.predictOne(model,sample);});}else if(Comp.obj.isArray(samples)&&typeof samples[0]=='number'){return RF.predictOne(model,samples);}}
break;case ML.SVM:if(!model._labels){if(Comp.obj.isMatrix(samples))
return samples.map(function(sample){return SVM.code.predict(model,sample);});else
return SVM.code.predict(model,samples);}else{if(Comp.obj.isMatrix(samples))
return samples.map(function(sample){solutions=model.svms.map(function(svm,index){if(svm.threshold==false)
return SVM.code.predict(svm,sample)
else
return SVM.code.predict(svm,sample);});return solutions.map(function(v,i){return{value:model._labels[i],prob:v}});});else{solutions=model.svms.map(function(svm,index){if(svm.threshold==false)
return SVM.code.predict(svm,samples)
else
return SVM.code.predict(svm,samples)==1;})
return solutions.map(function(v,i){return{value:model._labels[i],prob:v}});}}
break;case ML.SLP:case ML.MLP:if(Comp.obj.isMatrix(samples)){x=samples;if(model.xscale)
x=x.map(function(row){return scale(row,model.xscale)});result=model.labels?MLP.code.predict(model,x).map(function(r){var o={};r.forEach(function(v,i){o[model.labels[i]]=v});return o;}):relax(MLP.code.predict(model,x));}else if(Comp.obj.isArray(samples)&&typeof samples[0]=='number'){x=samples;if(model.xscale)
x=scale(x,model.xscale);result=model.labels?MLP.code.predict(model,[x]).map(function(r){var o={};r.forEach(function(v,i){o[model.labels[i]]=v});return o;})[0]:relax(MLP.code.predict(model,[x])[0]);}else if(Comp.obj.isArray(samples)&&typeof samples[0]=='object'){x=samples.map(function(sample){return model.features.map(function(f){return sample[f]})});if(model.xscale)
x=x.map(function(row){return scale(row,model.xscale)});result=model.labels?MLP.code.predict(model,x).map(function(r){var o={};r.forEach(function(v,i){o[model.labels[i]]=v});return o;}):relax(MLP.code.predict(model,x));}else if(Comp.obj.isObj(samples)&&model.features){x=model.features.map(function(f){return samples[f]});if(model.xscale)
x=scale(x,model.xscale);result=model.labels?MLP.code.predict(model,[x]).map(function(r){var o={};r.forEach(function(v,i){o[model.labels[i]]=v});return o;})[0]:relax(MLP.code.predict(model,[x])[0]);}
if(Comp.obj.isArray(result)){return model.yscale?result.map(function(y){return unscale(y,model.yscale)}):result;}else{return result;}
break;case ML.TXT:if(Comp.obj.isArray(samples))
return samples.map(function(sample){return TXT.classify(model,sample)});else
return TXT.classify(model,samples);break;}},compact:function(model){switch(model.algorithm){case ML.DTI:default:return DTI.compactTree(model);}},depth:function(model){switch(model.algorithm){case ML.DTI:return DTI.depth(model);case ML.DT:case ML.ICE:return ICE.depth(model);case ML.C45:return C45.depth(model);case ML.ID3:return ID3.depth(model);}},evaluate:function(model,target,samples){switch(model.algorithm){case ML.DTI:default:return DTI.evaluate(model,target,samples);}},info:function(model){switch(model.algorithm){case ML.C45:return C45.info(model);case ML.DT:case ML.ICE:return ICE.info(model);case ML.ID3:return ID3.info(model);}},learn:function(options){var model,data,data2,x,y,features,featureTypes,test,target,result,cols,n_ins,n_outs,x,y,xscale,xoffset,xshift,yscale,yoffset,yshift,key,err,t0=Io.time();if(options==_)options={};switch(options.algorithm){case ML.ANN:data=preprocess(options,'io',options);model={};model.algorithm=options.algorithm
if(!options.layers)options.layers=[]
if(data)
model.network=new ANN.Network(options.layers[0],options.layers[options.layers.length-1]);else throw'ML.learn.ANN: Invalid options';model.network.evolve(data,options);model.time=Io.time()-t0;return model;break;case ML.CNN:model=CNN.create(options);model.algorithm=options.algorithm;model.time=Io.time()-t0;return model;break;case ML.C45:var model=C45.create();if(options.x&&options.y){features=options.x[0].map(function(col,i){return String(i)});featureTypes=options.x[0].map(function(col,i){return'number'});data=options.x.map(function(row,i){row=row.slice();row.push(options.y[i]);return row});target='y';}else if(options.data&&Comp.obj.isMatrix(options.data)){data=options.data;features=options.features||options.data[0].slice(0,-1).map(function(col,i){return String(i)});featureTypes=options.data[0].slice(0,-1).map(function(col,i){return typeof col=='number'?'number':'category'});target=options.target||'y';}else if(options.data&&Comp.obj.isObj(options.data[0])&&options.data[0].x&&options.data[0].y!=undefined){data=options.data.map(function(row){return row.x.concat(row.y)});features=options.features||options.data[0].x.slice(0,-1).map(function(col,i){return String(i)});featureTypes=options.data[0].x.slice(0,-1).map(function(col,i){return typeof col=='number'?'number':'category'});target=options.target||'y';}else if(options.data&&Comp.obj.isArray(options.data)&&Comp.obj.isObj(options.data[0])&&options.target&&options.features){rowNames=Comp.obj.isArray(options.target)?options.features.concat(options.target):options.features.concat([options.target]);data=options.data.map(function(row){return obj2Array(row,rowNames)})
features=options.features;featureTypes=data[0].slice(0,-1).map(function(col,i){return typeof col=='number'?'number':'category'});target=options.target;}else throw'ML.learn.C45: Invalid options';C45.train(model,{data:data,target:target,features:features,featureTypes:featureTypes});model.algorithm=options.algorithm
model.time=Io.time()-t0;return model;break;case ML.DTI:if(options.eps==_)options.eps=0;if(options.maxdepth==_)options.maxdepth=20;if(options.data&&options.target&&options.features)
model=DTI.create(options);else if(options.x&&options.y){if(options.x.length!=options.y.length)throw'ML.learn.DTI: X and Y vector have different length';data=options.x.map(function(row,i){row=row.slice();row.push(options.y[i]);return row});features=Comp.array.init(data[0].length-1,function(i){return String(i)});target=String(data[0].length-1);model=DTI.create({data:data,features:features,target:target,eps:options.eps,maxdepth:options.maxdepth});}else throw'ML.learn.DTI: Invalid options';model.algorithm=options.algorithm;model.time=Io.time()-t0;return model;case ML.ICE:case ML.DT:if(options.eps==_)options.eps=0;if(options.data&&options.target&&options.features)
model=ICE.create(options);else if(options.x&&options.y){if(options.x.length!=options.y.length)throw'ML.learn.ICE: X and Y vector have different length';data=options.x.map(function(row,i){row=row.slice();row.push(options.y[i]);return row});features=Comp.array.init(data[0].length-1,function(i){return String(i)});target=String(data[0].length-1);model=ICE.create({data:data,features:features,target:target,eps:options.eps,});}else throw'ML.learn.ICE: Invalid options';model.algorithm=options.algorithm;model.eps=options.eps;model.time=Io.time()-t0;return model;break;case ML.ID3:if(options.data&&options.target&&options.features)
model=ID3.createTree(options.data,options.target,options.features);else throw'ML.learn.ID3: Invalid options';model.algorithm=options.algorithm
model.time=Io.time()-t0;return model;break;case ML.KNN:if(options.features&&options.target)target=options.target,features=options.features;else{features=[];if(options.data){for(key in options.data[0])features.push(key);target=features.pop()}else if(options.x){for(key in options.x[0])features.push('x'+key);target='y';}}
if(options.data&&Comp.obj.isObj(options.data[0])){x=options.data.map(function(row){return obj2Array(row,features)});y=options.data.map(function(row){return row[target]})}else if(options.data&&Comp.obj.isMatrix(options.data)){x=options.data,map(function(row){return row.slice(0,row.length-1)});y=options.data,map(function(row){return row[row.length-1]});}else if(options.x&&options.y){x=options.x;y=options.y;}
model=KNN.create(x,y,{distance:options.distance,k:options.k});model.algorithm=options.algorithm
model.features=features
model.target=target
model.time=Io.time()-t0;return model;break;case ML.KNN2:if(options.features&&options.target)target=options.target,features=options.features;else{features=[];if(options.data){for(key in options.data[0])features.push(key);target=features.pop()}else if(options.x){for(key in options.x[0])features.push('x'+key);target='y';}}
if(options.data&&Comp.obj.isObj(options.data[0])){x=options.data.map(function(row){return obj2Array(row,features)});y=options.data.map(function(row){return row[target]})}else if(options.data&&Comp.obj.isMatrix(options.data)){x=options.data,map(function(row){return row.slice(0,row.length-1)});y=options.data,map(function(row){return row[row.length-1]});}else if(options.x&&options.y){x=options.x;y=options.y;}
model=KNN.create2({x:x,y:y,distance:options.distance,k:options.k});model.algorithm=options.algorithm
model.features=features
model.target=target
model.time=Io.time()-t0;return model;break;case ML.KMN:if(options.data&&Comp.obj.isMatrix(options.data)){data=options.data;}
model=KMN.cluster({data:data,k:options.k,distance:options.distance,epochs:options.epochs,})
model.algorithm=options.algorithm
model.data=data
model.time=Io.time()-t0;return model;break;case ML.RF:var model={};if(!options.x||!options.y)throw'ML.learn.RF: Invalid options';data={x:options.x,y:options.y};if(options.labels){model.labels=options.labels;model.rfs=model.labels.map(function(label){return RF()});model.rfs.forEach(function(rf,i){var y=data.y.map(function(label){return label==model.labels[i]?1:-1});RF.code.train(rf,options.x,y,{numTrees:options.numTrees,maxDepth:options.maxDepth,numTries:options.numTries,type:options.weakType,});});}else{model=RF();features=options.x[0].map(function(col,i){return String(i)});target='y';RF.code.train(model,options.x,options.y,{numTrees:options.numTrees,maxDepth:options.maxDepth,numTries:options.numTries,type:options.weakType,});}
model.algorithm=options.algorithm
model.time=Io.time()-t0;return model;break;case ML.RL:model={}
options.environment=checkOptions(options.environment,{});options.environment.getMaxNumActions=checkOption(options.environment.getMaxNumActions,function(){return options.actions.length})
options.environment.getNumStates=checkOption(options.environment.getNumStates,function(){return options.states.length})
var allowedActions=checkOption(options.environment.allowedActions,function(){return options.actions});options.environment.allowedActions=function(state){return allowedActions(state).map(function(a){return options.actions.indexOf(a)})}
var nextState=options.environment.nextState;if(nextState){options.environment.nextState=function(state,action){return nextState(state,options.actions[action])}}
switch(options.kind){case ML.DQNAgent:model=RL.DQNAgent(options.environment,{alpha:options.alpha,gamma:options.gamma,epsilon:options.epsilon,experience_add_every:options.experience_add_every,experience_size:options.experience_size,learning_steps_per_iteration:options.learning_steps_per_iteration,tderror_clamp:options.tderror_clamp,num_hidden_units:options.num_hidden_units,update:options.update,})
break;case ML.DPAgent:model=RL.DPAgent(options.environment,{alpha:options.alpha,beta:options.beta,gamma:options.gamma,epsilon:options.epsilon,lambda:options.lambda})
break;case ML.TDAgent:model=RL.TDAgent(options.environment,{alpha:options.alpha,beta:options.beta,gamma:options.gamma,epsilon:options.epsilon,lambda:options.lambda,replacing_traces:options.replacing_traces,smooth_policy_update:options.smooth_policy_update,update:options.update,planN:options.planN})
break;}
model.algorithm=options.algorithm;model.kind=options.kind;if(options.actions)model.actions=options.actions;if(options.states)model.states=options.states;if(options.rewards)model.rewards=options.rewards;return model;break;case ML.SLP:case ML.MLP:x=options.x;if(Comp.obj.isArray(options.x)&&typeof options.x[0]=='number')
x=wrap(options.x);else if(!Comp.obj.isMatrix(options.x)&&Comp.obj.isArray(options.x)&&typeof options.x[0]=='object'&&options.features){x=options.x.map(function(o){return options.features.map(function(f){return o[f]});});}
if(Comp.obj.isMatrix(options.y))
y=options.y;else if(Comp.obj.isArray(options.y)&&typeof options.y[0]=='number')
y=wrap(options.y);else if(Comp.obj.isArray(options.y)&&options.labels){y=options.y.map(function(l1){return options.labels.map(function(l2){return l1==l2?1:0;});});}else throw'ML.learn.MLP: invalid options';if(options.normalize){var max=x[0].map(function(col){return col}),min=x[0].map(function(col){return col});x.forEach(function(row){row.forEach(function(col,i){max[i]=Math.max(max[i],col);min[i]=Math.min(min[i],col)})});xshift=options.bipolar?-1:0;xscale=max.map(function(x,i){return(xshift?2:1)/((x-min[i])==0?1:x-min[i])});xoffset=min;x=x.map(function(row){return row.map(function(col,i){return xshift+(col-xoffset[i])*xscale[i]})});if(options.regression){max=y[0].map(function(col){return col});min=y[0].map(function(col){return col});y.forEach(function(row){row.forEach(function(col,i){max[i]=Math.max(max[i],col);min[i]=Math.min(min[i],col)})});yshift=options.bipolar?-1:0;yscale=max.map(function(x,i){return(yshift?2:1)/((x-min[i])==0?1:x-min[i])});yoffset=min;y=y.map(function(row){return row.map(function(col,i){return yshift+(col-yoffset[i])*yscale[i]})});}}
model=MLP({input:x,output:y,n_ins:x[0].length,n_outs:y[0].length,hidden_layer_sizes:options.algorithm==ML.SLP?[]:(options.hidden_layers||[])});model.algorithm=options.algorithm;model.labels=options.labels;model.features=options.features;model.xscale=options.normalize?{k:xscale,off:xoffset,shift:xshift}:undefined;model.yscale=options.normalize&&options.regression?{k:yscale,off:yoffset,shift:yshift}:undefined;model.nOutputs=y[0].length;MLP.code.set(model,'log level',options.verbose||0);if(options.epochs)MLP.code.train(model,{epochs:options.epochs});model.time=Io.time()-t0;return model;break;case ML.SVM:if(!options.labels){model=SVM({x:options.x,y:options.y,threshold:options.threshold,});model.algorithm=options.algorithm
SVM.code.train(model,{C:options.C||1.0,tol:options.tol||1e-4,max_passes:options.max_passes||20,alpha_tol:options.alpha_tol||1e-5,kernel:options.kernel});}else{model={};model.algorithm=options.algorithm;model._labels=options.labels;model.svms=options.labels.map(function(cl){return SVM({x:options.x,y:options.y.map(function(y){return y==cl?1:-1}),threshold:options.threshold,});});model.svms.forEach(function(svm){SVM.code.train(svm,{C:options.C||1.0,tol:options.tol||1e-4,max_passes:options.max_passes||20,alpha_tol:options.alpha_tol||1e-5,kernel:options.kernel});});}
model.time=Io.time()-t0;return model;break;case ML.TXT:model=TXT.create(options.data,{});model.algorithm=options.algorithm
return model;break;}},noise:function(data,noise){if(Comp.obj.isMatrix(data)){return data.map(function(row){return row.map(function(v,i){if(typeof noise=='number')
return v+(Math.random()-0.5)*noise;else return v+(Math.random()-0.5)*noise[i]})})}else if(Comp.obj.isArray(data)&&Comp.obj.isObject(data[0])){return data.map(function(row){var o={};for(var p in row){if(typeof noise=='number')
o[p]=row[p]+(Math.random()-0.5)*noise;else o[p]=row[p]+(Math.random()-0.5)*noise[p]}
return o;})}},preprocess:preprocess,print:function(model,indent,compact){switch(model.algorithm){case ML.DTI:return DTI.print(model,indent,compact);case ML.DT:case ML.ICE:return ICE.print(model,indent);case ML.C45:return C45.print(model,indent);case ML.ID3:return ID3.print(model,indent);}},similarity:TXT.similarity,stats:STAT,test:function(model,samples){var x,y,data,res,p=0.0;switch(model.algorithm){case ML.ANN:data=preprocess(samples,'xmya',{features:model.features,target:model.target});break;case ML.C45:if(Comp.obj.isMatrix(samples)){samples.forEach(function(sample){x=sample.slice(0,sample.length-1);y=sample[sample.length-1];res=C45.classify(model,x);if(res==y)p+=1;});return p/samples.length;}else if(Comp.obj.isArray(samples)){x=samples.slice(0,samples.length-1);y=samples[samples.length-1];res=C45.classify(model,x);return res==y?1.0:0.0}else if(Comp.obj.isObj(samples)&&model.features){}
break;case ML.TXT:var model=model.string?{data:[model.string]}:model;if(Comp.obj.isArray(samples))
return samples.map(function(sample){return TXT.classify(model,sample).match});else
return TXT.classify(model,samples).match;break;}},update:function(model,options){switch(model.algorithm||options.algorithm){case ML.CNN:break;case ML.DTI:if(options.eps==_)options.eps=0;if(options.maxdepth==_)options.maxdepth=20;if(options.data&&options.target&&options.features)
model=DTI.update(model,options);else if(options.x&&options.y){if(options.x.length!=options.y.length)throw'ML.update.DTI: X and Y vector have different length';data=options.x.slice();data=data.map(function(row,i){row.push(options.y[i]);return row});features=Comp.array.init(data[0].length-1,function(i){return String(i)});target=String(data[0].length-1);console.log(data,features,target)
model=DTI.update(model,{data:data,features:features,target:target,eps:options.eps,maxdepth:options.maxdepth});}else throw'ML.update.DTI: Invalid options';model.algorithm=options.algorithm;return model;break;case ML.MLP:return MLP.code.train(model,{epochs:options.epochs||1});break;case ML.RL:switch(model.kind){case ML.DQNAgent:return RL.DQNAgent.code.learn(model,options);break;case ML.DPAgent:return RL.DPAgent.code.learn(model,options);break;case ML.TDAgent:return RL.TDAgent.code.learn(model,options);break;}
break;}},ML:ML,};ICE.ml=ml;CNN.ml=ml;ml.predict=ml.classify;ml.learner=ml.learn;ml.train=function(model,options){if(model.algorithm)return ml.update(model,options);else return ml.learn(model);}
ml.best=ml.stats.utils.best;module.exports={agent:ml,classify:ml.classify,column:ml.column,compact:ml.compact,depth:ml.depth,entropy:STAT.entropy,entropyN:STAT.entropyN,entropyDep:STAT.entropyDep,entropyT:STAT.entropyT,evaluate:ml.evaluate,info:ml.info,learn:ml.learn,noise:ml.noise,options:options,pca:PCA,preprocess:preprocess,print:ml.print,stats:STAT,test:ml.test,unique:ml.unique,update:ml.update,ML:ML,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['ml/ice']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var that;var NODE_TYPES={RESULT:'result',FEATURE:'feature',FEATURE_VALUE:'feature_value'};var NL='\n'
function createTree(data,target,features,eps){var ml=that.ml;var targets=ml.stats.unique(ml.stats.utils.column(data,target));if(targets.length==1){return{type:NODE_TYPES.RESULT,name:targets[0],};}
if(features.length==0){var topTarget=ml.stats.mostCommon(targets);return{type:NODE_TYPES.RESULT,name:topTarget,};}
var split=ml.stats.splitEps(data,features,target,targets,eps);var bestFeature=split.feature;var index=features.indexOf(bestFeature);var remainingFeatures=split.remainingFeatures;var remainingEps=typeof eps=='number'?eps:remainingFeatures.map(function(v){return eps[features.indexOf(v)]});var possibleValues=split.possibleValues;var node={type:NODE_TYPES.FEATURE,name:bestFeature,index:index,eps:that.ml.stats.utils.selectEps(eps,index)};node.vals=split.choices.map(function(c){var child_node={val:c.val,eps:that.ml.stats.utils.selectEps(eps,index),type:NODE_TYPES.FEATURE_VALUE};child_node.child=createTree(c.data,target,remainingFeatures,remainingEps);return child_node;})
return node;}
function depth(model){switch(model.type){case NODE_TYPES.RESULT:return 1;case NODE_TYPES.FEATURE:return 1+Comp.array.max(model.vals.map(function(val){return depth(val);}));case NODE_TYPES.FEATURE_VALUE:return 1+depth(model.child);}
return 0;}
function info(model){var vl=vars(model);return{depth:depth(model),nodes:vl.length,vars:vl.unique(),}}
function predictEps(model,sample,prob,eps){var root=model;if(!prob)prob=1;while(root.type!==NODE_TYPES.RESULT){var attr=root.name;var sampleVal=sample[attr];var childNode=null;root.vals.forEach(function(node){var fit=Math.abs(node.val-sampleVal);if(!childNode||fit<childNode.fit)childNode={fit:fit,node:node};});if(childNode){prob=prob*(1-Math.abs(childNode.fit/that.ml.stats.utils.selectEps(eps,root.index))/4)
root=childNode.node.child;}else{root=root.vals[0].child;}}
return{value:root.name,prob:prob};};function printModel(model,indent){var line='',sep;if(indent==undefined)indent=0;if(!model)return'';var sp=function(){var s='';for(var i=0;i<indent;i++)s+=' ';return s};switch(model.type){case NODE_TYPES.RESULT:return sp()+'-> '+model.name+NL;case NODE_TYPES.FEATURE:line=sp()+'$'+model.name+'?'+NL;model.vals.forEach(function(v){line+=printModel(v,indent+2);});return line;case NODE_TYPES.FEATURE_VALUE:line=sp()+'=['+(model.val-model.eps)+','+(model.val+model.eps)+']'+NL;return line+printModel(model.child,indent+2);}
return'model?';}
function vars(model){switch(model.type){case NODE_TYPES.RESULT:return[];case NODE_TYPES.FEATURE:return[model.name].concat(Comp.array.flatten(model.vals.map(vars)));case NODE_TYPES.FEATURE_VALUE:return vars(model.child);}
return[];}
that=module.exports={create:function(options){return createTree(options.data,options.target,options.features,options.eps)},depth:depth,info:info,ml:{},predict:function(model,sample){return predictEps(model,sample,1,model.eps)},print:printModel,}};BundleModuleCode['ml/dti']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var min=Comp.pervasives.min;var max=Comp.pervasives.max;var NODE_TYPES={RESULT:'result',FEATURE:'feature',FEATURE_VALUE:'feature_value'};function Result(key){return{type:NODE_TYPES.RESULT,name:key}}
function Feature(name,vals){return{type:NODE_TYPES.FEATURE,name:name,vals:vals}}
function Value(val,child){return{type:NODE_TYPES.FEATURE_VALUE,val:val,child:child}}
function add_training_set(data,set,merge){if(merge){}else
data.push(set);}
function log2(n){return Math.log(n)/Math.log(2);}
function results(model){var line='',sep;if(!model)return'';switch(model.type){case NODE_TYPES.RESULT:return model.name;case NODE_TYPES.FEATURE:sep='';line='';Comp.array.iter(model.vals,function(v){line+=sep+results(v);sep=',';});return line;case NODE_TYPES.FEATURE_VALUE:return results(model.child);}
return'result?';}
function mostCommon(list){var elementFrequencyMap={};var largestFrequency=-1;var mostCommonElement=null;list.forEach(function(element){var elementFrequency=(elementFrequencyMap[element]||0)+1;elementFrequencyMap[element]=elementFrequency;if(largestFrequency<elementFrequency){mostCommonElement=element;largestFrequency=elementFrequency;}});return mostCommonElement;}
function addVal(v1,v2){if(v1.a!=undefined){if(v2.a!=undefined)return{a:v1.a+v2.a,b:v1.b+v2.b};else return{a:v1.a+v2,b:v2.b+v2};}else if(v2.a!=undefined)return{a:v2.a+v1,b:v2.b+v1};else return v1+v2;}
function lowerBound(v){if(v.a==undefined)return v;else return v.a;}
function upperBound(v){if(v.b==undefined)return v;else return v.b;}
function equal(v1,v2){return(v1==v2||(upperBound(v1)==upperBound(v2)&&(lowerBound(v1)==lowerBound(v2))))}
function overlap(v1,v2){return(upperBound(v1)>=lowerBound(v2)&&upperBound(v1)<=upperBound(v2))||(upperBound(v2)>=lowerBound(v1)&&upperBound(v2)<=upperBound(v1))}
function containsVal(vl,v){for(var i in vl){var v2=vl[i];if(overlap(v,v2))return true;}
return false;}
function centerVal(v){if(v.a==undefined)return v;else return(v.a+v.b)/2;}
function distanceVal(v1,v2){return Math.abs(centerVal(v1)-centerVal(v2));}
function Bounds(vl,v){if(vl.length==0)return{a:v,b:v};else if(v==undefined)return{a:Min(vl),b:Max(vl)};else return{a:Min([Min(vl),v]),b:Max([Max(vl),v])};}
function Min(vals){var min=none;Comp.array.iter(vals,function(val){if(min==none)min=(val.a==undefined?val:val.a);else min=val.a==undefined?(val<min?val:min):(val.a<min?val.a:min);});return min;}
function Max(vals){var max=none;Comp.array.iter(vals,function(val){if(max==none)max=(val.b==undefined?val:val.b);else max=(val.b==undefined?(val>max?val:max):(val.b>max?val.a:max));});return max;}
function epsVal(x,eps){if(x.a==undefined)return{a:x-eps,b:x+eps};else if((x.b-x.a)<2*eps)return{a:centerVal(x)-eps,b:centerVal(x)+eps};else return x;}
function uniqueEps(data,eps){var results=[];Comp.array.iter(data,function(x){var found;if(!results.length)results.push(x);else{Comp.array.iter(results,function(y,i){if(found)return;found=Math.abs(centerVal(x)-centerVal(y))<eps;if(found)
results[i]={a:Min([x,y])-eps,b:Max([x,y])+eps}});if(!found)results.push(x);}});return results;}
function compactTree(model,adjust){var i,j,vi,vj,_vals,merged;function target(model){var line;switch(model.type){case NODE_TYPES.RESULT:return model.name;case NODE_TYPES.FEATURE:line=model.name+'?'+target;Comp.array.iter(model.vals,function(v){line+=target(v);});return line;case NODE_TYPES.FEATURE_VALUE:line='='+(model.val.a==undefined?model.val:'['+model.val.a+','+model.val.b+']')+NL;return line+target(model.child);}}
if(!model)return model;switch(model.type){case NODE_TYPES.RESULT:return model;break;case NODE_TYPES.FEATURE:_vals=[];for(i in model.vals){vi=model.vals[i];assert((vi.type==NODE_TYPES.FEATURE_VALUE)||'vi.type==NODE_TYPES.FEATURE_VALUE');merged=false;loopj:for(j in _vals){vj=_vals[j];if(target(vi.child)==target(vj.child)){merged=true;vj.val={a:Min([vi.val,vj.val]),b:Max([vi.val,vj.val])}
break loopj;}}
if(!merged){_vals.push(vi);vi.child=compactTree(vi.child);}}
if(adjust){for(i in _vals){i=Comp.pervasives.int_of_string(i);if(_vals[i+1]){if(upperBound(_vals[i].val)>lowerBound(_vals[i+1].val)){if(_vals[i].val.b)_vals[i].val.b=lowerBound(_vals[i+1].val)-1;else _vals[i+1].val.a=upperBound(_vals[i].val)+1;}}}}
model.vals=_vals;return model;break;case NODE_TYPES.FEATURE_VALUE:return model;break;}}
function createTree(data,target,features,options){var _newS,child_node,bounds;var targets=Comp.array.unique(Comp.array.pluck(data,target));if(options.maxdepth==undefined)options.maxdepth=1;if(options.maxdepth==0)return Result('-');if(Aios)Aios.aios.CP();if(targets.length==1)return Result(targets[0]);if(features.length==0){var topTarget=mostCommon(targets);return Result(topTarget)}
var bestFeatures=getBestFeatures(data,target,features,options.eps);var bestFeature=bestFeatures[0];var remainingFeatures=Comp.array.filtermap(bestFeatures,function(feat){if(feat.name!=bestFeature.name)return feat.name;else return none;});var possibleValues=getPossibleVals(data,bestFeature.name);var vals=[];var partitions=partitionVals(possibleValues,options.eps);if(partitions.length==1){bestFeatures.sort(function(ef1,ef2){if(ef1.d>ef2.d)return-1;else return 1;});bestFeature=bestFeatures[0];possibleValues=getPossibleVals(data,bestFeature.name);Comp.array.iter(mergeVals(possibleValues),function(val,i){_newS=data.filter(function(x){return overlap(val,x[bestFeature.name]);});child_node=Value(val);options.maxdepth--;child_node.child=createTree(_newS,target,remainingFeatures,options);vals.push(child_node);})}else Comp.array.iter(partitions,function(partition,i){_newS=data.filter(function(x){return containsVal(partition,x[bestFeature.name]);});bounds=Bounds(partition);child_node=Value(options.eps==0?{a:bounds.a,b:bounds.b}:{a:bounds.a-options.eps,b:bounds.b+options.eps});options.maxdepth--;child_node.child=createTree(_newS,target,remainingFeatures,options);vals.push(child_node);});return Feature(bestFeature.name,vals);}
function depth(model){switch(model.type){case NODE_TYPES.RESULT:return 0;case NODE_TYPES.FEATURE:return 1+Comp.array.max(model.vals,function(val){return depth(val);});case NODE_TYPES.FEATURE_VALUE:return depth(model.child);}
return 0;}
function entropyEps(vals,eps){var uniqueVals=Comp.array.unique(vals);var probs=uniqueVals.map(function(x){return probEps(x,vals,eps)});var logVals=probs.map(function(p){return-p*log2(p)});return logVals.reduce(function(a,b){return a+b},0);}
function entropyEps2(vals,eps){var uniqueVals=uniqueEps(vals,eps);var probs=uniqueVals.map(function(x){return probEps2(x,vals,eps)});var logVals=probs.map(function(p){return-p*log2(p)});return logVals.reduce(function(a,b){return a+b},0);}
function getBestFeatures(data,target,features,eps){var bestfeatures=[];function deviation(vals){var n=vals.length;var mu=Comp.array.sum(vals,function(val){return(lowerBound(val)+upperBound(val))/2;})/n;var dev=Comp.array.sum(vals,function(val){return Math.pow(((lowerBound(val)+upperBound(val))/2)-mu,2);})/n;return dev;}
for(var feature in features){if(features[feature]==undefined)throw'DTI.getBestFeatures: invalid feature vector';var vals=Comp.array.pluck(data,features[feature]).map(function(val){return val==undefined?0:val});var e=entropyEps(vals,eps);var d=deviation(vals);var min=Min(vals);var max=Max(vals);bestfeatures.push({e:e,d:d,range:{a:min,b:max},name:features[feature]});}
bestfeatures.sort(function(ef1,ef2){if(ef1.e>ef2.e)return-1;else return 1;});return bestfeatures;}
function getSignificantFeature(data,features){var f,sig;for(f in features){if(sig==undefined||sig.val<data[features[f]])sig={name:features[f],val:data[features[f]]};}
return sig;}
function getPossibleVals(data,feature){return Comp.array.sort(Comp.array.pluck(data,feature),function(x,y){if(upperBound(x)<lowerBound(y))return-1;else return 1;});}
function mergeVals(vals){var _vals,merged,i,j;for(i in vals){var vi=vals[i];if(!_vals)_vals=[vi];else{merged=false;loopj:for(j in _vals){var vj=_vals[j];if(equal(vi,vj)){merged=true;break loopj;}
else if(overlap(vi,vj)){merged=true;_vals[j]={a:Min([vi,vj]),b:Max([vi,vj])};break loopj;}}
if(!merged)_vals.push(vi);}}
return _vals||[];}
function nearestVal(vals,sample,fun){var best=none;for(var v in vals){var d=fun?distanceVal(fun(vals[v]),sample):distanceVal(vals[v],sample);if(best==none)
best={v:vals[v],d:d};else if(best.d>d)
best={v:vals[v],d:d};}
if(best)return best.v;else return none;}
function partitionVals(vals,eps){var last=none;var partitions=[];var partition=[];for(var i in vals){var val0=vals[i];var val1=vals[i-1];if(val1==undefined)partition.push(val0);else if(upperBound(val0)<upperBound(addVal(val1,2*eps)))partition.push(val0);else{partitions.push(partition);partition=[val0];}}
if(partition.length>0)partitions.push(partition);return partitions;}
function predict(model,sample){var root=model;while(root&&root.type!==NODE_TYPES.RESULT){var attr=root.name;var sampleVal=sample[attr];var childNode=nearestVal(root.vals,sampleVal,function(node){return node.val;});if(childNode){root=childNode.child;}else{root=none;}}
if(root)return root.name||root.val;else return none;};function print(model,indent,compact){var line='',sep;if(compact)return results(model);if(indent==undefined)indent=0;if(!model)return'';var sp=function(){return Comp.string.create(indent);};switch(model.type){case NODE_TYPES.RESULT:return sp()+'-> '+model.name+NL;case NODE_TYPES.FEATURE:line=sp()+'$'+model.name+'?'+NL;Comp.array.iter(model.vals,function(v){line+=print(v,indent+2);});return line;case NODE_TYPES.FEATURE_VALUE:line=sp()+'='+(model.val.a==undefined?model.val:'['+model.val.a+','+model.val.b+']')+NL;return line+print(model.child,indent+2);}
return'model?';}
function probEps(value,list,eps){var occurrences=Comp.array.filter(list,function(element){return(element>=(value-eps))&&(element<=(value+eps));});var numOccurrences=occurrences.length;var numElements=list.length;return numOccurrences/numElements;}
function probEps2(value,list,eps){var occurrences=Comp.array.filter(list,function(element){return overlap(epsVal(value),epsVal(element));});var numOccurrences=occurrences.length;var numElements=list.length;return numOccurrences/numElements;}
function updateTree(model,data,target,features,options){var eps=options.eps,maxdepth=options.maxdepth,verbose=options.verbose;var featuresINm={},results=[],set,i,v,feature,remainingFeatures,exists,sigFeature;var analyze=function(model,feature){var feature2;if(!model)return;switch(model.type){case NODE_TYPES.RESULT:if(!Comp.array.contains(results,model.name))results.push(model.name);break;case NODE_TYPES.FEATURE:feature2={name:model.name};if(!featuresINm[model.name])featuresINm[model.name]=feature2;Comp.array.iter(model.vals,function(v){analyze(v,featuresINm[model.name])});break;case NODE_TYPES.FEATURE_VALUE:if(!feature.val)feature.val={a:(model.val.a==undefined?model.val:model.val.a),b:(model.val.a==undefined?model.val:model.val.b)};else{feature.val.a=min(feature.val.a,(model.val.a==undefined?model.val:model.val.a));feature.val.b=max(feature.val.b,(model.val.a==undefined?model.val:model.val.b));}
analyze(model.child);break;}}
analyze(model);exists=Comp.array.contains(results,data[target]);function init(set){set=data[i];sigFeature1=getSignificantFeature(set,features);remainingFeatures=Comp.array.filter(features,function(feat){return sigFeature1.name!=feat;});sigFeature2=getSignificantFeature(set,remainingFeatures);featuresINm[sigFeature1.name]={name:sigFeature1.name,val:{a:sigFeature1.val-eps,b:sigFeature1.val+eps}};featuresINm[sigFeature2.name]={name:sigFeature2.name,val:{a:sigFeature2.val-eps,b:sigFeature2.val+eps}};results.push(set[target]);model=Feature(sigFeature1.name,[Value({a:set[sigFeature1.name]-eps,b:set[sigFeature1.name]+eps},Feature(sigFeature2.name,[Value({a:sigFeature2.val-eps,b:sigFeature2.val+eps},Result(set[target]))]))]);return model;}
remainingFeatures=Comp.array.filter(features,function(feat){return!featuresINm[feat];});var update=function(model,set,feature){var feature2,p;if(!model)return;switch(model.type){case NODE_TYPES.RESULT:if(model.name!=set[target]&&verbose)
console.log('Cannot insert new training set '+set[target]+' in tree. No more separating variables!');break;case NODE_TYPES.FEATURE:if(set[model.name]<(featuresINm[model.name].val.a-eps)||set[model.name]>(featuresINm[model.name].val.b+eps)){sigFeature=getSignificantFeature(set,remainingFeatures);featuresINm[sigFeature.name]={name:sigFeature.name,val:{a:sigFeature.val-eps,b:sigFeature.val+eps}};featuresINm[model.name].val.a=min(featuresINm[model.name].val.a,set[model.name]-eps);featuresINm[model.name].val.b=max(featuresINm[model.name].val.b,set[model.name]+eps);if(!Comp.array.contains(results,set[target]))results.push(set[target]);model.vals.push(Value({a:set[model.name]-eps,b:set[model.name]+eps},Feature(sigFeature.name,[Value({a:sigFeature.val-eps,b:sigFeature.val+eps},Result(set[target]))])));model.vals=Comp.array.sort(model.vals,function(v1,v2){return(lowerBound(v1.val)<lowerBound(v2.val))?-1:1});}else{Comp.array.iter_break(model.vals,function(fv){if(overlap(fv.val,{a:set[model.name]-eps,b:set[model.name]+eps})){fv.val.a=min(lowerBound(fv.val),set[model.name]-eps);fv.val.b=max(upperBound(fv.val),set[model.name]+eps);update(fv,set,model.name);return true;}else return false;});}
break;case NODE_TYPES.FEATURE_VALUE:update(model.child,set);break;}}
for(i in data){set=data[i];if(model==undefined||model.type==undefined)
model=init(set);else
update(model,set);}
return model;}
module.exports={NODE_TYPES:NODE_TYPES,compactTree:compactTree,create:function(options){return createTree(options.data,options.target,options.features,options)},depth:depth,entropy:entropyEps,evaluate:function evaluate(model,target,samples){},predict:predict,print:print,results:results,update:function(model,options){return updateTree(model,options.data,options.target,options.features,options)},current:function(module){current=module.current;Aios=module;}};};BundleModuleCode['ml/knn']=function(module,exports){var options={version:'1.2.1'}
var Comp=Require('com/compat');var math=Require('ml/math');var euclideanDistance=math.euclidean;function Node(obj,dimension,parent){var N={}
N.obj=obj;N.left=null;N.right=null;N.parent=parent;N.dimension=dimension;return N;}
function KDTree(points,metric){var K={}
if(!Array.isArray(points)){K.dimensions=points.dimensions;K.root=points;restoreParent(K.root);}else{K.dimensions=new Array(points[0].length);for(var i=0;i<K.dimensions.length;i++){K.dimensions[i]=i;}
K.root=buildTree(points,0,null,K.dimensions);}
K.metric=metric;return K;}
KDTree.code={nearest:function(K,point,maxNodes,maxDistance){var metric=K.metric;var dimensions=K.dimensions;var i;var bestNodes=BinaryHeap(function(e){return-e[1];});function nearestSearch(node){var dimension=dimensions[node.dimension];var ownDistance=metric(point,node.obj);var linearPoint={};var bestChild,linearDistance,otherChild,i;function saveNode(node,distance){BinaryHeap.code.push(bestNodes,[node,distance]);if(BinaryHeap.code.size(bestNodes)>maxNodes){BinaryHeap.code.pop(bestNodes);}}
for(i=0;i<dimensions.length;i+=1){if(i===node.dimension){linearPoint[dimensions[i]]=point[dimensions[i]];}else{linearPoint[dimensions[i]]=node.obj[dimensions[i]];}}
linearDistance=metric(linearPoint,node.obj);if(node.right===null&&node.left===null){if(BinaryHeap.code.size(bestNodes)<maxNodes||ownDistance<BinaryHeap.code.peek(bestNodes)[1]){saveNode(node,ownDistance);}
return;}
if(node.right===null){bestChild=node.left;}else if(node.left===null){bestChild=node.right;}else{if(point[dimension]<node.obj[dimension]){bestChild=node.left;}else{bestChild=node.right;}}
nearestSearch(bestChild);if(BinaryHeap.code.size(bestNodes)<maxNodes||ownDistance<BinaryHeap.code.peek(bestNodes)[1]){saveNode(node,ownDistance);}
if(BinaryHeap.code.size(bestNodes)<maxNodes||Math.abs(linearDistance)<BinaryHeap.code.peek(bestNodes)[1]){if(bestChild===node.left){otherChild=node.right;}else{otherChild=node.left;}
if(otherChild!==null){nearestSearch(otherChild);}}}
if(maxDistance){for(i=0;i<maxNodes;i+=1){BinaryHeap.code.push(bestNodes,[null,maxDistance]);}}
if(K.root){nearestSearch(K.root);}
var result=[];for(i=0;i<Math.min(maxNodes,bestNodes.content.length);i+=1){if(bestNodes.content[i][0]){result.push([bestNodes.content[i][0].obj,bestNodes.content[i][1]]);}}
return result;}}
function buildTree(points,depth,parent,dimensions){var dim=depth%dimensions.length;if(points.length===0){return null;}
if(points.length===1){return Node(points[0],dim,parent);}
points.sort(function(a,b){a[dimensions[dim]]-b[dimensions[dim]]});var median=Math.floor(points.length/2);var node=Node(points[median],dim,parent);node.left=buildTree(points.slice(0,median),depth+1,node,dimensions);node.right=buildTree(points.slice(median+1),depth+1,node,dimensions);return node;}
function restoreParent(root){if(root.left){root.left.parent=root;restoreParent(root.left);}
if(root.right){root.right.parent=root;restoreParent(root.right);}}
function BinaryHeap(scoreFunction){var B={}
B.content=[];B.scoreFunction=scoreFunction;return B;}
BinaryHeap.code={push:function(B,element){B.content.push(element);BinaryHeap.code.bubbleUp(B,B.content.length-1);},pop:function(B){var result=B.content[0];var end=B.content.pop();if(B.content.length>0){B.content[0]=end;BinaryHeap.code.sinkDown(B,0);}
return result;},peek:function(B){return B.content[0];},size:function(B){return B.content.length;},bubbleUp:function(B,n){var element=B.content[n];while(n>0){var parentN=Math.floor((n+1)/2)-1;var parent=B.content[parentN];if(B.scoreFunction(element)<B.scoreFunction(parent)){B.content[parentN]=element;B.content[n]=parent;n=parentN;}else{break;}}},sinkDown:function(B,n){var length=B.content.length;var element=B.content[n];var elemScore=B.scoreFunction(element);while(true){var child2N=(n+1)*2;var child1N=child2N-1;var swap=null;if(child1N<length){var child1=B.content[child1N];var child1Score=B.scoreFunction(child1);if(child1Score<elemScore){swap=child1N;}}
if(child2N<length){var child2=B.content[child2N];var child2Score=B.scoreFunction(child2);if(child2Score<(swap===null?elemScore:child1Score)){swap=child2N;}}
if(swap!==null){B.content[n]=B.content[swap];B.content[swap]=element;n=swap;}else{break;}}}}
function KNN(dataset,labels,options){var L={}
if(!options)options={};if(dataset===true){var model=labels;L.kdTree=KDTree(model.kdTree,options);L.k=model.k;L.classes=new Set(model.classes);L.isEuclidean=model.isEuclidean;return L;}
var classes=new Set(labels);var distance=getDistanceFunction(options.distance),k=options.k||classes.size+1;var points=new Array(dataset.length);for(var i=0;i<points.length;++i){points[i]=dataset[i].slice();}
for(i=0;i<labels.length;++i){points[i].push(labels[i]);}
L.kdTree=KDTree(points,distance);L.k=k;L.distance=distance;L.classes=classes;L.isEuclidean=distance===euclideanDistance;return L;}
KNN.code={predict:function(L,dataset){if(Array.isArray(dataset)){if(typeof dataset[0]==='number'){return getSinglePrediction(L,dataset);}else if(Array.isArray(dataset[0])&&typeof dataset[0][0]==='number'){var predictions=new Array(dataset.length);for(var i=0;i<dataset.length;i++){predictions[i]=getSinglePrediction(L,dataset[i]);}
return predictions;}}
throw new TypeError('dataset to predict must be an array or a matrix');}}
function getSinglePrediction(knn,currentCase){var nearestPoints=KDTree.code.nearest(knn.kdTree,currentCase,knn.k);var pointsPerClass={};var predictedClassMin=null;var predictedClassMax=null;var predictedClassDistance=0;var maxPoints=-1;var minDistance=1E30;var lastElement=nearestPoints[0][0].length-1;forof(knn.classes,function(element){pointsPerClass[element]=0;});for(var i=0;i<nearestPoints.length;++i){var currentClass=nearestPoints[i][0][lastElement];var currentPoints=++pointsPerClass[currentClass];if(currentPoints>maxPoints){predictedClassMax=currentClass;predictedClassDistance=predictedClassDistance+nearestPoints[i][1];maxPoints=currentPoints;}
if(nearestPoints[i][1]<minDistance){predictedClassMin=currentClass;minDistance=nearestPoints[i][1];}}
predictedClassDistance/=maxPoints;return maxPoints>2?predictedClassMax:predictedClassMin;}
var KNN2=function(options){var model={}
model.x=options.x;model.y=options.y;model.target=options.y;model.k=options.k||3
model.distance=getDistanceFunction(options.distance);model.weightf=getWeightedFunction(options.weightf);return model}
KNN2.code={predict:function(model,data){var x=data;var k=model.k;var weightf=model.weightf;var distance=model.distance;var distanceList=[];var i;for(i=0;i<model.x.length;i++)
distanceList.push([distance(x,model.x[i]),i]);distanceList.sort(function(a,b){return a[0]-b[0];});var avg=0.0;var totalWeight=0,weight;for(i=0;i<k;i++){var dist=distanceList[i][0];var idx=distanceList[i][1];weight=weightf(dist);avg+=weight*model.y[idx];totalWeight+=weight;}
avg/=totalWeight;return avg;}}
function getWeightedFunction(options){if(typeof options==='undefined'){return function(x){var sigma=10.0;return Math.exp(-1.*x*x/(2*sigma*sigma));}}else if(typeof options==='function'){return options;}else if(options==='gaussian'){return function(x){var sigma=options.sigma;return Math.exp(-1.*x*x/(2*sigma*sigma));}}else if(options==='none'){return function(dist){return 1.0;}}}
function getDistanceFunction(options){if(typeof options==='undefined'){return math.euclidean;}else if(typeof options==='function'){return options;}else if(options==='euclidean'){return math.euclidean;}else if(options==='pearson'){return math.pearson;}else
throw new TypeError('distance opions invalid: '+options);;}
module.exports={create:KNN,predict:KNN.code.predict,create2:KNN2,predict2:KNN2.code.predict,}};BundleModuleCode['ml/math']=function(module,exports){var m=module.exports;m.randn=function(){var v1,v2,s;do{v1=2*Math.random()-1;v2=2*Math.random()-1;s=v1*v1+v2*v2;}while(s>=1||s==0);s=Math.sqrt((-2*Math.log(s))/s);return v1*s;}
m.shape=function(mat){var row=mat.length;var col=mat[0].length;return[row,col];};m.addVec=function(vec1,vec2){if(vec1.length===vec2.length){var result=[];var i;for(i=0;i<vec1.length;i++)
result.push(vec1[i]+vec2[i]);return result;}else{throw new Error("Length Error : not same.")}}
m.minusVec=function(vec1,vec2){if(vec1.length===vec2.length){var result=[];var i;for(i=0;i<vec1.length;i++)
result.push(vec1[i]-vec2[i]);return result;}else{throw new Error("Length Error : not same.")}};m.addMatScalar=function(mat,scalar){var row=m.shape(mat)[0];var col=m.shape(mat)[1];var i,j,result=[];for(i=0;i<row;i++){var rowVec=[];for(j=0;j<col;j++){rowVec.push(mat[i][j]+scalar);}
result.push(rowVec);}
return result;}
m.addMatVec=function(mat,vec){if(mat[0].length===vec.length){var result=[];var i;for(i=0;i<mat.length;i++)
result.push(m.addVec(mat[i],vec));return result;}else{throw new Error("Length Error : not same.")}}
m.minusMatVec=function(mat,vec){if(mat[0].length===vec.length){var result=[];var i;for(i=0;i<mat.length;i++)
result.push(m.minusVec(mat[i],vec));return result;}else{throw new Error("Length Error : not same.")}}
m.addMat=function(mat1,mat2){if((mat1.length===mat2.length)&&(mat1[0].length===mat2[0].length)){var result=new Array(mat1.length);for(var i=0;i<mat1.length;i++){result[i]=new Array(mat1[i].length);for(var j=0;j<mat1[i].length;j++){result[i][j]=mat1[i][j]+mat2[i][j];}}
return result;}else{throw new Error('Matrix mismatch.');}};m.minusMat=function(mat1,mat2){if((mat1.length===mat2.length)&&(mat1[0].length===mat2[0].length)){var result=new Array(mat1.length);for(var i=0;i<mat1.length;i++){result[i]=new Array(mat1[i].length);for(var j=0;j<mat1[i].length;j++){result[i][j]=mat1[i][j]-mat2[i][j];}}
return result;}else{throw new Error('Matrix mismatch.');}}
m.transpose=function(mat){var result=new Array(mat[0].length);for(var i=0;i<mat[0].length;i++){result[i]=new Array(mat.length);for(var j=0;j<mat.length;j++){result[i][j]=mat[j][i];}}
return result;};m.dotVec=function(vec1,vec2){if(vec1.length===vec2.length){var result=0;for(var i=0;i<vec1.length;i++){result+=vec1[i]*vec2[i];}
return result;}else{throw new Error("Vector mismatch");}};m.outerVec=function(vec1,vec2){var mat1=m.transpose([vec1]);var mat2=[vec2];return m.mulMat(mat1,mat2);};m.mulVecScalar=function(vec,scalar){var i,result=[];for(i=0;i<vec.length;i++)
result.push(vec[i]*scalar);return result;};m.mulMatScalar=function(mat,scalar){var row=m.shape(mat)[0];var col=m.shape(mat)[1];var i,j,result=[];for(i=0;i<row;i++){var rowVec=[];for(j=0;j<col;j++){rowVec.push(mat[i][j]*scalar);}
result.push(rowVec);}
return result;};m.mulMatElementWise=function(mat1,mat2){if(mat1.length===mat2.length&&mat1[0].length===mat2[0].length){var result=new Array(mat1.length);for(var x=0;x<mat1.length;x++){result[x]=new Array(mat1[0].length);}
for(var i=0;i<result.length;i++){for(var j=0;j<result[i].length;j++){result[i][j]=mat1[i][j]*mat2[i][j]}}
return result;}else{throw new Error("Matrix shape error : not same");}};m.mulMat=function(mat1,mat2){if(mat1[0].length===mat2.length){var result=new Array(mat1.length);for(var x=0;x<mat1.length;x++){result[x]=new Array(mat2[0].length);}
var mat2_T=m.transpose(mat2);for(var i=0;i<result.length;i++){for(var j=0;j<result[i].length;j++){result[i][j]=m.dotVec(mat1[i],mat2_T[j]);}}
return result;}else{throw new Error("Array mismatch");}};m.sumVec=function(vec){var sum=0;var i=vec.length;while(i--){sum+=vec[i];}
return sum;};m.sumMat=function(mat){var sum=0;var i=mat.length;while(i--){for(var j=0;j<mat[0].length;j++)
sum+=mat[i][j];}
return sum;};m.sumMatAxis=function(mat,axis){if(axis===1){var row=m.shape(mat)[0];var i;var result=[];for(i=0;i<row;i++)
result.push(m.sumVec(mat[i]));return result;}else{mat_T=m.transpose(mat);return m.sumMatAxis(mat_T,1);}};m.meanVec=function(vec){return 1.*m.sumVec(vec)/vec.length;};m.meanMat=function(mat){var row=mat.length;var col=mat[0].length;return 1.*m.sumMat(mat)/(row*col);};m.meanMatAxis=function(mat,axis){if(axis===1){var row=m.shape(mat)[0];var i;var result=[];for(i=0;i<row;i++)
result.push(m.meanVec(mat[i]));return result;}else{mat_T=m.transpose(mat);return m.meanMatAxis(mat_T,1);}};m.squareVec=function(vec){var squareVec=[];var i;for(i=0;i<vec.length;i++){squareVec.push(vec[i]*vec[i]);}
return squareVec;};m.squareMat=function(mat){var squareMat=[];var i;for(i=0;i<mat.length;i++){squareMat.push(m.squareVec(mat[i]));}
return squareMat;};m.minVec=function(vec){var min=vec[0];var i=vec.length;while(i--){if(vec[i]<min)
min=vec[i];}
return min;};m.maxVec=function(vec){var max=vec[0];var i=vec.length;while(i--){if(vec[i]>max)
max=vec[i];}
return max;}
m.minMat=function(mat){var min=mat[0][0];var i=mat.length;while(i--){for(var j=0;j<mat[0].length;j++){if(mat[i][j]<min)
min=mat[i][j];}}
return min;};m.maxMat=function(mat){var max=mat[0][0];var i=mat.length;while(i--){for(var j=0;j<mat[0].length;j++){if(mat[i][j]<max)
max=mat[i][j];}}
return max;};m.zeroVec=function(n){var vec=[];while(vec.length<n)
vec.push(0);return vec;};m.zeroMat=function(row,col){var mat=[];while(mat.length<row)
mat.push(m.zeroVec(col));return mat;};m.oneVec=function(n){var vec=[];while(vec.length<n)
vec.push(1);return vec;};m.oneMat=function(row,col){var mat=[];while(mat.length<row)
mat.push(m.oneVec(col));return mat;};m.randVec=function(n,lower,upper){lower=(typeof lower!=='undefined')?lower:0;upper=(typeof upper!=='undefined')?upper:1;var vec=[];while(vec.length<n)
vec.push(lower+(upper-lower)*Math.random());return vec;};m.randMat=function(row,col,lower,upper){lower=(typeof lower!=='undefined')?lower:0;upper=(typeof upper!=='undefined')?upper:1;var mat=[];while(mat.length<row)
mat.push(m.randVec(col,lower,upper));return mat;};m.randnVec=function(n,mean,sigma){var vec=[];while(vec.length<n)
vec.push(mean+sigma*m.randn());return vec;};m.randnMat=function(row,col,mean,sigma){var mat=[];while(mat.length<row)
mat.push(m.randnVec(col,mean,sigma));return mat;};m.identity=function(n){var result=new Array(n);for(var i=0;i<n;i++){result[i]=new Array(n);for(var j=0;j<n;j++){result[i][j]=(i===j)?1:0;}}
return result;};m.sigmoid=function(x){var sigmoid=(1./(1+Math.exp(-x)))
if(sigmoid==1){sigmoid=0.99999999999999;}else if(sigmoid==0){sigmoid=1e-14;}
return sigmoid;};m.dSigmoid=function(x){a=m.sigmoid(x);return a*(1.-a);};m.probToBinaryMat=function(mat){var row=m.shape(mat)[0];var col=m.shape(mat)[1];var i,j;var result=[];for(i=0;i<row;i++){var rowVec=[];for(j=0;j<col;j++){if(Math.random()<mat[i][j])
rowVec.push(1);else
rowVec.push(0);}
result.push(rowVec);}
return result;};m.activateVec=function(vec,activation){var i,result=[];for(i=0;i<vec.length;i++)
result.push(activation(vec[i]));return result;};m.activateMat=function(mat,activation){var row=m.shape(mat)[0];var col=m.shape(mat)[1];var i,j,result=[];for(i=0;i<row;i++){var rowVec=[];for(j=0;j<col;j++)
rowVec.push(activation(mat[i][j]));result.push(rowVec);}
return result;};m.activateTwoVec=function(vec1,vec2,activation){if(vec1.length===vec2.length){var result=new Array(vec1.length);for(var i=0;i<result.length;i++){result[i]=activation(vec1[i],vec2[i]);}
return result;}else{throw new Error("Matrix shape error : not same");}};m.activateTwoMat=function(mat1,mat2,activation){if(mat1.length===mat2.length&&mat1[0].length===mat2[0].length){var result=new Array(mat1.length);for(var x=0;x<mat1.length;x++){result[x]=new Array(mat1[0].length);}
for(var i=0;i<result.length;i++){for(var j=0;j<result[i].length;j++){result[i][j]=activation(mat1[i][j],mat2[i][j]);}}
return result;}else{throw new Error("Matrix shape error : not same");}};m.fillVec=function(n,value){var vec=[];while(vec.length<n)
vec.push(value);return vec;};m.fillMat=function(row,col,value){var mat=[];while(mat.length<row){var rowVec=[];while(rowVec.length<col)
rowVec.push(value);mat.push(rowVec);}
return mat;};m.softmaxVec=function(vec){var max=m.maxVec(vec);var preSoftmaxVec=m.activateVec(vec,function(x){return Math.exp(x-max);})
return m.activateVec(preSoftmaxVec,function(x){return x/m.sumVec(preSoftmaxVec)})};m.softmaxMat=function(mat){var result=[],i;for(i=0;i<mat.length;i++)
result.push(m.softmaxVec(mat[i]));return result;};m.randInt=function(min,max){var rand=Math.random()*(max-min+0.9999)+min
return Math.floor(rand);}
m.normalizeVec=function(vec){var i;var newVec=[],tot=0;for(i=0;i<vec.length;i++)
tot+=vec[i];for(i=0;i<vec.length;i++)
newVec.push(1.*vec[i]/tot);return newVec;};m.euclidean=function(x1,x2){var i;var distance=0;for(i=0;i<x1.length;i++){var dx=x1[i]-x2[i];distance+=dx*dx;}
return Math.sqrt(distance);};m.pearson=function(x,y)
{var xy=[];var x2=[];var y2=[];for(var i=0;i<x.length;i++)
{xy.push(x[i]*y[i]);x2.push(x[i]*x[i]);y2.push(y[i]*y[i]);}
var sum_x=0;var sum_y=0;var sum_xy=0;var sum_x2=0;var sum_y2=0;for(var i=0;i<x.length;i++)
{sum_x+=x[i];sum_y+=y[i];sum_xy+=xy[i];sum_x2+=x2[i];sum_y2+=y2[i];}
var step1=(x.length*sum_xy)-(sum_x*sum_y);var step2=(x.length*sum_x2)-(sum_x*sum_x);var step3=(x.length*sum_y2)-(sum_y*sum_y);var step4=Math.sqrt(step2*step3);var answer=step1/step4;return answer;};m.getNormVec=function(vec){var i;var sqsum=0;for(i=0;i<vec.length;i++)
sqsum+=vec[i]*vec[i];return Math.sqrt(sqsum);}
m.gaussian=function(x,sigma){sigma=sigma||10.0;return Math.exp(-1.*x*x/(2*sigma*sigma));}
m.meanVecs=function(vecs){var sum=m.zeroVec(vecs[0].length);var i;for(i=0;i<vecs.length;i++)
sum=m.addVec(sum,vecs[i]);return m.activateVec(sum,function(x){return 1.*x/vecs.length;});};m.covarianceVecs=function(vecs){var mat=m.zeroMat(vecs[0].length,vecs[0].length);var meanVec=m.meanVecs(vecs);var i;for(i=0;i<vecs.length;i++){var a=m.minusVec(vecs[i],meanVec);mat=m.addMat(mat,m.mulMat(m.transpose([a]),[a]));}
return m.activateMat(mat,function(x){return 1.*x/(vecs.length-1);});};m.shuffle=function(arr){var o=[];for(var i=0;i<arr.length;i++)
o.push(arr[i]);for(var j,x,i=o.length;i;j=parseInt(Math.random()*i),x=o[--i],o[i]=o[j],o[j]=x);return o;};m.range=function(start,end,step){var ret=[];if(typeof step==="undefined")
step=1;if(typeof end==="undefined"){end=start;start=0;}
for(var i=start;i<end;i+=step)
ret.push(i);return ret;};};BundleModuleCode['ml/kmeans']=function(module,exports){var math=Require('ml/math')
var Kmeans=module.exports;Kmeans.cluster=function(options){var data=options['data'];var k=options['k'];var distance=getDistanceFunction(options['distance']);var epochs=options['epochs'];var init_using_data=options['init_using_data'];if(typeof init_using_data==="undefined");init_using_data=true;var means=getRandomMeans(data,k,init_using_data);var epoch,i,j,l;var clusters=[];for(i=0;i<k;i++)
clusters.push([]);for(epoch=0;epoch<epochs;epoch++){clusters=[];for(i=0;i<k;i++)
clusters.push([]);for(i=0;i<data.length;i++){var bestmatch=0;for(j=0;j<k;j++){if(distance(means[j],data[i])<distance(means[bestmatch],data[i]))bestmatch=j;}
clusters[bestmatch].push(i);}
for(i=0;i<k;i++){var avgs=[];for(j=0;j<data[0].length;j++)
avgs.push(0.0);if(clusters[i].length>0){for(j=0;j<clusters[i].length;j++){for(l=0;l<data[0].length;l++){avgs[l]+=data[clusters[i][j]][l];}}
for(j=0;j<data[0].length;j++){avgs[j]/=clusters[i].length;}
means[i]=avgs;}}}
return{clusters:clusters,means:means};}
var getRandomMeans=function(data,k,init_using_data){var clusters=[];if(init_using_data){var cluster_index=math.range(data.length);cluster_index=math.shuffle(cluster_index);for(i=0;i<k;i++){clusters.push(data[cluster_index[i]]);}}else{var i,j;var ranges=[];for(i=0;i<data[0].length;i++){var min=data[0][i],max=data[0][i];for(j=0;j<data.length;j++){if(data[j][i]<min)min=data[j][i];if(data[j][i]>max)max=data[j][i];}
ranges.push([min,max]);}
for(i=0;i<k;i++){var cluster=[];for(j=0;j<data[0].length;j++){cluster.push(Math.random()*(ranges[j][1]-ranges[j][0])+ranges[j][0]);}
clusters.push(cluster);}}
return clusters;}
function getDistanceFunction(options){if(typeof options==='undefined'){return math.euclidean;}else if(typeof options==='function'){return options;}else if(options['type']==='euclidean'){return math.euclidean;}else if(options['type']==='pearson'){return math.pearson;}}};BundleModuleCode['ml/svm']=function(module,exports){var math=Require('ml/math');var SVM=function(options){var L={};L.x=options.x;L.y=options.y;return L};SVM.code={train:function(L,options){var self=L;var C=options.C||1.0;var tol=options.tol||1e-4;var maxPasses=options.max_passes||20;var alphatol=options.alpha_tol||1e-5;L.options={kernel:options.kernel,iterations:maxPasses,alpha_tol:alphatol,C:C,tol:tol};self.kernel=getKernel(options.kernel);self.alphas=math.zeroVec(self.x.length);self.b=0;var passes=0,i;var count=0;while(passes<maxPasses){var numChangedAlphas=0;for(i=0;i<self.x.length;i++){var E_i=SVM.code.f(self,self.x[i])-self.y[i];if((self.y[i]*E_i<-tol&&self.alphas[i]<C)||(self.y[i]*E_i>tol&&self.alphas[i]>0)){var j=math.randInt(0,self.x.length-1);if(i==j)j=(j+1)%self.x.length;var E_j=SVM.code.f(self,self.x[j])-self.y[j];var alpha_i_old=self.alphas[i],alpha_j_old=self.alphas[j];var L,H;if(self.y[i]!==self.y[j]){L=Math.max(0,self.alphas[j]-self.alphas[i]);H=Math.min(C,C+self.alphas[j]-self.alphas[i]);}else{L=Math.max(0,self.alphas[j]+self.alphas[i]-C);H=Math.min(C,self.alphas[j]+self.alphas[i]);}
if(L===H)
continue;var ETA=2*self.kernel(self.x[i],self.x[j])-self.kernel(self.x[i],self.x[i])-self.kernel(self.x[j],self.x[j]);if(ETA>=0)
continue;self.alphas[j]-=1.*self.y[j]*(E_i-E_j)/ETA;if(self.alphas[j]>H)
self.alphas[j]=H;else if(self.alphas[j]<L)
self.alphas[j]=L;if(Math.abs(self.alphas[j]-alpha_j_old)<alphatol)
continue;self.alphas[i]+=self.y[i]*self.y[j]*(alpha_j_old-self.alphas[j]);var b1=self.b-E_i-self.y[i]*(self.alphas[i]-alpha_i_old)*self.kernel(self.x[i],self.x[i])
-self.y[j]*(self.alphas[j]-alpha_j_old)*self.kernel(self.x[i],self.x[j]);var b2=self.b-E_j-self.y[i]*(self.alphas[i]-alpha_i_old)*self.kernel(self.x[i],self.x[j])
-self.y[j]*(self.alphas[j]-alpha_j_old)*self.kernel(self.x[j],self.x[j]);if(0<self.alphas[i]&&self.alphas[i]<C)
self.b=b1;else if(0<self.alphas[j]&&self.alphas[j]<C)
self.b=b2;else
self.b=(b1+b2)/2.0;numChangedAlphas++;}}
if(numChangedAlphas==0)
passes++;else
passes=0;}},predict:function(L,x){var self=L;this.kernel=getKernel(L.options.kernel);if(SVM.code.f(L,x)>=0)
return 1;else
return-1;},f:function(L,x){var self=L;var f=0,j;for(j=0;j<self.x.length;j++)
f+=self.alphas[j]*self.y[j]*self.kernel(self.x[j],x);f+=self.b;return f;}}
function getKernel(options){if(typeof options==='undefined'){return function(x,y){var sigma=1.0;return Math.exp(-1.*Math.pow(math.getNormVec(math.minusVec(x,y)),2)/(2*sigma*sigma));}}else if(typeof options==='function'){return options;}else if(options['type']==='gaussian'){return function(x,y){var sigma=options['sigma'];return Math.exp(-1.*Math.pow(math.getNormVec(math.minusVec(x,y)),2)/(2*sigma*sigma));}}else if(options['type']==='linear'){return function(x,y){return math.dotVec(x,y);}}else if(options['type']==='polynomial'){return function(x,y){var c=options['c'];var d=options['d'];return Math.pow(math.dotVec(x,y)+c,d);}}else if(options['type']==='rbf'){return function(v1,v2){var s=0;var sigma=options.sigma||options.rbfsigma||0.5;for(var q=0;q<v1.length;q++){s+=(v1[q]-v2[q])*(v1[q]-v2[q]);}
return Math.exp(-s/(2.0*sigma*sigma));}}}
var SVM2=function(options){var L={};L.data=options.x;L.labels=options.y;L.threshold=checkOption(options.threshold,0);return L};SVM2.code={train:function(L,options){var data=L.data,labels=L.labels;options=options||{};var C=options.C||1.0;var tol=options.tol||1e-4;var alphatol=options.alphatol||options.alpha_tol||1e-7;var maxiter=options.maxiter||10000;var numpasses=options.numpasses||options.max_passes||10;var kernel=linearKernel;L.kernelType="linear";L.options={kernel:options.kernel};if("kernel"in options){if(typeof options.kernel=='object'){kernel=getKernel(options.kernel);L.kernelType=options.kernel.type;L.rbfSigma=options.kernel.sigma||options.kernel.rbfsigma;}else if(typeof options.kernel=='function'){L.kernelType="custom";kernel=options.kernel;}}
L.options.C=C;L.options.tol=tol;L.options.alphatol=alphatol;L.options.iterations=numpasses;L.kernel=kernel;L.N=data.length;var N=L.N;L.D=data[0].length;var D=L.D;L.alpha=zeros(N);L.b=0.0;L.usew_=false;if(options.memoize){L.kernelResults=new Array(N);for(var i=0;i<N;i++){L.kernelResults[i]=new Array(N);for(var j=0;j<N;j++){L.kernelResults[i][j]=kernel(data[i],data[j]);}}}
var iter=0;var passes=0;while(passes<numpasses&&iter<maxiter){var alphaChanged=0;for(var i=0;i<N;i++){var Ei=SVM2.code.marginOne(L,data[i])-labels[i];if((labels[i]*Ei<-tol&&L.alpha[i]<C)||(labels[i]*Ei>tol&&L.alpha[i]>0)){var j=i;while(j===i)j=randi(0,L.N);var Ej=SVM2.code.marginOne(L,data[j])-labels[j];ai=L.alpha[i];aj=L.alpha[j];var Lb=0;var Hb=C;if(labels[i]===labels[j]){Lb=Math.max(0,ai+aj-C);Hb=Math.min(C,ai+aj);}else{Lb=Math.max(0,aj-ai);Hb=Math.min(C,C+aj-ai);}
if(Math.abs(Lb-Hb)<1e-4)continue;var eta=2*SVM2.code.kernelResult(L,i,j)-SVM2.code.kernelResult(L,i,i)-SVM2.code.kernelResult(L,j,j);if(eta>=0)continue;var newaj=aj-labels[j]*(Ei-Ej)/eta;if(newaj>Hb)newaj=Hb;if(newaj<Lb)newaj=Lb;if(Math.abs(aj-newaj)<1e-4)continue;L.alpha[j]=newaj;var newai=ai+labels[i]*labels[j]*(aj-newaj);L.alpha[i]=newai;var b1=L.b-Ei-labels[i]*(newai-ai)*SVM2.code.kernelResult(L,i,i)
-labels[j]*(newaj-aj)*SVM2.code.kernelResult(L,i,j);var b2=L.b-Ej-labels[i]*(newai-ai)*SVM2.code.kernelResult(L,i,j)
-labels[j]*(newaj-aj)*SVM2.code.kernelResult(L,j,j);L.b=0.5*(b1+b2);if(newai>0&&newai<C)L.b=b1;if(newaj>0&&newaj<C)L.b=b2;alphaChanged++;}}
iter++;if(alphaChanged==0)passes++;else passes=0;}
if(L.kernelType==="linear"){L.w=new Array(L.D);for(var j=0;j<L.D;j++){var s=0.0;for(var i=0;i<L.N;i++){s+=L.alpha[i]*labels[i]*data[i][j];}
L.w[j]=s;L.usew_=true;}}else{var newdata=[];var newlabels=[];var newalpha=[];for(var i=0;i<L.N;i++){if(L.alpha[i]>alphatol){newdata.push(L.data[i]);newlabels.push(L.labels[i]);newalpha.push(L.alpha[i]);}}
L.data=newdata;L.labels=newlabels;L.alpha=newalpha;L.N=L.data.length;}
var trainstats={};trainstats.iters=iter;trainstats.passes=passes;return trainstats;},marginOne:function(L,inst){var f=L.b;if(L.usew_){for(var j=0;j<L.D;j++){f+=inst[j]*L.w[j];}}else{for(var i=0;i<L.N;i++){f+=L.alpha[i]*L.labels[i]*L.kernel(inst,L.data[i]);}}
return f;},predict:function(L,inst){L.kernel=getKernel(L.options.kernel);var result=SVM2.code.marginOne(L,inst);if(L.threshold===false)return result;else return result>L.threshold?1:-1;},margins:function(L,data){var N=data.length;var margins=new Array(N);for(var i=0;i<N;i++){margins[i]=SVM2.code.marginOne(L,data[i]);}
return margins;},kernelResult:function(L,i,j){if(L.kernelResults){return L.kernelResults[i][j];}
return L.kernel(L.data[i],L.data[j]);},predictN:function(L,data){L.kernel=getKernel(L.options.kernel);var margs=SVM2.code.margins(L,data);for(var i=0;i<margs.length;i++){if(L.threshold!=false)
margs[i]=margs[i]>L.threshold?1:-1;}
return margs;},getWeights:function(L){var w=new Array(L.D);for(var j=0;j<L.D;j++){var s=0.0;for(var i=0;i<L.N;i++){s+=L.alpha[i]*L.labels[i]*L.data[i][j];}
w[j]=s;}
return{w:w,b:L.b};},toJSON:function(L){if(L.kernelType==="custom"){console.log("Can't save this SVM because it's using custom, unsupported kernel...");return{};}
json={}
json.N=L.N;json.D=L.D;json.b=L.b;json.kernelType=L.kernelType;if(L.kernelType==="linear"){json.w=L.w;}
if(L.kernelType==="rbf"){json.rbfSigma=L.rbfSigma;json.data=L.data;json.labels=L.labels;json.alpha=L.alpha;}
return json;},fromJSON:function(L,json){this.N=json.N;this.D=json.D;this.b=json.b;this.kernelType=json.kernelType;if(this.kernelType==="linear"){this.w=json.w;this.usew_=true;this.kernel=linearKernel;}
else if(this.kernelType=="rbf"){this.rbfSigma=json.rbfSigma;this.kernel=makeRbfKernel(this.rbfSigma);this.data=json.data;this.labels=json.labels;this.alpha=json.alpha;}else{console.log("ERROR! unrecognized kernel type."+this.kernelType);}}}
function makeRbfKernel(sigma){return function(v1,v2){var s=0;for(var q=0;q<v1.length;q++){s+=(v1[q]-v2[q])*(v1[q]-v2[q]);}
return Math.exp(-s/(2.0*sigma*sigma));}}
function linearKernel(v1,v2){var s=0;for(var q=0;q<v1.length;q++){s+=v1[q]*v2[q];}
return s;}
function randf(a,b){return Math.random()*(b-a)+a;}
function randi(a,b){return Math.floor(Math.random()*(b-a)+a);}
function zeros(n){var arr=new Array(n);for(var i=0;i<n;i++){arr[i]=0;}
return arr;}
module.exports=SVM2};BundleModuleCode['ml/mlp']=function(module,exports){var math=Require('ml/math');var HiddenLayer=Require('ml/HiddenLayer');var MLP=function(settings){var L={}
var self=L;self.x=settings.input||settings.x;self.y=settings.output||settings.y;self.sigmoidLayers=[];self.nLayers=settings.hidden_layer_sizes.length;self.settings={'log level':1,hidden_layers:settings.hidden_layer_sizes};var i;for(i=0;i<self.nLayers+1;i++){var inputSize,layerInput;if(i==0)
inputSize=settings.n_ins;else
inputSize=settings.hidden_layer_sizes[i-1];if(i==0)
layerInput=self.x;else
layerInput=HiddenLayer.code.sampleHgivenV(self.sigmoidLayers[self.sigmoidLayers.length-1]);var sigmoidLayer;if(i==self.nLayers){sigmoidLayer=HiddenLayer({'input':layerInput,'n_in':inputSize,'n_out':settings.n_outs,'activation':math.sigmoid,'W':(typeof settings.w_array==='undefined')?undefined:settings.w_array[i],'b':(typeof settings.b_array==='undefined')?undefined:settings.b_array[i]});}else{sigmoidLayer=HiddenLayer({'input':layerInput,'n_in':inputSize,'n_out':settings.hidden_layer_sizes[i],'activation':math.sigmoid,'W':(typeof settings.w_array==='undefined')?undefined:settings.w_array[i],'b':(typeof settings.b_array==='undefined')?undefined:settings.b_array[i]});}
self.sigmoidLayers.push(sigmoidLayer);}
return L};MLP.code={train:function(L,settings){try{var self=L;var t0=Date.now();settings=settings||{}
if(settings.input||settings.x)self.x=settings.input||settings.x;if(settings.output||settings.y)self.y=settings.output||settings.y;var epochs=1000;if(typeof settings.epochs!=='undefined')
epochs=settings.epochs;self.settings.iterations=epochs;var epoch;var currentProgress=1;for(epoch=0;epoch<epochs;epoch++){var i;var layerInput=[];layerInput.push(self.x);for(i=0;i<self.nLayers+1;i++){layerInput.push(HiddenLayer.code.output(self.sigmoidLayers[i],layerInput[i]));}
var output=layerInput[self.nLayers+1];var delta=new Array(self.nLayers+1);delta[self.nLayers]=math.mulMatElementWise(math.minusMat(self.y,output),math.activateMat(HiddenLayer.code.linearOutput(self.sigmoidLayers[self.nLayers],layerInput[self.nLayers]),math.dSigmoid));for(i=self.nLayers-1;i>=0;i--){delta[i]=math.mulMatElementWise(HiddenLayer.code.backPropagate(self.sigmoidLayers[i+1],delta[i+1]),math.activateMat(HiddenLayer.code.linearOutput(self.sigmoidLayers[i],layerInput[i]),math.dSigmoid));}
for(var i=0;i<self.nLayers+1;i++){var deltaW=math.activateMat(math.mulMat(math.transpose(layerInput[i]),delta[i]),function(x){return 1.*x/self.x.length;})
var deltaB=math.meanMatAxis(delta[i],0);self.sigmoidLayers[i].W=math.addMat(self.sigmoidLayers[i].W,deltaW);self.sigmoidLayers[i].b=math.addVec(self.sigmoidLayers[i].b,deltaB);}
if(self.settings['log level']>0){var progress=(1.*epoch/epochs)*100;if(progress>currentProgress){console.log("MLP",progress.toFixed(0),"% Completed.");currentProgress+=8;}}}
var crossentropy=MLP.code.getReconstructionCrossEntropy(L);if(self.settings['log level']>0)
console.log("MLP Final Cross Entropy : ",crossentropy);var t1=Date.now();return{time:t1-t0,epochs:epochs,loss:crossentropy,};}catch(e){console.log(e)}},getReconstructionCrossEntropy:function(L){var self=L;var reconstructedOutput=MLP.code.predict(L,self.x);var a=math.activateTwoMat(self.y,reconstructedOutput,function(x,y){return x*Math.log(y);});var b=math.activateTwoMat(self.y,reconstructedOutput,function(x,y){return(1-x)*Math.log(1-y);});var crossEntropy=-math.meanVec(math.sumMatAxis(math.addMat(a,b),1));return crossEntropy},predict:function(L,x){var self=L;var output=x;for(i=0;i<self.nLayers+1;i++){output=HiddenLayer.code.output(self.sigmoidLayers[i],output);}
return output;},set:function(L,property,value){var self=L;self.settings[property]=value;}}
module.exports=MLP};BundleModuleCode['ml/HiddenLayer']=function(module,exports){var math=Require('ml/math');var HiddenLayer=module.exports=function(settings){var L={}
var self=L;self.input=settings['input'];if(typeof settings['W']==='undefined'){var a=1./settings['n_in'];settings['W']=math.randMat(settings['n_in'],settings['n_out'],-a,a);}
if(typeof settings['b']==='undefined')
settings['b']=math.zeroVec(settings['n_out']);if(typeof settings['activation']==='undefined')
settings['activation']=math.sigmoid;self.W=settings['W'];self.b=settings['b'];self.activation=settings['activation'];return L;}
HiddenLayer.code={output:function(L,input){var self=L;if(typeof input!=='undefined')
self.input=input;var linearOutput=math.addMatVec(math.mulMat(self.input,self.W),self.b);return math.activateMat(linearOutput,self.activation);},linearOutput:function(L,input){var self=L;if(typeof input!=='undefined')
self.input=input;var linearOutput=math.addMatVec(math.mulMat(self.input,self.W),self.b);return linearOutput;},backPropagate:function(L,input){var self=L;if(typeof input==='undefined')
throw new Error("No BackPropagation Input.")
var linearOutput=math.mulMat(input,math.transpose(self.W));return linearOutput;},sampleHgivenV:function(L,input){var self=L;if(typeof input!=='undefined')
self.input=input;var hMean=HiddenLayer.code.output(self);var hSample=math.probToBinaryMat(hMean);return hSample;}}};BundleModuleCode['ml/id3']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var NODE_TYPES={RESULT:'result',FEATURE:'feature',FEATURE_VALUE:'feature_value'};function isEqual(a,b){return a==b}
function predict(model,sample){var root=model;while(root.type!==NODE_TYPES.RESULT){var attr=root.name;var sampleVal=sample[attr];var childNode=Comp.array.min(root.vals,function(node){if(typeof node.value=='number'&&typeof sampleVal=='number')
return Math.pow(node.value-sampleVal,2);else
return node.value==sampleVal?0:1;});if(childNode){root=childNode.child;}else{root=root.vals[0].child;}}
return root.value;};function evaluate(model,target,samples){var total=0;var correct=0;Comp.array.iter(samples,function(s){total++;var pred=predict(model,s);var actual=s[target];if(isEqual(pred,actual)){correct++;}});return correct/total;};function createTree(data,target,features){var targets=Comp.array.unique(Comp.array.pluck(data,target));if(targets.length==1){return{type:NODE_TYPES.RESULT,value:targets[0],name:targets[0],};}
if(features.length==0){var topTarget=mostCommon(targets);return{type:NODE_TYPES.RESULT,value:topTarget,name:topTarget,};}
var bestFeature=maxGain(data,target,features);var remainingFeatures=Comp.array.without(features,bestFeature);var possibleValues=Comp.array.unique(Comp.array.pluck(data,bestFeature));var node={name:bestFeature,};node.type=NODE_TYPES.FEATURE;node.vals=Comp.array.map(possibleValues,function(v){var _newS=data.filter(function(x){return x[bestFeature]==v});var child_node={value:v,type:NODE_TYPES.FEATURE_VALUE};child_node.child=createTree(_newS,target,remainingFeatures);return child_node;});return node;}
function maxGain(data,target,features){var gains=[];var maxgain=Comp.array.max(features,function(element){var g=gain(data,target,element);gains.push(element+':'+g);return g;});return maxgain;}
function entropy(vals){var uniqueVals=Comp.array.unique(vals);var probs=uniqueVals.map(function(x){return prob(x,vals)});var logVals=probs.map(function(p){return-p*log2(p)});return logVals.reduce(function(a,b){return a+b},0);}
function gain(data,target,feature){var attrVals=Comp.array.unique(Comp.array.pluck(data,feature));var setEntropy=entropy(Comp.array.pluck(data,target));var setSize=data.length;var entropies=attrVals.map(function(n){var subset=data.filter(function(x){return x[feature]===n});return(subset.length/setSize)*entropy(Comp.array.pluck(subset,target));});var sumOfEntropies=entropies.reduce(function(a,b){return a+b},0);return setEntropy-sumOfEntropies;}
function prob(value,list){var occurrences=Comp.array.filter(list,function(element){return element===value});var numOccurrences=occurrences.length;var numElements=list.length;return numOccurrences/numElements;}
function log2(n){return Math.log(n)/Math.log(2);}
function mostCommon(list){var elementFrequencyMap={};var largestFrequency=-1;var mostCommonElement=null;list.forEach(function(element){var elementFrequency=(elementFrequencyMap[element]||0)+1;elementFrequencyMap[element]=elementFrequency;if(largestFrequency<elementFrequency){mostCommonElement=element;largestFrequency=elementFrequency;}});return mostCommonElement;}
function randomUUID(){return"_r"+Math.random().toString(32).slice(2);}
function depth(model){switch(model.type){case NODE_TYPES.RESULT:return 1;case NODE_TYPES.FEATURE:return 1+Comp.array.max(model.vals.map(function(val){return depth(val);}));case NODE_TYPES.FEATURE_VALUE:return 1+depth(model.child);}
return 0;}
function info(model){var vl=vars(model);return{depth:depth(model),nodes:vl.length,vars:vl.unique(),}}
function print(model,indent){var NL='\n',line='',sep,sp=function(){return Comp.string.create(indent);};if(indent==undefined)indent=0;switch(model.type){case NODE_TYPES.RESULT:return' -> '+model.name;case NODE_TYPES.FEATURE:line=NL+sp()+'($'+model.name+'?'+NL;sep='';Comp.array.iter(model.vals,function(v){line+=sep+print(v,indent+2)+NL;sep='';});return line+sp()+')';case NODE_TYPES.FEATURE_VALUE:return sp()+model.value+':'+print(model.child,indent+2);}
return 0;}
function vars(model){switch(model.type){case NODE_TYPES.RESULT:return[];case NODE_TYPES.FEATURE:return[model.name].concat(Comp.array.flatten(model.vals.map(vars)));case NODE_TYPES.FEATURE_VALUE:return vars(model.child);}
return[];}
module.exports={NODE_TYPES:NODE_TYPES,createTree:createTree,depth:depth,entropy:entropy,evaluate:evaluate,info:info,predict:predict,print:print,current:function(module){current=module.current;Aios=module;}};};BundleModuleCode['ml/C45']=function(module,exports){'use strict';var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var NODE_TYPES={RESULT:'result',FEATURE_NUMBER:'feature_number',FEATURE_VALUE:'feature_value',FEATURE_CATEGORY:'feature_category'};function unique(col){var u={},a=[];for(var i=0,l=col.length;i<l;++i){if(u.hasOwnProperty(col[i])){continue;}
a.push(col[i]);u[col[i]]=1;}
return a;}
function find(col,pred){var value;col.forEach(function(item){var result=pred(item);if(result){value=item;}});return value;}
function max(array,fn){var max=-Infinity;var index;for(var i=0;i<array.length;i++){var result=fn(array[i]);if(result>=max){max=result;index=i;}}
return typeof index!=='undefined'?array[index]:max;}
function sortBy(col,fn){col=[].slice.call(col);return col.sort(fn);}
var C45={create:function(){return{features:[],targets:[],model:null}},train:function(model,options){var data=options.data,target=options.target,features=options.features,featureTypes=options.featureTypes;featureTypes.forEach(function(f){if(['number','category'].indexOf(f)===-1){throw new Error('C4.5: Unrecognized option!');}});var targets=unique(data.map(function(d){return d[d.length-1];}));model.features=features;model.targets=targets;model.model=C45._c45(model,data,target,features,featureTypes,0);},_c45:function(model,data,target,features,featureTypes,depth){var targets=unique(data.map(function(d){return d[d.length-1];}));if(!targets.length){return{type:'result',value:'none data',name:'none data'};}
if(targets.length===1){return{type:'result',value:targets[0],name:targets[0]};}
if(!features.length){var topTarget=C45.mostCommon(targets);return{type:'result',value:topTarget,name:topTarget};}
var bestFeatureData=C45.maxGain(model,data,target,features,featureTypes);var bestFeature=bestFeatureData.feature;var remainingFeatures=features.slice(0);remainingFeatures.splice(features.indexOf(bestFeature),1);if(featureTypes[model.features.indexOf(bestFeature)]==='category'){var possibleValues=unique(data.map(function(d){return d[model.features.indexOf(bestFeature)];}));var node={name:bestFeature,type:'feature_category',values:possibleValues.map(function(v){var newData=data.filter(function(x){return x[model.features.indexOf(bestFeature)]===v;});var childNode={name:v,type:'feature_value',child:C45._c45(model,newData,target,remainingFeatures,featureTypes,depth+1)};return childNode;})};}else if(featureTypes[model.features.indexOf(bestFeature)]==='number'){var possibleValues=unique(data.map(function(d){return d[model.features.indexOf(bestFeature)];}));var node={name:bestFeature,type:'feature_number',cut:bestFeatureData.cut,values:[]};var newDataRight=data.filter(function(x){return parseFloat(x[model.features.indexOf(bestFeature)])>bestFeatureData.cut;});var childNodeRight={name:bestFeatureData.cut.toString(),type:'feature_value',child:C45._c45(model,newDataRight,target,remainingFeatures,featureTypes,depth+1)};node.values.push(childNodeRight);var newDataLeft=data.filter(function(x){return parseFloat(x[model.features.indexOf(bestFeature)])<=bestFeatureData.cut;});var childNodeLeft={name:bestFeatureData.cut.toString(),type:'feature_value',child:C45._c45(model,newDataLeft,target,remainingFeatures,featureTypes,depth+1),};node.values.push(childNodeLeft);}
return node;},classify:function(model,sample){var childNode,featureName,sampleVal;var root=model.model;if(typeof root==='undefined'){callback(new Error('model is undefined'));}
while(root.type!=NODE_TYPES.RESULT){if(root.type==NODE_TYPES.FEATURE_NUMBER){featureName=root.name;sampleVal=parseFloat(sample[featureName]);if(sampleVal<=root.cut){childNode=root.values[1];}else{childNode=root.values[0];}}else if(root.type==NODE_TYPES.FEATURE_CATEGORY){featureName=root.name;sampleVal=sample[featureName];childNode=find(root.values,function(x){return x.name===sampleVal;});}
if(typeof childNode==='undefined'){return'unknown';}
root=childNode.child;}
return root.value;},conditionalEntropy:function(model,data,feature,cut,target){var subset1=data.filter(function(x){return parseFloat(x[model.features.indexOf(feature)])<=cut;});var subset2=data.filter(function(x){return parseFloat(x[model.features.indexOf(feature)])>cut;});var setSize=data.length;return subset1.length/setSize*C45.entropy(model,subset1.map(function(d){return d[d.length-1];}))+subset2.length/setSize*C45.entropy(model,subset2.map(function(d){return d[d.length-1];}));},count:function(target,targets){return targets.filter(function(t){return t===target;}).length;},entropy:function(model,vals){var uniqueVals=unique(vals);var probs=uniqueVals.map(function(x){return C45.prob(x,vals);});var logVals=probs.map(function(p){return-p*C45.log2(p);});return logVals.reduce(function(a,b){return a+b;},0);},gain:function(model,data,target,features,feature,featureTypes){var setEntropy=C45.entropy(model,data.map(function(d){return d[d.length-1];}));if(featureTypes[model.features.indexOf(feature)]==='category'){var attrVals=unique(data.map(function(d){return d[model.features.indexOf(feature)];}));var setSize=data.length;var entropies=attrVals.map(function(n){var subset=data.filter(function(x){return x[feature]===n;});return(subset.length/setSize)*C45.entropy(model,subset.map(function(d){return d[d.length-1];}));});var sumOfEntropies=entropies.reduce(function(a,b){return a+b;},0);return{feature:feature,gain:setEntropy-sumOfEntropies,cut:0};}else if(featureTypes[model.features.indexOf(feature)]==='number'){var attrVals=unique(data.map(function(d){return d[model.features.indexOf(feature)];}));var gainVals=attrVals.map(function(cut){var cutf=parseFloat(cut);var gain=setEntropy-C45.conditionalEntropy(model,data,feature,cutf,target);return{feature:feature,gain:gain,cut:cutf};});var maxgain=max(gainVals,function(e){return e.gain;});return maxgain;}},log2:function(n){return Math.log(n)/Math.log(2);},maxGain:function(model,data,target,features,featureTypes){var g45=features.map(function(feature){return C45.gain(model,data,target,features,feature,featureTypes);});return max(g45,function(e){return e.gain;});},mostCommon:function(targets){return sortBy(targets,function(target){return C45.count(target,targets);}).reverse()[0];},print:function(model,indent){var NL='\n',line='',sep;if(indent==undefined)indent=0;if(!model)return'';var sp=function(){return Comp.string.create(indent);};switch(model.type){case NODE_TYPES.RESULT:return sp()+'-> '+model.name+NL;case NODE_TYPES.FEATURE_CATEGORY:line=sp()+'$'+model.name+'?'+NL;Comp.array.iter(model.values,function(v){line+=C45.print(v,indent+2);});return line;case NODE_TYPES.FEATURE_NUMBER:line=sp()+'$'+model.name+'>'+model.cut+'?'+NL;if(model.values[0].type==NODE_TYPES.FEATURE_VALUE)
line=line+C45.print(model.values[0].child,indent+2);else
line=line+C45.print(model.values[0],indent+2);line=line+sp()+'$'+model.name+'<='+model.cut+'?'+NL;if(model.values[0].type==NODE_TYPES.FEATURE_VALUE)
line=line+C45.print(model.values[1].child,indent+2);else
line=line+C45.print(model.values[1],indent+2);return line;case NODE_TYPES.FEATURE_VALUE:line=sp()+''+model.name+NL;line+=C45.print(model.child,indent+2);return line;}
return'model?';},prob:function(target,targets){return C45.count(target,targets)/targets.length;},};module.exports={classify:C45.classify,create:C45.create,entropy:C45.entropy,log2:C45.log2,print:function(model,indent){return C45.print(model.model,indent)},unique:unique,train:C45.train,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['ml/text']=function(module,exports){'use strict';var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;function similarity(s1,s2){var longer=s1;var shorter=s2;if(s1.length<s2.length){longer=s2;shorter=s1;}
var longerLength=longer.length;if(longerLength==0){return 1.0;}
return(longerLength-editDistance(longer,shorter))/parseFloat(longerLength);}
function editDistance(s1,s2){s1=s1.toLowerCase();s2=s2.toLowerCase();var costs=new Array();for(var i=0;i<=s1.length;i++){var lastValue=i;for(var j=0;j<=s2.length;j++){if(i==0)
costs[j]=j;else{if(j>0){var newValue=costs[j-1];if(s1.charAt(i-1)!=s2.charAt(j-1))
newValue=Math.min(Math.min(newValue,lastValue),costs[j])+1;costs[j-1]=lastValue;lastValue=newValue;}}}
if(i>0)
costs[s2.length]=lastValue;}
return costs[s2.length];}
function create(strings,options){return{data:strings}}
function classify(model,sample){var matches=model.data.map(function(h){return{match:similarity(h,sample),string:h}}).sort(function(a,b){if(a.match<b.match)return 1;else return-1;});return matches[0];}
module.exports={classify:classify,create:create,similarity:similarity,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['ml/rf']=function(module,exports){var RandomForest=function(options){var L={};return L}
RandomForest.code={train:function(L,data,labels,options){options=options||{};L.options=options;L.numTrees=options.numTrees||100;L.trees=new Array(L.numTrees);for(var i=0;i<L.numTrees;i++){L.trees[i]=DecisionTree();DecisionTree.code.train(L.trees[i],data,labels,options);}},predictOne:function(L,inst){var dec=0;for(var i=0;i<L.numTrees;i++){dec+=DecisionTree.code.predictOne(L.trees[i],inst);}
dec/=L.numTrees;return dec;},predict:function(L,data){var probabilities=new Array(data.length);for(var i=0;i<data.length;i++){probabilities[i]=RandomForest.code.predictOne(L,data[i]);}
return probabilities;}}
var DecisionTree=function(options){var L={};return L}
DecisionTree.code={train:function(L,data,labels,options){options=options||{};var maxDepth=options.maxDepth||4;var weakType=options.type||0;var trainFun=decisionStumpTrain;var testFun=decisionStumpTest;if(options.trainFun)trainFun=options.trainFun;if(options.testFun)testFun=options.testFun;if(weakType==0){trainFun=decisionStumpTrain;testFun=decisionStumpTest;}
if(weakType){trainFun=decision2DStumpTrain;L.testFun=testFun=decision2DStumpTest;}
var numInternals=Math.pow(2,maxDepth)-1;var numNodes=Math.pow(2,maxDepth+1)-1;var ixs=new Array(numNodes);for(var i=1;i<ixs.length;i++)ixs[i]=[];ixs[0]=new Array(labels.length);for(var i=0;i<labels.length;i++)ixs[0][i]=i;var models=new Array(numInternals);for(var n=0;n<numInternals;n++){var ixhere=ixs[n];if(ixhere.length==0){continue;}
if(ixhere.length==1){ixs[n*2+1]=[ixhere[0]];continue;}
var model=trainFun(data,labels,ixhere);models[n]=model;var ixleft=[];var ixright=[];for(var i=0;i<ixhere.length;i++){var label=testFun(data[ixhere[i]],model);if(label===1)ixleft.push(ixhere[i]);else ixright.push(ixhere[i]);}
ixs[n*2+1]=ixleft;ixs[n*2+2]=ixright;}
var leafPositives=new Array(numNodes);var leafNegatives=new Array(numNodes);for(var n=numInternals;n<numNodes;n++){var numones=0;for(var i=0;i<ixs[n].length;i++){if(labels[ixs[n][i]]===1)numones+=1;}
leafPositives[n]=numones;leafNegatives[n]=ixs[n].length-numones;}
L.models=models;L.leafPositives=leafPositives;L.leafNegatives=leafNegatives;L.maxDepth=maxDepth;},predictOne:function(L,inst){var testFun=L.testFun||decisionStumpTest;var n=0;for(var i=0;i<L.maxDepth;i++){var dir=testFun(inst,L.models[n]);if(dir===1)n=n*2+1;else n=n*2+2;}
return(L.leafPositives[n]+0.5)/(L.leafNegatives[n]+1.0);}}
function decisionStumpTrain(data,labels,ix,options){options=options||{};var numtries=options.numTries||10;var ri=randi(0,data[0].length);var N=ix.length;var H=entropy(labels,ix);var bestGain=0;var bestThr=0;for(var i=0;i<numtries;i++){var ix1=ix[randi(0,N)];var ix2=ix[randi(0,N)];while(ix2==ix1)ix2=ix[randi(0,N)];var a=Math.random();var thr=data[ix1][ri]*a+data[ix2][ri]*(1-a);var l1=1,r1=1,lm1=1,rm1=1;for(var j=0;j<ix.length;j++){if(data[ix[j]][ri]<thr){if(labels[ix[j]]==1)l1++;else lm1++;}else{if(labels[ix[j]]==1)r1++;else rm1++;}}
var t=l1+lm1;l1=l1/t;lm1=lm1/t;t=r1+rm1;r1=r1/t;rm1=rm1/t;var LH=-l1*Math.log(l1)-lm1*Math.log(lm1);var RH=-r1*Math.log(r1)-rm1*Math.log(rm1);var informationGain=H-LH-RH;if(informationGain>bestGain||i===0){bestGain=informationGain;bestThr=thr;}}
model={};model.thr=bestThr;model.ri=ri;return model;}
function decisionStumpTest(inst,model){if(!model){return 1;}
return inst[model.ri]<model.thr?1:-1;}
function decision2DStumpTrain(data,labels,ix,options){options=options||{};var numtries=options.numTries||10;var N=ix.length;var ri1=0;var ri2=1;if(data[0].length>2){ri1=randi(0,data[0].length);ri2=randi(0,data[0].length);while(ri2==ri1)ri2=randi(0,data[0].length);}
var H=entropy(labels,ix);var bestGain=0;var bestw1,bestw2,bestthr;var dots=new Array(ix.length);for(var i=0;i<numtries;i++){var alpha=randf(0,2*Math.PI);var w1=Math.cos(alpha);var w2=Math.sin(alpha);for(var j=0;j<ix.length;j++){dots[j]=w1*data[ix[j]][ri1]+w2*data[ix[j]][ri2];}
var ix1=ix[randi(0,N)];var ix2=ix[randi(0,N)];while(ix2==ix1)ix2=ix[randi(0,N)];var a=Math.random();var dotthr=dots[ix1]*a+dots[ix2]*(1-a);var l1=1,r1=1,lm1=1,rm1=1;for(var j=0;j<ix.length;j++){if(dots[j]<dotthr){if(labels[ix[j]]==1)l1++;else lm1++;}else{if(labels[ix[j]]==1)r1++;else rm1++;}}
var t=l1+lm1;l1=l1/t;lm1=lm1/t;t=r1+rm1;r1=r1/t;rm1=rm1/t;var LH=-l1*Math.log(l1)-lm1*Math.log(lm1);var RH=-r1*Math.log(r1)-rm1*Math.log(rm1);var informationGain=H-LH-RH;if(informationGain>bestGain||i===0){bestGain=informationGain;bestw1=w1;bestw2=w2;bestthr=dotthr;}}
model={};model.w1=bestw1;model.w2=bestw2;model.dotthr=bestthr;return model;}
function decision2DStumpTest(inst,model){if(!model){return 1;}
return inst[0]*model.w1+inst[1]*model.w2<model.dotthr?1:-1;}
function entropy(labels,ix){var N=ix.length;var p=0.0;for(var i=0;i<N;i++){if(labels[ix[i]]==1)p+=1;}
p=(1+p)/(N+2);q=(1+N-p)/(N+2);return(-p*Math.log(p)-q*Math.log(q));}
function randf(a,b){return Math.random()*(b-a)+a;}
function randi(a,b){return Math.floor(Math.random()*(b-a)+a);}
module.exports=RandomForest};BundleModuleCode['ml/rl']=function(module,exports){"use strict";var options={version:'1.1.2'}
var Io=Require('com/io')
var R=module.exports;function assert(condition,message){if(!condition){message=message||"Assertion failed";if(typeof Error!=="undefined"){throw new Error(message);}
throw message;}}
var return_v=false;var v_val=0.0;var gaussRandom=function(){if(return_v){return_v=false;return v_val;}
var u=2*Math.random()-1;var v=2*Math.random()-1;var r=u*u+v*v;if(r==0||r>1)return gaussRandom();var c=Math.sqrt(-2*Math.log(r)/r);v_val=v*c;return_v=true;return u*c;}
var randf=function(a,b){return Math.random()*(b-a)+a;}
var randi=function(a,b){return Math.floor(Math.random()*(b-a)+a);}
var randn=function(mu,std){return mu+gaussRandom()*std;}
var zeros=function(n){if(typeof(n)==='undefined'||isNaN(n)){return[];}
if(typeof ArrayBuffer==='undefined'){var arr=new Array(n);for(var i=0;i<n;i++){arr[i]=0;}
return arr;}else{return new Float64Array(n);}}
var Mat=function(n,d){var M={}
M.n=n;M.d=d;M.w=zeros(n*d);M.dw=zeros(n*d);return M;}
Mat.code={get:function(M,row,col){var ix=(M.d*row)+col;assert(ix>=0&&ix<M.w.length);return M.w[ix];},set:function(M,row,col,v){var ix=(M.d*row)+col;assert(ix>=0&&ix<M.w.length);M.w[ix]=v;},setFrom:function(M,arr){for(var i=0,n=arr.length;i<n;i++){M.w[i]=arr[i];}},setColumn:function(M,m,i){for(var q=0,n=m.w.length;q<n;q++){M.w[(M.d*q)+i]=m.w[q];}},toJSON:function(M){var json={};json['n']=M.n;json['d']=M.d;json['w']=M.w;return json;},fromJSON:function(M,json){M.n=json.n;M.d=json.d;M.w=zeros(M.n*M.d);M.dw=zeros(M.n*M.d);for(var i=0,n=M.n*M.d;i<n;i++){M.w[i]=json.w[i];}}}
var copyMat=function(b){var a=Mat(b.n,b.d);Mat.code.setFrom(a,b.w);return a;}
var copyNet=function(net){var new_net={};for(var p in net){if(net.hasOwnProperty(p)){new_net[p]=copyMat(net[p]);}}
return new_net;}
var updateMat=function(m,alpha){for(var i=0,n=m.n*m.d;i<n;i++){if(m.dw[i]!==0){m.w[i]+=-alpha*m.dw[i];m.dw[i]=0;}}}
var updateNet=function(net,alpha){for(var p in net){if(net.hasOwnProperty(p)){updateMat(net[p],alpha);}}}
var netToJSON=function(net){var j={};for(var p in net){if(net.hasOwnProperty(p)){j[p]=Mat.code.toJSON(net[p]);}}
return j;}
var netFromJSON=function(j){var net={};for(var p in j){if(j.hasOwnProperty(p)){net[p]=Mat(1,1);Mat.code.fromJSON(net[p],j[p]);}}
return net;}
var netZeroGrads=function(net){for(var p in net){if(net.hasOwnProperty(p)){var mat=net[p];gradFillConst(mat,0);}}}
var netFlattenGrads=function(net){var n=0;for(var p in net){if(net.hasOwnProperty(p)){var mat=net[p];n+=mat.dw.length;}}
var g=Mat(n,1);var ix=0;for(var p in net){if(net.hasOwnProperty(p)){var mat=net[p];for(var i=0,m=mat.dw.length;i<m;i++){g.w[ix]=mat.dw[i];ix++;}}}
return g;}
var RandMat=function(n,d,mu,std){var m=Mat(n,d);fillRandn(m,mu,std);return m;}
var fillRandn=function(m,mu,std){for(var i=0,n=m.w.length;i<n;i++){m.w[i]=randn(mu,std);}}
var fillRand=function(m,lo,hi){for(var i=0,n=m.w.length;i<n;i++){m.w[i]=randf(lo,hi);}}
var gradFillConst=function(m,c){for(var i=0,n=m.dw.length;i<n;i++){m.dw[i]=c}}
var Graph=function(needs_backprop){var G={}
if(typeof needs_backprop==='undefined'){needs_backprop=true;}
G.needs_backprop=needs_backprop;G.backprop=[];return G}
Graph.code={backward:function(G){for(var i=G.backprop.length-1;i>=0;i--){G.backprop[i]();}},rowPluck:function(G,m,ix){assert(ix>=0&&ix<m.n);var d=m.d;var out=Mat(d,1);for(var i=0,n=d;i<n;i++){out.w[i]=m.w[d*ix+i];}
if(G.needs_backprop){var backward=function(){for(var i=0,n=d;i<n;i++){m.dw[d*ix+i]+=out.dw[i];}}
G.backprop.push(backward);}
return out;},tanh:function(G,m){var out=Mat(m.n,m.d);var n=m.w.length;for(var i=0;i<n;i++){out.w[i]=Math.tanh(m.w[i]);}
if(G.needs_backprop){var backward=function(){for(var i=0;i<n;i++){var mwi=out.w[i];m.dw[i]+=(1.0-mwi*mwi)*out.dw[i];}}
G.backprop.push(backward);}
return out;},sigmoid:function(G,m){var out=Mat(m.n,m.d);var n=m.w.length;for(var i=0;i<n;i++){out.w[i]=sig(m.w[i]);}
if(G.needs_backprop){var backward=function(){for(var i=0;i<n;i++){var mwi=out.w[i];m.dw[i]+=mwi*(1.0-mwi)*out.dw[i];}}
G.backprop.push(backward);}
return out;},relu:function(G,m){var out=Mat(m.n,m.d);var n=m.w.length;for(var i=0;i<n;i++){out.w[i]=Math.max(0,m.w[i]);}
if(G.needs_backprop){var backward=function(){for(var i=0;i<n;i++){m.dw[i]+=m.w[i]>0?out.dw[i]:0.0;}}
G.backprop.push(backward);}
return out;},mul:function(G,m1,m2){assert(m1.d===m2.n,'matmul dimensions misaligned');var n=m1.n;var d=m2.d;var out=Mat(n,d);for(var i=0;i<m1.n;i++){for(var j=0;j<m2.d;j++){var dot=0.0;for(var k=0;k<m1.d;k++){dot+=m1.w[m1.d*i+k]*m2.w[m2.d*k+j];}
out.w[d*i+j]=dot;}}
if(G.needs_backprop){var backward=function(){for(var i=0;i<m1.n;i++){for(var j=0;j<m2.d;j++){for(var k=0;k<m1.d;k++){var b=out.dw[d*i+j];m1.dw[m1.d*i+k]+=m2.w[m2.d*k+j]*b;m2.dw[m2.d*k+j]+=m1.w[m1.d*i+k]*b;}}}}
G.backprop.push(backward);}
return out;},add:function(G,m1,m2){assert(m1.w.length===m2.w.length);var out=Mat(m1.n,m1.d);for(var i=0,n=m1.w.length;i<n;i++){out.w[i]=m1.w[i]+m2.w[i];}
if(G.needs_backprop){var backward=function(){for(var i=0,n=m1.w.length;i<n;i++){m1.dw[i]+=out.dw[i];m2.dw[i]+=out.dw[i];}}
G.backprop.push(backward);}
return out;},dot:function(G,m1,m2){assert(m1.w.length===m2.w.length);var out=Mat(1,1);var dot=0.0;for(var i=0,n=m1.w.length;i<n;i++){dot+=m1.w[i]*m2.w[i];}
out.w[0]=dot;if(G.needs_backprop){var backward=function(){for(var i=0,n=m1.w.length;i<n;i++){m1.dw[i]+=m2.w[i]*out.dw[0];m2.dw[i]+=m1.w[i]*out.dw[0];}}
G.backprop.push(backward);}
return out;},eltmul:function(G,m1,m2){assert(m1.w.length===m2.w.length);var out=Mat(m1.n,m1.d);for(var i=0,n=m1.w.length;i<n;i++){out.w[i]=m1.w[i]*m2.w[i];}
if(G.needs_backprop){var backward=function(){for(var i=0,n=m1.w.length;i<n;i++){m1.dw[i]+=m2.w[i]*out.dw[i];m2.dw[i]+=m1.w[i]*out.dw[i];}}
G.backprop.push(backward);}
return out;},}
var softmax=function(m){var out=Mat(m.n,m.d);var maxval=-999999;for(var i=0,n=m.w.length;i<n;i++){if(m.w[i]>maxval)maxval=m.w[i];}
var s=0.0;for(var i=0,n=m.w.length;i<n;i++){out.w[i]=Math.exp(m.w[i]-maxval);s+=out.w[i];}
for(var i=0,n=m.w.length;i<n;i++){out.w[i]/=s;}
return out;}
var Solver=function(){var S={}
S.decay_rate=0.999;S.smooth_eps=1e-8;S.step_cache={};return S}
Solver.code={step:function(S,model,step_size,regc,clipval){var solver_stats={};var num_clipped=0;var num_tot=0;for(var k in model){if(model.hasOwnProperty(k)){var m=model[k];if(!(k in S.step_cache)){S.step_cache[k]=Mat(m.n,m.d);}
var s=S.step_cache[k];for(var i=0,n=m.w.length;i<n;i++){var mdwi=m.dw[i];s.w[i]=s.w[i]*S.decay_rate+(1.0-S.decay_rate)*mdwi*mdwi;if(mdwi>clipval){mdwi=clipval;num_clipped++;}
if(mdwi<-clipval){mdwi=-clipval;num_clipped++;}
num_tot++;m.w[i]+=-step_size*mdwi/Math.sqrt(s.w[i]+S.smooth_eps)-regc*m.w[i];m.dw[i]=0;}}}
solver_stats['ratio_clipped']=num_clipped*1.0/num_tot;return solver_stats;}}
var initLSTM=function(input_size,hidden_sizes,output_size){var model={};for(var d=0;d<hidden_sizes.length;d++){var prev_size=d===0?input_size:hidden_sizes[d-1];var hidden_size=hidden_sizes[d];model['Wix'+d]=RandMat(hidden_size,prev_size,0,0.08);model['Wih'+d]=RandMat(hidden_size,hidden_size,0,0.08);model['bi'+d]=Mat(hidden_size,1);model['Wfx'+d]=RandMat(hidden_size,prev_size,0,0.08);model['Wfh'+d]=RandMat(hidden_size,hidden_size,0,0.08);model['bf'+d]=Mat(hidden_size,1);model['Wox'+d]=RandMat(hidden_size,prev_size,0,0.08);model['Woh'+d]=RandMat(hidden_size,hidden_size,0,0.08);model['bo'+d]=Mat(hidden_size,1);model['Wcx'+d]=RandMat(hidden_size,prev_size,0,0.08);model['Wch'+d]=RandMat(hidden_size,hidden_size,0,0.08);model['bc'+d]=Mat(hidden_size,1);}
model['Whd']=RandMat(output_size,hidden_size,0,0.08);model['bd']=Mat(output_size,1);return model;}
var forwardLSTM=function(G,model,hidden_sizes,x,prev){if(prev==null||typeof prev.h==='undefined'){var hidden_prevs=[];var cell_prevs=[];for(var d=0;d<hidden_sizes.length;d++){hidden_prevs.push(R.Mat(hidden_sizes[d],1));cell_prevs.push(R.Mat(hidden_sizes[d],1));}}else{var hidden_prevs=prev.h;var cell_prevs=prev.c;}
var hidden=[];var cell=[];for(var d=0;d<hidden_sizes.length;d++){var input_vector=d===0?x:hidden[d-1];var hidden_prev=hidden_prevs[d];var cell_prev=cell_prevs[d];var h0=Graph.code.mul(G,model['Wix'+d],input_vector);var h1=Graph.code.mul(G,model['Wih'+d],hidden_prev);var input_gate=Graph.code.sigmoid(G,Graph.code.add(G,Graph.code.add(G,h0,h1),model['bi'+d]));var h2=Graph.code.mul(G,model['Wfx'+d],input_vector);var h3=Graph.code.mul(G,model['Wfh'+d],hidden_prev);var forget_gate=Graph.code.sigmoid(G,Graph.code.add(G,Graph.code.add(G,h2,h3),model['bf'+d]));var h4=Graph.code.mul(G,model['Wox'+d],input_vector);var h5=Graph.code.mul(G,model['Woh'+d],hidden_prev);var output_gate=Graph.code.sigmoid(G,Graph.code.add(G,Graph.code.add(G,h4,h5),model['bo'+d]));var h6=Graph.code.mul(G,model['Wcx'+d],input_vector);var h7=Graph.code.mul(G,model['Wch'+d],hidden_prev);var cell_write=Graph.code.tanh(G,Graph.code.add(G,Graph.code.add(G,h6,h7),model['bc'+d]));var retain_cell=Graph.code.eltmul(G,forget_gate,cell_prev);var write_cell=Graph.code.eltmul(G,input_gate,cell_write);var cell_d=Graph.code.add(G,retain_cell,write_cell);var hidden_d=Graph.code.eltmul(G,output_gate,Graph.code.tanh(G,cell_d));hidden.push(hidden_d);cell.push(cell_d);}
var output=Graph.code.add(G,Graph.code.mul(G,model['Whd'],hidden[hidden.length-1]),model['bd']);return{'h':hidden,'c':cell,'o':output};}
var sig=function(x){return 1.0/(1+Math.exp(-x));}
var maxi=function(w){var maxv=w[0];var maxix=0;for(var i=1,n=w.length;i<n;i++){var v=w[i];if(v>maxv){maxix=i;maxv=v;}}
return maxix;}
var samplei=function(w){var r=randf(0,1);var x=0.0;var i=0;while(true){x+=w[i];if(x>r){return i;}
i++;}
return w.length-1;}
module.exports.assert=assert;module.exports.zeros=zeros;module.exports.maxi=maxi;module.exports.samplei=samplei;module.exports.randi=randi;module.exports.randn=randn;module.exports.softmax=softmax;module.exports.Mat=Mat;module.exports.RandMat=RandMat;module.exports.forwardLSTM=forwardLSTM;module.exports.initLSTM=initLSTM;module.exports.updateMat=updateMat;module.exports.updateNet=updateNet;module.exports.copyMat=copyMat;module.exports.copyNet=copyNet;module.exports.netToJSON=netToJSON;module.exports.netFromJSON=netFromJSON;module.exports.netZeroGrads=netZeroGrads;module.exports.netFlattenGrads=netFlattenGrads;module.exports.Solver=Solver;module.exports.Graph=Graph;var RL=module.exports;var getopt=function(opt,field_name,default_value){if(typeof opt==='undefined'){return default_value;}
return(typeof opt[field_name]!=='undefined')?opt[field_name]:default_value;}
var zeros=R.zeros;var assert=R.assert;var randi=R.randi;var randf=R.randf;var setConst=function(arr,c){for(var i=0,n=arr.length;i<n;i++){arr[i]=c;}}
var sampleWeighted=function(p){var r=Math.random();var c=0.0;for(var i=0,n=p.length;i<n;i++){c+=p[i];if(c>=r){return i;}}
return 0}
var DPAgent=function(env,opt){var L={};L.V=null;L.P=null;L.env=env;L.gamma=getopt(opt,'gamma',0.75);DPAgent.code.reset(L);return L;}
DPAgent.code={reset:function(L){L.ns=L.env.getNumStates();L.na=L.env.getMaxNumActions();L.V=zeros(L.ns);L.P=zeros(L.ns*L.na);for(var s=0;s<L.ns;s++){var poss=L.env.allowedActions(s);for(var i=0,n=poss.length;i<n;i++){L.P[poss[i]*L.ns+s]=1.0/poss.length;}}},act:function(L,s){var poss=L.env.allowedActions(s);var ps=[];for(var i=0,n=poss.length;i<n;i++){var a=poss[i];var prob=L.P[a*L.ns+s];ps.push(prob);}
var maxi=sampleWeighted(ps);return poss[maxi];},learn:function(L){DPAgent.code.evaluatePolicy(L);DPAgent.code.updatePolicy(L);},evaluatePolicy:function(L){var Vnew=zeros(L.ns);for(var s=0;s<L.ns;s++){var v=0.0;var poss=L.env.allowedActions(s);for(var i=0,n=poss.length;i<n;i++){var a=poss[i];var prob=L.P[a*L.ns+s];if(prob===0){continue;}
var ns=L.env.nextState(s,a);var rs=L.env.reward(s,a,ns);v+=prob*(rs+L.gamma*L.V[ns]);}
Vnew[s]=v;}
L.V=Vnew;},updatePolicy:function(L){for(var s=0;s<L.ns;s++){var poss=L.env.allowedActions(s);var vmax,nmax;var vs=[];for(var i=0,n=poss.length;i<n;i++){var a=poss[i];var ns=L.env.nextState(s,a);var rs=L.env.reward(s,a,ns);var v=rs+L.gamma*L.V[ns];vs.push(v);if(i===0||v>vmax){vmax=v;nmax=1;}
else if(v===vmax){nmax+=1;}}
for(var i=0,n=poss.length;i<n;i++){var a=poss[i];L.P[a*L.ns+s]=(vs[i]===vmax)?1.0/nmax:0.0;}}},}
var TDAgent=function(env,opt){var L={}
L.update=getopt(opt,'update','qlearn');L.gamma=getopt(opt,'gamma',0.75);L.epsilon=getopt(opt,'epsilon',0.1);L.alpha=getopt(opt,'alpha',0.01);L.smooth_policy_update=getopt(opt,'smooth_policy_update',false);L.beta=getopt(opt,'beta',0.01);L.lambda=getopt(opt,'lambda',0);L.replacing_traces=getopt(opt,'replacing_traces',true);L.q_init_val=getopt(opt,'q_init_val',0);L.planN=getopt(opt,'planN',0);L.Q=null;L.P=null;L.e=null;L.env_model_s=null;;L.env_model_r=null;;L.env=env;TDAgent.code.reset(L);return L;}
TDAgent.code={reset:function(L){L.ns=L.env.getNumStates();L.na=L.env.getMaxNumActions();L.Q=zeros(L.ns*L.na);if(L.q_init_val!==0){setConst(L.Q,L.q_init_val);}
L.P=zeros(L.ns*L.na);L.e=zeros(L.ns*L.na);L.env_model_s=zeros(L.ns*L.na);setConst(L.env_model_s,-1);L.env_model_r=zeros(L.ns*L.na);L.sa_seen=[];L.pq=zeros(L.ns*L.na);for(var s=0;s<L.ns;s++){var poss=L.env.allowedActions(s);for(var i=0,n=poss.length;i<n;i++){L.P[poss[i]*L.ns+s]=1.0/poss.length;}}
L.r0=null;L.s0=null;L.s1=null;L.a0=null;L.a1=null;},resetEpisode:function(L){},act:function(L,s){var poss=L.env.allowedActions(s);var probs=[];for(var i=0,n=poss.length;i<n;i++){probs.push(L.P[poss[i]*L.ns+s]);}
if(Math.random()<L.epsilon){var a=poss[randi(0,poss.length)];L.explored=true;}else{var a=poss[sampleWeighted(probs)];L.explored=false;}
L.s0=L.s1;L.a0=L.a1;L.s1=s;L.a1=a;return a;},learn:function(L,r1){if(!(L.r0==null)){TDAgent.code.learnFromTuple(L,L.s0,L.a0,L.r0,L.s1,L.a1,L.lambda);if(L.planN>0){TDAgent.code.updateModel(L,L.s0,L.a0,L.r0,L.s1);TDAgent.code.plan(L);}}
L.r0=r1;},updateModel:function(L,s0,a0,r0,s1){var sa=a0*L.ns+s0;if(L.env_model_s[sa]===-1){L.sa_seen.push(a0*L.ns+s0);}
L.env_model_s[sa]=s1;L.env_model_r[sa]=r0;},plan:function(L){var spq=[];for(var i=0,n=L.sa_seen.length;i<n;i++){var sa=L.sa_seen[i];var sap=L.pq[sa];if(sap>1e-5){spq.push({sa:sa,p:sap});}}
spq.sort(function(a,b){return a.p<b.p?1:-1});var nsteps=Math.min(L.planN,spq.length);for(var k=0;k<nsteps;k++){var s0a0=spq[k].sa;L.pq[s0a0]=0;var s0=s0a0%L.ns;var a0=Math.floor(s0a0/L.ns);var r0=L.env_model_r[s0a0];var s1=L.env_model_s[s0a0];var a1=-1;if(L.update==='sarsa'){var poss=L.env.allowedActions(s1);var a1=poss[randi(0,poss.length)];}
TDAgent.code.learnFromTuple(L,s0,a0,r0,s1,a1,0);}},learnFromTuple:function(L,s0,a0,r0,s1,a1,lambda){var sa=a0*L.ns+s0;if(L.update==='qlearn'){var poss=L.env.allowedActions(s1);var qmax=0;for(var i=0,n=poss.length;i<n;i++){var s1a=poss[i]*L.ns+s1;var qval=L.Q[s1a];if(i===0||qval>qmax){qmax=qval;}}
var target=r0+L.gamma*qmax;}else if(L.update==='sarsa'){var s1a1=a1*L.ns+s1;var target=r0+L.gamma*L.Q[s1a1];}
if(lambda>0){if(L.replacing_traces){L.e[sa]=1;}else{L.e[sa]+=1;}
var edecay=lambda*L.gamma;var state_update=zeros(L.ns);for(var s=0;s<L.ns;s++){var poss=L.env.allowedActions(s);for(var i=0;i<poss.length;i++){var a=poss[i];var saloop=a*L.ns+s;var esa=L.e[saloop];var update=L.alpha*esa*(target-L.Q[saloop]);L.Q[saloop]+=update;L.updatePriority(s,a,update);L.e[saloop]*=edecay;var u=Math.abs(update);if(u>state_update[s]){state_update[s]=u;}}}
for(var s=0;s<L.ns;s++){if(state_update[s]>1e-5){TDAgent.code.updatePolicy(L,s);}}
if(L.explored&&L.update==='qlearn'){L.e=zeros(L.ns*L.na);}}else{var update=L.alpha*(target-L.Q[sa]);L.Q[sa]+=update;TDAgent.code.updatePriority(L,s0,a0,update);TDAgent.code.updatePolicy(L,s0);}},updatePriority:function(L,s,a,u){u=Math.abs(u);if(u<1e-5){return;}
if(L.planN===0){return;}
for(var si=0;si<L.ns;si++){for(var ai=0;ai<L.na;ai++){var siai=ai*L.ns+si;if(L.env_model_s[siai]===s){L.pq[siai]+=u;}}}},updatePolicy:function(L,s){var poss=L.env.allowedActions(s);var qmax,nmax;var qs=[];for(var i=0,n=poss.length;i<n;i++){var a=poss[i];var qval=L.Q[a*L.ns+s];qs.push(qval);if(i===0||qval>qmax){qmax=qval;nmax=1;}
else if(qval===qmax){nmax+=1;}}
var psum=0.0;for(var i=0,n=poss.length;i<n;i++){var a=poss[i];var target=(qs[i]===qmax)?1.0/nmax:0.0;var ix=a*L.ns+s;if(L.smooth_policy_update){L.P[ix]+=L.beta*(target-L.P[ix]);psum+=L.P[ix];}else{L.P[ix]=target;}}
if(L.smooth_policy_update){for(var i=0,n=poss.length;i<n;i++){var a=poss[i];L.P[a*L.ns+s]/=psum;}}}}
var DQNAgent=function(env,opt){var L={}
L.gamma=getopt(opt,'gamma',0.75);L.epsilon=getopt(opt,'epsilon',0.1);L.alpha=getopt(opt,'alpha',0.01);L.experience_add_every=getopt(opt,'experience_add_every',25);L.experience_size=getopt(opt,'experience_size',5000);L.learning_steps_per_iteration=getopt(opt,'learning_steps_per_iteration',10);L.tderror_clamp=getopt(opt,'tderror_clamp',1.0);L.num_hidden_units=getopt(opt,'num_hidden_units',100);L.env=env;DQNAgent.code.reset(L);return L}
DQNAgent.code={reset:function(L){L.nh=L.num_hidden_units;L.ns=L.env.getNumStates();L.na=L.env.getMaxNumActions();L.net={};L.net.W1=R.RandMat(L.nh,L.ns,0,0.01);L.net.b1=R.Mat(L.nh,1,0,0.01);L.net.W2=R.RandMat(L.na,L.nh,0,0.01);L.net.b2=R.Mat(L.na,1,0,0.01);L.exp=[];L.expi=0;L.t=0;L.r0=null;L.s0=null;L.s1=null;L.a0=null;L.a1=null;L.tderror=0;},toJSON:function(L){var j={};j.nh=L.nh;j.ns=L.ns;j.na=L.na;j.net=R.netToJSON(L.net);return j;},fromJSON:function(L,j){L.nh=j.nh;L.ns=j.ns;L.na=j.na;L.net=R.netFromJSON(j.net);},forwardQ:function(L,net,s,needs_backprop){var G=R.Graph(needs_backprop);var a1mat=Graph.code.add(G,Graph.code.mul(G,net.W1,s),net.b1);var h1mat=Graph.code.tanh(G,a1mat);var a2mat=Graph.code.add(G,Graph.code.mul(G,net.W2,h1mat),net.b2);L.lastG=G;return a2mat;},act:function(L,slist){var s=R.Mat(L.ns,1);Mat.code.setFrom(s,slist);if(Math.random()<L.epsilon){var a=randi(0,L.na);}else{var amat=DQNAgent.code.forwardQ(L,L.net,s,false);var a=R.maxi(amat.w);}
L.s0=L.s1;L.a0=L.a1;L.s1=s;L.a1=a;return a;},learn:function(L,r1){if(!(L.r0==null)&&L.alpha>0){var tderror=DQNAgent.code.learnFromTuple(L,L.s0,L.a0,L.r0,L.s1,L.a1);L.tderror=tderror;if(L.t%L.experience_add_every===0){L.exp[L.expi]=[L.s0,L.a0,L.r0,L.s1,L.a1];L.expi+=1;if(L.expi>L.experience_size){L.expi=0;}}
L.t+=1;for(var k=0;k<L.learning_steps_per_iteration;k++){var ri=randi(0,L.exp.length);var e=L.exp[ri];DQNAgent.code.learnFromTuple(L,e[0],e[1],e[2],e[3],e[4])}}
L.r0=r1;},learnFromTuple:function(L,s0,a0,r0,s1,a1){var tmat=DQNAgent.code.forwardQ(L,L.net,s1,false);var qmax=r0+L.gamma*tmat.w[R.maxi(tmat.w)];var pred=DQNAgent.code.forwardQ(L,L.net,s0,true);var tderror=pred.w[a0]-qmax;var clamp=L.tderror_clamp;if(Math.abs(tderror)>clamp){if(tderror>clamp)tderror=clamp;if(tderror<-clamp)tderror=-clamp;}
pred.dw[a0]=tderror;Graph.code.backward(L.lastG);R.updateNet(L.net,L.alpha);return tderror;}}
module.exports.DPAgent=DPAgent;module.exports.TDAgent=TDAgent;module.exports.DQNAgent=DQNAgent;};BundleModuleCode['ml/stats']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var stat={max:function(array){return Math.max.apply(null,array);},min:function(array){return Math.min.apply(null,array);},range:function(array){return stat.max(array)-stat.min(array);},midrange:function(array){return stat.range(array)/2;},sum:function(array){var num=0;for(var i=0,l=array.length;i<l;i++)num+=array[i];return num;},mean:function(array){return stat.sum(array)/array.length;},median:function(array){array.sort(function(a,b){return a-b;});var mid=array.length/2;return mid%1?array[mid-0.5]:(array[mid-1]+array[mid])/2;},modes:function(array){if(!array.length)return[];var modeMap={},maxCount=0,modes=[];array.forEach(function(val){if(!modeMap[val])modeMap[val]=1;else modeMap[val]++;if(modeMap[val]>maxCount){modes=[val];maxCount=modeMap[val];}
else if(modeMap[val]===maxCount){modes.push(val);maxCount=modeMap[val];}});return modes;},variance:function(array){var mean=stat.mean(array);return stat.mean(array.map(function(num){return Math.pow(num-mean,2);}));},standardDeviation:function(array){return Math.sqrt(stat.variance(array));},meanAbsoluteDeviation:function(array){var mean=stat.mean(array);return stat.mean(array.map(function(num){return Math.abs(num-mean);}));},zScores:function(array){var mean=stat.mean(array);var standardDeviation=stat.standardDeviation(array);return array.map(function(num){return(num-mean)/standardDeviation;});}};stat.average=stat.mean;function best(o,normalize){var p,max,pos=0,sum=0,res;if(Comp.obj.isArray(o)&&typeof o[0]=='number'){max=-Infinity;for(p in o){sum+=o[p];if(o[p]>max)max=o[p],pos=p;}
res={index:pos,prob:max}}else if(Comp.obj.isArray(o)&&typeof o[0]=='object'){for(p in o){sum+=o[p].prob;if(!max||o[p].prob>max.prob)max=o[p];}
res={value:max.value,prob:max.prob}}else if(Comp.obj.isObj(o)){max=-Infinity;for(p in o){sum+=o[p];if(o[p]>max)max=o[p],pos=p;}
res={value:pos,prob:max}}
if(!res)return;switch(normalize){case 1:res.prob=res.prob/sum;break;case 2:res.prob=res.prob*(res.prob/sum);break;default:}
return res;}
function bestNormalize(o){return best(o,1)}
function log2(n){return Math.log(n)/Math.log(2);}
function max(array,fun){var res,max,num;for(var i in array){if(fun)num=fun(array[i],i);else num=array[i];if(max==undefined){max=num;res=array[i]}
else if(num>max){max=num;res=array[i]}}
return res;}
function mostCommon(list){var elementFrequencyMap={};var largestFrequency=-1;var mostCommonElement=null;list.forEach(function(element){var elementFrequency=(elementFrequencyMap[element]||0)+1;elementFrequencyMap[element]=elementFrequency;if(largestFrequency<elementFrequency){mostCommonElement=element;largestFrequency=elementFrequency;}});return mostCommonElement;}
function pluck(collection,key){return collection.map(function(object){return object==null?undefined:object[key];});}
function prob(value,list){var occurrences=list.filter(function(element){return element===value});var numOccurrences=occurrences.length;var numElements=list.length;return numOccurrences/numElements;}
function sort(array){return array.sort(function(a,b){return a<b?-1:1});}
function sum(a,b){return a+b}
function unique(array){var length=array?array.length:0;function baseUniq(array){var index=-1,length=array.length,seen,result=[];seen=result;outer:while(++index<length){var value=array[index];var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===value){continue outer;}}
result.push(value);}
return result;}
if(!length){return[];}
return baseUniq(array);}
function without(){var array,values=[];for(var i in arguments){if(i==0)array=arguments[0];else values.push(arguments[i]);}
return array.filter(function(e){return values.indexOf(e)==-1;});}
function entropy(vals){var uniqueVals=unique(vals);var probs=uniqueVals.map(function(x){return prob(x,vals)});var logVals=probs.map(function(p){return-p*log2(p)});return logVals.reduce(sum,0);}
function entropyN(dist,N){var p,probs=[];for(p in dist)probs.push(dist[p]/N);var logVals=probs.map(function(p){return p==0?0:-p*log2(p)});return logVals.reduce(sum,0);}
function entropyEps(vals,eps){var uniqueVals=uniqueEps(vals,eps);var probs=uniqueVals.map(function(x){return probEps(x,vals,eps)});var logVals=probs.map(function(p){return-p*log2(p)});return logVals.reduce(sum,0);}
function entropyT(data,featureIndex,targetIndex,targets){var en=0;var col=pluck(data,featureIndex);var uniqueVals=unique(col);uniqueVals.forEach(function(v){var frac=targets.map(function(){return 0}),cn=0;col.forEach(function(v2,row){if(v2==v)cn++,frac[targets.indexOf(data[row][targetIndex])]++;})
var p=cn/data.length;en+=(p*entropyN(frac,frac.reduce(sum)))})
return en;}
function entropyTEps(data,feature,target,targets,eps){var en=0;var col=pluck(data,feature);var uniqueVals=uniqueEps(col,eps);uniqueVals.forEach(function(v){var frac=targets.map(function(){return 0}),cn=0;col.forEach(function(v2,row){if(v2>=v-eps&&v2<=v+eps)cn++,frac[targets.indexOf(data[row][target])]++;})
var p=cn/data.length;en+=(p*entropyN(frac,frac.reduce(sum)))})
return en;}
function features(data,target){var f;if(Comp.obj.isObj(data[0]))
f=Object.keys(data[0]);else if(Comp.obj.isArray(data[0]))
f=data[0].map(function(x,i){return String(i)});if(f&&target)delete f[target];return f;}
function gainEps(data,feature,target,targets,eps){var et=entropy(pluck(data,target));return et/entropyTEps(data,feature,target,targets,eps)}
function maxGainEps(data,features,target,targets,eps){var maxgain=max(features,function(feature,index){var g=gainEps(data,feature,target,targets,selectEps(eps,index));return g;});return maxgain;}
function partition(data,feature,target,targets){var parts={};targets.forEach(function(t){parts[t]=[]});data.forEach(function(row){parts[row[target]].push(row[feature]);})
return parts}
function partitionEps(data,feature,target,targets,eps){var p,parts={}
targets.forEach(function(t){parts[t]={range:[Number.MAX_VALUE,-Number.MAX_VALUE],values:[]}});data.forEach(function(row){parts[row[target]].values.push(row[feature]);parts[row[target]].range[0]=Math.min(parts[row[target]].range[0],row[feature]);parts[row[target]].range[1]=Math.max(parts[row[target]].range[1],row[feature]);})
for(p in parts){parts[p].unique=uniqueEps(parts[p].values,eps)
parts[p].noise=2*stat.standardDeviation(parts[p].values);}
return parts}
function partitionUniqueEps(data,feature,target,targets,eps){var p,q,parts={}
targets.forEach(function(t){parts[t]={range:[Number.MAX_VALUE,-Number.MAX_VALUE],values:[]}});data.forEach(function(row){parts[row[target]].values.push(row[feature]);parts[row[target]].range[0]=Math.min(parts[row[target]].range[0],row[feature]);parts[row[target]].range[1]=Math.max(parts[row[target]].range[1],row[feature]);})
for(p in parts){parts[p].unique=uniqueEps(parts[p].values,eps)}
for(p in parts){if(!parts[p])continue;for(q in parts){if(!parts[p])break;if(p==q||!parts[q])continue;if((parts[p].range[0]-eps)<parts[q].range[1]||(parts[p].range[1]+eps)>parts[q].range[0]){if((parts[p].unique.length/parts[p].values.length)<(parts[q].unique.length/parts[q].values.length)){delete parts[q];}else{delete parts[p];}}}}
return parts}
function select(data,what){if(Comp.obj.isArray(what)&&what.length==2){var c0=what[0],c1=what[1];return data.map(function(row){return row.slice(c0,c1+1);})}}
function selectEps(eps,index){if(typeof eps=='number')return eps;else return eps[index]}
function splitEps(data,features,target,targets,eps){var bestFeature=maxGainEps(data,features,target,targets,eps);var index=features.indexOf(bestFeature);eps=selectEps(eps,index);var remainingFeatures=without(features,bestFeature);var possibleValues=sort(uniqueEps(pluck(data,bestFeature),eps));var choices=possibleValues.map(function(v){var dataS=data.filter(function(x){return Math.abs(x[bestFeature]-v)<=eps});return{val:v,data:dataS,}});return{feature:bestFeature,choices:choices,possibleValues:possibleValues,remainingFeatures:remainingFeatures};}
function uniqueEps(array,eps){var result=[];array.forEach(function(x){var found;if(!result.length)result.push(x);else{result.forEach(function(y){if(found)return;found=Math.abs(x-y)<=eps;});if(!found)result.push(x);}});return result;}
module.exports={analyze:function(data,features,target,eps){var noise=[];if(!eps)eps=0;var targets=unique(pluck(data,target));var parts={},partsUnique={},diversity={}
features.forEach(function(feature){partsUnique[feature]=partitionUniqueEps(data,feature,target,targets,eps);parts[feature]=partitionEps(data,feature,target,targets,eps);for(var p in parts[feature])noise.push(parts[feature][p].noise);})
features.forEach(function(feature){diversity[feature]=Object.keys(partsUnique[feature]).length;})
return{features:features,partitions:parts,diversity:diversity,noise:stat.mean(noise)}},entropy:entropy,entropyN:entropyN,entropyEps:entropyEps,entropyTEps:entropyTEps,entropyT:entropyT,features:features,gainEps:gainEps,maxGainEps:maxGainEps,mostCommon:mostCommon,partition:partition,partitionEps:partitionEps,partitionUniqueEps:partitionUniqueEps,splitEps:splitEps,unique:unique,uniqueEps:uniqueEps,utils:{best:best,bestNormalize:bestNormalize,column:pluck,log2:log2,prob:prob,relax:function(mat){if(Comp.obj.isMatrix(mat)&&mat[0].length==1)return mat.map(function(row){return row[0]})
else return mat;},select:select,selectEps:selectEps,sort:sort,stat:stat,without:without,wrap:function(mat){if(!Comp.obj.isMatrix(mat))return mat.map(function(v){return[v]})
else return mat},},};};BundleModuleCode['ml/cnn']=function(module,exports){'use strict';var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;var convnetjs=Require('ml/convnet')
var that;that=module.exports={create:function(options){var net=new convnetjs.Net();if(options.layers)
net.makeLayers(options.layers);if(!options.iterations)options.iterations=10;if(!options.depth)options.depth=1;if(!options.width)options.width=options.x[0].length,options.height=1;var trainer=new convnetjs.SGDTrainer(net,options.trainer||{method:'adadelta',l2_decay:0.001,batch_size:10});var x=options.x;if(options.normalize){var a,b,c=options.normalize[0],d=options.normalize[1];x.forEach(function(row){var min=Math.min.apply(null,row),max=Math.max.apply(null,row);if(a==undefined)a=min;else a=Math.min(a,min);if(b==undefined)b=max;else b=Math.max(b,max);})
x=x.map(function(row){return row.map(function(col){return(((col-a)/(b-a))*(d-c))+c})})}
x=x.map(function(row){var vol=new convnetjs.Vol(options.width,options.height,options.depth,0.0);vol.w=row;return vol;});x.forEach(function(row){})
var y=options.y;if(!options.targets){options.targets=that.ml.stats.unique(y);}
for(var iters=0;iters<options.iterations;iters++){y.forEach(function(v,i){trainer.train(x[i],options.targets.indexOf(v));})}
trainer.options={width:options.width,height:options.height,depth:options.depth,targets:options.targets};return trainer;},ml:{},predict:function(model,sample){var options=model.options;var vol=new convnetjs.Vol(options.width,options.height,options.depth,0.0);vol.w=sample;return model.net.forward(vol);},print:function(){},update:function(data){},current:function(module){current=module.current;Aios=module;}};};BundleModuleCode['ml/convnet']=function(module,exports){var convnet={REVISION:'ALPHA'}
module.exports=convnet;"use strict";var return_v=false;var v_val=0.0;var gaussRandom=function(){if(return_v){return_v=false;return v_val;}
var u=2*Math.random()-1;var v=2*Math.random()-1;var r=u*u+v*v;if(r==0||r>1)return gaussRandom();var c=Math.sqrt(-2*Math.log(r)/r);v_val=v*c;return_v=true;return u*c;}
var randf=function(a,b){return Math.random()*(b-a)+a;}
var randi=function(a,b){return Math.floor(Math.random()*(b-a)+a);}
var randn=function(mu,std){return mu+gaussRandom()*std;}
var zeros=function(n){if(typeof(n)==='undefined'||isNaN(n)){return[];}
if(typeof ArrayBuffer==='undefined'){var arr=new Array(n);for(var i=0;i<n;i++){arr[i]=0;}
return arr;}else{return new Float64Array(n);}}
var arrContains=function(arr,elt){for(var i=0,n=arr.length;i<n;i++){if(arr[i]===elt)return true;}
return false;}
var arrUnique=function(arr){var b=[];for(var i=0,n=arr.length;i<n;i++){if(!arrContains(b,arr[i])){b.push(arr[i]);}}
return b;}
var maxmin=function(w){if(w.length===0){return{};}
var maxv=w[0];var minv=w[0];var maxi=0;var mini=0;var n=w.length;for(var i=1;i<n;i++){if(w[i]>maxv){maxv=w[i];maxi=i;}
if(w[i]<minv){minv=w[i];mini=i;}}
return{maxi:maxi,maxv:maxv,mini:mini,minv:minv,dv:maxv-minv};}
var randperm=function(n){var i=n,j=0,temp;var array=[];for(var q=0;q<n;q++)array[q]=q;while(i--){j=Math.floor(Math.random()*(i+1));temp=array[i];array[i]=array[j];array[j]=temp;}
return array;}
var weightedSample=function(lst,probs){var p=randf(0,1.0);var cumprob=0.0;for(var k=0,n=lst.length;k<n;k++){cumprob+=probs[k];if(p<cumprob){return lst[k];}}}
var getopt=function(opt,field_name,default_value){if(typeof field_name==='string'){return(typeof opt[field_name]!=='undefined')?opt[field_name]:default_value;}else{var ret=default_value;for(var i=0;i<field_name.length;i++){var f=field_name[i];if(typeof opt[f]!=='undefined'){ret=opt[f];}}
return ret;}}
function assert(condition,message){if(!condition){message=message||"Assertion failed";if(typeof Error!=="undefined"){throw new Error(message);}
throw message;}}
convnet.randf=randf;convnet.randi=randi;convnet.randn=randn;convnet.zeros=zeros;convnet.maxmin=maxmin;convnet.randperm=randperm;convnet.weightedSample=weightedSample;convnet.arrUnique=arrUnique;convnet.arrContains=arrContains;convnet.getopt=getopt;convnet.assert=assert;var Vol=function(sx,sy,depth,c){if(Object.prototype.toString.call(sx)==='[object Array]'){this.sx=1;this.sy=1;this.depth=sx.length;this.w=convnet.zeros(this.depth);this.dw=convnet.zeros(this.depth);for(var i=0;i<this.depth;i++){this.w[i]=sx[i];}}else{this.sx=sx;this.sy=sy;this.depth=depth;var n=sx*sy*depth;this.w=convnet.zeros(n);this.dw=convnet.zeros(n);if(typeof c==='undefined'){var scale=Math.sqrt(1.0/(sx*sy*depth));for(var i=0;i<n;i++){this.w[i]=convnet.randn(0.0,scale);}}else{for(var i=0;i<n;i++){this.w[i]=c;}}}}
Vol.prototype={get:function(x,y,d){var ix=((this.sx*y)+x)*this.depth+d;return this.w[ix];},set:function(x,y,d,v){var ix=((this.sx*y)+x)*this.depth+d;this.w[ix]=v;},add:function(x,y,d,v){var ix=((this.sx*y)+x)*this.depth+d;this.w[ix]+=v;},get_grad:function(x,y,d){var ix=((this.sx*y)+x)*this.depth+d;return this.dw[ix];},set_grad:function(x,y,d,v){var ix=((this.sx*y)+x)*this.depth+d;this.dw[ix]=v;},add_grad:function(x,y,d,v){var ix=((this.sx*y)+x)*this.depth+d;this.dw[ix]+=v;},cloneAndZero:function(){return new Vol(this.sx,this.sy,this.depth,0.0)},clone:function(){var V=new Vol(this.sx,this.sy,this.depth,0.0);var n=this.w.length;for(var i=0;i<n;i++){V.w[i]=this.w[i];}
return V;},addFrom:function(V){for(var k=0;k<this.w.length;k++){this.w[k]+=V.w[k];}},addFromScaled:function(V,a){for(var k=0;k<this.w.length;k++){this.w[k]+=a*V.w[k];}},setConst:function(a){for(var k=0;k<this.w.length;k++){this.w[k]=a;}},toJSON:function(){var json={}
json.sx=this.sx;json.sy=this.sy;json.depth=this.depth;json.w=this.w;return json;},fromJSON:function(json){this.sx=json.sx;this.sy=json.sy;this.depth=json.depth;var n=this.sx*this.sy*this.depth;this.w=convnet.zeros(n);this.dw=convnet.zeros(n);for(var i=0;i<n;i++){this.w[i]=json.w[i];}}}
convnet.Vol=Vol;var Vol=convnet.Vol;var augment=function(V,crop,dx,dy,fliplr){if(typeof(fliplr)==='undefined')var fliplr=false;if(typeof(dx)==='undefined')var dx=convnet.randi(0,V.sx-crop);if(typeof(dy)==='undefined')var dy=convnet.randi(0,V.sy-crop);var W;if(crop!==V.sx||dx!==0||dy!==0){W=new Vol(crop,crop,V.depth,0.0);for(var x=0;x<crop;x++){for(var y=0;y<crop;y++){if(x+dx<0||x+dx>=V.sx||y+dy<0||y+dy>=V.sy)continue;for(var d=0;d<V.depth;d++){W.set(x,y,d,V.get(x+dx,y+dy,d));}}}}else{W=V;}
if(fliplr){var W2=W.cloneAndZero();for(var x=0;x<W.sx;x++){for(var y=0;y<W.sy;y++){for(var d=0;d<W.depth;d++){W2.set(x,y,d,W.get(W.sx-x-1,y,d));}}}
W=W2;}
return W;}
var img_to_vol=function(img,convert_grayscale){if(typeof(convert_grayscale)==='undefined')var convert_grayscale=false;var canvas=document.createElement('canvas');canvas.width=img.width;canvas.height=img.height;var ctx=canvas.getContext("2d");try{ctx.drawImage(img,0,0);}catch(e){if(e.name==="NS_ERROR_NOT_AVAILABLE"){return false;}else{throw e;}}
try{var img_data=ctx.getImageData(0,0,canvas.width,canvas.height);}catch(e){if(e.name==='IndexSizeError'){return false;}else{throw e;}}
var p=img_data.data;var W=img.width;var H=img.height;var pv=[]
for(var i=0;i<p.length;i++){pv.push(p[i]/255.0-0.5);}
var x=new Vol(W,H,4,0.0);x.w=pv;if(convert_grayscale){var x1=new Vol(W,H,1,0.0);for(var i=0;i<W;i++){for(var j=0;j<H;j++){x1.set(i,j,0,x.get(i,j,0));}}
x=x1;}
return x;}
convnet.augment=augment;convnet.img_to_vol=img_to_vol;var ConvLayer=function(opt){var opt=opt||{};this.out_depth=opt.filters;this.sx=opt.sx;this.in_depth=opt.in_depth;this.in_sx=opt.in_sx;this.in_sy=opt.in_sy;this.sy=typeof opt.sy!=='undefined'?opt.sy:this.sx;this.stride=typeof opt.stride!=='undefined'?opt.stride:1;this.pad=typeof opt.pad!=='undefined'?opt.pad:0;this.l1_decay_mul=typeof opt.l1_decay_mul!=='undefined'?opt.l1_decay_mul:0.0;this.l2_decay_mul=typeof opt.l2_decay_mul!=='undefined'?opt.l2_decay_mul:1.0;this.out_sx=Math.floor((this.in_sx+this.pad*2-this.sx)/this.stride+1);this.out_sy=Math.floor((this.in_sy+this.pad*2-this.sy)/this.stride+1);this.layer_type='conv';var bias=typeof opt.bias_pref!=='undefined'?opt.bias_pref:0.0;this.filters=[];for(var i=0;i<this.out_depth;i++){this.filters.push(new Vol(this.sx,this.sy,this.in_depth));}
this.biases=new Vol(1,1,this.out_depth,bias);}
ConvLayer.prototype={forward:function(V,is_training){this.in_act=V;var A=new Vol(this.out_sx|0,this.out_sy|0,this.out_depth|0,0.0);var V_sx=V.sx|0;var V_sy=V.sy|0;var xy_stride=this.stride|0;for(var d=0;d<this.out_depth;d++){var f=this.filters[d];var x=-this.pad|0;var y=-this.pad|0;for(var ay=0;ay<this.out_sy;y+=xy_stride,ay++){x=-this.pad|0;for(var ax=0;ax<this.out_sx;x+=xy_stride,ax++){var a=0.0;for(var fy=0;fy<f.sy;fy++){var oy=y+fy;for(var fx=0;fx<f.sx;fx++){var ox=x+fx;if(oy>=0&&oy<V_sy&&ox>=0&&ox<V_sx){for(var fd=0;fd<f.depth;fd++){a+=f.w[((f.sx*fy)+fx)*f.depth+fd]*V.w[((V_sx*oy)+ox)*V.depth+fd];}}}}
a+=this.biases.w[d];A.set(ax,ay,d,a);}}}
this.out_act=A;return this.out_act;},backward:function(){var V=this.in_act;V.dw=convnet.zeros(V.w.length);var V_sx=V.sx|0;var V_sy=V.sy|0;var xy_stride=this.stride|0;for(var d=0;d<this.out_depth;d++){var f=this.filters[d];var x=-this.pad|0;var y=-this.pad|0;for(var ay=0;ay<this.out_sy;y+=xy_stride,ay++){x=-this.pad|0;for(var ax=0;ax<this.out_sx;x+=xy_stride,ax++){var chain_grad=this.out_act.get_grad(ax,ay,d);for(var fy=0;fy<f.sy;fy++){var oy=y+fy;for(var fx=0;fx<f.sx;fx++){var ox=x+fx;if(oy>=0&&oy<V_sy&&ox>=0&&ox<V_sx){for(var fd=0;fd<f.depth;fd++){var ix1=((V_sx*oy)+ox)*V.depth+fd;var ix2=((f.sx*fy)+fx)*f.depth+fd;f.dw[ix2]+=V.w[ix1]*chain_grad;V.dw[ix1]+=f.w[ix2]*chain_grad;}}}}
this.biases.dw[d]+=chain_grad;}}}},getParamsAndGrads:function(){var response=[];for(var i=0;i<this.out_depth;i++){response.push({params:this.filters[i].w,grads:this.filters[i].dw,l2_decay_mul:this.l2_decay_mul,l1_decay_mul:this.l1_decay_mul});}
response.push({params:this.biases.w,grads:this.biases.dw,l1_decay_mul:0.0,l2_decay_mul:0.0});return response;},toJSON:function(){var json={};json.sx=this.sx;json.sy=this.sy;json.stride=this.stride;json.in_depth=this.in_depth;json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.l1_decay_mul=this.l1_decay_mul;json.l2_decay_mul=this.l2_decay_mul;json.pad=this.pad;json.filters=[];for(var i=0;i<this.filters.length;i++){json.filters.push(this.filters[i].toJSON());}
json.biases=this.biases.toJSON();return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.sx=json.sx;this.sy=json.sy;this.stride=json.stride;this.in_depth=json.in_depth;this.filters=[];this.l1_decay_mul=typeof json.l1_decay_mul!=='undefined'?json.l1_decay_mul:1.0;this.l2_decay_mul=typeof json.l2_decay_mul!=='undefined'?json.l2_decay_mul:1.0;this.pad=typeof json.pad!=='undefined'?json.pad:0;for(var i=0;i<json.filters.length;i++){var v=new Vol(0,0,0,0);v.fromJSON(json.filters[i]);this.filters.push(v);}
this.biases=new Vol(0,0,0,0);this.biases.fromJSON(json.biases);}}
var FullyConnLayer=function(opt){var opt=opt||{};this.out_depth=typeof opt.num_neurons!=='undefined'?opt.num_neurons:opt.filters;this.l1_decay_mul=typeof opt.l1_decay_mul!=='undefined'?opt.l1_decay_mul:0.0;this.l2_decay_mul=typeof opt.l2_decay_mul!=='undefined'?opt.l2_decay_mul:1.0;this.num_inputs=opt.in_sx*opt.in_sy*opt.in_depth;this.out_sx=1;this.out_sy=1;this.layer_type='fc';var bias=typeof opt.bias_pref!=='undefined'?opt.bias_pref:0.0;this.filters=[];for(var i=0;i<this.out_depth;i++){this.filters.push(new Vol(1,1,this.num_inputs));}
this.biases=new Vol(1,1,this.out_depth,bias);}
FullyConnLayer.prototype={forward:function(V,is_training){this.in_act=V;var A=new Vol(1,1,this.out_depth,0.0);var Vw=V.w;for(var i=0;i<this.out_depth;i++){var a=0.0;var wi=this.filters[i].w;for(var d=0;d<this.num_inputs;d++){a+=Vw[d]*wi[d];}
a+=this.biases.w[i];A.w[i]=a;}
this.out_act=A;return this.out_act;},backward:function(){var V=this.in_act;V.dw=convnet.zeros(V.w.length);for(var i=0;i<this.out_depth;i++){var tfi=this.filters[i];var chain_grad=this.out_act.dw[i];for(var d=0;d<this.num_inputs;d++){V.dw[d]+=tfi.w[d]*chain_grad;tfi.dw[d]+=V.w[d]*chain_grad;}
this.biases.dw[i]+=chain_grad;}},getParamsAndGrads:function(){var response=[];for(var i=0;i<this.out_depth;i++){response.push({params:this.filters[i].w,grads:this.filters[i].dw,l1_decay_mul:this.l1_decay_mul,l2_decay_mul:this.l2_decay_mul});}
response.push({params:this.biases.w,grads:this.biases.dw,l1_decay_mul:0.0,l2_decay_mul:0.0});return response;},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.num_inputs=this.num_inputs;json.l1_decay_mul=this.l1_decay_mul;json.l2_decay_mul=this.l2_decay_mul;json.filters=[];for(var i=0;i<this.filters.length;i++){json.filters.push(this.filters[i].toJSON());}
json.biases=this.biases.toJSON();return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.num_inputs=json.num_inputs;this.l1_decay_mul=typeof json.l1_decay_mul!=='undefined'?json.l1_decay_mul:1.0;this.l2_decay_mul=typeof json.l2_decay_mul!=='undefined'?json.l2_decay_mul:1.0;this.filters=[];for(var i=0;i<json.filters.length;i++){var v=new Vol(0,0,0,0);v.fromJSON(json.filters[i]);this.filters.push(v);}
this.biases=new Vol(0,0,0,0);this.biases.fromJSON(json.biases);}}
convnet.ConvLayer=ConvLayer;convnet.FullyConnLayer=FullyConnLayer;var PoolLayer=function(opt){var opt=opt||{};this.sx=opt.sx;this.in_depth=opt.in_depth;this.in_sx=opt.in_sx;this.in_sy=opt.in_sy;this.sy=typeof opt.sy!=='undefined'?opt.sy:this.sx;this.stride=typeof opt.stride!=='undefined'?opt.stride:2;this.pad=typeof opt.pad!=='undefined'?opt.pad:0;this.out_depth=this.in_depth;this.out_sx=Math.floor((this.in_sx+this.pad*2-this.sx)/this.stride+1);this.out_sy=Math.floor((this.in_sy+this.pad*2-this.sy)/this.stride+1);this.layer_type='pool';this.switchx=convnet.zeros(this.out_sx*this.out_sy*this.out_depth);this.switchy=convnet.zeros(this.out_sx*this.out_sy*this.out_depth);}
PoolLayer.prototype={forward:function(V,is_training){this.in_act=V;var A=new Vol(this.out_sx,this.out_sy,this.out_depth,0.0);var n=0;for(var d=0;d<this.out_depth;d++){var x=-this.pad;var y=-this.pad;for(var ax=0;ax<this.out_sx;x+=this.stride,ax++){y=-this.pad;for(var ay=0;ay<this.out_sy;y+=this.stride,ay++){var a=-99999;var winx=-1,winy=-1;for(var fx=0;fx<this.sx;fx++){for(var fy=0;fy<this.sy;fy++){var oy=y+fy;var ox=x+fx;if(oy>=0&&oy<V.sy&&ox>=0&&ox<V.sx){var v=V.get(ox,oy,d);if(v>a){a=v;winx=ox;winy=oy;}}}}
this.switchx[n]=winx;this.switchy[n]=winy;n++;A.set(ax,ay,d,a);}}}
this.out_act=A;return this.out_act;},backward:function(){var V=this.in_act;V.dw=convnet.zeros(V.w.length);var A=this.out_act;var n=0;for(var d=0;d<this.out_depth;d++){var x=-this.pad;var y=-this.pad;for(var ax=0;ax<this.out_sx;x+=this.stride,ax++){y=-this.pad;for(var ay=0;ay<this.out_sy;y+=this.stride,ay++){var chain_grad=this.out_act.get_grad(ax,ay,d);V.add_grad(this.switchx[n],this.switchy[n],d,chain_grad);n++;}}}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.sx=this.sx;json.sy=this.sy;json.stride=this.stride;json.in_depth=this.in_depth;json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.pad=this.pad;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.sx=json.sx;this.sy=json.sy;this.stride=json.stride;this.in_depth=json.in_depth;this.pad=typeof json.pad!=='undefined'?json.pad:0;this.switchx=convnet.zeros(this.out_sx*this.out_sy*this.out_depth);this.switchy=convnet.zeros(this.out_sx*this.out_sy*this.out_depth);}}
convnet.PoolLayer=PoolLayer;var getopt=convnet.getopt;var InputLayer=function(opt){var opt=opt||{};this.out_depth=getopt(opt,['out_depth','depth'],0);this.out_sx=getopt(opt,['out_sx','sx','width'],1);this.out_sy=getopt(opt,['out_sy','sy','height'],1);this.layer_type='input';}
InputLayer.prototype={forward:function(V,is_training){this.in_act=V;this.out_act=V;return this.out_act;},backward:function(){},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;}}
convnet.InputLayer=InputLayer;var SoftmaxLayer=function(opt){var opt=opt||{};this.num_inputs=opt.in_sx*opt.in_sy*opt.in_depth;this.out_depth=this.num_inputs;this.out_sx=1;this.out_sy=1;this.layer_type='softmax';}
SoftmaxLayer.prototype={forward:function(V,is_training){this.in_act=V;var A=new Vol(1,1,this.out_depth,0.0);var as=V.w;var amax=V.w[0];for(var i=1;i<this.out_depth;i++){if(as[i]>amax)amax=as[i];}
var es=convnet.zeros(this.out_depth);var esum=0.0;for(var i=0;i<this.out_depth;i++){var e=Math.exp(as[i]-amax);esum+=e;es[i]=e;}
for(var i=0;i<this.out_depth;i++){es[i]/=esum;A.w[i]=es[i];}
this.es=es;this.out_act=A;return this.out_act;},backward:function(y){var x=this.in_act;x.dw=convnet.zeros(x.w.length);for(var i=0;i<this.out_depth;i++){var indicator=i===y?1.0:0.0;var mul=-(indicator-this.es[i]);x.dw[i]=mul;}
return-Math.log(this.es[y]);},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.num_inputs=this.num_inputs;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.num_inputs=json.num_inputs;}}
var RegressionLayer=function(opt){var opt=opt||{};this.num_inputs=opt.in_sx*opt.in_sy*opt.in_depth;this.out_depth=this.num_inputs;this.out_sx=1;this.out_sy=1;this.layer_type='regression';}
RegressionLayer.prototype={forward:function(V,is_training){this.in_act=V;this.out_act=V;return V;},backward:function(y){var x=this.in_act;x.dw=convnet.zeros(x.w.length);var loss=0.0;if(y instanceof Array||y instanceof Float64Array){for(var i=0;i<this.out_depth;i++){var dy=x.w[i]-y[i];x.dw[i]=dy;loss+=0.5*dy*dy;}}else if(typeof y==='number'){var dy=x.w[0]-y;x.dw[0]=dy;loss+=0.5*dy*dy;}else{var i=y.dim;var yi=y.val;var dy=x.w[i]-yi;x.dw[i]=dy;loss+=0.5*dy*dy;}
return loss;},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.num_inputs=this.num_inputs;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.num_inputs=json.num_inputs;}}
var SVMLayer=function(opt){var opt=opt||{};this.num_inputs=opt.in_sx*opt.in_sy*opt.in_depth;this.out_depth=this.num_inputs;this.out_sx=1;this.out_sy=1;this.layer_type='svm';}
SVMLayer.prototype={forward:function(V,is_training){this.in_act=V;this.out_act=V;return V;},backward:function(y){var x=this.in_act;x.dw=convnet.zeros(x.w.length);var yscore=x.w[y];var margin=1.0;var loss=0.0;for(var i=0;i<this.out_depth;i++){if(y===i){continue;}
var ydiff=-yscore+x.w[i]+margin;if(ydiff>0){x.dw[i]+=1;x.dw[y]-=1;loss+=ydiff;}}
return loss;},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.num_inputs=this.num_inputs;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.num_inputs=json.num_inputs;}}
convnet.RegressionLayer=RegressionLayer;convnet.SoftmaxLayer=SoftmaxLayer;convnet.SVMLayer=SVMLayer;var ReluLayer=function(opt){var opt=opt||{};this.out_sx=opt.in_sx;this.out_sy=opt.in_sy;this.out_depth=opt.in_depth;this.layer_type='relu';}
ReluLayer.prototype={forward:function(V,is_training){this.in_act=V;var V2=V.clone();var N=V.w.length;var V2w=V2.w;for(var i=0;i<N;i++){if(V2w[i]<0)V2w[i]=0;}
this.out_act=V2;return this.out_act;},backward:function(){var V=this.in_act;var V2=this.out_act;var N=V.w.length;V.dw=convnet.zeros(N);for(var i=0;i<N;i++){if(V2.w[i]<=0)V.dw[i]=0;else V.dw[i]=V2.dw[i];}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;}}
var SigmoidLayer=function(opt){var opt=opt||{};this.out_sx=opt.in_sx;this.out_sy=opt.in_sy;this.out_depth=opt.in_depth;this.layer_type='sigmoid';}
SigmoidLayer.prototype={forward:function(V,is_training){this.in_act=V;var V2=V.cloneAndZero();var N=V.w.length;var V2w=V2.w;var Vw=V.w;for(var i=0;i<N;i++){V2w[i]=1.0/(1.0+Math.exp(-Vw[i]));}
this.out_act=V2;return this.out_act;},backward:function(){var V=this.in_act;var V2=this.out_act;var N=V.w.length;V.dw=convnet.zeros(N);for(var i=0;i<N;i++){var v2wi=V2.w[i];V.dw[i]=v2wi*(1.0-v2wi)*V2.dw[i];}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;}}
var MaxoutLayer=function(opt){var opt=opt||{};this.group_size=typeof opt.group_size!=='undefined'?opt.group_size:2;this.out_sx=opt.in_sx;this.out_sy=opt.in_sy;this.out_depth=Math.floor(opt.in_depth/this.group_size);this.layer_type='maxout';this.switches=convnet.zeros(this.out_sx*this.out_sy*this.out_depth);}
MaxoutLayer.prototype={forward:function(V,is_training){this.in_act=V;var N=this.out_depth;var V2=new Vol(this.out_sx,this.out_sy,this.out_depth,0.0);if(this.out_sx===1&&this.out_sy===1){for(var i=0;i<N;i++){var ix=i*this.group_size;var a=V.w[ix];var ai=0;for(var j=1;j<this.group_size;j++){var a2=V.w[ix+j];if(a2>a){a=a2;ai=j;}}
V2.w[i]=a;this.switches[i]=ix+ai;}}else{var n=0;for(var x=0;x<V.sx;x++){for(var y=0;y<V.sy;y++){for(var i=0;i<N;i++){var ix=i*this.group_size;var a=V.get(x,y,ix);var ai=0;for(var j=1;j<this.group_size;j++){var a2=V.get(x,y,ix+j);if(a2>a){a=a2;ai=j;}}
V2.set(x,y,i,a);this.switches[n]=ix+ai;n++;}}}}
this.out_act=V2;return this.out_act;},backward:function(){var V=this.in_act;var V2=this.out_act;var N=this.out_depth;V.dw=convnet.zeros(V.w.length);if(this.out_sx===1&&this.out_sy===1){for(var i=0;i<N;i++){var chain_grad=V2.dw[i];V.dw[this.switches[i]]=chain_grad;}}else{var n=0;for(var x=0;x<V2.sx;x++){for(var y=0;y<V2.sy;y++){for(var i=0;i<N;i++){var chain_grad=V2.get_grad(x,y,i);V.set_grad(x,y,this.switches[n],chain_grad);n++;}}}}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.group_size=this.group_size;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.group_size=json.group_size;this.switches=convnet.zeros(this.group_size);}}
function tanh(x){var y=Math.exp(2*x);return(y-1)/(y+1);}
var TanhLayer=function(opt){var opt=opt||{};this.out_sx=opt.in_sx;this.out_sy=opt.in_sy;this.out_depth=opt.in_depth;this.layer_type='tanh';}
TanhLayer.prototype={forward:function(V,is_training){this.in_act=V;var V2=V.cloneAndZero();var N=V.w.length;for(var i=0;i<N;i++){V2.w[i]=tanh(V.w[i]);}
this.out_act=V2;return this.out_act;},backward:function(){var V=this.in_act;var V2=this.out_act;var N=V.w.length;V.dw=convnet.zeros(N);for(var i=0;i<N;i++){var v2wi=V2.w[i];V.dw[i]=(1.0-v2wi*v2wi)*V2.dw[i];}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;}}
convnet.TanhLayer=TanhLayer;convnet.MaxoutLayer=MaxoutLayer;convnet.ReluLayer=ReluLayer;convnet.SigmoidLayer=SigmoidLayer;var DropoutLayer=function(opt){var opt=opt||{};this.out_sx=opt.in_sx;this.out_sy=opt.in_sy;this.out_depth=opt.in_depth;this.layer_type='dropout';this.drop_prob=typeof opt.drop_prob!=='undefined'?opt.drop_prob:0.5;this.dropped=convnet.zeros(this.out_sx*this.out_sy*this.out_depth);}
DropoutLayer.prototype={forward:function(V,is_training){this.in_act=V;if(typeof(is_training)==='undefined'){is_training=false;}
var V2=V.clone();var N=V.w.length;if(is_training){for(var i=0;i<N;i++){if(Math.random()<this.drop_prob){V2.w[i]=0;this.dropped[i]=true;}
else{this.dropped[i]=false;}}}else{for(var i=0;i<N;i++){V2.w[i]*=this.drop_prob;}}
this.out_act=V2;return this.out_act;},backward:function(){var V=this.in_act;var chain_grad=this.out_act;var N=V.w.length;V.dw=convnet.zeros(N);for(var i=0;i<N;i++){if(!(this.dropped[i])){V.dw[i]=chain_grad.dw[i];}}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.out_depth=this.out_depth;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.layer_type=this.layer_type;json.drop_prob=this.drop_prob;return json;},fromJSON:function(json){this.out_depth=json.out_depth;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.layer_type=json.layer_type;this.drop_prob=json.drop_prob;}}
convnet.DropoutLayer=DropoutLayer;var LocalResponseNormalizationLayer=function(opt){var opt=opt||{};this.k=opt.k;this.n=opt.n;this.alpha=opt.alpha;this.beta=opt.beta;this.out_sx=opt.in_sx;this.out_sy=opt.in_sy;this.out_depth=opt.in_depth;this.layer_type='lrn';if(this.n%2===0){console.log('WARNING n should be odd for LRN layer');}}
LocalResponseNormalizationLayer.prototype={forward:function(V,is_training){this.in_act=V;var A=V.cloneAndZero();this.S_cache_=V.cloneAndZero();var n2=Math.floor(this.n/2);for(var x=0;x<V.sx;x++){for(var y=0;y<V.sy;y++){for(var i=0;i<V.depth;i++){var ai=V.get(x,y,i);var den=0.0;for(var j=Math.max(0,i-n2);j<=Math.min(i+n2,V.depth-1);j++){var aa=V.get(x,y,j);den+=aa*aa;}
den*=this.alpha/this.n;den+=this.k;this.S_cache_.set(x,y,i,den);den=Math.pow(den,this.beta);A.set(x,y,i,ai/den);}}}
this.out_act=A;return this.out_act;},backward:function(){var V=this.in_act;V.dw=convnet.zeros(V.w.length);var A=this.out_act;var n2=Math.floor(this.n/2);for(var x=0;x<V.sx;x++){for(var y=0;y<V.sy;y++){for(var i=0;i<V.depth;i++){var chain_grad=this.out_act.get_grad(x,y,i);var S=this.S_cache_.get(x,y,i);var SB=Math.pow(S,this.beta);var SB2=SB*SB;for(var j=Math.max(0,i-n2);j<=Math.min(i+n2,V.depth-1);j++){var aj=V.get(x,y,j);var g=-aj*this.beta*Math.pow(S,this.beta-1)*this.alpha/this.n*2*aj;if(j===i)g+=SB;g/=SB2;g*=chain_grad;V.add_grad(x,y,j,g);}}}}},getParamsAndGrads:function(){return[];},toJSON:function(){var json={};json.k=this.k;json.n=this.n;json.alpha=this.alpha;json.beta=this.beta;json.out_sx=this.out_sx;json.out_sy=this.out_sy;json.out_depth=this.out_depth;json.layer_type=this.layer_type;return json;},fromJSON:function(json){this.k=json.k;this.n=json.n;this.alpha=json.alpha;this.beta=json.beta;this.out_sx=json.out_sx;this.out_sy=json.out_sy;this.out_depth=json.out_depth;this.layer_type=json.layer_type;}}
convnet.LocalResponseNormalizationLayer=LocalResponseNormalizationLayer;var assert=convnet.assert;var Net=function(options){this.layers=[];}
Net.prototype={makeLayers:function(defs){assert(defs.length>=2,'Error! At least one input layer and one loss layer are required.');assert(defs[0].type==='input','Error! First layer must be the input layer, to declare size of inputs');var desugar=function(){var new_defs=[];for(var i=0;i<defs.length;i++){var def=defs[i];if(def.type==='softmax'||def.type==='svm'){new_defs.push({type:'fc',num_neurons:def.num_classes});}
if(def.type==='regression'){new_defs.push({type:'fc',num_neurons:def.num_neurons});}
if((def.type==='fc'||def.type==='conv')&&typeof(def.bias_pref)==='undefined'){def.bias_pref=0.0;if(typeof def.activation!=='undefined'&&def.activation==='relu'){def.bias_pref=0.1;}}
new_defs.push(def);if(typeof def.activation!=='undefined'){if(def.activation==='relu'){new_defs.push({type:'relu'});}
else if(def.activation==='sigmoid'){new_defs.push({type:'sigmoid'});}
else if(def.activation==='tanh'){new_defs.push({type:'tanh'});}
else if(def.activation==='maxout'){var gs=def.group_size!=='undefined'?def.group_size:2;new_defs.push({type:'maxout',group_size:gs});}
else{console.log('ERROR unsupported activation '+def.activation);}}
if(typeof def.drop_prob!=='undefined'&&def.type!=='dropout'){new_defs.push({type:'dropout',drop_prob:def.drop_prob});}}
return new_defs;}
defs=desugar(defs);this.layers=[];for(var i=0;i<defs.length;i++){var def=defs[i];if(i>0){var prev=this.layers[i-1];def.in_sx=prev.out_sx;def.in_sy=prev.out_sy;def.in_depth=prev.out_depth;}
switch(def.type){case'fc':this.layers.push(new convnet.FullyConnLayer(def));break;case'lrn':this.layers.push(new convnet.LocalResponseNormalizationLayer(def));break;case'dropout':this.layers.push(new convnet.DropoutLayer(def));break;case'input':this.layers.push(new convnet.InputLayer(def));break;case'softmax':this.layers.push(new convnet.SoftmaxLayer(def));break;case'regression':this.layers.push(new convnet.RegressionLayer(def));break;case'conv':this.layers.push(new convnet.ConvLayer(def));break;case'pool':this.layers.push(new convnet.PoolLayer(def));break;case'relu':this.layers.push(new convnet.ReluLayer(def));break;case'sigmoid':this.layers.push(new convnet.SigmoidLayer(def));break;case'tanh':this.layers.push(new convnet.TanhLayer(def));break;case'maxout':this.layers.push(new convnet.MaxoutLayer(def));break;case'svm':this.layers.push(new convnet.SVMLayer(def));break;default:console.log('ERROR: UNRECOGNIZED LAYER TYPE: '+def.type);}}},forward:function(V,is_training){if(typeof(is_training)==='undefined')is_training=false;var act=this.layers[0].forward(V,is_training);for(var i=1;i<this.layers.length;i++){act=this.layers[i].forward(act,is_training);}
return act;},getCostLoss:function(V,y){this.forward(V,false);var N=this.layers.length;var loss=this.layers[N-1].backward(y);return loss;},backward:function(y){var N=this.layers.length;var loss=this.layers[N-1].backward(y);for(var i=N-2;i>=0;i--){this.layers[i].backward();}
return loss;},getParamsAndGrads:function(){var response=[];for(var i=0;i<this.layers.length;i++){var layer_reponse=this.layers[i].getParamsAndGrads();for(var j=0;j<layer_reponse.length;j++){response.push(layer_reponse[j]);}}
return response;},getPrediction:function(){var S=this.layers[this.layers.length-1];assert(S.layer_type==='softmax','getPrediction function assumes softmax as last layer of the net!');var p=S.out_act.w;var maxv=p[0];var maxi=0;for(var i=1;i<p.length;i++){if(p[i]>maxv){maxv=p[i];maxi=i;}}
return maxi;},toJSON:function(){var json={};json.layers=[];for(var i=0;i<this.layers.length;i++){json.layers.push(this.layers[i].toJSON());}
return json;},fromJSON:function(json){this.layers=[];for(var i=0;i<json.layers.length;i++){var Lj=json.layers[i]
var t=Lj.layer_type;var L;if(t==='input'){L=new convnet.InputLayer();}
if(t==='relu'){L=new convnet.ReluLayer();}
if(t==='sigmoid'){L=new convnet.SigmoidLayer();}
if(t==='tanh'){L=new convnet.TanhLayer();}
if(t==='dropout'){L=new convnet.DropoutLayer();}
if(t==='conv'){L=new convnet.ConvLayer();}
if(t==='pool'){L=new convnet.PoolLayer();}
if(t==='lrn'){L=new convnet.LocalResponseNormalizationLayer();}
if(t==='softmax'){L=new convnet.SoftmaxLayer();}
if(t==='regression'){L=new convnet.RegressionLayer();}
if(t==='fc'){L=new convnet.FullyConnLayer();}
if(t==='maxout'){L=new convnet.MaxoutLayer();}
if(t==='svm'){L=new convnet.SVMLayer();}
L.fromJSON(Lj);this.layers.push(L);}}}
convnet.Net=Net;var Trainer=function(net,options){this.net=net;var options=options||{};this.learning_rate=typeof options.learning_rate!=='undefined'?options.learning_rate:0.01;this.l1_decay=typeof options.l1_decay!=='undefined'?options.l1_decay:0.0;this.l2_decay=typeof options.l2_decay!=='undefined'?options.l2_decay:0.0;this.batch_size=typeof options.batch_size!=='undefined'?options.batch_size:1;this.method=typeof options.method!=='undefined'?options.method:'sgd';this.momentum=typeof options.momentum!=='undefined'?options.momentum:0.9;this.ro=typeof options.ro!=='undefined'?options.ro:0.95;this.eps=typeof options.eps!=='undefined'?options.eps:1e-8;this.beta1=typeof options.beta1!=='undefined'?options.beta1:0.9;this.beta2=typeof options.beta2!=='undefined'?options.beta2:0.999;this.k=0;this.gsum=[];this.xsum=[];if(this.net.layers[this.net.layers.length-1].layer_type==="regression")
this.regression=true;else
this.regression=false;}
Trainer.prototype={train:function(x,y){var start=new Date().getTime();this.net.forward(x,true);var end=new Date().getTime();var fwd_time=end-start;var start=new Date().getTime();var cost_loss=this.net.backward(y);var l2_decay_loss=0.0;var l1_decay_loss=0.0;var end=new Date().getTime();var bwd_time=end-start;if(this.regression&&y.constructor!==Array)
console.log("Warning: a regression net requires an array as training output vector.");this.k++;if(this.k%this.batch_size===0){var pglist=this.net.getParamsAndGrads();if(this.gsum.length===0&&(this.method!=='sgd'||this.momentum>0.0)){for(var i=0;i<pglist.length;i++){this.gsum.push(convnet.zeros(pglist[i].params.length));if(this.method==='adam'||this.method==='adadelta'){this.xsum.push(convnet.zeros(pglist[i].params.length));}else{this.xsum.push([]);}}}
for(var i=0;i<pglist.length;i++){var pg=pglist[i];var p=pg.params;var g=pg.grads;var l2_decay_mul=typeof pg.l2_decay_mul!=='undefined'?pg.l2_decay_mul:1.0;var l1_decay_mul=typeof pg.l1_decay_mul!=='undefined'?pg.l1_decay_mul:1.0;var l2_decay=this.l2_decay*l2_decay_mul;var l1_decay=this.l1_decay*l1_decay_mul;var plen=p.length;for(var j=0;j<plen;j++){l2_decay_loss+=l2_decay*p[j]*p[j]/2;l1_decay_loss+=l1_decay*Math.abs(p[j]);var l1grad=l1_decay*(p[j]>0?1:-1);var l2grad=l2_decay*(p[j]);var gij=(l2grad+l1grad+g[j])/this.batch_size;var gsumi=this.gsum[i];var xsumi=this.xsum[i];if(this.method==='adam'){gsumi[j]=gsumi[j]*this.beta1+(1-this.beta1)*gij;xsumi[j]=xsumi[j]*this.beta2+(1-this.beta2)*gij*gij;var biasCorr1=gsumi[j]*(1-Math.pow(this.beta1,this.k));var biasCorr2=xsumi[j]*(1-Math.pow(this.beta2,this.k));var dx=-this.learning_rate*biasCorr1/(Math.sqrt(biasCorr2)+this.eps);p[j]+=dx;}else if(this.method==='adagrad'){gsumi[j]=gsumi[j]+gij*gij;var dx=-this.learning_rate/Math.sqrt(gsumi[j]+this.eps)*gij;p[j]+=dx;}else if(this.method==='windowgrad'){gsumi[j]=this.ro*gsumi[j]+(1-this.ro)*gij*gij;var dx=-this.learning_rate/Math.sqrt(gsumi[j]+this.eps)*gij;p[j]+=dx;}else if(this.method==='adadelta'){gsumi[j]=this.ro*gsumi[j]+(1-this.ro)*gij*gij;var dx=-Math.sqrt((xsumi[j]+this.eps)/(gsumi[j]+this.eps))*gij;xsumi[j]=this.ro*xsumi[j]+(1-this.ro)*dx*dx;p[j]+=dx;}else if(this.method==='nesterov'){var dx=gsumi[j];gsumi[j]=gsumi[j]*this.momentum+this.learning_rate*gij;dx=this.momentum*dx-(1.0+this.momentum)*gsumi[j];p[j]+=dx;}else{if(this.momentum>0.0){var dx=this.momentum*gsumi[j]-this.learning_rate*gij;gsumi[j]=dx;p[j]+=dx;}else{p[j]+=-this.learning_rate*gij;}}
g[j]=0.0;}}}
return{fwd_time:fwd_time,bwd_time:bwd_time,l2_decay_loss:l2_decay_loss,l1_decay_loss:l1_decay_loss,cost_loss:cost_loss,softmax_loss:cost_loss,loss:cost_loss+l1_decay_loss+l2_decay_loss}}}
convnet.Trainer=Trainer;convnet.SGDTrainer=Trainer;var randf=convnet.randf;var randi=convnet.randi;var Net=convnet.Net;var Trainer=convnet.Trainer;var maxmin=convnet.maxmin;var randperm=convnet.randperm;var weightedSample=convnet.weightedSample;var getopt=convnet.getopt;var arrUnique=convnet.arrUnique;var MagicNet=function(data,labels,opt){var opt=opt||{};if(typeof data==='undefined'){data=[];}
if(typeof labels==='undefined'){labels=[];}
this.data=data;this.labels=labels;this.train_ratio=getopt(opt,'train_ratio',0.7);this.num_folds=getopt(opt,'num_folds',10);this.num_candidates=getopt(opt,'num_candidates',50);this.num_epochs=getopt(opt,'num_epochs',50);this.ensemble_size=getopt(opt,'ensemble_size',10);this.batch_size_min=getopt(opt,'batch_size_min',10);this.batch_size_max=getopt(opt,'batch_size_max',300);this.l2_decay_min=getopt(opt,'l2_decay_min',-4);this.l2_decay_max=getopt(opt,'l2_decay_max',2);this.learning_rate_min=getopt(opt,'learning_rate_min',-4);this.learning_rate_max=getopt(opt,'learning_rate_max',0);this.momentum_min=getopt(opt,'momentum_min',0.9);this.momentum_max=getopt(opt,'momentum_max',0.9);this.neurons_min=getopt(opt,'neurons_min',5);this.neurons_max=getopt(opt,'neurons_max',30);this.folds=[];this.candidates=[];this.evaluated_candidates=[];this.unique_labels=arrUnique(labels);this.iter=0;this.foldix=0;this.finish_fold_callback=null;this.finish_batch_callback=null;if(this.data.length>0){this.sampleFolds();this.sampleCandidates();}};MagicNet.prototype={sampleFolds:function(){var N=this.data.length;var num_train=Math.floor(this.train_ratio*N);this.folds=[];for(var i=0;i<this.num_folds;i++){var p=randperm(N);this.folds.push({train_ix:p.slice(0,num_train),test_ix:p.slice(num_train,N)});}},sampleCandidate:function(){var input_depth=this.data[0].w.length;var num_classes=this.unique_labels.length;var layer_defs=[];layer_defs.push({type:'input',out_sx:1,out_sy:1,out_depth:input_depth});var nwl=weightedSample([0,1,2,3],[0.2,0.3,0.3,0.2]);for(var q=0;q<nwl;q++){var ni=randi(this.neurons_min,this.neurons_max);var act=['tanh','maxout','relu'][randi(0,3)];if(randf(0,1)<0.5){var dp=Math.random();layer_defs.push({type:'fc',num_neurons:ni,activation:act,drop_prob:dp});}else{layer_defs.push({type:'fc',num_neurons:ni,activation:act});}}
layer_defs.push({type:'softmax',num_classes:num_classes});var net=new Net();net.makeLayers(layer_defs);var bs=randi(this.batch_size_min,this.batch_size_max);var l2=Math.pow(10,randf(this.l2_decay_min,this.l2_decay_max));var lr=Math.pow(10,randf(this.learning_rate_min,this.learning_rate_max));var mom=randf(this.momentum_min,this.momentum_max);var tp=randf(0,1);var trainer_def;if(tp<0.33){trainer_def={method:'adadelta',batch_size:bs,l2_decay:l2};}else if(tp<0.66){trainer_def={method:'adagrad',learning_rate:lr,batch_size:bs,l2_decay:l2};}else{trainer_def={method:'sgd',learning_rate:lr,momentum:mom,batch_size:bs,l2_decay:l2};}
var trainer=new Trainer(net,trainer_def);var cand={};cand.acc=[];cand.accv=0;cand.layer_defs=layer_defs;cand.trainer_def=trainer_def;cand.net=net;cand.trainer=trainer;return cand;},sampleCandidates:function(){this.candidates=[];for(var i=0;i<this.num_candidates;i++){var cand=this.sampleCandidate();this.candidates.push(cand);}},step:function(){this.iter++;var fold=this.folds[this.foldix];var dataix=fold.train_ix[randi(0,fold.train_ix.length)];for(var k=0;k<this.candidates.length;k++){var x=this.data[dataix];var l=this.labels[dataix];this.candidates[k].trainer.train(x,l);}
var lastiter=this.num_epochs*fold.train_ix.length;if(this.iter>=lastiter){var val_acc=this.evalValErrors();for(var k=0;k<this.candidates.length;k++){var c=this.candidates[k];c.acc.push(val_acc[k]);c.accv+=val_acc[k];}
this.iter=0;this.foldix++;if(this.finish_fold_callback!==null){this.finish_fold_callback();}
if(this.foldix>=this.folds.length){for(var k=0;k<this.candidates.length;k++){this.evaluated_candidates.push(this.candidates[k]);}
this.evaluated_candidates.sort(function(a,b){return(a.accv/a.acc.length)>(b.accv/b.acc.length)?-1:1;});if(this.evaluated_candidates.length>3*this.ensemble_size){this.evaluated_candidates=this.evaluated_candidates.slice(0,3*this.ensemble_size);}
if(this.finish_batch_callback!==null){this.finish_batch_callback();}
this.sampleCandidates();this.foldix=0;}else{for(var k=0;k<this.candidates.length;k++){var c=this.candidates[k];var net=new Net();net.makeLayers(c.layer_defs);var trainer=new Trainer(net,c.trainer_def);c.net=net;c.trainer=trainer;}}}},evalValErrors:function(){var vals=[];var fold=this.folds[this.foldix];for(var k=0;k<this.candidates.length;k++){var net=this.candidates[k].net;var v=0.0;for(var q=0;q<fold.test_ix.length;q++){var x=this.data[fold.test_ix[q]];var l=this.labels[fold.test_ix[q]];net.forward(x);var yhat=net.getPrediction();v+=(yhat===l?1.0:0.0);}
v/=fold.test_ix.length;vals.push(v);}
return vals;},predict_soft:function(data){var eval_candidates=[];var nv=0;if(this.evaluated_candidates.length===0){nv=this.candidates.length;eval_candidates=this.candidates;}else{nv=Math.min(this.ensemble_size,this.evaluated_candidates.length);eval_candidates=this.evaluated_candidates}
var xout,n;for(var j=0;j<nv;j++){var net=eval_candidates[j].net;var x=net.forward(data);if(j===0){xout=x;n=x.w.length;}else{for(var d=0;d<n;d++){xout.w[d]+=x.w[d];}}}
for(var d=0;d<n;d++){xout.w[d]/=nv;}
return xout;},predict:function(data){var xout=this.predict_soft(data);if(xout.w.length!==0){var stats=maxmin(xout.w);var predicted_label=stats.maxi;}else{var predicted_label=-1;}
return predicted_label;},toJSON:function(){var nv=Math.min(this.ensemble_size,this.evaluated_candidates.length);var json={};json.nets=[];for(var i=0;i<nv;i++){json.nets.push(this.evaluated_candidates[i].net.toJSON());}
return json;},fromJSON:function(json){this.ensemble_size=json.nets.length;this.evaluated_candidates=[];for(var i=0;i<this.ensemble_size;i++){var net=new Net();net.fromJSON(json.nets[i]);var dummy_candidate={};dummy_candidate.net=net;this.evaluated_candidates.push(dummy_candidate);}},onFinishFold:function(f){this.finish_fold_callback=f;},onFinishBatch:function(f){this.finish_batch_callback=f;}};convnet.MagicNet=MagicNet;};BundleModuleCode['ml/ann']=function(module,exports){var config={warnings:false};var activation={LOGISTIC:function LOGISTIC(x,derivate){var fx=1/(1+Math.exp(-x));if(!derivate)return fx;return fx*(1-fx);},TANH:function TANH(x,derivate){if(derivate)return 1-Math.pow(Math.tanh(x),2);return Math.tanh(x);},IDENTITY:function IDENTITY(x,derivate){return derivate?1:x;},STEP:function STEP(x,derivate){return derivate?0:x>0?1:0;},RELU:function RELU(x,derivate){if(derivate)return x>0?1:0;return x>0?x:0;},SOFTSIGN:function SOFTSIGN(x,derivate){var d=1+Math.abs(x);if(derivate)return x/Math.pow(d,2);return x/d;},SINUSOID:function SINUSOID(x,derivate){if(derivate)return Math.cos(x);return Math.sin(x);},GAUSSIAN:function GAUSSIAN(x,derivate){var d=Math.exp(-Math.pow(x,2));if(derivate)return-2*x*d;return d;},BENT_IDENTITY:function BENT_IDENTITY(x,derivate){var d=Math.sqrt(Math.pow(x,2)+1);if(derivate)return x/(2*d)+1;return(d-1)/2+x;},BIPOLAR:function BIPOLAR(x,derivate){return derivate?0:x>0?1:-1;},BIPOLAR_SIGMOID:function BIPOLAR_SIGMOID(x,derivate){var d=2/(1+Math.exp(-x))-1;if(derivate)return 1/2*(1+d)*(1-d);return d;},HARD_TANH:function HARD_TANH(x,derivate){if(derivate)return x>-1&&x<1?1:0;return Math.max(-1,Math.min(1,x));},ABSOLUTE:function ABSOLUTE(x,derivate){if(derivate)return x<0?-1:1;return Math.abs(x);},INVERSE:function INVERSE(x,derivate){if(derivate)return-1;return 1-x;},SELU:function SELU(x,derivate){var alpha=1.6732632423543772848170429916717;var scale=1.0507009873554804934193349852946;var fx=x>0?x:alpha*Math.exp(x)-alpha;if(derivate){return x>0?scale:(fx+alpha)*scale;}
return fx*scale;}};var mutation={ADD_NODE:{name:'ADD_NODE'},SUB_NODE:{name:'SUB_NODE',keep_gates:true},ADD_CONN:{name:'ADD_CONN'},SUB_CONN:{name:'REMOVE_CONN'},MOD_WEIGHT:{name:'MOD_WEIGHT',min:-1,max:1},MOD_BIAS:{name:'MOD_BIAS',min:-1,max:1},MOD_ACTIVATION:{name:'MOD_ACTIVATION',mutateOutput:true,allowed:[activation.LOGISTIC,activation.TANH,activation.RELU,activation.IDENTITY,activation.STEP,activation.SOFTSIGN,activation.SINUSOID,activation.GAUSSIAN,activation.BENT_IDENTITY,activation.BIPOLAR,activation.BIPOLAR_SIGMOID,activation.HARD_TANH,activation.ABSOLUTE,activation.INVERSE,activation.SELU]},ADD_SELF_CONN:{name:'ADD_SELF_CONN'},SUB_SELF_CONN:{name:'SUB_SELF_CONN'},ADD_GATE:{name:'ADD_GATE'},SUB_GATE:{name:'SUB_GATE'},ADD_BACK_CONN:{name:'ADD_BACK_CONN'},SUB_BACK_CONN:{name:'SUB_BACK_CONN'},SWAP_NODES:{name:'SWAP_NODES',mutateOutput:true}};mutation.ALL=[mutation.ADD_NODE,mutation.SUB_NODE,mutation.ADD_CONN,mutation.SUB_CONN,mutation.MOD_WEIGHT,mutation.MOD_BIAS,mutation.MOD_ACTIVATION,mutation.ADD_GATE,mutation.SUB_GATE,mutation.ADD_SELF_CONN,mutation.SUB_SELF_CONN,mutation.ADD_BACK_CONN,mutation.SUB_BACK_CONN,mutation.SWAP_NODES];mutation.FFW=[mutation.ADD_NODE,mutation.SUB_NODE,mutation.ADD_CONN,mutation.SUB_CONN,mutation.MOD_WEIGHT,mutation.MOD_BIAS,mutation.MOD_ACTIVATION,mutation.SWAP_NODES];var selection={FITNESS_PROPORTIONATE:{name:'FITNESS_PROPORTIONATE'},POWER:{name:'POWER',power:4},TOURNAMENT:{name:'TOURNAMENT',size:5,probability:0.5}};var crossover={SINGLE_POINT:{name:'SINGLE_POINT',config:[0.4]},TWO_POINT:{name:'TWO_POINT',config:[0.4,0.9]},UNIFORM:{name:'UNIFORM'},AVERAGE:{name:'AVERAGE'}};var cost={CROSS_ENTROPY:function(target,output){var error=0;for(var i=0;i<output.length;i++){error-=target[i]*Math.log(Math.max(output[i],1e-15))+(1-target[i])*Math.log(1-Math.max(output[i],1e-15));}
return error/output.length;},MSE:function(target,output){var error=0;for(var i=0;i<output.length;i++){error+=Math.pow(target[i]-output[i],2);}
return error/output.length;},BINARY:function(target,output){var misses=0;for(var i=0;i<output.length;i++){misses+=Math.round(target[i]*2)!==Math.round(output[i]*2);}
return misses;},MAE:function(target,output){var error=0;for(var i=0;i<output.length;i++){error+=Math.abs(target[i]-output[i]);}
return error/output.length;},MAPE:function(target,output){var error=0;for(var i=0;i<output.length;i++){error+=Math.abs((output[i]-target[i])/Math.max(target[i],1e-15));}
return error/output.length;},MSLE:function(target,output){var error=0;for(var i=0;i<output.length;i++){error+=Math.log(Math.max(target[i],1e-15))-Math.log(Math.max(output[i],1e-15));}
return error;},HINGE:function(target,output){var error=0;for(var i=0;i<output.length;i++){error+=Math.max(0,1-target[i]*output[i]);}
return error;}};var gating={OUTPUT:{name:'OUTPUT'},INPUT:{name:'INPUT'},SELF:{name:'SELF'}};var connection={ALL_TO_ALL:{name:'OUTPUT'},ALL_TO_ELSE:{name:'INPUT'},ONE_TO_ONE:{name:'SELF'}};var rate={FIXED:function(){var func=function(baseRate,iteration){return baseRate;};return func;},STEP:function(gamma,stepSize){gamma=gamma||0.9;stepSize=stepSize||100;var func=function(baseRate,iteration){return baseRate*Math.pow(gamma,Math.floor(iteration/stepSize));};return func;},EXP:function(gamma){gamma=gamma||0.999;var func=function(baseRate,iteration){return baseRate*Math.pow(gamma,iteration);};return func;},INV:function(gamma,power){gamma=gamma||0.001;power=power||2;var func=function(baseRate,iteration){return baseRate*Math.pow(1+gamma*iteration,-power);};return func;}};var methods={activation:activation,mutation:mutation,selection:selection,crossover:crossover,cost:cost,gating:gating,connection:connection,rate:rate};function Connection(from,to,weight){this.from=from;this.to=to;this.gain=1;this.weight=(typeof weight==='undefined')?Math.random()*0.2-0.1:weight;this.gater=null;this.elegibility=0;this.previousDeltaWeight=0;this.totalDeltaWeight=0;this.xtrace={nodes:[],values:[]};}
Connection.prototype={toJSON:function(){var json={weight:this.weight};return json;}};Connection.innovationID=function(a,b){return 1/2*(a+b)*(a+b+1)+b;};var mutation=methods.mutation;function Network(input,output){if(typeof input==='undefined'||typeof output==='undefined'){throw new Error('No input or output size given');}
this.input=input;this.output=output;this.nodes=[];this.connections=[];this.gates=[];this.selfconns=[];this.dropout=0;var i;for(i=0;i<this.input+this.output;i++){var type=i<this.input?'input':'output';this.nodes.push(new Node(type));}
for(i=0;i<this.input;i++){for(var j=this.input;j<this.output+this.input;j++){var weight=Math.random()*this.input*Math.sqrt(2/this.input);this.connect(this.nodes[i],this.nodes[j],weight);}}}
Network.prototype={activate:function(input,training){var output=[];for(var i=0;i<this.nodes.length;i++){if(this.nodes[i].type==='input'){this.nodes[i].activate(input[i]);}else if(this.nodes[i].type==='output'){var activation=this.nodes[i].activate();output.push(activation);}else{if(training)this.nodes[i].mask=Math.random()<this.dropout?0:1;this.nodes[i].activate();}}
return output;},noTraceActivate:function(input){var output=[];for(var i=0;i<this.nodes.length;i++){if(this.nodes[i].type==='input'){this.nodes[i].noTraceActivate(input[i]);}else if(this.nodes[i].type==='output'){var activation=this.nodes[i].noTraceActivate();output.push(activation);}else{this.nodes[i].noTraceActivate();}}
return output;},propagate:function(rate,momentum,update,target){if(typeof target==='undefined'||target.length!==this.output){throw new Error('Output target length should match network output length');}
var targetIndex=target.length;var i;for(i=this.nodes.length-1;i>=this.nodes.length-this.output;i--){this.nodes[i].propagate(rate,momentum,update,target[--targetIndex]);}
for(i=this.nodes.length-this.output-1;i>=this.input;i--){this.nodes[i].propagate(rate,momentum,update);}},clear:function(){for(var i=0;i<this.nodes.length;i++){this.nodes[i].clear();}},connect:function(from,to,weight){var connections=from.connect(to,weight);for(var i=0;i<connections.length;i++){var connection=connections[i];if(from!==to){this.connections.push(connection);}else{this.selfconns.push(connection);}}
return connections;},disconnect:function(from,to){var connections=from===to?this.selfconns:this.connections;for(var i=0;i<connections.length;i++){var connection=connections[i];if(connection.from===from&&connection.to===to){if(connection.gater!==null)this.ungate(connection);connections.splice(i,1);break;}}
from.disconnect(to);},gate:function(node,connection){if(this.nodes.indexOf(node)===-1){throw new Error('This node is not part of the network!');}else if(connection.gater!=null){if(config.warnings)console.warn('This connection is already gated!');return;}
node.gate(connection);this.gates.push(connection);},ungate:function(connection){var index=this.gates.indexOf(connection);if(index===-1){throw new Error('This connection is not gated!');}
this.gates.splice(index,1);connection.gater.ungate(connection);},remove:function(node){var index=this.nodes.indexOf(node);if(index===-1){throw new Error('This node does not exist in the network!');}
var gaters=[];this.disconnect(node,node);var inputs=[];for(var i=node.connections.in.length-1;i>=0;i--){var connection=node.connections.in[i];if(mutation.SUB_NODE.keep_gates&&connection.gater!==null&&connection.gater!==node){gaters.push(connection.gater);}
inputs.push(connection.from);this.disconnect(connection.from,node);}
var outputs=[];for(i=node.connections.out.length-1;i>=0;i--){var connection=node.connections.out[i];if(mutation.SUB_NODE.keep_gates&&connection.gater!==null&&connection.gater!==node){gaters.push(connection.gater);}
outputs.push(connection.to);this.disconnect(node,connection.to);}
var connections=[];for(i=0;i<inputs.length;i++){var input=inputs[i];for(var j=0;j<outputs.length;j++){var output=outputs[j];if(!input.isProjectingTo(output)){var conn=this.connect(input,output);connections.push(conn[0]);}}}
for(i=0;i<gaters.length;i++){if(connections.length===0)break;var gater=gaters[i];var connIndex=Math.floor(Math.random()*connections.length);this.gate(gater,connections[connIndex]);connections.splice(connIndex,1);}
for(i=node.connections.gated.length-1;i>=0;i--){var conn=node.connections.gated[i];this.ungate(conn);}
this.disconnect(node,node);this.nodes.splice(index,1);},mutate:function(method){if(typeof method==='undefined'){throw new Error('No (correct) mutate method given!');}
var i,j;switch(method){case mutation.ADD_NODE:var connection=this.connections[Math.floor(Math.random()*this.connections.length)];var gater=connection.gater;this.disconnect(connection.from,connection.to);var toIndex=this.nodes.indexOf(connection.to);var node=new Node('hidden');node.mutate(mutation.MOD_ACTIVATION);var minBound=Math.min(toIndex,this.nodes.length-this.output);this.nodes.splice(minBound,0,node);var newConn1=this.connect(connection.from,node)[0];var newConn2=this.connect(node,connection.to)[0];if(gater!=null){this.gate(gater,Math.random()>=0.5?newConn1:newConn2);}
break;case mutation.SUB_NODE:if(this.nodes.length===this.input+this.output){if(config.warnings)console.warn('No more nodes left to remove!');break;}
var index=Math.floor(Math.random()*(this.nodes.length-this.output-this.input)+this.input);this.remove(this.nodes[index]);break;case mutation.ADD_CONN:var available=[];for(i=0;i<this.nodes.length-this.output;i++){var node1=this.nodes[i];for(j=Math.max(i+1,this.input);j<this.nodes.length;j++){var node2=this.nodes[j];if(!node1.isProjectingTo(node2))available.push([node1,node2]);}}
if(available.length===0){if(config.warnings)console.warn('No more connections to be made!');break;}
var pair=available[Math.floor(Math.random()*available.length)];this.connect(pair[0],pair[1]);break;case mutation.SUB_CONN:var possible=[];for(i=0;i<this.connections.length;i++){var conn=this.connections[i];if(conn.from.connections.out.length>1&&conn.to.connections.in.length>1&&this.nodes.indexOf(conn.to)>this.nodes.indexOf(conn.from)){possible.push(conn);}}
if(possible.length===0){if(config.warnings)console.warn('No connections to remove!');break;}
var randomConn=possible[Math.floor(Math.random()*possible.length)];this.disconnect(randomConn.from,randomConn.to);break;case mutation.MOD_WEIGHT:var allconnections=this.connections.concat(this.selfconns);var connection=allconnections[Math.floor(Math.random()*allconnections.length)];var modification=Math.random()*(method.max-method.min)+method.min;connection.weight+=modification;break;case mutation.MOD_BIAS:var index=Math.floor(Math.random()*(this.nodes.length-this.input)+this.input);var node=this.nodes[index];node.mutate(method);break;case mutation.MOD_ACTIVATION:if(!method.mutateOutput&&this.input+this.output===this.nodes.length){if(config.warnings)console.warn('No nodes that allow mutation of activation function');break;}
var index=Math.floor(Math.random()*(this.nodes.length-(method.mutateOutput?0:this.output)-this.input)+this.input);var node=this.nodes[index];node.mutate(method);break;case mutation.ADD_SELF_CONN:var possible=[];for(i=this.input;i<this.nodes.length;i++){var node=this.nodes[i];if(node.connections.self.weight===0){possible.push(node);}}
if(possible.length===0){if(config.warnings)console.warn('No more self-connections to add!');break;}
var node=possible[Math.floor(Math.random()*possible.length)];this.connect(node,node);break;case mutation.SUB_SELF_CONN:if(this.selfconns.length===0){if(config.warnings)console.warn('No more self-connections to remove!');break;}
var conn=this.selfconns[Math.floor(Math.random()*this.selfconns.length)];this.disconnect(conn.from,conn.to);break;case mutation.ADD_GATE:var allconnections=this.connections.concat(this.selfconns);var possible=[];for(i=0;i<allconnections.length;i++){var conn=allconnections[i];if(conn.gater===null){possible.push(conn);}}
if(possible.length===0){if(config.warnings)console.warn('No more connections to gate!');break;}
var index=Math.floor(Math.random()*(this.nodes.length-this.input)+this.input);var node=this.nodes[index];var conn=possible[Math.floor(Math.random()*possible.length)];this.gate(node,conn);break;case mutation.SUB_GATE:if(this.gates.length===0){if(config.warnings)console.warn('No more connections to ungate!');break;}
var index=Math.floor(Math.random()*this.gates.length);var gatedconn=this.gates[index];this.ungate(gatedconn);break;case mutation.ADD_BACK_CONN:var available=[];for(i=this.input;i<this.nodes.length;i++){var node1=this.nodes[i];for(j=this.input;j<i;j++){var node2=this.nodes[j];if(!node1.isProjectingTo(node2))available.push([node1,node2]);}}
if(available.length===0){if(config.warnings)console.warn('No more connections to be made!');break;}
var pair=available[Math.floor(Math.random()*available.length)];this.connect(pair[0],pair[1]);break;case mutation.SUB_BACK_CONN:var possible=[];for(i=0;i<this.connections.length;i++){var conn=this.connections[i];if(conn.from.connections.out.length>1&&conn.to.connections.in.length>1&&this.nodes.indexOf(conn.from)>this.nodes.indexOf(conn.to)){possible.push(conn);}}
if(possible.length===0){if(config.warnings)console.warn('No connections to remove!');break;}
var randomConn=possible[Math.floor(Math.random()*possible.length)];this.disconnect(randomConn.from,randomConn.to);break;case mutation.SWAP_NODES:if((method.mutateOutput&&this.nodes.length-this.input<2)||(!method.mutateOutput&&this.nodes.length-this.input-this.output<2)){if(config.warnings)console.warn('No nodes that allow swapping of bias and activation function');break;}
var index=Math.floor(Math.random()*(this.nodes.length-(method.mutateOutput?0:this.output)-this.input)+this.input);var node1=this.nodes[index];index=Math.floor(Math.random()*(this.nodes.length-(method.mutateOutput?0:this.output)-this.input)+this.input);var node2=this.nodes[index];var biasTemp=node1.bias;var squashTemp=node1.squash;node1.bias=node2.bias;node1.squash=node2.squash;node2.bias=biasTemp;node2.squash=squashTemp;break;}},train:function(set,options){if(set[0].input.length!==this.input||set[0].output.length!==this.output){throw new Error('Dataset input/output size should be same as network input/output size!');}
options=options||{};if(typeof options.rate==='undefined'){if(config.warnings)console.warn('Using default learning rate, please define a rate!');}
if(typeof options.iterations==='undefined'){if(config.warnings)console.warn('No target iterations given, running until error is reached!');}
var targetError=options.error||0.05;var cost=options.cost||methods.cost.MSE;var baseRate=options.rate||0.3;var dropout=options.dropout||0;var momentum=options.momentum||0;var batchSize=options.batchSize||1;var ratePolicy=options.ratePolicy||methods.rate.FIXED();var start=Date.now();if(batchSize>set.length){throw new Error('Batch size must be smaller or equal to dataset length!');}else if(typeof options.iterations==='undefined'&&typeof options.error==='undefined'){throw new Error('At least one of the following options must be specified: error, iterations');}else if(typeof options.error==='undefined'){targetError=-1;}else if(typeof options.iterations==='undefined'){options.iterations=0;}
this.dropout=dropout;if(options.crossValidate){var numTrain=Math.ceil((1-options.crossValidate.testSize)*set.length);var trainSet=set.slice(0,numTrain);var testSet=set.slice(numTrain);}
var currentRate=baseRate;var iteration=0;var error=1;var i,j,x;while(error>targetError&&(options.iterations===0||iteration<options.iterations)){if(options.crossValidate&&error<=options.crossValidate.testError)break;iteration++;currentRate=ratePolicy(baseRate,iteration);if(options.crossValidate){this._trainSet(trainSet,batchSize,currentRate,momentum,cost);if(options.clear)this.clear();error=this.test(testSet,cost).error;if(options.clear)this.clear();}else{error=this._trainSet(set,batchSize,currentRate,momentum,cost);if(options.clear)this.clear();}
if(options.shuffle){for(j,x,i=set.length;i;j=Math.floor(Math.random()*i),x=set[--i],set[i]=set[j],set[j]=x);}
if(options.log&&iteration%options.log===0){console.log('iteration',iteration,'error',error,'rate',currentRate);}
if(options.schedule&&iteration%options.schedule.iterations===0){options.schedule.function({error:error,iteration:iteration});}}
if(options.clear)this.clear();if(dropout){for(i=0;i<this.nodes.length;i++){if(this.nodes[i].type==='hidden'||this.nodes[i].type==='constant'){this.nodes[i].mask=1-this.dropout;}}}
return{error:error,iterations:iteration,time:Date.now()-start};},_trainSet:function(set,batchSize,currentRate,momentum,costFunction){var errorSum=0;for(var i=0;i<set.length;i++){var input=set[i].input;var target=set[i].output;var update=!!((i+1)%batchSize===0||(i+1)===set.length);var output=this.activate(input,true);this.propagate(currentRate,momentum,update,target);errorSum+=costFunction(target,output);}
return errorSum/set.length;},test:function(set,cost){if(cost==undefined)cost=methods.cost.MSE;var i;if(this.dropout){for(i=0;i<this.nodes.length;i++){if(this.nodes[i].type==='hidden'||this.nodes[i].type==='constant'){this.nodes[i].mask=1-this.dropout;}}}
var error=0;var start=Date.now();for(i=0;i<set.length;i++){var input=set[i].input;var target=set[i].output;var output=this.noTraceActivate(input);error+=cost(target,output);}
error/=set.length;var results={error:error,time:Date.now()-start};return results;},graph:function(width,height){var input=0;var output=0;var json={nodes:[],links:[],constraints:[{type:'alignment',axis:'x',offsets:[]},{type:'alignment',axis:'y',offsets:[]}]};var i;for(i=0;i<this.nodes.length;i++){var node=this.nodes[i];if(node.type==='input'){if(this.input===1){json.constraints[0].offsets.push({node:i,offset:0});}else{json.constraints[0].offsets.push({node:i,offset:0.8*width/(this.input-1)*input++});}
json.constraints[1].offsets.push({node:i,offset:0});}else if(node.type==='output'){if(this.output===1){json.constraints[0].offsets.push({node:i,offset:0});}else{json.constraints[0].offsets.push({node:i,offset:0.8*width/(this.output-1)*output++});}
json.constraints[1].offsets.push({node:i,offset:-0.8*height});}
json.nodes.push({id:i,name:node.type==='hidden'?node.squash.name:node.type.toUpperCase(),activation:node.activation,bias:node.bias});}
var connections=this.connections.concat(this.selfconns);for(i=0;i<connections.length;i++){var connection=connections[i];if(connection.gater==null){json.links.push({source:this.nodes.indexOf(connection.from),target:this.nodes.indexOf(connection.to),weight:connection.weight});}else{var index=json.nodes.length;json.nodes.push({id:index,activation:connection.gater.activation,name:'GATE'});json.links.push({source:this.nodes.indexOf(connection.from),target:index,weight:1/2*connection.weight});json.links.push({source:index,target:this.nodes.indexOf(connection.to),weight:1/2*connection.weight});json.links.push({source:this.nodes.indexOf(connection.gater),target:index,weight:connection.gater.activation,gate:true});}}
return json;},toJSON:function(){var json={nodes:[],connections:[],input:this.input,output:this.output,dropout:this.dropout};var i;for(i=0;i<this.nodes.length;i++){this.nodes[i].index=i;}
for(i=0;i<this.nodes.length;i++){var node=this.nodes[i];var tojson=node.toJSON();tojson.index=i;json.nodes.push(tojson);if(node.connections.self.weight!==0){var tojson=node.connections.self.toJSON();tojson.from=i;tojson.to=i;tojson.gater=node.connections.self.gater!=null?node.connections.self.gater.index:null;json.connections.push(tojson);}}
for(i=0;i<this.connections.length;i++){var conn=this.connections[i];var tojson=conn.toJSON();tojson.from=conn.from.index;tojson.to=conn.to.index;tojson.gater=conn.gater!=null?conn.gater.index:null;json.connections.push(tojson);}
return json;},set:function(values){for(var i=0;i<this.nodes.length;i++){this.nodes[i].bias=values.bias||this.nodes[i].bias;this.nodes[i].squash=values.squash||this.nodes[i].squash;}},evolve:function(set,options){if(set[0].input.length!==this.input||set[0].output.length!==this.output){throw new Error('Dataset input/output size should be same as network input/output size!');}
options=options||{};var targetError=typeof options.error!=='undefined'?options.error:0.05;var growth=typeof options.growth!=='undefined'?options.growth:0.0001;var cost=options.cost||methods.cost.MSE;var amount=options.amount||1;var start=Date.now();if(typeof options.iterations==='undefined'&&typeof options.error==='undefined'){throw new Error('At least one of the following options must be specified: error, iterations');}else if(typeof options.error==='undefined'){targetError=-1;}else if(typeof options.iterations==='undefined'){options.iterations=0;}
var fitnessFunction;{fitnessFunction=function(genome){var score=0;for(var i=0;i<amount;i++){score-=genome.test(set,cost).error;}
score-=(genome.nodes.length-genome.input-genome.output+genome.connections.length+genome.gates.length)*growth;score=isNaN(score)?-Infinity:score;return score/amount;};}
options.network=this;var neat=new Neat(this.input,this.output,fitnessFunction,options);var error=-Infinity;var bestFitness=-Infinity;var bestGenome;while(error<-targetError&&(options.iterations===0||neat.generation<options.iterations)){var fittest=neat.evolve();var fitness=fittest.score;error=fitness+(fittest.nodes.length-fittest.input-fittest.output+fittest.connections.length+fittest.gates.length)*growth;if(fitness>bestFitness){bestFitness=fitness;bestGenome=fittest;}
if(options.log&&neat.generation%options.log===0){console.log('iteration',neat.generation,'fitness',fitness,'error',-error);}
if(options.schedule&&neat.generation%options.schedule.iterations===0){options.schedule.function({fitness:fitness,error:-error,iteration:neat.generation});}}
if(typeof bestGenome!=='undefined'){this.nodes=bestGenome.nodes;this.connections=bestGenome.connections;this.selfconns=bestGenome.selfconns;this.gates=bestGenome.gates;if(options.clear)this.clear();}
return{error:-error,iterations:neat.generation,time:Date.now()-start};},standalone:function(){var present=[];var activations=[];var states=[];var lines=[];var functions=[];var i;for(i=0;i<this.input;i++){var node=this.nodes[i];activations.push(node.activation);states.push(node.state);}
lines.push('for(var i = 0; i < input.length; i++) A[i] = input[i];');for(i=0;i<this.nodes.length;i++){this.nodes[i].index=i;}
for(i=this.input;i<this.nodes.length;i++){var node=this.nodes[i];activations.push(node.activation);states.push(node.state);var functionIndex=present.indexOf(node.squash.name);if(functionIndex===-1){functionIndex=present.length;present.push(node.squash.name);functions.push(node.squash.toString());}
var incoming=[];for(var j=0;j<node.connections.in.length;j++){var conn=node.connections.in[j];var computation="A["+conn.from.index+"] * "+conn.weight;if(conn.gater!=null){computation+=" * A["+conn.gater.index+"]";}
incoming.push(computation);}
if(node.connections.self.weight){var conn=node.connections.self;var computation="S["+i+"] * "+conn.weight;if(conn.gater!=null){computation+=" * A["+conn.gater.index+"]";}
incoming.push(computation);}
var line1="S["+i+"] = "+incoming.join(' + ')+" + "+node.bias+";";var line2="A["+i+"] = F["+functionIndex+"](S["+i+"])"+(!node.mask?' * '+node.mask:'')+";";lines.push(line1);lines.push(line2);}
var output=[];for(i=this.nodes.length-this.output;i<this.nodes.length;i++){output.push("A["+i+"]");}
output="return ["+output.join(',')+"];";lines.push(output);var total='';total+="var F = ["+functions.toString()+"];\r\n";total+="var A = ["+activations.toString()+"];\r\n";total+="var S = ["+states.toString()+"];\r\n";total+="function activate(input){\r\n"+lines.join('\r\n')+"\r\n}";return total;},serialize:function(){var activations=[];var states=[];var conns=[];var squashes=['LOGISTIC','TANH','IDENTITY','STEP','RELU','SOFTSIGN','SINUSOID','GAUSSIAN','BENT_IDENTITY','BIPOLAR','BIPOLAR_SIGMOID','HARD_TANH','ABSOLUTE','INVERSE','SELU'];conns.push(this.input);conns.push(this.output);var i;for(i=0;i<this.nodes.length;i++){var node=this.nodes[i];node.index=i;activations.push(node.activation);states.push(node.state);}
for(i=this.input;i<this.nodes.length;i++){var node=this.nodes[i];conns.push(node.index);conns.push(node.bias);conns.push(squashes.indexOf(node.squash.name));conns.push(node.connections.self.weight);conns.push(node.connections.self.gater==null?-1:node.connections.self.gater.index);for(var j=0;j<node.connections.in.length;j++){var conn=node.connections.in[j];conns.push(conn.from.index);conns.push(conn.weight);conns.push(conn.gater==null?-1:conn.gater.index);}
conns.push(-2);}
return[activations,states,conns];}};Network.fromJSON=function(json){var network=new Network(json.input,json.output);network.dropout=json.dropout;network.nodes=[];network.connections=[];var i;for(i=0;i<json.nodes.length;i++){network.nodes.push(Node.fromJSON(json.nodes[i]));}
for(i=0;i<json.connections.length;i++){var conn=json.connections[i];var connection=network.connect(network.nodes[conn.from],network.nodes[conn.to])[0];connection.weight=conn.weight;if(conn.gater!=null){network.gate(network.nodes[conn.gater],connection);}}
return network;};Network.merge=function(network1,network2){network1=Network.fromJSON(network1.toJSON());network2=Network.fromJSON(network2.toJSON());if(network1.output!==network2.input){throw new Error('Output size of network1 should be the same as the input size of network2!');}
var i;for(i=0;i<network2.connections.length;i++){var conn=network2.connections[i];if(conn.from.type==='input'){var index=network2.nodes.indexOf(conn.from);conn.from=network1.nodes[network1.nodes.length-1-index];}}
for(i=network2.input-1;i>=0;i--){network2.nodes.splice(i,1);}
for(i=network1.nodes.length-network1.output;i<network1.nodes.length;i++){network1.nodes[i].type='hidden';}
network1.connections=network1.connections.concat(network2.connections);network1.nodes=network1.nodes.concat(network2.nodes);return network1;};Network.crossOver=function(network1,network2,equal){if(network1.input!==network2.input||network1.output!==network2.output){throw new Error("Networks don't have the same input/output size!");}
var offspring=new Network(network1.input,network1.output);offspring.connections=[];offspring.nodes=[];var score1=network1.score||0;var score2=network2.score||0;var size;if(equal||score1===score2){var max=Math.max(network1.nodes.length,network2.nodes.length);var min=Math.min(network1.nodes.length,network2.nodes.length);size=Math.floor(Math.random()*(max-min+1)+min);}else if(score1>score2){size=network1.nodes.length;}else{size=network2.nodes.length;}
var outputSize=network1.output;var i;for(i=0;i<network1.nodes.length;i++){network1.nodes[i].index=i;}
for(i=0;i<network2.nodes.length;i++){network2.nodes[i].index=i;}
for(i=0;i<size;i++){var node;if(i<size-outputSize){var random=Math.random();node=random>=0.5?network1.nodes[i]:network2.nodes[i];var other=random<0.5?network1.nodes[i]:network2.nodes[i];if(typeof node==='undefined'||node.type==='output'){node=other;}}else{if(Math.random()>=0.5){node=network1.nodes[network1.nodes.length+i-size];}else{node=network2.nodes[network2.nodes.length+i-size];}}
var newNode=new Node();newNode.bias=node.bias;newNode.squash=node.squash;newNode.type=node.type;offspring.nodes.push(newNode);}
var n1conns={};var n2conns={};for(i=0;i<network1.connections.length;i++){var conn=network1.connections[i];var data={weight:conn.weight,from:conn.from.index,to:conn.to.index,gater:conn.gater!=null?conn.gater.index:-1};n1conns[Connection.innovationID(data.from,data.to)]=data;}
for(i=0;i<network1.selfconns.length;i++){var conn=network1.selfconns[i];var data={weight:conn.weight,from:conn.from.index,to:conn.to.index,gater:conn.gater!=null?conn.gater.index:-1};n1conns[Connection.innovationID(data.from,data.to)]=data;}
for(i=0;i<network2.connections.length;i++){var conn=network2.connections[i];var data={weight:conn.weight,from:conn.from.index,to:conn.to.index,gater:conn.gater!=null?conn.gater.index:-1};n2conns[Connection.innovationID(data.from,data.to)]=data;}
for(i=0;i<network2.selfconns.length;i++){var conn=network2.selfconns[i];var data={weight:conn.weight,from:conn.from.index,to:conn.to.index,gater:conn.gater!=null?conn.gater.index:-1};n2conns[Connection.innovationID(data.from,data.to)]=data;}
var connections=[];var keys1=Object.keys(n1conns);var keys2=Object.keys(n2conns);for(i=keys1.length-1;i>=0;i--){if(typeof n2conns[keys1[i]]!=='undefined'){var conn=Math.random()>=0.5?n1conns[keys1[i]]:n2conns[keys1[i]];connections.push(conn);n2conns[keys1[i]]=undefined;}else if(score1>=score2||equal){connections.push(n1conns[keys1[i]]);}}
if(score2>=score1||equal){for(i=0;i<keys2.length;i++){if(typeof n2conns[keys2[i]]!=='undefined'){connections.push(n2conns[keys2[i]]);}}}
for(i=0;i<connections.length;i++){var connData=connections[i];if(connData.to<size&&connData.from<size){var from=offspring.nodes[connData.from];var to=offspring.nodes[connData.to];var conn=offspring.connect(from,to)[0];conn.weight=connData.weight;if(connData.gater!==-1&&connData.gater<size){offspring.gate(offspring.nodes[connData.gater],conn);}}}
return offspring;};var architect={Construct:function(list){var network=new Network(0,0);var nodes=[];var i;for(i=0;i<list.length;i++){var j;if(list[i]instanceof Group){for(j=0;j<list[i].nodes.length;j++){nodes.push(list[i].nodes[j]);}}else if(list[i]instanceof Layer){for(j=0;j<list[i].nodes.length;j++){for(var k=0;k<list[i].nodes[j].nodes.length;k++){nodes.push(list[i].nodes[j].nodes[k]);}}}else if(list[i]instanceof Node){nodes.push(list[i]);}}
var inputs=[];var outputs=[];for(i=nodes.length-1;i>=0;i--){if(nodes[i].type==='output'||nodes[i].connections.out.length+nodes[i].connections.gated.length===0){nodes[i].type='output';network.output++;outputs.push(nodes[i]);nodes.splice(i,1);}else if(nodes[i].type==='input'||!nodes[i].connections.in.length){nodes[i].type='input';network.input++;inputs.push(nodes[i]);nodes.splice(i,1);}}
nodes=inputs.concat(nodes).concat(outputs);if(network.input===0||network.output===0){throw new Error('Given nodes have no clear input/output node!');}
for(i=0;i<nodes.length;i++){var j;for(j=0;j<nodes[i].connections.out.length;j++){network.connections.push(nodes[i].connections.out[j]);}
for(j=0;j<nodes[i].connections.gated.length;j++){network.gates.push(nodes[i].connections.gated[j]);}
if(nodes[i].connections.self.weight!==0){network.selfconns.push(nodes[i].connections.self);}}
network.nodes=nodes;return network;},Perceptron:function(){var layers=Array.prototype.slice.call(arguments);if(layers.length<3){throw new Error('You have to specify at least 3 layers');}
var nodes=[];nodes.push(new Group(layers[0]));for(var i=1;i<layers.length;i++){var layer=layers[i];layer=new Group(layer);nodes.push(layer);nodes[i-1].connect(nodes[i],methods.connection.ALL_TO_ALL);}
return architect.Construct(nodes);},Random:function(input,hidden,output,options){options=options||{};var connections=options.connections||hidden*2;var backconnections=options.backconnections||0;var selfconnections=options.selfconnections||0;var gates=options.gates||0;var network=new Network(input,output);var i;for(i=0;i<hidden;i++){network.mutate(methods.mutation.ADD_NODE);}
for(i=0;i<connections-hidden;i++){network.mutate(methods.mutation.ADD_CONN);}
for(i=0;i<backconnections;i++){network.mutate(methods.mutation.ADD_BACK_CONN);}
for(i=0;i<selfconnections;i++){network.mutate(methods.mutation.ADD_SELF_CONN);}
for(i=0;i<gates;i++){network.mutate(methods.mutation.ADD_GATE);}
return network;},LSTM:function(){var args=Array.prototype.slice.call(arguments);if(args.length<3){throw new Error('You have to specify at least 3 layers');}
var last=args.pop();var outputLayer;if(typeof last==='number'){outputLayer=new Group(last);last={};}else{outputLayer=new Group(args.pop());}
outputLayer.set({type:'output'});var options={};options.memoryToMemory=last.memoryToMemory||false;options.outputToMemory=last.outputToMemory||false;options.outputToGates=last.outputToGates||false;options.inputToOutput=last.inputToOutput===undefined?true:last.inputToOutput;options.inputToDeep=last.inputToDeep===undefined?true:last.inputToDeep;var inputLayer=new Group(args.shift());inputLayer.set({type:'input'});var blocks=args;var nodes=[];nodes.push(inputLayer);var previous=inputLayer;for(var i=0;i<blocks.length;i++){var block=blocks[i];var inputGate=new Group(block);var forgetGate=new Group(block);var memoryCell=new Group(block);var outputGate=new Group(block);var outputBlock=i===blocks.length-1?outputLayer:new Group(block);inputGate.set({bias:1});forgetGate.set({bias:1});outputGate.set({bias:1});var input=previous.connect(memoryCell,methods.connection.ALL_TO_ALL);previous.connect(inputGate,methods.connection.ALL_TO_ALL);previous.connect(outputGate,methods.connection.ALL_TO_ALL);previous.connect(forgetGate,methods.connection.ALL_TO_ALL);memoryCell.connect(inputGate,methods.connection.ALL_TO_ALL);memoryCell.connect(forgetGate,methods.connection.ALL_TO_ALL);memoryCell.connect(outputGate,methods.connection.ALL_TO_ALL);var forget=memoryCell.connect(memoryCell,methods.connection.ONE_TO_ONE);var output=memoryCell.connect(outputBlock,methods.connection.ALL_TO_ALL);inputGate.gate(input,methods.gating.INPUT);forgetGate.gate(forget,methods.gating.SELF);outputGate.gate(output,methods.gating.OUTPUT);if(options.inputToDeep&&i>0){var input=inputLayer.connect(memoryCell,methods.connection.ALL_TO_ALL);inputGate.gate(input,methods.gating.INPUT);}
if(options.memoryToMemory){var input=memoryCell.connect(memoryCell,methods.connection.ALL_TO_ELSE);inputGate.gate(input,methods.gating.INPUT);}
if(options.outputToMemory){var input=outputLayer.connect(memoryCell,methods.connection.ALL_TO_ALL);inputGate.gate(input,methods.gating.INPUT);}
if(options.outputToGates){outputLayer.connect(inputGate,methods.connection.ALL_TO_ALL);outputLayer.connect(forgetGate,methods.connection.ALL_TO_ALL);outputLayer.connect(outputGate,methods.connection.ALL_TO_ALL);}
nodes.push(inputGate);nodes.push(forgetGate);nodes.push(memoryCell);nodes.push(outputGate);if(i!==blocks.length-1)nodes.push(outputBlock);previous=outputBlock;}
if(options.inputToOutput){inputLayer.connect(outputLayer,methods.connection.ALL_TO_ALL);}
nodes.push(outputLayer);return architect.Construct(nodes);},GRU:function(){var args=Array.prototype.slice.call(arguments);if(args.length<3){throw new Error('not enough layers (minimum 3) !!');}
var inputLayer=new Group(args.shift());var outputLayer=new Group(args.pop());var blocks=args;var nodes=[];nodes.push(inputLayer);var previous=inputLayer;for(var i=0;i<blocks.length;i++){var layer=new Layer.GRU(blocks[i]);previous.connect(layer);previous=layer;nodes.push(layer);}
previous.connect(outputLayer);nodes.push(outputLayer);return architect.Construct(nodes);},Hopfield:function(size){var input=new Group(size);var output=new Group(size);input.connect(output,methods.connection.ALL_TO_ALL);input.set({type:'input'});output.set({squash:methods.activation.STEP,type:'output'});var network=new architect.Construct([input,output]);return network;},NARX:function(inputSize,hiddenLayers,outputSize,previousInput,previousOutput){if(!Array.isArray(hiddenLayers)){hiddenLayers=[hiddenLayers];}
var nodes=[];var input=new Layer.Dense(inputSize);var inputMemory=new Layer.Memory(inputSize,previousInput);var hidden=[];var output=new Layer.Dense(outputSize);var outputMemory=new Layer.Memory(outputSize,previousOutput);nodes.push(input);nodes.push(outputMemory);for(var i=0;i<hiddenLayers.length;i++){var hiddenLayer=new Layer.Dense(hiddenLayers[i]);hidden.push(hiddenLayer);nodes.push(hiddenLayer);if(typeof hidden[i-1]!=='undefined'){hidden[i-1].connect(hiddenLayer,methods.connection.ALL_TO_ALL);}}
nodes.push(inputMemory);nodes.push(output);input.connect(hidden[0],methods.connection.ALL_TO_ALL);input.connect(inputMemory,methods.connection.ONE_TO_ONE,1);inputMemory.connect(hidden[0],methods.connection.ALL_TO_ALL);hidden[hidden.length-1].connect(output,methods.connection.ALL_TO_ALL);output.connect(outputMemory,methods.connection.ONE_TO_ONE,1);outputMemory.connect(hidden[0],methods.connection.ALL_TO_ALL);input.set({type:'input'});output.set({type:'output'});return architect.Construct(nodes);}};function Node(type){this.bias=(type==='input')?0:Math.random()*0.2-0.1;this.squash=methods.activation.LOGISTIC;this.type=type||'hidden';this.activation=0;this.state=0;this.old=0;this.mask=1;this.previousDeltaBias=0;this.totalDeltaBias=0;this.connections={in:[],out:[],gated:[],self:new Connection(this,this,0)};this.error={responsibility:0,projected:0,gated:0};}
Node.prototype={activate:function(input){if(typeof input!=='undefined'){this.activation=input;return this.activation;}
this.old=this.state;this.state=this.connections.self.gain*this.connections.self.weight*this.state+this.bias;var i;for(i=0;i<this.connections.in.length;i++){var connection=this.connections.in[i];this.state+=connection.from.activation*connection.weight*connection.gain;}
this.activation=this.squash(this.state)*this.mask;this.derivative=this.squash(this.state,true);var nodes=[];var influences=[];for(i=0;i<this.connections.gated.length;i++){var conn=this.connections.gated[i];var node=conn.to;var index=nodes.indexOf(node);if(index>-1){influences[index]+=conn.weight*conn.from.activation;}else{nodes.push(node);influences.push(conn.weight*conn.from.activation+
(node.connections.self.gater===this?node.old:0));}
conn.gain=this.activation;}
for(i=0;i<this.connections.in.length;i++){var connection=this.connections.in[i];connection.elegibility=this.connections.self.gain*this.connections.self.weight*connection.elegibility+connection.from.activation*connection.gain;for(var j=0;j<nodes.length;j++){var node=nodes[j];var influence=influences[j];var index=connection.xtrace.nodes.indexOf(node);if(index>-1){connection.xtrace.values[index]=node.connections.self.gain*node.connections.self.weight*connection.xtrace.values[index]+this.derivative*connection.elegibility*influence;}else{connection.xtrace.nodes.push(node);connection.xtrace.values.push(this.derivative*connection.elegibility*influence);}}}
return this.activation;},noTraceActivate:function(input){if(typeof input!=='undefined'){this.activation=input;return this.activation;}
this.state=this.connections.self.gain*this.connections.self.weight*this.state+this.bias;var i;for(i=0;i<this.connections.in.length;i++){var connection=this.connections.in[i];this.state+=connection.from.activation*connection.weight*connection.gain;}
this.activation=this.squash(this.state);for(i=0;i<this.connections.gated.length;i++){this.connections.gated[i].gain=this.activation;}
return this.activation;},propagate:function(rate,momentum,update,target){momentum=momentum||0;rate=rate||0.3;var error=0;if(this.type==='output'){this.error.responsibility=this.error.projected=target-this.activation;}else{var i;for(i=0;i<this.connections.out.length;i++){var connection=this.connections.out[i];var node=connection.to;error+=node.error.responsibility*connection.weight*connection.gain;}
this.error.projected=this.derivative*error;error=0;for(i=0;i<this.connections.gated.length;i++){var conn=this.connections.gated[i];var node=conn.to;var influence=node.connections.self.gater===this?node.old:0;influence+=conn.weight*conn.from.activation;error+=node.error.responsibility*influence;}
this.error.gated=this.derivative*error;this.error.responsibility=this.error.projected+this.error.gated;}
if(this.type==='constant')return;for(i=0;i<this.connections.in.length;i++){var connection=this.connections.in[i];var gradient=this.error.projected*connection.elegibility;for(var j=0;j<connection.xtrace.nodes.length;j++){var node=connection.xtrace.nodes[j];var value=connection.xtrace.values[j];gradient+=node.error.responsibility*value;}
var deltaWeight=rate*gradient*this.mask;connection.totalDeltaWeight+=deltaWeight;if(update){connection.totalDeltaWeight+=momentum*connection.previousDeltaWeight;connection.weight+=connection.totalDeltaWeight;connection.previousDeltaWeight=connection.totalDeltaWeight;connection.totalDeltaWeight=0;}}
var deltaBias=rate*this.error.responsibility;this.totalDeltaBias+=deltaBias;if(update){this.totalDeltaBias+=momentum*this.previousDeltaBias;this.bias+=this.totalDeltaBias;this.previousDeltaBias=this.totalDeltaBias;this.totalDeltaBias=0;}},connect:function(target,weight){var connections=[];if(typeof target.bias!=='undefined'){if(target===this){if(this.connections.self.weight!==0){if(config.warnings)console.warn('This connection already exists!');}else{this.connections.self.weight=weight||1;}
connections.push(this.connections.self);}else if(this.isProjectingTo(target)){throw new Error('Already projecting a connection to this node!');}else{var connection=new Connection(this,target,weight);target.connections.in.push(connection);this.connections.out.push(connection);connections.push(connection);}}else{for(var i=0;i<target.nodes.length;i++){var connection=new Connection(this,target.nodes[i],weight);target.nodes[i].connections.in.push(connection);this.connections.out.push(connection);target.connections.in.push(connection);connections.push(connection);}}
return connections;},disconnect:function(node,twosided){if(this===node){this.connections.self.weight=0;return;}
for(var i=0;i<this.connections.out.length;i++){var conn=this.connections.out[i];if(conn.to===node){this.connections.out.splice(i,1);var j=conn.to.connections.in.indexOf(conn);conn.to.connections.in.splice(j,1);if(conn.gater!==null)conn.gater.ungate(conn);break;}}
if(twosided){node.disconnect(this);}},gate:function(connections){if(!Array.isArray(connections)){connections=[connections];}
for(var i=0;i<connections.length;i++){var connection=connections[i];this.connections.gated.push(connection);connection.gater=this;}},ungate:function(connections){if(!Array.isArray(connections)){connections=[connections];}
for(var i=connections.length-1;i>=0;i--){var connection=connections[i];var index=this.connections.gated.indexOf(connection);this.connections.gated.splice(index,1);connection.gater=null;connection.gain=1;}},clear:function(){for(var i=0;i<this.connections.in.length;i++){var connection=this.connections.in[i];connection.elegibility=0;connection.xtrace={nodes:[],values:[]};}
for(i=0;i<this.connections.gated.length;i++){var conn=this.connections.gated[i];conn.gain=0;}
this.error.responsibility=this.error.projected=this.error.gated=0;this.old=this.state=this.activation=0;},mutate:function(method){if(typeof method==='undefined'){throw new Error('No mutate method given!');}else if(!(method.name in methods.mutation)){throw new Error('This method does not exist!');}
switch(method){case methods.mutation.MOD_ACTIVATION:var squash=method.allowed[(method.allowed.indexOf(this.squash)+Math.floor(Math.random()*(method.allowed.length-1))+1)%method.allowed.length];this.squash=squash;break;case methods.mutation.MOD_BIAS:var modification=Math.random()*(method.max-method.min)+method.min;this.bias+=modification;break;}},isProjectingTo:function(node){if(node===this&&this.connections.self.weight!==0)return true;for(var i=0;i<this.connections.out.length;i++){var conn=this.connections.out[i];if(conn.to===node){return true;}}
return false;},isProjectedBy:function(node){if(node===this&&this.connections.self.weight!==0)return true;for(var i=0;i<this.connections.in.length;i++){var conn=this.connections.in[i];if(conn.from===node){return true;}}
return false;},toJSON:function(){var json={bias:this.bias,type:this.type,squash:this.squash.name,mask:this.mask};return json;}};Node.fromJSON=function(json){var node=new Node();node.bias=json.bias;node.type=json.type;node.mask=json.mask;node.squash=methods.activation[json.squash];return node;};function Layer(){this.output=null;this.nodes=[];this.connections={in:[],out:[],self:[]};}
Layer.prototype={activate:function(value){var values=[];if(typeof value!=='undefined'&&value.length!==this.nodes.length){throw new Error('Array with values should be same as the amount of nodes!');}
for(var i=0;i<this.nodes.length;i++){var activation;if(typeof value==='undefined'){activation=this.nodes[i].activate();}else{activation=this.nodes[i].activate(value[i]);}
values.push(activation);}
return values;},propagate:function(rate,momentum,target){if(typeof target!=='undefined'&&target.length!==this.nodes.length){throw new Error('Array with values should be same as the amount of nodes!');}
for(var i=this.nodes.length-1;i>=0;i--){if(typeof target==='undefined'){this.nodes[i].propagate(rate,momentum,true);}else{this.nodes[i].propagate(rate,momentum,true,target[i]);}}},connect:function(target,method,weight){var connections;if(target instanceof Group||target instanceof Node){connections=this.output.connect(target,method,weight);}else if(target instanceof Layer){connections=target.input(this,method,weight);}
return connections;},gate:function(connections,method){this.output.gate(connections,method);},set:function(values){for(var i=0;i<this.nodes.length;i++){var node=this.nodes[i];if(node instanceof Node){if(typeof values.bias!=='undefined'){node.bias=values.bias;}
node.squash=values.squash||node.squash;node.type=values.type||node.type;}else if(node instanceof Group){node.set(values);}}},disconnect:function(target,twosided){twosided=twosided||false;var i,j,k;if(target instanceof Group){for(i=0;i<this.nodes.length;i++){for(j=0;j<target.nodes.length;j++){this.nodes[i].disconnect(target.nodes[j],twosided);for(k=this.connections.out.length-1;k>=0;k--){var conn=this.connections.out[k];if(conn.from===this.nodes[i]&&conn.to===target.nodes[j]){this.connections.out.splice(k,1);break;}}
if(twosided){for(k=this.connections.in.length-1;k>=0;k--){var conn=this.connections.in[k];if(conn.from===target.nodes[j]&&conn.to===this.nodes[i]){this.connections.in.splice(k,1);break;}}}}}}else if(target instanceof Node){for(i=0;i<this.nodes.length;i++){this.nodes[i].disconnect(target,twosided);for(j=this.connections.out.length-1;j>=0;j--){var conn=this.connections.out[j];if(conn.from===this.nodes[i]&&conn.to===target){this.connections.out.splice(j,1);break;}}
if(twosided){for(k=this.connections.in.length-1;k>=0;k--){var conn=this.connections.in[k];if(conn.from===target&&conn.to===this.nodes[i]){this.connections.in.splice(k,1);break;}}}}}},clear:function(){for(var i=0;i<this.nodes.length;i++){this.nodes[i].clear();}}};Layer.Dense=function(size){var layer=new Layer();var block=new Group(size);layer.nodes.push(block);layer.output=block;layer.input=function(from,method,weight){if(from instanceof Layer)from=from.output;method=method||methods.connection.ALL_TO_ALL;return from.connect(block,method,weight);};return layer;};Layer.LSTM=function(size){var layer=new Layer();var inputGate=new Group(size);var forgetGate=new Group(size);var memoryCell=new Group(size);var outputGate=new Group(size);var outputBlock=new Group(size);inputGate.set({bias:1});forgetGate.set({bias:1});outputGate.set({bias:1});memoryCell.connect(inputGate,methods.connection.ALL_TO_ALL);memoryCell.connect(forgetGate,methods.connection.ALL_TO_ALL);memoryCell.connect(outputGate,methods.connection.ALL_TO_ALL);var forget=memoryCell.connect(memoryCell,methods.connection.ONE_TO_ONE);var output=memoryCell.connect(outputBlock,methods.connection.ALL_TO_ALL);forgetGate.gate(forget,methods.gating.SELF);outputGate.gate(output,methods.gating.OUTPUT);layer.nodes=[inputGate,forgetGate,memoryCell,outputGate,outputBlock];layer.output=outputBlock;layer.input=function(from,method,weight){if(from instanceof Layer)from=from.output;method=method||methods.connection.ALL_TO_ALL;var connections=[];var input=from.connect(memoryCell,method,weight);connections=connections.concat(input);connections=connections.concat(from.connect(inputGate,method,weight));connections=connections.concat(from.connect(outputGate,method,weight));connections=connections.concat(from.connect(forgetGate,method,weight));inputGate.gate(input,methods.gating.INPUT);return connections;};return layer;};Layer.GRU=function(size){var layer=new Layer();var updateGate=new Group(size);var inverseUpdateGate=new Group(size);var resetGate=new Group(size);var memoryCell=new Group(size);var output=new Group(size);var previousOutput=new Group(size);previousOutput.set({bias:0,squash:methods.activation.IDENTITY,type:'constant'});memoryCell.set({squash:methods.activation.TANH});inverseUpdateGate.set({bias:0,squash:methods.activation.INVERSE,type:'constant'});updateGate.set({bias:1});resetGate.set({bias:0});previousOutput.connect(updateGate,methods.connection.ALL_TO_ALL);updateGate.connect(inverseUpdateGate,methods.connection.ONE_TO_ONE,1);previousOutput.connect(resetGate,methods.connection.ALL_TO_ALL);var reset=previousOutput.connect(memoryCell,methods.connection.ALL_TO_ALL);resetGate.gate(reset,methods.gating.OUTPUT);var update1=previousOutput.connect(output,methods.connection.ALL_TO_ALL);var update2=memoryCell.connect(output,methods.connection.ALL_TO_ALL);updateGate.gate(update1,methods.gating.OUTPUT);inverseUpdateGate.gate(update2,methods.gating.OUTPUT);output.connect(previousOutput,methods.connection.ONE_TO_ONE,1);layer.nodes=[updateGate,inverseUpdateGate,resetGate,memoryCell,output,previousOutput];layer.output=output;layer.input=function(from,method,weight){if(from instanceof Layer)from=from.output;method=method||methods.connection.ALL_TO_ALL;var connections=[];connections=connections.concat(from.connect(updateGate,method,weight));connections=connections.concat(from.connect(resetGate,method,weight));connections=connections.concat(from.connect(memoryCell,method,weight));return connections;};return layer;};Layer.Memory=function(size,memory){var layer=new Layer();var previous=null;var i;for(i=0;i<memory;i++){var block=new Group(size);block.set({squash:methods.activation.IDENTITY,bias:0,type:'constant'});if(previous!=null){previous.connect(block,methods.connection.ONE_TO_ONE,1);}
layer.nodes.push(block);previous=block;}
layer.nodes.reverse();for(i=0;i<layer.nodes.length;i++){layer.nodes[i].nodes.reverse();}
var outputGroup=new Group(0);for(var group in layer.nodes){outputGroup.nodes=outputGroup.nodes.concat(layer.nodes[group].nodes);}
layer.output=outputGroup;layer.input=function(from,method,weight){if(from instanceof Layer)from=from.output;method=method||methods.connection.ALL_TO_ALL;if(from.nodes.length!==layer.nodes[layer.nodes.length-1].nodes.length){throw new Error('Previous layer size must be same as memory size');}
return from.connect(layer.nodes[layer.nodes.length-1],methods.connection.ONE_TO_ONE,1);};return layer;};function Group(size){this.nodes=[];this.connections={in:[],out:[],self:[]};for(var i=0;i<size;i++){this.nodes.push(new Node());}}
Group.prototype={activate:function(value){var values=[];if(typeof value!=='undefined'&&value.length!==this.nodes.length){throw new Error('Array with values should be same as the amount of nodes!');}
for(var i=0;i<this.nodes.length;i++){var activation;if(typeof value==='undefined'){activation=this.nodes[i].activate();}else{activation=this.nodes[i].activate(value[i]);}
values.push(activation);}
return values;},propagate:function(rate,momentum,target){if(typeof target!=='undefined'&&target.length!==this.nodes.length){throw new Error('Array with values should be same as the amount of nodes!');}
for(var i=this.nodes.length-1;i>=0;i--){if(typeof target==='undefined'){this.nodes[i].propagate(rate,momentum,true);}else{this.nodes[i].propagate(rate,momentum,true,target[i]);}}},connect:function(target,method,weight){var connections=[];var i,j;if(target instanceof Group){if(typeof method==='undefined'){if(this!==target){if(config.warnings)console.warn('No group connection specified, using ALL_TO_ALL');method=methods.connection.ALL_TO_ALL;}else{if(config.warnings)console.warn('No group connection specified, using ONE_TO_ONE');method=methods.connection.ONE_TO_ONE;}}
if(method===methods.connection.ALL_TO_ALL||method===methods.connection.ALL_TO_ELSE){for(i=0;i<this.nodes.length;i++){for(j=0;j<target.nodes.length;j++){if(method===methods.connection.ALL_TO_ELSE&&this.nodes[i]===target.nodes[j])continue;var connection=this.nodes[i].connect(target.nodes[j],weight);this.connections.out.push(connection[0]);target.connections.in.push(connection[0]);connections.push(connection[0]);}}}else if(method===methods.connection.ONE_TO_ONE){if(this.nodes.length!==target.nodes.length){throw new Error('From and To group must be the same size!');}
for(i=0;i<this.nodes.length;i++){var connection=this.nodes[i].connect(target.nodes[i],weight);this.connections.self.push(connection[0]);connections.push(connection[0]);}}}else if(target instanceof Layer){connections=target.input(this,method,weight);}else if(target instanceof Node){for(i=0;i<this.nodes.length;i++){var connection=this.nodes[i].connect(target,weight);this.connections.out.push(connection[0]);connections.push(connection[0]);}}
return connections;},gate:function(connections,method){if(typeof method==='undefined'){throw new Error('Please specify Gating.INPUT, Gating.OUTPUT');}
if(!Array.isArray(connections)){connections=[connections];}
var nodes1=[];var nodes2=[];var i,j;for(i=0;i<connections.length;i++){var connection=connections[i];if(!nodes1.includes(connection.from))nodes1.push(connection.from);if(!nodes2.includes(connection.to))nodes2.push(connection.to);}
switch(method){case methods.gating.INPUT:for(i=0;i<nodes2.length;i++){var node=nodes2[i];var gater=this.nodes[i%this.nodes.length];for(j=0;j<node.connections.in.length;j++){var conn=node.connections.in[j];if(connections.includes(conn)){gater.gate(conn);}}}
break;case methods.gating.OUTPUT:for(i=0;i<nodes1.length;i++){var node=nodes1[i];var gater=this.nodes[i%this.nodes.length];for(j=0;j<node.connections.out.length;j++){var conn=node.connections.out[j];if(connections.includes(conn)){gater.gate(conn);}}}
break;case methods.gating.SELF:for(i=0;i<nodes1.length;i++){var node=nodes1[i];var gater=this.nodes[i%this.nodes.length];if(connections.includes(node.connections.self)){gater.gate(node.connections.self);}}}},set:function(values){for(var i=0;i<this.nodes.length;i++){if(typeof values.bias!=='undefined'){this.nodes[i].bias=values.bias;}
this.nodes[i].squash=values.squash||this.nodes[i].squash;this.nodes[i].type=values.type||this.nodes[i].type;}},disconnect:function(target,twosided){twosided=twosided||false;var i,j,k;if(target instanceof Group){for(i=0;i<this.nodes.length;i++){for(j=0;j<target.nodes.length;j++){this.nodes[i].disconnect(target.nodes[j],twosided);for(k=this.connections.out.length-1;k>=0;k--){var conn=this.connections.out[k];if(conn.from===this.nodes[i]&&conn.to===target.nodes[j]){this.connections.out.splice(k,1);break;}}
if(twosided){for(k=this.connections.in.length-1;k>=0;k--){var conn=this.connections.in[k];if(conn.from===target.nodes[j]&&conn.to===this.nodes[i]){this.connections.in.splice(k,1);break;}}}}}}else if(target instanceof Node){for(i=0;i<this.nodes.length;i++){this.nodes[i].disconnect(target,twosided);for(j=this.connections.out.length-1;j>=0;j--){var conn=this.connections.out[j];if(conn.from===this.nodes[i]&&conn.to===target){this.connections.out.splice(j,1);break;}}
if(twosided){for(j=this.connections.in.length-1;j>=0;j--){var conn=this.connections.in[j];if(conn.from===target&&conn.to===this.nodes[i]){this.connections.in.splice(j,1);break;}}}}}},clear:function(){for(var i=0;i<this.nodes.length;i++){this.nodes[i].clear();}}};var selection=methods.selection;function Neat(input,output,fitness,options){this.input=input;this.output=output;this.fitness=fitness;options=options||{};this.equal=options.equal||false;this.clear=options.clear||false;this.popsize=options.popsize||50;this.elitism=options.elitism||0;this.provenance=options.provenance||0;this.mutationRate=options.mutationRate||0.3;this.mutationAmount=options.mutationAmount||1;this.fitnessPopulation=options.fitnessPopulation||false;this.selection=options.selection||methods.selection.POWER;this.crossover=options.crossover||[methods.crossover.SINGLE_POINT,methods.crossover.TWO_POINT,methods.crossover.UNIFORM,methods.crossover.AVERAGE];this.mutation=options.mutation||methods.mutation.FFW;this.template=options.network||false;this.maxNodes=options.maxNodes||Infinity;this.maxConns=options.maxConns||Infinity;this.maxGates=options.maxGates||Infinity;this.selectMutationMethod=typeof options.mutationSelection==='function'?options.mutationSelection.bind(this):this.selectMutationMethod;this.generation=0;this.createPool(this.template);}
Neat.prototype={createPool:function(network){this.population=[];for(var i=0;i<this.popsize;i++){var copy;if(this.template){copy=Network.fromJSON(network.toJSON());}else{copy=new Network(this.input,this.output);}
copy.score=undefined;this.population.push(copy);}},evolve:function(){if(typeof this.population[this.population.length-1].score==='undefined'){this.evaluate();}
this.sort();var fittest=Network.fromJSON(this.population[0].toJSON());fittest.score=this.population[0].score;var newPopulation=[];var elitists=[];for(var i=0;i<this.elitism;i++){elitists.push(this.population[i]);}
for(i=0;i<this.provenance;i++){newPopulation.push(Network.fromJSON(this.template.toJSON()));}
for(i=0;i<this.popsize-this.elitism-this.provenance;i++){newPopulation.push(this.getOffspring());}
this.population=newPopulation;this.mutate();var _this$population;(_this$population=this.population).push.apply(_this$population,elitists);for(i=0;i<this.population.length;i++){this.population[i].score=undefined;}
this.generation++;return fittest;},getOffspring:function(){var parent1=this.getParent();var parent2=this.getParent();return Network.crossOver(parent1,parent2,this.equal);},selectMutationMethod:function(genome){var mutationMethod=this.mutation[Math.floor(Math.random()*this.mutation.length)];if(mutationMethod===methods.mutation.ADD_NODE&&genome.nodes.length>=this.maxNodes){if(config.warnings)console.warn('maxNodes exceeded!');return;}
if(mutationMethod===methods.mutation.ADD_CONN&&genome.connections.length>=this.maxConns){if(config.warnings)console.warn('maxConns exceeded!');return;}
if(mutationMethod===methods.mutation.ADD_GATE&&genome.gates.length>=this.maxGates){if(config.warnings)console.warn('maxGates exceeded!');return;}
return mutationMethod;},mutate:function(){for(var i=0;i<this.population.length;i++){if(Math.random()<=this.mutationRate){for(var j=0;j<this.mutationAmount;j++){var mutationMethod=this.selectMutationMethod(this.population[i]);this.population[i].mutate(mutationMethod);}}}},evaluate:function(){var i;if(this.fitnessPopulation){if(this.clear){for(i=0;i<this.population.length;i++){this.population[i].clear();}}
this.fitness(this.population);}else{for(i=0;i<this.population.length;i++){var genome=this.population[i];if(this.clear)genome.clear();genome.score=this.fitness(genome);}}},sort:function(){this.population.sort(function(a,b){return b.score-a.score;});},getFittest:function(){if(typeof this.population[this.population.length-1].score==='undefined'){this.evaluate();}
if(this.population[0].score<this.population[1].score){this.sort();}
return this.population[0];},getAverage:function(){if(typeof this.population[this.population.length-1].score==='undefined'){this.evaluate();}
var score=0;for(var i=0;i<this.population.length;i++){score+=this.population[i].score;}
return score/this.population.length;},getParent:function(){var i;switch(this.selection){case selection.POWER:if(this.population[0].score<this.population[1].score)this.sort();var index=Math.floor(Math.pow(Math.random(),this.selection.power)*this.population.length);return this.population[index];case selection.FITNESS_PROPORTIONATE:var totalFitness=0;var minimalFitness=0;for(i=0;i<this.population.length;i++){var score=this.population[i].score;minimalFitness=score<minimalFitness?score:minimalFitness;totalFitness+=score;}
minimalFitness=Math.abs(minimalFitness);totalFitness+=minimalFitness*this.population.length;var random=Math.random()*totalFitness;var value=0;for(i=0;i<this.population.length;i++){var genome=this.population[i];value+=genome.score+minimalFitness;if(random<value)return genome;}
return this.population[Math.floor(Math.random()*this.population.length)];case selection.TOURNAMENT:if(this.selection.size>this.popsize){throw new Error('Your tournament size should be lower than the population size, please change methods.selection.TOURNAMENT.size');}
var individuals=[];for(i=0;i<this.selection.size;i++){var random=this.population[Math.floor(Math.random()*this.population.length)];individuals.push(random);}
individuals.sort(function(a,b){return b.score-a.score;});for(i=0;i<this.selection.size;i++){if(Math.random()<this.selection.probability||i===this.selection.size-1){return individuals[i];}}}},test:function(L,data){},export:function(){var json=[];for(var i=0;i<this.population.length;i++){var genome=this.population[i];json.push(genome.toJSON());}
return json;},import:function(json){var population=[];for(var i=0;i<json.length;i++){var genome=json[i];population.push(Network.fromJSON(genome));}
this.population=population;this.popsize=population.length;}};var Neataptic={methods:methods,Connection:Connection,architect:architect,Network:Network,config:config,Group:Group,Layer:Layer,Node:Node,Neat:Neat};module.exports=Neataptic};BundleModuleCode['ml/pca']=function(module,exports){var PCA=(function(){var options={};function computeDeviationMatrix(matrix){var unit=unitSquareMatrix(matrix.length);return subtract(matrix,scale(multiply(unit,matrix),1/matrix.length));}
function computeDeviationScores(deviation){var devSumOfSquares=multiply(transpose(deviation),deviation);return devSumOfSquares;}
function computeVarianceCovariance(devSumOfSquares,sample){var varianceCovariance;if(sample)
varianceCovariance=scale(devSumOfSquares,1/(devSumOfSquares.length-1));else
varianceCovariance=scale(devSumOfSquares,1/(devSumOfSquares.length));return varianceCovariance;}
function computeSVD(matrix){var result=svd(matrix);if(options.verbose)console.log(result)
var eigenvectors=result.U;var eigenvalues=result.S;var results=eigenvalues.map(function(value,i){var obj={};obj.eigenvalue=value;obj.vector=eigenvectors.map(function(vector,j){return-1*vector[i];});return obj;});return results;}
function computeAdjustedData(data){for(var _len=arguments.length,vectorObjs=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){vectorObjs[_key-1]=arguments[_key];}
var vectors=vectorObjs.map(function(v){return v.vector});var matrixMinusMean=computeDeviationMatrix(data);var adjustedData=multiply(vectors,transpose(matrixMinusMean));var unit=unitSquareMatrix(data.length);var avgData=scale(multiply(unit,data),-1/data.length);var formattedAdjustData=formatData(adjustedData,2);return{adjustedData:adjustedData,formattedAdjustedData:formattedAdjustData,avgData:avgData,selectedVectors:vectors};}
function computeOriginalData(adjustedData,vectors,avgData){var originalWithoutMean=transpose(multiply(transpose(vectors),adjustedData));var originalWithMean=subtract(originalWithoutMean,avgData);var formattedData=formatData(originalWithMean,2);return{originalData:originalWithMean,formattedOriginalData:formattedData}}
function computePercentageExplained(vectors){for(var _len=arguments.length,selected=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){selected[_key-1]=arguments[_key];}
var total=vectors.map(function(v){return v.eigenvalue}).reduce(function(a,b){return a+b;});var explained=selected.map(function(v){return v.eigenvalue}).reduce(function(a,b){return a+b;});return(explained/total);}
function getEigenVectors(data){return computeSVD(computeVarianceCovariance(computeDeviationScores(computeDeviationMatrix(data)),false));}
function analyseTopResult(data){var eigenVectors=getEigenVectors(data);var sorted=eigenVectors.sort(function(a,b){return b.eigenvalue-a.eigenvalue;});console.log('Sorted Vectors',sorted);var selected=sorted[0].vector;return computeAdjustedData(data,selected);}
function formatData(data,precision){var TEN=Math.pow(10,precision||2);return data.map(function(d,i){return d.map(function(n){return Math.round(n*TEN)/TEN;})})}
function multiply(a,b){if(!a[0]||!b[0]||!a.length||!b.length){throw new Error('Both A and B should be matrices');}
if(b.length!==a[0].length){throw new Error('Columns in A should be the same as the number of rows in B');}
var product=[];for(var i=0;i<a.length;i++){product[i]=[];for(var j=0;j<b[0].length;j++){for(var k=0;k<a[0].length;k++){(product[i])[j]=!!(product[i])[j]?(product[i])[j]+(a[i])[k]*(b[k])[j]:(a[i])[k]*(b[k])[j];}}}
return product;}
function subtract(a,b){if(!(a.length===b.length&&a[0].length===b[0].length))
throw new Error('Both A and B should have the same dimensions');var result=[];for(var i=0;i<a.length;i++){result[i]=[];for(var j=0;j<b[0].length;j++){(result[i])[j]=(a[i])[j]-(b[i])[j];}}
return result;}
function scale(matrix,factor){var result=[];for(var i=0;i<matrix.length;i++){result[i]=[];for(var j=0;j<matrix[0].length;j++){(result[i])[j]=(matrix[i])[j]*factor;}}
return result;}
function unitSquareMatrix(rows){var result=[];for(var i=0;i<rows;i++){result[i]=[];for(var j=0;j<rows;j++){(result[i])[j]=1;}}
return result;}
function transpose(matrix){var operated=clone(matrix);return operated[0].map(function(m,c){return matrix.map(function(r){return r[c];});});}
function clone(arr){var string=JSON.stringify(arr);var result=JSON.parse(string);return result;}
function svd(A){var temp;var prec=Math.pow(2,-52)
var tolerance=1.e-64/prec;var itmax=50;var c=0;var i=0;var j=0;var k=0;var l=0;var u=clone(A);var m=u.length;var n=u[0].length;if(m<n)throw"Need more rows than columns"
var e=new Array(n);var q=new Array(n);for(i=0;i<n;i++)e[i]=q[i]=0.0;var v=rep([n,n],0);function pythag(a,b){a=Math.abs(a)
b=Math.abs(b)
if(a>b)
return a*Math.sqrt(1.0+(b*b/a/a))
else if(b==0.0)
return a
return b*Math.sqrt(1.0+(a*a/b/b))}
function rep(s,v,k){if(typeof k==="undefined"){k=0;}
var n=s[k],ret=Array(n),i;if(k===s.length-1){for(i=n-2;i>=0;i-=2){ret[i+1]=v;ret[i]=v;}
if(i===-1){ret[0]=v;}
return ret;}
for(i=n-1;i>=0;i--){ret[i]=rep(s,v,k+1);}
return ret;}
var f=0.0;var g=0.0;var h=0.0;var x=0.0;var y=0.0;var z=0.0;var s=0.0;for(i=0;i<n;i++){e[i]=g;s=0.0;l=i+1;for(j=i;j<m;j++)
s+=(u[j][i]*u[j][i]);if(s<=tolerance)
g=0.0;else{f=u[i][i];g=Math.sqrt(s);if(f>=0.0)g=-g;h=f*g-s
u[i][i]=f-g;for(j=l;j<n;j++){s=0.0
for(k=i;k<m;k++)
s+=u[k][i]*u[k][j]
f=s/h
for(k=i;k<m;k++)
u[k][j]+=f*u[k][i]}}
q[i]=g
s=0.0
for(j=l;j<n;j++)
s=s+u[i][j]*u[i][j]
if(s<=tolerance)
g=0.0
else{f=u[i][i+1]
g=Math.sqrt(s)
if(f>=0.0)g=-g
h=f*g-s
u[i][i+1]=f-g;for(j=l;j<n;j++)e[j]=u[i][j]/h
for(j=l;j<m;j++){s=0.0
for(k=l;k<n;k++)
s+=(u[j][k]*u[i][k])
for(k=l;k<n;k++)
u[j][k]+=s*e[k]}}
y=Math.abs(q[i])+Math.abs(e[i])
if(y>x)
x=y}
for(i=n-1;i!=-1;i+=-1){if(g!=0.0){h=g*u[i][i+1]
for(j=l;j<n;j++)
v[j][i]=u[i][j]/h
for(j=l;j<n;j++){s=0.0
for(k=l;k<n;k++)
s+=u[i][k]*v[k][j]
for(k=l;k<n;k++)
v[k][j]+=(s*v[k][i])}}
for(j=l;j<n;j++){v[i][j]=0;v[j][i]=0;}
v[i][i]=1;g=e[i]
l=i}
for(i=n-1;i!=-1;i+=-1){l=i+1
g=q[i]
for(j=l;j<n;j++)
u[i][j]=0;if(g!=0.0){h=u[i][i]*g
for(j=l;j<n;j++){s=0.0
for(k=l;k<m;k++)s+=u[k][i]*u[k][j];f=s/h
for(k=i;k<m;k++)u[k][j]+=f*u[k][i];}
for(j=i;j<m;j++)u[j][i]=u[j][i]/g;}else
for(j=i;j<m;j++)u[j][i]=0;u[i][i]+=1;}
prec=prec*x
for(k=n-1;k!=-1;k+=-1){for(var iteration=0;iteration<itmax;iteration++){var test_convergence=false
for(l=k;l!=-1;l+=-1){if(Math.abs(e[l])<=prec){test_convergence=true
break}
if(Math.abs(q[l-1])<=prec)
break}
if(!test_convergence){c=0.0
s=1.0
var l1=l-1
for(i=l;i<k+1;i++){f=s*e[i]
e[i]=c*e[i]
if(Math.abs(f)<=prec)
break
g=q[i]
h=pythag(f,g)
q[i]=h
c=g/h
s=-f/h
for(j=0;j<m;j++){y=u[j][l1]
z=u[j][i]
u[j][l1]=y*c+(z*s)
u[j][i]=-y*s+(z*c)}}}
z=q[k]
if(l==k){if(z<0.0){q[k]=-z
for(j=0;j<n;j++)
v[j][k]=-v[j][k]}
break}
if(iteration>=itmax-1)
throw'Error: no convergence.'
x=q[l]
y=q[k-1]
g=e[k-1]
h=e[k]
f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y)
g=pythag(f,1.0)
if(f<0.0)
f=((x-z)*(x+z)+h*(y/(f-g)-h))/x
else
f=((x-z)*(x+z)+h*(y/(f+g)-h))/x
c=1.0
s=1.0
for(i=l+1;i<k+1;i++){g=e[i]
y=q[i]
h=s*g
g=c*g
z=pythag(f,h)
e[i-1]=z
c=f/z
s=h/z
f=x*c+g*s
g=-x*s+g*c
h=y*s
y=y*c
for(j=0;j<n;j++){x=v[j][i-1]
z=v[j][i]
v[j][i-1]=x*c+z*s
v[j][i]=-x*s+z*c}
z=pythag(f,h)
q[i-1]=z
c=f/z
s=h/z
f=c*g+s*y
x=-s*g+c*y
for(j=0;j<m;j++){y=u[j][i-1]
z=u[j][i]
u[j][i-1]=y*c+z*s
u[j][i]=-y*s+z*c}}
e[l]=0.0
e[k]=f
q[k]=x}}
for(i=0;i<q.length;i++)
if(q[i]<prec)q[i]=0
for(i=0;i<n;i++){for(j=i-1;j>=0;j--){if(q[j]<q[i]){c=q[j]
q[j]=q[i]
q[i]=c
for(k=0;k<u.length;k++){temp=u[k][i];u[k][i]=u[k][j];u[k][j]=temp;}
for(k=0;k<v.length;k++){temp=v[k][i];v[k][i]=v[k][j];v[k][j]=temp;}
i=j}}}
return{U:u,S:q,V:v}}
return{computeDeviationScores:computeDeviationScores,computeDeviationMatrix:computeDeviationMatrix,computeSVD:computeSVD,computePercentageExplained:computePercentageExplained,computeOriginalData:computeOriginalData,computeVarianceCovariance:computeVarianceCovariance,computeAdjustedData:computeAdjustedData,getEigenVectors:getEigenVectors,analyseTopResult:analyseTopResult,transpose:transpose,multiply:multiply,clone:clone,scale:scale,options:options}})();if(typeof module!=='undefined')
module.exports=PCA;};BundleModuleCode['nn/nn']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var current=none;var Aios=none;function inputFunction(flags){return function(x,y0){var p,y=0,w=1,c,i;if(x==undefined)return y0;for(p in flags){var k=flags[p];switch(p){case'invert':x=-x;break;case'threshold':x=(x>=k?x:0);break;case'weight':w=k;break;case'decay':c=k;break;case'integrate':i=k;break;}}
if(c!=undefined)y=y0-y0*c;if(i!=undefined)y=(c==undefined?y0:y)+x*i;else y=y+x;return{y:Math.max(-1.0,Math.min(1.0,y)),w:w};}}
var nn={compute:function(node,input){var i,ys=0,yw,neuron,neuron_input,next,computed,more;function ready(node){var p;for(p in node.input)if(node.input[p].x==undefined)return false;return true;}
switch(node.type){case'neuron':if(!input)
{input={};for(p in node.input)input[p]=node.input[p].x};for(i in node.input){if(input[i]==undefined)continue;yw=node.input[i].f(input[i],node.input[i].y);node.input[i].y=yw.y;node.input[i].x=undefined;ys+=(yw.y*yw.w);}
if(node.threshold!=undefined)
node.output=(ys>=node.threshold?1:0);else
node.output=Math.max(-1.0,Math.min(1.0,ys));break;case'network':for(p in input){if(node.input[p])
neuron_input=node.input[p].param;neuron=node.nodes[node.input[p].node];if(neuron)neuron.input[neuron_input].x=input[p];}
more=1;while(more){computed=0;for(i in node.nodes){neuron=node.nodes[i];if(ready(neuron)){nn.compute(neuron);computed++;if(neuron.connect)
for(p in neuron.connect){next=node.nodes[p];if(next)next.input[neuron.connect[p]].x=neuron.output;}}}
more=(computed!=node.nodes.length&&computed>0);}
break;}},connect:function(node1,node2,input){var c={};node1.connect[node2.id]=input;},network:function(nodes,connect){var i,n,p,conn,nw={type:'network',input:{}};for(i in nodes)nodes[i].id=i;function getNode(o){var p;for(p in o)if(p!='output'&&p!='input')return o[p];}
function getInput(o){var p;for(p in o)if(p!='output'&&p!='input')return p;}
function getIndex(o){var i;for(i in nodes)if(nodes[i].id==o.id)return i;}
nw.nodes=nodes;for(i in connect){conn=connect[i];if(conn.output){nn.connect(conn.output,getNode(conn),getInput(conn));}
else if(conn.input){for(p in conn){if(p!='input')nw.input[p]={node:getIndex(conn.input),param:conn[p]};}}}
return nw;},neuron:function(settings){var p,i,input,o={type:'neuron',id:(Math.random()*1000000)|0,threshold:settings.threshold,connect:{},input:{},output:settings.init||0}
for(p in settings){if(p=='init'||p=='threshold')continue;input=settings[p];o.input[p]={x:undefined,y:0,f:inputFunction(input)};}
return o;}}
module.exports={agent:nn,compute:nn.compute,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['csp/csp']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var simple=Require('csp/cspS');var current=none;var Aios=none;var CSP={SIMPLE:'SIMPLE',}
var options={version:'1.1.1'}
var csp={C:function(model,v1,v2,f){switch(model.algorithm){case CSP.SIMPLE:model.constraints.push([v1,v2,f]);break;}},V:function(model,name,val){switch(model.algorithm){case CSP.SIMPLE:model.variables[name]=val;break;}},range:function(a,b,step){var res=[];if(step==undefined)step=1;for(var i=a;i<=b;i=i+step)res.push(i);return res;},solver:function(options){var model={}
options=checkOptions(options,{});options.algorithm=checkOption(options.algorithm,CSP.SIMPLE);model.algorithm=options.algorithm;switch(options.algorithm){case CSP.SIMPLE:model.variables={}
model.constraints=[]
break;}
return model},solve:function(model,options){switch(model.algorithm){case CSP.SIMPLE:return simple.solve(model)}},CSP:CSP,}
module.exports={agent:csp,CSP:CSP,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['csp/cspS']=function(module,exports){var CSP={},FAILURE='FAILURE',stepCounter=0;CSP.solve=function solve(csp){var result=backtrack({},csp.variables,csp);if(result==FAILURE){return result;}
for(var key in result){result[key]=result[key][0];}
if(csp.cb)csp.cb(result);return result;}
function backtrack(_assigned,unassigned,csp){var assigned={};for(var key in _assigned){assigned[key]=_assigned[key];}
if(finished(unassigned)){return assigned;}
var nextKey=selectUnassignedVariable(unassigned),values=orderValues(nextKey,assigned,unassigned,csp);delete unassigned[nextKey];for(var i=0;i<values.length;i++){stepCounter++;assigned[nextKey]=[values[i]];var consistent=enforceConsistency(assigned,unassigned,csp);var newUnassigned={},newAssigned={};for(var key in consistent){if(assigned[key]){newAssigned[key]=assigned[key].slice();}
else{newUnassigned[key]=consistent[key].slice();}}
if(anyEmpty(consistent)){continue;}
var result=backtrack(newAssigned,newUnassigned,csp);if(result!=FAILURE){return result;}}
return FAILURE;}
function finished(unassigned){return Object.keys(unassigned).length==0;}
function anyEmpty(consistent){for(var key in consistent){if(consistent[key].length==0){return true;}}
return false;}
function partialAssignment(assigned,unassigned){var partial={};for(var key in unassigned){partial[key]=unassigned[key].slice();}
for(var key in assigned){partial[key]=assigned[key].slice();}
return partial;}
function enforceConsistency(assigned,unassigned,csp){function removeInconsistentValues(head,tail,constraint,variables){var hv,tv,validHeadValues,validTailValues,removed;if(tail){hv=variables[head],tv=variables[tail];validTailValues=tv.filter(function(t){return hv.some(function(h){return constraint(h,t);});});removed=tv.length!=validTailValues.length;variables[tail]=validTailValues;}else{hv=variables[head];validHeadValues=hv.filter(function(h){return constraint(h);});removed=hv.length!=validHeadValues.length;variables[head]=validHeadValues;}
return removed;}
function incomingConstraints(node){return csp.constraints.filter(function(c){return c[0]==node;});}
var queue=csp.constraints.slice(),variables=partialAssignment(assigned,unassigned);while(queue.length){var c=queue.shift(),head=c[0],tail=c[1],constraint=c[2];if(removeInconsistentValues(head,tail,constraint,variables)){queue=queue.concat(incomingConstraints(tail));}}
return variables;}
function selectUnassignedVariable(unassigned){var minKey=null,minLen=Number.POSITIVE_INFINITY;for(var key in unassigned){var len=unassigned[key].length;if(len<minLen){minKey=key,minLen=len;}}
return minKey;}
function orderValues(nextKey,assigned,unassigned,csp){function countValues(vars){var sum=0;for(var key in vars){sum+=vars[key].length;}
return sum;}
function valuesEliminated(val){assigned[nextKey]=[val];var newLength=countValues(enforceConsistency(assigned,unassigned,csp));delete assigned[nextKey];return newLength;}
var cache={},values=unassigned[nextKey];values.forEach(function(val){cache[val]=valuesEliminated(val);});values.sort(function(a,b){return cache[b]-cache[a];});return values;}
module.exports=CSP;};BundleModuleCode['logic/sat']=function(module,exports){var current=none;var Aios=none;var options={version:'1.1.1'}
var Logic=Require('logic/logic-solver');var Solved=[];var sat={create:function(options){var model={id:Aios.aidgen(),life:Aios.time()}
return model;},eval:function(model,what){sat.setup(model);if(!Solved[model.id])return;Solved[model.id].life=Aios.time();return Solved[model.id].evaluate(what)},gc:function(){var time=Aios.time();for(var p in Solved){if(Solved[p]&&(Solved[p].time+sat.lifetime)<time){delete Solved[p];delete Logic._minisatSolvers[p];delete Logic._termifiers[p];}}},F:function(model,logic){sat.setup(model);Logic.Solver.forbid(model,logic)},L:Logic,R:function(model,logic){sat.setup(model);Logic.Solver.require(model,logic)},solver:function(options){var model=sat.create();Logic.Solver(model);return model},solve:function(model,assume){sat.setup(model);if(!Solved[model.id]){model._numClausesAddedToMiniSat=0;}
if(assume)
Solved[model.id]=Logic.Solver.solveAssuming(model,assume)
else
Solved[model.id]=Logic.Solver.solve(model);if(Solved[model.id])Solved[model.id].life=Aios.time();return Solved[model.id]?Solved[model.id].getTrueVars():null},lifetime:1E9,setup:function(model){if(!Logic._termifiers[model.id]||!Logic._minisatSolvers[model.id]){model.id=Aios.aidgen();model.life=Aios.time();Logic._termifiers[model.id]=new Logic.Termifier(model);model._numClausesAddedToMiniSat=0;Logic._minisatSolvers[model.id]=new Logic.MiniSat();}},true:function(model){sat.setup(model);if(!Solved[model.id])return;Solved[model.id].life=Aios.time();return Solved[model.id].getTrueVars()}}
sat.Logic=sat.L;sat.require=sat.R;sat.forbid=sat.F;module.exports={agent:sat,Logic:Logic,current:function(module){current=module.current;Aios=module;}}};BundleModuleCode['logic/logic-solver']=function(module,exports){var MiniSat=Require("logic/minisat_wrapper.js");var _=Require("ext/underscore");var parse=Require('ext/jsep');var Logic;Logic={};Logic.MiniSat=MiniSat;var withDescription=function(description,tester){tester.description=description;return tester;};var lazyInstanceofTester=function(description,obj,constructorName){return withDescription(description,function(x){return x instanceof obj[constructorName];});};Logic.isNumTerm=withDescription('a NumTerm (non-zero integer)',function(x){return(x===(x|0))&&x!==0;});Logic.isNameTerm=withDescription('a NameTerm (string)',function(x){return(typeof x==='string')&&!/^-*[0-9]*$/.test(x);});Logic.isTerm=withDescription('a Term (appropriate string or number)',function(x){return Logic.isNumTerm(x)||Logic.isNameTerm(x);});Logic.isWholeNumber=withDescription('a whole number (integer >= 0)',function(x){return(x===(x|0))&&x>=0;});Logic.isFormula=lazyInstanceofTester('a Formula',Logic,'Formula');Logic.isClause=function(o){return o&&o.tag=='Clause'}
Logic.isBits=lazyInstanceofTester('a Bits',Logic,'Bits');Logic._isInteger=withDescription('an integer',function(x){return x===(x|0);});Logic._isFunction=withDescription('a Function',function(x){return typeof x==='function';});Logic._isString=withDescription('a String',function(x){return typeof x==='string';});Logic._isArrayWhere=function(tester){var description='an array';if(tester.description){description+=' of '+tester.description;}
return withDescription(description,function(x){if(!_.isArray(x)){return false;}else{for(var i=0;i<x.length;i++){if(!tester(x[i])){return false;}}
return true;}});};Logic._isFormulaOrTerm=withDescription('a Formula or Term',function(x){return Logic.isFormula(x)||Logic.isTerm(x);});Logic._isFormulaOrTermOrBits=withDescription('a Formula, Term, or Bits',function(x){return Logic.isFormula(x)||Logic.isBits(x)||Logic.isTerm(x);});Logic._MiniSat=MiniSat;var isInteger=Logic._isInteger;var isFunction=Logic._isFunction;var isString=Logic._isString;var isArrayWhere=Logic._isArrayWhere;var isFormulaOrTerm=Logic._isFormulaOrTerm;var isFormulaOrTermOrBits=Logic._isFormulaOrTermOrBits;Logic._assert=function(value,tester,description){if(!tester(value)){var displayValue=(typeof value==='string'?JSON.stringify(value):value);throw new Error(displayValue+" is not "+
(tester.description||description));}};var assertNumArgs=function(actual,expected,funcName){if(actual!==expected){throw new Error("Expected "+expected+" args in "+funcName+", got "+actual);}};var assert=Logic._assert;Logic._assertIfEnabled=function(value,tester,description){if(assert)assert(value,tester,description);};Logic.disablingAssertions=function(f){var oldAssert=assert;try{assert=null;return f();}finally{assert=oldAssert;}};Logic._disablingTypeChecks=Logic.disablingAssertions;Logic.not=function(operand){if(assert)assert(operand,isFormulaOrTerm);if(operand instanceof Logic.Formula){return new Logic.NotFormula(operand);}else{if(typeof operand==='number'){return-operand;}else if(operand.charAt(0)==='-'){return operand.slice(1);}else{return'-'+operand;}}};Logic.NAME_FALSE="$F";Logic.NAME_TRUE="$T";Logic.NUM_FALSE=1;Logic.NUM_TRUE=2;Logic.TRUE=Logic.NAME_TRUE;Logic.FALSE=Logic.NAME_FALSE;Logic.Formula=function(){};Logic._defineFormula=function(constructor,typeName,methods){if(assert)assert(constructor,isFunction);if(assert)assert(typeName,isString);constructor.prototype=new Logic.Formula();constructor.prototype.type=typeName;if(methods){_.extend(constructor.prototype,methods);}};Logic.Formula.prototype.generateClauses=function(isTrue,termifier){throw new Error("Cannot generate this Formula; it must be expanded");};Logic.Formula._nextGuid=1;Logic.Formula.prototype._guid=null;Logic.Formula.prototype.guid=function(){if(this._guid===null){this._guid=Logic.Formula._nextGuid++;}
return this._guid;};Logic.Clause=function(){var terms=_.flatten(arguments);if(assert)assert(terms,isArrayWhere(Logic.isNumTerm));return{tag:'Clause',terms:terms,}};if(0)Logic.Clause.prototype.append=function(){return new Logic.Clause(this.terms.concat(_.flatten(arguments)));};Logic.Clause.append=function(){var args=_.flatten(arguments);var self=args[0];args=args.slice(1);return Logic.Clause(self.terms.concat(args));};var FormulaInfo=function(){this.varName=null;this.varNum=null;this.occursPositively=false;this.occursNegatively=false;this.isRequired=false;this.isForbidden=false;};Logic.Termifier=function(solver){this.solver=solver;};Logic.Termifier.prototype.clause=function(){var self=this;var formulas=_.flatten(arguments);if(assert)assert(formulas,isArrayWhere(isFormulaOrTerm));return new Logic.Clause(_.map(formulas,function(f){return self.term(f);}));};Logic.Termifier.prototype.term=function(formula){return Logic.Solver._formulaToTerm(this.solver,formula);};Logic.Termifier.prototype.generate=function(isTrue,formula){return Logic.Solver._generateFormula(this.solver,isTrue,formula,this);};Logic._minisatSolvers=[];Logic._termifiers=[];Logic.Solver=function(model){var solver=model||{};solver.tag='Solver';solver.clauses=[];solver._num2name=[null];solver._name2num={};var F=Logic.Solver.getVarNum(solver,Logic.NAME_FALSE,false,true);var T=Logic.Solver.getVarNum(solver,Logic.NAME_TRUE,false,true);if(F!==Logic.NUM_FALSE||T!==Logic.NUM_TRUE){throw new Error("Assertion failure: $T and $F have wrong numeric value");}
solver._F_used=false;solver._T_used=false;solver.clauses.push(new Logic.Clause(-Logic.NUM_FALSE));solver.clauses.push(new Logic.Clause(Logic.NUM_TRUE));solver._formulaInfo={};solver._nextFormulaNumByType={};solver._ungeneratedFormulas={};solver._numClausesAddedToMiniSat=0;solver._unsat=false;Logic._minisatSolvers[model.id]=new MiniSat();Logic._termifiers[model.id]=new Logic.Termifier(solver);return solver;};Logic.Solver.getVarNum=function(solver,vname,noCreate,_createInternals){var key=' '+vname;if(_.has(solver._name2num,key)){return solver._name2num[key];}else if(noCreate){return 0;}else{if(vname.charAt(0)==="$"&&!_createInternals){throw new Error("Only generated variable names can start with $");}
var vnum=solver._num2name.length;solver._name2num[key]=vnum;solver._num2name.push(vname);return vnum;}};Logic.Solver.getVarName=function(solver,vnum){if(assert)assert(vnum,isInteger);var num2name=solver._num2name;if(vnum<1||vnum>=num2name.length){throw new Error("Bad variable num: "+vnum);}else{return num2name[vnum];}};Logic.Solver.toNumTerm=function(solver,t,noCreate){if(assert)assert(t,Logic.isTerm);if(typeof t==='number'){return t;}else{var not=false;while(t.charAt(0)==='-'){t=t.slice(1);not=!not;}
var n=Logic.Solver.getVarNum(solver,t,noCreate);if(!n){return 0;}else{return(not?-n:n);}}};Logic.Solver.toNameTerm=function(solver,t){if(assert)assert(t,Logic.isTerm);if(typeof t==='string'){while(t.slice(0,2)==='--'){t=t.slice(2);}
return t;}else{var not=false;if(t<0){not=true;t=-t;}
t=Logic.Solver.getVarName(solver,t);if(not){t='-'+t;}
return t;}};Logic.Solver._addClause=function(solver,cls,_extraTerms,_useTermOverride){if(assert)assert(cls,Logic.isClause);var extraTerms=null;if(_extraTerms){extraTerms=_extraTerms;if(assert)assert(extraTerms,isArrayWhere(Logic.isNumTerm));}
var usedF=false;var usedT=false;var numRealTerms=cls.terms.length;if(extraTerms){cls=Logic.Clause.append(cls,extraTerms);}
for(var i=0;i<cls.terms.length;i++){var t=cls.terms[i];var v=(t<0)?-t:t;if(v===Logic.NUM_FALSE){usedF=true;}else if(v===Logic.NUM_TRUE){usedT=true;}else if(v<1||v>=solver._num2name.length){throw new Error("Bad variable number: "+v);}else if(i<numRealTerms){if(_useTermOverride){_useTermOverride(t);}else{Logic.Solver._useFormulaTerm(solver,t);}}}
solver._F_used=(solver._F_used||usedF);solver._T_used=(solver._T_used||usedT);solver.clauses.push(cls);};Logic.Solver._useFormulaTerm=function(solver,t,_addClausesOverride){if(assert)assert(t,Logic.isNumTerm);var v=(t<0)?-t:t;if(!_.has(solver._ungeneratedFormulas,v)){return;}
var formula=solver._ungeneratedFormulas[v];var info=Logic.Solver._getFormulaInfo(solver,formula);var positive=t>0;var deferredAddClauses=null;var addClauses;if(!_addClausesOverride){deferredAddClauses=[];addClauses=function(clauses,extraTerms){deferredAddClauses.push({clauses:clauses,extraTerms:extraTerms});};}else{addClauses=_addClausesOverride;}
if(positive&&!info.occursPositively){info.occursPositively=true;var clauses=Logic.Solver._generateFormula(solver,true,formula);addClauses(clauses,[-v]);}else if((!positive)&&!info.occursNegatively){info.occursNegatively=true;var clauses=Logic.Solver._generateFormula(solver,false,formula);addClauses(clauses,[v]);}
if(info.occursPositively&&info.occursNegatively){delete solver._ungeneratedFormulas[v];}
if(!(deferredAddClauses&&deferredAddClauses.length)){return;}
var useTerm=function(t){Logic.Solver._useFormulaTerm(solver,t,addClauses);};while(deferredAddClauses.length){var next=deferredAddClauses.pop();Logic.Solver._addClauses(solver,next.clauses,next.extraTerms,useTerm);}};Logic.Solver._addClauses=function(solver,array,_extraTerms,_useTermOverride){if(assert)assert(array,isArrayWhere(Logic.isClause));_.each(array,function(cls){Logic.Solver._addClause(solver,cls,_extraTerms,_useTermOverride);});};Logic.Solver.require=function(){var args=_.flatten(arguments);var solver=args[0];args=args.slice(1);Logic.Solver._requireForbidImpl(solver,true,args);};Logic.Solver.forbid=function(){var args=_.flatten(arguments);var solver=args[0];args=args.slice(1);Logic.Solver._requireForbidImpl(solver,false,args);};Logic.Solver._requireForbidImpl=function(solver,isRequire,formulas){if(assert)assert(formulas,isArrayWhere(isFormulaOrTerm));_.each(formulas,function(f){if(f instanceof Logic.NotFormula){Logic.Solver._requireForbidImpl(solver,!isRequire,[f.operand]);}else if(f instanceof Logic.Formula){var info=Logic.Solver._getFormulaInfo(solver,f);if(info.varNum!==null){var sign=isRequire?1:-1;Logic.Solver._addClause(solver,new Logic.Clause(sign*info.varNum));}else{Logic.Solver._addClauses(solver,Logic.Solver._generateFormula(solver,isRequire,f));}
if(isRequire){info.isRequired=true;}else{info.isForbidden=true;}}else{Logic.Solver._addClauses(solver,Logic.Solver._generateFormula(solver,isRequire,f));}});};Logic.Solver._generateFormula=function(solver,isTrue,formula,_termifier){if(assert)assert(formula,isFormulaOrTerm);if(formula instanceof Logic.NotFormula){return Logic.Solver._generateFormula(solver,!isTrue,formula.operand);}else if(formula instanceof Logic.Formula){var info=Logic.Solver._getFormulaInfo(solver,formula);if((isTrue&&info.isRequired)||(!isTrue&&info.isForbidden)){return[];}else if((isTrue&&info.isForbidden)||(!isTrue&&info.isRequired)){return[new Logic.Clause()];}else{var ret=formula.generateClauses(isTrue,_termifier||Logic._termifiers[solver.id]);return _.isArray(ret)?ret:[ret];}}else{var t=Logic.Solver.toNumTerm(solver,formula);var sign=isTrue?1:-1;if(t===sign*Logic.NUM_TRUE||t===-sign*Logic.NUM_FALSE){return[];}else if(t===sign*Logic.NUM_FALSE||t===-sign*Logic.NUM_TRUE){return[new Logic.Clause()];}else{return[new Logic.Clause(sign*t)];}}};Logic.Solver._clauseData=function(solver){var clauses=_.pluck(solver.clauses,'terms');if(!solver._T_used){clauses.splice(1,1);}
if(!solver._F_used){clauses.splice(0,1);}
return clauses;};Logic.Solver._clauseStrings=function(solver){var clauseData=Logic.Solver._clauseData(solver);return _.map(clauseData,function(clause){return _.map(clause,function(nterm){var str=Logic.Solver.toNameTerm(solver,nterm);if(/\s/.test(str)){var sign='';if(str.charAt(0)==='-'){sign='-';str=str.slice(1);}
str=sign+'"'+str+'"';}
return str;}).join(' v ');});};Logic.Solver._getFormulaInfo=function(solver,formula,_noCreate){var guid=formula.guid();if(!solver._formulaInfo[guid]){if(_noCreate){return null;}
solver._formulaInfo[guid]=new FormulaInfo();}
return solver._formulaInfo[guid];};Logic.Solver._formulaToTerm=function(solver,formula){if(_.isArray(formula)){if(assert)assert(formula,isArrayWhere(isFormulaOrTerm));return _.map(formula,_.bind(solver._formulaToTerm,solver));}else{if(assert)assert(formula,isFormulaOrTerm);}
if(formula instanceof Logic.NotFormula){return Logic.not(Logic.Solver._formulaToTerm(solver,formula.operand));}else if(formula instanceof Logic.Formula){var info=Logic.Solver._getFormulaInfo(solver,formula);if(info.isRequired){return Logic.NUM_TRUE;}else if(info.isForbidden){return Logic.NUM_FALSE;}else if(info.varNum===null){var type=formula.type;if(!solver._nextFormulaNumByType[type]){solver._nextFormulaNumByType[type]=1;}
var numForVarName=solver._nextFormulaNumByType[type]++;info.varName="$"+formula.type+numForVarName;info.varNum=Logic.Solver.getVarNum(solver,info.varName,false,true);solver._ungeneratedFormulas[info.varNum]=formula;}
return info.varNum;}else{return Logic.Solver.toNumTerm(solver,formula);}};Logic.or=function(){var args=_.flatten(arguments);if(args.length===0){return Logic.FALSE;}else if(args.length===1){if(assert)assert(args[0],isFormulaOrTerm);return args[0];}else{return new Logic.OrFormula(args);}};Logic.OrFormula=function(operands){if(assert)assert(operands,isArrayWhere(isFormulaOrTerm));this.operands=operands;};Logic._defineFormula(Logic.OrFormula,'or',{generateClauses:function(isTrue,t){if(isTrue){return t.clause(this.operands);}else{var result=[];_.each(this.operands,function(o){result.push.apply(result,t.generate(false,o));});return result;}}});Logic.NotFormula=function(operand){if(assert)assert(operand,isFormulaOrTerm);this.operand=operand;};Logic._defineFormula(Logic.NotFormula,'not');Logic.and=function(){var args=_.flatten(arguments);if(args.length===0){return Logic.TRUE;}else if(args.length===1){if(assert)assert(args[0],isFormulaOrTerm);return args[0];}else{return new Logic.AndFormula(args);}};Logic.AndFormula=function(operands){if(assert)assert(operands,isArrayWhere(isFormulaOrTerm));this.operands=operands;};Logic._defineFormula(Logic.AndFormula,'and',{generateClauses:function(isTrue,t){if(isTrue){var result=[];_.each(this.operands,function(o){result.push.apply(result,t.generate(true,o));});return result;}else{return t.clause(_.map(this.operands,Logic.not));}}});var group=function(array,N){var ret=[];for(var i=0;i<array.length;i+=N){ret.push(array.slice(i,i+N));}
return ret;};Logic.xor=function(){var args=_.flatten(arguments);if(args.length===0){return Logic.FALSE;}else if(args.length===1){if(assert)assert(args[0],isFormulaOrTerm);return args[0];}else{return new Logic.XorFormula(args);}};Logic.XorFormula=function(operands){if(assert)assert(operands,isArrayWhere(isFormulaOrTerm));this.operands=operands;};Logic._defineFormula(Logic.XorFormula,'xor',{generateClauses:function(isTrue,t){var args=this.operands;var not=Logic.not;if(args.length>3){return t.generate(isTrue,Logic.xor(_.map(group(this.operands,3),function(group){return Logic.xor(group);})));}else if(isTrue){if(args.length===0){return t.clause();}else if(args.length===1){return t.clause(args[0]);}else if(args.length===2){var A=args[0],B=args[1];return[t.clause(A,B),t.clause(not(A),not(B))];}else if(args.length===3){var A=args[0],B=args[1],C=args[2];return[t.clause(A,B,C),t.clause(A,not(B),not(C)),t.clause(not(A),B,not(C)),t.clause(not(A),not(B),C)];}}else{if(args.length===0){return[];}else if(args.length===1){return t.clause(not(args[0]));}else if(args.length===2){var A=args[0],B=args[1];return[t.clause(A,not(B)),t.clause(not(A),B)];}else if(args.length===3){var A=args[0],B=args[1],C=args[2];return[t.clause(not(A),not(B),not(C)),t.clause(not(A),B,C),t.clause(A,not(B),C),t.clause(A,B,not(C))];}}}});Logic.atMostOne=function(){var args=_.flatten(arguments);if(args.length<=1){return Logic.TRUE;}else{return new Logic.AtMostOneFormula(args);}};Logic.AtMostOneFormula=function(operands){if(assert)assert(operands,isArrayWhere(isFormulaOrTerm));this.operands=operands;};Logic._defineFormula(Logic.AtMostOneFormula,'atMostOne',{generateClauses:function(isTrue,t){var args=this.operands;var not=Logic.not;if(args.length<=1){return[];}else if(args.length===2){return t.generate(isTrue,Logic.not(Logic.and(args)));}else if(isTrue&&args.length===3){var clauses=[];for(var i=0;i<args.length;i++){for(var j=i+1;j<args.length;j++){clauses.push(t.clause(not(args[i]),not(args[j])));}}
return clauses;}else if((!isTrue)&&args.length===3){var A=args[0],B=args[1],C=args[2];return[t.clause(A,B),t.clause(A,C),t.clause(B,C)];}else{var groups=group(args,3);var ors=_.map(groups,function(g){return Logic.or(g);});if(groups[groups.length-1].length<2){groups.pop();}
var atMostOnes=_.map(groups,function(g){return Logic.atMostOne(g);});return t.generate(isTrue,Logic.and(Logic.atMostOne(ors),atMostOnes));}}});Logic.implies=function(A,B){if(assert)assertNumArgs(arguments.length,2,"Logic.implies");return new Logic.ImpliesFormula(A,B);};Logic.ImpliesFormula=function(A,B){if(assert)assert(A,isFormulaOrTerm);if(assert)assert(B,isFormulaOrTerm);if(assert)assertNumArgs(arguments.length,2,"Logic.implies");this.A=A;this.B=B;};Logic._defineFormula(Logic.ImpliesFormula,'implies',{generateClauses:function(isTrue,t){return t.generate(isTrue,Logic.or(Logic.not(this.A),this.B));}});Logic.equiv=function(A,B){if(assert)assertNumArgs(arguments.length,2,"Logic.equiv");return new Logic.EquivFormula(A,B);};Logic.EquivFormula=function(A,B){if(assert)assert(A,isFormulaOrTerm);if(assert)assert(B,isFormulaOrTerm);if(assert)assertNumArgs(arguments.length,2,"Logic.equiv");this.A=A;this.B=B;};Logic._defineFormula(Logic.EquivFormula,'equiv',{generateClauses:function(isTrue,t){return t.generate(!isTrue,Logic.xor(this.A,this.B));}});Logic.exactlyOne=function(){var args=_.flatten(arguments);if(args.length===0){return Logic.FALSE;}else if(args.length===1){if(assert)assert(args[0],isFormulaOrTerm);return args[0];}else{return new Logic.ExactlyOneFormula(args);}};Logic.ExactlyOneFormula=function(operands){if(assert)assert(operands,isArrayWhere(isFormulaOrTerm));this.operands=operands;};Logic._defineFormula(Logic.ExactlyOneFormula,'exactlyOne',{generateClauses:function(isTrue,t){var args=this.operands;if(args.length<3){return t.generate(isTrue,Logic.xor(args));}else{return t.generate(isTrue,Logic.and(Logic.atMostOne(args),Logic.or(args)));}}});Logic.Bits=function(formulaArray){if(assert)assert(formulaArray,isArrayWhere(isFormulaOrTerm));this.bits=formulaArray;};Logic.constantBits=function(wholeNumber){if(assert)assert(wholeNumber,Logic.isWholeNumber);var result=[];while(wholeNumber){result.push((wholeNumber&1)?Logic.TRUE:Logic.FALSE);wholeNumber>>>=1;}
return new Logic.Bits(result);};Logic.variableBits=function(baseName,nbits){if(assert)assert(nbits,Logic.isWholeNumber);var result=[];for(var i=0;i<nbits;i++){result.push(baseName+'$'+i);}
return new Logic.Bits(result);};Logic.lessThanOrEqual=function(bits1,bits2){return new Logic.LessThanOrEqualFormula(bits1,bits2);};Logic.LessThanOrEqualFormula=function(bits1,bits2){if(assert)assert(bits1,Logic.isBits);if(assert)assert(bits2,Logic.isBits);if(assert)assertNumArgs(arguments.length,2,"Bits comparison function");this.bits1=bits1;this.bits2=bits2;};var genLTE=function(bits1,bits2,t,notEqual){var ret=[];var A=bits1.bits.slice();var B=bits2.bits.slice();if(notEqual&&!bits2.bits.length){return t.clause();}
while(A.length>B.length){var hi=A.pop();ret.push(t.clause(Logic.not(hi)));}
var xors=_.map(B,function(b,i){if(i<A.length){return Logic.xor(A[i],b);}else{return b;}});for(var i=A.length-1;i>=0;i--){ret.push(t.clause(xors.slice(i+1),Logic.not(A[i]),B[i]));}
if(notEqual){ret.push.apply(ret,t.generate(true,Logic.or(xors)));}
return ret;};Logic._defineFormula(Logic.LessThanOrEqualFormula,'lte',{generateClauses:function(isTrue,t){if(isTrue){return genLTE(this.bits1,this.bits2,t,false);}else{return genLTE(this.bits2,this.bits1,t,true);}}});Logic.lessThan=function(bits1,bits2){return new Logic.LessThanFormula(bits1,bits2);};Logic.LessThanFormula=function(bits1,bits2){if(assert)assert(bits1,Logic.isBits);if(assert)assert(bits2,Logic.isBits);if(assert)assertNumArgs(arguments.length,2,"Bits comparison function");this.bits1=bits1;this.bits2=bits2;};Logic._defineFormula(Logic.LessThanFormula,'lt',{generateClauses:function(isTrue,t){if(isTrue){return genLTE(this.bits1,this.bits2,t,true);}else{return genLTE(this.bits2,this.bits1,t,false);}}});Logic.greaterThan=function(bits1,bits2){return Logic.lessThan(bits2,bits1);};Logic.greaterThanOrEqual=function(bits1,bits2){return Logic.lessThanOrEqual(bits2,bits1);};Logic.equalBits=function(bits1,bits2){return new Logic.EqualBitsFormula(bits1,bits2);};Logic.EqualBitsFormula=function(bits1,bits2){if(assert)assert(bits1,Logic.isBits);if(assert)assert(bits2,Logic.isBits);if(assert)assertNumArgs(arguments.length,2,"Logic.equalBits");this.bits1=bits1;this.bits2=bits2;};Logic._defineFormula(Logic.EqualBitsFormula,'equalBits',{generateClauses:function(isTrue,t){var A=this.bits1.bits;var B=this.bits2.bits;var nbits=Math.max(A.length,B.length);var facts=[];for(var i=0;i<nbits;i++){if(i>=A.length){facts.push(Logic.not(B[i]));}else if(i>=B.length){facts.push(Logic.not(A[i]));}else{facts.push(Logic.equiv(A[i],B[i]));}}
return t.generate(isTrue,Logic.and(facts));}});Logic.HalfAdderSum=function(formula1,formula2){if(assert)assert(formula1,isFormulaOrTerm);if(assert)assert(formula2,isFormulaOrTerm);if(assert)assertNumArgs(arguments.length,2,"Logic.HalfAdderSum");this.a=formula1;this.b=formula2;};Logic._defineFormula(Logic.HalfAdderSum,'hsum',{generateClauses:function(isTrue,t){return t.generate(isTrue,Logic.xor(this.a,this.b));}});Logic.HalfAdderCarry=function(formula1,formula2){if(assert)assert(formula1,isFormulaOrTerm);if(assert)assert(formula2,isFormulaOrTerm);if(assert)assertNumArgs(arguments.length,2,"Logic.HalfAdderCarry");this.a=formula1;this.b=formula2;};Logic._defineFormula(Logic.HalfAdderCarry,'hcarry',{generateClauses:function(isTrue,t){return t.generate(isTrue,Logic.and(this.a,this.b));}});Logic.FullAdderSum=function(formula1,formula2,formula3){if(assert)assert(formula1,isFormulaOrTerm);if(assert)assert(formula2,isFormulaOrTerm);if(assert)assert(formula3,isFormulaOrTerm);if(assert)assertNumArgs(arguments.length,3,"Logic.FullAdderSum");this.a=formula1;this.b=formula2;this.c=formula3;};Logic._defineFormula(Logic.FullAdderSum,'fsum',{generateClauses:function(isTrue,t){return t.generate(isTrue,Logic.xor(this.a,this.b,this.c));}});Logic.FullAdderCarry=function(formula1,formula2,formula3){if(assert)assert(formula1,isFormulaOrTerm);if(assert)assert(formula2,isFormulaOrTerm);if(assert)assert(formula3,isFormulaOrTerm);if(assert)assertNumArgs(arguments.length,3,"Logic.FullAdderCarry");this.a=formula1;this.b=formula2;this.c=formula3;};Logic._defineFormula(Logic.FullAdderCarry,'fcarry',{generateClauses:function(isTrue,t){return t.generate(!isTrue,Logic.atMostOne(this.a,this.b,this.c));}});var binaryWeightedSum=function(varsByWeight){if(assert)assert(varsByWeight,isArrayWhere(isArrayWhere(isFormulaOrTerm)));var buckets=_.map(varsByWeight,_.clone);var lowestWeight=0;var output=[];while(lowestWeight<buckets.length){var bucket=buckets[lowestWeight];if(!bucket.length){output.push(Logic.FALSE);lowestWeight++;}else if(bucket.length===1){output.push(bucket[0]);lowestWeight++;}else if(bucket.length===2){var sum=new Logic.HalfAdderSum(bucket[0],bucket[1]);var carry=new Logic.HalfAdderCarry(bucket[0],bucket[1]);bucket.length=0;bucket.push(sum);pushToNth(buckets,lowestWeight+1,carry);}else{var c=bucket.pop();var b=bucket.pop();var a=bucket.pop();var sum=new Logic.FullAdderSum(a,b,c);var carry=new Logic.FullAdderCarry(a,b,c);bucket.push(sum);pushToNth(buckets,lowestWeight+1,carry);}}
return output;};var pushToNth=function(arrayOfArrays,n,newItem){while(n>=arrayOfArrays.length){arrayOfArrays.push([]);}
arrayOfArrays[n].push(newItem);};var checkWeightedSumArgs=function(formulas,weights){if(assert)assert(formulas,isArrayWhere(isFormulaOrTerm));if(typeof weights==='number'){if(assert)assert(weights,Logic.isWholeNumber);}else{if(assert)assert(weights,isArrayWhere(Logic.isWholeNumber));if(formulas.length!==weights.length){throw new Error("Formula array and weight array must be same length"+"; they are "+formulas.length+" and "+weights.length);}}};Logic.weightedSum=function(formulas,weights){checkWeightedSumArgs(formulas,weights);if(formulas.length===0){return new Logic.Bits([]);}
if(typeof weights==='number'){weights=_.map(formulas,function(){return weights;});}
var binaryWeighted=[];_.each(formulas,function(f,i){var w=weights[i];var whichBit=0;while(w){if(w&1){pushToNth(binaryWeighted,whichBit,f);}
w>>>=1;whichBit++;}});return new Logic.Bits(binaryWeightedSum(binaryWeighted));};Logic.sum=function(){var things=_.flatten(arguments);if(assert)assert(things,isArrayWhere(isFormulaOrTermOrBits));var binaryWeighted=[];_.each(things,function(x){if(x instanceof Logic.Bits){_.each(x.bits,function(b,i){pushToNth(binaryWeighted,i,b);});}else{pushToNth(binaryWeighted,0,x);}});return new Logic.Bits(binaryWeightedSum(binaryWeighted));};Logic.Parse=function(formulas){var res=[];if(!(formulas instanceof Array))formulas=[formulas];formulas.forEach(function(formula){var ast=parse(formula);if(ast&&ast.type=='BinaryExpression'){switch(ast.operator){case'^':res.push(Logic.atMostOne(ast.left.name,ast.right.name))
break;case'|':res.push(Logic.or(ast.left.name,ast.right.name))
break;case'&':res.push(Logic.and(ast.left.name,ast.right.name))
break;}}});if(res.length==1)return res[0];else return res;}
Logic.Solver.solve=function(solver,_assumpVar){if(_assumpVar!==undefined){if(!(_assumpVar>=1)){throw new Error("_assumpVar must be a variable number");}}
if(solver._unsat){return null;}
while(solver._numClausesAddedToMiniSat<solver.clauses.length){var i=solver._numClausesAddedToMiniSat;var terms=solver.clauses[i].terms;if(assert)assert(terms,isArrayWhere(Logic.isNumTerm));var stillSat=Logic._minisatSolvers[solver.id].addClause(terms);solver._numClausesAddedToMiniSat++;if(!stillSat){solver._unsat=true;return null;}}
if(assert)assert(solver._num2name.length-1,Logic.isWholeNumber);Logic._minisatSolvers[solver.id].ensureVar(solver._num2name.length-1);var stillSat=(_assumpVar?Logic._minisatSolvers[solver.id].solveAssuming(_assumpVar):Logic._minisatSolvers[solver.id].solve());if(!stillSat){if(!_assumpVar){solver._unsat=true;}
return null;}
return new Logic.Solution(solver,Logic._minisatSolvers[solver.id].getSolution());};Logic.Solver.solveAssuming=function(solver,formula){if(assert)assert(formula,isFormulaOrTerm);var assump=new Logic.Assumption(formula);var assumpVar=Logic.Solver._formulaToTerm(solver,assump);if(!(typeof assumpVar==='number'&&assumpVar>0)){throw new Error("Assertion failure: not a positive numeric term");}
Logic.Solver._useFormulaTerm(solver,assumpVar);var result=Logic.Solver.solve(solver,assumpVar);Logic._minisatSolvers[solver.id].retireVar(assumpVar);return result;};Logic.Assumption=function(formula){if(assert)assert(formula,isFormulaOrTerm);this.formula=formula;};Logic._defineFormula(Logic.Assumption,'assump',{generateClauses:function(isTrue,t){if(isTrue){return t.clause(this.formula);}else{return t.clause(Logic.not(this.formula));}}});Logic.Solution=function(_solver,_assignment){var self=this;self._solver=_solver;self._assignment=_assignment;self._ungeneratedFormulas=_.clone(_solver._ungeneratedFormulas);self._formulaValueCache={};self._termifier=new Logic.Termifier(self._solver);self._termifier.term=function(formula){return self.evaluate(formula)?Logic.NUM_TRUE:Logic.NUM_FALSE;};self._ignoreUnknownVariables=false;};Logic.Solution.prototype.ignoreUnknownVariables=function(){this._ignoreUnknownVariables=true;};Logic.Solution.prototype.getMap=function(){var solver=this._solver;var assignment=this._assignment;var result={};for(var i=1;i<assignment.length;i++){var name=Logic.Solver.getVarName(solver,i);if(name&&name.charAt(0)!=='$'){result[name]=assignment[i];}}
return result;};Logic.Solution.prototype.getTrueVars=function(){var solver=this._solver;var assignment=this._assignment;var result=[];for(var i=1;i<assignment.length;i++){if(assignment[i]){var name=Logic.Solver.getVarName(solver,i);if(name&&name.charAt(0)!=='$'){result.push(name);}}}
result.sort();return result;};Logic.Solution.prototype.getFormula=function(){var solver=this._solver;var assignment=this._assignment;var terms=[];for(var i=1;i<assignment.length;i++){var name=Logic.Solver.getVarName(solver,i);if(name&&name.charAt(0)!=='$'){terms.push(assignment[i]?i:-i);}}
return Logic.and(terms);};Logic.Solution.prototype.evaluate=function(formulaOrBits){var self=this;if(assert)assert(formulaOrBits,isFormulaOrTermOrBits);if(formulaOrBits instanceof Logic.Bits){var ret=0;_.each(formulaOrBits.bits,function(f,i){if(self.evaluate(f)){ret+=1<<i;}});return ret;}
var solver=self._solver;var ignoreUnknownVariables=self._ignoreUnknownVariables;var assignment=self._assignment;var formula=formulaOrBits;if(formula instanceof Logic.NotFormula){return!self.evaluate(formula.operand);}else if(formula instanceof Logic.Formula){var cachedResult=self._formulaValueCache[formula.guid()];if(typeof cachedResult==='boolean'){return cachedResult;}else{var value;var info=Logic.Solver._getFormulaInfo(solver,formula,true);if(info&&info.varNum&&info.varNum<assignment.length&&!_.has(self._ungeneratedFormulas,info.varNum)){value=assignment[info.varNum];}else{var clauses=Logic.Solver._generateFormula(solver,true,formula,self._termifier);var value=_.all(clauses,function(cls){return _.any(cls.terms,function(t){return self.evaluate(t);});});}
self._formulaValueCache[formula.guid()]=value;return value;}}else{var numTerm=Logic.Solver.toNumTerm(solver,formula,true);if(!numTerm){if(ignoreUnknownVariables){return false;}else{var vname=String(formula).replace(/^-*/,'');throw new Error("No such variable: "+vname);}}
var v=numTerm;var isNot=false;if(numTerm<0){v=-v;isNot=true;}
if(v<1||v>=assignment.length){var vname=v;if(v>=1&&v<solver._num2name.length){vname=solver._num2name[v];}
if(ignoreUnknownVariables){return false;}else{throw new Error("Variable not part of solution: "+vname);}}
var ret=assignment[v];if(isNot){ret=!ret;}
return ret;}};Logic.Solution.prototype.getWeightedSum=function(formulas,weights){checkWeightedSumArgs(formulas,weights);var total=0;if(typeof weights==='number'){for(var i=0;i<formulas.length;i++){total+=weights*(this.evaluate(formulas[i])?1:0);}}else{for(var i=0;i<formulas.length;i++){total+=weights[i]*(this.evaluate(formulas[i])?1:0);}}
return total;};var getNonZeroWeightedTerms=function(costTerms,costWeights){if(typeof costWeights==='number'){return costWeights?costTerms:[];}else{var terms=[];for(var i=0;i<costTerms.length;i++){if(costWeights[i]){terms.push(costTerms[i]);}}
return terms;}};var minMaxWS=function(solver,solution,costTerms,costWeights,options,isMin){var curSolution=solution;var curCost=curSolution.getWeightedSum(costTerms,costWeights);var optFormula=options&&options.formula;var weightedSum=(optFormula||Logic.weightedSum(costTerms,costWeights));var progress=options&&options.progress;var strategy=options&&options.strategy;var nonZeroTerms=null;if(isMin&&curCost>0){if(progress){progress('trying',0);}
var zeroSolution=null;nonZeroTerms=getNonZeroWeightedTerms(costTerms,costWeights);var zeroSolution=Logic.Solver.solveAssuming(solver,Logic.not(Logic.or(nonZeroTerms)));if(zeroSolution){curSolution=zeroSolution;curCost=0;}}
if(isMin&&strategy==='bottom-up'){for(var trialCost=1;trialCost<curCost;trialCost++){if(progress){progress('trying',trialCost);}
var costIsTrialCost=Logic.equalBits(weightedSum,Logic.constantBits(trialCost));var newSolution=Logic.Solver.solveAssuming(solver,costIsTrialCost);if(newSolution){curSolution=newSolution;curCost=trialCost;break;}}}else if(strategy&&strategy!=='default'){throw new Error("Bad strategy: "+strategy);}else{strategy='default';}
if(strategy==='default'){while(isMin?curCost>0:true){if(progress){progress('improving',curCost);}
var improvement=(isMin?Logic.lessThan:Logic.greaterThan)(weightedSum,Logic.constantBits(curCost));var newSolution=Logic.Solver.solveAssuming(solver,improvement);if(!newSolution){break;}
Logic.Solver.require(solver,improvement);curSolution=newSolution;curCost=curSolution.getWeightedSum(costTerms,costWeights);}}
if(isMin&&curCost===0){if(!nonZeroTerms){nonZeroTerms=getNonZeroWeightedTerms(costTerms,costWeights);}
Logic.Solver.forbid(solver,nonZeroTerms);}else{Logic.Solver.require(solver,Logic.equalBits(weightedSum,Logic.constantBits(curCost)));}
if(progress){progress('finished',curCost);}
return curSolution;};Logic.Solver.minimizeWeightedSum=function(solver,solution,costTerms,costWeights,options){return minMaxWS(solver,solution,costTerms,costWeights,options,true);};Logic.Solver.maximizeWeightedSum=function(solver,solution,costTerms,costWeights,options){return minMaxWS(solver,solution,costTerms,costWeights,options,false);};module.exports=Logic;};BundleModuleCode['logic/minisat_wrapper.js']=function(module,exports){var C_MINISAT=Require("logic/minisat.js");var _=Require("ext/underscore");var MiniSat;MiniSat=function(){var C=this._C=C_MINISAT();this._native={getStackPointer:function(){return C.Runtime.stackSave();},setStackPointer:function(ptr){C.Runtime.stackRestore(ptr);},allocateBytes:function(len){return C.allocate(len,'i8',C.ALLOC_STACK);},pushString:function(str){return this.allocateBytes(C.intArrayFromString(str));},savingStack:function(func){var SP=this.getStackPointer();try{return func(this,C);}finally{this.setStackPointer(SP);}}};C._createTheSolver();this._clauses=[];};MiniSat.prototype.ensureVar=function(v){this._C._ensureVar(v);};MiniSat.prototype.addClause=function(terms){this._clauses.push(terms);return this._native.savingStack(function(native,C){var termsPtr=C.allocate((terms.length+1)*4,'i32',C.ALLOC_STACK);_.each(terms,function(t,i){C.setValue(termsPtr+i*4,t,'i32');});C.setValue(termsPtr+terms.length*4,0,'i32');return C._addClause(termsPtr)?true:false;});};MiniSat.prototype.solve=function(){return this._C._solve()?true:false;};MiniSat.prototype.solveAssuming=function(v){return this._C._solveAssuming(v)?true:false;};MiniSat.prototype.getSolution=function(){var solution=[null];var C=this._C;var numVars=C._getNumVars();var solPtr=C._getSolution();for(var i=0;i<numVars;i++){solution[i+1]=(C.getValue(solPtr+i,'i8')===0);}
return solution;};MiniSat.prototype.retireVar=function(v){this._C._retireVar(v);};MiniSat.prototype.getConflictClause=function(){var C=this._C;var numTerms=C._getConflictClauseSize();var clausePtr=C._getConflictClause();var terms=[];for(var i=0;i<numTerms;i++){var t=C.getValue(clausePtr+i*4,'i32');var v=(t>>>1);var s=(t&1)?-1:1;terms[i]=v*s;}
return terms;};module.exports=MiniSat;};BundleModuleCode['logic/minisat.js']=function(module,exports){var C_MINISAT;C_MINISAT=(function(){var module={};var require=(function(){});var process={argv:["node","minisat"],on:(function(){}),stdout:{write:(function(str){console.log("MINISAT-out:",str.replace(/\n$/,""))})},stderr:{write:(function(str){console.log("MINISAT-err:",str.replace(/\n$/,""))})}};var window=0;var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function";var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);if(!ret&&filename!=nodePath["resolve"](filename)){filename=path.join(__dirname,"..","src",filename);ret=nodeFS["readFileSync"](filename)}if(ret&&!binary)ret=ret.toString();return ret};Module["readBinary"]=function readBinary(filename){return Module["read"](filename,true)};Module["load"]=function load(f){globalEval(read(f))};if(process["argv"].length>1){Module["thisProgram"]=process["argv"][1].replace(/\\/g,"/")}else{Module["thisProgram"]="unknown-program"}Module["arguments"]=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("uncaughtException",(function(ex){if(!(ex instanceof ExitStatus)){throw ex}}))}else if(ENVIRONMENT_IS_SHELL){if(!Module["print"])Module["print"]=print;if(typeof printErr!="undefined")Module["printErr"]=printErr;if(typeof read!="undefined"){Module["read"]=read}else{Module["read"]=function read(){throw"no read() available (jsc?)"}}Module["readBinary"]=function readBinary(f){if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}var data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){Module["arguments"]=scriptArgs}else if(typeof arguments!="undefined"){Module["arguments"]=arguments}this["Module"]=Module}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){Module["read"]=function read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(typeof arguments!="undefined"){Module["arguments"]=arguments}if(typeof console!=="undefined"){if(!Module["print"])Module["print"]=function print(x){console.log(x)};if(!Module["printErr"])Module["printErr"]=function printErr(x){console.log(x)}}else{var TRY_USE_DUMP=false;if(!Module["print"])Module["print"]=TRY_USE_DUMP&&typeof dump!=="undefined"?(function(x){dump(x)}):(function(x){})}if(ENVIRONMENT_IS_WEB){window["Module"]=Module}else{Module["load"]=importScripts}}else{throw"Unknown runtime environment. Where are we?"}function globalEval(x){eval.call(null,x)}if(!Module["load"]&&Module["read"]){Module["load"]=function load(f){globalEval(Module["read"](f))}}if(!Module["print"]){Module["print"]=(function(){})}if(!Module["printErr"]){Module["printErr"]=Module["print"]}if(!Module["arguments"]){Module["arguments"]=[]}if(!Module["thisProgram"]){Module["thisProgram"]="./this.program"}Module.print=Module["print"];Module.printErr=Module["printErr"];Module["preRun"]=[];Module["postRun"]=[];for(var key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}var Runtime={setTempRet0:(function(value){tempRet0=value}),getTempRet0:(function(){return tempRet0}),stackSave:(function(){return STACKTOP}),stackRestore:(function(stackTop){STACKTOP=stackTop}),getNativeTypeSize:(function(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":ret
function Xd(b,e,f){b=b|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0.0,r=0,s=0,t=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,G=0.0,H=0,I=0.0,J=0.0,K=0.0,L=0.0;g=i;i=i+512|0;k=g;if(!e){e=24;j=-149}else if((e|0)==2){e=53;j=-1074}else if((e|0)==1){e=53;j=-1074}else{J=0.0;i=g;return+J}n=b+4|0;o=b+100|0;do{h=c[n>>2]|0;if(h>>>0<(c[o>>2]|0)>>>0){c[n>>2]=h+1;w=d[h>>0]|0}else w=Zd(b)|0}while((Vd(w)|0)!=0);do if((w|0)==43|(w|0)==45){h=1-(((w|0)==45&1)<<1)|0;m=c[n>>2]|0;if(m>>>0<(c[o>>2]|0)>>>0){c[n>>2]=m+1;w=d[m>>0]|0;break}else{w=Zd(b)|0;break}}else h=1;while(0);r=0;do{if((w|32|0)!=(a[5600+r>>0]|0))break;do if(r>>>0<7){m=c[n>>2]|0;if(m>>>0<(c[o>>2]|0)>>>0){c[n>>2]=m+1;w=d[m>>0]|0;break}else{w=Zd(b)|0;break}}while(0);r=r+1|0}while(r>>>0<8);do if((r|0)==3)p=23;else if((r|0)!=8){m=(f|0)!=0;if(r>>>0>3&m)if((r|0)==8)break;else{p=23;break}a:do if(!r){r=0;do{if((w|32|0)!=(a[5616+r>>0]|0))break a;do if(r>>>0<2){s=c[n>>2]|0;if(s>>>0<(c[o>>2]|0)>>>0){c[n>>2]=s+1;w=d[s>>0]|0;break}else{w=Zd(b)|0;break}}while(0);r=r+1|0}while(r>>>0<3)}while(0);if(!r){do if((w|0)==48){m=c[n>>2]|0;if(m>>>0<(c[o>>2]|0)>>>0){c[n>>2]=m+1;m=d[m>>0]|0}else m=Zd(b)|0;if((m|32|0)!=120){if(!(c[o>>2]|0)){w=48;break}c[n>>2]=(c[n>>2]|0)+ -1;w=48;break}k=c[n>>2]|0;if(k>>>0<(c[o>>2]|0)>>>0){c[n>>2]=k+1;z=d[k>>0]|0;x=0}else{z=Zd(b)|0;x=0}while(1){if((z|0)==46){p=70;break}else if((z|0)!=48){k=0;m=0;s=0;r=0;w=0;y=0;G=1.0;t=0;q=0.0;break}k=c[n>>2]|0;if(k>>>0<(c[o>>2]|0)>>>0){c[n>>2]=k+1;z=d[k>>0]|0;x=1;continue}else{z=Zd(b)|0;x=1;continue}}if((p|0)==70){k=c[n>>2]|0;if(k>>>0<(c[o>>2]|0)>>>0){c[n>>2]=k+1;z=d[k>>0]|0}else z=Zd(b)|0;if((z|0)==48){s=0;r=0;do{k=c[n>>2]|0;if(k>>>0<(c[o>>2]|0)>>>0){c[n>>2]=k+1;z=d[k>>0]|0}else z=Zd(b)|0;s=ne(s|0,r|0,-1,-1)|0;r=F}while((z|0)==48);k=0;m=0;x=1;w=1;y=0;G=1.0;t=0;q=0.0}else{k=0;m=0;s=0;r=0;w=1;y=0;G=1.0;t=0;q=0.0}}b:while(1){B=z+ -48|0;do if(B>>>0>=10){A=z|32;C=(z|0)==46;if(!((A+ -97|0)>>>0<6|C))break b;if(C)if(!w){s=m;r=k;w=1;break}else{z=46;break b}else{B=(z|0)>57?A+ -87|0:B;p=83;break}}else p=83;while(0);if((p|0)==83){p=0;do if(!((k|0)<0|(k|0)==0&m>>>0<8)){if((k|0)<0|(k|0)==0&m>>>0<14){J=G*.0625;I=J;q=q+J*+(B|0);break}if((B|0)==0|(y|0)!=0)I=G;else{y=1;I=G;q=q+G*.5}}else{I=G;t=B+(t<<4)|0}while(0);m=ne(m|0,k|0,1,0)|0;k=F;x=1;G=I}z=c[n>>2]|0;if(z>>>0<(c[o>>2]|0)>>>0){c[n>>2]=z+1;z=d[z>>0]|0;continue}else{z=Zd(b)|0;continue}}if(!x){e=(c[o>>2]|0)==0;if(!e)c[n>>2]=(c[n>>2]|0)+ -1;if(f){if(!e?(l=c[n>>2]|0,c[n>>2]=l+ -1,(w|0)!=0):0)c[n>>2]=l+ -2}else Yd(b,0);J=+(h|0)*0.0;i=g;return+J}p=(w|0)==0;l=p?m:s;p=p?k:r;if((k|0)<0|(k|0)==0&m>>>0<8)do{t=t<<4;m=ne(m|0,k|0,1,0)|0;k=F}while((k|0)<0|(k|0)==0&m>>>0<8);do if((z|32|0)==112){m=he(b,f)|0;k=F;if((m|0)==0&(k|0)==-2147483648)if(!f){Yd(b,0);J=0.0;i=g;return+J}else{if(!(c[o>>2]|0)){m=0;k=0;break}c[n>>2]=(c[n>>2]|0)+ -1;m=0;k=0;break}}else if(!(c[o>>2]|0)){m=0;k=0}else{c[n>>2]=(c[n>>2]|0)+ -1;m=0;k=0}while(0);l=le(l|0,p|0,2)|0;l=ne(l|0,F|0,-32,-1)|0;k=ne(l|0,F|0,m|0,k|0)|0;l=F;if(!t){J=+(h|0)*0.0;i=g;return+J}if((l|0)>0|(l|0)==0&k>>>0>(0-j|0)>>>0){c[(Oa()|0)>>2]=34;J=+(h|0)*1.7976931348623157e+308*1.7976931348623157e+308;i=g;return+J}H=j+ -106|0;E=((H|0)<0)<<31>>31;if((l|0)<(E|0)|(l|0)==(E|0)&k>>>0<H>>>0){c[(Oa()|0)>>2]=34;J=+(h|0)*2.2250738585072014e-308*2.2250738585072014e-308;i=g;return+J}if((t|0)>-1)do{t=t<<1;if(!(q>=.5))G=q;else{G=q+-1.0;t=t|1}q=q+G;k=ne(k|0,l|0,-1,-1)|0;l=F}while((t|0)>-1);j=je(32,0,j|0,((j|0)<0)<<31>>31|0)|0;j=ne(k|0,l|0,j|0,F|0)|0;H=F;if(0>(H|0)|0==(H|0)&e>>>0>j>>>0)if((j|0)<0){e=0;p=126}else{e=j;p=124}else p=124;if((p|0)==124)if((e|0)<53)p=126;else{j=e;G=+(h|0);I=0.0}if((p|0)==126){I=+(h|0);j=e;G=I;I=+Va(+(+_d(1.0,84-e|0)),+I)}H=(j|0)<32&q!=0.0&(t&1|0)==0;q=G*(H?0.0:q)+(I+G*+(((H&1)+t|0)>>>0))-I;if(!(q!=0.0))c[(Oa()|0)>>2]=34;J=+$d(q,k);i=g;return+J}while(0);m=j+e|0;l=0-m|0;B=0;while(1){if((w|0)==46){p=137;break}else if((w|0)!=48){D=0;C=0;A=0;break}r=c[n>>2]|0;if(r>>>0<(c[o>>2]|0)>>>0){c[n>>2]=r+1;w=d[r>>0]|0;B=1;continue}else{w=Zd(b)|0;B=1;continue}}if((p|0)==137){p=c[n>>2]|0;if(p>>>0<(c[o>>2]|0)>>>0){c[n>>2]=p+1;w=d[p>>0]|0}else w=Zd(b)|0;if((w|0)==48){D=0;C=0;do{D=ne(
var eb=[Je,Dd];var fb=[Ke,Kd,Jd,Ke];var gb=[Le,wb,yb,Ab,Db,Ib,Hb,bc,dc,zc,yc,Oc,rd,qd,yd,Bd,zd,Ad,Cd,zb,Rd,Le,Le,Le,Le,Le,Le,Le,Le,Le,Le,Le];var hb=[Me,Cb,Fb,fc];var ib=[Ne,sd];var jb=[Oe,Pe,Pd,Qd];var kb=[Qe,Md,Ld,Qe];var lb=[Re,Bb,Eb,ec];var mb=[Se,Fd,Gd,Se];return{_yo:$c,_strlen:me,_retireVar:id,_bitshift64Lshr:oe,_unyo:ad,_solve:ed,_bitshift64Shl:le,_getSolution:fd,___cxa_is_pointer_type:Od,_memset:ke,_getNumVars:gd,_memcpy:pe,_getConflictClauseSize:jd,_addClause:dd,_i64Subtract:je,_createTheSolver:bd,_realloc:Ud,_i64Add:ne,_solveAssuming:hd,___cxa_can_catch:Nd,_ensureVar:cd,_getConflictClause:kd,_free:Td,_malloc:Sd,__GLOBAL__I_a:cc,__GLOBAL__I_a127:Pc,runPostSets:ie,stackAlloc:nb,stackSave:ob,stackRestore:pb,setThrew:qb,setTempRet0:tb,getTempRet0:ub,dynCall_iiii:Ae,dynCall_viiiii:Be,dynCall_vi:Ce,dynCall_vii:De,dynCall_ii:Ee,dynCall_v:Fe,dynCall_viiiiii:Ge,dynCall_iii:He,dynCall_viiii:Ie}})
(Module.asmGlobalArg,Module.asmLibraryArg,buffer);var _yo=Module["_yo"]=asm["_yo"];var _strlen=Module["_strlen"]=asm["_strlen"];var _retireVar=Module["_retireVar"]=asm["_retireVar"];var _bitshift64Lshr=Module["_bitshift64Lshr"]=asm["_bitshift64Lshr"];var _unyo=Module["_unyo"]=asm["_unyo"];var _solve=Module["_solve"]=asm["_solve"];var _bitshift64Shl=Module["_bitshift64Shl"]=asm["_bitshift64Shl"];var _getSolution=Module["_getSolution"]=asm["_getSolution"];var ___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=asm["___cxa_is_pointer_type"];var _memset=Module["_memset"]=asm["_memset"];var _getNumVars=Module["_getNumVars"]=asm["_getNumVars"];var _memcpy=Module["_memcpy"]=asm["_memcpy"];var _getConflictClauseSize=Module["_getConflictClauseSize"]=asm["_getConflictClauseSize"];var _addClause=Module["_addClause"]=asm["_addClause"];var _i64Subtract=Module["_i64Subtract"]=asm["_i64Subtract"];var _createTheSolver=Module["_createTheSolver"]=asm["_createTheSolver"];var _realloc=Module["_realloc"]=asm["_realloc"];var _i64Add=Module["_i64Add"]=asm["_i64Add"];var _solveAssuming=Module["_solveAssuming"]=asm["_solveAssuming"];var ___cxa_can_catch=Module["___cxa_can_catch"]=asm["___cxa_can_catch"];var _ensureVar=Module["_ensureVar"]=asm["_ensureVar"];var _getConflictClause=Module["_getConflictClause"]=asm["_getConflictClause"];var _free=Module["_free"]=asm["_free"];var _malloc=Module["_malloc"]=asm["_malloc"];var __GLOBAL__I_a=Module["__GLOBAL__I_a"]=asm["__GLOBAL__I_a"];var __GLOBAL__I_a127=Module["__GLOBAL__I_a127"]=asm["__GLOBAL__I_a127"];var runPostSets=Module["runPostSets"]=asm["runPostSets"];var dynCall_iiii=Module["dynCall_iiii"]=asm["dynCall_iiii"];var dynCall_viiiii=Module["dynCall_viiiii"]=asm["dynCall_viiiii"];var dynCall_vi=Module["dynCall_vi"]=asm["dynCall_vi"];var dynCall_vii=Module["dynCall_vii"]=asm["dynCall_vii"];var dynCall_ii=Module["dynCall_ii"]=asm["dynCall_ii"];var dynCall_v=Module["dynCall_v"]=asm["dynCall_v"];var dynCall_viiiiii=Module["dynCall_viiiiii"]=asm["dynCall_viiiiii"];var dynCall_iii=Module["dynCall_iii"]=asm["dynCall_iii"];var dynCall_viiii=Module["dynCall_viiii"]=asm["dynCall_viiii"];Runtime.stackAlloc=asm["stackAlloc"];Runtime.stackSave=asm["stackSave"];Runtime.stackRestore=asm["stackRestore"];Runtime.setTempRet0=asm["setTempRet0"];Runtime.getTempRet0=asm["getTempRet0"];var i64Math=(function(){var goog={math:{}};goog.math.Long=(function(low,high){this.low_=low|0;this.high_=high|0});goog.math.Long.IntCache_={};goog.math.Long.fromInt=(function(value){if(-128<=value&&value<128){var cachedObj=goog.math.Long.IntCache_[value];if(cachedObj){return cachedObj}}var obj=new goog.math.Long(value|0,value<0?-1:0);if(-128<=value&&value<128){goog.math.Long.IntCache_[value]=obj}return obj});goog.math.Long.fromNumber=(function(value){if(isNaN(value)||!isFinite(value)){return goog.math.Long.ZERO}else if(value<=-goog.math.Long.TWO_PWR_63_DBL_){return goog.math.Long.MIN_VALUE}else if(value+1>=goog.math.Long.TWO_PWR_63_DBL_){return goog.math.Long.MAX_VALUE}else if(value<0){return goog.math.Long.fromNumber(-value).negate()}else{return new goog.math.Long(value%goog.math.Long.TWO_PWR_32_DBL_|0,value/goog.math.Long.TWO_PWR_32_DBL_|0)}});goog.math.Long.fromBits=(function(lowBits,highBits){return new goog.math.Long(lowBits,highBits)});goog.math.Long.fromString=(function(str,opt_radix){if(str.length==0){throw Error("number format error: empty string")}var radix=opt_radix||10;if(radix<2||36<radix){throw Error("radix out of range: "+radix)}if(str.charAt(0)=="-"){return goog.math.Long.fromString(str.substring(1),radix).negate()}else if(str.indexOf("-")>=0){throw Error('number format error: interior "-" character: '+str)}var radixToPower=goog.math.Long.fromNumber(Math.pow(radix,8));var result=goog.math.Long.ZERO;for(var i=0;i<str.length;i+=8){var size=Math.min(8,str.length-i);var value=parseInt(str.substring(i,i+size),radix);if(size<8){var power=goog.math.Long.fromNumber(Math.pow(radix,size));result=result.multiply(power).add(goog.math.Long.fromNumber(value))}else{result=result.multiply(radixToPower);result=result.add(goog.math.Lon
exports._=_;}else{root._=_;}
_.VERSION='1.9.0';var optimizeCb=function(func,context,argCount){if(context===void 0)return func;switch(argCount==null?3:argCount){case 1:return function(value){return func.call(context,value);};case 3:return function(value,index,collection){return func.call(context,value,index,collection);};case 4:return function(accumulator,value,index,collection){return func.call(context,accumulator,value,index,collection);};}
return function(){return func.apply(context,arguments);};};var builtinIteratee;var cb=function(value,context,argCount){if(_.iteratee!==builtinIteratee)return _.iteratee(value,context);if(value==null)return _.identity;if(_.isFunction(value))return optimizeCb(value,context,argCount);if(_.isObject(value)&&!_.isArray(value))return _.matcher(value);return _.property(value);};_.iteratee=builtinIteratee=function(value,context){return cb(value,context,Infinity);};var restArguments=function(func,startIndex){startIndex=startIndex==null?func.length-1:+startIndex;return function(){var length=Math.max(arguments.length-startIndex,0),rest=Array(length),index=0;for(;index<length;index++){rest[index]=arguments[index+startIndex];}
switch(startIndex){case 0:return func.call(this,rest);case 1:return func.call(this,arguments[0],rest);case 2:return func.call(this,arguments[0],arguments[1],rest);}
var args=Array(startIndex+1);for(index=0;index<startIndex;index++){args[index]=arguments[index];}
args[startIndex]=rest;return func.apply(this,args);};};var baseCreate=function(prototype){if(!_.isObject(prototype))return{};if(nativeCreate)return nativeCreate(prototype);Ctor.prototype=prototype;var result=new Ctor;Ctor.prototype=null;return result;};var shallowProperty=function(key){return function(obj){return obj==null?void 0:obj[key];};};var has=function(obj,path){return obj!=null&&hasOwnProperty.call(obj,path);}
var deepGet=function(obj,path){var length=path.length;for(var i=0;i<length;i++){if(obj==null)return void 0;obj=obj[path[i]];}
return length?obj:void 0;};var MAX_ARRAY_INDEX=Math.pow(2,53)-1;var getLength=shallowProperty('length');var isArrayLike=function(collection){var length=getLength(collection);return typeof length=='number'&&length>=0&&length<=MAX_ARRAY_INDEX;};_.each=_.forEach=function(obj,iteratee,context){iteratee=optimizeCb(iteratee,context);var i,length;if(isArrayLike(obj)){for(i=0,length=obj.length;i<length;i++){iteratee(obj[i],i,obj);}}else{var keys=_.keys(obj);for(i=0,length=keys.length;i<length;i++){iteratee(obj[keys[i]],keys[i],obj);}}
return obj;};_.map=_.collect=function(obj,iteratee,context){iteratee=cb(iteratee,context);var keys=!isArrayLike(obj)&&_.keys(obj),length=(keys||obj).length,results=Array(length);for(var index=0;index<length;index++){var currentKey=keys?keys[index]:index;results[index]=iteratee(obj[currentKey],currentKey,obj);}
return results;};var createReduce=function(dir){var reducer=function(obj,iteratee,memo,initial){var keys=!isArrayLike(obj)&&_.keys(obj),length=(keys||obj).length,index=dir>0?0:length-1;if(!initial){memo=obj[keys?keys[index]:index];index+=dir;}
for(;index>=0&&index<length;index+=dir){var currentKey=keys?keys[index]:index;memo=iteratee(memo,obj[currentKey],currentKey,obj);}
return memo;};return function(obj,iteratee,memo,context){var initial=arguments.length>=3;return reducer(obj,optimizeCb(iteratee,context,4),memo,initial);};};_.reduce=_.foldl=_.inject=createReduce(1);_.reduceRight=_.foldr=createReduce(-1);_.find=_.detect=function(obj,predicate,context){var keyFinder=isArrayLike(obj)?_.findIndex:_.findKey;var key=keyFinder(obj,predicate,context);if(key!==void 0&&key!==-1)return obj[key];};_.filter=_.select=function(obj,predicate,context){var results=[];predicate=cb(predicate,context);_.each(obj,function(value,index,list){if(predicate(value,index,list))results.push(value);});return results;};_.reject=function(obj,predicate,context){return _.filter(obj,_.negate(cb(predicate)),context);};_.every=_.all=function(obj,predicate,context){predicate=cb(predicate,context);var keys=!isArrayLike(obj)&&_.keys(obj),length=(keys||obj).length;for(var index=0;index<length;index++){var currentKey=keys?keys[index]:index;if(!predicate(obj[currentKey],currentKey,obj))return false;}
return true;};_.some=_.any=function(obj,predicate,context){predicate=cb(predicate,context);var keys=!isArrayLike(obj)&&_.keys(obj),length=(keys||obj).length;for(var index=0;index<length;index++){var currentKey=keys?keys[index]:index;if(predicate(obj[currentKey],currentKey,obj))return true;}
return false;};_.contains=_.includes=_.include=function(obj,item,fromIndex,guard){if(!isArrayLike(obj))obj=_.values(obj);if(typeof fromIndex!='number'||guard)fromIndex=0;return _.indexOf(obj,item,fromIndex)>=0;};_.invoke=restArguments(function(obj,path,args){var contextPath,func;if(_.isFunction(path)){func=path;}else if(_.isArray(path)){contextPath=path.slice(0,-1);path=path[path.length-1];}
return _.map(obj,function(context){var method=func;if(!method){if(contextPath&&contextPath.length){context=deepGet(context,contextPath);}
if(context==null)return void 0;method=context[path];}
return method==null?method:method.apply(context,args);});});_.pluck=function(obj,key){return _.map(obj,_.property(key));};_.where=function(obj,attrs){return _.filter(obj,_.matcher(attrs));};_.findWhere=function(obj,attrs){return _.find(obj,_.matcher(attrs));};_.max=function(obj,iteratee,context){var result=-Infinity,lastComputed=-Infinity,value,computed;if(iteratee==null||typeof iteratee=='number'&&typeof obj[0]!='object'&&obj!=null){obj=isArrayLike(obj)?obj:_.values(obj);for(var i=0,length=obj.length;i<length;i++){value=obj[i];if(value!=null&&value>result){result=value;}}}else{iteratee=cb(iteratee,context);_.each(obj,function(v,index,list){computed=iteratee(v,index,list);if(computed>lastComputed||computed===-Infinity&&result===-Infinity){result=v;lastComputed=computed;}});}
return result;};_.min=function(obj,iteratee,context){var result=Infinity,lastComputed=Infinity,value,computed;if(iteratee==null||typeof iteratee=='number'&&typeof obj[0]!='object'&&obj!=null){obj=isArrayLike(obj)?obj:_.values(obj);for(var i=0,length=obj.length;i<length;i++){value=obj[i];if(value!=null&&value<result){result=value;}}}else{iteratee=cb(iteratee,context);_.each(obj,function(v,index,list){computed=iteratee(v,index,list);if(computed<lastComputed||computed===Infinity&&result===Infinity){result=v;lastComputed=computed;}});}
return result;};_.shuffle=function(obj){return _.sample(obj,Infinity);};_.sample=function(obj,n,guard){if(n==null||guard){if(!isArrayLike(obj))obj=_.values(obj);return obj[_.random(obj.length-1)];}
var sample=isArrayLike(obj)?_.clone(obj):_.values(obj);var length=getLength(sample);n=Math.max(Math.min(n,length),0);var last=length-1;for(var index=0;index<n;index++){var rand=_.random(index,last);var temp=sample[index];sample[index]=sample[rand];sample[rand]=temp;}
return sample.slice(0,n);};_.sortBy=function(obj,iteratee,context){var index=0;iteratee=cb(iteratee,context);return _.pluck(_.map(obj,function(value,key,list){return{value:value,index:index++,criteria:iteratee(value,key,list)};}).sort(function(left,right){var a=left.criteria;var b=right.criteria;if(a!==b){if(a>b||a===void 0)return 1;if(a<b||b===void 0)return-1;}
return left.index-right.index;}),'value');};var group=function(behavior,partition){return function(obj,iteratee,context){var result=partition?[[],[]]:{};iteratee=cb(iteratee,context);_.each(obj,function(value,index){var key=iteratee(value,index,obj);behavior(result,value,key);});return result;};};_.groupBy=group(function(result,value,key){if(has(result,key))result[key].push(value);else result[key]=[value];});_.indexBy=group(function(result,value,key){result[key]=value;});_.countBy=group(function(result,value,key){if(has(result,key))result[key]++;else result[key]=1;});var reStrSymbol=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(_.isString(obj)){return obj.match(reStrSymbol);}
if(isArrayLike(obj))return _.map(obj,_.identity);return _.values(obj);};_.size=function(obj){if(obj==null)return 0;return isArrayLike(obj)?obj.length:_.keys(obj).length;};_.partition=group(function(result,value,pass){result[pass?0:1].push(value);},true);_.first=_.head=_.take=function(array,n,guard){if(array==null||array.length<1)return void 0;if(n==null||guard)return array[0];return _.initial(array,array.length-n);};_.initial=function(array,n,guard){return slice.call(array,0,Math.max(0,array.length-(n==null||guard?1:n)));};_.last=function(array,n,guard){if(array==null||array.length<1)return void 0;if(n==null||guard)return array[array.length-1];return _.rest(array,Math.max(0,array.length-n));};_.rest=_.tail=_.drop=function(array,n,guard){return slice.call(array,n==null||guard?1:n);};_.compact=function(array){return _.filter(array,Boolean);};var flatten=function(input,shallow,strict,output){output=output||[];var idx=output.length;for(var i=0,length=getLength(input);i<length;i++){var value=input[i];if(isArrayLike(value)&&(_.isArray(value)||_.isArguments(value))){if(shallow){var j=0,len=value.length;while(j<len)output[idx++]=value[j++];}else{flatten(value,shallow,strict,output);idx=output.length;}}else if(!strict){output[idx++]=value;}}
return output;};_.flatten=function(array,shallow){return flatten(array,shallow,false);};_.without=restArguments(function(array,otherArrays){return _.difference(array,otherArrays);});_.uniq=_.unique=function(array,isSorted,iteratee,context){if(!_.isBoolean(isSorted)){context=iteratee;iteratee=isSorted;isSorted=false;}
if(iteratee!=null)iteratee=cb(iteratee,context);var result=[];var seen=[];for(var i=0,length=getLength(array);i<length;i++){var value=array[i],computed=iteratee?iteratee(value,i,array):value;if(isSorted&&!iteratee){if(!i||seen!==computed)result.push(value);seen=computed;}else if(iteratee){if(!_.contains(seen,computed)){seen.push(computed);result.push(value);}}else if(!_.contains(result,value)){result.push(value);}}
return result;};_.union=restArguments(function(arrays){return _.uniq(flatten(arrays,true,true));});_.intersection=function(array){var result=[];var argsLength=arguments.length;for(var i=0,length=getLength(array);i<length;i++){var item=array[i];if(_.contains(result,item))continue;var j;for(j=1;j<argsLength;j++){if(!_.contains(arguments[j],item))break;}
if(j===argsLength)result.push(item);}
return result;};_.difference=restArguments(function(array,rest){rest=flatten(rest,true,true);return _.filter(array,function(value){return!_.contains(rest,value);});});_.unzip=function(array){var length=array&&_.max(array,getLength).length||0;var result=Array(length);for(var index=0;index<length;index++){result[index]=_.pluck(array,index);}
return result;};_.zip=restArguments(_.unzip);_.object=function(list,values){var result={};for(var i=0,length=getLength(list);i<length;i++){if(values){result[list[i]]=values[i];}else{result[list[i][0]]=list[i][1];}}
return result;};var createPredicateIndexFinder=function(dir){return function(array,predicate,context){predicate=cb(predicate,context);var length=getLength(array);var index=dir>0?0:length-1;for(;index>=0&&index<length;index+=dir){if(predicate(array[index],index,array))return index;}
return-1;};};_.findIndex=createPredicateIndexFinder(1);_.findLastIndex=createPredicateIndexFinder(-1);_.sortedIndex=function(array,obj,iteratee,context){iteratee=cb(iteratee,context,1);var value=iteratee(obj);var low=0,high=getLength(array);while(low<high){var mid=Math.floor((low+high)/2);if(iteratee(array[mid])<value)low=mid+1;else high=mid;}
return low;};var createIndexFinder=function(dir,predicateFind,sortedIndex){return function(array,item,idx){var i=0,length=getLength(array);if(typeof idx=='number'){if(dir>0){i=idx>=0?idx:Math.max(idx+length,i);}else{length=idx>=0?Math.min(idx+1,length):idx+length+1;}}else if(sortedIndex&&idx&&length){idx=sortedIndex(array,item);return array[idx]===item?idx:-1;}
if(item!==item){idx=predicateFind(slice.call(array,i,length),_.isNaN);return idx>=0?idx+i:-1;}
for(idx=dir>0?i:length-1;idx>=0&&idx<length;idx+=dir){if(array[idx]===item)return idx;}
return-1;};};_.indexOf=createIndexFinder(1,_.findIndex,_.sortedIndex);_.lastIndexOf=createIndexFinder(-1,_.findLastIndex);_.range=function(start,stop,step){if(stop==null){stop=start||0;start=0;}
if(!step){step=stop<start?-1:1;}
var length=Math.max(Math.ceil((stop-start)/step),0);var range=Array(length);for(var idx=0;idx<length;idx++,start+=step){range[idx]=start;}
return range;};_.chunk=function(array,count){if(count==null||count<1)return[];var result=[];var i=0,length=array.length;while(i<length){result.push(slice.call(array,i,i+=count));}
return result;};var executeBound=function(sourceFunc,boundFunc,context,callingContext,args){if(!(callingContext instanceof boundFunc))return sourceFunc.apply(context,args);var self=baseCreate(sourceFunc.prototype);var result=sourceFunc.apply(self,args);if(_.isObject(result))return result;return self;};_.bind=restArguments(function(func,context,args){if(!_.isFunction(func))throw new TypeError('Bind must be called on a function');var bound=restArguments(function(callArgs){return executeBound(func,bound,context,this,args.concat(callArgs));});return bound;});_.partial=restArguments(function(func,boundArgs){var placeholder=_.partial.placeholder;var bound=function(){var position=0,length=boundArgs.length;var args=Array(length);for(var i=0;i<length;i++){args[i]=boundArgs[i]===placeholder?arguments[position++]:boundArgs[i];}
while(position<arguments.length)args.push(arguments[position++]);return executeBound(func,bound,this,this,args);};return bound;});_.partial.placeholder=_;_.bindAll=restArguments(function(obj,keys){keys=flatten(keys,false,false);var index=keys.length;if(index<1)throw new Error('bindAll must be passed function names');while(index--){var key=keys[index];obj[key]=_.bind(obj[key],obj);}});_.memoize=function(func,hasher){var memoize=function(key){var cache=memoize.cache;var address=''+(hasher?hasher.apply(this,arguments):key);if(!has(cache,address))cache[address]=func.apply(this,arguments);return cache[address];};memoize.cache={};return memoize;};_.delay=restArguments(function(func,wait,args){return setTimeout(function(){return func.apply(null,args);},wait);});_.defer=_.partial(_.delay,_,1);_.throttle=function(func,wait,options){var timeout,context,args,result;var previous=0;if(!options)options={};var later=function(){previous=options.leading===false?0:_.now();timeout=null;result=func.apply(context,args);if(!timeout)context=args=null;};var throttled=function(){var now=_.now();if(!previous&&options.leading===false)previous=now;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0||remaining>wait){if(timeout){clearTimeout(timeout);timeout=null;}
previous=now;result=func.apply(context,args);if(!timeout)context=args=null;}else if(!timeout&&options.trailing!==false){timeout=setTimeout(later,remaining);}
return result;};throttled.cancel=function(){clearTimeout(timeout);previous=0;timeout=context=args=null;};return throttled;};_.debounce=function(func,wait,immediate){var timeout,result;var later=function(context,args){timeout=null;if(args)result=func.apply(context,args);};var debounced=restArguments(function(args){if(timeout)clearTimeout(timeout);if(immediate){var callNow=!timeout;timeout=setTimeout(later,wait);if(callNow)result=func.apply(this,args);}else{timeout=_.delay(later,wait,this,args);}
return result;});debounced.cancel=function(){clearTimeout(timeout);timeout=null;};return debounced;};_.wrap=function(func,wrapper){return _.partial(wrapper,func);};_.negate=function(predicate){return function(){return!predicate.apply(this,arguments);};};_.compose=function(){var args=arguments;var start=args.length-1;return function(){var i=start;var result=args[start].apply(this,arguments);while(i--)result=args[i].call(this,result);return result;};};_.after=function(times,func){return function(){if(--times<1){return func.apply(this,arguments);}};};_.before=function(times,func){var memo;return function(){if(--times>0){memo=func.apply(this,arguments);}
if(times<=1)func=null;return memo;};};_.once=_.partial(_.before,2);_.restArguments=restArguments;var hasEnumBug=!{toString:null}.propertyIsEnumerable('toString');var nonEnumerableProps=['valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'];var collectNonEnumProps=function(obj,keys){var nonEnumIdx=nonEnumerableProps.length;var constructor=obj.constructor;var proto=_.isFunction(constructor)&&constructor.prototype||ObjProto;var prop='constructor';if(has(obj,prop)&&!_.contains(keys,prop))keys.push(prop);while(nonEnumIdx--){prop=nonEnumerableProps[nonEnumIdx];if(prop in obj&&obj[prop]!==proto[prop]&&!_.contains(keys,prop)){keys.push(prop);}}};_.keys=function(obj){if(!_.isObject(obj))return[];if(nativeKeys)return nativeKeys(obj);var keys=[];for(var key in obj)if(has(obj,key))keys.push(key);if(hasEnumBug)collectNonEnumProps(obj,keys);return keys;};_.allKeys=function(obj){if(!_.isObject(obj))return[];var keys=[];for(var key in obj)keys.push(key);if(hasEnumBug)collectNonEnumProps(obj,keys);return keys;};_.values=function(obj){var keys=_.keys(obj);var length=keys.length;var values=Array(length);for(var i=0;i<length;i++){values[i]=obj[keys[i]];}
return values;};_.mapObject=function(obj,iteratee,context){iteratee=cb(iteratee,context);var keys=_.keys(obj),length=keys.length,results={};for(var index=0;index<length;index++){var currentKey=keys[index];results[currentKey]=iteratee(obj[currentKey],currentKey,obj);}
return results;};_.pairs=function(obj){var keys=_.keys(obj);var length=keys.length;var pairs=Array(length);for(var i=0;i<length;i++){pairs[i]=[keys[i],obj[keys[i]]];}
return pairs;};_.invert=function(obj){var result={};var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){result[obj[keys[i]]]=keys[i];}
return result;};_.functions=_.methods=function(obj){var names=[];for(var key in obj){if(_.isFunction(obj[key]))names.push(key);}
return names.sort();};var createAssigner=function(keysFunc,defaults){return function(obj){var length=arguments.length;if(defaults)obj=Object(obj);if(length<2||obj==null)return obj;for(var index=1;index<length;index++){var source=arguments[index],keys=keysFunc(source),l=keys.length;for(var i=0;i<l;i++){var key=keys[i];if(!defaults||obj[key]===void 0)obj[key]=source[key];}}
return obj;};};_.extend=createAssigner(_.allKeys);_.extendOwn=_.assign=createAssigner(_.keys);_.findKey=function(obj,predicate,context){predicate=cb(predicate,context);var keys=_.keys(obj),key;for(var i=0,length=keys.length;i<length;i++){key=keys[i];if(predicate(obj[key],key,obj))return key;}};var keyInObj=function(value,key,obj){return key in obj;};_.pick=restArguments(function(obj,keys){var result={},iteratee=keys[0];if(obj==null)return result;if(_.isFunction(iteratee)){if(keys.length>1)iteratee=optimizeCb(iteratee,keys[1]);keys=_.allKeys(obj);}else{iteratee=keyInObj;keys=flatten(keys,false,false);obj=Object(obj);}
for(var i=0,length=keys.length;i<length;i++){var key=keys[i];var value=obj[key];if(iteratee(value,key,obj))result[key]=value;}
return result;});_.omit=restArguments(function(obj,keys){var iteratee=keys[0],context;if(_.isFunction(iteratee)){iteratee=_.negate(iteratee);if(keys.length>1)context=keys[1];}else{keys=_.map(flatten(keys,false,false),String);iteratee=function(value,key){return!_.contains(keys,key);};}
return _.pick(obj,iteratee,context);});_.defaults=createAssigner(_.allKeys,true);_.create=function(prototype,props){var result=baseCreate(prototype);if(props)_.extendOwn(result,props);return result;};_.clone=function(obj){if(!_.isObject(obj))return obj;return _.isArray(obj)?obj.slice():_.extend({},obj);};_.tap=function(obj,interceptor){interceptor(obj);return obj;};_.isMatch=function(object,attrs){var keys=_.keys(attrs),length=keys.length;if(object==null)return!length;var obj=Object(object);for(var i=0;i<length;i++){var key=keys[i];if(attrs[key]!==obj[key]||!(key in obj))return false;}
return true;};var eq,deepEq;eq=function(a,b,aStack,bStack){if(a===b)return a!==0||1/a===1/b;if(a==null||b==null)return false;if(a!==a)return b!==b;var type=typeof a;if(type!=='function'&&type!=='object'&&typeof b!='object')return false;return deepEq(a,b,aStack,bStack);};deepEq=function(a,b,aStack,bStack){if(a instanceof _)a=a._wrapped;if(b instanceof _)b=b._wrapped;var className=toString.call(a);if(className!==toString.call(b))return false;switch(className){case'[object RegExp]':case'[object String]':return''+a===''+b;case'[object Number]':if(+a!==+a)return+b!==+b;return+a===0?1/ +a===1/b:+a===+b;case'[object Date]':case'[object Boolean]':return+a===+b;case'[object Symbol]':return SymbolProto.valueOf.call(a)===SymbolProto.valueOf.call(b);}
var areArrays=className==='[object Array]';if(!areArrays){if(typeof a!='object'||typeof b!='object')return false;var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&aCtor instanceof aCtor&&_.isFunction(bCtor)&&bCtor instanceof bCtor)&&('constructor'in a&&'constructor'in b)){return false;}}
aStack=aStack||[];bStack=bStack||[];var length=aStack.length;while(length--){if(aStack[length]===a)return bStack[length]===b;}
aStack.push(a);bStack.push(b);if(areArrays){length=a.length;if(length!==b.length)return false;while(length--){if(!eq(a[length],b[length],aStack,bStack))return false;}}else{var keys=_.keys(a),key;length=keys.length;if(_.keys(b).length!==length)return false;while(length--){key=keys[length];if(!(has(b,key)&&eq(a[key],b[key],aStack,bStack)))return false;}}
aStack.pop();bStack.pop();return true;};_.isEqual=function(a,b){return eq(a,b);};_.isEmpty=function(obj){if(obj==null)return true;if(isArrayLike(obj)&&(_.isArray(obj)||_.isString(obj)||_.isArguments(obj)))return obj.length===0;return _.keys(obj).length===0;};_.isElement=function(obj){return!!(obj&&obj.nodeType===1);};_.isArray=nativeIsArray||function(obj){return toString.call(obj)==='[object Array]';};_.isObject=function(obj){var type=typeof obj;return type==='function'||type==='object'&&!!obj;};_.each(['Arguments','Function','String','Number','Date','RegExp','Error','Symbol','Map','WeakMap','Set','WeakSet'],function(name){_['is'+name]=function(obj){return toString.call(obj)==='[object '+name+']';};});if(!_.isArguments(arguments)){_.isArguments=function(obj){return has(obj,'callee');};}
var nodelist=root.document&&root.document.childNodes;if(typeof/./!='function'&&typeof Int8Array!='object'&&typeof nodelist!='function'){_.isFunction=function(obj){return typeof obj=='function'||false;};}
_.isFinite=function(obj){return!_.isSymbol(obj)&&isFinite(obj)&&!isNaN(parseFloat(obj));};_.isNaN=function(obj){return _.isNumber(obj)&&isNaN(obj);};_.isBoolean=function(obj){return obj===true||obj===false||toString.call(obj)==='[object Boolean]';};_.isNull=function(obj){return obj===null;};_.isUndefined=function(obj){return obj===void 0;};_.has=function(obj,path){if(!_.isArray(path)){return has(obj,path);}
var length=path.length;for(var i=0;i<length;i++){var key=path[i];if(obj==null||!hasOwnProperty.call(obj,key)){return false;}
obj=obj[key];}
return!!length;};_.noConflict=function(){root._=previousUnderscore;return this;};_.identity=function(value){return value;};_.constant=function(value){return function(){return value;};};_.noop=function(){};_.property=function(path){if(!_.isArray(path)){return shallowProperty(path);}
return function(obj){return deepGet(obj,path);};};_.propertyOf=function(obj){if(obj==null){return function(){};}
return function(path){return!_.isArray(path)?obj[path]:deepGet(obj,path);};};_.matcher=_.matches=function(attrs){attrs=_.extendOwn({},attrs);return function(obj){return _.isMatch(obj,attrs);};};_.times=function(n,iteratee,context){var accum=Array(Math.max(0,n));iteratee=optimizeCb(iteratee,context,1);for(var i=0;i<n;i++)accum[i]=iteratee(i);return accum;};_.random=function(min,max){if(max==null){max=min;min=0;}
return min+Math.floor(Math.random()*(max-min+1));};_.now=Date.now||function(){return new Date().getTime();};var escapeMap={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#x27;','`':'&#x60;'};var unescapeMap=_.invert(escapeMap);var createEscaper=function(map){var escaper=function(match){return map[match];};var source='(?:'+_.keys(map).join('|')+')';var testRegexp=RegExp(source);var replaceRegexp=RegExp(source,'g');return function(string){string=string==null?'':''+string;return testRegexp.test(string)?string.replace(replaceRegexp,escaper):string;};};_.escape=createEscaper(escapeMap);_.unescape=createEscaper(unescapeMap);_.result=function(obj,path,fallback){if(!_.isArray(path))path=[path];var length=path.length;if(!length){return _.isFunction(fallback)?fallback.call(obj):fallback;}
for(var i=0;i<length;i++){var prop=obj==null?void 0:obj[path[i]];if(prop===void 0){prop=fallback;i=length;}
obj=_.isFunction(prop)?prop.call(obj):prop;}
return obj;};var idCounter=0;_.uniqueId=function(prefix){var id=++idCounter+'';return prefix?prefix+id:id;};_.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var noMatch=/(.)^/;var escapes={"'":"'",'\\':'\\','\r':'r','\n':'n','\u2028':'u2028','\u2029':'u2029'};var escapeRegExp=/\\|'|\r|\n|\u2028|\u2029/g;var escapeChar=function(match){return'\\'+escapes[match];};_.template=function(text,settings,oldSettings){if(!settings&&oldSettings)settings=oldSettings;settings=_.defaults({},settings,_.templateSettings);var matcher=RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join('|')+'|$','g');var index=0;var source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){source+=text.slice(index,offset).replace(escapeRegExp,escapeChar);index=offset+match.length;if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'";}else if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'";}else if(evaluate){source+="';\n"+evaluate+"\n__p+='";}
return match;});source+="';\n";if(!settings.variable)source='with(obj||{}){\n'+source+'}\n';source="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+
source+'return __p;\n';var render;try{render=new Function(settings.variable||'obj','_',source);}catch(e){e.source=source;throw e;}
var template=function(data){return render.call(this,data,_);};var argument=settings.variable||'obj';template.source='function('+argument+'){\n'+source+'}';return template;};_.chain=function(obj){var instance=_(obj);instance._chain=true;return instance;};var chainResult=function(instance,obj){return instance._chain?_(obj).chain():obj;};_.mixin=function(obj){_.each(_.functions(obj),function(name){var func=_[name]=obj[name];_.prototype[name]=function(){var args=[this._wrapped];push.apply(args,arguments);return chainResult(this,func.apply(_,args));};});return _;};_.mixin(_);_.each(['pop','push','reverse','shift','sort','splice','unshift'],function(name){var method=ArrayProto[name];_.prototype[name]=function(){var obj=this._wrapped;method.apply(obj,arguments);if((name==='shift'||name==='splice')&&obj.length===0)delete obj[0];return chainResult(this,obj);};});_.each(['concat','join','slice'],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return chainResult(this,method.apply(this._wrapped,arguments));};});_.prototype.value=function(){return this._wrapped;};_.prototype.valueOf=_.prototype.toJSON=_.prototype.value;_.prototype.toString=function(){return String(this._wrapped);};if(typeof define=='function'&&define.amd){define('underscore',[],function(){return _;});}}());};BundleModuleCode['ext/jsep']=function(module,exports){(function(root){'use strict';var COMPOUND='Compound',IDENTIFIER='Identifier',MEMBER_EXP='MemberExpression',LITERAL='Literal',THIS_EXP='ThisExpression',CALL_EXP='CallExpression',UNARY_EXP='UnaryExpression',BINARY_EXP='BinaryExpression',LOGICAL_EXP='LogicalExpression',CONDITIONAL_EXP='ConditionalExpression',ARRAY_EXP='ArrayExpression',PERIOD_CODE=46,COMMA_CODE=44,SQUOTE_CODE=39,DQUOTE_CODE=34,OPAREN_CODE=40,CPAREN_CODE=41,OBRACK_CODE=91,CBRACK_CODE=93,QUMARK_CODE=63,SEMCOL_CODE=59,COLON_CODE=58,throwError=function(message,index){var error=new Error(message+' at character '+index);error.index=index;error.description=message;throw error;},t=true,unary_ops={'-':t,'!':t,'~':t,'+':t},binary_ops={'||':1,'&&':2,'|':3,'^':4,'^1':4,'^0':4,'&':5,'->':5,'==':6,'!=':6,'===':6,'!==':6,'==~':6,'<':7,'>':7,'<=':7,'>=':7,'<<':8,'>>':8,'>>>':8,'+':9,'-':9,'*':10,'/':10,'%':10,},getMaxKeyLen=function(obj){var max_len=0,len;for(var key in obj){if((len=key.length)>max_len&&obj.hasOwnProperty(key)){max_len=len;}}
return max_len;},max_unop_len=getMaxKeyLen(unary_ops),max_binop_len=getMaxKeyLen(binary_ops),literals={'true':true,'false':false,'null':null},this_str='this',binaryPrecedence=function(op_val){return binary_ops[op_val]||0;},createBinaryExpression=function(operator,left,right){var type=(operator==='||'||operator==='&&')?LOGICAL_EXP:BINARY_EXP;return{type:type,operator:operator,left:left,right:right};},isDecimalDigit=function(ch){return(ch>=48&&ch<=57);},isIdentifierStart=function(ch){return(ch===36)||(ch===95)||(ch>=65&&ch<=90)||(ch>=97&&ch<=122)||(ch>=128&&!binary_ops[String.fromCharCode(ch)]);},isIdentifierPart=function(ch){return(ch===36)||(ch===95)||(ch>=65&&ch<=90)||(ch>=97&&ch<=122)||(ch>=48&&ch<=57)||(ch>=128&&!binary_ops[String.fromCharCode(ch)]);},jsep=function(expr){var index=0,charAtFunc=expr.charAt,charCodeAtFunc=expr.charCodeAt,exprI=function(i){return charAtFunc.call(expr,i);},exprICode=function(i){return charCodeAtFunc.call(expr,i);},length=expr.length,gobbleSpaces=function(){var ch=exprICode(index);while(ch===32||ch===9||ch===10||ch===13){ch=exprICode(++index);}},gobbleExpression=function(){var test=gobbleBinaryExpression(),consequent,alternate;gobbleSpaces();if(exprICode(index)===QUMARK_CODE){index++;consequent=gobbleExpression();if(!consequent){throwError('Expected expression',index);}
gobbleSpaces();if(exprICode(index)===COLON_CODE){index++;alternate=gobbleExpression();if(!alternate){throwError('Expected expression',index);}
return{type:CONDITIONAL_EXP,test:test,consequent:consequent,alternate:alternate};}else{throwError('Expected :',index);}}else{return test;}},gobbleBinaryOp=function(){gobbleSpaces();var biop,to_check=expr.substr(index,max_binop_len),tc_len=to_check.length;while(tc_len>0){if(binary_ops.hasOwnProperty(to_check)&&(!isIdentifierStart(exprICode(index))||(index+to_check.length<expr.length&&!isIdentifierPart(exprICode(index+to_check.length))))){index+=tc_len;return to_check;}
to_check=to_check.substr(0,--tc_len);}
return false;},gobbleBinaryExpression=function(){var ch_i,node,biop,prec,stack,biop_info,left,right,i,cur_biop;left=gobbleToken();biop=gobbleBinaryOp();if(!biop){return left;}
biop_info={value:biop,prec:binaryPrecedence(biop)};right=gobbleToken();if(!right){throwError("Expected expression after "+biop,index);}
stack=[left,biop_info,right];while((biop=gobbleBinaryOp())){prec=binaryPrecedence(biop);if(prec===0){break;}
biop_info={value:biop,prec:prec};cur_biop=biop;while((stack.length>2)&&(prec<=stack[stack.length-2].prec)){right=stack.pop();biop=stack.pop().value;left=stack.pop();node=createBinaryExpression(biop,left,right);stack.push(node);}
node=gobbleToken();if(!node){throwError("Expected expression after "+cur_biop,index);}
stack.push(biop_info,node);}
i=stack.length-1;node=stack[i];while(i>1){node=createBinaryExpression(stack[i-1].value,stack[i-2],node);i-=2;}
return node;},gobbleToken=function(){var ch,to_check,tc_len;gobbleSpaces();ch=exprICode(index);if(isDecimalDigit(ch)||ch===PERIOD_CODE){return gobbleNumericLiteral();}else if(ch===SQUOTE_CODE||ch===DQUOTE_CODE){return gobbleStringLiteral();}else if(ch===OBRACK_CODE){return gobbleArray();}else{to_check=expr.substr(index,max_unop_len);tc_len=to_check.length;while(tc_len>0){if(unary_ops.hasOwnProperty(to_check)&&(!isIdentifierStart(exprICode(index))||(index+to_check.length<expr.length&&!isIdentifierPart(exprICode(index+to_check.length))))){index+=tc_len;return{type:UNARY_EXP,operator:to_check,argument:gobbleToken(),prefix:true};}
to_check=to_check.substr(0,--tc_len);}
if(isIdentifierStart(ch)||ch===OPAREN_CODE){return gobbleVariable();}}
return false;},gobbleNumericLiteral=function(){var number='',ch,chCode;while(isDecimalDigit(exprICode(index))){number+=exprI(index++);}
if(exprICode(index)===PERIOD_CODE){number+=exprI(index++);while(isDecimalDigit(exprICode(index))){number+=exprI(index++);}}
ch=exprI(index);if(ch==='e'||ch==='E'){number+=exprI(index++);ch=exprI(index);if(ch==='+'||ch==='-'){number+=exprI(index++);}
while(isDecimalDigit(exprICode(index))){number+=exprI(index++);}
if(!isDecimalDigit(exprICode(index-1))){throwError('Expected exponent ('+number+exprI(index)+')',index);}}
chCode=exprICode(index);if(isIdentifierStart(chCode)){throwError('Variable names cannot start with a number ('+
number+exprI(index)+')',index);}else if(chCode===PERIOD_CODE){throwError('Unexpected period',index);}
return{type:LITERAL,value:parseFloat(number),raw:number};},gobbleStringLiteral=function(){var str='',quote=exprI(index++),closed=false,ch;while(index<length){ch=exprI(index++);if(ch===quote){closed=true;break;}else if(ch==='\\'){ch=exprI(index++);switch(ch){case'n':str+='\n';break;case'r':str+='\r';break;case't':str+='\t';break;case'b':str+='\b';break;case'f':str+='\f';break;case'v':str+='\x0B';break;default:str+=ch;}}else{str+=ch;}}
if(!closed){throwError('Unclosed quote after "'+str+'"',index);}
return{type:LITERAL,value:str,raw:quote+str+quote};},gobbleIdentifier=function(){var ch=exprICode(index),start=index,identifier;if(isIdentifierStart(ch)){index++;}else{throwError('Unexpected '+exprI(index),index);}
while(index<length){ch=exprICode(index);if(isIdentifierPart(ch)){index++;}else{break;}}
identifier=expr.slice(start,index);if(literals.hasOwnProperty(identifier)){return{type:LITERAL,value:literals[identifier],raw:identifier};}else if(identifier===this_str){return{type:THIS_EXP};}else{return{type:IDENTIFIER,name:identifier};}},gobbleArguments=function(termination){var ch_i,args=[],node,closed=false;while(index<length){gobbleSpaces();ch_i=exprICode(index);if(ch_i===termination){closed=true;index++;break;}else if(ch_i===COMMA_CODE){index++;}else{node=gobbleExpression();if(!node||node.type===COMPOUND){throwError('Expected comma',index);}
args.push(node);}}
if(!closed){throwError('Expected '+String.fromCharCode(termination),index);}
return args;},gobbleVariable=function(){var ch_i,node;ch_i=exprICode(index);if(ch_i===OPAREN_CODE){node=gobbleGroup();}else{node=gobbleIdentifier();}
gobbleSpaces();ch_i=exprICode(index);while(ch_i===PERIOD_CODE||ch_i===OBRACK_CODE||ch_i===OPAREN_CODE){index++;if(ch_i===PERIOD_CODE){gobbleSpaces();node={type:MEMBER_EXP,computed:false,object:node,property:gobbleIdentifier()};}else if(ch_i===OBRACK_CODE){node={type:MEMBER_EXP,computed:true,object:node,property:gobbleExpression()};gobbleSpaces();ch_i=exprICode(index);if(ch_i!==CBRACK_CODE){throwError('Unclosed [',index);}
index++;}else if(ch_i===OPAREN_CODE){node={type:CALL_EXP,'arguments':gobbleArguments(CPAREN_CODE),callee:node};}
gobbleSpaces();ch_i=exprICode(index);}
return node;},gobbleGroup=function(){index++;var node=gobbleExpression();gobbleSpaces();if(exprICode(index)===CPAREN_CODE){index++;return node;}else{throwError('Unclosed (',index);}},gobbleArray=function(){index++;return{type:ARRAY_EXP,elements:gobbleArguments(CBRACK_CODE)};},nodes=[],ch_i,node;while(index<length){ch_i=exprICode(index);if(ch_i===SEMCOL_CODE||ch_i===COMMA_CODE){index++;}else{if((node=gobbleExpression())){nodes.push(node);}else if(index<length){throwError('Unexpected "'+exprI(index)+'"',index);}}}
if(nodes.length===1){return nodes[0];}else{return{type:COMPOUND,body:nodes};}};jsep.version='<%= version %>';jsep.toString=function(){return'JavaScript Expression Parser (JSEP) v'+jsep.version;};jsep.addUnaryOp=function(op_name){max_unop_len=Math.max(op_name.length,max_unop_len);unary_ops[op_name]=t;return this;};jsep.addBinaryOp=function(op_name,precedence){max_binop_len=Math.max(op_name.length,max_binop_len);binary_ops[op_name]=precedence;return this;};jsep.addLiteral=function(literal_name,literal_value){literals[literal_name]=literal_value;return this;};jsep.removeUnaryOp=function(op_name){delete unary_ops[op_name];if(op_name.length===max_unop_len){max_unop_len=getMaxKeyLen(unary_ops);}
return this;};jsep.removeAllUnaryOps=function(){unary_ops={};max_unop_len=0;return this;};jsep.removeBinaryOp=function(op_name){delete binary_ops[op_name];if(op_name.length===max_binop_len){max_binop_len=getMaxKeyLen(binary_ops);}
return this;};jsep.removeAllBinaryOps=function(){binary_ops={};max_binop_len=0;return this;};jsep.removeLiteral=function(literal_name){delete literals[literal_name];return this;};jsep.removeAllLiterals=function(){literals={};return this;};if(typeof exports==='undefined'){var old_jsep=root.jsep;root.jsep=jsep;jsep.noConflict=function(){if(root.jsep===jsep){root.jsep=old_jsep;}
return jsep;};}else{if(typeof module!=='undefined'&&module.exports){exports=module.exports=jsep;}else{exports.parse=jsep;}}}(this));};BundleModuleCode['logic/prolog']=function(module,exports){var prolog;(function(){var version={major:0,minor:2,patch:87,status:"beta"};function cd(working_directory,path){if(path[0]==="/")
working_directory=path;else
working_directory+=working_directory[working_directory.length-1]==="/"?path:"/"+path;working_directory=working_directory.replace(/\/\.\//g,"/");var dirs=working_directory.split("/");var dirs2=[];for(var i=0;i<dirs.length;i++){if(dirs[i]!==".."){dirs2.push(dirs[i]);}else{if(dirs2.length!==0)
dirs2.pop();}}
return dirs2.join("/").replace(/\/\.$/,"/");}
function TauFile(name,type,parent,text){text=text===undefined?"":text;this.name=name;this.type=type;this.parent=parent;this.text=text;this.created=Date.now()/1000;this.modified=this.created;}
TauFile.prototype.get=function(length,position){if(position===this.text.length){return"end_of_file";}else if(position>this.text.length){return"end_of_file";}else{return this.text.substring(position,position+length);}};TauFile.prototype.put=function(text,position){if(position==="end_of_file"){this.text+=text;return true;}else if(position==="past_end_of_file"){return null;}else{this.text=this.text.substring(0,position)+text+this.text.substring(position+text.length);return true;}};TauFile.prototype.get_byte=function(position){if(position==="end_of_stream")
return-1;var index=Math.floor(position/2);if(this.text.length<=index)
return-1;var code=codePointAt(this.text[Math.floor(position/2)],0);if(position%2===0)
return code&0xff;else
return code/256>>>0;};TauFile.prototype.put_byte=function(byte,position){var index=position==="end_of_stream"?this.text.length:Math.floor(position/2);if(this.text.length<index)
return null;var code=this.text.length===index?-1:codePointAt(this.text[Math.floor(position/2)],0);if(position%2===0){code=code/256>>>0;code=((code&0xff)<<8)|(byte&0xff);}else{code=code&0xff;code=((byte&0xff)<<8)|(code&0xff);}
if(this.text.length===index)
this.text+=fromCodePoint(code);else
this.text=this.text.substring(0,index)+fromCodePoint(code)+this.text.substring(index+1);return true;};TauFile.prototype.flush=function(){return true;};TauFile.prototype.close=function(){this.modified=Date.now()/1000;return true;};TauFile.prototype.size=function(){return this.text.length;};function TauDirectory(name,parent){this.name=name;this.parent=parent;this.files={};this.length=0;this.created=Date.now()/1000;this.modified=this.created;}
TauDirectory.prototype.lookup=function(file){if(this.files.hasOwnProperty(file))
return this.files[file];return null;};TauDirectory.prototype.push=function(name,file){if(!this.files.hasOwnProperty(name))
this.length++;this.files[name]=file;this.modified=Date.now()/1000;};TauDirectory.prototype.remove=function(name){if(this.files.hasOwnProperty(name)){this.length--;delete this.files[name];this.modified=Date.now()/1000;}};TauDirectory.prototype.empty=function(){return this.length===0;};TauDirectory.prototype.size=function(){return 4096;};tau_file_system={files:new TauDirectory("/","/",null),open:function(path,type,mode){var dirs=path.replace(/\/$/,"").split("/");var dir=tau_file_system.files;var name=dirs[dirs.length-1];for(var i=1;i<dirs.length-1;i++){dir=dir.lookup(dirs[i]);if(!pl.type.is_directory(dir))
return null;}
var file=dir.lookup(name);if(file===null){if(mode==="read")
return null;file=new TauFile(name,type,dir);dir.push(name,file);}else if(!pl.type.is_file(file)){return null;}
if(mode==="write")
file.text="";return file;},get:function(path){var dirs=path.replace(/\/$/,"").split("/");var file=tau_file_system.files;for(var i=1;i<dirs.length;i++)
if(pl.type.is_directory(file))
file=file.lookup(dirs[i]);else
return null;return file;}};tau_user_input={buffer:"",get:function(length,_){var text;while(tau_user_input.buffer.length<length){text=window.prompt();if(text){tau_user_input.buffer+=text;}}
text=tau_user_input.buffer.substr(0,length);tau_user_input.buffer=tau_user_input.buffer.substr(length);return text;}};tau_user_output={put:function(text,_){console.log(text);return true;},flush:function(){return true;}};nodejs_file_system={open:function(path,type,mode){var fs=require('fs');var fd=fs.openSync(path,mode[0]);if(mode==="read"&&!fs.existsSync(path))
return null;return{get:function(length,position){var buffer=new Buffer(length);fs.readSync(fd,buffer,0,length,position);return buffer.toString();},put:function(text,position){var buffer=Buffer.from(text);if(position==="end_of_file")
fs.writeSync(fd,buffer);else if(position==="past_end_of_file")
return null;else
fs.writeSync(fd,buffer,0,buffer.length,position);return true;},get_byte:function(position){return null;},put_byte:function(byte,position){return null;},flush:function(){return true;},close:function(){fs.closeSync(fd);return true;}};}};nodejs_user_input={buffer:"",get:function(length,_){var text;var readlineSync=require('readline-sync');while(nodejs_user_input.buffer.length<length)
nodejs_user_input.buffer+=readlineSync.question();text=nodejs_user_input.buffer.substr(0,length);nodejs_user_input.buffer=nodejs_user_input.buffer.substr(length);return text;}};nodejs_user_output={put:function(text,_){process.stdout.write(text);return true;},flush:function(){return true;}};var indexOf;if(!Array.prototype.indexOf){indexOf=function(array,elem){var len=array.length;for(var i=0;i<len;i++){if(elem===array[i])return i;}
return-1;};}else{indexOf=function(array,elem){return array.indexOf(elem);};}
var reduce=function(array,fn){if(array.length===0)return undefined;var elem=array[0];var len=array.length;for(var i=1;i<len;i++){elem=fn(elem,array[i]);}
return elem;};var map;if(!Array.prototype.map){map=function(array,fn){var a=[];var len=array.length;for(var i=0;i<len;i++){a.push(fn(array[i]));}
return a;};}else{map=function(array,fn){return array.map(fn);};}
var filter;if(!Array.prototype.filter){filter=function(array,fn){var a=[];var len=array.length;for(var i=0;i<len;i++){if(fn(array[i]))
a.push(array[i]);}
return a;};}else{filter=function(array,fn){return array.filter(fn);};}
var codePointAt;if(!String.prototype.codePointAt){codePointAt=function(str,i){return str.charCodeAt(i);};}else{codePointAt=function(str,i){return str.codePointAt(i);};}
var fromCodePoint;if(!String.fromCodePoint){fromCodePoint=function(){return String.fromCharCode.apply(null,arguments);};}else{fromCodePoint=function(){return String.fromCodePoint.apply(null,arguments);};}
var stringLength;var regexAstralSymbols=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;if(Array.from)
stringLength=function(str){return Array.from(str).length;};else
stringLength=function(str){return str.replace(regexAstralSymbols,'_').length;};var ERROR=0;var SUCCESS=1;var regex_escape=/(\\a)|(\\b)|(\\f)|(\\n)|(\\r)|(\\t)|(\\v)|\\x([0-9a-fA-F]+)\\|\\([0-7]+)\\|(\\\\)|(\\')|('')|(\\")|(\\`)|(\\.)|(.)/g;var escape_map={"\\a":7,"\\b":8,"\\f":12,"\\n":10,"\\r":13,"\\t":9,"\\v":11};function escape(str){var s=[];var _error=false;str.replace(regex_escape,function(match,a,b,f,n,r,t,v,hex,octal,back,single,dsingle,double,backquote,error,char){switch(true){case hex!==undefined:s.push(parseInt(hex,16));return"";case octal!==undefined:s.push(parseInt(octal,8));return"";case back!==undefined:case single!==undefined:case dsingle!==undefined:case double!==undefined:case backquote!==undefined:s.push(codePointAt(match.substr(1),0));return"";case char!==undefined:s.push(codePointAt(char,0));return"";case error!==undefined:_error=true;default:s.push(escape_map[match]);return"";}});if(_error)
return null;return s;}
function escapeAtom(str,quote){var atom='';if(str==="\\")return null;if(str.length<2)return str;try{str=str.replace(/\\([0-7]+)\\/g,function(match,g1){return fromCodePoint(parseInt(g1,8));});str=str.replace(/\\x([0-9a-fA-F]+)\\/g,function(match,g1){return fromCodePoint(parseInt(g1,16));});}catch(error){return null;}
for(var i=0;i<str.length;i++){var a=str.charAt(i);var b=str.charAt(i+1);if(a===quote&&b===quote){i++;atom+=quote;}else if(a==='\\'){if(['a','b','f','n','r','t','v',"'",'"','\\','\a','\b','\f','\n','\r','\t','\v'].indexOf(b)!==-1){i+=1;switch(b){case'a':atom+='\a';break;case'b':atom+='\b';break;case'f':atom+='\f';break;case'n':atom+='\n';break;case'r':atom+='\r';break;case't':atom+='\t';break;case'v':atom+='\v';break;case"'":atom+="'";break;case'"':atom+='"';break;case'\\':atom+='\\';break;}}else{return null;}}else{atom+=a;}}
return atom;}
function redoEscape(str){var atom='';for(var i=0;i<str.length;i++){switch(str.charAt(i)){case"'":atom+="\\'";break;case'\\':atom+='\\\\';break;case'\b':atom+='\\b';break;case'\f':atom+='\\f';break;case'\n':atom+='\\n';break;case'\r':atom+='\\r';break;case'\t':atom+='\\t';break;case'\v':atom+='\\v';break;default:atom+=str.charAt(i);break;}}
return atom;}
function convertNum(num){var n=num.substr(2);switch(num.substr(0,2).toLowerCase()){case"0x":return parseInt(n,16);case"0b":return parseInt(n,2);case"0o":return parseInt(n,8);case"0'":return escape(n)[0];default:return parseFloat(num);}}
var rules={whitespace:/^\s*(?:(?:%.*)|(?:\/\*(?:\n|\r|.)*?\*\/)|(?:\s+))\s*/,variable:/^(?:[A-Z_][a-zA-Z0-9_]*)/,atom:/^(\!|,|;|[a-z][0-9a-zA-Z_]*|[#\$\&\*\+\-\.\/\:\<\=\>\?\@\^\~\\]+|'(?:(?:'')|(?:\\')|[^'])*')/,number:/^(?:0o[0-7]+|0x[0-9a-fA-F]+|0b[01]+|0'(?:''|\\[abfnrtv\\'"`]|\\x?\d+\\|[^\\])|\d+(?:\.\d+(?:[eE][+-]?\d+)?)?)/,string:/^(?:"([^"]|""|\\")*"|`([^`]|``|\\`)*`)/,l_brace:/^(?:\[)/,r_brace:/^(?:\])/,l_bracket:/^(?:\{)/,r_bracket:/^(?:\})/,bar:/^(?:\|)/,l_paren:/^(?:\()/,r_paren:/^(?:\))/};function replace(thread,text){if(thread.get_flag("char_conversion").id==="on"){return text.replace(/./g,function(char){return thread.get_char_conversion(char);});}
return text;}
function Tokenizer(thread){this.thread=thread;this.text="";this.tokens=[];}
Tokenizer.prototype.set_last_tokens=function(tokens){return this.tokens=tokens;};Tokenizer.prototype.new_text=function(text){this.text=text;this.tokens=[];};Tokenizer.prototype.get_tokens=function(init){var text;var len=0;var line=0;var start=0;var tokens=[];var last_in_blank=false;if(init){var token=this.tokens[init-1];len=token.len;text=replace(this.thread,this.text.substr(token.len));line=token.line;start=token.start;}
else
text=this.text;if(/^\s*$/.test(text))
return null;while(text!==""){var matches=[];var last_is_blank=false;if(/^\n/.exec(text)!==null){line++;start=0;len++;text=text.replace(/\n/,"");last_in_blank=true;continue;}
for(var rule in rules){if(rules.hasOwnProperty(rule)){var matchs=rules[rule].exec(text);if(matchs){matches.push({value:matchs[0],name:rule,matches:matchs});}}}
if(!matches.length)
return this.set_last_tokens([{value:text,matches:[],name:"lexical",line:line,start:start}]);var token=reduce(matches,function(a,b){return a.value.length>=b.value.length?a:b;});token.start=start;token.line=line;text=text.replace(token.value,"");start+=token.value.length;len+=token.value.length;switch(token.name){case"atom":token.raw=token.value;if(token.value.charAt(0)==="'"){token.value=escapeAtom(token.value.substr(1,token.value.length-2),"'");if(token.value===null){token.name="lexical";token.value="unknown escape sequence";}}
break;case"number":token.float=token.value.substring(0,2)!=="0x"&&token.value.match(/[.eE]/)!==null&&token.value!=="0'.";token.value=convertNum(token.value);token.blank=last_is_blank;break;case"string":var del=token.value.charAt(0);token.value=escapeAtom(token.value.substr(1,token.value.length-2),del);if(token.value===null){token.name="lexical";token.value="unknown escape sequence";}
break;case"whitespace":var last=tokens[tokens.length-1];if(last)last.space=true;last_is_blank=true;continue;case"r_bracket":if(tokens.length>0&&tokens[tokens.length-1].name==="l_bracket"){token=tokens.pop();token.name="atom";token.value="{}";token.raw="{}";token.space=false;}
break;case"r_brace":if(tokens.length>0&&tokens[tokens.length-1].name==="l_brace"){token=tokens.pop();token.name="atom";token.value="[]";token.raw="[]";token.space=false;}
break;}
token.len=len;tokens.push(token);last_is_blank=false;}
var t=this.set_last_tokens(tokens);return t.length===0?null:t;};function parseExpr(thread,tokens,start,priority,toplevel){if(!tokens[start])return{type:ERROR,value:pl.error.syntax(tokens[start-1],"expression expected",true)};var error;if(priority==="0"){var token=tokens[start];switch(token.name){case"number":return{type:SUCCESS,len:start+1,value:new pl.type.Num(token.value,token.float)};case"variable":return{type:SUCCESS,len:start+1,value:new pl.type.Var(token.value)};case"string":var str;switch(thread.get_flag("double_quotes").id){case"atom":;str=new Term(token.value,[]);break;case"codes":str=new Term("[]",[]);for(var i=token.value.length-1;i>=0;i--)
str=new Term(".",[new pl.type.Num(codePointAt(token.value,i),false),str]);break;case"chars":str=new Term("[]",[]);for(var i=token.value.length-1;i>=0;i--)
str=new Term(".",[new pl.type.Term(token.value.charAt(i),[]),str]);break;}
return{type:SUCCESS,len:start+1,value:str};case"l_paren":var expr=parseExpr(thread,tokens,start+1,thread.__get_max_priority(),true);if(expr.type!==SUCCESS)return expr;if(tokens[expr.len]&&tokens[expr.len].name==="r_paren"){expr.len++;return expr;}
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[expr.len]?tokens[expr.len]:tokens[expr.len-1],") or operator expected",!tokens[expr.len])}
case"l_bracket":var expr=parseExpr(thread,tokens,start+1,thread.__get_max_priority(),true);if(expr.type!==SUCCESS)return expr;if(tokens[expr.len]&&tokens[expr.len].name==="r_bracket"){expr.len++;expr.value=new Term("{}",[expr.value]);return expr;}
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[expr.len]?tokens[expr.len]:tokens[expr.len-1],"} or operator expected",!tokens[expr.len])}}
var result=parseTerm(thread,tokens,start,toplevel);if(result.type===SUCCESS||result.derived)
return result;result=parseList(thread,tokens,start);if(result.type===SUCCESS||result.derived)
return result;return{type:ERROR,derived:false,value:pl.error.syntax(tokens[start],"unexpected token")};}
var max_priority=thread.__get_max_priority();var next_priority=thread.__get_next_priority(priority);var aux_start=start;if(tokens[start].name==="atom"&&tokens[start+1]&&(tokens[start].space||tokens[start+1].name!=="l_paren")){var token=tokens[start++];var classes=thread.__lookup_operator_classes(priority,token.value);if(classes&&classes.indexOf("fy")>-1){var expr=parseExpr(thread,tokens,start,priority,toplevel);if(expr.type!==ERROR){if(token.value==="-"&&!token.space&&pl.type.is_number(expr.value)){return{value:new pl.type.Num(-expr.value.value,expr.value.is_float),len:expr.len,type:SUCCESS};}else{return{value:new pl.type.Term(token.value,[expr.value]),len:expr.len,type:SUCCESS};}}else{error=expr;}}else if(classes&&classes.indexOf("fx")>-1){var expr=parseExpr(thread,tokens,start,next_priority,toplevel);if(expr.type!==ERROR){return{value:new pl.type.Term(token.value,[expr.value]),len:expr.len,type:SUCCESS};}else{error=expr;}}}
start=aux_start;var expr=parseExpr(thread,tokens,start,next_priority,toplevel);if(expr.type===SUCCESS){start=expr.len;var token=tokens[start];if(tokens[start]&&(tokens[start].name==="atom"&&thread.__lookup_operator_classes(priority,token.value)||tokens[start].name==="bar"&&thread.__lookup_operator_classes(priority,"|"))){var next_priority_lt=next_priority;var next_priority_eq=priority;var classes=thread.__lookup_operator_classes(priority,token.value);if(classes.indexOf("xf")>-1){return{value:new pl.type.Term(token.value,[expr.value]),len:++expr.len,type:SUCCESS};}else if(classes.indexOf("xfx")>-1){var expr2=parseExpr(thread,tokens,start+1,next_priority_lt,toplevel);if(expr2.type===SUCCESS){return{value:new pl.type.Term(token.value,[expr.value,expr2.value]),len:expr2.len,type:SUCCESS};}else{expr2.derived=true;return expr2;}}else if(classes.indexOf("xfy")>-1){var expr2=parseExpr(thread,tokens,start+1,next_priority_eq,toplevel);if(expr2.type===SUCCESS){return{value:new pl.type.Term(token.value,[expr.value,expr2.value]),len:expr2.len,type:SUCCESS};}else{expr2.derived=true;return expr2;}}else if(expr.type!==ERROR){while(true){start=expr.len;var token=tokens[start];if(token&&token.name==="atom"&&thread.__lookup_operator_classes(priority,token.value)){var classes=thread.__lookup_operator_classes(priority,token.value);if(classes.indexOf("yf")>-1){expr={value:new pl.type.Term(token.value,[expr.value]),len:++start,type:SUCCESS};}else if(classes.indexOf("yfx")>-1){var expr2=parseExpr(thread,tokens,++start,next_priority_lt,toplevel);if(expr2.type===ERROR){expr2.derived=true;return expr2;}
start=expr2.len;expr={value:new pl.type.Term(token.value,[expr.value,expr2.value]),len:start,type:SUCCESS};}else{break;}}else{break;}}}}else{error={type:ERROR,value:pl.error.syntax(tokens[expr.len-1],"operator expected")};}
return expr;}
return expr;}
function parseTerm(thread,tokens,start,toplevel){if(!tokens[start]||(tokens[start].name==="atom"&&tokens[start].raw==="."&&!toplevel&&(tokens[start].space||!tokens[start+1]||tokens[start+1].name!=="l_paren")))
return{type:ERROR,derived:false,value:pl.error.syntax(tokens[start-1],"unfounded token")};var atom=tokens[start];var exprs=[];if(tokens[start].name==="atom"&&tokens[start].raw!==","){start++;if(tokens[start-1].space)return{type:SUCCESS,len:start,value:new pl.type.Term(atom.value,exprs)};if(tokens[start]&&tokens[start].name==="l_paren"){if(tokens[start+1]&&tokens[start+1].name==="r_paren")
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start+1],"argument expected")};var expr=parseExpr(thread,tokens,++start,"999",true);if(expr.type===ERROR){if(expr.derived)
return expr;else
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start]?tokens[start]:tokens[start-1],"argument expected",!tokens[start])};}
exprs.push(expr.value);start=expr.len;while(tokens[start]&&tokens[start].name==="atom"&&tokens[start].value===","){expr=parseExpr(thread,tokens,start+1,"999",true);if(expr.type===ERROR){if(expr.derived)
return expr;else
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start+1]?tokens[start+1]:tokens[start],"argument expected",!tokens[start+1])};}
exprs.push(expr.value);start=expr.len;}
if(tokens[start]&&tokens[start].name==="r_paren")start++;else return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start]?tokens[start]:tokens[start-1],", or ) expected",!tokens[start])};}
return{type:SUCCESS,len:start,value:new pl.type.Term(atom.value,exprs)};}
return{type:ERROR,derived:false,value:pl.error.syntax(tokens[start],"term expected")};}
function parseList(thread,tokens,start){if(!tokens[start])
return{type:ERROR,derived:false,value:pl.error.syntax(tokens[start-1],"[ expected")};if(tokens[start]&&tokens[start].name==="l_brace"){var expr=parseExpr(thread,tokens,++start,"999",true);var exprs=[expr.value];var cons=undefined;if(expr.type===ERROR){if(tokens[start]&&tokens[start].name==="r_brace"){return{type:SUCCESS,len:start+1,value:new pl.type.Term("[]",[])};}
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start],"] expected")};}
start=expr.len;while(tokens[start]&&tokens[start].name==="atom"&&tokens[start].value===","){expr=parseExpr(thread,tokens,start+1,"999",true);if(expr.type===ERROR){if(expr.derived)
return expr;else
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start+1]?tokens[start+1]:tokens[start],"argument expected",!tokens[start+1])};}
exprs.push(expr.value);start=expr.len;}
var bar=false
if(tokens[start]&&tokens[start].name==="bar"){bar=true;expr=parseExpr(thread,tokens,start+1,"999",true);if(expr.type===ERROR){if(expr.derived)
return expr;else
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start+1]?tokens[start+1]:tokens[start],"argument expected",!tokens[start+1])};}
cons=expr.value;start=expr.len;}
if(tokens[start]&&tokens[start].name==="r_brace")
return{type:SUCCESS,len:start+1,value:arrayToList(exprs,cons)};else
return{type:ERROR,derived:true,value:pl.error.syntax(tokens[start]?tokens[start]:tokens[start-1],bar?"] expected":", or | or ] expected",!tokens[start])};}
return{type:ERROR,derived:false,value:pl.error.syntax(tokens[start],"list expected")};}
function parseRule(thread,tokens,start){var line=tokens[start].line;var expr=parseExpr(thread,tokens,start,thread.__get_max_priority(),false);var rule=null;var obj;if(expr.type!==ERROR){start=expr.len;if(tokens[start]&&tokens[start].name==="atom"&&tokens[start].raw==="."){start++;if(pl.type.is_term(expr.value)){if(expr.value.indicator===":-/2"){rule=new pl.type.Rule(expr.value.args[0],body_conversion(expr.value.args[1]))
obj={value:rule,len:start,type:SUCCESS};}else if(expr.value.indicator==="-->/2"){rule=rule_to_dcg(new pl.type.Rule(expr.value.args[0],expr.value.args[1]),thread);if(!pl.type.is_rule(rule))
return{value:rule,len:start,type:ERROR};rule.body=body_conversion(rule.body);obj={value:rule,len:start,type:pl.type.is_rule(rule)?SUCCESS:ERROR};}else{rule=new pl.type.Rule(expr.value,null);obj={value:rule,len:start,type:SUCCESS};}
if(rule){var singleton=rule.singleton_variables();if(singleton.length>0)
thread.throw_warning(pl.warning.singleton(singleton,rule.head.indicator,line));}
return obj;}else{return{type:ERROR,value:pl.error.syntax(tokens[start],"callable expected")};}}else{return{type:ERROR,value:pl.error.syntax(tokens[start]?tokens[start]:tokens[start-1],". or operator expected")};}}
return expr;}
function parseProgram(thread,string,options){options=options?options:{};options.from=options.from?options.from:"$tau-js";options.reconsult=options.reconsult!==undefined?options.reconsult:true;var tokenizer=new Tokenizer(thread);var reconsulted={};var indicator;tokenizer.new_text(string);var n=0;var tokens=tokenizer.get_tokens(n);while(tokens!==null&&tokens[n]){var expr=parseRule(thread,tokens,n);if(expr.type===ERROR){return new Term("throw",[expr.value]);}else{var term_expansion=thread.session.rules["term_expansion/2"];if(term_expansion&&term_expansion.length>0){var n_thread=new Thread(thread.session);var term=expr.value.body?new Term(":-",[expr.value.head,expr.value.body]):expr.value.head;term=term.rename(thread.session);n_thread.query("term_expansion("+term.toString()+", X).");n_thread.answer(function(answer){if(answer&&!pl.type.is_error(answer)&&pl.type.is_term(answer.links['X'])){var term=answer.links['X'];var rule=term.indicator===":-/2"?new Rule(term.args[0],term.args[1]):new Rule(term,null);parseProgramExpansion(thread,options,reconsulted,{value:rule,len:expr.len,type:expr.type});}else{parseProgramExpansion(thread,options,reconsulted,expr);}});}else{parseProgramExpansion(thread,options,reconsulted,expr);}
n=expr.len;if(expr.value.body===null&&expr.value.head.indicator===":-/1"&&expr.value.head.args[0].indicator==="char_conversion/2"){tokens=tokenizer.get_tokens(n);n=0;}}}
return true;}
function parseGoalExpansion(thread,head,term,set,origin){var n_thread=new Thread(thread.session);n_thread.__goal_expansion=true;var varterm=thread.next_free_variable();var varhead=thread.next_free_variable();var goal=varhead+" = "+head+", goal_expansion("+term+", "+varterm+").";n_thread.query(goal);n_thread.answer(function(answer){if(answer&&!pl.type.is_error(answer)&&answer.links[varterm]){set(answer.links[varhead],body_conversion(answer.links[varterm]));parseGoalExpansion(thread,origin.head(),origin.term(),origin.set,origin);}});}
function parseQueryExpansion(thread,term){var n_thread=new Thread(thread.session);n_thread.__goal_expansion=true;var varterm=thread.next_free_variable();var goal="goal_expansion("+term+", "+varterm+").";n_thread.query(goal);var variables=n_thread.head_point().substitution.domain();n_thread.answer(function(answer){if(answer&&!pl.type.is_error(answer)&&answer.links[varterm]){for(var i=0;i<variables.length;i++){if(variables[i]!==varterm.id&&answer.links[variables[i]]){var subs=new Substitution();subs.links[answer.links[variables[i]]]=variables[i];answer.links[varterm]=answer.links[varterm].apply(subs);}}
parseQueryExpansion(thread,body_conversion(answer.links[varterm]));}else{thread.add_goal(term);}});}
function parseProgramExpansion(thread,options,reconsulted,expr){var exprs=[];if(pl.type.is_instantiated_list(expr.value.head)&&expr.value.body===null){var pointer=expr.value.head;while(pointer.indicator==="./2"){var rule=pointer.args[0];if(rule.indicator===":-/2")
exprs.push(new Rule(rule.args[0],rule.args[1]));else
exprs.push(new Rule(rule,null));pointer=pointer.args[1];}}else{exprs.push(expr.value);}
for(var i=0;i<exprs.length;i++){expr.value=exprs[i];if(expr.value.body===null&&expr.value.head.indicator==="?-/1"){var n_thread=new Thread(thread.session);n_thread.add_goal(expr.value.head.args[0]);n_thread.answer(function(answer){if(pl.type.is_error(answer)){thread.throw_warning(answer.args[0]);}else if(answer===false||answer===null){thread.throw_warning(pl.warning.failed_goal(expr.value.head.args[0],expr.len));}});}else if(expr.value.body===null&&expr.value.head.indicator===":-/1"){thread.run_directive(expr.value.head.args[0]);}else{indicator=expr.value.head.indicator;if(options.reconsult!==false&&reconsulted[indicator]!==true&&!thread.is_multifile_predicate(indicator)){thread.session.rules[indicator]=filter(thread.session.rules[indicator]||[],function(rule){return rule.dynamic;});reconsulted[indicator]=true;}
var goal_expansion=thread.session.rules["goal_expansion/2"];if(expr.value.body!==null&&goal_expansion&&goal_expansion.length>0){thread.renamed_variables={};var origin={head:function(){return expr.value.head;},term:function(){return expr.value.body;},set:function(h,p){expr.value.head=h;expr.value.body=p;}};parseGoalExpansion(thread,expr.value.head,body_conversion(expr.value.body),origin.set,origin);}
thread.add_rule(expr.value,options);}}}
function parseQuery(thread,string){var tokenizer=new Tokenizer(thread);tokenizer.new_text(string);var n=0;do{var tokens=tokenizer.get_tokens(n);if(tokens===null)break;var expr=parseExpr(thread,tokens,0,thread.__get_max_priority(),false);if(expr.type!==ERROR){var expr_position=expr.len;var tokens_pos=expr_position;if(tokens[expr_position]&&tokens[expr_position].name==="atom"&&tokens[expr_position].raw==="."){expr.value=body_conversion(expr.value);var goal_expansion=thread.session.rules["goal_expansion/2"];if(!thread.__goal_expansion&&goal_expansion&&goal_expansion.length>0){parseQueryExpansion(thread,expr.value);}else{thread.add_goal(expr.value);}}else{var token=tokens[expr_position];return new Term("throw",[pl.error.syntax(token?token:tokens[expr_position-1],". or operator expected",!token)]);}
n=expr.len+1;}else{return new Term("throw",[expr.value]);}}while(true);return true;}
function rule_to_dcg(rule,thread){rule=rule.rename(thread);var begin=thread.next_free_variable();var dcg=body_to_dcg(rule.body,begin,thread);if(dcg.error)
return dcg.value;rule.body=dcg.value;if(rule.head.indicator===",/2"){var terminals=rule.head.args[1];rule.head=rule.head.args[0];var last=thread.next_free_variable();var pointer=terminals;if(!pl.type.is_list(pointer)){return pl.error.type("list",pointer,"DCG/0");}
if(pointer.indicator==="[]/0"){terminals=dcg.variable;}else{while(pointer.indicator==="./2"&&pl.type.is_list(pointer)&&pointer.args[1].indicator!=="[]/0"){pointer=pointer.args[1];}
if(pl.type.is_variable(pointer))
return pl.error.instantiation("DCG/0");else if(!pl.type.is_list(pointer))
return pl.error.type("list",terminals,"DCG/0");pointer.args[1]=dcg.variable;}
rule.body=new Term(",",[rule.body,new Term("=",[last,terminals])]);rule.head=new Term(rule.head.id,rule.head.args.concat([begin,last]));}else{var first_assign=rule.body;if(pl.type.is_term(first_assign)&&first_assign.indicator===",/2")
first_assign=first_assign.args[0];if(pl.type.is_term(first_assign)&&first_assign.indicator==="=/2"&&pl.type.is_variable(first_assign.args[0])&&first_assign.args[0]===begin){begin=first_assign.args[1];rule.body=rule.body.replace(null);}
rule.head=new Term(rule.head.id,rule.head.args.concat([begin,dcg.variable]));}
return rule;}
function body_to_dcg(expr,last,thread){var free;if(pl.type.is_term(expr)&&expr.indicator==="!/0"){free=thread.next_free_variable();return{value:new Term(",",[expr,new Term("=",[last,free])]),variable:free,error:false};}else if(pl.type.is_term(expr)&&expr.indicator==="\\+/1"){var left=body_to_dcg(expr.args[0],last,thread);if(left.error)return left;return{value:new Term(expr.id,[left.value]),variable:last,error:false};}else if(pl.type.is_term(expr)&&(expr.indicator===",/2"||expr.indicator==="->/2")){var left=body_to_dcg(expr.args[0],last,thread);if(left.error)return left;var right=body_to_dcg(expr.args[1],left.variable,thread);if(right.error)return right;return{value:new Term(expr.id,[left.value,right.value]),variable:right.variable,error:false};}else if(pl.type.is_term(expr)&&expr.indicator===";/2"){var left=body_to_dcg(expr.args[0],last,thread);if(left.error)return left;var right=body_to_dcg(expr.args[1],last,thread);if(right.error)return right;return{value:new Term(",",[new Term(";",[left.value,right.value]),new Term("=",[left.variable,right.variable])]),variable:right.variable,error:false};}else if(pl.type.is_term(expr)&&expr.indicator==="{}/1"){free=thread.next_free_variable();return{value:new Term(",",[expr.args[0],new Term("=",[last,free])]),variable:free,error:false};}else if(pl.type.is_empty_list(expr)){return{value:new Term("true",[]),variable:last,error:false};}else if(pl.type.is_list(expr)){free=thread.next_free_variable();var pointer=expr;var prev;while(pointer.indicator==="./2"){prev=pointer;pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){return{value:pl.error.instantiation("DCG/0"),variable:last,error:true};}else if(!pl.type.is_empty_list(pointer)){return{value:pl.error.type("list",expr,"DCG/0"),variable:last,error:true};}else{prev.args[1]=free;return{value:new Term("=",[last,expr]),variable:free,error:false};}}else if(pl.type.is_callable(expr)){free=thread.next_free_variable();expr=new Term(expr.id,expr.args.concat([last,free]));return{value:expr,variable:free,error:false};}else{return{value:pl.error.type("callable",expr,"DCG/0"),variable:last,error:true};}}
function body_conversion(expr){if(pl.type.is_variable(expr))
return new Term("call",[expr]);else if(pl.type.is_term(expr)&&[",/2",";/2","->/2"].indexOf(expr.indicator)!==-1)
return new Term(expr.id,[body_conversion(expr.args[0]),body_conversion(expr.args[1])]);return expr;}
function arrayToList(array,cons){var list=cons?cons:new Term("[]",[]);for(var i=array.length-1;i>=0;i--)
list=new Term(".",[array[i],list]);return list;}
function remove(array,element){for(var i=array.length-1;i>=0;i--){if(array[i]===element){array.splice(i,1);}}}
function nub(array){var seen={};var unique=[];for(var i=0;i<array.length;i++){if(!(array[i]in seen)){unique.push(array[i]);seen[array[i]]=true;}}
return unique;}
function retract(thread,point,indicator,rule){if(thread.session.rules[indicator]!==null){for(var i=0;i<thread.session.rules[indicator].length;i++){if(thread.session.rules[indicator][i]===rule){thread.session.rules[indicator].splice(i,1);thread.success(point);break;}}}}
function callN(n){return function(thread,point,atom){var closure=atom.args[0],args=atom.args.slice(1,n);if(pl.type.is_variable(closure)){thread.throw_error(pl.error.instantiation(thread.level));}else if(!pl.type.is_callable(closure)){thread.throw_error(pl.error.type("callable",closure,thread.level));}else{var goal=new Term(closure.id,closure.args.concat(args));thread.prepend([new State(point.goal.replace(goal),point.substitution,point)]);}};}
function str_indicator(str){for(var i=str.length-1;i>=0;i--)
if(str.charAt(i)==="/")
return new Term("/",[new Term(str.substring(0,i)),new Num(parseInt(str.substring(i+1)),false)]);}
function Var(id){this.id=id;}
function Num(value,is_float){this.is_float=is_float!==undefined?is_float:parseInt(value)!==value;this.value=this.is_float?value:parseInt(value);}
var term_ref=0;function Term(id,args,ref){term_ref++;this.ref=ref||term_ref;this.id=id;this.args=args||[];this.indicator=id+"/"+this.args.length;}
var stream_ref=0;function Stream(stream,mode,alias,type,reposition,eof_action){this.id=stream_ref++;this.stream=stream;this.mode=mode;this.alias=alias;this.type=type!==undefined?type:"text";this.reposition=reposition!==undefined?reposition:true;this.eof_action=eof_action!==undefined?eof_action:"eof_code";this.position=this.mode==="append"?"end_of_stream":0;this.output=this.mode==="write"||this.mode==="append";this.input=this.mode==="read";}
function Substitution(links,attrs){links=links||{};attrs=attrs||{};this.links=links;this.attrs=attrs;}
function State(goal,subs,parent){subs=subs||new Substitution();parent=parent||null;this.goal=goal;this.substitution=subs;this.parent=parent;}
function Rule(head,body,dynamic){this.head=head;this.body=body;this.dynamic=dynamic?dynamic:false;}
function Session(limit,output){var self=this;limit=limit===undefined||limit<=0?1000:limit;this.rules={};this.src_predicates={};this.rename=0;this.modules=[];this.total_threads=1;this.renamed_variables={};this.public_predicates={};this.multifile_predicates={};this.limit=limit;this.streams={"user_input":new Stream(nodejs_flag?nodejs_user_input:tau_user_input,"read","user_input","text",false,"reset"),"user_output":new Stream(nodejs_flag?nodejs_user_output:output?{put:function(text,arg){output(text);return true;},flush:function(){return true},}:tau_user_output,"write","user_output","text",false,"eof_code")};this.file_system=nodejs_flag?nodejs_file_system:tau_file_system;this.standard_input=this.streams["user_input"];this.standard_output=this.streams["user_output"];this.current_input=this.streams["user_input"];this.current_output=this.streams["user_output"];this.working_directory="/";this.format_success=function(state){return state.substitution;};this.format_error=function(state){return state.goal;};this.flag={bounded:pl.flag.bounded.value,max_integer:pl.flag.max_integer.value,min_integer:pl.flag.min_integer.value,integer_rounding_function:pl.flag.integer_rounding_function.value,char_conversion:pl.flag.char_conversion.value,debug:pl.flag.debug.value,max_arity:pl.flag.max_arity.value,unknown:pl.flag.unknown.value,double_quotes:pl.flag.double_quotes.value,occurs_check:pl.flag.occurs_check.value,dialect:pl.flag.dialect.value,version_data:pl.flag.version_data.value,nodejs:pl.flag.nodejs.value,argv:pl.flag.argv.value};this.__loaded_modules=[];this.__char_conversion={};this.__operators={1200:{":-":["fx","xfx"],"-->":["xfx"],"?-":["fx"]},1100:{";":["xfy"]},1050:{"->":["xfy"]},1000:{",":["xfy"]},900:{"\\+":["fy"]},700:{"=":["xfx"],"\\=":["xfx"],"==":["xfx"],"\\==":["xfx"],"@<":["xfx"],"@=<":["xfx"],"@>":["xfx"],"@>=":["xfx"],"=..":["xfx"],"is":["xfx"],"=:=":["xfx"],"=\\=":["xfx"],"<":["xfx"],"=<":["xfx"],">":["xfx"],">=":["xfx"]},600:{":":["xfy"]},500:{"+":["yfx"],"-":["yfx"],"/\\":["yfx"],"\\/":["yfx"]},400:{"*":["yfx"],"/":["yfx"],"//":["yfx"],"rem":["yfx"],"mod":["yfx"],"<<":["yfx"],">>":["yfx"],"div":["yfx"]},200:{"**":["xfx"],"^":["xfy"],"-":["fy"],"+":["fy"],"\\":["fy"]}};this.thread=new Thread(this);}
function Thread(session){this.epoch=Date.now();this.session=session;this.session.total_threads++;this.format_success=session.format_success;this.format_error=session.format_error;this.total_steps=0;this.cpu_time=0;this.cpu_time_last=0;this.points=[];this.debugger=false;this.debugger_states=[];this.level="top_level/0";this.current_limit=this.session.limit;this.warnings=[];this.__calls=[];this.__goal_expansion=false;}
function Module(id,rules,exports){this.id=id;this.rules=rules;this.exports=exports;pl.module[id]=this;}
Module.prototype.exports_predicate=function(indicator){return this.exports.indexOf(indicator)!==-1;};Var.prototype.unify=function(obj,occurs_check){if(occurs_check&&indexOf(obj.variables(),this.id)!==-1&&!pl.type.is_variable(obj)){return null;}
var links={};links[this.id]=obj;return new Substitution(links);};Num.prototype.unify=function(obj,_){if(pl.type.is_number(obj)&&this.value===obj.value&&this.is_float===obj.is_float){return new Substitution();}
return null;};Term.prototype.unify=function(obj,occurs_check){if(pl.type.is_term(obj)&&this.indicator===obj.indicator){var subs=new Substitution();for(var i=0;i<this.args.length;i++){var mgu=pl.unify(this.args[i].apply(subs),obj.args[i].apply(subs),occurs_check);if(mgu===null)
return null;for(var x in mgu.links)
subs.links[x]=mgu.links[x];subs=subs.apply(mgu);}
return subs;}
return null;};Stream.prototype.unify=function(obj,occurs_check){if(pl.type.is_stream(obj)&&this.id===obj.id){return new Substitution();}
return null;};Var.prototype.toString=function(_){return this.id;};Num.prototype.toString=function(_){var str=this.value.toString();var e=str.indexOf("e");if(e!==-1){if(str.indexOf(".")!==-1)
return str
else
return str.replace("e",".0e");}
return this.is_float&&indexOf(str,".")===-1?this.value+".0":str;};Term.prototype.toString=function(options,priority,from){options=!options?{}:options;options.quoted=options.quoted===undefined?true:options.quoted;options.ignore_ops=options.ignore_ops===undefined?false:options.ignore_ops;options.numbervars=options.numbervars===undefined?false:options.numbervars;priority=priority===undefined?{priority:999,class:"",indicator:""}:priority;from=from===undefined?"":from;if(options.numbervars&&this.indicator==="$VAR/1"&&pl.type.is_integer(this.args[0])&&this.args[0].value>=0){var i=this.args[0].value;var number=Math.floor(i/26);var letter=i%26;return"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[letter]+(number!==0?number:"");}
switch(this.indicator){case"[]/0":case"{}/0":case"!/0":return this.id;case"{}/1":return"{"+this.args[0].toString(options)+"}";case"./2":if(options.ignore_ops===false){var list="["+this.args[0].toString(options);var pointer=this.args[1];while(pointer.indicator==="./2"){list+=", "+pointer.args[0].toString(options);pointer=pointer.args[1];}
if(pointer.indicator!=="[]/0"){list+="|"+pointer.toString(options);}
list+="]";return list;}
default:var id=this.id;var operator=options.session?options.session.lookup_operator(this.id,this.args.length):null;if(options.session===undefined||options.ignore_ops||operator===null){if(options.quoted&&!/^(!|;|[a-z][0-9a-zA-Z_]*|[#\$\&\*\+\-\.\/\:\<\=\>\?\@\^\~\\]+)$/.test(id)&&id!=="{}"&&id!=="[]")
id="'"+redoEscape(id)+"'";return id+(this.args.length?"("+map(this.args,function(x){return x.toString(options);}).join(", ")+")":"");}else{var priority_op=parseInt(operator.priority);var priority_arg=parseInt(priority.priority);var cond=priority_op>priority_arg||priority_op===priority_arg&&(operator.class==="xfx"||operator.class==="xfy"&&this.indicator!==priority.indicator||operator.class==="yfx"&&this.indicator!==priority.indicator||this.indicator===priority.indicator&&operator.class==="yfx"&&from==="right"||this.indicator===priority.indicator&&operator.class==="xfy"&&from==="left");operator.indicator=this.indicator;var lpar=cond?"(":"";var rpar=cond?")":"";var space=/^[a-z][0-9a-zA-Z_]*$/.test(id)?" ":"";if(this.args.length===0){return"("+this.id+")";}else if(["fy","fx"].indexOf(operator.class)!==-1){return lpar+id+space+this.args[0].toString(options,operator)+rpar;}else if(["yf","xf"].indexOf(operator.class)!==-1){return lpar+this.args[0].toString(options,operator)+space+id+rpar;}else{return lpar+this.args[0].toString(options,operator,"left")+space+this.id+space+this.args[1].toString(options,operator,"right")+rpar;}}}};Stream.prototype.toString=function(_){return"<stream>("+this.id+")";};Substitution.prototype.toString=function(options){var str="{";for(var link in this.links){if(!this.links.hasOwnProperty(link))continue;if(str!=="{"){str+=", ";}
str+=link+"/"+this.links[link].toString(options);}
str+="}";return str;};State.prototype.toString=function(options){if(this.goal===null){return"<"+this.substitution.toString(options)+">";}else{return"<"+this.goal.toString(options)+", "+this.substitution.toString(options)+">";}};Rule.prototype.toString=function(options){if(!this.body){return this.head.toString(options)+".";}else{return this.head.toString(options,1200,"left")+" :- "+this.body.toString(options,1200,"right")+".";}};Session.prototype.toString=function(options){var str="";for(var i=0;i<this.modules.length;i++){str+=":- use_module(library("+this.modules[i]+")).\n";}
str+="\n";for(var key in this.rules){if(!this.rules.hasOwnProperty(key))continue;for(i=0;i<this.rules[key].length;i++){str+=this.rules[key][i].toString(options);str+="\n";}}
return str;};Var.prototype.clone=function(){return new Var(this.id);};Num.prototype.clone=function(){return new Num(this.value,this.is_float);};Term.prototype.clone=function(){return new Term(this.id,map(this.args,function(arg){return arg.clone();}));};Stream.prototype.clone=function(){return new Stram(this.stream,this.mode,this.alias,this.type,this.reposition,this.eof_action);};Substitution.prototype.clone=function(){var links={};var attrs={};for(var link in this.links){if(!this.links.hasOwnProperty(link))continue;links[link]=this.links[link].clone();}
for(var attr in this.attrs){if(!this.attrs.hasOwnProperty(attrs))continue;attrs[attr]={};for(var m in this.attrs[attr]){if(!this.attrs[attr].hasOwnProperty(m))continue;attrs[attr][m]=this.attrs[attr][m].clone();}}
return new Substitution(links,attrs);};State.prototype.clone=function(){return new State(this.goal.clone(),this.substitution.clone(),this.parent);};Rule.prototype.clone=function(){return new Rule(this.head.clone(),this.body!==null?this.body.clone():null);};Var.prototype.equals=function(obj){return pl.type.is_variable(obj)&&this.id===obj.id;};Num.prototype.equals=function(obj){return pl.type.is_number(obj)&&this.value===obj.value&&this.is_float===obj.is_float;};Term.prototype.equals=function(obj){if(!pl.type.is_term(obj)||this.indicator!==obj.indicator){return false;}
for(var i=0;i<this.args.length;i++){if(!this.args[i].equals(obj.args[i])){return false;}}
return true;};Stream.prototype.equals=function(obj){return pl.type.is_stream(obj)&&this.id===obj.id;};Substitution.prototype.equals=function(obj){var link;if(!pl.type.is_substitution(obj)){return false;}
for(link in this.links){if(!this.links.hasOwnProperty(link))continue;if(!obj.links[link]||!this.links[link].equals(obj.links[link])){return false;}}
for(link in obj.links){if(!obj.links.hasOwnProperty(link))continue;if(!this.links[link]){return false;}}
return true;};State.prototype.equals=function(obj){return pl.type.is_state(obj)&&this.goal.equals(obj.goal)&&this.substitution.equals(obj.substitution)&&this.parent===obj.parent;};Rule.prototype.equals=function(obj){return pl.type.is_rule(obj)&&this.head.equals(obj.head)&&(this.body===null&&obj.body===null||this.body!==null&&this.body.equals(obj.body));};Var.prototype.rename=function(thread){return thread.get_free_variable(this);};Num.prototype.rename=function(_){return this;};Term.prototype.rename=function(thread){if(this.indicator==="./2"){var arr=[],pointer=this;var last_neq=-1,pointer_neq=null,i=0;while(pointer.indicator==="./2"){var app=pointer.args[0].rename(thread);var cmp=app==pointer.args[0];arr.push(app);pointer=pointer.args[1];if(!cmp){last_neq=i;pointer_neq=pointer;}
i++;}
var list=pointer.rename(thread);var cmp=list==pointer;if(last_neq===-1&&cmp)
return this;var start=cmp?last_neq:arr.length-1;var list=cmp?pointer_neq:list;for(var i=start;i>=0;i--){list=new Term(".",[arr[i],list]);}
return list;}
var eq=true;var args=[];for(var i=0;i<this.args.length;i++){var app=this.args[i].rename(thread);eq=eq&&this.args[i]==app;args.push(app);}
return new Term(this.id,args);};Stream.prototype.rename=function(thread){return this;};Rule.prototype.rename=function(thread){return new Rule(this.head.rename(thread),this.body!==null?this.body.rename(thread):null);};Var.prototype.variables=function(){return[this.id];};Num.prototype.variables=function(){return[];};Term.prototype.variables=function(){return[].concat.apply([],map(this.args,function(arg){return arg.variables();}));};Stream.prototype.variables=function(){return[];};Rule.prototype.variables=function(){if(this.body===null){return this.head.variables();}else{return this.head.variables().concat(this.body.variables());}};Var.prototype.apply=function(subs){if(subs.lookup(this.id)){return subs.lookup(this.id);}
return this;};Num.prototype.apply=function(_){return this;};Term.prototype.apply=function(subs){if(this.args.length===0)
return this;if(this.indicator==="./2"){var arr=[],pointer=this;var last_neq=-1,pointer_neq=null,i=0;while(pointer.indicator==="./2"){var app=pointer.args[0].apply(subs);var cmp=app==pointer.args[0];arr.push(app);pointer=pointer.args[1];if(!cmp){last_neq=i;pointer_neq=pointer;}
i++;}
var list=pointer.apply(subs);var cmp=list==pointer;if(last_neq===-1&&cmp)
return this;var start=cmp?last_neq:arr.length-1;var list=cmp?pointer_neq:list;for(var i=start;i>=0;i--){list=new Term(".",[arr[i],list]);}
return list;}
var eq=true;var args=[];for(var i=0;i<this.args.length;i++){var app=this.args[i].apply(subs);eq=eq&&this.args[i]==app;args.push(app);}
if(eq)
return this;return new Term(this.id,args,this.ref);};Stream.prototype.apply=function(_){return this;};Rule.prototype.apply=function(subs){return new Rule(this.head.apply(subs),this.body!==null?this.body.apply(subs):null);};Substitution.prototype.apply=function(subs){var link,links={},attr,attrs={},m;for(link in this.links){if(!this.links.hasOwnProperty(link))continue;links[link]=this.links[link].apply(subs);}
for(attr in this.attrs){if(!this.attrs.hasOwnProperty(attr))continue;attrs[attr]={};for(m in this.attrs[attr]){if(!this.attrs[attr].hasOwnProperty(m))continue;attrs[attr][m]=this.attrs[attr][m].apply(subs);}}
return new Substitution(links,attrs);};Term.prototype.select=function(){var pointer=this;while(pointer.indicator===",/2")
pointer=pointer.args[0];return pointer;};Term.prototype.replace=function(expr){if(this.indicator===",/2"){if(this.args[0].indicator===",/2"){return new Term(",",[this.args[0].replace(expr),this.args[1]]);}else{return expr===null?this.args[1]:new Term(",",[expr,this.args[1]]);}}else{return expr;}};Term.prototype.search=function(expr){if(this==expr||this.ref===expr.ref)
return true;for(var i=0;i<this.args.length;i++)
if(pl.type.is_term(this.args[i])&&this.args[i].search(expr))
return true;return false;};Session.prototype.get_current_input=function(){return this.current_input;};Thread.prototype.get_current_input=function(){return this.session.get_current_input();};Session.prototype.get_current_output=function(){return this.current_output;};Thread.prototype.get_current_output=function(){return this.session.get_current_output();};Session.prototype.set_current_input=function(input){this.current_input=input;};Thread.prototype.set_current_input=function(input){return this.session.set_current_input(input);};Session.prototype.set_current_output=function(output){this.current_output=output;};Thread.prototype.set_current_output=function(output){return this.session.set_current_output(output);};Session.prototype.get_stream_by_alias=function(alias){return this.streams[alias];};Thread.prototype.get_stream_by_alias=function(alias){return this.session.get_stream_by_alias(alias);};Session.prototype.file_system_open=function(path,type,mode){if(this.get_flag("nodejs").indicator==="false/0")
path=cd(this.working_directory,path);return this.file_system.open(path,type,mode);};Thread.prototype.file_system_open=function(path,type,mode){return this.session.file_system_open(path,type,mode);};Session.prototype.get_char_conversion=function(char){return this.__char_conversion[char]||char;};Thread.prototype.get_char_conversion=function(char){return this.session.get_char_conversion(char);};Session.prototype.parse=function(string){return this.thread.parse(string);};Thread.prototype.parse=function(string){var tokenizer=new Tokenizer(this);tokenizer.new_text(string);var tokens=tokenizer.get_tokens();if(tokens===null)
return false;var expr=parseExpr(this,tokens,0,this.__get_max_priority(),false);if(expr.len!==tokens.length)
return false;return{value:expr.value,expr:expr,tokens:tokens};};Session.prototype.get_flag=function(flag){return this.flag[flag];};Thread.prototype.get_flag=function(flag){return this.session.get_flag(flag);};Session.prototype.add_rule=function(rule,options){options=options?options:{};options.from=options.from?options.from:"$tau-js";this.src_predicates[rule.head.indicator]=options.from;if(!this.rules[rule.head.indicator]){this.rules[rule.head.indicator]=[];}
this.rules[rule.head.indicator].push(rule);if(!this.public_predicates.hasOwnProperty(rule.head.indicator))
this.public_predicates[rule.head.indicator]=false;return true;};Thread.prototype.add_rule=function(rule,options){return this.session.add_rule(rule,options);};Session.prototype.run_directive=function(directive){this.thread.run_directive(directive);};Thread.prototype.run_directive=function(directive){if(pl.type.is_directive(directive)){if(pl.directive[directive.indicator])
pl.directive[directive.indicator](this,directive);else
pl.directive[directive.id+"/*"](this,directive);return true;}
return false;};Session.prototype.__get_max_priority=function(){return"1200";};Thread.prototype.__get_max_priority=function(){return this.session.__get_max_priority();};Session.prototype.__get_next_priority=function(priority){var max=0;priority=parseInt(priority);for(var key in this.__operators){if(!this.__operators.hasOwnProperty(key))continue;var n=parseInt(key);if(n>max&&n<priority)max=n;}
return max.toString();};Thread.prototype.__get_next_priority=function(priority){return this.session.__get_next_priority(priority);};Session.prototype.__lookup_operator_classes=function(priority,operator){if(this.__operators.hasOwnProperty(priority)&&this.__operators[priority][operator]instanceof Array){return this.__operators[priority][operator]||false;}
return false;};Thread.prototype.__lookup_operator_classes=function(priority,operator){return this.session.__lookup_operator_classes(priority,operator);};Session.prototype.lookup_operator=function(name,arity){for(var p in this.__operators)
if(this.__operators[p][name])
for(var i=0;i<this.__operators[p][name].length;i++)
if(arity===0||this.__operators[p][name][i].length===arity+1)
return{priority:p,class:this.__operators[p][name][i]};return null;};Thread.prototype.lookup_operator=function(name,arity){return this.session.lookup_operator(name,arity);};Session.prototype.throw_warning=function(warning){this.thread.throw_warning(warning);};Thread.prototype.throw_warning=function(warning){this.warnings.push(warning);};Session.prototype.get_warnings=function(){return this.thread.get_warnings();};Thread.prototype.get_warnings=function(){return this.warnings;};Session.prototype.add_goal=function(goal,unique){this.thread.add_goal(goal,unique);};Thread.prototype.add_goal=function(goal,unique,parent){parent=parent?parent:null;if(unique===true)
this.points=[];var vars=goal.variables();var links={};for(var i=0;i<vars.length;i++)
links[vars[i]]=new Var(vars[i]);this.points.push(new State(goal,new Substitution(links),parent));};Session.prototype.consult=function(program,options){return this.thread.consult(program,options);};Thread.prototype.consult=function(program,options){var string="";if(typeof program==="string"){string=program;var len=string.length;if(this.get_flag("nodejs").indicator==="false/0"&&program!=""&&document.getElementById(string)){var script=document.getElementById(string);var type=script.getAttribute("type");if(type!==null&&type.replace(/ /g,"").toLowerCase()==="text/prolog"){string=script.text;}}else if(this.get_flag("nodejs").indicator==="true/0"){var fs=require("fs");const isFile=fs.existsSync(program);if(isFile)string=fs.readFileSync(program).toString();else string=program;}else if(program!=""&&!(/\s/.test(program))){try{var xhttp=new XMLHttpRequest();xhttp.onreadystatechange=function(){if(this.readyState==4&&this.status==200)
string=xhttp.responseText;}
xhttp.open("GET",program,false);xhttp.send();}catch(ex){}}}else if(program.nodeName){switch(program.nodeName.toLowerCase()){case"input":case"textarea":string=program.value;break;default:string=program.innerHTML;break;}}else{return false;}
this.warnings=[];return parseProgram(this,string,options);};Session.prototype.query=function(string){return this.thread.query(string);};Thread.prototype.query=function(string){this.points=[];this.debugger_states=[];return parseQuery(this,string);};Session.prototype.head_point=function(){return this.thread.head_point();};Thread.prototype.head_point=function(){return this.points[this.points.length-1];};Session.prototype.get_free_variable=function(variable){return this.thread.get_free_variable(variable);};Thread.prototype.get_free_variable=function(variable){var variables=[];if(variable.id==="_"||this.session.renamed_variables[variable.id]===undefined){this.session.rename++;if(this.current_point)
variables=this.current_point.substitution.domain();while(indexOf(variables,pl.format_variable(this.session.rename))!==-1){this.session.rename++;}
if(variable.id==="_"){return new Var(pl.format_variable(this.session.rename));}else{this.session.renamed_variables[variable.id]=pl.format_variable(this.session.rename);}}
return new Var(this.session.renamed_variables[variable.id]);};Session.prototype.next_free_variable=function(){return this.thread.next_free_variable();};Thread.prototype.next_free_variable=function(){this.session.rename++;var variables=[];if(this.current_point)
variables=this.current_point.substitution.domain();while(indexOf(variables,pl.format_variable(this.session.rename))!==-1){this.session.rename++;}
return new Var(pl.format_variable(this.session.rename));};Session.prototype.is_public_predicate=function(indicator){return!this.public_predicates.hasOwnProperty(indicator)||this.public_predicates[indicator]===true;};Thread.prototype.is_public_predicate=function(indicator){return this.session.is_public_predicate(indicator);};Session.prototype.is_multifile_predicate=function(indicator){return this.multifile_predicates.hasOwnProperty(indicator)&&this.multifile_predicates[indicator]===true;};Thread.prototype.is_multifile_predicate=function(indicator){return this.session.is_multifile_predicate(indicator);};Session.prototype.prepend=function(states){return this.thread.prepend(states);};Thread.prototype.prepend=function(states){for(var i=states.length-1;i>=0;i--)
this.points.push(states[i]);};Session.prototype.success=function(point,parent){return this.thread.success(point,parent);}
Thread.prototype.success=function(point,parent){var parent=typeof parent==="undefined"?point:parent;this.prepend([new State(point.goal.replace(null),point.substitution,parent)]);};Session.prototype.throw_error=function(error){return this.thread.throw_error(error);};Thread.prototype.throw_error=function(error){this.prepend([new State(new Term("throw",[error]),new Substitution(),null,null)]);};Session.prototype.step_rule=function(mod,atom){return this.thread.step_rule(mod,atom);}
Thread.prototype.step_rule=function(mod,atom){var name=atom.indicator;if(mod==="user")
mod=null;if(mod===null&&this.session.rules.hasOwnProperty(name))
return this.session.rules[name];var modules=mod===null?this.session.modules:(indexOf(this.session.modules,mod)===-1?[]:[mod]);for(var i=0;i<modules.length;i++){var module=pl.module[modules[i]];if(module.rules.hasOwnProperty(name)&&(module.rules.hasOwnProperty(this.level)||module.exports_predicate(name)))
return pl.module[modules[i]].rules[name];}
return null;};Session.prototype.step=function(){return this.thread.step();}
Thread.prototype.step=function(){if(this.points.length===0){return;}
var asyn=false;var point=this.points.pop();this.current_point=point;if(this.debugger)
this.debugger_states.push(point);if(pl.type.is_term(point.goal)){var atom=point.goal.select();var mod=null;var states=[];if(atom!==null){this.total_steps++;var level=point;while(level.parent!==null&&level.parent.goal.search(atom))
level=level.parent;this.level=level.parent===null?"top_level/0":level.parent.goal.select().indicator;if(pl.type.is_term(atom)&&atom.indicator===":/2"){mod=atom.args[0].id;atom=atom.args[1];atom.from_module=mod;}
if((mod===null||atom.indicator==="listing/0"||atom.indicator==="listing/1")&&pl.type.is_builtin(atom)){this.__call_indicator=atom.indicator;asyn=pl.predicate[atom.indicator](this,point,atom);}else{var srule=this.step_rule(mod,atom);if(srule===null){if(!this.session.rules.hasOwnProperty(atom.indicator)){if(this.get_flag("unknown").id==="error"){this.throw_error(pl.error.existence("procedure",atom.indicator,this.level));}else if(this.get_flag("unknown").id==="warning"){this.throw_warning("unknown procedure "+atom.indicator+" (from "+this.level+")");}}}else if(srule instanceof Function){asyn=srule(this,point,atom);}else{if(this.__goal_expansion&&atom.indicator==="goal_expansion/2")
srule=srule.concat(pl.predicate["goal_expansion/2"]);for(var _rule in srule){if(!srule.hasOwnProperty(_rule))continue;var rule=srule[_rule];this.session.renamed_variables={};rule=rule.rename(this);var occurs_check=this.get_flag("occurs_check").indicator==="true/0";var state=new State();var mgu=pl.unify(atom,rule.head,occurs_check);if(mgu!==null){state.goal=point.goal.replace(rule.body);if(state.goal!==null){state.goal=state.goal.apply(mgu);}
state.substitution=point.substitution.apply(mgu);state.parent=point;states.push(state);}}
this.prepend(states);}}}}else if(pl.type.is_variable(point.goal)){this.throw_error(pl.error.instantiation(this.level));}else{this.throw_error(pl.error.type("callable",point.goal,this.level));}
return asyn;};Session.prototype.answer=function(success){return this.thread.answer(success);}
Thread.prototype.answer=function(success){success=success||function(_){};this.__calls.push(success);if(this.__calls.length>1){return;}
this.again();};Session.prototype.answers=function(callback,max,after){return this.thread.answers(callback,max,after);}
Thread.prototype.answers=function(callback,max,after){var answers=max||1000;var thread=this;if(max<=0){if(after)
after();return;}
this.answer(function(answer){callback(answer);if(answer!==false){setTimeout(function(){thread.answers(callback,max-1,after);},1);}else if(after){after();}});};Session.prototype.again=function(reset_limit){return this.thread.again(reset_limit);};Thread.prototype.again=function(reset_limit){var answer;var t0=Date.now();while(this.__calls.length>0){this.warnings=[];if(reset_limit!==false)
this.current_limit=this.session.limit;while(this.current_limit>0&&this.points.length>0&&this.head_point().goal!==null&&!pl.type.is_error(this.head_point().goal)){this.current_limit--;if(this.step()===true){return;}}
var t1=Date.now();this.cpu_time_last=t1-t0;this.cpu_time+=this.cpu_time_last;var success=this.__calls.shift();if(this.current_limit<=0){success(null);}else if(this.points.length===0){success(false);}else if(pl.type.is_error(this.head_point().goal)){answer=this.format_error(this.points.pop());this.points=[];success(answer);}else{if(this.debugger)
this.debugger_states.push(this.head_point());answer=this.format_success(this.points.pop());success(answer);}}};Session.prototype.unfold=function(rule){if(rule.body===null)
return false;var head=rule.head;var body=rule.body;var atom=body.select();var thread=new Thread(this);var unfolded=[];thread.add_goal(atom);thread.step();for(var i=thread.points.length-1;i>=0;i--){var point=thread.points[i];var head2=head.apply(point.substitution);var body2=body.replace(point.goal);if(body2!==null)
body2=body2.apply(point.substitution);unfolded.push(new Rule(head2,body2));}
var rules=this.rules[head.indicator];var index=indexOf(rules,rule);if(unfolded.length>0&&index!==-1){rules.splice.apply(rules,[index,1].concat(unfolded));return true;}
return false;};Thread.prototype.unfold=function(rule){return this.session.unfold(rule);};Var.prototype.interpret=function(thread){return pl.error.instantiation(thread.level);};Num.prototype.interpret=function(thread){return this;};Term.prototype.interpret=function(thread){if(pl.type.is_unitary_list(this)){return this.args[0].interpret(thread);}else{return pl.operate(thread,this);}};Var.prototype.compare=function(obj){if(this.id<obj.id){return-1;}else if(this.id>obj.id){return 1;}else{return 0;}};Num.prototype.compare=function(obj){if(this.value===obj.value&&this.is_float===obj.is_float){return 0;}else if(this.value<obj.value||this.value===obj.value&&this.is_float&&!obj.is_float){return-1;}else if(this.value>obj.value){return 1;}};Term.prototype.compare=function(obj){if(this.args.length<obj.args.length||this.args.length===obj.args.length&&this.id<obj.id){return-1;}else if(this.args.length>obj.args.length||this.args.length===obj.args.length&&this.id>obj.id){return 1;}else{for(var i=0;i<this.args.length;i++){var arg=pl.compare(this.args[i],obj.args[i]);if(arg!==0){return arg;}}
return 0;}};Substitution.prototype.lookup=function(variable){if(this.links[variable]){return this.links[variable];}else{return null;}};Substitution.prototype.filter=function(predicate){var links={};for(var id in this.links){if(!this.links.hasOwnProperty(id))continue;var value=this.links[id];if(predicate(id,value)){links[id]=value;}}
return new Substitution(links,this.attrs);};Substitution.prototype.exclude=function(variables){var links={};for(var variable in this.links){if(!this.links.hasOwnProperty(variable))continue;if(indexOf(variables,variable)===-1){links[variable]=this.links[variable];}}
return new Substitution(links,this.attrs);};Substitution.prototype.add=function(variable,value){this.links[variable]=value;};Substitution.prototype.domain=function(plain){var f=plain===true?function(x){return x;}:function(x){return new Var(x);};var vars=[];for(var x in this.links)
vars.push(f(x));return vars;};Substitution.prototype.get_attribute=function(variable,module){if(this.attrs[variable])
return this.attrs[variable][module];}
Substitution.prototype.set_attribute=function(variable,module,value){var subs=new Substitution(this.links);for(var v in this.attrs){if(v===variable){subs.attrs[v]={};for(var m in this.attrs[v]){subs.attrs[v][m]=this.attrs[v][m];}}else{subs.attrs[v]=this.attrs[v];}}
if(!subs.attrs[variable]){subs.attrs[variable]={};}
subs.attrs[variable][module]=value;return subs;}
Substitution.prototype.has_attributes=function(variable){return this.attrs[variable]&&this.attrs[variable]!=={};}
Var.prototype.compile=function(){return'new pl.type.Var("'+this.id.toString()+'")';};Num.prototype.compile=function(){return'new pl.type.Num('+this.value.toString()+', '+this.is_float.toString()+')';};Term.prototype.compile=function(){return'new pl.type.Term("'+this.id.replace(/"/g,'\\"')+'", ['+map(this.args,function(arg){return arg.compile();})+'])';};Rule.prototype.compile=function(){return'new pl.type.Rule('+this.head.compile()+', '+(this.body===null?'null':this.body.compile())+')';};Session.prototype.compile=function(){var str,obj=[],rules;for(var _indicator in this.rules){if(!this.rules.hasOwnProperty(_indicator))continue;var indicator=this.rules[_indicator];rules=[];str="\""+_indicator+"\": [";for(var i=0;i<indicator.length;i++){rules.push(indicator[i].compile());}
str+=rules.join();str+="]";obj.push(str);}
return"{"+obj.join()+"};";};Var.prototype.toJavaScript=function(){return this.toString();};Num.prototype.toJavaScript=function(){return this.value;};Term.prototype.toJavaScript=function(){if(this.args.length===0&&this.indicator!=="[]/0"){return this.toString();}else if(pl.type.is_list(this)){var all_obj=true;var arr=[];var obj={};var pointer=this;var value;while(pointer.indicator==="./2"){value=pointer.args[0].toJavaScript();arr.push(value);all_obj=all_obj&&pl.type.is_term(pointer.args[0])&&pointer.args[0].indicator==="-/2"&&pl.type.is_atom(pointer.args[0].args[0]);if(all_obj)
obj[pointer.args[0].args[0].id]=pointer.args[0].args[1].toJavaScript();pointer=pointer.args[1];}
if(pointer.indicator==="[]/0")
return all_obj&&arr.length>0?obj:arr;}
return this.toString();};Rule.prototype.singleton_variables=function(){var variables=this.head.variables();var count={};var singleton=[];if(this.body!==null)
variables=variables.concat(this.body.variables());for(var i=0;i<variables.length;i++){if(count[variables[i]]===undefined)
count[variables[i]]=0;count[variables[i]]++;}
for(var key in count)
if(key!=="_"&&count[key]===1)
singleton.push(key);return singleton;};var nodejs_flag=typeof process!=='undefined'&&!process.browser
var nodejs_arguments=nodejs_flag?arrayToList(map(process.argv.slice(1),function(arg){return new Term(arg);})):new Term("[]",[]);var pl={__env:nodejs_flag?global:window,module:{},version:version,parser:{tokenizer:Tokenizer,expression:parseExpr},utils:{str_indicator:str_indicator,codePointAt:codePointAt,fromCodePoint:fromCodePoint,cd:cd},statistics:{getCountTerms:function(){return term_ref;}},fromJavaScript:{test:{boolean:function(obj,tobj){return obj===true||obj===false;},number:function(obj,tobj){return typeof obj==="number";},string:function(obj,tobj){return typeof obj==="string";},list:function(obj,tobj){return obj instanceof Array;},variable:function(obj,tobj){return obj===undefined;},object:function(obj,tobj){tobj=tobj===undefined?false:tobj;return tobj&&!(obj instanceof Array)&&typeof obj==="object";},any:function(_,tobj){return true;}},conversion:{boolean:function(obj,tobj){return new Term(obj?"true":"false",[]);},number:function(obj,tobj){return new Num(obj,obj%1!==0);},string:function(obj,tobj){return new Term(obj,[]);},list:function(obj,tobj){tobj=tobj===undefined?false:tobj;var arr=[];var elem;for(var i=0;i<obj.length;i++){elem=pl.fromJavaScript.apply(obj[i],tobj);if(elem===undefined)
return undefined;arr.push(elem);}
return arrayToList(arr);},variable:function(obj,tobj){return new Var("_");},object:function(obj,tobj){tobj=tobj===undefined?false:tobj;var list=new Term("[]",[]);var arr=[];for(var prop in obj){if(!obj.hasOwnProperty(prop))continue;arr.push(new Term("-",[pl.fromJavaScript.apply(prop,tobj),pl.fromJavaScript.apply(obj[prop],tobj)]));}
return arrayToList(arr);},any:function(obj,tobj){return undefined;}},apply:function(obj,tobj){tobj=tobj===undefined?false:tobj;for(var i in pl.fromJavaScript.test)
if(i!=="any"&&pl.fromJavaScript.test[i](obj,tobj))
return pl.fromJavaScript.conversion[i](obj,tobj);return pl.fromJavaScript.conversion.any(obj,tobj);}},type:{Var:Var,Num:Num,Term:Term,Rule:Rule,State:State,Stream:Stream,Module:Module,Thread:Thread,Session:Session,Substitution:Substitution,File:TauFile,Directory:TauDirectory,order:[Var,Num,Term,Stream],compare:function(x,y){var ord_x=indexOf(pl.type.order,x.constructor);var ord_y=indexOf(pl.type.order,y.constructor);if(ord_x<ord_y){return-1;}else if(ord_x>ord_y){return 1;}else{if(x.constructor===Num)
if(x.is_float&&y.is_float)
return 0;else if(x.is_float)
return-1;else if(y.is_float)
return 1;return 0;}},is_substitution:function(obj){return obj instanceof Substitution;},is_state:function(obj){return obj instanceof State;},is_rule:function(obj){return obj instanceof Rule;},is_variable:function(obj){return obj instanceof Var;},is_stream:function(obj){return obj instanceof Stream;},is_anonymous_var:function(obj){return obj instanceof Var&&obj.id==="_";},is_callable:function(obj){return obj instanceof Term;},is_number:function(obj){return obj instanceof Num;},is_integer:function(obj){return obj instanceof Num&&!obj.is_float;},is_float:function(obj){return obj instanceof Num&&obj.is_float;},is_term:function(obj){return obj instanceof Term;},is_atom:function(obj){return obj instanceof Term&&obj.args.length===0;},is_ground:function(obj){if(obj instanceof Var)return false;if(obj instanceof Term)
for(var i=0;i<obj.args.length;i++)
if(!pl.type.is_ground(obj.args[i]))
return false;return true;},is_atomic:function(obj){return obj instanceof Term&&obj.args.length===0||obj instanceof Num;},is_compound:function(obj){return obj instanceof Term&&obj.args.length>0;},is_list:function(obj){return obj instanceof Term&&(obj.indicator==="[]/0"||obj.indicator==="./2");},is_empty_list:function(obj){return obj instanceof Term&&obj.indicator==="[]/0";},is_non_empty_list:function(obj){return obj instanceof Term&&obj.indicator==="./2";},is_fully_list:function(obj){while(obj instanceof Term&&obj.indicator==="./2"){obj=obj.args[1];}
return obj instanceof Var||obj instanceof Term&&obj.indicator==="[]/0";},is_instantiated_list:function(obj){while(obj instanceof Term&&obj.indicator==="./2"){obj=obj.args[1];}
return obj instanceof Term&&obj.indicator==="[]/0";},is_unitary_list:function(obj){return obj instanceof Term&&obj.indicator==="./2"&&obj.args[1]instanceof Term&&obj.args[1].indicator==="[]/0";},is_character:function(obj){return obj instanceof Term&&(obj.id.length===1||obj.id.length>0&&obj.id.length<=2&&codePointAt(obj.id,0)>=65536);},is_character_code:function(obj){return obj instanceof Num&&!obj.is_float&&obj.value>=0&&obj.value<=1114111;},is_byte:function(obj){return obj instanceof Num&&!obj.is_float&&obj.value>=0&&obj.value<=255;},is_operator:function(obj){return obj instanceof Term&&pl.arithmetic.evaluation[obj.indicator];},is_directive:function(obj){return obj instanceof Term&&(pl.directive[obj.indicator]!==undefined||pl.directive[obj.id+"/*"]!==undefined);},is_builtin:function(obj){return obj instanceof Term&&pl.predicate[obj.indicator]!==undefined&&obj.indicator!=="goal_expansion/2";},is_error:function(obj){return obj instanceof Term&&obj.indicator==="throw/1";},is_predicate_indicator:function(obj){return obj instanceof Term&&obj.indicator==="//2"&&obj.args[0]instanceof Term&&obj.args[0].args.length===0&&obj.args[1]instanceof Num&&obj.args[1].is_float===false;},is_flag:function(obj){return obj instanceof Term&&obj.args.length===0&&pl.flag[obj.id]!==undefined;},is_value_flag:function(flag,obj){if(!pl.type.is_flag(flag))return false;for(var value in pl.flag[flag.id].allowed){if(!pl.flag[flag.id].allowed.hasOwnProperty(value))continue;if(pl.flag[flag.id].allowed[value].equals(obj))return true;}
return false;},is_io_mode:function(obj){return pl.type.is_atom(obj)&&["read","write","append"].indexOf(obj.id)!==-1;},is_stream_option:function(obj){return pl.type.is_term(obj)&&(obj.indicator==="alias/1"&&pl.type.is_atom(obj.args[0])||obj.indicator==="reposition/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="true"||obj.args[0].id==="false")||obj.indicator==="type/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="text"||obj.args[0].id==="binary")||obj.indicator==="eof_action/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="error"||obj.args[0].id==="eof_code"||obj.args[0].id==="reset"));},is_stream_position:function(obj){return pl.type.is_integer(obj)&&obj.value>=0||pl.type.is_atom(obj)&&(obj.id==="end_of_stream"||obj.id==="past_end_of_stream");},is_stream_property:function(obj){return pl.type.is_term(obj)&&(obj.indicator==="input/0"||obj.indicator==="output/0"||obj.indicator==="alias/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0]))||obj.indicator==="file_name/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0]))||obj.indicator==="position/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_stream_position(obj.args[0]))||obj.indicator==="reposition/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="true"||obj.args[0].id==="false"))||obj.indicator==="type/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="text"||obj.args[0].id==="binary"))||obj.indicator==="mode/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="read"||obj.args[0].id==="write"||obj.args[0].id==="append"))||obj.indicator==="eof_action/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="error"||obj.args[0].id==="eof_code"||obj.args[0].id==="reset"))||obj.indicator==="end_of_stream/1"&&(pl.type.is_variable(obj.args[0])||pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="at"||obj.args[0].id==="past"||obj.args[0].id==="not")));},is_streamable:function(obj){return obj.__proto__.stream!==undefined;},is_read_option:function(obj){return pl.type.is_term(obj)&&["variables/1","variable_names/1","singletons/1"].indexOf(obj.indicator)!==-1;},is_write_option:function(obj){return pl.type.is_term(obj)&&(obj.indicator==="quoted/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="true"||obj.args[0].id==="false")||obj.indicator==="ignore_ops/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="true"||obj.args[0].id==="false")||obj.indicator==="numbervars/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="true"||obj.args[0].id==="false"));},is_close_option:function(obj){return pl.type.is_term(obj)&&obj.indicator==="force/1"&&pl.type.is_atom(obj.args[0])&&(obj.args[0].id==="true"||obj.args[0].id==="false");},is_modifiable_flag:function(obj){return pl.type.is_flag(obj)&&pl.flag[obj.id].changeable;},is_module:function(obj){return obj instanceof Term&&obj.indicator==="library/1"&&obj.args[0]instanceof Term&&obj.args[0].args.length===0&&pl.module[obj.args[0].id]!==undefined;},is_file:function(obj){return obj instanceof TauFile;},is_directory:function(obj){return obj instanceof TauDirectory;}},arithmetic:{evaluation:{"e/0":{type_args:null,type_result:true,fn:function(_){return Math.E;}},"pi/0":{type_args:null,type_result:true,fn:function(_){return Math.PI;}},"tau/0":{type_args:null,type_result:true,fn:function(_){return 2*Math.PI;}},"epsilon/0":{type_args:null,type_result:true,fn:function(_){return Number.EPSILON;}},"+/1":{type_args:null,type_result:null,fn:function(x,_){return x;}},"-/1":{type_args:null,type_result:null,fn:function(x,_){return-x;}},"\\/1":{type_args:false,type_result:false,fn:function(x,_){return~x;}},"abs/1":{type_args:null,type_result:null,fn:function(x,_){return Math.abs(x);}},"sign/1":{type_args:null,type_result:null,fn:function(x,_){return Math.sign(x);}},"float_integer_part/1":{type_args:true,type_result:false,fn:function(x,_){return parseInt(x);}},"float_fractional_part/1":{type_args:true,type_result:true,fn:function(x,_){return x-parseInt(x);}},"float/1":{type_args:
indicators=arrayToList([indicators]);var pointer=indicators;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){indicator=pointer.args[0];if(pl.type.is_variable(indicator)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_compound(indicator)||indicator.indicator!=="//2"){thread.throw_error(pl.error.type("predicate_indicator",indicator,atom.indicator));}else if(pl.type.is_variable(indicator.args[0])||pl.type.is_variable(indicator.args[1])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(indicator.args[0])){thread.throw_error(pl.error.type("atom",indicator.args[0],atom.indicator));}else if(!pl.type.is_integer(indicator.args[1])){thread.throw_error(pl.error.type("integer",indicator.args[1],atom.indicator));}else{var key=indicator.args[0].id+"/"+indicator.args[1].value;thread.session.public_predicates[key]=true;if(!thread.session.rules[key])
thread.session.rules[key]=[];}
pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_term(pointer)||pointer.indicator!=="[]/0"){thread.throw_error(pl.error.type("predicate_indicator",indicator,atom.indicator));}},"dynamic/*":function(thread,atom){for(var i=0;i<atom.args.length;i++){pl.directive["dynamic/1"](thread,new Term("dynamic",[atom.args[i]]));}},"multifile/1":function(thread,atom){var indicator=atom.args[0];if(pl.type.is_variable(indicator)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_compound(indicator)||indicator.indicator!=="//2"){thread.throw_error(pl.error.type("predicate_indicator",indicator,atom.indicator));}else if(pl.type.is_variable(indicator.args[0])||pl.type.is_variable(indicator.args[1])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(indicator.args[0])){thread.throw_error(pl.error.type("atom",indicator.args[0],atom.indicator));}else if(!pl.type.is_integer(indicator.args[1])){thread.throw_error(pl.error.type("integer",indicator.args[1],atom.indicator));}else{thread.session.multifile_predicates[atom.args[0].args[0].id+"/"+atom.args[0].args[1].value]=true;}},"set_prolog_flag/2":function(thread,atom){var flag=atom.args[0],value=atom.args[1];if(pl.type.is_variable(flag)||pl.type.is_variable(value)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(flag)){thread.throw_error(pl.error.type("atom",flag,atom.indicator));}else if(!pl.type.is_flag(flag)){thread.throw_error(pl.error.domain("prolog_flag",flag,atom.indicator));}else if(!pl.type.is_value_flag(flag,value)){thread.throw_error(pl.error.domain("flag_value",new Term("+",[flag,value]),atom.indicator));}else if(!pl.type.is_modifiable_flag(flag)){thread.throw_error(pl.error.permission("modify","flag",flag,atom.indicator));}else{thread.session.flag[flag.id]=value;}},"use_module/1":function(thread,atom){var module=atom.args[0];if(pl.type.is_variable(module)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_term(module)){thread.throw_error(pl.error.type("term",module,atom.indicator));}else{if(pl.type.is_module(module)){var name=module.args[0].id;if(indexOf(thread.session.modules,name)===-1)
thread.session.modules.push(name);}else{}}},"char_conversion/2":function(thread,atom){var inchar=atom.args[0],outchar=atom.args[1];if(pl.type.is_variable(inchar)||pl.type.is_variable(outchar)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_character(inchar)){thread.throw_error(pl.error.type("character",inchar,atom.indicator));}else if(!pl.type.is_character(outchar)){thread.throw_error(pl.error.type("character",outchar,atom.indicator));}else{if(inchar.id===outchar.id){delete thread.session.__char_conversion[inchar.id];}else{thread.session.__char_conversion[inchar.id]=outchar.id;}}},"op/3":function(thread,atom){var priority=atom.args[0],type=atom.args[1],operator=atom.args[2];if(pl.type.is_variable(priority)||pl.type.is_variable(type)||pl.type.is_variable(operator)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_integer(priority)){thread.throw_error(pl.error.type("integer",priority,atom.indicator));}else if(!pl.type.is_atom(type)){thread.throw_error(pl.error.type("atom",type,atom.indicator));}else if(!pl.type.is_atom(operator)){thread.throw_error(pl.error.type("atom",operator,atom.indicator));}else if(priority.value<0||priority.value>1200){thread.throw_error(pl.error.domain("operator_priority",priority,atom.indicator));}else if(operator.id===","){thread.throw_error(pl.error.permission("modify","operator",operator,atom.indicator));}else if(operator.id==="|"&&(priority.value<1001||type.id.length!==3)){thread.throw_error(pl.error.permission("modify","operator",operator,atom.indicator));}else if(["fy","fx","yf","xf","xfx","yfx","xfy"].indexOf(type.id)===-1){thread.throw_error(pl.error.domain("operator_specifier",type,atom.indicator));}else{var fix={prefix:null,infix:null,postfix:null};for(var p in thread.session.__operators){if(!thread.session.__operators.hasOwnProperty(p))continue;var classes=thread.session.__operators[p][operator.id];if(classes){if(indexOf(classes,"fx")!==-1){fix.prefix={priority:p,type:"fx"};}
if(indexOf(classes,"fy")!==-1){fix.prefix={priority:p,type:"fy"};}
if(indexOf(classes,"xf")!==-1){fix.postfix={priority:p,type:"xf"};}
if(indexOf(classes,"yf")!==-1){fix.postfix={priority:p,type:"yf"};}
if(indexOf(classes,"xfx")!==-1){fix.infix={priority:p,type:"xfx"};}
if(indexOf(classes,"xfy")!==-1){fix.infix={priority:p,type:"xfy"};}
if(indexOf(classes,"yfx")!==-1){fix.infix={priority:p,type:"yfx"};}}}
var current_class;switch(type.id){case"fy":case"fx":current_class="prefix";break;case"yf":case"xf":current_class="postfix";break;default:current_class="infix";break;}
if(((fix.prefix&&current_class==="prefix"||fix.postfix&&current_class==="postfix"||fix.infix&&current_class==="infix")&&fix[current_class].type!==type.id||fix.infix&&current_class==="postfix"||fix.postfix&&current_class==="infix")&&priority.value!==0){thread.throw_error(pl.error.permission("create","operator",operator,atom.indicator));}else{if(fix[current_class]){remove(thread.session.__operators[fix[current_class].priority][operator.id],type.id);if(thread.session.__operators[fix[current_class].priority][operator.id].length===0){delete thread.session.__operators[fix[current_class].priority][operator.id];}}
if(priority.value>0){if(!thread.session.__operators[priority.value])thread.session.__operators[priority.value.toString()]={};if(!thread.session.__operators[priority.value][operator.id])thread.session.__operators[priority.value][operator.id]=[];thread.session.__operators[priority.value][operator.id].push(type.id);}
return true;}}}},predicate:{"goal_expansion/2":[new Rule(new Term("goal_expansion",[new Term(",",[new Var("X"),new Var("Y")]),new Term(",",[new Var("X_"),new Var("Y_")])]),new Term(";",[new Term(",",[new Term("goal_expansion",[new Var("X"),new Var("X_")]),new Term(";",[new Term("goal_expansion",[new Var("Y"),new Var("Y_")]),new Term("=",[new Var("Y_"),new Var("Y")])])]),new Term(",",[new Term("=",[new Var("X"),new Var("X_")]),new Term("goal_expansion",[new Var("Y"),new Var("Y_")])])])),new Rule(new Term("goal_expansion",[new Term(";",[new Var("X"),new Var("Y")]),new Term(";",[new Var("X_"),new Var("Y_")])]),new Term(";",[new Term(",",[new Term("goal_expansion",[new Var("X"),new Var("X_")]),new Term(";",[new Term("goal_expansion",[new Var("Y"),new Var("Y_")]),new Term("=",[new Var("Y_"),new Var("Y")])])]),new Term(",",[new Term("=",[new Var("X"),new Var("X_")]),new Term("goal_expansion",[new Var("Y"),new Var("Y_")])])])),new Rule(new Term("goal_expansion",[new Term("->",[new Var("X"),new Var("Y")]),new Term("->",[new Var("X_"),new Var("Y_")])]),new Term(";",[new Term(",",[new Term("goal_expansion",[new Var("X"),new Var("X_")]),new Term(";",[new Term("goal_expansion",[new Var("Y"),new Var("Y_")]),new Term("=",[new Var("Y_"),new Var("Y")])])]),new Term(",",[new Term("=",[new Var("X"),new Var("X_")]),new Term("goal_expansion",[new Var("Y"),new Var("Y_")])])])),new Rule(new Term("goal_expansion",[new Term("catch",[new Var("X"),new Var("Y"),new Var("Z")]),new Term("catch",[new Var("X_"),new Var("Y"),new Var("Z_")])]),new Term(";",[new Term(",",[new Term("goal_expansion",[new Var("X"),new Var("X_")]),new Term(";",[new Term("goal_expansion",[new Var("Z"),new Var("Z_")]),new Term("=",[new Var("Z_"),new Var("Z")])])]),new Term(",",[new Term("=",[new Var("X_"),new Var("X")]),new Term("goal_expansion",[new Var("Z"),new Var("Z_")])])])),new Rule(new Term("goal_expansion",[new Term("\\+",[new Var("X")]),new Term("\\+",[new Var("X_")])]),new Term(",",[new Term("nonvar",[new Var("X")]),new Term("goal_expansion",[new Var("X"),new Var("X_")])])),new Rule(new Term("goal_expansion",[new Term("once",[new Var("X")]),new Term("once",[new Var("X_")])]),new Term(",",[new Term("nonvar",[new Var("X")]),new Term("goal_expansion",[new Var("X"),new Var("X_")])])),new Rule(new Term("goal_expansion",[new Term("findall",[new Var("X"),new Var("Y"),new Var("Z")]),new Term("findall",[new Var("X"),new Var("Y_"),new Var("Z")])]),new Term("goal_expansion",[new Var("Y"),new Var("Y_")])),new Rule(new Term("goal_expansion",[new Term("setof",[new Var("X"),new Var("Y"),new Var("Z")]),new Term("findall",[new Var("X"),new Var("Y_"),new Var("Z")])]),new Term("goal_expansion",[new Var("Y"),new Var("Y_")])),new Rule(new Term("goal_expansion",[new Term("bagof",[new Var("X"),new Var("Y"),new Var("Z")]),new Term("findall",[new Var("X"),new Var("Y_"),new Var("Z")])]),new Term("goal_expansion",[new Var("Y"),new Var("Y_")])),new Rule(new Term("goal_expansion",[new Term("call",[new Var("X")]),new Term("call",[new Var("X_")])]),new Term(",",[new Term("nonvar",[new Var("X")]),new Term("goal_expansion",[new Var("X"),new Var("X_")])])),new Rule(new Term("goal_expansion",[new Term("call",[new Var("X"),new Var("A1")]),new Term("call",[new Var("F_")])]),new Term(",",[new Term("=..",[new Var("F"),new Term(".",[new Var("X"),new Term(".",[new Var("A1"),new Term("[]",[])])])]),new Term("goal_expansion",[new Var("F"),new Var("F_")])])),new Rule(new Term("goal_expansion",[new Term("call",[new Var("X"),new Var("A1"),new Var("A2")]),new Term("call",[new Var("F_")])]),new Term(",",[new Term("=..",[new Var("F"),new Term(".",[new Var("X"),new Term(".",[new Var("A1"),new Term(".",[new Var("A2"),new Term("[]",[])])])])]),new Term("goal_expansion",[new Var("F"),new Var("F_")])])),new Rule(new Term("goal_expansion",[new Term("call",[new Var("X"),new Var("A1"),new Var("A2"),new Var("A3")]),new Term("call",[new Var("F_")])]),new Term(",",[new Term("=..",[new Var("F"),new Term(".",[new Var("X"),new Term(".",[new Var("A1"),new Term(".",[new Var("A2"),new Term(".",[new Var("A3"),new Term("[]",[])])])]
thread.success(point);},"current_op/3":function(thread,point,atom){var priority=atom.args[0],specifier=atom.args[1],operator=atom.args[2];var points=[];for(var p in thread.session.__operators)
for(var o in thread.session.__operators[p])
for(var i=0;i<thread.session.__operators[p][o].length;i++)
points.push(new State(point.goal.replace(new Term(",",[new Term("=",[new Num(p,false),priority]),new Term(",",[new Term("=",[new Term(thread.session.__operators[p][o][i],[]),specifier]),new Term("=",[new Term(o,[]),operator])])])),point.substitution,point));thread.prepend(points);},";/2":function(thread,point,atom){var left=atom.args[0],right=atom.args[1];if(pl.type.is_term(left)&&left.indicator==="->/2"){var cond=left.args[0],then=left.args[1],otherwise=right;var goal_fst=point.goal.replace(new Term(",",[cond,new Term(",",[new Term("!"),then])]));var goal_snd=point.goal.replace(new Term(",",[new Term("!"),otherwise]));thread.prepend([new State(goal_fst,point.substitution,point),new State(goal_snd,point.substitution,point)]);}else{thread.prepend([new State(point.goal.replace(left),point.substitution,point),new State(point.goal.replace(right),point.substitution,point)]);}},"!/0":function(thread,point,atom){var parent_cut,last_cut,states=[];parent_cut=point;last_cut=null;while(parent_cut.parent!==null&&parent_cut.parent.goal.search(atom)){last_cut=parent_cut;parent_cut=parent_cut.parent;if(parent_cut.goal!==null){var selected=parent_cut.goal.select();if(selected&&selected.id==="call"&&selected.search(atom)){parent_cut=last_cut;break;}}}
for(var i=thread.points.length-1;i>=0;i--){var state=thread.points[i];var node=state.parent;while(node!==null&&node!==parent_cut.parent){node=node.parent;}
if(node===null&&node!==parent_cut.parent)
states.push(state);}
thread.points=states.reverse();thread.success(point);},"\\+/1":function(thread,point,atom){var goal=atom.args[0];if(pl.type.is_variable(goal)){thread.throw_error(pl.error.instantiation(thread.level));}else if(!pl.type.is_callable(goal)){thread.throw_error(pl.error.type("callable",goal,thread.level));}else{thread.prepend([new State(point.goal.replace(new Term(",",[new Term(",",[new Term("call",[goal]),new Term("!",[])]),new Term("fail",[])])),point.substitution,point),new State(point.goal.replace(null),point.substitution,point)]);}},"->/2":function(thread,point,atom){var cond=atom.args[0],then=atom.args[1];var goal=point.goal.replace(new Term(",",[cond,new Term(",",[new Term("!"),then])]));thread.prepend([new State(goal,point.substitution,point)]);},"fail/0":function(_1,_2,_3){},"false/0":function(_1,_2,_3){},"true/0":function(thread,point,_){thread.success(point);},"call/1":callN(1),"call/2":callN(2),"call/3":callN(3),"call/4":callN(4),"call/5":callN(5),"call/6":callN(6),"call/7":callN(7),"call/8":callN(8),"once/1":function(thread,point,atom){var goal=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("call",[goal]),new Term("!",[])])),point.substitution,point)]);},"forall/2":function(thread,point,atom){var generate=atom.args[0],test=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("\\+",[new Term(",",[new Term("call",[generate]),new Term("\\+",[new Term("call",[test])])])])),point.substitution,point)]);},"repeat/0":function(thread,point,_){thread.prepend([new State(point.goal.replace(null),point.substitution,point),point]);},"throw/1":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.throw_error(pl.error.instantiation(thread.level));}else{thread.throw_error(atom.args[0]);}},"catch/3":function(thread,point,atom){var points=thread.points;thread.points=[];thread.prepend([new State(atom.args[0],point.substitution,point)]);var format_success=thread.session.format_success;var format_error=thread.session.format_error;thread.session.format_success=function(x){return x.substitution;};thread.session.format_error=function(x){return x.goal;};var callback=function(answer){var call_points=thread.points;thread.points=points;thread.session.format_success=format_success;thread.session.format_error=format_error;if(pl.type.is_error(answer)){var states=[];for(var i=thread.points.length-1;i>=0;i--){var state=thread.points[i];var node=state.parent;while(node!==null&&node!==point.parent){node=node.parent;}
if(node===null&&node!==point.parent)
states.push(state);}
thread.points=states;var occurs_check=thread.get_flag("occurs_check").indicator==="true/0";var state=new State();var mgu=pl.unify(answer.args[0],atom.args[1],occurs_check);if(mgu!==null){state.substitution=point.substitution.apply(mgu);state.goal=point.goal.replace(atom.args[2]).apply(mgu);state.parent=point;thread.prepend([state]);}else{thread.throw_error(answer.args[0]);}}else if(answer!==false){var answer_state=answer===null?[]:[new State(point.goal.apply(answer).replace(null),point.substitution.apply(answer),point)];var filter_points=[];for(var i=call_points.length-1;i>=0;i--){filter_points.push(call_points[i]);var selected=call_points[i].goal!==null?call_points[i].goal.select():null;if(pl.type.is_term(selected)&&selected.indicator==="!/0")
break;}
var catch_points=map(filter_points,function(state){if(state.goal===null)
state.goal=new Term("true",[]);state=new State(point.goal.replace(new Term("catch",[state.goal,atom.args[1],atom.args[2]])),point.substitution.apply(state.substitution),state.parent);state.exclude=atom.args[0].variables();return state;}).reverse();thread.prepend(catch_points);thread.prepend(answer_state);if(answer===null){this.current_limit=0;thread.__calls.shift()(null);}}};thread.__calls.unshift(callback);},"=/2":function(thread,point,atom){var occurs_check=thread.get_flag("occurs_check").indicator==="true/0";var state=new State();var mgu=pl.unify(atom.args[0],atom.args[1],occurs_check);if(mgu!==null){state.goal=point.goal.apply(mgu).replace(null);state.substitution=point.substitution.apply(mgu);state.parent=point;thread.prepend([state]);}},"unify_with_occurs_check/2":function(thread,point,atom){var state=new State();var mgu=pl.unify(atom.args[0],atom.args[1],true);if(mgu!==null){state.goal=point.goal.apply(mgu).replace(null);state.substitution=point.substitution.apply(mgu);state.parent=point;thread.prepend([state]);}},"\\=/2":function(thread,point,atom){var occurs_check=thread.get_flag("occurs_check").indicator==="true/0";var mgu=pl.unify(atom.args[0],atom.args[1],occurs_check);if(mgu===null){thread.success(point);}},"subsumes_term/2":function(thread,point,atom){var occurs_check=thread.get_flag("occurs_check").indicator==="true/0";var mgu=pl.unify(atom.args[1],atom.args[0],occurs_check);if(mgu!==null&&atom.args[1].apply(mgu).equals(atom.args[1])){thread.success(point);}},"findall/3":function(thread,point,atom){var template=atom.args[0],goal=atom.args[1],instances=atom.args[2];if(pl.type.is_variable(goal)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(goal)){thread.throw_error(pl.error.type("callable",goal,atom.indicator));}else if(!pl.type.is_variable(instances)&&!pl.type.is_list(instances)){thread.throw_error(pl.error.type("list",instances,atom.indicator));}else{var variable=thread.next_free_variable();var newGoal=new Term(",",[goal,new Term("=",[variable,template])]);var nthread=new Thread(thread.session);nthread.debugger=thread.debugger;nthread.format_success=function(state){return state.substitution;};nthread.format_error=function(state){return state.goal;};nthread.add_goal(newGoal,true,point);nthread.head_point().parent=point;var answers=[];var callback=function(answer){if(answer!==false&&answer!==null&&!pl.type.is_error(answer)){answers.push(answer.links[variable.id]);nthread.answer(callback);}else{var reset_limit=true;if(pl.type.is_error(answer)){thread.throw_error(answer.args[0]);}else if(nthread.current_limit>0){var list=arrayToList(answers);thread.prepend([new State(point.goal.replace(new Term("=",[instances,list])),point.substitution,point)]);}else{thread.prepend([point]);thread.current_limit=0;reset_limit=false;}
if(reset_limit&&nthread.debugger)
thread.debugger_states=thread.debugger_states.concat(nthread.debugger_states);thread.again(reset_limit);}};nthread.answer(callback);return true;}},"bagof/3":function(thread,point,atom){var answer,template=atom.args[0],goal=atom.args[1],instances=atom.args[2];if(pl.type.is_variable(goal)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(goal)){thread.throw_error(pl.error.type("callable",goal,atom.indicator));}else if(!pl.type.is_variable(instances)&&!pl.type.is_list(instances)){thread.throw_error(pl.error.type("list",instances,atom.indicator));}else{var variable=thread.next_free_variable();var template_vars;if(goal.indicator==="^/2"){template_vars=goal.args[0].variables();goal=goal.args[1];}else{template_vars=[];}
template_vars=template_vars.concat(template.variables());var free_vars=goal.variables().filter(function(v){return indexOf(template_vars,v)===-1;});var list_vars=new Term("[]");for(var i=free_vars.length-1;i>=0;i--){list_vars=new Term(".",[new Var(free_vars[i]),list_vars]);}
var newGoal=new Term(",",[goal,new Term("=",[variable,new Term(",",[list_vars,template])])]);var nthread=new Thread(thread.session);nthread.debugger=thread.debugger;nthread.format_success=function(state){return state.substitution;};nthread.format_error=function(state){return state.goal;};nthread.add_goal(newGoal,true,point);nthread.head_point().parent=point;var answers=[];var callback=function(answer){if(answer!==false&&answer!==null&&!pl.type.is_error(answer)){var match=false;var arg_vars=answer.links[variable.id].args[0];var arg_template=answer.links[variable.id].args[1];for(var _elem in answers){if(!answers.hasOwnProperty(_elem))continue;var elem=answers[_elem];if(elem.variables.equals(arg_vars)){elem.answers.push(arg_template);match=true;break;}}
if(!match)
answers.push({variables:arg_vars,answers:[arg_template]});nthread.answer(callback);}else{reset_limit=true;if(pl.type.is_error(answer)){thread.throw_error(answer.args[0]);}else if(thread.current_limit>0){var states=[];for(var i=0;i<answers.length;i++){answer=answers[i].answers;var list=arrayToList(answer);states.push(new State(point.goal.replace(new Term(",",[new Term("=",[list_vars,answers[i].variables]),new Term("=",[instances,list])])),point.substitution,point));}
thread.prepend(states);}else{thread.prepend([point]);thread.current_limit=0;reset_limit=false;}
if(reset_limit&&nthread.debugger)
thread.debugger_states=thread.debugger_states.concat(nthread.debugger_states);thread.again(reset_limit);}};nthread.answer(callback);return true;}},"setof/3":function(thread,point,atom){var answer,template=atom.args[0],goal=atom.args[1],instances=atom.args[2];if(pl.type.is_variable(goal)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(goal)){thread.throw_error(pl.error.type("callable",goal,atom.indicator));}else if(!pl.type.is_variable(instances)&&!pl.type.is_list(instances)){thread.throw_error(pl.error.type("list",instances,atom.indicator));}else{var variable=thread.next_free_variable();var template_vars;if(goal.indicator==="^/2"){template_vars=goal.args[0].variables();goal=goal.args[1];}else{template_vars=[];}
template_vars=template_vars.concat(template.variables());var free_vars=goal.variables().filter(function(v){return indexOf(template_vars,v)===-1;});var list_vars=new Term("[]");for(var i=free_vars.length-1;i>=0;i--){list_vars=new Term(".",[new Var(free_vars[i]),list_vars]);}
var newGoal=new Term(",",[goal,new Term("=",[variable,new Term(",",[list_vars,template])])]);var nthread=new Thread(thread.session);nthread.debugger=thread.debugger;nthread.format_success=function(state){return state.substitution;};nthread.format_error=function(state){return state.goal;};nthread.add_goal(newGoal,true,point);nthread.head_point().parent=point;var answers=[];var callback=function(answer){if(answer!==false&&answer!==null&&!pl.type.is_error(answer)){var match=false;var arg_vars=answer.links[variable.id].args[0];var arg_template=answer.links[variable.id].args[1];for(var _elem in answers){if(!answers.hasOwnProperty(_elem))continue;var elem=answers[_elem];if(elem.variables.equals(arg_vars)){elem.answers.push(arg_template);match=true;break;}}
if(!match)
answers.push({variables:arg_vars,answers:[arg_template]});nthread.answer(callback);}else{reset_limit=true;if(pl.type.is_error(answer)){thread.throw_error(answer.args[0]);}else if(thread.current_limit>0){var states=[];for(var i=0;i<answers.length;i++){answer=answers[i].answers.sort(pl.compare);var list=arrayToList(answer);states.push(new State(point.goal.replace(new Term(",",[new Term("=",[list_vars,answers[i].variables]),new Term("=",[instances,list])])),point.substitution,point));}
thread.prepend(states);}else{thread.prepend([point]);thread.current_limit=0;reset_limit=false;}
if(reset_limit&&nthread.debugger)
thread.debugger_states=thread.debugger_states.concat(nthread.debugger_states);thread.again(reset_limit);}};nthread.answer(callback);return true;}},"functor/3":function(thread,point,atom){var subs;var term=atom.args[0],name=atom.args[1],arity=atom.args[2];if(pl.type.is_variable(term)&&(pl.type.is_variable(name)||pl.type.is_variable(arity))){thread.throw_error(pl.error.instantiation("functor/3"));}else if(!pl.type.is_variable(arity)&&!pl.type.is_integer(arity)){thread.throw_error(pl.error.type("integer",atom.args[2],"functor/3"));}else if(!pl.type.is_variable(name)&&!pl.type.is_atomic(name)){thread.throw_error(pl.error.type("atomic",atom.args[1],"functor/3"));}else if(pl.type.is_integer(name)&&pl.type.is_integer(arity)&&arity.value!==0){thread.throw_error(pl.error.type("atom",atom.args[1],"functor/3"));}else if(pl.type.is_variable(term)){if(atom.args[2].value>=0){var args=[];for(var i=0;i<arity.value;i++)
args.push(thread.next_free_variable());var functor=pl.type.is_integer(name)?name:new Term(name.id,args);thread.prepend([new State(point.goal.replace(new Term("=",[term,functor])),point.substitution,point)]);}}else{var id=pl.type.is_integer(term)?term:new Term(term.id,[]);var length=pl.type.is_integer(term)?new Num(0,false):new Num(term.args.length,false);var goal=new Term(",",[new Term("=",[id,name]),new Term("=",[length,arity])]);thread.prepend([new State(point.goal.replace(goal),point.substitution,point)]);}},"arg/3":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])||pl.type.is_variable(atom.args[1])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(atom.args[0].value<0){thread.throw_error(pl.error.domain("not_less_than_zero",atom.args[0],atom.indicator));}else if(!pl.type.is_compound(atom.args[1])){thread.throw_error(pl.error.type("compound",atom.args[1],atom.indicator));}else{var n=atom.args[0].value;if(n>0&&n<=atom.args[1].args.length){var goal=new Term("=",[atom.args[1].args[n-1],atom.args[2]]);thread.prepend([new State(point.goal.replace(goal),point.substitution,point)]);}}},"=../2":function(thread,point,atom){var list;if(pl.type.is_variable(atom.args[0])&&(pl.type.is_variable(atom.args[1])||pl.type.is_non_empty_list(atom.args[1])&&pl.type.is_variable(atom.args[1].args[0]))){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_fully_list(atom.args[1])){thread.throw_error(pl.error.type("list",atom.args[1],atom.indicator));}else if(!pl.type.is_variable(atom.args[0])){if(pl.type.is_atomic(atom.args[0])){list=new Term(".",[atom.args[0],new Term("[]")]);}else{list=new Term("[]");for(var i=atom.args[0].args.length-1;i>=0;i--){list=new Term(".",[atom.args[0].args[i],list]);}
list=new Term(".",[new Term(atom.args[0].id),list]);}
thread.prepend([new State(point.goal.replace(new Term("=",[list,atom.args[1]])),point.substitution,point)]);}else if(!pl.type.is_variable(atom.args[1])){var args=[];list=atom.args[1].args[1];while(list.indicator==="./2"){args.push(list.args[0]);list=list.args[1];}
if(pl.type.is_variable(atom.args[0])&&pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(args.length===0&&pl.type.is_compound(atom.args[1].args[0])){thread.throw_error(pl.error.type("atomic",atom.args[1].args[0],atom.indicator));}else if(args.length>0&&(pl.type.is_compound(atom.args[1].args[0])||pl.type.is_number(atom.args[1].args[0]))){thread.throw_error(pl.error.type("atom",atom.args[1].args[0],atom.indicator));}else{if(args.length===0){thread.prepend([new State(point.goal.replace(new Term("=",[atom.args[1].args[0],atom.args[0]],point)),point.substitution,point)]);}else{thread.prepend([new State(point.goal.replace(new Term("=",[new Term(atom.args[1].args[0].id,args),atom.args[0]])),point.substitution,point)]);}}}},"copy_term/2":function(thread,point,atom){var renamed=atom.args[0].rename(thread);thread.prepend([new State(point.goal.replace(new Term("=",[renamed,atom.args[1]])),point.substitution,point.parent)]);},"term_variables/2":function(thread,point,atom){var term=atom.args[0],vars=atom.args[1];if(!pl.type.is_fully_list(vars)){thread.throw_error(pl.error.type("list",vars,atom.indicator));}else{var list=arrayToList(map(nub(term.variables()),function(v){return new Var(v);}));thread.prepend([new State(point.goal.replace(new Term("=",[vars,list])),point.substitution,point)]);}},"clause/2":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(atom.args[0])){thread.throw_error(pl.error.type("callable",atom.args[0],atom.indicator));}else if(!pl.type.is_variable(atom.args[1])&&!pl.type.is_callable(atom.args[1])){thread.throw_error(pl.error.type("callable",atom.args[1],atom.indicator));}else if(thread.session.rules[atom.args[0].indicator]!==undefined){if(thread.is_public_predicate(atom.args[0].indicator)){var states=[];for(var _rule in thread.session.rules[atom.args[0].indicator]){if(!thread.session.rules[atom.args[0].indicator].hasOwnProperty(_rule))continue;var rule=thread.session.rules[atom.args[0].indicator][_rule];thread.session.renamed_variables={};rule=rule.rename(thread);if(rule.body===null){rule.body=new Term("true");}
var goal=new Term(",",[new Term("=",[rule.head,atom.args[0]]),new Term("=",[rule.body,atom.args[1]])]);states.push(new State(point.goal.replace(goal),point.substitution,point));}
thread.prepend(states);}else{thread.throw_error(pl.error.permission("access","private_procedure",atom.args[0].indicator,atom.indicator));}}},"current_predicate/1":function(thread,point,atom){var indicator=atom.args[0];if(!pl.type.is_variable(indicator)&&(!pl.type.is_compound(indicator)||indicator.indicator!=="//2")){thread.throw_error(pl.error.type("predicate_indicator",indicator,atom.indicator));}else if(!pl.type.is_variable(indicator)&&!pl.type.is_variable(indicator.args[0])&&!pl.type.is_atom(indicator.args[0])){thread.throw_error(pl.error.type("atom",indicator.args[0],atom.indicator));}else if(!pl.type.is_variable(indicator)&&!pl.type.is_variable(indicator.args[1])&&!pl.type.is_integer(indicator.args[1])){thread.throw_error(pl.error.type("integer",indicator.args[1],atom.indicator));}else{var states=[];for(var i in thread.session.rules){if(!thread.session.rules.hasOwnProperty(i))continue;var index=i.lastIndexOf("/");var name=i.substr(0,index);var arity=parseInt(i.substr(index+1,i.length-(index+1)));var predicate=new Term("/",[new Term(name),new Num(arity,false)]);var goal=new Term("=",[predicate,indicator]);states.push(new State(point.goal.replace(goal),point.substitution,point));}
thread.prepend(states);}},"listing/0":function(thread,point,atom){var from_module=atom.from_module?atom.from_module:"user";var rules;if(from_module==="user"){rules=thread.session.rules;}else{if(pl.module[from_module])
rules=pl.module[from_module].rules;else
rules={};}
var str="";for(var indicator in rules){if(!rules.hasOwnProperty(indicator))continue;var predicate=rules[indicator];str+="% "+indicator+"\n";if(predicate instanceof Array){for(var i=0;i<predicate.length;i++)
str+=predicate[i].toString({session:thread.session})+"\n";}else{str+="/*\n"+predicate.toString()+"\n*/";}
str+="\n";}
thread.session.result=str;if(!thread.session.silent)thread.prepend([new State(point.goal.replace(new Term("write",[new Term(str,[])])),point.substitution,point)]);},"listing/1":function(thread,point,atom){var indicator=atom.args[0];if(pl.type.is_variable(indicator)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_predicate_indicator(indicator)){thread.throw_error(pl.error.type("predicate_indicator",indicator,atom.indicator));}else{var from_module=atom.from_module?atom.from_module:"user";var rules;if(from_module==="user"){rules=thread.session.rules;}else{if(pl.module[from_module])
rules=pl.module[from_module].rules;else
rules={};}
var str="";var str_indicator=indicator.args[0].id+"/"+indicator.args[1].value;if(rules.hasOwnProperty(str_indicator)){var predicate=rules[str_indicator];if(predicate instanceof Array){for(var i=0;i<predicate.length;i++)
str+=predicate[i].toString({session:thread.session})+"\n";}else{str+="/*\n"+predicate.toString()+"\n*/";}
str+="\n";}
thread.session.result=str;if(!thread.session.silent)thread.prepend([new State(point.goal.replace(new Term("write",[new Term(str,[])])),point.substitution,point)]);}},"asserta/1":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(atom.args[0])){thread.throw_error(pl.error.type("callable",atom.args[0],atom.indicator));}else{var head,body;if(atom.args[0].indicator===":-/2"){head=atom.args[0].args[0];body=body_conversion(atom.args[0].args[1]);}else{head=atom.args[0];body=null;}
if(!pl.type.is_callable(head)){thread.throw_error(pl.error.type("callable",head,atom.indicator));}else if(body!==null&&!pl.type.is_callable(body)){thread.throw_error(pl.error.type("callable",body,atom.indicator));}else if(thread.is_public_predicate(head.indicator)){if(thread.session.rules[head.indicator]===undefined){thread.session.rules[head.indicator]=[];}
thread.session.public_predicates[head.indicator]=true;thread.session.rules[head.indicator]=[new Rule(head,body,true)].concat(thread.session.rules[head.indicator]);thread.success(point);}else{thread.throw_error(pl.error.permission("modify","static_procedure",head.indicator,atom.indicator));}}},"assertz/1":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(atom.args[0])){thread.throw_error(pl.error.type("callable",atom.args[0],atom.indicator));}else{var head,body;if(atom.args[0].indicator===":-/2"){head=atom.args[0].args[0];body=body_conversion(atom.args[0].args[1]);}else{head=atom.args[0];body=null;}
if(!pl.type.is_callable(head)){thread.throw_error(pl.error.type("callable",head,atom.indicator));}else if(body!==null&&!pl.type.is_callable(body)){thread.throw_error(pl.error.type("callable",body,atom.indicator));}else if(thread.is_public_predicate(head.indicator)){if(thread.session.rules[head.indicator]===undefined){thread.session.rules[head.indicator]=[];}
thread.session.public_predicates[head.indicator]=true;thread.session.rules[head.indicator].push(new Rule(head,body,true));thread.success(point);}else{thread.throw_error(pl.error.permission("modify","static_procedure",head.indicator,atom.indicator));}}},"retract/1":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(atom.args[0])){thread.throw_error(pl.error.type("callable",atom.args[0],atom.indicator));}else{var head,body;if(atom.args[0].indicator===":-/2"){head=atom.args[0].args[0];body=atom.args[0].args[1];}else{head=atom.args[0];body=new Term("true");}
if(typeof point.retract==="undefined"){if(thread.is_public_predicate(head.indicator)){if(thread.session.rules[head.indicator]!==undefined){var states=[];for(var i=0;i<thread.session.rules[head.indicator].length;i++){thread.session.renamed_variables={};var orule=thread.session.rules[head.indicator][i];var rule=orule.rename(thread);if(rule.body===null)
rule.body=new Term("true",[]);var occurs_check=thread.get_flag("occurs_check").indicator==="true/0";var mgu=pl.unify(new Term(",",[head,body]),new Term(",",[rule.head,rule.body]),occurs_check);if(mgu!==null){var state=new State(point.goal.replace(new Term(",",[new Term("retract",[new Term(":-",[head,body])]),new Term(",",[new Term("=",[head,rule.head]),new Term("=",[body,rule.body])])])),point.substitution,point);state.retract=orule;states.push(state);}}
thread.prepend(states);}}else{thread.throw_error(pl.error.permission("modify","static_procedure",head.indicator,atom.indicator));}}else{retract(thread,point,head.indicator,point.retract);}}},"retractall/1":function(thread,point,atom){var head=atom.args[0];if(pl.type.is_variable(head)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(head)){thread.throw_error(pl.error.type("callable",head,atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term(",",[new Term("retract",[new pl.type.Term(":-",[head,new Var("_")])]),new Term("fail",[])])),point.substitution,point),new State(point.goal.replace(null),point.substitution,point)]);}},"abolish/1":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])||pl.type.is_term(atom.args[0])&&atom.args[0].indicator==="//2"&&(pl.type.is_variable(atom.args[0].args[0])||pl.type.is_variable(atom.args[0].args[1]))){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_term(atom.args[0])||atom.args[0].indicator!=="//2"){thread.throw_error(pl.error.type("predicate_indicator",atom.args[0],atom.indicator));}else if(!pl.type.is_atom(atom.args[0].args[0])){thread.throw_error(pl.error.type("atom",atom.args[0].args[0],atom.indicator));}else if(!pl.type.is_integer(atom.args[0].args[1])){thread.throw_error(pl.error.type("integer",atom.args[0].args[1],atom.indicator));}else if(atom.args[0].args[1].value<0){thread.throw_error(pl.error.domain("not_less_than_zero",atom.args[0].args[1],atom.indicator));}else if(pl.type.is_number(thread.get_flag("max_arity"))&&atom.args[0].args[1].value>thread.get_flag("max_arity").value){thread.throw_error(pl.error.representation("max_arity",atom.indicator));}else{var indicator=atom.args[0].args[0].id+"/"+atom.args[0].args[1].value;if(thread.is_public_predicate(indicator)){delete thread.session.rules[indicator];thread.success(point);}else{thread.throw_error(pl.error.permission("modify","static_procedure",indicator,atom.indicator));}}},"atom_length/2":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(atom.args[0])){thread.throw_error(pl.error.type("atom",atom.args[0],atom.indicator));}else if(!pl.type.is_variable(atom.args[1])&&!pl.type.is_integer(atom.args[1])){thread.throw_error(pl.error.type("integer",atom.args[1],atom.indicator));}else if(pl.type.is_integer(atom.args[1])&&atom.args[1].value<0){thread.throw_error(pl.error.domain("not_less_than_zero",atom.args[1],atom.indicator));}else{var length=new Num(stringLength(atom.args[0].id),false);thread.prepend([new State(point.goal.replace(new Term("=",[length,atom.args[1]])),point.substitution,point)]);}},"atom_concat/3":function(thread,point,atom){var str,goal,start=atom.args[0],end=atom.args[1],whole=atom.args[2];if(pl.type.is_variable(whole)&&(pl.type.is_variable(start)||pl.type.is_variable(end))){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(start)&&!pl.type.is_atom(start)){thread.throw_error(pl.error.type("atom",start,atom.indicator));}else if(!pl.type.is_variable(end)&&!pl.type.is_atom(end)){thread.throw_error(pl.error.type("atom",end,atom.indicator));}else if(!pl.type.is_variable(whole)&&!pl.type.is_atom(whole)){thread.throw_error(pl.error.type("atom",whole,atom.indicator));}else{var v1=pl.type.is_variable(start);var v2=pl.type.is_variable(end);if(!v1&&!v2){goal=new Term("=",[whole,new Term(start.id+end.id)]);thread.prepend([new State(point.goal.replace(goal),point.substitution,point)]);}else if(v1&&!v2){str=whole.id.substr(0,whole.id.length-end.id.length);if(str+end.id===whole.id){goal=new Term("=",[start,new Term(str)]);thread.prepend([new State(point.goal.replace(goal),point.substitution,point)]);}}else if(v2&&!v1){str=whole.id.substr(start.id.length);if(start.id+str===whole.id){goal=new Term("=",[end,new Term(str)]);thread.prepend([new State(point.goal.replace(goal),point.substitution,point)]);}}else{var states=[];for(var i=0;i<=whole.id.length;i++){var atom1=new Term(whole.id.substr
thread.prepend(states);}}},"sub_atom/5":function(thread,point,atom){var i,atom1=atom.args[0],before=atom.args[1],length=atom.args[2],after=atom.args[3],subatom=atom.args[4];if(pl.type.is_variable(atom1)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(before)&&!pl.type.is_integer(before)){thread.throw_error(pl.error.type("integer",before,atom.indicator));}else if(!pl.type.is_variable(length)&&!pl.type.is_integer(length)){thread.throw_error(pl.error.type("integer",length,atom.indicator));}else if(!pl.type.is_variable(after)&&!pl.type.is_integer(after)){thread.throw_error(pl.error.type("integer",after,atom.indicator));}else if(pl.type.is_integer(before)&&before.value<0){thread.throw_error(pl.error.domain("not_less_than_zero",before,atom.indicator));}else if(pl.type.is_integer(length)&&length.value<0){thread.throw_error(pl.error.domain("not_less_than_zero",length,atom.indicator));}else if(pl.type.is_integer(after)&&after.value<0){thread.throw_error(pl.error.domain("not_less_than_zero",after,atom.indicator));}else{var bs=[],ls=[],as=[];if(pl.type.is_variable(before)){for(i=0;i<=atom1.id.length;i++){bs.push(i);}}else{bs.push(before.value);}
if(pl.type.is_variable(length)){for(i=0;i<=atom1.id.length;i++){ls.push(i);}}else{ls.push(length.value);}
if(pl.type.is_variable(after)){for(i=0;i<=atom1.id.length;i++){as.push(i);}}else{as.push(after.value);}
var states=[];for(var _i in bs){if(!bs.hasOwnProperty(_i))continue;i=bs[_i];for(var _j in ls){if(!ls.hasOwnProperty(_j))continue;var j=ls[_j];var k=atom1.id.length-i-j;if(indexOf(as,k)!==-1){if(i+j+k===atom1.id.length){var str=atom1.id.substr(i,j);if(atom1.id===atom1.id.substr(0,i)+str+atom1.id.substr(i+j,k)){var pl1=new Term("=",[new Term(str),subatom]);var pl2=new Term("=",[before,new Num(i)]);var pl3=new Term("=",[length,new Num(j)]);var pl4=new Term("=",[after,new Num(k)]);var goal=new Term(",",[new Term(",",[new Term(",",[pl2,pl3]),pl4]),pl1]);states.push(new State(point.goal.replace(goal),point.substitution,point));}}}}}
thread.prepend(states);}},"atom_chars/2":function(thread,point,atom){var atom1=atom.args[0],list=atom.args[1];if(pl.type.is_variable(atom1)&&pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(atom1)&&!pl.type.is_atom(atom1)){thread.throw_error(pl.error.type("atom",atom1,atom.indicator));}else{if(!pl.type.is_variable(atom1)){var list1=new Term("[]");var unilen=stringLength(atom1.id);for(var i=unilen-1;i>=0;i--){list1=new Term(".",[new Term(atom1.id.charAt(i)),list1]);}
thread.prepend([new State(point.goal.replace(new Term("=",[list,list1])),point.substitution,point)]);}else{var pointer=list;var v=pl.type.is_variable(atom1);var str="";while(pointer.indicator==="./2"){if(!pl.type.is_character(pointer.args[0])){if(pl.type.is_variable(pointer.args[0])&&v){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_variable(pointer.args[0])){thread.throw_error(pl.error.type("character",pointer.args[0],atom.indicator));return;}}else{str+=pointer.args[0].id;}
pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)&&v){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_empty_list(pointer)&&!pl.type.is_variable(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[new Term(str),atom1])),point.substitution,point)]);}}}},"atom_codes/2":function(thread,point,atom){var atom1=atom.args[0],list=atom.args[1];if(pl.type.is_variable(atom1)&&pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(atom1)&&!pl.type.is_atom(atom1)){thread.throw_error(pl.error.type("atom",atom1,atom.indicator));}else{if(!pl.type.is_variable(atom1)){var list1=new Term("[]");var unilen=stringLength(atom1.id);for(var i=unilen-1;i>=0;i--){list1=new Term(".",[new Num(codePointAt(atom1.id,i),false),list1]);}
thread.prepend([new State(point.goal.replace(new Term("=",[list,list1])),point.substitution,point)]);}else{var pointer=list;var v=pl.type.is_variable(atom1);var str="";while(pointer.indicator==="./2"){if(!pl.type.is_character_code(pointer.args[0])){if(pl.type.is_variable(pointer.args[0])&&v){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_variable(pointer.args[0])){thread.throw_error(pl.error.representation("character_code",atom.indicator));return;}}else{str+=fromCodePoint(pointer.args[0].value);}
pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)&&v){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_empty_list(pointer)&&!pl.type.is_variable(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[new Term(str),atom1])),point.substitution,point)]);}}}},"char_code/2":function(thread,point,atom){var char=atom.args[0],code=atom.args[1];if(pl.type.is_variable(char)&&pl.type.is_variable(code)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(char)&&!pl.type.is_character(char)){thread.throw_error(pl.error.type("character",char,atom.indicator));}else if(!pl.type.is_variable(code)&&!pl.type.is_integer(code)){thread.throw_error(pl.error.type("integer",code,atom.indicator));}else if(!pl.type.is_variable(code)&&!pl.type.is_character_code(code)){thread.throw_error(pl.error.representation("character_code",atom.indicator));}else{if(pl.type.is_variable(code)){var code1=new Num(codePointAt(char.id,0),false);thread.prepend([new State(point.goal.replace(new Term("=",[code1,code])),point.substitution,point)]);}else{var char1=new Term(fromCodePoint(code.value));thread.prepend([new State(point.goal.replace(new Term("=",[char1,char])),point.substitution,point)]);}}},"number_chars/2":function(thread,point,atom){var str,num=atom.args[0],list=atom.args[1];if(pl.type.is_variable(num)&&pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(num)&&!pl.type.is_number(num)){thread.throw_error(pl.error.type("number",num,atom.indicator));}else if(!pl.type.is_variable(list)&&!pl.type.is_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var isvar=pl.type.is_variable(num);if(!pl.type.is_variable(list)){var pointer=list;var total=true;str="";while(pointer.indicator==="./2"){if(!pl.type.is_character(pointer.args[0])){if(pl.type.is_variable(pointer.args[0])){total=false;}else if(!pl.type.is_variable(pointer.args[0])){thread.throw_error(pl.error.type("character",pointer.args[0],atom.indicator));return;}}else{str+=pointer.args[0].id;}
pointer=pointer.args[1];}
total=total&&pl.type.is_empty_list(pointer);if(!pl.type.is_empty_list(pointer)&&!pl.type.is_variable(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));return;}
if(!total&&isvar){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(total){if(pl.type.is_variable(pointer)&&isvar){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else{var expr=thread.parse(str);var num2=expr.value;if(!pl.type.is_number(num2)||expr.tokens[expr.tokens.length-1].space){thread.throw_error(pl.error.syntax_by_predicate("parseable_number",atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[num,num2])),point.substitution,point)]);}
return;}}}
if(!isvar){str=num.toString();var list2=new Term("[]");for(var i=str.length-1;i>=0;i--){list2=new Term(".",[new Term(str.charAt(i)),list2]);}
thread.prepend([new State(point.goal.replace(new Term("=",[list,list2])),point.substitution,point)]);}}},"number_codes/2":function(thread,point,atom){var str,num=atom.args[0],list=atom.args[1];if(pl.type.is_variable(num)&&pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(num)&&!pl.type.is_number(num)){thread.throw_error(pl.error.type("number",num,atom.indicator));}else if(!pl.type.is_variable(list)&&!pl.type.is_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var isvar=pl.type.is_variable(num);if(!pl.type.is_variable(list)){var pointer=list;var total=true;str="";while(pointer.indicator==="./2"){if(!pl.type.is_character_code(pointer.args[0])){if(pl.type.is_variable(pointer.args[0])){total=false;}else if(!pl.type.is_variable(pointer.args[0])){thread.throw_error(pl.error.type("character_code",pointer.args[0],atom.indicator));return;}}else{str+=fromCodePoint(pointer.args[0].value);}
pointer=pointer.args[1];}
total=total&&pl.type.is_empty_list(pointer);if(!pl.type.is_empty_list(pointer)&&!pl.type.is_variable(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));return;}
if(!total&&isvar){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(total){if(pl.type.is_variable(pointer)&&isvar){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else{var expr=thread.parse(str);var num2=expr.value;if(!pl.type.is_number(num2)||expr.tokens[expr.tokens.length-1].space){thread.throw_error(pl.error.syntax_by_predicate("parseable_number",atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[num,num2])),point.substitution,point)]);}
return;}}}
if(!isvar){str=num.toString();var list2=new Term("[]");for(var i=str.length-1;i>=0;i--){list2=new Term(".",[new Num(codePointAt(str,i),false),list2]);}
thread.prepend([new State(point.goal.replace(new Term("=",[list,list2])),point.substitution,point)]);}}},"upcase_atom/2":function(thread,point,atom){var original=atom.args[0],upcase=atom.args[1];if(pl.type.is_variable(original)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(original)){thread.throw_error(pl.error.type("atom",original,atom.indicator));}else if(!pl.type.is_variable(upcase)&&!pl.type.is_atom(upcase)){thread.throw_error(pl.error.type("atom",upcase,atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[upcase,new Term(original.id.toUpperCase(),[])])),point.substitution,point)]);}},"downcase_atom/2":function(thread,point,atom){var original=atom.args[0],downcase=atom.args[1];if(pl.type.is_variable(original)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(original)){thread.throw_error(pl.error.type("atom",original,atom.indicator));}else if(!pl.type.is_variable(downcase)&&!pl.type.is_atom(downcase)){thread.throw_error(pl.error.type("atom",downcase,atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[downcase,new Term(original.id.toLowerCase(),[])])),point.substitution,point)]);}},"atomic_list_concat/2":function(thread,point,atom){var list=atom.args[0],concat=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("atomic_list_concat",[list,new Term("",[]),concat])),point.substitution,point)]);},"atomic_list_concat/3":function(thread,point,atom){var list=atom.args[0],separator=atom.args[1],concat=atom.args[2];if(pl.type.is_variable(separator)||pl.type.is_variable(list)&&pl.type.is_variable(concat)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(list)&&!pl.type.is_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else if(!pl.type.is_variable(concat)&&!pl.type.is_atom(concat)){thread.throw_error(pl.error.type("atom",concat,atom.indicator));}else{if(!pl.type.is_variable(concat)){var atomic=arrayToList(map(concat.id.split(separator.id),function(id){return new Term(id,[]);}));thread.prepend([new State(point.goal.replace(new Term("=",[atomic,list])),point.substitution,point)]);}else{var id="";var pointer=list;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){if(!pl.type.is_atom(pointer.args[0])&&!pl.type.is_number(pointer.args[0])){thread.throw_error(pl.error.type("atomic",pointer.args[0],atom.indicator));return;}
if(id!=="")
id+=separator.id;if(pl.type.is_atom(pointer.args[0]))
id+=pointer.args[0].id;else
id+=""+pointer.args[0].value;pointer=pointer.args[1];}
id=new Term(id,[]);if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_term(pointer)||pointer.indicator!=="[]/0"){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{thread.prepend([new State(point.goal.replace(new Term("=",[id,concat])),point.substitution,point)]);}}}},"@=</2":function(thread,point,atom){if(pl.compare(atom.args[0],atom.args[1])<=0){thread.success(point);}},"==/2":function(thread,point,atom){if(pl.compare(atom.args[0],atom.args[1])===0){thread.success(point);}},"\\==/2":function(thread,point,atom){if(pl.compare(atom.args[0],atom.args[1])!==0){thread.success(point);}},"@</2":function(thread,point,atom){if(pl.compare(atom.args[0],atom.args[1])<0){thread.success(point);}},"@>/2":function(thread,point,atom){if(pl.compare(atom.args[0],atom.args[1])>0){thread.success(point);}},"@>=/2":function(thread,point,atom){if(pl.compare(atom.args[0],atom.args[1])>=0){thread.success(point);}},"compare/3":function(thread,point,atom){var order=atom.args[0],left=atom.args[1],right=atom.args[2];if(!pl.type.is_variable(order)&&!pl.type.is_atom(order)){thread.throw_error(pl.error.type("atom",order,atom.indicator));}else if(pl.type.is_atom(order)&&["<",">","="].indexOf(order.id)===-1){thread.throw_error(pl.type.domain("order",order,atom.indicator));}else{var compare=pl.compare(left,right);compare=compare===0?"=":(compare===-1?"<":">");thread.prepend([new State(point.goal.replace(new Term("=",[order,new Term(compare,[])])),point.substitution,point)]);}},"is/2":function(thread,point,atom){var op=atom.args[1].interpret(thread);if(!pl.type.is_number(op)){thread.throw_error(op);}else{thread.prepend([new State(point.goal.replace(new Term("=",[atom.args[0],op],thread.level)),point.substitution,point)]);}},"between/3":function(thread,point,atom){var lower=atom.args[0],upper=atom.args[1],bet=atom.args[2];if(pl.type.is_variable(lower)||pl.type.is_variable(upper)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_integer(lower)){thread.throw_error(pl.error.type("integer",lower,atom.indicator));}else if(!pl.type.is_integer(upper)){thread.throw_error(pl.error.type("integer",upper,atom.indicator));}else if(!pl.type.is_variable(bet)&&!pl.type.is_integer(bet)){thread.throw_error(pl.error.type("integer",bet,atom.indicator));}else{if(pl.type.is_variable(bet)){var states=[new State(point.goal.replace(new Term("=",[bet,lower])),point.substitution,point)];if(lower.value<upper.value)
states.push(new State(point.goal.replace(new Term("between",[new Num(lower.value+1,false),upper,bet])),point.substitution,point));thread.prepend(states);}else if(lower.value<=bet.value&&upper.value>=bet.value){thread.success(point);}}},"succ/2":function(thread,point,atom){var n=atom.args[0],m=atom.args[1];if(pl.type.is_variable(n)&&pl.type.is_variable(m)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(n)&&!pl.type.is_integer(n)){thread.throw_error(pl.error.type("integer",n,atom.indicator));}else if(!pl.type.is_variable(m)&&!pl.type.is_integer(m)){thread.throw_error(pl.error.type("integer",m,atom.indicator));}else if(!pl.type.is_variable(n)&&n.value<0){thread.throw_error(pl.error.domain("not_less_than_zero",n,atom.indicator));}else if(!pl.type.is_variable(m)&&m.value<0){thread.throw_error(pl.error.domain("not_less_than_zero",m,atom.indicator));}else{if(pl.type.is_variable(m)||m.value>0){if(pl.type.is_variable(n)){thread.prepend([new State(point.goal.replace(new Term("=",[n,new Num(m.value-1,false)])),point.substitution,point)]);}else{thread.prepend([new State(point.goal.replace(new Term("=",[m,new Num(n.value+1,false)])),point.substitution,point)]);}}}},"=:=/2":function(thread,point,atom){var cmp=pl.arithmetic_compare(thread,atom.args[0],atom.args[1]);if(pl.type.is_term(cmp)){thread.throw_error(cmp);}else if(cmp===0){thread.success(point);}},"=\\=/2":function(thread,point,atom){var cmp=pl.arithmetic_compare(thread,atom.args[0],atom.args[1]);if(pl.type.is_term(cmp)){thread.throw_error(cmp);}else if(cmp!==0){thread.success(point);}},"</2":function(thread,point,atom){var cmp=pl.arithmetic_compare(thread,atom.args[0],atom.args[1]);if(pl.type.is_term(cmp)){thread.throw_error(cmp);}else if(cmp<0){thread.success(point);}},"=</2":function(thread,point,atom){var cmp=pl.arithmetic_compare(thread,atom.args[0],atom.args[1]);if(pl.type.is_term(cmp)){thread.throw_error(cmp);}else if(cmp<=0){thread.success(point);}},">/2":function(thread,point,atom){var cmp=pl.arithmetic_compare(thread,atom.args[0],atom.args[1]);if(pl.type.is_term(cmp)){thread.throw_error(cmp);}else if(cmp>0){thread.success(point);}},">=/2":function(thread,point,atom){var cmp=pl.arithmetic_compare(thread,atom.args[0],atom.args[1]);if(pl.type.is_term(cmp)){thread.throw_error(cmp);}else if(cmp>=0){thread.success(point);}},"var/1":function(thread,point,atom){if(pl.type.is_variable(atom.args[0])){thread.success(point);}},"atom/1":function(thread,point,atom){if(pl.type.is_atom(atom.args[0])){thread.success(point);}},"atomic/1":function(thread,point,atom){if(pl.type.is_atomic(atom.args[0])){thread.success(point);}},"compound/1":function(thread,point,atom){if(pl.type.is_compound(atom.args[0])){thread.success(point);}},"integer/1":function(thread,point,atom){if(pl.type.is_integer(atom.args[0])){thread.success(point);}},"float/1":function(thread,point,atom){if(pl.type.is_float(atom.args[0])){thread.success(point);}},"number/1":function(thread,point,atom){if(pl.type.is_number(atom.args[0])){thread.success(point);}},"nonvar/1":function(thread,point,atom){if(!pl.type.is_variable(atom.args[0])){thread.success(point);}},"ground/1":function(thread,point,atom){if(atom.variables().length===0){thread.success(point);}},"acyclic_term/1":function(thread,point,atom){var test=point.substitution.apply(point.substitution);var variables=atom.args[0].variables();for(var i=0;i<variables.length;i++)
if(point.substitution.links[variables[i]]!==undefined&&!point.substitution.links[variables[i]].equals(test.links[variables[i]]))
return;thread.success(point);},"callable/1":function(thread,point,atom){if(pl.type.is_callable(atom.args[0])){thread.success(point);}},"is_list/1":function(thread,point,atom){var list=atom.args[0];while(pl.type.is_term(list)&&list.indicator==="./2")
list=list.args[1];if(pl.type.is_term(list)&&list.indicator==="[]/0")
thread.success(point);},"current_input/1":function(thread,point,atom){var stream=atom.args[0];if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream",stream,atom.indicator));}else{if(pl.type.is_atom(stream)&&thread.get_stream_by_alias(stream.id))
stream=thread.get_stream_by_alias(stream.id);thread.prepend([new State(point.goal.replace(new Term("=",[stream,thread.get_current_input()])),point.substitution,point)]);}},"current_output/1":function(thread,point,atom){var stream=atom.args[0];if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else{if(pl.type.is_atom(stream)&&thread.get_stream_by_alias(stream.id))
stream=thread.get_stream_by_alias(stream.id);thread.prepend([new State(point.goal.replace(new Term("=",[stream,thread.get_current_output()])),point.substitution,point)]);}},"set_input/1":function(thread,point,atom){var input=atom.args[0];var stream=pl.type.is_stream(input)?input:thread.get_stream_by_alias(input.id);if(pl.type.is_variable(input)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(input)&&!pl.type.is_stream(input)&&!pl.type.is_atom(input)){thread.throw_error(pl.error.domain("stream_or_alias",input,atom.indicator));}else if(!pl.type.is_stream(stream)){thread.throw_error(pl.error.existence("stream",input,atom.indicator));}else if(stream.output===true){thread.throw_error(pl.error.permission("input","stream",input,atom.indicator));}else{thread.set_current_input(stream);thread.success(point);}},"set_output/1":function(thread,point,atom){var output=atom.args[0];var stream=pl.type.is_stream(output)?output:thread.get_stream_by_alias(output.id);if(pl.type.is_variable(output)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(output)&&!pl.type.is_stream(output)&&!pl.type.is_atom(output)){thread.throw_error(pl.error.domain("stream_or_alias",output,atom.indicator));}else if(!pl.type.is_stream(stream)){thread.throw_error(pl.error.existence("stream",output,atom.indicator));}else if(stream.input===true){thread.throw_error(pl.error.permission("output","stream",output,atom.indicator));}else{thread.set_current_output(stream);thread.success(point);}},"open/3":function(thread,point,atom){var dest=atom.args[0],mode=atom.args[1],stream=atom.args[2];thread.prepend([new State(point.goal.replace(new Term("open",[dest,mode,stream,new Term("[]",[])])),point.substitution,point)]);},"open/4":function(thread,point,atom){var dest=atom.args[0],mode=atom.args[1],stream=atom.args[2],options=atom.args[3];if(pl.type.is_variable(dest)||pl.type.is_variable(mode)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(mode)&&!pl.type.is_atom(mode)){thread.throw_error(pl.error.type("atom",mode,atom.indicator));}else if(!pl.type.is_list(options)){thread.throw_error(pl.error.type("list",options,atom.indicator));}else if(!pl.type.is_variable(stream)){thread.throw_error(pl.error.type("variable",stream,atom.indicator));}else if(!pl.type.is_atom(dest)&&!pl.type.is_streamable(dest)){thread.throw_error(pl.error.domain("source_sink",dest,atom.indicator));}else if(!pl.type.is_io_mode(mode)){thread.throw_error(pl.error.domain("io_mode",mode,atom.indicator));}else{var obj_options={};var pointer=options;var property;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){property=pointer.args[0];if(pl.type.is_variable(property)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_stream_option(property)){thread.throw_error(pl.error.domain("stream_option",property,atom.indicator));return;}
obj_options[property.id]=property.args[0].id;pointer=pointer.args[1];}
if(pointer.indicator!=="[]/0"){if(pl.type.is_variable(pointer))
thread.throw_error(pl.error.instantiation(atom.indicator));else
thread.throw_error(pl.error.type("list",options,atom.indicator));return;}else{var alias=obj_options["alias"];if(alias&&thread.get_stream_by_alias(alias)){thread.throw_error(pl.error.permission("open","source_sink",new Term("alias",[new Term(alias,[])]),atom.indicator));return;}
if(!obj_options["type"])
obj_options["type"]="text";var file;if(pl.type.is_atom(dest))
file=thread.file_system_open(dest.id,obj_options["type"],mode.id);else
file=dest.stream(obj_options["type"],mode.id);if(file===false){thread.throw_error(pl.error.permission("open","source_sink",dest,atom.indicator));return;}else if(file===null){thread.throw_error(pl.error.existence("source_sink",dest,atom.indicator));return;}
var newstream=new Stream(file,mode.id,obj_options["alias"],obj_options["type"],obj_options["reposition"]==="true",obj_options["eof_action"]);if(alias)
thread.session.streams[alias]=newstream;else
thread.session.streams[newstream.id]=newstream;thread.prepend([new State(point.goal.replace(new Term("=",[stream,newstream])),point.substitution,point)]);}}},"close/1":function(thread,point,atom){var stream=atom.args[0];thread.prepend([new State(point.goal.replace(new Term("close",[stream,new Term("[]",[])])),point.substitution,point)]);},"close/2":function(thread,point,atom){var stream=atom.args[0],options=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(options)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_list(options)){thread.throw_error(pl.error.type("list",options,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else{var obj_options={};var pointer=options;var property;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){property=pointer.args[0];if(pl.type.is_variable(property)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_close_option(property)){thread.throw_error(pl.error.domain("close_option",property,atom.indicator));return;}
obj_options[property.id]=property.args[0].id==="true";pointer=pointer.args[1];}
if(pointer.indicator!=="[]/0"){if(pl.type.is_variable(pointer))
thread.throw_error(pl.error.instantiation(atom.indicator));else
thread.throw_error(pl.error.type("list",options,atom.indicator));return;}else{if(stream2===thread.session.standard_input||stream2===thread.session.standard_output){thread.success(point);return;}else if(stream2===thread.session.current_input){thread.session.current_input=thread.session.standard_input;}else if(stream2===thread.session.current_output){thread.session.current_output=thread.session.current_output;}
if(stream2.alias!==null)
delete thread.session.streams[stream2.alias];else
delete thread.session.streams[stream2.id];if(stream2.output)
stream2.stream.flush();var closed=stream2.stream.close();stream2.stream=null;if(obj_options.force===true||closed===true){thread.success(point);}}}},"flush_output/0":function(thread,point,atom){thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("flush_output",[new Var("S")])])),point.substitution,point)]);},"flush_output/1":function(thread,point,atom){var stream=atom.args[0];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream.input===true){thread.throw_error(pl.error.permission("output","stream",output,atom.indicator));}else{stream2.stream.flush();thread.success(point);}},"stream_property/2":function(thread,point,atom){var stream=atom.args[0],property=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_variable(stream)&&(!pl.type.is_stream(stream2)||stream2.stream===null)){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(!pl.type.is_variable(property)&&!pl.type.is_stream_property(property)){thread.throw_error(pl.error.domain("stream_property",property,atom.indicator));}else{var streams=[];var states=[];if(!pl.type.is_variable(stream))
streams.push(stream2);else
for(var key in thread.session.streams)
streams.push(thread.session.streams[key]);for(var i=0;i<streams.length;i++){var properties=[];if(streams[i].filename)
properties.push(new Term("file_name",[new Term(streams[i].file_name,[])]));properties.push(new Term("mode",[new Term(streams[i].mode,[])]));properties.push(new Term(streams[i].input?"input":"output",[]));if(streams[i].alias)
properties.push(new Term("alias",[new Term(streams[i].alias,[])]));properties.push(new Term("position",[typeof streams[i].position==="number"?new Num(streams[i].position,false):new Term(streams[i].position,[])]));properties.push(new Term("end_of_stream",[new Term(streams[i].position==="end_of_stream"?"at":streams[i].position==="past_end_of_stream"?"past":"not",[])]));properties.push(new Term("eof_action",[new Term(streams[i].eof_action,[])]));properties.push(new Term("reposition",[new Term(streams[i].reposition?"true":"false",[])]));properties.push(new Term("type",[new Term(streams[i].type,[])]));for(var j=0;j<properties.length;j++){states.push(new State(point.goal.replace(new Term(",",[new Term("=",[pl.type.is_variable(stream)?stream:stream2,streams[i]]),new Term("=",[property,properties[j]])])),point.substitution,point));}}
thread.prepend(states);}},"at_end_of_stream/0":function(thread,point,atom){thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term(",",[new Term("stream_property",[new Var("S"),new Term("end_of_stream",[new Var("E")])]),new Term(",",[new Term("!",[]),new Term(";",[new Term("=",[new Var("E"),new Term("at",[])]),new Term("=",[new Var("E"),new Term("past",[])])])])])])),point.substitution,point)]);},"at_end_of_stream/1":function(thread,point,atom){var stream=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("stream_property",[stream,new Term("end_of_stream",[new Var("E")])]),new Term(",",[new Term("!",[]),new Term(";",[new Term("=",[new Var("E"),new Term("at",[])]),new Term("=",[new Var("E"),new Term("past",[])])])])])),point.substitution,point)]);},"set_stream_position/2":function(thread,point,atom){var stream=atom.args[0],position=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(position)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(!pl.type.is_stream_position(position)){thread.throw_error(pl.error.domain("stream_position",position,atom.indicator));}else if(stream2.reposition===false){thread.throw_error(pl.error.permission("reposition","stream",stream,atom.indicator));}else{if(pl.type.is_integer(position))
stream2.position=position.value;else
stream2.position=position.id;thread.success(point);}},"get_char/1":function(thread,point,atom){var char=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("get_char",[new Var("S"),char])])),point.substitution,point)]);},"get_char/2":function(thread,point,atom){var stream=atom.args[0],char=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(char)&&!pl.type.is_character(char)){thread.throw_error(pl.error.type("in_character",char,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("input","binary_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var stream_char;if(stream2.position==="end_of_stream"){stream_char="end_of_file";stream2.position="past_end_of_stream";}else{stream_char=stream2.stream.get(1,stream2.position);if(stream_char===null){thread.throw_error(pl.error.representation("character",atom.indicator));return;}
stream2.position++;}
thread.prepend([new State(point.goal.replace(new Term("=",[new Term(stream_char,[]),char])),point.substitution,point)]);}},"get_code/1":function(thread,point,atom){var code=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("get_code",[new Var("S"),code])])),point.substitution,point)]);},"get_code/2":function(thread,point,atom){var stream=atom.args[0],code=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(code)&&!pl.type.is_integer(code)){thread.throw_error(pl.error.type("integer",char,atom.indicator));}else if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("input","binary_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var stream_code;if(stream2.position==="end_of_stream"){stream_code=-1;stream2.position="past_end_of_stream";}else{stream_code=stream2.stream.get(1,stream2.position);if(stream_code===null){thread.throw_error(pl.error.representation("character",atom.indicator));return;}
stream_code=codePointAt(stream_code,0);stream2.position++;}
thread.prepend([new State(point.goal.replace(new Term("=",[new Num(stream_code,false),code])),point.substitution,point)]);}},"peek_char/1":function(thread,point,atom){var char=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("peek_char",[new Var("S"),char])])),point.substitution,point)]);},"peek_char/2":function(thread,point,atom){var stream=atom.args[0],char=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(char)&&!pl.type.is_character(char)){thread.throw_error(pl.error.type("in_character",char,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("input","binary_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var stream_char;if(stream2.position==="end_of_stream"){stream_char="end_of_file";stream2.position="past_end_of_stream";}else{stream_char=stream2.stream.get(1,stream2.position);if(stream_char===null){thread.throw_error(pl.error.representation("character",atom.indicator));return;}}
thread.prepend([new State(point.goal.replace(new Term("=",[new Term(stream_char,[]),char])),point.substitution,point)]);}},"peek_code/1":function(thread,point,atom){var code=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("peek_code",[new Var("S"),code])])),point.substitution,point)]);},"peek_code/2":function(thread,point,atom){var stream=atom.args[0],code=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(code)&&!pl.type.is_integer(code)){thread.throw_error(pl.error.type("integer",char,atom.indicator));}else if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("input","binary_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var stream_code;if(stream2.position==="end_of_stream"){stream_code=-1;stream2.position="past_end_of_stream";}else{stream_code=stream2.stream.get(1,stream2.position);if(stream_code===null){thread.throw_error(pl.error.representation("character",atom.indicator));return;}
stream_code=codePointAt(stream_code,0);}
thread.prepend([new State(point.goal.replace(new Term("=",[new Num(stream_code,false),code])),point.substitution,point)]);}},"put_char/1":function(thread,point,atom){var char=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("put_char",[new Var("S"),char])])),point.substitution,point)]);},"put_char/2":function(thread,point,atom){var stream=atom.args[0],char=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(char)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_character(char)){thread.throw_error(pl.error.type("character",char,atom.indicator));}else if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.input){thread.throw_error(pl.error.permission("output","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("output","binary_stream",stream,atom.indicator));}else{if(stream2.stream.put(char.id,stream2.position)){if(typeof stream2.position==="number")
stream2.position++;thread.success(point);}}},"put_code/1":function(thread,point,atom){var code=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("put_code",[new Var("S"),code])])),point.substitution,point)]);},"put_code/2":function(thread,point,atom){var stream=atom.args[0],code=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(code)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_integer(code)){thread.throw_error(pl.error.type("integer",code,atom.indicator));}else if(!pl.type.is_character_code(code)){thread.throw_error(pl.error.representation("character_code",atom.indicator));}else if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.input){thread.throw_error(pl.error.permission("output","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("output","binary_stream",stream,atom.indicator));}else{if(stream2.stream.put_char(fromCodePoint(code.value),stream2.position)){if(typeof stream2.position==="number")
stream2.position++;thread.success(point);}}},"nl/0":function(thread,point,atom){thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("put_char",[new Var("S"),new Term("\n",[])])])),point.substitution,point)]);},"nl/1":function(thread,point,atom){var stream=atom.args[0];thread.prepend([new State(point.goal.replace(new Term("put_char",[stream,new Term("\n",[])])),point.substitution,point)]);},"get_byte/1":function(thread,point,atom){var byte=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("get_byte",[new Var("S"),byte])])),point.substitution,point)]);},"get_byte/2":function(thread,point,atom){var stream=atom.args[0],byte=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(byte)&&!pl.type.is_byte(byte)){thread.throw_error(pl.error.type("in_byte",char,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="text"){thread.throw_error(pl.error.permission("input","text_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var stream_byte;if(stream2.position==="end_of_stream"){stream_byte="end_of_file";stream2.position="past_end_of_stream";}else{stream_byte=stream2.stream.get_byte(stream2.position);if(stream_byte===null){thread.throw_error(pl.error.representation("byte",atom.indicator));return;}
stream2.position++;}
thread.prepend([new State(point.goal.replace(new Term("=",[new Num(stream_byte,false),byte])),point.substitution,point)]);}},"peek_byte/1":function(thread,point,atom){var byte=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("peek_byte",[new Var("S"),byte])])),point.substitution,point)]);},"peek_byte/2":function(thread,point,atom){var stream=atom.args[0],byte=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(byte)&&!pl.type.is_byte(byte)){thread.throw_error(pl.error.type("in_byte",char,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="text"){thread.throw_error(pl.error.permission("input","text_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var stream_byte;if(stream2.position==="end_of_stream"){stream_byte="end_of_file";stream2.position="past_end_of_stream";}else{stream_byte=stream2.stream.get_byte(stream2.position);if(stream_byte===null){thread.throw_error(pl.error.representation("byte",atom.indicator));return;}}
thread.prepend([new State(point.goal.replace(new Term("=",[new Num(stream_byte,false),byte])),point.substitution,point)]);}},"put_byte/1":function(thread,point,atom){var byte=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("put_byte",[new Var("S"),byte])])),point.substitution,point)]);},"put_byte/2":function(thread,point,atom){var stream=atom.args[0],byte=atom.args[1];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(byte)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_byte(byte)){thread.throw_error(pl.error.type("byte",byte,atom.indicator));}else if(!pl.type.is_variable(stream)&&!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.input){thread.throw_error(pl.error.permission("output","stream",stream,atom.indicator));}else if(stream2.type==="text"){thread.throw_error(pl.error.permission("output","text_stream",stream,atom.indicator));}else{if(stream2.stream.put_byte(byte.value,stream2.position)){if(typeof stream2.position==="number")
stream2.position++;thread.success(point);}}},"read/1":function(thread,point,atom){var term=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("read_term",[new Var("S"),term,new Term("[]",[])])])),point.substitution,point)]);},"read/2":function(thread,point,atom){var stream=atom.args[0],term=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("read_term",[stream,term,new Term("[]",[])])),point.substitution,point)]);},"read_term/2":function(thread,point,atom){var term=atom.args[0],options=atom.args[1];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_input",[new Var("S")]),new Term("read_term",[new Var("S"),term,options])])),point.substitution,point)]);},"read_term/3":function(thread,point,atom){var stream=atom.args[0],term=atom.args[1],options=atom.args[2];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(options)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_list(options)){thread.throw_error(pl.error.type("list",options,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.output){thread.throw_error(pl.error.permission("input","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("input","binary_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("input","past_end_of_stream",stream,atom.indicator));}else{var obj_options={};var pointer=options;var property;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){property=pointer.args[0];if(pl.type.is_variable(property)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_read_option(property)){thread.throw_error(pl.error.domain("read_option",property,atom.indicator));return;}
obj_options[property.id]=property.args[0];pointer=pointer.args[1];}
if(pointer.indicator!=="[]/0"){if(pl.type.is_variable(pointer))
thread.throw_error(pl.error.instantiation(atom.indicator));else
thread.throw_error(pl.error.type("list",options,atom.indicator));return;}else{var char,tokenizer,expr;var text="";var tokens=[];var last_token=null;while(last_token===null||last_token.name!=="atom"||last_token.value!=="."||(expr.type===ERROR&&pl.flatten_error(new Term("throw",[expr.value])).found==="token_not_found")){char=stream2.stream.get(1,stream2.position);if(char===null){thread.throw_error(pl.error.representation("character",atom.indicator));return;}
if(char==="end_of_file"||char==="past_end_of_file"){if(expr)
thread.throw_error(pl.error.syntax(tokens[expr.len-1],". or expression expected",false));else
thread.throw_error(pl.error.syntax(null,"token not found",true));return;}
stream2.position++;text+=char;tokenizer=new Tokenizer(thread);tokenizer.new_text(text);tokens=tokenizer.get_tokens();last_token=tokens!==null&&tokens.length>0?tokens[tokens.length-1]:null;if(tokens===null)
continue;expr=parseExpr(thread,tokens,0,thread.__get_max_priority(),false);}
if(expr.type===SUCCESS&&expr.len===tokens.length-1&&last_token.value==="."){expr=expr.value.rename(thread);var eq=new Term("=",[term,expr]);if(obj_options.variables){var vars=arrayToList(map(nub(expr.variables()),function(v){return new Var(v);}));eq=new Term(",",[eq,new Term("=",[obj_options.variables,vars])])}
if(obj_options.variable_names){var vars=arrayToList(map(nub(expr.variables()),function(v){var prop;for(prop in thread.session.renamed_variables){if(thread.session.renamed_variables.hasOwnProperty(prop)){if(thread.session.renamed_variables[prop]===v)
break;}}
return new Term("=",[new Term(prop,[]),new Var(v)]);}));eq=new Term(",",[eq,new Term("=",[obj_options.variable_names,vars])])}
if(obj_options.singletons){var vars=arrayToList(map(new Rule(expr,null).singleton_variables(),function(v){var prop;for(prop in thread.session.renamed_variables){if(thread.session.renamed_variables.hasOwnProperty(prop)){if(thread.session.renamed_variables[prop]===v)
break;}}
return new Term("=",[new Term(prop,[]),new Var(v)]);}));eq=new Term(",",[eq,new Term("=",[obj_options.singletons,vars])])}
thread.prepend([new State(point.goal.replace(eq),point.substitution,point)]);}else{if(expr.type===SUCCESS)
thread.throw_error(pl.error.syntax(tokens[expr.len],"unexpected token",false));else
thread.throw_error(expr.value);}}}},"write/1":function(thread,point,atom){var term=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("write",[new Var("S"),term])])),point.substitution,point)]);},"write/2":function(thread,point,atom){var stream=atom.args[0],term=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("write_term",[stream,term,new Term(".",[new Term("quoted",[new Term("false",[])]),new Term(".",[new Term("ignore_ops",[new Term("false")]),new Term(".",[new Term("numbervars",[new Term("true")]),new Term("[]",[])])])])])),point.substitution,point)]);},"writeq/1":function(thread,point,atom){var term=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("writeq",[new Var("S"),term])])),point.substitution,point)]);},"writeq/2":function(thread,point,atom){var stream=atom.args[0],term=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("write_term",[stream,term,new Term(".",[new Term("quoted",[new Term("true",[])]),new Term(".",[new Term("ignore_ops",[new Term("false")]),new Term(".",[new Term("numbervars",[new Term("true")]),new Term("[]",[])])])])])),point.substitution,point)]);},"write_canonical/1":function(thread,point,atom){var term=atom.args[0];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("write_canonical",[new Var("S"),term])])),point.substitution,point)]);},"write_canonical/2":function(thread,point,atom){var stream=atom.args[0],term=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("write_term",[stream,term,new Term(".",[new Term("quoted",[new Term("true",[])]),new Term(".",[new Term("ignore_ops",[new Term("true")]),new Term(".",[new Term("numbervars",[new Term("false")]),new Term("[]",[])])])])])),point.substitution,point)]);},"write_term/2":function(thread,point,atom){var term=atom.args[0],options=atom.args[1];thread.prepend([new State(point.goal.replace(new Term(",",[new Term("current_output",[new Var("S")]),new Term("write_term",[new Var("S"),term,options])])),point.substitution,point)]);},"write_term/3":function(thread,point,atom){var stream=atom.args[0],term=atom.args[1],options=atom.args[2];var stream2=pl.type.is_stream(stream)?stream:thread.get_stream_by_alias(stream.id);if(pl.type.is_variable(stream)||pl.type.is_variable(options)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_list(options)){thread.throw_error(pl.error.type("list",options,atom.indicator));}else if(!pl.type.is_stream(stream)&&!pl.type.is_atom(stream)){thread.throw_error(pl.error.domain("stream_or_alias",stream,atom.indicator));}else if(!pl.type.is_stream(stream2)||stream2.stream===null){thread.throw_error(pl.error.existence("stream",stream,atom.indicator));}else if(stream2.input){thread.throw_error(pl.error.permission("output","stream",stream,atom.indicator));}else if(stream2.type==="binary"){thread.throw_error(pl.error.permission("output","binary_stream",stream,atom.indicator));}else if(stream2.position==="past_end_of_stream"&&stream2.eof_action==="error"){thread.throw_error(pl.error.permission("output","past_end_of_stream",stream,atom.indicator));}else{var obj_options={};var pointer=options;var property;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){property=pointer.args[0];if(pl.type.is_variable(property)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_write_option(property)){thread.throw_error(pl.error.domain("write_option",property,atom.indicator));return;}
obj_options[property.id]=property.args[0].id==="true";pointer=pointer.args[1];}
if(pointer.indicator!=="[]/0"){if(pl.type.is_variable(pointer))
thread.throw_error(pl.error.instantiation(atom.indicator));else
thread.throw_error(pl.error.type("list",options,atom.indicator));return;}else{obj_options.session=thread.session;var text=term.toString(obj_options);stream2.stream.put(text,stream2.position);if(typeof stream2.position==="number")
stream2.position+=text.length;thread.success(point);}}},"halt/0":function(thread,point,_){if(thread.get_flag("nodejs").indicator==="true/0")
process.exit();thread.points=[];},"halt/1":function(thread,point,atom){var int=atom.args[0];if(pl.type.is_variable(int)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_integer(int)){thread.throw_error(pl.error.type("integer",int,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0")
process.exit(int.value);thread.points=[];}},"current_prolog_flag/2":function(thread,point,atom){var flag=atom.args[0],value=atom.args[1];if(!pl.type.is_variable(flag)&&!pl.type.is_atom(flag)){thread.throw_error(pl.error.type("atom",flag,atom.indicator));}else if(!pl.type.is_variable(flag)&&!pl.type.is_flag(flag)){thread.throw_error(pl.error.domain("prolog_flag",flag,atom.indicator));}else{var states=[];for(var name in pl.flag){if(!pl.flag.hasOwnProperty(name))continue;var goal=new Term(",",[new Term("=",[new Term(name),flag]),new Term("=",[thread.get_flag(name),value])]);states.push(new State(point.goal.replace(goal),point.substitution,point));}
thread.prepend(states);}},"set_prolog_flag/2":function(thread,point,atom){var flag=atom.args[0],value=atom.args[1];if(pl.type.is_variable(flag)||pl.type.is_variable(value)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(flag)){thread.throw_error(pl.error.type("atom",flag,atom.indicator));}else if(!pl.type.is_flag(flag)){thread.throw_error(pl.error.domain("prolog_flag",flag,atom.indicator));}else if(!pl.type.is_value_flag(flag,value)){thread.throw_error(pl.error.domain("flag_value",new Term("+",[flag,value]),atom.indicator));}else if(!pl.type.is_modifiable_flag(flag)){thread.throw_error(pl.error.permission("modify","flag",flag));}else{thread.session.flag[flag.id]=value;thread.success(point);}},"consult/1":function(thread,point,atom){var src=atom.args[0];if(pl.type.is_variable(src)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(src)){thread.throw_error(pl.error.type("atom",src,atom.indicator));}else{if(thread.consult(src.id))
thread.success(point);}},"get_time/1":function(thread,point,atom){var time=atom.args[0];if(!pl.type.is_variable(time)&&!pl.type.is_number(time)){thread.throw_error(pl.error.type("number",time,atom.indicator));}else{var current=new Num(Date.now(),true);thread.prepend([new State(point.goal.replace(new Term("=",[time,current])),point.substitution,point)]);}},"phrase/3":function(thread,point,atom){var grbody=atom.args[0],s0=atom.args[1],s=atom.args[2];if(pl.type.is_variable(grbody)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_callable(grbody)){thread.throw_error(pl.error.type("callable",grbody,atom.indicator));}else{var goal=body_to_dcg(grbody.clone(),s0,thread);if(goal!==null){thread.prepend([new State(point.goal.replace(new Term(",",[goal.value,new Term("=",[goal.variable,s])])),point.substitution,point)]);}}},"phrase/2":function(thread,point,atom){var grbody=atom.args[0],s0=atom.args[1];thread.prepend([new State(point.goal.replace(new Term("phrase",[grbody,s0,new Term("[]",[])])),point.substitution,point)]);},"version/0":function(thread,point,atom){var msg="Welcome to Tau Prolog version "+version.major+"."+version.minor+"."+version.patch+"\n";msg+="Tau Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.\n";msg+="Please run ?- license. for legal details.\n";msg+="For online help and background, visit http:/tau-prolog.org";thread.prepend([new State(point.goal.replace(new Term("write",[new Term(msg,[])])),point.substitution,point)]);},"license/0":function(thread,point,atom){var msg="Tau Prolog. A Prolog interpreter in JavaScript.\n";msg+="Copyright (C) 2017 - 2020 José Antonio Riaza Valverde\n\n";msg+="Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n";msg+="1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n";msg+="2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n";msg+="3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\n";msg+="THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n";msg+="You should have received a copy of the BSD 3-Clause License along with this program. If not, see https://opensource.org/licenses/BSD-3-Clause";thread.prepend([new State(point.goal.replace(new Term("write",[new Term(msg,[])])),point.substitution,point)]);}},flag:{bounded:{allowed:[new Term("true"),new Term("false")],value:new Term("true"),changeable:false},max_integer:{allowed:[new Num(Number.MAX_SAFE_INTEGER)],value:new Num(Number.MAX_SAFE_INTEGER),changeable:false},min_integer:{allowed:[new Num(Number.MIN_SAFE_INTEGER)],value:new Num(Number.MIN_SAFE_INTEGER),changeable:false},integer_rounding_function:{allowed:[new Term("down"),new Term("toward_zero")],value:new Term("toward_zero"),changeable:false},char_conversion:{allowed:[new Term("on"),new Term("off")],value:new Term("on"),changeable:true},debug:{allowed:[new Term("on"),new Term("off")],value:new Term("off"),changeable:true},max_arity:{allowed:[new Term("unbounded")],value:ne
continue;if(pl.type.is_term(s)&&pl.type.is_term(t)){if(s.indicator!==t.indicator)
return null;if(s.indicator==="./2"){var pointer_s=s,pointer_t=t;while(pointer_s.indicator==="./2"&&pointer_t.indicator==="./2"){G.push({left:pointer_s.args[0],right:pointer_t.args[0]});pointer_s=pointer_s.args[1];pointer_t=pointer_t.args[1];}
G.push({left:pointer_s,right:pointer_t});}else{for(var i=0;i<s.args.length;i++)
G.push({left:s.args[i],right:t.args[i]});}}else if(pl.type.is_number(s)&&pl.type.is_number(t)){if(s.value!==t.value||s.is_float!==t.is_float)
return null;}else if(pl.type.is_variable(s)){if(pl.type.is_variable(t)&&s.id===t.id)
continue;if(occurs_check===true&&indexOf(t.variables(),s.id)!==-1)
return null;if(s.id!=="_"){var subs=new Substitution();subs.add(s.id,t);for(var i=0;i<G.length;i++){G[i].left=G[i].left.apply(subs);G[i].right=G[i].right.apply(subs);}
for(var i in links)
links[i]=links[i].apply(subs);links[s.id]=t;}}else if(pl.type.is_variable(t)){G.push({left:t,right:s});}else if(s.unify!==undefined){if(!s.unify(t))
return null;}else{return null;}}
return new Substitution(links);},compare:function(obj1,obj2){var type=pl.type.compare(obj1,obj2);return type!==0?type:obj1.compare(obj2);},arithmetic_compare:function(thread,obj1,obj2){var expr1=obj1.interpret(thread);if(!pl.type.is_number(expr1)){return expr1;}else{var expr2=obj2.interpret(thread);if(!pl.type.is_number(expr2)){return expr2;}else{return expr1.value<expr2.value?-1:(expr1.value>expr2.value?1:0);}}},operate:function(thread,obj){if(pl.type.is_operator(obj)){var op=pl.type.is_operator(obj);var args=[],value;var type=false;for(var i=0;i<obj.args.length;i++){value=obj.args[i].interpret(thread);if(!pl.type.is_number(value)){return value;}else if(op.type_args!==null&&value.is_float!==op.type_args){return pl.error.type(op.type_args?"float":"integer",value,thread.__call_indicator);}else{args.push(value.value);}
type=type||value.is_float;}
args.push(thread);value=pl.arithmetic.evaluation[obj.indicator].fn.apply(this,args);type=op.type_result===null?type:op.type_result;if(pl.type.is_term(value)){return value;}else if(value===Number.POSITIVE_INFINITY||value===Number.NEGATIVE_INFINITY){return pl.error.evaluation("overflow",thread.__call_indicator);}else if(type===false&&thread.get_flag("bounded").id==="true"&&(value>thread.get_flag("max_integer").value||value<thread.get_flag("min_integer").value)){return pl.error.evaluation("int_overflow",thread.__call_indicator);}else{return new Num(value,type);}}else{return pl.error.type("evaluable",obj.indicator,thread.__call_indicator);}},error:{existence:function(type,object,indicator){if(typeof object==="string")
object=str_indicator(object);return new Term("error",[new Term("existence_error",[new Term(type),object]),str_indicator(indicator)]);},type:function(expected,found,indicator){return new Term("error",[new Term("type_error",[new Term(expected),found]),str_indicator(indicator)]);},instantiation:function(indicator){return new Term("error",[new Term("instantiation_error"),str_indicator(indicator)]);},domain:function(expected,found,indicator){return new Term("error",[new Term("domain_error",[new Term(expected),found]),str_indicator(indicator)]);},representation:function(flag,indicator){return new Term("error",[new Term("representation_error",[new Term(flag)]),str_indicator(indicator)]);},permission:function(operation,type,found,indicator){return new Term("error",[new Term("permission_error",[new Term(operation),new Term(type),found]),str_indicator(indicator)]);},evaluation:function(error,indicator){return new Term("error",[new Term("evaluation_error",[new Term(error)]),str_indicator(indicator)]);},syntax:function(token,expected,last){token=token||{value:"",line:0,column:0,matches:[""],start:0};var position=last&&token.matches.length>0?token.start+token.matches[0].length:token.start;var found=last?new Term("token_not_found"):new Term("found",[new Term(token.value.toString())]);var info=new Term(".",[new Term("line",[new Num(token.line+1)]),new Term(".",[new Term("column",[new Num(position+1)]),new Term(".",[found,new Term("[]",[])])])]);return new Term("error",[new Term("syntax_error",[new Term(expected)]),info]);},syntax_by_predicate:function(expected,indicator){return new Term("error",[new Term("syntax_error",[new Term(expected)]),str_indicator(indicator)]);}},warning:{singleton:function(variables,rule,line){var list=new Term("[]");for(var i=variables.length-1;i>=0;i--)
list=new Term(".",[new Var(variables[i]),list]);return new Term("warning",[new Term("singleton_variables",[list,str_indicator(rule)]),new Term(".",[new Term("line",[new Num(line,false)]),new Term("[]")])]);},failed_goal:function(goal,line){return new Term("warning",[new Term("failed_goal",[goal]),new Term(".",[new Term("line",[new Num(line,false)]),new Term("[]")])]);}},format_variable:function(variable){return"_"+variable;},format_answer:function(answer,thread,options){if(thread instanceof Session)
thread=thread.thread;var options=options?options:{};options.session=thread?thread.session:undefined;if(pl.type.is_error(answer)){return"uncaught exception: "+answer.args[0].toString();}else if(answer===false){return"false.";}else if(answer===null){return"limit exceeded ;";}else{var i=0;var str="";if(pl.type.is_substitution(answer)){var dom=answer.domain(true);for(var link in answer.links){if(!answer.links.hasOwnProperty(link))continue;if(pl.type.is_variable(answer.links[link])){var links={};links[answer.links[link].id]=new Var(link);answer=answer.apply(new Substitution(links));}}
answer=answer.filter(function(id,value){return!pl.type.is_variable(value)||pl.type.is_variable(value)&&answer.has_attributes(id)||indexOf(dom,value.id)!==-1&&id!==value.id;});}
for(var link in answer.links){if(!answer.links.hasOwnProperty(link))
continue;if(pl.type.is_variable(answer.links[link])&&link===answer.links[link].id){var attrs=answer.attrs[link];for(var module in attrs){if(!attrs.hasOwnProperty(module))
continue;i++;if(str!=="")
str+=", ";str+="put_attr("+link+", "+module+", "+attrs[module].toString(options)+")";}}else{i++;if(str!=="")
str+=", ";str+=link.toString(options)+" = "+
answer.links[link].toString(options,{priority:"700",class:"xfx",indicator:"=/2"},"right");}}
var delimiter=typeof thread==="undefined"||thread.points.length>0?" ;":".";if(i===0){return"true"+delimiter;}else{return str+delimiter;}}},flatten_error:function(error){if(!pl.type.is_error(error))return null;error=error.args[0];var obj={};obj.type=error.args[0].id;obj.thrown=obj.type==="syntax_error"?null:error.args[1].id;obj.expected=null;obj.found=null;obj.representation=null;obj.existence=null;obj.existence_type=null;obj.line=null;obj.column=null;obj.permission_operation=null;obj.permission_type=null;obj.evaluation_type=null;if(obj.type==="type_error"||obj.type==="domain_error"){obj.expected=error.args[0].args[0].id;obj.found=error.args[0].args[1].toString();}else if(obj.type==="syntax_error"){if(error.args[1].indicator==="./2"){obj.expected=error.args[0].args[0].id;obj.found=error.args[1].args[1].args[1].args[0];obj.found=obj.found.id==="token_not_found"?obj.found.id:obj.found.args[0].id;obj.line=error.args[1].args[0].args[0].value;obj.column=error.args[1].args[1].args[0].args[0].value;}else{obj.thrown=error.args[1].id;}}else if(obj.type==="permission_error"){obj.found=error.args[0].args[2].toString();obj.permission_operation=error.args[0].args[0].id;obj.permission_type=error.args[0].args[1].id;}else if(obj.type==="evaluation_error"){obj.evaluation_type=error.args[0].args[0].id;}else if(obj.type==="representation_error"){obj.representation=error.args[0].args[0].id;}else if(obj.type==="existence_error"){obj.existence=error.args[0].args[1].toString();obj.existence_type=error.args[0].args[0].id;}
return obj;},create:function(limit,output){return new pl.type.Session(limit,output);}};if(typeof module!=='undefined'){prolog=pl;}else{window.prolog=pl;}})();(function(pl){var predicates=function(){return{"append/2":[new pl.type.Rule(new pl.type.Term("append",[new pl.type.Var("X"),new pl.type.Var("L")]),new pl.type.Term("foldl",[new pl.type.Term("append",[]),new pl.type.Var("X"),new pl.type.Term("[]",[]),new pl.type.Var("L")]))],"append/3":[new pl.type.Rule(new pl.type.Term("append",[new pl.type.Term("[]",[]),new pl.type.Var("X"),new pl.type.Var("X")]),null),new pl.type.Rule(new pl.type.Term("append",[new pl.type.Term(".",[new pl.type.Var("H"),new pl.type.Var("T")]),new pl.type.Var("X"),new pl.type.Term(".",[new pl.type.Var("H"),new pl.type.Var("S")])]),new pl.type.Term("append",[new pl.type.Var("T"),new pl.type.Var("X"),new pl.type.Var("S")]))],"member/2":[new pl.type.Rule(new pl.type.Term("member",[new pl.type.Var("X"),new pl.type.Term(".",[new pl.type.Var("X"),new pl.type.Var("_")])]),null),new pl.type.Rule(new pl.type.Term("member",[new pl.type.Var("X"),new pl.type.Term(".",[new pl.type.Var("_"),new pl.type.Var("Xs")])]),new pl.type.Term("member",[new pl.type.Var("X"),new pl.type.Var("Xs")]))],"permutation/2":[new pl.type.Rule(new pl.type.Term("permutation",[new pl.type.Term("[]",[]),new pl.type.Term("[]",[])]),null),new pl.type.Rule(new pl.type.Term("permutation",[new pl.type.Term(".",[new pl.type.Var("H"),new pl.type.Var("T")]),new pl.type.Var("S")]),new pl.type.Term(",",[new pl.type.Term("permutation",[new pl.type.Var("T"),new pl.type.Var("P")]),new pl.type.Term(",",[new pl.type.Term("append",[new pl.type.Var("X"),new pl.type.Var("Y"),new pl.type.Var("P")]),new pl.type.Term("append",[new pl.type.Var("X"),new pl.type.Term(".",[new pl.type.Var("H"),new pl.type.Var("Y")]),new pl.type.Var("S")])])]))],"maplist/2":[new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("_"),new pl.type.Term("[]",[])]),null),new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Term(".",[new pl.type.Var("X"),new pl.type.Var("Xs")])]),new pl.type.Term(",",[new pl.type.Term("call",[new pl.type.Var("P"),new pl.type.Var("X")]),new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Var("Xs")])]))],"maplist/3":[new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("_"),new pl.type.Term("[]",[]),new pl.type.Term("[]",[])]),null),new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Term(".",[new pl.type.Var("A"),new pl.type.Var("As")]),new pl.type.Term(".",[new pl.type.Var("B"),new pl.type.Var("Bs")])]),new pl.type.Term(",",[new pl.type.Term("call",[new pl.type.Var("P"),new pl.type.Var("A"),new pl.type.Var("B")]),new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Var("As"),new pl.type.Var("Bs")])]))],"maplist/4":[new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("_"),new pl.type.Term("[]",[]),new pl.type.Term("[]",[]),new pl.type.Term("[]",[])]),null),new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Term(".",[new pl.type.Var("A"),new pl.type.Var("As")]),new pl.type.Term(".",[new pl.type.Var("B"),new pl.type.Var("Bs")]),new pl.type.Term(".",[new pl.type.Var("C"),new pl.type.Var("Cs")])]),new pl.type.Term(",",[new pl.type.Term("call",[new pl.type.Var("P"),new pl.type.Var("A"),new pl.type.Var("B"),new pl.type.Var("C")]),new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Var("As"),new pl.type.Var("Bs"),new pl.type.Var("Cs")])]))],"maplist/5":[new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("_"),new pl.type.Term("[]",[]),new pl.type.Term("[]",[]),new pl.type.Term("[]",[]),new pl.type.Term("[]",[])]),null),new pl.type.Rule(new pl.type.Term("maplist",[new pl.type.Var("P"),new pl.type.Term(".",[new pl.type.Var("A"),new pl.type.Var("As")]),new pl.type.Term(".",[new pl.type.Var("B"),new pl.type.Var("Bs")]),new pl.type.Term(".",[new pl.type.Var("C"),new pl.type.Var("Cs")]),new pl.type.Term(".",[new pl.type.Var("D"),new pl.type.Var("Ds")])]),new pl.type.Term(",",[new pl.type.Term("call",[new pl.type.Var("P"),new pl.t
newgoal=new pl.type.Term(",",[newgoal,new pl.type.Term("!",[])]);thread.prepend([new pl.type.State(point.goal.replace(newgoal),point.substitution,point)]);}},"length/3":[new pl.type.Rule(new pl.type.Term("length",[new pl.type.Term("[]",[]),new pl.type.Var("N"),new pl.type.Var("N")]),null),new pl.type.Rule(new pl.type.Term("length",[new pl.type.Term(".",[new pl.type.Var("_"),new pl.type.Var("X")]),new pl.type.Var("A"),new pl.type.Var("N")]),new pl.type.Term(",",[new pl.type.Term("succ",[new pl.type.Var("A"),new pl.type.Var("B")]),new pl.type.Term("length",[new pl.type.Var("X"),new pl.type.Var("B"),new pl.type.Var("N")])]))],"replicate/3":function(thread,point,atom){var elem=atom.args[0],times=atom.args[1],list=atom.args[2];if(pl.type.is_variable(times)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_integer(times)){thread.throw_error(pl.error.type("integer",times,atom.indicator));}else if(times.value<0){thread.throw_error(pl.error.domain("not_less_than_zero",times,atom.indicator));}else if(!pl.type.is_variable(list)&&!pl.type.is_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var replicate=new pl.type.Term("[]");for(var i=0;i<times.value;i++){replicate=new pl.type.Term(".",[elem,replicate]);}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[replicate,list])),point.substitution,point)]);}},"sort/2":function(thread,point,atom){var list=atom.args[0],expected=atom.args[1];if(pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(expected)&&!pl.type.is_fully_list(expected)){thread.throw_error(pl.error.type("list",expected,atom.indicator));}else{var arr=[];var pointer=list;while(pointer.indicator==="./2"){arr.push(pointer.args[0]);pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_empty_list(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var sorted_arr=arr.sort(pl.compare);for(var i=sorted_arr.length-1;i>0;i--){if(sorted_arr[i].equals(sorted_arr[i-1]))
sorted_arr.splice(i,1);}
var sorted_list=new pl.type.Term("[]");for(var i=sorted_arr.length-1;i>=0;i--){sorted_list=new pl.type.Term(".",[sorted_arr[i],sorted_list]);}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[sorted_list,expected])),point.substitution,point)]);}}},"msort/2":function(thread,point,atom){var list=atom.args[0],expected=atom.args[1];if(pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(expected)&&!pl.type.is_fully_list(expected)){thread.throw_error(pl.error.type("list",expected,atom.indicator));}else{var arr=[];var pointer=list;while(pointer.indicator==="./2"){arr.push(pointer.args[0]);pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_empty_list(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var sorted_arr=arr.sort(pl.compare);var sorted_list=new pl.type.Term("[]");for(var i=sorted_arr.length-1;i>=0;i--){sorted_list=new pl.type.Term(".",[sorted_arr[i],sorted_list]);}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[sorted_list,expected])),point.substitution,point)]);}}},"keysort/2":function(thread,point,atom){var list=atom.args[0],expected=atom.args[1];if(pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(expected)&&!pl.type.is_fully_list(expected)){thread.throw_error(pl.error.type("list",expected,atom.indicator));}else{var arr=[];var elem;var pointer=list;while(pointer.indicator==="./2"){elem=pointer.args[0];if(pl.type.is_variable(elem)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_term(elem)||elem.indicator!=="-/2"){thread.throw_error(pl.error.type("pair",elem,atom.indicator));return;}
elem.args[0].pair=elem.args[1];arr.push(elem.args[0]);pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_empty_list(pointer)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var sorted_arr=arr.sort(pl.compare);var sorted_list=new pl.type.Term("[]");for(var i=sorted_arr.length-1;i>=0;i--){sorted_list=new pl.type.Term(".",[new pl.type.Term("-",[sorted_arr[i],sorted_arr[i].pair]),sorted_list]);delete sorted_arr[i].pair;}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[sorted_list,expected])),point.substitution,point)]);}}},"take/3":function(thread,point,atom){var number=atom.args[0],list=atom.args[1],take=atom.args[2];if(pl.type.is_variable(list)||pl.type.is_variable(number)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else if(!pl.type.is_integer(number)){thread.throw_error(pl.error.type("integer",number,atom.indicator));}else if(!pl.type.is_variable(take)&&!pl.type.is_list(take)){thread.throw_error(pl.error.type("list",take,atom.indicator));}else{var i=number.value;var arr=[];var pointer=list;while(i>0&&pointer.indicator==="./2"){arr.push(pointer.args[0]);pointer=pointer.args[1];i--;}
if(i===0){var new_list=new pl.type.Term("[]");for(var i=arr.length-1;i>=0;i--){new_list=new pl.type.Term(".",[arr[i],new_list]);}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[new_list,take])),point.substitution,point)]);}}},"drop/3":function(thread,point,atom){var number=atom.args[0],list=atom.args[1],drop=atom.args[2];if(pl.type.is_variable(list)||pl.type.is_variable(number)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else if(!pl.type.is_integer(number)){thread.throw_error(pl.error.type("integer",number,atom.indicator));}else if(!pl.type.is_variable(drop)&&!pl.type.is_list(drop)){thread.throw_error(pl.error.type("list",drop,atom.indicator));}else{var i=number.value;var arr=[];var pointer=list;while(i>0&&pointer.indicator==="./2"){arr.push(pointer.args[0]);pointer=pointer.args[1];i--;}
if(i===0)
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[pointer,drop])),point.substitution,point)]);}},"reverse/2":function(thread,point,atom){var list=atom.args[0],reversed=atom.args[1];var ins_list=pl.type.is_instantiated_list(list);var ins_reversed=pl.type.is_instantiated_list(reversed);if(pl.type.is_variable(list)&&pl.type.is_variable(reversed)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(list)&&!pl.type.is_fully_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else if(!pl.type.is_variable(reversed)&&!pl.type.is_fully_list(reversed)){thread.throw_error(pl.error.type("list",reversed,atom.indicator));}else if(!ins_list&&!ins_reversed){thread.throw_error(pl.error.instantiation(atom.indicator));}else{var pointer=ins_list?list:reversed;var new_reversed=new pl.type.Term("[]",[]);while(pointer.indicator==="./2"){new_reversed=new pl.type.Term(".",[pointer.args[0],new_reversed]);pointer=pointer.args[1];}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[new_reversed,ins_list?reversed:list])),point.substitution,point)]);}},"list_to_set/2":function(thread,point,atom){var list=atom.args[0],lset=atom.args[1];if(pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else{var pointer=list;var elems=[];while(pointer.indicator==="./2"){elems.push(pointer.args[0]);pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_term(pointer)||pointer.indicator!=="[]/0"){thread.throw_error(pl.error.type("list",list,atom.indicator));}else{var arr=[],nub=new pl.type.Term("[]",[]);var match;for(var i=0;i<elems.length;i++){match=false
for(var j=0;j<arr.length&&!match;j++){match=pl.compare(elems[i],arr[j])===0;}
if(!match)
arr.push(elems[i]);}
for(i=arr.length-1;i>=0;i--)
nub=new pl.type.Term(".",[arr[i],nub]);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[lset,nub])),point.substitution,point)]);}}}};};var exports=["append/2","append/3","member/2","permutation/2","maplist/2","maplist/3","maplist/4","maplist/5","maplist/6","maplist/7","maplist/8","include/3","exclude/3","foldl/4","sum_list/2","max_list/2","min_list/2","prod_list/2","last/2","prefix/2","nth0/3","nth1/3","nth0/4","nth1/4","length/2","replicate/3","select/3","sort/2","msort/2","keysort/2","take/3","drop/3","reverse/2","list_to_set/2"];new pl.type.Module("lists",predicates(),exports);})(prolog);(function(pl){var predicates=function(){return{"maybe/0":function(thread,point,_){if(Math.random()<0.5){thread.success(point);}},"maybe/1":function(thread,point,atom){var num=atom.args[0];if(Math.random()<num.value){thread.success(point);}},"random/1":function(thread,point,atom){var rand=atom.args[0];if(!pl.type.is_variable(rand)&&!pl.type.is_number(rand)){thread.throw_error(pl.error.type("number",rand,atom.indicator));}else{var gen=Math.random();thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[rand,new pl.type.Num(gen,true)])),point.substitution,point)]);}},"random/3":function(thread,point,atom){var lower=atom.args[0],upper=atom.args[1],rand=atom.args[2];if(pl.type.is_variable(lower)||pl.type.is_variable(upper)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_number(lower)){thread.throw_error(pl.error.type("number",lower,atom.indicator));}else if(!pl.type.is_number(upper)){thread.throw_error(pl.error.type("number",upper,atom.indicator));}else if(!pl.type.is_variable(rand)&&!pl.type.is_number(rand)){thread.throw_error(pl.error.type("number",rand,atom.indicator));}else{if(lower.value<upper.value){var float=lower.is_float||upper.is_float;var gen=lower.value+Math.random()*(upper.value-lower.value);if(!float)
gen=Math.floor(gen);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[rand,new pl.type.Num(gen,float)])),point.substitution,point)]);}}},"random_between/3":function(thread,point,atom){var lower=atom.args[0],upper=atom.args[1],rand=atom.args[2];if(pl.type.is_variable(lower)||pl.type.is_variable(upper)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_integer(lower)){thread.throw_error(pl.error.type("integer",lower,atom.indicator));}else if(!pl.type.is_integer(upper)){thread.throw_error(pl.error.type("integer",upper,atom.indicator));}else if(!pl.type.is_variable(rand)&&!pl.type.is_integer(rand)){thread.throw_error(pl.error.type("integer",rand,atom.indicator));}else{if(lower.value<upper.value){var gen=Math.floor(lower.value+Math.random()*(upper.value-lower.value+1));thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[rand,new pl.type.Num(gen,false)])),point.substitution,point)]);}}},"random_member/2":function(thread,point,atom){var member=atom.args[0],list=atom.args[1];if(pl.type.is_variable(list)){thread.throw_error(pl.error.instantiation(atom.indicator));}else{var array=[];var pointer=list;while(pointer.indicator==="./2"){array.push(pointer.args[0]);pointer=pointer.args[1];}
if(array.length>0){var gen=Math.floor(Math.random()*array.length);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[member,array[gen]])),point.substitution,point)]);}}},"random_permutation/2":function(thread,point,atom){var i;var list=atom.args[0],permutation=atom.args[1];var ins_list=pl.type.is_instantiated_list(list);var ins_permutation=pl.type.is_instantiated_list(permutation);if(pl.type.is_variable(list)&&pl.type.is_variable(permutation)||!ins_list&&!ins_permutation){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(list)&&!pl.type.is_fully_list(list)){thread.throw_error(pl.error.type("list",list,atom.indicator));}else if(!pl.type.is_variable(permutation)&&!pl.type.is_fully_list(permutation)){thread.throw_error(pl.error.type("list",permutation,atom.indicator));}else{var pointer=ins_list?list:permutation;var array=[];while(pointer.indicator==="./2"){array.push(pointer.args[0]);pointer=pointer.args[1];}
for(i=0;i<array.length;i++){var rand=Math.floor(Math.random()*array.length);var tmp=array[i];array[i]=array[rand];array[rand]=tmp;}
var new_list=new pl.type.Term("[]",[]);for(i=array.length-1;i>=0;i--)
new_list=new pl.type.Term(".",[array[i],new_list]);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[new_list,ins_list?permutation:list])),point.substitution,point)]);}}};};var exports=["maybe/0","maybe/1","random/1","random/3","random_between/3","random_member/2","random_permutation/2"];new pl.type.Module("random",predicates(),exports);})(prolog);(function(pl){var predicates=function(){return{"time/1":function(thread,point,atom){var goal=atom.args[0];if(pl.type.is_variable(goal)){thread.throw_error(pl.error.instantiation(thread.level));}else if(!pl.type.is_callable(goal)){thread.throw_error(pl.error.type("callable",goal,thread.level));}else{var points=thread.points;thread.points=[new pl.type.State(goal,point.substitution,point)];var t0=Date.now();var c0=pl.statistics.getCountTerms();var i0=thread.total_steps;var format_success=thread.session.format_success;var format_error=thread.session.format_error;thread.session.format_success=function(x){return x.substitution;};thread.session.format_error=function(x){return x.goal;};var callback=function(answer){var t1=Date.now();var c1=pl.statistics.getCountTerms();var i1=thread.total_steps;var newpoints=thread.points;thread.points=points;thread.session.format_success=format_success;thread.session.format_error=format_error;if(pl.type.is_error(answer)){thread.throw_error(answer.args[0]);}else if(answer===null){thread.points=points;thread.prepend([point]);thread.__calls.shift()(null);}else{console.log("% Tau Prolog: executed in "+(t1-t0)+" milliseconds, "+(c1-c0)+" atoms created, "+(i1-i0)+" resolution steps performed.");if(answer!==false){for(var i=0;i<newpoints.length;i++){if(newpoints[i].goal===null)
newpoints[i].goal=new pl.type.Term("true",[]);newpoints[i].goal=point.goal.replace(new pl.type.Term("time",[newpoints[i].goal]));}
thread.points=points;thread.prepend(newpoints);thread.prepend([new pl.type.State(point.goal.apply(answer).replace(null),answer,point)]);}}};thread.__calls.unshift(callback);}},"statistics/0":function(thread,point,atom){var stats="% Tau Prolog statistics";for(var x in statistics)
stats+="\n%%% "+x+": "+statistics[x](thread).toString();thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("write",[new pl.type.Term(stats)])),point.substitution,point)]);},"statistics/2":function(thread,point,atom){var key=atom.args[0],value=atom.args[1];if(!pl.type.is_variable(key)&&!pl.type.is_atom(key)){thread.throw_error(pl.error.type("atom",key,atom.indicator));}else if(!pl.type.is_variable(key)&&statistics[key.id]===undefined){thread.throw_error(pl.error.domain("statistics_key",key,atom.indicator));}else{if(!pl.type.is_variable(key)){var value_=statistics[key.id](thread);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,value_])),point.substitution,point)]);}else{var states=[];for(var x in statistics){var value_=statistics[x](thread);states.push(new pl.type.State(point.goal.replace(new pl.type.Term(",",[new pl.type.Term("=",[key,new pl.type.Term(x,[])]),new pl.type.Term("=",[value,value_])])),point.substitution,point));}
thread.prepend(states);}}}};};var exports=["time/1","statistics/0","statistics/2"];var statistics={atoms:function(thread){return new pl.type.Num(pl.statistics.getCountTerms(),false);},clauses:function(thread){var total=0;for(var x in thread.session.rules)
if(thread.session.rules[x]instanceof Array)
total+=thread.session.rules[x].length;for(var i=0;i<thread.session.modules.length;i++){var module=pl.module[thread.session.modules[i]];for(var j=0;j<module.exports.length;j++){var predicate=module.rules[module.exports[j]];if(predicate instanceof Array)
total+=predicate.length;}}
return new pl.type.Num(total,false);},cputime:function(thread){return new pl.type.Num(thread.cpu_time,false);},epoch:function(thread){return new pl.type.Num(thread.epoch,false);},inferences:function(thread){return new pl.type.Num(thread.total_steps,false);},modules:function(thread){return new pl.type.Num(thread.session.modules.length,false);},predicates:function(thread){var total=Object.keys(thread.session.rules).length;for(var i=0;i<thread.session.modules.length;i++){var module=pl.module[thread.session.modules[i]];total+=module.exports.length;}
return new pl.type.Num(total,false);},runtime:function(thread){return new pl.type.Term(".",[new pl.type.Num(thread.cpu_time,false),new pl.type.Term(".",[new pl.type.Num(thread.cpu_time_last,false),new pl.type.Term("[]",[])])]);},threads:function(thread){return new pl.type.Num(thread.session.total_threads,false);}};new pl.type.Module("statistics",predicates(),exports);})(prolog);(function(pl){var predicates=function(){return{"bind/4":function(thread,point,atom){var elem=atom.args[0],type=atom.args[1],event=atom.args[2],goal=atom.args[3];if(pl.type.is_variable(elem)||pl.type.is_variable(type)&&pl.type.is_variable(goal)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(elem)){thread.throw_error(pl.error.type("HTMLObject",elem,atom.indicator));}else if(!pl.type.is_atom(type)){thread.throw_error(pl.error.type("atom",type,atom.indicator));}else if(!pl.type.is_variable(event)&&!pl.type.is_dom_event_object(event)){thread.throw_error(pl.error.type("DOMEventObject",type,atom.indicator));}else if(!pl.type.is_variable(goal)){var thread_=new pl.type.Thread(thread.session);var eventObject=new pl.type.DOMEvent(type.id);var links={};if(pl.type.is_variable(event))
links[event.id]=eventObject;var subs=new pl.type.Substitution(links);var handler=function(e){eventObject.event=e;thread_.add_goal(goal.apply(subs));thread_.answer(thread.__calls[0]);};events.add(elem.object,type.id,handler);elem.object.tau_events=elem.object.tau_events===undefined?{}:elem.object.tau_events;if(elem.object.tau_events[type.id]===undefined)
elem.object.tau_events[type.id]=[];elem.object.tau_events[type.id].push({goal:goal,fn:handler});thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[eventObject,event])),point.substitution,point)]);}else{var event=elem.object.tau_events?elem.object.tau_events[type.id]:undefined;if(event!==undefined){var states=[];for(var i=0;i<event.length;i++)
states.push(new pl.type.State(point.goal.replace(new pl.type.Term("=",[goal,event[i].goal.rename(thread)])),point.substitution,point));thread.prepend(states);}}},"unbind/2":function(thread,point,atom){var elem=atom.args[0],type=atom.args[1];if(pl.type.is_variable(elem)||pl.type.is_variable(type)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(elem)){thread.throw_error(pl.error.type("HTMLObject",elem,atom.indicator));}else if(!pl.type.is_atom(type)){thread.throw_error(pl.error.type("atom",type,atom.indicator));}else if(!pl.type.is_variable(goal)){if(elem.object.tau_events&&elem.object.tau_events[type.id]){var event=elem.object.tau_events[type.id];for(var i=0;i<event.length;i++){events.remove(elem.object,type.id,event[i].fn);}
delete elem.object.tau_events[type.id];}
thread.success(point);}},"unbind/3":function(thread,point,atom){var elem=atom.args[0],type=atom.args[1],goal=atom.args[2];if(pl.type.is_variable(elem)||pl.type.is_variable(type)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(elem)){thread.throw_error(pl.error.type("HTMLObject",elem,atom.indicator));}else if(!pl.type.is_atom(type)){thread.throw_error(pl.error.type("atom",type,atom.indicator));}else if(!pl.type.is_variable(goal)&&!pl.type.is_term(goal)){thread.throw_error(pl.error.type("term",goal,atom.indicator));}else if(!pl.type.is_variable(goal)){if(elem.object.tau_events&&elem.object.tau_events[type.id]){var event=elem.object.tau_events[type.id];var newevents=[];for(var i=0;i<event.length;i++){if(pl.unify(event[i].goal,goal)!==null){events.remove(elem.object,type.id,event[i].fn);}else{newevents.push(event[i]);}}
elem.object.tau_events[type.id]=newevents;}
thread.success(point);}},"event_property/3":function(thread,point,atom){var event=atom.args[0],prop=atom.args[1],val=atom.args[2]
if(pl.type.is_variable(event)||pl.type.is_variable(prop)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_event_object(event)){thread.throw_error(pl.error.type("DOMEventObject",event,atom.indicator));}else if(!pl.type.is_atom(prop)){thread.throw_error(pl.error.type("atom",prop,atom.indicator));}else if(!pl.type.is_variable(val)&&!pl.type.is_atomic(val)){thread.throw_error(pl.error.type("atomic",val,atom.indicator));}else{if(event.event!==null&&event.event[prop.id]){var value=event.event[prop.id];value=isNaN(value)?new pl.type.Term(value,[]):new pl.type.Num(value);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,val])),point.substitution,point)]);}}},"prevent_default/1":function(thread,point,atom){var event=atom.args[0];if(pl.type.is_variable(event)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_event_object(event)){thread.throw_error(pl.error.type("eventObject",event,atom.indicator));}else{if(event.event!==null){event.event.preventDefault();thread.success(point);}}},"hide/1":function(thread,point,atom){var element=atom.args[0];if(pl.type.is_variable(element)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else{var state=document.defaultView.getComputedStyle(element.object,"").display;if(state!==undefined&&state!=="none")
element.object.tau_display=state;element.object.style.display="none";thread.success(point);}},"show/1":function(thread,point,atom){var element=atom.args[0];if(pl.type.is_variable(element)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else{element.object.style.display=element.object.tau_display!==undefined?element.object.tau_display:"block";thread.success(point);}},"toggle/1":[new pl.type.Rule(new pl.type.Term("toggle",[new pl.type.Var("X")]),new pl.type.Term(";",[new pl.type.Term("->",[new pl.type.Term(",",[new pl.type.Term("style",[new pl.type.Var("X"),new pl.type.Term("display",[]),new pl.type.Var("Y")]),new pl.type.Term("=",[new pl.type.Var("Y"),new pl.type.Term("none",[])])]),new pl.type.Term("show",[new pl.type.Var("X")])]),new pl.type.Term("hide",[new pl.type.Var("X")])]))],"document/1":function(session,point,atom){var doc=atom.args[0];var newdoc=new pl.type.DOM(document);session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[doc,newdoc])),point.substitution,point)]);},"head/1":function(session,point,atom){var head=atom.args[0];var newhead=new pl.type.DOM(document.head);session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[head,newhead])),point.substitution,point)]);},"body/1":function(session,point,atom){var body=atom.args[0];var newbody=new pl.type.DOM(document.body);session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[body,newbody])),point.substitution,point)]);},"get_by_id/2":function(session,point,atom){var id=atom.args[0],object=atom.args[1];if(pl.type.is_variable(id)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(id)){session.throw_error(pl.error.type("atom",id,atom.indicator));}else if(!pl.type.is_variable(object)&&!pl.type.is_dom_object(object)){session.throw_error(pl.error.type("HTMLObject",object,atom.indicator));}else{var element=document.getElementById(id.id);if(element){var html=new pl.type.DOM(element);session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[html,object])),point.substitution,point)]);}}},"get_by_class/2":[new pl.type.Rule(new pl.type.Term("get_by_class",[new pl.type.Var("Class"),new pl.type.Var("Html")]),new pl.type.Term(",",[new pl.type.Term("document",[new pl.type.Var("D")]),new pl.type.Term("get_by_class",[new pl.type.Var("D"),new pl.type.Var("Class"),new pl.type.Var("Html")])]))],"get_by_class/3":function(session,point,atom){var parent=atom.args[0],name=atom.args[1],object=atom.args[2];if(pl.type.is_variable(parent)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(parent)){session.throw_error(pl.error.type("HTMLObject",parent,atom.indicator));}else if(pl.type.is_variable(name)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(name)){session.throw_error(pl.error.type("atom",name,atom.indicator));}else if(!pl.type.is_variable(object)&&!pl.type.is_dom_object(object)){session.throw_error(pl.error.type("HTMLObject",object,atom.indicator));}else{var elements=parent.object.getElementsByClassName(name.id);if(elements){var states=[];for(var i=0;i<elements.length;i++){var html=new pl.type.DOM(elements[i]);states.push(new pl.type.State(point.goal.replace(new pl.type.Term("=",[html,object])),point.substitution,point));}
session.prepend(states);}}},"get_by_tag/2":[new pl.type.Rule(new pl.type.Term("get_by_tag",[new pl.type.Var("Tag"),new pl.type.Var("Html")]),new pl.type.Term(",",[new pl.type.Term("document",[new pl.type.Var("D")]),new pl.type.Term("get_by_tag",[new pl.type.Var("D"),new pl.type.Var("Tag"),new pl.type.Var("Html")])]))],"get_by_tag/3":function(session,point,atom){var parent=atom.args[0],tag=atom.args[1],object=atom.args[2];if(pl.type.is_variable(parent)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(parent)){session.throw_error(pl.error.type("HTMLObject",parent,atom.indicator));}else if(pl.type.is_variable(tag)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(tag)){session.throw_error(pl.error.type("atom",tag,atom.indicator));}else if(!pl.type.is_variable(object)&&!pl.type.is_dom_object(object)){session.throw_error(pl.error.type("HTMLObject",object,atom.indicator));}else{var elements=parent.object.getElementsByTagName(tag.id);if(elements){var states=[];for(var i=0;i<elements.length;i++){var html=new pl.type.DOM(elements[i]);states.push(new pl.type.State(point.goal.replace(new pl.type.Term("=",[html,object])),point.substitution,point));}
session.prepend(states);}}},"get_by_name/2":function(session,point,atom){var name=atom.args[0],object=atom.args[1];if(pl.type.is_variable(name)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(name)){session.throw_error(pl.error.type("atom",name,atom.indicator));}else if(!pl.type.is_variable(object)&&!pl.type.is_dom_object(object)){session.throw_error(pl.error.type("HTMLObject",object,atom.indicator));}else{var elements=document.getElementsByName(name.id);if(elements){var states=[];for(var i=0;i<elements.length;i++){var html=new pl.type.DOM(elements[i]);states.push(new pl.type.State(point.goal.replace(new pl.type.Term("=",[html,object])),point.substitution,point));}
session.prepend(states);}}},"get_style/3":function(session,point,atom){var html=atom.args[0],property=atom.args[1],value=atom.args[2];if(pl.type.is_variable(html)||pl.type.is_variable(property)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",selector,atom.indicator));}else if(!pl.type.is_atom(property)){session.throw_error(pl.error.type("atom",property,atom.indicator));}else{if(html.object===document)return;var style=document.defaultView.getComputedStyle(html.object,"")[property.id]||"";if(style===''&&html.object.style[property.id])
style=html.object.style[property.id];var html_value=styleToProlog(style);session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,html_value])),point.substitution,point)]);}},"set_style/3":function(session,point,atom){var html=atom.args[0],property=atom.args[1],value=atom.args[2];var styleValue=styleFromProlog(value);var ground=pl.type.is_ground(value);if(pl.type.is_variable(html)||pl.type.is_variable(property)||!ground){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",selector,atom.indicator));}else if(!pl.type.is_atom(property)){session.throw_error(pl.error.type("atom",property,atom.indicator));}else if(styleValue===false){session.throw_error(pl.error.domain("style_value",value,atom.indicator));}else{if(html.object===document)return;html.object.style[property.id]=styleValue;session.success(point);}},"style/3":function(session,point,atom){var html=atom.args[0],property=atom.args[1],value=atom.args[2];var styleValue=styleFromProlog(value);var ground=pl.type.is_ground(value);if(pl.type.is_variable(html)||pl.type.is_variable(property)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",html,atom.indicator));}else if(!pl.type.is_atom(property)){session.throw_error(pl.error.type("atom",property,atom.indicator));}else if(!pl.type.is_variable(value)&&ground&&styleValue===false){session.throw_error(pl.error.domain("style_value",value,atom.indicator));}else{if(html.object===document)return;if(!ground){var style=document.defaultView.getComputedStyle(html.object,"")[property.id]||"";if(style===''&&html.object.style[property.id])
style=html.object.style[property.id];var html_value=styleToProlog(style);session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,html_value])),point.substitution,point)]);}else{html.object.style[property.id]=styleValue;session.success(point);}}},"get_attr/3":function(session,point,atom){var html=atom.args[0],attr=atom.args[1],value=atom.args[2];if(pl.type.is_variable(html)||pl.type.is_variable(attr)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",selector,atom.indicator));}else if(!pl.type.is_atom(attr)){session.throw_error(pl.error.type("atom",attr,atom.indicator));}else{if(html.object===document)return;var html_value=attr.id==="value"?new pl.type.Term(html.object.value):styleToProlog(html.object.getAttribute(attr.id));if(html_value!==null&&html_value!==undefined)
session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,html_value])),point.substitution,point)]);}},"set_attr/3":function(session,point,atom){var html=atom.args[0],attr=atom.args[1],value=atom.args[2];var styleValue=styleFromProlog(value);var ground=pl.type.is_ground(value);if(pl.type.is_variable(html)||pl.type.is_variable(attr)||!ground){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",selector,atom.indicator));}else if(!pl.type.is_atom(attr)){session.throw_error(pl.error.type("atom",attr,atom.indicator));}else if(styleValue===false){session.throw_error(pl.error.domain("attribute_value",value,atom.indicator));}else{if(html.object===document)return;if(attr.id==="value"){html.object.value=styleValue;}else{html.object.setAttribute(attr.id,styleValue);}
session.success(point);}},"attr/3":function(session,point,atom){var html=atom.args[0],attr=atom.args[1],value=atom.args[2];var styleValue=styleFromProlog(value);var ground=pl.type.is_ground(value);if(pl.type.is_variable(html)||pl.type.is_variable(attr)){session.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",selector,atom.indicator));}else if(!pl.type.is_atom(attr)){session.throw_error(pl.error.type("atom",attr,atom.indicator));}else if(!pl.type.is_variable(value)&&ground&&styleValue===false){session.throw_error(pl.error.domain("attribute_value",value,atom.indicator));}else{if(html.object===document)return;if(!ground){var html_value=attr.id==="value"?new pl.type.Term(html.object.value):styleToProlog(html.object.getAttribute(attr.id));if(html_value!==null&&html_value!==undefined)
session.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,html_value])),point.substitution,point)]);}else{if(attr.id==="value"){html.object.value=styleValue;}else{html.object.setAttribute(attr.id,styleValue);}
session.success(point);}}},"get_html/2":function(thread,point,atom){var html=atom.args[0],value=atom.args[1];if(pl.type.is_variable(html)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",html,atom.indicator));}else{if(html.object===document)return;var inner=new pl.type.Term(html.object.innerHTML);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[inner,value])),point.substitution,point)]);}},"set_html/2":function(thread,point,atom){var html=atom.args[0],value=atom.args[1];if(pl.type.is_variable(html)||pl.type.is_variable(value)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(html)){session.throw_error(pl.error.type("HTMLObject",html,atom.indicator));}else{if(html.object===document)return;if(pl.type.is_atom(value))
html.object.innerHTML=value.id;else
html.object.innerHTML=value.toString();thread.success(point);}},"html/2":function(thread,point,atom){var html=atom.args[0],value=atom.args[1];if(pl.type.is_variable(html)){thread.throw_error(pl.error.instantiation(atom.indicator));}else{if(html.object===document)return;if(pl.type.is_variable(value)){var inner=new pl.type.Term(html.object.innerHTML);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[inner,value])),point.substitution,point)]);}else{if(pl.type.is_atom(value))
html.object.innerHTML=value.id;else
html.object.innerHTML=value.toString();thread.success(point);}}},"create/2":function(thread,point,atom){var tag=atom.args[0],element=atom.args[1];if(pl.type.is_variable(tag)&&pl.type.is_variable(element)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(tag)&&!pl.type.is_atom(tag)){thread.throw_error(pl.error.type("atom",tag,atom.indicator));}else if(!pl.type.is_variable(element)&&!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else if(pl.type.is_variable(element)){var node=new pl.type.DOM(document.createElement(tag.id));thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[element,node])),point.substitution,point)]);}else if(pl.type.is_variable(element)){var node=new pl.type.DOM(document.createElement(tag.id.toLowerCase()));thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[element,node])),point.substitution,point)]);}else if(pl.type.is_variable(tag)){var type=new pl.type.Term(element.object.nodeName.toLowerCase());thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[type,tag])),point.substitution,point)]);}},"parent_of/2":function(thread,point,atom){var child=atom.args[0],parent=atom.args[1];if(pl.type.is_variable(parent)&&pl.type.is_variable(child)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(parent)&&!pl.type.is_dom_object(parent)){thread.throw_error(pl.error.type("HTMLObject",parent,atom.indicator));}else if(!pl.type.is_variable(child)&&!pl.type.is_dom_object(child)){thread.throw_error(pl.error.type("HTMLObject",child,atom.indicator));}else if(pl.type.is_variable(child)){var children=parent.object.children;var states=[];for(var i=0;i<children.length;i++){states.push(new pl.type.State(point.goal.replace(new pl.type.Term("=",[child,new pl.type.DOM(children[i])])),point.substitution,point));}
thread.prepend(states);}else{if(child.object.parentNode){thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[parent,new pl.type.DOM(child.object.parentNode)])),point.substitution,point)]);}}},"sibling/2":function(thread,point,atom){var left=atom.args[0],right=atom.args[1];if(pl.type.is_variable(left)&&pl.type.is_variable(right)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(left)&&!pl.type.is_dom_object(left)){thread.throw_error(pl.error.type("HTMLObject",left,atom.indicator));}else if(!pl.type.is_variable(right)&&!pl.type.is_dom_object(right)){thread.throw_error(pl.error.type("HTMLObject",right,atom.indicator));}else{if(pl.type.is_variable(left)&&right.object.previousElementSibling){var elem=new pl.type.DOM(right.object.previousElementSibling);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[left,elem])),point.substitution,point)]);}else if(!pl.type.is_variable(left)&&left.object.nextElementSibling){var elem=new pl.type.DOM(left.object.nextElementSibling);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[right,elem])),point.substitution,point)]);}}},"remove/1":function(thread,point,atom){var element=atom.args[0];if(pl.type.is_variable(element)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else{if(element.object.parentNode){element.object.parentNode.removeChild(element.object);thread.success(point);}}},"insert_after/2":function(thread,point,atom){var element=atom.args[0],reference=atom.args[1];if(pl.type.is_variable(element)||pl.type.is_variable(reference)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else if(!pl.type.is_dom_object(reference)){thread.throw_error(pl.error.type("HTMLObject",reference,atom.indicator));}else{if(reference.object.parentNode){reference.object.parentNode.insertBefore(element.object,reference.object.nextSibling);thread.success(point);}}},"insert_before/2":function(thread,point,atom){var element=atom.args[0],reference=atom.args[1];if(pl.type.is_variable(element)||pl.type.is_variable(reference)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else if(!pl.type.is_dom_object(reference)){thread.throw_error(pl.error.type("HTMLObject",reference,atom.indicator));}else{if(reference.object.parentNode){reference.object.parentNode.insertBefore(element.object,reference.object);thread.success(point);}}},"prepend_child/2":function(thread,point,atom){var parent=atom.args[0],child=atom.args[1];if(pl.type.is_variable(parent)||pl.type.is_variable(child)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(parent)){thread.throw_error(pl.error.type("HTMLObject",parent,atom.indicator));}else if(!pl.type.is_dom_object(child)){thread.throw_error(pl.error.type("HTMLObject",child,atom.indicator));}else{if(parent.object.firstChild)
parent.object.insertBefore(child.object,parent.object.firstChild);else
parent.object.appendChild(child.object);thread.success(point);}},"append_child/2":function(thread,point,atom){var parent=atom.args[0],child=atom.args[1];if(pl.type.is_variable(parent)||pl.type.is_variable(child)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(parent)){thread.throw_error(pl.error.type("HTMLObject",parent,atom.indicator));}else if(!pl.type.is_dom_object(child)){thread.throw_error(pl.error.type("HTMLObject",child,atom.indicator));}else{parent.object.appendChild(child.object);thread.success(point);}},"add_class/2":function(thread,point,atom){var element=atom.args[0],name=atom.args[1];if(pl.type.is_variable(element)||pl.type.is_variable(name)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else if(!pl.type.is_atom(name)){thread.throw_error(pl.error.type("atom",name,atom.indicator));}else{var arr=element.object.className.split(" ");if(arr.indexOf(name.id)===-1){element.object.className+=" "+name.id;}
thread.success(point);}},"remove_class/2":function(thread,point,atom){var element=atom.args[0],name=atom.args[1];if(pl.type.is_variable(element)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else if(!pl.type.is_atom(name)&&!pl.type.is_variable(name)){thread.throw_error(pl.error.type("atom",name,atom.indicator));}else{var arr=element.object.className.split(" ");if(pl.type.is_variable(name)){var states=[];for(var i=0;i<arr.length;i++){states.push(new pl.type.State(point.goal.replace(new pl.type.Term(",",[new pl.type.Term("=",[name,new pl.type.Term(arr[i],[])]),new pl.type.Term("remove_class",[element,name])])),point.substitution,point));}
thread.prepend(states);}else{var newclasses="";for(var i=0;i<arr.length;i++)
if(arr[i]!==name.id)
newclasses+=arr[i]+" ";element.object.className=newclasses;thread.success(point);}}},"hasClass/2":function(thread,point,atom){var element=atom.args[0],name=atom.args[1];if(pl.type.is_variable(element)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_dom_object(element)){thread.throw_error(pl.error.type("HTMLObject",element,atom.indicator));}else if(!pl.type.is_atom(name)&&!pl.type.is_variable(name)){thread.throw_error(pl.error.type("atom",name,atom.indicator));}else{var arr=element.object.className.split(" ");if(pl.type.is_variable(name)){var states=[];for(var i=0;i<arr.length;i++)
states.push(new pl.type.State(point.goal.replace(new pl.type.Term("=",[name,new pl.type.Term(arr[i],[])])),point.substitution,point));thread.prepend(states);}else{if(arr.indexOf(name.id)!==-1)
thread.success(point);}}}};};var exports=["document/1","head/1","body/1","show/1","hide/1","toggle/1","create/2","get_by_id/2","get_by_tag/2","get_by_tag/3","get_by_class/2","get_by_class/3","get_by_name/2","attr/3","set_attr/3","get_attr/3","style/3","set_style/3","get_style/3","html/2","set_html/2","get_html/2","parent_of/2","insert_after/2","insert_before/2","append_child/2","prepend_child/2","sibling/2","remove/1","add_class/2","remove_class/2","has_class/2","bind/4","unbind/2","unbind/3","event_property/3","prevent_default/1"];function styleFromProlog(obj){if(obj===undefined||obj===null)
return false;else if(pl.type.is_number(obj))
return obj.value;else if(pl.type.is_term(obj)&&obj.args.length===0)
return obj.id;else if(pl.type.is_term(obj)&&obj.indicator==="px/1"&&pl.type.is_number(obj.args[0]))
return obj.args[0].value.toString()+"px";else if(pl.type.is_term(obj)&&obj.indicator==="%/1"&&pl.type.is_number(obj.args[0]))
return obj.args[0].value.toString()+"%";else if(pl.type.is_term(obj)&&obj.indicator==="url/1"&&pl.type.is_atom(obj.args[0]))
return"url(\""+obj.args[0].id+"\")";else if(pl.type.is_term(obj)&&obj.indicator==="rgb/3"&&pl.type.is_integer(obj.args[0])&&pl.type.is_integer(obj.args[1])&&pl.type.is_integer(obj.args[2]))
return obj.toString();return false;}
function styleToProlog(str){if(str===undefined||str===null)
return
else if(/^-?[0-9]*\.?[0-9]*\s*px\s*$/.test(str))
return new pl.type.Term("px",[new pl.type.Num(parseInt(str))]);else if(/^-?[0-9]*\.?[0-9]*\s*\%\s*$/.test(str))
return new pl.type.Term("%",[new pl.type.Num(parseFloat(str))]);else if(/^url\(["'].*["']\)$/.test(str))
return new pl.type.Term("url",[new pl.type.Term(str.substring(5,str.length-2))]);else if(/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)\s*$/.test(str)){var rgb=str.replace("rgb","").replace("(","").replace(")","").split(",");return new pl.type.Term("rgb",[new pl.type.Num(parseInt(rgb[0]),false),new pl.type.Num(parseInt(rgb[1]),false),new pl.type.Num(parseInt(rgb[2]),false)]);}
return new pl.type.Term(str.toString(),[]);}
pl.type.is_dom_object=function(obj){return obj instanceof pl.type.DOM;};pl.type.order.push(pl.type.DOM);pl.type.DOM=function(object){this.object=object;}
pl.type.DOM.prototype.toString=function(){return"<html>("+(this.object.id!==""&&this.object.id!==undefined?"#"+this.object.id:this.object.nodeName.toLowerCase().replace("#",""))+")";};pl.type.DOM.prototype.clone=function(){return new pl.type.DOM(this.object);};pl.type.DOM.prototype.equals=function(obj){return pl.type.is_dom_object(obj)&&this.object===obj.object;};pl.type.DOM.prototype.rename=function(_){return this;};pl.type.DOM.prototype.variables=function(){return[];};pl.type.DOM.prototype.apply=function(_){return this;};pl.type.DOM.prototype.unify=function(obj,_){if(pl.type.is_dom_object(obj)&&this.object===obj.object){return new pl.type.State(obj,new pl.type.Substitution());}
return null;};pl.type.DOM.prototype.interpret=function(indicator){return pl.error.instantiation(indicator);};pl.type.DOM.prototype.compare=function(obj){if(this.object===obj.object){return 0;}else if(this.object<obj.object){return-1;}else if(this.object>obj.object){return 1;}};pl.type.DOM.prototype.toJavaScript=function(){return this.object;};pl.fromJavaScript.test.dom=function(obj){return obj instanceof HTMLElement;};pl.fromJavaScript.conversion.dom=function(obj){return new pl.type.DOM(obj);};pl.fromJavaScript.test.dom_collection=function(obj){return obj instanceof HTMLCollection;};pl.fromJavaScript.conversion.dom_collection=function(obj){var arr=Array.prototype.slice.call(obj,0);return pl.fromJavaScript.apply(arr);};pl.type.DOM.prototype.stream=function(options,mode){if(mode==="write")
if(this.object instanceof HTMLInputElement)
this.object.value="";else
this.object.innerHTML="";return{object:this.object,get:function(length,position){var text;if(this.object instanceof HTMLInputElement)
text=this.object.value.substring(position,position+length);else
text=this.object.innerHTML;if(position>=text.length)
return"end_of_html";return text.substring(position,position+length);},put:function(text,position){if(position==="end_of_file"){if(this.object instanceof HTMLInputElement)
this.object.value+=text;else
this.object.innerHTML+=text;return true;}else if(position==="past_end_of_file"){return null;}else{if(this.object instanceof HTMLInputElement)
this.object.value=this.object.value.substring(0,position)+text+this.object.value.substring(position+text.length);else
this.object.innerHTML=this.object.innerHTML.substring(0,position)+text+this.object.innerHTML.substring(position+text.length);return true;}},get_byte:function(position){if(position==="end_of_stream")
return-1;var index=Math.floor(position/2);var text;if(this.object instanceof HTMLInputElement)
text=this.object.value.substring(position,position+length);else
text=this.object.innerHTML;if(text.length<=index)
return-1;var code=pl.utils.codePointAt(text[Math.floor(position/2)],0);if(position%2===0)
return code&0xff;else
return code/256>>>0;},put_byte:function(byte,position){var text;if(this.object instanceof HTMLInputElement)
text=this.object.value;else
text=this.object.innerHTML;var index=position==="end_of_stream"?text.length:Math.floor(position/2);if(text.length<index)
return null;var code=text.length===index?-1:pl.utils.codePointAt(text[Math.floor(position/2)],0);if(position%2===0){code=code/256>>>0;code=((code&0xff)<<8)|(byte&0xff);}else{code=code&0xff;code=((byte&0xff)<<8)|(code&0xff);}
if(text.length===index)
text+=pl.utils.fromCodePoint(code);else
text=text.substring(0,index)+pl.utils.fromCodePoint(code)+text.substring(index+1);if(this.object instanceof HTMLInputElement)
this.object.value=text;else
this.object.innerHTML=text;return true;},flush:function(){return true;},close:function(){return true;}};};pl.type.is_dom_event_object=function(obj){return obj instanceof pl.type.DOMEvent;};pl.type.order.push(pl.type.DOMEvent);pl.type.DOMEvent=function(type,event,epoch){this.type=type;this.event=event||null;this.epoch=epoch||(new Date).getTime();}
pl.type.DOMEvent.prototype.toString=function(){return"<event>("+this.type.toLowerCase()+")";};pl.type.DOMEvent.prototype.clone=function(){return new pl.type.DOMEvent(this.type,this.event,this.epoch);};pl.type.DOMEvent.prototype.equals=function(obj){return pl.type.is_dom_event_object(obj)&&this.type===obj.type&&this.epoch===obj.epoch;};pl.type.DOMEvent.prototype.rename=function(_){return this;};pl.type.DOMEvent.prototype.variables=function(){return[];};pl.type.DOMEvent.prototype.apply=function(_){return this;};pl.type.DOMEvent.prototype.unify=function(obj,_){if(pl.type.is_dom_event_object(obj)&&this.type===obj.type&&this.epoch===obj.epoch){return new pl.type.State(obj,new pl.type.Substitution());}
return null;};pl.type.DOMEvent.prototype.interpret=function(indicator){return pl.error.instantiation(indicator);};pl.type.DOMEvent.prototype.compare=function(obj){if(this.epoch===obj.epoch){return 0;}else if(this.epoch<obj.epoch){return-1;}else if(this.epoch>obj.epoch){return 1;}};pl.type.DOMEvent.prototype.toJavaScript=function(){return this.event;};pl.fromJavaScript.test.event=function(obj){return obj instanceof Event;};pl.fromJavaScript.conversion.event=function(obj){return new pl.type.DOMEvent(obj.type,obj);};var events=(function(){var tau_fn_event={};var add=function(element,evt,fn){if(element.addEventListener!==undefined){element.addEventListener(evt,fn);return true;}
else if(element.attachEvent!==undefined){element.attachEvent("on"+evt,fn);return true;}
var prop=element["on"+evt];var fns=[];if(prop){if(prop.tau_fn_event===tau_fn_event){if(prop.fns.indexOf(fn)===-1)
prop.fns.push(fn);return true;}else{fns.push(prop);}}
fns.push(fn);element["on"+evt]=function(e){for(var i=0;i<fns.length;i++)
fns[i].call(element,e,element);};element["on"+evt].fns=fns;element["on"+evt].tau_fn_event=tau_fn_event;return true;};var remove=function(element,evt,fn){if(element.removeEventListener){element.removeEventListener(evt,fn);return true;}
else if(element.detachEvent){element.detachEvent("on"+evt,fn);return true;}
else if(element["on"+evt]){var f=element["on"+evt];if(f===fn)
element["on"+evt]=undefined;else if(f.tau_fn_event===tau_fn_event){for(var i=0;i<f.fns.length;i++){if(f.fns[i]===fn){f.fns.splice(i,1);break;}}
return true;}
else
return false;}
return true;};return{add:add,remove:remove};})();new pl.type.Module("dom",predicates(),exports);})(prolog);(function(pl){var predicates=function(){return{"global/1":function(thread,point,atom){thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[atom.args[0],pl.fromJavaScript.apply(pl.__env)])),point.substitution,point)]);},"apply/3":[new pl.type.Rule(new pl.type.Term("apply",[new pl.type.Var("X"),new pl.type.Var("Y"),new pl.type.Var("Z")]),new pl.type.Term(",",[new pl.type.Term("global",[new pl.type.Var("G")]),new pl.type.Term("apply",[new pl.type.Var("G"),new pl.type.Var("X"),new pl.type.Var("Y"),new pl.type.Var("Z")])]))],"apply/4":function(thread,point,atom){var context=atom.args[0],name=atom.args[1],args=atom.args[2],result=atom.args[3];if(pl.type.is_variable(context)||pl.type.is_variable(name)||pl.type.is_variable(args)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(name)&&(!pl.type.is_js_object(name)||typeof name.value!=="function")){thread.throw_error(pl.error.type("atom_or_JSValueFUNCTION",name,atom.indicator));}else if(!pl.type.is_list(args)){thread.throw_error(pl.error.type("list",args,atom.indicator));}
var ctx=context.toJavaScript();var fn=pl.type.is_atom(name)?ctx[name.id]:name.toJavaScript();if(typeof fn==="function"){var pointer=args;var pltojs;var arr=[];while(pointer.indicator==="./2"){pltojs=pointer.args[0].toJavaScript();if(pltojs===undefined){thread.throw_error(pl.error.domain("javascript_object",pointer.args[0],atom.indicator));return undefined;}
arr.push(pltojs);pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(pointer.indicator!=="[]/0"){thread.throw_error(pl.error.type("list",args,atom.indicator));return}
var value;try{value=fn.apply(ctx,arr);}catch(e){thread.throw_error(pl.error.javascript(e.toString(),atom.indicator));return;}
value=pl.fromJavaScript.apply(value);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,result])),point.substitution,point)]);}},"prop/2":[new pl.type.Rule(new pl.type.Term("prop",[new pl.type.Var("X"),new pl.type.Var("Y")]),new pl.type.Term(",",[new pl.type.Term("global",[new pl.type.Var("G")]),new pl.type.Term("prop",[new pl.type.Var("G"),new pl.type.Var("X"),new pl.type.Var("Y")])]))],"prop/3":function(thread,point,atom){var context=atom.args[0],name=atom.args[1],result=atom.args[2];if(pl.type.is_variable(context)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(name)&&!pl.type.is_atom(name)){thread.throw_error(pl.error.type("atom",name,atom.indicator));}else{if(pl.type.is_atom(name)){var fn=context.toJavaScript()[name.id];if(fn!==undefined){fn=pl.fromJavaScript.apply(fn);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[fn,result])),point.substitution,point)]);}}else{var fn=context.toJavaScript();var states=[];for(var x in fn){if(fn.hasOwnProperty(x)){var fn_=pl.fromJavaScript.apply(fn[x]);states.push(new pl.type.State(point.goal.replace(new pl.type.Term(",",[new pl.type.Term("=",[fn_,result]),new pl.type.Term("=",[new pl.type.Term(x,[]),name])])),point.substitution,point));}}
thread.prepend(states);}}},"json_prolog/2":function(thread,point,atom){var json=atom.args[0],prolog=atom.args[1];if(pl.type.is_variable(json)&&pl.type.is_variable(prolog)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(json)&&(!pl.type.is_js_object(json)||typeof(json.value)!=="object")){thread.throw_error(pl.error.type("JsValueOBJECT",json,atom.indicator));}else if(!pl.type.is_variable(prolog)&&!pl.type.is_list(prolog)){thread.throw_error(pl.error.type("list",prolog,atom.indicator));}else{if(pl.type.is_variable(prolog)){var list=pl.fromJavaScript.apply(json.value,true);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[prolog,list])),point.substitution,point)]);}else{var obj=new pl.type.JSValue(prolog.toJavaScript());thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[json,obj])),point.substitution,point)]);}}},"json_atom/2":function(thread,point,atom){var json=atom.args[0],prolog=atom.args[1];if(pl.type.is_variable(json)&&pl.type.is_variable(prolog)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(json)&&(!pl.type.is_js_object(json)||typeof(json.value)!=="object")){thread.throw_error(pl.error.type("JsValueOBJECT",json,atom.indicator));}else if(!pl.type.is_variable(prolog)&&!pl.type.is_atom(prolog)){thread.throw_error(pl.error.type("atom",prolog,atom.indicator));}else{if(pl.type.is_variable(prolog)){try{var jatom=new pl.type.Term(JSON.stringify(json.value),[]);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[prolog,jatom])),point.substitution,point)]);}catch(ex){}}else{try{console.log(JSON.parse(prolog.id));var obj=pl.fromJavaScript.apply(JSON.parse(prolog.id));thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[json,obj])),point.substitution,point)]);}catch(ex){}}}},"ajax/3":[new pl.type.Rule(new pl.type.Term("ajax",[new pl.type.Var("Method"),new pl.type.Var("URL"),new pl.type.Var("Response")]),new pl.type.Term("ajax",[new pl.type.Var("Method"),new pl.type.Var("URL"),new pl.type.Var("Response"),new pl.type.Term("[]",[])]))],"ajax/4":function(thread,point,atom){var method=atom.args[0],url=atom.args[1],value=atom.args[2],options=atom.args[3];if(pl.type.is_variable(url)||pl.type.is_variable(method)||pl.type.is_variable(options)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(url)){thread.throw_error(pl.error.type("atom",url,atom.indicator));}else if(!pl.type.is_atom(method)){thread.throw_error(pl.error.type("atom",method,atom.indicator));}else if(!pl.type.is_list(options)){thread.throw_error(pl.error.type("list",options,atom.indicator));}else if(["connect","delete","get","head","options","patch","post","put","trace"].indexOf(method.id)===-1){thread.throw_error(pl.error.domain("http_method",method,atom.indicator));}else{var pointer=options;var opt_type=null;var opt_timeout=0;var opt_credentials="false";var opt_async="true";var opt_mime=null;var opt_headers=[];var opt_body=new FormData();var opt_user=null;var opt_password=null;while(pl.type.is_term(pointer)&&pointer.indicator==="./2"){var option=pointer.args[0];if(!pl.type.is_term(option)||option.args.length!==1){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
var prop=option.args[0];if(option.indicator==="type/1"){if(!pl.type.is_atom(prop)||prop.id!=="text"&&prop.id!=="json"&&prop.id!=="document"){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_type=prop.id;}else if(option.indicator==="user/1"){if(!pl.type.is_atom(prop)){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_user=prop.id;}else if(option.indicator==="password/1"){if(!pl.type.is_atom(prop)){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_password=prop.id;}else if(option.indicator==="timeout/1"){if(!pl.type.is_integer(prop)||prop.value<0){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_timeout=prop.value;}else if(option.indicator==="async/1"){if(!pl.type.is_atom(prop)||prop.id!=="true"&&prop.id!=="false"){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_async=prop.id;}else if(option.indicator==="credentials/1"){if(!pl.type.is_atom(prop)||prop.id!=="true"&&prop.id!=="false"){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_credentials=prop.id;}else if(option.indicator==="mime/1"){if(!pl.type.is_atom(prop)){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_mime=prop.id;}else if(option.indicator==="headers/1"){if(!pl.type.is_list(prop)){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
var hpointer=prop;while(pl.type.is_term(hpointer)&&hpointer.indicator==="./2"){var header=hpointer.args[0];if(!pl.type.is_term(header)||header.indicator!=="-/2"||!pl.type.is_atom(header.args[0])||!pl.type.is_atom(header.args[1])){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_headers.push({header:header.args[0].id,value:header.args[1].id});hpointer=hpointer.args[1];}
if(pl.type.is_variable(hpointer)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_term(hpointer)||hpointer.indicator!=="[]/0"){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}}else if(option.indicator==="body/1"){if(!pl.type.is_list(prop)&&(pl.type.is_dom_object===undefined||!pl.type.is_dom_object(prop))&&!pl.type.is_atom(prop)){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
if(pl.type.is_list(prop)){var hpointer=prop;while(pl.type.is_term(hpointer)&&hpointer.indicator==="./2"){var body=hpointer.args[0];if(!pl.type.is_term(body)||body.indicator!=="-/2"||!pl.type.is_atom(body.args[0])||!pl.type.is_atom(body.args[1])){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
opt_body.append(body.args[0].id,body.args[1].id);hpointer=hpointer.args[1];}
if(pl.type.is_variable(hpointer)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_term(hpointer)||hpointer.indicator!=="[]/0"){thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}}else if(pl.type.is_atom(prop)){opt_body=prop.id;}else{opt_body=prop.value;}}else{thread.throw_error(pl.error.domain("ajax_option",option,atom.indicator));return;}
pointer=pointer.args[1];}
if(pl.type.is_variable(pointer)){thread.throw_error(pl.error.instantiation(atom.indicator));return;}else if(!pl.type.is_term(pointer)||pointer.indicator!=="[]/0"){thread.throw_error(pl.error.type("list",options,atom.indicator));return;}
var xhttp=new XMLHttpRequest();if(opt_mime!==null)
xhttp.overrideMimeType(opt_mime);var fn=function(){if(this.readyState==4){if(this.status==200){var data=null;var content_type=this.getResponseHeader("Content-Type");if(this.responseType==="json"&&this.response){data=pl.fromJavaScript.apply(this.response);}else if(this.responseType===""&&content_type.indexOf("application/json")!==-1){try{data=pl.fromJavaScript.apply(JSON.parse(this.responseText));}catch(e){}}
if(data===null){if((this.responseType==="document"||this.responseType===""&&content_type.indexOf("text/html")!==-1||this.responseType===""&&content_type.indexOf("application/xml")!==-1)&&this.responseXML!==null&&pl.type.DOM!==undefined){data=new pl.type.DOM(this.responseXML);}else if(this.responseType===""||this.responseType==="text"){data=new pl.type.Term(this.responseText,[]);}}
if(data!==null)
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[value,data])),point.substitution,point)]);}
if(opt_async==="true")
thread.again();}};xhttp.onreadystatechange=fn;xhttp.open(method.id.toUpperCase(),url.id,opt_async==="true",opt_user,opt_password);if(opt_type!==null&&opt_async==="true")
xhttp.responseType=opt_type;xhttp.withCredentials=opt_credentials==="true";if(opt_async==="true")
xhttp.timeout=opt_timeout;for(var i=0;i<opt_headers.length;i++)
xhttp.setRequestHeader(opt_headers[i].header,opt_headers[i].value);xhttp.send(opt_body);if(opt_async==="true")
return true;else
fn.apply(xhttp);}}};};var exports=["global/1","apply/3","apply/4","prop/2","prop/3","json_prolog/2","json_atom/2","ajax/3","ajax/4"];function define_properties(){pl.type.is_js_object=function(obj){return obj instanceof pl.type.JSValue;};pl.type.order.push(pl.type.JSValue);pl.type.JSValue=function(value){this.value=value;}
pl.type.JSValue.prototype.toString=function(){return"<javascript>("+(typeof this.value).toLowerCase()+")";};pl.type.JSValue.prototype.clone=function(){return new pl.type.JSValue(this.value);};pl.type.JSValue.prototype.equals=function(obj){return pl.type.is_js_object(obj)&&this.value===obj.value;};pl.type.JSValue.prototype.rename=function(_){return this;};pl.type.JSValue.prototype.variables=function(){return[];};pl.type.JSValue.prototype.apply=function(_){return this;};pl.type.JSValue.prototype.unify=function(obj,_){if(pl.type.is_js_object(obj)&&this.value===obj.value){return new pl.type.State(obj,new pl.type.Substitution());}
return null;};pl.type.JSValue.prototype.interpret=function(indicator){return pl.error.instantiation(indicator);};pl.type.JSValue.prototype.compare=function(obj){if(this.value===obj.value){return 0;}else if(this.value<obj.value){return-1;}else if(this.value>obj.value){return 1;}};pl.type.JSValue.prototype.toJavaScript=function(){return this.value;};pl.fromJavaScript.conversion.any=function(obj){return new pl.type.JSValue(obj);};pl.error.javascript=function(error,indicator){return new pl.type.Term("error",[new pl.type.Term("javascript_error",[new pl.type.Term(error)]),pl.utils.str_indicator(indicator)]);};}
define_properties();new pl.type.Module("js",predicates(),exports);})(prolog);(function(pl){var predicates=function(){return{"sleep/1":function(thread,point,atom){var time=atom.args[0];if(pl.type.is_variable(time)){thread.throw_error(pl.error.instantiation(thread.level));}else if(!pl.type.is_integer(time)){thread.throw_error(pl.error.type("integer",time,thread.level));}else{setTimeout(function(){thread.success(point);thread.again();},time.value);return true;}},"shell/1":function(thread,point,atom){var command=atom.args[0];thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("shell",[command,new pl.type.Num(0,false)])),point.substitution,point)]);},"shell/2":function(thread,point,atom){var command=atom.args[0],status=atom.args[1];if(pl.type.is_variable(command)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(command)){thread.throw_error(pl.error.type("atom",command,atom.indicator));}else if(!pl.type.is_variable(status)&&!pl.type.is_integer(status)){thread.throw_error(pl.error.type("integer",status,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){const exec=require('child_process').exec;exec(command.id,function(){}).on('exit',function(code){thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[status,new pl.type.Num(code,false)])),point.substitution,point)]);thread.again();});return true;}else{try{eval(command.id);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[status,new pl.type.Num(0,false)])),point.substitution,point)]);}catch(error){thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[status,new pl.type.Num(1,false)])),point.substitution,point)]);}}}},"directory_files/2":function(thread,point,atom){var path=atom.args[0],entries=atom.args[1];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else if(!pl.type.is_variable(entries)&&!pl.type.is_list(entries)){thread.throw_error(pl.error.type("list",entries,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.readdir(path.id,function(error,items){if(error){thread.throw_error(pl.error.existence("directory",path,atom.indicator));}else{var listing=new pl.type.Term("[]",[]);for(var i=items.length-1;i>=0;i--)
listing=new pl.type.Term(".",[new pl.type.Term(items[i],[]),listing]);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[entries,listing])),point.substitution,point)]);}
thread.again();});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_directory(file)){var items=[];for(var prop in file.files)
items.push(prop);var listing=new pl.type.Term("[]",[]);for(var i=items.length-1;i>=0;i--)
listing=new pl.type.Term(".",[new pl.type.Term(items[i],[]),listing]);thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[entries,listing])),point.substitution,point)]);}else{thread.throw_error(pl.error.existence("directory",path,atom.indicator));}}}},"working_directory/2":function(thread,point,atom){var oldcwd=atom.args[0],newcwd=atom.args[1];if(pl.type.is_variable(newcwd)&&(!pl.type.is_variable(oldcwd)||oldcwd.id!==newcwd.id)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_variable(oldcwd)&&!pl.type.is_atom(oldcwd)){thread.throw_error(pl.error.type("atom",oldcwd,atom.indicator));}else if(!pl.type.is_variable(newcwd)&&!pl.type.is_atom(newcwd)){thread.throw_error(pl.error.type("atom",newcwd,atom.indicator));}else{var wd;if(thread.get_flag("nodejs").indicator==="true/0"){wd=process.cwd();if(!pl.type.is_variable(newcwd))
process.chdir(newcwd.id);}else{wd=thread.session.working_directory;if(!pl.type.is_variable(newcwd)){thread.session.working_directory=pl.utils.cd(wd,newcwd.id);}}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[oldcwd,new pl.type.Term(wd,[])])),point.substitution,point)]);}},"delete_file/1":function(thread,point,atom){var path=atom.args[0];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error&&stat.isFile()){fs.unlink(path.id,function(error){if(error)
thread.throw_error(pl.error.permission("delete","source_sink",path,atom.indicator));else
thread.success(point);thread.again();});}else{thread.throw_error(pl.error.existence("source_sink",path,atom.indicator));thread.again();}});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_file(file)){file.parent.remove(file.name);thread.success(point);}else{thread.throw_error(pl.error.existence("source_sink",path,atom.indicator));}}}},"delete_directory/1":function(thread,point,atom){var path=atom.args[0];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error&&stat.isDirectory()){fs.rmdir(path.id,function(error){if(error)
thread.throw_error(pl.error.permission("delete","directory",path,atom.indicator));else
thread.success(point);thread.again();});}else{thread.throw_error(pl.error.existence("directory",path,atom.indicator));thread.again();}});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_directory(file)){if(file!==thread.session.file_system.files&&file.empty()){file.parent.remove(file.name);thread.success(point);}else{thread.throw_error(pl.error.permission("delete","directory",path,atom.indicator));}}else{thread.throw_error(pl.error.existence("directory",path,atom.indicator));}}}},"make_directory/1":function(thread,point,atom){var path=atom.args[0];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error&&(stat.isDirectory()||stat.isFile())){thread.throw_error(pl.error.permission("create","directory",path,atom.indicator));thread.again();}else{fs.mkdir(path.id,function(error){if(error)
thread.throw_error(pl.error.existence("directory",path,atom.indicator));else
thread.success(point);thread.again();});}});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var dirs=absolute.replace(/\/$/,"").split("/");var dir=thread.session.file_system.files;var name=dirs[dirs.length-1];for(var i=1;i<dirs.length-1;i++){dir=dir.lookup(dirs[i]);if(!pl.type.is_directory(dir)){thread.throw_error(pl.error.existence("directory",path,atom.indicator));return;}}
if(dir.lookup(name)){thread.throw_error(pl.error.permission("create","directory",path,atom.indicator));}else{dir.push(name,new pl.type.Directory(name,dir));thread.success(point);}}}},"rename_file/2":function(thread,point,atom){var old_path=atom.args[0],new_path=atom.args[1];if(pl.type.is_variable(old_path)||pl.type.is_variable(new_path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(old_path)){thread.throw_error(pl.error.type("atom",old_path,atom.indicator));}else if(!pl.type.is_atom(new_path)){thread.throw_error(pl.error.type("atom",new_path,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(old_path.id,function(error,stat){if(error||!stat.isFile()){thread.throw_error(pl.error.existence("source_sink",old_path,atom.indicator));thread.again();}else{fs.rename(old_path.id,new_path.id,function(error){if(error)
thread.throw_error(pl.error.existence("source_sink",new_path,atom.indicator));else
thread.success(point);thread.again();});}});return true;}else{var old_file=thread.file_system_open(old_path.id,"text","read");if(old_file){var new_file=thread.file_system_open(new_path.id,"text","write");if(new_file){new_file.text=old_file.text;var absolute=pl.utils.cd(thread.session.working_directory,old_path.id);var dirs=absolute.replace(/\/$/,"").split("/");var dir=thread.session.file_system.files;var name=dirs[dirs.length-1];for(var i=1;i<dirs.length-1;i++)
dir=dir.lookup(dirs[i]);dir.remove(name);thread.success(point);}else{thread.throw_error(pl.error.existence("source_sink",new_path,atom.indicator));}}else{thread.throw_error(pl.error.existence("source_sink",old_path,atom.indicator));}}}},"exists_file/1":function(thread,point,atom){var path=atom.args[0];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error&&stat.isFile())
thread.success(point);thread.again();});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_file(file))
thread.success(point);}}},"exists_directory/1":function(thread,point,atom){var path=atom.args[0];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error&&stat.isDirectory())
thread.success(point);thread.again();});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_directory(file))
thread.success(point);}}},"same_file/2":function(thread,point,atom){var fst_path=atom.args[0],snd_path=atom.args[1];if(pl.type.is_variable(fst_path)||pl.type.is_variable(snd_path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(fst_path)){thread.throw_error(pl.error.type("atom",fst_path,atom.indicator));}else if(!pl.type.is_atom(snd_path)){thread.throw_error(pl.error.type("atom",snd_path,atom.indicator));}else{if(fst_path.id===snd_path.id){thread.success(point);}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(fst_path.id,function(error,fst_stat){if(!error)
fs.stat(snd_path.id,function(error,snd_stat){if(!error&&fst_stat.dev===snd_stat.dev&&fst_stat.ino===snd_stat.ino)
thread.success(point);thread.again();});else
thread.again();});return true;}else{var working_directory=thread.session.working_directory;var fst_file=thread.session.file_system.get(pl.utils.cd(working_directory,fst_path.id));var snd_file=thread.session.file_system.get(pl.utils.cd(working_directory,snd_path.id));if(fst_file&&snd_file&&fst_file===snd_file)
thread.success(point);}}}},"absolute_file_name/2":function(thread,point,atom){var filename=atom.args[0],absolute=atom.args[1];if(pl.type.is_variable(filename)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(filename)){thread.throw_error(pl.error.type("atom",filename,atom.indicator));}else if(!pl.type.is_variable(absolute)&&!pl.type.is_atom(absolute)){thread.throw_error(pl.error.type("atom",absolute,atom.indicator));}else{var absolute_filename;if(thread.get_flag("nodejs").indicator==="true/0"){var path=require("path");absolute_filename=path.resolve(filename.id);}else{absolute_filename=pl.utils.cd(thread.session.working_directory,filename.id);}
thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[absolute,new pl.type.Term(absolute_filename,[])])),point.substitution,point)]);}},"is_absolute_file_name/1":function(thread,point,atom){var filename=atom.args[0];if(pl.type.is_variable(filename)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(filename)){thread.throw_error(pl.error.type("atom",filename,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var path=require('path');if(path.isAbsolute(filename.id))
thread.success(point);}else{if(filename.id.length>0&&filename.id[0]==="/")
thread.success(point);}}},"size_file/2":function(thread,point,atom){var path=atom.args[0],size=atom.args[1];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else if(!pl.type.is_variable(size)&&!pl.type.is_integer(size)){thread.throw_error(pl.error.type("integer",size,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error){var filesize=stat.size;thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[size,new pl.type.Num(filesize,false)])),point.substitution,point)]);}else{thread.throw_error(pl.error.existence("source_sink",path,atom.indicator));}
thread.again();});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_file(file)||pl.type.is_directory(file)){var filesize=file.size();thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[size,new pl.type.Num(filesize,false)])),point.substitution,point)]);}else{thread.throw_error(pl.error.existence("source_sink",path,atom.indicator));}}}},"time_file/2":function(thread,point,atom){var path=atom.args[0],time=atom.args[1];if(pl.type.is_variable(path)){thread.throw_error(pl.error.instantiation(atom.indicator));}else if(!pl.type.is_atom(path)){thread.throw_error(pl.error.type("atom",path,atom.indicator));}else if(!pl.type.is_variable(time)&&!pl.type.is_number(time)){thread.throw_error(pl.error.type("number",time,atom.indicator));}else{if(thread.get_flag("nodejs").indicator==="true/0"){var fs=require('fs');fs.stat(path.id,function(error,stat){if(!error){var mtime=stat.mtime/1000;thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[time,new pl.type.Num(mtime)])),point.substitution,point)]);}else{thread.throw_error(pl.error.existence("source_sink",path,atom.indicator));}
thread.again();});return true;}else{var absolute=pl.utils.cd(thread.session.working_directory,path.id);var file=thread.session.file_system.get(absolute);if(pl.type.is_file(file)||pl.type.is_directory(file)){var mtime=file.modified;thread.prepend([new pl.type.State(point.goal.replace(new pl.type.Term("=",[time,new pl.type.Num(mtime)])),point.substitution,point)]);}else{thread.throw_error(pl.error.existence("source_sink",path,atom.indicator));}}}}};};var exports=["sleep/1","shell/1","shell/2","directory_files/2","working_directory/2","delete_file/1","delete_directory/1","rename_file/2","make_directory/1","exists_file/1","exists_directory/1","same_file/2","absolute_file_name/2","is_absolute_file_name/1","size_file/2","time_file/2"];new pl.type.Module("os",predicates(),exports);})(prolog);if(typeof module!='undefined')module.exports=prolog;};BundleModuleCode['parser/papaparse']=function(module,exports){(function(global)
{'use strict';var IS_WORKER=!global.document&&!!global.postMessage,IS_PAPA_WORKER=IS_WORKER&&/(\?|&)papaworker(=|&|$)/.test(global.location.search),LOADED_SYNC=false,AUTO_SCRIPT_PATH;var workers={},workerIdCounter=0;var Papa={};Papa.parse=CsvToJson;Papa.unparse=JsonToCsv;Papa.RECORD_SEP=String.fromCharCode(30);Papa.UNIT_SEP=String.fromCharCode(31);Papa.BYTE_ORDER_MARK='\ufeff';Papa.BAD_DELIMITERS=['\r','\n','"',Papa.BYTE_ORDER_MARK];Papa.WORKERS_SUPPORTED=!IS_WORKER&&!!global.Worker;Papa.SCRIPT_PATH=null;Papa.LocalChunkSize=1024*1024*10;Papa.RemoteChunkSize=1024*1024*5;Papa.DefaultDelimiter=',';Papa.Parser=Parser;Papa.ParserHandle=ParserHandle;Papa.NetworkStreamer=NetworkStreamer;Papa.FileStreamer=FileStreamer;Papa.StringStreamer=StringStreamer;function detectCSV(chunk,opts){opts=opts||{}
if(Buffer.isBuffer(chunk))chunk=chunk+''
var delimiters=opts.delimiters||[',',';','\t','|']
var newlines=opts.newlines||['\n','\r']
var lines=chunk.split(/[\n\r]+/g)
var delimiter=determineMost(lines[0],delimiters)
var newline=determineMost(chunk,newlines)
if(!delimiter){if(isQuoted(lines[0]))return{newline:newline}
return null}
return{delimiter:delimiter,newline:newline}}
function determineMost(chunk,items){var ignoreString=false
var itemCount={}
var maxValue=0
var maxChar
var currValue
items.forEach(function(item){itemCount[item]=0})
for(var i=0;i<chunk.length;i++){if(chunk[i]==='"')ignoreString=!ignoreString
else if(!ignoreString&&chunk[i]in itemCount){currValue=++itemCount[chunk[i]]
if(currValue>maxValue){maxValue=currValue
maxChar=chunk[i]}}}
return maxChar}
function isQuoted(chunk){var nextQuote=false
if(chunk[0]!=='"')return false
if(chunk[chunk.length-1]!=='"')return false
for(var i=1;i<chunk.length-1;i++){if(chunk[i]==='"')nextQuote=!nextQuote
else if(nextQuote)return false}
return!nextQuote}
Papa.detect=detectCSV;if(typeof module!=='undefined'&&module.exports)
{module.exports=Papa;}
else if(isFunction(global.define)&&global.define.amd)
{define(function(){return Papa;});}
else
{global.Papa=Papa;}
if(global.jQuery)
{var $=global.jQuery;$.fn.parse=function(options)
{var config=options.config||{};var queue=[];this.each(function(idx)
{var supported=$(this).prop('tagName').toUpperCase()==='INPUT'&&$(this).attr('type').toLowerCase()==='file'&&global.FileReader;if(!supported||!this.files||this.files.length===0)
return true;for(var i=0;i<this.files.length;i++)
{queue.push({file:this.files[i],inputElem:this,instanceConfig:$.extend({},config)});}});parseNextFile();return this;function parseNextFile()
{if(queue.length===0)
{if(isFunction(options.complete))
options.complete();return;}
var f=queue[0];if(isFunction(options.before))
{var returned=options.before(f.file,f.inputElem);if(typeof returned==='object')
{if(returned.action==='abort')
{error('AbortError',f.file,f.inputElem,returned.reason);return;}
else if(returned.action==='skip')
{fileComplete();return;}
else if(typeof returned.config==='object')
f.instanceConfig=$.extend(f.instanceConfig,returned.config);}
else if(returned==='skip')
{fileComplete();return;}}
var userCompleteFunc=f.instanceConfig.complete;f.instanceConfig.complete=function(results)
{if(isFunction(userCompleteFunc))
userCompleteFunc(results,f.file,f.inputElem);fileComplete();};Papa.parse(f.file,f.instanceConfig);}
function error(name,file,elem,reason)
{if(isFunction(options.error))
options.error({name:name},file,elem,reason);}
function fileComplete()
{queue.splice(0,1);parseNextFile();}}}
if(IS_PAPA_WORKER)
{global.onmessage=workerThreadReceivedMessage;}
else if(Papa.WORKERS_SUPPORTED)
{AUTO_SCRIPT_PATH=getScriptPath();if(!document.body)
{LOADED_SYNC=true;}
else
{document.addEventListener('DOMContentLoaded',function(){LOADED_SYNC=true;},true);}}
function CsvToJson(_input,_config)
{_config=_config||{};if(_config.worker&&Papa.WORKERS_SUPPORTED)
{var w=newWorker();w.userStep=_config.step;w.userChunk=_config.chunk;w.userComplete=_config.complete;w.userError=_config.error;_config.step=isFunction(_config.step);_config.chunk=isFunction(_config.chunk);_config.complete=isFunction(_config.complete);_config.error=isFunction(_config.error);delete _config.worker;w.postMessage({input:_input,config:_config,workerId:w.id});return;}
var streamer=null;if(typeof _input==='string')
{if(_config.download)
streamer=new NetworkStreamer(_config);else
streamer=new StringStreamer(_config);}
else if((global.File&&_input instanceof File)||_input instanceof Object)
streamer=new FileStreamer(_config);return streamer.stream(_input);}
function JsonToCsv(_input,_config)
{var _output='';var _fields=[];var _quotes=false;var _delimiter=',';var _newline='\r\n';unpackConfig();if(typeof _input==='string')
_input=JSON.parse(_input);if(_input instanceof Array)
{if(!_input.length||_input[0]instanceof Array)
return serialize(null,_input);else if(typeof _input[0]==='object')
return serialize(objectKeys(_input[0]),_input);}
else if(typeof _input==='object')
{if(typeof _input.data==='string')
_input.data=JSON.parse(_input.data);if(_input.data instanceof Array)
{if(!_input.fields)
_input.fields=_input.meta&&_input.meta.fields;if(!_input.fields)
_input.fields=_input.data[0]instanceof Array?_input.fields:objectKeys(_input.data[0]);if(!(_input.data[0]instanceof Array)&&typeof _input.data[0]!=='object')
_input.data=[_input.data];}
return serialize(_input.fields||[],_input.data||[]);}
throw'exception: Unable to serialize unrecognized input';function unpackConfig()
{if(typeof _config!=='object')
return;if(typeof _config.delimiter==='string'&&_config.delimiter.length===1&&Papa.BAD_DELIMITERS.indexOf(_config.delimiter)===-1)
{_delimiter=_config.delimiter;}
if(typeof _config.quotes==='boolean'||_config.quotes instanceof Array)
_quotes=_config.quotes;if(typeof _config.newline==='string')
_newline=_config.newline;}
function objectKeys(obj)
{if(typeof obj!=='object')
return[];var keys=[];for(var key in obj)
keys.push(key);return keys;}
function serialize(fields,data)
{var csv='';if(typeof fields==='string')
fields=JSON.parse(fields);if(typeof data==='string')
data=JSON.parse(data);var hasHeader=fields instanceof Array&&fields.length>0;var dataKeyedByField=!(data[0]instanceof Array);if(hasHeader)
{for(var i=0;i<fields.length;i++)
{if(i>0)
csv+=_delimiter;csv+=safe(fields[i],i);}
if(data.length>0)
csv+=_newline;}
for(var row=0;row<data.length;row++)
{var maxCol=hasHeader?fields.length:data[row].length;for(var col=0;col<maxCol;col++)
{if(col>0)
csv+=_delimiter;var colIdx=hasHeader&&dataKeyedByField?fields[col]:col;csv+=safe(data[row][colIdx],col);}
if(row<data.length-1)
csv+=_newline;}
return csv;}
function safe(str,col)
{if(typeof str==='undefined'||str===null)
return'';str=str.toString().replace(/"/g,'""');var needsQuotes=(typeof _quotes==='boolean'&&_quotes)||(_quotes instanceof Array&&_quotes[col])||hasAny(str,Papa.BAD_DELIMITERS)||str.indexOf(_delimiter)>-1||str.charAt(0)===' '||str.charAt(str.length-1)===' ';return needsQuotes?'"'+str+'"':str;}
function hasAny(str,substrings)
{for(var i=0;i<substrings.length;i++)
if(str.indexOf(substrings[i])>-1)
return true;return false;}}
function ChunkStreamer(config)
{this._handle=null;this._paused=false;this._finished=false;this._input=null;this._baseIndex=0;this._partialLine='';this._rowCount=0;this._start=0;this._nextChunk=null;this.isFirstChunk=true;this._completeResults={data:[],errors:[],meta:{}};replaceConfig.call(this,config);this.parseChunk=function(chunk)
{if(this.isFirstChunk&&isFunction(this._config.beforeFirstChunk))
{var modifiedChunk=this._config.beforeFirstChunk(chunk);if(modifiedChunk!==undefined)
chunk=modifiedChunk;}
this.isFirstChunk=false;var aggregate=this._partialLine+chunk;this._partialLine='';var results=this._handle.parse(aggregate,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted())
return;var lastIndex=results.meta.cursor;if(!this._finished)
{this._partialLine=aggregate.substring(lastIndex-this._baseIndex);this._baseIndex=lastIndex;}
if(results&&results.data)
this._rowCount+=results.data.length;var finishedIncludingPreview=this._finished||(this._config.preview&&this._rowCount>=this._config.preview);if(IS_PAPA_WORKER)
{global.postMessage({results:results,workerId:Papa.WORKER_ID,finished:finishedIncludingPreview});}
else if(isFunction(this._config.chunk))
{this._config.chunk(results,this._handle);if(this._paused)
return;results=undefined;this._completeResults=undefined;}
if(!this._config.step&&!this._config.chunk){this._completeResults.data=this._completeResults.data.concat(results.data);this._completeResults.errors=this._completeResults.errors.concat(results.errors);this._completeResults.meta=results.meta;}
if(finishedIncludingPreview&&isFunction(this._config.complete)&&(!results||!results.meta.aborted))
this._config.complete(this._completeResults,this._input);if(!finishedIncludingPreview&&(!results||!results.meta.paused))
this._nextChunk();return results;};this._sendError=function(error)
{if(isFunction(this._config.error))
this._config.error(error);else if(IS_PAPA_WORKER&&this._config.error)
{global.postMessage({workerId:Papa.WORKER_ID,error:error,finished:false});}};function replaceConfig(config)
{var configCopy=copy(config);configCopy.chunkSize=parseInt(configCopy.chunkSize);if(!config.step&&!config.chunk)
configCopy.chunkSize=null;this._handle=new ParserHandle(configCopy);this._handle.streamer=this;this._config=configCopy;}}
function NetworkStreamer(config)
{config=config||{};if(!config.chunkSize)
config.chunkSize=Papa.RemoteChunkSize;ChunkStreamer.call(this,config);var xhr;if(IS_WORKER)
{this._nextChunk=function()
{this._readChunk();this._chunkLoaded();};}
else
{this._nextChunk=function()
{this._readChunk();};}
this.stream=function(url)
{this._input=url;this._nextChunk();};this._readChunk=function()
{if(this._finished)
{this._chunkLoaded();return;}
xhr=new XMLHttpRequest();if(this._config.withCredentials)
{xhr.withCredentials=this._config.withCredentials;}
if(!IS_WORKER)
{xhr.onload=bindFunction(this._chunkLoaded,this);xhr.onerror=bindFunction(this._chunkError,this);}
xhr.open('GET',this._input,!IS_WORKER);if(this._config.chunkSize)
{var end=this._start+this._config.chunkSize-1;xhr.setRequestHeader('Range','bytes='+this._start+'-'+end);xhr.setRequestHeader('If-None-Match','webkit-no-cache');}
try{xhr.send();}
catch(err){this._chunkError(err.message);}
if(IS_WORKER&&xhr.status===0)
this._chunkError();else
this._start+=this._config.chunkSize;}
this._chunkLoaded=function()
{if(xhr.readyState!=4)
return;if(xhr.status<200||xhr.status>=400)
{this._chunkError();return;}
this._finished=!this._config.chunkSize||this._start>getFileSize(xhr);this.parseChunk(xhr.responseText);}
this._chunkError=function(errorMessage)
{var errorText=xhr.statusText||errorMessage;this._sendError(errorText);}
function getFileSize(xhr)
{var contentRange=xhr.getResponseHeader('Content-Range');return parseInt(contentRange.substr(contentRange.lastIndexOf('/')+1));}}
NetworkStreamer.prototype=Object.create(ChunkStreamer.prototype);NetworkStreamer.prototype.constructor=NetworkStreamer;function FileStreamer(config)
{config=config||{};if(!config.chunkSize)
config.chunkSize=Papa.LocalChunkSize;ChunkStreamer.call(this,config);var reader,slice;var usingAsyncReader=typeof FileReader!=='undefined';this.stream=function(file)
{this._input=file;slice=file.slice||file.webkitSlice||file.mozSlice;if(usingAsyncReader)
{reader=new FileReader();reader.onload=bindFunction(this._chunkLoaded,this);reader.onerror=bindFunction(this._chunkError,this);}
else
reader=new FileReaderSync();this._nextChunk();};this._nextChunk=function()
{if(!this._finished&&(!this._config.preview||this._rowCount<this._config.preview))
this._readChunk();}
this._readChunk=function()
{var input=this._input;if(this._config.chunkSize)
{var end=Math.min(this._start+this._config.chunkSize,this._input.size);input=slice.call(input,this._start,end);}
var txt=reader.readAsText(input,this._config.encoding);if(!usingAsyncReader)
this._chunkLoaded({target:{result:txt}});}
this._chunkLoaded=function(event)
{this._start+=this._config.chunkSize;this._finished=!this._config.chunkSize||this._start>=this._input.size;this.parseChunk(event.target.result);}
this._chunkError=function()
{this._sendError(reader.error);}}
FileStreamer.prototype=Object.create(ChunkStreamer.prototype);FileStreamer.prototype.constructor=FileStreamer;function StringStreamer(config)
{config=config||{};ChunkStreamer.call(this,config);var string;var remaining;this.stream=function(s)
{string=s;remaining=s;return this._nextChunk();}
this._nextChunk=function()
{if(this._finished)return;var size=this._config.chunkSize;var chunk=size?remaining.substr(0,size):remaining;remaining=size?remaining.substr(size):'';this._finished=!remaining;return this.parseChunk(chunk);}}
StringStreamer.prototype=Object.create(StringStreamer.prototype);StringStreamer.prototype.constructor=StringStreamer;function ParserHandle(_config)
{var FLOAT=/^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i;var self=this;var _stepCounter=0;var _input;var _parser;var _paused=false;var _aborted=false;var _delimiterError;var _fields=[];var _results={data:[],errors:[],meta:{}};if(isFunction(_config.step))
{var userStep=_config.step;_config.step=function(results)
{_results=results;if(needsHeaderRow())
processResults();else
{processResults();if(_results.data.length===0)
return;_stepCounter+=results.data.length;if(_config.preview&&_stepCounter>_config.preview)
_parser.abort();else
userStep(_results,self);}};}
this.parse=function(input,baseIndex,ignoreLastRow)
{if(!_config.newline)
_config.newline=guessLineEndings(input);_delimiterError=false;if(!_config.delimiter)
{var delimGuess=guessDelimiter(input,_config.newline);if(delimGuess.successful)
_config.delimiter=delimGuess.bestDelimiter;else
{_delimiterError=true;_config.delimiter=Papa.DefaultDelimiter;}
_results.meta.delimiter=_config.delimiter;}
var parserConfig=copy(_config);if(_config.preview&&_config.header)
parserConfig.preview++;_input=input;_parser=new Parser(parserConfig);_results=_parser.parse(_input,baseIndex,ignoreLastRow);processResults();return _paused?{meta:{paused:true}}:(_results||{meta:{paused:false}});};this.paused=function()
{return _paused;};this.pause=function()
{_paused=true;_parser.abort();_input=_input.substr(_parser.getCharIndex());};this.resume=function()
{_paused=false;self.streamer.parseChunk(_input);};this.aborted=function()
{return _aborted;};this.abort=function()
{_aborted=true;_parser.abort();_results.meta.aborted=true;if(isFunction(_config.complete))
_config.complete(_results);_input='';};function processResults()
{if(_results&&_delimiterError)
{addError('Delimiter','UndetectableDelimiter','Unable to auto-detect delimiting character; defaulted to \''+Papa.DefaultDelimiter+'\'');_delimiterError=false;}
if(_config.skipEmptyLines)
{for(var i=0;i<_results.data.length;i++)
if(_results.data[i].length===1&&_results.data[i][0]==='')
_results.data.splice(i--,1);}
if(needsHeaderRow())
fillHeaderFields();return applyHeaderAndDynamicTyping();}
function needsHeaderRow()
{return _config.header&&_fields.length===0;}
function fillHeaderFields()
{if(!_results)
return;for(var i=0;needsHeaderRow()&&i<_results.data.length;i++)
for(var j=0;j<_results.data[i].length;j++)
_fields.push(_results.data[i][j]);_results.data.splice(0,1);}
function applyHeaderAndDynamicTyping()
{if(!_results||(!_config.header&&!_config.dynamicTyping))
return _results;for(var i=0;i<_results.data.length;i++)
{var row={};for(var j=0;j<_results.data[i].length;j++)
{if(_config.dynamicTyping)
{var value=_results.data[i][j];if(value==='true'||value==='TRUE')
_results.data[i][j]=true;else if(value==='false'||value==='FALSE')
_results.data[i][j]=false;else
_results.data[i][j]=tryParseFloat(value);}
if(_config.header)
{if(j>=_fields.length)
{if(!row['__parsed_extra'])
row['__parsed_extra']=[];row['__parsed_extra'].push(_results.data[i][j]);}
else
row[_fields[j]]=_results.data[i][j];}}
if(_config.header)
{_results.data[i]=row;if(j>_fields.length)
addError('FieldMismatch','TooManyFields','Too many fields: expected '+_fields.length+' fields but parsed '+j,i);else if(j<_fields.length)
addError('FieldMismatch','TooFewFields','Too few fields: expected '+_fields.length+' fields but parsed '+j,i);}}
if(_config.header&&_results.meta)
_results.meta.fields=_fields;return _results;}
function guessDelimiter(input,newline)
{var delimChoices=[',','\t','|',';',Papa.RECORD_SEP,Papa.UNIT_SEP];var bestDelim,bestDelta,fieldCountPrevRow;for(var i=0;i<delimChoices.length;i++)
{var delim=delimChoices[i];var delta=0,avgFieldCount=0;fieldCountPrevRow=undefined;var preview=new Parser({delimiter:delim,newline:newline,preview:10}).parse(input);for(var j=0;j<preview.data.length;j++)
{var fieldCount=preview.data[j].length;avgFieldCount+=fieldCount;if(typeof fieldCountPrevRow==='undefined')
{fieldCountPrevRow=fieldCount;continue;}
else if(fieldCount>1)
{delta+=Math.abs(fieldCount-fieldCountPrevRow);fieldCountPrevRow=fieldCount;}}
if(preview.data.length>0)
avgFieldCount/=preview.data.length;if((typeof bestDelta==='undefined'||delta<bestDelta)&&avgFieldCount>1.99)
{bestDelta=delta;bestDelim=delim;}}
_config.delimiter=bestDelim;return{successful:!!bestDelim,bestDelimiter:bestDelim}}
function guessLineEndings(input)
{input=input.substr(0,1024*1024);var r=input.split('\r');var n=input.split('\n');var nAppearsFirst=(n.length>1&&n[0].length<r[0].length);if(r.length===1||nAppearsFirst)
return'\n';var numWithN=0;for(var i=0;i<r.length;i++)
{if(r[i][0]==='\n')
numWithN++;}
return numWithN>=r.length/2?'\r\n':'\r';}
function tryParseFloat(val)
{var isNumber=FLOAT.test(val);return isNumber?parseFloat(val):val;}
function addError(type,code,msg,row)
{_results.errors.push({type:type,code:code,message:msg,row:row});}}
function Parser(config)
{config=config||{};var delim=config.delimiter;var newline=config.newline;var comments=config.comments;var step=config.step;var preview=config.preview;var fastMode=config.fastMode;if(typeof delim!=='string'||Papa.BAD_DELIMITERS.indexOf(delim)>-1)
delim=',';if(comments===delim)
throw'Comment character same as delimiter';else if(comments===true)
comments='#';else if(typeof comments!=='string'||Papa.BAD_DELIMITERS.indexOf(comments)>-1)
comments=false;if(newline!='\n'&&newline!='\r'&&newline!='\r\n')
newline='\n';var cursor=0;var aborted=false;this.parse=function(input,baseIndex,ignoreLastRow)
{if(typeof input!=='string')
throw'Input must be a string';var inputLen=input.length,delimLen=delim.length,newlineLen=newline.length,commentsLen=comments.length;var stepIsFunction=typeof step==='function';cursor=0;var data=[],errors=[],row=[],lastCursor=0;if(!input)
return returnable();if(fastMode||(fastMode!==false&&input.indexOf('"')===-1))
{var rows=input.split(newline);for(var i=0;i<rows.length;i++)
{var row=rows[i];cursor+=row.length;if(i!==rows.length-1)
cursor+=newline.length;else if(ignoreLastRow)
return returnable();if(comments&&row.substr(0,commentsLen)===comments)
continue;if(stepIsFunction)
{data=[];pushRow(row.split(delim));doStep();if(aborted)
return returnable();}
else
pushRow(row.split(delim));if(preview&&i>=preview)
{data=data.slice(0,preview);return returnable(true);}}
return returnable();}
var nextDelim=input.indexOf(delim,cursor);var nextNewline=input.indexOf(newline,cursor);for(;;)
{if(input[cursor]==='"')
{var quoteSearch=cursor;cursor++;for(;;)
{var quoteSearch=input.indexOf('"',quoteSearch+1);if(quoteSearch===-1)
{if(!ignoreLastRow){errors.push({type:'Quotes',code:'MissingQuotes',message:'Quoted field unterminated',row:data.length,index:cursor});}
return finish();}
if(quoteSearch===inputLen-1)
{var value=input.substring(cursor,quoteSearch).replace(/""/g,'"');return finish(value);}
if(input[quoteSearch+1]==='"')
{quoteSearch++;continue;}
if(input[quoteSearch+1]===delim)
{row.push(input.substring(cursor,quoteSearch).replace(/""/g,'"'));cursor=quoteSearch+1+delimLen;nextDelim=input.indexOf(delim,cursor);nextNewline=input.indexOf(newline,cursor);break;}
if(input.substr(quoteSearch+1,newlineLen)===newline)
{row.push(input.substring(cursor,quoteSearch).replace(/""/g,'"'));saveRow(quoteSearch+1+newlineLen);nextDelim=input.indexOf(delim,cursor);if(stepIsFunction)
{doStep();if(aborted)
return returnable();}
if(preview&&data.length>=preview)
return returnable(true);break;}}
continue;}
if(comments&&row.length===0&&input.substr(cursor,commentsLen)===comments)
{if(nextNewline===-1)
return returnable();cursor=nextNewline+newlineLen;nextNewline=input.indexOf(newline,cursor);nextDelim=input.indexOf(delim,cursor);continue;}
if(nextDelim!==-1&&(nextDelim<nextNewline||nextNewline===-1))
{row.push(input.substring(cursor,nextDelim));cursor=nextDelim+delimLen;nextDelim=input.indexOf(delim,cursor);continue;}
if(nextNewline!==-1)
{row.push(input.substring(cursor,nextNewline));saveRow(nextNewline+newlineLen);if(stepIsFunction)
{doStep();if(aborted)
return returnable();}
if(preview&&data.length>=preview)
return returnable(true);continue;}
break;}
return finish();function pushRow(row)
{data.push(row);lastCursor=cursor;}
function finish(value)
{if(ignoreLastRow)
return returnable();if(typeof value==='undefined')
value=input.substr(cursor);row.push(value);cursor=inputLen;pushRow(row);if(stepIsFunction)
doStep();return returnable();}
function saveRow(newCursor)
{cursor=newCursor;pushRow(row);row=[];nextNewline=input.indexOf(newline,cursor);}
function returnable(stopped)
{return{data:data,errors:errors,meta:{delimiter:delim,linebreak:newline,aborted:aborted,truncated:!!stopped,cursor:lastCursor+(baseIndex||0)}};}
function doStep()
{step(returnable());data=[],errors=[];}};this.abort=function()
{aborted=true;};this.getCharIndex=function()
{return cursor;};}
function getScriptPath()
{var scripts=document.getElementsByTagName('script');return scripts.length?scripts[scripts.length-1].src:'';}
function newWorker()
{if(!Papa.WORKERS_SUPPORTED)
return false;if(!LOADED_SYNC&&Papa.SCRIPT_PATH===null)
throw new Error('Script path cannot be determined automatically when Papa Parse is loaded asynchronously. '+'You need to set Papa.SCRIPT_PATH manually.');var workerUrl=Papa.SCRIPT_PATH||AUTO_SCRIPT_PATH;workerUrl+=(workerUrl.indexOf('?')!==-1?'&':'?')+'papaworker';var w=new global.Worker(workerUrl);w.onmessage=mainThreadReceivedMessage;w.id=workerIdCounter++;workers[w.id]=w;return w;}
function mainThreadReceivedMessage(e)
{var msg=e.data;var worker=workers[msg.workerId];var aborted=false;if(msg.error)
worker.userError(msg.error,msg.file);else if(msg.results&&msg.results.data)
{var abort=function(){aborted=true;completeWorker(msg.workerId,{data:[],errors:[],meta:{aborted:true}});};var handle={abort:abort,pause:notImplemented,resume:notImplemented};if(isFunction(worker.userStep))
{for(var i=0;i<msg.results.data.length;i++)
{worker.userStep({data:[msg.results.data[i]],errors:msg.results.errors,meta:msg.results.meta},handle);if(aborted)
break;}
delete msg.results;}
else if(isFunction(worker.userChunk))
{worker.userChunk(msg.results,handle,msg.file);delete msg.results;}}
if(msg.finished&&!aborted)
completeWorker(msg.workerId,msg.results);}
function completeWorker(workerId,results){var worker=workers[workerId];if(isFunction(worker.userComplete))
worker.userComplete(results);worker.terminate();delete workers[workerId];}
function notImplemented(){throw'Not implemented.';}
function workerThreadReceivedMessage(e)
{var msg=e.data;if(typeof Papa.WORKER_ID==='undefined'&&msg)
Papa.WORKER_ID=msg.workerId;if(typeof msg.input==='string')
{global.postMessage({workerId:Papa.WORKER_ID,results:Papa.parse(msg.input,msg.config),finished:true});}
else if((global.File&&msg.input instanceof File)||msg.input instanceof Object)
{var results=Papa.parse(msg.input,msg.config);if(results)
global.postMessage({workerId:Papa.WORKER_ID,results:results,finished:true});}}
function copy(obj)
{if(typeof obj!=='object')
return obj;var cpy=obj instanceof Array?[]:{};for(var key in obj)
cpy[key]=copy(obj[key]);return cpy;}
function bindFunction(f,self)
{return function(){f.apply(self,arguments);};}
function isFunction(func)
{return typeof func==='function';}})(typeof window!=='undefined'?window:this);};BundleModuleCode['numerics/numerics']=function(module,exports){var current=none;var Aios=none;var options={version:'1.1.1'}
module.exports={current:function(module){current=module.current;Aios=module;},agent:{fft:Require('numerics/fft'),matrix:Require('numerics/matrix'),vector:Require('numerics/vector'),}}};BundleModuleCode['numerics/fft']=function(module,exports){var Vector=Require('numerics/vector');var Matrix=Require('numerics/matrix');var complex={add:function(a,b)
{return[a[0]+b[0],a[1]+b[1]];},subtract:function(a,b)
{return[a[0]-b[0],a[1]-b[1]];},multiply:function(a,b)
{return[(a[0]*b[0]-a[1]*b[1]),(a[0]*b[1]+a[1]*b[0])];},magnitude:function(c)
{return Math.sqrt(c[0]*c[0]+c[1]*c[1]);},phase:function(c)
{return c[0]!=0?Math.atan(c[1]/c[0])*180/Math.PI:(c[1]>0?90:-90);}}
var mapExponent={};var fftUtil={exponent:function(k,N){var x=-2*Math.PI*(k/N);mapExponent[N]=mapExponent[N]||{};mapExponent[N][k]=mapExponent[N][k]||[Math.cos(x),Math.sin(x)];return mapExponent[N][k];},fftMag:function(fftBins){if(isArray(fftBins)){var ret=fftBins.map(complex.magnitude);return ret.slice(0,ret.length/2);}else if(isVector(fftBins)||isMatrix(fftBins)){if(fftBins.columns!=2)throw"fft.fftMag: Complex matrix columns != 2";var ret=Vector(fftBins.rows,{dtn:fftBins.dtn})
return ret.eval(function(v,i){return complex.magnitude([fftBins.get(i,0),fftBins.get(i,1)])});}},fftPha:function(fftBins){if(isArray(fftBins)){var ret=fftBins.map(complex.phase);return ret.slice(0,ret.length/2);}else if(isVector(fftBins)||isMatrix(fftBins)){if(fftBins.columns!=2)throw"fft.fftMag: Complex matrix columns != 2";var ret=Vector(fftBins.rows,{dtn:fftBins.dtn})
return ret.eval(function(v,i){return complex.phase([fftBins.get(i,0),fftBins.get(i,1)])});}},fftFreq:function(fftBins,sampleRate){var stepFreq=sampleRate/(fftBins.length);var ret=fftBins.slice(0,fftBins.length/2);return ret.map(function(__,ix){return ix*stepFreq;});}}
var REVERSE_TABLE=new Array(256);var INT_BITS=32;(function(tab){for(var i=0;i<256;++i){var v=i,r=i,s=7;for(v>>>=1;v;v>>>=1){r<<=1;r|=v&1;--s;}
tab[i]=(r<<s)&0xff;}})(REVERSE_TABLE);var twiddle={INT_BITS:INT_BITS,INT_MAX:0x7fffffff,INT_MIN:-1<<(INT_BITS-1),sign:function(v){return(v>0)-(v<0);},abs:function(v){var mask=v>>(INT_BITS-1);return(v^mask)-mask;},min:function(x,y){return y^((x^y)&-(x<y));},max:function(x,y){return x^((x^y)&-(x<y));},isPow2:function(v){return!(v&(v-1))&&(!!v);},log2:function(v){var r,shift;r=(v>0xFFFF)<<4;v>>>=r;shift=(v>0xFF)<<3;v>>>=shift;r|=shift;shift=(v>0xF)<<2;v>>>=shift;r|=shift;shift=(v>0x3)<<1;v>>>=shift;r|=shift;return r|(v>>1);},log10:function(v){return(v>=1000000000)?9:(v>=100000000)?8:(v>=10000000)?7:(v>=1000000)?6:(v>=100000)?5:(v>=10000)?4:(v>=1000)?3:(v>=100)?2:(v>=10)?1:0;},popCount:function(v){v=v-((v>>>1)&0x55555555);v=(v&0x33333333)+((v>>>2)&0x33333333);return((v+(v>>>4)&0xF0F0F0F)*0x1010101)>>>24;},countTrailingZeros:function(v){var c=32;v&=-v;if(v)c--;if(v&0x0000FFFF)c-=16;if(v&0x00FF00FF)c-=8;if(v&0x0F0F0F0F)c-=4;if(v&0x33333333)c-=2;if(v&0x55555555)c-=1;return c;},nextPow2:function(v){v+=v===0;--v;v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v+1;},prevPow2:function(v){v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v-(v>>>1);},parity:function(v){v^=v>>>16;v^=v>>>8;v^=v>>>4;v&=0xf;return(0x6996>>>v)&1;},reverse:function(v){return(REVERSE_TABLE[v&0xff]<<24)|(REVERSE_TABLE[(v>>>8)&0xff]<<16)|(REVERSE_TABLE[(v>>>16)&0xff]<<8)|REVERSE_TABLE[(v>>>24)&0xff];},interleave2:function(x,y){x&=0xFFFF;x=(x|(x<<8))&0x00FF00FF;x=(x|(x<<4))&0x0F0F0F0F;x=(x|(x<<2))&0x33333333;x=(x|(x<<1))&0x55555555;y&=0xFFFF;y=(y|(y<<8))&0x00FF00FF;y=(y|(y<<4))&0x0F0F0F0F;y=(y|(y<<2))&0x33333333;y=(y|(y<<1))&0x55555555;return x|(y<<1);},deinterleave2:function(v,n){v=(v>>>n)&0x55555555;v=(v|(v>>>1))&0x33333333;v=(v|(v>>>2))&0x0F0F0F0F;v=(v|(v>>>4))&0x00FF00FF;v=(v|(v>>>16))&0x000FFFF;return(v<<16)>>16;},interleave3:function(x,y,z){x&=0x3FF;x=(x|(x<<16))&4278190335;x=(x|(x<<8))&251719695;x=(x|(x<<4))&3272356035;x=(x|(x<<2))&1227133513;y&=0x3FF;y=(y|(y<<16))&4278190335;y=(y|(y<<8))&251719695;y=(y|(y<<4))&3272356035;y=(y|(y<<2))&1227133513;x|=(y<<1);z&=0x3FF;z=(z|(z<<16))&4278190335;z=(z|(z<<8))&251719695;z=(z|(z<<4))&3272356035;z=(z|(z<<2))&1227133513;return x|(z<<2);},deinterleave3:function(v,n){v=(v>>>n)&1227133513;v=(v|(v>>>2))&3272356035;v=(v|(v>>>4))&251719695;v=(v|(v>>>8))&4278190335;v=(v|(v>>>16))&0x3FF;return(v<<22)>>22;},nextCombination:function(v){var t=v|(v-1);return(t+1)|(((~t&-~t)-1)>>>(twiddle.countTrailingZeros(v)+1));}}
function checkpow2(info,vector){if(Math.floor(Math.log2(vector.length))!=Math.log2(vector.length))
throw('fft.'+info+' error: vector length must be a power of 2')}
module.exports={fft:function fft(vector){if(vector.data)vector=vector.data;checkpow2('fft',vector);var X=[],N=vector.length;if(N==1){if(Array.isArray(vector[0]))
return[[vector[0][0],vector[0][1]]];else
return[[vector[0],0]];}
var X_evens=fft(vector.filter(even)),X_odds=fft(vector.filter(odd));for(var k=0;k<N/2;k++){var t=X_evens[k],e=complex.multiply(fftUtil.exponent(k,N),X_odds[k]);X[k]=complex.add(t,e);X[k+(N/2)]=complex.subtract(t,e);}
function even(__,ix){return ix%2==0;}
function odd(__,ix){return ix%2==1;}
return X;},fftInPlace:function(vector){if(vector.data)vector=vector.data;checkpow2('fftInPlace',vector);var N=vector.length;var trailingZeros=twiddle.countTrailingZeros(N);for(var k=0;k<N;k++){var p=twiddle.reverse(k)>>>(twiddle.INT_BITS-trailingZeros);if(p>k){var complexTemp=[vector[k],0];vector[k]=vector[p];vector[p]=complexTemp;}else{vector[p]=[vector[p],0];}}
for(var len=2;len<=N;len+=len){for(var i=0;i<len/2;i++){var w=fftUtil.exponent(i,len);for(var j=0;j<N/len;j++){var t=complex.multiply(w,vector[j*len+i+len/2]);vector[j*len+i+len/2]=complex.subtract(vector[j*len+i],t);vector[j*len+i]=complex.add(vector[j*len+i],t);}}}},ifft:function ifft(signal){if(signal.data)signal=signal.data;checkpow2('ifft',signal);var csignal=[];for(var i=0;i<signal.length;i++){csignal[i]=[signal[i][1],signal[i][0]];}
var ps=module.exports.fft(csignal);var res=[];for(var j=0;j<ps.length;j++){res[j]=[ps[j][1]/ps.length,ps[j][0]/ps.length];}
return res;},fftMag:fftUtil.fftMag,fftPha:fftUtil.fftPha,fftFreq:fftUtil.fftFreq,};};BundleModuleCode['numerics/vector']=function(module,exports){Require('numerics/polyfill')
var sprintf=Require('com/sprintf');if(typeof Array.prototype.get=='undefined'){Object.defineProperty(Array.prototype,'get',{value:function(i){return this[i];},configurable:true})
Object.defineProperty(Array.prototype,'set',{value:function(a,b){this[a]=b;},configurable:true})}
if(typeof Array.prototype.print=='undefined'){Object.defineProperty(Array.prototype,'print',{value:function(format){var i,s='',sep='',columns=this.length,complex=isArray(this[0]);if(!format)format='%4.2f';for(i=0;i<columns;i++){if(i!=0)s=s+'\n';if(complex)
s=s+sprintf.sprintf(format,this[i][0])+','+
sprintf.sprintf(format,this[i][1]);else
s=s+sprintf.sprintf(format,this[i]);}
return s;},configurable:true})}
if(typeof Array.prototype.info=='undefined'){Object.defineProperty(Array.prototype,'info',{value:function(){return{dtn:'Array',size:this.length,columns:this.length,offset:0,}},configurable:true})}
function toUTF8Array(str){var utf8=[];for(var i=0;i<str.length;i++){var charcode=str.charCodeAt(i);if(charcode<0x80)utf8.push(charcode);else if(charcode<0x800){utf8.push(0xc0|(charcode>>6),0x80|(charcode&0x3f));}
else if(charcode<0xd800||charcode>=0xe000){utf8.push(0xe0|(charcode>>12),0x80|((charcode>>6)&0x3f),0x80|(charcode&0x3f));}
else{i++;charcode=((charcode&0x3ff)<<10)|(str.charCodeAt(i)&0x3ff)
utf8.push(0xf0|(charcode>>18),0x80|((charcode>>12)&0x3f),0x80|((charcode>>6)&0x3f),0x80|(charcode&0x3f));}}
return utf8;}
function fromUTF8Array(data){var str='',i;for(i=0;i<data.length;i++){var value=data[i];if(value<0x80){str+=String.fromCharCode(value);}else if(value>0xBF&&value<0xE0){str+=String.fromCharCode((value&0x1F)<<6|data[i+1]&0x3F);i+=1;}else if(value>0xDF&&value<0xF0){str+=String.fromCharCode((value&0x0F)<<12|(data[i+1]&0x3F)<<6|data[i+2]&0x3F);i+=2;}else{var charCode=((value&0x07)<<18|(data[i+1]&0x3F)<<12|(data[i+2]&0x3F)<<6|data[i+3]&0x3F)-0x010000;str+=String.fromCharCode(charCode>>10|0xD800,charCode&0x03FF|0xDC00);i+=3;}}
return str;}
var complex={add:function(a,b)
{return[a[0]+b[0],a[1]+b[1]];},subtract:function(a,b)
{return[a[0]-b[0],a[1]-b[1]];},multiply:function(a,b)
{return[(a[0]*b[0]-a[1]*b[1]),(a[0]*b[1]+a[1]*b[0])];},magnitude:function(offset,c)
{return Math.sqrt(c[offset]*c[offset]+c[offset+1]*c[offset+1]);},phase:function(offset,c)
{return c[offset]!=0?Math.atan(c[offset+1]/c[offset])*180/Math.PI:(c[offset+1]>0?90:-90);}}
function Vector(a,b){var self=this;var i,columns,size,offset=0,dim=1,dtn,dt=Vector.options.dt,data;if(!(this instanceof Vector))return new Vector(a,b);var options=isObject(b)?b:{};if(isNumber(a)){columns=a;if(options.type)dt=options.type;if(options.dtn)dt=options.dtn=='Array'?Array:TypedArrayOfName[options.dtn];size=columns;if(options.complex)size*=2;if(options.dtn&&!dt)throw("Vector: Unknown array type dtn="+options.dtn)
data=new dt(size);}else if(isArray(a)){size=columns=a.length;if(options.type)dt=options.type;if(options.dtn)dt=options.dtn=='Array'?Array:TypedArrayOfName[options.dtn];if(options.dtn&&!dt)throw("Vector: Unknown array type dtn="+options.dtn)
if(options.dtn&&options.dtn!='Array'){data=new dt(a);}else{dt=Array;data=a;}}else if(isObject(a)){columns=a.columns;size=a.size||columns;scale=options.scale;if(options.dtn)dt=options.dtn=='Array'?Array:TypedArrayOfName[options.dtn];if(options.dtn&&!dt)throw("Vector: Unknown array type dtn="+options.dtn)
if(options.dtn&&a.dtn!=options.dtn){if(isArray(a.data)&&!scale)
data=new dt(a.data);else{data=new dt(size);if(scale)for(i=0;i<size;i++)data[i]=a.data[i]/scale;else for(i=0;i<size;i++)data[i]=a.data[i];}
dtn=options.dtn;}else{dtn=a.dtn;data=a.data;offset=a.offset;}
if(a.scale)this.scale=a.scale;if(a.complex)this.complex=a.complex;}else if(isString(a)){columns=a.length;if(options.type)dt=options.type;if(options.dtn)dt=options.dtn=='Array'?Array:TypedArrayOfName[options.dtn];if(options.dtn&&!dt)throw("Vector: Unknown array type dtn="+options.dtn)
data=new dt(toUTF8Array(a));}
this.columns=columns;this.size=this.length=size;this.layout=1;this.data=data;this.dims=dim;this.offset=offset;if(options.complex)this.complex=true;if(options.scale)this.scaler=options.scale;this.dtn=dtn||dt.name;if(this.dtn=='Array')this._arrayFix();}
Vector.options={dt:Float32Array,dtn:'Float32Array'}
Vector.abs=function(m){return Vector.clone(m).abs();}
Vector.add=function(m,v){return Vector.clone(m).add(v);}
Vector.clone=function(src){return Vector(src);}
Vector.checkVector=function(o){if(o instanceof Vector)return o;else return Vector(o);}
Vector.cos=function(m){return Vector.clone(m).cos();}
Vector.div=function(m,v){return Vector.clone(m).div(v);}
Vector.empty=function(columns){return Vector(columns);}
Vector.exp=function(m){return Vector.clone(m).exp();}
isVector=Vector.isVector=function(o){return(o instanceof Vector)}
Vector.max=function(vector1,vector2){vector1=Vector.checkVector(vector1);vector2=Vector.checkVector(vector2);var columns=vector1.columns;var result=Vector(columns,{dtn:vector1.dtn});for(var i=0;i<columns;i++){result.data[i]=Math.max(vector1.data[i],vector2.data[i]);}
return result;}
Vector.min=function(vector1,vector2){vector1=Vector.checkVector(vector1);vector2=Vector.checkVector(vector2);var columns=vector1.columns;var result=Vector(columns,{dtn:vector1.dtn});for(var i=0;i<columns;i++){result.data[i]=Math.min(vector1.data[i],vector2.data[i]);}
return result;}
Vector.mod=function(m,v){return Vector.clone(m).mod(v);}
Vector.mul=function(m,v){return Vector.clone(m).mul(v);}
Vector.neg=function(m){return Vector.clone(m).neg();}
Vector.ones=function(columns){return Vector(columns).fill(1);}
Vector.rand=function(columns,rng){if(rng==undefined)rng=Math.random;return Vector(columns).fill(function(){return rng();});}
Vector.randInt=function(columns,maxValue,rng){if(rng==undefined)rng=Math.random;return Vector(columns).fill(function(){return(rng()*maxValue)|0;});}
Vector.sin=function(m){return Vector.clone(m).sin();}
Vector.sub=function(m,v){return Vector.clone(m).sub(v);}
Vector.zero=function(columns){return Vector(columns).fill(0);}
Vector.prototype._arrayFix=function(){var self=this;this.get=function(column){return self.data[self.offset+column]};this.set=function(column,v){self.data[self.offset+column]=v};}
Vector.prototype.abs=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]=Math.abs(this.data[i]);return this;}
Vector.prototype.add=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]+=v;return this;}
Vector.prototype.apply=function(f){for(var i=0;i<this.columns;i++)
f.call(this,i)}
Vector.prototype.clone=function(){return Vector(this);}
Vector.prototype.cos=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]=Math.cos(this.data[i]);return this;}
Vector.prototype.div=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]/=v;return this;}
Vector.prototype.divide=function(column,k){return this.data[column]/=k;}
Vector.prototype.eval=function(f){var i;switch(this.dtn){case'Array':for(i=0;i<this.columns;i++)
this.set(i,f(this.get(i)))
break;default:for(i=0;i<this.size;i++)this.data[i]=f(this.data[i],i);}
return this;}
Vector.prototype.exp=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]=Math.exp(this.data[i]);return this;}
Vector.prototype.fill=function(valueOrFunction){if(typeof valueOrFunction=='function'){for(var i=0;i<this.columns;i++){this.data[i]=valueOrFunction(i);}}else this.data.fill(valueOrFunction);return this;}
Vector.prototype.filter=function(f,asArray){var i,j=0,res=Vector(this.columns,{dtn:asArray?'Array':this.dtn});for(i=0;i<this.columns;i++){v=f(this.data[i],i);if(v)res.data[j]=this.data[i],j++;}
return j<this.columns?res.slice(j):res;}
Vector.prototype.get=function(column){return this.data[this.offset+column];}
Vector.prototype.imag=function(i){if(this.complex)return this.get(i*2+1);}
Vector.prototype.incr=function(column,delta){return this.data[column]+=delta;}
Vector.prototype.info=function(){var i={dtn:this.dtn,size:this.size,columns:this.columns,offset:this.offset,}
if(this.scaler)i.scaler=this.scaler;if(this.complex)i.complex=true;return i;}
isVector=Vector.isVector=function(o){return(o instanceof Vector)}
Vector.prototype.magnitude=function(){var res;if(this.complex){res=Vector(this.columns,{dtn:this.dtn});for(var i=0;i<res.columns;i++)
res.data[i]=complex.magnitude(this.offset+i*2,this.data);}
return res;}
Vector.prototype.map=function(f,asArray){var res=Vector(this.columns,{dtn:asArray?'Array':this.dtn});for(var i=0;j<this.columns;i++)
res.data[i]=f(this.data[i],i);return res;}
Vector.prototype.multiply=function(column,k){return this.data[column]*=k;}
Vector.prototype.mean=function(v){return this.sum()/this.size;}
Vector.prototype.mod=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]=this.data[i]%v;return this;}
Vector.prototype.mul=function(v){var i,j;for(var i=0;i<this.size;i++)this.data[i]*=v;return this;}
Vector.prototype.neg=function(v){var i,j;for(var i=0;i<this.size;i++)this.data[i]=-this.data[i];return this;}
Vector.prototype.phase=function(){var res;if(this.complex){res=Vector(this.columns,{dtn:this.dtn});for(var i=0;i<res.columns;i++)
res.data[i]=complex.phase(this.offset+i*2,this.data);}
return res;}
Vector.prototype.prod=function(v){var i,j,v=1;for(i=0;i<this.size;i++)v*=this.data[i];return v;}
Vector.prototype.print=function(format,transpose){var j,s='';if(!format)format='%4.2f';if(!this.complex)
for(j=0;j<this.columns;j++){if(j!=0)s=s+(transpose?' ':'\n');s=s+sprintf.sprintf(format,this.data[j]);}
else
for(j=0;j<this.columns;j=j+2){if(j!=0)s=s+(transpose?' ':'\n');s=s+'('+sprintf.sprintf(format,this.data[j])+','+sprintf.sprintf(format,this.data[j+1])+')';}
return s;}
Vector.prototype.reduce=function(f){return this.data.reduce(f);}
Vector.prototype.real=function(i){if(this.complex)return this.get(i*2);}
Vector.prototype.resize=function(options){if((options.offset&&(options.columns+options.offset)>this.columns)||!options.columns)throw new Error('Vecotr.resize: invalid argument(s)');this.columns=options.columns;if(options.offset)this.offset=options.offset;this.size=this.length=this.columns;if(options.slice)
this.data=options.offset?this.data.slice(options.offset,options.columns+offset):this.data.slice(0,options.columns);return this;}
Vector.prototype.set=function(column,val){this.data[this.offset+column]=val;return this;}
Vector.prototype.sin=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]=Math.sin(this.data[i]);}
Vector.prototype.size=function(){return this.size;}
Vector.prototype.slice=function(columns,offset){return Vector(this,{columns:columns,offset:offset,slice:true});}
Vector.prototype.sub=function(v){var i,j;for(i=0;i<this.size;i++)this.data[i]-=v;return this;}
Vector.prototype.subRange=function(columns,offset){offset=checkOption(offset,0);var res=Vector({columns:columns,data:this.data.slice(offset,columns+offset),dtn:this.dtn});return res;}
Vector.prototype.sum=function(){var sum=0;for(var i=0;i<this.size;i++)sum+=this.data[i];return sum}
module.exports=Vector;};BundleModuleCode['numerics/polyfill']=function(module,exports){var typed_arrays=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];TypedArrayOfName={Int8Array:Int8Array,Uint8Array:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array}
typed_arrays.forEach(function(typed_array){if(!typed_array.prototype.slice)typed_array.prototype.slice=function(begin,end){var len=this.length;;var size;var start=begin||0;start=(start>=0)?start:Math.max(0,len+start);end=end||len;var up_to=(typeof end=='number')?Math.min(end,len):len;if(end<0)up_to=len+end;size=up_to-start;if(size<=0)size=0;var typed_array_constructor=this.constructor;var cloned=new typed_array_constructor(size);for(var i=0;i<size;i++){cloned[i]=this[start+i];}
return cloned;};if(!typed_array.prototype.print)typed_array.prototype.print=function(){var s='[ ',sep='';for(var i=0;i<this.length;i++){s=s+(i>0?' , ':'')+this[i].toString();}
return s+' ]';};if(!typed_array.prototype.reduce)typed_array.prototype.reduce=function(apply){var res=this[0];for(var i=1;i<this.length;i++){res=apply(res,this[i]);}
return res;};});isTypedArray=function(o){for(var t in typed_arrays)if(o instanceof typed_arrays[t])return true;return false;}
isArray=function(v){return v instanceof Array}
isNumber=function(v){return typeof v=='number'}
isObject=function(v){return typeof v=='object'}
isBuffer=function(v){return v instanceof Buffer}
isFunction=function(v){return typeof v=='function'}
isString=function(v){return typeof v=='string'}
isBoolean=function(v){return typeof v=='boolean'}
if(typeof Array.prototype.scale!='function')
Object.defineProperty(Array.prototype,'scale',{value:function(k,off,inplace){var ar=this;if(isBoolean(off))inplave=off,off=undefined;if(off!=undefined){if(inplace)for(var i=0;i<ar.length;i++)ar[i]=(ar[i]-off)*k;else ar=this.map(function(v){return(v-off)*k});}else{if(inplace)for(var i=0;i<ar.length;i++)ar[i]=ar[i]*k;else ar=this.map(function(v){return v*k});}
return ar;},configurable:true})
if(typeof Array.prototype.get=='undefined'){Object.defineProperty(Array.prototype,'get',{value:function(i){return this[i];},configurable:true})
Object.defineProperty(Array.prototype,'set',{value:function(i,v){this[i]=v;},configurable:true})}};BundleModuleCode['numerics/matrix']=function(module,exports){Require('numerics/polyfill')
var sprintf=Require('com/sprintf');var Vector=Require('numerics/vector');var ALL=[],FORALL='*',FOREACH='x';isRange=function(v){return isArray(v)&&v.length==2}
isAll=function(v){return v=='*'||(isArray(v)&&v.length==0)}
isForEach=function(v){return v==FOREACH}
isArrayArray=function(v){return isArray(v)&&isArray(v[0])}
isArrayArrayArray=function(v){return isArray(v)&&isArray(v[0])&&isArray(v[0][0])}
integer=function(v){return Math.floor(v)}
divide=function(a,b){return Math.floor(a/b)}
function todo(what){throw("Not implemented: Matrix."+what)}
function checkNumber(name,value){if(typeof value!=='number'){throw new TypeError(name+' must be a number');}}
function transpose(layout){switch(layout){case 12:return 21;case 21:return 12;}}
Object.defineProperty(Array.prototype,'get',{value:function(i,j,k){if(k!=undefined)
return this[i][j][k];else if(j!=undefined)
return this[i][j];else
return this[i];},configurable:true})
Object.defineProperty(Array.prototype,'getRow',{value:function(i){return this[i];},configurable:true})
Object.defineProperty(Array.prototype,'mapRow',{value:function(f){return this[i].map(f);},configurable:true})
Object.defineProperty(Array.prototype,'set',{value:function(a,b,c,d){if(d!=undefined)
return this[a][b][c]=d;else if(c!=undefined)
return this[a][b]=c;else
return this[a]=b;},configurable:true})
Object.defineProperty(Array.prototype,'setRow',{value:function(i,row){return this[i]=row;},configurable:true})
Object.defineProperty(Array.prototype,'print',{value:function(format){var i,j,k,s='',sep='',info=this.info();if(!format)format='%4.2f';switch(info.dims){case 1:for(j=0;j<info.columns;j++){if(j!=0)s=s+'\n';s=s+sprintf.sprintf(format,this[j]);}
break;case 2:for(j=0;j<info.rows;j++){sep='';if(j!=0)s=s+'\n';for(i=0;i<info.columns;i++){s=s+sep+sprintf.sprintf(format,this[j][i]);sep=' ';}}
break;case 3:for(k=0;k<info.levels;k++){if(k!=0)s=s+'\n\n';for(j=0;j<info.rows;j++){sep='';if(j!=0)s=s+'\n';for(i=0;i<info.columns;i++){s=s+sep+sprintf.sprintf(format,this[k][j][i]);sep=' ';}}}}
return s;},configurable:true})
Object.defineProperty(Array.prototype,'info',{value:function(){var rows,columns,levels;if(isArrayArrayArray(this))levels=this.length,rows=this[0].length,columns=this[0][0].length;else if(isArrayArray(this))rows=this.length,columns=this[0].length;else columns=this.length;if(levels)return{dtn:'Array',size:levels*rows*columns,levels:levels,rows:rows,columns:columns,dims:3,offset:0,};else if(rows)return{dtn:'Array',size:rows*columns,rows:rows,columns:columns,dims:2,offset:0,};else return{dtn:'Array',size:columns,columns:columns,dims:1,offset:0,}},configurable:true})
function Matrix(a,b,c,d){var self=this;var rows,columns,levels,dims=2,dtn,dt=Matrix.options.dt,data,layout=12,size,transpose;var options=isObject(d)?d:(isObject(c)?c:(isObject(b)?b:{}));if(!(this instanceof Matrix))return new Matrix(a,b,c,d);if(isNumber(a)&&isNumber(b)){rows=a;columns=b;if(isNumber(c))levels=c;dims=levels?3:2;if(options.type)dt=options.type;if(options.dtn)dt=options.dtn=='Array'?Array:TypedArrayOfName[options.dtn];if(options.layout)layout=options.layout;else layout=dims==2?12:123;size=rows*columns;if(levels)size*=levels;if(options.dtn&&!dt)throw("Matrix: Unknown array type dtn="+options.dtn)
if(dt.name=='Array')
data=new Array(rows).fill(null).map(function(row){return new Array(columns).fill(0)});else
data=new dt(size);}
else if(isNumber(a)){rows=1;columns=a;dims=2;if(options.type)dt=options.type;if(options.dtn)dt=TypedArrayOfName[options.dtn];if(options.layout)layout=options.layout;else layout=12;if(options.dtn&&!dt)throw("Matrix: Unknown array type dtn="+options.dtn)
size=columns;data=new dt(size);}
else if(isArrayArray(a)){rows=a.length;columns=a[0].length;if(isArrayArrayArray(a))levels=rows,rows=a[0].length,columns=a[0][0].length;size=rows*columns;if(levels)size*=levels;dims=levels?3:2;if(options.type)dt=options.type;if(options.dtn){dt=TypedArrayOfName[options.dtn];}
if(options.layout)layout=options.layout;else layout=dims==2?12:123;if(options.dtn&&!dt)throw("Matrix: Unknown array type dtn="+options.dtn)
if(options.dtn&&options.dtn!='Array'){data=new dt(size);switch(layout){case 12:a.forEach(function(row,rowi){row.forEach(function(col,coli){data[coli+rowi*columns]=col;})});break;case 21:a.forEach(function(row,rowi){row.forEach(function(col,coli){data[rowi+coli*rows]=col;})});break;}}else{dt=Array;data=a;}}else if(isArray(a)){rows=1;columns=a.length;size=columns;dims=2;if(options.type)dt=options.type;if(options.dtn)dt=TypedArrayOfName[options.dtn];if(options.layout)layout=options.layout;else layout=12;if(options.dtn&&!dt)throw("Matrix: Unknown array type dtn="+options.dtn)
if(options.dtn&&options.dtn!='Array'){data=new dt(a);}else{dt=Array;data=[a];}}else if(a instanceof Matrix){if(options.transpose){rows=a.columns;columns=a.rows;levels=a.levels;size=a.size;dims=a.dims;transpose=true;data=a.data;dtn=a.dtn;switch(a.layout){case 12:layout=21;break;case 21:layout=12;break;case 123:layout=321;break;case 321:layout=123;break;}}else{rows=options.rows||a.rows;columns=options.columns||a.columns;levels=options.levels||a.levels;dims=a.dims;size=rows*columns;if(levels)size*=levels;transpose=false;scale=options.scale;if((options.dtn&&options.dtn!=a.dtn)||size!=a.size){dtn=options.dtn;data=new dt(size);if(scale)for(i=0;i<size;i++)data[i]=a.data[i]/scale;else for(i=0;i<size;i++)data[i]=a.data[i];}else{dtn=a.dtn;if(dtn!='Array')
data=a.data.slice();else{data=a.data.map(function(row){return row.slice()});}}
if(a.scale)this.scale=a.scale;if(a.complex)this.complex=a.complex;layout=a.layout;}}else if(isObject(a)&&a.data){rows=a.rows||(a.y&&a.x);columns=a.columns||a.y||a.x;levels=a.levels||a.z;size=a.size||((rows?rows:1)*(columns?columns:1)*(levels?levels:1));dims=a.dims||(levels?3:(rows?2:1));layout=a.layout||(levels?123:(rows?12:1));dtn=a.dtn;data=a.data;}
if(levels)this.levels=levels;this.rows=rows;this.columns=columns;this.size=size;this.layout=layout;this.data=data;this.dims=dims;this.length=levels?levels:(rows?rows:columns);this.dtn=dtn||dt.name;if(options.complex)this.complex=true;if(options.scale)this.scaler=options.scale;if(this.dtn=='Array'){switch(this.layout){case 12:this.get=function(row,column){return this.data[row][column]};this.set=function(row,column,v){this.data[row][column]=v};break;case 21:this.get=function(column,row){return this.data[row][column]};this.set=function(column,row,v){this.data[row][column]=v};break;case 123:this.get=function(row,column,level){return this.data[row][column][level]};this.set=function(row,column,level,v){this.data[row][column][level]=v};break;}}else switch(this.layout){case 1:this.index=function(x){return x}
this.get=function(x){return this.data[x]}
this.set=function(x,v){return this.data[x]=v}
break;case 12:this.index=function(x,y){return x*self.columns+y}
this.get=function(x,y){return this.data[x*this.columns+y]}
this.set=function(x,y,v){return this.data[x*this.columns+y]=v}
break;case 21:this.index=function(x,y){return y*this.rows+x}
this.get=function(x,y){return this.data[y*this.rows+x]}
this.set=function(x,y,v){return this.data[y*this.rows+x]=v}
break;case 123:this.index=function(x,y,z){return z+y*self.columns+x*this.columns*this.rows}
this.get=function(x,y,z){return this.data[z+y*this.levels*this.rows+x*this.levels]}
this.set=function(x,y,z,v){return this.data[z+y*this.levels*this.rows+x*this.levels]=v}
break;case 321:this.index=function(x,y,z){return x+y*self.rows+z*this.columns*this.rows}
this.get=function(x,y,z){return this.data[x+y*this.rows+z*this.columns*this.rows]}
this.set=function(x,y,z,v){return this.data[x+y*self.rows+z*this.columns*this.rows]=v}
break;}}
Matrix.options={dt:Float32Array,dtn:'Float32Array'}
Matrix.abs=function(m){return Matrix.clone(m).abs();}
Matrix.add=function(m,v){return Matrix.clone(m).add(v);}
Matrix.clone=function(src){return Matrix(src);}
Matrix.columnVector=function(array){return Matrix(array)}
Matrix.checkArray=function(arrayOrMatrix){if(arrayOrMatrix instanceof _MatrixConstructor)return arrayOrMatrix.data;else return arrayOrMatrix;}
Matrix.checkMatrix=function(arrayOrMatrix){if(arrayOrMatrix instanceof Matrix)return arrayOrMatrix;else return Matrix(arrayOrMatrix);}
Matrix.checkMatrixSize=function(matrix1,matrix2){if(matrix1.dims!=matrix2.dims)return false;if(matrix1.rows!=matrix2.rows||matrix1.columns!=matrix2.columns||matrix1.levels!=matrix2.levels)return false;}
Matrix.cos=function(m){return Matrix.clone(m).cos();}
Matrix.diag=function(array,rows,columns){if(!rows)rows=array.length;if(!columns)columns=rows;if(rows!=columns)Matrix.error("Not a square matrix",'diag');return Matrix(rows,columns).fill(function(i,j){return i==j?array[i]:0;})}
Matrix.div=function(m,v){return Matrix.clone(m).div(v);}
Matrix.empty=function(rows,columns){return Matrix(rows,columns);}
Matrix.error=function(what,where,ref){throw new Error((where?('Matrix.'+where+': '):'')+what);}
Matrix.errorRange=function(what,where,ref){throw new RangeError((where?('Matrix.'+where+': '):'')+what);}
Matrix.eye=function(rows,columns,val,options){if(!val)val=1;if(!columns)columns=rows;return Matrix(rows,columns,options).fill(function(i,j){return i==j?val:0;});}
Matrix.exp=function(m){return Matrix.clone(m).exp();}
isMatrix=Matrix.isMatrix=function(o){return(o instanceof Matrix)}
Matrix.max=function(matrix1,matrix2){var result;matrix1=this.checkMatrix(matrix1);matrix2=this.checkMatrix(matrix2);if(!this.checkMatrixSize(matrix1,matrix2))Matrix.error('matrix1 not compatble with matrix2','max');var rows=matrix1.rows;var columns=matrix1.columns;var levels=matrix1.levels;switch(matrix1.dims){case 1:break;case 2:result=Matrix(rows,columns,{dtn:matrix1.dtn});for(var i=0;i<rows;i++){for(var j=0;j<columns;j++){result.set(i,j,Math.max(matrix1.get(i,j),matrix2.get(i,j)));}}
break;case 3:break;}
return result;}
Matrix.min=function(matrix1,matrix2){var result;matrix1=this.checkMatrix(matrix1);matrix2=this.checkMatrix(matrix2);if(!this.checkMatrixSize(matrix1,matrix2))Matrix.error('matrix1 not compatble with matrix2','min');var rows=matrix1.rows;var columns=matrix1.columns;var levels=matrix1.levels;switch(matrix1.dims){case 1:break;case 2:result=Matrix(rows,columns,levels,{dtn:matrix1.dtn});for(var i=0;i<rows;i++){for(var j=0;j<columns;j++){result.set(i,j,Math.min(matrix1.get(i,j),matrix2.get(i,j)));}}
break;}
return result;}
Matrix.mod=function(m,v){return Matrix.clone(m).mod(v);}
Matrix.mul=function(m,v){return Matrix.clone(m).mul(v);}
Matrix.neg=function(m){return Matrix.clone(m).neg();}
Matrix.ones=function(rows,columns){return Matrix(rows,columns).fill(1);}
Matrix.rand=function(rows,columns,rng){if(rng==undefined)rng=Math.random;return Matrix(rows,columns).fill(function(){return rng();});}
Matrix.randInt=function(rows,columns,maxValue,rng){if(rng==undefined)rng=Math.random;return Matrix(rows,columns).fill(function(){return(rng()*maxValue)|0;});}
Matrix.sin=function(m){return Matrix.clone(m).sin();}
Matrix.sub=function(m,v){return Matrix.clone(m).sub(v);}
Matrix.zero=function(rows,columns){return Matrix(columns,rows).fill(0);}
Matrix.prototype.abs=function(v){this.eval(Math.abs);return this;}
Matrix.prototype.add=function(v){this.eval(function(x){return x+v});return this;}
Matrix.prototype.apply=function(f){var i,j,k;switch(this.dims){case 1:for(j=0;j<this.columns;j++)
f.call(this,j)
return this;case 2:for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
f.call(this,i,j)
return this;case 3:for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
for(k=0;k<this.levels;k++)
f.call(this,i,j,k)
return this;}}
Matrix.prototype.checkMatrixDims=function(dims){if(this.dims!=dims)this.errorRange('Matrix has not expected dimension '+dims);}
Matrix.prototype.checkColumnIndex=function(index,outer){var max=outer?this.columns:this.columns-1;if(index<0||index>max)this.errorRange('Column index out of range');}
Matrix.prototype.checkRowIndex=function(index,outer){var max=outer?this.rows:this.rows-1;if(index<0||index>max)
this.errorRange('Row index out of range');}
Matrix.prototype.checkRowVector=function(vector){if(vector.to1DArray){vector=vector.to1DArray();}
if(vector.length!==this.columns)
this.errorRange('vector size must be the same as the number of columns');return vector;}
Matrix.prototype.checkColumnVector=function(vector){if(vector.to1DArray){vector=vector.to1DArray();}
if(vector.length!==this.rows)
this.errorRange('vector size must be the same as the number of rows');return vector;}
Matrix.prototype.checkIndices=function(rowIndices,columnIndices){return{row:this.checkRowIndices(rowIndices),column:this.checkColumnIndices(columnIndices)};}
Matrix.prototype.checkRowIndices=function(rowIndices){var self=this;if(typeof rowIndices!=='object'){throw new TypeError('unexpected type for row indices');}
var rowOut=rowIndices.some(function(r){return r<0||r>=self.rows;});if(rowOut){throw new RangeError('row indices are out of range');}
if(!Array.isArray(rowIndices))rowIndices=Array.from(rowIndices);return rowIndices;}
Matrix.prototype.checkColumnIndices=function(columnIndices){var self=this;if(typeof columnIndices!=='object'){throw new TypeError('unexpected type for column indices');}
var columnOut=columnIndices.some(function(c){return c<0||c>=self.columns;});if(columnOut){throw new RangeError('column indices are out of range');}
if(!Array.isArray(columnIndices))columnIndices=Array.from(columnIndices);return columnIndices;}
Matrix.prototype.checkRange=function(startRow,endRow,startColumn,endColumn){if(arguments.length!==4){throw new RangeError('expected 4 arguments');}
checkNumber('startRow',startRow);checkNumber('endRow',endRow);checkNumber('startColumn',startColumn);checkNumber('endColumn',endColumn);if(startRow>endRow||startColumn>endColumn||startRow<0||startRow>=this.rows||endRow<0||endRow>=this.rows||startColumn<0||startColumn>=this.columns||endColumn<0||endColumn>=this.columns){throw new RangeError('Submatrix indices are out of range');}}
Matrix.prototype.clone=function(){return Matrix(this);}
Matrix.prototype.copy=function(a,b,c,d){var x,y,z,rx,ry,rz,i,j,k,src;if(isNumber(a))i=a;if(isNumber(b))j=b;if(isNumber(c))k=c;if(isArray(a))rx=a;if(isArray(b))ry=b;if(isArray(c))rz=c;if(isArray(d))src=d;if(isVector(d))src=d;if(!src&&!d&&(isArray(c)||isVector(c)))src=c,rz=undefined;if(!src&&!c&&(isArray(b)||isVector(b)))src=b,ry=undefined;if(!src&&!a&&(isArray(a)||isVector(a)))src=a,rx=[0,this.columns-1];if(isVector(src))src=src.data;if(!src)return Matrix({rows:this.rows,columns:this.columns,levels:this.levels,dtn:this.dtn,layout:this.layout,data:this.data.slice()})
if(!src)throw"Matrix.copy: no source array provided";if(rx&&rx.length==0)rx=[0,this.rows-1];if(ry&&ry.length==0)ry=[0,this.columns-1];if(rz&&rz.length==0)rz=[0,this.levels-1];if(rx&&(rx[1]-rx[0]+1)!=src.length)throw"Matrix.copy: range mismatch (src)"
if(ry&&(ry[1]-ry[0]+1)!=src.length)throw"Matrix.copy: range mismatch (src)"
if(rz&&(rz[1]-rz[0]+1)!=src.length)throw"Matrix.copy: range mismatch (src)"
switch(this.dims){case 1:for(x=rx[0];x<rx[1];x++)this.data[x]=src[x-rx[0]];break;case 2:if(rx&&j!=undefined)
for(x=rx[0];x<=rx[1];x++)
this.data[this.index(x,j)]=src[x-rx[0]];else if(i!=undefined&&ry)
for(y=ry[0];y<=ry[1];y++)
this.data[this.index(i,y)]=src[y-ry[0]];else todo('copy 2');break;case 3:if(rx&&j!=undefined&&k!=undefined)
for(x=rx[0];x<=rx[1];x++)
this.data[this.index(x,j,k)]=src[x-rx[0]];else if(ry&&i!=undefined&&k!=undefined)
for(y=ry[0];y<=ry[1];y++)
this.data[this.index(i,y,k)]=src[y-ry[0]];else if(rz&&i!=undefined&&j!=undefined)
for(z=rz[0];z<=rz[1];z++)
this.data[this.index(i,j,z)]=src[z-rz[0]];else todo('copy 3');break;}
return this;}
Matrix.prototype.convert=function(a,b,c,d){var i,j,k,d,v,m,ni,nj,nk,filter;if(isNumber(a))i=a;if(isNumber(b))j=b;if(isNumber(c))k=c;if(isString(b))filter=b;if(isString(c))filter=c;if(isString(d))filter=d;if(!filter)filter='mean';if(!i)throw"Matrix.convert: no target size (number)";m=Matrix(i,j,k);switch(filter){case'mean':filter=function(a,b,i,n){if(i==n-1)return(a+b)/n;else return a+b};break;case'exp':filter=function(a,b,i,n){return(a+b)/2};break;case'exp-peak':filter=function(a,b,i,n){return(Math.abs(a)+Math.abs(b))/2};break;case'peak':filter=function(a,b,i,n){if(Math.abs(a)>Math.abs(b))return Math.abs(a);else return Math.abs(a);};break;case'min':filter=function(a,b,i,n){return a<b?a:b};break;case'max':filter=function(a,b,i,n){return a>b?a:b};break;default:filter=function(){return 0}}
switch(this.dims){case 1:ni=Math.floor(this.i/m.i);for(i=0;i<m.i;i++){v=this.data[i*ni];for(d=1;d<ni;d++){v=filter(v,this.data[i*ni+d],d,ni);}
m.data[i]=v;}
break;}
return m;}
Matrix.prototype.cos=function(v){this.eval(Math.cos);return this;}
Matrix.prototype.diag=function(v){var a=[];if(this.rows!=this.columns)return;for(var i=0;i<this.rows;i++)a.push(this.data[i+i*this.i]);return a;}
Matrix.prototype.dim=function(){switch(this.dims){case 1:return[this.columns];case 2:return[this.rows,this.columns];case 3:return[this.rows,this.columns,this.levels];}}
Matrix.prototype.div=function(v){this.eval(function(x){return x/v});return this;}
Matrix.prototype.divide=function(a,b,c,d){switch(this.dims){case 1:return this.set(a,this.get(a)/b);case 2:return this.set(a,b,this.get(a,b)/c);case 3:return this.set(a,b,c,this.get(a,b,c)/d);}}
Matrix.prototype.error=function(what,where){throw new Error((where?('Matrix.'+where+': '):'')+what);}
Matrix.prototype.errorRange=function(what,where){throw new RangeError((where?('Matrix.'+where+': '):'')+what);}
Matrix.prototype.eval=function(f){var i,j,k;switch(this.dtn){case'Array':switch(this.dims){case 1:for(i=0;i<this.columns;i++)
this.set(i,f(this.get(i)))
break;case 2:for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
this.set(i,j,f(this.get(i,j)))
break
case 3:for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
for(k=0;k<this.levels;k++)
this.set(i,j,k,f(this.get(i,j,k)))
break;}
break;default:for(i=0;i<this.size;i++)this.data[i]=f(this.data[i]);}
return this;}
Matrix.prototype.exp=function(v){this.eval(Math.exp);return this;}
Matrix.prototype.fill=function(valueOrFunction){if(typeof valueOrFunction=='function'){switch(this.dims){case 1:for(i=0;i<this.columns;i++)
this.set(i,valueOrFunction(i.j))
return this;case 2:for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
this.set(i,j,valueOrFunction(i,j))
return this;case 3:for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
for(k=0;k<this.levels;k++)
this.set(i,j,k,valueOrFunction(i,j,k))
return this;}}else this.data.fill(valueOrFunction);return this;}
Matrix.prototype.getCol=function(index,asVector){}
Matrix.prototype.getRow=function(index,asVector){this.checkMatrixDims(2);this.checkRowIndex(index);var row,data,i,j;switch(this.dtn){case'Array':if(this.layout==12){if(!asVector)
return this.data[index];else
return Vector(this.data[index]);}else{if(!asVector){row=new Array(this.columns);if(this.rows==1)return this.data;for(i=0;i<this.columns;i++){row[i]=this.get(index,i);}}else{if(this.rows==1)return this.data;row=Vector(this.columns,{dtn:this.dtn});for(i=0;i<this.columns;i++){row.set(i,this.get(index,i));};}}
break;default:if(!asVector){row=new Array(this.columns);if(this.rows==1)return this.data;for(i=0;i<this.columns;i++){row[i]=this.get(index,i);}}else if(this.layout==12){row=Vector({dtn:this.dtn,data:this.data,offset:index*this.columns,columns:this.columns});}else{if(this.rows==1)return this.data;row=Vector(this.columns,{dtn:this.dtn});for(i=0;i<this.columns;i++){row.set(i,this.get(index,i));};}}
return row;}
Matrix.prototype.incr=function(a,b,c,d){switch(this.dims){case 1:return this.set(a,this.get(a)+b);case 2:return this.set(a,b,this.get(a,b)+c);case 3:return this.set(a,b,c,this.get(a,b,c)+d);}}
Matrix.prototype.info=function(){var o={dtn:this.dtn,size:this.size,columns:this.columns,layout:this.layout,dims:this.dims}
if(this.rows)o.rows=this.rows;if(this.levels)o.levels=this.levels;if(this.scaler)o.scaler=this.scaler;if(this.complex)o.complex=true;return o;}
Matrix.prototype.isColumnVector=function(){return this.columns===1;}
Matrix.prototype.isEchelonForm=function(){this.checkMatrixDims(2);var i=0;var j=0;var previousColumn=-1;var isEchelonForm=true;var checked=false;while((i<this.rows)&&(isEchelonForm)){j=0;checked=false;while((j<this.columns)&&(checked===false)){if(this.get(i,j)===0){j++;}else if((this.get(i,j)===1)&&(j>previousColumn)){checked=true;previousColumn=j;}else{isEchelonForm=false;checked=true;}}
i++;}
return isEchelonForm;}
Matrix.prototype.isReducedEchelonForm=function(){this.checkMatrixDims(2);var i=0;var j=0;var previousColumn=-1;var isReducedEchelonForm=true;var checked=false;while((i<this.rows)&&(isReducedEchelonForm)){j=0;checked=false;while((j<this.columns)&&(checked===false)){if(this.get(i,j)===0){j++;}else if((this.get(i,j)===1)&&(j>previousColumn)){checked=true;previousColumn=j;}else{isReducedEchelonForm=false;checked=true;}}
for(var k=j+1;k<this.rows;k++){if(this.get(i,k)!==0){isReducedEchelonForm=false;}}
i++;}
return isReducedEchelonForm;}
Matrix.prototype.isRowVector=function(){return this.rows===1;}
Matrix.prototype.isSquare=function(){return this.rows==this.columns}
Matrix.prototype.isSymmetric=function(){if(this.isSquare()){for(var i=0;i<this.rows;i++){for(var j=0;j<=i;j++){if(this.get(i,j)!==this.get(j,i)){return false;}}}
return true;}
return false;}
Matrix.prototype.iter=function(a,b,c,d){var func,rx,ry,rz,x,y,z,self=this;if(isFunction(a))func=a;else if(isFunction(b))func=b;else if(isFunction(c))func=c;else if(isFunction(d))func=d;if(isArray(a))rx=a;if(isArray(b))ry=b;if(isArray(c))rz=c;if(isString(a))rx=a;if(isString(b))ry=b;if(isString(c))rz=c;if(!func)throw"Matrx.iter: no function supplied";if(!rx&&!ry&&!rz)
return this.data.forEach(func);switch(this.dims){case 1:break;todo('iter 1')
case 2:break;todo('iter 2')
case 3:if(isArray(rx)&&rx.length==0)rx=[0,this.rows];if(isArray(ry)&&ry.length==0)ry=[0,this.columns];if(isArray(rz)&&rz.length==0)rz=[0,this.levels];if(rz==FORALL){for(x=rx[0];x<rx[1];x++){for(y=ry[0];y<ry[1];y++){func(x,y,this.subMatrixRange(x,y,ALL))}}}else if(rx==FORALL){todo('iter 3.ryx=FORALL')}else if(ry==FORALL){todo('iter 3.ry=FORALL')}else{todo('iter 3')}}
return this;}
Matrix.prototype.map=function(f,asArray){var res,i,j,k;switch(this.dims){case 1:res=Matrix(this.columns,{dtn:asArray?'Array':this.dtn});for(j=0;j<this.columns;j++)
res.set(j,f(this.get(j),j));break;case 2:res=Matrix(this.rows,this.columns,{dtn:asArray?'Array':this.dtn});for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
res.set(i,j,f(this.get(i,j),i,j));break;case 3:res=Matrix(this.rows,this.columns,this.levels,{dtn:asArray?'Array':this.dtn});for(i=0;i<this.rows;i++)
for(j=0;j<this.columns;j++)
for(k=0;k<this.levels;k++)
res.set(i,j,k,f(this.get(i,j,k),i,j,k));break;}
return res;}
Matrix.prototype.mapRow=function(f){var res=[];for(var row=0;row<this.rows;row++){res.push(f(this.getRow(row)));}
return res;}
Matrix.prototype.minmax=function(){var d0=Number.MAX_VALUE,d1=Number.MIN_VALUE;for(i=0;i<this.size;i++){d0=Math.min(d0,this.data[i]);d1=Math.max(d1,this.data[i]);}
return{min:d0,max:d1};}
Matrix.prototype.mapToArray=function(f){var res=new Array(this.size);for(var i=0;i<this.rows;i++)
for(var j=0;j<this.columns;j++)
res[i*this.columns+j]=f(this.get(i,j),i,j);return res;}
Matrix.prototype.multiply=function(a,b,c,d){switch(this.dims){case 1:return this.set(a,this.get(a)*b);case 2:return this.set(a,b,this.get(a,b)*c);case 3:return this.set(a,b,c,this.get(a,b,c)*d);}}
Matrix.prototype.mean=function(v){return this.sum()/this.size;}
Matrix.prototype.mod=function(v){this.eval(function(x){return x%v});return this;}
Matrix.prototype.mmul=function(other){this.checkMatrixDims(2);other=Matrix.checkMatrix(other);if(this.columns!==other.rows){console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');}
var m=this.rows;var n=this.columns;var p=other.columns;var result=Matrix(m,p,{dtn:this.dtn});var Bcolj=new Array(n);for(var j=0;j<p;j++){for(var k=0;k<n;k++){Bcolj[k]=other.get(k,j);}
for(var i=0;i<m;i++){var s=0;for(k=0;k<n;k++){s+=this.get(i,k)*Bcolj[k];}
result.set(i,j,s);}}
return result;}
Matrix.prototype.mul=function(v){this.eval(function(x){return x*v});return this;}
Matrix.prototype.neg=function(v){this.eval(function(x){return-x});return this;}
Matrix.prototype.prod=function(v){var i,j,k,v=1;switch(this.dtn+this.dims){case'Array1':for(i=0;i<this.columns;i++){v*=this.data[i];}
break;case'Array2':for(i=0;i<this.rows;i++){for(j=0;j<this.columns;j++){v*=this.data[i][j];}}
break;case'Array3':for(i=0;i<this.rows;i++){for(j=0;j<this.columns;j++){for(k=0;k<this.levels;k++){v*=this.data[i][j][k];}}}
break;default:for(i=0;i<this.size;i++)v*=this.data[i];}
return v;}
Matrix.prototype.print=function(format){var i,j,k,s='',sep='';if(!format)format='%4.2f';switch(this.dims){case 1:for(i=0;i<this.columns;i++){if(i!=0)s=s+'\n';s=s+sprintf.sprintf(format,this.get(i));}
break;case 2:for(i=0;i<this.rows;i++){sep='';if(i!=0)s=s+'\n';for(j=0;j<this.columns;j++){s=s+sep+sprintf.sprintf(format,this.get(i,j));sep=' ';}}
break;case 3:for(k=0;k<this.levels;k++){if(k!=0)s=s+'\n\n';for(i=0;i<this.rows;i++){sep='';if(i!=0)s=s+'\n';for(j=0;j<this.columns;j++){s=s+sep+sprintf.sprintf(format,this.get(i,j,k));sep=' ';}}}}
return s;}
Matrix.prototype.reduce=function(f){return this.data.reduce(f);}
Matrix.prototype.resize=function(options){for(var p in options){switch(p){case'rows':case'columns':case'levels':this[p]=options[p];break;}}
this.size=this.columns*(this.rows?this.rows:1)*(this.levels?this.levels:1);this.length=this.rows?this.rows:this.columns;return this}
Matrix.prototype.reverseRow=function(row){var t,len=this.columns;for(var i=0;i<(len/2)|0;i++){t=this.get(row,i);this.set(row,i,this.get(row,len-i-1));this.set(row,len-i-1,t);}
return this;}
Matrix.prototype.scale=function(a,b,c){var m,k=1,offset,inplace=false;if(isNumber(a))k=a;if(isBoolean(b))inplace=b;else if(isBoolean(c))inplace=c;if(isNumber(b))offset=b;else if(isNumber(c))offset=c;m=inplace?this:this.copy();if(k!=1){if(offset)
for(var i=0;i<m.data.length;i++)m.data[i]=(m.data[i]-offset)*k;else
for(var i=0;i<m.data.length;i++)m.data[i]=m.data[i]*k;}else if(offset){for(var i=0;i<m.data.length;i++)m.data[i]=m.data[i]-offset;}
return m;}
Matrix.prototype.selection=function(rowIndices,columnIndices){this.checkMatrixDims(2);var newMatrix=Matrix(rowIndices.length,columnIndices.length,{dtn:this.dtn});for(var i=0;i<rowIndices.length;i++){var rowIndex=rowIndices[i];for(var j=0;j<columnIndices.length;j++){var columnIndex=columnIndices[j];newMatrix.set(i,j,this.get(rowIndex,columnIndex));}}
return newMatrix;}
Matrix.prototype.setRow=function(row,data){data=Matrix.checkArray(data);for(var i=0;i<this.columns;i++){this.set(row,i,data[i]);}}
Matrix.prototype.slice=function(i,offset){var rows,columns,levels;switch(this.dims){case 1:return Matrix(this,{columns:i,offset:offset,slice:true});break;case 2:case 3:return Matrix(this,{rows:i,offset:offset,slice:true});break;}}
Matrix.prototype.sin=function(){this.eval(Math.sin);return this;}
Matrix.prototype.size=function(){return this.size;}
Matrix.prototype.sub=function(v){this.eval(function(x){return x-v});return this;}
Matrix.prototype.subMatrix=function(startRow,endRow,startColumn,endColumn){this.checkMatrixDims(2);this.checkRange(startRow,endRow,startColumn,endColumn);var newMatrix=Matrix(endRow-startRow+1,endColumn-startColumn+1,{dtn:this.dtn});for(var i=startRow;i<=endRow;i++){for(var j=startColumn;j<=endColumn;j++){newMatrix.set(i-startRow,j-startColumn,this.get(i,j));}}
return newMatrix;}
Matrix.prototype.subMatrixRange=function(rx,ry,rz){var i,j,i0,i1,x0,x1,y0,y1,z0,z1,res;switch(this.dims){case 1:x0=0,x1=this.i-1;if(isRange(rx))x0=rx[0],x1=rx[1];else throw"Matrix.subMatrixRange: no range";var i0=x0,i1=i0+1+x1;return Vector({data:this.data.slice(i0,i1),columns:i1-i0,dtn:this.dtn});case 2:todo('subMatrixRange 2')
case 3:if((isAll(rz)||(isRange(rz))&&isNumber(rx)&&isNumber(ry)&&this.layout==123)){z0=0,z1=this.levels-1;if(isRange(rz))z0=rz[0],z1=rz[1];var i0=this.index(rx,ry,z0),i1=i0+1+z1;return Vector({data:this.data.slice(i0,i1),columns:i1-i0,dtn:this.dtn});}if((isAll(rx)||isRange(rx))&&(isAll(ry)||isRange(ry))&&isNumber(rz)){res=Matrix(this.rows,this.columns,{dtn:this.dtn});x0=0,x1=this.rows-1;if(isRange(rx))x0=rx[0],x1=rx[1];y0=0,y1=this.columns-1;if(isRange(ry))y0=ry[0],y1=ry[1];z0=rz;for(i=x0;i<x1;i++)
for(j=y0;j<y1;j++)
res.set(i,j,this.get(i,j,z0));return res;}
else todo('subMatrixRange 3.rx/ry')}}
Matrix.prototype.subMatrixRow=function(indices,startColumn,endColumn){this.checkMatrixDims(2);if(startColumn===undefined)startColumn=0;if(endColumn===undefined)endColumn=this.columns-1;if((startColumn>endColumn)||(startColumn<0)||(startColumn>=this.columns)||(endColumn<0)||(endColumn>=this.columns)){throw new RangeError('Argument out of range');}
var newMatrix=Matrix(indices.length,endColumn-startColumn+1,{dtn:this.dtn});for(var i=0;i<indices.length;i++){for(var j=startColumn;j<=endColumn;j++){if(indices[i]<0||indices[i]>=this.rows){throw new RangeError('Row index out of range: '+indices[i]);}
newMatrix.set(i,j-startColumn,this.get(indices[i],j));}}
return newMatrix;}
Matrix.prototype.subMatrixColumn=function(indices,startRow,endRow){this.checkMatrixDims(2);if(startRow===undefined)startRow=0;if(endRow===undefined)endRow=this.rows-1;if((startRow>endRow)||(startRow<0)||(startRow>=this.rows)||(endRow<0)||(endRow>=this.rows)){throw new RangeError('Argument out of range');}
var newMatrix=Matrix(endRow-startRow+1,indices.length,{dtn:this.dtn});for(var i=0;i<indices.length;i++){for(var j=startRow;j<=endRow;j++){if(indices[i]<0||indices[i]>=this.columns){throw new RangeError('Column index out of range: '+indices[i]);}
newMatrix.set(j-startRow,i,this.get(j,indices[i]));}}
return newMatrix;}
Matrix.prototype.subRowVector=function(vector){this.checkMatrixDims(2);vector=this.checkRowVector(vector);for(var i=0;i<this.rows;i++){for(var j=0;j<this.columns;j++){this.set(i,j,this.get(i,j)-vector[j]);}}
return this;}
Matrix.prototype.setSubMatrix=function(matrix,startRow,startColumn){matrix=this.checkMatrix(matrix);this.checkMatrixDims(2);matrix.checkMatrixDims(2);var endRow=startRow+matrix.rows-1;var endColumn=startColumn+matrix.columns-1;this.checkRange(startRow,endRow,startColumn,endColumn);for(var i=0;i<matrix.rows;i++){for(var j=0;j<matrix.columns;j++){this.set(startRow+i,startColumn+j)=matrix.get(i,j);}}
return this;}
Matrix.prototype.sum=function(by){var i,j,k,v=0;switch(by){case'row':return this.sumByRow();case'column':return this.sumByColumn();default:switch(this.dtn+this.dims){case'Array1':for(i=0;i<this.columns;i++){v+=this.data[i];}
break;case'Array2':for(i=0;i<this.rows;i++){for(j=0;j<this.columns;j++){v+=this.data[i][j];}}
break;case'Array3':for(i=0;i<this.rows;i++){for(j=0;j<this.columns;j++){for(k=0;k<this.levels;k++){v+=this.data[i][j][k];}}}
break;default:for(i=0;i<this.size;i++)v+=this.data[i];}
return v;}}
Matrix.prototype.sumByRow=function(){var sum=Matrix.zeros(this.rows,1);for(var i=0;i<this.rows;++i){for(var j=0;j<this.columns;++j){sum.set(i,0,sum.get(i,0)+this.get(i,j));}}
return sum;}
Matrix.prototype.sumByColumn=function(){var sum=Matrix.zeros(1,this.columns);for(var i=0;i<this.rows;++i){for(var j=0;j<this.columns;++j){sum.set(0,j,sum.get(0,j)+this.get(i,j));}}
return sum;}
Matrix.prototype.toArray=function(rx,ry,rz){switch(this.dims){case 1:return Array.from(this.data);case 2:todo('toArray 2')
case 3:todo('toArray 3')}}
Matrix.ALL=ALL;Matrix.FOREACH=FOREACH;Matrix.FORALL=FORALL;module.exports=Matrix};BundleModuleCode['ui/app/app']=function(module,exports){var Io=Require('com/io');var Comp=Require('com/compat');var blessed=Require('term/blessed');var options={version:'1.8.2'}
var LAYOUT={SMALL:'small',NORMAL:'normal',LARGE:'large',XLARGE:'xlarge',PORTRAIT:'portrait',LANDSCAPE:'landscape',from:function(screen){if(screen.width>screen.height){if(screen.width<70)return{small:true,landscape:true};else return{normal:true,landscape:true};}else{if(screen.height<70)return{small:true,portrait:true};else return{normal:true,portrait:true};}}}
function UI(options){var self=this,i;if(!(this instanceof UI)){return new UI(options);}
this.options=options||{};if(!this.options.pages)this.options.pages=1;if(!this.options.terminal){this.options.terminal=(process.platform==='win32'?'windows-ansi':'xterm-color');}
if(this.options.forceCursor==undefined)this.options.forceCursor=true;this.page=1;this.pages=[];this.static={};this.styles=options.styles||{};for(i=0;i<=this.options.pages;i++){this.pages.push({});}
this.pages.show=function(page){var thepage,p,current=self.page;switch(page){case'prev':if(self.pages[self.page]&&self.pages[self.page].prev)page=self.pages[self.page].prev;else if(self.pages[self.page-1])page=self.page-1;break;case'next':if(self.pages[self.page]&&self.pages[self.page].next)page=self.pages[self.page].next;else if(self.pages[self.page+1])page=self.page+1;break;case'this':case undefined:page=self.page;break;}
thepage=self.pages[page];if(self.events[page]&&self.events[page]['load'])
self.events[page]['load']();for(p in thepage){if(thepage[p]&&thepage[p].show&&!thepage[p].noshow)thepage[p].show();}
self.screen.render();self.page=page;};this.pages.hide=function(page){var thepage,p;if(page=='this'||page==undefined)page=self.page;thepage=self.pages[page];for(p in thepage)
if(thepage[p]&&thepage[p].hide)thepage[p].hide();if(self.options.terminal.indexOf('xterm')!=-1&&self.options.forceCursor)
self.screen.program.hideCursor(true);};this.events=[];this.pages.on=function(page,event,callback){if(!self.events[page])self.events[page]=[];self.events[page][event]=callback;}}
UI.prototype.button=function(options){var self=this,width=options.width;if(Comp.obj.isString(options.width)){width=Comp.pervasives.int_of_string(options.width);width=this.screen.width*width/100;}
var obj=blessed.button({width:options.width||(options.content.length+4),left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top||0,height:3,align:'center',content:options.content||'?',mouse:true,focus:false,border:options.border||this.getStyle('button.border',{type:'line'}),style:{fg:options.fg||this.getStyle('button.fg','white'),bg:options.bg||this.getStyle('button.bg','blue'),bold:true,border:{fg:this.getStyle('button.border.fg','black'),bg:this.getStyle('button.border.bg',undefined),},hover:{border:{fg:'red'}}}});obj.noshow=options.hidden;this.screen.append(obj);if(options.click)obj.on('press',options.click);if(options.action){switch(typeof options.action){case'function':obj.on('press',options.action);break;case'string':if(options.action=='next'||options.action=='prev'){obj.on('press',function(){if(self.pages[self.page][options.action]){self.pages.hide('this');self.pages.show(self.pages[self.page][options.action]);}});}else{obj.on('press',function(){if(self.pages[options.action]){self.pages.hide('this');self.pages.show(options.action);}});}
break;}}
return obj;}
UI.prototype.chat=function(options){var self=this,width=options.width||(this.screen.width-(options.left*2||2));options.scrollable=true;options.scrollbar={ch:' ',track:{bg:'yellow'},style:{fg:'cyan',inverse:true}};options.mouse=true;var obj=blessed.chat({label:options.label||'My Text',value:options.value||'',bg:'default',barBg:'default',barFg:'blue',width:width,height:options.height||8,left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top||0,keys:true,vi:false,mouse:true,inputOnFocus:true,tags:true,focus:true,wrap:options.wrap,multiline:true,scrollbar:options.scrollbar,scrollable:options.scrollable,prompt:options.prompt,border:this.getStyle('input.border',{type:'line'}),style:{fg:options.fg||this.getStyle('input.fg','blue'),bg:options.bg||this.getStyle('input.bg',undefined),user:options.user,bot:options.bot,border:{fg:this.getStyle('input.border.fg','black'),bg:this.getStyle('input.border.bg',undefined),},label:this.getStyle('input.label',undefined),focus:{border:{fg:'red'}}}});obj.noshow=options.hidden;this.screen.append(obj);obj.on('focus',function(){if(!self.options.keyboard)
return self.options.terminal.indexOf('xterm')!=-1&&self.options.forceCursor?self.screen.program._write('\x1b[?12;25h'):0;if(!self._keyboard)
self._keyboard=self.keyboard({width:self.screen.width<60?'100%':'80%',height:self.layout.small?'100%':'90%',compact:self.layout.small});self._keyboard.setCallback(function(v){if(v)obj.setValue(v),obj.update();});self._keyboard.setValue(obj.getValue());self._keyboard.setLabel(obj.getLabel());self._keyboard.show();});return obj;}
UI.prototype.checkbox=function(options){var obj=blessed.checkbox({checked:options.value||false,left:options.left,right:options.right,top:options.top||0,mouse:true,inputOnFocus:true,height:1,text:options.text||'empty'});obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.dialog=function(options){var width=options.width,height=options.height;if(Comp.obj.isString(options.width)){width=Comp.pervasives.int_of_string(options.width);width=int(this.screen.width*width/100);}
if(Comp.obj.isString(options.height)){height=Comp.pervasives.int_of_string(options.height);height=int(this.screen.height*height/100);}
var obj=blessed.Question({width:width,left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top||(options.center?int(this.screen.height/2-height/2):0),height:height,noshow:true,okButton:options.okButton||'Okay',cancelButton:options.cancelButton,style:{bg:this.getStyle('dialog.bg','red'),fg:this.getStyle('dialog.fg','white'),bold:true}});this.screen.append(obj);return obj;}
UI.prototype.fileManager=function(options){if(options.box){options.box.border=this.getStyle('filemanager.box.border',options.box.border);options.box.bg=this.getStyle('filemanager.box.bg',options.box.bg);options.input=this.getStyle('filemanager.input',options.input);}
if(options.arrows){options.arrows.fg=this.getStyle('filemanager.arrows.fg',options.arrows.fg);options.arrows.bg=this.getStyle('filemanager.arrows.bg',options.arrows.bg);}
var obj=blessed.FileManager({parent:options.parent,border:options.border||this.getStyle('filemanager.border',{}),style:{fg:options.fg||this.getStyle('filemanager.fg',undefined),bg:options.bg||this.getStyle('filemanager.bg',undefined),label:options.label||this.getStyle('filemanager.label',undefined),selected:{bg:'blue',fg:'white'},focus:{border:{fg:'red'}}},height:options.height||'half',width:options.width||'half',top:options.top||'center',left:options.left||'center',label:'%path',cwd:options.cwd||process.env.PWD||process.env.CWD||process.env.HOME,autohide:options.autohide,hidden:options.hidden,noshow:options.hidden,keys:true,vi:true,scrollbar:{bg:'white',ch:' '},okayButton:options.okayButton||'OK',cancelButton:options.cancelButton||'Cancel',input:options.input,arrows:options.arrows,box:options.box,border:this.getStyle('filemanager.border',undefined)});this.screen.append(obj);return obj;}
UI.prototype.filterOptions=function(options,wname){var self=this,attr,wopts={};for(attr in options){switch(attr){case'type':case'index':break;case'on':switch(options.type){case'button':if(options.on.click&&typeof options.on.click=='function')
wopts.click=function(){options[attr](wname)};if(options.on.onclick&&typeof options.on.onclick=='function')
wopts.click=function(){options[attr](wname)};break;}
break;case'click':case'onclick':switch(options.type){case'button':if(typeof options[attr]=='string')
wopts.click=function(){if(!self.pages[options[attr]])return;self.pages.hide('this');self.pages.show(options[attr]);};else
wopts.click=options[attr];break;}
break;default:wopts[attr]=options[attr];}}
return wopts;}
UI.prototype.getStyle=function(attr,def){var path=attr.split('.'),elem,style=this.styles;while(path.length&&style){elem=path.shift();style=style[elem];}
return style!=undefined?style:def;}
UI.prototype.info=function(options){var width=options.width;if(Comp.obj.isString(options.width)){width=Comp.pervasives.int_of_string(options.width);width=this.screen.width*width/100;}
if(options.scrollable&&!options.scrollbar){options.scrollbar={ch:' ',track:{bg:'yellow'},style:{fg:'cyan',inverse:true}};options.mouse=true;}
var obj=blessed.textbox({top:options.top||1,left:(options.center?int(this.screen.width/2-width/2):options.left||(options.right?undefined:1)),right:options.right,width:options.width||(this.screen.width-(options.left*2||2)),height:options.height||3,label:options.label,value:options.value||'',focus:true,wrap:options.wrap,multiline:options.multiline,scrollbar:options.scrollbar,scrollable:options.scrollable,mouse:options.mouse,border:this.getStyle('info.border',{type:'line'}),style:{fg:options.fg||this.getStyle('info.fg','blue'),bg:options.bg||this.getStyle('info.bg',undefined),label:this.getStyle('info.label',undefined),border:{fg:this.getStyle('info.border.fg','black'),bg:this.getStyle('info.border.bg',undefined),},}});obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.init=function(){var self=this;this.screen=blessed.screen({smartCSR:false,terminal:this.options.terminal,forceCursor:this.options.forceCursor,});this.screen.title=this.options.title||'APP (C) Stefan Bosse';this.screen.cursor.color='red';this.layout=LAYOUT.from(this.screen);if(this.options.terminal.indexOf('xterm')!=-1&&this.options.forceCursor)
process.on('exit',function(){self.screen.program._write('\x1b[?12;25h')});}
UI.prototype.input=function(options){var self=this,width=options.width||(this.screen.width-(options.left*2||2));var obj=blessed.textbox({label:options.label||'My Input',value:options.value||'',bg:'default',barBg:'default',barFg:'blue',width:width,height:options.height||3,left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top,bottom:options.bottom,keys:true,mouse:true,inputOnFocus:true,focus:true,wrap:options.wrap,multiline:options.multiline,border:this.getStyle('input.border',{type:'line'}),style:{fg:options.fg||this.getStyle('input.fg','blue'),bg:options.bg||this.getStyle('input.bg',undefined),border:{fg:this.getStyle('input.border.fg','black'),bg:this.getStyle('input.border.bg',undefined),},label:this.getStyle('input.label',undefined),focus:{border:{fg:'red'}}}});obj.noshow=options.hidden;this.screen.append(obj);obj.on('focus',function(){if(!self.options.keyboard)
return self.options.terminal.indexOf('xterm')!=-1&&self.options.forceCursor?self.screen.program._write('\x1b[?12;25h'):0;if(!self._keyboard)
self._keyboard=self.keyboard({width:self.screen.width<60?'100%':'80%',height:self.layout.small?'100%':'90%',compact:self.layout.small});self._keyboard.setCallback(function(v){if(v)obj.setValue(v),obj.update();});self._keyboard.setValue(obj.getValue());self._keyboard.setLabel(obj.getLabel());self._keyboard.show();});return obj;}
UI.prototype.keyboard=function(options){var obj=blessed.keyboard({parent:options.parent||this.screen,border:'line',height:options.height||'half',width:options.width||'half',top:options.top||'center',left:options.left||'center',label:'Keyboard',hidden:options.hidden,compact:options.compact,okayButton:options.okayButton||'OK',cancelButton:options.cancelButton||(this.layout.small?'CAN':'Cancel'),delButton:'DEL',shiftButton:'>>',border:options.border||this.getStyle('keyboard.border',{}),style:{bg:options.bg||this.getStyle('keyboard.bg',undefined),label:options.label||this.getStyle('keyboard.label',undefined),}});this.screen.append(obj);return obj;}
UI.prototype.label=function(options){var obj=blessed.text({width:options.width||(options.content.length),left:(options.center?int(this.screen.width/2-options.content.length/2):options.left),right:options.right,top:options.top||0,height:options.height||1,focus:false,align:'center',content:options.content||'?',style:{bg:options.style?options.style.bg:this.getStyle('label.bg',undefined),fg:options.style?options.style.fg:this.getStyle('label.fg',undefined),bold:this.getStyle('label.bold',false)}});if(options.mutable)
obj.setValue=function(content){obj.setContent('');obj.position.left=(options.center?int(this.screen.width/2-content.length/2):options.left);obj.setContent(content);};obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.list=function(options){var obj=blessed.list({top:options.top,left:options.left,width:options.width||(this.screen.width-options.left*2),height:options.height||(this.screen.height-options.top-4),label:options.label||'Log',focus:true,mouse:true,keys:true,arrows:options.arrows,border:this.getStyle('list.border',{type:'line'}),style:{bg:options.bg||this.getStyle('list.bg',undefined),selected:options.selected||{fg:'white',bg:'red',bold:true},item:options.item||{bold:true},border:{fg:this.getStyle('list.border.fg','black')},label:this.getStyle('list.label',undefined),hover:{border:{fg:'red'}},focus:{border:{fg:'red'}}}});obj.noshow=options.hidden;obj.set=obj.update=function(data){var p,items=[];obj.clearItems();if(Comp.obj.isArray(data))items=data;else for(p in data){items.push(p);}
obj.setItems(items);obj.screen.render();}
this.screen.append(obj);return obj;}
UI.prototype.log=function(options){if(options.top==undefined)options.top=2;if(options.left==undefined&&options.right==undefined)options.left=1;var obj=blessed.log({top:options.top,left:options.left,right:options.right,width:options.width||(this.screen.width-options.left*2),height:options.height||(this.screen.height-options.top-4),label:options.label||'Log',mouse:true,keys:true,scrollback:options.scrollback||100,border:this.getStyle('log.border',{type:'line'}),scrollbar:{ch:' ',track:{bg:'yellow'},style:{fg:'cyan',inverse:true}},alwaysScroll:true,scrollOnInput:true,style:{fg:options.fg||this.getStyle('log.fg','white'),bg:options.bg||this.getStyle('log.bg','black'),label:this.getStyle('log.label',undefined),border:{fg:this.getStyle('log.border.fg','green'),bg:this.getStyle('log.border.bg',undefined),},focus:{border:{fg:'red'}}},arrows:options.arrows,});obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.postOptions=function(options,widget,wname){var self=this,attr;for(attr in options){switch(attr){case'on':switch(options.type){case'checkbox':if(options.on.click&&typeof options.on.click=='function')
widget.on('check',function(){options.on.click(wname,true)}),widget.on('uncheck',function(){options.on.click(wname,false)});if(options.on.onclick&&typeof options.on.onclick=='function')
widget.on('check',function(){options.on.onclick(wname,true)}),widget.on('uncheck',function(){options.on.onclick(wname,false)});if(options.on.check&&typeof options.on.check=='function')
widget.on('check',function(){options.on.check(wname,true)});if(options.on.uncheck&&typeof options.on.uncheck=='function')
widget.on('uncheck',function(){options.on.uncheck(wname,false)});if(options.on.selected&&typeof options.on.selected=='function')
widget.on('selected',function(data){options.on.uncheck(wname,data)});if(options.on.change&&typeof options.on.change=='function')
widget.on('change',function(data){options.on.change(wname,data)});break;}
break;case'click':case'onclick':switch(options.type){case'checkbox':if(typeof options[attr]=='function')
widget.on('check',function(){options[attr](wname,true)}),widget.on('uncheck',function(){options[attr](wname,false)})
break;case'list':if(typeof options[attr]=='function')
widget.on('selected',function(data){options[attr](wname,data.content,data)})
break;case'tree':if(typeof options[attr]=='function')
widget.on('selected',function(data){var _data=data,path=data.name;data=data.parent;while(data)
path=data.name+(data.name!='/'?'/':'')+path,data=data.parent;options[attr](wname,_data.name,path,_data)})
break;}
break;case'onchange':switch(options.type){case'input':if(typeof options[attr]=='function')
widget.on('change',function(data){var content=widget.getContent();options[attr](wname,content)})
break;}
break;}}}
UI.prototype.radiobutton=function(options){var obj=blessed.radiobutton({checked:options.value||false,left:options.left,right:options.right,top:options.top||0,group:options.group,mouse:true,inputOnFocus:true,height:1,text:options.text||'empty'});obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.start=function(main){var self=this;if(main==undefined)main=this.pages.main?'main':null;Object.keys(this.pages).forEach(function(page){if(typeof self.pages[page]!='object')return;if(Object.keys(self.pages[page]).length==0)return;self.pages.hide(page);if(!main)main=page;});if(main)this.pages.show(main);this.screen.render();this.screen.program.hideCursor(this.options.terminal.indexOf('xterm')!=-1&&this.options.forceCursor);}
UI.prototype.status=function(options){var self=this,width=options.width||(this.screen.width-(options.left*2||2));var obj=blessed.textbox({label:options.label||'My Input',value:options.value||'',bg:'default',barBg:'default',barFg:'blue',width:width,height:options.height||3,left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top,bottom:options.bottom,wrap:options.wrap,multiline:options.multiline,border:this.getStyle('input.border',{type:'line'}),style:{fg:options.fg||this.getStyle('input.fg','blue'),bg:options.bg||this.getStyle('input.bg',undefined),border:{fg:this.getStyle('input.border.fg','black'),bg:this.getStyle('input.border.bg',undefined),},label:this.getStyle('input.label',undefined),focus:{border:{fg:'red'}}}});obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.table=function(options){if(options.top==undefined)options.top=2;if(options.left==undefined&&options.right==undefined)options.left=1;var obj=blessed.table({top:options.top,left:options.left,right:options.right,width:options.width||(this.screen.width-options.left*2),height:options.height||(this.screen.height-options.top-4),label:options.label||'Table',data:options.data,border:this.getStyle('table.border',{type:'line'}),style:{fg:options.fg||this.getStyle('log.fg','white'),bg:options.bg||this.getStyle('log.bg','black'),label:this.getStyle('log.label',undefined),border:{fg:this.getStyle('log.border.fg','green'),bg:this.getStyle('log.border.bg',undefined),},header:options.header,cell:options.cell,focus:{border:{fg:'red'}}},});obj.noshow=options.hidden;this.screen.append(obj);return obj;}
UI.prototype.terminal=function(options){var self=this,width=options.width||(this.screen.width-(options.left*2||2));options.scrollable=true;if(options.scrollable&&!options.scrollbar){options.scrollbar={ch:' ',track:{bg:'yellow'},style:{fg:'cyan',inverse:true}};options.mouse=true;}
var obj=blessed.terminal({label:options.label||'My Text',value:options.value||'',bg:'default',barBg:'default',barFg:'blue',width:width,height:options.height||8,left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top||0,keys:true,vi:false,mouse:true,inputOnFocus:true,focus:true,wrap:options.wrap,multiline:true,scrollbar:options.scrollbar,scrollable:options.scrollable,prompt:options.prompt,border:this.getStyle('input.border',{type:'line'}),style:{fg:options.fg||this.getStyle('input.fg','blue'),bg:options.bg||this.getStyle('input.bg',undefined),border:{fg:this.getStyle('input.border.fg','black'),bg:this.getStyle('input.border.bg',undefined),},label:this.getStyle('input.label',undefined),focus:{border:{fg:'red'}}}});obj.noshow=options.hidden;this.screen.append(obj);obj.on('focus',function(){if(!self.options.keyboard)
return self.options.terminal.indexOf('xterm')!=-1&&self.options.forceCursor?self.screen.program._write('\x1b[?12;25h'):0;if(!self._keyboard)
self._keyboard=self.keyboard({width:self.screen.width<60?'100%':'80%',height:self.layout.small?'100%':'90%',compact:self.layout.small});self._keyboard.setCallback(function(v){if(v)obj.setValue(v),obj.update();});self._keyboard.setValue(obj.getValue());self._keyboard.setLabel(obj.getLabel());self._keyboard.show();});return obj;}
UI.prototype.text=function(options){var self=this,width=options.width||(this.screen.width-(options.left*2||2));if(options.scrollable&&!options.scrollbar){options.scrollbar={ch:' ',track:{bg:'yellow'},style:{fg:'cyan',inverse:true}};options.mouse=true;}
var obj=blessed.textarea({label:options.label||'My Text',value:options.value||'',bg:'default',barBg:'default',barFg:'blue',width:width,height:options.height||8,left:(options.center?int(this.screen.width/2-width/2):options.left),right:options.right,top:options.top||0,keys:true,vi:false,mouse:true,inputOnFocus:true,focus:true,wrap:options.wrap,multiline:true,scrollbar:options.scrollbar,scrollable:options.scrollable,border:this.getStyle('input.border',{type:'line'}),style:{fg:options.fg||this.getStyle('input.fg','blue'),bg:options.bg||this.getStyle('input.bg',undefined),border:{fg:this.getStyle('input.border.fg','black'),bg:this.getStyle('input.border.bg',undefined),},label:this.getStyle('input.label',undefined),focus:{border:{fg:'red'}}}});obj.noshow=options.hidden;this.screen.append(obj);obj.on('focus',function(){if(!self.options.keyboard)
return self.options.terminal.indexOf('xterm')!=-1&&self.options.forceCursor?self.screen.program._write('\x1b[?12;25h'):0;if(!self._keyboard)
self._keyboard=self.keyboard({width:self.screen.width<60?'100%':'80%',height:self.layout.small?'100%':'90%',compact:self.layout.small});self._keyboard.setCallback(function(v){if(v)obj.setValue(v),obj.update();});self._keyboard.setValue(obj.getValue());self._keyboard.setLabel(obj.getLabel());self._keyboard.show();});return obj;}
UI.prototype.tree=function(options){var obj=blessed.tree({top:options.top,left:options.left,width:options.width||(this.screen.width-options.left*2),height:options.height||(this.screen.height-options.top-4),label:options.label||'Log',focus:true,arrows:options.arrows,border:this.getStyle('tree.border',{type:'line'}),style:{bold:true,border:{fg:this.getStyle('tree.border.fg','black')},label:this.getStyle('tree.label',undefined),hover:{border:{fg:'red'}},focus:{border:{fg:'red'}}}});function makeleaf(element,reference,data){var content,children,name,funpat,isfun,p;children={};name=element.toString();funpat=/function[\s0-9a-zA-Z_$]*\(/i;isfun=Comp.obj.isFunction(element)||funpat.test(name);if(isfun){element=Comp.string.sub(name,0,name.indexOf('{'));}
if(!isfun||(isfun&&options.showfun)){children[element]={};content={children:children,reference:reference,data:data};}
return content;}
function maketree(element,reference){var content,children,p;children={};if(element&&(Comp.obj.isObject(element)||Comp.obj.isArray(element))){if(element._update!=undefined)element._update(element);if(element._value!=undefined)return makeleaf(element._value,_,element);for(p in element){if(p!='_update')
children[p]={};}
content={children:children,data:element}}else if(element!=undefined){return makeleaf(element,reference);}else{children[element]={};content={children:children};}
return content;};obj.noshow=options.hidden;obj.on('preselect',function(node){var content,children,element,data,name;if(node.name!='/'&&!node.extended){data=node.data;if(data!=none&&(Comp.obj.isObject(data)||Comp.obj.isArray(data))){node.children={};if(Comp.obj.isArray(data)&&Comp.array.empty(data)&&Comp.hashtbl.empty(data)){node.children={'[]':{}};}else{if(data._update!=undefined)data._update(data);if(data._value!=undefined)return node.children=makeleaf(data._value,_,data).children;for(var p in data){if(p!='_update'){element=data[p];content=maketree(element,data);if(content)node.children[p]=content;}}}}else if(data==none&&node.reference){node.children={};element=node.reference[node.name];name=element.toString();var funpat=/function[\s0-9a-zA-Z_$]*\(/i;var isfun=Comp.obj.isFunction(element)||funpat.test(name);if(isfun){element=Comp.string.sub(name,0,name.indexOf('{'));}
node.children[element]={};}}else if(node.name=='/'&&node.extended){if(node.data&&node.data._update){node.data._update()}}});obj.set=obj.update=function(data){obj.DATA={name:'/',extended:true,children:{},data:data,};for(var p in data){var element=data[p];var content=options.depth&&options.depth==1?{}:maketree(element,data);if(content)obj.DATA.children[p]=content;}
obj.setData(obj.DATA);};obj.DATA={name:'/',extended:true,children:{},};obj.setData(obj.DATA);this.screen.append(obj);return obj;}
UI.prototype.builder=function(styles,content,options){var self=this,pagename,page,pagedesc,entryname,entry,handler,o,childs,index;this.styles=Comp.obj.inherit(this.styles,styles);if(!content.pages)throw Error("UI.builder: empty or invalid pages template (missing pages)");if(!content.pages.main)throw Error("UI.builder: no main page");function addhandler(obj,event,handler,arg1,arg2){obj.on(event,function(){handler(arg1,arg2)})}
function addhandlerP(page,event,handler,arg1,arg2){self.pages.on(page,event,function(){handler(arg1,arg2)})}
for(pagename in content.pages){pagedesc=content.pages[pagename];this.pages[pagename]=page={};for(entryname in pagedesc){entry=pagedesc[entryname];switch(entryname){case'next':page.next=entry;continue;break;case'prev':page.prev=entry;continue;break;case'on':if(pagedesc.on.show)addhandlerP(pagename,'load',pagedesc.on.show,pagename);if(pagedesc.on.load)addhandlerP(pagename,'load',pagedesc.on.load,pagename);continue;break;case'onclick':continue;break;}
switch(entry.type){case'label':page[entryname]=this.label(this.filterOptions(entry,entryname));break;case'button':page[entryname]=this.button(this.filterOptions(entry,entryname));break;case'input':page[entryname]=this.input(this.filterOptions(entry,entryname));this.postOptions(entry,page[entryname],entryname);break;case'info':page[entryname]=this.info(this.filterOptions(entry,entryname));break;case'tree':page[entryname]=this.tree(this.filterOptions(entry,entryname));this.postOptions(entry,page[entryname],entryname);break;case'list':page[entryname]=this.list(this.filterOptions(entry,entryname));this.postOptions(entry,page[entryname],entryname);break;case'checkbox':page[entryname]=this.checkbox(this.filterOptions(entry,entryname));this.postOptions(entry,page[entryname],entryname);break;case'radiobutton':break;case'log':page[entryname]=this.log(this.filterOptions(entry,entryname));this.postOptions(entry,page[entryname],entryname);break;case'group':childs={};handler=undefined;for(o in entry){switch(o){case'type':break;case'onclick':handler=entry[o];break;default:if(entry[o].type=='radiobutton')childs[o]=entry[o];}}
for(o in childs){options=this.filterOptions(childs[o],entryname);options.group=entryname;page[entryname+'.'+o]=this.radiobutton(options);if(handler){if(childs[o].index!=undefined)index=childs[o].index;else index=childs[o].text;addhandler(page[entryname+'.'+o],'check',handler,entryname,index);}}
break;default:throw Error("UI.builder: invalid or unsupported widget type "+entry.type+" in "+entryname);}}}
if(content.static){for(entryname in content.static){entry=content.static[entryname];switch(entry.type){case'info':this.static[entryname]=this.info(this.filterOptions(entry,entryname));break;}}}
if(content.on&&content.on.keypress&&Comp.obj.isArray(content.on.keypress)){content.on.keypress.forEach(function(entry){if(typeof entry.key=='string')
self.screen.key([entry.key],entry.handler);else if(entry.key&&Comp.obj.isArray(entry.key))
self.screen.key(entry.key,entry.handler);});}
for(page in this.pages)this.pages.hide(page);this.pages.show('main');}
module.exports={options:options,LAYOUT:LAYOUT,UI:UI}};BundleModuleCode['term/blessed']=function(module,exports){function blessed(){return blessed.program.apply(null,arguments);}
blessed.program=blessed.Program=Require('term/program');blessed.tput=blessed.Tput=Require('term/tput');blessed.widget=Require('term/widget');blessed.colors=Require('term/colors');blessed.unicode=Require('term/unicode');blessed.helpers=Require('term/helpers');blessed.helpers.sprintf=blessed.tput.sprintf;blessed.helpers.tryRead=blessed.tput.tryRead;blessed.helpers.merge(blessed,blessed.helpers);blessed.helpers.merge(blessed,blessed.widget);module.exports=blessed;};BundleModuleCode['term/program']=function(module,exports){var options={version:'1.9.3'}
var Comp=Require('com/compat');var EventEmitter=Require('events').EventEmitter,StringDecoder=Require('string_decoder').StringDecoder,cp=Require('child_process'),util=Require('util'),fs=Require('fs');var Tput=Require('term/tput'),colors=Require('term/colors'),slice=Array.prototype.slice;var nextTick=global.setImmediate||process.nextTick.bind(process);function Program(options){var self=this;if(!instanceOf(this,Program)){return new Program(options);}
Program.bind(this);EventEmitter.call(this);if(!options){options={input:arguments[0],output:arguments[1]};}
this.options=options;this.input=options.input||process.stdin;this.output=options.output||process.stdout;options.log=options.log||options.dump;if(options.log){this._logger=fs.createWriteStream(options.log);if(options.dump)this.setupDump();}
this.zero=options.zero!==false;this.useBuffer=options.buffer;this.x=0;this.y=0;this.savedX=0;this.savedY=0;this.cols=this.output.columns||80;this.rows=this.output.rows||20;console.log('Terminal: '+this.cols+' x '+this.rows);this.scrollTop=0;this.scrollBottom=this.rows-1;this._terminal=options.terminal||options.term||process.env.TERM||(process.platform==='win32'?'windows-ansi':'xterm');this._terminal=this._terminal.toLowerCase();this.isOSXTerm=process.env.TERM_PROGRAM==='Apple_Terminal';this.isiTerm2=process.env.TERM_PROGRAM==='iTerm.app'||!!process.env.ITERM_SESSION_ID;this.isXFCE=/xfce/i.test(process.env.COLORTERM);this.isTerminator=!!process.env.TERMINATOR_UUID;this.isLXDE=false;this.isVTE=!!process.env.VTE_VERSION||this.isXFCE||this.isTerminator||this.isLXDE;this.isRxvt=/rxvt/i.test(process.env.COLORTERM);this.isXterm=false;this.tmux=!!process.env.TMUX;this.tmuxVersion=(function(){if(!self.tmux)return 2;try{var version=cp.execFileSync('tmux',['-V'],{encoding:'utf8'});return+/^tmux ([\d.]+)/i.exec(version.trim().split('\n')[0])[1];}catch(e){return 2;}})();this._buf='';this._flush=this.flush.bind(this);if(options.tput!==false){this.setupTput();}
this.listen();if(process.platform=='win32'){process.winmouse.init(function(x,y,button,action){var key={name:'mouse',ctrl:false,meta:false,shift:false,action:action,x:x,y:y};self.emit('mouse',key);});}}
Program.global=null;Program.total=0;Program.instances=[];Program.bind=function(program){if(!Program.global){Program.global=program;}
if(!~Program.instances.indexOf(program)){Program.instances.push(program);program.index=Program.total;Program.total++;}
if(Program._bound)return;Program._bound=true;unshiftEvent(process,'exit',Program._exitHandler=function(){Program.instances.forEach(function(program){if(program._originalTitle){program.setTitle(program._originalTitle);}
program.flush();program._exiting=true;});});};inheritPrototype(Program,EventEmitter);Program.prototype.type='program';Program.prototype.log=function(){return this._log('LOG',util.format.apply(util,arguments));};Program.prototype.debug=function(){if(!this.options.debug)return;return this._log('DEBUG',util.format.apply(util,arguments));};Program.prototype._log=function(pre,msg){if(!this._logger)return;return this._logger.write(pre+': '+msg+'\n-\n');};Program.prototype.setupDump=function(){var self=this,write=this.output.write,decoder=new StringDecoder('utf8');function stringify(data){return caret(data.replace(/\r/g,'\\r').replace(/\n/g,'\\n').replace(/\t/g,'\\t')).replace(/[^ -~]/g,function(ch){if(ch.charCodeAt(0)>0xff)return ch;ch=ch.charCodeAt(0).toString(16);if(ch.length>2){if(ch.length<4)ch='0'+ch;return'\\u'+ch;}
if(ch.length<2)ch='0'+ch;return'\\x'+ch;});}
function caret(data){return data.replace(/[\0\x80\x1b-\x1f\x7f\x01-\x1a]/g,function(ch){switch(ch){case'\0':case'\200':ch='@';break;case'\x1b':ch='[';break;case'\x1c':ch='\\';break;case'\x1d':ch=']';break;case'\x1e':ch='^';break;case'\x1f':ch='_';break;case'\x7f':ch='?';break;default:ch=ch.charCodeAt(0);if(ch>=1&&ch<=26){ch=String.fromCharCode(ch+64);}else{return String.fromCharCode(ch);}
break;}
return'^'+ch;});}
this.input.on('data',function(data){self._log('IN',stringify(decoder.write(data)));});this.output.write=function(data){self._log('OUT',stringify(data));return write.apply(this,arguments);};};Program.prototype.setupTput=function(){if(this._tputSetup)return;this._tputSetup=true;var self=this,options=this.options,write=this._write.bind(this);var tput=this.tput=new Tput({terminal:this.terminal,padding:options.padding,extended:options.extended,printf:options.printf,termcap:options.termcap,forceUnicode:options.forceUnicode});if(tput.error){nextTick(function(){self.emit('warning',tput.error.message);});}
if(tput.padding){nextTick(function(){self.emit('warning','Terminfo padding has been enabled.');});}
this.put=function(){var args=slice.call(arguments),cap=args.shift();if(tput[cap]){return this._write(tput[cap].apply(tput,args));}};Object.keys(tput).forEach(function(key){if(self[key]==null){self[key]=tput[key];}
if(typeof tput[key]!=='function'){self.put[key]=tput[key];return;}
if(tput.padding){self.put[key]=function(){return tput._print(tput[key].apply(tput,arguments),write);};}else{self.put[key]=function(){return self._write(tput[key].apply(tput,arguments));};}});};Object.defineProperty(Program.prototype,'terminal',{get:function(){return this._terminal;},set:function(terminal){this.setTerminal(terminal);return this.terminal;}});Program.prototype.setTerminal=function(terminal){this._terminal=terminal.toLowerCase();delete this._tputSetup;this.setupTput();};Program.prototype.has=function(name){return this.tput?this.tput.has(name):false;};Program.prototype.term=function(is){return this.terminal.indexOf(is)===0;};Program.prototype.listen=function(){var self=this;if(!this.input._blessedInput){this.input._blessedInput=1;this._listenInput();}else{this.input._blessedInput++;}
this.on('newListener',this._newHandler=function fn(type){if(type==='keypress'||type==='mouse'){self.removeListener('newListener',fn);if(self.input.setRawMode&&!self.input.isRaw){self.input.setRawMode(true);self.input.resume();}}});this.on('newListener',function fn(type){if(type==='mouse'){self.removeListener('newListener',fn);self.bindMouse();}});if(!this.output._blessedOutput){this.output._blessedOutput=1;this._listenOutput();}else{this.output._blessedOutput++;}};var _keys=Require('term/keys');Program.prototype._listenInput=function(){var keys=_keys,self=this;this.input.on('keypress',this.input._keypressHandler=function(ch,key){key=key||{ch:ch};if(key.name==='undefined'&&(key.code==='[M'||key.code==='[I'||key.code==='[O')){return;}
if(key.name==='undefined'){return;}
if(key.name==='enter'&&key.sequence==='\n'){key.name='linefeed';}
if(key.name==='return'&&key.sequence==='\r'){self.input.emit('keypress',ch,merge({},key,{name:'enter'}));}
var name=(key.ctrl?'C-':'')
+(key.meta?'M-':'')
+(key.shift&&key.name?'S-':'')
+(key.name||ch);key.full=name;Program.instances.forEach(function(program){if(program.input!==self.input)return;program.emit('keypress',ch,key);program.emit('key '+name,ch,key);});});this.input.on('data',this.input._dataHandler=function(data){Program.instances.forEach(function(program){if(program.input!==self.input)return;program.emit('data',data);});});keys.emitKeypressEvents(this.input);};Program.prototype._listenOutput=function(){var self=this;if(!this.output.isTTY){nextTick(function(){self.emit('warning','Output is not a TTY');});}
function resize(){Program.instances.forEach(function(program){if(program.output!==self.output)return;program.cols=program.output.columns;program.rows=program.output.rows;program.emit('resize');});}
this.output.on('resize',this.output._resizeHandler=function(){Program.instances.forEach(function(program){if(program.output!==self.output)return;if(!program.options.resizeTimeout){return resize();}
if(program._resizeTimer){clearTimeout(program._resizeTimer);delete program._resizeTimer;}
var time=typeof program.options.resizeTimeout==='number'?program.options.resizeTimeout:300;program._resizeTimer=setTimeout(resize,time);});});};Program.prototype.destroy=function(){var index=Program.instances.indexOf(this);if(~index){Program.instances.splice(index,1);Program.total--;this.flush();this._exiting=true;Program.global=Program.instances[0];if(Program.total===0){Program.global=null;process.removeListener('exit',Program._exitHandler);delete Program._exitHandler;delete Program._bound;}
this.input._blessedInput--;this.output._blessedOutput--;if(this.input._blessedInput===0){this.input.removeListener('keypress',this.input._keypressHandler);this.input.removeListener('data',this.input._dataHandler);delete this.input._keypressHandler;delete this.input._dataHandler;if(this.input.setRawMode){if(this.input.isRaw){this.input.setRawMode(false);}
if(!this.input.destroyed){this.input.pause();}}}
if(this.output._blessedOutput===0){this.output.removeListener('resize',this.output._resizeHandler);delete this.output._resizeHandler;}
this.removeListener('newListener',this._newHandler);delete this._newHandler;this.destroyed=true;this.emit('destroy');}};Program.prototype.key=function(key,listener){if(typeof key==='string')key=key.split(/\s*,\s*/);key.forEach(function(key){return this.on('key '+key,listener);},this);};Program.prototype.onceKey=function(key,listener){if(typeof key==='string')key=key.split(/\s*,\s*/);key.forEach(function(key){return this.once('key '+key,listener);},this);};Program.prototype.unkey=Program.prototype.removeKey=function(key,listener){if(typeof key==='string')key=key.split(/\s*,\s*/);key.forEach(function(key){return this.removeListener('key '+key,listener);},this);};Program.prototype.bindMouse=function(){if(this._boundMouse)return;this._boundMouse=true;var decoder=new StringDecoder('utf8'),self=this;this.on('data',function(data){var text,seq=[data],_data,i,n=0,m=0;if(data.length&&data.indexOf(0x1b,1)>0){seq=[];while(n<data.length){m=data.indexOf(0x1b,m+1);if(m==-1)m=data.length;seq.push(data.slice(n,m));n=m;}}
for(i in seq){_data=seq[i];text=decoder.write(_data);if(!text)continue;self._bindMouse(text,_data);}});};Program.prototype._bindMouse=function(s,buf){var self=this,key,parts,b,x,y,mod,params,down,page,button;key={name:undefined,ctrl:false,meta:false,shift:false};if(Buffer.isBuffer(s)){if(s[0]>127&&s[1]===undefined){s[0]-=128;s='\x1b'+s.toString('utf-8');}else{s=s.toString('utf-8');}}
var bx=s.charCodeAt(4);var by=s.charCodeAt(5);if(buf[0]===0x1b&&buf[1]===0x5b&&buf[2]===0x4d&&(this.isVTE||bx>=65533||by>=65533||(bx>0x00&&bx<0x20)||(by>0x00&&by<0x20)||(buf[4]>223&&buf[4]<248&&buf.length===6)||(buf[5]>223&&buf[5]<248&&buf.length===6))){b=buf[3];x=buf[4];y=buf[5];if(x<0x20)x+=0xff;if(y<0x20)y+=0xff;s='\x1b[M'
+String.fromCharCode(b)
+String.fromCharCode(x)
+String.fromCharCode(y);}
if(parts=/^\x1b\[M([\x00\u0020-\ufffe]{3})/.exec(s)){b=parts[1].charCodeAt(0);x=parts[1].charCodeAt(1);y=parts[1].charCodeAt(2);key.name='mouse';key.type='X10';key.raw=[b,x,y,parts[0]];key.buf=buf;key.x=x-32;key.y=y-32;if(this.zero)key.x--,key.y--;if(x===0)key.x=255;if(y===0)key.y=255;mod=b>>2;key.shift=!!(mod&1);key.meta=!!((mod>>1)&1);key.ctrl=!!((mod>>2)&1);b-=32;if((b>>6)&1){key.action=b&1?'wheeldown':'wheelup';key.button='middle';}else if(b===3&&this._lastButton){key.action='mouseup';key.button=this._lastButton;delete this._lastButton;}else if((b&3)<3){key.action='mousedown';button=b&3;key.button=button===0?'left':button===1?'middle':button===2?'right':'unknown';this._lastButton=key.button;}
if(b===35||b===39||b===51||b===43||(this.isVTE&&(b===32||b===36||b===48||b===40))){delete key.button;key.action='mousemove';}
self.emit('mouse',key);return;}
if(parts=/^\x1b\[(\d+;\d+;\d+)M/.exec(s)){params=parts[1].split(';');b=+params[0];x=+params[1];y=+params[2];key.name='mouse';key.type='urxvt';key.raw=[b,x,y,parts[0]];key.buf=buf;key.x=x;key.y=y;if(this.zero)key.x--,key.y--;mod=b>>2;key.shift=!!(mod&1);key.meta=!!((mod>>1)&1);key.ctrl=!!((mod>>2)&1);if(b===128||b===129){b=67;}
b-=32;if((b>>6)&1){key.action=b&1?'wheeldown':'wheelup';key.button='middle';}else if(b===3){key.action='mouseup';key.button=this._lastButton||'unknown';delete this._lastButton;}else{key.action='mousedown';button=b&3;key.button=button===0?'left':button===1?'middle':button===2?'right':'unknown';this._lastButton=key.button;}
if(b===35||b===39||b===51||b===43||(this.isVTE&&(b===32||b===36||b===48||b===40))){delete key.button;key.action='mousemove';}
self.emit('mouse',key);return;}
if(parts=/^\x1b\[<(\d+;\d+;\d+)([mM])/.exec(s)){down=parts[2]==='M';params=parts[1].split(';');b=+params[0];x=+params[1];y=+params[2];key.name='mouse';key.type='sgr';key.raw=[b,x,y,parts[0]];key.buf=buf;key.x=x;key.y=y;if(this.zero)key.x--,key.y--;mod=b>>2;key.shift=!!(mod&1);key.meta=!!((mod>>1)&1);key.ctrl=!!((mod>>2)&1);if((b>>6)&1){key.action=b&1?'wheeldown':'wheelup';key.button='middle';}else{key.action=down?'mousedown':'mouseup';button=b&3;key.button=button===0?'left':button===1?'middle':button===2?'right':'unknown';}
if(b===35||b===39||b===51||b===43||(this.isVTE&&(b===32||b===36||b===48||b===40))){delete key.button;key.action='mousemove';}
self.emit('mouse',key);return;}
if(parts=/^\x1b\[<(\d+;\d+;\d+;\d+)&w/.exec(s)){params=parts[1].split(';');b=+params[0];x=+params[1];y=+params[2];page=+params[3];key.name='mouse';key.type='dec';key.raw=[b,x,y,parts[0]];key.buf=buf;key.x=x;key.y=y;key.page=page;if(this.zero)key.x--,key.y--;key.action=b===3?'mouseup':'mousedown';key.button=b===2?'left':b===4?'middle':b===6?'right':'unknown';self.emit('mouse',key);return;}
if(parts=/^\x1b\[24([0135])~\[(\d+),(\d+)\]\r/.exec(s)){b=+parts[1];x=+parts[2];y=+parts[3];key.name='mouse';key.type='vt300';key.raw=[b,x,y,parts[0]];key.buf=buf;key.x=x;key.y=y;if(this.zero)key.x--,key.y--;key.action='mousedown';key.button=b===1?'left':b===2?'middle':b===5?'right':'unknown';self.emit('mouse',key);return;}
if(parts=/^\x1b\[(O|I)/.exec(s)){key.action=parts[1]==='I'?'focus':'blur';self.emit('mouse',key);self.emit(key.action);return;}};Program.prototype.enableGpm=function(){var self=this;var gpmclient=Require('term/gpmclient');if(this.gpm)return;this.gpm=gpmclient();this.gpm.on('btndown',function(btn,modifier,x,y){x--,y--;var key={name:'mouse',type:'GPM',action:'mousedown',button:self.gpm.ButtonName(btn),raw:[btn,modifier,x,y],x:x,y:y,shift:self.gpm.hasShiftKey(modifier),meta:self.gpm.hasMetaKey(modifier),ctrl:self.gpm.hasCtrlKey(modifier)};self.emit('mouse',key);});this.gpm.on('btnup',function(btn,modifier,x,y){x--,y--;var key={name:'mouse',type:'GPM',action:'mouseup',button:self.gpm.ButtonName(btn),raw:[btn,modifier,x,y],x:x,y:y,shift:self.gpm.hasShiftKey(modifier),meta:self.gpm.hasMetaKey(modifier),ctrl:self.gpm.hasCtrlKey(modifier)};self.emit('mouse',key);});this.gpm.on('move',function(btn,modifier,x,y){x--,y--;var key={name:'mouse',type:'GPM',action:'mousemove',button:self.gpm.ButtonName(btn),raw:[btn,modifier,x,y],x:x,y:y,shift:self.gpm.hasShiftKey(modifier),meta:self.gpm.hasMetaKey(modifier),ctrl:self.gpm.hasCtrlKey(modifier)};self.emit('mouse',key);});this.gpm.on('drag',function(btn,modifier,x,y){x--,y--;var key={name:'mouse',type:'GPM',action:'mousemove',button:self.gpm.ButtonName(btn),raw:[btn,modifier,x,y],x:x,y:y,shift:self.gpm.hasShiftKey(modifier),meta:self.gpm.hasMetaKey(modifier),ctrl:self.gpm.hasCtrlKey(modifier)};self.emit('mouse',key);});this.gpm.on('mousewheel',function(btn,modifier,x,y,dx,dy){var key={name:'mouse',type:'GPM',action:dy>0?'wheelup':'wheeldown',button:self.gpm.ButtonName(btn),raw:[btn,modifier,x,y,dx,dy],x:x,y:y,shift:self.gpm.hasShiftKey(modifier),meta:self.gpm.hasMetaKey(modifier),ctrl:self.gpm.hasCtrlKey(modifier)};self.emit('mouse',key);});};Program.prototype.disableGpm=function(){if(this.gpm){this.gpm.stop();delete this.gpm;}};Program.prototype.bindResponse=function(){if(this._boundResponse)return;this._boundResponse=true;var decoder=new StringDecoder('utf8'),self=this;this.on('data',function(data){data=decoder.write(data);if(!data)return;self._bindResponse(data);});};Program.prototype._bindResponse=function(s){var out={},parts;if(Buffer.isBuffer(s)){if(s[0]>127&&s[1]===undefined){s[0]-=128;s='\x1b'+s.toString('utf-8');}else{s=s.toString('utf-8');}}
if(parts=/^\x1b\[(\?|>)(\d*(?:;\d*)*)c/.exec(s)){parts=parts[2].split(';').map(function(ch){return+ch||0;});out.event='device-attributes';out.code='DA';if(parts[1]==='?'){out.type='primary-attribute';if(parts[0]===1&&parts[2]===2){out.term='vt100';out.advancedVideo=true;}else if(parts[0]===1&&parts[2]===0){out.term='vt101';}else if(parts[0]===6){out.term='vt102';}else if(parts[0]===60&&parts[1]===1&&parts[2]===2&&parts[3]===6&&parts[4]===8&&parts[5]===9&&parts[6]===15){out.term='vt220';}else{parts.forEach(function(attr){switch(attr){case 1:out.cols132=true;break;case 2:out.printer=true;break;case 6:out.selectiveErase=true;break;case 8:out.userDefinedKeys=true;break;case 9:out.nationalReplacementCharsets=true;break;case 15:out.technicalCharacters=true;break;case 18:out.userWindows=true;break;case 21:out.horizontalScrolling=true;break;case 22:out.ansiColor=true;break;case 29:out.ansiTextLocator=true;break;}});}}else{out.type='secondary-attribute';switch(parts[0]){case 0:out.term='vt100';break;case 1:out.term='vt220';break;case 2:out.term='vt240';break;case 18:out.term='vt330';break;case 19:out.term='vt340';break;case 24:out.term='vt320';break;case 41:out.term='vt420';break;case 61:out.term='vt510';break;case 64:out.term='vt520';break;case 65:out.term='vt525';break;}
out.firmwareVersion=parts[1];out.romCartridgeRegistrationNumber=parts[2];}
out.deviceAttributes=out;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts=/^\x1b\[(\?)?(\d+)(?:;(\d+);(\d+);(\d+))?n/.exec(s)){out.event='device-status';out.code='DSR';if(!parts[1]&&parts[2]==='0'&&!parts[3]){out.type='device-status';out.status='OK';out.deviceStatus=out.status;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]&&(parts[2]==='10'||parts[2]==='11')&&!parts[3]){out.type='printer-status';out.status=parts[2]==='10'?'ready':'not ready';out.printerStatus=out.status;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]&&(parts[2]==='20'||parts[2]==='21')&&!parts[3]){out.type='udk-status';out.status=parts[2]==='20'?'unlocked':'locked';out.UDKStatus=out.status;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]&&parts[2]==='27'&&parts[3]==='1'&&parts[4]==='0'&&parts[5]==='0'){out.type='keyboard-status';out.status='OK';out.keyboardStatus=out.status;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]&&(parts[2]==='53'||parts[2]==='50')&&!parts[3]){out.type='locator-status';out.status=parts[2]==='53'?'available':'unavailable';out.locator=out.status;this.emit('response',out);this.emit('response '+out.event,out);return;}
out.type='error';out.text='Unhandled: '+JSON.stringify(parts);out.error=out.text;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts=/^\x1b\[(\?)?(\d+);(\d+)R/.exec(s)){out.event='device-status';out.code='DSR';out.type='cursor-status';out.status={x:+parts[3],y:+parts[2],page:!parts[1]?undefined:0};out.x=out.status.x;out.y=out.status.y;out.page=out.status.page;out.cursor=out.status;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts=/^\x1b\[(\d+)(?:;(\d+);(\d+))?t/.exec(s)){out.event='window-manipulation';out.code='';if((parts[1]==='1'||parts[1]==='2')&&!parts[2]){out.type='window-state';out.state=parts[1]==='1'?'non-iconified':'iconified';out.windowState=out.state;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]==='3'&&parts[2]){out.type='window-position';out.position={x:+parts[2],y:+parts[3]};out.x=out.position.x;out.y=out.position.y;out.windowPosition=out.position;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]==='4'&&parts[2]){out.type='window-size-pixels';out.size={height:+parts[2],width:+parts[3]};out.height=out.size.height;out.width=out.size.width;out.windowSizePixels=out.size;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]==='8'&&parts[2]){out.type='textarea-size';out.size={height:+parts[2],width:+parts[3]};out.height=out.size.height;out.width=out.size.width;out.textAreaSizeCharacters=out.size;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]==='9'&&parts[2]){out.type='screen-size';out.size={height:+parts[2],width:+parts[3]};out.height=out.size.height;out.width=out.size.width;out.screenSizeCharacters=out.size;this.emit('response',out);this.emit('response '+out.event,out);return;}
out.type='error';out.text='Unhandled: '+JSON.stringify(parts);out.error=out.text;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts=/^\x1b\](l|L)([^\x07\x1b]*)$/.exec(s)){parts[2]='rxvt';s='\x1b]'+parts[1]+parts[2]+'\x1b\\';}
if(parts=/^\x1b\](l|L)([^\x07\x1b]*)(?:\x07|\x1b\\)/.exec(s)){out.event='window-manipulation';out.code='';if(parts[1]==='L'){out.type='window-icon-label';out.text=parts[2];out.windowIconLabel=out.text;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts[1]==='l'){out.type='window-title';out.text=parts[2];out.windowTitle=out.text;this.emit('response',out);this.emit('response '+out.event,out);return;}
out.type='error';out.text='Unhandled: '+JSON.stringify(parts);out.error=out.text;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts=/^\x1b\[(\d+(?:;\d+){4})&w/.exec(s)){parts=parts[1].split(';').map(function(ch){return+ch;});out.event='locator-position';out.code='DECRQLP';switch(parts[0]){case 0:out.status='locator-unavailable';break;case 1:out.status='request';break;case 2:out.status='left-button-down';break;case 3:out.status='left-button-up';break;case 4:out.status='middle-button-down';break;case 5:out.status='middle-button-up';break;case 6:out.status='right-button-down';break;case 7:out.status='right-button-up';break;case 8:out.status='m4-button-down';break;case 9:out.status='m4-button-up';break;case 10:out.status='locator-outside';break;}
out.mask=parts[1];out.row=parts[2];out.col=parts[3];out.page=parts[4];out.locatorPosition=out;this.emit('response',out);this.emit('response '+out.event,out);return;}
if(parts=/^\x1b\](\d+);([^\x07\x1b]+)(?:\x07|\x1b\\)/.exec(s)){out.event='text-params';out.code='Set Text Parameters';out.ps=+s[1];out.pt=s[2];this.emit('response',out);this.emit('response '+out.event,out);}};Program.prototype.response=function(name,text,callback,noBypass){var self=this;if(arguments.length===2){callback=text;text=name;name=null;}
if(!callback){callback=function(){};}
this.bindResponse();name=name?'response '+name:'response';var onresponse;this.once(name,onresponse=function(event){if(timeout)clearTimeout(timeout);if(event.type==='error'){return callback(new Error(event.event+': '+event.text));}
return callback(null,event);});var timeout=setTimeout(function(){self.removeListener(name,onresponse);return callback(new Error('Timeout.'));},2000);return noBypass?this._write(text):this._twrite(text);};Program.prototype._owrite=Program.prototype.write=function(text){if(!this.output.writable)return;return this.output.write(text);};Program.prototype._buffer=function(text){if(this._exiting){this.flush();this._owrite(text);return;}
if(this._buf){this._buf+=text;return;}
this._buf=text;nextTick(this._flush);return true;};Program.prototype.flush=function(){if(!this._buf)return;this._owrite(this._buf);this._buf='';};Program.prototype._write=function(text){if(this.ret)return text;if(this.useBuffer){return this._buffer(text);}
return this._owrite(text);};Program.prototype._twrite=function(data){var self=this,iterations=0,timer;if(this.tmux){data=data.replace(/\x1b\\/g,'\x07');data='\x1bPtmux;\x1b'+data+'\x1b\\';if(this.output.bytesWritten===0){timer=setInterval(function(){if(self.output.bytesWritten>0||++iterations===50){clearInterval(timer);self.flush();self._owrite(data);}},100);return true;}
this.flush();return this._owrite(data);}
return this._write(data);};Program.prototype.echo=Program.prototype.print=function(text,attr){return attr?this._write(this.text(text,attr)):this._write(text);};Program.prototype._ncoords=function(){if(this.x<0)this.x=0;else if(this.x>=this.cols)this.x=this.cols-1;if(this.y<0)this.y=0;else if(this.y>=this.rows)this.y=this.rows-1;};Program.prototype.setx=function(x){return this.cursorCharAbsolute(x);};Program.prototype.sety=function(y){return this.linePosAbsolute(y);};Program.prototype.move=function(x,y){return this.cursorPos(y,x);};Program.prototype.omove=function(x,y){if(!this.zero){x=(x||1)-1;y=(y||1)-1;}else{x=x||0;y=y||0;}
if(y===this.y&&x===this.x){return;}
if(y===this.y){if(x>this.x){this.cuf(x-this.x);}else if(x<this.x){this.cub(this.x-x);}}else if(x===this.x){if(y>this.y){this.cud(y-this.y);}else if(y<this.y){this.cuu(this.y-y);}}else{if(!this.zero)x++,y++;this.cup(y,x);}};Program.prototype.rsetx=function(x){if(!x)return;return x>0?this.forward(x):this.back(-x);};Program.prototype.rsety=function(y){if(!y)return;return y>0?this.up(y):this.down(-y);};Program.prototype.rmove=function(x,y){this.rsetx(x);this.rsety(y);};Program.prototype.simpleInsert=function(ch,i,attr){return this._write(this.repeat(ch,i),attr);};Program.prototype.repeat=function(ch,i){if(!i||i<0)i=0;return Array(i+1).join(ch);};Object.defineProperty(Program.prototype,'title',{get:function(){return this._title;},set:function(title){this.setTitle(title);return this._title;}});Program.prototype.copyToClipboard=function(text){if(this.isiTerm2){this._twrite('\x1b]50;CopyToCliboard='+text+'\x07');return true;}
return false;};Program.prototype.cursorShape=function(shape,blink){if(this.isiTerm2){switch(shape){case'block':if(!blink){this._twrite('\x1b]50;CursorShape=0;BlinkingCursorEnabled=0\x07');}else{this._twrite('\x1b]50;CursorShape=0;BlinkingCursorEnabled=1\x07');}
break;case'underline':if(!blink){}else{}
break;case'line':if(!blink){this._twrite('\x1b]50;CursorShape=1;BlinkingCursorEnabled=0\x07');}else{this._twrite('\x1b]50;CursorShape=1;BlinkingCursorEnabled=1\x07');}
break;}
return true;}else if(this.term('xterm')||this.term('xterm-color')||this.term('screen')){switch(shape){case'block':if(!blink){this._twrite('\x1b[0 q');}else{this._twrite('\x1b[1 q');}
break;case'underline':if(!blink){this._twrite('\x1b[2 q');}else{this._twrite('\x1b[3 q');}
break;case'line':if(!blink){this._twrite('\x1b[4 q');}else{this._twrite('\x1b[5 q');}
break;}
return true;}
return false;};Program.prototype.cursorColor=function(color){if(this.term('xterm')||this.term('rxvt')||this.term('screen')){this._twrite('\x1b]12;'+color+'\x07');return true;}
return false;};Program.prototype.cursorReset=Program.prototype.resetCursor=function(){if(this.term('xterm')||this.term('xterm-color')||this.term('rxvt')||this.term('screen')){this._twrite('\x1b[0 q');this._twrite('\x1b]112\x07');this._twrite('\x1b]12;white\x07');return true;}
return false;};Program.prototype.getTextParams=function(param,callback){return this.response('text-params','\x1b]'+param+';?\x07',function(err,data){if(err)return callback(err);return callback(null,data.pt);});};Program.prototype.getCursorColor=function(callback){return this.getTextParams(12,callback);};Program.prototype.nul=function(){return this._write('\200');};Program.prototype.bel=Program.prototype.bell=function(){if(this.has('bel'))return this.put.bel();return this._write('\x07');};Program.prototype.vtab=function(){this.y++;this._ncoords();return this._write('\x0b');};Program.prototype.ff=Program.prototype.form=function(){if(this.has('ff'))return this.put.ff();return this._write('\x0c');};Program.prototype.kbs=Program.prototype.backspace=function(){this.x--;this._ncoords();if(this.has('kbs'))return this.put.kbs();return this._write('\x08');};Program.prototype.ht=Program.prototype.tab=function(){this.x+=8;this._ncoords();if(this.has('ht'))return this.put.ht();return this._write('\t');};Program.prototype.shiftOut=function(){return this._write('\x0e');};Program.prototype.shiftIn=function(){return this._write('\x0f');};Program.prototype.cr=Program.prototype.return=function(){this.x=0;if(this.has('cr'))return this.put.cr();return this._write('\r');};Program.prototype.nel=Program.prototype.newline=Program.prototype.feed=function(){if(this.tput&&this.tput.bools.eat_newline_glitch&&this.x>=this.cols){return;}
this.x=0;this.y++;this._ncoords();if(this.has('nel'))return this.put.nel();return this._write('\n');};Program.prototype.ind=Program.prototype.index=function(){this.y++;this._ncoords();if(this.tput)return this.put.ind();return this._write('\x1bD');};Program.prototype.ri=Program.prototype.reverse=Program.prototype.reverseIndex=function(){this.y--;this._ncoords();if(this.tput)return this.put.ri();return this._write('\x1bM');};Program.prototype.nextLine=function(){this.y++;this.x=0;this._ncoords();if(this.has('nel'))return this.put.nel();return this._write('\x1bE');};Program.prototype.reset=function(){this.x=this.y=0;if(this.has('rs1')||this.has('ris')){return this.has('rs1')?this.put.rs1():this.put.ris();}
return this._write('\x1bc');};Program.prototype.tabSet=function(){if(this.tput)return this.put.hts();return this._write('\x1bH');};Program.prototype.sc=Program.prototype.saveCursor=function(key){if(key)return this.lsaveCursor(key);this.savedX=this.x||0;this.savedY=this.y||0;if(this.tput)return this.put.sc();return this._write('\x1b7');};Program.prototype.rc=Program.prototype.restoreCursor=function(key,hide){if(key)return this.lrestoreCursor(key,hide);this.x=this.savedX||0;this.y=this.savedY||0;if(this.tput)return this.put.rc();return this._write('\x1b8');};Program.prototype.lsaveCursor=function(key){key=key||'local';this._saved=this._saved||{};this._saved[key]=this._saved[key]||{};this._saved[key].x=this.x;this._saved[key].y=this.y;this._saved[key].hidden=this.cursorHidden;};Program.prototype.lrestoreCursor=function(key,hide){var pos;key=key||'local';if(!this._saved||!this._saved[key])return;pos=this._saved[key];this.cup(pos.y,pos.x);if(hide&&pos.hidden!==this.cursorHidden){if(pos.hidden){this.hideCursor();}else{this.showCursor();}}};Program.prototype.lineHeight=function(){return this._write('\x1b#');};Program.prototype.charset=function(val,level){level=level||0;switch(level){case 0:level='(';break;case 1:level=')';break;case 2:level='*';break;case 3:level='+';break;}
var name=typeof val==='string'?val.toLowerCase():val;switch(name){case'acs':case'scld':if(this.tput)return this.put.smacs();val='0';break;case'uk':val='A';break;case'us':case'usascii':case'ascii':if(this.tput)return this.put.rmacs();val='B';break;case'dutch':val='4';break;case'finnish':val='C';val='5';break;case'french':val='R';break;case'frenchcanadian':val='Q';break;case'german':val='K';break;case'italian':val='Y';break;case'norwegiandanish':val='E';val='6';break;case'spanish':val='Z';break;case'swedish':val='H';val='7';break;case'swiss':val='=';break;case'isolatin':val='/A';break;default:if(this.tput)return this.put.rmacs();val='B';break;}
return this._write('\x1b('+val);};Program.prototype.enter_alt_charset_mode=Program.prototype.as=Program.prototype.smacs=function(){return this.charset('acs');};Program.prototype.exit_alt_charset_mode=Program.prototype.ae=Program.prototype.rmacs=function(){return this.charset('ascii');};Program.prototype.setG=function(val){switch(val){case 1:val='~';break;case 2:val='n';val='}';val='N';break;case 3:val='o';val='|';val='O';break;}
return this._write('\x1b'+val);};Program.prototype.setTitle=function(title){this._title=title;return this._twrite('\x1b]0;'+title+'\x07');};Program.prototype.resetColors=function(param){if(this.has('Cr')){return this.put.Cr(param);}
return this._twrite('\x1b]112\x07');};Program.prototype.dynamicColors=function(param){if(this.has('Cs')){return this.put.Cs(param);}
return this._twrite('\x1b]12;'+param+'\x07');};Program.prototype.selData=function(a,b){if(this.has('Ms')){return this.put.Ms(a,b);}
return this._twrite('\x1b]52;'+a+';'+b+'\x07');};Program.prototype.cuu=Program.prototype.up=Program.prototype.cursorUp=function(param){this.y-=param||1;this._ncoords();if(this.tput){if(!this.tput.strings.parm_up_cursor){return this._write(this.repeat(this.tput.cuu1(),param));}
return this.put.cuu(param);}
return this._write('\x1b['+(param||'')+'A');};Program.prototype.cud=Program.prototype.down=Program.prototype.cursorDown=function(param){this.y+=param||1;this._ncoords();if(this.tput){if(!this.tput.strings.parm_down_cursor){return this._write(this.repeat(this.tput.cud1(),param));}
return this.put.cud(param);}
return this._write('\x1b['+(param||'')+'B');};Program.prototype.cuf=Program.prototype.right=Program.prototype.forward=Program.prototype.cursorForward=function(param){this.x+=param||1;this._ncoords();if(this.tput){if(!this.tput.strings.parm_right_cursor){return this._write(this.repeat(this.tput.cuf1(),param));}
return this.put.cuf(param);}
return this._write('\x1b['+(param||'')+'C');};Program.prototype.cub=Program.prototype.left=Program.prototype.back=Program.prototype.cursorBackward=function(param){this.x-=param||1;this._ncoords();if(this.tput){if(!this.tput.strings.parm_left_cursor){return this._write(this.repeat(this.tput.cub1(),param));}
return this.put.cub(param);}
return this._write('\x1b['+(param||'')+'D');};Program.prototype.cup=Program.prototype.pos=Program.prototype.cursorPos=function(row,col){if(!this.zero){row=(row||1)-1;col=(col||1)-1;}else{row=row||0;col=col||0;}
this.x=col;this.y=row;this._ncoords();if(this.tput)return this.put.cup(row,col);return this._write('\x1b['+(row+1)+';'+(col+1)+'H');};Program.prototype.ed=Program.prototype.eraseInDisplay=function(param){if(this.tput){switch(param){case'above':param=1;break;case'all':param=2;break;case'saved':param=3;break;case'below':default:param=0;break;}
return this.put.ed(param);}
switch(param){case'above':return this._write('\X1b[1J');case'all':return this._write('\x1b[2J');case'saved':return this._write('\x1b[3J');case'below':default:return this._write('\x1b[J');}};Program.prototype.clear=function(){this.x=0;this.y=0;if(this.tput)return this.put.clear();return this._write('\x1b[H\x1b[J');};Program.prototype.el=Program.prototype.eraseInLine=function(param){if(this.tput){switch(param){case'left':param=1;break;case'all':param=2;break;case'right':default:param=0;break;}
return this.put.el(param);}
switch(param){case'left':return this._write('\x1b[1K');case'all':return this._write('\x1b[2K');case'right':default:return this._write('\x1b[K');}};Program.prototype.sgr=Program.prototype.attr=Program.prototype.charAttributes=function(param,val){return this._write(this._attr(param,val));};Program.prototype.text=function(text,attr){return this._attr(attr,true)+text+this._attr(attr,false);};Program.prototype._attr=function(param,val){var self=this,parts,color,m;if(Array.isArray(param)){parts=param;param=parts[0]||'normal';}else{param=param||'normal';parts=param.split(/\s*[,;]\s*/);}
if(parts.length>1){var used={},out=[];parts.forEach(function(part){part=self._attr(part,val).slice(2,-1);if(part==='')return;if(used[part])return;used[part]=true;out.push(part);});return'\x1b['+out.join(';')+'m';}
if(param.indexOf('no ')===0){param=param.substring(3);val=false;}else if(param.indexOf('!')===0){param=param.substring(1);val=false;}
switch(param){case'normal':case'default':if(val===false)return'';return'\x1b[m';case'bold':return val===false?'\x1b[22m':'\x1b[1m';case'ul':case'underline':case'underlined':return val===false?'\x1b[24m':'\x1b[4m';case'blink':return val===false?'\x1b[25m':'\x1b[5m';case'inverse':return val===false?'\x1b[27m':'\x1b[7m';case'invisible':return val===false?'\x1b[28m':'\x1b[8m';case'black fg':return val===false?'\x1b[39m':'\x1b[30m';case'red fg':return val===false?'\x1b[39m':'\x1b[31m';case'green fg':return val===false?'\x1b[39m':'\x1b[32m';case'yellow fg':return val===false?'\x1b[39m':'\x1b[33m';case'blue fg':return val===false?'\x1b[39m':'\x1b[34m';case'magenta fg':return val===false?'\x1b[39m':'\x1b[35m';case'cyan fg':return val===false?'\x1b[39m':'\x1b[36m';case'white fg':case'light grey fg':case'light gray fg':case'bright grey fg':case'bright gray fg':return val===false?'\x1b[39m':'\x1b[37m';case'default fg':if(val===false)return'';return'\x1b[39m';case'black bg':return val===false?'\x1b[49m':'\x1b[40m';case'red bg':return val===false?'\x1b[49m':'\x1b[41m';case'green bg':return val===false?'\x1b[49m':'\x1b[42m';case'yellow bg':return val===false?'\x1b[49m':'\x1b[43m';case'blue bg':return val===false?'\x1b[49m':'\x1b[44m';case'magenta bg':return val===false?'\x1b[49m':'\x1b[45m';case'cyan bg':return val===false?'\x1b[49m':'\x1b[46m';case'white bg':case'light grey bg':case'light gray bg':case'bright grey bg':case'bright gray bg':return val===false?'\x1b[49m':'\x1b[47m';case'default bg':if(val===false)return'';return'\x1b[49m';case'light black fg':case'bright black fg':case'grey fg':case'gray fg':return val===false?'\x1b[39m':'\x1b[90m';case'light red fg':case'bright red fg':return val===false?'\x1b[39m':'\x1b[91m';case'light green fg':case'bright green fg':return val===false?'\x1b[39m':'\x1b[92m';case'light yellow fg':case'bright yellow fg':return val===false?'\x1b[39m':'\x1b[93m';case'light blue fg':case'bright blue fg':return val===false?'\x1b[39m':'\x1b[94m';case'light magenta fg':case'bright magenta fg':return val===false?'\x1b[39m':'\x1b[95m';case'light cyan fg':case'bright cyan fg':return val===false?'\x1b[39m':'\x1b[96m';case'light white fg':case'bright white fg':return val===false?'\x1b[39m':'\x1b[97m';case'light black bg':case'bright black bg':case'grey bg':case'gray bg':return val===false?'\x1b[49m':'\x1b[100m';case'light red bg':case'bright red bg':return val===false?'\x1b[49m':'\x1b[101m';case'light green bg':case'bright green bg':return val===false?'\x1b[49m':'\x1b[102m';case'light yellow bg':case'bright yellow bg':return val===false?'\x1b[49m':'\x1b[103m';case'light blue bg':case'bright blue bg':return val===false?'\x1b[49m':'\x1b[104m';case'light magenta bg':case'bright magenta bg':return val===false?'\x1b[49m':'\x1b[105m';case'light cyan bg':case'bright cyan bg':return val===false?'\x1b[49m':'\x1b[106m';case'light white bg':case'bright white bg':return val===false?'\x1b[49m':'\x1b[107m';case'default fg bg':if(val===false)return'';return this.term('rxvt')?'\x1b[100m':'\x1b[39;49m';default:if(param[0]==='#'){param=param.replace(/#(?:[0-9a-f]{3}){1,2}/i,colors.match);}
m=/^(-?\d+) (fg|bg)$/.exec(param);if(m){color=+m[1];if(val===false||color===-1){return this._attr('default '+m[2]);}
color=colors.reduce(color,this.tput.colors);if(color<16||(this.tput&&this.tput.colors<=16)){if(m[2]==='fg'){if(color<8){color+=30;}else if(color<16){color-=8;color+=90;}}else if(m[2]==='bg'){if(color<8){color+=40;}else if(color<16){color-=8;color+=100;}}
return'\x1b['+color+'m';}
if(m[2]==='fg'){return'\x1b[38;5;'+color+'m';}
if(m[2]==='bg'){return'\x1b[48;5;'+color+'m';}}
if(/^[\d;]*$/.test(param)){return'\x1b['+param+'m';}
return null;}};Program.prototype.fg=Program.prototype.setForeground=function(color,val){color=color.split(/\s*[,;]\s*/).join(' fg, ')+' fg';return this.attr(color,val);};Program.prototype.bg=Program.prototype.setBackground=function(color,val){color=color.split(/\s*[,;]\s*/).join(' bg, ')+' bg';return this.attr(color,val);};Program.prototype.dsr=Program.prototype.deviceStatus=function(param,callback,dec,noBypass){if(dec){return this.response('device-status','\x1b[?'+(param||'0')+'n',callback,noBypass);}
return this.response('device-status','\x1b['+(param||'0')+'n',callback,noBypass);};Program.prototype.getCursor=function(callback){return this.deviceStatus(6,callback,false,true);};Program.prototype.saveReportedCursor=function(callback){var self=this;if(this.tput.strings.user7==='\x1b[6n'||this.term('screen')){return this.getCursor(function(err,data){if(data){self._rx=data.status.x;self._ry=data.status.y;}
if(!callback)return;return callback(err);});}
if(!callback)return;return callback();};Program.prototype.restoreReportedCursor=function(){if(this._rx==null)return;return this.cup(this._ry,this._rx);};Program.prototype.ich=Program.prototype.insertChars=function(param){this.x+=param||1;this._ncoords();if(this.tput)return this.put.ich(param);return this._write('\x1b['+(param||1)+'@');};Program.prototype.cnl=Program.prototype.cursorNextLine=function(param){this.y+=param||1;this._ncoords();return this._write('\x1b['+(param||'')+'E');};Program.prototype.cpl=Program.prototype.cursorPrecedingLine=function(param){this.y-=param||1;this._ncoords();return this._write('\x1b['+(param||'')+'F');};Program.prototype.cha=Program.prototype.cursorCharAbsolute=function(param){if(!this.zero){param=(param||1)-1;}else{param=param||0;}
this.x=param;this.y=0;this._ncoords();if(this.tput)return this.put.hpa(param);return this._write('\x1b['+(param+1)+'G');};Program.prototype.il=Program.prototype.insertLines=function(param){if(this.tput)return this.put.il(param);return this._write('\x1b['+(param||'')+'L');};Program.prototype.dl=Program.prototype.deleteLines=function(param){if(this.tput)return this.put.dl(param);return this._write('\x1b['+(param||'')+'M');};Program.prototype.dch=Program.prototype.deleteChars=function(param){if(this.tput)return this.put.dch(param);return this._write('\x1b['+(param||'')+'P');};Program.prototype.ech=Program.prototype.eraseChars=function(param){if(this.tput)return this.put.ech(param);return this._write('\x1b['+(param||'')+'X');};Program.prototype.hpa=Program.prototype.charPosAbsolute=function(param){this.x=param||0;this._ncoords();if(this.tput){return this.put.hpa.apply(this.put,arguments);}
param=slice.call(arguments).join(';');return this._write('\x1b['+(param||'')+'`');};Program.prototype.hpr=Program.prototype.HPositionRelative=function(param){if(this.tput)return this.cuf(param);this.x+=param||1;this._ncoords();return this._write('\x1b['+(param||'')+'a');};Program.prototype.da=Program.prototype.sendDeviceAttributes=function(param,callback){return this.response('device-attributes','\x1b['+(param||'')+'c',callback);};Program.prototype.vpa=Program.prototype.linePosAbsolute=function(param){this.y=param||1;this._ncoords();if(this.tput){return this.put.vpa.apply(this.put,arguments);}
param=slice.call(arguments).join(';');return this._write('\x1b['+(param||'')+'d');};Program.prototype.vpr=Program.prototype.VPositionRelative=function(param){if(this.tput)return this.cud(param);this.y+=param||1;this._ncoords();return this._write('\x1b['+(param||'')+'e');};Program.prototype.hvp=Program.prototype.HVPosition=function(row,col){if(!this.zero){row=(row||1)-1;col=(col||1)-1;}else{row=row||0;col=col||0;}
this.y=row;this.x=col;this._ncoords();if(this.tput)return this.put.cup(row,col);return this._write('\x1b['+(row+1)+';'+(col+1)+'f');};Program.prototype.sm=Program.prototype.setMode=function(){var param=slice.call(arguments).join(';');return this._write('\x1b['+(param||'')+'h');};Program.prototype.decset=function(){var param=slice.call(arguments).join(';');return this.setMode('?'+param);};Program.prototype.dectcem=Program.prototype.cnorm=Program.prototype.cvvis=Program.prototype.showCursor=function(){this.cursorHidden=false;if(this.tput)return this.put.cnorm();return this.setMode('?25');};Program.prototype.alternate=Program.prototype.smcup=Program.prototype.alternateBuffer=function(){this.isAlt=true;if(this.tput)return this.put.smcup();if(this.term('vt')||this.term('linux'))return;this.setMode('?47');return this.setMode('?1049');};Program.prototype.rm=Program.prototype.resetMode=function(){var param=slice.call(arguments).join(';');return this._write('\x1b['+(param||'')+'l');};Program.prototype.decrst=function(){var param=slice.call(arguments).join(';');return this.resetMode('?'+param);};Program.prototype.dectcemh=Program.prototype.cursor_invisible=Program.prototype.vi=Program.prototype.civis=Program.prototype.hideCursor=function(force){this.cursorHidden=true;if(!force&&this.tput)return this.put.civis();return this.resetMode('?25');};Program.prototype.rmcup=Program.prototype.normalBuffer=function(){this.isAlt=false;if(this.tput)return this.put.rmcup();this.resetMode('?47');return this.resetMode('?1049');};Program.prototype.enableMouse=function(){if(process.env.BLESSED_FORCE_MODES){var modes=process.env.BLESSED_FORCE_MODES.split(',');var options={};for(var n=0;n<modes.length;++n){var pair=modes[n].split('=');var v=pair[1]!=='0';switch(pair[0].toUpperCase()){case'SGRMOUSE':options.sgrMouse=v;break;case'UTFMOUSE':options.utfMouse=v;break;case'VT200MOUSE':options.vt200Mouse=v;break;case'URXVTMOUSE':options.urxvtMouse=v;break;case'X10MOUSE':options.x10Mouse=v;break;case'DECMOUSE':options.decMouse=v;break;case'PTERMMOUSE':options.ptermMouse=v;break;case'JSBTERMMOUSE':options.jsbtermMouse=v;break;case'VT200HILITE':options.vt200Hilite=v;break;case'GPMMOUSE':options.gpmMouse=v;break;case'CELLMOTION':options.cellMotion=v;break;case'ALLMOTION':options.allMotion=v;break;case'SENDFOCUS':options.sendFocus=v;break;}}
return this.setMouse(options,true);}
if(this.term('rxvt-unicode')){return this.setMouse({urxvtMouse:true,cellMotion:true,allMotion:true},true);}
if(this.term('rxvt')){return this.setMouse({vt200Mouse:true,x10Mouse:true,cellMotion:true,allMotion:true},true);}
if(this.isVTE){return this.setMouse({sgrMouse:true,cellMotion:true,allMotion:true},true);}
if(this.term('linux')){return this.setMouse({vt200Mouse:true,gpmMouse:true},true);}
if(this.term('xterm')||this.term('screen')||(this.tput&&this.tput.strings.key_mouse)){return this.setMouse({vt200Mouse:true,utfMouse:true,cellMotion:true,allMotion:true},true);}};Program.prototype.disableMouse=function(){if(!this._currentMouse)return;var obj={};Object.keys(this._currentMouse).forEach(function(key){obj[key]=false;});return this.setMouse(obj,false);};Program.prototype.setMouse=function(opt,enable){if(opt.normalMouse!=null){opt.vt200Mouse=opt.normalMouse;opt.allMotion=opt.normalMouse;}
if(opt.hiliteTracking!=null){opt.vt200Hilite=opt.hiliteTracking;}
if(enable===true){if(this._currentMouse){this.setMouse(opt);Object.keys(opt).forEach(function(key){this._currentMouse[key]=opt[key];},this);return;}
this._currentMouse=opt;this.mouseEnabled=true;}else if(enable===false){delete this._currentMouse;this.mouseEnabled=false;}
if(opt.x10Mouse!=null){if(opt.x10Mouse)this.setMode('?9');else this.resetMode('?9');}
if(opt.vt200Mouse!=null){if(opt.vt200Mouse)this.setMode('?1000');else this.resetMode('?1000');}
if(opt.vt200Hilite!=null){if(opt.vt200Hilite)this.setMode('?1001');else this.resetMode('?1001');}
if(opt.cellMotion!=null){if(opt.cellMotion)this.setMode('?1002');else this.resetMode('?1002');}
if(opt.allMotion!=null){if(this.tmux&&this.tmuxVersion>=2){if(opt.allMotion)this._twrite('\x1b[?1003h');else this._twrite('\x1b[?1003l');}else{if(opt.allMotion)this.setMode('?1003');else this.resetMode('?1003');}}
if(opt.sendFocus!=null){if(opt.sendFocus)this.setMode('?1004');else this.resetMode('?1004');}
if(opt.utfMouse!=null){if(opt.utfMouse)this.setMode('?1005');else this.resetMode('?1005');}
if(opt.sgrMouse!=null){if(opt.sgrMouse)this.setMode('?1006');else this.resetMode('?1006');}
if(opt.urxvtMouse!=null){if(opt.urxvtMouse)this.setMode('?1015');else this.resetMode('?1015');}
if(opt.decMouse!=null){if(opt.decMouse)this._write('\x1b[1;2\'z\x1b[1;3\'{');else this._write('\x1b[\'z');}
if(opt.ptermMouse!=null){if(opt.ptermMouse)this._write('\x1b[>1h\x1b[>6h\x1b[>7h\x1b[>1h\x1b[>9l');else this._write('\x1b[>1l\x1b[>6l\x1b[>7l\x1b[>1l\x1b[>9h');}
if(opt.jsbtermMouse!=null){if(opt.jsbtermMouse)this._write('\x1b[0~ZwLMRK+1Q\x1b\\');else this._write('\x1b[0~ZwQ\x1b\\');}
if(opt.gpmMouse!=null){if(opt.gpmMouse)this.enableGpm();else this.disableGpm();}};Program.prototype.decstbm=Program.prototype.csr=Program.prototype.setScrollRegion=function(top,bottom){if(!this.zero){top=(top||1)-1;bottom=(bottom||this.rows)-1;}else{top=top||0;bottom=bottom||(this.rows-1);}
this.scrollTop=top;this.scrollBottom=bottom;this.x=0;this.y=0;this._ncoords();if(this.tput)return this.put.csr(top,bottom);return this._write('\x1b['+(top+1)+';'+(bottom+1)+'r');};Program.prototype.scA=Program.prototype.saveCursorA=function(){this.savedX=this.x;this.savedY=this.y;if(this.tput)return this.put.sc();return this._write('\x1b[s');};Program.prototype.rcA=Program.prototype.restoreCursorA=function(){this.x=this.savedX||0;this.y=this.savedY||0;if(this.tput)return this.put.rc();return this._write('\x1b[u');};Program.prototype.cht=Program.prototype.cursorForwardTab=function(param){this.x+=8;this._ncoords();if(this.tput)return this.put.tab(param);return this._write('\x1b['+(param||1)+'I');};Program.prototype.su=Program.prototype.scrollUp=function(param){this.y-=param||1;this._ncoords();if(this.tput)return this.put.parm_index(param);return this._write('\x1b['+(param||1)+'S');};Program.prototype.sd=Program.prototype.scrollDown=function(param){this.y+=param||1;this._ncoords();if(this.tput)return this.put.parm_rindex(param);return this._write('\x1b['+(param||1)+'T');};Program.prototype.initMouseTracking=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'T');};Program.prototype.resetTitleModes=function(){return this._write('\x1b[>'+slice.call(arguments).join(';')+'T');};Program.prototype.cbt=Program.prototype.cursorBackwardTab=function(param){this.x-=8;this._ncoords();if(this.tput)return this.put.cbt(param);return this._write('\x1b['+(param||1)+'Z');};Program.prototype.rep=Program.prototype.repeatPrecedingCharacter=function(param){this.x+=param||1;this._ncoords();if(this.tput)return this.put.rep(param);return this._write('\x1b['+(param||1)+'b');};Program.prototype.tbc=Program.prototype.tabClear=function(param){if(this.tput)return this.put.tbc(param);return this._write('\x1b['+(param||0)+'g');};Program.prototype.mc=Program.prototype.mediaCopy=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'i');};Program.prototype.print_screen=Program.prototype.ps=Program.prototype.mc0=function(){if(this.tput)return this.put.mc0();return this.mc('0');};Program.prototype.prtr_on=Program.prototype.po=Program.prototype.mc5=function(){if(this.tput)return this.put.mc5();return this.mc('5');};Program.prototype.prtr_off=Program.prototype.pf=Program.prototype.mc4=function(){if(this.tput)return this.put.mc4();return this.mc('4');};Program.prototype.prtr_non=Program.prototype.pO=Program.prototype.mc5p=function(){if(this.tput)return this.put.mc5p();return this.mc('?5');};Program.prototype.setResources=function(){return this._write('\x1b[>'+slice.call(arguments).join(';')+'m');};Program.prototype.disableModifiers=function(param){return this._write('\x1b[>'+(param||'')+'n');};Program.prototype.setPointerMode=function(param){return this._write('\x1b[>'+(param||'')+'p');};Program.prototype.decstr=Program.prototype.rs2=Program.prototype.softReset=function(){if(this.tput)return this.put.rs2();return this._write('\x1b[!p\x1b[?3;4l\x1b[4l\x1b>');};Program.prototype.decrqm=Program.prototype.requestAnsiMode=function(param){return this._write('\x1b['+(param||'')+'$p');};Program.prototype.decrqmp=Program.prototype.requestPrivateMode=function(param){return this._write('\x1b[?'+(param||'')+'$p');};Program.prototype.decscl=Program.prototype.setConformanceLevel=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'"p');};Program.prototype.decll=Program.prototype.loadLEDs=function(param){return this._write('\x1b['+(param||'')+'q');};Program.prototype.decscusr=Program.prototype.setCursorStyle=function(param){switch(param){case'blinking block':param=1;break;case'block':case'steady block':param=2;break;case'blinking underline':param=3;break;case'underline':case'steady underline':param=4;break;case'blinking bar':param=5;break;case'bar':case'steady bar':param=6;break;}
if(param===2&&this.has('Se')){return this.put.Se();}
if(this.has('Ss')){return this.put.Ss(param);}
return this._write('\x1b['+(param||1)+' q');};Program.prototype.decsca=Program.prototype.setCharProtectionAttr=function(param){return this._write('\x1b['+(param||0)+'"q');};Program.prototype.restorePrivateValues=function(){return this._write('\x1b[?'+slice.call(arguments).join(';')+'r');};Program.prototype.deccara=Program.prototype.setAttrInRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'$r');};Program.prototype.savePrivateValues=function(){return this._write('\x1b[?'+slice.call(arguments).join(';')+'s');};Program.prototype.manipulateWindow=function(){var args=slice.call(arguments);var callback=typeof args[args.length-1]==='function'?args.pop():function(){};return this.response('window-manipulation','\x1b['+args.join(';')+'t',callback);};Program.prototype.getWindowSize=function(callback){return this.manipulateWindow(18,callback);};Program.prototype.decrara=Program.prototype.reverseAttrInRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'$t');};Program.prototype.setTitleModeFeature=function(){return this._twrite('\x1b[>'+slice.call(arguments).join(';')+'t');};Program.prototype.decswbv=Program.prototype.setWarningBellVolume=function(param){return this._write('\x1b['+(param||'')+' t');};Program.prototype.decsmbv=Program.prototype.setMarginBellVolume=function(param){return this._write('\x1b['+(param||'')+' u');};Program.prototype.deccra=Program.prototype.copyRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'$v');};Program.prototype.decefr=Program.prototype.enableFilterRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'\'w');};Program.prototype.decreqtparm=Program.prototype.requestParameters=function(param){return this._write('\x1b['+(param||0)+'x');};Program.prototype.decsace=Program.prototype.selectChangeExtent=function(param){return this._write('\x1b['+(param||0)+'x');};Program.prototype.decfra=Program.prototype.fillRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'$x');};Program.prototype.decelr=Program.prototype.enableLocatorReporting=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'\'z');};Program.prototype.decera=Program.prototype.eraseRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'$z');};Program.prototype.decsle=Program.prototype.setLocatorEvents=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'\'{');};Program.prototype.decsera=Program.prototype.selectiveEraseRectangle=function(){return this._write('\x1b['+slice.call(arguments).join(';')+'${');};Program.prototype.decrqlp=Program.prototype.req_mouse_pos=Program.prototype.reqmp=Program.prototype.requestLocatorPosition=function(param,callback){if(this.has('req_mouse_pos')){var code=this.tput.req_mouse_pos(param);return this.response('locator-position',code,callback);}
return this.response('locator-position','\x1b['+(param||'')+'\'|',callback);};Program.prototype.decic=Program.prototype.insertColumns=function(){return this._write('\x1b['+slice.call(arguments).join(';')+' }');};Program.prototype.decdc=Program.prototype.deleteColumns=function(){return this._write('\x1b['+slice.call(arguments).join(';')+' ~');};Program.prototype.out=function(name){var args=Array.prototype.slice.call(arguments,1);this.ret=true;var out=this[name].apply(this,args);this.ret=false;return out;};Program.prototype.sigtstp=function(callback){var resume=this.pause();process.once('SIGCONT',function(){resume();if(callback)callback();});process.kill(process.pid,'SIGTSTP');};Program.prototype.pause=function(callback){var self=this,isAlt=this.isAlt,mouseEnabled=this.mouseEnabled;this.lsaveCursor('pause');if(isAlt)this.normalBuffer();this.showCursor();if(mouseEnabled)this.disableMouse();var write=this.output.write;this.output.write=function(){};if(this.input.setRawMode){this.input.setRawMode(false);}
this.input.pause();return this._resume=function(){delete self._resume;if(self.input.setRawMode){self.input.setRawMode(true);}
self.input.resume();self.output.write=write;if(isAlt)self.alternateBuffer();if(mouseEnabled)self.enableMouse();self.lrestoreCursor('pause',true);if(callback)callback();};};Program.prototype.resume=function(){if(this._resume)return this._resume();};function unshiftEvent(obj,event,listener){var listeners;if(obj.listeners){listeners=obj.listeners(event);obj.removeAllListeners(event);obj.on(event,listener);listeners.forEach(function(listener){obj.on(event,listener);});}else{if(obj==process)process.on(event,listener);}}
function merge(out){slice.call(arguments,1).forEach(function(obj){Object.keys(obj).forEach(function(key){out[key]=obj[key];});});return out;}
module.exports=Program;};BundleModuleCode['term/tput']=function(module,exports){var assert=Require('assert'),path=Require('path'),fs=Require('fs'),cp=Require('child_process');FileEmbedd('term/def/xterm');FileEmbedd('term/def/windows-ansi');function Tput(options){if(!(this instanceof Tput)){return new Tput(options);}
options=options||{};if(typeof options==='string'){options={terminal:options};}
this.options=options;this.terminal=options.terminal||options.term||process.env.TERM||(process.platform==='win32'?'windows-ansi':'xterm');this.terminal=this.terminal.toLowerCase();this.debug=options.debug;this.padding=options.padding;this.extended=options.extended;this.printf=options.printf;this.termcap=options.termcap;this.error=null;this.terminfoPrefix=options.terminfoPrefix;this.terminfoFile=options.terminfoFile;this.termcapFile=options.termcapFile;if(options.terminal||options.term){this.setup();}}
Tput.prototype.setup=function(){this.error=null;try{if(this.termcap){try{this.injectTermcap();}catch(e){if(this.debug)throw e;this.error=new Error('Termcap parse error.');this._useInternalCap(this.terminal);}}else{try{this.injectTerminfo();}catch(e){if(this.debug)throw e;this.error=new Error('Terminfo parse error.');this._useInternalInfo(this.terminal);}}}catch(e){if(this.debug)throw e;this.error=new Error('Terminfo not found.');this._useXtermInfo();}};Tput.prototype.term=function(is){return this.terminal.indexOf(is)===0;};Tput.prototype._debug=function(){if(!this.debug)return;return console.log.apply(console,arguments);};Tput.prototype._useVt102Cap=function(){return this.injectTermcap('vt102');};Tput.prototype._useXtermCap=function(){return this.injectTermcap('term/def/xterm.termcap');};Tput.prototype._useXtermInfo=function(){return this.injectTerminfo('term/def/xterm');};Tput.prototype._useInternalInfo=function(name){name=path.basename(name);return this.injectTerminfo('term/def/'+name);};Tput.prototype._useInternalCap=function(name){name=path.basename(name);return this.injectTermcap('term/def/'+name+'.termcap');};Tput.ipaths=[__dirname+'/..',process.env.TERMINFO||'',(process.env.TERMINFO_DIRS||'').split(':'),(process.env.HOME||'')+'/.terminfo','/usr/share/terminfo','/usr/share/lib/terminfo','/usr/lib/terminfo','/usr/local/share/terminfo','/usr/local/share/lib/terminfo','/usr/local/lib/terminfo','/usr/local/ncurses/lib/terminfo','/lib/terminfo'];Tput.prototype.readTerminfo=function(term){var data,file,info;term=term||this.terminal;try{data=FileEmbedded(term);}catch(e){};if(!data){file=path.normalize(this._prefix(term));console.log('Reading '+file);data=fs.readFileSync(file);}else file=term;info=this.parseTerminfo(data,file);if(this.debug){this._terminfo=info;}
return info;};Tput._prefix=Tput.prototype._prefix=function(term){if(term){if(term.indexOf(path.sep)==0){return term;}
if(this.terminfoFile){return this.terminfoFile;}}
var paths=Tput.ipaths.slice(),file;if(this.terminfoPrefix){paths.unshift(this.terminfoPrefix);}
file=this._tprefix(paths,term);if(file)return file;file=this._tprefix(paths,term,true);if(file)return file;throw new Error('Terminfo directory not found.');};Tput._tprefix=Tput.prototype._tprefix=function(prefix,term,soft){if(!prefix)return;var file,dir,i,sdiff,sfile,list;try{file=prefix+'/'+term;fs.statSync(file);return file;}catch(e){;}
if(Array.isArray(prefix)){for(i=0;i<prefix.length;i++){file=this._tprefix(prefix[i],term,soft);if(file)return file;}
return;}
var find=function(word){var file,ch;file=path.resolve(prefix,word[0]);try{fs.statSync(file);return file;}catch(e){;}
ch=word[0].charCodeAt(0).toString(16);if(ch.length<2)ch='0'+ch;file=path.resolve(prefix,ch);try{fs.statSync(file);return file;}catch(e){;}};if(!term){try{dir=fs.readdirSync(prefix).filter(function(file){return file.length!==1&&!/^[0-9a-fA-F]{2}$/.test(file);});if(!dir.length){return prefix;}}catch(e){;}
return;}
term=path.basename(term);dir=find(term);if(!dir)return;if(soft){try{list=fs.readdirSync(dir);}catch(e){return;}
list.forEach(function(file){if(file.indexOf(term)===0){var diff=file.length-term.length;if(!sfile||diff<sdiff){sdiff=diff;sfile=file;}}});return sfile&&(soft||sdiff===0)?path.resolve(dir,sfile):null;}
file=path.resolve(dir,term);try{fs.statSync(file);return file;}catch(e){;}};Tput.prototype.parseTerminfo=function(data,file){var info={},extended,l=data.length,i=0,v,o;var h=info.header={dataSize:data.length,headerSize:12,magicNumber:(data[1]<<8)|data[0],namesSize:(data[3]<<8)|data[2],boolCount:(data[5]<<8)|data[4],numCount:(data[7]<<8)|data[6],strCount:(data[9]<<8)|data[8],strTableSize:(data[11]<<8)|data[10]};console.log('parseTerminfo '+file+':'+data.length)
h.total=h.headerSize
+h.namesSize
+h.boolCount
+h.numCount*2
+h.strCount*2
+h.strTableSize;i+=h.headerSize;var names=data.toString('ascii',i,i+h.namesSize-1),parts=names.split('|'),name=parts[0],desc=parts.pop();info.name=name;info.names=parts;info.desc=desc;info.dir=path.resolve(file,'..','..');info.file=file;i+=h.namesSize-1;assert.equal(data[i],0);i++;info.bools={};l=i+h.boolCount;o=0;for(;i<l;i++){v=Tput.bools[o++];info.bools[v]=data[i]===1;}
if(i%2){assert.equal(data[i],0);i++;}
info.numbers={};l=i+h.numCount*2;o=0;for(;i<l;i+=2){v=Tput.numbers[o++];if(data[i+1]===0377&&data[i]===0377){info.numbers[v]=-1;}else{info.numbers[v]=(data[i+1]<<8)|data[i];}}
info.strings={};l=i+h.strCount*2;o=0;for(;i<l;i+=2){v=Tput.strings[o++];if(data[i+1]===0377&&data[i]===0377){info.strings[v]=-1;}else{info.strings[v]=(data[i+1]<<8)|data[i];}}
Object.keys(info.strings).forEach(function(key){if(info.strings[key]===-1){delete info.strings[key];return;}
if(info.strings[key]===65534){delete info.strings[key];return;}
var s=i+info.strings[key],j=s;while(data[j])j++;assert(j<data.length);info.strings[key]=data.toString('ascii',s,j);});if(this.extended!==false){i--;i+=h.strTableSize;if(i%2){assert.equal(data[i],0);i++;}
l=data.length;if(i<l-1){try{extended=this.parseExtended(data.slice(i));}catch(e){if(this.debug){throw e;}
return info;}
info.header.extended=extended.header;['bools','numbers','strings'].forEach(function(key){merge(info[key],extended[key]);});}}
return info;};Tput.prototype.parseExtended=function(data){var info={},l=data.length,i=0;var h=info.header={dataSize:data.length,headerSize:10,boolCount:(data[i+1]<<8)|data[i+0],numCount:(data[i+3]<<8)|data[i+2],strCount:(data[i+5]<<8)|data[i+4],strTableSize:(data[i+7]<<8)|data[i+6],lastStrTableOffset:(data[i+9]<<8)|data[i+8]};h.total=h.headerSize
+h.boolCount
+h.numCount*2
+h.strCount*2
+h.strTableSize;i+=h.headerSize;var _bools=[];l=i+h.boolCount;for(;i<l;i++){_bools.push(data[i]===1);}
if(i%2){assert.equal(data[i],0);i++;}
var _numbers=[];l=i+h.numCount*2;for(;i<l;i+=2){if(data[i+1]===0377&&data[i]===0377){_numbers.push(-1);}else{_numbers.push((data[i+1]<<8)|data[i]);}}
var _strings=[];l=i+h.strCount*2;for(;i<l;i+=2){if(data[i+1]===0377&&data[i]===0377){_strings.push(-1);}else{_strings.push((data[i+1]<<8)|data[i]);}}
i=data.length-h.lastStrTableOffset;var high=0;_strings.forEach(function(offset,k){if(offset===-1){_strings[k]='';return;}
var s=i+offset,j=s;while(data[j])j++;assert(j<data.length);if(high<j-i){high=j-i;}
_strings[k]=data.toString('ascii',s,j);});i+=high+1;l=data.length;var sym=[],j;for(;i<l;i++){j=i;while(data[j])j++;sym.push(data.toString('ascii',i,j));i=j;}
j=0;info.bools={};_bools.forEach(function(bool){info.bools[sym[j++]]=bool;});info.numbers={};_numbers.forEach(function(number){info.numbers[sym[j++]]=number;});info.strings={};_strings.forEach(function(string){info.strings[sym[j++]]=string;});assert.equal(i,data.length);return info;};Tput.prototype.compileTerminfo=function(term){return this.compile(this.readTerminfo(term));};Tput.prototype.injectTerminfo=function(term){return this.inject(this.compileTerminfo(term));};Tput.prototype.compile=function(info){var self=this;if(!info){throw new Error('Terminal not found.');}
this.detectFeatures(info);this._debug(info);info.all={};info.methods={};['bools','numbers','strings'].forEach(function(type){Object.keys(info[type]).forEach(function(key){info.all[key]=info[type][key];info.methods[key]=self._compile(info,key,info.all[key]);});});Tput.bools.forEach(function(key){if(info.methods[key]==null)info.methods[key]=false;});Tput.numbers.forEach(function(key){if(info.methods[key]==null)info.methods[key]=-1;});Tput.strings.forEach(function(key){if(!info.methods[key])info.methods[key]=noop;});Object.keys(info.methods).forEach(function(key){if(!Tput.alias[key])return;Tput.alias[key].forEach(function(alias){info.methods[alias]=info.methods[key];});});return info;};Tput.prototype.inject=function(info){var self=this,methods=info.methods||info;Object.keys(methods).forEach(function(key){if(typeof methods[key]!=='function'){self[key]=methods[key];return;}
self[key]=function(){var args=Array.prototype.slice.call(arguments);return methods[key].call(self,args);};});this.info=info;this.all=info.all;this.methods=info.methods;this.bools=info.bools;this.numbers=info.numbers;this.strings=info.strings;if(!~info.names.indexOf(this.terminal)){this.terminal=info.name;}
this.features=info.features;Object.keys(info.features).forEach(function(key){if(key==='padding'){if(!info.features.padding&&self.options.padding!==true){self.padding=false;}
return;}
self[key]=info.features[key];});};Tput.prototype._compile=function(info,key,str){var v;this._debug('Compiling %s: %s',key,JSON.stringify(str));switch(typeof str){case'boolean':return str;case'number':return str;case'string':break;default:return noop;}
if(!str){return noop;}
if(key==='init_file'||key==='reset_file'){try{str=fs.readFileSync(str,'utf8');if(this.debug){v=('return '+JSON.stringify(str)+';').replace(/\x1b/g,'\\x1b').replace(/\r/g,'\\r').replace(/\n/g,'\\n');process.stdout.write(v+'\n');}
return function(){return str;};}catch(e){return noop;}}
var tkey=info.name+'.'+key,header='var v, dyn = {}, stat = {}, stack = [], out = [];',footer=';return out.join("");',code=header,val=str,buff='',cap,ch,fi,then,els,end;function read(regex,no){cap=regex.exec(val);if(!cap)return;val=val.substring(cap[0].length);ch=cap[1];if(!no)clear();return cap;}
function stmt(c){if(code[code.length-1]===','){code=code.slice(0,-1);}
code+=c;}
function expr(c){code+=c+',';}
function echo(c){if(c==='""')return;expr('out.push('+c+')');}
function print(c){buff+=c;}
function clear(){if(buff){echo(JSON.stringify(buff).replace(/\\u00([0-9a-fA-F]{2})/g,'\\x$1'));buff='';}}
while(val){if(read(/^\n /,true)){continue;}
if(read(/^\^(.)/i,true)){if(!(ch>=' '&&ch<='~')){this._debug('%s: bad caret char.',tkey);print(cap[0]);continue;}
if(ch==='?'){ch='\x7f';}else{ch=ch.charCodeAt(0)&31;if(ch===0)ch=128;ch=String.fromCharCode(ch);}
print(ch);continue;}
if(read(/^\\([0-7]{3})/,true)){print(String.fromCharCode(parseInt(ch,8)));continue;}
if(read(/^\\([eEnlrtbfs\^\\,:0]|.)/,true)){switch(ch){case'e':case'E':ch='\x1b';break;case'n':ch='\n';break;case'l':ch='\x85';break;case'r':ch='\r';break;case't':ch='\t';break;case'b':ch='\x08';break;case'f':ch='\x0c';break;case's':ch=' ';break;case'^':ch='^';break;case'\\':ch='\\';break;case',':ch=',';break;case':':ch=':';break;case'0':ch='\200';break;case'a':ch='\x07';break;default:this._debug('%s: bad backslash char.',tkey);ch=cap[0];break;}
print(ch);continue;}
if(read(/^\$<(\d+)([*\/]{0,2})>/,true)){if(this.padding)print(cap[0]);continue;}
if(read(/^%%/,true)){print('%');continue;}
if(read(/^%((?::-|[+# ]){1,4})?(\d+(?:\.\d+)?)?([doxXsc])/)){if(this.printf||cap[1]||cap[2]||~'oxX'.indexOf(cap[3])){echo('sprintf("'+cap[0].replace(':-','-')+'", stack.pop())');}else if(cap[3]==='c'){echo('(v = stack.pop(), isFinite(v) '
+'? String.fromCharCode(v || 0200) : "")');}else{echo('stack.pop()');}
continue;}
if(read(/^%p([1-9])/)){expr('(stack.push(v = params['+(ch-1)+']), v)');continue;}
if(read(/^%P([a-z])/)){expr('dyn.'+ch+' = stack.pop()');continue;}
if(read(/^%g([a-z])/)){expr('(stack.push(dyn.'+ch+'), dyn.'+ch+')');continue;}
if(read(/^%P([A-Z])/)){expr('stat.'+ch+' = stack.pop()');continue;}
if(read(/^%g([A-Z])/)){expr('(stack.push(v = stat.'+ch+'), v)');continue;}
if(read(/^%'(.)'/)){expr('(stack.push(v = '+ch.charCodeAt(0)+'), v)');continue;}
if(read(/^%\{(\d+)\}/)){expr('(stack.push(v = '+ch+'), v)');continue;}
if(read(/^%l/)){expr('(stack.push(v = (stack.pop() || "").length || 0), v)');continue;}
if(read(/^%([+\-*\/m&|\^=><])/)){if(ch==='=')ch='===';else if(ch==='m')ch='%';expr('(v = stack.pop(),'
+' stack.push(v = (stack.pop() '+ch+' v) || 0),'
+' v)');continue;}
if(read(/^%([AO])/)){expr('(stack.push(v = (stack.pop() '
+(ch==='A'?'&&':'||')
+' stack.pop())), v)');continue;}
if(read(/^%([!~])/)){expr('(stack.push(v = '+ch+'stack.pop()), v)');continue;}
if(read(/^%i/)){expr('(params[0]++, params[1]++)');continue;}
if(read(/^%\?/)){end=-1;stmt(';if (');continue;}
if(read(/^%t/)){end=-1;stmt(') {');continue;}
if(read(/^%e/)){fi=val.indexOf('%?');then=val.indexOf('%t');els=val.indexOf('%e');end=val.indexOf('%;');if(end===-1)end=Infinity;if(then!==-1&&then<end&&(fi===-1||then<fi)&&(els===-1||then<els)){stmt('} else if (');}else{stmt('} else {');}
continue;}
if(read(/^%;/)){end=null;stmt('}');continue;}
buff+=val[0];val=val.substring(1);}
clear();if(end!=null){stmt('}');}
stmt(footer);v=code.slice(header.length,-footer.length);if(!v.length){code='return "";';}else if(v=/^out\.push\(("(?:[^"]|\\")+")\)$/.exec(v)){code='return '+v[1]+';';}else{code=code.replace(/\(stack\.push\(v = params\[(\d+)\]\), v\),out\.push\(stack\.pop\(\)\)/g,'out.push(params[$1])');v=code.slice(header.length,-footer.length);if(!~v.indexOf('v = '))code=code.replace('v, ','');if(!~v.indexOf('dyn'))code=code.replace('dyn = {}, ','');if(!~v.indexOf('stat'))code=code.replace('stat = {}, ','');if(!~v.indexOf('stack'))code=code.replace('stack = [], ','');code=code.replace(/out = \[\];out\.push\(("(?:[^"]|\\")+")\),/,'out = [$1];');}
if(str==='\u001b%?'){code='return "\\x1b";';}
if(this.debug){v=code.replace(/\x1b/g,'\\x1b').replace(/\r/g,'\\r').replace(/\n/g,'\\n');process.stdout.write(v+'\n');}
try{if(this.options.stringify&&code.indexOf('return ')===0){return new Function('',code)();}
return this.printf||~code.indexOf('sprintf(')?new Function('sprintf, params',code).bind(null,sprintf):new Function('params',code);}catch(e){console.error('');console.error('Error on %s:',tkey);console.error(JSON.stringify(str));console.error('');console.error(code.replace(/(,|;)/g,'$1\n'));e.stack=e.stack.replace(/\x1b/g,'\\x1b');throw e;}};Tput.prototype._print=function(code,print,done){var xon=!this.bools.needs_xon_xoff||this.bools.xon_xoff;print=print||write;done=done||noop;if(!this.padding){print(code);return done();}
var parts=code.split(/(?=\$<[\d.]+[*\/]{0,2}>)/),i=0;(function next(){if(i===parts.length){return done();}
var part=parts[i++],padding=/^\$<([\d.]+)([*\/]{0,2})>/.exec(part),amount,suffix;if(!padding){print(part);return next();}
part=part.substring(padding[0].length);amount=+padding[1];suffix=padding[2];if(xon&&!~suffix.indexOf('/')){print(part);return next();}
if(~suffix.indexOf('*')){amount=amount;}
return setTimeout(function(){print(part);return next();},amount);})();};Tput.print=function(){var fake={padding:true,bools:{needs_xon_xoff:true,xon_xoff:false}};return Tput.prototype._print.apply(fake,arguments);};Tput.cpaths=[process.env.TERMCAP||'',(process.env.TERMPATH||'').split(/[: ]/),(process.env.HOME||'')+'/.termcap','/usr/share/misc/termcap','/etc/termcap'];Tput.prototype.readTermcap=function(term){var self=this,terms,term_,root,paths;term=term||this.terminal;if(~term.indexOf(path.sep)&&(terms=this._tryCap(path.resolve(term)))){term_=path.basename(term).split('.')[0];if(terms[process.env.TERM]){term=process.env.TERM;}else if(terms[term_]){term=term_;}else{term=Object.keys(terms)[0];}}else{paths=Tput.cpaths.slice();if(this.termcapFile){paths.unshift(this.termcapFile);}
paths.push(Tput.termcap);terms=this._tryCap(paths,term);}
if(!terms){throw new Error('Cannot find termcap for: '+term);}
root=terms[term];if(this.debug){this._termcap=terms;}
(function tc(term){if(term&&term.strings.tc){root.inherits=root.inherits||[];root.inherits.push(term.strings.tc);var names=terms[term.strings.tc]?terms[term.strings.tc].names:[term.strings.tc];self._debug('%s inherits from %s.',term.names.join('/'),names.join('/'));var inherit=tc(terms[term.strings.tc]);if(inherit){['bools','numbers','strings'].forEach(function(type){merge(term[type],inherit[type]);});}}
return term;})(root);root=this.translateTermcap(root);return root;};Tput.prototype._tryCap=function(file,term){if(!file)return;var terms,data,i;if(Array.isArray(file)){for(i=0;i<file.length;i++){data=this._tryCap(file[i],term);if(data)return data;}
return;}
data=file[0]==='/'?tryRead(file):file;if(!data)return;terms=this.parseTermcap(data,file);if(term&&!terms[term]){return;}
return terms;};Tput.prototype.parseTermcap=function(data,file){var terms={},parts,term,entries,fields,field,names,i,j,k;data=data.replace(/\\\n[ \t]*/g,'');data=data.replace(/^#[^\n]+/gm,'');entries=data.trim().split(/\n+/);for(i=0;i<entries.length;i++){fields=entries[i].split(/:+/);for(j=0;j<fields.length;j++){field=fields[j].trim();if(!field)continue;if(j===0){names=field.split('|');term={name:names[0],names:names,desc:names.pop(),file:~file.indexOf(path.sep)?path.resolve(file):file,termcap:true};for(k=0;k<names.length;k++){terms[names[k]]=term;}
term.bools={};term.numbers={};term.strings={};continue;}
if(~field.indexOf('=')){parts=field.split('=');term.strings[parts[0]]=parts.slice(1).join('=');}else if(~field.indexOf('#')){parts=field.split('#');term.numbers[parts[0]]=+parts.slice(1).join('#');}else{term.bools[field]=true;}}}
return terms;};Tput.prototype.translateTermcap=function(info){var self=this,out={};if(!info)return;this._debug(info);['name','names','desc','file','termcap'].forEach(function(key){out[key]=info[key];});var map=(function(){var out={};Object.keys(Tput.alias).forEach(function(key){var aliases=Tput.alias[key];out[aliases.termcap]=key;});return out;})();['bools','numbers','strings'].forEach(function(key){out[key]={};Object.keys(info[key]).forEach(function(cap){if(key==='strings'){info.strings[cap]=self._captoinfo(cap,info.strings[cap],1);}
if(map[cap]){out[key][map[cap]]=info[key][cap];}else{out[key][cap]=info[key][cap];}});});return out;};Tput.prototype.compileTermcap=function(term){return this.compile(this.readTermcap(term));};Tput.prototype.injectTermcap=function(term){return this.inject(this.compileTermcap(term));};Tput.prototype._captoinfo=function(cap,s,parameterized){var self=this;var capstart;if(parameterized==null){parameterized=0;}
var MAX_PUSHED=16,stack=[];var stackptr=0,onstack=0,seenm=0,seenn=0,seenr=0,param=1,i=0,out='';function warn(){var args=Array.prototype.slice.call(arguments);args[0]='captoinfo: '+(args[0]||'');return self._debug.apply(self,args);}
function isdigit(ch){return ch>='0'&&ch<='9';}
function isgraph(ch){return ch>' '&&ch<='~';}
function cvtchar(sp){var c='\0',len;var j=i;switch(sp[j]){case'\\':switch(sp[++j]){case'\'':case'$':case'\\':case'%':c=sp[j];len=2;break;case'\0':c='\\';len=1;break;case'0':case'1':case'2':case'3':len=1;while(isdigit(sp[j])){c=String.fromCharCode(8*c.charCodeAt(0)
+(sp[j++].charCodeAt(0)-'0'.charCodeAt(0)));len++;}
break;default:c=sp[j];len=2;break;}
break;case'^':c=String.fromCharCode(sp[++j].charCodeAt(0)&0x1f);len=2;break;default:c=sp[j];len=1;}
if(isgraph(c)&&c!==','&&c!=='\''&&c!=='\\'&&c!==':'){out+='%\'';out+=c;out+='\'';}else{out+='%{';if(c.charCodeAt(0)>99){out+=String.fromCharCode((c.charCodeAt(0)/100|0)+'0'.charCodeAt(0));}
if(c.charCodeAt(0)>9){out+=String.fromCharCode((c.charCodeAt(0)/10|0)%10+'0'.charCodeAt(0));}
out+=String.fromCharCode(c.charCodeAt(0)%10+'0'.charCodeAt(0));out+='}';}
return len;}
function getparm(parm,n){if(seenr){if(parm===1){parm=2;}else if(parm===2){parm=1;}}
if(onstack===parm){if(n>1){warn('string may not be optimal');out+='%Pa';while(n--){out+='%ga';}}
return;}
if(onstack!==0){push();}
onstack=parm;while(n--){out+='%p';out+=String.fromCharCode('0'.charCodeAt(0)+parm);}
if(seenn&&parm<3){out+='%{96}%^';}
if(seenm&&parm<3){out+='%{127}%^';}}
function push(){if(stackptr>=MAX_PUSHED){warn('string too complex to convert');}else{stack[stackptr++]=onstack;}}
function pop(){if(stackptr===0){if(onstack===0){warn('I\'m confused');}else{onstack=0;}}else{onstack=stack[--stackptr];}
param++;}
function see03(){getparm(param,1);out+='%3d';pop();}
function invalid(){out+='%';i--;warn('unknown %% code %s (%#x) in %s',JSON.stringify(s[i]),s[i].charCodeAt(0),cap);}
capstart=null;if(s==null)s='';if(parameterized>=0&&isdigit(s[i])){for(capstart=i;;i++){if(!(isdigit(s[i])||s[i]==='*'||s[i]==='.')){break;}}}
while(s[i]){switch(s[i]){case'%':i++;if(parameterized<1){out+='%';break;}
switch(s[i++]){case'%':out+='%';break;case'r':if(seenr++===1){warn('saw %%r twice in %s',cap);}
break;case'm':if(seenm++===1){warn('saw %%m twice in %s',cap);}
break;case'n':if(seenn++===1){warn('saw %%n twice in %s',cap);}
break;case'i':out+='%i';break;case'6':case'B':getparm(param,1);out+='%{10}%/%{16}%*';getparm(param,1);out+='%{10}%m%+';break;case'8':case'D':getparm(param,2);out+='%{2}%*%-';break;case'>':getparm(param,2);out+='%?';i+=cvtchar(s);out+='%>%t';i+=cvtchar(s);out+='%+%;';break;case'a':if((s[i]==='='||s[i]==='+'||s[i]==='-'||s[i]==='*'||s[i]==='/')&&(s[i+1]==='p'||s[i+1]==='c')&&s[i+2]!=='\0'&&s[i+2]){var l;l=2;if(s[i]!=='='){getparm(param,1);}
if(s[i+1]==='p'){getparm(param+s[i+2].charCodeAt(0)-'@'.charCodeAt(0),1);if(param!==onstack){pop();param--;}
l++;}else{i+=2,l+=cvtchar(s),i-=2;}
switch(s[i]){case'+':out+='%+';break;case'-':out+='%-';break;case'*':out+='%*';break;case'/':out+='%/';break;case'=':if(seenr){if(param===1){onstack=2;}else if(param===2){onstack=1;}else{onstack=param;}}else{onstack=param;}
break;}
i+=l;break;}
getparm(param,1);i+=cvtchar(s);out+='%+';break;case'+':getparm(param,1);i+=cvtchar(s);out+='%+%c';pop();break;case's':getparm(param,1);out+='%s';pop();break;case'-':i+=cvtchar(s);getparm(param,1);out+='%-%c';pop();break;case'.':getparm(param,1);out+='%c';pop();break;case'0':if(s[i]==='3'){see03();break;}else if(s[i]!=='2'){invalid();break;}
case'2':getparm(param,1);out+='%2d';pop();break;case'3':see03();break;case'd':getparm(param,1);out+='%d';pop();break;case'f':param++;break;case'b':param--;break;case'\\':out+='%\\';break;default:invalid();break;}
break;default:out+=s[i++];break;}}
if(capstart!=null){out+='$<';for(i=capstart;;i++){if(isdigit(s[i])||s[i]==='*'||s[i]==='.'){out+=s[i];}else{break;}}
out+='/>';}
if(s!==out){warn('Translating %s from %s to %s.',cap,JSON.stringify(s),JSON.stringify(out));}
return out;};Tput.prototype.getAll=function(){var dir=this._prefix(),list=asort(fs.readdirSync(dir)),infos=[];list.forEach(function(letter){var terms=asort(fs.readdirSync(path.resolve(dir,letter)));infos.push.apply(infos,terms);});function asort(obj){return obj.sort(function(a,b){a=a.toLowerCase().charCodeAt(0);b=b.toLowerCase().charCodeAt(0);return a-b;});}
return infos;};Tput.prototype.compileAll=function(start){var self=this,all={};this.getAll().forEach(function(name){if(start&&name!==start){return;}else{start=null;}
all[name]=self.compileTerminfo(name);});return all;};Tput.prototype.detectFeatures=function(info){var data=this.parseACS(info);info.features={unicode:this.detectUnicode(info),brokenACS:this.detectBrokenACS(info),PCRomSet:this.detectPCRomSet(info),magicCookie:this.detectMagicCookie(info),padding:this.detectPadding(info),setbuf:this.detectSetbuf(info),acsc:data.acsc,acscr:data.acscr};return info.features;};Tput.prototype.detectUnicode=function(){if(this.options.forceUnicode!=null){return this.options.forceUnicode;}
var LANG=process.env.LANG
+':'+process.env.LANGUAGE
+':'+process.env.LC_ALL
+':'+process.env.LC_CTYPE;return/utf-?8/i.test(LANG)||(this.GetConsoleCP()===65001);};Tput.prototype.detectBrokenACS=function(info){if(process.env.NCURSES_NO_UTF8_ACS!=null){return!!+process.env.NCURSES_NO_UTF8_ACS;}
if(info.numbers.U8>=0){return!!info.numbers.U8;}
if(info.name==='linux'){return true;}
if(this.detectPCRomSet(info)){return true;}
if(this.termcap&&info.name.indexOf('screen')===0&&process.env.TERMCAP&&~process.env.TERMCAP.indexOf('screen')&&~process.env.TERMCAP.indexOf('hhII00')){if(~info.strings.enter_alt_charset_mode.indexOf('\016')||~info.strings.enter_alt_charset_mode.indexOf('\017')||~info.strings.set_attributes.indexOf('\016')||~info.strings.set_attributes.indexOf('\017')){return true;}}
return false;};Tput.prototype.detectPCRomSet=function(info){var s=info.strings;if(s.enter_pc_charset_mode&&s.enter_alt_charset_mode&&s.enter_pc_charset_mode===s.enter_alt_charset_mode&&s.exit_pc_charset_mode===s.exit_alt_charset_mode){return true;}
return false;};Tput.prototype.detectMagicCookie=function(){return process.env.NCURSES_NO_MAGIC_COOKIE==null;};Tput.prototype.detectPadding=function(){return process.env.NCURSES_NO_PADDING==null;};Tput.prototype.detectSetbuf=function(){return process.env.NCURSES_NO_SETBUF==null;};Tput.prototype.parseACS=function(info){var data={};data.acsc={};data.acscr={};if(this.detectPCRomSet(info)){return data;}
Object.keys(Tput.acsc).forEach(function(ch){var acs_chars=info.strings.acs_chars||'',i=acs_chars.indexOf(ch),next=acs_chars[i+1];if(!next||i===-1||!Tput.acsc[next]){return;}
data.acsc[ch]=Tput.acsc[next];data.acscr[Tput.acsc[next]]=ch;});return data;};Tput.prototype.GetConsoleCP=function(){var ccp;if(process.platform!=='win32'){return-1;}
if(+process.env.NCURSES_UNICODE!==0){return 65001;}
try{ccp=cp.execFileSync(process.env.WINDIR+'\\system32\\chcp.com',[],{stdio:['ignore','pipe','ignore'],encoding:'ascii',timeout:1500});}catch(e){;}
ccp=/\d+/.exec(ccp);if(!ccp){return-1;}
ccp=+ccp[0];return ccp;};function noop(){return'';}
noop.unsupported=true;function merge(a,b){Object.keys(b).forEach(function(key){a[key]=b[key];});return a;}
function write(data){return process.stdout.write(data);}
function tryRead(file){if(Array.isArray(file)){for(var i=0;i<file.length;i++){var data=tryRead(file[i]);if(data)return data;}
return'';}
if(!file)return'';file=path.resolve.apply(path,arguments);try{return fs.readFileSync(file,'utf8');}catch(e){return'';}}
function sprintf(src){var params=Array.prototype.slice.call(arguments,1),rule=/%([\-+# ]{1,4})?(\d+(?:\.\d+)?)?([doxXsc])/g,i=0;return src.replace(rule,function(_,flag,width,type){var flags=(flag||'').split(''),param=params[i]!=null?params[i]:'',initial=param,opt={},pre='';i++;switch(type){case'd':param=(+param).toString(10);break;case'o':param=(+param).toString(8);break;case'x':param=(+param).toString(16);break;case'X':param=(+param).toString(16).toUppercase();break;case's':break;case'c':param=isFinite(param)?String.fromCharCode(param||0200):'';break;}
flags.forEach(function(flag){switch(flag){case'-':opt.left=true;break;case'+':opt.signs=true;break;case'#':opt.hexpoint=true;break;case' ':opt.space=true;break;}});width=+width.split('.')[0];if(width&&!opt.left){param=param+'';while(param.length<width){param='0'+param;}}
if(opt.signs){if(+initial>=0){pre+='+';}}
if(opt.space){if(!opt.signs&&+initial>=0){pre+=' ';}}
if(opt.hexpoint){switch(type){case'o':pre+='0';break;case'x':pre+='0x';break;case'X':pre+='0X';break;}}
if(opt.left){if(width>(pre.length+param.length)){width-=pre.length+param.length;pre=Array(width+1).join(' ')+pre;}}
return pre+param;});}
Tput._alias=Require('term/alias');Tput.alias={};['bools','numbers','strings'].forEach(function(type){Object.keys(Tput._alias[type]).forEach(function(key){var aliases=Tput._alias[type][key];Tput.alias[key]=[aliases[0]];Tput.alias[key].terminfo=aliases[0];Tput.alias[key].termcap=aliases[1];});});Tput.alias.no_esc_ctlc.push('beehive_glitch');Tput.alias.dest_tabs_magic_smso.push('teleray_glitch');Tput.alias.micro_col_size.push('micro_char_size');Tput.aliasMap={};Object.keys(Tput.alias).forEach(function(key){Tput.aliasMap[key]=key;Tput.alias[key].forEach(function(k){Tput.aliasMap[k]=key;});});Tput.prototype.has=function(name){name=Tput.aliasMap[name];var val=this.all[name];if(!name)return false;if(typeof val==='number'){return val!==-1;}
return!!val;};Tput.termcap=''
+'vt102|dec vt102:'
+':do=^J:co#80:li#24:cl=50\\E[;H\\E[2J:'
+':le=^H:bs:cm=5\\E[%i%d;%dH:nd=2\\E[C:up=2\\E[A:'
+':ce=3\\E[K:cd=50\\E[J:so=2\\E[7m:se=2\\E[m:us=2\\E[4m:ue=2\\E[m:'
+':md=2\\E[1m:mr=2\\E[7m:mb=2\\E[5m:me=2\\E[m:is=\\E[1;24r\\E[24;1H:'
+':rs=\\E>\\E[?3l\\E[?4l\\E[?5l\\E[?7h\\E[?8h:ks=\\E[?1h\\E=:ke=\\E[?1l\\E>:'
+':ku=\\EOA:kd=\\EOB:kr=\\EOC:kl=\\EOD:kb=^H:\\\n'
+':ho=\\E[H:k1=\\EOP:k2=\\EOQ:k3=\\EOR:k4=\\EOS:pt:sr=5\\EM:vt#3:'
+':sc=\\E7:rc=\\E8:cs=\\E[%i%d;%dr:vs=\\E[?7l:ve=\\E[?7h:'
+':mi:al=\\E[L:dc=\\E[P:dl=\\E[M:ei=\\E[4l:im=\\E[4h:';Tput.bools=['auto_left_margin','auto_right_margin','no_esc_ctlc','ceol_standout_glitch','eat_newline_glitch','erase_overstrike','generic_type','hard_copy','has_meta_key','has_status_line','insert_null_glitch','memory_above','memory_below','move_insert_mode','move_standout_mode','over_strike','status_line_esc_ok','dest_tabs_magic_smso','tilde_glitch','transparent_underline','xon_xoff','needs_xon_xoff','prtr_silent','hard_cursor','non_rev_rmcup','no_pad_char','non_dest_scroll_region','can_change','back_color_erase','hue_lightness_saturation','col_addr_glitch','cr_cancels_micro_mode','has_print_wheel','row_addr_glitch','semi_auto_right_margin','cpi_changes_res','lpi_changes_res','backspaces_with_bs','crt_no_scrolling','no_correctly_working_cr','gnu_has_meta_key','linefeed_is_newline','has_hardware_tabs','return_does_clr_eol'];Tput.numbers=['columns','init_tabs','lines','lines_of_memory','magic_cookie_glitch','padding_baud_rate','virtual_terminal','width_status_line','num_labels','label_height','label_width','max_attributes','maximum_windows','max_colors','max_pairs','no_color_video','buffer_capacity','dot_vert_spacing','dot_horz_spacing','max_micro_address','max_micro_jump','micro_col_size','micro_line_size','number_of_pins','output_res_char','output_res_line','output_res_horz_inch','output_res_vert_inch','print_rate','wide_char_size','buttons','bit_image_entwining','bit_image_type','magic_cookie_glitch_ul','carriage_return_delay','new_line_delay','backspace_delay','horizontal_tab_delay','number_of_function_keys'];Tput.strings=['back_tab','bell','carriage_return','change_scroll_region','clear_all_tabs','clear_screen','clr_eol','clr_eos','column_address','command_character','cursor_address','cursor_down','cursor_home','cursor_invisible','cursor_left','cursor_mem_address','cursor_normal','cursor_right','cursor_to_ll','cursor_up','cursor_visible','delete_character','delete_line','dis_status_line','down_half_line','enter_alt_charset_mode','enter_blink_mode','enter_bold_mode','enter_ca_mode','enter_delete_mode','enter_dim_mode','enter_insert_mode','enter_secure_mode','enter_protected_mode','enter_reverse_mode','enter_standout_mode','enter_underline_mode','erase_chars','exit_alt_charset_mode','exit_attribute_mode','exit_ca_mode','exit_delete_mode','exit_insert_mode','exit_standout_mode','exit_underline_mode','flash_screen','form_feed','from_status_line','init_1string','init_2string','init_3string','init_file','insert_character','insert_line','insert_padding','key_backspace','key_catab','key_clear','key_ctab','key_dc','key_dl','key_down','key_eic','key_eol','key_eos','key_f0','key_f1','key_f10','key_f2','key_f3','key_f4','key_f5','key_f6','key_f7','key_f8','key_f9','key_home','key_ic','key_il','key_left','key_ll','key_npage','key_ppage','key_right','key_sf','key_sr','key_stab','key_up','keypad_local','keypad_xmit','lab_f0','lab_f1','lab_f10','lab_f2','lab_f3','lab_f4','lab_f5','lab_f6','lab_f7','lab_f8','lab_f9','meta_off','meta_on','newline','pad_char','parm_dch','parm_delete_line','parm_down_cursor','parm_ich','parm_index','parm_insert_line','parm_left_cursor','parm_right_cursor','parm_rindex','parm_up_cursor','pkey_key','pkey_local','pkey_xmit','print_screen','prtr_off','prtr_on','repeat_char','reset_1string','reset_2string','reset_3string','reset_file','restore_cursor','row_address','save_cursor','scroll_forward','scroll_reverse','set_attributes','set_tab','set_window','tab','to_status_line','underline_char','up_half_line','init_prog','key_a1','key_a3','key_b2','key_c1','key_c3','prtr_non','char_padding','acs_chars','plab_norm','key_btab','enter_xon_mode','exit_xon_mode','enter_am_mode','exit_am_mode','xon_character','xoff_character','ena_acs','label_on','label_off','key_beg','key_cancel','key_close','key_command','key_copy','key_create','key_end','key_enter','key_exit','key_find','key_help','key_mark','key_message','key_move','key_next','key_open','key_options','key_previous','key_print','key_redo','key_reference','key_refresh','key_replace','key_restart','key_resume','k
hex=exports.hexToRGB(hex);r1=hex[0],g1=hex[1],b1=hex[2];}else if(Array.isArray(r1)){b1=r1[2],g1=r1[1],r1=r1[0];}
var hash=(r1<<16)|(g1<<8)|b1;if(exports._cache[hash]!=null){return exports._cache[hash];}
var ldiff=Infinity,li=-1,i=0,c,r2,g2,b2,diff;for(;i<exports.vcolors.length;i++){c=exports.vcolors[i];r2=c[0];g2=c[1];b2=c[2];diff=colorDistance(r1,g1,b1,r2,g2,b2);if(diff===0){li=i;break;}
if(diff<ldiff){ldiff=diff;li=i;}}
return exports._cache[hash]=li;};exports.RGBToHex=function(r,g,b){if(Array.isArray(r)){b=r[2],g=r[1],r=r[0];}
function hex(n){n=n.toString(16);if(n.length<2)n='0'+n;return n;}
return'#'+hex(r)+hex(g)+hex(b);};exports.hexToRGB=function(hex){if(hex.length===4){hex=hex[0]
+hex[1]+hex[1]
+hex[2]+hex[2]
+hex[3]+hex[3];}
var col=parseInt(hex.substring(1),16),r=(col>>16)&0xff,g=(col>>8)&0xff,b=col&0xff;return[r,g,b];};function colorDistance(r1,g1,b1,r2,g2,b2){return Math.pow(30*(r1-r2),2)
+Math.pow(59*(g1-g2),2)
+Math.pow(11*(b1-b2),2);}
exports.mixColors=function(c1,c2,alpha){if(c1===0x1ff)c1=0;if(c2===0x1ff)c2=0;if(alpha==null)alpha=0.5;c1=exports.vcolors[c1];var r1=c1[0];var g1=c1[1];var b1=c1[2];c2=exports.vcolors[c2];var r2=c2[0];var g2=c2[1];var b2=c2[2];r1+=(r2-r1)*alpha|0;g1+=(g2-g1)*alpha|0;b1+=(b2-b1)*alpha|0;return exports.match([r1,g1,b1]);};exports.blend=function blend(attr,attr2,alpha){var name,i,c,nc;var bg=attr&0x1ff;if(attr2!=null){var bg2=attr2&0x1ff;if(bg===0x1ff)bg=0;if(bg2===0x1ff)bg2=0;bg=exports.mixColors(bg,bg2,alpha);}else{if(blend._cache[bg]!=null){bg=blend._cache[bg];}else if(bg>=8&&bg<=15){bg-=8;}else{name=exports.ncolors[bg];if(name){for(i=0;i<exports.ncolors.length;i++){if(name===exports.ncolors[i]&&i!==bg){c=exports.vcolors[bg];nc=exports.vcolors[i];if(nc[0]+nc[1]+nc[2]<c[0]+c[1]+c[2]){blend._cache[bg]=i;bg=i;break;}}}}}}
attr&=~0x1ff;attr|=bg;var fg=(attr>>9)&0x1ff;if(attr2!=null){var fg2=(attr2>>9)&0x1ff;if(fg===0x1ff){fg=248;}else{if(fg===0x1ff)fg=7;if(fg2===0x1ff)fg2=7;fg=exports.mixColors(fg,fg2,alpha);}}else{if(blend._cache[fg]!=null){fg=blend._cache[fg];}else if(fg>=8&&fg<=15){fg-=8;}else{name=exports.ncolors[fg];if(name){for(i=0;i<exports.ncolors.length;i++){if(name===exports.ncolors[i]&&i!==fg){c=exports.vcolors[fg];nc=exports.vcolors[i];if(nc[0]+nc[1]+nc[2]<c[0]+c[1]+c[2]){blend._cache[fg]=i;fg=i;break;}}}}}}
attr&=~(0x1ff<<9);attr|=fg<<9;return attr;};exports.blend._cache={};exports._cache={};exports.reduce=function(color,total){if(color>=16&&total<=16){color=exports.ccolors[color];}else if(color>=8&&total<=8){color-=8;}else if(color>=2&&total<=2){color%=2;}
return color;};exports.xterm=['#000000','#cd0000','#00cd00','#cdcd00','#0000ee','#cd00cd','#00cdcd','#e5e5e5','#7f7f7f','#ff0000','#00ff00','#ffff00','#5c5cff','#ff00ff','#00ffff','#ffffff'];exports.colors=(function(){var cols=exports.colors=[],_cols=exports.vcolors=[],r,g,b,i,l;function hex(n){n=n.toString(16);if(n.length<2)n='0'+n;return n;}
function push(i,r,g,b){cols[i]='#'+hex(r)+hex(g)+hex(b);_cols[i]=[r,g,b];}
exports.xterm.forEach(function(c,i){c=parseInt(c.substring(1),16);push(i,(c>>16)&0xff,(c>>8)&0xff,c&0xff);});for(r=0;r<6;r++){for(g=0;g<6;g++){for(b=0;b<6;b++){i=16+(r*36)+(g*6)+b;push(i,r?(r*40+55):0,g?(g*40+55):0,b?(b*40+55):0);}}}
for(g=0;g<24;g++){l=(g*10)+8;i=232+g;push(i,l,l,l);}
return cols;})();exports.ccolors=(function(){var _cols=exports.vcolors.slice(),cols=exports.colors.slice(),out;exports.vcolors=exports.vcolors.slice(0,8);exports.colors=exports.colors.slice(0,8);out=cols.map(exports.match);exports.colors=cols;exports.vcolors=_cols;exports.ccolors=out;return out;})();var colorNames=exports.colorNames={default:-1,normal:-1,bg:-1,fg:-1,black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,white:7,lightblack:8,lightred:9,lightgreen:10,lightyellow:11,lightblue:12,lightmagenta:13,lightcyan:14,lightwhite:15,brightblack:8,brightred:9,brightgreen:10,brightyellow:11,brightblue:12,brightmagenta:13,brightcyan:14,brightwhite:15,grey:8,gray:8,lightgrey:7,lightgray:7,brightgrey:7,brightgray:7};exports.convert=function(color){if(typeof color==='number'){;}else if(typeof color==='string'){color=color.replace(/[\- ]/g,'');if(colorNames[color]!=null){color=colorNames[color];}else{color=exports.match(color);}}else if(Array.isArray(color)){color=exports.match(color);}else{color=-1;}
return color!==-1?color:0x1ff;};exports.ccolors={blue:[4,12,[17,21],[24,27],[31,33],[38,39],45,[54,57],[60,63],[67,69],[74,75],81,[91,93],[97,99],[103,105],[110,111],117,[128,129],[134,135],[140,141],[146,147],153,165,171,177,183,189],green:[2,10,22,[28,29],[34,36],[40,43],[46,50],[64,65],[70,72],[76,79],[82,86],[106,108],[112,115],[118,122],[148,151],[154,158],[190,194]],cyan:[6,14,23,30,37,44,51,66,73,80,87,109,116,123,152,159,195],red:[1,9,52,[88,89],[94,95],[124,126],[130,132],[136,138],[160,163],[166,169],[172,175],[178,181],[196,200],[202,206],[208,212],[214,218],[220,224]],magenta:[5,13,53,90,96,127,133,139,164,170,176,182,201,207,213,219,225],yellow:[3,11,58,[100,101],[142,144],[184,187],[226,230]],black:[0,8,16,59,102,[232,243]],white:[7,15,145,188,231,[244,255]]};exports.ncolors=[];Object.keys(exports.ccolors).forEach(function(name){exports.ccolors[name].forEach(function(offset){if(typeof offset==='number'){exports.ncolors[offset]=name;exports.ccolors[offset]=exports.colorNames[name];return;}
for(var i=offset[0],l=offset[1];i<=l;i++){exports.ncolors[i]=name;exports.ccolors[i]=exports.colorNames[name];}});delete exports.ccolors[name];});};BundleModuleCode['term/keys']=function(module,exports){var EventEmitter=Require('events').EventEmitter;function listenerCount(stream,event){return EventEmitter.listenerCount?EventEmitter.listenerCount(stream,event):stream.listeners(event).length;}
function emitKeypressEvents(stream){if(stream._keypressDecoder)return;var StringDecoder=Require('string_decoder').StringDecoder;stream._keypressDecoder=new StringDecoder('utf8');function onData(b){if(listenerCount(stream,'keypress')>0){var r=stream._keypressDecoder.write(b);if(r)emitKeys(stream,r);}else{stream.removeListener('data',onData);stream.on('newListener',onNewListener);}}
function onNewListener(event){if(event==='keypress'){stream.on('data',onData);stream.removeListener('newListener',onNewListener);}}
if(listenerCount(stream,'keypress')>0){stream.on('data',onData);}else{stream.on('newListener',onNewListener);}}
exports.emitKeypressEvents=emitKeypressEvents;var metaKeyCodeReAnywhere=/(?:\x1b)([a-zA-Z0-9])/;var metaKeyCodeRe=new RegExp('^'+metaKeyCodeReAnywhere.source+'$');var functionKeyCodeReAnywhere=new RegExp('(?:\x1b+)(O|N|\\[|\\[\\[)(?:'+['(\\d+)(?:;(\\d+))?([~^$])','(?:M([@ #!a`])(.)(.))','(?:1;)?(\\d+)?([a-zA-Z])'].join('|')+')');var functionKeyCodeRe=new RegExp('^'+functionKeyCodeReAnywhere.source);var escapeCodeReAnywhere=new RegExp([functionKeyCodeReAnywhere.source,metaKeyCodeReAnywhere.source,/\x1b./.source].join('|'));function emitKeys(stream,s){if(Buffer.isBuffer(s)){if(s[0]>127&&s[1]===undefined){s[0]-=128;s='\x1b'+s.toString(stream.encoding||'utf-8');}else{s=s.toString(stream.encoding||'utf-8');}}
if(isMouse(s))return;var buffer=[];var match;while(match=escapeCodeReAnywhere.exec(s)){buffer=buffer.concat(s.slice(0,match.index).split(''));buffer.push(match[0]);s=s.slice(match.index+match[0].length);}
buffer=buffer.concat(s.split(''));buffer.forEach(function(s){var ch,key={sequence:s,name:undefined,ctrl:false,meta:false,shift:false},parts;if(s==='\r'){key.name='return';}else if(s==='\n'){key.name='enter';}else if(s==='\t'){key.name='tab';}else if(s==='\b'||s==='\x7f'||s==='\x1b\x7f'||s==='\x1b\b'){key.name='backspace';key.meta=(s.charAt(0)==='\x1b');}else if(s==='\x1b'||s==='\x1b\x1b'){key.name='escape';key.meta=(s.length===2);}else if(s===' '||s==='\x1b '){key.name='space';key.meta=(s.length===2);}else if(s.length===1&&s<='\x1a'){key.name=String.fromCharCode(s.charCodeAt(0)+'a'.charCodeAt(0)-1);key.ctrl=true;}else if(s.length===1&&s>='a'&&s<='z'){key.name=s;}else if(s.length===1&&s>='A'&&s<='Z'){key.name=s.toLowerCase();key.shift=true;}else if(parts=metaKeyCodeRe.exec(s)){key.name=parts[1].toLowerCase();key.meta=true;key.shift=/^[A-Z]$/.test(parts[1]);}else if(parts=functionKeyCodeRe.exec(s)){var code=(parts[1]||'')+(parts[2]||'')+
(parts[4]||'')+(parts[9]||''),modifier=(parts[3]||parts[8]||1)-1;key.ctrl=!!(modifier&4);key.meta=!!(modifier&10);key.shift=!!(modifier&1);key.code=code;switch(code){case'OP':key.name='f1';break;case'OQ':key.name='f2';break;case'OR':key.name='f3';break;case'OS':key.name='f4';break;case'[11~':key.name='f1';break;case'[12~':key.name='f2';break;case'[13~':key.name='f3';break;case'[14~':key.name='f4';break;case'[[A':key.name='f1';break;case'[[B':key.name='f2';break;case'[[C':key.name='f3';break;case'[[D':key.name='f4';break;case'[[E':key.name='f5';break;case'[15~':key.name='f5';break;case'[17~':key.name='f6';break;case'[18~':key.name='f7';break;case'[19~':key.name='f8';break;case'[20~':key.name='f9';break;case'[21~':key.name='f10';break;case'[23~':key.name='f11';break;case'[24~':key.name='f12';break;case'[A':key.name='up';break;case'[B':key.name='down';break;case'[C':key.name='right';break;case'[D':key.name='left';break;case'[E':key.name='clear';break;case'[F':key.name='end';break;case'[H':key.name='home';break;case'OA':key.name='up';break;case'OB':key.name='down';break;case'OC':key.name='right';break;case'OD':key.name='left';break;case'OE':key.name='clear';break;case'OF':key.name='end';break;case'OH':key.name='home';break;case'[1~':key.name='home';break;case'[2~':key.name='insert';break;case'[3~':key.name='delete';break;case'[4~':key.name='end';break;case'[5~':key.name='pageup';break;case'[6~':key.name='pagedown';break;case'[[5~':key.name='pageup';break;case'[[6~':key.name='pagedown';break;case'[7~':key.name='home';break;case'[8~':key.name='end';break;case'[a':key.name='up';key.shift=true;break;case'[b':key.name='down';key.shift=true;break;case'[c':key.name='right';key.shift=true;break;case'[d':key.name='left';key.shift=true;break;case'[e':key.name='clear';key.shift=true;break;case'[2$':key.name='insert';key.shift=true;break;case'[3$':key.name='delete';key.shift=true;break;case'[5$':key.name='pageup';key.shift=true;break;case'[6$':key.name='pagedown';key.shift=true;break;case'[7$':key.name='home';key.shift=true;break;case'[8$':key.name='end';key.shift=true;break;case'Oa':key.name='up';key.ctrl=true;break;case'Ob':key.name='down';key.ctrl=true;break;case'Oc':key.name='right';key.ctrl=true;break;case'Od':key.name='left';key.ctrl=true;break;case'Oe':key.name='clear';key.ctrl=true;break;case'[2^':key.name='insert';key.ctrl=true;break;case'[3^':key.name='delete';key.ctrl=true;break;case'[5^':key.name='pageup';key.ctrl=true;break;case'[6^':key.name='pagedown';key.ctrl=true;break;case'[7^':key.name='home';key.ctrl=true;break;case'[8^':key.name='end';key.ctrl=true;break;case'[Z':key.name='tab';key.shift=true;break;default:key.name='undefined';break;}}
if(key.name===undefined){key=undefined;}
if(s.length===1){ch=s;}
if(key||ch){stream.emit('keypress',ch,key);}});}
function isMouse(s){return/\x1b\[M/.test(s)||/\x1b\[M([\x00\u0020-\ufffe]{3})/.test(s)||/\x1b\[(\d+;\d+;\d+)M/.test(s)||/\x1b\[<(\d+;\d+;\d+)([mM])/.test(s)||/\x1b\[<(\d+;\d+;\d+;\d+)&w/.test(s)||/\x1b\[24([0135])~\[(\d+),(\d+)\]\r/.test(s)||/\x1b\[(O|I)/.test(s);}};BundleModuleCode['term/widget']=function(module,exports){var widget=exports;widget.classes=['Node','Screen','Element','Box','Chat','Text','Line','ScrollableBox','ScrollableText','BigText','List','Form','Input','Textarea','Textbox','Button','ProgressBar','FileManager','Checkbox','RadioSet','RadioButton','Prompt','Question','Message','Keyboard','Loading','Listbar','Log','Table','ListTable','Terminal','Image','ANSIImage','OverlayImage','Video','Layout','Log','Tree'];widget.classes.forEach(function(name){var file=name.toLowerCase();widget[name]=widget[file]=Require('term/widgets/'+file);});widget.aliases={'ListBar':'Listbar','PNG':'ANSIImage'};Object.keys(widget.aliases).forEach(function(key){var name=widget.aliases[key];widget[key]=widget[name];widget[key.toLowerCase()]=widget[name];});};BundleModuleCode['term/widgets/node']=function(module,exports){var Comp=Require('com/compat');var EventEmitter=Require('term/events').EventEmitter;function Node(options){var self=this;var Screen=Require('term/widgets/screen');if(!instanceOf(this,Node)){return new Node(options);}
EventEmitter.call(this);options=options||{};this.options=options;this.screen=this.screen||options.screen;if(!this.screen){if(this.type==='screen'){this.screen=this;}else if(Screen.total===1){this.screen=Screen.global;}else if(options.parent){this.screen=options.parent;while(this.screen&&this.screen.type!=='screen'){this.screen=this.screen.parent;}}else if(Screen.total){this.screen=Screen.instances[Screen.instances.length-1];process.nextTick(function(){if(!self.parent){throw new Error('Element ('+self.type+')'
+' was not appended synchronously after the'
+' screen\'s creation. Please set a `parent`'
+' or `screen` option in the element\'s constructor'
+' if you are going to use multiple screens and'
+' append the element later.');}});}else{throw new Error('No active screen.');}}
this.parent=options.parent||null;this.children=[];this.$=this._=this.data={};this.uid=Node.uid++;this.index=this.index!=null?this.index:-1;if(this.type!=='screen'){this.detached=true;}
if(this.parent){this.parent.append(this);}
(options.children||[]).forEach(this.append.bind(this));}
Node.uid=0;inheritPrototype(Node,EventEmitter);Node.prototype.type='node';Node.prototype.insert=function(element,i){var self=this;if(element.screen&&element.screen!==this.screen){throw new Error('Cannot switch a node\'s screen.');}
element.detach();element.parent=this;element.screen=this.screen;if(i===0){this.children.unshift(element);}else if(i===this.children.length){this.children.push(element);}else{this.children.splice(i,0,element);}
element.emit('reparent',this);this.emit('adopt',element);(function emit(el){var n=el.detached!==self.detached;el.detached=self.detached;if(n)el.emit('attach');el.children.forEach(emit);})(element);if(!this.screen.focused){this.screen.focused=element;}};Node.prototype.prepend=function(element){this.insert(element,0);};Node.prototype.append=function(element){this.insert(element,this.children.length);};Node.prototype.insertBefore=function(element,other){var i=this.children.indexOf(other);if(~i)this.insert(element,i);};Node.prototype.insertAfter=function(element,other){var i=this.children.indexOf(other);if(~i)this.insert(element,i+1);};Node.prototype.remove=function(element){if(element.parent!==this)return;var i=this.children.indexOf(element);if(!~i)return;element.clearPos();element.parent=null;this.children.splice(i,1);i=this.screen.clickable.indexOf(element);if(~i)this.screen.clickable.splice(i,1);i=this.screen.keyable.indexOf(element);if(~i)this.screen.keyable.splice(i,1);element.emit('reparent',null);this.emit('remove',element);(function emit(el){var n=el.detached!==true;el.detached=true;if(n)el.emit('detach');el.children.forEach(emit);})(element);if(this.screen.focused===element){this.screen.rewindFocus();}};Node.prototype.detach=function(){if(this.parent)this.parent.remove(this);};Node.prototype.free=function(){return;};Node.prototype.destroy=function(){this.detach();this.forDescendants(function(el){el.free();el.destroyed=true;el.emit('destroy');},this);};Node.prototype.forDescendants=function(iter,s){if(s)iter(this);this.children.forEach(function emit(el){iter(el);el.children.forEach(emit);});};Node.prototype.forAncestors=function(iter,s){var el=this;if(s)iter(this);while(el=el.parent){iter(el);}};Node.prototype.collectDescendants=function(s){var out=[];this.forDescendants(function(el){out.push(el);},s);return out;};Node.prototype.collectAncestors=function(s){var out=[];this.forAncestors(function(el){out.push(el);},s);return out;};Node.prototype.emitDescendants=function(){var args=Array.prototype.slice(arguments),iter;if(typeof args[args.length-1]==='function'){iter=args.pop();}
return this.forDescendants(function(el){if(iter)iter(el);el.emit.apply(el,args);},true);};Node.prototype.emitAncestors=function(){var args=Array.prototype.slice(arguments),iter;if(typeof args[args.length-1]==='function'){iter=args.pop();}
return this.forAncestors(function(el){if(iter)iter(el);el.emit.apply(el,args);},true);};Node.prototype.hasDescendant=function(target){return(function find(el){for(var i=0;i<el.children.length;i++){if(el.children[i]===target){return true;}
if(find(el.children[i])===true){return true;}}
return false;})(this);};Node.prototype.hasAncestor=function(target){var el=this;while(el=el.parent){if(el===target)return true;}
return false;};Node.prototype.get=function(name,value){if(this.data.hasOwnProperty(name)){return this.data[name];}
return value;};Node.prototype.set=function(name,value){return this.data[name]=value;};module.exports=Node;};BundleModuleCode['term/events']=function(module,exports){var slice=Array.prototype.slice;function EventEmitter(){if(!this._events)this._events={};}
EventEmitter.prototype.setMaxListeners=function(n){this._maxListeners=n;};EventEmitter.prototype.addListener=function(type,listener){if(!this._events[type]){this._events[type]=listener;}else if(typeof this._events[type]==='function'){this._events[type]=[this._events[type],listener];}else{this._events[type].push(listener);}
this._emit('newListener',[type,listener]);};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.removeListener=function(type,listener){var handler=this._events[type];if(!handler)return;if(typeof handler==='function'){if(!(handler===listener))return;delete this._events[type];this._emit('removeListener',[type,listener]);return;}
if(handler.length===1){if(!(handler[0]===listener))return;delete this._events[type];this._emit('removeListener',[type,listener]);return;}
for(var i=0;i<handler.length;i++){if(handler[i]===listener||handler[i].listener===listener){handler.splice(i,1);this._emit('removeListener',[type,listener]);return;}}};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function(type){if(type){delete this._events[type];}else{this._events={};}};EventEmitter.prototype.once=function(type,listener){function on(){this.removeListener(type,on);return listener.apply(this,arguments);}
on.listener=listener;return this.on(type,on);};EventEmitter.prototype.listeners=function(type){return typeof this._events[type]==='function'?[this._events[type]]:this._events[type]||[];};EventEmitter.prototype._emit=function(type,args){var handler=this._events[type],ret;if(!handler){if(type==='error'){throw new args[0];}
return;}
if(typeof handler==='function'){return handler.apply(this,args);}
for(var i=0;i<handler.length;i++){if(handler[i].apply(this,args)===false){ret=false;}}
return ret!==false;};EventEmitter.prototype.emit=function(type){var args=slice.call(arguments,1),params=slice.call(arguments),el=this;this._emit('event',params);if(this.type==='screen'){return this._emit(type,args);}
if(this._emit(type,args)===false){return false;}
type='element '+type;args.unshift(this);do{if(!el._events[type])continue;if(el._emit(type,args)===false){return false;}}while(el=el.parent);return true;};exports=EventEmitter;exports.EventEmitter=EventEmitter;module.exports=exports;};BundleModuleCode['term/widgets/screen']=function(module,exports){var Comp=Require('com/compat');var path=Require('path'),fs=Require('fs'),cp=Require('child_process');var colors=Require('term/colors'),program=Require('term/program'),unicode=Require('term/unicode');var nextTick=global.setImmediate||process.nextTick.bind(process);var helpers=Require('term/helpers');var Node=Require('term/widgets/node');var Log=Require('term/widgets/log');var Element=Require('term/widgets/element');var Box=Require('term/widgets/box');function Screen(options){var self=this;if(!instanceOf(this,Node)){return new Screen(options);}
Screen.bind(this);options=options||{};if(options.rsety&&options.listen){options={program:options};}
this.program=options.program;if(!this.program){this.program=program({input:options.input,output:options.output,log:options.log,debug:options.debug,dump:options.dump,terminal:options.terminal||options.term,resizeTimeout:options.resizeTimeout,forceUnicode:options.forceUnicode,tput:true,buffer:true,zero:true});}else{this.program.setupTput();this.program.useBuffer=true;this.program.zero=true;this.program.options.resizeTimeout=options.resizeTimeout;if(options.forceUnicode!=null){this.program.tput.features.unicode=options.forceUnicode;this.program.tput.unicode=options.forceUnicode;}}
this.tput=this.program.tput;Node.call(this,options);this.autoPadding=options.autoPadding!==false;this.tabc=Array((options.tabSize||4)+1).join(' ');this.dockBorders=options.dockBorders;this.forceCursor=options.forceCursor;this.ignoreLocked=options.ignoreLocked||[];this._unicode=this.tput.unicode||this.tput.numbers.U8===1;this.fullUnicode=this.options.fullUnicode&&this._unicode;this.dattr=((0<<18)|(0x1ff<<9))|0x1ff;this.renders=0;this.position={left:this.left=this.aleft=this.rleft=0,right:this.right=this.aright=this.rright=0,top:this.top=this.atop=this.rtop=0,bottom:this.bottom=this.abottom=this.rbottom=0,get height(){return self.height;},get width(){return self.width;}};this.ileft=0;this.itop=0;this.iright=0;this.ibottom=0;this.iheight=0;this.iwidth=0;this.padding={left:0,top:0,right:0,bottom:0};this.hover=null;this.history=[];this.clickable=[];this.keyable=[];this.grabKeys=false;this.lockKeys=false;this.focused;this._buf='';this._ci=-1;if(options.title){this.title=options.title;}
options.cursor=options.cursor||{artificial:options.artificialCursor,shape:options.cursorShape,blink:options.cursorBlink,color:options.cursorColor};this.cursor={artificial:options.cursor.artificial||false,shape:options.cursor.shape||'block',blink:options.cursor.blink||false,color:options.cursor.color||null,_set:false,_state:1,_hidden:true};this.program.on('resize',function(){self.alloc();self.render();(function emit(el){el.emit('resize');el.children.forEach(emit);})(self);});this.program.on('focus',function(){self.emit('focus');});this.program.on('blur',function(){self.emit('blur');});this.program.on('warning',function(text){self.emit('warning',text);});this.on('newListener',function fn(type){if(type==='keypress'||type.indexOf('key ')===0||type==='mouse'){if(type==='keypress'||type.indexOf('key ')===0)self._listenKeys();if(type==='mouse')self._listenMouse();}
if(type==='mouse'||type==='click'||type==='mouseover'||type==='mouseout'||type==='mousedown'||type==='mouseup'||type==='mousewheel'||type==='wheeldown'||type==='wheelup'||type==='mousemove'){self._listenMouse();}});this.setMaxListeners(Infinity);this.enter();this.postEnter();}
Screen.global=null;Screen.total=0;Screen.instances=[];Screen.bind=function(screen){if(!Screen.global){Screen.global=screen;}
if(!~Screen.instances.indexOf(screen)){Screen.instances.push(screen);screen.index=Screen.total;Screen.total++;}
if(Screen._bound)return;Screen._bound=true;process.on('uncaughtException',Screen._exceptionHandler=function(err){if(process.listeners('uncaughtException').length>1){return;}
Screen.instances.slice().forEach(function(screen){screen.destroy();});err=err||new Error('Uncaught Exception.');console.error(err.stack?err.stack+'':err+'');nextTick(function(){process.exit(1);});});['SIGTERM','SIGINT','SIGQUIT'].forEach(function(signal){var name='_'+signal.toLowerCase()+'Handler';process.on(signal,Screen[name]=function(){if(process.listeners(signal).length>1){return;}
nextTick(function(){process.exit(0);});});});process.on('exit',Screen._exitHandler=function(){Screen.instances.slice().forEach(function(screen){screen.destroy();});});};inheritPrototype(Screen,Node);Screen.prototype.type='screen';defineGetter(Screen,'title',function(){return this.program.title;});defineSetter(Screen,'title',function(title){return this.program.title=title;});defineGetter(Screen,'terminal',function(){return this.program.terminal;});defineSetter(Screen,'terminal',function(terminal){this.setTerminal(terminal);return this.program.terminal;});Screen.prototype.setTerminal=function(terminal){var entered=!!this.program.isAlt;if(entered){this._buf='';this.program._buf='';this.leave();}
this.program.setTerminal(terminal);this.tput=this.program.tput;if(entered){this.enter();}};Screen.prototype.enter=function(){if(this.program.isAlt)return;if(!this.cursor._set){if(this.options.cursor.shape){this.cursorShape(this.cursor.shape,this.cursor.blink);}
if(this.options.cursor.color){this.cursorColor(this.cursor.color);}}
if(process.platform==='win32'){try{cp.execSync('cls',{stdio:'ignore',timeout:1000});}catch(e){;}}
this.program.alternateBuffer();this.program.put.keypad_xmit();this.program.csr(0,this.height-1);this.program.hideCursor();this.program.cup(0,0);if(this.tput.strings.ena_acs){this.program._write(this.tput.enacs());}
this.alloc();};Screen.prototype.leave=function(){if(!this.program.isAlt)return;this.program.put.keypad_local();if(this.program.scrollTop!==0||this.program.scrollBottom!==this.rows-1){this.program.csr(0,this.height-1);}
this.program.showCursor();this.alloc();if(this._listenedMouse){this.program.disableMouse();}
this.program.normalBuffer();if(this.cursor._set)this.cursorReset();this.program.flush();if(process.platform==='win32'){try{cp.execSync('cls',{stdio:'ignore',timeout:1000});}catch(e){;}}};Screen.prototype.postEnter=function(){var self=this;if(this.options.debug){this.debugLog=new Log({screen:this,parent:this,hidden:true,draggable:true,left:'center',top:'center',width:'30%',height:'30%',border:'line',label:' {bold}Debug Log{/bold} ',tags:true,keys:true,vi:true,mouse:true,scrollbar:{ch:' ',track:{bg:'yellow'},style:{inverse:true}}});this.debugLog.toggle=function(){if(self.debugLog.hidden){self.saveFocus();self.debugLog.show();self.debugLog.setFront();self.debugLog.focus();}else{self.debugLog.hide();self.restoreFocus();}
self.render();};this.debugLog.key(['q','escape'],self.debugLog.toggle);this.key('f12',self.debugLog.toggle);}
if(this.options.warnings){this.on('warning',function(text){var warning=new Box({screen:self,parent:self,left:'center',top:'center',width:'shrink',padding:1,height:'shrink',align:'center',valign:'middle',border:'line',label:' {red-fg}{bold}WARNING{/} ',content:'{bold}'+text+'{/bold}',tags:true});self.render();var timeout=setTimeout(function(){warning.destroy();self.render();},1500);if(timeout.unref){timeout.unref();}});}};Screen.prototype._destroy=Screen.prototype.destroy;Screen.prototype.destroy=function(){if(!this.program)return;this.leave();var index=Screen.instances.indexOf(this);if(~index){Screen.instances.splice(index,1);Screen.total--;Screen.global=Screen.instances[0];if(Screen.total===0){Screen.global=null;process.removeListener('uncaughtException',Screen._exceptionHandler);process.removeListener('SIGTERM',Screen._sigtermHandler);process.removeListener('SIGINT',Screen._sigintHandler);process.removeListener('SIGQUIT',Screen._sigquitHandler);process.removeListener('exit',Screen._exitHandler);delete Screen._exceptionHandler;delete Screen._sigtermHandler;delete Screen._sigintHandler;delete Screen._sigquitHandler;delete Screen._exitHandler;delete Screen._bound;}
this.destroyed=true;this.emit('destroy');this._destroy();}
this.program.destroy();};Screen.prototype.log=function(){return this.program.log.apply(this.program,arguments);};Screen.prototype.debug=function(){if(this.debugLog){this.debugLog.log.apply(this.debugLog,arguments);}
return this.program.debug.apply(this.program,arguments);};Screen.prototype._listenMouse=function(el){var self=this;if(el&&!~this.clickable.indexOf(el)){el.clickable=true;this.clickable.push(el);}
if(this._listenedMouse)return;this._listenedMouse=true;this.program.enableMouse();if(this.options.sendFocus){this.program.setMouse({sendFocus:true},true);}
this.on('render',function(){self._needsClickableSort=true;});this.program.on('mouse',function(data){if(self.lockKeys)return;if(self._needsClickableSort){self.clickable=helpers.hsort(self.clickable);self._needsClickableSort=false;}
var i=0,el,set,pos;for(;i<self.clickable.length;i++){el=self.clickable[i];if(el.detached||!el.visible){continue;}
pos=el.lpos;if(!pos)continue;if(data.x>=pos.xi&&data.x<pos.xl&&data.y>=pos.yi&&data.y<pos.yl){el.emit('mouse',data);if(data.action==='mousedown'){self.mouseDown=el;}else if(data.action==='mouseup'){(self.mouseDown||el).emit('click',data);self.mouseDown=null;}else if(data.action==='mousemove'){if(self.hover&&el.index>self.hover.index){set=false;}
if(self.hover!==el&&!set){if(self.hover){self.hover.emit('mouseout',data);}
el.emit('mouseover',data);self.hover=el;}
set=true;}
el.emit(data.action,data);break;}}
if((data.action==='mousemove'||data.action==='mousedown'||data.action==='mouseup')&&self.hover&&!set){self.hover.emit('mouseout',data);self.hover=null;}
self.emit('mouse',data);self.emit(data.action,data);});this.on('element click',function(el){if(el.clickable===true&&el.options.autoFocus!==false){el.focus();}});};Screen.prototype.enableMouse=function(el){this._listenMouse(el);};Screen.prototype._listenKeys=function(el){var self=this;if(el&&!~this.keyable.indexOf(el)){el.keyable=true;this.keyable.push(el);}
if(this._listenedKeys)return;this._listenedKeys=true;this.program.on('keypress',function(ch,key){if(key.name=='tab'){self.program.hideCursor(self.forceCursor);var last=self.focused;var first=undefined;var next=undefined;for(var c in self.children){var child=self.children[c];if(first==undefined)first=child;if(last==undefined&&next==undefined&&child&&child.options&&child.options.focus)next=child;if(last&&child==last)last=undefined;if(last&&child[last.type]==last)last=undefined;}
if(!next)next=first;if(next)next.focus();self.render();return;}
if(self.lockKeys&&!~self.ignoreLocked.indexOf(key.full)){return;}
var focused=self.focused,grabKeys=self.grabKeys;if(!grabKeys||~self.ignoreLocked.indexOf(key.full)){self.emit('keypress',ch,key);self.emit('key '+key.full,ch,key);}
if(self.grabKeys!==grabKeys||self.lockKeys){return;}
if(focused&&focused.keyable){focused.emit('keypress',ch,key);focused.emit('key '+key.full,ch,key);}});};Screen.prototype.enableKeys=function(el){this._listenKeys(el);};Screen.prototype.enableInput=function(el){this._listenMouse(el);this._listenKeys(el);};Screen.prototype._initHover=function(){var self=this;if(this._hoverText){return;}
this._hoverText=new Box({screen:this,left:0,top:0,tags:false,height:'shrink',width:'shrink',border:'line',style:{border:{fg:'default'},bg:'default',fg:'default'}});this.on('mousemove',function(data){if(self._hoverText.detached)return;self._hoverText.rleft=data.x+1;self._hoverText.rtop=data.y;self.render();});this.on('element mouseover',function(el,data){if(!el._hoverOptions)return;self._hoverText.parseTags=el.parseTags;self._hoverText.setContent(el._hoverOptions.text);self.append(self._hoverText);self._hoverText.rleft=data.x+1;self._hoverText.rtop=data.y;self.render();});this.on('element mouseout',function(){if(self._hoverText.detached)return;self._hoverText.detach();self.render();});this.on('element mouseup',function(el){if(!self._hoverText.getContent())return;if(!el._hoverOptions)return;self.append(self._hoverText);self.render();});};Object.defineProperty(Screen.prototype,'cols',{get:function(){return this.program.cols;},});Object.defineProperty(Screen.prototype,'rows',{get:function(){return this.program.rows;},});Object.defineProperty(Screen.prototype,'width',{get:function(){return this.program.cols;},});Object.defineProperty(Screen.prototype,'height',{get:function(){return this.program.rows;},});Screen.prototype.alloc=function(dirty){var x,y;this.lines=[];for(y=0;y<this.rows;y++){this.lines[y]=[];for(x=0;x<this.cols;x++){this.lines[y][x]=[this.dattr,' '];}
this.lines[y].dirty=!!dirty;}
this.olines=[];for(y=0;y<this.rows;y++){this.olines[y]=[];for(x=0;x<this.cols;x++){this.olines[y][x]=[this.dattr,' '];}}
this.program.clear();};Screen.prototype.realloc=function(){return this.alloc(true);};Screen.prototype.render=function(){var self=this;if(this.destroyed)return;this.emit('prerender');this._borderStops={};this._ci=0;this.children.forEach(function(el){el.index=self._ci++;el.render();});this._ci=-1;if(this.screen.dockBorders){this._dockBorders();}
this.draw(0,this.lines.length-1);if(this.focused&&this.focused._updateCursor){this.focused._updateCursor(true);}
this.renders++;this.emit('render');};Screen.prototype.blankLine=function(ch,dirty){var out=[];for(var x=0;x<this.cols;x++){out[x]=[this.dattr,ch||' '];}
out.dirty=dirty;return out;};Screen.prototype.insertLine=function(n,y,top,bottom){if(!this.tput.strings.change_scroll_region||!this.tput.strings.delete_line||!this.tput.strings.insert_line)return;this._buf+=this.tput.csr(top,bottom);this._buf+=this.tput.cup(y,0);this._buf+=this.tput.il(n);this._buf+=this.tput.csr(0,this.height-1);var j=bottom+1;while(n--){this.lines.splice(y,0,this.blankLine());this.lines.splice(j,1);this.olines.splice(y,0,this.blankLine());this.olines.splice(j,1);}};Screen.prototype.deleteLine=function(n,y,top,bottom){if(!this.tput.strings.change_scroll_region||!this.tput.strings.delete_line||!this.tput.strings.insert_line)return;this._buf+=this.tput.csr(top,bottom);this._buf+=this.tput.cup(y,0);this._buf+=this.tput.dl(n);this._buf+=this.tput.csr(0,this.height-1);var j=bottom+1;while(n--){this.lines.splice(j,0,this.blankLine());this.lines.splice(y,1);this.olines.splice(j,0,this.blankLine());this.olines.splice(y,1);}};Screen.prototype.insertLineNC=function(n,y,top,bottom){if(!this.tput.strings.change_scroll_region||!this.tput.strings.delete_line)return;this._buf+=this.tput.csr(top,bottom);this._buf+=this.tput.cup(top,0);this._buf+=this.tput.dl(n);this._buf+=this.tput.csr(0,this.height-1);var j=bottom+1;while(n--){this.lines.splice(j,0,this.blankLine());this.lines.splice(y,1);this.olines.splice(j,0,this.blankLine());this.olines.splice(y,1);}};Screen.prototype.deleteLineNC=function(n,y,top,bottom){if(!this.tput.strings.change_scroll_region||!this.tput.strings.delete_line)return;this._buf+=this.tput.csr(top,bottom);this._buf+=this.tput.cup(bottom,0);this._buf+=Array(n+1).join('\n');this._buf+=this.tput.csr(0,this.height-1);var j=bottom+1;while(n--){this.lines.splice(j,0,this.blankLine());this.lines.splice(y,1);this.olines.splice(j,0,this.blankLine());this.olines.splice(y,1);}};Screen.prototype.insertBottom=function(top,bottom){return this.deleteLine(1,top,top,bottom);};Screen.prototype.insertTop=function(top,bottom){return this.insertLine(1,top,top,bottom);};Screen.prototype.deleteBottom=function(top,bottom){return this.clearRegion(0,this.width,bottom,bottom);};Screen.prototype.deleteTop=function(top,bottom){return this.deleteLine(1,top,top,bottom);};Screen.prototype.cleanSides=function(el){var pos=el.lpos;if(!pos){return false;}
if(pos._cleanSides!=null){return pos._cleanSides;}
if(pos.xi<=0&&pos.xl>=this.width){return pos._cleanSides=true;}
if(this.options.fastCSR){if(pos.yi<0)return pos._cleanSides=false;if(pos.yl>this.height)return pos._cleanSides=false;if(this.width-(pos.xl-pos.xi)<40){return pos._cleanSides=true;}
return pos._cleanSides=false;}
if(!this.options.smartCSR){return false;}
var yi=pos.yi+el.itop,yl=pos.yl-el.ibottom,first,ch,x,y;if(pos.yi<0)return pos._cleanSides=false;if(pos.yl>this.height)return pos._cleanSides=false;if(pos.xi-1<0)return pos._cleanSides=true;if(pos.xl>this.width)return pos._cleanSides=true;for(x=pos.xi-1;x>=0;x--){if(!this.olines[yi])break;first=this.olines[yi][x];for(y=yi;y<yl;y++){if(!this.olines[y]||!this.olines[y][x])break;ch=this.olines[y][x];if(ch[0]!==first[0]||ch[1]!==first[1]){return pos._cleanSides=false;}}}
for(x=pos.xl;x<this.width;x++){if(!this.olines[yi])break;first=this.olines[yi][x];for(y=yi;y<yl;y++){if(!this.olines[y]||!this.olines[y][x])break;ch=this.olines[y][x];if(ch[0]!==first[0]||ch[1]!==first[1]){return pos._cleanSides=false;}}}
return pos._cleanSides=true;};Screen.prototype._dockBorders=function(){var lines=this.lines,stops=this._borderStops,i,y,x,ch;stops=Object.keys(stops).map(function(k){return+k;}).sort(function(a,b){return a-b;});for(i=0;i<stops.length;i++){y=stops[i];if(!lines[y])continue;for(x=0;x<this.width;x++){ch=lines[y][x][1];if(angles[ch]){lines[y][x][1]=this._getAngle(lines,x,y);lines[y].dirty=true;}}}};Screen.prototype._getAngle=function(lines,x,y){var angle=0,attr=lines[y][x][0],ch=lines[y][x][1];if(lines[y][x-1]&&langles[lines[y][x-1][1]]){if(!this.options.ignoreDockContrast){if(lines[y][x-1][0]!==attr)return ch;}
angle|=1<<3;}
if(lines[y-1]&&uangles[lines[y-1][x][1]]){if(!this.options.ignoreDockContrast){if(lines[y-1][x][0]!==attr)return ch;}
angle|=1<<2;}
if(lines[y][x+1]&&rangles[lines[y][x+1][1]]){if(!this.options.ignoreDockContrast){if(lines[y][x+1][0]!==attr)return ch;}
angle|=1<<1;}
if(lines[y+1]&&dangles[lines[y+1][x][1]]){if(!this.options.ignoreDockContrast){if(lines[y+1][x][0]!==attr)return ch;}
angle|=1<<0;}
return angleTable[angle]||ch;};Screen.prototype.draw=function(start,end){var x,y,line,out,ch,data,attr,fg,bg,flags;var main='',pre,post;var clr,neq,xx;var lx=-1,ly=-1,o;var acs;if(this._buf){main+=this._buf;this._buf='';}
for(y=start;y<=end;y++){line=this.lines[y];o=this.olines[y];if(!line.dirty&&!(this.cursor.artificial&&y===this.program.y)){continue;}
line.dirty=false;out='';attr=this.dattr;for(x=0;x<line.length;x++){data=line[x][0];ch=line[x][1];if(this.cursor.artificial&&!this.cursor._hidden&&this.cursor._state&&x===this.program.x&&y===this.program.y){var cattr=this._cursorAttr(this.cursor,data);if(cattr.ch)ch=cattr.ch;data=cattr.attr;}
if(this.options.useBCE&&ch===' '&&(this.tput.bools.back_color_erase||(data&0x1ff)===(this.dattr&0x1ff))&&((data>>18)&8)===((this.dattr>>18)&8)){clr=true;neq=false;for(xx=x;xx<line.length;xx++){if(line[xx][0]!==data||line[xx][1]!==' '){clr=false;break;}
if(line[xx][0]!==o[xx][0]||line[xx][1]!==o[xx][1]){neq=true;}}
if(clr&&neq){lx=-1,ly=-1;if(data!==attr){out+=this.codeAttr(data);attr=data;}
out+=this.tput.cup(y,x);out+=this.tput.el();for(xx=x;xx<line.length;xx++){o[xx][0]=data;o[xx][1]=' ';}
break;}}
if(data===o[x][0]&&ch===o[x][1]){if(lx===-1){lx=x;ly=y;}
continue;}else if(lx!==-1){if(this.tput.strings.parm_right_cursor){out+=y===ly?this.tput.cuf(x-lx):this.tput.cup(y,x);}else{out+=this.tput.cup(y,x);}
lx=-1,ly=-1;}
o[x][0]=data;o[x][1]=ch;if(data!==attr){if(attr!==this.dattr){out+='\x1b[m';}
if(data!==this.dattr){out+='\x1b[';bg=data&0x1ff;fg=(data>>9)&0x1ff;flags=data>>18;if(flags&1){out+='1;';}
if(flags&2){out+='4;';}
if(flags&4){out+='5;';}
if(flags&8){out+='7;';}
if(flags&16){out+='8;';}
if(bg!==0x1ff){bg=this._reduceColor(bg);if(bg<16){if(bg<8){bg+=40;}else if(bg<16){bg-=8;bg+=100;}
out+=bg+';';}else{out+='48;5;'+bg+';';}}
if(fg!==0x1ff){fg=this._reduceColor(fg);if(fg<16){if(fg<8){fg+=30;}else if(fg<16){fg-=8;fg+=90;}
out+=fg+';';}else{out+='38;5;'+fg+';';}}
if(out[out.length-1]===';')out=out.slice(0,-1);out+='m';}}
if(this.fullUnicode){if(unicode.charWidth(line[x][1])===2){if(x===line.length-1||angles[line[x+1][1]]){ch=' ';o[x][1]='\0';}else{o[x][1]='\0';o[++x][1]='\0';}}}
if(this.tput.strings.enter_alt_charset_mode&&!this.tput.brokenACS&&(this.tput.acscr[ch]||acs)){if(this.tput.acscr[ch]){if(acs){ch=this.tput.acscr[ch];}else{ch=this.tput.smacs()
+this.tput.acscr[ch];acs=true;}}else if(acs){ch=this.tput.rmacs()+ch;acs=false;}}else{if(!this.tput.unicode&&this.tput.numbers.U8!==1&&ch>'~'){ch=this.tput.utoa[ch]||'?';}}
out+=ch;attr=data;}
if(attr!==this.dattr){out+='\x1b[m';}
if(out){main+=this.tput.cup(y,0)+out;}}
if(acs){main+=this.tput.rmacs();acs=false;}
if(main){pre='';post='';pre+=this.tput.sc();post+=this.tput.rc();if(!this.program.cursorHidden){pre+=this.tput.civis();post+=this.tput.cnorm();}
this.program._write(pre+main+post);}};Screen.prototype._reduceColor=function(color){return colors.reduce(color,this.tput.colors);};Screen.prototype.attrCode=function(code,cur,def){var flags=(cur>>18)&0x1ff,fg=(cur>>9)&0x1ff,bg=cur&0x1ff,c,i;code=code.slice(2,-1).split(';');if(!code[0])code[0]='0';for(i=0;i<code.length;i++){c=+code[i]||0;switch(c){case 0:bg=def&0x1ff;fg=(def>>9)&0x1ff;flags=(def>>18)&0x1ff;break;case 1:flags|=1;break;case 22:flags=(def>>18)&0x1ff;break;case 4:flags|=2;break;case 24:flags=(def>>18)&0x1ff;break;case 5:flags|=4;break;case 25:flags=(def>>18)&0x1ff;break;case 7:flags|=8;break;case 27:flags=(def>>18)&0x1ff;break;case 8:flags|=16;break;case 28:flags=(def>>18)&0x1ff;break;case 39:fg=(def>>9)&0x1ff;break;case 49:bg=def&0x1ff;break;case 100:fg=(def>>9)&0x1ff;bg=def&0x1ff;break;default:if(c===48&&+code[i+1]===5){i+=2;bg=+code[i];break;}else if(c===48&&+code[i+1]===2){i+=2;bg=colors.match(+code[i],+code[i+1],+code[i+2]);if(bg===-1)bg=def&0x1ff;i+=2;break;}else if(c===38&&+code[i+1]===5){i+=2;fg=+code[i];break;}else if(c===38&&+code[i+1]===2){i+=2;fg=colors.match(+code[i],+code[i+1],+code[i+2]);if(fg===-1)fg=(def>>9)&0x1ff;i+=2;break;}
if(c>=40&&c<=47){bg=c-40;}else if(c>=100&&c<=107){bg=c-100;bg+=8;}else if(c===49){bg=def&0x1ff;}else if(c>=30&&c<=37){fg=c-30;}else if(c>=90&&c<=97){fg=c-90;fg+=8;}else if(c===39){fg=(def>>9)&0x1ff;}else if(c===100){fg=(def>>9)&0x1ff;bg=def&0x1ff;}
break;}}
return(flags<<18)|(fg<<9)|bg;};Screen.prototype.codeAttr=function(code){var flags=(code>>18)&0x1ff,fg=(code>>9)&0x1ff,bg=code&0x1ff,out='';if(flags&1){out+='1;';}
if(flags&2){out+='4;';}
if(flags&4){out+='5;';}
if(flags&8){out+='7;';}
if(flags&16){out+='8;';}
if(bg!==0x1ff){bg=this._reduceColor(bg);if(bg<16){if(bg<8){bg+=40;}else if(bg<16){bg-=8;bg+=100;}
out+=bg+';';}else{out+='48;5;'+bg+';';}}
if(fg!==0x1ff){fg=this._reduceColor(fg);if(fg<16){if(fg<8){fg+=30;}else if(fg<16){fg-=8;fg+=90;}
out+=fg+';';}else{out+='38;5;'+fg+';';}}
if(out[out.length-1]===';')out=out.slice(0,-1);return'\x1b['+out+'m';};Screen.prototype.focusOffset=function(offset){var shown=this.keyable.filter(function(el){return!el.detached&&el.visible;}).length;if(!shown||!offset){return;}
var i=this.keyable.indexOf(this.focused);if(!~i)return;if(offset>0){while(offset--){if(++i>this.keyable.length-1)i=0;if(this.keyable[i].detached||!this.keyable[i].visible)offset++;}}else{offset=-offset;while(offset--){if(--i<0)i=this.keyable.length-1;if(this.keyable[i].detached||!this.keyable[i].visible)offset++;}}
return this.keyable[i].focus();};Screen.prototype.focusPrev=Screen.prototype.focusPrevious=function(){return this.focusOffset(-1);};Screen.prototype.focusNext=function(){return this.focusOffset(1);};Screen.prototype.focusPush=function(el){if(!el)return;var old=this.history[this.history.length-1];if(this.history.length===10){this.history.shift();}
this.history.push(el);this._focus(el,old);};Screen.prototype.focusPop=function(){var old=this.history.pop();if(this.history.length){this._focus(this.history[this.history.length-1],old);}
return old;};Screen.prototype.saveFocus=function(){return this._savedFocus=this.focused;};Screen.prototype.restoreFocus=function(){if(!this._savedFocus)return;this._savedFocus.focus();delete this._savedFocus;return this.focused;};Screen.prototype.rewindFocus=function(){var old=this.history.pop(),el;while(this.history.length){el=this.history.pop();if(!el.detached&&el.visible){this.history.push(el);this._focus(el,old);return el;}}
if(old){old.emit('blur');}};Screen.prototype._focus=function(self,old){var el=self;while(el=el.parent){if(el.scrollable)break;}
if(el&&!el.detached){var visible=self.screen.height-el.atop-el.itop-el.abottom-el.ibottom;if(self.rtop<el.childBase){el.scrollTo(self.rtop);self.screen.render();}else if(self.rtop+self.height-self.ibottom>el.childBase+visible){el.scrollTo(self.rtop-(el.height-self.height)+el.itop,true);self.screen.render();}}
if(old){old.emit('blur',self);}
self.emit('focus',old);};Object.defineProperty(Screen.prototype,'focused',{get:function(){return this.history[this.history.length-1];},set:function(el){return this.focusPush(el);}});Screen.prototype.clearRegion=function(xi,xl,yi,yl,override){return this.fillRegion(this.dattr,' ',xi,xl,yi,yl,override);};Screen.prototype.fillRegion=function(attr,ch,xi,xl,yi,yl,override){var lines=this.lines,cell,xx;if(xi<0)xi=0;if(yi<0)yi=0;for(;yi<yl;yi++){if(!lines[yi])break;for(xx=xi;xx<xl;xx++){cell=lines[yi][xx];if(!cell)break;if(override||attr!==cell[0]||ch!==cell[1]){lines[yi][xx][0]=attr;lines[yi][xx][1]=ch;lines[yi].dirty=true;}}}};Screen.prototype.key=function(){return this.program.key.apply(this,arguments);};Screen.prototype.onceKey=function(){return this.program.onceKey.apply(this,arguments);};Screen.prototype.unkey=Screen.prototype.removeKey=function(){return this.program.unkey.apply(this,arguments);};Screen.prototype.spawn=function(file,args,options){if(!Array.isArray(args)){options=args;args=[];}
var screen=this,program=screen.program,spawn=require('child_process').spawn,mouse=program.mouseEnabled,ps;options=options||{};options.stdio=options.stdio||'inherit';program.lsaveCursor('spawn');program.normalBuffer();program.showCursor();if(mouse)program.disableMouse();var write=program.output.write;program.output.write=function(){};program.input.pause();if(program.input.setRawMode){program.input.setRawMode(false);}
var resume=function(){if(resume.done)return;resume.done=true;if(program.input.setRawMode){program.input.setRawMode(true);}
program.input.resume();program.output.write=write;program.alternateBuffer();if(mouse){program.enableMouse();if(screen.options.sendFocus){screen.program.setMouse({sendFocus:true},true);}}
screen.alloc();screen.render();screen.program.lrestoreCursor('spawn',true);};ps=spawn(file,args,options);ps.on('error',resume);ps.on('exit',resume);return ps;};Screen.prototype.exec=function(file,args,options,callback){var ps=this.spawn(file,args,options);ps.on('error',function(err){if(!callback)return;return callback(err,false);});ps.on('exit',function(code){if(!callback)return;return callback(null,code===0);});return ps;};Screen.prototype.readEditor=function(options,callback){if(typeof options==='string'){options={editor:options};}
if(!callback){callback=options;options=null;}
if(!callback){callback=function(){};}
options=options||{};var self=this,editor=options.editor||process.env.EDITOR||'vi',name=options.name||process.title||'blessed',rnd=Math.random().toString(36).split('.').pop(),file='/tmp/'+name+'.'+rnd,args=[file],opt;opt={stdio:'inherit',env:process.env,cwd:process.env.HOME};function writeFile(callback){if(!options.value)return callback();return fs.writeFile(file,options.value,callback);}
return writeFile(function(err){if(err)return callback(err);return self.exec(editor,args,opt,function(err,success){if(err)return callback(err);return fs.readFile(file,'utf8',function(err,data){return fs.unlink(file,function(){if(!success)return callback(new Error('Unsuccessful.'));if(err)return callback(err);return callback(null,data);});});});});};Screen.prototype.displayImage=function(file,callback){if(!file){if(!callback)return;return callback(new Error('No image.'));}
file=path.resolve(process.cwd(),file);if(!~file.indexOf('://')){file='file://'+file;}
var args=['w3m','-T','text/html'];var input='<title>press q to exit</title>'
+'<img align="center" src="'+file+'">';var opt={stdio:['pipe',1,2],env:process.env,cwd:process.env.HOME};var ps=this.spawn(args[0],args.slice(1),opt);ps.on('error',function(err){if(!callback)return;return callback(err);});ps.on('exit',function(code){if(!callback)return;if(code!==0)return callback(new Error('Exit Code: '+code));return callback(null,code===0);});ps.stdin.write(input+'\n');ps.stdin.end();};Screen.prototype.setEffects=function(el,fel,over,out,effects,temp){if(!effects)return;var tmp={};if(temp)el[temp]=tmp;if(typeof el!=='function'){var _el=el;el=function(){return _el;};}
fel.on(over,function(){var element=el();Object.keys(effects).forEach(function(key){var val=effects[key];if(val!==null&&typeof val==='object'){tmp[key]=tmp[key]||{};Object.keys(val).forEach(function(k){var v=val[k];tmp[key][k]=element.style[key][k];element.style[key][k]=v;});return;}
tmp[key]=element.style[key];element.style[key]=val;});element.screen.render();});fel.on(out,function(){var element=el();Object.keys(effects).forEach(function(key){var val=effects[key];if(val!==null&&typeof val==='object'){tmp[key]=tmp[key]||{};Object.keys(val).forEach(function(k){if(tmp[key].hasOwnProperty(k)){element.style[key][k]=tmp[key][k];}});return;}
if(tmp.hasOwnProperty(key)){element.style[key]=tmp[key];}});element.screen.render();});};Screen.prototype.sigtstp=function(callback){var self=this;this.program.sigtstp(function(){self.alloc();self.render();self.program.lrestoreCursor('pause',true);if(callback)callback();});};Screen.prototype.copyToClipboard=function(text){return this.program.copyToClipboard(text);};Screen.prototype.cursorShape=function(shape,blink){var self=this;this.cursor.shape=shape||'block';this.cursor.blink=blink||false;this.cursor._set=true;if(this.cursor.artificial){if(!this.program.hideCursor_old){var hideCursor=this.program.hideCursor;this.program.hideCursor_old=this.program.hideCursor;this.program.hideCursor=function(){hideCursor.call(self.program);self.cursor._hidden=true;if(self.renders)self.render();};}
if(!this.program.showCursor_old){var showCursor=this.program.showCursor;this.program.showCursor_old=this.program.showCursor;this.program.showCursor=function(){self.cursor._hidden=false;if(self.program._exiting)showCursor.call(self.program);if(self.renders)self.render();};}
if(!this._cursorBlink){this._cursorBlink=setInterval(function(){if(!self.cursor.blink)return;self.cursor._state^=1;if(self.renders)self.render();},500);if(this._cursorBlink.unref){this._cursorBlink.unref();}}
return true;}
return this.program.cursorShape(this.cursor.shape,this.cursor.blink);};Screen.prototype.cursorColor=function(color){this.cursor.color=color!=null?colors.convert(color):null;this.cursor._set=true;if(this.cursor.artificial){return true;}
return this.program.cursorColor(colors.ncolors[this.cursor.color]);};Screen.prototype.cursorReset=Screen.prototype.resetCursor=function(){this.cursor.shape='block';this.cursor.blink=false;this.cursor.color=null;this.cursor._set=false;if(this.cursor.artificial){this.cursor.artificial=false;if(this.program.hideCursor_old){this.program.hideCursor=this.program.hideCursor_old;delete this.program.hideCursor_old;}
if(this.program.showCursor_old){this.program.showCursor=this.program.showCursor_old;delete this.program.showCursor_old;}
if(this._cursorBlink){clearInterval(this._cursorBlink);delete this._cursorBlink;}
return true;}
return this.program.cursorReset();};Screen.prototype._cursorAttr=function(cursor,dattr){var attr=dattr||this.dattr,cattr,ch;if(cursor.shape==='line'){attr&=~(0x1ff<<9);attr|=7<<9;ch='\u2502';}else if(cursor.shape==='underline'){attr&=~(0x1ff<<9);attr|=7<<9;attr|=2<<18;}else if(cursor.shape==='block'){attr&=~(0x1ff<<9);attr|=7<<9;attr|=8<<18;}else if(typeof cursor.shape==='object'&&cursor.shape){cattr=Element.prototype.sattr.call(cursor,cursor.shape);if(cursor.shape.bold||cursor.shape.underline||cursor.shape.blink||cursor.shape.inverse||cursor.shape.invisible){attr&=~(0x1ff<<18);attr|=((cattr>>18)&0x1ff)<<18;}
if(cursor.shape.fg){attr&=~(0x1ff<<9);attr|=((cattr>>9)&0x1ff)<<9;}
if(cursor.shape.bg){attr&=~(0x1ff<<0);attr|=cattr&0x1ff;}
if(cursor.shape.ch){ch=cursor.shape.ch;}}
if(cursor.color!=null){attr&=~(0x1ff<<9);attr|=cursor.color<<9;}
return{ch:ch,attr:attr};};Screen.prototype.screenshot=function(xi,xl,yi,yl,term){if(xi==null)xi=0;if(xl==null)xl=this.cols;if(yi==null)yi=0;if(yl==null)yl=this.rows;if(xi<0)xi=0;if(yi<0)yi=0;var x,y,line,out,ch,data,attr;var sdattr=this.dattr;if(term){this.dattr=term.defAttr;}
var main='';for(y=yi;y<yl;y++){line=term?term.lines[y]:this.lines[y];if(!line)break;out='';attr=this.dattr;for(x=xi;x<xl;x++){if(!line[x])break;data=line[x][0];ch=line[x][1];if(data!==attr){if(attr!==this.dattr){out+='\x1b[m';}
if(data!==this.dattr){var _data=data;if(term){if(((_data>>9)&0x1ff)===257)_data|=0x1ff<<9;if((_data&0x1ff)===256)_data|=0x1ff;}
out+=this.codeAttr(_data);}}
if(this.fullUnicode){if(unicode.charWidth(line[x][1])===2){if(x===xl-1){ch=' ';}else{x++;}}}
out+=ch;attr=data;}
if(attr!==this.dattr){out+='\x1b[m';}
if(out){main+=(y>0?'\n':'')+out;}}
main=main.replace(/(?:\s*\x1b\[40m\s*\x1b\[m\s*)*$/,'')+'\n';if(term){this.dattr=sdattr;}
return main;};Screen.prototype._getPos=function(){return this;};var angles={'\u2518':true,'\u2510':true,'\u250c':true,'\u2514':true,'\u253c':true,'\u251c':true,'\u2524':true,'\u2534':true,'\u252c':true,'\u2502':true,'\u2500':true};var langles={'\u250c':true,'\u2514':true,'\u253c':true,'\u251c':true,'\u2534':true,'\u252c':true,'\u2500':true};var uangles={'\u2510':true,'\u250c':true,'\u253c':true,'\u251c':true,'\u2524':true,'\u252c':true,'\u2502':true};var rangles={'\u2518':true,'\u2510':true,'\u253c':true,'\u2524':true,'\u2534':true,'\u252c':true,'\u2500':true};var dangles={'\u2518':true,'\u2514':true,'\u253c':true,'\u251c':true,'\u2524':true,'\u2534':true,'\u2502':true};var angleTable={'0000':'','0001':'\u2502','0010':'\u2500','0011':'\u250c','0100':'\u2502','0101':'\u2502','0110':'\u2514','0111':'\u251c','1000':'\u2500','1001':'\u2510','1010':'\u2500','1011':'\u252c','1100':'\u2518','1101':'\u2524','1110':'\u2534','1111':'\u253c'};Object.keys(angleTable).forEach(function(key){angleTable[parseInt(key,2)]=angleTable[key];delete angleTable[key];});module.exports=Screen;};BundleModuleCode['term/unicode']=function(module,exports){var stringFromCharCode=String.fromCharCode;var floor=Math.floor;exports.charWidth=function(str,i){var point=typeof str!=='number'?exports.codePointAt(str,i||0):str;if(point===0)return 0;if(point===0x09){if(!exports.blessed){}
return exports.blessed.screen.global?exports.blessed.screen.global.tabc.length:8;}
if(point<32||(point>=0x7f&&point<0xa0)){return 0;}
if(exports.combining[point]){return 0;}
if((0x3000===point)||(0xFF01<=point&&point<=0xFF60)||(0xFFE0<=point&&point<=0xFFE6)){return 2;}
if((0x1100<=point&&point<=0x115F)||(0x11A3<=point&&point<=0x11A7)||(0x11FA<=point&&point<=0x11FF)||(0x2329<=point&&point<=0x232A)||(0x2E80<=point&&point<=0x2E99)||(0x2E9B<=point&&point<=0x2EF3)||(0x2F00<=point&&point<=0x2FD5)||(0x2FF0<=point&&point<=0x2FFB)||(0x3001<=point&&point<=0x303E)||(0x3041<=point&&point<=0x3096)||(0x3099<=point&&point<=0x30FF)||(0x3105<=point&&point<=0x312D)||(0x3131<=point&&point<=0x318E)||(0x3190<=point&&point<=0x31BA)||(0x31C0<=point&&point<=0x31E3)||(0x31F0<=point&&point<=0x321E)||(0x3220<=point&&point<=0x3247)||(0x3250<=point&&point<=0x32FE)||(0x3300<=point&&point<=0x4DBF)||(0x4E00<=point&&point<=0xA48C)||(0xA490<=point&&point<=0xA4C6)||(0xA960<=point&&point<=0xA97C)||(0xAC00<=point&&point<=0xD7A3)||(0xD7B0<=point&&point<=0xD7C6)||(0xD7CB<=point&&point<=0xD7FB)||(0xF900<=point&&point<=0xFAFF)||(0xFE10<=point&&point<=0xFE19)||(0xFE30<=point&&point<=0xFE52)||(0xFE54<=point&&point<=0xFE66)||(0xFE68<=point&&point<=0xFE6B)||(0x1B000<=point&&point<=0x1B001)||(0x1F200<=point&&point<=0x1F202)||(0x1F210<=point&&point<=0x1F23A)||(0x1F240<=point&&point<=0x1F248)||(0x1F250<=point&&point<=0x1F251)||(0x20000<=point&&point<=0x2F73F)||(0x2B740<=point&&point<=0x2FFFD)||(0x30000<=point&&point<=0x3FFFD)){return 2;}
if(process.env.NCURSES_CJK_WIDTH){if((0x00A1===point)||(0x00A4===point)||(0x00A7<=point&&point<=0x00A8)||(0x00AA===point)||(0x00AD<=point&&point<=0x00AE)||(0x00B0<=point&&point<=0x00B4)||(0x00B6<=point&&point<=0x00BA)||(0x00BC<=point&&point<=0x00BF)||(0x00C6===point)||(0x00D0===point)||(0x00D7<=point&&point<=0x00D8)||(0x00DE<=point&&point<=0x00E1)||(0x00E6===point)||(0x00E8<=point&&point<=0x00EA)||(0x00EC<=point&&point<=0x00ED)||(0x00F0===point)||(0x00F2<=point&&point<=0x00F3)||(0x00F7<=point&&point<=0x00FA)||(0x00FC===point)||(0x00FE===point)||(0x0101===point)||(0x0111===point)||(0x0113===point)||(0x011B===point)||(0x0126<=point&&point<=0x0127)||(0x012B===point)||(0x0131<=point&&point<=0x0133)||(0x0138===point)||(0x013F<=point&&point<=0x0142)||(0x0144===point)||(0x0148<=point&&point<=0x014B)||(0x014D===point)||(0x0152<=point&&point<=0x0153)||(0x0166<=point&&point<=0x0167)||(0x016B===point)||(0x01CE===point)||(0x01D0===point)||(0x01D2===point)||(0x01D4===point)||(0x01D6===point)||(0x01D8===point)||(0x01DA===point)||(0x01DC===point)||(0x0251===point)||(0x0261===point)||(0x02C4===point)||(0x02C7===point)||(0x02C9<=point&&point<=0x02CB)||(0x02CD===point)||(0x02D0===point)||(0x02D8<=point&&point<=0x02DB)||(0x02DD===point)||(0x02DF===point)||(0x0300<=point&&point<=0x036F)||(0x0391<=point&&point<=0x03A1)||(0x03A3<=point&&point<=0x03A9)||(0x03B1<=point&&point<=0x03C1)||(0x03C3<=point&&point<=0x03C9)||(0x0401===point)||(0x0410<=point&&point<=0x044F)||(0x0451===point)||(0x2010===point)||(0x2013<=point&&point<=0x2016)||(0x2018<=point&&point<=0x2019)||(0x201C<=point&&point<=0x201D)||(0x2020<=point&&point<=0x2022)||(0x2024<=point&&point<=0x2027)||(0x2030===point)||(0x2032<=point&&point<=0x2033)||(0x2035===point)||(0x203B===point)||(0x203E===point)||(0x2074===point)||(0x207F===point)||(0x2081<=point&&point<=0x2084)||(0x20AC===point)||(0x2103===point)||(0x2105===point)||(0x2109===point)||(0x2113===point)||(0x2116===point)||(0x2121<=point&&point<=0x2122)||(0x2126===point)||(0x212B===point)||(0x2153<=point&&point<=0x2154)||(0x215B<=point&&point<=0x215E)||(0x2160<=point&&point<=0x216B)||(0x2170<=point&&point<=0x2179)||(0x2189===point)||(0x2190<=point&&point<=0x2199)||(0x21B8<=point&&point<=0x21B9)||(0x21D2===point)||(0x21D4===point)||(0x21E7===point)||(0x2200===point)||(0x2202<=point&&point<=0x2203)||(0x2207<=point&&point<=0x2208)||(0x220B===point)||(0x220F===point)||(0x2211===point)||(0x2215===point)||(0x221A===point)||(0x221D<=point&&point<=0x2220)||(0x2223===point)||(0x2225===point)||(0x2227<=point&&point<=0x222C)||(0x222E===point)||(0x2234<=point&&point<=0x2237)||(0x223C<=point&&point<=0x223D)||(0x2248===point)||(0x224C===point)||(0x2252===point)||(0x2260<=point&&point<=0x2261)||(0x2264<=point&&point<=0x2267)||(0x226A<=point&&point<=0x226B)||(0x226E<=point&&point<=0x226F)||(0x2282<=point&&point<=0x2283)||(0x2286<=point&&point<=0x2287)||(0x2295===point)||(0x2299===point)||(0x22A5===point)||(0x22BF===point)||(0x2312===point)||(0x2460<=point&&point<=0x24E9)||(0x24EB<=point&&point<=0x254B)||(0x2550<=point&&point<=0x2573)||(0x2580<=point&&point<=0x258F)||(0x2592<=point&&point<=0x2595)||(0x25A0<=point&&point<=0x25A1)||(0x25A3<=point&&point<=0x25A9)||(0x25B2<=point&&point<=0x25B3)||(0x25B6<=point&&point<=0x25B7)||(0x25BC<=point&&point<=0x25BD)||(0x25C0<=point&&point<=0x25C1)||(0x25C6<=point&&point<=0x25C8)||(0x25CB===point)||(0x25CE<=point&&point<=0x25D1)||(0x25E2<=point&&point<=0x25E5)||(0x25EF===point)||(0x2605<=point&&point<=0x2606)||(0x2609===point)||(0x260E<=point&&point<=0x260F)||(0x2614<=point&&point<=0x2615)||(0x261C===point)||(0x261E===point)||(0x2640===point)||(0x2642===point)||(0x2660<=point&&point<=0x2661)||(0x2663<=point&&point<=0x2665)||(0x2667<=point&&point<=0x266A)||(0x266C<=point&&point<=0x266D)||(0x266F===point)||(0x269E<=point&&point<=0x269F)||(0x26BE<=point&&point<=0x26BF)||(0x26C4<=point&&point<=0x26CD)||(0x26CF<=point&&point<=0x26E1)||(0x26E3===point)||(0x26E8<=point&&point<=0x26FF)||(0x273D===point)||(0x2757===point)||(0x2776<=point&&point<=0x277F)||(0x2B55<=point&&point<=0x2B59)||(0x3248<=point&&point<=0x324F)||(0xE
return 1;};exports.strWidth=function(str){var width=0;for(var i=0;i<str.length;i++){width+=exports.charWidth(str,i);if(exports.isSurrogate(str,i))i++;}
return width;};exports.isSurrogate=function(str,i){var point=typeof str!=='number'?exports.codePointAt(str,i||0):str;return point>0x00ffff;};exports.combiningTable=[[0x0300,0x036F],[0x0483,0x0486],[0x0488,0x0489],[0x0591,0x05BD],[0x05BF,0x05BF],[0x05C1,0x05C2],[0x05C4,0x05C5],[0x05C7,0x05C7],[0x0600,0x0603],[0x0610,0x0615],[0x064B,0x065E],[0x0670,0x0670],[0x06D6,0x06E4],[0x06E7,0x06E8],[0x06EA,0x06ED],[0x070F,0x070F],[0x0711,0x0711],[0x0730,0x074A],[0x07A6,0x07B0],[0x07EB,0x07F3],[0x0901,0x0902],[0x093C,0x093C],[0x0941,0x0948],[0x094D,0x094D],[0x0951,0x0954],[0x0962,0x0963],[0x0981,0x0981],[0x09BC,0x09BC],[0x09C1,0x09C4],[0x09CD,0x09CD],[0x09E2,0x09E3],[0x0A01,0x0A02],[0x0A3C,0x0A3C],[0x0A41,0x0A42],[0x0A47,0x0A48],[0x0A4B,0x0A4D],[0x0A70,0x0A71],[0x0A81,0x0A82],[0x0ABC,0x0ABC],[0x0AC1,0x0AC5],[0x0AC7,0x0AC8],[0x0ACD,0x0ACD],[0x0AE2,0x0AE3],[0x0B01,0x0B01],[0x0B3C,0x0B3C],[0x0B3F,0x0B3F],[0x0B41,0x0B43],[0x0B4D,0x0B4D],[0x0B56,0x0B56],[0x0B82,0x0B82],[0x0BC0,0x0BC0],[0x0BCD,0x0BCD],[0x0C3E,0x0C40],[0x0C46,0x0C48],[0x0C4A,0x0C4D],[0x0C55,0x0C56],[0x0CBC,0x0CBC],[0x0CBF,0x0CBF],[0x0CC6,0x0CC6],[0x0CCC,0x0CCD],[0x0CE2,0x0CE3],[0x0D41,0x0D43],[0x0D4D,0x0D4D],[0x0DCA,0x0DCA],[0x0DD2,0x0DD4],[0x0DD6,0x0DD6],[0x0E31,0x0E31],[0x0E34,0x0E3A],[0x0E47,0x0E4E],[0x0EB1,0x0EB1],[0x0EB4,0x0EB9],[0x0EBB,0x0EBC],[0x0EC8,0x0ECD],[0x0F18,0x0F19],[0x0F35,0x0F35],[0x0F37,0x0F37],[0x0F39,0x0F39],[0x0F71,0x0F7E],[0x0F80,0x0F84],[0x0F86,0x0F87],[0x0F90,0x0F97],[0x0F99,0x0FBC],[0x0FC6,0x0FC6],[0x102D,0x1030],[0x1032,0x1032],[0x1036,0x1037],[0x1039,0x1039],[0x1058,0x1059],[0x1160,0x11FF],[0x135F,0x135F],[0x1712,0x1714],[0x1732,0x1734],[0x1752,0x1753],[0x1772,0x1773],[0x17B4,0x17B5],[0x17B7,0x17BD],[0x17C6,0x17C6],[0x17C9,0x17D3],[0x17DD,0x17DD],[0x180B,0x180D],[0x18A9,0x18A9],[0x1920,0x1922],[0x1927,0x1928],[0x1932,0x1932],[0x1939,0x193B],[0x1A17,0x1A18],[0x1B00,0x1B03],[0x1B34,0x1B34],[0x1B36,0x1B3A],[0x1B3C,0x1B3C],[0x1B42,0x1B42],[0x1B6B,0x1B73],[0x1DC0,0x1DCA],[0x1DFE,0x1DFF],[0x200B,0x200F],[0x202A,0x202E],[0x2060,0x2063],[0x206A,0x206F],[0x20D0,0x20EF],[0x302A,0x302F],[0x3099,0x309A],[0xA806,0xA806],[0xA80B,0xA80B],[0xA825,0xA826],[0xFB1E,0xFB1E],[0xFE00,0xFE0F],[0xFE20,0xFE23],[0xFEFF,0xFEFF],[0xFFF9,0xFFFB],[0x10A01,0x10A03],[0x10A05,0x10A06],[0x10A0C,0x10A0F],[0x10A38,0x10A3A],[0x10A3F,0x10A3F],[0x1D167,0x1D169],[0x1D173,0x1D182],[0x1D185,0x1D18B],[0x1D1AA,0x1D1AD],[0x1D242,0x1D244],[0xE0001,0xE0001],[0xE0020,0xE007F],[0xE0100,0xE01EF]];exports.combining=exports.combiningTable.reduce(function(out,row){for(var i=row[0];i<=row[1];i++){out[i]=true;}
return out;},{});exports.isCombining=function(str,i){var point=typeof str!=='number'?exports.codePointAt(str,i||0):str;return exports.combining[point]===true;};exports.codePointAt=function(str,position){if(str==null){throw TypeError();}
var string=String(str);if(string.codePointAt){return string.codePointAt(position);}
var size=string.length;var index=position?Number(position):0;if(index!==index){index=0;}
if(index<0||index>=size){return undefined;}
var first=string.charCodeAt(index);var second;if(first>=0xD800&&first<=0xDBFF&&size>index+1){second=string.charCodeAt(index+1);if(second>=0xDC00&&second<=0xDFFF){return(first-0xD800)*0x400+second-0xDC00+0x10000;}}
return first;};exports.fromCodePoint=function(){if(String.fromCodePoint){return String.fromCodePoint.apply(String,arguments);}
var MAX_SIZE=0x4000;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return'';}
var result='';while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>0x10FFFF||floor(codePoint)!==codePoint){throw RangeError('Invalid code point: '+codePoint);}
if(codePoint<=0xFFFF){codeUnits.push(codePoint);}else{codePoint-=0x10000;highSurrogate=(codePoint>>10)+0xD800;lowSurrogate=(codePoint%0x400)+0xDC00;codeUnits.push(highSurrogate,lowSurrogate);}
if(index+1===length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0;}}
return result;};exports.chars={};exports.chars.wide=new RegExp('(['
+'\\u1100-\\u115f'
+'\\u2329\\u232a'
+'\\u2e80-\\u303e\\u3040-\\ua4cf'
+'\\uac00-\\ud7a3'
+'\\uf900-\\ufaff'
+'\\ufe10-\\ufe19'
+'\\ufe30-\\ufe6f'
+'\\uff00-\\uff60'
+'\\uffe0-\\uffe6'
+'])','g');exports.chars.swide=new RegExp('('
+'[\\ud840-\\ud87f][\\udc00-\\udffd]'
+'|'
+'[\\ud880-\\ud8bf][\\udc00-\\udffd]'
+')','g');exports.chars.all=new RegExp('('
+exports.chars.swide.source.slice(1,-1)
+'|'
+exports.chars.wide.source.slice(1,-1)
+')','g');exports.chars.surrogate=/[\ud800-\udbff][\udc00-\udfff]/g;exports.chars.combining=exports.combiningTable.reduce(function(out,row){var low,high,range;if(row[0]>0x00ffff){low=exports.fromCodePoint(row[0]);low=[hexify(low.charCodeAt(0)),hexify(low.charCodeAt(1))];high=exports.fromCodePoint(row[1]);high=[hexify(high.charCodeAt(0)),hexify(high.charCodeAt(1))];range='[\\u'+low[0]+'-'+'\\u'+high[0]+']'
+'[\\u'+low[1]+'-'+'\\u'+high[1]+']';if(!~out.indexOf('|'))out+=']';out+='|'+range;}else{low=hexify(row[0]);high=hexify(row[1]);low='\\u'+low;high='\\u'+high;out+=low+'-'+high;}
return out;},'[');exports.chars.combining=new RegExp(exports.chars.combining,'g');function hexify(n){n=n.toString(16);while(n.length<4)n='0'+n;return n;}};BundleModuleCode['term/helpers']=function(module,exports){var fs=Require('fs');var Comp=Require('com/compat');var unicode=Require('term/unicode');var helpers=exports;helpers.asort=function(obj){return obj.sort(function(a,b){a=a.name.toLowerCase();b=b.name.toLowerCase();if(a[0]==='.'&&b[0]==='.'){a=a[1];b=b[1];}else{a=a[0];b=b[0];}
return a>b?1:(a<b?-1:0);});};helpers.attrToBinary=function(style,element){return helpers.Element.prototype.sattr.call(element||{},style);};helpers.bbox=function(parent,options){function eval(a,b){if(a.indexOf('%'))return int(Number(a.substring(0,a.length-1))*b/100);}
var bbox={width:options.width,height:options.height,top:options.top,left:options.left,right:options.right};if(bbox.width=='half')bbox.width=int(parent.width/2);if(typeof bbox.width=='string'&&bbox.width.indexOf('%')!=-1)bbox.width=eval(bbox.width,parent.width);if(bbox.height=='half')bbox.height=int(parent.height/2);if(typeof bbox.height=='string'&&bbox.height.indexOf('%')!=-1)bbox.height=eval(bbox.height,parent.height);if(bbox.left=='center')bbox.left=int((parent.width/2)-(bbox.width/2));if(bbox.top=='center')bbox.top=int((parent.height/2)-(bbox.height/2));return bbox;}
helpers.cleanTags=function(text){return helpers.stripTags(text).trim();};helpers.dropUnicode=function(text){if(!text)return'';return text.replace(unicode.chars.all,'??').replace(unicode.chars.combining,'').replace(unicode.chars.surrogate,'?');};helpers.findFile=function(start,target){return(function read(dir){var files,file,stat,out;if(dir==='/dev'||dir==='/sys'||dir==='/proc'||dir==='/net'){return null;}
try{files=fs.readdirSync(dir);}catch(e){files=[];}
for(var i=0;i<files.length;i++){file=files[i];if(file===target){return(dir==='/'?'':dir)+'/'+file;}
try{stat=fs.lstatSync((dir==='/'?'':dir)+'/'+file);}catch(e){stat=null;}
if(stat&&stat.isDirectory()&&!stat.isSymbolicLink()){out=read((dir==='/'?'':dir)+'/'+file);if(out)return out;}}
return null;})(start);};helpers.escape=function(text){return text.replace(/[{}]/g,function(ch){return ch==='{'?'{open}':'{close}';});};helpers.generateTags=function(style,text){var open='',close='';Object.keys(style||{}).forEach(function(key){var val=style[key];if(typeof val==='string'){val=val.replace(/^light(?!-)/,'light-');val=val.replace(/^bright(?!-)/,'bright-');open='{'+val+'-'+key+'}'+open;close+='{/'+val+'-'+key+'}';}else{if(val===true){open='{'+key+'}'+open;close+='{/'+key+'}';}}});if(text!=null){return open+text+close;}
return{open:open,close:close};};helpers.hsort=function(obj){return obj.sort(function(a,b){return b.index-a.index;});};helpers.merge=function(a,b){Object.keys(b).forEach(function(key){a[key]=b[key];});return a;};helpers.parseTags=function(text,screen){return helpers.Element.prototype._parseTags.call({parseTags:true,screen:screen||helpers.Screen.global},text);};helpers.stripTags=function(text){if(!text)return'';return text.replace(/\{(\/?)([\w\-,;!#]*)\}/g,'').replace(/\x1b\[[\d;]*m/g,'');};Object.defineProperty(helpers,'Screen',{get:function(){if(!helpers._screen){helpers._screen=Require('term/widgets/screen');}
return helpers._screen;}});Object.defineProperty(helpers,'Element',{get:function(){if(!helpers._element){helpers._element=Require('term/widgets/element');}
return helpers._element;}});};BundleModuleCode['term/widgets/log']=function(module,exports){var options={version:'1.3.2'}
var Comp=Require('com/compat');var util=require('util');var Helpers=Require('term/helpers');var Button=Require('term/widgets/button');var Arrows=Require('term/widgets/arrows');var nextTick=global.setImmediate||process.nextTick.bind(process);var Node=Require('term/widgets/node');var ScrollableText=Require('term/widgets/scrollabletext');function Log(options){var self=this,bbox;if(!instanceOf(this,Node)){return new Log(options);}
options=options||{};ScrollableText.call(this,options);this.scrollback=options.scrollback!=null?options.scrollback:Infinity;this.scrollOnInput=options.scrollOnInput;this._updating=false;if(options.arrows)
Arrows(self,options,function(){self.scroll(-2)},function(){self.scroll(2)});this.on('set content',function(){if(!self._updating&&!self._userScrolled&&self.scrollOnInput){self._updating=true;setTimeout(function(){self.setScrollPerc(100);self._userScrolled=false;self._updating=false;self.screen.render();},20);}});}
inheritPrototype(Log,ScrollableText);Log.prototype.type='log';Log.prototype.log=Log.prototype.add=function(){var args=Array.prototype.slice.call(arguments);if(typeof args[0]==='object'){args[0]=util.inspect(args[0],true,20,true);}
var text=util.format.apply(util,args);this.emit('log',text);var ret=this.pushLine(text);return ret;};Log.prototype.clear=function(){if(this._userScrolled)this.setScrollPerc(100);this.setContent('');this.resetScroll();}
Log.prototype._scroll=Log.prototype.scroll;Log.prototype.scroll=function(offset,always){if(offset>this.getScrollHeight()||(this.getScrollHeight()+offset)<0)return;if(offset===0)return this._scroll(offset,always);this._userScrolled=true;var ret=this._scroll(offset,always);if(this.getScrollPerc()===100){this._userScrolled=false;}
return ret;};module.exports=Log;Log.prototype.logold=function(str){var i;this.logLines.push(str)
if(this.logLines.length==1){this.setContent(str);}
else if(this.logLines.length>this.options.bufferLength){this.logLines.shift();this.setContent(this.logLines[0]);for(i=1;i<this.logLines.length;i++){this.insertLine(i,this.logLines[i]);}
this.scrollBottom();}else{this.scrollBottom();this.insertBottom(str);this.scrollBottom();}}};BundleModuleCode['term/widgets/button']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Input=Require('term/widgets/input');function Button(options){var self=this;if(!instanceOf(this,Node)){return new Button(options);}
options=options||{};if(options.autoFocus==null){options.autoFocus=false;}
if(!options.style)options.style={fg:'white',bg:'blue',bold:true,border:{fg:'black'},hover:{border:{fg:'red'}},focus:{border:{fg:'red'}}}
if(options.object)this.object=options.object;Input.call(this,options);this.on('keypress',function(ch,key){if(key.name=='enter'||key.name=='return'){return self.press();}});if(this.options.mouse){this.on('click',function(){return self.press();});}}
inheritPrototype(Button,Input);Button.prototype.type='button';Button.prototype.press=function(){this.focus();this.value=true;var result=this.emit('press');delete this.value;return result;};module.exports=Button;};BundleModuleCode['term/widgets/input']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Input(options){if(!instanceOf(this,Node)){return new Input(options);}
options=options||{};Box.call(this,options);}
inheritPrototype(Input,Box);Input.prototype.type='input';Input.prototype.focus=function(){this.screen.rewindFocus();return this.screen.focused=this;}
module.exports=Input;};BundleModuleCode['term/widgets/box']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Element=Require('term/widgets/element');function Box(options){if(!instanceOf(this,Node)){return new Box(options);}
options=options||{};Element.call(this,options);}
inheritPrototype(Box,Element);Box.prototype.type='box';module.exports=Box;};BundleModuleCode['term/widgets/element']=function(module,exports){var Comp=Require('com/compat');var assert=Require('assert');var colors=Require('term/colors'),unicode=Require('term/unicode');var nextTick=global.setImmediate||process.nextTick.bind(process);var helpers=Require('term/helpers');var Node=Require('term/widgets/node');function Element(options){var self=this;if(!instanceOf(this,Node)){return new Element(options);}
options=options||{};if(options.scrollable&&!this._ignore&&this.type!=='scrollable-box'){var ScrollableBox=Require('term/widgets/scrollablebox');Object.getOwnPropertyNames(ScrollableBox.prototype).forEach(function(key){if(key==='type')return;Object.defineProperty(this,key,Object.getOwnPropertyDescriptor(ScrollableBox.prototype,key));},this);this._ignore=true;ScrollableBox.call(this,options);delete this._ignore;if(options.mouse){this.onScreenEvent('mouse',function(data){var x=data.x-self.aleft;var y=data.y-self.atop;if(!self.hidden&&data.action=='mousedown'&&x===self.width-self.iright-1){self.focus();var perc=(y-self.itop)/(self.height-self.iheight);self.setScrollPerc(perc*100|0);self.screen.render();}});}
return this;}
Node.call(this,options);this.name=options.name;options.position=options.position||{left:options.left,right:options.right,top:options.top,bottom:options.bottom,width:options.width,height:options.height};if(options.position.width==='shrink'||options.position.height==='shrink'){if(options.position.width==='shrink'){delete options.position.width;}
if(options.position.height==='shrink'){delete options.position.height;}
options.shrink=true;}
this.position=options.position;this.noOverflow=options.noOverflow;this.dockBorders=options.dockBorders;this.shadow=options.shadow;this.style=options.style;if(!this.style){this.style={};this.style.fg=options.fg;this.style.bg=options.bg;this.style.bold=options.bold;this.style.underline=options.underline;this.style.blink=options.blink;this.style.inverse=options.inverse;this.style.invisible=options.invisible;this.style.transparent=options.transparent;}
this.hidden=options.hidden||false;this.fixed=options.fixed||false;this.align=options.align||'left';this.valign=options.valign||'top';this.wrap=options.wrap!==false;this.shrink=options.shrink;this.ch=options.ch||' ';if(typeof options.padding==='number'||!options.padding){options.padding={left:options.padding,top:options.padding,right:options.padding,bottom:options.padding};}
this.padding={left:options.padding.left||0,top:options.padding.top||0,right:options.padding.right||0,bottom:options.padding.bottom||0};this.border=options.border;if(this.border){if(typeof this.border==='string'){this.border={type:this.border};}
this.border.type=this.border.type||'bg';if(this.border.type==='ascii')this.border.type='line';this.border.ch=this.border.ch||' ';this.style.border=this.style.border||this.border.style;if(!this.style.border){this.style.border={};this.style.border.fg=this.border.fg;this.style.border.bg=this.border.bg;}
if(this.border.left==null)this.border.left=true;if(this.border.top==null)this.border.top=true;if(this.border.right==null)this.border.right=true;if(this.border.bottom==null)this.border.bottom=true;}
if(options.clickable){this.screen._listenMouse(this);}
if(options.input||options.keyable){this.screen._listenKeys(this);}
this.parseTags=options.parseTags||options.tags;this.setContent(options.content||'',true);if(options.label){this.setLabel(options.label);}
if(options.hoverText){this.setHover(options.hoverText);}
this.on('newListener',function fn(type){if(type==='mouse'||type==='click'||type==='mouseover'||type==='mouseout'||type==='mousedown'||type==='mouseup'||type==='mousewheel'||type==='wheeldown'||type==='wheelup'||type==='mousemove'){self.screen._listenMouse(self);}else if(type==='keypress'||type.indexOf('key ')===0){self.screen._listenKeys(self);}});this.on('resize',function(){self.parseContent();});this.on('attach',function(){self.parseContent();});this.on('detach',function(){delete self.lpos;});if(options.hoverBg!=null){options.hoverEffects=options.hoverEffects||{};options.hoverEffects.bg=options.hoverBg;}
if(this.style.hover){options.hoverEffects=this.style.hover;}
if(this.style.focus){options.focusEffects=this.style.focus;}
if(options.effects){if(options.effects.hover)options.hoverEffects=options.effects.hover;if(options.effects.focus)options.focusEffects=options.effects.focus;}
[['hoverEffects','mouseover','mouseout','_htemp'],['focusEffects','focus','blur','_ftemp']].forEach(function(props){var pname=props[0],over=props[1],out=props[2],temp=props[3];self.screen.setEffects(self,self,over,out,self.options[pname],temp);});if(this.options.draggable){this.draggable=true;}
if(options.focused){this.focus();}}
inheritPrototype(Element,Node);Element.prototype.type='element';Object.defineProperty(Element.prototype,'focused',{get:function(){return this.screen.focused===this;}});Element.prototype.sattr=function(style,fg,bg){var bold=style.bold,underline=style.underline,blink=style.blink,inverse=style.inverse,invisible=style.invisible;if(fg==null&&bg==null){fg=style.fg;bg=style.bg;}
if(typeof bold==='function')bold=bold(this);if(typeof underline==='function')underline=underline(this);if(typeof blink==='function')blink=blink(this);if(typeof inverse==='function')inverse=inverse(this);if(typeof invisible==='function')invisible=invisible(this);if(typeof fg==='function')fg=fg(this);if(typeof bg==='function')bg=bg(this);return((invisible?16:0)<<18)|((inverse?8:0)<<18)|((blink?4:0)<<18)|((underline?2:0)<<18)|((bold?1:0)<<18)|(colors.convert(fg)<<9)|colors.convert(bg);};Element.prototype.onScreenEvent=function(type,handler){var listeners=this._slisteners=this._slisteners||[];listeners.push({type:type,handler:handler});this.screen.on(type,handler);};Element.prototype.onceScreenEvent=function(type,handler){var listeners=this._slisteners=this._slisteners||[];var entry={type:type,handler:handler};listeners.push(entry);this.screen.once(type,function(){var i=listeners.indexOf(entry);if(~i)listeners.splice(i,1);return handler.apply(this,arguments);});};Element.prototype.removeScreenEvent=function(type,handler){var listeners=this._slisteners=this._slisteners||[];for(var i=0;i<listeners.length;i++){var listener=listeners[i];if(listener.type===type&&listener.handler===handler){listeners.splice(i,1);if(this._slisteners.length===0){delete this._slisteners;}
break;}}
this.screen.removeListener(type,handler);};Element.prototype.free=function(){var listeners=this._slisteners=this._slisteners||[];for(var i=0;i<listeners.length;i++){var listener=listeners[i];this.screen.removeListener(listener.type,listener.handler);}
delete this._slisteners;};Element.prototype.hide=function(){if(this.hidden)return;this.clearPos();this.hidden=true;this.emit('hide');if(this.screen.focused===this){this.screen.rewindFocus();}};Element.prototype.show=function(){if(!this.hidden)return;this.hidden=false;this.emit('show');};Element.prototype.toggle=function(){return this.hidden?this.show():this.hide();};Element.prototype.focus=function(){return this.screen.focused=this;};Element.prototype.isfocus=function(){return this.screen.focused==this;};Element.prototype.setStyle=function(styles){for(var p in styles){if(this.style[p]!=undefined)this.style[p]=styles[p];}};Element.prototype.setContent=function(content,noClear,noTags){var changed=this.content!=content;if(!noClear)this.clearPos();this.content=content||'';this.parseContent(noTags);this.emit('set content');if(changed)this.emit('change',content);};Element.prototype.getContent=function(){if(!this._clines)return'';return this._clines.fake.join('\n');};Element.prototype.setText=function(content,noClear){content=content||'';content=content.replace(/\x1b\[[\d;]*m/g,'');return this.setContent(content,noClear,true);};Element.prototype.getText=function(){return this.getContent().replace(/\x1b\[[\d;]*m/g,'');};Element.prototype.parseContent=function(noTags){var self=this;if(this.detached)return false;var width=this.width-this.iwidth;if(this._clines==null||this._clines.width!==width||this._clines.content!==this.content){var content=this.content;content=content.replace(/[\x00-\x08\x0b-\x0c\x0e-\x1a\x1c-\x1f\x7f]/g,'').replace(/\x1b(?!\[[\d;]*m)/g,'').replace(/\r\n|\r/g,'\n').replace(/\t/g,this.screen.tabc);if(this.screen.fullUnicode){content=content.replace(unicode.chars.all,'$1\x03');if(this.screen.program.isiTerm2){content=content.replace(unicode.chars.combining,'');}}else{content=content.replace(unicode.chars.all,'??');content=content.replace(unicode.chars.combining,'');content=content.replace(unicode.chars.surrogate,'?');}
if(!noTags){content=this._parseTags(content);}
this._clines=this._wrapContent(content,width);this._clines.width=width;this._clines.content=this.content;this._clines.attr=this._parseAttr(this._clines);this._clines.ci=[];this._clines.reduce(function(total,line){self._clines.ci.push(total);return total+line.length+1;},0);this._pcontent=this._clines.join('\n');this.emit('parsed content');return true;}
this._clines.attr=this._parseAttr(this._clines)||this._clines.attr;return false;};Element.prototype._parseTags=function(text){if(!this.parseTags)return text;if(!/\{\/?[\w\-,;!#]*\}/.test(text))return text;var program=this.screen.program,out='',state,bg=[],fg=[],flag=[],cap,slash,param,attr,esc;for(;;){if(!esc&&(cap=/^\{escape\}/.exec(text))){text=text.substring(cap[0].length);esc=true;continue;}
if(esc&&(cap=/^([\s\S]+?)\{\/escape\}/.exec(text))){text=text.substring(cap[0].length);out+=cap[1];esc=false;continue;}
if(esc){out+=text;break;}
if(cap=/^\{(\/?)([\w\-,;!#]*)\}/.exec(text)){text=text.substring(cap[0].length);slash=cap[1]==='/';param=cap[2].replace(/-/g,' ');if(param==='open'){out+='{';continue;}else if(param==='close'){out+='}';continue;}
if(param.slice(-3)===' bg')state=bg;else if(param.slice(-3)===' fg')state=fg;else state=flag;if(slash){if(!param){out+=program._attr('normal');bg.length=0;fg.length=0;flag.length=0;}else{attr=program._attr(param,false);if(attr==null){out+=cap[0];}else{state.pop();if(state.length){out+=program._attr(state[state.length-1]);}else{out+=attr;}}}}else{if(!param){out+=cap[0];}else{attr=program._attr(param);if(attr==null){out+=cap[0];}else{state.push(param);out+=attr;}}}
continue;}
if(cap=/^[\s\S]+?(?=\{\/?[\w\-,;!#]*\})/.exec(text)){text=text.substring(cap[0].length);out+=cap[0];continue;}
out+=text;break;}
return out;};Element.prototype._parseAttr=function(lines){var dattr=this.sattr(this.style),attr=dattr,attrs=[],line,i,j,c;if(lines[0].attr===attr){return;}
for(j=0;j<lines.length;j++){line=lines[j];attrs[j]=attr;for(i=0;i<line.length;i++){if(line[i]==='\x1b'){if(c=/^\x1b\[[\d;]*m/.exec(line.substring(i))){attr=this.screen.attrCode(c[0],attr,dattr);i+=c[0].length-1;}}}}
return attrs;};Element.prototype._align=function(line,width,align){if(!align)return line;var cline=line.replace(/\x1b\[[\d;]*m/g,''),len=cline.length,s=width-len;if(this.shrink){s=0;}
if(len===0)return line;if(s<0)return line;if(align==='center'){s=Array(((s/2)|0)+1).join(' ');return s+line+s;}else if(align==='right'){s=Array(s+1).join(' ');return s+line;}else if(this.parseTags&&~line.indexOf('{|}')){var parts=line.split('{|}');var cparts=cline.split('{|}');s=Math.max(width-cparts[0].length-cparts[1].length,0);s=Array(s+1).join(' ');return parts[0]+s+parts[1];}
return line;};Element.prototype._wrapContent=function(content,width){var tags=this.parseTags,state=this.align,wrap=this.wrap,margin=0,rtof=[],ftor=[],out=[],no=0,line,align,cap,total,i,part,j,lines,rest;lines=content.split('\n');if(!content){out.push(content);out.rtof=[0];out.ftor=[[0]];out.fake=lines;out.real=out;out.mwidth=0;return out;}
if(this.scrollbar)margin++;if(this.type==='textarea')margin++;if(width>margin)width-=margin;main:for(;no<lines.length;no++){line=lines[no];align=state;ftor.push([]);if(tags){if(cap=/^\{(left|center|right)\}/.exec(line)){line=line.substring(cap[0].length);align=state=cap[1]!=='left'?cap[1]:null;}
if(cap=/\{\/(left|center|right)\}$/.exec(line)){line=line.slice(0,-cap[0].length);state=this.align;}}
while(line.length>width){if(this.break=='all')
i=width;else for(i=0,total=0;i<line.length;i++){while(line[i]==='\x1b'){while(line[i]&&line[i++]!=='m');}
if(!line[i])break;if(++total===width){i++;if(!wrap){rest=line.substring(i).match(/\x1b\[[^m]*m/g);rest=rest?rest.join(''):'';out.push(this._align(line.substring(0,i)+rest,width,align));ftor[no].push(out.length-1);rtof.push(no);continue main;}
if(!this.screen.fullUnicode){if(i!==line.length){j=i;while(j>i-10&&j>0&&line[--j]!==' ');if(line[j]===' ')i=j+1;}}else{if(i!==line.length){if(unicode.isSurrogate(line,i))i--;for(var s=0,n=0;n<i;n++){if(unicode.isSurrogate(line,n))s++,n++;}
i+=s;j=i;while(j>i-10&&j>0){j--;if(line[j]===' '||line[j]==='\x03'||(unicode.isSurrogate(line,j-1)&&line[j+1]!=='\x03')||unicode.isCombining(line,j)){break;}}
if(line[j]===' '||line[j]==='\x03'||(unicode.isSurrogate(line,j-1)&&line[j+1]!=='\x03')||unicode.isCombining(line,j)){i=j+1;}}}
break;}}
part=line.substring(0,i);line=line.substring(i);out.push(this._align(part,width,align));ftor[no].push(out.length-1);rtof.push(no);if(line==='')continue main;if(/^(?:\x1b[\[\d;]*m)+$/.test(line)){out[out.length-1]+=line;continue main;}}
out.push(this._align(line,width,align));ftor[no].push(out.length-1);rtof.push(no);}
out.rtof=rtof;out.ftor=ftor;out.fake=lines;out.real=out;out.mwidth=out.reduce(function(current,line){line=line.replace(/\x1b\[[\d;]*m/g,'');return line.length>current?line.length:current;},0);return out;};Object.defineProperty(Element.prototype,'visible',{get:function(){var el=this;do{if(el.detached)return false;if(el.hidden)return false;}while(el=el.parent);return true;}});Object.defineProperty(Element.prototype,'_detached',{get:function(){var el=this;do{if(el.type==='screen')return false;if(!el.parent)return true;}while(el=el.parent);return false;}});Element.prototype.enableMouse=function(){this.screen._listenMouse(this);};Element.prototype.enableKeys=function(){this.screen._listenKeys(this);};Element.prototype.enableInput=function(){this.screen._listenMouse(this);this.screen._listenKeys(this);};Object.defineProperty(Element.prototype,'draggable',{get:function(){return this._draggable===true;},set:function(draggable){return draggable?this.enableDrag(draggable):this.disableDrag();}});Element.prototype.enableDrag=function(verify){var self=this;if(this._draggable)return true;if(typeof verify!=='function'){verify=function(){return true;};}
this.enableMouse();this.on('mousedown',this._dragMD=function(data){if(self.screen._dragging)return;if(!verify(data))return;self.screen._dragging=self;self._drag={x:data.x-self.aleft,y:data.y-self.atop};self.setFront();});this.onScreenEvent('mouse',this._dragM=function(data){if(self.screen._dragging!==self)return;if(data.action!=='mousedown'&&data.action!=='mousemove'){delete self.screen._dragging;delete self._drag;return;}
if(!self.parent)return;var ox=self._drag.x,oy=self._drag.y,px=self.parent.aleft,py=self.parent.atop,x=data.x-px-ox,y=data.y-py-oy;if(self.position.right!=null){if(self.position.left!=null){self.width='100%-'+(self.parent.width-self.width);}
self.position.right=null;}
if(self.position.bottom!=null){if(self.position.top!=null){self.height='100%-'+(self.parent.height-self.height);}
self.position.bottom=null;}
self.rleft=x;self.rtop=y;self.screen.render();});return this._draggable=true;};Element.prototype.disableDrag=function(){if(!this._draggable)return false;delete this.screen._dragging;delete this._drag;this.removeListener('mousedown',this._dragMD);this.removeScreenEvent('mouse',this._dragM);return this._draggable=false;};Element.prototype.key=function(){return this.screen.program.key.apply(this,arguments);};Element.prototype.onceKey=function(){return this.screen.program.onceKey.apply(this,arguments);};Element.prototype.unkey=Element.prototype.removeKey=function(){return this.screen.program.unkey.apply(this,arguments);};Element.prototype.setIndex=function(index){if(!this.parent)return;if(index<0){index=this.parent.children.length+index;}
index=Math.max(index,0);index=Math.min(index,this.parent.children.length-1);var i=this.parent.children.indexOf(this);if(!~i)return;var item=this.parent.children.splice(i,1)[0];this.parent.children.splice(index,0,item);};Element.prototype.setFront=function(){return this.setIndex(-1);};Element.prototype.setBack=function(){return this.setIndex(0);};Element.prototype.clearPos=function(get,override){if(this.detached)return;var lpos=this._getCoords(get);if(!lpos)return;this.screen.clearRegion(lpos.xi,lpos.xl,lpos.yi,lpos.yl,override);};Element.prototype.getLabel=function(){if(this._label)return this._label.getContent();}
Element.prototype.setLabel=function(options){var self=this;var Box=Require('term/widgets/box');if(typeof options==='string'){options={text:options};}
if(this._label){this._label.setContent(options.text);if(options.side!=='right'){this._label.rleft=2+(this.border?-1:0);this._label.position.right=undefined;if(!this.screen.autoPadding){this._label.rleft=2;}}else{this._label.rright=2+(this.border?-1:0);this._label.position.left=undefined;if(!this.screen.autoPadding){this._label.rright=2;}}
return;}
this._label=new Box({screen:this.screen,parent:this,content:options.text,top:-this.itop,tags:this.parseTags,shrink:true,style:this.style.label});if(options.side!=='right'){this._label.rleft=2-this.ileft;}else{this._label.rright=2-this.iright;}
if(this.border&&this.border.type=='none')this._label.rleft=0;this._label._isLabel=true;if(!this.screen.autoPadding){if(options.side!=='right'){this._label.rleft=2;}else{this._label.rright=2;}
this._label.rtop=0;}
var reposition=function(){self._label.rtop=(self.childBase||0)-self.itop;if(!self.screen.autoPadding){self._label.rtop=(self.childBase||0);}
self.screen.render();};this.on('scroll',this._labelScroll=function(){reposition();});this.on('resize',this._labelResize=function(){nextTick(function(){reposition();});});};Element.prototype.removeLabel=function(){if(!this._label)return;this.removeListener('scroll',this._labelScroll);this.removeListener('resize',this._labelResize);this._label.detach();delete this._labelScroll;delete this._labelResize;delete this._label;};Element.prototype.setHover=function(options){if(typeof options==='string'){options={text:options};}
this._hoverOptions=options;this.enableMouse();this.screen._initHover();};Element.prototype.removeHover=function(){delete this._hoverOptions;if(!this.screen._hoverText||this.screen._hoverText.detached)return;this.screen._hoverText.detach();this.screen.render();};Element.prototype._getPos=function(){var pos=this.lpos;assert.ok(pos);if(pos.aleft!=null)return pos;pos.aleft=pos.xi;pos.atop=pos.yi;pos.aright=this.screen.cols-pos.xl;pos.abottom=this.screen.rows-pos.yl;pos.width=pos.xl-pos.xi;pos.height=pos.yl-pos.yi;return pos;};Element.prototype._getWidth=function(get){var parent=get?this.parent._getPos():this.parent,width=this.position.width,left,expr;if(typeof width==='string'){if(width==='half')width='50%';expr=width.split(/(?=\+|-)/);width=expr[0];width=+width.slice(0,-1)/100;width=parent.width*width|0;width+=+(expr[1]||0);return width;}
if(width==null){left=this.position.left||0;if(typeof left==='string'){if(left==='center')left='50%';expr=left.split(/(?=\+|-)/);left=expr[0];left=+left.slice(0,-1)/100;left=parent.width*left|0;left+=+(expr[1]||0);}
width=parent.width-(this.position.right||0)-left;if(this.screen.autoPadding){if((this.position.left!=null||this.position.right==null)&&this.position.left!=='center'){width-=this.parent.ileft;}
width-=this.parent.iright;}}
return width;};Object.defineProperty(Element.prototype,'width',{get:function(){return this._getWidth(false);},set:function(val){if(this.position.width===val)return;if(/^\d+$/.test(val))val=+val;this.emit('resize');this.clearPos();return this.position.width=val;}});Element.prototype._getHeight=function(get){var parent=get?this.parent._getPos():this.parent,height=this.position.height,top,expr;if(typeof height==='string'){if(height==='half')height='50%';expr=height.split(/(?=\+|-)/);height=expr[0];height=+height.slice(0,-1)/100;height=parent.height*height|0;height+=+(expr[1]||0);return height;}
if(height==null){top=this.position.top||0;if(typeof top==='string'){if(top==='center')top='50%';expr=top.split(/(?=\+|-)/);top=expr[0];top=+top.slice(0,-1)/100;top=parent.height*top|0;top+=+(expr[1]||0);}
height=parent.height-(this.position.bottom||0)-top;if(this.screen.autoPadding){if((this.position.top!=null||this.position.bottom==null)&&this.position.top!=='center'){height-=this.parent.itop;}
height-=this.parent.ibottom;}}
return height;};Object.defineProperty(Element.prototype,'height',{get:function(){return this._getHeight(false);},set:function(val){if(this.position.height===val)return;if(/^\d+$/.test(val))val=+val;this.emit('resize');this.clearPos();return this.position.height=val;}});Element.prototype._getLeft=function(get){var parent=get?this.parent._getPos():this.parent,left=this.position.left||0,expr;if(typeof left==='string'){if(left==='center')left='50%';expr=left.split(/(?=\+|-)/);left=expr[0];left=+left.slice(0,-1)/100;left=parent.width*left|0;left+=+(expr[1]||0);if(this.position.left==='center'){left-=this._getWidth(get)/2|0;}}
if(this.position.left==null&&this.position.right!=null){return this.screen.cols-this._getWidth(get)-this._getRight(get);}
if(this.screen.autoPadding){if((this.position.left!=null||this.position.right==null)&&this.position.left!=='center'){left+=this.parent.ileft;}}
return(parent.aleft||0)+left;};Object.defineProperty(Element.prototype,'aleft',{get:function(){return this._getLeft(false);},set:function(val){var expr;if(typeof val==='string'){if(val==='center'){val=this.screen.width/2|0;val-=this.width/2|0;}else{expr=val.split(/(?=\+|-)/);val=expr[0];val=+val.slice(0,-1)/100;val=this.screen.width*val|0;val+=+(expr[1]||0);}}
val-=this.parent.aleft;if(this.position.left===val)return;this.emit('move');this.clearPos();return this.position.left=val;}});Element.prototype._getRight=function(get){var parent=get?this.parent._getPos():this.parent,right=this.position.right||0;if(typeof right==='string'){expr=right.split(/(?=\+|-)/);right=expr[0];right=+right.slice(0,-1)/100;right=Math.ceil(parent.width*right)|0;return right;}
if(this.position.right==null&&this.position.left!=null){right=this.screen.cols-(this._getLeft(get)+this._getWidth(get));if(this.screen.autoPadding){right+=this.parent.iright;}
return right;}
right=(parent.aright||0)+(this.position.right||0);if(this.screen.autoPadding){right+=this.parent.iright;}
return right;};Object.defineProperty(Element.prototype,'aright',{get:function(){return this._getRight(false);},set:function(val){val-=this.parent.aright;if(this.position.right===val)return;this.emit('move');this.clearPos();return this.position.right=val;}});Element.prototype._getTop=function(get){var parent=get?this.parent._getPos():this.parent,top=this.position.top||0,expr;if(typeof top==='string'){if(top==='center')top='50%';expr=top.split(/(?=\+|-)/);top=expr[0];top=+top.slice(0,-1)/100;top=parent.height*top|0;top+=+(expr[1]||0);if(this.position.top==='center'){top-=this._getHeight(get)/2|0;}}
if(this.position.top==null&&this.position.bottom!=null){return this.screen.rows-this._getHeight(get)-this._getBottom(get);}
if(this.screen.autoPadding){if((this.position.top!=null||this.position.bottom==null)&&this.position.top!=='center'){top+=this.parent.itop;}}
return(parent.atop||0)+top;};Object.defineProperty(Element.prototype,'atop',{get:function(){return this._getTop(false);},set:function(val){var expr;if(typeof val==='string'){if(val==='center'){val=this.screen.height/2|0;val-=this.height/2|0;}else{expr=val.split(/(?=\+|-)/);val=expr[0];val=+val.slice(0,-1)/100;val=this.screen.height*val|0;val+=+(expr[1]||0);}}
val-=this.parent.atop;if(this.position.top===val)return;this.emit('move');this.clearPos();return this.position.top=val;}});Element.prototype._getBottom=function(get){var parent=get?this.parent._getPos():this.parent,bottom;if(this.position.bottom==null&&this.position.top!=null){bottom=this.screen.rows-(this._getTop(get)+this._getHeight(get));if(this.screen.autoPadding){bottom+=this.parent.ibottom;}
return bottom;}
bottom=(parent.abottom||0)+(this.position.bottom||0);if(this.screen.autoPadding){bottom+=this.parent.ibottom;}
return bottom;};Object.defineProperty(Element.prototype,'abottom',{get:function(){return this._getBottom(false);},set:function(val){val-=this.parent.abottom;if(this.position.bottom===val)return;this.emit('move');this.clearPos();return this.position.bottom=val;}});Object.defineProperty(Element.prototype,'rleft',{get:function(){return this.aleft-this.parent.aleft;},set:function(val){if(this.position.left===val)return;if(/^\d+$/.test(val))val=+val;this.emit('move');this.clearPos();return this.position.left=val;}});Object.defineProperty(Element.prototype,'rright',{get:function(){return this.aright-this.parent.aright;},set:function(val){if(this.position.right===val)return;this.emit('move');this.clearPos();return this.position.right=val;}});Object.defineProperty(Element.prototype,'rtop',{get:function(){return this.atop-this.parent.atop;},set:function(val){if(this.position.top===val)return;if(/^\d+$/.test(val))val=+val;this.emit('move');this.clearPos();return this.position.top=val;}});Object.defineProperty(Element.prototype,'rbottom',{get:function(){return this.abottom-this.parent.abottom;},set:function(val){if(this.position.bottom===val)return;this.emit('move');this.clearPos();return this.position.bottom=val;}});Object.defineProperty(Element.prototype,'ileft',{get:function(){return(this.border?1:0)+this.padding.left;}});Object.defineProperty(Element.prototype,'itop',{get:function(){return(this.border?1:0)+this.padding.top;}});Object.defineProperty(Element.prototype,'iright',{get:function(){return(this.border?1:0)+this.padding.right;}});Object.defineProperty(Element.prototype,'ibottom',{get:function(){return(this.border?1:0)+this.padding.bottom;}});Object.defineProperty(Element.prototype,'iwidth',{get:function(){return(this.border?2:0)+this.padding.left+this.padding.right;}});Object.defineProperty(Element.prototype,'iheight',{get:function(){return(this.border?2:0)+this.padding.top+this.padding.bottom;}});Object.defineProperty(Element.prototype,'tpadding',{get:function(){return this.padding.left+this.padding.top
+this.padding.right+this.padding.bottom;}});Object.defineProperty(Element.prototype,'left',{get:function(){return this.rleft;},set:function(val){return this.rleft=val;}});Object.defineProperty(Element.prototype,'right',{get:function(){return this.rright;},set:function(val){return this.rright=val;}});Object.defineProperty(Element.prototype,'top',{get:function(){return this.rtop;},set:function(val){return this.rtop=val;}});Object.defineProperty(Element.prototype,'bottom',{get:function(){return this.rbottom;},set:function(val){return this.rbottom=val;}});Element.prototype._getShrinkBox=function(xi,xl,yi,yl,get){if(!this.children.length){return{xi:xi,xl:xi+1,yi:yi,yl:yi+1};}
var i,el,ret,mxi=xi,mxl=xi+1,myi=yi,myl=yi+1;var _lpos;if(get){_lpos=this.lpos;this.lpos={xi:xi,xl:xl,yi:yi,yl:yl};}
for(i=0;i<this.children.length;i++){el=this.children[i];ret=el._getCoords(get);if(!ret)continue;if(el.position.left==null&&el.position.right!=null){ret.xl=xi+(ret.xl-ret.xi);ret.xi=xi;if(this.screen.autoPadding){ret.xl+=this.ileft;ret.xi+=this.ileft;}}
if(el.position.top==null&&el.position.bottom!=null){ret.yl=yi+(ret.yl-ret.yi);ret.yi=yi;if(this.screen.autoPadding){ret.yl+=this.itop;ret.yi+=this.itop;}}
if(ret.xi<mxi)mxi=ret.xi;if(ret.xl>mxl)mxl=ret.xl;if(ret.yi<myi)myi=ret.yi;if(ret.yl>myl)myl=ret.yl;}
if(get){this.lpos=_lpos;}
if(this.position.width==null&&(this.position.left==null||this.position.right==null)){if(this.position.left==null&&this.position.right!=null){xi=xl-(mxl-mxi);if(!this.screen.autoPadding){xi-=this.padding.left+this.padding.right;}else{xi-=this.ileft;}}else{xl=mxl;if(!this.screen.autoPadding){xl+=this.padding.left+this.padding.right;if(this.type==='list-table'){xl-=this.padding.left+this.padding.right;xl+=this.iright;}}else{xl+=this.iright;}}}
if(this.position.height==null&&(this.position.top==null||this.position.bottom==null)&&(!this.scrollable||this._isList)){if(this._isList){myi=0-this.itop;myl=this.items.length+this.ibottom;}
if(this.position.top==null&&this.position.bottom!=null){yi=yl-(myl-myi);if(!this.screen.autoPadding){yi-=this.padding.top+this.padding.bottom;}else{yi-=this.itop;}}else{yl=myl;if(!this.screen.autoPadding){yl+=this.padding.top+this.padding.bottom;}else{yl+=this.ibottom;}}}
return{xi:xi,xl:xl,yi:yi,yl:yl};};Element.prototype._getShrinkContent=function(xi,xl,yi,yl){if(!this._clines)return{xi:xi,xl:xl,yi:yi,yl:yl};var h=this._clines.length,w=this._clines.mwidth||1;if(this.position.width==null&&(this.position.left==null||this.position.right==null)){if(this.position.left==null&&this.position.right!=null){xi=xl-w-this.iwidth;}else{xl=xi+w+this.iwidth;}}
if(this.position.height==null&&(this.position.top==null||this.position.bottom==null)&&(!this.scrollable||this._isList)){if(this.position.top==null&&this.position.bottom!=null){yi=yl-h-this.iheight;}else{yl=yi+h+this.iheight;}}
return{xi:xi,xl:xl,yi:yi,yl:yl};};Element.prototype._getShrink=function(xi,xl,yi,yl,get){var shrinkBox=this._getShrinkBox(xi,xl,yi,yl,get),shrinkContent=this._getShrinkContent(xi,xl,yi,yl,get),xll=xl,yll=yl;if(shrinkBox.xl-shrinkBox.xi>shrinkContent.xl-shrinkContent.xi){xi=shrinkBox.xi;xl=shrinkBox.xl;}else{xi=shrinkContent.xi;xl=shrinkContent.xl;}
if(shrinkBox.yl-shrinkBox.yi>shrinkContent.yl-shrinkContent.yi){yi=shrinkBox.yi;yl=shrinkBox.yl;}else{yi=shrinkContent.yi;yl=shrinkContent.yl;}
if(xl<xll&&this.position.left==='center'){xll=(xll-xl)/2|0;xi+=xll;xl+=xll;}
if(yl<yll&&this.position.top==='center'){yll=(yll-yl)/2|0;yi+=yll;yl+=yll;}
return{xi:xi,xl:xl,yi:yi,yl:yl};};Element.prototype._getCoords=function(get,noscroll){if(this.hidden)return;var xi=this._getLeft(get),xl=xi+this._getWidth(get),yi=this._getTop(get),yl=yi+this._getHeight(get),base=this.childBase||0,el=this,fixed=this.fixed,coords,v,noleft,noright,notop,nobot,ppos,b;if(this.shrink){coords=this._getShrink(xi,xl,yi,yl,get);xi=coords.xi,xl=coords.xl;yi=coords.yi,yl=coords.yl;}
while(el=el.parent){if(el.scrollable){if(fixed){fixed=false;continue;}
break;}}
var thisparent=el;if(el&&!noscroll){ppos=thisparent.lpos;if(!ppos)return;yi-=ppos.base;yl-=ppos.base;b=thisparent.border?1:0;if(this._isLabel){b=0;}
if(yi<ppos.yi+b){if(yl-1<ppos.yi+b){return;}else{notop=true;v=ppos.yi-yi;if(this.border)v--;if(thisparent.border)v++;base+=v;yi+=v;}}else if(yl>ppos.yl-b){if(yi>ppos.yl-1-b){return;}else{nobot=true;v=yl-ppos.yl;if(this.border)v--;if(thisparent.border)v++;yl-=v;}}
if(yi>=yl)return;if(xi<el.lpos.xi){xi=el.lpos.xi;noleft=true;if(this.border)xi--;if(thisparent.border)xi++;}
if(xl>el.lpos.xl){xl=el.lpos.xl;noright=true;if(this.border)xl++;if(thisparent.border)xl--;}
if(xi>=xl)return;}
if(this.noOverflow&&this.parent.lpos){if(xi<this.parent.lpos.xi+this.parent.ileft){xi=this.parent.lpos.xi+this.parent.ileft;}
if(xl>this.parent.lpos.xl-this.parent.iright){xl=this.parent.lpos.xl-this.parent.iright;}
if(yi<this.parent.lpos.yi+this.parent.itop){yi=this.parent.lpos.yi+this.parent.itop;}
if(yl>this.parent.lpos.yl-this.parent.ibottom){yl=this.parent.lpos.yl-this.parent.ibottom;}}
return{xi:xi,xl:xl,yi:yi,yl:yl,base:base,noleft:noleft,noright:noright,notop:notop,nobot:nobot,renders:this.screen.renders};};Element.prototype.render=function(){this._emit('prerender');this.parseContent();var coords=this._getCoords(true);if(!coords){delete this.lpos;return;}
if(coords.xl-coords.xi<=0){coords.xl=Math.max(coords.xl,coords.xi);return;}
if(coords.yl-coords.yi<=0){coords.yl=Math.max(coords.yl,coords.yi);return;}
var lines=this.screen.lines,xi=coords.xi,xl=coords.xl,yi=coords.yi,yl=coords.yl,x,y,cell,attr,ch,content=this._pcontent,ci=this._clines.ci[coords.base],battr,dattr,c,visible,i,bch=this.ch;if(coords.base>=this._clines.ci.length){ci=this._pcontent.length;}
this.lpos=coords;if(this.border&&this.border.type==='line'){this.screen._borderStops[coords.yi]=true;this.screen._borderStops[coords.yl-1]=true;}
dattr=this.sattr(this.style);attr=dattr;if(ci>0){attr=this._clines.attr[Math.min(coords.base,this._clines.length-1)];}
if(this.border)xi++,xl--,yi++,yl--;if(this.tpadding||(this.valign&&this.valign!=='top')){if(this.style.transparent){for(y=Math.max(yi,0);y<yl;y++){if(!lines[y])break;for(x=Math.max(xi,0);x<xl;x++){if(!lines[y][x])break;lines[y][x][0]=colors.blend(attr,lines[y][x][0]);lines[y].dirty=true;}}}else{this.screen.fillRegion(dattr,bch,xi,xl,yi,yl);}}
if(this.tpadding){xi+=this.padding.left,xl-=this.padding.right;yi+=this.padding.top,yl-=this.padding.bottom;}
if(this.valign==='middle'||this.valign==='bottom'){visible=yl-yi;if(this._clines.length<visible){if(this.valign==='middle'){visible=visible/2|0;visible-=this._clines.length/2|0;}else if(this.valign==='bottom'){visible-=this._clines.length;}
ci-=visible*(xl-xi);}}
for(y=yi;y<yl;y++){if(!lines[y]){if(y>=this.screen.height||yl<this.ibottom){break;}else{continue;}}
for(x=xi;x<xl;x++){cell=lines[y][x];if(!cell){if(x>=this.screen.width||xl<this.iright){break;}else{continue;}}
ch=content[ci++]||bch;while(ch==='\x1b'){if(c=/^\x1b\[[\d;]*m/.exec(content.substring(ci-1))){ci+=c[0].length-1;attr=this.screen.attrCode(c[0],attr,dattr);if(this.parent._isList&&this.parent.interactive&&this.parent.items[this.parent.selected]===this&&this.parent.options.invertSelected!==false){attr=(attr&~(0x1ff<<9))|(dattr&(0x1ff<<9));}
ch=content[ci]||bch;ci++;}else{break;}}
if(ch==='\t')ch=bch;if(ch==='\n'){if(x===xi&&y!==yi&&content[ci-2]!=='\n'){x--;continue;}
ch=bch;for(;x<xl;x++){cell=lines[y][x];if(!cell)break;if(this.style.transparent){lines[y][x][0]=colors.blend(attr,lines[y][x][0]);if(content[ci])lines[y][x][1]=ch;lines[y].dirty=true;}else{if(attr!==cell[0]||ch!==cell[1]){lines[y][x][0]=attr;lines[y][x][1]=ch;lines[y].dirty=true;}}}
continue;}
if(this.screen.fullUnicode&&content[ci-1]){var point=unicode.codePointAt(content,ci-1);if(unicode.combining[point]){if(point>0x00ffff){ch=content[ci-1]+content[ci];ci++;}
if(x-1>=xi){lines[y][x-1][1]+=ch;}else if(y-1>=yi){lines[y-1][xl-1][1]+=ch;}
x--;continue;}
if(point>0x00ffff){ch=content[ci-1]+content[ci];ci++;}}
if(this._noFill)continue;if(this.style.transparent){lines[y][x][0]=colors.blend(attr,lines[y][x][0]);if(content[ci])lines[y][x][1]=ch;lines[y].dirty=true;}else{if(attr!==cell[0]||ch!==cell[1]){lines[y][x][0]=attr;lines[y][x][1]=ch;lines[y].dirty=true;}}}}
if(this.scrollbar){i=Math.max(this._clines.length,this._scrollBottom());}
if(coords.notop||coords.nobot)i=-Infinity;if(this.scrollbar&&(yl-yi)<i){x=xl-1;if(this.scrollbar.ignoreBorder&&this.border)x++;if(this.alwaysScroll){y=this.childBase/(i-(yl-yi));}else{y=(this.childBase+this.childOffset)/(i-1);}
y=yi+((yl-yi)*y|0);if(y>=yl)y=yl-1;cell=lines[y]&&lines[y][x];if(cell){if(this.track){ch=this.track.ch||' ';attr=this.sattr(this.style.track,this.style.track.fg||this.style.fg,this.style.track.bg||this.style.bg);this.screen.fillRegion(attr,ch,x,x+1,yi,yl);}
ch=this.scrollbar.ch||' ';attr=this.sattr(this.style.scrollbar,this.style.scrollbar.fg||this.style.fg,this.style.scrollbar.bg||this.style.bg);if(attr!==cell[0]||ch!==cell[1]){lines[y][x][0]=attr;lines[y][x][1]=ch;lines[y].dirty=true;}}}
if(this.border)xi--,xl++,yi--,yl++;if(this.tpadding){xi-=this.padding.left,xl+=this.padding.right;yi-=this.padding.top,yl+=this.padding.bottom;}
if(this.border){battr=this.sattr(this.style.border);y=yi;if(coords.notop)y=-1;for(x=xi;x<xl;x++){if(!lines[y])break;if(coords.noleft&&x===xi)continue;if(coords.noright&&x===xl-1)continue;cell=lines[y][x];if(!cell)continue;if(this.border.type==='line'){if(x===xi){if(!this.border.double)ch='\u250c';else ch='\u2554';if(!this.border.left){if(this.border.top){if(!this.border.double)ch='\u2500';else ch='\u2550';}else{continue;}}else{if(!this.border.top){if(!this.border.double)ch='\u2502';else ch='\u2551';}}}else if(x===xl-1){if(!this.border.double)ch='\u2510';else ch='\u2557';if(!this.border.right){if(this.border.top){if(!this.border.double)ch='\u2500';else ch='\u2550';}else{continue;}}else{if(!this.border.top){if(!this.border.double)ch='\u2502';else ch='\u2551';}}}else{if(!this.border.double)ch='\u2500';else ch='\u2550';}}else if(this.border.type==='bg'){ch=this.border.ch;}
if(!this.border.top&&x!==xi&&x!==xl-1){ch=' ';if(dattr!==cell[0]||ch!==cell[1]){lines[y][x][0]=dattr;lines[y][x][1]=ch;lines[y].dirty=true;continue;}}
if(battr!==cell[0]||ch!==cell[1]){lines[y][x][0]=battr;lines[y][x][1]=ch;lines[y].dirty=true;}}
y=yi+1;for(;y<yl-1;y++){if(!lines[y])continue;cell=lines[y][xi];if(cell){if(this.border.left){if(this.border.type==='line'){if(!this.border.double)ch='\u2502';else ch='\u2551';}else if(this.border.type==='bg'){ch=this.border.ch;}
if(!coords.noleft)
if(battr!==cell[0]||ch!==cell[1]){lines[y][xi][0]=battr;lines[y][xi][1]=ch;lines[y].dirty=true;}}else{ch=' ';if(dattr!==cell[0]||ch!==cell[1]){lines[y][xi][0]=dattr;lines[y][xi][1]=ch;lines[y].dirty=true;}}}
cell=lines[y][xl-1];if(cell){if(this.border.right){if(this.border.type==='line'){if(!this.border.double)ch='\u2502';else ch='\u2551';}else if(this.border.type==='bg'){ch=this.border.ch;}
if(!coords.noright)
if(battr!==cell[0]||ch!==cell[1]){lines[y][xl-1][0]=battr;lines[y][xl-1][1]=ch;lines[y].dirty=true;}}else{ch=' ';if(dattr!==cell[0]||ch!==cell[1]){lines[y][xl-1][0]=dattr;lines[y][xl-1][1]=ch;lines[y].dirty=true;}}}}
y=yl-1;if(coords.nobot)y=-1;for(x=xi;x<xl;x++){if(!lines[y])break;if(coords.noleft&&x===xi)continue;if(coords.noright&&x===xl-1)continue;cell=lines[y][x];if(!cell)continue;if(this.border.type==='line'){if(x===xi){if(!this.border.double)ch='\u2514';else ch='\u255a';if(!this.border.left){if(this.border.bottom){if(!this.border.double)ch='\u2500';else ch='\u2550';}else{continue;}}else{if(!this.border.bottom){if(!this.border.double)ch='\u2502';else ch='\u2551';}}}else if(x===xl-1){if(!this.border.double)ch='\u2518';else ch='\u255d';if(!this.border.right){if(this.border.bottom){if(!this.border.double)ch='\u2500';else ch='\u2550';}else{continue;}}else{if(!this.border.bottom){if(!this.border.double)ch='\u2502';else ch='\u2551';}}}else{if(!this.border.double)ch='\u2500';else ch='\u2550';}}else if(this.border.type==='bg'){ch=this.border.ch;}
if(!this.border.bottom&&x!==xi&&x!==xl-1){ch=' ';if(dattr!==cell[0]||ch!==cell[1]){lines[y][x][0]=dattr;lines[y][x][1]=ch;lines[y].dirty=true;}
continue;}
if(battr!==cell[0]||ch!==cell[1]){lines[y][x][0]=battr;lines[y][x][1]=ch;lines[y].dirty=true;}}}
if(this.shadow){y=Math.max(yi+1,0);for(;y<yl+1;y++){if(!lines[y])break;x=xl;for(;x<xl+2;x++){if(!lines[y][x])break;lines[y][x][0]=colors.blend(lines[y][x][0]);lines[y].dirty=true;}}
y=yl;for(;y<yl+1;y++){if(!lines[y])break;for(x=Math.max(xi+1,0);x<xl;x++){if(!lines[y][x])break;lines[y][x][0]=colors.blend(lines[y][x][0]);lines[y].dirty=true;}}}
this.children.forEach(function(el){if(el.screen._ci!==-1){el.index=el.screen._ci++;}
el.render();});this._emit('render',[coords]);return coords;};Element.prototype._render=Element.prototype.render;Element.prototype.insertLine=function(i,line){if(typeof line==='string')line=line.split('\n');if(i!==i||i==null){i=this._clines.ftor.length;}
i=Math.max(i,0);while(this._clines.fake.length<i){this._clines.fake.push('');this._clines.ftor.push([this._clines.push('')-1]);this._clines.rtof(this._clines.fake.length-1);}
var start=this._clines.length,diff,real;if(i>=this._clines.ftor.length){real=this._clines.ftor[this._clines.ftor.length-1];real=real[real.length-1]+1;}else{real=this._clines.ftor[i][0];}
for(var j=0;j<line.length;j++){this._clines.fake.splice(i+j,0,line[j]);}
this.setContent(this._clines.fake.join('\n'),true);diff=this._clines.length-start;if(diff>0){var pos=this._getCoords();if(!pos)return;var height=pos.yl-pos.yi-this.iheight,base=this.childBase||0,visible=real>=base&&real-base<height;if(pos&&visible&&this.screen.cleanSides(this)){this.screen.insertLine(diff,pos.yi+this.itop+real-base,pos.yi,pos.yl-this.ibottom-1);}}};Element.prototype.deleteLine=function(i,n){n=n||1;if(i!==i||i==null){i=this._clines.ftor.length-1;}
i=Math.max(i,0);i=Math.min(i,this._clines.ftor.length-1);var start=this._clines.length,diff,real=this._clines.ftor[i][0];while(n--){this._clines.fake.splice(i,1);}
this.setContent(this._clines.fake.join('\n'),true);diff=start-this._clines.length;var height=0;if(diff>0){var pos=this._getCoords();if(!pos)return;height=pos.yl-pos.yi-this.iheight;var base=this.childBase||0,visible=real>=base&&real-base<height;if(pos&&visible&&this.screen.cleanSides(this)){this.screen.deleteLine(diff,pos.yi+this.itop+real-base,pos.yi,pos.yl-this.ibottom-1);}}
if(this._clines.length<height){this.clearPos();}};Element.prototype.insertTop=function(line){var fake=this._clines.rtof[this.childBase||0];return this.insertLine(fake,line);};Element.prototype.insertBottom=function(line){var h=(this.childBase||0)+this.height-this.iheight,i=Math.min(h,this._clines.length),fake=this._clines.rtof[i-1]+1;return this.insertLine(fake,line);};Element.prototype.deleteTop=function(n){var fake=this._clines.rtof[this.childBase||0];return this.deleteLine(fake,n);};Element.prototype.deleteBottom=function(n){var h=(this.childBase||0)+this.height-1-this.iheight,i=Math.min(h,this._clines.length-1),fake=this._clines.rtof[i];n=n||1;return this.deleteLine(fake-(n-1),n);};Element.prototype.setLine=function(i,line){i=Math.max(i,0);while(this._clines.fake.length<i){this._clines.fake.push('');}
this._clines.fake[i]=line;return this.setContent(this._clines.fake.join('\n'),true);};Element.prototype.setBaseLine=function(i,line){var fake=this._clines.rtof[this.childBase||0];return this.setLine(fake+i,line);};Element.prototype.getLine=function(i){i=Math.max(i,0);i=Math.min(i,this._clines.fake.length-1);return this._clines.fake[i];};Element.prototype.getBaseLine=function(i){var fake=this._clines.rtof[this.childBase||0];return this.getLine(fake+i);};Element.prototype.clearLine=function(i){i=Math.min(i,this._clines.fake.length-1);return this.setLine(i,'');};Element.prototype.clearBaseLine=function(i){var fake=this._clines.rtof[this.childBase||0];return this.clearLine(fake+i);};Element.prototype.unshiftLine=function(line){return this.insertLine(0,line);};Element.prototype.shiftLine=function(n){return this.deleteLine(0,n);};Element.prototype.pushLine=function(line){if(!this.content)return this.setLine(0,line);return this.insertLine(this._clines.fake.length,line);};Element.prototype.popLine=function(n){return this.deleteLine(this._clines.fake.length-1,n);};Element.prototype.getLines=function(){return this._clines.fake.slice();};Element.prototype.getScreenLines=function(){return this._clines.slice();};Element.prototype.strWidth=function(text){text=this.parseTags?helpers.stripTags(text):text;return this.screen.fullUnicode?unicode.strWidth(text):helpers.dropUnicode(text).length;};Element.prototype.screenshot=function(xi,xl,yi,yl){xi=this.lpos.xi+this.ileft+(xi||0);if(xl!=null){xl=this.lpos.xi+this.ileft+(xl||0);}else{xl=this.lpos.xl-this.iright;}
yi=this.lpos.yi+this.itop+(yi||0);if(yl!=null){yl=this.lpos.yi+this.itop+(yl||0);}else{yl=this.lpos.yl-this.ibottom;}
return this.screen.screenshot(xi,xl,yi,yl);};module.exports=Element;};BundleModuleCode['term/widgets/arrows']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Helpers=Require('term/helpers');var Button=Require('term/widgets/button');module.exports=function(parent,options,up,down,nocontrol){var bbox;bbox=Helpers.bbox(parent.screen,options);parent._.up=new Button({screen:parent.screen,top:bbox.top+1,height:options.arrows.height||1,left:bbox.left+bbox.width,width:options.arrows.width||3,content:options.arrows.up||'[-]',align:'center',style:{fg:options.arrows.fg||'red',bg:options.arrows.bg||'white',bold:true,},autoFocus:false,hidden:options.hidden,mouse:true});parent._.up.on('press',up);parent.screen.append(parent._.up);parent._.down=new Button({screen:this.screen,top:bbox.top+bbox.height-1-(options.arrows.height||1),height:options.arrows.height||1,left:bbox.left+bbox.width,width:options.arrows.width||3,content:options.arrows.down||'[+]',align:'center',style:{fg:options.arrows.fg||'red',bg:options.arrows.bg||'white',bold:true,},autoFocus:false,hidden:options.hidden,mouse:true});parent._.down.on('press',down);parent.screen.append(parent._.down);if(!nocontrol){parent._hide=parent.hide;parent.hide=function(){parent._hide();if(parent._.up)parent._.up.hide();if(parent._.down)parent._.down.hide();parent.screen.render();}
parent._show=parent.show;parent.show=function(){parent._show();if(parent._.up)parent._.up.show();if(parent._.down)parent._.down.show();parent.screen.render();}}}};BundleModuleCode['term/widgets/scrollabletext']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var ScrollableBox=Require('term/widgets/scrollablebox');function ScrollableText(options){if(!instanceOf(this,Node)){return new ScrollableText(options);}
options=options||{};options.alwaysScroll=true;ScrollableBox.call(this,options);}
inheritPrototype(ScrollableText,ScrollableBox);ScrollableText.prototype.type='scrollable-text';module.exports=ScrollableText;};BundleModuleCode['term/widgets/scrollablebox']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function ScrollableBox(options){var self=this;if(!instanceOf(this,Node)){return new ScrollableBox(options);}
options=options||{};Box.call(this,options);if(options.scrollable===false){return this;}
this.scrollable=true;this.childOffset=0;this.childBase=0;this.baseLimit=options.baseLimit||Infinity;this.alwaysScroll=options.alwaysScroll;this.scrollbar=options.scrollbar;if(this.scrollbar){this.scrollbar.ch=this.scrollbar.ch||' ';this.style.scrollbar=this.style.scrollbar||this.scrollbar.style;if(!this.style.scrollbar){this.style.scrollbar={};this.style.scrollbar.fg=this.scrollbar.fg;this.style.scrollbar.bg=this.scrollbar.bg;this.style.scrollbar.bold=this.scrollbar.bold;this.style.scrollbar.underline=this.scrollbar.underline;this.style.scrollbar.inverse=this.scrollbar.inverse;this.style.scrollbar.invisible=this.scrollbar.invisible;}
if(this.track||this.scrollbar.track){this.track=this.scrollbar.track||this.track;this.style.track=this.style.scrollbar.track||this.style.track;this.track.ch=this.track.ch||' ';this.style.track=this.style.track||this.track.style;if(!this.style.track){this.style.track={};this.style.track.fg=this.track.fg;this.style.track.bg=this.track.bg;this.style.track.bold=this.track.bold;this.style.track.underline=this.track.underline;this.style.track.inverse=this.track.inverse;this.style.track.invisible=this.track.invisible;}
this.track.style=this.style.track;}
if(options.mouse){this.on('mousedown',function(data){if(self._scrollingBar){delete self.screen._dragging;delete self._drag;return;}
var x=data.x-self.aleft;var y=data.y-self.atop;self.emit('clicked',{x:x-1,y:y-1,ev:'click'});if(x===self.width-self.iright-1){delete self.screen._dragging;delete self._drag;var perc=(y-self.itop)/(self.height-self.iheight);self.setScrollPerc(perc*100|0);self.screen.render();var smd,smu;self._scrollingBar=true;self.onScreenEvent('mousedown',smd=function(data){var y=data.y-self.atop;var perc=y/self.height;self.setScrollPerc(perc*100|0);self.screen.render();});self.onScreenEvent('mouseup',smu=function(){self._scrollingBar=false;self.removeScreenEvent('mousedown',smd);self.removeScreenEvent('mouseup',smu);});}});}}
if(options.mouse){this.on('wheeldown',function(){self.scroll(self.height/2|0||1);self.screen.render();});this.on('wheelup',function(){self.scroll(-(self.height/2|0)||-1);self.screen.render();});}
if(options.keys&&!options.ignoreKeys){this.on('keypress',function(ch,key){if(key.name==='up'||(options.vi&&key.name==='k')){self.scroll(-1);self.screen.render();return;}
if(key.name==='down'||(options.vi&&key.name==='j')){self.scroll(1);self.screen.render();return;}
if(key.name==='pageup'){self.scroll(-(self.height/2|0)||-1);self.screen.render();return;}
if(key.name==='pagedown'){self.scroll(self.height/2|0||1);self.screen.render();return;}
if(options.vi&&key.name==='u'&&key.ctrl){self.scroll(-(self.height/2|0)||-1);self.screen.render();return;}
if(options.vi&&key.name==='d'&&key.ctrl){self.scroll(self.height/2|0||1);self.screen.render();return;}
if(options.vi&&key.name==='b'&&key.ctrl){self.scroll(-self.height||-1);self.screen.render();return;}
if(options.vi&&key.name==='f'&&key.ctrl){self.scroll(self.height||1);self.screen.render();return;}
if(options.vi&&key.name==='g'&&!key.shift){self.scrollTo(0);self.screen.render();return;}
if(options.vi&&key.name==='g'&&key.shift){self.scrollTo(self.getScrollHeight());self.screen.render();return;}});}
this.on('parsed content',function(){self._recalculateIndex();});self._recalculateIndex();}
inheritPrototype(ScrollableBox,Box);ScrollableBox.prototype.type='scrollable-box';Object.defineProperty(ScrollableBox.prototype,'reallyScrollable',{get:function(){if(this.shrink)return this.scrollable;return this.getScrollHeight()>this.height;},set:function(val){}});ScrollableBox.prototype._scrollBottom=function(){if(!this.scrollable)return 0;if(this._isList){return this.items?this.items.length:0;}
if(this.lpos&&this.lpos._scrollBottom){return this.lpos._scrollBottom;}
var bottom=this.children.reduce(function(current,el){if(!el.detached){var lpos=el._getCoords(false,true);if(lpos){return Math.max(current,el.rtop+(lpos.yl-lpos.yi));}}
return Math.max(current,el.rtop+el.height);},0);if(this.lpos)this.lpos._scrollBottom=bottom;return bottom;};ScrollableBox.prototype.setScroll=ScrollableBox.prototype.scrollTo=function(offset,always){this.scroll(0);return this.scroll(offset-(this.childBase+this.childOffset),always);};ScrollableBox.prototype.getScroll=function(){return this.childBase+this.childOffset;};ScrollableBox.prototype.scroll=function(offset,always){if(!this.scrollable)return;if(this.detached)return;var visible=this.height-this.iheight,base=this.childBase,d,p,t,b,max,emax;if(this.alwaysScroll||always){this.childOffset=offset>0?visible-1+offset:offset;}else{this.childOffset+=offset;}
if(this.childOffset>visible-1){d=this.childOffset-(visible-1);this.childOffset-=d;this.childBase+=d;}else if(this.childOffset<0){d=this.childOffset;this.childOffset+=-d;this.childBase+=d;}
if(this.childBase<0){this.childBase=0;}else if(this.childBase>this.baseLimit){this.childBase=this.baseLimit;}
if(this.childBase===base){return this.emit('scroll');}
this.parseContent();max=this._clines.length-(this.height-this.iheight);if(max<0)max=0;emax=this._scrollBottom()-(this.height-this.iheight);if(emax<0)emax=0;this.childBase=Math.min(this.childBase,Math.max(emax,max));if(this.childBase<0){this.childBase=0;}else if(this.childBase>this.baseLimit){this.childBase=this.baseLimit;}
p=this.lpos;if(p&&this.childBase!==base&&this.screen.cleanSides(this)){t=p.yi+this.itop;b=p.yl-this.ibottom-1;d=this.childBase-base;if(d>0&&d<visible){this.screen.deleteLine(d,t,t,b);}else if(d<0&&-d<visible){d=-d;this.screen.insertLine(d,t,t,b);}}
return this.emit('scroll');};ScrollableBox.prototype.scrollBottom=function(){this.scrollTo(10000000);};ScrollableBox.prototype._recalculateIndex=function(){var max,emax;if(this.detached||!this.scrollable){return 0;}
max=this._clines.length-(this.height-this.iheight);if(max<0)max=0;emax=this._scrollBottom()-(this.height-this.iheight);if(emax<0)emax=0;this.childBase=Math.min(this.childBase,Math.max(emax,max));if(this.childBase<0){this.childBase=0;}else if(this.childBase>this.baseLimit){this.childBase=this.baseLimit;}};ScrollableBox.prototype.resetScroll=function(){if(!this.scrollable)return;this.childOffset=0;this.childBase=0;return this.emit('scroll');};ScrollableBox.prototype.getScrollHeight=function(){return Math.max(this._clines.length,this._scrollBottom());};ScrollableBox.prototype.getScrollPerc=function(s){var pos=this.lpos||this._getCoords();if(!pos)return s?-1:0;var height=(pos.yl-pos.yi)-this.iheight,i=this.getScrollHeight(),p;if(height<i){if(this.alwaysScroll){p=this.childBase/(i-height);}else{p=(this.childBase+this.childOffset)/(i-1);}
return p*100;}
return s?-1:0;};ScrollableBox.prototype.setScrollPerc=function(i){var m=Math.max(this._clines.length,this._scrollBottom());return this.scrollTo((i/100)*m|0);};module.exports=ScrollableBox;};BundleModuleCode['term/widgets/chat']=function(module,exports){var Comp=Require('com/compat');var unicode=Require('term/unicode');var nextTick=global.setImmediate||process.nextTick.bind(process);var Node=Require('term/widgets/node');var Input=Require('term/widgets/input');function setCharAt(str,index,chr){if(index>str.length-1)return str;return str.substring(0,index)+chr+str.substring(index+1);}
function Chat(options){var self=this;if(!instanceOf(this,Node)){return new Chat(options);}
options=options||{};options.scrollable=options.scrollable!==false;Input.call(this,options);this.screen._listenKeys(this);this.value=options.value||'';this.cpos={x:-1,y:-1};this.cursorControl=true;this.multiline=options.multiline;this.tags=true;this.input='text';this.history=[];this.historyTop=0;this.__updateCursor=this._updateCursor.bind(this);this.on('resize',this.__updateCursor);this.on('move',this.__updateCursor);if(options.inputOnFocus){this.on('focus',this.readInput.bind(this,null));}
if(!options.inputOnFocus&&options.keys){this.on('keypress',function(ch,key){if(self._reading)return;if(key.name==='enter'||(options.vi&&key.name==='i')){return self.readInput();}
if(key.name==='e'){return self.readEditor();}});}
if(options.mouse){this.on('click',function(data){if(self._reading)return;if(data.button!=='right')return;self.readEditor();});}
var offsetY=0;if(this._clines)offsetY=this._clines.length-(this.childBase||0);if(options.prompt){this.value=options.prompt;this.prompt=options.prompt;this.inputRange={x0:options.prompt.length,y0:offsetY,y1:offsetY,last:0,line:0};}else{this.inputRange={x0:0,y0:offsetY,y1:offsetY,last:0,line:0};this.prompt='';}}
inheritPrototype(Chat,Input);Chat.prototype.type='terminal';Chat.prototype._updateCursor=function(get){var offsetY=this.childBase||0;if(this.screen.focused!==this){this.cpos.y=Math.min(this._clines.length-1-offsetY,this.cpos.y);return;}
var lpos=get?this.lpos:this._getCoords();if(!lpos)return;var last=this._clines[this._clines.length-1],program=this.screen.program,line,offsetY=this.childBase||0,cx,cy;if(last===''&&this.value[this.value.length-1]!=='\n'){last=this._clines[this._clines.length-2]||'';}
line=Math.min(this._clines.length-1-(this.childBase||0),(lpos.yl-lpos.yi)-this.iheight-1);line=Math.max(0,line);if(this.cpos.x==-1||!this.cursorControl)this.cpos.x=this.strWidth(last);if(this.cpos.y==-1||!this.cursorControl)this.cpos.y=line;this.cpos.y=Math.min(this.cpos.y,line);this.cpos.x=Math.min(this.cpos.x,this.strWidth(this._clines[offsetY+this.cpos.y]));cx=lpos.xi+this.ileft+this.cpos.x;cy=lpos.yi+this.itop+this.cpos.y;if(cy===program.y&&cx===program.x){return;}
if(cy===program.y){if(cx>program.x){program.cuf(cx-program.x);}else if(cx<program.x){program.cub(program.x-cx);}}else if(cx===program.x){if(cy>program.y){program.cud(cy-program.y);}else if(cy<program.y){program.cuu(program.y-cy);}}else{program.cup(cy,cx);}};Chat.prototype.input=Chat.prototype.setInput=Chat.prototype.readInput=function(callback){var self=this,focused=this.screen.focused===this;if(this._reading)return;this._reading=true;this._callback=callback;if(!focused){this.screen.saveFocus();this.focus();}
this.screen.grabKeys=true;this._updateCursor();this.screen.program.showCursor();this._done=function fn(err,value){if(!self._reading)return;if(fn.done)return;fn.done=true;self._reading=false;delete self._callback;delete self._done;self.removeListener('keypress',self.__listener);delete self.__listener;self.removeListener('blur',self.__done);delete self.__done;self.screen.program.hideCursor();self.screen.grabKeys=false;if(!focused){self.screen.restoreFocus();}
if(self.options.inputOnFocus){self.screen.rewindFocus();}
if(err==='stop')return;if(err){self.emit('error',err);}else if(value!=null){self.emit('submit',value);}else{self.emit('cancel',value);}
self.emit('action',value);if(!callback)return;return err?callback(err):callback(null,value);};nextTick(function(){if(self.__listener){return;}
self.__listener=self._listener.bind(self);self.on('keypress',self.__listener);});this.__done=this._done.bind(this,null,null);this.on('blur',this.__done);};Chat.prototype.ask=function(message,options,callback){var offsetY=this.childBase||0,prompt=this.prompt,self=this;options=options||{};if(this.request){return;}
var restorePos=offsetY+this.cpos.y;function ask(command,restore){offsetY=self.childBase||0;var start=self.getLinearPos(self.value,offsetY+self.inputRange.y0,0),end=self.getLinearPos(self.value,offsetY+self.inputRange.y1,self._clines[offsetY+self.inputRange.y1].length);var line;if(restore)start=self.getLinearPos(self.value,restorePos,0);self.value=self.value.slice(0,start)+self.prompt+command+self.value.slice(end);self.screen.render();self.scrollBottom();self.cpos.x=self._clines[self._clines.length-1].length;self.cpos.y+=10;self._updateCursor(true);self.inputRange.y1=self.cpos.y;offsetY=self.childBase||0;var y0=self.cpos.y;self.inputRange.x0=self.prompt.length;self.inputRange.x1=null;while(self._clines[offsetY+y0].indexOf(self.prompt)!=0)y0--;self.inputRange.y0=y0;self.inputRange.last=self.inputRange.y1-self.inputRange.y0;}
this.print('{bold}'+message+'{/bold}');if(options.choices){var choices=options.choices.slice();this.prompt='? ';var delim=options.layout=='vertical'?'\n':' ',indent=options.layout=='vertical'?' ':'';if(!options.mutable){line=choices.map(function(s,i){return(i>0?indent:'')+'[ ] '+s}).join(delim);line+=(delim+indent+'[Ok] [Cancel]');choices.push(restore1);choices.push(restore1);}else{line=choices.map(function(s,i){return(i>0?indent:'')+'['+s+']'}).join(delim);line+=(delim+indent+'[Cancel]');choices.push(restore1);}
ask(line);this.input='mouse';this.screen.program.hideCursor(true);var y=this.inputRange.y0,x=this.inputRange.x0;line=this._clines[offsetY+y];var actions=choices.map(function(choice,index){while(line[x]&&line[x]!='['){x++;if(!line[x]&&y<self.inputRange.y1){x=0;y++;line=self._clines[offsetY+y];}}
if(line[x]&&line[x+1]==' '){x++;return{choice:choice,index:index,fake:self.getLinearPos(self.value,offsetY+y,x),pos:{x:x,y:y}};}else{x++;var start={x:x,y:y};while(line[x]&&line[x]!=']'){x++;if(!line[x]&&y<self.inputRange.y1){x=0;y++;line=self._clines[offsetY+y];}}
var end={x:x-1,y:y}
return typeof choice=='string'?{choice:choice,index:index,pos:[start,end]}:{action:choice,index:index,pos:[start,end]};}});function clicked1(pos){var offsetY=self.childBase||0;function within(o){if(typeof o.x!='undefined'){return pos.x==o.x&&pos.y==o.y}else if(o.length==2){if(o[0].y==o[1].y&&o[0].y==pos.y)
return pos.x>=o[0].x&&pos.x<=o[1].x;else if(pos.y>=o[0].y&&pos.y<=o[1].y)
return pos.x>=o[0].x&&pos.x<=o[1].x}}
actions.forEach(function(action){if(!action)return;if(within(action.pos)){if(action.choice){if(self.selected.indexOf(action.choice)!=-1){self.selected=self.selected.filter(function(choice){return choice!=action.choice});self.value=setCharAt(self.value,action.fake,' ');self.screen.render();}else{if(!options.mutable){self.value=setCharAt(self.value,action.fake,'X');self.screen.render();changed1();}
self.selected.push(action.choice);if(options.mutable)restore1();}}
if(action.action){action.action();}}})};function changed1(){if(options.timeout){if(self.timer)clearTimeout(self.timer);self.timer=setTimeout(restore1,options.timeout);}}
function restore1(timeout){var result=callback?callback(self.selected):null;if(self.selected!=undefined&&self.selected.length)
self.print(self.selected.join(', '),self.style.user);if(result)self.print(result);self.prompt=prompt;ask('',!result&&self.selected.length==0);self.input='text';self.removeListener('clicked',clicked1);if(!timeout&&self.timer)clearTimeout(self.timer);self.timer=null;self.request=null;}
this.on('clicked',clicked1);this.selected=[];if(options.timeout){this.timer=setTimeout(restore1,options.timeout);}}
if(options.range){var sign=options.range[0]<0,step=options.step||1,digits=Math.floor(Math.log10(options.range[1]-options.range[0]+1))+1;if(sign)digits++;var value=options.default||options.value||options.range[0];line='[-] '+Comp.printf.sprintf("%"+digits+"d",value)+' [+] [Ok] [Cancel]';this.prompt='? ';ask(line);var x0=this._clines[offsetY+this.cpos.y].indexOf('[-] ')+4;var x1=this._clines[offsetY+this.cpos.y].indexOf(' [+]')-1;this.cpos.x=x1;this.inputRange.x0=x0;this.inputRange.x1=x1;this.inputRange.right=true;this.inputRange.action=function(){var _value=Number(self._clines[offsetY+self.cpos.y].slice(x0,x1+1));if(_value>=options.range[0]&&_value<=options.range[1]){self.selected=value;restore2();}else{value=options.range[0];line='[-] '+Comp.printf.sprintf("%"+digits+"d",value)+' [+] [Ok] [Cancel]';ask(line);self.inputRange.x0=x0;self.inputRange.x1=x1;self.cpos.x=x1;self._updateCursor();}}
this._updateCursor();actions=[{pos:{x:this._clines[offsetY+this.cpos.y].indexOf('[-]')+1,y:this.cpos.y},action:function(){value=Math.max(options.range[0],value-step);line='[-] '+Comp.printf.sprintf("%"+digits+"d",value)+' [+] [Ok] [Cancel]';ask(line);self.inputRange.x0=x0;self.inputRange.x1=x1;self.cpos.x=x1;self._updateCursor();}},{pos:{x:this._clines[offsetY+this.cpos.y].indexOf('[+]')+1,y:this.cpos.y},action:function(){value=Math.min(options.range[1],value+step);line='[-] '+Comp.printf.sprintf("%"+digits+"d",value)+' [+] [Ok] [Cancel]';ask(line);self.inputRange.x0=x0;self.inputRange.x1=x1;self.cpos.x=x1;self._updateCursor();}},{pos:[{x:this._clines[offsetY+this.cpos.y].indexOf('[Ok]')+1,y:this.cpos.y},{x:this._clines[offsetY+this.cpos.y].indexOf('[Ok]')+2,y:this.cpos.y}],action:function(){var _value=Number(self._clines[offsetY+self.cpos.y].slice(x0,x1+1));if(_value>=options.range[0]&&_value<=options.range[1]){self.selected=value;restore2();}else{value=options.range[0];line='[-] '+Comp.printf.sprintf("%"+digits+"d",value)+' [+] [Ok] [Cancel]';ask(line);self.inputRange.x0=x0;self.inputRange.x1=x1;self.cpos.x=x1;self._updateCursor();}}},{pos:[{x:this._clines[offsetY+this.cpos.y].indexOf('[Cancel]')+1,y:this.cpos.y},{x:this._clines[offsetY+this.cpos.y].indexOf('[Cancel]')+6,y:this.cpos.y}],action:function(){restore2()}}]
function clicked2(pos){var offsetY=self.childBase||0;function within(o){if(typeof o.x!='undefined'){return pos.x==o.x&&pos.y==o.y}else if(o.length==2){if(o[0].y==o[1].y&&o[0].y==pos.y)
return pos.x>=o[0].x&&pos.x<=o[1].x;else if(pos.y>=o[0].y&&pos.y<=o[1].y)
return pos.x>=o[0].x&&pos.x<=o[1].x}}
actions.forEach(function(action){if(!action)return;if(within(action.pos))action.action();})}
function changed2(){var _value=Number(self._clines[offsetY+self.cpos.y].slice(x0,x1+1));if(isNaN(_value)||_value<options.range[0]||_value>options.range[1]){}else value=_value;if(options.timeout){if(self.timer)clearTimeout(self.timer);self.timer=setTimeout(restore2,options.timeout);}}
function restore2(timeout){var result=callback?callback(self.selected):null;if(self.selected!=undefined)self.print(self.selected,self.style.user);if(result)self.print(result);self.prompt=prompt;ask('',!result&&self.selected==undefined);self.removeListener('clicked',clicked2);self.removeListener('modified',changed2);if(!timeout&&self.timer)clearTimeout(self.timer);self.timer=null;self.inputRange.action=null;self.inputRange.right=null;self.request=null;}
this.selected=null;this.on('clicked',clicked2);this.on('modified',changed2);if(options.timeout){this.timer=setTimeout(restore2,options.timeout);}}
if(options.text){this.selected=null;function changed3(){var offsetY=self.childBase||0,vpos=self.getLinearPos(self.value,offsetY+self.inputRange.y0,self.inputRange.x0);self.selected=value=self.value.slice(vpos,1000000);if(options.timeout){if(self.timer)clearTimeout(self.timer);self.timer=setTimeout(restore3,options.timeout);}}
function restore3(timeout){var result=callback?callback(self.selected):null;if(self.selected!=undefined)self.print(self.selected,self.style.user);if(result)self.print(result);self.prompt=prompt;ask('',!result&&self.selected==undefined);self.removeListener('modified',changed3);if(!timeout&&self.timer)clearTimeout(self.timer);self.timer=null;self.inputRange.action=null;self.request=null;}
this.inputRange.action=function(){restore3()}
this.on('modified',changed3);if(options.timeout){this.timer=setTimeout(restore3,options.timeout);}}
this.request={message:message,options:options,callback:callback};}
Chat.prototype.message=function(line,style){return this.print(line,style||this.style.bot);}
Chat.prototype.print=function(line,style){var offsetY=this.childBase||0,cn1=this._clines.length,y0=this.inputRange.y0,start=this.getLinearPos(this.value,offsetY+this.inputRange.y0,0),end=this.getLinearPos(this.value,offsetY+this.inputRange.y1,this._clines[offsetY+this.inputRange.y1].length);if(style){if(style.color)line='{'+style.color+'-fg}'+line+'{/'+style.color+'-fg}';if(style.align=='right')line='{right}'+line+'{/right}';}
var command=this.value.slice(start,end);this.value=this.value.slice(0,start)+line+'\n'+command+this.value.slice(end);this.screen.render();var cn2=this._clines.length;this.scrollBottom();this.cpos.y+=10;this.cpos.x=this.inputRange.x0=this.prompt.length;this._updateCursor(true);this.inputRange.y0=Math.min(this._clines.length-1,this.cpos.y-this.inputRange.last);this.inputRange.y1=Math.min(this._clines.length-1,this.cpos.y);}
Chat.prototype._listener=function(ch,key){var done=this._done,self=this,value=this.value,clinesLength=this._clines.length,offsetY=this.childBase||0,newline=false,lastchar=false,backspace=false,controlkey=false,lastline=(this.cpos.y+offsetY+1)==clinesLength;if(key.name==='return')return;if(key.name==='delete'){if(this.inputRange.x1!=undefined){vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);var vpos0=vpos-(this.cpos.x-this.inputRange.x0);this.value=this.value.substr(0,vpos0)+' '+
this.value.substr(vpos0,vpos-vpos0)+
this.value.substr(vpos+1,1000000);this.screen.render();}
return;}
if(key.name==='enter'){if(this.inputRange.action)return this.inputRange.action();var start=this.getLinearPos(this.value,offsetY+this.inputRange.y0,0),end=this.getLinearPos(this.value,offsetY+this.inputRange.y1,this._clines[offsetY+this.inputRange.y1].length);var command=this.value.slice(start+this.prompt.length,end);if(command&&command!=this.history[this.historyTop-1]){this.history.push(command);this.historyTop=this.history.length;}
this.value=this.value.slice(0,start)+this.prompt+this.value.slice(end);this.screen.render();offsetY=this.childBase||0;self.cpos.y+=10;this._updateCursor(true);this.cpos.x=self._clines[offsetY+self.cpos.y].length;this.inputRange.y0=this.inputRange.y1=this.cpos.y;this.inputRange.last=0;this.print(command,this.style.user);this.emit('eval',command);return;}
if(this.input!='text')return;function history(delta){if(self.historyTop+delta<0)return self.scrollBottom();self.historyTop+=delta;var start=self.getLinearPos(self.value,offsetY+self.inputRange.y0,0),end=self.getLinearPos(self.value,offsetY+self.inputRange.y1,self._clines[offsetY+self.inputRange.y1].length);var command=self.history[self.historyTop]||'';self.historyTop=Math.min(Math.max(0,self.historyTop),self.history.length);self.value=self.value.slice(0,start)+self.prompt+command+self.value.slice(end);self.screen.render();self.scrollBottom();self.cpos.x=self._clines[self._clines.length-1].length;self.cpos.y+=10;self._updateCursor(true);self.inputRange.y1=self.cpos.y;offsetY=self.childBase||0;var y0=self.cpos.y;while(self._clines[offsetY+y0].indexOf(self.prompt)!=0)y0--;self.inputRange.y0=y0;self.inputRange.last=self.inputRange.y1-self.inputRange.y0;}
if(this.cursorControl)switch(key.name){case'left':controlkey=true;if(this.cpos.y==this.inputRange.y0&&this.cpos.x>this.inputRange.x0)this.cpos.x--;else if(this.cpos.y!=this.inputRange.y0&&this.cpos.x>0)this.cpos.x--;else if(this.cpos.y!=this.inputRange.y0&&this.cpos.x==0){this.cpos.y--;this.cpos.x=this._clines[offsetY+this.cpos.y].length;}
this._updateCursor(true);break;case'right':controlkey=true;if(this.inputRange.x1!=undefined&&this.cpos.x>=this.inputRange.x1)return;if(this.cpos.y>=this.inputRange.y0&&this.cpos.y<=this.inputRange.y1&&this.cpos.x<this._clines[offsetY+this.cpos.y].length-1){this.cpos.x++;}else if(this.cpos.y>=this.inputRange.y0&&this.cpos.y<this.inputRange.y1&&this.cpos.x==this._clines[offsetY+this.cpos.y].length-1){this.cpos.x=0;this.cpos.y++;}else if(this.cpos.y>=this.inputRange.y0&&this.cpos.y==this.inputRange.y1&&this.cpos.x<this._clines[offsetY+this.cpos.y].length){this.cpos.x++;}
this._updateCursor(true);break;case'up':controlkey=true;history(-1);return;break;case'down':controlkey=true;history(1);return;break;}
if(this.options.keys&&key.ctrl&&key.name==='e'){return this.readEditor();}
if(key.name==='escape'){done(null,null);}else if(key.name==='backspace'){backspace=true;if(this.cpos.y==this.inputRange.y0&&this.cpos.x<=this.inputRange.x0)return;if(this.inputRange.x1!=undefined){vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);var vpos0=vpos-(this.cpos.x-this.inputRange.x0);this.value=this.value.substr(0,vpos0)+' '+
this.value.substr(vpos0,vpos-vpos0)+
this.value.substr(vpos+1,1000000);this.screen.render();return;}
if(this.value.length){if(this.screen.fullUnicode){if(unicode.isSurrogate(this.value,this.value.length-2)){this.value=this.value.slice(0,-2);}else{this.value=this.value.slice(0,-1);}}else{if(!this.cursorControl||this.cpos.x==-1||(this.cpos.x==this._clines[offsetY+this.cpos.y].length&&this.cpos.y==this._clines.length-1-offsetY)){this.value=this.value.slice(0,-1);}else{vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);this.value=this.value.substr(0,vpos-1)+
this.value.substr(vpos,1000000);}}
if(this.cpos.x>0)this.cpos.x--;else{this.cpos.x=-1;if(offsetY==0&&this.cpos.y>0&&lastline)this.cpos.y--;};}}else if(!controlkey&&ch&&this.inputRange.x1==undefined){if(!/^[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]$/.test(ch)){if(!this.cursorControl||this.cpos.x==-1||(this.cpos.x==this._clines[offsetY+this.cpos.y].length&&this.cpos.y==this._clines.length-1-offsetY)){lastchar=true;this.value+=ch;}else{vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);this.value=this.value.substr(0,vpos)+ch+
this.value.substr(vpos,1000000);}
if(newline){this.cpos.x=0;this.cpos.y++;}else
this.cpos.x++;}}else if(!controlkey&&ch&&this.inputRange.x1!=undefined){if(!/^[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]$/.test(ch)){vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);if(this.cpos.x!=this.inputRange.x1){this.value=setCharAt(this.value,vpos,ch);}else{var vpos0=vpos-(this.inputRange.x1-this.inputRange.x0);this.value=this.value.substr(0,vpos0)+
this.value.substr(vpos0+1,vpos-vpos0)+ch+
this.value.substr(vpos+1,1000000);}
if(this.cpos.x<this.inputRange.x1)this.cpos.x++;}}
var rmline=this.cpos.x==-1;if(this.value!==value){var cn0=clinesLength,endofline=this.cpos.x==this._clines[offsetY+this.cpos.y].length+1,cn1=this._clines.length;var linelength1=this._clines[offsetY+this.cpos.y]&&this._clines[offsetY+this.cpos.y].length;this.screen.render();var linelength2=this._clines[offsetY+this.cpos.y]&&this._clines[offsetY+this.cpos.y].length;var cn2=this._clines.length;if(cn2>cn0&&endofline){this.scrollBottom();this.cpos.y++;this.inputRange.last++;if(this._clines[offsetY+this.cpos.y]&&lastchar)this.cpos.x=this._clines[offsetY+this.cpos.y].length;else this.cpos.x=linelength1-linelength2-1;this._updateCursor(true);this.inputRange.y0=this.cpos.y-this.inputRange.last;this.inputRange.y1=this.cpos.y;}else if(cn2<cn0&&!rmline){if(this.cpos.y>0&&!lastline&&lastchar)this.cpos.y--;this.inputRange.last--;if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);this.inputRange.y0=this.cpos.y-this.inputRange.last;this.inputRange.y1=this.cpos.y;offsetY=this.childBase||0;this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);}else if(linelength2<linelength1&&!backspace){this.cpos.y++;this.cpos.x=linelength1-linelength2;this._updateCursor(true);}
if(offsetY>0&&backspace){this.scroll(0);this.screen.render();if(rmline){if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;else if(this._clines[offsetY+this.cpos.y-1])this.cpos.x=this._clines[offsetY+this.cpos.y-1].length;this._updateCursor(true);}}
this.emit('modified');}};Chat.prototype.getLinearPos=function(v,clineIndex,cposx){var lines=v.split('\n'),line=this._clines[clineIndex],flinenum=this._clines.rtof[clineIndex],vpos=flinenum>0?lines.slice(0,flinenum).map(function(line){return line.length+1}).reduce(function(a,b){return a+b}):0;function search(part,line){var i=line.indexOf(part);if(i==-1)return 0;else return i;}
if(lines[flinenum]){return vpos+search(line,lines[flinenum])+cposx;}else
return vpos+cposx;}
Chat.prototype._typeScroll=function(){var height=this.height-this.iheight;if(this.cpos.y==height){this.scroll(this._clines.length);}};Chat.prototype.getValue=function(){return this.value;};Chat.prototype.setValue=function(value){if(value==null){value=this.value;}
if(this._value!==value){this.value=value;this._value=value;this.setContent(this.value);this._typeScroll();this._updateCursor();}};Chat.prototype.clearInput=Chat.prototype.clearValue=function(){return this.setValue('');};Chat.prototype.submit=function(){if(!this.__listener)return;return this.__listener('\x1b',{name:'escape'});};Chat.prototype.cancel=function(){if(!this.__listener)return;return this.__listener('\x1b',{name:'escape'});};Chat.prototype.render=function(){this.setValue();return this._render();};Chat.prototype.editor=Chat.prototype.setEditor=Chat.prototype.readEditor=function(callback){var self=this;if(this._reading){var _cb=this._callback,cb=callback;this._done('stop');callback=function(err,value){if(_cb)_cb(err,value);if(cb)cb(err,value);};}
if(!callback){callback=function(){};}
return this.screen.readEditor({value:this.value},function(err,value){if(err){if(err.message==='Unsuccessful.'){self.screen.render();return self.readInput(callback);}
self.screen.render();self.readInput(callback);return callback(err);}
self.setValue(value);self.screen.render();return self.readInput(callback);});};module.exports=Chat;};BundleModuleCode['term/widgets/text']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Element=Require('term/widgets/element');function Text(options){if(!instanceOf(this,Node)){return new Text(options);}
options=options||{};options.shrink=true;Element.call(this,options);}
inheritPrototype(Text,Element);Text.prototype.type='text';module.exports=Text;};BundleModuleCode['term/widgets/line']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Line(options){if(!instanceOf(this,Node)){return new Line(options);}
options=options||{};var orientation=options.orientation||'vertical';delete options.orientation;if(orientation==='vertical'){options.width=1;}else{options.height=1;}
Box.call(this,options);this.ch=!options.type||options.type==='line'?orientation==='horizontal'?'─':'│':options.ch||' ';this.border={type:'bg',__proto__:this};this.style.border=this.style;}
inheritPrototype(Line,Box);Line.prototype.type='line';module.exports=Line;};BundleModuleCode['term/widgets/bigtext']=function(module,exports){var Comp=Require('com/compat');var fs=require('fs');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function BigText(options){if(!instanceOf(this instanceof Node)){return new BigText(options);}
options=options||{};options.font=options.font||__dirname+'/../../usr/fonts/ter-u14n.json';options.fontBold=options.font||__dirname+'/../../usr/fonts/ter-u14b.json';this.fch=options.fch;this.ratio={};this.font=this.loadFont(options.font);this.fontBold=this.loadFont(options.font);Box.call(this,options);if(this.style.bold){this.font=this.fontBold;}}
inheritPrototype(BigText,Box);BigText.prototype.type='bigtext';BigText.prototype.loadFont=function(filename){var self=this,data,font;data=JSON.parse(fs.readFileSync(filename,'utf8'));this.ratio.width=data.width;this.ratio.height=data.height;function convertLetter(ch,lines){var line,i;while(lines.length>self.ratio.height){lines.shift();lines.pop();}
lines=lines.map(function(line){var chs=line.split('');chs=chs.map(function(ch){return ch===' '?0:1;});while(chs.length<self.ratio.width){chs.push(0);}
return chs;});while(lines.length<self.ratio.height){line=[];for(i=0;i<self.ratio.width;i++){line.push(0);}
lines.push(line);}
return lines;}
font=Object.keys(data.glyphs).reduce(function(out,ch){var lines=data.glyphs[ch].map;out[ch]=convertLetter(ch,lines);return out;},{});delete font[' '];return font;};BigText.prototype.setContent=function(content){this.content='';this.text=content||'';};BigText.prototype.render=function(){if(this.position.width==null||this._shrinkWidth){this.position.width=this.ratio.width*this.text.length+1;this._shrinkWidth=true;}
if(this.position.height==null||this._shrinkHeight){this.position.height=this.ratio.height+0;this._shrinkHeight=true;}
var coords=this._render();if(!coords)return;var lines=this.screen.lines,left=coords.xi+this.ileft,top=coords.yi+this.itop,right=coords.xl-this.iright,bottom=coords.yl-this.ibottom;var dattr=this.sattr(this.style),bg=dattr&0x1ff,fg=(dattr>>9)&0x1ff,flags=(dattr>>18)&0x1ff,attr=(flags<<18)|(bg<<9)|fg;for(var x=left,i=0;x<right;x+=this.ratio.width,i++){var ch=this.text[i];if(!ch)break;var map=this.font[ch];if(!map)continue;for(var y=top;y<Math.min(bottom,top+this.ratio.height);y++){if(!lines[y])continue;var mline=map[y-top];if(!mline)continue;for(var mx=0;mx<this.ratio.width;mx++){var mcell=mline[mx];if(mcell==null)break;if(this.fch&&this.fch!==' '){lines[y][x+mx][0]=dattr;lines[y][x+mx][1]=mcell===1?this.fch:this.ch;}else{lines[y][x+mx][0]=mcell===1?attr:dattr;lines[y][x+mx][1]=mcell===1?' ':this.ch;}}
lines[y].dirty=true;}}
return coords;};module.exports=BigText;};BundleModuleCode['term/widgets/list']=function(module,exports){var Comp=Require('com/compat');var Io=Require('com/io');var helpers=Require('term/helpers');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Button=Require('term/widgets/button');var Arrows=Require('term/widgets/arrows');function List(options){var self=this;if(!instanceOf(this,Node)){return new List(options);}
options=options||{};options.ignoreKeys=true;options.scrollable=true;Box.call(this,options);this.value='';this.items=[];this.ritems=[];this.selected=0;this._isList=true;if(!this.style.selected){this.style.selected={};this.style.selected.bg=options.selectedBg;this.style.selected.fg=options.selectedFg;this.style.selected.bold=options.selectedBold;this.style.selected.underline=options.selectedUnderline;this.style.selected.blink=options.selectedBlink;this.style.selected.inverse=options.selectedInverse;this.style.selected.invisible=options.selectedInvisible;}
if(!this.style.item){this.style.item={};this.style.item.bg=options.itemBg;this.style.item.fg=options.itemFg;this.style.item.bold=options.itemBold;this.style.item.underline=options.itemUnderline;this.style.item.blink=options.itemBlink;this.style.item.inverse=options.itemInverse;this.style.item.invisible=options.itemInvisible;}
['bg','fg','bold','underline','blink','inverse','invisible'].forEach(function(name){if(self.style[name]!=null&&self.style.item[name]==null){self.style.item[name]=self.style[name];}});if(this.options.itemHoverBg){this.options.itemHoverEffects={bg:this.options.itemHoverBg};}
if(this.options.itemHoverEffects){this.style.item.hover=this.options.itemHoverEffects;}
if(this.options.itemFocusEffects){this.style.item.focus=this.options.itemFocusEffects;}
this.interactive=options.interactive!==false;this.mouse=options.mouse||false;if(options.items){this.ritems=options.items;options.items.forEach(this.add.bind(this));}
this.select(0);if(options.mouse){this.screen._listenMouse(this);this.on('element wheeldown',function(){self.select(self.selected+2);self.screen.render();});this.on('element wheelup',function(){self.select(self.selected-2);self.screen.render();});}
if(options.keys){this.on('keypress',function(ch,key){if(key.name==='up'||(options.vi&&key.name==='k')){self.up();self.screen.render();self.emit('selected',self.items[self.selected]);return;}
if(key.name==='down'||(options.vi&&key.name==='j')){self.down();self.screen.render();self.emit('selected',self.items[self.selected]);return;}
if(key.name==='enter'||(options.vi&&key.name==='l'&&!key.shift)){self.enterSelected();return;}
if(key.name==='escape'||(options.vi&&key.name==='q')){self.cancelSelected();return;}
if(options.vi&&key.name==='u'&&key.ctrl){self.move(-((self.height-self.iheight)/2)|0);self.screen.render();return;}
if(options.vi&&key.name==='d'&&key.ctrl){self.move((self.height-self.iheight)/2|0);self.screen.render();return;}
if(options.vi&&key.name==='b'&&key.ctrl){self.move(-(self.height-self.iheight));self.screen.render();return;}
if(options.vi&&key.name==='f'&&key.ctrl){self.move(self.height-self.iheight);self.screen.render();return;}
if(options.vi&&key.name==='h'&&key.shift){self.move(self.childBase-self.selected);self.screen.render();return;}
if(options.vi&&key.name==='m'&&key.shift){var visible=Math.min(self.height-self.iheight,self.items.length)/2|0;self.move(self.childBase+visible-self.selected);self.screen.render();return;}
if(options.vi&&key.name==='l'&&key.shift){self.down(self.childBase
+Math.min(self.height-self.iheight,self.items.length)
-self.selected);self.screen.render();return;}
if(options.vi&&key.name==='g'&&!key.shift){self.select(0);self.screen.render();return;}
if(options.vi&&key.name==='g'&&key.shift){self.select(self.items.length-1);self.screen.render();return;}
if(options.vi&&(key.ch==='/'||key.ch==='?')){if(typeof self.options.search!=='function'){return;}
return self.options.search(function(err,value){if(typeof err==='string'||typeof err==='function'||typeof err==='number'||(err&&err.test)){value=err;err=null;}
if(err||!value)return self.screen.render();self.select(self.fuzzyFind(value,key.ch==='?'));self.screen.render();});}});}
this.on('resize',function(){var visible=self.height-self.iheight;if(visible>=self.selected+1){self.childBase=0;self.childOffset=self.selected;}else{self.childBase=self.selected-visible+1;self.childOffset=visible-1;}});this.on('adopt',function(el){if(!~self.items.indexOf(el)){el.fixed=true;}});this.on('remove',function(el){self.removeItem(el);});if(options.arrows)
Arrows(self,options,function(){self.select(self.selected-2);self.screen.render()},function(){self.select(self.selected+2);self.screen.render()});}
inheritPrototype(List,Box);List.prototype.type='list';List.prototype.createItem=function(content){var self=this;var options={screen:this.screen,content:content,align:this.align||'left',top:0,left:0,right:(this.scrollbar?1:0),tags:this.parseTags,height:1,hoverEffects:this.mouse?this.style.item.hover:null,focusEffects:this.mouse?this.style.item.focus:null,autoFocus:false};if(!this.screen.autoPadding){options.top=1;options.left=this.ileft;options.right=this.iright+(this.scrollbar?1:0);}
if(this.shrink&&this.options.normalShrink){delete options.right;options.width='shrink';}
['bg','fg','bold','underline','blink','inverse','invisible'].forEach(function(name){options[name]=function(){var attr=self.items[self.selected]===item&&self.interactive?self.style.selected[name]:self.style.item[name];if(typeof attr==='function')attr=attr(item);return attr;};});if(this.style.transparent){options.transparent=true;}
var item=new Box(options);if(this.mouse){item.on('click',function(){self.focus();if(self.items[self.selected]===item){self.emit('action',item,self.selected);self.emit('select',item,self.selected);return;}
self.select(item);self.emit('selected',self.items[self.selected]);self.screen.render();});}
this.emit('create item');return item;};List.prototype.add=List.prototype.addItem=List.prototype.appendItem=function(content){content=typeof content==='string'?content:content.getContent();var item=this.createItem(content);item.position.top=this.items.length;if(!this.screen.autoPadding){item.position.top=this.itop+this.items.length;}
this.ritems.push(content);this.items.push(item);this.append(item);if(this.items.length===1){this.select(0);}
this.emit('add item');return item;};List.prototype.removeItem=function(child){var i=this.getItemIndex(child);if(~i&&this.items[i]){child=this.items.splice(i,1)[0];this.ritems.splice(i,1);this.remove(child);for(var j=i;j<this.items.length;j++){this.items[j].position.top--;}
if(i===this.selected){this.select(i-1);}}
this.emit('remove item');return child;};List.prototype.insertItem=function(child,content){content=typeof content==='string'?content:content.getContent();var i=this.getItemIndex(child);if(!~i)return;if(i>=this.items.length)return this.appendItem(content);var item=this.createItem(content);for(var j=i;j<this.items.length;j++){this.items[j].position.top++;}
item.position.top=i+(!this.screen.autoPadding?1:0);this.ritems.splice(i,0,content);this.items.splice(i,0,item);this.append(item);if(i===this.selected){this.select(i+1);}
this.emit('insert item');};List.prototype.getItem=function(child){return this.items[this.getItemIndex(child)];};List.prototype.setItem=function(child,content){content=typeof content==='string'?content:content.getContent();var i=this.getItemIndex(child);if(!~i)return;this.items[i].setContent(content);this.ritems[i]=content;};List.prototype.clearItems=function(){return this.setItems([]);};List.prototype.setItems=function(items){var original=this.items.slice(),selected=this.selected,sel=this.ritems[this.selected],i=0;items=items.slice();this.select(0);for(;i<items.length;i++){if(this.items[i]){this.items[i].setContent(items[i]);}else{this.add(items[i]);}}
for(;i<original.length;i++){this.remove(original[i]);}
this.ritems=items;sel=items.indexOf(sel);if(this.options.selectlast)this.select(selected);if(items.length===original.length){this.select(selected);}else{this.select(Math.min(selected,items.length-1));}
this.emit('set items');};List.prototype.pushItem=function(content){this.appendItem(content);return this.items.length;};List.prototype.popItem=function(){return this.removeItem(this.items.length-1);};List.prototype.unshiftItem=function(content){this.insertItem(0,content);return this.items.length;};List.prototype.shiftItem=function(){return this.removeItem(0);};List.prototype.spliceItem=function(child,n){var self=this;var i=this.getItemIndex(child);if(!~i)return;var items=Array.prototype.slice.call(arguments,2);var removed=[];while(n--){removed.push(this.removeItem(i));}
items.forEach(function(item){self.insertItem(i++,item);});return removed;};List.prototype.find=List.prototype.fuzzyFind=function(search,back){var start=this.selected+(back?-1:1),i;if(typeof search==='number')search+='';if(search&&search[0]==='/'&&search[search.length-1]==='/'){try{search=new RegExp(search.slice(1,-1));}catch(e){;}}
var test=typeof search==='string'?function(item){return!!~item.indexOf(search);}:(search.test?search.test.bind(search):search);if(typeof test!=='function'){if(this.screen.options.debug){throw new Error('fuzzyFind(): `test` is not a function.');}
return this.selected;}
if(!back){for(i=start;i<this.ritems.length;i++){if(test(helpers.cleanTags(this.ritems[i])))return i;}
for(i=0;i<start;i++){if(test(helpers.cleanTags(this.ritems[i])))return i;}}else{for(i=start;i>=0;i--){if(test(helpers.cleanTags(this.ritems[i])))return i;}
for(i=this.ritems.length-1;i>start;i--){if(test(helpers.cleanTags(this.ritems[i])))return i;}}
return this.selected;};List.prototype.getItemIndex=function(child){if(typeof child==='number'){return child;}else if(typeof child==='string'){var i=this.ritems.indexOf(child);if(~i)return i;for(i=0;i<this.ritems.length;i++){if(helpers.cleanTags(this.ritems[i])===child){return i;}}
return-1;}else{return this.items.indexOf(child);}};List.prototype.getSelected=function(){return this.items[this.selected];}
List.prototype.select=function(index){var lastindex=this.selected;if(!this.interactive){return;}
if(!this.items.length){this.selected=0;this.value='';this.scrollTo(0);return;}
if(typeof index==='object'){index=this.items.indexOf(index);}
if(index<0){index=0;}else if(index>=this.items.length){index=this.items.length-1;}
if(this.selected===index&&this._listInitialized)return;this._listInitialized=true;this.selected=index;this.value=helpers.cleanTags(this.ritems[this.selected]);if(!this.parent)return;if(index>=lastindex)
this.scrollTo(this.selected+(this.options.selectoffset||0));else
this.scrollTo(this.selected);this.emit('select item',this.items[this.selected],this.selected);};List.prototype.move=function(offset){this.select(this.selected+offset);};List.prototype.up=function(offset){this.move(-(offset||1));};List.prototype.down=function(offset){this.move(offset||1);};List.prototype.pick=function(label,callback){if(!callback){callback=label;label=null;}
if(!this.interactive){return callback();}
var self=this;var focused=this.screen.focused;if(focused&&focused._done)focused._done('stop');this.screen.saveFocus();this.focus();this.show();this.select(0);if(label)this.setLabel(label);this.screen.render();this.once('action',function(el,selected){if(label)self.removeLabel();self.screen.restoreFocus();self.hide();self.screen.render();if(!el)return callback();return callback(null,helpers.cleanTags(self.ritems[selected]));});};List.prototype.enterSelected=function(i){if(i!=null)this.select(i);this.emit('action',this.items[this.selected],this.selected);this.emit('select',this.items[this.selected],this.selected);};List.prototype.cancelSelected=function(i){if(i!=null)this.select(i);this.emit('action');this.emit('cancel');};module.exports=List;};BundleModuleCode['term/widgets/form']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Form(options){var self=this;if(!instanceOf(this,Node)){return new Form(options);}
options=options||{};options.ignoreKeys=true;Box.call(this,options);if(options.keys){this.screen._listenKeys(this);this.on('element keypress',function(el,ch,key){if((key.name==='tab'&&!key.shift)||(el.type==='textbox'&&options.autoNext&&key.name==='enter')||key.name==='down'||(options.vi&&key.name==='j')){if(el.type==='textbox'||el.type==='textarea'){if(key.name==='j')return;if(key.name==='tab'){el.emit('keypress',null,{name:'backspace'});}
el.emit('keypress','\x1b',{name:'escape'});}
self.focusNext();return;}
if((key.name==='tab'&&key.shift)||key.name==='up'||(options.vi&&key.name==='k')){if(el.type==='textbox'||el.type==='textarea'){if(key.name==='k')return;el.emit('keypress','\x1b',{name:'escape'});}
self.focusPrevious();return;}
if(key.name==='escape'){self.focus();return;}});}}
inheritPrototype(Form,Box),Form.prototype.type='form';Form.prototype._refresh=function(){if(!this._children){var out=[];this.children.forEach(function fn(el){if(el.keyable)out.push(el);el.children.forEach(fn);});this._children=out;}};Form.prototype._visible=function(){return!!this._children.filter(function(el){return el.visible;}).length;};Form.prototype.next=function(){this._refresh();if(!this._visible())return;if(!this._selected){this._selected=this._children[0];if(!this._selected.visible)return this.next();if(this.screen.focused!==this._selected)return this._selected;}
var i=this._children.indexOf(this._selected);if(!~i||!this._children[i+1]){this._selected=this._children[0];if(!this._selected.visible)return this.next();return this._selected;}
this._selected=this._children[i+1];if(!this._selected.visible)return this.next();return this._selected;};Form.prototype.previous=function(){this._refresh();if(!this._visible())return;if(!this._selected){this._selected=this._children[this._children.length-1];if(!this._selected.visible)return this.previous();if(this.screen.focused!==this._selected)return this._selected;}
var i=this._children.indexOf(this._selected);if(!~i||!this._children[i-1]){this._selected=this._children[this._children.length-1];if(!this._selected.visible)return this.previous();return this._selected;}
this._selected=this._children[i-1];if(!this._selected.visible)return this.previous();return this._selected;};Form.prototype.focusNext=function(){var next=this.next();if(next)next.focus();};Form.prototype.focusPrevious=function(){var previous=this.previous();if(previous)previous.focus();};Form.prototype.resetSelected=function(){this._selected=null;};Form.prototype.focusFirst=function(){this.resetSelected();this.focusNext();};Form.prototype.focusLast=function(){this.resetSelected();this.focusPrevious();};Form.prototype.submit=function(){var out={};this.children.forEach(function fn(el){if(el.value!=null){var name=el.name||el.type;if(Array.isArray(out[name])){out[name].push(el.value);}else if(out[name]){out[name]=[out[name],el.value];}else{out[name]=el.value;}}
el.children.forEach(fn);});this.emit('submit',out);return this.submission=out;};Form.prototype.cancel=function(){this.emit('cancel');};Form.prototype.reset=function(){this.children.forEach(function fn(el){switch(el.type){case'screen':break;case'box':break;case'text':break;case'line':break;case'scrollable-box':break;case'list':el.select(0);return;case'form':break;case'input':break;case'textbox':el.clearInput();return;case'textarea':el.clearInput();return;case'button':delete el.value;break;case'progress-bar':el.setProgress(0);break;case'file-manager':el.refresh(el.options.cwd);return;case'checkbox':el.uncheck();return;case'radio-set':break;case'radio-button':el.uncheck();return;case'prompt':break;case'question':break;case'message':break;case'info':break;case'loading':break;case'list-bar':break;case'dir-manager':el.refresh(el.options.cwd);return;case'terminal':el.write('');return;case'image':return;}
el.children.forEach(fn);});this.emit('reset');};module.exports=Form;};BundleModuleCode['term/widgets/textarea']=function(module,exports){var Comp=Require('com/compat');var unicode=Require('term/unicode');var nextTick=global.setImmediate||process.nextTick.bind(process);var Node=Require('term/widgets/node');var Input=Require('term/widgets/input');function Textarea(options){var self=this;if(!instanceOf(this,Node)){return new Textarea(options);}
options=options||{};options.scrollable=options.scrollable!==false;Input.call(this,options);this.screen._listenKeys(this);this.value=options.value||'';this.cpos={x:-1,y:-1};this.cursorControl=true;this.multiline=options.multiline;this.__updateCursor=this._updateCursor.bind(this);this.on('resize',this.__updateCursor);this.on('move',this.__updateCursor);if(options.inputOnFocus){this.on('focus',this.readInput.bind(this,null));}
if(!options.inputOnFocus&&options.keys){this.on('keypress',function(ch,key){if(self._reading)return;if(key.name==='enter'||(options.vi&&key.name==='i')){return self.readInput();}
if(key.name==='e'){return self.readEditor();}});}
if(options.mouse){this.on('click',function(data){if(self._reading)return;if(data.button!=='right')return;self.readEditor();});}}
inheritPrototype(Textarea,Input);Textarea.prototype.type='textarea';Textarea.prototype._updateCursor=function(get){if(this.screen.focused!==this){return;}
var lpos=get?this.lpos:this._getCoords();if(!lpos)return;var last=this._clines[this._clines.length-1],program=this.screen.program,line,offsetY=this.childBase||0,cx,cy;if(last===''&&this.value[this.value.length-1]!=='\n'){last=this._clines[this._clines.length-2]||'';}
line=Math.min(this._clines.length-1-(this.childBase||0),(lpos.yl-lpos.yi)-this.iheight-1);line=Math.max(0,line);if(this.cpos.x==-1||!this.cursorControl)this.cpos.x=this.strWidth(last);if(this.cpos.y==-1||!this.cursorControl)this.cpos.y=line;this.cpos.y=Math.min(this.cpos.y,line);this.cpos.x=Math.min(this.cpos.x,this.strWidth(this._clines[offsetY+this.cpos.y]));cx=lpos.xi+this.ileft+this.cpos.x;cy=lpos.yi+this.itop+this.cpos.y;if(cy===program.y&&cx===program.x){return;}
if(cy===program.y){if(cx>program.x){program.cuf(cx-program.x);}else if(cx<program.x){program.cub(program.x-cx);}}else if(cx===program.x){if(cy>program.y){program.cud(cy-program.y);}else if(cy<program.y){program.cuu(program.y-cy);}}else{program.cup(cy,cx);}};Textarea.prototype.input=Textarea.prototype.setInput=Textarea.prototype.readInput=function(callback){var self=this,focused=this.screen.focused===this;if(this._reading)return;this._reading=true;this._callback=callback;if(!focused){this.screen.saveFocus();this.focus();}
this.screen.grabKeys=true;this._updateCursor();this.screen.program.showCursor();this._done=function fn(err,value){if(!self._reading)return;if(fn.done)return;fn.done=true;delete self._callback;delete self._done;self.removeListener('keypress',self.__listener);delete self.__listener;self.removeListener('blur',self.__done);delete self.__done;self.screen.program.hideCursor();self.screen.grabKeys=false;if(!focused){self.screen.restoreFocus();}
if(self.options.inputOnFocus){self.screen.rewindFocus();}
self._reading=false;if(err==='stop')return;if(err){self.emit('error',err);}else if(value!=null){self.emit('submit',value);}else{self.emit('cancel',value);}
self.emit('action',value);if(!callback)return;return err?callback(err):callback(null,value);};nextTick(function(){if(self.__listener){return;}
self.__listener=self._listener.bind(self);self.on('keypress',self.__listener);});this.__done=this._done.bind(this,null,null);this.on('blur',this.__done);};Textarea.prototype._listener=function(ch,key){var done=this._done,self=this,value=this.value,clinesLength=this._clines.length,offsetY=this.childBase||0,newline=false,backspace=false,lastline=(this.cpos.y+offsetY+1)==clinesLength;if(key.name=='linefeed'||(!this.multiline&&key.name=='enter'))return this.emit('enter',this.value);if(key.name==='return')return;if(key.name==='enter'){ch='\n';newline=true;}
if(this.cursorControl)switch(key.name){case'left':if(this.cpos.x>0)this.cpos.x--;else{if(this.cpos.y>0){this.cpos.y--;this.cpos.x=this._clines[offsetY+this.cpos.y].length;}else if(offsetY>0){if(this.scrollable)this.scroll(-1);self.screen.render();this.cpos.x=this._clines[offsetY+this.cpos.y-1].length;}}
this._updateCursor(true);break;case'right':var next=++this.cpos.x;this._updateCursor(true);if(this.cpos.x!=next&&(offsetY+this.cpos.y+1)<this._clines.length){next=++this.cpos.y;this.cpos.x=0;this._updateCursor(true);if(this.scrollable&&this.cpos.y!=next)this.scroll(1);}
break;case'up':if(this.cpos.y>0){this.cpos.y--;}
this._updateCursor(true);break;case'down':this.cpos.y++;this._updateCursor(true);break;}
if(this.options.keys&&key.ctrl&&key.name==='e'){return this.readEditor();}
if(key.name==='escape'){done(null,null);}else if(key.name==='backspace'){backspace=true;if(this.value.length){if(this.screen.fullUnicode){if(unicode.isSurrogate(this.value,this.value.length-2)){this.value=this.value.slice(0,-2);}else{this.value=this.value.slice(0,-1);}}else{if(!this.cursorControl||this.cpos.x==-1||(this.cpos.x==this._clines[offsetY+this.cpos.y].length&&this.cpos.y==this._clines.length-1-offsetY)){this.value=this.value.slice(0,-1);}else{vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);this.value=this.value.substr(0,vpos-1)+
this.value.substr(vpos,1000000);}}
if(this.cpos.x>0)this.cpos.x--;else{this.cpos.x=-1;if(offsetY==0&&this.cpos.y>0&&lastline)this.cpos.y--;};}}else if(ch){if(!/^[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]$/.test(ch)){if(!this.cursorControl||this.cpos.x==-1||(this.cpos.x==this._clines[offsetY+this.cpos.y].length&&this.cpos.y==this._clines.length-1-offsetY))
this.value+=ch;else{vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);this.value=this.value.substr(0,vpos)+ch+
this.value.substr(vpos,1000000);}
if(newline){this.cpos.x=0;this.cpos.y++;}else
this.cpos.x++;}}
var rmline=this.cpos.x==-1;if(this.value!==value){var cn0=clinesLength,cn1=this._clines.length,y0=this.cpos.y,linelength=this._clines[offsetY+this.cpos.y]&&this._clines[offsetY+this.cpos.y].length,endofline=this.cpos.x==linelength+1;this.screen.render();var cn2=this._clines.length;if(!newline&&endofline&&cn2>cn0){if(this.scrollable&&lastline)this.scrollBottom();this.cpos.y++;this._updateCursor(true);if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);}else if(cn2<cn0&&!rmline){if(this.cpos.y>0&&!lastline&&endofline)this.cpos.y--;this._updateCursor(true);offsetY=this.childBase||0;if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);}else if(cn2<cn0&&!rmline&&this.cpos.x==0){if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);};if(offsetY>0&&backspace){if(this.scrollable)this.scroll(0);this.screen.render();if(rmline&&cn0!=cn2){if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;else if(this._clines[offsetY+this.cpos.y-1])this.cpos.x=this._clines[offsetY+this.cpos.y-1].length;this._updateCursor(true);}}}};Textarea.prototype.getLinearPos=function(v,clineIndex,cposx){var vpos=0,len=v.length,cline,clinePos=0,clineNum=0;cline=this._clines[clineNum];while(vpos<len&&clineIndex){if(v.charAt(vpos)=='\n'){clinePos=-1;clineIndex--;clineNum++;cline=this._clines[clineNum];}else{if(v.charAt(vpos)!=cline.charAt(clinePos)){clinePos=0;clineIndex--;clineNum++;cline=this._clines[clineNum];continue;}}
vpos++;clinePos++;}
if(clineIndex==0)return vpos+cposx;else 0}
Textarea.prototype._typeScroll=function(){var height=this.height-this.iheight;if(this.cpos.y==height){if(this.scrollable)this.scroll(this._clines.length);}};Textarea.prototype.getValue=function(){return this.value;};Textarea.prototype.setValue=function(value){if(value==null){value=this.value;}
if(this._value!==value){this.value=value;this._value=value;this.setContent(this.value);this._typeScroll();this._updateCursor();}};Textarea.prototype.clearInput=Textarea.prototype.clearValue=function(){return this.setValue('');};Textarea.prototype.submit=function(){if(!this.__listener)return;return this.__listener('\x1b',{name:'escape'});};Textarea.prototype.cancel=function(){if(!this.__listener)return;return this.__listener('\x1b',{name:'escape'});};Textarea.prototype.render=function(){this.setValue();return this._render();};Textarea.prototype.editor=Textarea.prototype.setEditor=Textarea.prototype.readEditor=function(callback){var self=this;if(this._reading){var _cb=this._callback,cb=callback;this._done('stop');callback=function(err,value){if(_cb)_cb(err,value);if(cb)cb(err,value);};}
if(!callback){callback=function(){};}
return this.screen.readEditor({value:this.value},function(err,value){if(err){if(err.message==='Unsuccessful.'){self.screen.render();return self.readInput(callback);}
self.screen.render();self.readInput(callback);return callback(err);}
self.setValue(value);self.screen.render();return self.readInput(callback);});};module.exports=Textarea;};BundleModuleCode['term/widgets/textbox']=function(module,exports){var options={version:'1.5.2'}
var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Textarea=Require('term/widgets/textarea');function Textbox(options){if(!instanceOf(this,Node)){return new Textbox(options);}
options=options||{};options.scrollable=options.scrollable||false;Textarea.call(this,options);this.secret=options.secret;this.censor=options.censor;this.wrap=options.wrap;this.multiline=options.multiline;}
inheritPrototype(Textbox,Textarea);Textbox.prototype.type='textbox';Textbox.prototype.__olistener=Textbox.prototype._listener;Textbox.prototype._listener=function(ch,key){if(!this.multiline&&key.name==='enter'){this.emit('enter',this.value);this._done(null,this.value);return;}
return this.__olistener(ch,key);};Textbox.prototype.setValue=function(value){var visible,val,i,line,sep;if(value==null){value=this.value;}
if(this._value!==value){if(!this.multiline){value=value.replace(/\n/g,'');}
this.value=value;this._value=value;if(this.secret){this.setContent('');}else if(this.censor){this.setContent(Array(this.value.length+1).join('*'));}else if(this.wrap&&this.value.length>(this.width-this.iwidth-1)){line='';i=0,sep='';visible=this.width-this.iwidth-1;val=this.value;while(val.length>0){line=line+val.substr(0,visible);val=val.substr(visible,val.length-visible);sep='\n';}
this.setContent(line);}else if(this.multiline){val=this.value.replace(/\t/g,this.screen.tabc);this.setContent(val);}else{visible=-(this.width-this.iwidth-1);val=this.value.replace(/\t/g,this.screen.tabc);this.setContent(val.slice(visible));}
this._updateCursor();}};Textbox.prototype.update=function(value){this.setValue(value);this.screen.render();}
Textbox.prototype.submit=function(){if(!this.__listener)return;return this.__listener('\r',{name:'enter'});};module.exports=Textbox;};BundleModuleCode['term/widgets/progressbar']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Input=Require('term/widgets/input');function ProgressBar(options){var self=this;if(!instanceOf(this,Node)){return new ProgressBar(options);}
options=options||{};Input.call(this,options);this.filled=options.filled||0;if(typeof this.filled==='string'){this.filled=+this.filled.slice(0,-1);}
this.value=this.filled;this.pch=options.pch||' ';if(options.ch){this.pch=options.ch;this.ch=' ';}
if(options.bch){this.ch=options.bch;}
if(!this.style.bar){this.style.bar={};this.style.bar.fg=options.barFg;this.style.bar.bg=options.barBg;}
this.orientation=options.orientation||'horizontal';if(options.keys){this.on('keypress',function(ch,key){var back,forward;if(self.orientation==='horizontal'){back=['left','h'];forward=['right','l'];}else if(self.orientation==='vertical'){back=['down','j'];forward=['up','k'];}
if(key.name===back[0]||(options.vi&&key.name===back[1])){self.progress(-5);self.screen.render();return;}
if(key.name===forward[0]||(options.vi&&key.name===forward[1])){self.progress(5);self.screen.render();return;}});}
if(options.mouse){this.on('click',function(data){var x,y,m,p;if(!self.lpos)return;if(self.orientation==='horizontal'){x=data.x-self.lpos.xi;m=(self.lpos.xl-self.lpos.xi)-self.iwidth;p=x/m*100|0;}else if(self.orientation==='vertical'){y=data.y-self.lpos.yi;m=(self.lpos.yl-self.lpos.yi)-self.iheight;p=y/m*100|0;}
self.setProgress(p);});}}
inheritPrototype(ProgressBar,Input);ProgressBar.prototype.type='progress-bar';ProgressBar.prototype.render=function(){var ret=this._render();if(!ret)return;var xi=ret.xi,xl=ret.xl,yi=ret.yi,yl=ret.yl,dattr;if(this.border)xi++,yi++,xl--,yl--;if(this.orientation==='horizontal'){xl=xi+((xl-xi)*(this.filled/100))|0;}else if(this.orientation==='vertical'){yi=yi+((yl-yi)-(((yl-yi)*(this.filled/100))|0));}
dattr=this.sattr(this.style.bar);this.screen.fillRegion(dattr,this.pch,xi,xl,yi,yl);if(this.content){var line=this.screen.lines[yi];for(var i=0;i<this.content.length;i++){line[xi+i][1]=this.content[i];}
line.dirty=true;}
return ret;};ProgressBar.prototype.progress=function(filled){this.filled+=filled;if(this.filled<0)this.filled=0;else if(this.filled>100)this.filled=100;if(this.filled===100){this.emit('complete');}
this.value=this.filled;};ProgressBar.prototype.setProgress=function(filled){this.filled=0;this.progress(filled);};ProgressBar.prototype.reset=function(){this.emit('reset');this.filled=0;this.value=this.filled;};module.exports=ProgressBar;};BundleModuleCode['term/widgets/filemanager']=function(module,exports){var options={version:'1.4.2'}
var Comp=Require('com/compat');var path=Require('path'),fs=Require('fs');var Node=Require('term/widgets/node');var List=Require('term/widgets/list');var Button=Require('term/widgets/button');var Helpers=Require('term/helpers');var Box=Require('term/widgets/box');var TextBox=Require('term/widgets/textbox');var Arrows=Require('term/widgets/arrows');var Screen=Require('term/widgets/screen');function FileManager(options){var self=this,bbox,off1=0,off2=0,arrows=options.arrows;if(!instanceOf(this,Node)){return new FileManager(options);}
options=options||{};options.parseTags=true;options.mouse=true;options.arrows=_;if(options.parent==Screen.global){bbox=Helpers.bbox(Screen.global,options);if(options.box)bbox.top+=1,bbox.height-=2,bbox.width-=4,bbox.left+=2;if(options.input)bbox.height-=3;if(options.cancelButton||options.okayButton)bbox.height-=1;if(arrows)bbox.width-=4,bbox.left+=2;options.top=bbox.top;options.left=bbox.left;options.height=bbox.height;options.width=bbox.width;}
List.call(this,options);options.arrows=arrows;this.cwd=options.cwd||process.cwd();this.file=this.cwd;this.value=this.cwd;this.noshow=options.noshow;if(options.parent==this.screen){this._clickable=this.screen.clickable;this.screen.clickable=[];bbox=Helpers.bbox(this.screen,options);if(options.cancelButton||options.okayButton)off1=2;if(options.input)off2=3;if(options.box)
this._.box=new Box({top:bbox.top-2,width:bbox.width+8,left:bbox.left-4,height:bbox.height+3+off1+off2,hidden:options.hidden,border:options.box.border,style:{label:options.label,fg:options.box.fg,bg:options.box.bg||'white'}});if(this._.box)this.screen.append(this._.box);if(options.input){this._.input=new TextBox({screen:this.screen,top:bbox.top+bbox.height+(options.box?1:0)-1,height:options.input.border&&options.input.border.type=='line'?3:1,width:bbox.width,left:bbox.left,keys:options.input.mutable?true:undefined,vi:options.input.mutable?true:undefined,mouse:options.input.mutable?true:undefined,inputOnFocus:options.input.mutable?true:undefined,value:options.input.value||'<input>',hidden:options.hidden,border:options.input.border,style:{fg:options.input.fg||'black',bg:options.input.bg||'white',bold:true}});this.screen.append(this._.input);}
if(options.okayButton){this._.okay=new Button({screen:this.screen,top:bbox.top+bbox.height+(options.box?1:0)+off2,height:1,left:bbox.left+1,width:10,content:options.okayButton,align:'center',style:{fg:'white',bg:'blue',bold:true,},autoFocus:false,hidden:options.hidden,mouse:true});this._.okay.on('press',function(){var item=self.items[self.selected],value=self._.input?self._.input.getValue():item.content.replace(/\{[^{}]+\}/g,'').replace(/@$/,''),file=path.resolve(self.cwd,value);self.emit('file',file);self.hide();});this.screen.append(this._.okay);}
if(options.cancelButton){this._.cancel=new Button({screen:this.screen,top:bbox.top+bbox.height+(options.box?1:0)+off2,height:1,left:bbox.left+bbox.width-10-1,width:10,content:options.cancelButton,align:'center',style:{fg:'white',bg:'red',bold:true,},autoFocus:false,hidden:options.hidden,mouse:true});this._.cancel.on('press',function(){self.hide();});this.screen.append(this._.cancel);}
if(options.arrows)
Arrows(self,options,function(){self.emit('element wheelup')},function(){self.emit('element wheeldown')},true);this._hide=this.hide;this.hide=function(){self._hide();if(self._.box)self._.box.hide();if(self._.input)self._.input.hide();if(self._.okay)self._.okay.hide();if(self._.cancel)self._.cancel.hide();if(self._.up)self._.up.hide();if(self._.down)self._.down.hide();self.screen.render();self.screen.clickable=self._clickable;}
this._show=this.show;this.show=function(){self._clickable=self.screen.clickable;self.screen.clickable=self.clickable;self._show();if(self._.box)self._.box.show();if(self._.input)self._.input.show();if(self._.okay)self._.okay.show();if(self._.cancel)self._.cancel.show();if(self._.up)self._.up.show();if(self._.down)self._.down.show();self.screen.render();}
this.clickable=this.screen.clickable;this.screen.clickable=this._clickable;}
if(options.label&&~options.label.indexOf('%path')){this._label.setContent(options.label.replace('%path',this.cwd));}
if(this._.input)
this.on('selected',function(item){var value=item.content.replace(/\{[^{}]+\}/g,'').replace(/@$/,'');if(value.indexOf('/')!=-1)value='';self._.input.setValue(value);self._.input.update();});this.on('select',function(item){var value=item.content.replace(/\{[^{}]+\}/g,'').replace(/@$/,''),file=path.resolve(self.cwd,value);return fs.stat(file,function(err,stat){var _cwd=self.cwd;if(err){return self.emit('ioerror',err,file);}
self.file=file;self.value=file;if(stat.isDirectory()){self.cwd=file;self.refresh(undefined,function(err){if(err)self.cwd=_cwd;else if(options.label&&~options.label.indexOf('%path')){self._label.setContent(options.label.replace('%path',self.cwd));self.emit('cd',file,self.cwd);self.screen.render();}});}else{if(self.options.select)self.emit('file',file);if(self.options.select&&self.options.autohide)self.hide();}});});}
inheritPrototype(FileManager,List);FileManager.prototype.type='file-manager';FileManager.prototype.refresh=function(cwd,callback){var self=this;if(cwd)this.cwd=cwd;else cwd=this.cwd;return fs.readdir(cwd,function(err,list){if(err&&err.code==='ENOENT'){self.cwd=cwd!==process.env.HOME?process.env.HOME:'/';return self.refresh(undefined,callback);}
if(err){if(callback)return callback(err);return self.emit('ioerror',err,cwd);}
var dirs=[],files=[];list.unshift('..');list.forEach(function(name){var f=path.resolve(cwd,name),stat;try{stat=fs.lstatSync(f);}catch(e){;}
if((stat&&stat.isDirectory())||name==='..'){dirs.push({name:name,text:'{light-blue-fg}'+name+'{/light-blue-fg}/',dir:true});}else if(stat&&stat.isSymbolicLink()){files.push({name:name,text:'{light-cyan-fg}'+name+'{/light-cyan-fg}@',dir:false});}else{files.push({name:name,text:name,dir:false});}});dirs=Helpers.asort(dirs);files=Helpers.asort(files);list=dirs.concat(files).map(function(data){return data.text;});self.setItems(list);self.select(0);self.screen.render();self.emit('refresh');if(callback)callback();});};FileManager.prototype.pick=function(cwd,callback){if(!callback){callback=cwd;cwd=null;}
var self=this,focused=this.screen.focused===this,hidden=this.hidden,onfile,oncancel;function resume(){self.removeListener('file',onfile);self.removeListener('cancel',oncancel);if(hidden){self.hide();}
if(!focused){self.screen.restoreFocus();}
self.screen.render();}
this.on('file',onfile=function(file){resume();return callback(null,file);});this.on('cancel',oncancel=function(){resume();return callback();});this.refresh(cwd,function(err){if(err)return callback(err);if(hidden){self.show();}
if(!focused){self.screen.saveFocus();self.focus();}
self.screen.render();});};FileManager.prototype.reset=function(cwd,callback){if(!callback){callback=cwd;cwd=null;}
this.cwd=cwd||this.options.cwd;this.refresh(callback);};module.exports=FileManager;};BundleModuleCode['term/widgets/checkbox']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Input=Require('term/widgets/input');function Checkbox(options){var self=this;if(!instanceOf(this,Node)){return new Checkbox(options);}
options=options||{};Input.call(this,options);this.text=options.content||options.text||'';this.checked=this.value=options.checked||false;this.on('keypress',function(ch,key){if(key.name==='enter'||key.name==='space'){self.toggle();self.screen.render();}});if(options.mouse){this.on('click',function(){self.toggle();self.screen.render();});}
this.on('focus',function(){var lpos=self.lpos;if(!lpos)return;self.screen.program.lsaveCursor('checkbox');self.screen.program.cup(lpos.yi,lpos.xi+1);self.screen.program.showCursor();});this.on('blur',function(){self.screen.program.lrestoreCursor('checkbox',true);});}
inheritPrototype(Checkbox,Input);Checkbox.prototype.type='checkbox';Checkbox.prototype.render=function(){this.clearPos(true);this.setContent('['+(this.checked?'x':' ')+'] '+this.text,true);return this._render();};Checkbox.prototype.check=function(){if(this.checked)return;this.checked=this.value=true;this.emit('check',this);this.emit('select',true);};Checkbox.prototype.uncheck=function(){if(!this.checked)return;this.checked=this.value=false;this.emit('uncheck',this);this.emit('select',false);};Checkbox.prototype.toggle=function(){return this.checked?this.uncheck():this.check();};module.exports=Checkbox;};BundleModuleCode['term/widgets/radioset']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function RadioSet(options){if(!instanceOf(this,Node)){return new RadioSet(options);}
options=options||{};Box.call(this,options);}
inheritPrototype(RadioSet,Box);RadioSet.prototype.type='radio-set';module.exports=RadioSet;};BundleModuleCode['term/widgets/radiobutton']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Checkbox=Require('term/widgets/checkbox');function RadioButton(options){var self=this;if(!instanceOf(this,Node)){return new RadioButton(options);}
options=options||{};this.group=options.group;Checkbox.call(this,options);this.on('check',function(){var el=self,group=self.group;while(el=el.parent){if(el.type==='radio-set'||el.type==='form')break;}
el=el||self.parent;var index=0;el.forDescendants(function(el){if(el.type!=='radio-button'||el===self||el.group!=group){return;}
index++;el.uncheck();});});}
inheritPrototype(RadioButton,Checkbox);RadioButton.prototype.type='radio-button';RadioButton.prototype.render=function(){this.clearPos(true);this.setContent('('+(this.checked?'*':' ')+') '+this.text,true);return this._render();};RadioButton.prototype.toggle=RadioButton.prototype.check;module.exports=RadioButton;};BundleModuleCode['term/widgets/prompt']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Button=Require('term/widgets/button');var Textbox=Require('term/widgets/textbox');function Prompt(options){if(!instanceOf(this,Node)){return new Prompt(options);}
options=options||{};options.hidden=true;Box.call(this,options);this._.input=new Textbox({parent:this,top:3,height:1,left:2,right:2,bg:'black'});this._.okay=new Button({parent:this,top:5,height:1,left:2,width:6,content:'Okay',align:'center',bg:'black',hoverBg:'blue',autoFocus:false,mouse:true});this._.cancel=new Button({parent:this,top:5,height:1,shrink:true,left:10,width:8,content:'Cancel',align:'center',bg:'black',hoverBg:'blue',autoFocus:false,mouse:true});}
inheritPrototype(Prompt,Box);Prompt.prototype.type='prompt';Prompt.prototype.input=Prompt.prototype.setInput=Prompt.prototype.readInput=function(text,value,callback){var self=this;var okay,cancel;if(!callback){callback=value;value='';}
this.show();this.setContent(' '+text);this._.input.value=value;this.screen.saveFocus();this._.okay.on('press',okay=function(){self._.input.submit();});this._.cancel.on('press',cancel=function(){self._.input.cancel();});this._.input.readInput(function(err,data){self.hide();self.screen.restoreFocus();self._.okay.removeListener('press',okay);self._.cancel.removeListener('press',cancel);return callback(err,data);});this.screen.render();};module.exports=Prompt;};BundleModuleCode['term/widgets/question']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Button=Require('term/widgets/button');function Question(options){if(!instanceOf(this,Node)){return new Question(options);}
options=options||{};options.hidden=true;if(!options.height||options.height<5)options.height=5;Box.call(this,options);this._clickable=this.screen.clickable;this.screen.clickable=[];this._.okay=new Button({screen:this.screen,parent:this,top:options.height?(options.height-2):3,height:1,left:2,width:10,content:options.okButton||'Okay',align:'center',bg:'black',hoverBg:'blue',autoFocus:false,mouse:true});if(options.cancelButton)
this._.cancel=new Button({screen:this.screen,parent:this,top:options.height?(options.height-2):3,height:1,left:options.width?(options.width-12):10,width:10,content:options.cancelButton,align:'center',bg:'black',hoverBg:'blue',autoFocus:false,mouse:true});this.clickable=this.screen.clickable;this.screen.clickable=this._clickable;}
inheritPrototype(Question,Box);Question.prototype.type='question';Question.prototype.ask=function(text,callback){var self=this,press,okay,cancel,off,room;if(!callback)callback=function(){};this._clickable=this.screen.clickable;this.screen.clickable=this.clickable;this.show();if(text.length>this.options.width-4){var tokens=text.split(' '),curlen=0,temp='';for(var t in tokens){var token=tokens[t];if(curlen+token.length+1<this.options.width-4){temp=temp+token+' ';curlen=curlen+token.length+1;}else{if(token.length<this.options.width-4){temp=temp+'\n'+token+' ';curlen=token.length+1;}else{off=0,room=this.options.width-4-curlen;temp=temp+token.substr(0,room);off=room;room=this.options.width-4;while(off<token.length){frag=token.substr(off,room);temp=temp+'\n'+frag;off+=room;curlen=frag;}
temp=temp+' ';curlen++;}}}
text=temp;}
this.setContent('\n '+text.replace(/\n/g,'\n '));this.onScreenEvent('keypress',press=function(ch,key){if(key.name==='mouse')return;if(key.name!=='enter'&&key.name!=='escape'&&key.name!=='q'&&key.name!=='y'&&key.name!=='n'){return;}
done(null,key.name==='enter'||key.name==='y');});this._.okay.on('press',okay=function(){done(null,true);});if(this._.cancel)this._.cancel.on('press',cancel=function(){done(null,false);});this.screen.saveFocus();this.focus();function done(err,data){self.hide();self.screen.clickable=self._clickable;self.screen.restoreFocus();self.removeScreenEvent('keypress',press);self._.okay.removeListener('press',okay);if(self._.cancel)self._.cancel.removeListener('press',cancel);return callback(err,data);}
this.screen.render();};module.exports=Question;};BundleModuleCode['term/widgets/message']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Message(options){if(!instanceOf(this,Node)){return new Message(options);}
options=options||{};options.tags=true;Box.call(this,options);}
inheritPrototype(Message,Box);Message.prototype.type='message';Message.prototype.log=Message.prototype.display=function(text,time,callback){var self=this;if(typeof time==='function'){callback=time;time=null;}
if(time==null)time=3;if(this.scrollable){this.screen.saveFocus();this.focus();this.scrollTo(0);}
this.show();this.setContent(text);this.screen.render();if(time===Infinity||time===-1||time===0){var end=function(){if(end.done)return;end.done=true;if(self.scrollable){try{self.screen.restoreFocus();}catch(e){;}}
self.hide();self.screen.render();if(callback)callback();};setTimeout(function(){self.onScreenEvent('keypress',function fn(ch,key){if(key.name==='mouse')return;if(self.scrollable){if((key.name==='up'||(self.options.vi&&key.name==='k'))||(key.name==='down'||(self.options.vi&&key.name==='j'))||(self.options.vi&&key.name==='u'&&key.ctrl)||(self.options.vi&&key.name==='d'&&key.ctrl)||(self.options.vi&&key.name==='b'&&key.ctrl)||(self.options.vi&&key.name==='f'&&key.ctrl)||(self.options.vi&&key.name==='g'&&!key.shift)||(self.options.vi&&key.name==='g'&&key.shift)){return;}}
if(self.options.ignoreKeys&&~self.options.ignoreKeys.indexOf(key.name)){return;}
self.removeScreenEvent('keypress',fn);end();});if(!self.options.mouse)return;self.onScreenEvent('mouse',function fn(data){if(data.action==='mousemove')return;self.removeScreenEvent('mouse',fn);end();});},10);return;}
setTimeout(function(){self.hide();self.screen.render();if(callback)callback();},time*1000);};Message.prototype.error=function(text,time,callback){return this.display('{red-fg}Error: '+text+'{/red-fg}',time,callback);};module.exports=Message;};BundleModuleCode['term/widgets/keyboard']=function(module,exports){var options={version:'1.2.3'}
var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Button=Require('term/widgets/button');var TextBox=Require('term/widgets/textbox');var Helpers=Require('term/helpers');function Keyboard(options){var self=this,x,y,key,i=0,bbox;if(!instanceOf(this,Node)){return new Keyboard(options);}
options=options||{};options.hidden=true;if(!options.height||options.height<10)options.height=10;Box.call(this,options);this._clickable=this.screen.clickable;this.screen.clickable=[];if(!options.button)options.button={width:3,height:2};if(!options.margin)options.margin={x:2,y:1};this.shift=false;this.group=0;this._.buttons=[];var Keys=[['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],['0','1','2','3','4','5','6','7','8','9','.','+','-','*',':',';'],['"','!','=','_','<','>','(',')','{','}','[',']','?','#','~',' ']];var keys=Comp.array.flatten(Keys);var complen=Keys[0].length+Keys[1].length;bbox=Helpers.bbox(this.screen,options);if(options.okayButton){this._.okay=new Button({screen:this.screen,parent:this,top:bbox.height-3,height:1,left:1,width:Math.max(6,options.okayButton.length+2),content:options.okayButton,align:'center',autoFocus:false,mouse:true,style:{bold:true,bg:'green',fg:'white'}});this._.okay.on('press',function(){self.hide();if(self._.callback)self._.callback(self._.input.getValue())});}
if(options.cancelButton){this._.cancel=new Button({screen:this.screen,parent:this,top:bbox.height-3,height:1,right:1,width:options.cancelButton.length+2,content:options.cancelButton,align:'center',autoFocus:false,mouse:true,style:{bold:true,bg:'red',fg:'white'}});this._.cancel.on('press',function(){self.hide();});}
this._.shift=new Button({screen:this.screen,parent:this,top:bbox.height-3,height:1,right:int(bbox.width/2)+(options.compact?1:int(options.margin.x)),width:(options.shiftButton&&options.shiftButton.length+2)||6,content:options.shiftButton||'Shft',align:'center',autoFocus:false,mouse:true});this._.shift.on('press',function(){self.shift=~self.shift;for(var i=0;i<26;i++){self._.buttons[i].setContent(self.shift?Keys[0][i].toUpperCase():Keys[0][i]);}
if(options.compact&&self.shift)for(i in Keys[1])self._.buttons[26+Number(i)].setContent(Keys[2][i]);if(options.compact&&!self.shift)for(i in Keys[1])self._.buttons[26+Number(i)].setContent(Keys[1][i]);if(self.shift&&options.nlButton)self._.delete.setContent(options.nlButton);else if(!self.shift&&options.nlButton)self._.delete.setContent(options.delButton||'DEL');self.screen.render();});this._.delete=new Button({screen:this.screen,parent:this,top:bbox.height-3,height:1,left:int(bbox.width/2)+(options.compact?0:int(options.margin.x)),width:(options.delButton&&options.delButton.length+2)||6,content:options.delButton||'DEL',align:'center',autoFocus:false,mouse:true});this._.delete.on('press',function(){var line=self._.input.getValue();if(!self.shift||!options.nlButton){self._.input.setValue(line.substring(0,line.length-1));}else if(self.shift&&options.nlButton){self._.input.setValue(line+'\n');}
self._.input.update();});this._.input=new TextBox({parent:this,value:options.value||'content',width:bbox.width-4,height:1,left:1,top:0,style:{fg:(options.style.input&&options.style.input.fg)||'black',bg:(options.style.input&&options.style.input.bg)||'white',bold:true}});y=1+options.margin.y;i=0;while((options.compact?i<complen:true)&&keys[i]&&y<(bbox.height-options.button.height-options.margin.y)-1){x=options.margin.x;while((options.compact?i<complen:true)&&keys[i]&&x<(bbox.width-options.button.width-options.margin.x)){function make(i){key=new Button({screen:self.screen,parent:self,top:y,height:options.button.height,left:x,width:options.button.width,content:keys[i],align:'center',autoFocus:false,mouse:true});self._.buttons.push(key);key.on('press',function(){self.emit('key',i)});}
make(i);i++,x+=(options.button.width+options.margin.x);}
y+=(options.button.height+options.margin.y);}
this.clickable=this.screen.clickable;this.screen.clickable=this._clickable;this._hide=this.hide;this.hide=function(){self._hide();self.screen.render();self.screen.clickable=self._clickable;}
this._show=this.show;this.show=function(){self._clickable=self.screen.clickable;self.screen.clickable=self.clickable;self._show();self.screen.render();}
this.on('key',function(index){var line=self._.input.getValue(),ch;if(options.compact){if(index<26){ch=self.shift?Keys[0][index].toUpperCase():Keys[0][index];}else{ch=self.shift?Keys[2][index-26]:Keys[1][index-26];}}else{if(!self.shift||index>26)ch=keys[index];else ch=keys[index].toUpperCase();}
line+=ch;self._.input.setValue(line);self._.input.update();});}
inheritPrototype(Keyboard,Box);Keyboard.prototype.setCallback=function(cb){this._.callback=cb}
Keyboard.prototype.setValue=function(line){this._.input.setValue(line);this._.input.update();}
Keyboard.prototype.type='keyboard';module.exports=Keyboard;};BundleModuleCode['term/widgets/loading']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Text=Require('term/widgets/text');function Loading(options){if(!instanceOf(this,Node)){return new Loading(options);}
options=options||{};Box.call(this,options);this._.icon=new Text({parent:this,align:'center',top:2,left:1,right:1,height:1,content:'|'});}
inheritPrototype(Loading,Box);Loading.prototype.type='loading';Loading.prototype.load=function(text){var self=this;this.show();this.setContent(text);if(this._.timer){this.stop();}
this.screen.lockKeys=true;this._.timer=setInterval(function(){if(self._.icon.content==='|'){self._.icon.setContent('/');}else if(self._.icon.content==='/'){self._.icon.setContent('-');}else if(self._.icon.content==='-'){self._.icon.setContent('\\');}else if(self._.icon.content==='\\'){self._.icon.setContent('|');}
self.screen.render();},200);};Loading.prototype.stop=function(){this.screen.lockKeys=false;this.hide();if(this._.timer){clearInterval(this._.timer);delete this._.timer;}
this.screen.render();};module.exports=Loading;};BundleModuleCode['term/widgets/listbar']=function(module,exports){var Comp=Require('com/compat');var helpers=Require('term/helpers');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Listbar(options){var self=this;if(!instanceOf(this,Node)){return new Listbar(options);}
options=options||{};this.items=[];this.ritems=[];this.commands=[];this.leftBase=0;this.leftOffset=0;this.mouse=options.mouse||false;Box.call(this,options);if(!this.style.selected){this.style.selected={};}
if(!this.style.item){this.style.item={};}
if(options.commands||options.items){this.setItems(options.commands||options.items);}
if(options.keys){this.on('keypress',function(ch,key){if(key.name==='left'||(options.vi&&key.name==='h')||(key.shift&&key.name==='tab')){self.moveLeft();self.screen.render();if(key.name==='tab')return false;return;}
if(key.name==='right'||(options.vi&&key.name==='l')||key.name==='tab'){self.moveRight();self.screen.render();if(key.name==='tab')return false;return;}
if(key.name==='enter'||(options.vi&&key.name==='k'&&!key.shift)){self.emit('action',self.items[self.selected],self.selected);self.emit('select',self.items[self.selected],self.selected);var item=self.items[self.selected];if(item._.cmd.callback){item._.cmd.callback();}
self.screen.render();return;}
if(key.name==='escape'||(options.vi&&key.name==='q')){self.emit('action');self.emit('cancel');return;}});}
if(options.autoCommandKeys){this.onScreenEvent('keypress',function(ch){if(/^[0-9]$/.test(ch)){var i=+ch-1;if(!~i)i=9;return self.selectTab(i);}});}
this.on('focus',function(){self.select(self.selected);});}
inheritPrototype(Listbar,Box);Listbar.prototype.type='listbar';Object.defineProperty(Listbar.prototype,'selected',{get:function(){return this.leftBase+this.leftOffset;}});Listbar.prototype.setItems=function(commands){var self=this;if(!Array.isArray(commands)){commands=Object.keys(commands).reduce(function(obj,key,i){var cmd=commands[key],cb;if(typeof cmd==='function'){cb=cmd;cmd={callback:cb};}
if(cmd.text==null)cmd.text=key;if(cmd.prefix==null)cmd.prefix=++i+'';if(cmd.text==null&&cmd.callback){cmd.text=cmd.callback.name;}
obj.push(cmd);return obj;},[]);}
this.items.forEach(function(el){el.detach();});this.items=[];this.ritems=[];this.commands=[];commands.forEach(function(cmd){self.add(cmd);});this.emit('set items');};Listbar.prototype.add=Listbar.prototype.addItem=Listbar.prototype.appendItem=function(item,callback){var self=this,prev=this.items[this.items.length-1],drawn,cmd,title,len;if(!this.parent){drawn=0;}else{drawn=prev?prev.aleft+prev.width:0;if(!this.screen.autoPadding){drawn+=this.ileft;}}
if(typeof item==='object'){cmd=item;if(cmd.prefix==null)cmd.prefix=(this.items.length+1)+'';}
if(typeof item==='string'){cmd={prefix:(this.items.length+1)+'',text:item,callback:callback};}
if(typeof item==='function'){cmd={prefix:(this.items.length+1)+'',text:item.name,callback:item};}
if(cmd.keys&&cmd.keys[0]){cmd.prefix=cmd.keys[0];}
var t=helpers.generateTags(this.style.prefix||{fg:'lightblack'});title=(cmd.prefix!=null?t.open+cmd.prefix+t.close+':':'')+cmd.text;len=((cmd.prefix!=null?cmd.prefix+':':'')+cmd.text).length;var options={screen:this.screen,top:0,left:drawn+1,height:1,content:title,width:len+2,align:'center',autoFocus:false,tags:true,mouse:true,style:helpers.merge({},this.style.item),noOverflow:true};if(!this.screen.autoPadding){options.top+=this.itop;options.left+=this.ileft;}
['bg','fg','bold','underline','blink','inverse','invisible'].forEach(function(name){options.style[name]=function(){var attr=self.items[self.selected]===el?self.style.selected[name]:self.style.item[name];if(typeof attr==='function')attr=attr(el);return attr;};});var el=new Box(options);this._[cmd.text]=el;cmd.element=el;el._.cmd=cmd;this.ritems.push(cmd.text);this.items.push(el);this.commands.push(cmd);this.append(el);if(cmd.callback){if(cmd.keys){this.screen.key(cmd.keys,function(){self.emit('action',el,self.selected);self.emit('select',el,self.selected);if(el._.cmd.callback){el._.cmd.callback();}
self.select(el);self.screen.render();});}}
if(this.items.length===1){this.select(0);}
if(this.mouse){el.on('click',function(){self.emit('action',el,self.selected);self.emit('select',el,self.selected);if(el._.cmd.callback){el._.cmd.callback();}
self.select(el);self.screen.render();});}
this.emit('add item');};Listbar.prototype.render=function(){var self=this,drawn=0;if(!this.screen.autoPadding){drawn+=this.ileft;}
this.items.forEach(function(el,i){if(i<self.leftBase){el.hide();}else{el.rleft=drawn+1;drawn+=el.width+2;el.show();}});return this._render();};Listbar.prototype.select=function(offset){if(typeof offset!=='number'){offset=this.items.indexOf(offset);}
if(offset<0){offset=0;}else if(offset>=this.items.length){offset=this.items.length-1;}
if(!this.parent){this.emit('select item',this.items[offset],offset);return;}
var lpos=this._getCoords();if(!lpos)return;var self=this,width=(lpos.xl-lpos.xi)-this.iwidth,drawn=0,visible=0,el;el=this.items[offset];if(!el)return;this.items.forEach(function(el,i){if(i<self.leftBase)return;var lpos=el._getCoords();if(!lpos)return;if(lpos.xl-lpos.xi<=0)return;drawn+=(lpos.xl-lpos.xi)+2;if(drawn<=width)visible++;});var diff=offset-(this.leftBase+this.leftOffset);if(offset>this.leftBase+this.leftOffset){if(offset>this.leftBase+visible-1){this.leftOffset=0;this.leftBase=offset;}else{this.leftOffset+=diff;}}else if(offset<this.leftBase+this.leftOffset){diff=-diff;if(offset<this.leftBase){this.leftOffset=0;this.leftBase=offset;}else{this.leftOffset-=diff;}}
this.emit('select item',el,offset);};Listbar.prototype.removeItem=function(child){var i=typeof child!=='number'?this.items.indexOf(child):child;if(~i&&this.items[i]){child=this.items.splice(i,1)[0];this.ritems.splice(i,1);this.commands.splice(i,1);this.remove(child);if(i===this.selected){this.select(i-1);}}
this.emit('remove item');};Listbar.prototype.move=function(offset){this.select(this.selected+offset);};Listbar.prototype.moveLeft=function(offset){this.move(-(offset||1));};Listbar.prototype.moveRight=function(offset){this.move(offset||1);};Listbar.prototype.selectTab=function(index){var item=this.items[index];if(item){if(item._.cmd.callback){item._.cmd.callback();}
this.select(index);this.screen.render();}
this.emit('select tab',item,index);};module.exports=Listbar;};BundleModuleCode['term/widgets/table']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Table(options){var self=this;if(!instanceOf(this,Node)){return new Table(options);}
options=options||{};options.shrink=true;options.style=options.style||{};options.style.border=options.style.border||{};options.style.header=options.style.header||{};options.style.cell=options.style.cell||{};options.align=options.align||'center';delete options.height;Box.call(this,options);this.pad=options.pad!=null?options.pad:2;this.setData(options.rows||options.data);this.on('attach',function(){self.setContent('');self.setData(self.rows);});this.on('resize',function(){self.setContent('');self.setData(self.rows);self.screen.render();});}
inheritPrototype(Table,Box);Table.prototype.type='table';Table.prototype._calculateMaxes=function(){var self=this;var maxes=[];if(this.detached)return;this.rows=this.rows||[];this.rows.forEach(function(row){row.forEach(function(cell,i){var clen=self.strWidth(cell);if(!maxes[i]||maxes[i]<clen){maxes[i]=clen;}});});var total=maxes.reduce(function(total,max){return total+max;},0);total+=maxes.length+1;if(this.width<total){delete this.position.width;}
if(this.position.width!=null){var missing=this.width-total;var w=missing/maxes.length|0;var wr=missing%maxes.length;maxes=maxes.map(function(max,i){if(i===maxes.length-1){return max+w+wr;}
return max+w;});}else{maxes=maxes.map(function(max){return max+self.pad;});}
return this._maxes=maxes;};Table.prototype.setRows=Table.prototype.setData=function(rows){var self=this,text='',align=this.align;this.rows=rows||[];this._calculateMaxes();if(!this._maxes)return;this.rows.forEach(function(row,i){var isFooter=i===self.rows.length-1;row.forEach(function(cell,i){var width=self._maxes[i];var clen=self.strWidth(cell);if(i!==0){text+=' ';}
while(clen<width){if(align==='center'){cell=' '+cell+' ';clen+=2;}else if(align==='left'){cell=cell+' ';clen+=1;}else if(align==='right'){cell=' '+cell;clen+=1;}}
if(clen>width){if(align==='center'){cell=cell.substring(1);clen--;}else if(align==='left'){cell=cell.slice(0,-1);clen--;}else if(align==='right'){cell=cell.substring(1);clen--;}}
text+=cell;});if(!isFooter){text+='\n\n';}});delete this.align;this.setContent(text);this.align=align;};Table.prototype.render=function(){var self=this;var coords=this._render();if(!coords)return;this._calculateMaxes();if(!this._maxes)return coords;var lines=this.screen.lines,xi=coords.xi,yi=coords.yi,rx,ry,i;var dattr=this.sattr(this.style),hattr=this.sattr(this.style.header),cattr=this.sattr(this.style.cell),battr=this.sattr(this.style.border);var width=coords.xl-coords.xi-this.iright,height=coords.yl-coords.yi-this.ibottom;for(var y=this.itop;y<height;y++){if(!lines[yi+y])break;for(var x=this.ileft;x<width;x++){if(!lines[yi+y][xi+x])break;if(lines[yi+y][xi+x][0]!==dattr)continue;if(y===this.itop){lines[yi+y][xi+x][0]=hattr;}else{lines[yi+y][xi+x][0]=cattr;}
lines[yi+y].dirty=true;}}
if(!this.border||this.options.noCellBorders)return coords;ry=0;for(i=0;i<self.rows.length+1;i++){if(!lines[yi+ry])break;rx=0;self._maxes.forEach(function(max,i){rx+=max;if(i===0){if(!lines[yi+ry][xi+0])return;if(ry===0){lines[yi+ry][xi+0][0]=battr;}else if(ry/2===self.rows.length){lines[yi+ry][xi+0][0]=battr;}else{lines[yi+ry][xi+0][0]=battr;lines[yi+ry][xi+0][1]='\u251c';if(!self.border.left){lines[yi+ry][xi+0][1]='\u2500';}}
lines[yi+ry].dirty=true;}else if(i===self._maxes.length-1){if(!lines[yi+ry][xi+rx+1])return;if(ry===0){rx++;lines[yi+ry][xi+rx][0]=battr;}else if(ry/2===self.rows.length){rx++;lines[yi+ry][xi+rx][0]=battr;}else{rx++;lines[yi+ry][xi+rx][0]=battr;lines[yi+ry][xi+rx][1]='\u2524';if(!self.border.right){lines[yi+ry][xi+rx][1]='\u2500';}}
lines[yi+ry].dirty=true;return;}
if(!lines[yi+ry][xi+rx+1])return;if(ry===0){rx++;lines[yi+ry][xi+rx][0]=battr;lines[yi+ry][xi+rx][1]='\u252c';if(!self.border.top){lines[yi+ry][xi+rx][1]='\u2502';}}else if(ry/2===self.rows.length){rx++;lines[yi+ry][xi+rx][0]=battr;lines[yi+ry][xi+rx][1]='\u2534';if(!self.border.bottom){lines[yi+ry][xi+rx][1]='\u2502';}}else{if(self.options.fillCellBorders){var lbg=(ry<=2?hattr:cattr)&0x1ff;rx++;lines[yi+ry][xi+rx][0]=(battr&~0x1ff)|lbg;}else{rx++;lines[yi+ry][xi+rx][0]=battr;}
lines[yi+ry][xi+rx][1]='\u253c';}
lines[yi+ry].dirty=true;});ry+=2;}
for(ry=1;ry<self.rows.length*2;ry++){if(!lines[yi+ry])break;rx=0;self._maxes.slice(0,-1).forEach(function(max){rx+=max;if(!lines[yi+ry][xi+rx+1])return;if(ry%2!==0){if(self.options.fillCellBorders){var lbg=(ry<=2?hattr:cattr)&0x1ff;rx++;lines[yi+ry][xi+rx][0]=(battr&~0x1ff)|lbg;}else{rx++;lines[yi+ry][xi+rx][0]=battr;}
lines[yi+ry][xi+rx][1]='\u2502';lines[yi+ry].dirty=true;}else{rx++;}});rx=1;self._maxes.forEach(function(max){while(max--){if(ry%2===0){if(!lines[yi+ry])break;if(!lines[yi+ry][xi+rx+1])break;if(self.options.fillCellBorders){var lbg=(ry<=2?hattr:cattr)&0x1ff;lines[yi+ry][xi+rx][0]=(battr&~0x1ff)|lbg;}else{lines[yi+ry][xi+rx][0]=battr;}
lines[yi+ry][xi+rx][1]='\u2500';lines[yi+ry].dirty=true;}
rx++;}
rx++;});}
return coords;};module.exports=Table;};BundleModuleCode['term/widgets/listtable']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var List=Require('term/widgets/list');var Table=Require('term/widgets/table');function ListTable(options){var self=this;if(!instanceOf(this,Node)){return new ListTable(options);}
options=options||{};options.shrink=true;options.normalShrink=true;options.style=options.style||{};options.style.border=options.style.border||{};options.style.header=options.style.header||{};options.style.cell=options.style.cell||{};this.__align=options.align||'center';delete options.align;options.style.selected=options.style.cell.selected;options.style.item=options.style.cell;List.call(this,options);this._header=new Box({parent:this,left:this.screen.autoPadding?0:this.ileft,top:0,width:'shrink',height:1,style:options.style.header,tags:options.parseTags||options.tags});this.on('scroll',function(){self._header.setFront();self._header.rtop=self.childBase;if(!self.screen.autoPadding){self._header.rtop=self.childBase+(self.border?1:0);}});this.pad=options.pad!=null?options.pad:2;this.setData(options.rows||options.data);this.on('attach',function(){self.setData(self.rows);});this.on('resize',function(){var selected=self.selected;self.setData(self.rows);self.select(selected);self.screen.render();});}
inheritPrototype(ListTable,List);ListTable.prototype.type='list-table';ListTable.prototype._calculateMaxes=Table.prototype._calculateMaxes;ListTable.prototype.setRows=ListTable.prototype.setData=function(rows){var self=this,align=this.__align;if(this.visible&&this.lpos){this.clearPos();}
this.clearItems();this.rows=rows||[];this._calculateMaxes();if(!this._maxes)return;this.addItem('');this.rows.forEach(function(row,i){var isHeader=i===0;var text='';row.forEach(function(cell,i){var width=self._maxes[i];var clen=self.strWidth(cell);if(i!==0){text+=' ';}
while(clen<width){if(align==='center'){cell=' '+cell+' ';clen+=2;}else if(align==='left'){cell=cell+' ';clen+=1;}else if(align==='right'){cell=' '+cell;clen+=1;}}
if(clen>width){if(align==='center'){cell=cell.substring(1);clen--;}else if(align==='left'){cell=cell.slice(0,-1);clen--;}else if(align==='right'){cell=cell.substring(1);clen--;}}
text+=cell;});if(isHeader){self._header.setContent(text);}else{self.addItem(text);}});this._header.setFront();this.select(0);};ListTable.prototype._select=ListTable.prototype.select;ListTable.prototype.select=function(i){if(i===0){i=1;}
if(i<=this.childBase){this.setScroll(this.childBase-1);}
return this._select(i);};ListTable.prototype.render=function(){var self=this;var coords=this._render();if(!coords)return;this._calculateMaxes();if(!this._maxes)return coords;var lines=this.screen.lines,xi=coords.xi,yi=coords.yi,rx,ry,i;var battr=this.sattr(this.style.border);var height=coords.yl-coords.yi-this.ibottom;if(!this.border||this.options.noCellBorders)return coords;ry=0;for(i=0;i<height+1;i++){if(!lines[yi+ry])break;rx=0;self._maxes.slice(0,-1).forEach(function(max){rx+=max;if(!lines[yi+ry][xi+rx+1])return;if(ry===0){rx++;lines[yi+ry][xi+rx][0]=battr;lines[yi+ry][xi+rx][1]='\u252c';if(!self.border.top){lines[yi+ry][xi+rx][1]='\u2502';}
lines[yi+ry].dirty=true;}else if(ry===height){rx++;lines[yi+ry][xi+rx][0]=battr;lines[yi+ry][xi+rx][1]='\u2534';if(!self.border.bottom){lines[yi+ry][xi+rx][1]='\u2502';}
lines[yi+ry].dirty=true;}else{rx++;}});ry+=1;}
for(ry=1;ry<height;ry++){if(!lines[yi+ry])break;rx=0;self._maxes.slice(0,-1).forEach(function(max){rx+=max;if(!lines[yi+ry][xi+rx+1])return;if(self.options.fillCellBorders!==false){var lbg=lines[yi+ry][xi+rx][0]&0x1ff;rx++;lines[yi+ry][xi+rx][0]=(battr&~0x1ff)|lbg;}else{rx++;lines[yi+ry][xi+rx][0]=battr;}
lines[yi+ry][xi+rx][1]='\u2502';lines[yi+ry].dirty=true;});}
return coords;};module.exports=ListTable;};BundleModuleCode['term/widgets/terminal']=function(module,exports){var Comp=Require('com/compat');var unicode=Require('term/unicode');var nextTick=global.setImmediate||process.nextTick.bind(process);var Node=Require('term/widgets/node');var Input=Require('term/widgets/input');function Terminal(options){var self=this;if(!instanceOf(this,Node)){return new Terminal(options);}
options=options||{};options.scrollable=options.scrollable!==false;Input.call(this,options);this.screen._listenKeys(this);this.value=options.value||'';this.cpos={x:-1,y:-1};this.cursorControl=true;this.multiline=options.multiline;this.history=[];this.historyTop=0;this.break='all';this.__updateCursor=this._updateCursor.bind(this);this.on('resize',this.__updateCursor);this.on('move',this.__updateCursor);if(options.inputOnFocus){this.on('focus',this.readInput.bind(this,null));}
if(!options.inputOnFocus&&options.keys){this.on('keypress',function(ch,key){if(self._reading)return;if(key.name==='enter'||(options.vi&&key.name==='i')){return self.readInput();}
if(key.name==='e'){return self.readEditor();}});}
if(options.mouse){this.on('click',function(data){if(self._reading)return;if(data.button!=='right')return;self.readEditor();});}
var offsetY=0;if(this._clines)offsetY=this._clines.length-(this.childBase||0);if(options.prompt){this.value=options.prompt;this.prompt=options.prompt;this.inputRange={x0:options.prompt.length,y0:offsetY,y1:offsetY,last:0,line:0};}else{this.inputRange={x0:0,y0:offsetY,y1:offsetY,last:0,line:0};this.prompt='';}}
inheritPrototype(Terminal,Input);Terminal.prototype.type='terminal';Terminal.prototype._updateCursor=function(get){if(this.screen.focused!==this){return;}
var lpos=get?this.lpos:this._getCoords();if(!lpos)return;var last=this._clines[this._clines.length-1],program=this.screen.program,line,offsetY=this.childBase||0,cx,cy;if(last===''&&this.value[this.value.length-1]!=='\n'){last=this._clines[this._clines.length-2]||'';}
line=Math.min(this._clines.length-1-(this.childBase||0),(lpos.yl-lpos.yi)-this.iheight-1);line=Math.max(0,line);if(this.cpos.x==-1||!this.cursorControl)this.cpos.x=this.strWidth(last);if(this.cpos.y==-1||!this.cursorControl)this.cpos.y=line;this.cpos.y=Math.min(this.cpos.y,line);this.cpos.x=Math.min(this.cpos.x,this.strWidth(this._clines[offsetY+this.cpos.y]));cx=lpos.xi+this.ileft+this.cpos.x;cy=lpos.yi+this.itop+this.cpos.y;if(cy===program.y&&cx===program.x){return;}
if(cy===program.y){if(cx>program.x){program.cuf(cx-program.x);}else if(cx<program.x){program.cub(program.x-cx);}}else if(cx===program.x){if(cy>program.y){program.cud(cy-program.y);}else if(cy<program.y){program.cuu(program.y-cy);}}else{program.cup(cy,cx);}};Terminal.prototype.input=Terminal.prototype.setInput=Terminal.prototype.readInput=function(callback){var self=this,focused=this.screen.focused===this;if(this._reading)return;this._reading=true;this._callback=callback;if(!focused){this.screen.saveFocus();this.focus();}
this.screen.grabKeys=true;this._updateCursor();this.screen.program.showCursor();this._done=function fn(err,value){if(!self._reading)return;if(fn.done)return;fn.done=true;self._reading=false;delete self._callback;delete self._done;self.removeListener('keypress',self.__listener);delete self.__listener;self.removeListener('blur',self.__done);delete self.__done;self.screen.program.hideCursor();self.screen.grabKeys=false;if(!focused){self.screen.restoreFocus();}
if(self.options.inputOnFocus){self.screen.rewindFocus();}
if(err==='stop')return;if(err){self.emit('error',err);}else if(value!=null){self.emit('submit',value);}else{self.emit('cancel',value);}
self.emit('action',value);if(!callback)return;return err?callback(err):callback(null,value);};nextTick(function(){if(self.__listener){return;}
self.__listener=self._listener.bind(self);self.on('keypress',self.__listener);});this.__done=this._done.bind(this,null,null);this.on('blur',this.__done);};Terminal.prototype.print=function(line){var offsetY=this.childBase||0,cn1=this._clines.length,y0=this.inputRange.y0,start=this.getLinearPos(this.value,offsetY+this.inputRange.y0,0),end=this.getLinearPos(this.value,offsetY+this.inputRange.y1,this._clines[offsetY+this.inputRange.y1].length);var command=this.value.slice(start,end);this.value=this.value.slice(0,start)+line+'\n'+command+this.value.slice(end);this.screen.render();var cn2=this._clines.length;this.scrollBottom();this.cpos.y+=10;this.cpos.x=this.inputRange.x0=this.prompt.length;this._updateCursor(true);this.inputRange.y0=Math.min(this._clines.length-1,this.cpos.y-this.inputRange.last);this.inputRange.y1=Math.min(this._clines.length-1,this.cpos.y);}
Terminal.prototype._listener=function(ch,key){var done=this._done,self=this,value=this.value,clinesLength=this._clines.length,offsetY=this.childBase||0,newline=false,lastchar=false,backspace=false,controlkey=false,lastline=(this.cpos.y+offsetY+1)==clinesLength;if(key.name==='return')return;if(key.name==='enter'){var start=this.getLinearPos(this.value,offsetY+this.inputRange.y0,0),end=this.getLinearPos(this.value,offsetY+this.inputRange.y1,this._clines[offsetY+this.inputRange.y1].length);var command=this.value.slice(start+this.prompt.length,end);this.value=this.value.slice(0,start)+this.prompt+this.value.slice(end);if(command&&command!=this.history[this.historyTop-1]){this.history.push(command);this.historyTop=this.history.length;}
this.screen.render();offsetY=this.childBase||0;self.cpos.y+=10;this._updateCursor(true);this.cpos.x=self._clines[offsetY+self.cpos.y].length;this.inputRange.y0=this.inputRange.y1=this.cpos.y;this.inputRange.last=0;this.emit('eval',command);return;}
function history(delta){if(self.historyTop+delta<0)return self.scrollBottom();self.historyTop+=delta;var start=self.getLinearPos(self.value,offsetY+self.inputRange.y0,0),end=self.getLinearPos(self.value,offsetY+self.inputRange.y1,self._clines[offsetY+self.inputRange.y1].length);var command=self.history[self.historyTop]||'';self.historyTop=Math.min(Math.max(0,self.historyTop),self.history.length);self.value=self.value.slice(0,start)+self.prompt+command+self.value.slice(end);self.screen.render();self.scrollBottom();self.cpos.x=self._clines[self._clines.length-1].length;self.cpos.y+=10;self._updateCursor(true);self.inputRange.y1=self.cpos.y;offsetY=self.childBase||0;var y0=self.cpos.y;while(self._clines[offsetY+y0].indexOf(self.prompt)!=0)y0--;self.inputRange.y0=y0;self.inputRange.last=self.inputRange.y1-self.inputRange.y0;}
if(this.cursorControl)switch(key.name){case'left':controlkey=true;if(this.cpos.y==this.inputRange.y0&&this.cpos.x>this.inputRange.x0)this.cpos.x--;else if(this.cpos.y!=this.inputRange.y0&&this.cpos.x>0)this.cpos.x--;else if(this.cpos.y!=this.inputRange.y0&&this.cpos.x==0){this.cpos.y--;this.cpos.x=this._clines[offsetY+this.cpos.y].length;}
this._updateCursor(true);break;case'right':controlkey=true;if(this.cpos.y>=this.inputRange.y0&&this.cpos.y<=this.inputRange.y1&&this.cpos.x<this._clines[offsetY+this.cpos.y].length-1){this.cpos.x++;}else if(this.cpos.y>=this.inputRange.y0&&this.cpos.y<this.inputRange.y1&&this.cpos.x==this._clines[offsetY+this.cpos.y].length-1){this.cpos.x=0;this.cpos.y++;}else if(this.cpos.y>=this.inputRange.y0&&this.cpos.y==this.inputRange.y1&&this.cpos.x<this._clines[offsetY+this.cpos.y].length){this.cpos.x++;}
this._updateCursor(true);break;case'up':controlkey=true;history(-1);return;break;case'down':controlkey=true;history(1);return;break;}
if(this.options.keys&&key.ctrl&&key.name==='e'){return this.readEditor();}
if(key.name==='escape'){done(null,null);}else if(key.name==='backspace'){backspace=true;if(this.cpos.y==this.inputRange.y0&&this.cpos.x<=this.inputRange.x0)return;if(this.value.length){if(this.screen.fullUnicode){if(unicode.isSurrogate(this.value,this.value.length-2)){this.value=this.value.slice(0,-2);}else{this.value=this.value.slice(0,-1);}}else{if(!this.cursorControl||this.cpos.x==-1||(this.cpos.x==this._clines[offsetY+this.cpos.y].length&&this.cpos.y==this._clines.length-1-offsetY)){this.value=this.value.slice(0,-1);}else{vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);this.value=this.value.substr(0,vpos-1)+
this.value.substr(vpos,1000000);}}
if(this.cpos.x>0)this.cpos.x--;else{this.cpos.x=-1;if(offsetY==0&&this.cpos.y>0&&lastline)this.cpos.y--;};}}else if(!controlkey&&ch){if(!/^[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]$/.test(ch)){if(!this.cursorControl||this.cpos.x==-1||(this.cpos.x==this._clines[offsetY+this.cpos.y].length&&this.cpos.y==this._clines.length-1-offsetY)){lastchar=true;this.value+=ch;}else{vpos=this.getLinearPos(this.value,offsetY+this.cpos.y,this.cpos.x);this.value=this.value.substr(0,vpos)+ch+
this.value.substr(vpos,1000000);}
if(newline){this.cpos.x=0;this.cpos.y++;}else
this.cpos.x++;}}
var rmline=this.cpos.x==-1;this.inputRange.line=this._clines.rtof[offsetY+this.cpos.y];if(this.value!==value){var cn0=clinesLength,endofline=this.cpos.x==this._clines[offsetY+this.cpos.y].length+1,cn1=this._clines.length;var linelength1=this._clines[offsetY+this.cpos.y]&&this._clines[offsetY+this.cpos.y].length;this.screen.render();var linelength2=this._clines[offsetY+this.cpos.y]&&this._clines[offsetY+this.cpos.y].length;var cn2=this._clines.length;if(cn2>cn0&&endofline){this.scrollBottom();this.cpos.y++;this.inputRange.last++;if(this._clines[offsetY+this.cpos.y]&&lastchar)this.cpos.x=this._clines[offsetY+this.cpos.y].length;else this.cpos.x=linelength1-linelength2-1;this._updateCursor(true);this.inputRange.y0=this.cpos.y-this.inputRange.last;this.inputRange.y1=this.cpos.y;}else if(cn2<cn0&&!rmline){if(this.cpos.y>0&&!lastline&&lastchar)this.cpos.y--;this.inputRange.last--;if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);this.inputRange.y0=this.cpos.y-this.inputRange.last;this.inputRange.y1=this.cpos.y;offsetY=this.childBase||0;this.cpos.x=this._clines[offsetY+this.cpos.y].length;this._updateCursor(true);}else if(linelength2<linelength1&&!backspace){this.cpos.y++;this.cpos.x=linelength1-linelength2;this._updateCursor(true);}
if(offsetY>0&&backspace){this.scroll(0);this.screen.render();if(rmline){if(this._clines[offsetY+this.cpos.y])this.cpos.x=this._clines[offsetY+this.cpos.y].length;else if(this._clines[offsetY+this.cpos.y-1])this.cpos.x=this._clines[offsetY+this.cpos.y-1].length;this._updateCursor(true);}}}};Terminal.prototype.getLinearPos=function(v,clineIndex,cposx){var lines=v.split('\n'),line=this._clines[clineIndex],flinenum=this._clines.rtof[clineIndex],vpos=flinenum>0?lines.slice(0,flinenum).map(function(line){return line.length+1}).reduce(function(a,b){return a+b}):0;function search(part,line){var i=line.indexOf(part);if(i==-1)return 0;else return i;}
if(lines[flinenum]){return vpos+search(line,lines[flinenum])+cposx;}else
return vpos+cposx;var vpos=0,len=v.length,cline,clinePos=0,clineNum=0;cline=this._clines[clineNum];while(vpos<len&&clineIndex){if(v.charAt(vpos)=='\n'){clinePos=-1;clineIndex--;clineNum++;cline=this._clines[clineNum];}else{if(v.charAt(vpos)!=cline.charAt(clinePos)){clinePos=0;clineIndex--;clineNum++;cline=this._clines[clineNum];continue;}}
vpos++;clinePos++;}
if(clineIndex==0)return vpos+cposx;else 0}
Terminal.prototype._typeScroll=function(){var height=this.height-this.iheight;if(this.cpos.y==height){this.scroll(this._clines.length);}};Terminal.prototype.getValue=function(){return this.value;};Terminal.prototype.setValue=function(value){if(value==null){value=this.value;}
if(this._value!==value){this.value=value;this._value=value;this.setContent(this.value);this._typeScroll();this._updateCursor();}};Terminal.prototype.clearInput=Terminal.prototype.clearValue=function(){return this.setValue('');};Terminal.prototype.submit=function(){if(!this.__listener)return;return this.__listener('\x1b',{name:'escape'});};Terminal.prototype.cancel=function(){if(!this.__listener)return;return this.__listener('\x1b',{name:'escape'});};Terminal.prototype.render=function(){this.setValue();return this._render();};Terminal.prototype.editor=Terminal.prototype.setEditor=Terminal.prototype.readEditor=function(callback){var self=this;if(this._reading){var _cb=this._callback,cb=callback;this._done('stop');callback=function(err,value){if(_cb)_cb(err,value);if(cb)cb(err,value);};}
if(!callback){callback=function(){};}
return this.screen.readEditor({value:this.value},function(err,value){if(err){if(err.message==='Unsuccessful.'){self.screen.render();return self.readInput(callback);}
self.screen.render();self.readInput(callback);return callback(err);}
self.setValue(value);self.screen.render();return self.readInput(callback);});};module.exports=Terminal;};BundleModuleCode['term/widgets/image']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function Image(options){if(!instanceOf(this,Node)){return new Image(options);}
options=options||{};options.type=options.itype||options.type||'ansi';Box.call(this,options);if(options.type==='ansi'&&this.type!=='ansiimage'){var ANSIImage=require('./ansiimage');Object.getOwnPropertyNames(ANSIImage.prototype).forEach(function(key){if(key==='type')return;Object.defineProperty(this,key,Object.getOwnPropertyDescriptor(ANSIImage.prototype,key));},this);ANSIImage.call(this,options);return this;}
if(options.type==='overlay'&&this.type!=='overlayimage'){var OverlayImage=require('./overlayimage');Object.getOwnPropertyNames(OverlayImage.prototype).forEach(function(key){if(key==='type')return;Object.defineProperty(this,key,Object.getOwnPropertyDescriptor(OverlayImage.prototype,key));},this);OverlayImage.call(this,options);return this;}
throw new Error('`type` must either be `ansi` or `overlay`.');}
inheritPrototype(Image,Box);Image.prototype.type='image';module.exports=Image;};BundleModuleCode['term/widgets/ansiimage']=function(module,exports){var Comp=Require('com/compat');var cp=Require('child_process');var colors=Require('term/colors');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var tng=Require('term/tng');function ANSIImage(options){var self=this;if(!instanceOf(this,Node)){return new ANSIImage(options);}
options=options||{};options.shrink=true;Box.call(this,options);this.scale=this.options.scale||1.0;this.options.animate=this.options.animate!==false;this._noFill=true;if(this.options.file){this.setImage(this.options.file);}
this.screen.on('prerender',function(){var lpos=self.lpos;if(!lpos)return;self.screen.clearRegion(lpos.xi,lpos.xl,lpos.yi,lpos.yl);});this.on('destroy',function(){self.stop();});}
inheritPrototype(ANSIImage,Box);ANSIImage.prototype.type='ansiimage';ANSIImage.curl=function(url){try{return cp.execFileSync('curl',['-s','-A','',url],{stdio:['ignore','pipe','ignore']});}catch(e){;}
try{return cp.execFileSync('wget',['-U','','-O','-',url],{stdio:['ignore','pipe','ignore']});}catch(e){;}
throw new Error('curl or wget failed.');};ANSIImage.prototype.setImage=function(file){this.file=typeof file==='string'?file:null;if(/^https?:/.test(file)){file=ANSIImage.curl(file);}
var width=this.position.width;var height=this.position.height;if(width!=null){width=this.width;}
if(height!=null){height=this.height;}
try{this.setContent('');this.img=tng(file,{colors:colors,width:width,height:height,scale:this.scale,ascii:this.options.ascii,speed:this.options.speed,filename:this.file});if(width==null||height==null){this.width=this.img.cellmap[0].length;this.height=this.img.cellmap.length;}
if(this.img.frames&&this.options.animate){this.play();}else{this.cellmap=this.img.cellmap;}}catch(e){this.setContent('Image Error: '+e.message);this.img=null;this.cellmap=null;}};ANSIImage.prototype.play=function(){var self=this;if(!this.img)return;return this.img.play(function(bmp,cellmap){self.cellmap=cellmap;self.screen.render();});};ANSIImage.prototype.pause=function(){if(!this.img)return;return this.img.pause();};ANSIImage.prototype.stop=function(){if(!this.img)return;return this.img.stop();};ANSIImage.prototype.clearImage=function(){this.stop();this.setContent('');this.img=null;this.cellmap=null;};ANSIImage.prototype.render=function(){var coords=this._render();if(!coords)return;if(this.img&&this.cellmap){this.img.renderElement(this.cellmap,this);}
return coords;};module.exports=ANSIImage;};BundleModuleCode['term/tng']=function(module,exports){var fs=Require('fs'),util=Require('util'),path=Require('path'),zlib=Require('zlib'),assert=Require('assert'),cp=Require('child_process'),exec=cp?cp.execFileSync:_;function PNG(file,options){var buf,chunks,idat,pixels;if(!(this instanceof PNG)){return new PNG(file,options);}
if(!file)throw new Error('no file');this.options=options||{};this.colors=options.colors||Require('term/colors');this.optimization=this.options.optimization||'mem';this.speed=this.options.speed||1;if(Buffer.isBuffer(file)){this.file=this.options.filename||null;buf=file;}else{this.options.filename=file;this.file=path.resolve(process.cwd(),file);buf=fs.readFileSync(this.file);}
this.format=buf.readUInt32BE(0)===0x89504e47?'png':buf.slice(0,3).toString('ascii')==='GIF'?'gif':buf.readUInt16BE(0)===0xffd8?'jpg':path.extname(this.file).slice(1).toLowerCase()||'png';if(this.format!=='png'){try{return this.toPNG(buf);}catch(e){throw e;}}
chunks=this.parseRaw(buf);idat=this.parseChunks(chunks);pixels=this.parseLines(idat);this.bmp=this.createBitmap(pixels);this.cellmap=this.createCellmap(this.bmp);this.frames=this.compileFrames(this.frames);}
PNG.prototype.parseRaw=function(buf){var chunks=[],index=0,i=0,buf,len,type,name,data,crc,check,critical,public_,conforming,copysafe,pos;this._debug(this.file);if(buf.readUInt32BE(0)!==0x89504e47||buf.readUInt32BE(4)!==0x0d0a1a0a){throw new Error('bad header');}
i+=8;while(i<buf.length){try{len=buf.readUInt32BE(i);i+=4;pos=i;type=buf.slice(i,i+4);name=type.toString('ascii');i+=4;data=buf.slice(i,i+len);i+=len;check=this.crc32(buf.slice(pos,i));crc=buf.readInt32BE(i);i+=4;critical=!!(~type[0]&32);public_=!!(~type[1]&32);conforming=!!(~type[2]&32);copysafe=!!(~type[3]&32);if(crc!==check){throw new Error(name+': bad crc');}}catch(e){if(this.options.debug)throw e;break;}
chunks.push({index:index++,id:name.toLowerCase(),len:len,pos:pos,end:i,type:type,name:name,data:data,crc:crc,check:check,raw:buf.slice(pos,i),flags:{critical:critical,public_:public_,conforming:conforming,copysafe:copysafe}});}
return chunks;};PNG.prototype.parseChunks=function(chunks){var i,chunk,name,data,p,idat,info;for(i=0;i<chunks.length;i++){chunk=chunks[i];name=chunk.id;data=chunk.data;info={};switch(name){case'ihdr':{this.width=info.width=data.readUInt32BE(0);this.height=info.height=data.readUInt32BE(4);this.bitDepth=info.bitDepth=data.readUInt8(8);this.colorType=info.colorType=data.readUInt8(9);this.compression=info.compression=data.readUInt8(10);this.filter=info.filter=data.readUInt8(11);this.interlace=info.interlace=data.readUInt8(12);switch(this.bitDepth){case 1:case 2:case 4:case 8:case 16:case 24:case 32:break;default:throw new Error('bad bit depth: '+this.bitDepth);}
switch(this.colorType){case 0:case 2:case 3:case 4:case 6:break;default:throw new Error('bad color: '+this.colorType);}
switch(this.compression){case 0:break;default:throw new Error('bad compression: '+this.compression);}
switch(this.filter){case 0:case 1:case 2:case 3:case 4:break;default:throw new Error('bad filter: '+this.filter);}
switch(this.interlace){case 0:case 1:break;default:throw new Error('bad interlace: '+this.interlace);}
break;}
case'plte':{this.palette=info.palette=[];for(p=0;p<data.length;p+=3){this.palette.push({r:data[p+0],g:data[p+1],b:data[p+2],a:255});}
break;}
case'idat':{this.size=this.size||0;this.size+=data.length;this.idat=this.idat||[];this.idat.push(data);info.size=data.length;break;}
case'iend':{this.end=true;break;}
case'trns':{this.alpha=info.alpha=Array.prototype.slice.call(data);if(this.palette){for(p=0;p<data.length;p++){if(!this.palette[p])break;this.palette[p].a=data[p];}}
break;}
case'actl':{this.actl=info={};this.frames=[];this.actl.numFrames=data.readUInt32BE(0);this.actl.numPlays=data.readUInt32BE(4);break;}
case'fctl':{if(!this.idat){this.idat=[];this.frames.push({idat:true,fctl:info,fdat:this.idat});}else{this.frames.push({fctl:info,fdat:[]});}
info.sequenceNumber=data.readUInt32BE(0);info.width=data.readUInt32BE(4);info.height=data.readUInt32BE(8);info.xOffset=data.readUInt32BE(12);info.yOffset=data.readUInt32BE(16);info.delayNum=data.readUInt16BE(20);info.delayDen=data.readUInt16BE(22);info.disposeOp=data.readUInt8(24);info.blendOp=data.readUInt8(25);break;}
case'fdat':{info.sequenceNumber=data.readUInt32BE(0);info.data=data.slice(4);this.frames[this.frames.length-1].fdat.push(info.data);break;}}
chunk.info=info;}
this._debug(chunks);if(this.frames){this.frames=this.frames.map(function(frame,i){frame.fdat=this.decompress(frame.fdat);if(!frame.fdat.length)throw new Error('no data');return frame;},this);}
idat=this.decompress(this.idat);if(!idat.length)throw new Error('no data');return idat;};PNG.prototype.parseLines=function(data){var pixels=[],x,p,prior,line,filter,samples,pendingSamples,ch,shiftStart,i,toShift,sample;this.sampleDepth=this.colorType===0?1:this.colorType===2?3:this.colorType===3?1:this.colorType===4?2:this.colorType===6?4:1;this.bitsPerPixel=this.bitDepth*this.sampleDepth;this.bytesPerPixel=Math.ceil(this.bitsPerPixel/8);this.wastedBits=((this.width*this.bitsPerPixel)/8)-((this.width*this.bitsPerPixel/8)|0);this.byteWidth=Math.ceil(this.width*(this.bitsPerPixel/8));this.shiftStart=((this.bitDepth+(8/this.bitDepth-this.bitDepth))-1)|0;this.shiftMult=this.bitDepth>=8?0:this.bitDepth;this.mask=this.bitDepth===32?0xffffffff:(1<<this.bitDepth)-1;if(this.interlace===1){samples=this.sampleInterlacedLines(data);for(i=0;i<samples.length;i+=this.sampleDepth){pixels.push(samples.slice(i,i+this.sampleDepth));}
return pixels;}
for(p=0;p<data.length;p+=this.byteWidth){prior=line||[];filter=data[p++];line=data.slice(p,p+this.byteWidth);line=this.unfilterLine(filter,line,prior);samples=this.sampleLine(line);for(i=0;i<samples.length;i+=this.sampleDepth){pixels.push(samples.slice(i,i+this.sampleDepth));}}
return pixels;};PNG.prototype.unfilterLine=function(filter,line,prior){for(var x=0;x<line.length;x++){if(filter===0){break;}else if(filter===1){line[x]=this.filters.sub(x,line,prior,this.bytesPerPixel);}else if(filter===2){line[x]=this.filters.up(x,line,prior,this.bytesPerPixel);}else if(filter===3){line[x]=this.filters.average(x,line,prior,this.bytesPerPixel);}else if(filter===4){line[x]=this.filters.paeth(x,line,prior,this.bytesPerPixel);}}
return line;};PNG.prototype.sampleLine=function(line,width){var samples=[],x=0,pendingSamples,ch,i,sample,shiftStart,toShift;while(x<line.length){pendingSamples=this.sampleDepth;while(pendingSamples--){ch=line[x];if(this.bitDepth===16){ch=(ch<<8)|line[++x];}else if(this.bitDepth===24){ch=(ch<<16)|(line[++x]<<8)|line[++x];}else if(this.bitDepth===32){ch=(ch<<24)|(line[++x]<<16)|(line[++x]<<8)|line[++x];}else if(this.bitDepth>32){throw new Error('bitDepth '+this.bitDepth+' unsupported.');}
shiftStart=this.shiftStart;toShift=shiftStart-(x===line.length-1?this.wastedBits:0);for(i=0;i<=toShift;i++){sample=(ch>>(this.shiftMult*shiftStart))&this.mask;if(this.colorType!==3){if(this.bitDepth<8){sample*=0xff/this.mask;sample|=0;}else if(this.bitDepth>8){sample=(sample/this.mask)*255|0;}}
samples.push(sample);shiftStart--;}
x++;}}
if(width!=null){samples=samples.slice(0,width*this.sampleDepth);}
return samples;};PNG.prototype.filters={sub:function Sub(x,line,prior,bpp){if(x<bpp)return line[x];return(line[x]+line[x-bpp])%256;},up:function Up(x,line,prior,bpp){return(line[x]+(prior[x]||0))%256;},average:function Average(x,line,prior,bpp){if(x<bpp)return Math.floor((prior[x]||0)/2);return(line[x]
+Math.floor((line[x-bpp]+prior[x])/2))%256;},paeth:function Paeth(x,line,prior,bpp){if(x<bpp)return prior[x]||0;return(line[x]+this._predictor(line[x-bpp],prior[x]||0,prior[x-bpp]||0))%256;},_predictor:function PaethPredictor(a,b,c){var p=a+b-c,pa=Math.abs(p-a),pb=Math.abs(p-b),pc=Math.abs(p-c);if(pa<=pb&&pa<=pc)return a;if(pb<=pc)return b;return c;}};PNG.prototype.sampleInterlacedLines=function(raw){var psize,vpr,samples,source_offset,i,pass,xstart,ystart,xstep,ystep,recon,ppr,row_size,y,filter_type,scanline,flat,offset,k,end_offset,skip,j,k,f;var adam7=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]];psize=(this.bitDepth/8)*this.sampleDepth;vpr=this.width*this.sampleDepth;samples=new Buffer(vpr*this.height);samples.fill(0);source_offset=0;for(i=0;i<adam7.length;i++){pass=adam7[i];xstart=pass[0];ystart=pass[1];xstep=pass[2];ystep=pass[3];if(xstart>=this.width)continue;recon=[];ppr=Math.ceil((this.width-xstart)/xstep);row_size=Math.ceil(psize*ppr);for(y=ystart;y<this.height;y+=ystep){filter_type=raw[source_offset];source_offset+=1;scanline=raw.slice(source_offset,source_offset+row_size);source_offset+=row_size;recon=this.unfilterLine(filter_type,scanline,recon);flat=this.sampleLine(recon,ppr);if(xstep===1){assert.equal(xstart,0);offset=y*vpr;for(k=offset,f=0;k<offset+vpr;k++,f++){samples[k]=flat[f];}}else{offset=y*vpr+xstart*this.sampleDepth;end_offset=(y+1)*vpr;skip=this.sampleDepth*xstep;for(j=0;j<this.sampleDepth;j++){for(k=offset+j,f=j;k<end_offset;k+=skip,f+=this.sampleDepth){samples[k]=flat[f];}}}}}
return samples;};PNG.prototype.createBitmap=function(pixels){var bmp=[],i;if(this.colorType===0){pixels=pixels.map(function(sample){return{r:sample[0],g:sample[0],b:sample[0],a:255};});}else if(this.colorType===2){pixels=pixels.map(function(sample){return{r:sample[0],g:sample[1],b:sample[2],a:255};});}else if(this.colorType===3){pixels=pixels.map(function(sample){if(!this.palette[sample[0]])throw new Error('bad palette index');return this.palette[sample[0]];},this);}else if(this.colorType===4){pixels=pixels.map(function(sample){return{r:sample[0],g:sample[0],b:sample[0],a:sample[1]};});}else if(this.colorType===6){pixels=pixels.map(function(sample){return{r:sample[0],g:sample[1],b:sample[2],a:sample[3]};});}
for(i=0;i<pixels.length;i+=this.width){bmp.push(pixels.slice(i,i+this.width));}
return bmp;};PNG.prototype.createCellmap=function(bmp,options){var bmp=bmp||this.bmp,options=options||this.options,cellmap=[],scale=options.scale||0.20,height=bmp.length,width=bmp[0].length,cmwidth=options.width,cmheight=options.height,line,x,y,xx,yy,scale,xs,ys;if(cmwidth){scale=cmwidth/width;}else if(cmheight){scale=cmheight/height;}
if(!cmheight){cmheight=Math.round(height*scale);}
if(!cmwidth){cmwidth=Math.round(width*scale);}
ys=height/cmheight;xs=width/cmwidth;for(y=0;y<bmp.length;y+=ys){line=[];yy=Math.round(y);if(!bmp[yy])break;for(x=0;x<bmp[yy].length;x+=xs){xx=Math.round(x);if(!bmp[yy][xx])break;line.push(bmp[yy][xx]);}
cellmap.push(line);}
return cellmap;};PNG.prototype.renderANSI=function(bmp){var self=this,out='';bmp.forEach(function(line,y){line.forEach(function(pixel,x){var outch=self.getOutch(x,y,line,pixel);out+=self.pixelToSGR(pixel,outch);});out+='\n';});return out;};PNG.prototype.renderContent=function(bmp,el){var self=this,out='';bmp.forEach(function(line,y){line.forEach(function(pixel,x){var outch=self.getOutch(x,y,line,pixel);out+=self.pixelToTags(pixel,outch);});out+='\n';});el.setContent(out);return out;};PNG.prototype.renderScreen=function(bmp,screen,xi,xl,yi,yl){var self=this,lines=screen.lines,cellLines,y,yy,x,xx,alpha,attr,ch;cellLines=bmp.reduce(function(cellLines,line,y){var cellLine=[];line.forEach(function(pixel,x){var outch=self.getOutch(x,y,line,pixel),cell=self.pixelToCell(pixel,outch);cellLine.push(cell);});cellLines.push(cellLine);return cellLines;},[]);for(y=yi;y<yl;y++){yy=y-yi;for(x=xi;x<xl;x++){xx=x-xi;if(lines[y]&&lines[y][x]&&cellLines[yy]&&cellLines[yy][xx]){alpha=cellLines[yy][xx].pop();if(alpha===0.0){continue;}
if(alpha<1.0){attr=cellLines[yy][xx][0];ch=cellLines[yy][xx][1];lines[y][x][0]=this.colors.blend(lines[y][x][0],attr,alpha);if(ch!==' ')lines[y][x][1]=ch;lines[y].dirty=true;continue;}
lines[y][x]=cellLines[yy][xx];lines[y].dirty=true;}}}};PNG.prototype.renderElement=function(bmp,el){var xi=el.aleft+el.ileft,xl=el.aleft+el.width-el.iright,yi=el.atop+el.itop,yl=el.atop+el.height-el.ibottom;return this.renderScreen(bmp,el.screen,xi,xl,yi,yl);};PNG.prototype.pixelToSGR=function(pixel,ch){var bga=1.0,fga=0.5,a=pixel.a/255,bg,fg;bg=this.colors.match(pixel.r*a*bga|0,pixel.g*a*bga|0,pixel.b*a*bga|0);if(ch&&this.options.ascii){fg=this.colors.match(pixel.r*a*fga|0,pixel.g*a*fga|0,pixel.b*a*fga|0);if(a===0){return'\x1b[38;5;'+fg+'m'+ch+'\x1b[m';}
return'\x1b[38;5;'+fg+'m\x1b[48;5;'+bg+'m'+ch+'\x1b[m';}
if(a===0)return' ';return'\x1b[48;5;'+bg+'m \x1b[m';};PNG.prototype.pixelToTags=function(pixel,ch){var bga=1.0,fga=0.5,a=pixel.a/255,bg,fg;bg=this.colors.RGBtoHex(pixel.r*a*bga|0,pixel.g*a*bga|0,pixel.b*a*bga|0);if(ch&&this.options.ascii){fg=this.colors.RGBtoHex(pixel.r*a*fga|0,pixel.g*a*fga|0,pixel.b*a*fga|0);if(a===0){return'{'+fg+'-fg}'+ch+'{/}';}
return'{'+fg+'-fg}{'+bg+'-bg}'+ch+'{/}';}
if(a===0)return' ';return'{'+bg+'-bg} {/'+bg+'-bg}';};PNG.prototype.pixelToCell=function(pixel,ch){var bga=1.0,fga=0.5,a=pixel.a/255,bg,fg;bg=this.colors.match(pixel.r*bga|0,pixel.g*bga|0,pixel.b*bga|0);if(ch&&this.options.ascii){fg=this.colors.match(pixel.r*fga|0,pixel.g*fga|0,pixel.b*fga|0);}else{fg=0x1ff;ch=null;}
return[(0<<18)|(fg<<9)|(bg<<0),ch||' ',a];};PNG.prototype.getOutch=(function(){var dchars='????8@8@#8@8##8#MKXWwz$&%x><\\/xo;+=|^-:i\'.`, `. ';var luminance=function(pixel){var a=pixel.a/255,r=pixel.r*a,g=pixel.g*a,b=pixel.b*a,l=0.2126*r+0.7152*g+0.0722*b;return l/255;};return function(x,y,line,pixel){var lumi=luminance(pixel),outch=dchars[lumi*(dchars.length-1)|0];return outch;};})();PNG.prototype.compileFrames=function(frames){return this.optimization==='mem'?this.compileFrames_lomem(frames):this.compileFrames_locpu(frames);};PNG.prototype.compileFrames_lomem=function(frames){if(!this.actl)return;return frames.map(function(frame,i){this.width=frame.fctl.width;this.height=frame.fctl.height;var pixels=frame._pixels||this.parseLines(frame.fdat),bmp=frame._bmp||this.createBitmap(pixels),fc=frame.fctl;return{actl:this.actl,fctl:frame.fctl,delay:(fc.delayNum/(fc.delayDen||100))*1000|0,bmp:bmp};},this);};PNG.prototype.compileFrames_locpu=function(frames){if(!this.actl)return;this._curBmp=null;this._lastBmp=null;return frames.map(function(frame,i){this.width=frame.fctl.width;this.height=frame.fctl.height;var pixels=frame._pixels||this.parseLines(frame.fdat),bmp=frame._bmp||this.createBitmap(pixels),renderBmp=this.renderFrame(bmp,frame,i),cellmap=this.createCellmap(renderBmp),fc=frame.fctl;return{actl:this.actl,fctl:frame.fctl,delay:(fc.delayNum/(fc.delayDen||100))*1000|0,bmp:renderBmp,cellmap:cellmap};},this);};PNG.prototype.renderFrame=function(bmp,frame,i){var first=this.frames[0],last=this.frames[i-1],fc=frame.fctl,xo=fc.xOffset,yo=fc.yOffset,lxo,lyo,x,y,line,p;if(!this._curBmp){this._curBmp=[];for(y=0;y<first.fctl.height;y++){line=[];for(x=0;x<first.fctl.width;x++){p=bmp[y][x];line.push({r:p.r,g:p.g,b:p.b,a:p.a});}
this._curBmp.push(line);}}
if(last&&last.fctl.disposeOp!==0){lxo=last.fctl.xOffset;lyo=last.fctl.yOffset;for(y=0;y<last.fctl.height;y++){for(x=0;x<last.fctl.width;x++){if(last.fctl.disposeOp===0){}else if(last.fctl.disposeOp===1){this._curBmp[lyo+y][lxo+x]={r:0,g:0,b:0,a:0};}else if(last.fctl.disposeOp===2){p=this._lastBmp[y][x];this._curBmp[lyo+y][lxo+x]={r:p.r,g:p.g,b:p.b,a:p.a};}}}}
if(frame.fctl.disposeOp===2){this._lastBmp=[];for(y=0;y<frame.fctl.height;y++){line=[];for(x=0;x<frame.fctl.width;x++){p=this._curBmp[yo+y][xo+x];line.push({r:p.r,g:p.g,b:p.b,a:p.a});}
this._lastBmp.push(line);}}else{this._lastBmp=null;}
for(y=0;y<frame.fctl.height;y++){for(x=0;x<frame.fctl.width;x++){p=bmp[y][x];if(fc.blendOp===0){this._curBmp[yo+y][xo+x]={r:p.r,g:p.g,b:p.b,a:p.a};}else if(fc.blendOp===1){if(p.a!==0){this._curBmp[yo+y][xo+x]={r:p.r,g:p.g,b:p.b,a:p.a};}}}}
return this._curBmp;};PNG.prototype._animate=function(callback){if(!this.frames){return callback(this.bmp,this.cellmap);}
var self=this,numPlays=this.actl.numPlays||Infinity,running=0,i=-1;this._curBmp=null;this._lastBmp=null;var next_lomem=function(){if(!running)return;var frame=self.frames[++i];if(!frame){if(!--numPlays)return callback();i=-1;self._curBmp=null;self._lastBmp=null;return setImmediate(next);}
var bmp=frame.bmp,renderBmp=self.renderFrame(bmp,frame,i),cellmap=self.createCellmap(renderBmp);callback(renderBmp,cellmap);return setTimeout(next,frame.delay/self.speed|0);};var next_locpu=function(){if(!running)return;var frame=self.frames[++i];if(!frame){if(!--numPlays)return callback();i=-1;return setImmediate(next);}
callback(frame.bmp,frame.cellmap);return setTimeout(next,frame.delay/self.speed|0);};var next=this.optimization==='mem'?next_lomem:next_locpu;this._control=function(state){if(state===-1){i=-1;self._curBmp=null;self._lastBmp=null;running=0;callback(self.frames[0].bmp,self.frames[0].cellmap||self.createCellmap(self.frames[0].bmp));return;}
if(state===running)return;running=state;return next();};this._control(1);};PNG.prototype.play=function(callback){if(!this._control||callback){this.stop();return this._animate(callback);}
this._control(1);};PNG.prototype.pause=function(){if(!this._control)return;this._control(0);};PNG.prototype.stop=function(){if(!this._control)return;this._control(-1);};PNG.prototype.toPNG=function(input){var options=this.options,file=this.file,format=this.format,buf,img,gif,i,control,disposeOp;if(format!=='gif'){buf=exec('convert',[format+':-','png:-'],{stdio:['pipe','pipe','ignore'],input:input});img=PNG(buf,options);img.file=file;return img;}
gif=GIF(input,options);this.width=gif.width;this.height=gif.height;this.frames=[];for(i=0;i<gif.images.length;i++){img=gif.images[i];control=img.control||gif;disposeOp=Math.max(0,(control.disposeMethod||0)-1);if(disposeOp>2)disposeOp=0;this.frames.push({fctl:{sequenceNumber:i,width:img.width,height:img.height,xOffset:img.left,yOffset:img.top,delayNum:control.delay,delayDen:100,disposeOp:disposeOp,blendOp:1},fdat:[],_pixels:[],_bmp:img.bmp});}
this.bmp=this.frames[0]._bmp;this.cellmap=this.createCellmap(this.bmp);if(this.frames.length>1){this.actl={numFrames:gif.images.length,numPlays:gif.numPlays||0};this.frames=this.compileFrames(this.frames);}else{this.frames=undefined;}
return this;};PNG.prototype.gifMagick=function(input){var options=this.options,file=this.file,format=this.format,buf,fmt,img,frames,frame,width,height,iwidth,twidth,i,lines,line,x,y;buf=exec('convert',[format+':-','-coalesce','+append','png:-'],{stdio:['pipe','pipe','ignore'],input:input});fmt='{"W":%W,"H":%H,"w":%w,"h":%h,"d":%T,"x":"%X","y":"%Y"},'
frames=exec('identify',['-format',fmt,format+':-'],{encoding:'utf8',stdio:['pipe','pipe','ignore'],input:input});frames=JSON.parse('['+frames.trim().slice(0,-1)+']');img=PNG(buf,options);img.file=file;Object.keys(img).forEach(function(key){this[key]=img[key];},this);width=frames[0].W;height=frames[0].H;iwidth=0;twidth=0;this.width=width;this.height=height;this.frames=[];for(i=0;i<frames.length;i++){frame=frames[i];frame.x=+frame.x;frame.y=+frame.y;iwidth=twidth;twidth+=width;lines=[];for(y=frame.y;y<height;y++){line=[];for(x=iwidth+frame.x;x<twidth;x++){line.push(img.bmp[y][x]);}
lines.push(line);}
this.frames.push({fctl:{sequenceNumber:i,width:frame.w,height:frame.h,xOffset:frame.x,yOffset:frame.y,delayNum:frame.d,delayDen:100,disposeOp:0,blendOp:0},fdat:[],_pixels:[],_bmp:lines});}
this.bmp=this.frames[0]._bmp;this.cellmap=this.createCellmap(this.bmp);if(this.frames.length>1){this.actl={numFrames:frames.length,numPlays:0};this.frames=this.compileFrames(this.frames);}else{this.frames=undefined;}
return this;};PNG.prototype.decompress=function(buffers){return zlib.inflateSync(new Buffer(buffers.reduce(function(out,data){return out.concat(Array.prototype.slice.call(data));},[])));};PNG.prototype.crc32=(function(){var crcTable=[0x00000000,0x77073096,0xee0e612c,0x990951ba,0x076dc419,0x706af48f,0xe963a535,0x9e6495a3,0x0edb8832,0x79dcb8a4,0xe0d5e91e,0x97d2d988,0x09b64c2b,0x7eb17cbd,0xe7b82d07,0x90bf1d91,0x1db71064,0x6ab020f2,0xf3b97148,0x84be41de,0x1adad47d,0x6ddde4eb,0xf4d4b551,0x83d385c7,0x136c9856,0x646ba8c0,0xfd62f97a,0x8a65c9ec,0x14015c4f,0x63066cd9,0xfa0f3d63,0x8d080df5,0x3b6e20c8,0x4c69105e,0xd56041e4,0xa2677172,0x3c03e4d1,0x4b04d447,0xd20d85fd,0xa50ab56b,0x35b5a8fa,0x42b2986c,0xdbbbc9d6,0xacbcf940,0x32d86ce3,0x45df5c75,0xdcd60dcf,0xabd13d59,0x26d930ac,0x51de003a,0xc8d75180,0xbfd06116,0x21b4f4b5,0x56b3c423,0xcfba9599,0xb8bda50f,0x2802b89e,0x5f058808,0xc60cd9b2,0xb10be924,0x2f6f7c87,0x58684c11,0xc1611dab,0xb6662d3d,0x76dc4190,0x01db7106,0x98d220bc,0xefd5102a,0x71b18589,0x06b6b51f,0x9fbfe4a5,0xe8b8d433,0x7807c9a2,0x0f00f934,0x9609a88e,0xe10e9818,0x7f6a0dbb,0x086d3d2d,0x91646c97,0xe6635c01,0x6b6b51f4,0x1c6c6162,0x856530d8,0xf262004e,0x6c0695ed,0x1b01a57b,0x8208f4c1,0xf50fc457,0x65b0d9c6,0x12b7e950,0x8bbeb8ea,0xfcb9887c,0x62dd1ddf,0x15da2d49,0x8cd37cf3,0xfbd44c65,0x4db26158,0x3ab551ce,0xa3bc0074,0xd4bb30e2,0x4adfa541,0x3dd895d7,0xa4d1c46d,0xd3d6f4fb,0x4369e96a,0x346ed9fc,0xad678846,0xda60b8d0,0x44042d73,0x33031de5,0xaa0a4c5f,0xdd0d7cc9,0x5005713c,0x270241aa,0xbe0b1010,0xc90c2086,0x5768b525,0x206f85b3,0xb966d409,0xce61e49f,0x5edef90e,0x29d9c998,0xb0d09822,0xc7d7a8b4,0x59b33d17,0x2eb40d81,0xb7bd5c3b,0xc0ba6cad,0xedb88320,0x9abfb3b6,0x03b6e20c,0x74b1d29a,0xead54739,0x9dd277af,0x04db2615,0x73dc1683,0xe3630b12,0x94643b84,0x0d6d6a3e,0x7a6a5aa8,0xe40ecf0b,0x9309ff9d,0x0a00ae27,0x7d079eb1,0xf00f9344,0x8708a3d2,0x1e01f268,0x6906c2fe,0xf762575d,0x806567cb,0x196c3671,0x6e6b06e7,0xfed41b76,0x89d32be0,0x10da7a5a,0x67dd4acc,0xf9b9df6f,0x8ebeeff9,0x17b7be43,0x60b08ed5,0xd6d6a3e8,0xa1d1937e,0x38d8c2c4,0x4fdff252,0xd1bb67f1,0xa6bc5767,0x3fb506dd,0x48b2364b,0xd80d2bda,0xaf0a1b4c,0x36034af6,0x41047a60,0xdf60efc3,0xa867df55,0x316e8eef,0x4669be79,0xcb61b38c,0xbc66831a,0x256fd2a0,0x5268e236,0xcc0c7795,0xbb0b4703,0x220216b9,0x5505262f,0xc5ba3bbe,0xb2bd0b28,0x2bb45a92,0x5cb36a04,0xc2d7ffa7,0xb5d0cf31,0x2cd99e8b,0x5bdeae1d,0x9b64c2b0,0xec63f226,0x756aa39c,0x026d930a,0x9c0906a9,0xeb0e363f,0x72076785,0x05005713,0x95bf4a82,0xe2b87a14,0x7bb12bae,0x0cb61b38,0x92d28e9b,0xe5d5be0d,0x7cdcefb7,0x0bdbdf21,0x86d3d2d4,0xf1d4e242,0x68ddb3f8,0x1fda836e,0x81be16cd,0xf6b9265b,0x6fb077e1,0x18b74777,0x88085ae6,0xff0f6a70,0x66063bca,0x11010b5c,0x8f659eff,0xf862ae69,0x616bffd3,0x166ccf45,0xa00ae278,0xd70dd2ee,0x4e048354,0x3903b3c2,0xa7672661,0xd06016f7,0x4969474d,0x3e6e77db,0xaed16a4a,0xd9d65adc,0x40df0b66,0x37d83bf0,0xa9bcae53,0xdebb9ec5,0x47b2cf7f,0x30b5ffe9,0xbdbdf21c,0xcabac28a,0x53b39330,0x24b4a3a6,0xbad03605,0xcdd70693,0x54de5729,0x23d967bf,0xb3667a2e,0xc4614ab8,0x5d681b02,0x2a6f2b94,0xb40bbe37,0xc30c8ea1,0x5a05df1b,0x2d02ef8d];return function crc32(buf){var crc=-1;for(var i=0,len=buf.length;i<len;i++){crc=crcTable[(crc^buf[i])&0xff]^(crc>>>8);}
return crc^-1;};})();PNG.prototype._debug=function(){if(!this.options.log)return;return this.options.log.apply(null,arguments);};function GIF(file,options){var self=this;if(!(this instanceof GIF)){return new GIF(file,options);}
var info={},p=0,buf,i,total,sig,desc,img,ext,label,size;if(!file)throw new Error('no file');options=options||{};this.options=options;this.pixelLimit=this.options.pixelLimit||7622550;this.totalPixels=0;if(Buffer.isBuffer(file)){buf=file;file=null;}else{file=path.resolve(process.cwd(),file);buf=fs.readFileSync(file);}
sig=buf.slice(0,6).toString('ascii');if(sig!=='GIF87a'&&sig!=='GIF89a'){throw new Error('bad header: '+sig);}
this.width=buf.readUInt16LE(6);this.height=buf.readUInt16LE(8);this.flags=buf.readUInt8(10);this.gct=!!(this.flags&0x80);this.gctsize=(this.flags&0x07)+1;this.bgIndex=buf.readUInt8(11);this.aspect=buf.readUInt8(12);p+=13;if(this.gct){this.colors=[];total=1<<this.gctsize;for(i=0;i<total;i++,p+=3){this.colors.push([buf[p],buf[p+1],buf[p+2],255]);}}
this.images=[];this.extensions=[];try{while(p<buf.length){desc=buf.readUInt8(p);p+=1;if(desc===0x2c){img={};img.left=buf.readUInt16LE(p);p+=2;img.top=buf.readUInt16LE(p);p+=2;img.width=buf.readUInt16LE(p);p+=2;img.height=buf.readUInt16LE(p);p+=2;img.flags=buf.readUInt8(p);p+=1;img.lct=!!(img.flags&0x80);img.ilace=!!(img.flags&0x40);img.lctsize=(img.flags&0x07)+1;if(img.lct){img.lcolors=[];total=1<<img.lctsize;for(i=0;i<total;i++,p+=3){img.lcolors.push([buf[p],buf[p+1],buf[p+2],255]);}}
img.codeSize=buf.readUInt8(p);p+=1;img.size=buf.readUInt8(p);p+=1;img.lzw=[buf.slice(p,p+img.size)];p+=img.size;while(buf[p]!==0x00){if(buf[p]===0x3b&&p===buf.length-1){p--;break;}
size=buf.readUInt8(p);p+=1;img.lzw.push(buf.slice(p,p+size));p+=size;}
assert.equal(buf.readUInt8(p),0x00);p+=1;if(ext&&ext.label===0xf9){img.control=ext;}
this.totalPixels+=img.width*img.height;this.images.push(img);if(this.totalPixels>=this.pixelLimit){break;}}else if(desc===0x21){ext={};label=buf.readUInt8(p);p+=1;ext.label=label;if(label===0xf9){size=buf.readUInt8(p);assert.equal(size,0x04);p+=1;ext.fields=buf.readUInt8(p);ext.disposeMethod=(ext.fields>>2)&0x07;ext.useTransparent=!!(ext.fields&0x01);p+=1;ext.delay=buf.readUInt16LE(p);p+=2;ext.transparentColor=buf.readUInt8(p);p+=1;while(buf[p]!==0x00){size=buf.readUInt8(p);p+=1;p+=size;}
assert.equal(buf.readUInt8(p),0x00);p+=1;this.delay=ext.delay;this.transparentColor=ext.transparentColor;this.disposeMethod=ext.disposeMethod;this.useTransparent=ext.useTransparent;}else if(label===0xff){size=buf.readUInt8(p);p+=1;ext.id=buf.slice(p,p+8).toString('ascii');p+=8;ext.auth=buf.slice(p,p+3).toString('ascii');p+=3;ext.data=[];while(buf[p]!==0x00){size=buf.readUInt8(p);p+=1;ext.data.push(buf.slice(p,p+size));p+=size;}
ext.data=new Buffer(ext.data.reduce(function(out,data){return out.concat(Array.prototype.slice.call(data));},[]));if(ext.id==='ANIMEXTS'&&ext.auth==='1.0'){ext.id='NETSCAPE';ext.auth='2.0';ext.animexts=true;}
if(ext.id==='NETSCAPE'&&ext.auth==='2.0'){if(ext.data.readUInt8(0)===0x01){ext.numPlays=ext.data.readUInt16LE(1);this.numPlays=ext.numPlays;}else if(ext.data.readUInt8(0)===0x02){this.minBuffer=ext.data;}}
if(ext.id==='XMP Data'&&ext.auth==='XMP'){ext.xmp=ext.data.toString('utf8');this.xmp=ext.xmp;}
if(ext.id==='ICCRGBG1'&&ext.auth==='012'){this.icc=ext.data;}
if(ext.id==='fractint'&&/^00[1-7]$/.test(ext.auth)){this.fractint=ext.data;}
assert.equal(buf.readUInt8(p),0x00);p+=1;}else{ext.data=[];while(buf[p]!==0x00){size=buf.readUInt8(p);p+=1;ext.data.push(buf.slice(p,p+size));p+=size;}
assert.equal(buf.readUInt8(p),0x00);p+=1;}
this.extensions.push(ext);}else if(desc===0x3b){break;}else if(p===buf.length-1){break;}else{throw new Error('unknown block');}}}catch(e){if(options.debug){throw e;}}
this.images=this.images.map(function(img,imageIndex){var control=img.control||this;img.lzw=new Buffer(img.lzw.reduce(function(out,data){return out.concat(Array.prototype.slice.call(data));},[]));try{img.data=this.decompress(img.lzw,img.codeSize);}catch(e){if(options.debug)throw e;return;}
var interlacing=[[0,8],[4,8],[2,4],[1,2],[0,0]];var table=img.lcolors||this.colors,row=0,col=0,ilp=0,p=0,b,idx,i,y,x,line,pixel;img.samples=[];for(;;){b=img.data[p++];if(b==null)break;idx=(row*img.width+col)*4;if(!table[b]){if(options.debug)throw new Error('bad samples');table[b]=[0,0,0,0];}
img.samples[idx]=table[b][0];img.samples[idx+1]=table[b][1];img.samples[idx+2]=table[b][2];img.samples[idx+3]=table[b][3];if(control.useTransparent&&b===control.transparentColor){img.samples[idx+3]=0;}
if(++col>=img.width){col=0;if(img.ilace){row+=interlacing[ilp][1];if(row>=img.height){row=interlacing[++ilp][0];}}else{row++;}}}
img.pixels=[];for(i=0;i<img.samples.length;i+=4){img.pixels.push(img.samples.slice(i,i+4));}
img.bmp=[];for(y=0,p=0;y<img.height;y++){line=[];for(x=0;x<img.width;x++){pixel=img.pixels[p++];if(!pixel){if(options.debug)throw new Error('no pixel');line.push({r:0,g:0,b:0,a:0});continue;}
line.push({r:pixel[0],g:pixel[1],b:pixel[2],a:pixel[3]});}
img.bmp.push(line);}
return img;},this).filter(Boolean);if(!this.images.length){throw new Error('no image data or bad decompress');}}
GIF.prototype.decompress=function(input,codeSize){var bitDepth=codeSize+1,CC=1<<codeSize,EOI=CC+1,stack=[],table=[],ntable=0,oldCode=null,buffer=0,nbuffer=0,p=0,buf=[],bits,read,ans,n,code,i,K,b,maxElem;for(;;){if(stack.length===0){bits=bitDepth;read=0;ans=0;while(read<bits){if(nbuffer===0){if(p>=input.length)return buf;buffer=input[p++];nbuffer=8;}
n=Math.min(bits-read,nbuffer);ans|=(buffer&((1<<n)-1))<<read;read+=n;nbuffer-=n;buffer>>=n;}
code=ans;if(code===EOI){break;}
if(code===CC){table=[];for(i=0;i<CC;++i){table[i]=[i,-1,i];}
bitDepth=codeSize+1;maxElem=1<<bitDepth;ntable=CC+2;oldCode=null;continue;}
if(oldCode===null){oldCode=code;buf.push(table[code][0]);continue;}
if(code<ntable){for(i=code;i>=0;i=table[i][1]){stack.push(table[i][0]);}
table[ntable++]=[table[code][2],oldCode,table[oldCode][2]];}else{K=table[oldCode][2];table[ntable++]=[K,oldCode,K];for(i=code;i>=0;i=table[i][1]){stack.push(table[i][0]);}}
oldCode=code;if(ntable===maxElem){maxElem=1<<(++bitDepth);if(bitDepth>12)bitDepth=12;}}
b=stack.pop();if(b==null)break;buf.push(b);}
return buf;};exports=PNG;exports.png=PNG;exports.gif=GIF;module.exports=exports;};BundleModuleCode['term/widgets/overlayimage']=function(module,exports){var Comp=Require('com/compat');var fs=Require('fs'),cp=Require('child_process');var helpers=Require('term/helpers');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');function OverlayImage(options){var self=this;if(!instanceOf(this,Node)){return new OverlayImage(options);}
options=options||{};Box.call(this,options);if(options.w3m){OverlayImage.w3mdisplay=options.w3m;}
if(OverlayImage.hasW3MDisplay==null){if(fs.existsSync(OverlayImage.w3mdisplay)){OverlayImage.hasW3MDisplay=true;}else if(options.search!==false){var file=helpers.findFile('/usr','w3mimgdisplay')||helpers.findFile('/lib','w3mimgdisplay')||helpers.findFile('/bin','w3mimgdisplay');if(file){OverlayImage.hasW3MDisplay=true;OverlayImage.w3mdisplay=file;}else{OverlayImage.hasW3MDisplay=false;}}}
this.on('hide',function(){self._lastFile=self.file;self.clearImage();});this.on('show',function(){if(!self._lastFile)return;self.setImage(self._lastFile);});this.on('detach',function(){self._lastFile=self.file;self.clearImage();});this.on('attach',function(){if(!self._lastFile)return;self.setImage(self._lastFile);});this.onScreenEvent('resize',function(){self._needsRatio=true;});this.onScreenEvent('render',function(){self.screen.program.flush();if(!self._noImage){self.setImage(self.file);}});if(this.options.file||this.options.img){this.setImage(this.options.file||this.options.img);}}
inheritPrototype(OverlayImage,Box);OverlayImage.prototype.type='overlayimage';OverlayImage.w3mdisplay='/usr/lib/w3m/w3mimgdisplay';OverlayImage.prototype.spawn=function(file,args,opt,callback){var spawn=require('child_process').spawn,ps;opt=opt||{};ps=spawn(file,args,opt);ps.on('error',function(err){if(!callback)return;return callback(err);});ps.on('exit',function(code){if(!callback)return;if(code!==0)return callback(new Error('Exit Code: '+code));return callback(null,code===0);});return ps;};OverlayImage.prototype.setImage=function(img,callback){var self=this;if(this._settingImage){this._queue=this._queue||[];this._queue.push([img,callback]);return;}
this._settingImage=true;var reset=function(){self._settingImage=false;self._queue=self._queue||[];var item=self._queue.shift();if(item){self.setImage(item[0],item[1]);}};if(OverlayImage.hasW3MDisplay===false){reset();if(!callback)return;return callback(new Error('W3M Image Display not available.'));}
if(!img){reset();if(!callback)return;return callback(new Error('No image.'));}
this.file=img;return this.getPixelRatio(function(err,ratio){if(err){reset();if(!callback)return;return callback(err);}
return self.renderImage(img,ratio,function(err,success){if(err){reset();if(!callback)return;return callback(err);}
if(self.shrink||self.options.autofit){delete self.shrink;delete self.options.shrink;self.options.autofit=true;return self.imageSize(function(err,size){if(err){reset();if(!callback)return;return callback(err);}
if(self._lastSize&&ratio.tw===self._lastSize.tw&&ratio.th===self._lastSize.th&&size.width===self._lastSize.width&&size.height===self._lastSize.height&&self.aleft===self._lastSize.aleft&&self.atop===self._lastSize.atop){reset();if(!callback)return;return callback(null,success);}
self._lastSize={tw:ratio.tw,th:ratio.th,width:size.width,height:size.height,aleft:self.aleft,atop:self.atop};self.position.width=size.width/ratio.tw|0;self.position.height=size.height/ratio.th|0;self._noImage=true;self.screen.render();self._noImage=false;reset();return self.renderImage(img,ratio,callback);});}
reset();if(!callback)return;return callback(null,success);});});};OverlayImage.prototype.renderImage=function(img,ratio,callback){var self=this;if(cp.execSync){callback=callback||function(err,result){return result;};try{return callback(null,this.renderImageSync(img,ratio));}catch(e){return callback(e);}}
if(OverlayImage.hasW3MDisplay===false){if(!callback)return;return callback(new Error('W3M Image Display not available.'));}
if(!ratio){if(!callback)return;return callback(new Error('No ratio.'));}
var _file=self.file;var _lastSize=self._lastSize;return self.clearImage(function(err){if(err)return callback(err);self.file=_file;self._lastSize=_lastSize;var opt={stdio:'pipe',env:process.env,cwd:process.env.HOME};var ps=self.spawn(OverlayImage.w3mdisplay,[],opt,function(err,success){if(!callback)return;return err?callback(err):callback(null,success);});var width=self.width*ratio.tw|0,height=self.height*ratio.th|0,aleft=self.aleft*ratio.tw|0,atop=self.atop*ratio.th|0;var input='0;1;'
+aleft+';'
+atop+';'
+width+';'
+height+';;;;;'
+img
+'\n4;\n3;\n';self._props={aleft:aleft,atop:atop,width:width,height:height};ps.stdin.write(input);ps.stdin.end();});};OverlayImage.prototype.clearImage=function(callback){if(cp.execSync){callback=callback||function(err,result){return result;};try{return callback(null,this.clearImageSync());}catch(e){return callback(e);}}
if(OverlayImage.hasW3MDisplay===false){if(!callback)return;return callback(new Error('W3M Image Display not available.'));}
if(!this._props){if(!callback)return;return callback(null);}
var opt={stdio:'pipe',env:process.env,cwd:process.env.HOME};var ps=this.spawn(OverlayImage.w3mdisplay,[],opt,function(err,success){if(!callback)return;return err?callback(err):callback(null,success);});var width=this._props.width+2,height=this._props.height+2,aleft=this._props.aleft,atop=this._props.atop;if(this._drag){aleft-=10;atop-=10;width+=10;height+=10;}
var input='6;'
+aleft+';'
+atop+';'
+width+';'
+height
+'\n4;\n3;\n';delete this.file;delete this._props;delete this._lastSize;ps.stdin.write(input);ps.stdin.end();};OverlayImage.prototype.imageSize=function(callback){var img=this.file;if(cp.execSync){callback=callback||function(err,result){return result;};try{return callback(null,this.imageSizeSync());}catch(e){return callback(e);}}
if(OverlayImage.hasW3MDisplay===false){if(!callback)return;return callback(new Error('W3M Image Display not available.'));}
if(!img){if(!callback)return;return callback(new Error('No image.'));}
var opt={stdio:'pipe',env:process.env,cwd:process.env.HOME};var ps=this.spawn(OverlayImage.w3mdisplay,[],opt);var buf='';ps.stdout.setEncoding('utf8');ps.stdout.on('data',function(data){buf+=data;});ps.on('error',function(err){if(!callback)return;return callback(err);});ps.on('exit',function(){if(!callback)return;var size=buf.trim().split(/\s+/);return callback(null,{raw:buf.trim(),width:+size[0],height:+size[1]});});var input='5;'+img+'\n';ps.stdin.write(input);ps.stdin.end();};OverlayImage.prototype.termSize=function(callback){var self=this;if(cp.execSync){callback=callback||function(err,result){return result;};try{return callback(null,this.termSizeSync());}catch(e){return callback(e);}}
if(OverlayImage.hasW3MDisplay===false){if(!callback)return;return callback(new Error('W3M Image Display not available.'));}
var opt={stdio:'pipe',env:process.env,cwd:process.env.HOME};var ps=this.spawn(OverlayImage.w3mdisplay,['-test'],opt);var buf='';ps.stdout.setEncoding('utf8');ps.stdout.on('data',function(data){buf+=data;});ps.on('error',function(err){if(!callback)return;return callback(err);});ps.on('exit',function(){if(!callback)return;if(!buf.trim()){return self.termSize(callback);}
var size=buf.trim().split(/\s+/);return callback(null,{raw:buf.trim(),width:+size[0],height:+size[1]});});ps.stdin.end();};OverlayImage.prototype.getPixelRatio=function(callback){var self=this;if(cp.execSync){callback=callback||function(err,result){return result;};try{return callback(null,this.getPixelRatioSync());}catch(e){return callback(e);}}
if(this._ratio&&!this._needsRatio){return callback(null,this._ratio);}
return this.termSize(function(err,dimensions){if(err)return callback(err);self._ratio={tw:dimensions.width/self.screen.width,th:dimensions.height/self.screen.height};self._needsRatio=false;return callback(null,self._ratio);});};OverlayImage.prototype.renderImageSync=function(img,ratio){if(OverlayImage.hasW3MDisplay===false){throw new Error('W3M Image Display not available.');}
if(!ratio){throw new Error('No ratio.');}
var _file=this.file;var _lastSize=this._lastSize;this.clearImageSync();this.file=_file;this._lastSize=_lastSize;var width=this.width*ratio.tw|0,height=this.height*ratio.th|0,aleft=this.aleft*ratio.tw|0,atop=this.atop*ratio.th|0;var input='0;1;'
+aleft+';'
+atop+';'
+width+';'
+height+';;;;;'
+img
+'\n4;\n3;\n';this._props={aleft:aleft,atop:atop,width:width,height:height};try{cp.execFileSync(OverlayImage.w3mdisplay,[],{env:process.env,encoding:'utf8',input:input,timeout:1000});}catch(e){;}
return true;};OverlayImage.prototype.clearImageSync=function(){if(OverlayImage.hasW3MDisplay===false){throw new Error('W3M Image Display not available.');}
if(!this._props){return false;}
var width=this._props.width+2,height=this._props.height+2,aleft=this._props.aleft,atop=this._props.atop;if(this._drag){aleft-=10;atop-=10;width+=10;height+=10;}
var input='6;'
+aleft+';'
+atop+';'
+width+';'
+height
+'\n4;\n3;\n';delete this.file;delete this._props;delete this._lastSize;try{cp.execFileSync(OverlayImage.w3mdisplay,[],{env:process.env,encoding:'utf8',input:input,timeout:1000});}catch(e){;}
return true;};OverlayImage.prototype.imageSizeSync=function(){var img=this.file;if(OverlayImage.hasW3MDisplay===false){throw new Error('W3M Image Display not available.');}
if(!img){throw new Error('No image.');}
var buf='';var input='5;'+img+'\n';try{buf=cp.execFileSync(OverlayImage.w3mdisplay,[],{env:process.env,encoding:'utf8',input:input,timeout:1000});}catch(e){;}
var size=buf.trim().split(/\s+/);return{raw:buf.trim(),width:+size[0],height:+size[1]};};OverlayImage.prototype.termSizeSync=function(_,recurse){if(OverlayImage.hasW3MDisplay===false){throw new Error('W3M Image Display not available.');}
var buf='';try{buf=cp.execFileSync(OverlayImage.w3mdisplay,['-test'],{env:process.env,encoding:'utf8',timeout:1000});}catch(e){;}
if(!buf.trim()){recurse=recurse||0;if(++recurse===5){throw new Error('Term size not determined.');}
return this.termSizeSync(_,recurse);}
var size=buf.trim().split(/\s+/);return{raw:buf.trim(),width:+size[0],height:+size[1]};};OverlayImage.prototype.getPixelRatioSync=function(){if(this._ratio&&!this._needsRatio){return this._ratio;}
this._needsRatio=false;var dimensions=this.termSizeSync();this._ratio={tw:dimensions.width/this.screen.width,th:dimensions.height/this.screen.height};return this._ratio;};OverlayImage.prototype.displayImage=function(callback){return this.screen.displayImage(this.file,callback);};module.exports=OverlayImage;};BundleModuleCode['term/widgets/video']=function(module,exports){var Comp=Require('com/compat');var cp=Require('child_process');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var Terminal=Require('term/widgets/terminal');function Video(options){var self=this,shell,args;if(!instanceOf(this,Node)){return new Video(options);}
options=options||{};Box.call(this,options);if(this.exists('mplayer')){shell='mplayer';args=['-vo','caca','-quiet',options.file];}else if(this.exists('mpv')){shell='mpv';args=['--vo','caca','--really-quiet',options.file];}else{this.parseTags=true;this.setContent('{red-fg}{bold}Error:{/bold}'
+' mplayer or mpv not installed.{/red-fg}');return this;}
var opts={parent:this,left:0,top:0,width:this.width-this.iwidth,height:this.height-this.iheight,shell:shell,args:args.slice()};this.now=Date.now()/1000|0;this.start=opts.start||0;if(this.start){if(shell==='mplayer'){opts.args.unshift('-ss',this.start+'');}else if(shell==='mpv'){opts.args.unshift('--start',this.start+'');}}
var DISPLAY=process.env.DISPLAY;delete process.env.DISPLAY;this.tty=new Terminal(opts);process.env.DISPLAY=DISPLAY;this.on('click',function(){self.tty.pty.write('p');});this.on('resize',function(){self.tty.destroy();var opts={parent:self,left:0,top:0,width:self.width-self.iwidth,height:self.height-self.iheight,shell:shell,args:args.slice()};var watched=(Date.now()/1000|0)-self.now;self.now=Date.now()/1000|0;self.start+=watched;if(shell==='mplayer'){opts.args.unshift('-ss',self.start+'');}else if(shell==='mpv'){opts.args.unshift('--start',self.start+'');}
var DISPLAY=process.env.DISPLAY;delete process.env.DISPLAY;self.tty=new Terminal(opts);process.env.DISPLAY=DISPLAY;self.screen.render();});}
inheritPrototype(Video,Box);Video.prototype.type='video';Video.prototype.exists=function(program){try{return!!+cp.execSync('type '
+program+' > /dev/null 2> /dev/null'
+' && echo 1',{encoding:'utf8'}).trim();}catch(e){return false;}};module.exports=Video;};BundleModuleCode['term/widgets/layout']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Element=Require('term/widgets/element');function Layout(options){if(!instanceOf(this,Node)){return new Layout(options);}
options=options||{};if((options.width==null&&(options.left==null&&options.right==null))||(options.height==null&&(options.top==null&&options.bottom==null))){throw new Error('`Layout` must have a width and height!');}
options.layout=options.layout||'inline';Element.call(this,options);if(options.renderer){this.renderer=options.renderer;}}
inheritPrototype(Layout,Element);Layout.prototype.type='layout';Layout.prototype.isRendered=function(el){if(!el.lpos)return false;return(el.lpos.xl-el.lpos.xi)>0&&(el.lpos.yl-el.lpos.yi)>0;};Layout.prototype.getLast=function(i){while(this.children[--i]){var el=this.children[i];if(this.isRendered(el))return el;}};Layout.prototype.getLastCoords=function(i){var last=this.getLast(i);if(last)return last.lpos;};Layout.prototype._renderCoords=function(){var coords=this._getCoords(true);var children=this.children;this.children=[];this._render();this.children=children;return coords;};Layout.prototype.renderer=function(coords){var self=this;var width=coords.xl-coords.xi,height=coords.yl-coords.yi,xi=coords.xi,yi=coords.yi;var rowOffset=0;var rowIndex=0;var lastRowIndex=0;if(this.options.layout==='grid'){var highWidth=this.children.reduce(function(out,el){out=Math.max(out,el.width);return out;},0);}
return function iterator(el,i){el.shrink=true;var last=self.getLast(i);if(!last){el.position.left=0;el.position.top=0;}else{el.position.left=last.lpos.xl-xi;if(self.options.layout==='grid'){el.position.left+=highWidth-(last.lpos.xl-last.lpos.xi);}
if(el.position.left+el.width<=width){el.position.top=rowOffset;}else{rowOffset+=self.children.slice(rowIndex,i).reduce(function(out,el){if(!self.isRendered(el))return out;out=Math.max(out,el.lpos.yl-el.lpos.yi);return out;},0);lastRowIndex=rowIndex;rowIndex=i;el.position.left=0;el.position.top=rowOffset;}}
if(self.options.layout==='inline'){var above=null;var abovea=Infinity;for(var j=lastRowIndex;j<rowIndex;j++){var l=self.children[j];if(!self.isRendered(l))continue;var abs=Math.abs(el.position.left-(l.lpos.xi-xi));if(abs<abovea){above=l;abovea=abs;}}
if(above){el.position.top=above.lpos.yl-yi;}}
if(el.position.top+el.height>height){}};};Layout.prototype.render=function(){this._emit('prerender');var coords=this._renderCoords();if(!coords){delete this.lpos;return;}
if(coords.xl-coords.xi<=0){coords.xl=Math.max(coords.xl,coords.xi);return;}
if(coords.yl-coords.yi<=0){coords.yl=Math.max(coords.yl,coords.yi);return;}
this.lpos=coords;if(this.border)coords.xi++,coords.xl--,coords.yi++,coords.yl--;if(this.tpadding){coords.xi+=this.padding.left,coords.xl-=this.padding.right;coords.yi+=this.padding.top,coords.yl-=this.padding.bottom;}
var iterator=this.renderer(coords);if(this.border)coords.xi--,coords.xl++,coords.yi--,coords.yl++;if(this.tpadding){coords.xi-=this.padding.left,coords.xl+=this.padding.right;coords.yi-=this.padding.top,coords.yl+=this.padding.bottom;}
this.children.forEach(function(el,i){if(el.screen._ci!==-1){el.index=el.screen._ci++;}
var rendered=iterator(el,i);if(rendered===false){delete el.lpos;return;}
el.render();});this._emit('render',[coords]);return coords;};module.exports=Layout;};BundleModuleCode['term/widgets/tree']=function(module,exports){var Comp=Require('com/compat');var Node=Require('term/widgets/node');var Box=Require('term/widgets/box');var List=Require('term/widgets/list');var Arrows=Require('term/widgets/arrows');function Tree(options){var self=this,height=0;function strequal(str1,str2){var i;var eq=true;if(str1.length!=str2.length)return false;for(i=0;i<str1.length;i++){if(str1.charAt(i)!=str2.charAt(i))eq=false;}
return eq;};if(!instanceOf(this,Node)){return new Tree(options);}
options=options||{};if(!options.style)options.style={border:{fg:'black'},focus:{border:{fg:'red'}}};if(!options.border)options.border={type:'line'};options.style.border._fg=options.style.border.fg;options.bold=true;var self=this;this.options=options;this.data={};this.nodeLines=[];this.lineNbr=0;this.init=true;Box.call(this,options);var boxfocus=this.focus;if(options.height){if(typeof options.height=='number')height=options.height;else if(typeof options.height=='string'){var perc=0;perc=parseInt(options.height);height=this.screen.height*perc/100;}}
options.extended=options.extended||false;options.keys=options.keys||['space','enter'];options.template=options.template||{};options.template.extend=options.template.extend||' [+]';options.template.retract=options.template.retract||' [-]';options.template.lines=options.template.lines||true;this.listOptions={height:0,top:1,width:0,left:1,selectedFg:'white',selectedBg:'blue',fg:"green",keys:true,mouse:true,selectoffset:height>8?4:2,};if(!options.scrollbar)this.listOptions.scrollbar={ch:' ',track:{bg:'yellow'},style:{fg:'cyan',inverse:true}};else if(options.scrollbar!=null)
this.listOptions.scrollbar=options.scrollbar;this.list=new List(this.listOptions);this.list.key(options.keys,function(){var ind=this.getItemIndex(this.selected);var line=self.nodeLines[ind];self.emit('preselect',line);self.nodeLines[ind].extended=!self.nodeLines[ind].extended;self.setData(self.data);self.screen.render();self.emit('select',line);});this.list.on('element click',function(w,ev){var ind=this.getItemIndex(this.selected);var line=self.nodeLines[ind];var pos=ev.x-w.aleft;var item=this.ritems[ind];if(item){self.emit('preselect',line);var len1=self.options.template.extend.length;var len2=self.options.template.retract.length;var roi1=item.indexOf(self.options.template.extend);var roi2=item.indexOf(self.options.template.retract);if((pos>roi1&&pos<roi1+len1)||(pos>roi2&&pos<roi2+len1)){self.nodeLines[ind].extended=!self.nodeLines[ind].extended;self.setData(self.data);self.screen.render();self.emit('select',line);}}});if(options.arrows)
Arrows(self,options,function(){self.list.select(self.list.selected-2);self.screen.render()},function(){self.list.select(self.list.selected+2);self.screen.render()});this.on('mousedown',function(data){self.focus();Box.prototype.render.call(self);self.screen.render();});this.list.on('selected',function(){var ind=this.getItemIndex(this.selected);var line=self.nodeLines[ind];self.emit('selected',line);});this.append(this.list);}
Tree.prototype.walk=function(node,treeDepth){var lines=[];if(!node.parent)
node.parent=null;if(treeDepth==''&&node.name){this.lineNbr=0;this.nodeLines[this.lineNbr++]=node;lines.push(node.name);treeDepth=' ';}
node.depth=treeDepth.length-1;if(node.children&&node.extended){var i=0;if(typeof node.children=='function')
node.childrenContent=node.children(node);if(!node.childrenContent)
node.childrenContent=node.children;for(var child in node.childrenContent){if(!node.childrenContent[child].name)
node.childrenContent[child].name=child;var childIndex=child;child=node.childrenContent[child];child.parent=node;child.position=i++;if(typeof child.extended=='undefined')
child.extended=this.options.extended;if(typeof child.children=='function')
child.childrenContent=child.children(child);else
child.childrenContent=child.children;var isLastChild=child.position==Object.keys(child.parent.childrenContent).length-1;var tree;var suffix='';if(isLastChild){tree='└';}else{tree='├';}
if(!child.childrenContent||Object.keys(child.childrenContent).length==0){tree+='─';}else if(child.extended){tree+='┬';suffix=this.options.template.retract;}else{tree+='─';suffix=this.options.template.extend;}
if(!this.options.template.lines){tree='|-';}
lines.push(treeDepth+tree+child.name+suffix);this.nodeLines[this.lineNbr++]=child;var parentTree;if(isLastChild||!this.options.template.lines){parentTree=treeDepth+" ";}else{parentTree=treeDepth+"│";}
lines=lines.concat(this.walk(child,parentTree));}}
return lines;}
Tree.prototype.focus=function(){this.list.focus();}
Tree.prototype.render=function(){if((this.screen.focused==this.list||this.screen.focused==this)){if(this.style.focus.border.fg)this.style.border.fg=this.style.focus.border.fg;}else if((this.screen.focused!=this.list&&this.screen.focused!=this)){if(this.style.border._fg)this.style.border.fg=this.style.border._fg;}
this.list.width=this.width-3;this.list.height=this.height-3;Box.prototype.render.call(this);}
Tree.prototype.setData=function(data){var formatted=[];formatted=this.walk(data,'');this.data=data;if(this.init){this.screen.render();this.init=false;};this.list.setItems(formatted);this.screen.render();}
inheritPrototype(Tree,Box);Tree.prototype.type='tree';module.exports=Tree};FilesEmbedded['term/def/xterm']=function(format){return Base64.decodeBuf('GgEcACYADwCdAWwFeHRlcm18WDExIHRlcm1pbmFsIGVtdWxhdG9yAAABAAABAAAAAQAAAAABAQAAAAAAAAABAAABAAABAAAAAAAAAAABUAAIABgA//////////////////////////8IAEAAAAAEAAYACAAZAB4AJgAqAC4A//85AEoATABQAFcA//9ZAGYA//9qAG4AeAB8AP////+AAIQAiQCOAP////+XAJwA//+hAKYAqwCwALkAvQDEAP//zQDSANgA3gD////////wAP///////wIB//8GAf///////wgB//8NAf//////////EQEVARsBHwEjAScBLQEzATkBPwFFAUkB//9OAf//UgFXAVwBYAFnAf//bgFyAXoB/////////////////////////////4IBiwH/////lAGdAaYBrwG4AcEBygHTAdwB5QH////////uAfIB9wH///wB/wH/////EQIUAh8CIgIkAicCeQL//3wC////////////////fgL//////////4IC//+3Av////+7AsEC/////////////////////////////8cCywL//////////////////////////////////////////////////////////////////88C/////9YC///////////dAuQC6wL/////8gL///kC////////AAP/////////////BwMNAxMDGgMhAygDLwM3Az8DRwNPA1cDXwNnA28DdgN9A4QDiwOTA5sDowOrA7MDuwPDA8sD0gPZA+AD5wPvA/cD/wMHBA8EFwQfBCcELgQ1BDwEQwRLBFMEWwRjBGsEcwR7BIMEigSRBJgE/////////////////////////////////////////////////////////////50EqAStBLUEuQT//////////8IECAX///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9OBf///////1IFXAX/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ZgVpBRtbWgAHAA0AG1slaSVwMSVkOyVwMiVkcgAbWzNnABtbSBtbMkoAG1tLABtbSgAbWyVpJXAxJWRHABtbJWklcDElZDslcDIlZEgACgAbW0gAG1s/MjVsAAgAG1s/MTJsG1s/MjVoABtbQwAbW0EAG1s/MTI7MjVoABtbUAAbW00AGygwABtbNW0AG1sxbQAbWz8xMDQ5aAAbWzRoABtbOG0AG1s3bQAbWzdtABtbNG0AG1slcDElZFgAGyhCABsoQhtbbQAbWz8xMDQ5bAAbWzRsABtbMjdtABtbMjRtABtbPzVoJDwxMDAvPhtbPzVsABtbIXAbWz8zOzRsG1s0bBs+ABtbTAAIABtbM34AG09CABtPUAAbWzIxfgAbT1EAG09SABtPUwAbWzE1fgAbWzE3fgAbWzE4fgAbWzE5fgAbWzIwfgAbT0gAG1syfgAbT0QAG1s2fgAbWzV+ABtPQwAbWzE7MkIAG1sxOzJBABtPQQAbWz8xbBs+ABtbPzFoGz0AG1s/MTAzNGwAG1s/MTAzNGgAG1slcDElZFAAG1slcDElZE0AG1slcDElZEIAG1slcDElZEAAG1slcDElZFMAG1slcDElZEwAG1slcDElZEQAG1slcDElZEMAG1slcDElZFQAG1slcDElZEEAG1tpABtbNGkAG1s1aQAbYwAbWyFwG1s/Mzs0bBtbNGwbPgAbOAAbWyVpJXAxJWRkABs3AAoAG00AJT8lcDkldBsoMCVlGyhCJTsbWzAlPyVwNiV0OzElOyU/JXAyJXQ7NCU7JT8lcDElcDMlfCV0OzclOyU/JXA0JXQ7NSU7JT8lcDcldDs4JTttABtIAAkAG09FAGBgYWFmZmdnaWlqamtrbGxtbW5ub29wcHFxcnJzc3R0dXV2dnd3eHh5eXp6e3t8fH19fn4AG1taABtbPzdoABtbPzdsABtPRgAbT00AG1szOzJ+ABtbMTsyRgAbWzE7MkgAG1syOzJ+ABtbMTsyRAAbWzY7Mn4AG1s1OzJ+ABtbMTsyQwAbWzIzfgAbWzI0fgAbWzE7MlAAG1sxOzJRABtbMTsyUgAbWzE7MlMAG1sxNTsyfgAbWzE3OzJ+ABtbMTg7Mn4AG1sxOTsyfgAbWzIwOzJ+ABtbMjE7Mn4AG1syMzsyfgAbWzI0OzJ+ABtbMTs1UAAbWzE7NVEAG1sxOzVSABtbMTs1UwAbWzE1OzV+ABtbMTc7NX4AG1sxODs1fgAbWzE5OzV+ABtbMjA7NX4AG1syMTs1fgAbWzIzOzV+ABtbMjQ7NX4AG1sxOzZQABtbMTs2UQAbWzE7NlIAG1sxOzZTABtbMTU7Nn4AG1sxNzs2fgAbWzE4OzZ+ABtbMTk7Nn4AG1syMDs2fgAbWzIxOzZ+ABtbMjM7Nn4AG1syNDs2fgAbWzE7M1AAG1sxOzNRABtbMTszUgAbWzE7M1MAG1sxNTszfgAbWzE3OzN+ABtbMTg7M34AG1sxOTszfgAbWzIwOzN+ABtbMjE7M34AG1syMzszfgAbWzI0OzN+ABtbMTs0UAAbWzE7NFEAG1sxOzRSABtbMUsAG1slaSVkOyVkUgAbWzZuABtbPzE7MmMAG1tjABtbMzk7NDltABtbMyU/JXAxJXsxfSU9JXQ0JWUlcDElezN9JT0ldDYlZSVwMSV7NH0lPSV0MSVlJXAxJXs2fSU9JXQzJWUlcDElZCU7bQAbWzQlPyVwMSV7MX0lPSV0NCVlJXAxJXszfSU9JXQ2JWUlcDElezR9JT0ldDElZSVwMSV7Nn0lPSV0MyVlJXAxJWQlO20AG1tNABtbMyVwMSVkbQAbWzQlcDElZG0AG2wAG20AAgAAAD4AfgDvAgEBAAAHABMAGQArADEAOwBCAEkAUABXAF4AZQBsAHMAegCBAIgAjwCWAJ0ApACrALIAuQDAAMcAzgDVANwA4wDqAPEA+AD/AAYBDQEUARsBIgEpATABNwE+AUUBTAFTAVoBYQFoAW8BdgF9AYQBiwGSAZkBoAH//////////wAAAwAGAAkADAAPABIAFQAYAB0AIgAnACwAMQA1ADoAPwBEAEkATgBUAFoAYABmAGwAcgB4AH4AhACKAI8AlACZAJ4AowCpAK8AtQC7AMEAxwDNANMA2QDfAOUA6wDxAPcA/QADAQkBDwEVARsBHwEkASkBLgEzATgBPAFAAUQBG10xMTIHABtdMTI7JXAxJXMHABtbMztKABtdNTI7JXAxJXM7JXAyJXMHABtbMiBxABtbJXAxJWQgcQAbWzM7M34AG1szOzR+ABtbMzs1fgAbWzM7Nn4AG1szOzd+ABtbMTsyQgAbWzE7M0IAG1sxOzRCABtbMTs1QgAbWzE7NkIAG1sxOzdCABtbMTszRgAbWzE7NEYAG1sxOzVGABtbMTs2RgAbWzE7N0YAG1sxOzNIABtbMTs0SAAbWzE7NUgAG1sxOzZIABtbMTs3SAAbWzI7M34AG1syOzR+ABtbMjs1fgAbWzI7Nn4AG1syOzd+ABtbMTszRAAbWzE7NEQAG1sxOzVEABtbMTs2RAAbWzE7N0QAG1s2OzN+ABtbNjs0fgAbWzY7NX4AG1s2OzZ+ABtbNjs3fgAbWzU7M34AG1s1OzR+ABtbNTs1fgAbWzU7Nn4AG1s1Ozd+ABtbMTszQwAbWzE7NEMAG1sxOzVDABtbMTs2Qw