From edb523e83ac50c417be25242d61d42ab54178972 Mon Sep 17 00:00:00 2001
From: sbosse
Date: Tue, 27 Aug 2024 00:12:14 +0200
Subject: [PATCH] Tue 27 Aug 00:11:59 CEST 2024
---
build/jamsh/jamsh | 9671 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 9671 insertions(+)
create mode 100644 build/jamsh/jamsh
diff --git a/build/jamsh/jamsh b/build/jamsh/jamsh
new file mode 100644
index 0000000..53a6c68
--- /dev/null
+++ b/build/jamsh/jamsh
@@ -0,0 +1,9671 @@
+#!/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.\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.\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.\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()>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>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>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>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>>0;if(typeof predicate!=='function'){throw new TypeError('predicate must be a function');}
+var thisArg=arguments[1];var k=0;while(k=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=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=-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=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=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=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;i1){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=array.length)return[];a=array.slice(0,begin);for(i=end;i1;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-1;},copy:function(src){var i;var dst='';for(i=0;i>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=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=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=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&&pos0&&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(ab)?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<=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(/"/g,'"').replace(/>/g,'>').replace(/</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*'
++'|\\n*'
++'|\\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=//;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*$)'
++'|\\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 ?/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(;i1&&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?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:noop,tag:'^comment'
++'|^[a-zA-Z][\\w:-]*\\s*>'
++'|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>'
++'|^<\\?[\\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]+?(?=[\\?@\[\]\\^_`{|}~])/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&&/^/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(;i0.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''
++(escaped?code:escape(code,true))
++'\n
';}
+return''
++(escaped?code:escape(code,true))
++'\n
\n';};Renderer.prototype.blockquote=function(quote){return'\n'+quote+'
\n';};Renderer.prototype.html=function(html){return html;};Renderer.prototype.heading=function(text,level,raw){if(this.options.headerIds){return'\n';}
+return''+text+'\n';};Renderer.prototype.hr=function(){return this.options.xhtml?'
\n':'
\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''+text+'\n';};Renderer.prototype.dl=function(body){return'\n'+body+'
\n';};Renderer.prototype.dt=function(body){return''+body+'\n';};Renderer.prototype.dd=function(body){return''+body+'\n';};Renderer.prototype.paragraph=function(text){return''+text+'
\n';};Renderer.prototype.table=function(header,body){return'\n'
++'\n'
++header
++'\n'
++'\n'
++body
++'\n'
++'
\n';};Renderer.prototype.tablerow=function(content){return'\n'+content+'
\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''+text+'';};Renderer.prototype.em=function(text){return''+text+'';};Renderer.prototype.codespan=function(text){return''+text+'
';};Renderer.prototype.br=function(){return this.options.xhtml?'
':'
';};Renderer.prototype.del=function(text){return''+text+'';};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=''+text+'';return out;};Renderer.prototype.image=function(href,title,text){if(this.options.baseUrl&&!originIndependentUrl.test(href)){href=resolveUrl(this.options.baseUrl,href);}
+var out='':'>';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/g,'>').replace(/"/g,'"').replace(/'/g,''');}
+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(;iAn error occurred:
'
++escape(e.message+'',true)
++'
';}
+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=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:posmax_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;j0){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=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.cursorb.length?a:b;}).length+2;var maxColumns=Math.floor(self.columns/width)||1;var group=[],c;for(var i=0,compLen=completions.length;icompleteOn.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=group.length){break;}
+var item=group[idx];self._writeToOutput(item);if(col0){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.cursor0&&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.cursor0){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=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.cursorthis.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.cursor0){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;i0){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=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\n'+'And the length must be: $',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:'$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'&¶m!=='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?'$>':(process.env.USER||'')+
+(process.env.HOSTNAME?'@'+process.env.HOSTNAME.replace(/\..*$/,''):'')+':$$ ';})()}));};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*$/,'')+' [$]: ';}
+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=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=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-1?geoip.ipblocks[pn]:null;if(step>0){if(!next||next.a1)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;iconn.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>>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>1;}}else{value=1;for(i=0;i>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>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>1;}}else{value=1;for(i=0;i>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>1;}}
+context_enlargeIn--;if(context_enlargeIn==0){context_enlargeIn=Math.pow(2,context_numBits);context_numBits++;}}
+value=2;for(i=0;i>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.lengthsize){buf.data=Buffer.slice(buf.data,size);}}
+function buf_put_string(buf,str){buf_extend(buf,str.length+1);for(var i=0;i>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>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=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;i0)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>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;j5)
+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;i0)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;i0)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&¤t.world.id),stats:(current.world&¤t.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;i5)
+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;i0)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.lengthmin&&value>>0;for(this.mti=1;this.mti>>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>>1)^mag01[y&0x1];}
+for(;kk>>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(n1)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(n1)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.tries0&&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.triesobj.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.tries0&&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.triesobj.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;i0&&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.tries0)return b.toString('base64');}
+switch(ftyp){case Float32Array:b=Buffer(ta.length*4);for(i=0;i0&&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.tries0){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;i0){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] [--