gun.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432
  1. ;(function(){
  2. /* UNBUILD */
  3. function USE(arg, req){
  4. return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){
  5. arg(mod = {exports: {}});
  6. USE[R(path)] = mod.exports;
  7. }
  8. function R(p){
  9. return p.split('/').slice(-1).toString().replace('.js','');
  10. }
  11. }
  12. if(typeof module !== "undefined"){ var MODULE = module }
  13. /* UNBUILD */
  14. ;USE(function(module){
  15. // Generic javascript utilities.
  16. var Type = {};
  17. //Type.fns = Type.fn = {is: function(fn){ return (!!fn && fn instanceof Function) }}
  18. Type.fn = {is: function(fn){ return (!!fn && 'function' == typeof fn) }}
  19. Type.bi = {is: function(b){ return (b instanceof Boolean || typeof b == 'boolean') }}
  20. Type.num = {is: function(n){ return !list_is(n) && ((n - parseFloat(n) + 1) >= 0 || Infinity === n || -Infinity === n) }}
  21. Type.text = {is: function(t){ return (typeof t == 'string') }}
  22. Type.text.ify = function(t){
  23. if(Type.text.is(t)){ return t }
  24. if(typeof JSON !== "undefined"){ return JSON.stringify(t) }
  25. return (t && t.toString)? t.toString() : t;
  26. }
  27. Type.text.random = function(l, c){
  28. var s = '';
  29. l = l || 24; // you are not going to make a 0 length random number, so no need to check type
  30. c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
  31. while(l > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); l-- }
  32. return s;
  33. }
  34. Type.text.match = function(t, o){ var tmp, u;
  35. if('string' !== typeof t){ return false }
  36. if('string' == typeof o){ o = {'=': o} }
  37. o = o || {};
  38. tmp = (o['='] || o['*'] || o['>'] || o['<']);
  39. if(t === tmp){ return true }
  40. if(u !== o['=']){ return false }
  41. tmp = (o['*'] || o['>'] || o['<']);
  42. if(t.slice(0, (tmp||'').length) === tmp){ return true }
  43. if(u !== o['*']){ return false }
  44. if(u !== o['>'] && u !== o['<']){
  45. return (t >= o['>'] && t <= o['<'])? true : false;
  46. }
  47. if(u !== o['>'] && t >= o['>']){ return true }
  48. if(u !== o['<'] && t <= o['<']){ return true }
  49. return false;
  50. }
  51. Type.text.hash = function(s, c){ // via SO
  52. if(typeof s !== 'string'){ return }
  53. c = c || 0;
  54. if(!s.length){ return c }
  55. for(var i=0,l=s.length,n; i<l; ++i){
  56. n = s.charCodeAt(i);
  57. c = ((c<<5)-c)+n;
  58. c |= 0;
  59. }
  60. return c;
  61. }
  62. Type.list = {is: function(l){ return (l instanceof Array) }}
  63. Type.list.slit = Array.prototype.slice;
  64. Type.list.sort = function(k){ // creates a new sort function based off some key
  65. return function(A,B){
  66. if(!A || !B){ return 0 } A = A[k]; B = B[k];
  67. if(A < B){ return -1 }else if(A > B){ return 1 }
  68. else { return 0 }
  69. }
  70. }
  71. Type.list.map = function(l, c, _){ return obj_map(l, c, _) }
  72. Type.list.index = 1; // change this to 0 if you want non-logical, non-mathematical, non-matrix, non-convenient array notation
  73. Type.obj = {is: function(o){ return o? (o instanceof Object && o.constructor === Object) || Object.prototype.toString.call(o).match(/^\[object (\w+)\]$/)[1] === 'Object' : false }}
  74. Type.obj.put = function(o, k, v){ return (o||{})[k] = v, o }
  75. Type.obj.has = function(o, k){ return o && Object.prototype.hasOwnProperty.call(o, k) }
  76. Type.obj.del = function(o, k){
  77. if(!o){ return }
  78. o[k] = null;
  79. delete o[k];
  80. return o;
  81. }
  82. Type.obj.as = function(o, k, v, u){ return o[k] = o[k] || (u === v? {} : v) }
  83. Type.obj.ify = function(o){
  84. if(obj_is(o)){ return o }
  85. try{o = JSON.parse(o);
  86. }catch(e){o={}};
  87. return o;
  88. }
  89. ;(function(){ var u;
  90. function map(v,k){
  91. if(obj_has(this,k) && u !== this[k]){ return }
  92. this[k] = v;
  93. }
  94. Type.obj.to = function(from, to){
  95. to = to || {};
  96. obj_map(from, map, to);
  97. return to;
  98. }
  99. }());
  100. Type.obj.copy = function(o){ // because http://web.archive.org/web/20140328224025/http://jsperf.com/cloning-an-object/2
  101. return !o? o : JSON.parse(JSON.stringify(o)); // is shockingly faster than anything else, and our data has to be a subset of JSON anyways!
  102. }
  103. ;(function(){
  104. function empty(v,i){ var n = this.n, u;
  105. if(n && (i === n || (obj_is(n) && obj_has(n, i)))){ return }
  106. if(u !== i){ return true }
  107. }
  108. Type.obj.empty = function(o, n){
  109. if(!o){ return true }
  110. return obj_map(o,empty,{n:n})? false : true;
  111. }
  112. }());
  113. ;(function(){
  114. function t(k,v){
  115. if(2 === arguments.length){
  116. t.r = t.r || {};
  117. t.r[k] = v;
  118. return;
  119. } t.r = t.r || [];
  120. t.r.push(k);
  121. };
  122. var keys = Object.keys, map, u;
  123. Object.keys = Object.keys || function(o){ return map(o, function(v,k,t){t(k)}) }
  124. Type.obj.map = map = function(l, c, _){
  125. var u, i = 0, x, r, ll, lle, f = 'function' == typeof c;
  126. t.r = u;
  127. if(keys && obj_is(l)){
  128. ll = keys(l); lle = true;
  129. }
  130. _ = _ || {};
  131. if(list_is(l) || ll){
  132. x = (ll || l).length;
  133. for(;i < x; i++){
  134. var ii = (i + Type.list.index);
  135. if(f){
  136. r = lle? c.call(_, l[ll[i]], ll[i], t) : c.call(_, l[i], ii, t);
  137. if(r !== u){ return r }
  138. } else {
  139. //if(Type.test.is(c,l[i])){ return ii } // should implement deep equality testing!
  140. if(c === l[lle? ll[i] : i]){ return ll? ll[i] : ii } // use this for now
  141. }
  142. }
  143. } else {
  144. for(i in l){
  145. if(f){
  146. if(obj_has(l,i)){
  147. r = _? c.call(_, l[i], i, t) : c(l[i], i, t);
  148. if(r !== u){ return r }
  149. }
  150. } else {
  151. //if(a.test.is(c,l[i])){ return i } // should implement deep equality testing!
  152. if(c === l[i]){ return i } // use this for now
  153. }
  154. }
  155. }
  156. return f? t.r : Type.list.index? 0 : -1;
  157. }
  158. }());
  159. Type.time = {};
  160. Type.time.is = function(t){ return t? t instanceof Date : (+new Date().getTime()) }
  161. var fn_is = Type.fn.is;
  162. var list_is = Type.list.is;
  163. var obj = Type.obj, obj_is = obj.is, obj_has = obj.has, obj_map = obj.map;
  164. module.exports = Type;
  165. })(USE, './type');
  166. ;USE(function(module){
  167. // On event emitter generic javascript utility.
  168. module.exports = function onto(tag, arg, as){
  169. if(!tag){ return {to: onto} }
  170. var u, tag = (this.tag || (this.tag = {}))[tag] ||
  171. (this.tag[tag] = {tag: tag, to: onto._ = {
  172. next: function(arg){ var tmp;
  173. if((tmp = this.to)){
  174. tmp.next(arg);
  175. }}
  176. }});
  177. if('function' == typeof arg){
  178. var be = {
  179. off: onto.off ||
  180. (onto.off = function(){
  181. if(this.next === onto._.next){ return !0 }
  182. if(this === this.the.last){
  183. this.the.last = this.back;
  184. }
  185. this.to.back = this.back;
  186. this.next = onto._.next;
  187. this.back.to = this.to;
  188. if(this.the.last === this.the){
  189. delete this.on.tag[this.the.tag];
  190. }
  191. }),
  192. to: onto._,
  193. next: arg,
  194. the: tag,
  195. on: this,
  196. as: as,
  197. };
  198. (be.back = tag.last || tag).to = be;
  199. return tag.last = be;
  200. }
  201. if((tag = tag.to) && u !== arg){ tag.next(arg) }
  202. return tag;
  203. };
  204. })(USE, './onto');
  205. ;USE(function(module){
  206. var to = (typeof setImmediate !== "undefined")? setImmediate : setTimeout, puff = function(cb){
  207. if(Q.length){ Q.push(cb); return } Q = [cb];
  208. to(function go(S){ S = S || +new Date;
  209. var i = 0, cb; while(i < 9 && (cb = Q[i++])){ cb() }
  210. console.STAT && console.STAT(S, +new Date - S, 'puff');
  211. if(cb && !(+new Date - S)){ return go(S) }
  212. if(!(Q = Q.slice(i)).length){ return }
  213. to(go, 0);
  214. }, 0);
  215. }, Q = [];
  216. module.exports = setTimeout.puff = puff;
  217. })(USE, './puff');
  218. ;USE(function(module){
  219. /* Based on the Hypothetical Amnesia Machine thought experiment */
  220. function HAM(machineState, incomingState, currentState, incomingValue, currentValue){
  221. if(machineState < incomingState){
  222. return {defer: true}; // the incoming value is outside the boundary of the machine's state, it must be reprocessed in another state.
  223. }
  224. if(incomingState < currentState){
  225. return {historical: true}; // the incoming value is within the boundary of the machine's state, but not within the range.
  226. }
  227. if(currentState < incomingState){
  228. return {converge: true, incoming: true}; // the incoming value is within both the boundary and the range of the machine's state.
  229. }
  230. if(incomingState === currentState){
  231. incomingValue = Lexical(incomingValue) || "";
  232. currentValue = Lexical(currentValue) || "";
  233. if(incomingValue === currentValue){ // Note: while these are practically the same, the deltas could be technically different
  234. return {state: true};
  235. }
  236. /*
  237. The following is a naive implementation, but will always work.
  238. Never change it unless you have specific needs that absolutely require it.
  239. If changed, your data will diverge unless you guarantee every peer's algorithm has also been changed to be the same.
  240. As a result, it is highly discouraged to modify despite the fact that it is naive,
  241. because convergence (data integrity) is generally more important.
  242. Any difference in this algorithm must be given a new and different name.
  243. */
  244. if(incomingValue < currentValue){ // Lexical only works on simple value types!
  245. return {converge: true, current: true};
  246. }
  247. if(currentValue < incomingValue){ // Lexical only works on simple value types!
  248. return {converge: true, incoming: true};
  249. }
  250. }
  251. return {err: "Invalid CRDT Data: "+ incomingValue +" to "+ currentValue +" at "+ incomingState +" to "+ currentState +"!"};
  252. }
  253. if(typeof JSON === 'undefined'){
  254. throw new Error(
  255. 'JSON is not included in this browser. Please load it first: ' +
  256. 'ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js'
  257. );
  258. }
  259. var Lexical = JSON.stringify, undefined;
  260. module.exports = HAM;
  261. })(USE, './HAM');
  262. ;USE(function(module){
  263. var Type = USE('./type');
  264. var Val = {};
  265. Val.is = function(v){ // Valid values are a subset of JSON: null, binary, number (!Infinity), text, or a soul relation. Arrays need special algorithms to handle concurrency, so they are not supported directly. Use an extension that supports them if needed but research their problems first.
  266. if(v === u){ return false }
  267. if(v === null){ return true } // "deletes", nulling out keys.
  268. if(v === Infinity){ return false } // we want this to be, but JSON does not support it, sad face.
  269. if(text_is(v) // by "text" we mean strings.
  270. || bi_is(v) // by "binary" we mean boolean.
  271. || num_is(v)){ // by "number" we mean integers or decimals.
  272. return true; // simple values are valid.
  273. }
  274. return Val.link.is(v) || false; // is the value a soul relation? Then it is valid and return it. If not, everything else remaining is an invalid data type. Custom extensions can be built on top of these primitives to support other types.
  275. }
  276. Val.link = Val.rel = {_: '#'};
  277. ;(function(){
  278. Val.link.is = function(v){ // this defines whether an object is a soul relation or not, they look like this: {'#': 'UUID'}
  279. if(v && v[rel_] && !v._ && obj_is(v)){ // must be an object.
  280. var o = {};
  281. obj_map(v, map, o);
  282. if(o.id){ // a valid id was found.
  283. return o.id; // yay! Return it.
  284. }
  285. }
  286. return false; // the value was not a valid soul relation.
  287. }
  288. function map(s, k){ var o = this; // map over the object...
  289. if(o.id){ return o.id = false } // if ID is already defined AND we're still looping through the object, it is considered invalid.
  290. if(k == rel_ && text_is(s)){ // the key should be '#' and have a text value.
  291. o.id = s; // we found the soul!
  292. } else {
  293. return o.id = false; // if there exists anything else on the object that isn't the soul, then it is considered invalid.
  294. }
  295. }
  296. }());
  297. Val.link.ify = function(t){ return obj_put({}, rel_, t) } // convert a soul into a relation and return it.
  298. Type.obj.has._ = '.';
  299. var rel_ = Val.link._, u;
  300. var bi_is = Type.bi.is;
  301. var num_is = Type.num.is;
  302. var text_is = Type.text.is;
  303. var obj = Type.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map;
  304. module.exports = Val;
  305. })(USE, './val');
  306. ;USE(function(module){
  307. var Type = USE('./type');
  308. var Val = USE('./val');
  309. var Node = {_: '_'};
  310. Node.soul = function(n, o){ return (n && n._ && n._[o || soul_]) } // convenience function to check to see if there is a soul on a node and return it.
  311. Node.soul.ify = function(n, o){ // put a soul on an object.
  312. o = (typeof o === 'string')? {soul: o} : o || {};
  313. n = n || {}; // make sure it exists.
  314. n._ = n._ || {}; // make sure meta exists.
  315. n._[soul_] = o.soul || n._[soul_] || text_random(); // put the soul on it.
  316. return n;
  317. }
  318. Node.soul._ = Val.link._;
  319. ;(function(){
  320. Node.is = function(n, cb, as){ var s; // checks to see if an object is a valid node.
  321. if(!obj_is(n)){ return false } // must be an object.
  322. if(s = Node.soul(n)){ // must have a soul on it.
  323. return !obj_map(n, map, {as:as,cb:cb,s:s,n:n});
  324. }
  325. return false; // nope! This was not a valid node.
  326. }
  327. function map(v, k){ // we invert this because the way we check for this is via a negation.
  328. if(k === Node._){ return } // skip over the metadata.
  329. if(!Val.is(v)){ return true } // it is true that this is an invalid node.
  330. if(this.cb){ this.cb.call(this.as, v, k, this.n, this.s) } // optionally callback each key/value.
  331. }
  332. }());
  333. ;(function(){
  334. Node.ify = function(obj, o, as){ // returns a node from a shallow object.
  335. if(!o){ o = {} }
  336. else if(typeof o === 'string'){ o = {soul: o} }
  337. else if('function' == typeof o){ o = {map: o} }
  338. if(o.map){ o.node = o.map.call(as, obj, u, o.node || {}) }
  339. if(o.node = Node.soul.ify(o.node || {}, o)){
  340. obj_map(obj, map, {o:o,as:as});
  341. }
  342. return o.node; // This will only be a valid node if the object wasn't already deep!
  343. }
  344. function map(v, k){ var o = this.o, tmp, u; // iterate over each key/value.
  345. if(o.map){
  346. tmp = o.map.call(this.as, v, ''+k, o.node);
  347. if(u === tmp){
  348. obj_del(o.node, k);
  349. } else
  350. if(o.node){ o.node[k] = tmp }
  351. return;
  352. }
  353. if(Val.is(v)){
  354. o.node[k] = v;
  355. }
  356. }
  357. }());
  358. var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_map = obj.map;
  359. var text = Type.text, text_random = text.random;
  360. var soul_ = Node.soul._;
  361. var u;
  362. module.exports = Node;
  363. })(USE, './node');
  364. ;USE(function(module){
  365. var Type = USE('./type');
  366. var Node = USE('./node');
  367. function State(){
  368. var t;
  369. /*if(perf){
  370. t = start + perf.now(); // Danger: Accuracy decays significantly over time, even if precise.
  371. } else {*/
  372. t = +new Date;
  373. //}
  374. if(last < t){
  375. return N = 0, last = t + State.drift;
  376. }
  377. return last = t + ((N += 1) / D) + State.drift;
  378. }
  379. var time = Type.time.is, last = -Infinity, N = 0, D = 1000; // WARNING! In the future, on machines that are D times faster than 2016AD machines, you will want to increase D by another several orders of magnitude so the processing speed never out paces the decimal resolution (increasing an integer effects the state accuracy).
  380. var perf = (typeof performance !== 'undefined')? (performance.timing && performance) : false, start = (perf && perf.timing && perf.timing.navigationStart) || (perf = false);
  381. var S_ = State._ = '>';
  382. State.drift = 0;
  383. State.is = function(n, k, o){ // convenience function to get the state on a key on a node and return it.
  384. var tmp = (k && n && n[N_] && n[N_][S_]) || o;
  385. if(!tmp){ return }
  386. return num_is(tmp = tmp[k])? tmp : -Infinity;
  387. }
  388. State.lex = function(){ return State().toString(36).replace('.','') }
  389. State.ify = function(n, k, s, v, soul){ // put a key's state on a node.
  390. if(!n || !n[N_]){ // reject if it is not node-like.
  391. if(!soul){ // unless they passed a soul
  392. return;
  393. }
  394. n = Node.soul.ify(n, soul); // then make it so!
  395. }
  396. var tmp = obj_as(n[N_], S_); // grab the states data.
  397. if(u !== k && k !== N_){
  398. if(num_is(s)){
  399. tmp[k] = s; // add the valid state.
  400. }
  401. if(u !== v){ // Note: Not its job to check for valid values!
  402. n[k] = v;
  403. }
  404. }
  405. return n;
  406. }
  407. State.to = function(from, k, to){
  408. var val = (from||{})[k];
  409. if(obj_is(val)){
  410. val = obj_copy(val);
  411. }
  412. return State.ify(to, k, State.is(from, k), val, Node.soul(from));
  413. }
  414. ;(function(){
  415. State.map = function(cb, s, as){ var u; // for use with Node.ify
  416. var o = obj_is(o = cb || s)? o : null;
  417. cb = fn_is(cb = cb || s)? cb : null;
  418. if(o && !cb){
  419. s = num_is(s)? s : State();
  420. o[N_] = o[N_] || {};
  421. obj_map(o, map, {o:o,s:s});
  422. return o;
  423. }
  424. as = as || obj_is(s)? s : u;
  425. s = num_is(s)? s : State();
  426. return function(v, k, o, opt){
  427. if(!cb){
  428. map.call({o: o, s: s}, v,k);
  429. return v;
  430. }
  431. cb.call(as || this || {}, v, k, o, opt);
  432. if(obj_has(o,k) && u === o[k]){ return }
  433. map.call({o: o, s: s}, v,k);
  434. }
  435. }
  436. function map(v,k){
  437. if(N_ === k){ return }
  438. State.ify(this.o, k, this.s) ;
  439. }
  440. }());
  441. var obj = Type.obj, obj_as = obj.as, obj_has = obj.has, obj_is = obj.is, obj_map = obj.map, obj_copy = obj.copy;
  442. var num = Type.num, num_is = num.is;
  443. var fn = Type.fn, fn_is = fn.is;
  444. var N_ = Node._, u;
  445. module.exports = State;
  446. })(USE, './state');
  447. ;USE(function(module){
  448. var Type = USE('./type');
  449. var Val = USE('./val');
  450. var Node = USE('./node');
  451. var Graph = {};
  452. ;(function(){
  453. Graph.is = function(g, cb, fn, as){ // checks to see if an object is a valid graph.
  454. if(!g || !obj_is(g) || obj_empty(g)){ return false } // must be an object.
  455. return !obj_map(g, map, {cb:cb,fn:fn,as:as}); // makes sure it wasn't an empty object.
  456. }
  457. function map(n, s){ // we invert this because the way'? we check for this is via a negation.
  458. if(!n || s !== Node.soul(n) || !Node.is(n, this.fn, this.as)){ return true } // it is true that this is an invalid graph.
  459. if(!this.cb){ return }
  460. nf.n = n; nf.as = this.as; // sequential race conditions aren't races.
  461. this.cb.call(nf.as, n, s, nf);
  462. }
  463. function nf(fn){ // optional callback for each node.
  464. if(fn){ Node.is(nf.n, fn, nf.as) } // where we then have an optional callback for each key/value.
  465. }
  466. }());
  467. ;(function(){
  468. Graph.ify = function(obj, env, as){
  469. var at = {path: [], obj: obj};
  470. if(!env){
  471. env = {};
  472. } else
  473. if(typeof env === 'string'){
  474. env = {soul: env};
  475. } else
  476. if('function' == typeof env){
  477. env.map = env;
  478. }
  479. if(typeof as === 'string'){
  480. env.soul = env.soul || as;
  481. as = u;
  482. }
  483. if(env.soul){
  484. at.link = Val.link.ify(env.soul);
  485. }
  486. env.shell = (as||{}).shell;
  487. env.graph = env.graph || {};
  488. env.seen = env.seen || [];
  489. env.as = env.as || as;
  490. node(env, at);
  491. env.root = at.node;
  492. return env.graph;
  493. }
  494. function node(env, at){ var tmp;
  495. if(tmp = seen(env, at)){ return tmp }
  496. at.env = env;
  497. at.soul = soul;
  498. if(Node.ify(at.obj, map, at)){
  499. at.link = at.link || Val.link.ify(Node.soul(at.node));
  500. if(at.obj !== env.shell){
  501. env.graph[Val.link.is(at.link)] = at.node;
  502. }
  503. }
  504. return at;
  505. }
  506. function map(v,k,n){
  507. var at = this, env = at.env, is, tmp;
  508. if(Node._ === k && obj_has(v,Val.link._)){
  509. return n._; // TODO: Bug?
  510. }
  511. if(!(is = valid(v,k,n, at,env))){ return }
  512. if(!k){
  513. at.node = at.node || n || {};
  514. if(obj_has(v, Node._) && Node.soul(v)){ // ? for safety ?
  515. at.node._ = obj_copy(v._);
  516. }
  517. at.node = Node.soul.ify(at.node, Val.link.is(at.link));
  518. at.link = at.link || Val.link.ify(Node.soul(at.node));
  519. }
  520. if(tmp = env.map){
  521. tmp.call(env.as || {}, v,k,n, at);
  522. if(obj_has(n,k)){
  523. v = n[k];
  524. if(u === v){
  525. obj_del(n, k);
  526. return;
  527. }
  528. if(!(is = valid(v,k,n, at,env))){ return }
  529. }
  530. }
  531. if(!k){ return at.node }
  532. if(true === is){
  533. return v;
  534. }
  535. tmp = node(env, {obj: v, path: at.path.concat(k)});
  536. if(!tmp.node){ return }
  537. return tmp.link; //{'#': Node.soul(tmp.node)};
  538. }
  539. function soul(id){ var at = this;
  540. var prev = Val.link.is(at.link), graph = at.env.graph;
  541. at.link = at.link || Val.link.ify(id);
  542. at.link[Val.link._] = id;
  543. if(at.node && at.node[Node._]){
  544. at.node[Node._][Val.link._] = id;
  545. }
  546. if(obj_has(graph, prev)){
  547. graph[id] = graph[prev];
  548. obj_del(graph, prev);
  549. }
  550. }
  551. function valid(v,k,n, at,env){ var tmp;
  552. if(Val.is(v)){ return true }
  553. if(obj_is(v)){ return 1 }
  554. if(tmp = env.invalid){
  555. v = tmp.call(env.as || {}, v,k,n);
  556. return valid(v,k,n, at,env);
  557. }
  558. env.err = "Invalid value at '" + at.path.concat(k).join('.') + "'!";
  559. if(Type.list.is(v)){ env.err += " Use `.set(item)` instead of an Array." }
  560. }
  561. function seen(env, at){
  562. var arr = env.seen, i = arr.length, has;
  563. while(i--){ has = arr[i];
  564. if(at.obj === has.obj){ return has }
  565. }
  566. arr.push(at);
  567. }
  568. }());
  569. Graph.node = function(node){
  570. var soul = Node.soul(node);
  571. if(!soul){ return }
  572. return obj_put({}, soul, node);
  573. }
  574. ;(function(){
  575. Graph.to = function(graph, root, opt){
  576. if(!graph){ return }
  577. var obj = {};
  578. opt = opt || {seen: {}};
  579. obj_map(graph[root], map, {obj:obj, graph: graph, opt: opt});
  580. return obj;
  581. }
  582. function map(v,k){ var tmp, obj;
  583. if(Node._ === k){
  584. if(obj_empty(v, Val.link._)){
  585. return;
  586. }
  587. this.obj[k] = obj_copy(v);
  588. return;
  589. }
  590. if(!(tmp = Val.link.is(v))){
  591. this.obj[k] = v;
  592. return;
  593. }
  594. if(obj = this.opt.seen[tmp]){
  595. this.obj[k] = obj;
  596. return;
  597. }
  598. this.obj[k] = this.opt.seen[tmp] = Graph.to(this.graph, tmp, this.opt);
  599. }
  600. }());
  601. var fn_is = Type.fn.is;
  602. var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_has = obj.has, obj_empty = obj.empty, obj_put = obj.put, obj_map = obj.map, obj_copy = obj.copy;
  603. var u;
  604. module.exports = Graph;
  605. })(USE, './graph');
  606. ;USE(function(module){
  607. // request / response module, for asking and acking messages.
  608. USE('./onto'); // depends upon onto!
  609. module.exports = function ask(cb, as){
  610. if(!this.on){ return }
  611. if(!('function' == typeof cb)){
  612. if(!cb || !as){ return }
  613. var id = cb['#'] || cb, tmp = (this.tag||'')[id];
  614. if(!tmp){ return }
  615. tmp = this.on(id, as);
  616. clearTimeout(tmp.err);
  617. return true;
  618. }
  619. var id = (as && as['#']) || Math.random().toString(36).slice(2);
  620. if(!cb){ return id }
  621. var to = this.on(id, cb, as);
  622. to.err = to.err || setTimeout(function(){
  623. to.next({err: "Error: No ACK yet.", lack: true});
  624. to.off();
  625. }, (this.opt||{}).lack || 9000);
  626. return id;
  627. }
  628. })(USE, './ask');
  629. ;USE(function(module){
  630. var Type = USE('./type');
  631. function Dup(opt){
  632. var dup = {s:{}}, s = dup.s;
  633. opt = opt || {max: 1000, age: /*1000 * 9};//*/ 1000 * 9 * 3};
  634. dup.check = function(id){
  635. if(!s[id]){ return false }
  636. return dt(id);
  637. }
  638. var dt = dup.track = function(id){
  639. var it = s[id] || (s[id] = {});
  640. it.was = +new Date;
  641. if(!dup.to){ dup.to = setTimeout(dup.drop, opt.age + 9) }
  642. return it;
  643. }
  644. dup.drop = function(age){
  645. var now = +new Date;
  646. Type.obj.map(s, function(it, id){
  647. if(it && (age || opt.age) > (now - it.was)){ return }
  648. delete s[id];
  649. });
  650. dup.to = null;
  651. console.STAT && (age = +new Date - now) > 9 && console.STAT(now, age, 'dup drop');
  652. }
  653. return dup;
  654. }
  655. module.exports = Dup;
  656. })(USE, './dup');
  657. ;USE(function(module){
  658. function Gun(o){
  659. if(o instanceof Gun){ return (this._ = {$: this}).$ }
  660. if(!(this instanceof Gun)){ return new Gun(o) }
  661. return Gun.create(this._ = {$: this, opt: o});
  662. }
  663. Gun.is = function($){ return ($ instanceof Gun) || ($ && $._ && ($ === $._.$)) || false }
  664. Gun.version = 0.2020;
  665. Gun.chain = Gun.prototype;
  666. Gun.chain.toJSON = function(){};
  667. var Type = USE('./type');
  668. Type.obj.to(Type, Gun);
  669. Gun.HAM = USE('./HAM');
  670. Gun.val = USE('./val');
  671. Gun.node = USE('./node');
  672. Gun.state = USE('./state');
  673. Gun.graph = USE('./graph');
  674. Gun.on = USE('./onto');
  675. Gun.ask = USE('./ask');
  676. Gun.dup = USE('./dup');
  677. Gun.puff = USE('./puff');
  678. ;(function(){
  679. Gun.create = function(at){
  680. at.root = at.root || at;
  681. at.graph = at.graph || {};
  682. at.on = at.on || Gun.on;
  683. at.ask = at.ask || Gun.ask;
  684. at.dup = at.dup || Gun.dup();
  685. var gun = at.$.opt(at.opt);
  686. if(!at.once){
  687. at.on('in', universe, at);
  688. at.on('out', universe, at);
  689. at.on('put', map, at);
  690. Gun.on('create', at);
  691. at.on('create', at);
  692. }
  693. at.once = 1;
  694. return gun;
  695. }
  696. function universe(msg){
  697. if(!msg){ return }
  698. if(msg.out === universe){ this.to.next(msg); return }
  699. var eve = this, as = eve.as, at = as.at || as, gun = at.$, dup = at.dup, tmp, DBG = msg.DBG;
  700. (tmp = msg['#']) || (tmp = msg['#'] = text_rand(9));
  701. if(dup.check(tmp)){ return } dup.track(tmp);
  702. tmp = msg._; msg._ = ('function' == typeof tmp)? tmp : function(){};
  703. (msg.$ && (msg.$ === (msg.$._||'').$)) || (msg.$ = gun);
  704. if(!at.ask(msg['@'], msg)){ // is this machine listening for an ack?
  705. DBG && (DBG.u = +new Date);
  706. if(msg.get){ Gun.on._get(msg, gun) }
  707. if(msg.put){ put(msg); return }
  708. }
  709. DBG && (DBG.uc = +new Date);
  710. eve.to.next(msg);
  711. DBG && (DBG.ua = +new Date);
  712. msg.out = universe; at.on('out', msg);
  713. DBG && (DBG.ue = +new Date);
  714. }
  715. function put(msg){
  716. if(!msg){ return }
  717. var ctx = msg._||'', root = ctx.root = ((msg.$||'')._||'').root;
  718. var put = msg.put, id = msg['#'], err, tmp;
  719. var DBG = ctx.DBG = msg.DBG;
  720. if(put['#'] && put['.']){ root.on('put', msg); return }
  721. /*root.on(id, function(m){
  722. console.log('ack:', m);
  723. });*/
  724. ctx.out = msg;
  725. ctx.lot = {s: 0, more: 1};
  726. var S = +new Date;
  727. DBG && (DBG.p = S);
  728. for(var soul in put){ // Gun.obj.native() makes this safe.
  729. var node = put[soul], states;
  730. if(!node){ err = ERR+cut(soul)+"no node."; break }
  731. if(!(tmp = node._)){ err = ERR+cut(soul)+"no meta."; break }
  732. if(soul !== tmp[_soul]){ err = ERR+cut(soul)+"soul not same."; break }
  733. if(!(states = tmp[state_])){ err = ERR+cut(soul)+"no state."; break }
  734. for(var key in node){ // double loop uncool, but have to support old format.
  735. if(node_ === key){ continue }
  736. var val = node[key], state = states[key];
  737. if(u === state){ err = ERR+cut(key)+"on"+cut(soul)+"no state."; break }
  738. if(!val_is(val)){ err = ERR+cut(key)+"on"+cut(soul)+"bad "+(typeof val)+cut(val); break }
  739. ham(val, key, soul, state, msg);
  740. }
  741. if(err){ break }
  742. }
  743. DBG && (DBG.pe = +new Date);
  744. if(console.STAT){ console.STAT(S, +new Date - S, 'mix');console.STAT(S, ctx.lot.s, 'mix #') }
  745. if(ctx.err = err){ root.on('in', {'@': id, err: Gun.log(err)}); return }
  746. if(!(--ctx.lot.more)){ fire(ctx) } // if synchronous.
  747. if(!ctx.stun && !msg['@']){ root.on('in', {'@': id, ok: -1}) } // in case no diff sent to storage, etc., still ack.
  748. } Gun.on.put = put;
  749. function ham(val, key, soul, state, msg){
  750. var ctx = msg._||'', root = ctx.root, graph = root.graph, lot;
  751. var vertex = graph[soul] || empty, was = state_is(vertex, key, 1), known = vertex[key];
  752. var machine = State(), is = HAM(machine, state, was, val, known), u;
  753. if(!is.incoming){
  754. if(is.defer){
  755. var to = state - machine;
  756. setTimeout(function(){
  757. ham(val, key, soul, state, msg);
  758. }, to > MD? MD : to); // setTimeout Max Defer 32bit :(
  759. if(!ctx.to){ root.on('in', {'@': msg['#'], err: to}) } ctx.to = 1;
  760. return to;
  761. }
  762. return;
  763. }
  764. (lot = ctx.lot||'').s++; lot.more++;
  765. (ctx.stun || (ctx.stun = {}))[soul+key] = 1;
  766. var DBG = ctx.DBG; DBG && (DBG.ph = DBG.ph || +new Date);
  767. root.on('put', {'#': msg['#'], '@': msg['@'], put: {'#': soul, '.': key, ':': val, '>': state}, _: ctx});
  768. }
  769. function map(msg){
  770. var DBG; if(DBG = (msg._||'').DBG){ DBG.pa = +new Date; DBG.pm = DBG.pm || +new Date}
  771. var eve = this, root = eve.as, graph = root.graph, ctx = msg._, put = msg.put, soul = put['#'], key = put['.'], val = put[':'], state = put['>'], id = msg['#'], tmp;
  772. graph[soul] = state_ify(graph[soul], key, state, val, soul); // TODO: Only put in graph if subscribed? Relays vs Browsers?
  773. chain(ctx, soul, key, (u !== (tmp = put['=']))? tmp : val, state); // TODO: This should NOT be how the API works, this should be done at an extension layer, but hacky solution to migrate with old code for now.
  774. if((tmp = ctx.out) && (tmp = tmp.put)){
  775. tmp[soul] = state_ify(tmp[soul], key, state, val, soul); // TODO: Hacky, fix & come back later, for actual pushing messages.
  776. }
  777. if(!(--ctx.lot.more)){ fire(ctx) }
  778. eve.to.next(msg);
  779. }
  780. function chain(ctx, soul, key,val, state){
  781. var root = ctx.root, put, tmp;
  782. (root.opt||'').super && root.$.get(soul); // I think we need super for now, but since we are rewriting, should consider getting rid of it.
  783. if(!root || !(tmp = root.next) || !(tmp = tmp[soul]) || !tmp.$){ return }
  784. (put = ctx.put || (ctx.put = {}))[soul] = state_ify(put[soul], key, state, val, soul);
  785. tmp.put = state_ify(tmp.put, key, state, val, soul);
  786. }
  787. function fire(ctx){
  788. if(ctx.err){ return }
  789. var stop = {};
  790. var root = ctx.root, next = root.next||'', put = ctx.put, tmp;
  791. var S = +new Date;
  792. //Gun.graph.is(put, function(node, soul){
  793. for(var soul in put){ var node = put[soul]; // Gun.obj.native() makes this safe.
  794. if(!(tmp = next[soul]) || !tmp.$){ continue }
  795. root.stop = stop; // temporary fix till a better solution?
  796. tmp.on('in', {$: tmp.$, get: soul, put: node});
  797. root.stop = null; // temporary fix till a better solution?
  798. }
  799. console.STAT && console.STAT(S, +new Date - S, 'fire');
  800. ctx.DBG && (ctx.DBG.f = +new Date);
  801. if(!(tmp = ctx.out)){ return }
  802. tmp.out = universe;
  803. root.on('out', tmp);
  804. }
  805. var ERR = "Error: Invalid graph!";
  806. var cut = function(s){ return " '"+(''+s).slice(0,9)+"...' " }
  807. var HAM = Gun.HAM, MD = 2147483647, State = Gun.state;
  808. }());
  809. ;(function(){
  810. Gun.on._put = function(msg, gun){
  811. var at = gun._, ctx = {$: gun, graph: at.graph, put: {}, map: {}, souls: {}, machine: Gun.state(), ack: msg['@'], cat: at, stop: {}};
  812. if(!Gun.obj.map(msg.put, perf, ctx)){ return } // HNPERF: performance test, not core code, do not port.
  813. if(!Gun.graph.is(msg.put, null, verify, ctx)){ ctx.err = "Error: Invalid graph!" }
  814. if(ctx.err){ return at.on('in', {'@': msg['#'], err: Gun.log(ctx.err) }) }
  815. obj_map(ctx.put, merge, ctx);
  816. if(!ctx.async){ obj_map(ctx.map, map, ctx) }
  817. if(u !== ctx.defer){
  818. var to = ctx.defer - ctx.machine;
  819. setTimeout(function(){
  820. Gun.on._put(msg, gun);
  821. }, to > MD? MD : to ); // setTimeout Max Defer 32bit :(
  822. }
  823. if(!ctx.diff){ return }
  824. at.on('put', obj_to(msg, {put: ctx.diff}));
  825. };
  826. function verify(val, key, node, soul){ var ctx = this;
  827. var state = Gun.state.is(node, key), tmp;
  828. if(!state){ return ctx.err = "Error: No state on '"+key+"' in node '"+soul+"'!" }
  829. var vertex = ctx.graph[soul] || empty, was = Gun.state.is(vertex, key, true), known = vertex[key];
  830. var HAM = Gun.HAM(ctx.machine, state, was, val, known);
  831. if(!HAM.incoming){
  832. if(HAM.defer){ // pick the lowest
  833. ctx.defer = (state < (ctx.defer || Infinity))? state : ctx.defer;
  834. }
  835. return;
  836. }
  837. ctx.put[soul] = Gun.state.to(node, key, ctx.put[soul]);
  838. (ctx.diff || (ctx.diff = {}))[soul] = Gun.state.to(node, key, ctx.diff[soul]);
  839. ctx.souls[soul] = true;
  840. }
  841. function merge(node, soul){
  842. var ctx = this, cat = ctx.$._, at = (cat.next || empty)[soul];
  843. if(!at){
  844. if(!(cat.opt||empty).super){
  845. ctx.souls[soul] = false;
  846. return;
  847. }
  848. at = (ctx.$.get(soul)._);
  849. }
  850. var msg = ctx.map[soul] = {
  851. put: node,
  852. get: soul,
  853. $: at.$
  854. }, as = {ctx: ctx, msg: msg};
  855. ctx.async = !!cat.tag.node;
  856. if(ctx.ack){ msg['@'] = ctx.ack }
  857. obj_map(node, each, as);
  858. if(!ctx.async){ return }
  859. if(!ctx.and){
  860. // If it is async, we only need to setup one listener per context (ctx)
  861. cat.on('node', function(m){
  862. this.to.next(m); // make sure to call other context's listeners.
  863. if(m !== ctx.map[m.get]){ return } // filter out events not from this context!
  864. ctx.souls[m.get] = false; // set our many-async flag
  865. obj_map(m.put, patch, m); // merge into view
  866. if(obj_map(ctx.souls, function(v){ if(v){ return v } })){ return } // if flag still outstanding, keep waiting.
  867. if(ctx.c){ return } ctx.c = 1; // failsafe for only being called once per context.
  868. this.off();
  869. obj_map(ctx.map, map, ctx); // all done, trigger chains.
  870. });
  871. }
  872. ctx.and = true;
  873. cat.on('node', msg); // each node on the current context's graph needs to be emitted though.
  874. }
  875. function each(val, key){
  876. var ctx = this.ctx, graph = ctx.graph, msg = this.msg, soul = msg.get, node = msg.put, at = (msg.$._), tmp;
  877. graph[soul] = Gun.state.to(node, key, graph[soul]);
  878. if(ctx.async){ return }
  879. at.put = Gun.state.to(node, key, at.put);
  880. }
  881. function patch(val, key){
  882. var msg = this, node = msg.put, at = (msg.$._);
  883. at.put = Gun.state.to(node, key, at.put);
  884. }
  885. function map(msg, soul){
  886. if(!msg.$){ return }
  887. this.cat.stop = this.stop; // temporary fix till a better solution?
  888. (msg.$._).on('in', msg);
  889. this.cat.stop = null; // temporary fix till a better solution?
  890. }
  891. function perf(node, soul){ if(node !== this.graph[soul]){ return true } } // HNPERF: do not port!
  892. Gun.on._get = function(msg, gun){
  893. var root = gun._, get = msg.get, soul = get[_soul], node = root.graph[soul], has = get[_has], tmp;
  894. var next = root.next || (root.next = {}), at = next[soul];
  895. // queue concurrent GETs?
  896. var ctx = msg._||'', DBG = ctx.DBG = msg.DBG;
  897. DBG && (DBG.g = +new Date);
  898. if(!node){ return root.on('get', msg) }
  899. if(has){
  900. if('string' != typeof has || !obj_has(node, has)){ return root.on('get', msg) }
  901. node = Gun.state.to(node, has);
  902. // If we have a key in-memory, do we really need to fetch?
  903. // Maybe... in case the in-memory key we have is a local write
  904. // we still need to trigger a pull/merge from peers.
  905. } else {
  906. node = Gun.window? Gun.obj.copy(node) : node; // HNPERF: If !browser bump Performance? Is this too dangerous to reference root graph? Copy / shallow copy too expensive for big nodes. Gun.obj.to(node); // 1 layer deep copy // Gun.obj.copy(node); // too slow on big nodes
  907. }
  908. node = Gun.graph.node(node);
  909. tmp = (at||empty).ack;
  910. var faith = function(){}; faith.ram = faith.faith = true; // HNPERF: We're testing performance improvement by skipping going through security again, but this should be audited.
  911. DBG && (DBG.ga = +new Date);
  912. root.on('in', {
  913. '@': msg['#'],
  914. put: node,
  915. ram: 1,
  916. $: gun,
  917. _: faith
  918. });
  919. DBG && (DBG.gm = +new Date);
  920. //if(0 < tmp){ return }
  921. root.on('get', msg);
  922. DBG && (DBG.gd = +new Date);
  923. }
  924. }());
  925. ;(function(){
  926. Gun.chain.opt = function(opt){
  927. opt = opt || {};
  928. var gun = this, at = gun._, tmp = opt.peers || opt;
  929. if(!obj_is(opt)){ opt = {} }
  930. if(!obj_is(at.opt)){ at.opt = opt }
  931. if(text_is(tmp)){ tmp = [tmp] }
  932. if(list_is(tmp)){
  933. tmp = obj_map(tmp, function(url, i, map){
  934. i = {}; i.id = i.url = url; map(url, i);
  935. });
  936. if(!obj_is(at.opt.peers)){ at.opt.peers = {}}
  937. at.opt.peers = obj_to(tmp, at.opt.peers);
  938. }
  939. at.opt.peers = at.opt.peers || {};
  940. obj_map(opt, function each(v,k){
  941. if(!obj_has(this, k) || text.is(v) || obj.empty(v)){ this[k] = v ; return }
  942. if(v && v.constructor !== Object && !list_is(v)){ return }
  943. obj_map(v, each, this[k]);
  944. }, at.opt);
  945. Gun.on('opt', at);
  946. //at.opt.uuid = at.opt.uuid || function(){ return state_lex() + text_rand(12) }
  947. Gun.obj.native();
  948. return gun;
  949. }
  950. }());
  951. Gun.obj.native = function(){ var p = Object.prototype; for(var i in p){ console.log("Native Object.prototype polluted, reverting", i); delete p[i]; } };
  952. var list_is = Gun.list.is;
  953. var text = Gun.text, text_is = text.is, text_rand = text.random;
  954. var obj = Gun.obj, obj_empty = obj.empty, obj_is = obj.is, obj_has = obj.has, obj_to = obj.to, obj_map = obj.map, obj_copy = obj.copy;
  955. var state_lex = Gun.state.lex, state_ify = Gun.state.ify, state_is = Gun.state.is, _soul = Gun.val.link._, _has = '.', node_ = Gun.node._, val_is = Gun.val.is, rel_is = Gun.val.link.is, state_ = Gun.state._;
  956. var empty = {}, u;
  957. var C;
  958. Gun.log = function(){ return (!Gun.log.off && C.log.apply(C, arguments)), [].slice.call(arguments).join(' ') };
  959. Gun.log.once = function(w,s,o){ return (o = Gun.log.once)[w] = o[w] || 0, o[w]++ || Gun.log(s) };
  960. if(typeof window !== "undefined"){ (window.GUN = window.Gun = Gun).window = window }
  961. try{ if(typeof MODULE !== "undefined"){ MODULE.exports = Gun } }catch(e){}
  962. module.exports = Gun;
  963. (Gun.window||'').console = (Gun.window||'').console || {log: function(){}};
  964. (C = console).only = function(i, s){ return (C.only.i && i === C.only.i && C.only.i++) && (C.log.apply(C, arguments) || s) };
  965. ;"Please do not remove welcome log unless you are paying for a monthly sponsorship, thanks!";
  966. Gun.log.once("welcome", "Hello wonderful person! :) Thanks for using GUN, please ask for help on http://chat.gun.eco if anything takes you longer than 5min to figure out!");
  967. })(USE, './root');
  968. ;USE(function(module){
  969. var Gun = USE('./root');
  970. Gun.chain.back = function(n, opt){ var tmp;
  971. n = n || 1;
  972. if(-1 === n || Infinity === n){
  973. return this._.root.$;
  974. } else
  975. if(1 === n){
  976. return (this._.back || this._).$;
  977. }
  978. var gun = this, at = gun._;
  979. if(typeof n === 'string'){
  980. n = n.split('.');
  981. }
  982. if(n instanceof Array){
  983. var i = 0, l = n.length, tmp = at;
  984. for(i; i < l; i++){
  985. tmp = (tmp||empty)[n[i]];
  986. }
  987. if(u !== tmp){
  988. return opt? gun : tmp;
  989. } else
  990. if((tmp = at.back)){
  991. return tmp.$.back(n, opt);
  992. }
  993. return;
  994. }
  995. if('function' == typeof n){
  996. var yes, tmp = {back: at};
  997. while((tmp = tmp.back)
  998. && u === (yes = n(tmp, opt))){}
  999. return yes;
  1000. }
  1001. if(Gun.num.is(n)){
  1002. return (at.back || at).$.back(n - 1);
  1003. }
  1004. return this;
  1005. }
  1006. var empty = {}, u;
  1007. })(USE, './back');
  1008. ;USE(function(module){
  1009. // WARNING: GUN is very simple, but the JavaScript chaining API around GUN
  1010. // is complicated and was extremely hard to build. If you port GUN to another
  1011. // language, consider implementing an easier API to build.
  1012. var Gun = USE('./root');
  1013. Gun.chain.chain = function(sub){
  1014. var gun = this, at = gun._, chain = new (sub || gun).constructor(gun), cat = chain._, root;
  1015. cat.root = root = at.root;
  1016. cat.id = ++root.once;
  1017. cat.back = gun._;
  1018. cat.on = Gun.on;
  1019. cat.on('in', input, cat); // For 'in' if I add my own listeners to each then I MUST do it before in gets called. If I listen globally for all incoming data instead though, regardless of individual listeners, I can transform the data there and then as well.
  1020. cat.on('out', output, cat); // However for output, there isn't really the global option. I must listen by adding my own listener individually BEFORE this one is ever called.
  1021. return chain;
  1022. }
  1023. function output(msg){
  1024. var put, get, at = this.as, back = at.back, root = at.root, tmp;
  1025. if(!msg.$){ msg.$ = at.$ }
  1026. this.to.next(msg);
  1027. if(get = msg.get){
  1028. /*if(u !== at.put){
  1029. at.on('in', at);
  1030. return;
  1031. }*/
  1032. if(at.lex){ msg.get = obj_to(at.lex, msg.get) }
  1033. if(get['#'] || at.soul){
  1034. get['#'] = get['#'] || at.soul;
  1035. msg['#'] || (msg['#'] = text_rand(9));
  1036. back = (root.$.get(get['#'])._);
  1037. if(!(get = get['.'])){
  1038. tmp = back.ack;
  1039. if(!tmp){ back.ack = -1 }
  1040. if(obj_has(back, 'put')){
  1041. back.on('in', back);
  1042. }
  1043. if(tmp && u !== back.put){ return } //if(tmp){ return }
  1044. msg.$ = back.$;
  1045. } else
  1046. if(obj_has(back.put, get)){ // TODO: support #LEX !
  1047. put = (back.$.get(get)._);
  1048. if(!(tmp = put.ack)){ put.ack = -1 }
  1049. back.on('in', {
  1050. $: back.$,
  1051. put: Gun.state.to(back.put, get),
  1052. get: back.get
  1053. });
  1054. if(tmp){ return }
  1055. } else
  1056. if('string' != typeof get){
  1057. var put = {}, meta = (back.put||{})._;
  1058. Gun.obj.map(back.put, function(v,k){
  1059. if(!Gun.text.match(k, get)){ return }
  1060. put[k] = v;
  1061. })
  1062. if(!Gun.obj.empty(put)){
  1063. put._ = meta;
  1064. back.on('in', {$: back.$, put: put, get: back.get})
  1065. }
  1066. if(tmp = at.lex){
  1067. tmp = (tmp._) || (tmp._ = function(){});
  1068. if(back.ack < tmp.ask){ tmp.ask = back.ack }
  1069. if(tmp.ask){ return }
  1070. tmp.ask = 1;
  1071. }
  1072. }
  1073. root.ask(ack, msg);
  1074. return root.on('in', msg);
  1075. }
  1076. if(root.now){ root.now[at.id] = root.now[at.id] || true; at.pass = {} }
  1077. if(get['.']){
  1078. if(at.get){
  1079. msg = {get: {'.': at.get}, $: at.$};
  1080. //if(back.ask || (back.ask = {})[at.get]){ return }
  1081. (back.ask || (back.ask = {}));
  1082. back.ask[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
  1083. return back.on('out', msg);
  1084. }
  1085. msg = {get: {}, $: at.$};
  1086. return back.on('out', msg);
  1087. }
  1088. at.ack = at.ack || -1;
  1089. if(at.get){
  1090. msg.$ = at.$;
  1091. get['.'] = at.get;
  1092. (back.ask || (back.ask = {}))[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
  1093. return back.on('out', msg);
  1094. }
  1095. }
  1096. return back.on('out', msg);
  1097. }
  1098. function input(msg){
  1099. var eve = this, cat = eve.as, root = cat.root, gun = msg.$, at = (gun||empty)._ || empty, change = msg.put, rel, tmp;
  1100. if(cat.get && msg.get !== cat.get){
  1101. msg = obj_to(msg, {get: cat.get});
  1102. }
  1103. if(cat.has && at !== cat){
  1104. msg = obj_to(msg, {$: cat.$});
  1105. if(at.ack){
  1106. cat.ack = at.ack;
  1107. //cat.ack = cat.ack || at.ack;
  1108. }
  1109. }
  1110. if(u === change){
  1111. tmp = at.put;
  1112. eve.to.next(msg);
  1113. if(cat.soul){ return } // TODO: BUG, I believee the fresh input refactor caught an edge case that a `gun.get('soul').get('key')` that points to a soul that doesn't exist will not trigger val/get etc.
  1114. if(u === tmp && u !== at.put){ return }
  1115. echo(cat, msg, eve);
  1116. if(cat.has){
  1117. not(cat, msg);
  1118. }
  1119. obj_del(at.echo, cat.id);
  1120. obj_del(cat.map, at.id);
  1121. return;
  1122. }
  1123. if(cat.soul){
  1124. eve.to.next(msg);
  1125. echo(cat, msg, eve);
  1126. if(cat.next){ obj_map(change, map, {msg: msg, cat: cat}) }
  1127. return;
  1128. }
  1129. if(!(rel = Gun.val.link.is(change))){
  1130. if(Gun.val.is(change)){
  1131. if(cat.has || cat.soul){
  1132. not(cat, msg);
  1133. } else
  1134. if(at.has || at.soul){
  1135. (at.echo || (at.echo = {}))[cat.id] = at.echo[at.id] || cat;
  1136. (cat.map || (cat.map = {}))[at.id] = cat.map[at.id] || {at: at};
  1137. //if(u === at.put){ return } // Not necessary but improves performance. If we have it but at does not, that means we got things out of order and at will get it. Once at gets it, it will tell us again.
  1138. }
  1139. eve.to.next(msg);
  1140. echo(cat, msg, eve);
  1141. return;
  1142. }
  1143. if(cat.has && at !== cat && obj_has(at, 'put')){
  1144. cat.put = at.put;
  1145. };
  1146. if((rel = Gun.node.soul(change)) && at.has){
  1147. at.put = (cat.root.$.get(rel)._).put;
  1148. }
  1149. tmp = (root.stop || {})[at.id];
  1150. //if(tmp && tmp[cat.id]){ } else {
  1151. eve.to.next(msg);
  1152. //}
  1153. relate(cat, msg, at, rel);
  1154. echo(cat, msg, eve);
  1155. if(cat.next){ obj_map(change, map, {msg: msg, cat: cat}) }
  1156. return;
  1157. }
  1158. var was = root.stop;
  1159. tmp = root.stop || {};
  1160. tmp = tmp[at.id] || (tmp[at.id] = {});
  1161. //if(tmp[cat.id]){ return }
  1162. tmp.is = tmp.is || at.put;
  1163. tmp[cat.id] = at.put || true;
  1164. //if(root.stop){
  1165. eve.to.next(msg)
  1166. //}
  1167. relate(cat, msg, at, rel);
  1168. echo(cat, msg, eve);
  1169. }
  1170. function relate(at, msg, from, rel){
  1171. if(!rel || node_ === at.get){ return }
  1172. var tmp = (at.root.$.get(rel)._);
  1173. if(at.has){
  1174. from = tmp;
  1175. } else
  1176. if(from.has){
  1177. relate(from, msg, from, rel);
  1178. }
  1179. if(from === at){ return }
  1180. if(!from.$){ from = {} }
  1181. (from.echo || (from.echo = {}))[at.id] = from.echo[at.id] || at;
  1182. if(at.has && !(at.map||empty)[from.id]){ // if we haven't seen this before.
  1183. not(at, msg);
  1184. }
  1185. tmp = from.id? ((at.map || (at.map = {}))[from.id] = at.map[from.id] || {at: from}) : {};
  1186. if(rel === tmp.link){
  1187. if(!(tmp.pass || at.pass)){
  1188. return;
  1189. }
  1190. }
  1191. if(at.pass){
  1192. Gun.obj.map(at.map, function(tmp){ tmp.pass = true })
  1193. obj_del(at, 'pass');
  1194. }
  1195. if(tmp.pass){ obj_del(tmp, 'pass') }
  1196. if(at.has){ at.link = rel }
  1197. ask(at, tmp.link = rel);
  1198. }
  1199. function echo(at, msg, ev){
  1200. if(!at.echo){ return } // || node_ === at.get ?
  1201. //if(at.has){ msg = obj_to(msg, {event: ev}) }
  1202. obj_map(at.echo, reverb, msg);
  1203. }
  1204. function reverb(to){
  1205. if(!to || !to.on){ return }
  1206. to.on('in', this);
  1207. }
  1208. function map(data, key){ // Map over only the changes on every update.
  1209. var cat = this.cat, next = cat.next || empty, via = this.msg, chain, at, tmp;
  1210. if(node_ === key && !next[key]){ return }
  1211. if(!(at = next[key])){
  1212. return;
  1213. }
  1214. //if(data && data[_soul] && (tmp = Gun.val.link.is(data)) && (tmp = (cat.root.$.get(tmp)._)) && obj_has(tmp, 'put')){
  1215. // data = tmp.put;
  1216. //}
  1217. if(at.has){
  1218. //if(!(data && data[_soul] && Gun.val.link.is(data) === Gun.node.soul(at.put))){
  1219. if(u === at.put || !Gun.val.link.is(data)){
  1220. at.put = data;
  1221. }
  1222. chain = at.$;
  1223. } else
  1224. if(tmp = via.$){
  1225. tmp = (chain = via.$.get(key))._;
  1226. if(u === tmp.put || !Gun.val.link.is(data)){
  1227. tmp.put = data;
  1228. }
  1229. }
  1230. at.on('in', {
  1231. put: data,
  1232. get: key,
  1233. $: chain,
  1234. via: via
  1235. });
  1236. }
  1237. function not(at, msg){
  1238. if(!(at.has || at.soul)){ return }
  1239. var tmp = at.map, root = at.root;
  1240. at.map = null;
  1241. if(at.has){
  1242. if(at.dub && at.root.stop){ at.dub = null }
  1243. at.link = null;
  1244. }
  1245. //if(!root.now || !root.now[at.id]){
  1246. if(!at.pass){
  1247. if((!msg['@']) && null === tmp){ return }
  1248. //obj_del(at, 'pass');
  1249. }
  1250. if(u === tmp && Gun.val.link.is(at.put)){ return } // This prevents the very first call of a thing from triggering a "clean up" call. // TODO: link.is(at.put) || !val.is(at.put) ?
  1251. obj_map(tmp, function(proxy){
  1252. if(!(proxy = proxy.at)){ return }
  1253. obj_del(proxy.echo, at.id);
  1254. });
  1255. tmp = at.put;
  1256. obj_map(at.next, function(neat, key){
  1257. if(u === tmp && u !== at.put){ return true }
  1258. neat.put = u;
  1259. if(neat.ack){
  1260. neat.ack = -1; // Shouldn't this be reset to 0? If we do that, SEA test `set user ref should be found` fails, odd.
  1261. }
  1262. neat.on('in', {
  1263. get: key,
  1264. $: neat.$,
  1265. put: u
  1266. });
  1267. });
  1268. }
  1269. function ask(at, soul){
  1270. var tmp = (at.root.$.get(soul)._), lex = at.lex;
  1271. if(at.ack || lex){
  1272. (lex = lex||{})['#'] = soul;
  1273. tmp.on('out', {get: lex});
  1274. if(!at.ask){ return } // TODO: PERFORMANCE? More elegant way?
  1275. }
  1276. tmp = at.ask; Gun.obj.del(at, 'ask');
  1277. obj_map(tmp || at.next, function(neat, key){
  1278. var lex = neat.lex || {}; lex['#'] = soul; lex['.'] = lex['.'] || key;
  1279. neat.on('out', {get: lex});
  1280. });
  1281. Gun.obj.del(at, 'ask'); // TODO: PERFORMANCE? More elegant way?
  1282. }
  1283. function ack(msg, ev){
  1284. var as = this.as, get = as.get||'', at = as.$._, tmp = (msg.put||'')[get['#']];
  1285. if(at.ack){ at.ack = (at.ack + 1) || 1; }
  1286. if(!msg.put || ('string' == typeof get['.'] && !obj_has(tmp, at.get))){
  1287. if(at.put !== u){ return }
  1288. at.on('in', {
  1289. get: at.get,
  1290. put: at.put = u,
  1291. $: at.$,
  1292. '@': msg['@']
  1293. });
  1294. return;
  1295. }
  1296. if(node_ == get['.']){ // is this a security concern?
  1297. at.on('in', {get: at.get, put: Gun.val.link.ify(get['#']), $: at.$, '@': msg['@']});
  1298. return;
  1299. }
  1300. Gun.on.put(msg);
  1301. }
  1302. var empty = {}, u;
  1303. var obj = Gun.obj, obj_has = obj.has, obj_put = obj.put, obj_del = obj.del, obj_to = obj.to, obj_map = obj.map;
  1304. var text_rand = Gun.text.random;
  1305. var _soul = Gun.val.link._, node_ = Gun.node._;
  1306. })(USE, './chain');
  1307. ;USE(function(module){
  1308. var Gun = USE('./root');
  1309. Gun.chain.get = function(key, cb, as){
  1310. var gun, tmp;
  1311. if(typeof key === 'string'){
  1312. var back = this, cat = back._;
  1313. var next = cat.next || empty;
  1314. if(!(gun = next[key])){
  1315. gun = cache(key, back);
  1316. }
  1317. gun = gun.$;
  1318. } else
  1319. if('function' == typeof key){
  1320. if(true === cb){ return soul(this, key, cb, as), this }
  1321. gun = this;
  1322. var at = gun._, root = at.root, tmp = root.now, ev;
  1323. as = cb || {};
  1324. as.at = at;
  1325. as.use = key;
  1326. as.out = as.out || {};
  1327. as.out.get = as.out.get || {};
  1328. (ev = at.on('in', use, as)).rid = rid;
  1329. (root.now = {$:1})[as.now = at.id] = ev;
  1330. var mum = root.mum; root.mum = {};
  1331. at.on('out', as.out);
  1332. root.mum = mum;
  1333. root.now = tmp;
  1334. return gun;
  1335. } else
  1336. if(num_is(key)){
  1337. return this.get(''+key, cb, as);
  1338. } else
  1339. if(tmp = rel.is(key)){
  1340. return this.get(tmp, cb, as);
  1341. } else
  1342. if(obj.is(key)){
  1343. gun = this;
  1344. if(tmp = ((tmp = key['#'])||empty)['='] || tmp){ gun = gun.get(tmp) }
  1345. gun._.lex = key;
  1346. return gun;
  1347. } else {
  1348. (as = this.chain())._.err = {err: Gun.log('Invalid get request!', key)}; // CLEAN UP
  1349. if(cb){ cb.call(as, as._.err) }
  1350. return as;
  1351. }
  1352. if(tmp = this._.stun){ // TODO: Refactor?
  1353. gun._.stun = gun._.stun || tmp;
  1354. }
  1355. if(cb && 'function' == typeof cb){
  1356. gun.get(cb, as);
  1357. }
  1358. return gun;
  1359. }
  1360. function cache(key, back){
  1361. var cat = back._, next = cat.next, gun = back.chain(), at = gun._;
  1362. if(!next){ next = cat.next = {} }
  1363. next[at.get = key] = at;
  1364. if(back === cat.root.$){
  1365. at.soul = key;
  1366. } else
  1367. if(cat.soul || cat.has){
  1368. at.has = key;
  1369. //if(obj_has(cat.put, key)){
  1370. //at.put = cat.put[key];
  1371. //}
  1372. }
  1373. return at;
  1374. }
  1375. function soul(gun, cb, opt, as){
  1376. var cat = gun._, acks = 0, tmp;
  1377. if(tmp = cat.soul || cat.link || cat.dub){ return cb(tmp, as, cat) }
  1378. if(cat.jam){ return cat.jam.push([cb, as]) }
  1379. cat.jam = [[cb,as]];
  1380. gun.get(function go(msg, eve){
  1381. if(u === msg.put && (tmp = Object.keys(cat.root.opt.peers).length) && ++acks <= tmp){
  1382. return;
  1383. }
  1384. eve.rid(msg);
  1385. var at = ((at = msg.$) && at._) || {}, i = 0, as;
  1386. tmp = cat.jam; delete cat.jam; // tmp = cat.jam.splice(0, 100);
  1387. //if(tmp.length){ process.nextTick(function(){ go(msg, eve) }) }
  1388. while(as = tmp[i++]){ //Gun.obj.map(tmp, function(as, cb){
  1389. var cb = as[0], id; as = as[1];
  1390. cb && cb(id = at.link || at.soul || rel.is(msg.put) || node_soul(msg.put) || at.dub, as, msg, eve);
  1391. } //);
  1392. }, {out: {get: {'.':true}}});
  1393. return gun;
  1394. }
  1395. function use(msg){
  1396. var eve = this, as = eve.as, cat = as.at, root = cat.root, gun = msg.$, at = (gun||{})._ || {}, data = msg.put || at.put, tmp;
  1397. if((tmp = root.now) && eve !== tmp[as.now]){ return eve.to.next(msg) }
  1398. //if(at.async && msg.root){ return }
  1399. //if(at.async === 1 && cat.async !== true){ return }
  1400. //if(root.stop && root.stop[at.id]){ return } root.stop && (root.stop[at.id] = true);
  1401. //if(!at.async && !cat.async && at.put && msg.put === at.put){ return }
  1402. //else if(!cat.async && msg.put !== at.put && root.stop && root.stop[at.id]){ return } root.stop && (root.stop[at.id] = true);
  1403. //root.stop && (root.stop.id = root.stop.id || Gun.text.random(2));
  1404. //if((tmp = root.stop) && (tmp = tmp[at.id] || (tmp[at.id] = {})) && tmp[cat.id]){ return } tmp && (tmp[cat.id] = true);
  1405. if(eve.seen && at.id && eve.seen[at.id]){ return eve.to.next(msg) }
  1406. //if((tmp = root.stop)){ if(tmp[at.id]){ return } tmp[at.id] = msg.root; } // temporary fix till a better solution?
  1407. if((tmp = data) && tmp[rel._] && (tmp = rel.is(tmp))){
  1408. tmp = ((msg.$$ = at.root.$.get(tmp))._);
  1409. if(u !== tmp.put){
  1410. msg = obj_to(msg, {put: data = tmp.put});
  1411. }
  1412. }
  1413. if((tmp = root.mum) && at.id){ // TODO: can we delete mum entirely now?
  1414. var id = at.id + (eve.id || (eve.id = Gun.text.random(9)));
  1415. if(tmp[id]){ return }
  1416. if(u !== data && !rel.is(data)){ tmp[id] = true; }
  1417. }
  1418. as.use(msg, eve);
  1419. if(eve.stun){
  1420. eve.stun = null;
  1421. return;
  1422. }
  1423. eve.to.next(msg);
  1424. }
  1425. function rid(at){
  1426. var cat = this.on;
  1427. if(!at || cat.soul || cat.has){ return this.off() }
  1428. if(!(at = (at = (at = at.$ || at)._ || at).id)){ return }
  1429. var map = cat.map, tmp, seen;
  1430. //if(!map || !(tmp = map[at]) || !(tmp = tmp.at)){ return }
  1431. if(tmp = (seen = this.seen || (this.seen = {}))[at]){ return true }
  1432. seen[at] = true;
  1433. return;
  1434. //tmp.echo[cat.id] = {}; // TODO: Warning: This unsubscribes ALL of this chain's listeners from this link, not just the one callback event.
  1435. //obj.del(map, at); // TODO: Warning: This unsubscribes ALL of this chain's listeners from this link, not just the one callback event.
  1436. return;
  1437. }
  1438. var obj = Gun.obj, obj_map = obj.map, obj_has = obj.has, obj_to = Gun.obj.to;
  1439. var num_is = Gun.num.is;
  1440. var rel = Gun.val.link, node_soul = Gun.node.soul, node_ = Gun.node._;
  1441. var empty = {}, u;
  1442. })(USE, './get');
  1443. ;USE(function(module){
  1444. var Gun = USE('./root');
  1445. Gun.chain.put = function(data, cb, as){
  1446. var gun = this, at = (gun._), root = at.root.$, ctx = root._, M = 100, tmp;
  1447. as = as || {};
  1448. as.data = data;
  1449. as.via = as.$ = as.via || as.$ || gun;
  1450. if(typeof cb === 'string'){
  1451. as.soul = cb;
  1452. } else {
  1453. as.ack = as.ack || cb;
  1454. }
  1455. if(at.soul){
  1456. as.soul = at.soul;
  1457. }
  1458. if(as.soul || root === gun){
  1459. if(!obj_is(as.data)){
  1460. (as.ack||noop).call(as, as.out = {err: Gun.log("Data saved to the root level of the graph must be a node (an object), not a", (typeof as.data), 'of "' + as.data + '"!')});
  1461. if(as.res){ as.res() }
  1462. return gun;
  1463. }
  1464. as.soul = as.soul || (as.not = Gun.node.soul(as.data) || (as.via.back('opt.uuid') /*|| Gun.text.random*/)());
  1465. if(!as.soul){ // polyfill async uuid for SEA
  1466. as.via.back('opt.uuid')(function(err, soul){ // TODO: improve perf without anonymous callback
  1467. if(err){ return Gun.log(err) } // TODO: Handle error!
  1468. (as.ref||as.$).put(as.data, as.soul = soul, as);
  1469. });
  1470. return gun;
  1471. }
  1472. as.$ = root.get(as.soul);
  1473. as.ref = as.$;
  1474. ify(as);
  1475. return gun;
  1476. }
  1477. if(Gun.is(data)){
  1478. data.get(function(soul, o, msg){
  1479. if(!soul){
  1480. return Gun.log("The reference you are saving is a", typeof msg.put, '"'+ msg.put +'", not a node (object)!');
  1481. }
  1482. gun.put(Gun.val.link.ify(soul), cb, as);
  1483. }, true);
  1484. return gun;
  1485. }
  1486. if(at.has && (tmp = Gun.val.link.is(data))){ at.dub = tmp }
  1487. as.ref = as.ref || (root._ === (tmp = at.back))? gun : tmp.$;
  1488. if(as.ref._.soul && Gun.val.is(as.data) && at.get){
  1489. as.data = obj_put({}, at.get, as.data);
  1490. as.ref.put(as.data, as.soul, as);
  1491. return gun;
  1492. }
  1493. as.ref.get(any, true, {as: as});
  1494. if(!as.out){
  1495. // TODO: Perf idea! Make a global lock, that blocks everything while it is on, but if it is on the lock it does the expensive lookup to see if it is a dependent write or not and if not then it proceeds full speed. Meh? For write heavy async apps that would be terrible.
  1496. as.res = as.res || stun; // Gun.on.stun(as.ref); // TODO: BUG! Deal with locking?
  1497. as.$._.stun = as.ref._.stun;
  1498. }
  1499. return gun;
  1500. };
  1501. /*Gun.chain.put = function(data, cb, as){ // don't rewrite! :(
  1502. var gun = this, at = gun._;
  1503. as = as || {};
  1504. as.soul || (as.soul = at.soul || ('string' == typeof cb && cb));
  1505. if(!as.soul){ return get(data, cb, as) }
  1506. return gun;
  1507. }*/
  1508. function ify(as){
  1509. as.batch = batch;
  1510. var opt = as.opt||{}, env = as.env = Gun.state.map(map, opt.state);
  1511. env.soul = as.soul;
  1512. as.graph = Gun.graph.ify(as.data, env, as);
  1513. if(env.err){
  1514. (as.ack||noop).call(as, as.out = {err: Gun.log(env.err)});
  1515. if(as.res){ as.res() }
  1516. return;
  1517. }
  1518. as.batch();
  1519. }
  1520. function stun(cb){
  1521. if(cb){ cb() }
  1522. return;
  1523. var as = this;
  1524. if(!as.ref){ return }
  1525. if(cb){
  1526. as.after = as.ref._.tag;
  1527. as.now = as.ref._.tag = {};
  1528. cb();
  1529. return;
  1530. }
  1531. if(as.after){
  1532. as.ref._.tag = as.after;
  1533. }
  1534. }
  1535. function batch(){ var as = this;
  1536. if(!as.graph || !obj_empty(as.stun)){ return }
  1537. as.res = as.res || function(cb){ if(cb){ cb() } };
  1538. as.res(function(){
  1539. var cat = (as.$.back(-1)._), ask = cat.ask(function(ack){
  1540. cat.root.on('ack', ack);
  1541. if(ack.err){ Gun.log(ack) }
  1542. if(++acks > (as.acks || 0)){ this.off() } // Adjustable ACKs! Only 1 by default.
  1543. if(!as.ack){ return }
  1544. as.ack(ack, this);
  1545. //--C;
  1546. }, as.opt), acks = 0;
  1547. //C++;
  1548. // NOW is a hack to get synchronous replies to correctly call.
  1549. // and STOP is a hack to get async behavior to correctly call.
  1550. // neither of these are ideal, need to be fixed without hacks,
  1551. // but for now, this works for current tests. :/
  1552. var tmp = cat.root.now; obj.del(cat.root, 'now');
  1553. var mum = cat.root.mum; cat.root.mum = {};
  1554. (as.ref._).on('out', {
  1555. $: as.ref, put: as.out = as.env.graph, opt: as.opt, '#': ask
  1556. });
  1557. cat.root.mum = mum? obj.to(mum, cat.root.mum) : mum;
  1558. cat.root.now = tmp;
  1559. }, as);
  1560. if(as.res){ as.res() }
  1561. } function no(v,k){ if(v){ return true } }
  1562. function map(v,k,n, at){ var as = this;
  1563. var is = Gun.is(v);
  1564. if(k || !at.path.length){ return }
  1565. (as.res||iife)(function(){
  1566. var path = at.path, ref = as.ref, opt = as.opt;
  1567. var i = 0, l = path.length;
  1568. for(i; i < l; i++){
  1569. ref = ref.get(path[i]);
  1570. }
  1571. if(is){ ref = v }
  1572. //if(as.not){ (ref._).dub = Gun.text.random() } // This might optimize stuff? Maybe not needed anymore. Make sure it doesn't introduce bugs.
  1573. var id = (ref._).dub;
  1574. if(id || (id = Gun.node.soul(at.obj))){
  1575. ref.back(-1).get(id);
  1576. at.soul(id);
  1577. return;
  1578. }
  1579. (as.stun = as.stun || {})[path] = 1;
  1580. ref.get(soul, true, {as: {at: at, as: as, p:path}});
  1581. }, {as: as, at: at});
  1582. //if(is){ return {} }
  1583. }
  1584. var G = String.fromCharCode(31);
  1585. function soul(id, as, msg, eve){
  1586. var as = as.as, path = as.p, cat = as.at; as = as.as;
  1587. var at = ((msg || {}).$ || {})._ || {};
  1588. id = at.dub = at.dub || id || Gun.node.soul(cat.obj) || Gun.node.soul(msg.put || at.put) || Gun.val.link.is(msg.put || at.put) || (as.via.back('opt.uuid') || function(){
  1589. return (as.soul+'.')+Gun.text.hash(path.join(G)).toString(32);
  1590. })(); // TODO: BUG!? Do we really want the soul of the object given to us? Could that be dangerous? What about copy operations?
  1591. if(eve){ eve.stun = true }
  1592. if(!id){ // polyfill async uuid for SEA
  1593. as.via.back('opt.uuid')(function(err, id){ // TODO: improve perf without anonymous callback
  1594. if(err){ return Gun.log(err) } // TODO: Handle error.
  1595. solve(at, at.dub = at.dub || id, cat, as);
  1596. });
  1597. return;
  1598. }
  1599. solve(at, at.dub = id, cat, as);
  1600. }
  1601. function solve(at, id, cat, as){
  1602. at.$.back(-1).get(id);
  1603. cat.soul(id);
  1604. delete as.stun[cat.path];
  1605. as.batch();
  1606. }
  1607. function any(soul, as, msg, eve){
  1608. as = as.as;
  1609. if(!msg.$ || !msg.$._){ return } // TODO: Handle
  1610. if(msg.err){ // TODO: Handle
  1611. Gun.log("Please report this as an issue! Put.any.err");
  1612. return;
  1613. }
  1614. var at = (msg.$._), data = at.put, opt = as.opt||{}, root, tmp;
  1615. if((tmp = as.ref) && tmp._.now){ return }
  1616. if(eve){ eve.stun = true }
  1617. if(as.ref !== as.$){
  1618. tmp = (as.$._).get || at.get;
  1619. if(!tmp){ // TODO: Handle
  1620. Gun.log("Please report this as an issue! Put.no.get"); // TODO: BUG!??
  1621. return;
  1622. }
  1623. as.data = obj_put({}, tmp, as.data);
  1624. tmp = null;
  1625. }
  1626. if(u === data){
  1627. if(!at.get){ return } // TODO: Handle
  1628. if(!soul){
  1629. tmp = at.$.back(function(at){
  1630. if(at.link || at.soul){ return at.link || at.soul }
  1631. as.data = obj_put({}, at.get, as.data);
  1632. });
  1633. as.not = true; // maybe consider this?
  1634. }
  1635. tmp = tmp || at.soul || at.link || at.dub;// || at.get;
  1636. at = tmp? (at.root.$.get(tmp)._) : at;
  1637. as.soul = tmp;
  1638. data = as.data;
  1639. }
  1640. if(!as.not && !(as.soul = as.soul || soul)){
  1641. if(as.path && obj_is(as.data)){
  1642. as.soul = (opt.uuid || as.via.back('opt.uuid') /*|| Gun.text.random*/)();
  1643. } else {
  1644. //as.data = obj_put({}, as.$._.get, as.data);
  1645. if(node_ == at.get){
  1646. as.soul = (at.put||empty)['#'] || at.dub;
  1647. }
  1648. as.soul = as.soul || at.soul || at.link || (opt.uuid || as.via.back('opt.uuid') /*|| Gun.text.random*/)();
  1649. }
  1650. if(!as.soul){ // polyfill async uuid for SEA
  1651. as.via.back('opt.uuid')(function(err, soul){ // TODO: improve perf without anonymous callback
  1652. if(err){ return Gun.log(err) } // Handle error.
  1653. as.ref.put(as.data, as.soul = soul, as);
  1654. });
  1655. return;
  1656. }
  1657. }
  1658. as.ref.put(as.data, as.soul, as);
  1659. }
  1660. var obj = Gun.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map, obj_empty = obj.empty;
  1661. var u, empty = {}, noop = function(){}, iife = function(fn,as){fn.call(as||empty)};
  1662. var node_ = Gun.node._;
  1663. })(USE, './put');
  1664. ;USE(function(module){
  1665. var Gun = USE('./root');
  1666. USE('./chain');
  1667. USE('./back');
  1668. USE('./put');
  1669. USE('./get');
  1670. module.exports = Gun;
  1671. })(USE, './index');
  1672. ;USE(function(module){
  1673. var Gun = USE('./index');
  1674. Gun.chain.on = function(tag, arg, eas, as){
  1675. var gun = this, at = gun._, tmp, act, off;
  1676. if(typeof tag === 'string'){
  1677. if(!arg){ return at.on(tag) }
  1678. act = at.on(tag, arg, eas || at, as);
  1679. if(eas && eas.$){
  1680. (eas.subs || (eas.subs = [])).push(act);
  1681. }
  1682. return gun;
  1683. }
  1684. var opt = arg;
  1685. opt = (true === opt)? {change: true} : opt || {};
  1686. opt.at = at;
  1687. opt.ok = tag;
  1688. //opt.last = {};
  1689. gun.get(ok, opt); // TODO: PERF! Event listener leak!!!?
  1690. return gun;
  1691. }
  1692. function ok(msg, ev){ var opt = this;
  1693. var gun = msg.$, at = (gun||{})._ || {}, data = at.put || msg.put, cat = opt.at, tmp;
  1694. if(u === data){
  1695. return;
  1696. }
  1697. if(tmp = msg.$$){
  1698. tmp = (msg.$$._);
  1699. if(u === tmp.put){
  1700. return;
  1701. }
  1702. data = tmp.put;
  1703. }
  1704. if(opt.change){ // TODO: BUG? Move above the undef checks?
  1705. data = msg.put;
  1706. }
  1707. // DEDUPLICATE // TODO: NEEDS WORK! BAD PROTOTYPE
  1708. //if(tmp.put === data && tmp.get === id && !Gun.node.soul(data)){ return }
  1709. //tmp.put = data;
  1710. //tmp.get = id;
  1711. // DEDUPLICATE // TODO: NEEDS WORK! BAD PROTOTYPE
  1712. //at.last = data;
  1713. if(opt.as){
  1714. opt.ok.call(opt.as, msg, ev);
  1715. } else {
  1716. opt.ok.call(gun, data, msg.get, msg, ev);
  1717. }
  1718. }
  1719. Gun.chain.val = function(cb, opt){
  1720. Gun.log.once("onceval", "Future Breaking API Change: .val -> .once, apologies unexpected.");
  1721. return this.once(cb, opt);
  1722. }
  1723. Gun.chain.once = function(cb, opt){
  1724. var gun = this, at = gun._, data = at.put;
  1725. if(0 < at.ack && u !== data){
  1726. (cb || noop).call(gun, data, at.get);
  1727. return gun;
  1728. }
  1729. if(cb){
  1730. (opt = opt || {}).ok = cb;
  1731. opt.at = at;
  1732. opt.out = {'#': Gun.text.random(9)};
  1733. gun.get(val, {as: opt});
  1734. opt.async = true; //opt.async = at.stun? 1 : true;
  1735. } else {
  1736. Gun.log.once("valonce", "Chainable val is experimental, its behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
  1737. var chain = gun.chain();
  1738. chain._.nix = gun.once(function(){
  1739. chain._.on('in', gun._);
  1740. });
  1741. return chain;
  1742. }
  1743. return gun;
  1744. }
  1745. function val(msg, eve, to){
  1746. if(!msg.$){ eve.off(); return }
  1747. var opt = this.as, cat = opt.at, gun = msg.$, at = gun._, data = at.put || msg.put, link, tmp;
  1748. if(tmp = msg.$$){
  1749. link = tmp = (msg.$$._);
  1750. if(u !== link.put){
  1751. data = link.put;
  1752. }
  1753. }
  1754. if((tmp = eve.wait) && (tmp = tmp[at.id])){ clearTimeout(tmp) }
  1755. eve.ack = (eve.ack||0)+1;
  1756. if(!to && u === data && eve.ack <= (opt.acks || Object.keys(at.root.opt.peers).length)){ return }
  1757. if((!to && (u === data || at.soul || at.link || (link && !(0 < link.ack))))
  1758. || (u === data && (tmp = Object.keys(at.root.opt.peers).length) && (!to && (link||at).ack < tmp))){
  1759. tmp = (eve.wait = {})[at.id] = setTimeout(function(){
  1760. val.call({as:opt}, msg, eve, tmp || 1);
  1761. }, opt.wait || 99);
  1762. return;
  1763. }
  1764. if(link && u === link.put && (tmp = rel.is(data))){ data = Gun.node.ify({}, tmp) }
  1765. eve.rid? eve.rid(msg) : eve.off();
  1766. opt.ok.call(gun || opt.$, data, msg.get);
  1767. }
  1768. Gun.chain.off = function(){
  1769. // make off more aggressive. Warning, it might backfire!
  1770. var gun = this, at = gun._, tmp;
  1771. var cat = at.back;
  1772. if(!cat){ return }
  1773. at.ack = 0; // so can resubscribe.
  1774. if(tmp = cat.next){
  1775. if(tmp[at.get]){
  1776. obj_del(tmp, at.get);
  1777. } else {
  1778. }
  1779. }
  1780. if(tmp = cat.ask){
  1781. obj_del(tmp, at.get);
  1782. }
  1783. if(tmp = cat.put){
  1784. obj_del(tmp, at.get);
  1785. }
  1786. if(tmp = at.soul){
  1787. obj_del(cat.root.graph, tmp);
  1788. }
  1789. if(tmp = at.map){
  1790. obj_map(tmp, function(at){
  1791. if(at.link){
  1792. cat.root.$.get(at.link).off();
  1793. }
  1794. });
  1795. }
  1796. if(tmp = at.next){
  1797. obj_map(tmp, function(neat){
  1798. neat.$.off();
  1799. });
  1800. }
  1801. at.on('off', {});
  1802. return gun;
  1803. }
  1804. var obj = Gun.obj, obj_map = obj.map, obj_has = obj.has, obj_del = obj.del, obj_to = obj.to;
  1805. var rel = Gun.val.link;
  1806. var empty = {}, noop = function(){}, u;
  1807. })(USE, './on');
  1808. ;USE(function(module){
  1809. var Gun = USE('./index');
  1810. Gun.chain.map = function(cb, opt, t){
  1811. var gun = this, cat = gun._, chain;
  1812. if(!cb){
  1813. if(chain = cat.each){ return chain }
  1814. cat.each = chain = gun.chain();
  1815. chain._.nix = gun.back('nix');
  1816. gun.on('in', map, chain._);
  1817. return chain;
  1818. }
  1819. Gun.log.once("mapfn", "Map functions are experimental, their behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
  1820. chain = gun.chain();
  1821. gun.map().on(function(data, key, at, ev){
  1822. var next = (cb||noop).call(this, data, key, at, ev);
  1823. if(u === next){ return }
  1824. if(data === next){ return chain._.on('in', at) }
  1825. if(Gun.is(next)){ return chain._.on('in', next._) }
  1826. chain._.on('in', {get: key, put: next});
  1827. });
  1828. return chain;
  1829. }
  1830. function map(msg){
  1831. if(!msg.put || Gun.val.is(msg.put)){ return this.to.next(msg) }
  1832. if(this.as.nix){ this.off() } // TODO: Ugly hack!
  1833. obj_map(msg.put, each, {at: this.as, msg: msg});
  1834. this.to.next(msg);
  1835. }
  1836. function each(v,k){
  1837. if(n_ === k){ return }
  1838. var msg = this.msg, gun = msg.$, at = gun._, cat = this.at, tmp = at.lex;
  1839. if(tmp && !Gun.text.match(k, tmp['.'] || tmp['#'] || tmp)){ return } // review?
  1840. ((tmp = gun.get(k)._).echo || (tmp.echo = {}))[cat.id] = tmp.echo[cat.id] || cat;
  1841. }
  1842. var obj_map = Gun.obj.map, noop = function(){}, event = {stun: noop, off: noop}, n_ = Gun.node._, u;
  1843. })(USE, './map');
  1844. ;USE(function(module){
  1845. var Gun = USE('./index');
  1846. Gun.chain.set = function(item, cb, opt){
  1847. var gun = this, soul;
  1848. cb = cb || function(){};
  1849. opt = opt || {}; opt.item = opt.item || item;
  1850. if(soul = Gun.node.soul(item)){ item = Gun.obj.put({}, soul, Gun.val.link.ify(soul)) }
  1851. if(!Gun.is(item)){
  1852. if(Gun.obj.is(item)){;
  1853. item = gun.back(-1).get(soul = soul || Gun.node.soul(item) || (gun.back('opt.uuid') || uuid)()).put(item);
  1854. }
  1855. return gun.get(soul || uuid()).put(item, cb, opt);
  1856. }
  1857. item.get(function(soul, o, msg){
  1858. if(!soul){ return cb.call(gun, {err: Gun.log('Only a node can be linked! Not "' + msg.put + '"!')}) }
  1859. gun.put(Gun.obj.put({}, soul, Gun.val.link.ify(soul)), cb, opt);
  1860. },true);
  1861. return item;
  1862. }
  1863. function uuid(){ return Gun.state.lex() + Gun.text.random(7) }
  1864. })(USE, './set');
  1865. ;USE(function(module){
  1866. if(typeof Gun === 'undefined'){ return } // TODO: localStorage is Browser only. But it would be nice if it could somehow plugin into NodeJS compatible localStorage APIs?
  1867. var root, noop = function(){}, store, u;
  1868. try{store = (Gun.window||noop).localStorage}catch(e){}
  1869. if(!store){
  1870. Gun.log("Warning: No localStorage exists to persist data to!");
  1871. store = {setItem: function(k,v){this[k]=v}, removeItem: function(k){delete this[k]}, getItem: function(k){return this[k]}};
  1872. }
  1873. /*
  1874. NOTE: Both `lib/file.js` and `lib/memdisk.js` are based on this design!
  1875. If you update anything here, consider updating the other adapters as well.
  1876. */
  1877. Gun.on('create', function(root){
  1878. // This code is used to queue offline writes for resync.
  1879. // See the next 'opt' code below for actual saving of data.
  1880. var ev = this.to, opt = root.opt;
  1881. if(root.once){ return ev.next(root) }
  1882. if(false === opt.localStorage){ return ev.next(root) } // we want offline resynce queue regardless! // actually, this doesn't help, per @go1dfish 's observation. Disabling for now, will need better solution later.
  1883. opt.prefix = opt.file || 'gun/';
  1884. var gap = Gun.obj.ify(store.getItem('gap/'+opt.prefix)) || {};
  1885. var empty = Gun.obj.empty, id, to, go;
  1886. // add re-sync command.
  1887. if(!empty(gap)){
  1888. var disk = Gun.obj.ify(store.getItem(opt.prefix)) || {}, send = {};
  1889. Gun.obj.map(gap, function(node, soul){
  1890. Gun.obj.map(node, function(val, key){
  1891. send[soul] = Gun.state.to(disk[soul], key, send[soul]);
  1892. });
  1893. });
  1894. setTimeout(function(){
  1895. // TODO: Holy Grail dangling by this thread! If gap / offline resync doesn't trigger, it doesn't work. Ouch, and this is a localStorage specific adapter. :(
  1896. root.on('out', {put: send, '#': root.ask(ack)});
  1897. },1);
  1898. }
  1899. root.on('out', function(msg){
  1900. if(msg.lS){ return } // TODO: for IndexedDB and others, shouldn't send to peers ACKs to our own GETs. // THIS IS BLOCKING BROWSERS REPLYING TO REQUESTS, NO??? CHANGE THIS SOON!! UNDER CONTROLLED CIRCUMSTANCES!! Or maybe in-memory already doe sit?
  1901. if(Gun.is(msg.$) && msg.put && !msg['@']){
  1902. id = msg['#'];
  1903. Gun.graph.is(msg.put, null, map);
  1904. if(!to){ to = setTimeout(flush, opt.wait || 1) }
  1905. }
  1906. this.to.next(msg);
  1907. });
  1908. root.on('ack', ack);
  1909. function ack(ack){ // TODO: This is experimental, not sure if we should keep this type of event hook.
  1910. if(ack.err || !ack.ok){ return }
  1911. var id = ack['@'];
  1912. setTimeout(function(){
  1913. Gun.obj.map(gap, function(node, soul){
  1914. Gun.obj.map(node, function(val, key){
  1915. if(id !== val){ return }
  1916. delete node[key];
  1917. });
  1918. if(empty(node)){
  1919. delete gap[soul];
  1920. }
  1921. });
  1922. flush();
  1923. }, opt.wait || 1);
  1924. };
  1925. ev.next(root);
  1926. var map = function(val, key, node, soul){
  1927. (gap[soul] || (gap[soul] = {}))[key] = id;
  1928. }
  1929. var flush = function(){
  1930. clearTimeout(to);
  1931. to = false;
  1932. try{store.setItem('gap/'+opt.prefix, JSON.stringify(gap));
  1933. }catch(e){ Gun.log(err = e || "localStorage failure") }
  1934. }
  1935. });
  1936. Gun.on('create', function(root){
  1937. this.to.next(root);
  1938. var opt = root.opt;
  1939. if(root.once){ return }
  1940. if(false === opt.localStorage){ return }
  1941. opt.prefix = opt.file || 'gun/';
  1942. var graph = root.graph, acks = {}, count = 0, to;
  1943. var disk = Gun.obj.ify(store.getItem(opt.prefix)) || {};
  1944. var lS = function(){}, u;
  1945. root.on('localStorage', disk); // NON-STANDARD EVENT!
  1946. root.on('put', function(msg){
  1947. this.to.next(msg);
  1948. var put = msg.put, soul = put['#'], key = put['.'], val = put[':'], state = put['>'], tmp;
  1949. disk[soul] = Gun.state.ify(disk[soul], key, state, val, soul);
  1950. if(!msg['@']){ (acks[msg['#']] = (tmp = (msg._||'').lot || {})).lS = (tmp.lS||0)+1; } // only ack non-acks.
  1951. count += 1;
  1952. if(count >= (opt.batch || 1000)){
  1953. return flush();
  1954. }
  1955. if(to){ return }
  1956. to = setTimeout(flush, opt.wait || 1);
  1957. });
  1958. root.on('get', function(msg){
  1959. this.to.next(msg);
  1960. var lex = msg.get, soul, data, u;
  1961. function to(){
  1962. if(!lex || !(soul = lex['#'])){ return }
  1963. //if(0 >= msg.cap){ return }
  1964. var has = lex['.'];
  1965. data = disk[soul] || u;
  1966. if(data && has){
  1967. data = Gun.state.to(data, has);
  1968. }
  1969. //if(!data && !Gun.obj.empty(opt.peers)){ return } // if data not found, don't ack if there are peers. // Hmm, what if we have peers but we are disconnected?
  1970. root.on('in', {'@': msg['#'], put: Gun.graph.node(data), lS:1});// || root.$});
  1971. };
  1972. Gun.debug? setTimeout(to,1) : to();
  1973. });
  1974. var map = function(val, key, node, soul){
  1975. disk[soul] = Gun.state.to(node, key, disk[soul]);
  1976. }
  1977. var flush = function(data){
  1978. var err;
  1979. count = 0;
  1980. clearTimeout(to);
  1981. to = false;
  1982. var ack = acks;
  1983. acks = {};
  1984. if(data){ disk = data }
  1985. try{store.setItem(opt.prefix, JSON.stringify(disk));
  1986. }catch(e){
  1987. Gun.log(err = (e || "localStorage failure") + " Consider using GUN's IndexedDB plugin for RAD for more storage space, https://gun.eco/docs/RAD#install");
  1988. root.on('localStorage:error', {err: err, file: opt.prefix, flush: disk, retry: flush});
  1989. }
  1990. if(!err && !Gun.obj.empty(opt.peers)){ return } // only ack if there are no peers.
  1991. Gun.obj.map(ack, function(yes, id){
  1992. if(yes){
  1993. if(yes.more){ acks[id] = yes; return }
  1994. if(yes.s !== yes.lS){ err = "localStorage batch not same." }
  1995. }
  1996. root.on('in', {
  1997. '@': id,
  1998. err: err,
  1999. ok: 0 // localStorage isn't reliable, so make its `ok` code be a low number.
  2000. });
  2001. });
  2002. }
  2003. });
  2004. })(USE, './adapters/localStorage');
  2005. ;USE(function(module){
  2006. var Type = USE('../type');
  2007. function Mesh(root){
  2008. var mesh = function(){};
  2009. var opt = root.opt || {};
  2010. opt.log = opt.log || console.log;
  2011. opt.gap = opt.gap || opt.wait || 0;
  2012. opt.pack = opt.pack || (opt.memory? (opt.memory * 1000 * 1000) : 1399000000) * 0.3; // max_old_space_size defaults to 1400 MB.
  2013. opt.puff = opt.puff || 9; // IDEA: do a start/end benchmark, divide ops/result.
  2014. var puff = setTimeout.puff || setTimeout;
  2015. var dup = root.dup, dup_check = dup.check, dup_track = dup.track;
  2016. var hear = mesh.hear = function(raw, peer){
  2017. if(!raw){ return }
  2018. if(opt.pack <= raw.length){ return mesh.say({dam: '!', err: "Message too big!"}, peer) }
  2019. var msg, id, hash, tmp = raw[0], DBG;
  2020. if(mesh === this){ hear.d += raw.length||0 ; ++hear.c } // STATS!
  2021. if('[' === tmp){
  2022. try{msg = JSON.parse(raw)}catch(e){opt.log('DAM JSON parse error', e)}
  2023. raw = '';
  2024. if(!msg){ return }
  2025. console.STAT && console.STAT(+new Date, msg.length, '# on hear batch');
  2026. var P = opt.puff;
  2027. (function go(){
  2028. var S = +new Date;
  2029. //var P = peer.puff || opt.puff, s = +new Date; // TODO: For future, but in mix?
  2030. var i = 0, m; while(i < P && (m = msg[i++])){ hear(m, peer) }
  2031. //peer.puff = Math.ceil((+new Date - s)? P * 1.1 : P * 0.9);
  2032. msg = msg.slice(i); // slicing after is faster than shifting during.
  2033. console.STAT && console.STAT(S, +new Date - S, 'hear loop');
  2034. flush(peer); // force send all synchronously batched acks.
  2035. if(!msg.length){ return }
  2036. puff(go, 0);
  2037. }());
  2038. return;
  2039. }
  2040. if('{' === tmp || ((raw['#'] || obj_is(raw)) && (msg = raw))){
  2041. try{msg = msg || JSON.parse(raw);
  2042. }catch(e){return opt.log('DAM JSON parse error', e)}
  2043. if(!msg){ return }
  2044. if(msg.DBG){ msg.DBG = DBG = {DBG: msg.DBG} }
  2045. DBG && (DBG.hp = +new Date);
  2046. if(!(id = msg['#'])){ id = msg['#'] = Type.text.random(9) }
  2047. if(tmp = dup_check(id)){ return }
  2048. /*if(!(hash = msg['##']) && u !== msg.put){ hash = msg['##'] = Type.obj.hash(msg.put) }
  2049. if(hash && (tmp = msg['@'] || (msg.get && id))){ // Reduces backward daisy in case varying hashes at different daisy depths are the same.
  2050. if(dup.check(tmp+hash)){ return }
  2051. dup.track(tmp+hash, true).it = it(msg); // GUN core also dedups, so `true` is needed. // Does GUN core need to dedup anymore?
  2052. }
  2053. if(tmp = msg['><']){ (msg._).to = Type.obj.map(tmp.split(','), tomap) }
  2054. */ // TOOD: COME BACK TO THIS LATER!!! IMPORTANT MESH STUFF!!
  2055. (msg._ = function(){}).via = mesh.leap = peer;
  2056. if(tmp = msg.dam){
  2057. if(tmp = mesh.hear[tmp]){
  2058. tmp(msg, peer, root);
  2059. }
  2060. dup_track(id);
  2061. return;
  2062. }
  2063. var S = +new Date, ST;
  2064. DBG && (DBG.is = S);
  2065. root.on('in', msg);
  2066. //ECHO = msg.put || ECHO; !(msg.ok !== -3740) && mesh.say({ok: -3740, put: ECHO, '@': msg['#']}, peer);
  2067. DBG && (DBG.hd = +new Date);
  2068. console.STAT && (ST = +new Date - S) > 9 && console.STAT(S, ST, 'msg'); // TODO: PERF: caught one > 1.5s on tgif
  2069. dup_track(id).via = peer;
  2070. mesh.leap = null; // warning! mesh.leap could be buggy.
  2071. }
  2072. }
  2073. var tomap = function(k,i,m){m(k,true)};
  2074. var noop = function(){};
  2075. hear.c = hear.d = 0;
  2076. ;(function(){
  2077. var SMIA = 0;
  2078. var message, loop;
  2079. function each(peer){ mesh.say(message, peer) }
  2080. var say = mesh.say = function(msg, peer){
  2081. if(this.to){ this.to.next(msg) } // compatible with middleware adapters.
  2082. if(!msg){ return false }
  2083. var id, hash, tmp, raw;
  2084. var DBG = msg.DBG, S; if(!peer){ S = +new Date ; DBG && (DBG.y = S) }
  2085. var meta = msg._||(msg._=function(){});
  2086. if(!(id = msg['#'])){ id = msg['#'] = Type.text.random(9) }
  2087. //if(!(hash = msg['##']) && u !== msg.put){ hash = msg['##'] = Type.obj.hash(msg.put) }
  2088. if(!(raw = meta.raw)){
  2089. raw = mesh.raw(msg);
  2090. /*if(hash && (tmp = msg['@'])){
  2091. dup.track(tmp+hash).it = it(msg);
  2092. if(tmp = (dup.s[tmp]||ok).it){
  2093. if(hash === tmp['##']){ return false }
  2094. tmp['##'] = hash;
  2095. }
  2096. }*/
  2097. }
  2098. S && console.STAT && console.STAT(S, +new Date - S, 'say prep');
  2099. !loop && dup_track(id);//.it = it(msg); // track for 9 seconds, default. Earth<->Mars would need more! // always track, maybe move this to the 'after' logic if we split function.
  2100. //console.log("SEND!", JSON.parse(JSON.stringify(msg)));
  2101. if(!peer && (tmp = msg['@'])){ peer = ((tmp = dup.s[tmp]) && (tmp.via || ((tmp = tmp.it) && (tmp = tmp._) && tmp.via))) || mesh.leap } // warning! mesh.leap could be buggy!
  2102. if(!peer && msg['@']){
  2103. console.STAT && console.STAT(+new Date, ++SMIA, 'total no peer to ack to');
  2104. return false;
  2105. } // TODO: Temporary? If ack via trace has been lost, acks will go to all peers, which trashes browser bandwidth. Not relaying the ack will force sender to ask for ack again. Note, this is technically wrong for mesh behavior.
  2106. if(!peer && mesh.way){ return mesh.way(msg) }
  2107. if(!peer || !peer.id){ message = msg;
  2108. if(!Type.obj.is(peer || opt.peers)){ return false }
  2109. var P = opt.puff, ps = opt.peers, pl = Object.keys(peer || opt.peers || {}); // TODO: BETTER PERF? No object.keys? It is polyfilled by Type.js tho.
  2110. ;(function go(){
  2111. var S = +new Date;
  2112. //Type.obj.map(peer || opt.peers, each); // in case peer is a peer list.
  2113. loop = 1; var wr = meta.raw; meta.raw = raw; // quick perf hack
  2114. var i = 0, p; while(i < 9 && (p = (pl||'')[i++])){
  2115. if(!(p = ps[p])){ continue }
  2116. say(msg, p);
  2117. }
  2118. meta.raw = wr; loop = 0;
  2119. pl = pl.slice(i); // slicing after is faster than shifting during.
  2120. console.STAT && console.STAT(S, +new Date - S, 'say loop');
  2121. if(!pl.length){ return }
  2122. puff(go, 0);
  2123. dup_track(msg['@']); // keep for later
  2124. }());
  2125. return;
  2126. }
  2127. // TODO: PERF: consider splitting function here, so say loops do less work.
  2128. if(!peer.wire && mesh.wire){ mesh.wire(peer) }
  2129. if(id === peer.last){ return } peer.last = id; // was it just sent?
  2130. if(peer === meta.via){ return false } // don't send back to self.
  2131. if((tmp = meta.to) && (tmp[peer.url] || tmp[peer.pid] || tmp[peer.id]) /*&& !o*/){ return false }
  2132. if(peer.batch){
  2133. peer.tail = (tmp = peer.tail || 0) + raw.length;
  2134. if(peer.tail <= opt.pack){
  2135. //peer.batch.push(raw);
  2136. peer.batch += (tmp?',':'')+raw; // TODO: Prevent double JSON! // FOR v1.0 !?
  2137. return;
  2138. }
  2139. flush(peer);
  2140. }
  2141. //peer.batch = [];
  2142. peer.batch = '['; // TODO: Prevent double JSON!
  2143. var S = +new Date, ST;
  2144. setTimeout(function(){
  2145. console.STAT && (ST = +new Date - S) > 9 && console.STAT(S, ST, '0ms TO', id, peer.id);
  2146. flush(peer);
  2147. }, opt.gap);
  2148. send(raw, peer);
  2149. }
  2150. mesh.say.c = mesh.say.d = 0;
  2151. }());
  2152. function flush(peer){
  2153. var tmp = peer.batch, t = 'string' == typeof tmp, l;
  2154. if(t){ tmp += ']' }// TODO: Prevent double JSON!
  2155. peer.batch = peer.tail = null;
  2156. if(!tmp){ return }
  2157. if(t? 3 > tmp.length : !tmp.length){ return } // TODO: ^
  2158. if(!t){try{tmp = (1 === tmp.length? tmp[0] : JSON.stringify(tmp));
  2159. }catch(e){return opt.log('DAM JSON stringify error', e)}}
  2160. if(!tmp){ return }
  2161. send(tmp, peer);
  2162. }
  2163. // for now - find better place later.
  2164. function send(raw, peer){ try{
  2165. var wire = peer.wire;
  2166. if(peer.say){
  2167. peer.say(raw);
  2168. } else
  2169. if(wire.send){
  2170. wire.send(raw);
  2171. }
  2172. mesh.say.d += raw.length||0; ++mesh.say.c; // STATS!
  2173. }catch(e){
  2174. (peer.queue = peer.queue || []).push(raw);
  2175. }}
  2176. ;(function(){
  2177. // TODO: this caused a out-of-memory crash!
  2178. mesh.raw = function(msg){ // TODO: Clean this up / delete it / move logic out!
  2179. if(!msg){ return '' }
  2180. var meta = (msg._) || {}, put, hash, tmp;
  2181. if(tmp = meta.raw){ return tmp }
  2182. if('string' == typeof msg){ return msg }
  2183. /*if(!msg.dam){ // TOOD: COME BACK TO THIS LATER!!! IMPORTANT MESH STUFF!!
  2184. var i = 0, to = []; Type.obj.map(opt.peers, function(p){
  2185. to.push(p.url || p.pid || p.id); if(++i > 3){ return true } // limit server, fast fix, improve later! // For "tower" peer, MUST include 6 surrounding ids. // REDUCED THIS TO 3 for temporary relay peer performance, towers still should list neighbors.
  2186. }); if(i > 1){ msg['><'] = to.join() }
  2187. }*/ // TOOD: COME BACK TO THIS LATER!!! IMPORTANT MESH STUFF!!
  2188. var raw = $(msg); // optimize by reusing put = the JSON.stringify from .hash?
  2189. /*if(u !== put){
  2190. tmp = raw.indexOf(_, raw.indexOf('put'));
  2191. raw = raw.slice(0, tmp-1) + put + raw.slice(tmp + _.length + 1);
  2192. //raw = raw.replace('"'+ _ +'"', put); // NEVER USE THIS! ALSO NEVER DELETE IT TO NOT MAKE SAME MISTAKE! https://github.com/amark/gun/wiki/@$$ Heisenbug
  2193. }*/
  2194. // TODO: PERF: tgif, CPU way too much on re-JSONifying ^ it.
  2195. /*
  2196. // NOTE TO SELF: Switch NTS to DAM now.
  2197. */
  2198. if(meta && (raw||'').length < (1000 * 100)){ meta.raw = raw } // HNPERF: If string too big, don't keep in memory.
  2199. return raw;
  2200. }
  2201. var $ = JSON.stringify, _ = ':])([:';
  2202. }());
  2203. mesh.hi = function(peer){
  2204. var tmp = peer.wire || {};
  2205. if(peer.id){
  2206. opt.peers[peer.url || peer.id] = peer;
  2207. } else {
  2208. tmp = peer.id = peer.id || Type.text.random(9);
  2209. mesh.say({dam: '?', pid: root.opt.pid}, opt.peers[tmp] = peer);
  2210. delete dup.s[peer.last]; // IMPORTANT: see https://gun.eco/docs/DAM#self
  2211. }
  2212. peer.met = peer.met || +(new Date);
  2213. if(!tmp.hied){ root.on(tmp.hied = 'hi', peer) }
  2214. // @rogowski I need this here by default for now to fix go1dfish's bug
  2215. tmp = peer.queue; peer.queue = [];
  2216. Type.obj.map(tmp, function(msg){
  2217. send(msg, peer);
  2218. });
  2219. Type.obj.native && Type.obj.native(); // dirty place to check if other JS polluted.
  2220. }
  2221. mesh.bye = function(peer){
  2222. root.on('bye', peer);
  2223. var tmp = +(new Date); tmp = (tmp - (peer.met||tmp));
  2224. mesh.bye.time = ((mesh.bye.time || tmp) + tmp) / 2;
  2225. }
  2226. mesh.hear['!'] = function(msg, peer){ opt.log('Error:', msg.err) }
  2227. mesh.hear['?'] = function(msg, peer){
  2228. if(msg.pid){
  2229. if(!peer.pid){ peer.pid = msg.pid }
  2230. if(msg['@']){ return }
  2231. }
  2232. mesh.say({dam: '?', pid: opt.pid, '@': msg['#']}, peer);
  2233. delete dup.s[peer.last]; // IMPORTANT: see https://gun.eco/docs/DAM#self
  2234. }
  2235. root.on('create', function(root){
  2236. root.opt.pid = root.opt.pid || Type.text.random(9);
  2237. this.to.next(root);
  2238. root.on('out', mesh.say);
  2239. });
  2240. root.on('bye', function(peer, tmp){
  2241. peer = opt.peers[peer.id || peer] || peer;
  2242. this.to.next(peer);
  2243. peer.bye? peer.bye() : (tmp = peer.wire) && tmp.close && tmp.close();
  2244. Type.obj.del(opt.peers, peer.id);
  2245. peer.wire = null;
  2246. });
  2247. var gets = {};
  2248. root.on('bye', function(peer, tmp){ this.to.next(peer);
  2249. if(!(tmp = peer.url)){ return } gets[tmp] = true;
  2250. setTimeout(function(){ delete gets[tmp] },opt.lack || 9000);
  2251. });
  2252. root.on('hi', function(peer, tmp){ this.to.next(peer);
  2253. if(!(tmp = peer.url) || !gets[tmp]){ return } delete gets[tmp];
  2254. if(opt.super){ return } // temporary (?) until we have better fix/solution?
  2255. Type.obj.map(root.next, function(node, soul){
  2256. tmp = {}; tmp[soul] = root.graph[soul];
  2257. mesh.say({'##': Type.obj.hash(tmp), get: {'#': soul}}, peer);
  2258. })
  2259. });
  2260. return mesh;
  2261. }
  2262. ;(function(){
  2263. var $ = JSON.stringify, u;
  2264. Type.obj.hash = function(obj, hash){
  2265. if(!hash && u === (obj = $(obj, sort))){ return }
  2266. return Type.text.hash(hash || obj || '');
  2267. }
  2268. function sort(k, v){ var tmp;
  2269. if(!(v instanceof Object)){ return v }
  2270. var S = +new Date;
  2271. Type.obj.map(Object.keys(v).sort(), map, {to: tmp = {}, on: v});
  2272. console.STAT && console.STAT(S, +new Date - S, 'sort');
  2273. return tmp;
  2274. }
  2275. Type.obj.hash.sort = sort;
  2276. function map(k){
  2277. this.to[k] = this.on[k];
  2278. }
  2279. }());
  2280. function it(msg){ return msg || {_: msg._, '##': msg['##']} } // HNPERF: Only need some meta data, not full reference (took up too much memory). // HNPERF: Garrrgh! We add meta data to msg over time, copying the object happens to early.
  2281. var empty = {}, ok = true, u;
  2282. var obj_is = Type.obj.is, obj_map = Type.obj.map;
  2283. try{ module.exports = Mesh }catch(e){}
  2284. })(USE, './adapters/mesh');
  2285. ;USE(function(module){
  2286. var Gun = USE('../index');
  2287. Gun.Mesh = USE('./mesh');
  2288. Gun.on('opt', function(root){
  2289. this.to.next(root);
  2290. var opt = root.opt;
  2291. if(root.once){ return }
  2292. if(false === opt.WebSocket){ return }
  2293. var env;
  2294. if(typeof window !== "undefined"){ env = window }
  2295. if(typeof global !== "undefined"){ env = global }
  2296. env = env || {};
  2297. var websocket = opt.WebSocket || env.WebSocket || env.webkitWebSocket || env.mozWebSocket;
  2298. if(!websocket){ return }
  2299. opt.WebSocket = websocket;
  2300. var mesh = opt.mesh = opt.mesh || Gun.Mesh(root);
  2301. var wire = mesh.wire || opt.wire;
  2302. mesh.wire = opt.wire = open;
  2303. function open(peer){ try{
  2304. if(!peer || !peer.url){ return wire && wire(peer) }
  2305. var url = peer.url.replace('http', 'ws');
  2306. var wire = peer.wire = new opt.WebSocket(url);
  2307. wire.onclose = function(){
  2308. opt.mesh.bye(peer);
  2309. reconnect(peer);
  2310. };
  2311. wire.onerror = function(error){
  2312. reconnect(peer);
  2313. };
  2314. wire.onopen = function(){
  2315. opt.mesh.hi(peer);
  2316. }
  2317. wire.onmessage = function(msg){
  2318. if(!msg){ return }
  2319. opt.mesh.hear(msg.data || msg, peer);
  2320. };
  2321. return wire;
  2322. }catch(e){}}
  2323. setTimeout(function(){ root.on('out', {dam:'hi'}) },1); // it can take a while to open a socket, so maybe no longer lazy load for perf reasons?
  2324. var wait = 2 * 1000;
  2325. function reconnect(peer){
  2326. clearTimeout(peer.defer);
  2327. if(doc && peer.retry <= 0){ return } peer.retry = (peer.retry || opt.retry || 60) - 1;
  2328. peer.defer = setTimeout(function to(){
  2329. if(doc && doc.hidden){ return setTimeout(to,wait) }
  2330. open(peer);
  2331. }, wait);
  2332. }
  2333. var doc = 'undefined' !== typeof document && document;
  2334. });
  2335. var noop = function(){};
  2336. })(USE, './adapters/websocket');
  2337. }());