@ibgib/space-gib 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ var Cd=Object.defineProperty;var b=(o,t)=>Cd(o,"name",{value:t,configurable:!0});var Ie=/^[a-zA-Z0-9_\-.]{1,256}$/,zt=/^[a-zA-Z0-9_]{1,255}$/,Xs=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,qs=/^(\[.+\]).+$/,Ys=/^[0-9a-fA-F]{32}$/,Ws=/^[0-9a-fA-F]{64}$/;var Pr="/",zs="_nonalphanumerics_";var Rr=!1,Js=globalThis.crypto,{subtle:Nd}=Js,De={sha_256:"SHA-256",sha_512:"SHA-512"};function U(o){return JSON.parse(JSON.stringify(o))}b(U,"clone");function Ce(o){return(o??new Date).toUTCString()}b(Ce,"getTimestamp");async function _e({s:o,algorithm:t="SHA-256"}){if(!o)return"";try{let e=Object.values(De);if(!e.includes(t))throw new Error(`Only ${e} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let r=new TextEncoder().encode(o),n=await Nd.digest(t,r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(e){throw console.error(w(e.message)),e}}b(_e,"hash");async function V(o=64){let t="";if(o<32)throw new Error("Seed size must be at least 32");if(!globalThis.crypto)throw new Error("Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)");let e=Js.getRandomValues(new Uint8Array(16));if(t=await _e({s:e.join("")}),!t)throw new Error("Did not create UUID...hmm...");return t}b(V,"getUUID");function F(o){return JSON.stringify(o,null,2)}b(F,"pretty");async function Se(o){return new Promise(t=>{setTimeout(()=>{t()},o)})}b(Se,"delay");function w(o){return!o&&o!==0?"[error is falsy]":typeof o=="string"?o:typeof o.message=="string"?o.message:typeof o=="number"?JSON.stringify(o):o.error?(console.warn(`[${w.name}] this fn takes the raw error object. no destructure required. change your call from extractErrorMsg({error}) to extractErrorMsg(error). (W: ea49af5fd76d4b80a55a108d73a3e9b4)`),w(o.error)):`[error is not a string and error.message is not a string. typeof error: ${typeof o} (E: d5a7723ca59646838308bc9e53a43134)]`}b(w,"extractErrorMsg");function Qn({items:o,keyFn:t}){let e=`[${Qn.name}]`;try{let r={};for(let n=0;n<o.length;n++){let a=o[n],s=t(a);r[s]=[...r[s]??[],a]}return r}catch(r){throw console.error(`${e} ${r.message}`),r}}b(Qn,"groupBy");function Lo({min:o,max:t,chars:e,noSpaces:r}){return o=o??1,t=t??999999999999,e=e??"",r?new RegExp(`^[\\w${e}]{${o},${t}}$`):new RegExp(`^[\\w\\s${e}]{${o},${t}}$`)}b(Lo,"getRegExp");function rt(o){let t;if(o){if(t=new Date(o),t.toString()==="Invalid Date")throw new Error(`invalid date created by timestamp (${o}) (E: cbd6aeefe00708184e276ea3c2532b22)`)}else t=new Date;return t.getTime().toString()}b(rt,"getTimestampInTicks");function ea({startDate:o,years:t,months:e,days:r,hours:n,seconds:a}){let s=`[${ea.name}]`;try{return mr({startDate:o,years:t,months:e,days:r,hours:n,seconds:a}).toUTCString()}catch(i){throw console.log(`${s} ${i.message}`),i}}b(ea,"getExpirationUTCString");function mr({startDate:o,years:t,months:e,days:r,hours:n,seconds:a}){let s=`[${mr.name}]`;try{if(!o&&!t&&!e&&!r&&!n&&!a)throw new Error("either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)");o=o?new Date(o):new Date;let i,c;return t?(i=o.getFullYear()+t,c=o.setFullYear(i),mr({startDate:new Date(c),months:e,days:r,hours:n,seconds:a})):e?(i=o.getMonth()+e,c=o.setMonth(i),mr({startDate:new Date(c),years:t,days:r,hours:n,seconds:a})):r?(i=o.getDate()+r,c=o.setDate(i),mr({startDate:new Date(c),years:t,months:e,hours:n,seconds:a})):n?(i=o.getHours()+n,c=o.setHours(i),mr({startDate:new Date(c),years:t,months:e,days:r,seconds:a})):a?(i=o.getSeconds()+a,c=o.setSeconds(i),mr({startDate:new Date(c),years:t,months:e,days:r,hours:n})):o}catch(i){throw console.log(`${s} ${i.message}`),i}}b(mr,"addTimeToDate");function ta({expirationTimestampUTC:o}){let t=`[${ta.name}]`;try{if(!o)throw new Error("expirationTimestampUTC required (E: 5eeb1e29f93d64f70c71a8112080a222)");let e=new Date(o);if(e.toUTCString()==="Invalid Date")throw new Error(`invalid expirationTimestampUTC: ${o} (E: 66a1a165bcf1f9336fe78856ab777822)`);return e<new Date}catch(e){throw console.error(`${t} ${e.message}`),e}}b(ta,"isExpired");function Po(o){return Array.from(new Set(o))}b(Po,"unique");function ra({obj:o,value:t,path:e,pathDelimiter:r,logalot:n}){let a=`[${ra.name}]`;try{if(n&&console.log(`${a} starting...`),!o)throw new Error("obj required (E: 6a9dd32a361476e80b1bf7b91ec50522)");if(typeof o!="object")throw new Error("obj must be type 'object' (E: 66fdc289b32c06492bd95f5d266e6a22)");if(!e)throw new Error("path required (at the very least should be the key in the root obj.) (E: fc779e7794ead8a0b44e5f2e776b0e22)");r=r||Pr;let s=o,i=e.split(r).filter(l=>!!l),c=i.pop();i.forEach(l=>{let d=s[l];if(d){if(typeof d!="object")throw new Error(`invalid path into object. Each step along the path must be typeof === 'object', but typeof targetObj["${l}"] === ${typeof d}. (value: ${d}) (E: 38cf29c5f624a40b4b56502c2ec39d22)`)}else s[l]={};s=s[l]}),s[c]=t}catch(s){throw console.error(`${a} ${s.message}`),s}finally{n&&console.log(`${a} complete.`)}}b(ra,"patchObject");async function no({n:o}){let t=`[${no.name}]`;try{Rr&&console.log(`${t} starting...`);let e=[];for(let r=0;r<o;r++){let n=await V();e.push(n.substring(0,16))}return e}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Rr&&console.log(`${t} complete.`)}}b(no,"getIdPool");function Dd({text:o,length:t,keepLiterals:e=["-"],replaceMap:r}){let n=`[${Dd.name}]`;try{if(Rr&&console.log(`${n} starting... (I: 27437e312e5aa621adfebb84e059c822)`),!o)throw new Error("text required (E: 87e0493613c8b30dfade83e1d2862a22)");let a=o,s={};e=e??[];for(let c=0;c<e.length;c++){let l=e[c],d;do d=Zs({count:10});while(d.includes(l)||l.includes(d)||o.includes(d));if(a.includes(l))for(s[d]=l;a.includes(l);)a=a.replace(l,d)}if(r&&Object.keys(r).length>0)for(let c=0;c<Object.keys(r).length;c++){let l=Object.keys(r)[c],d=r[l];for(;a.includes(l);)a=a.replace(l,d)}a=a.replace(/\W/g,"");let i=Object.keys(s);for(let c=0;c<i.length;c++){let l=i[c];for(;a.includes(l);)a=a.replace(l,s[l])}return t&&t>0&&a.length>t&&(Rr&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),a=a.substring(0,t)),a.length===0&&(a=zs),a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{Rr&&console.log(`${n} complete.`)}}b(Dd,"getSaferSubstring");function Od({x:o}){if((o??[]).length===0)return;let t=Math.floor(Math.random()*o.length);return o[t]}b(Od,"pickRandom");function Zs({count:o}){let t=`${Zs.name}]`;try{if(!Number.isInteger(o))throw new Error("count required to be a number. (E: c0a21d884ebd9afc4b2e8025207e0522)");let e="";for(let r=0;r<o;r++)e+=Od({x:"a b c d e f g h i j k l m n o p q r s t u v w x y z".split(" ")});if(e.length!==o)throw new Error(`${t} (UNEXPECTED) result.length !== count ? (E: 9bec4ec8f78610d8055e565415392a22)`);return e}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Rr&&console.log(`${t} complete.`)}}b(Zs,"pickRandom_Letters");function Br({dominant:o,recessive:t}){let e=`[${Br.name}]`;try{if(Array.isArray(o)&&Array.isArray(t)){let r=U(o),n=!1;return t.forEach(a=>{if(typeof a=="string")r.includes(a)||r.push(a);else{n||(console.warn(`${e} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`),n=!0);let s=JSON.stringify(a);r.some(i=>JSON.stringify(i)===s)||r.push(a)}}),r}else if(typeof o=="object"&&typeof t=="object"){let r={...t},n=Object.keys(o),a=Object.keys(t);return n.forEach(s=>{a.includes(s)?Array.isArray(o[s])&&Array.isArray(t[s])?r[s]=Br({dominant:o[s],recessive:t[s]}):o[s]&&!Array.isArray(o[s])&&typeof o[s]=="object"&&t[s]&&!Array.isArray(t[s])&&typeof t[s]=="object"?r[s]=Br({dominant:o[s],recessive:t[s]}):r[s]=o[s]:r[s]=o[s]}),r}else return console.warn(`${e} unknown values or value types do not match. Both should either be an array or map. Dominant one wins categorically without any merging. (W: 3690ea19b81a4b89b98c1940637df62c)`),o}catch(r){throw console.error(`${e} ${r.message}`),r}}b(Br,"mergeMapsOrArrays_Naive");var Ld=globalThis.crypto,{subtle:ti}=Ld,ri=new Array(256);for(let o=0;o<256;++o)ri[o]=o.toString(16).padStart(2,"0");function oi(o){let t=new Uint8Array(o),e="";for(let r=0;r<t.length;r++)e+=ri[t[r]];return e}b(oi,"bufToHex");function so(o){if(o===null||typeof o!="object")return o;if(Array.isArray(o))return o.map(r=>so(r));let t={},e=Object.keys(o).sort();for(let r of e){let n=o[r];n!==void 0&&(t[r]=so(n))}return t}b(so,"toNormalizedForHashing");async function ao(o){if(!o)return"";let t=new TextEncoder().encode(o),e=await ti.digest("SHA-256",t);return oi(e)}b(ao,"hashToHex");async function Pd(o,t){let e;if(o){let n=new TextEncoder().encode(o);e=new Uint8Array(n.length+t.length),e.set(n),e.set(t,n.length)}else e=t;let r=await ti.digest("SHA-256",e);return oi(r)}b(Pd,"hashToHex_Uint8Array");var Rd=!1,Ro=0,Qs=0;async function ei(o,t=""){let e=t||"",r=o.ib,n=o.data,a=o.rel8ns,s=Object.keys(a||{}).length>0&&Object.keys(a||{}).some(p=>a[p]&&a[p].length>0),i=!!n;i&&(typeof n=="string"?i=n.length>0:n instanceof Uint8Array?i=!0:typeof n=="object"?i=Object.keys(n||{}).length>0:i=!0);let c=(await ao(e?e+r:r)).toUpperCase(),l="";if(s){let p=so(a),h=JSON.stringify(p);l=(await ao(e?e+h:h)).toUpperCase()}let d="";if(i)if(n instanceof Uint8Array)d=(await Pd(e,n)).toUpperCase();else{let p=so(n),h=JSON.stringify(p);d=(await ao(e?e+h:h)).toUpperCase()}let f;if(s||i){let p=c+l+d;f=(await ao(e?e+p:p)).toUpperCase()}else f=(await ao(e?e+c:c)).toUpperCase();return f}b(ei,"sha256v1_Internal");async function Jt(o,t=""){if(Rd){let e=globalThis.performance?globalThis.performance.now():Date.now(),r=await ei(o,t),n=(globalThis.performance?globalThis.performance.now():Date.now())-e;return Ro++,Qs+=n,Ro%1e3===0&&console.log(`[sha256v1 Profile] Total Runs: ${Ro} | Average Duration: ${(Qs/Ro).toFixed(4)} ms`),r}return ei(o,t)}b(Jt,"sha256v1");function y({ib:o,gib:t,ibGib:e,delimiter:r="^"}){return o=o||e?.ib||"",t=t||e?.gib||"",o+r+t}b(y,"getIbGibAddr");function J({ibGib:o,ibGibAddr:t,delimiter:e="^"}){let r="[getIbAndGib]";if(!t)if(o)t=y({ibGib:o});else throw new Error(`${r} We need either an address or an ibGib object`);if(!t)throw new Error(`${r} Couldn't get ibGibAddr. ibGib invalid?`);e||(e="^");let n=t.split(e);return n.length===2?{ib:n[0],gib:n[1]}:n.length===1&&t.endsWith(e)?{ib:n[0],gib:""}:n.length===1&&t.startsWith(e)?{ib:"",gib:n[0]}:n.length===2&&n[0]===""&&n[1]===""?{ib:e,gib:""}:(console.warn(`${r} multiple delimiters found in ibGibAddr. Considering last delimiter as the demarcation of gib hash`),{ib:n.slice(0,n.length-1).join(e),gib:n.slice(n.length-1)[0]})}b(J,"getIbAndGib");var pe;(function(o){o.past="past",o.ancestor="ancestor",o.dna="dna",o.identity="identity",o.tjp="tjp",o.secret="secret",o.encryption="encryption"})(pe||(pe={}));var kr="ib",z="gib",j={ib:kr,gib:z},Ae="^",At=".",ni="ib^gib",Er=["past","ancestor","dna","tjp"],Bd=155,ai=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${Bd}}$`);async function wr(o){let t=U(o),e=`[${wr.name}]`;t.srcAddr&&delete t.srcAddr,delete t.src;let r={ib:t.type,data:t,rel8ns:{ancestor:[`${t.type.toString()}${Ae}${z}`]}};return r.gib=await Jt(r),r}b(wr,"buildDna");function oa({ibGib:o}){let t=`[${oa.name}]`;try{if(!o)throw new Error("ibGib required.");let e=["fork","mut8","rel8","plan"].map(n=>`${n}^${z}`);return o.rel8ns&&o.rel8ns.ancestor&&Array.isArray(o.rel8ns.ancestor)&&o.rel8ns.ancestor.some(n=>e.includes(n))||!1}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(oa,"isDna");function ue({ibGib:o,gib:t}){return o?ue({gib:o.gib}):t?t===z:!0}b(ue,"isPrimitive");async function ce({ibGib:o,hasTjp:t,tjpAddr:e,gibDelimiter:r,isPrimitive:n,hashAlgorithm:a}){let s=`[${ce.name}]`;try{if(!o)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return z;let i=await Jt(o,""),c=o.rel8ns??{},l=o.data??{};if(r=r||At,t||(t=(c.tjp??[]).length>0||l.isTjp||!1),t){let d;if(c.tjp)if(c.tjp.length===1)if(c.tjp[0])e=c.tjp[0];else throw new Error("rel8ns.tjp[0] is falsy. (E: ed879d2b039543f8b1902e8b7b5a5a7b)");else if(c.tjp.length>1)if(c.tjp[c.tjp.length-1])console.warn(`${s} found more than one tjp addr...only expecting 1 ATOW. (W: 10ed43f716e743e0afd1954f1ab46789)`),e=c.tjp[c.tjp.length-1];else throw new Error("multiple tjp addrs, and the last (most recent) one is falsy. (E: bc835dc89be24075bba8b2b6616ea069)");else throw new Error("hasTjp is true but rel8ns.tjp is empty array. (E: d08b2f9e86494814b5e7d7b4602b2ab7)");else if(l.isTjp)e=y({ib:o.ib,gib:i});else throw new Error("hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)");if(d=e?J({ibGibAddr:e}).gib:void 0,d)return l.isTjp?i:`${i}${At}${d}`;throw new Error("hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)")}else return i}catch(i){throw console.error(`${s} ${w(i)}`),i}}b(ce,"getGib");function Oe({ibGibAddr:o,gib:t,gibDelimiter:e}){let r=`[${Oe.name}]`;try{if(!o&&!t)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(t=t||J({ibGibAddr:o}).gib,t===z)return{isPrimitive:!0};if(e=e??At,t.includes(e)){let n=t.split(e);if(n.some(i=>i===""))throw new Error(`unexpected gib that contains gibDelimiter (${e}) but has at least one piece with empty string. (E: 75a94280045541009ee68182d12d3449)`);let a=n.length;return a>2&&console.warn(`${r} gib only expected to have two pieces ATOW. re-examine please. (W: aa4283ac5a5747a386a69966ecdad39d)`),{punctiliarHash:n.splice(0,1)[0],tjpGib:n.join(e),piecesCount:a,delimiter:e}}else return{punctiliarHash:t,piecesCount:1,delimiter:e}}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(Oe,"getGibInfo");async function Bo(o){let{noTimestamp:t,dna:e,linkedRel8ns:r,destIb:n,uuid:a,tjp:s,cloneRel8ns:i,cloneData:c,type:l="fork"}=o,d=o.src,f="[fork_v1]";if(l!=="fork")throw new Error(`${f} not a fork transform.`);if(o.type||(o.type="fork"),!d)throw new Error(`${f} src required to fork.`);if(!d.ib)throw new Error(`${f} src.ib required.`);if(n&&n.includes(Ae))throw new Error(`${f} destIb can't contain (hardcoded) delimiter right now.`);if(!d.gib)throw new Error(`${f} src.gib required.`);let p={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(p.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(p.rel8ns=d.rel8ns),d=p;let h=y({ib:d.ib,gib:d.gib});o.srcAddr=h;let g=i&&d.rel8ns&&Object.keys(d.rel8ns).length>0?U(d.rel8ns):{};delete g.past;let m=c&&d?.data?U(d.data):{};o.nCounter&&(m.n=0);let E=r?.includes(pe.ancestor)?[h]:(g.ancestor||[]).concat([h]);g.ancestor=E,g.tjp&&delete g.tjp;let S=U(d);if(t&&s?.timestamp)throw new Error(`${f} both noTimestamp and tjp.timestamp selected.`);if(!t||s?.timestamp){let $=new Date;m.timestamp=Ce($),m.timestampMs=$.getMilliseconds()}(s?.uuid||a)&&(m.uuid=await V()),s?.uuid||s?.timestamp?m.isTjp=!0:m.isTjp&&delete m.isTjp,S.ib=n||"ib",h!==ni&&(S.rel8ns=g),Object.keys(m).length>0&&(S.data=m);let A=null;if(e){A=await wr(o);let $=y({ibGib:A});g.dna=r?.includes(pe.dna)?g.dna=[$]:g.dna=(g.dna||[]).concat($)}S.gib=await Jt(S,"");let _={newIbGib:S};return A&&(_.dnas=[A]),_}b(Bo,"fork");async function ot(o){let{noTimestamp:t,dna:e,linkedRel8ns:r,dataToRename:n,dataToRemove:a,dataToAddOrPatch:s,mut8Ib:i,type:c="mut8"}=o,l=o.src,d="[mut8_v1]";if(c!=="mut8")throw new Error(`${d} not a mut8 transform.`);if(o.type||(o.type="mut8"),!l)throw new Error(`${d} src required to mut8.`);if(!l.ib)throw new Error(`${d} src.ib required.`);if(l.ib.includes(Ae))throw new Error(`${d} ib can't contain hardcoded delimiter (${Ae}) right now.`);if(!l.gib)throw new Error(`${d} src.gib required.`);if(!i&&!n&&!a&&!s)throw new Error(`${d} gotta provide either a mut8Ib or some data to change.`);let f=y({ib:l.ib,gib:l.gib});if(o.srcAddr&&f!==o.srcAddr)throw new Error(`${d} srcAddr from src does not equal opts.srcAddr`);if(o.srcAddr=f,ue({ibGib:l}))throw new Error(`${d} cannot mutate primitive ibgib`);let p={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(p.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(p.rel8ns=l.rel8ns),l=p;let h=U(l),g=l.rel8ns?l.rel8ns:{},m=U(g);m.past=r?.includes(pe.past)?[f]:(m.past||[]).concat([f]);let E=l?.data?U(l.data):{};if(n&&(E=na(E,n,"rename")),a&&(E=na(E,a,"remove")),s&&(E=si(E,s)),!t){let T=new Date;E.timestamp=Ce(T),E.timestampMs=T.getMilliseconds()}if(o.nCounter||Object.keys(E).includes("n"))if(Object.keys(E).includes("n"))if(Number.isInteger(E.n))E.n>=0?E.n=E.n+1:(console.warn(`${d} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),E.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else E.n=0;if(E.isTjp){let T=m.tjp??[];T.push(f),m.tjp=T,delete E.isTjp}let A=null;if(e){A=await wr(o);let T=y({ibGib:A});m.dna=r?.includes(pe.dna)?m.dna=[T]:m.dna=(m.dna||[]).concat(T)}h.ib=i||h.ib,h.rel8ns=m,Object.keys(E).length>0?h.data=E:delete h.data;let _=(m.tjp?.length??0)>0;h.gib=await ce({ibGib:h,hasTjp:_});let $={newIbGib:h};return A&&($.dnas=[A]),$}b(ot,"mut8");function na(o,t,e){let r="[renameOrRemove]",n=["timestamp"];return Object.keys(t).forEach(a=>{if(n.includes(a))throw new Error(`${r} Cannot rename to ${a}.`);if(Object.keys(o).includes(a)){let s=t[a];if(typeof s=="string"){if(n.includes(s))throw new Error(`${r} Cannot rename to ${s}.`);e==="rename"&&(o[s]=o[a]),delete o[a]}else o[a]=na(o[a],s,e)}else console.log(`${r} key to ${e} does not exist`)}),o}b(na,"renameOrRemove");function si(o,t){return Object.keys(t).forEach(e=>{let r=t[e],n=o[e];n?Array.isArray(r)||Array.isArray(n)?o[e]=r:typeof r=="object"&&typeof n=="object"?o[e]=si(n,r):o[e]=r:o[e]=r}),o}b(si,"patch");async function He(o){let{noTimestamp:t,dna:e,linkedRel8ns:r,rel8nsToAddByAddr:n,rel8nsToRemoveByAddr:a,type:s="rel8"}=o,i=o.src,c="[rel8_v1]";if(s!=="rel8")throw new Error(`${c} not a rel8 transform.`);if(o.type||(o.type="rel8"),s!=="rel8")throw new Error(`${c} not a rel8 transform.`);if(o.type||(o.type="rel8"),!i)throw new Error(`${c} src required.`);if(!i.ib)throw new Error(`${c} src.ib required.`);if(i.ib.includes(Ae))throw new Error(`${c} ib can't contain hardcoded delimiter (${Ae}) right now.`);if(!i.gib)throw new Error(`${c} src.gib required.`);if(ue({ibGib:i}))throw new Error(`${c} cannot relate/unrelate primitive ibgib`);let l=n&&Object.keys(n).length>0,d=a&&Object.keys(a).length>0;if(!(l||d))throw new Error(`${c} gotta provide relations to either add or remove.`);let f=y({ib:i.ib,gib:i.gib});if(o.srcAddr&&f!==o.srcAddr)throw new Error(`${c} srcAddr from src does not equal opts.srcAddr`);o.srcAddr=f;let p=b($=>$&&typeof $=="string"&&$.length>=2&&$.includes("^")&&$.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map($=>(n||{})[$]).forEach($=>{if(!($&&$.every(T=>p(T))))throw new Error(`${c} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(a||{}).map($=>(a||{})[$]).forEach($=>{if(!($&&$.every(T=>p(T))))throw new Error(`${c} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)});let h={ib:i.ib,gib:i.gib};i.data&&Object.keys(i.data).length>0&&(h.data=i.data),i.rel8ns&&Object.keys(i.rel8ns).length>0&&(h.rel8ns=i.rel8ns),i=h;let g=U(i),m=U(i.data||{});if(o.nCounter||Object.keys(m).includes("n"))if(Object.keys(m).includes("n"))if(Number.isInteger(m.n))m.n>=0?m.n=m.n+1:(console.warn(`${c} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),m.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else m.n=0;if(!t){let $=new Date;m.timestamp=Ce($),m.timestampMs=$.getMilliseconds()}let E=U(i.rel8ns||{});if(Object.keys(n||{}).forEach($=>{if(Er.includes($))throw new Error(`${c} Cannot manually add relationship: ${$}.`);let T=E[$]||[],G=n[$].filter(v=>!T.includes(v));E[$]=T.concat(G)}),Object.keys(a||{}).forEach($=>{if(Er.includes($))throw new Error(`${c} Cannot manually remove relationship: ${$}.`);let T=E[$]||[],I=a[$]||[],G=T.filter(v=>!I.includes(v));G.length>0?E[$]=G:delete E[$]}),E.past=(E.past||[]).concat([f]),(r||[]).filter($=>Object.keys(E).includes($)).filter($=>(E[$]||[]).length>1).forEach($=>{let T=E[$].length;E[$]=[E[$][T-1]]}),m.isTjp){let $=E.tjp||[];$.push(f),E.tjp=$,delete m.isTjp}g.data=m,g.rel8ns=E;let S=(E.tjp?.length??0)>0,A=null;if(e){A=await wr(o);let $=y({ibGib:A});E.dna=r?.includes(pe.dna)?E.dna=[$]:E.dna=(E.dna||[]).concat($)}g.gib=await ce({ibGib:g,hasTjp:S});let _={newIbGib:g};return A&&(_.dnas=[A]),_}b(He,"rel8");function ko({ibGib:o}){let t=`[${ko.name}]`;if(!o)return console.warn(`${t} ibGib falsy. (W: 884178562f5b4f15933ac4d98db74cc6)`),!1;if(o.data?.isTjp||o.rel8ns?.tjp?.length>0)return!0;let e=["fork^gib","mut8^gib","rel8^gib"];return(o.rel8ns?.ancestor??[]).some(n=>e.includes(n))?!1:o.gib?o.gib.includes(At)?!0:o.gib===z?!1:!!Oe({ibGibAddr:y({ibGib:o})}).tjpGib:(console.warn(`${t} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}b(ko,"hasTjp");function Mo({ibGib:o}){let t=`[${Mo.name}]`;o.ib||console.warn(`${t} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),o.gib||console.warn(`${t} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let e={ib:(o.ib||"").slice()};return o.gib&&(e.gib=o.gib.slice()),o.data&&(e.data=o.data instanceof Uint8Array?o.data:U(o.data)),o.rel8ns&&(e.rel8ns=U(o.rel8ns)),e}b(Mo,"toDto");var aa=!1;async function le({ibGib:o}){let t=`[${le.name}]`;try{let e=[];if(o){let r=y({ibGib:o});if(e=Ur({addr:r})??[],e.length>0)return console.error(`${t} errors found in addr: ${r}`),e;if(ue({gib:o.gib}))return null;let n=await ce({ibGib:Mo({ibGib:o}),hasTjp:ko({ibGib:o})});return n!==o.gib&&(o.data?.src&&o.data.srcAddr&&o.ib==="rel8"?(delete o.data.src,delete o.data.srcAddr,n=await ce({ibGib:Mo({ibGib:o}),hasTjp:ko({ibGib:o})}),n!==o.gib&&e.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${o.gib}). (E: 020b71479e944b2198fe436e7e137786)`)):e.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${o.gib}). (E: 7416db016878430ca3c5b20697f164ed)`)),e.length>0?e:null}else return e.push("ibGib is itself falsy. (E: 4fb98caf6ed24ef7b35a19cef56e2d7e)"),e}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(le,"validateIbGibIntrinsically");function Ur({addr:o,delimiter:t,version:e}){let r=`[${Ur.name}]`;try{let n=[];if(e&&console.warn(`${r} version not implemented yet. Ignoring. (W: 2d19db16ec0c4766b5d35248787671f3)`),!o)return n.push("addr required. (E: e9a54041aa0b41c1bb2324d9d2d42c7f)"),n;t=t||Ae,o.includes(t)||n.push(`No delimiter (${t}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`),o.startsWith(t)&&n.push("addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)");let{ib:a,gib:s}=J({ibGibAddr:o,delimiter:t}),i=Fr({ib:a,ibGibAddrDelimiter:t,version:e});i&&(n=n.concat(i));let c=Mr({gib:s,ibGibAddrDelimiter:t,version:e});return c&&(n=n.concat(c)),n.length>0&&aa&&console.log(`${r} errors.length > 0. errors: ${n.join("|")} (I: 9c18f993e138f15613e4c6a340d41722)`),n.length>0?n:null}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(Ur,"validateIbGibAddr");function Fr({ib:o,ibGibAddrDelimiter:t,version:e}){let r=`[${Fr.name}]`;try{let n=[];return e&&console.warn(`${r} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),o?o===kr?null:(t=t||Ae,o.includes(t)&&n.push(`ib contains ibGibAddrDelimiter (${t}) (E: 09e61b46c3e84874bc02b6918f1f2c39)`),n.length>0?n:null):(n.push("ib required. (E: a76d06c7b9c24db3a731a91dbe46acd5)"),n)}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(Fr,"validateIb");function Mr({gib:o,gibDelimiter:t,ibGibAddrDelimiter:e,version:r}){let n=`[${Mr.name}]`;try{let a=[];if(r&&console.warn(`${n} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`),!o)return a.push("gib required. (E: e217de4035b04086827199f4bace189c)"),a;e=e||Ae;let s=[e],i=[];s.forEach(h=>{o.includes(h)&&i.push(h)}),i.length>0&&a.push(`gib (${o}}) contains invalid characters: (${JSON.stringify(i.join(","))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);let{punctiliarHash:c,tjpGib:l,isPrimitive:d}=Oe({gib:o,gibDelimiter:t||At});if(d)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let f=c.match(Ys),p=c.match(Ws);if(!f&&!p&&a.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),l){let h=Mr({gib:l});(h??[]).length>0&&a.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${h.join(". ")}`)}return a.length>0?a:null}catch(a){throw console.error(`${n} ${w(a)}`),a}}b(Mr,"validateGib");function sa({rel8ns:o}){let t=`[${sa.name}]`;try{aa&&console.log(`${t} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`);let e=[],r=Object.keys(o);for(let n=0;n<r.length;n++){let a=Object.keys(o)[n];typeof a!="string"&&e.push("non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)");let s=o[a]??[];for(let i=0;i<s.length;i++){let c=s[i],l=Ur({addr:c})??[];l.length>0&&e.push(`invalid addr found for rel8nName (${a}). addr errors: ${l.join("|")} (E: 56809a746c4f462db426e90395b80364)`)}}return e.length>0?e:null}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{aa&&console.log(`${t} complete.`)}}b(sa,"validateRel8nsIntrinsically");var ii=!1,B=class o{static{b(this,"Factory_V1")}static root(){return o.primitive({ib:kr})}static primitive({ib:t}){return{ib:t,gib:z}}static primitives({ibs:t}){return t.map(e=>o.primitive({ib:e}))}static async firstGen({ib:t=kr,parentIbGib:e=o.root(),data:r,rel8ns:n,dna:a,tjp:s,linkedRel8ns:i,noTimestamp:c,nCounter:l,squash:d}){let f=`[${o.name}][${o.firstGen.name}]`;try{if(ii&&console.log(`${f} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),a&&d)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let p=[],h=e||j,g=await Bo({src:h,destIb:t,tjp:s,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:l});if(p.push(g),h=g.newIbGib,r){let m=await ot({src:h,dataToAddOrPatch:r,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:l});p.push(m),h=m.newIbGib}if(n){let m=await He({src:h,rel8nsToAddByAddr:n,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:l});p.push(m)}if(p.length>1){let m=p.slice(p.length-1)[0].newIbGib,E={newIbGib:m,intermediateIbGibs:p.slice(0,p.length-1).map(S=>S.newIbGib)};if(a){d&&`${f}`;let S=[];return p.forEach(A=>{S=S.concat(A.dnas)}),E.dnas=S,E}else if(d){if(!m.rel8ns)throw new Error("(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)");return delete m.rel8ns.past,m.rel8ns.tjp&&(delete m.rel8ns.tjp,m.data??={},m.data.isTjp=!0),l&&(m.data??={},m.data.n=0),m.gib=await ce({ibGib:m}),{newIbGib:m}}else return E}else{if(p.length===1)return p[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(p){throw console.error(`${f} ${w(p)}`),p}finally{ii&&console.log(`${f} complete.`)}}static async stone({parentPrimitiveIb:t,ib:e,ibRegExpPattern:r,data:n,rel8ns:a,noTimestamp:s,uuid:i}){let c=`[${o.name}][${o.stone.name}]`;try{if(!t)throw new Error("parentPrimitiveIb required. (E: genuuid)");if(Fr({ib:t})!==null)throw new Error(`Invalid parentPrimitiveIb: ${t}. (E: genuuid)`);if(!e)throw new Error("ib required. (E: genuuid)");let l=r?new RegExp(r):ai;if(!e.match(l))throw new Error(`invalid ib. does not match regexp (${l}) (E: genuuid)`);let d=Object.keys(a??{}),f=[...Er,"tjp"];if(d.some(m=>f.includes(m)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${f}. rel8ns keys: ${Object.keys(a??{})}. (E: genuuid)`);let g=(await o.firstGen({ib:e,parentIbGib:o.primitive({ib:t}),data:n,rel8ns:a,dna:!1,noTimestamp:s,nCounter:!1})).newIbGib;return i&&(g.data||(g.data={}),g.data.uuid=await V()),g.rel8ns?.past&&delete g.rel8ns.past,g.rel8ns?.tjp&&delete g.rel8ns.tjp,g.gib=await ce({ibGib:{ib:g.ib,data:g.data,rel8ns:g.rel8ns},hasTjp:!1}),g}catch(l){throw console.error(`${c} ${l.message}`),l}}static async constant({parentPrimitiveIb:t,ib:e,ibRegExpPattern:r,data:n,rel8ns:a}){let s=`[${o.name}][${o.constant.name}]`;try{return await o.stone({parentPrimitiveIb:t,ib:e,ibRegExpPattern:r,data:n,rel8ns:a,noTimestamp:!0,uuid:!1})}catch(i){throw console.error(`${s} ${i.message}`),i}}};var Jp="[core^gib timer]";var ia=`.'",!?-`;var ci=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var Zp=/^[a-zA-Z0-9_\-.]{1,255}$/,Qp=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var Uo={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var kd="robbot";var li="zero",di="zerospace";var uh=!1,gh="This is a local space. There are many like it, but this one is mine.";var mh=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,Md="syncSpace";var Eh=3e4;var Fo="space";var fi="space_lock",bi=100,pi=100,wh=60*2,ca=30;var la="root",da="x",hi="root",fa="analytics-outline",ba='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var pa="tag",Ud="target";var ui="pricetag-outline",gi="This is a tag used for organizing data.";var Gh="always",mi="archive",Ei="trash";var ha=/^\w{1,32}$/,jo="Invalid Date";var ua={ib:"true",gib:z};var wi={ib:"false",gib:z};var yi="config_key";var io=/^[a-zA-Z0-9_\-.]{1,32}$/,Vo="app";var yr=`bootstrap^${z}`,Tt="defaultSpaceId",$i="spaceIds";var Gt={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},Zt=Object.values(Gt),nt={sha_256:"SHA-256",sha_512:"SHA-512"},Lh=Object.values(nt),Fd={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},kt=Object.values(Fd);function co(o){let t=`[${co.name}]`;return new Promise((e,r)=>{try{let n=Ii(o),a=_i(n);e(a)}catch(n){console.error(`${t} ${w(n)}`),r(n)}})}b(co,"encodeStringToHexString");function Ii(o){let t=`[${Ii.name}]`;try{return new TextEncoder().encode(o)}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(Ii,"stringToUTF8Bytes");function _i(o){let t=`[${_i.name}]`;try{return Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(_i,"bytesToHexString");function Mt(o){let t=`[${Mt.name}]`;return new Promise((e,r)=>{try{let n=Si(o),a=Ai(n);e(a)}catch(n){console.error(`${t} ${w(n)}`),r(n)}})}b(Mt,"decodeHexStringToString");function Si(o){let t=`[${Si.name}]`;try{if(o.length%2!==0)throw new Error("invalid hex string. length %2 !== 0");let e=o.length/2,r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=parseInt(o.substr(n*2,2),16);return r}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(Si,"hexStringToBytes");function Ai(o){let t=`[${Ai.name}]`;try{return new TextDecoder().decode(o)}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(Ai,"utf8BytesToString");var Ut=Gt.appendPerHash,Ft="SHA-512",jt=1024,vt=2e4,Vt=1,Ti="indexOf",Ko="lastIndexOf",Ho=5e6,Xo=4,Qt=",";function jd({secret:o,prevHash:t,salt:e,saltStrategy:r}){if(!(t||o))throw new Error("Either secret or prevHash is required, but both are falsy (E: bee2849729ff410081d963777dcedb49))");switch(r){case Gt.prependPerHash:return e+(t||o);case Gt.appendPerHash:return(t||o)+e;case Gt.initialPrepend:return t||e+o;case Gt.initialAppend:return t||o+e;default:throw new Error(`Unknown saltStrategy: ${r} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}b(jd,"getPreHash");async function lt({secret:o,prevHash:t,count:e,salt:r,saltStrategy:n,hashAlgorithm:a}){let s=`[${lt.name}]`;try{let i=t||void 0;for(let c=0;c<e;c++){let l=jd({secret:o,prevHash:i,salt:r,saltStrategy:n});i=await _e({s:l,algorithm:a})}if(!i)throw new Error("hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)");return i}catch(i){throw console.error(`${s} ${w(i)}`),i}}b(lt,"execRound_getNextHash");async function Kt({secret:o,initialRecursions:t,salt:e,saltStrategy:r,hashAlgorithm:n}){let a=`[${Kt.name}]`;try{return await lt({secret:o,count:t,salt:e,saltStrategy:r,hashAlgorithm:n})}catch(s){throw console.error(`${a} ${w(s)}`),s}}b(Kt,"doInitialRecursions_keystretch");async function ga({hexEncodedData:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c}){let l=`[${ga.name}]`;try{let d=await Kt({secret:a,initialRecursions:t,salt:r,saltStrategy:n,hashAlgorithm:s}),f=c==="indexOf"?(g,m)=>g.indexOf(m):(g,m)=>g.lastIndexOf(m),p=[];for(let g=0;g<o.length;g++){let m=o[g],E="",S;for(;!E.includes(m);)S=await lt({count:e,prevHash:d,salt:r,saltStrategy:n,hashAlgorithm:s}),E+=S,d=S;let A=f(E,m);p.push(A)}return p.join(i)}catch(d){throw console.error(`${l} ${w(d)}`),d}}b(ga,"encryptFromHex_stream");async function ma({encryptedData:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${ma.name}]`;try{let l=await Kt({secret:a,initialRecursions:t,salt:r,saltStrategy:n,hashAlgorithm:s}),d=o.split(i).map(h=>parseInt(h)),f=[];for(let h=0;h<d.length;h++){let g=d[h],m="",E;for(;g>=m.length;)E=await lt({count:e,prevHash:l,salt:r,saltStrategy:n,hashAlgorithm:s}),m+=E,l=E;let S=m[g];f.push(S)}return f.join("")}catch(l){throw console.error(`${c} ${w(l)}`),l}}b(ma,"decryptToHex_stream");async function lo({encryptedData:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${lo.name}]`,l=[],d=[];t=t||vt,e=e||Vt,n=n||Ut,s=s||Ft,r=r||await V(jt),i=i||Qt;let f="[validation]";if(!t||t<1){let g=`${f} initialRecursions required, and greater than 0`;console.error(g),l.push(g)}if(!e||e<1){let g=`${f} recursionsPerHash required, and greater than 0`;console.error(g),l.push(g)}if(!o){let g=`${f} encryptedData required`;console.error(g),l.push(g)}if(!r){let g=`${f} salt required`;console.error(g),l.push(g)}if(!n){let g=`${f} saltStrategy required`;console.error(g),l.push(g)}if(!a){let g=`${f} secret required`;console.error(g),l.push(g)}if(!i){let g=`${f} encryptedDataDelimiter required`;console.error(g),l.push(g)}if(!Object.values(nt).includes(s)){let g=`${f} only ${Object.values(nt)} hash algorithms implemented`;console.error(g),l.push(g)}if(n&&!Zt.includes(n)){let g=`${f} unknown saltStrategy: ${n}`;console.error(g),l.push(g)}if(l.length>0)return{errors:l,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let p=await ma({encryptedData:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});return{decryptedData:await Mt(p),initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:d.length>0?d:void 0}}b(lo,"decryptImpl_stream");async function Ea({dataToEncrypt:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,confirm:c,indexingMode:l}){let d=`[${Ea.name}]`,f=[],p=[];t||(console.warn(`${d} initial recursions required. defaulting to ${vt}`),t=vt),e=e||Vt,n=n||Ut,s=s||Ft,r=r||await V(jt),i=i||Qt,l=l||Ti;let h="[validation]";if(!t||t<1){let E=`${h} initialRecursions required, and greater than 0`;console.error(E),f.push(E)}if(!e||e<1){let E=`${h} recursionsPerHash required, and greater than 0`;console.error(E),f.push(E)}if(!o){let E=`${h} dataToEncrypt required`;console.error(E),f.push(E)}if(!r){let E=`${h} salt required`;console.error(E),f.push(E)}if(!n){let E=`${h} saltStrategy required`;console.error(E),f.push(E)}if(!a){let E=`${h} secret required`;console.error(E),f.push(E)}if(!i){let E=`${h} encryptedDataDelimiter required`;console.error(E),f.push(E)}if(!kt.includes(l)){let E=`${h} invalid indexingMode (${l}). Must be one of ${kt} (E: 5955c46755434982982823c97adcf076)`;console.error(E),f.push(E)}if(!Object.values(nt).includes(s)){let E=`${h} only ${Object.values(nt)} hash algorithms implemented`;console.error(E),f.push(E)}if(n&&!Zt.includes(n)){let E=`${h} unknown saltStrategy: ${n}`;console.error(E),f.push(E)}if(f.length>0)return{errors:f,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let g=await co(o);if(c&&await Mt(g)!==o)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let m=await ga({hexEncodedData:g,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:"indexOf"});if(c){let E=await lo({encryptedData:m,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});if((E.errors||[]).length>0)return{errors:["Confirm check found that decrypt had errors.",...E.errors],initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};if(E.decryptedData){if(E.decryptedData!==o)throw new Error("The ENCRYPTED data did not decrypt back to the original data.")}else throw new Error("Confirm check call to decrypt produced falsy decryptedData");(E.warnings||[]).length>0&&(p=p.concat(["Confirm check call to decrypt had warnings.",...E.warnings]))}return{encryptedData:m,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:p.length>0?p:void 0}}b(Ea,"encryptImpl_stream");async function wa({hexEncodedData:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c,maxBlockSize:l,numOfPasses:d}){let f=`[${wa.name}]`;try{let p=await Kt({secret:a,initialRecursions:t,salt:r,saltStrategy:n,hashAlgorithm:s}),h=c==="indexOf"?(T,I)=>T.indexOf(I):(T,I)=>T.lastIndexOf(I),g=[],m=o.length,E=l;E>m&&(E=m);let S=Math.ceil(m/E),A=m%E||E,_=0;for(let T=0;T<S;T++){T===S-1&&(E=A);let G=await Gi({blockSize:E,indexHexEncodedDataAtStartOfPass:_,numOfPasses:d,hexEncodedData:o,recursionsPerHash:e,salt:r,saltStrategy:n,prevHash:p,hashAlgorithm:s}),v=G.alphabetsThisBlock;p=G.prevHash;let N=await vi({alphabetsThisBlock:v,blockSize:E,indexHexEncodedDataAtStartOfPass:_,hexEncodedData:o,getIndexOfCharInAlphabet:h});g=g.concat(N),_+=E}return g.join(i)}catch(p){throw console.error(`${f} ${w(p)}`),p}}b(wa,"encryptFromHex_blockMode");async function Gi({blockSize:o,numOfPasses:t,indexHexEncodedDataAtStartOfPass:e,hexEncodedData:r,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let l=`[${Gi.name}]`;try{let d=[],f,p;for(let h=0;h<t;h++)for(let g=0;g<o;g++){f=e+g;let m=d[g]??"";p=await lt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p,d[g]=m}for(let h=0;h<o;h++){f=e+h;let g=r[f],m=d[h];for(;!m.includes(g);)p=await lt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p;d[h]=m}return{alphabetsThisBlock:d,prevHash:i}}catch(d){throw console.error(`${l} error: ${w(d)}`),d}}b(Gi,"getAlphabetsThisBlock");async function vi({alphabetsThisBlock:o,blockSize:t,indexHexEncodedDataAtStartOfPass:e,hexEncodedData:r,getIndexOfCharInAlphabet:n}){let a=`[${vi.name}]`;try{let s=[];for(let i=0;i<t;i++){let c=e+i,l=o[i],d=n(l,r[c]);s.push(d)}return s}catch(s){throw console.error(`${a} ${w(s)}`),s}}b(vi,"getEncryptedIndexesThisBlock");async function ya({encryptedData:o,initialRecursions:t,recursionsPerHash:e,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,maxBlockSize:c,numOfPasses:l}){let d=`[${ya.name}]`;try{let f=await Kt({secret:a,initialRecursions:t,salt:r,saltStrategy:n,hashAlgorithm:s}),p=o.split(i).map($=>parseInt($)),h=[],g=p.length,m=c;m>g&&(m=g);let E=Math.ceil(g/m),S=g%m||m,A=0;for(let $=0;$<E;$++){$===E-1&&(m=S);let I=await Ci({blockSize:m,indexEncryptedDataIndexesAtStartOfPass:A,numOfPasses:l,encryptedDataIndexes:p,recursionsPerHash:e,salt:r,saltStrategy:n,prevHash:f,hashAlgorithm:s}),G=I.alphabetsThisBlock;f=I.prevHash;let v=await xi({alphabetsThisBlock:G,blockSize:m,indexEncryptedDataIndexesAtStartOfPass:A,encryptedDataIndexes:p});h=h.concat(v),A+=m}return h.join("")}catch(f){throw console.error(`${d} ${w(f)}`),f}}b(ya,"decryptToHex_blockMode");async function Ci({blockSize:o,numOfPasses:t,indexEncryptedDataIndexesAtStartOfPass:e,encryptedDataIndexes:r,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let l=`[${Ci.name}]`;try{let d=[],f,p;for(let h=0;h<t;h++)for(let g=0;g<o;g++){f=e+g;let m=d[g]??"";p=await lt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p,d[g]=m}for(let h=0;h<o;h++){f=e+h;let g=r[f],m=d[h];for(;m.at(g)===void 0;)p=await lt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p;d[h]=m}return{alphabetsThisBlock:d,prevHash:i}}catch(d){throw console.error(`${l} error: ${w(d)}`),d}}b(Ci,"getAlphabetsThisBlock");async function xi({alphabetsThisBlock:o,blockSize:t,indexEncryptedDataIndexesAtStartOfPass:e,encryptedDataIndexes:r}){let n=`[${xi.name}]`;try{let a=[];for(let s=0;s<t;s++){let i=e+s,c=r[i],d=o[s][c];a.push(d)}return a}catch(a){throw console.error(`${n} ${w(a)}`),a}}b(xi,"getDecryptedDataArrayThisBlock");async function fo(o){let t=`[${fo.name}]`,{encryptedData:e,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:d,blockMode:f,multipass:p}=o,h=[],g=[];if(f&&p)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: b9b3cd1f701c700835c0419260278223)");if(!f&&p&&(console.warn(`${t}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),f=p),!f)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");r=r||vt,n=n||Vt,s=s||Ut,c=c||Ft,a=a||await V(jt),l=l||Qt,d=d||Ko;let{maxBlockSize:m,maxPassSectionLength:E,numOfPasses:S}=f;!m&&E&&(console.warn(`${t}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`),m=E),m=m||Ho,S=S||Xo;let A="[validation]";if(!r||r<1){let I=`${A} initialRecursions required, and greater than 0`;console.error(I),h.push(I)}if(!n||n<1){let I=`${A} recursionsPerHash required, and greater than 0`;console.error(I),h.push(I)}if(!e){let I=`${A} encryptedData required`;console.error(I),h.push(I)}if(!a){let I=`${A} salt required`;console.error(I),h.push(I)}if(!s){let I=`${A} saltStrategy required`;console.error(I),h.push(I)}if(!i){let I=`${A} secret required`;console.error(I),h.push(I)}if(!l){let I=`${A} encryptedDataDelimiter required`;console.error(I),h.push(I)}if(!d){let I=`${A} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error(I),h.push(I)}if(!kt.includes(d)){let I=`${A} invalid indexingMode (${d}). Must be one of ${kt} (E: 17435268651444e0b7a594135635fc58)`;console.error(I),h.push(I)}if(m<1){let I=`${A} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error(I),h.push(I)}if(S<1){let I=`${A} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error(I),h.push(I)}if(!Object.values(nt).includes(c)){let I=`${A} only ${Object.values(nt)} hash algorithms implemented`;console.error(I),h.push(I)}if(s&&!Zt.includes(s)){let I=`${A} unknown saltStrategy: ${s}`;console.error(I),h.push(I)}if(h.length>0){let I={...o,errors:h};return delete I.encryptedData,delete I.secret,I}let _=await ya({encryptedData:e,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,maxBlockSize:m,numOfPasses:S}),$=await Mt(_),T={...o,decryptedData:$,warnings:g.length>0?g:void 0};return delete T.encryptedData,delete T.secret,T}b(fo,"decryptImpl_blockMode");async function $a(o){let t=`[${$a.name}]`,{dataToEncrypt:e,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,confirm:d,indexingMode:f,blockMode:p,multipass:h}=o,g=[],m=[];if(p&&h)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: bde5efd1a3e449dca549c5bff147f09b)");if(!p&&h&&(console.warn(`${t}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),p=h),!p)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 0b87871f81d849ef8f0263b7775bd3e3)");r||(console.warn(`${t} initial recursions required. defaulting to ${vt}`),r=vt),l=l||Qt,f=f||Ko;let{maxBlockSize:E,maxPassSectionLength:S,numOfPasses:A}=p;!E&&S&&(console.warn(`${t}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`),E=S),E=E||Ho,A=A||Xo;let _="[validation]";if(!r||r<1){let G=`${_} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(G),g.push(G)}if(!n||n<1){let G=`${_} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(G),g.push(G)}if(!a){let G=`${_} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(G),g.push(G)}if(!s){let G=`${_} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(G),g.push(G)}if(!i){let G=`${_} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(G),g.push(G)}if(!l){let G=`${_} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(G),g.push(G)}if(!f){let G=`${_} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(G),g.push(G)}if(!kt.includes(f)){let G=`${_} invalid indexingMode (${f}). Must be one of ${kt} (E: 17435268651444e0b7a594135635fc58)`;console.error(G),g.push(G)}if(E<1){let G=`${_} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(G),g.push(G)}if(A<1){let G=`${_} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(G),g.push(G)}if(!Object.values(nt).includes(c)){let G=`${_} only ${Object.values(nt)} hash algorithms implemented`;console.error(G),g.push(G)}if(s&&!Zt.includes(s)){let G=`${_} unknown saltStrategy: ${s}`;console.error(G),g.push(G)}if(g.length>0){let G={...o,errors:g};return delete G.dataToEncrypt,delete G.secret,G}let $=await co(e);if(d&&await Mt($)!==e)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let T=await wa({hexEncodedData:$,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:f,maxBlockSize:E,numOfPasses:A});if(d)try{let G=await fo({encryptedData:T,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:f,blockMode:p});if(G.decryptedData){if(G.decryptedData!==e)throw new Error("The ENCRYPTED data did not decrypt back to the original data. (E: 16b5f1a11e4f438ab38a7f124178a7b8)")}else throw new Error("Confirm check call to decrypt produced falsy decryptedData (E: a4fe82dee61f497e9dea188ea9c287a4)");(G.warnings||[]).length>0&&(m=m.concat(["Confirm check call to decrypt had warnings.",...G.warnings]))}catch(G){throw new Error(`${t} confirm failed. decrypt error: ${w(G)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let I={...o,encryptedData:T,warnings:m.length>0?m:void 0};return delete I.dataToEncrypt,delete I.secret,I}b($a,"encryptImpl_blockMode");async function Vd(o){let t=`[${Vd.name}]`;try{if(!o)throw new Error("args required (E: 22e58e03c78f4c27bf18295b8d2cdd3a)");if(!o.dataToEncrypt)throw new Error("dataToEncrypt required (E: 168c9076e5434c83ba81e3485ee6f3e4)");o.salt=o.salt||await V(jt),o.saltStrategy=o.saltStrategy||Ut,o.hashAlgorithm=o.hashAlgorithm||Ft,o.recursionsPerHash=o.recursionsPerHash||Vt;let e;return o.blockMode?e=await $a(o):e=await Ea(o),(e.errors??[]).length>0&&e.errors.forEach(r=>console.warn(`${t} ${r}`)),(e.warnings??[]).length>0&&e.warnings.forEach(r=>console.warn(`${t} ${r}`)),e}catch(e){throw console.error(`${t}${e.message}`),e}}b(Vd,"encrypt");async function Kd(o){let t=`[${Kd.name}]`;try{if(!o)throw new Error("args required (E: fcd9b4aad85c4deba5fe5fde0b9ecb30)");if(!o.encryptedData)throw new Error("encryptedData required (E: f879f612428b4283bae089acee929a58)");o.salt=o.salt||await V(jt),o.saltStrategy=o.saltStrategy||Ut,o.hashAlgorithm=o.hashAlgorithm||Ft,o.recursionsPerHash=o.recursionsPerHash||Vt;let e;return o.blockMode||o.multipass?e=await fo(o):e=await lo(o),(e.warnings??[]).length>0&&e.warnings.forEach(r=>console.warn(`${t} ${r}`)),(e.errors??[]).length>0&&e.errors.forEach(r=>console.warn(`${t} ${r}`)),e}catch(e){throw console.error(`${t}${e.message}`),e}}b(Kd,"decrypt");var Hu=5e4;var Xu=Gt.appendPerHash,qu=10,Yu="SHA-256";var Wu="encryption",zu="ciphertext";var Hd={local:"local",outerspace:"outerspace",innerspace:"innerspace"},eg=Object.values(Hd).concat(),Xd={user:"user",sync:"sync"},Ia=Object.values(Xd).concat(),qd={node_filesystem:"node-filesystem"},Yd={aws_dynamodb:"aws-dynamodb"},Wd={...qd,...Yd},_a=Object.values(Wd).concat(),zd={get:"get",put:"put",delete:"delete"},Jd={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var Zd=!1,Yo=class o{static{b(this,"DynamicFormBuilder")}lc=`[${o.name}]`;items=[];what="";idPool=[];getNewId(){let t=`${this.lc}[${this.getNewId.name}]`;if(this.idPool?.length>0)return this.idPool.pop()??"";{let e=[],r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n=r.length;for(let s=0;s<32;s++){let i=Math.floor(Math.random()*n);e.push(r[i])}let a=e.join("");return Zd&&console.log(`${t} id: ${a} (I: c6591ffee6d5bbea79ed19cfa6630422)`),a}}forA({what:t}){return this.what=t||"thingy",this}addItem(t){t.uuid||(t.uuid=this.getNewId()),this.items.push(t)}with({idPool:t}){return t&&(this.idPool=t),this}and(){return this}name({of:t,required:e=!0,defaultValue:r}){return this.addItem({name:"name",description:`What to call this ${this.what}. Doesn't have to be unique, no spaces, up to 32 alphanumerics/underscores in length.`,label:"Name",placeholder:'e.g. "bob_the_cool"',regexp:Lo({min:1,max:32,noSpaces:!0}),regexpErrorMsg:"1 to 32 characters, no spaces, underscores allowed.",required:e,dataType:"text",value:t,defaultValue:r}),this}description({of:t,required:e,defaultValue:r}){return this.addItem({name:"description",description:`Description/notes for this ${this.what}.`,label:"Description",placeholder:`Describe these ${this.what} settings here...`,regexp:Lo({min:0,max:155,chars:ia}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${ia}`,dataType:"textarea",required:e,value:t,defaultValue:r}),this}classname({of:t,required:e=!0}){return this.addItem({name:"classname",description:`Technical setting that is the name of the ${this.what}'s class in computer code.`,label:"Classname",regexp:Lo({min:1,max:128,noSpaces:!0}),regexpErrorMsg:"1 to 128 alphanumerics or underscores without spaces",dataType:"text",value:t,readonly:!0,required:e}),this}uuid({of:t,label:e,required:r}){return this.addItem({name:"uuid",description:`Unique(ish) id of the ${this.what}.`,label:e??"ID",dataType:"text",value:t,regexp:Ie,regexpErrorMsg:"1 to 256 alphanumerics, underscores, dots, hyphens allowed.",readonly:!0,required:r}),this}version({of:t,required:e}){return this.addItem({name:"version",description:`Technical setting indicating the version of the ${this.what}.`,label:"Version",dataType:"text",value:t||"",readonly:!0,required:e}),this}customItem(t){return this.addItem(t),this}outputItems(){return this.items}outputForm({formName:t,label:e}){return{name:t,description:`This is a form for a ${this.what}`,label:e??this.what,items:this.items}}};var er=class o extends Yo{static{b(this,"WitnessFormBuilder")}lc=`[${o.name}]`;allowPrimitiveArgs({of:t,required:e=!0}){return this.addItem({name:"allowPrimitiveArgs",description:`Technical setting on if this ${this.what} accepts primitive incoming ibgibs`,label:"Allow Primitive Args",dataType:"toggle",value:t??!0,readonly:!0,required:e}),this}catchAllErrors({of:t,required:e=!0}){return this.addItem({name:"catchAllErrors",description:`Technical setting on what the ${this.what} does when it encounters an internal error.`,label:"Catch All Errors",dataType:"toggle",value:t??!0,readonly:!0,required:e}),this}persistOptsAndResultIbGibs({of:t,required:e=!0}){return this.addItem({name:"persistOptsAndResultIbGibs",description:`Technical setting on if the ${this.what} maintains an audit trail of all of its inputs/outputs.`,label:"Persist Opts and Result IbGibs",dataType:"toggle",value:t??!1,readonly:!0,required:e}),this}trace({of:t,required:e}){return this.addItem({name:"trace",description:`Technical setting on if the ${this.what}'s activity should be traced (logged to the console).`,label:"Trace",dataType:"toggle",value:t??!1,readonly:!0,required:e}),this}commonWitnessFields({data:t,allowPrimitiveArgs:e=!0,catchAllErrors:r=!0,persistOptsAndResultIbGibs:n=!0,trace:a=!0,version:s=!0}){return e&&this.allowPrimitiveArgs({of:t.allowPrimitiveArgs}),r&&this.catchAllErrors({of:t.catchAllErrors}),n&&this.persistOptsAndResultIbGibs({of:t.persistOptsAndResultIbGibs}),a&&this.trace({of:t.trace}),s&&this.version({of:t.version}),this}};var Wo=!1;function Ni({appData:o}){let t=`[${Ni.name}]`;try{if(Wo&&console.log(`${t} starting...`),!o)throw new Error("appData required (E: 3df782b29bc4406a87e4895cfcea28ed)");let e=[],{name:r,uuid:n,classname:a}=o;return r?r.match(io)||e.push(`name must match regexp: ${io}`):e.push("name required."),n?n.match(Ie)||e.push(`uuid must match regexp: ${Ie}`):e.push("uuid required."),a&&(a.match(io)||e.push(`classname must match regexp: ${io}`)),e}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Wo&&console.log(`${t} complete.`)}}b(Ni,"validateCommonAppData");function Sa({appData:o,classname:t}){let e=`[${Sa.name}]`;try{let r=Ni({appData:o});if(r.length>0)throw new Error(`invalid appData: ${r} (E: 9aff04f0cfc54a5188ca8bc40764160d)`);if(t){if(o.classname&&o.classname!==t)throw new Error("classname does not match appData.classname (E: 66f1447eef97485fba521c40980f5eb5)")}else if(t=o.classname,!t)throw new Error("classname required (E: 5f6ffb4317044125b94f662070e1f40b)");let{name:n,uuid:a}=o;return`app ${t} ${n} ${a}`}catch(r){throw console.error(`${e} ${r.message}`),r}}b(Sa,"getAppIb");function Qd({appIb:o}){let t=`[${Qd.name}]`;try{if(!o)throw new Error("appIb required (E: 6b065aee67e641ba9f9c6db367ebb0fb)");let e=o.split(" ");return{appClassname:e[1],appName:e[2],appId:e[3]}}catch(e){throw console.error(`${t} ${e.message}`),e}}b(Qd,"getInfoFromAppIb");async function ef({fnPromptApp:o,ibgibs:t,space:e}){let r=`[${ef.name}]`;try{if(Wo&&console.log(`${r} starting...`),!t)throw new Error("ibgibs all powerful service required. (E: b24e78de0d204dc78909022bee296b30)");e=e??await t.getLocalUserSpace({lock:!0});let n=await o(e,null);if(!n)throw new Error("resApp falsy after prompt for app. (E: 2225a567abcd680a5e957e81fbb64123)");let a=n.newIbGib,s=[];s.push(a),n.intermediateIbGibs?.forEach(d=>s.push(d)),n.dnas?.forEach(d=>s.push(d));for(let d=0;d<s.length;d++){let f=s[d],p=await le({ibGib:f});if((p??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${p}. app: ${F(a.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await ge({resTransform:n,space:e});let{zeroSpace:i,fnBroadcast:c,fnUpdateBootstrap:l}=t;return await Te({ibGib:a,space:e,fnBroadcast:b(d=>c(d),"fnBroadcast")}),await jr({type:"apps",rel8nName:Vo,ibGibsToRel8:[a],space:e,zeroSpace:i,fnUpdateBootstrap:l,fnBroadcast:c}),a}catch(n){debugger;console.error(`${r} ${n.message}`);return}finally{Wo&&console.log(`${r} complete.`)}}b(ef,"createNewApp");var tf="0",rf="chat_gib",of="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",Di={version:"1",uuid:tf,name:rf,description:of,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Oi=void 0;var nf="0",af="raw_gib",sf="Explorer app for navigating raw ibgib data.",Li={version:"1",uuid:nf,name:af,description:sf,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Pi=void 0;var Aa="0",cf="todo_gib",lf="Todo app for viewing and interacting with ibgibs like they're checklists.",Ri={version:"1",uuid:Aa,name:cf,description:lf,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Bi=void 0;async function Ta(o){let t=`[${Ta.name}]`,e=[];try{y({ibGib:o})!==yr&&e.push(`invalid bootstrapSpace addr. Should equal "${yr}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await le({ibGib:o});(n?.length??!1)&&n.forEach(i=>e.push(i));let a=o.data,s=o.rel8ns;return Object.keys(a||{}).length===0&&e.push("invalid bootstrapSpace data. data required (E: 5a9bd15dd0644f9b93cafbbba660cfdf)"),(a.spaceIds??[]).length===0&&e.push("invalid bootstrapSpace, data.spaceIds required. (E: 6b91ddc12cfd41e59ded7d7502c1909f)"),Object.keys(o.rel8ns||{}).length===0&&e.push("invalid bootstrapSpace rel8ns (empty). Should have at least one rel8n, with rel8nName corresponding to the spaceId (E: b188ce4ae25e49f794f35e141bc2ecde)"),a.spaceIds.forEach(i=>{(s[i]??[]).length===0&&e.push(`invalid bootstrap. Each spaceId listed in data should have a corresponding address in rel8ns. spaceId (${i}) missing. (E: 62dd0d76e29a415a98b4b27deb8db17e)`)}),a[Tt]?(s[a[Tt]]??[]).length===0&&e.push(`invalid bootstrap. data.${Tt} (${a[Tt]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):e.push(`invalid bootstrap. data.${Tt} required. (E: f763af2e275f445cbf1db5801bacafad)`),e.length===0?!0:(console.error(`${t} errors: ${e.join("|")}`),!1)}catch(r){return console.error(`${t} ${r.message}`),!1}}b(Ta,"validateBootstrapIbGib");var Vr="meta_stone";var Ga="undefined",bo="target",zo="targetTjp";var dt=!1;function Mi({ib:o}){let t=`[${Mi.name}]`;try{dt&&console.log(`${t} starting...`);let e=[],r=o.split(" ");r[0]!==Vr&&e.push(`${t} invalid ib. atom is expected to be META_STONE_ATOM: ${Vr} (E: a9812bffc18f44418aa091fb0ed260bd)`);let a=r[1],s=Mr({gib:a})??[];s.length>0&&e.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${s} (E: 233db2babfbe4d28a80f98261f1c0e01)`);let i=r[2],c=Number.parseInt(i);isNaN(c)&&e.push("invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)");let l=r[3];if(l!=="undefined"){let d=tr({timestamp:l});d.valid||e.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${d.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`)}return e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{dt&&console.log(`${t} complete.`)}}b(Mi,"validateCommonMetaStoneIb");function va({data:o}){let t=`[${va.name}]`;try{if(dt&&console.log(`${t} starting...`),!o)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let e=[],{targetData:r,timestamp:n}=o;tr({timestamp:n}).valid||e.push("invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)");let{tjpGib:s,n:i,timestamp:c}=r;if(s&&s!=="undefined"){let d=Mr({gib:s})??[];d.length>0&&e.push(`invalid data (targetTjpGib). validation errors: ${d} (E: d216b12eb75544ef8c5ffb27cd132e2e)`)}if(typeof i!="number"&&e.push("invalid n. should be valid integer. if target.data.n is falsy, targetN should be -1 (E: 8f234967b388ad80776c8054d71fbc23)"),c&&c!=="undefined"){let d=tr({timestamp:c});d.valid||e.push(`invalid targetTimestamp. emsg: ${d.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`)}let l=new Date(n);return e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{dt&&console.log(`${t} complete.`)}}b(va,"validateCommonMetaStoneData");function Ui({rel8ns:o}){let t=`[${Ui.name}]`;try{if(dt&&console.log(`${t} starting...`),!o)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let e=[],r=sa({rel8ns:o??{}})??[];r.length>0&&e.push(`invalid rel8ns intrinsically. errors: ${r.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=o[bo]??[];n.length===0?e.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${bo}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&e.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${bo}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let a=o[zo]??[];return a.length>1&&e.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${zo}. has ${a.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{dt&&console.log(`${t} complete.`)}}b(Ui,"validateCommonMetaStoneRel8ns");async function df({ibGib:o}){let t=`[${df.name}]`;try{dt&&console.log(`${t} starting... (I: f32249d08105b997871a06cdee006311)`);let e=await le({ibGib:o})??[];if(!o.data)throw new Error("MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)");let r=[];try{let{atom:i,tjpGib:c,n:l,timestampInTicks:d}=ji({ib:o.ib})}catch(i){r.push(w(i))}let n=va({data:o.data}),a=Ui({rel8ns:o.rel8ns}),s=[...e??[],...r??[],...n??[],...a??[]];return s.length>0?s:void 0}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{dt&&console.log(`${t} complete.`)}}b(df,"validateCommonMetaStoneIbGib");function Fi({data:o,classname:t}){let e=`[${Fi.name}]`;try{let r=va({data:o});if(r.length>0)throw new Error(`invalid MetaStone data: ${r} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);t&&dt&&console.log(`${e} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`);let n=o.targetData.timestamp,a=n&&n!=="undefined"?rt(n):Ga;return`${Vr} ${o.targetData.tjpGib} ${o.targetData.n} ${a}`}catch(r){throw console.error(`${e} ${w(r)}`),r}}b(Fi,"getMetaStoneIb");function ji({ib:o}){let t=`[${ji.name}]`;try{if(!o)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let e=Mi({ib:o});if(e.length>0)throw new Error(`invalid ib. validationErrors: ${e} (E: a6107f62200eb943e523f70f51300623)`);let r=o.split(" ");return{atom:r[0],tjpGib:r[1],n:Number.parseInt(r[2]),timestampInTicks:r[3]}}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(ji,"parseMetaStoneIb");function Bg({addr:o,ibGib:t}){if(o||=y({ibGib:t}),!o)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return o.startsWith(`${Vr} `)}b(Bg,"isMetaStone");async function Ca({targetIbGib:o}){let t=`[${Ca.name}]`;try{dt&&console.log(`${t} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let e=y({ibGib:o}),r=ee({ibGib:o,defaultIfNone:"incomingAddr"}),n,a={[bo]:[e],[zo]:[r]};if(!o.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let s=o.data?.isTjp?o.gib:Oe({ibGibAddr:e}).tjpGib??o.gib;if(s===z)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let i=new Date,c=Ce(i),l=i.getMilliseconds();o.data?po({ibGib:o})?n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:l}:(n={targetData:{n:o.data.n??-1,tjpGib:s,timestamp:o.data.timestamp??Ga},timestamp:c,timestampMs:l},o.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:l};let d=Fi({data:n}),f=await mt({parentPrimitiveIb:Vr,ib:d,data:n,rel8ns:a});return dt&&(console.log(`${t} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(f)),f}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{dt&&console.log(`${t} complete.`)}}b(Ca,"newUpMetaStone");var Jo="witness",ho="witness_arg",Zo="witness_result",Ug="context";var x=!1;async function W({addr:o,addrs:t,isDna:e,space:r,force:n}){let a=`[${W.name}]`;try{if(x&&console.log(`${a} starting...`),!r)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(!o&&(t??[]).length===0)throw new Error("addr or addrs required. (E: 1a0b92564ba942f1ba91a089ac1a2125)");o&&(t?.length??0)>0&&(console.warn(`${a} both addr and addrs provided, but supposed to be used one or the other. (W: 87226c2ac50e4ea28211334a7b58782f)`),t.includes(o)||t.push(o)),t=(t??[]).length>0?t:[o];let s=await r.argy({ibMetadata:Ht({space:r}),argData:{cmd:"get",ibGibAddrs:t,isDna:e}}),i=await r.witness(s);return i?.data?.success?(x&&console.log(`${a} got.`),{success:!0,ibGibs:i.ibGibs,rawResultIbGib:i}):(x&&console.log(`${a} didn't get.`),{success:!1,errorMsg:i.data?.errors?.join("|")||`${a} something went wrong. addrs: ${t.join(`
2
+ `)} (E: b9e9d5ce0cde4122bfb74f7688db85e0)`,rawResultIbGib:i})}catch(s){return console.error(`${a} ${s.message}`),{errorMsg:s.message}}}b(W,"getFromSpace");async function Xe({ibGib:o,ibGibs:t,isDna:e,force:r,space:n}){let a=`[${Xe.name}]`;try{if(!o&&(t??[]).length===0)throw new Error("ibGib or ibGibs required. (E: e59c4de3695f4dd28c8fe82dbb9c4e90)");if(!n)throw new Error("space required. (E: dd0b7189c67c43c586b905a8ed6f51c9)");o&&(t??[]).length>0&&(console.warn(`${a} Both ibGib and ibGibs is assigned, whereas this is intended to be exclusive one or the other. (W: 4c797835b620445f88e4cba6b5aa3460)`),t.some(c=>c.gib===o.gib)||(t=t.concat([o]))),t=t??[o],x&&console.log(`${a} ibGibs.length: ${t.length}`);let s=await n.argy({ibMetadata:Ht({space:n}),argData:{cmd:"put",force:r,isDna:e,ibGibAddrs:t.map(c=>y({ibGib:c}))},ibGibs:t.concat()}),i=await n.witness(s);if(i.data?.success)return(i.data.warnings??[]).length>0&&i.data.warnings.forEach(c=>console.warn(`${a} ${c}`)),{success:!0};{let c=i?.data?.errors?.length>0?`Error(s) putting in local space:
3
+ ${i.data.errors.join(`
4
+ `)}`:"(UNEXPECTED) unknown error putting ibGibs (E: 3d7426d4527243b79c5e55eb25f3fa73)";throw new Error(c)}}catch(s){return console.error(`${a} ${s.message}`),{errorMsg:s.message}}}b(Xe,"putInSpace");async function Na({addr:o,isDna:t,space:e}){let r=`[${Na.name}]`;try{if(!e)throw new Error("space required. (E: 40ab3b51e91c4b5eb4f215baeefbcef0)");if(!e.data)throw new Error("space.data required. (E: 0d02c8e85ee143b8bd6a1a1db0d9af1b)");r=`${r}[${e.data.name||"noname?"}][${e.data.uuid||"nouuid?"}]`;let n=await e.argy({ibMetadata:Ht({space:e}),argData:{cmd:"delete",ibGibAddrs:[o],isDna:t}}),a=await e.witness(n);if(a.data?.success)return{success:!0};{a.data?.warnings?.length>0&&console.warn(`${r} warnings with delete (${o}): ${a.data.warnings.join("|")}`),a.data?.addrs?.length>0&&console.warn(`${r} partial addrs deleted: ${a.data.addrs.join("|")}`);let s=a.data?.errors?.join("|")||`${r} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;return s.includes("File does not exist")&&x&&console.log(`${r} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`),{errorMsg:s}}}catch(n){return console.error(`${r} ${n.message}`),{errorMsg:n.message}}}b(Na,"deleteFromSpace");async function ge({resTransform:o,space:t,force:e}){let r=`[${ge.name}]`;try{if(x&&console.log(`${r} starting... (I: dc6835614ff1a1b82b179225023ae823)`),!t)throw new Error("space required. (E: cf94f1d74f1c4561bb88025a2095965b)");let{newIbGib:n,intermediateIbGibs:a,dnas:s}=o,i=[n,...a||[]],c=await t.argy({ibMetadata:Ht({space:t}),argData:{cmd:"put",force:e,ibGibAddrs:i.map(d=>y({ibGib:d}))},ibGibs:i.concat()}),l=await t.witness(c);if(l.data?.success)l.data.warnings?.length>0&&l.data.warnings.forEach(d=>console.warn(`${r} ${d}`));else{let d=l?.data?.errors?.length>0?l.data.errors.join(`
5
+ `):"unknown error putting ibGibs";throw new Error(d)}if(s?.length??!1){let d=await t.argy({ibMetadata:Ht({space:t}),argData:{cmd:"put",isDna:!0,force:e,ibGibAddrs:s.map(p=>y({ibGib:p}))},ibGibs:s.concat()}),f=await t.witness(d);if(f.data?.success)f.data.warnings?.length>0&&f.data.warnings.forEach(p=>console.warn(`${r} ${p}`));else{let p=f?.data?.errors?.length>0?f.data.errors.join(`
6
+ `):"unknown error putting dna ibGibs";throw new Error(p)}}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{x&&console.log(`${r} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}b(ge,"persistTransformResult");async function ff({type:o,rel8nName:t,space:e}){let r=`[${ff.name}]`;try{if(!e)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await tn({type:o,space:e});if(!n)throw new Error(`couldn't get special (${o}) (E: a65bef190416479697605be486846731)`);let a=n.rel8ns?n.rel8ns[t]||[]:[],s=[];for(let i=0;i<a.length;i++){let c=a[i],l=await W({addr:c,space:e});if(l.success&&l.ibGibs?.length===1)s.push(l.ibGibs[0]);else throw new Error(`couldn't get addr: ${c} (E: 76ef256ee80149ab860c5786484b0e89)`)}return s}catch(n){throw console.error(`${r} ${n.message}`),n}}b(ff,"getSpecialRel8dIbGibs");async function tn({type:o,initialize:t,space:e,zeroSpace:r,fnUpdateBootstrap:n,fnBroadcast:a,fnGetInitializing:s,fnSetInitializing:i,dontWarnIfNotExist:c}){let l=`[${tn.name}]`;try{if(!e)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let d=Ge({type:o}),f=await rn({key:d,space:e,dontWarn:c||!!t});if(!f){if(t&&(!s||!i))throw new Error("if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)");if(t&&!s()){i(!0);try{if(!r)throw new Error("zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)");f=await Hi({type:o,space:e,zeroSpace:r,fnBroadcast:a,fnUpdateBootstrap:n})??void 0}catch(m){console.error(`${l} error initializing: ${m.message}`)}finally{i(!1)}}if(!f){if(s&&s())return console.warn(`${l} couldn't get addr, but we're still initializing...`),null;throw new Error("Special address not in config and couldn't initialize it either. (E: d8ebdc9eaaa640b99cd206f132962c93)")}}x&&console.log(`${l} getting addr: ${f}`);let p=await W({addr:f,space:e});if(p.success||(p=await W({addr:f,space:e}),p.success&&(console.warn(`${l} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await Xe({ibGib:p.ibGibs[0],space:e})).success||console.warn(`${l} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!p.success)throw new Error(p.errorMsg);if(p.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let h=p.ibGibs[0],g=await Me({ibGibs:[h],space:e});if(g?.data?.success&&g.data.addrs?.length===1){let m=y({ibGib:h}),E=g.data.addrs[0];E!==m&&console.warn(`${l} latest addr is not the one associated with the local space.
7
+ specialAddr: ${m}
8
+ latestAddr: ${E} (W: 141b69dc3c414efc9645bb76fcf12df9)`)}return h}catch(d){let f=`${l} ${d.message}`;return f.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(f),null}}b(tn,"getSpecialIbGib");async function rn({key:o,space:t,dontWarn:e}){let r=`[${rn.name}](${o})`;try{if(x&&console.log(`${r} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!t)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!t.rel8ns){(x||!e)&&console.warn(`${r} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!t.rel8ns[o]){(x||!e)&&console.warn(`${r} space.rel8ns[${o}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(t.rel8ns[o].length===1)return x&&console.log(`${r} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),t.rel8ns[o][0];if(t.rel8ns[o].length>1)return(x||!e)&&console.warn(`${r} more than one config addr with ${o} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),t.rel8ns[o][0];x&&console.log(`${r} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${r} ${n.message}`);return}}b(rn,"getConfigAddr");async function ke({key:o,addr:t,space:e,zeroSpace:r,fnUpdateBootstrap:n}){let a=`[${ke.name}]`;try{if(!e)throw new Error("space required. (E: c28b663c991d44419aef1026cc689636)");if(!r)throw new Error("zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)");let s={[o]:[t]},i=await He({src:e.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",o],rel8nsToAddByAddr:s,nCounter:!0});if(!i.newIbGib)throw new Error("create new space failed.");await ge({resTransform:i,space:r}),await ge({resTransform:i,space:e});let c=i.newIbGib;return await e.loadIbGibDto(c),n?await n(c):console.warn(`${a} fnUpdateBootstrap is falsy. (W: 9fb874de2b19454dac18645e61ac463f)`),c}catch(s){throw console.error(`${a} ${s.message}`),s}}b(ke,"setConfigAddr");async function Vi({space:o}){let t=`[${Vi.name}]`;try{if(!o)throw new Error("space required. (E: f0d546101fba4c169256158114ab3c56)");let e=await tn({type:"roots",space:o});if(!e)throw new Error("Roots not initialized. (E: 89b1ba12ed12416aac41cef9fdaf1fc2)");if(!e.rel8ns)throw new Error("Roots not initialized properly. No rel8ns. (E: 8513a07cf530484db9521a2a3a27b7f6)");if(!e.rel8ns.current)throw new Error("Roots not initialized properly. No current root. (E: 459c3a007a30486d96fb8d83f696e239)");if(e.rel8ns.current.length===0)throw new Error("Invalid Roots: empty current root rel8n. (E: bede5864090440bca01ea7ab7fd107d6)");if(e.rel8ns.current.length>1)throw new Error("Invalid Roots: multiple current roots selected. (E: 97561acbf63a48ecaa037697bd26555a)");let r=e.rel8ns.current[0],n=await W({addr:r,space:o});if(n.ibGibs?.length===1)return n.ibGibs[0];throw new Error(`could not get current root. addr: ${r}`)}catch(e){console.error(`${t} ${e.message}`);return}}b(Vi,"getCurrentRoot");async function Da({root:o,space:t,zeroSpace:e,fnUpdateBootstrap:r,fnBroadcast:n}){let a=`[${Da.name}]`;try{if(x&&console.log(`${a} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`),!o)throw new Error("root required.");if(!t)throw new Error("space required. (E: 186af2731c5342a78b063a0a4346f3db)");let s=y({ibGib:o}),i=await tn({type:"roots",space:t});if(!i)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let l=await He({src:i,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[s]},nCounter:!0});await ge({resTransform:l,space:t});let d=Ge({type:"roots"}),f=l.newIbGib,p=y({ibGib:f});await ke({key:d,addr:p,space:t,zeroSpace:e,fnUpdateBootstrap:r}),await Te({ibGib:f,space:t,fnBroadcast:n})}catch(s){throw console.error(`${a} ${s.message}`),s}finally{x&&console.log(`${a} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}b(Da,"setCurrentRoot");async function Ki({ibGib:o,linked:t,rel8nName:e,space:r,fnBroadcast:n,zeroSpace:a,fnUpdateBootstrap:s}){let i=`[${Ki.name}]`;try{if(!r)throw new Error("space required. (E: f2758eab3bb844d2b749515672d9e392)");if(!o)throw new Error("ibGib required (E: f1bfd67754a7271553f4af544d30bc22)");let c=await Vi({space:r});if(!c)throw new Error("currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750");let l=ee({ibGib:o,defaultIfNone:"incomingAddr"}),d=y({ibGib:o});if(e&&l&&c.rel8ns&&c.rel8ns[e]&&c.rel8ns[e].includes(l))return;e=e||da;let f=await He({src:c,dna:!1,linkedRel8ns:t?["past","ancestor",e]:["past","ancestor"],rel8nsToAddByAddr:{[e]:[d]},nCounter:!0});await ge({resTransform:f,space:r});let p=f.newIbGib,h=y({ibGib:p});x&&console.log(`${i} updating _currentRoot root. newRootAddr: ${h}`),await Te({ibGib:p,space:r,fnBroadcast:n}),await Da({root:p,space:r,zeroSpace:a,fnUpdateBootstrap:s,fnBroadcast:n})}catch(c){console.error(`${i} ${c.message}`);return}}b(Ki,"rel8ToCurrentRoot");async function xa({targetIbGib:o,space:t}){let e=`[${xa.name}]`;try{x&&console.log(`${e} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let r=await Ca({targetIbGib:o}),n=await Xe({ibGib:r,space:t});if(!n.success)throw new Error(`error putting metaStone in space. error: ${n.errorMsg??"[unknown error (E: 45f700f4f1ff463ca8f5353c8e796ac7)]"} (E: 4c25379e66365055e3e423561a7d6123)`)}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{x&&console.log(`${e} complete.`)}}b(xa,"createAndSaveNewMetaStone");async function Te({ibGib:o,space:t,fnBroadcast:e}){let r=`[${Te.name}]`,n=x;try{let a=y({ibGib:o});if(r=`${r}[${a}]`,!t)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(x&&console.log(`${r} starting...`),!Oe({ibGibAddr:a}).tjpGib&&!o.data?.isTjp){x&&console.log(`${r} incoming ibGib has no timeline, so no broadcast. still going to create a metastone for it and return early. (I: 649752e3b1be0e0ceb078e0ec2a84f23)`),await xa({targetIbGib:o,space:t});return}let i=ee({ibGib:o,defaultIfNone:"undefined"});if(!i){let g=o.data?.isTjp?o:await uo({ibGib:o,space:t});g||(console.warn(`${r} tjp not found for ${a}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`),g=o),i=y({ibGib:g})}if(!i)throw new Error("(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)");let c=b(async()=>{x&&console.log(`${r} adding/replacing latest. tjp: ${i} (I: 7f848da003a2436089fd6f044d96bb42)`),await xa({targetIbGib:o,space:t}),e&&(x&&console.log(`${r} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{x&&console.log(`${r} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),e({ib:"IbGibTimelineUpdateInfo",tjpAddr:i,latestAddr:a,latestIbGib:o})}))},"replaceLatest");if(o.data?.isTjp){x&&console.log(`${r} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}x&&console.log(`${r} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let l=await Me({ibGibs:[o],space:t});if(!l.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:d,latestAddrsMap:f}=l.data;if(!d){let{errors:g}=l.data;throw g??=["[unknown error (E: 344857f1853641aa842cea3931f90428)]"],new Error(`resLatest.success falsy. errors: ${F(g)}. addr: ${a} (E: b66721da6e1ef9ac4f4089e86c059323)`)}if(!f)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let p=Object.keys(f);if(p.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(p[0]!==a)throw new Error(`(UNEXPECTED) latestAddrsMap has 1 key (correct) but the key isn't the incoming ibGibAddr? (incorrect). incoming ibGibAddr: ${a}. key found: ${p[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);x&&(console.log(`${r} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(f));let h=f[a];if(h)if(h===a){x&&console.log(`${r} no other found. possible idempotent replacement. addr: ${a} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{x&&console.log(`${r} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${h}. incoming addr: ${a} (I: 6cadf13f82aabeb71d76babf1813e623)`);let g=await W({addr:h,space:t});if(!g.success||g.ibGibs?.length!==1){console.error(`Didn't find existing latest ibGib (${h}). I haven't implemented more robust multi-node/distributed strategies for this scenario yet. so we are going ahead with setting the incoming ibgib as the latest in the timeline. (E: 10f6cca6e5ef45bfacbfe48f652e2102)`),await c();return}let m=g.ibGibs[0];if(typeof o.data?.n=="number"&&o.data.n>=0){x&&console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${o.data.n}`);let S=o.data.n;if(typeof m.data?.n=="number"&&m.data.n>=0){let _=m.data.n;if(S>_)x&&console.log(`${r} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{x&&console.log("is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)"),console.warn(`${r} incoming ibGib (${a}) is NOT NEWER than existing latest (${h}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${S}. n_existingLatest: ${_}. space.ib: ${t.ib} (W: 057baadca494473dabb26fb4fb879774)`);return}}else m.data?.isTjp&&o.data.n===0?await c():(console.warn(`${r} (UNEXPECTED) only existingLatestIbGib (isTjp: ${m.data?.isTjp}) has a data.n counter? ibGib.data.n: ${o.data.n}. usually this only happens when existing latest is a tjp and the new ibGib we are registering is n === 0. This is falsy in this instance though. We will go ahead and replace the latest with the new one, but this is an anomalous state. (W: 73d08aea17ad4e1481a5f97e2556a878)`),console.log(`${r} console.dir(existingLatestIbGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(m),console.log(`${r} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(o),await c())}else if(x&&console.log(`${r} no nCounter found. Trying brute force method.`),await oc({ibGib:o,ibGibAddr:a,existingLatest:m,existingLatestAddr:h,tjpAddr:i,space:t})===a)await c();else return}else if(h===null){x&&console.log(`${r} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${a} (I: 4f2bbc32b31e4fa982d95b3a785db82f)`),await c();return}else throw new Error("(UNEXPECTED) latestAddr is falsy but not null? the getLatestAddrs impl in the space should be guaranteed to provide either the incoming ibgib addr, the latest addr (if exists), or null if not found. (E: 3159dd531c0bc0efc1ece116adf28923)")}catch(a){throw console.error(`${r} ${a.message}`),a}finally{x&&console.log(`${r} complete.`),x=n}}b(Te,"registerNewIbGib");async function jr({type:o,rel8nName:t,ibGibsToRel8:e,ibGibsToUnRel8:r,addrsToUnRel8:n,linked:a,severPast:s,deletePreviousSpecialIbGib:i,space:c,zeroSpace:l,fnUpdateBootstrap:d,fnBroadcast:f}){let p=`[${jr.name}](type:${o},rel8nName:${t})`;try{if(!c)throw new Error("space required. (E: 956192eea28047eba6dad81620bb96fb)");if((e??[]).length===0&&(r??[]).length===0&&(n??[]).length===0)throw new Error("either ibGibsToRel8 or ibGibsToUnRel8 required. (E: 5add49c8e46a54e2c6b057c22646a822)");if((r??[]).length>0&&(n??[]).length>0)throw new Error("can't provide both ibGibsToUnRel8 and addrsToUnRel8. There isn't a technical reason but I'm too tired right now to implement the overhead to enable this atow (05/2025). (E: 31ef66be26349cfe1b1f352389b99425)");let h=e?.map(I=>y({ibGib:I}));n??=r?.map(I=>y({ibGib:I}));let g=Ge({type:o}),m=await rn({key:g,space:c});if(!m)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let E=await W({addr:m,space:c});if(!E.success)throw new Error("couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)");if(!E.ibGibs)throw new Error("resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)");if(E.ibGibs.length!==1)throw new Error(`resGetSpecial.ibGibs count is not 1 (${E.ibGibs.length}) (E: b4547789016a4729af30cd972a4ca4ab)`);let S=E.ibGibs[0],A=await He({src:S,rel8nsToAddByAddr:h?{[t]:h}:void 0,rel8nsToRemoveByAddr:n?{[t]:n}:void 0,dna:!1,linkedRel8ns:a?[pe.past,t]:[pe.past],nCounter:!0}),_=A.newIbGib;if(s){if(A.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");_.rel8ns.past=[],_.gib=await ce({ibGib:_})}await ge({resTransform:A,space:c});let $=y({ibGib:_}),T=ee({ibGib:_});return await ke({key:g,addr:$,space:c,zeroSpace:l,fnUpdateBootstrap:d}),i&&await Na({addr:m,space:c}),await Te({ibGib:_,fnBroadcast:f,space:c}),$}catch(h){throw console.error(`${p} ${h.message}`),h}}b(jr,"rel8ToSpecialIbGib");async function uo({ibGib:o,naive:t=!0,space:e}){let r=`[${uo.name}]`;try{if(!e)throw new Error("space required. (E: 941f973d50e84415b58724af173f52c2)");if(!o)throw new Error("ibGib required.");let n=y({ibGib:o}),{gib:a}=J({ibGibAddr:n});if(a===z||await Ba({ibGib:o,naive:t}))return o;if(!o.rel8ns){x&&console.log(`${r} ibgib not tjp in data, and rel8ns is falsy. so tjp is undefined (I: acdadb76a7568807db7a68f6f866de22)`);return}if(o.rel8ns.tjp&&o.rel8ns.tjp.length>0){let f=o.rel8ns.tjp[0],p=await W({addr:f,space:e});if(p.success&&p.ibGibs?.length===1)return p.ibGibs[0];{let h=p.errorMsg??"[unspecified error in get result]";throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${h} (E: 94f0340706ad48c794c6a62c1b235a22)`)}}let i=o.rel8ns.past||[];if(i.length===0){console.warn(`${r} past.length === 0, so there is no tjp.`),x&&console.log(`${r} ibgib is not tjp in data, not in tjp rel8n, and past is empty. so tjp is undefined (I: bf06f664917dcf4492fb9c4c106a6222)`);return}let c=i[i.length-1],l=await W({addr:c,space:e});if(!l.success||l.ibGibs?.length!==1)throw new Error(`get past failed. addr: ${c}`);let d=l.ibGibs[0];return await uo({ibGib:d,naive:t,space:e})}catch(n){throw console.error(`${r} ${n.message}`),n}}b(uo,"getTjpIbGib");async function Hi({type:o,space:t,zeroSpace:e,fnUpdateBootstrap:r,fnBroadcast:n}){let a=`[${Hi.name}]`;try{if(!t)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(o){case"roots":return Yi({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"tags":return Xi({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"secrets":return zi({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"encryptions":return Ji({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"outerspaces":return Zi({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"autosyncs":return Qi({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"robbots":return ec({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});case"apps":return tc({space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});default:return rc({type:o,space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r})}}catch(s){throw console.error(`${a} ${s.message}`),s}}b(Hi,"createSpecial");async function xt({type:o,skipRel8ToRoot:t,space:e,zeroSpace:r,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${xt.name}][${o||"falsy type?"}]`;try{x&&console.log(`${s} starting...`);let i=Pa({type:o}),c=B.primitive({ib:i}),l=await Bo({src:c,destIb:i,linkedRel8ns:[pe.past,pe.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await ge({resTransform:l,space:e}),o!=="roots"&&o!=="latest"&&!t&&await Ki({ibGib:l.newIbGib,linked:!0,space:e,zeroSpace:r,fnBroadcast:a,fnUpdateBootstrap:n}),x&&console.log(`${s} complete.`),l.newIbGib}catch(i){throw console.error(`${s} ${i.message}`),i}}b(xt,"createSpecialIbGib");async function Xi({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${Xi.name}]`;try{if(!o)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let a=Ge({type:"tags"}),s=await xt({type:"tags",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e}),i=y({ibGib:s});await ke({key:a,addr:i,space:o,zeroSpace:t,fnUpdateBootstrap:e});let c=[{text:"home",icon:"home-outline"},{text:"favorite",icon:"heart-outline"}];for(let l of c)i=(await qi({...l,space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e})).newTagsAddr,await ke({key:a,addr:i,space:o,zeroSpace:t,fnUpdateBootstrap:e});return i}catch(a){return console.error(`${n} ${a.message}`),null}}b(Xi,"createSpecial_Tags");async function qi({text:o,icon:t,description:e,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${qi.name}]`;try{if(x&&console.log(`${i} starting...`),!r)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!o)throw new Error(`${i} text required`);t=t||ui,e=e||gi;let c=$r(o),l=B.primitive({ib:"tag"}),d=await B.firstGen({parentIbGib:l,ib:c,data:{text:o,icon:t,description:e},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),f=d.newIbGib;await ge({resTransform:d,space:r}),await Te({ibGib:f,space:r,fnBroadcast:s});let p=await bf({tagIbGib:f,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newTagIbGib:f,newTagsAddr:p}}catch(c){throw console.error(`${i} ${c.message}`),c}finally{x&&console.log(`${i} complete.`)}}b(qi,"createTagIbGibAndSundry");async function Yi({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${Yi.name}]`;try{if(!o)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let a=Ge({type:"roots"}),s=await xt({type:"roots",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e}),i=y({ibGib:s});await ke({key:a,addr:i,space:o,zeroSpace:t,fnUpdateBootstrap:e});let l=["A","B","C","D","E","F","G"].map(f=>({text:`${f}root`,icon:fa,description:ba})),d;for(let f=0;f<l.length;f++){let p=l[f],h=await Wi({...p,space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r});if(d||(d=h.newRootIbGib),!h.newRootIbGib)throw new Error("(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)");i=h.newRootsAddr,await ke({key:a,addr:i,space:o,zeroSpace:t,fnUpdateBootstrap:e})}if(!d)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await Da({root:d,space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}),i=await rn({key:a,space:o}),!i)throw new Error("(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)");return i}catch(a){return console.error(`${n} ${a.message}`),null}}b(Yi,"createSpecial_Roots");async function Wi({text:o,icon:t,description:e,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Wi.name}]`;try{if(!r)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");o=o||hi,t=t||fa,e=e||ba;let c=Ra(o),l=B.primitive({ib:"root"}),d=await B.firstGen({parentIbGib:l,ib:c,data:{text:o,icon:t,description:e},linkedRel8ns:[pe.past,pe.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:f}=d;await ge({resTransform:d,space:r});let p=await jr({type:"roots",rel8nName:la,ibGibsToRel8:[f],space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newRootIbGib:f,newRootsAddr:p}}catch(c){throw console.error(`${i} ${c.message}`),c}}b(Wi,"createRootIbGib");async function zi({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${zi.name}]`;try{if(!o)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let a,s=Ge({type:"secrets"}),i=await xt({type:"secrets",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e});return a=y({ibGib:i}),await ke({key:s,addr:a,space:o,zeroSpace:t,fnUpdateBootstrap:e}),a}catch(a){return console.error(`${n} ${a.message}`),null}}b(zi,"createSpecial_Secrets");async function Ji({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${Ji.name}]`;try{if(!o)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let a,s=Ge({type:"encryptions"}),i=await xt({type:"encryptions",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e});return a=y({ibGib:i}),await ke({key:s,addr:a,space:o,zeroSpace:t,fnUpdateBootstrap:e}),a}catch(a){return console.error(`${n} ${a.message}`),null}}b(Ji,"createSpecial_Encryptions");async function Zi({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${Zi.name}]`;try{if(!o)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let a,s=Ge({type:"outerspaces"}),i=await xt({type:"outerspaces",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e});return a=y({ibGib:i}),await ke({key:s,addr:a,space:o,zeroSpace:t,fnUpdateBootstrap:e}),a}catch(a){return console.error(`${n} ${a.message}`),null}}b(Zi,"createSpecial_OuterSpaces");async function Qi({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${Qi.name}]`;try{if(!o)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Ge({type:"autosyncs"}),i=await xt({type:"autosyncs",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e});return a=y({ibGib:i}),await ke({key:s,addr:a,space:o,zeroSpace:t,fnUpdateBootstrap:e}),a}catch(a){return console.error(`${n} ${a.message}`),null}}b(Qi,"createSpecial_Autosyncs");async function ec({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${ec.name}]`;try{if(!o)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Ge({type:"robbots"}),i=await xt({type:"robbots",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e});return a=y({ibGib:i}),await ke({key:s,addr:a,space:o,zeroSpace:t,fnUpdateBootstrap:e}),a}catch(a){return console.error(`${n} ${a.message}`),null}}b(ec,"createSpecial_Robbots");async function tc({space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}){let n=`[${tc.name}]`;try{if(!o)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Ge({type:"apps"}),i=await xt({type:"apps",space:o,zeroSpace:t,fnBroadcast:r,fnUpdateBootstrap:e});return a=y({ibGib:i}),await ke({key:s,addr:a,space:o,zeroSpace:t,fnUpdateBootstrap:e}),a=await Qo({defaultAppData:Di,defaultAppRel8ns:Oi,space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}),a=await Qo({defaultAppData:Li,defaultAppRel8ns:Pi,space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}),a=await Qo({defaultAppData:Ri,defaultAppRel8ns:Bi,space:o,zeroSpace:t,fnUpdateBootstrap:e,fnBroadcast:r}),a}catch(a){return console.error(`${n} ${a.message}`),null}}b(tc,"createSpecial_Apps");async function Qo({defaultAppData:o,defaultAppRel8ns:t,space:e,zeroSpace:r,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${Qo.name}]`;try{x&&console.log(`${s} starting... (I: 677f68789abdc7316887e8f38c764e22)`),x&&console.log(`${s} starting...`);let i=U(o),c=t?U(t):void 0;i.uuid=!i.uuid||i.uuid===Aa?await V():i.uuid;let{classname:l}=i,d=Sa({appData:i,classname:l}),f=await B.firstGen({ib:d,parentIbGib:B.primitive({ib:`app ${l}`}),data:i,rel8ns:c,dna:!0,linkedRel8ns:[pe.ancestor,pe.past],nCounter:!0,tjp:{timestamp:!0}});return await ge({resTransform:f,space:e}),await Te({ibGib:f.newIbGib,fnBroadcast:a,space:e}),await jr({type:"apps",rel8nName:Vo,ibGibsToRel8:[f.newIbGib],fnBroadcast:a,fnUpdateBootstrap:n,space:e,zeroSpace:r})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{x&&console.log(`${s} complete.`)}}b(Qo,"createApp");async function rc({type:o,space:t,zeroSpace:e,fnUpdateBootstrap:r,fnBroadcast:n}){let a=`[${rc.name}]`;try{if(!t)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");x&&console.log(`${a} creating special of type: ${o} (I: 283c8bb30ed6f9698b74b886c6078622)`);let s,i=Ge({type:o}),c=await xt({type:o,space:t,zeroSpace:e,fnBroadcast:n,fnUpdateBootstrap:r});return s=y({ibGib:c}),await ke({key:i,addr:s,space:t,zeroSpace:e,fnUpdateBootstrap:r}),s}catch(s){return console.error(`${a} ${s.message}`),null}}b(rc,"createSpecial_Default");async function oc({ibGib:o,ibGibAddr:t,existingLatest:e,existingLatestAddr:r,tjpAddr:n,space:a}){let s=`[${oc.name}][${t}]`;try{if(x&&console.log(`${s} starting...`),!a)throw new Error("space required. (E: 64eb9a271f5d43deadec30b9638746c8)");let i=o.rel8ns?.past||[],c=e.rel8ns?.past||[];if(i.length===1&&c.length===0)return x&&console.log(`prospective has a past, so it "must" be newer. (won't quote "must" anymore)`),t;if(c.length===1&&i.length===0)return x&&console.log("existing has a past, so it must be newer."),r;if(c.length===0&&i.length===0)return console.warn(`${s} neither existing latest nor prospective new ibGib has a past, so keeping existing.`),r;if(c.includes(t))return x&&console.log("existing by definition is newer"),r;if(i.includes(r))return x&&console.log("ibGib by definition is newer"),t;if(r===t)return x&&console.log("they're the same!"),r;if(r===n&&e.rel8ns?.tjp?.length===1)return x&&console.log("ibGib must be newer because the existingLatestAddr is the tjp, which is by definition first in unique past."),t;if(t===n&&o.rel8ns?.tjp?.length===1)return x&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),r;x&&console.log(`${s} brute forcing through iterating the pasts.`);let l,d=-1,f=b(async(g,m,E)=>{let S=g.rel8ns?.past||[];if(S.includes(E))return l=y({ibGib:g}),-1;if(S.length===0)return m;let A=m+S.length;if(d!==-1&&A>d)return l=y({ibGib:g}),-1;let _=await W({addr:S[0],space:a});if(!_.success||_.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${S[0]}`);return f(_.ibGibs[0],m+S.length,E)},"getPastCount");x&&console.log(`${s} doing ibGibPastCount`);let p=await f(o,0,r);if(l)return l;x&&console.log(`${s} Doing existingPastCount`),d=p;let h=await f(e,0,t);return l||(p>h?(x&&console.log(`${s} ibGibPastCount (${p}) is longer than existingPastCount (${h}), so ibGib is newer.`),l=t):(x&&console.log(`${s} existingPastCount (${h}) is longer than ibGibPastCount (${p}), so ibGib is newer.`),l=r),l)}catch(i){throw console.error(`${s} ${i.message}`),i}finally{x&&console.log(`${s} complete.`)}}b(oc,"getLatestAddr_Brute");function bf({tagIbGib:o,space:t,zeroSpace:e,fnUpdateBootstrap:r,fnBroadcast:n}){return jr({type:"tags",rel8nName:pa,ibGibsToRel8:[o],space:t,zeroSpace:e,fnUpdateBootstrap:r,fnBroadcast:n})}b(bf,"rel8TagToTagsIbGib");function Oa({space:o,scope:t}){let e=`[${Oa.name}]`;try{if(x&&console.log(`${e} starting...`),!o)throw new Error("space required. (E: 3ba16e6c3e5e47948b0e63448da11752)");if(!o.data?.uuid)throw new Error("invalid space (space.data.uuid falsy) (E: 273262b32f2ef27b2e690bc699f33822)");if(!t)throw new Error("scope required. (E: f47801d6c45e2247b42a53d9b604b522)");for(;t.includes(Ae);)x&&console.log(`${e} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),t=t.replace(Ae,"_");let r=o.data.uuid,n=`${fi} ${r} ${t}`;return y({ib:n,gib:z})}catch(r){throw console.error(`${e} ${r.message}`),r}finally{x&&console.log(`${e} complete.`)}}b(Oa,"getSpaceLockAddr");async function Ct({space:o,scope:t,secondsValid:e,maxDelayMs:r,fn:n,callerInstanceId:a,maxLockAttempts:s}){let i=`[${Ct.name}]`;try{if(x&&console.log(`${i} starting...`),!o)throw new Error("space required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");if(!e)throw new Error("secondsValid required. (E: 92c5610e57ceede5ce83cff86d5c2a22)");if(e<0)throw new Error("secondsValid must be positive. (E: 970a7510c517235d7a355a843d18d222)");if(!n)throw new Error("fn required (E: 7022e280252ec2faf756b6db05c56e22)");let c;x&&console.log(`${i} attempting to acquire lock with scope ${t} (I: fed36d42a975b1c52897a4df804ac722)`);let l;r=(r??0)>0?r:bi;let d=0;s=s??!1?s:pi;do{if(l=await nc({space:o,scope:t,secondsValid:e,instanceId:a}),l?.data?.success)break;let p=Math.ceil(Math.random()*r);await Se(p),d++}while(d<s);if(l?.data?.success)x&&console.log(`${i} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`);else throw new Error(`could not acquire lock after ${d} attempts with intermittent delays of ${r} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);let f=`${i}[fn]`;try{x&&console.log(`${f} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(p){throw console.error(`${f} ${p.message}`),p}finally{x&&console.log(`${f} unlocking space with scope: ${t} (I: 21034d9c3395499756e9000e40417d22)`),await ac({space:o,scope:t,instanceId:a}),x&&console.log(`${f} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${i} ${c.message}`),c}finally{x&&console.log(`${i} complete.`)}}b(Ct,"execInSpaceWithLocking");async function en({zeroSpace:o}){let t=`[${en.name}]`;try{if(x&&console.log(`${t} starting...`),!o)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let e=yr;x&&console.log(`${t} getting from zeroSpace...`);let r=await o.argy({ibMetadata:Ht({space:o}),argData:{cmd:"get",ibGibAddrs:[e]}}),n=await o.witness(r);if(n?.data?.success&&n.ibGibs?.length===1){let a=n.ibGibs[0];return x&&console.log(`${t} bootstrapibGib found: ${F(a)}`),await Ta(a)?a:(x&&console.log(`${t} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return x&&console.log(`${t} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(e){throw console.error(`${t} ${e.message}`),e}finally{x&&console.log(`${t} complete.`)}}b(en,"getValidatedBootstrapIbGib");async function pf({zeroSpace:o,bootstrapIbGib:t,localSpaceId:e,lock:r,callerInstanceId:n,fnDtoToSpace:a,localSpaceCacheSvc:s}){let i=`[${pf.name}]`;try{if(!o)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!t)if(x&&console.log(`${i} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),r){let d=yr;x&&console.log(`${i} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),t=await Ct({space:o,scope:d,fn:b(async()=>{let f=await en({zeroSpace:o});if(f)return f;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:ca})}else x&&console.log(`${i} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),t=await en({zeroSpace:o})??void 0;if(!t)throw new Error("bootstrapIbGib falsy. not initialized? (E: 91f5c82b5e124178d958701ebcb09822)");if(!t.data)throw new Error("(UNEXPECTED) bootstrapIbGib.data required. invalid bootstrap? (E: 568c6b837c1a39f7a25d188a90167423)");e=e??t.data[Tt];let c=t.rel8ns[e][0],l=b(async()=>{let d=await o.argy({ibMetadata:Ht({space:o}),argData:{cmd:"get",ibGibAddrs:[c]}}),f=await o.witness(d);if(f?.data?.success&&f.ibGibs?.length===1){let p=f.ibGibs[0],h=await a(p);return s&&(h.cacheSvc=s),h}else throw new Error(`Could not get local space addr (${c}) specified in bootstrap space (${y({ibGib:t})}). (E: 6d6b45e7eae4472697ddc971438e4922)`)},"fnGet");return r?(x&&console.log(`${i} getting localSpaceId (${e}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await Ct({space:o,scope:e,fn:b(()=>l(),"fn"),callerInstanceId:n,secondsValid:ca})):(x&&console.log(`${i} getting localSpaceId (${e}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),l())}catch(c){throw console.error(`${i} ${c.message}`),c}}b(pf,"getLocalSpace");async function nc({space:o,scope:t,secondsValid:e,instanceId:r}){let n=`[${nc.name}]`;try{if(x&&console.log(`${n} starting...`),!o)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!t)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");if(!e)throw new Error("secondsValid required and positive (E: b42b6733638b46c06c9aff59a6c49822)");if(e<0)throw new Error("secondsValid must be positive (E: bbe3b6d567583bfb35a1c0825eb29622)");let a,s=Oa({space:o,scope:t}),i,c=await W({addr:s,space:o,force:!0});if(c.success&&c.ibGibs?.length===1?(i=c.ibGibs[0],i?.data?.expirationUTC?ta({expirationTimestampUTC:i.data.expirationUTC})&&(console.warn(`${n} ignoring expired existing lock in space at ${s}. Should be overwritten (W: 7421c5b051724b189f88cecbbd449b22)`),i=void 0):(console.error(`${n} (UNEXPECTED) exisingLock.data.expirationUTC falsy? (E: 218dc0e935534a149d0be153c532cf25)`),i=void 0)):x&&console.log(`${n} existing lock not found for ${s} (I: 191af56ec4e2db3d19084e46bf949222)`),i){if(!i.data)throw new Error("(UNEXPECTED) existingLock.data falsy? (E: 00069b4662e5566d971760d15e293723)");a=U(i),a.data.alreadyLocked=!0,a.data.success=!1}else{let{ib:l,gib:d}=J({ibGibAddr:s});a={ib:l,gib:d,data:{scope:t,secondsValid:e,instanceId:r,expirationUTC:ea({seconds:e})}};let f=await o.argy({ibMetadata:Ht({space:o}),argData:{cmd:"put",force:!0,ibGibAddrs:[s]},ibGibs:[a]}),p=await o.witness(f);if(p.data?.success)if((p.data.addrsAlreadyHave??[]).includes(s)){x&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${s}) (I: 2e8a1562947c40698110b64251141753)`);let h=await W({addr:s,space:o,force:!0});if(h.success&&h.ibGibs?.length===1){let g=h.ibGibs[0];a=U(g),a.data.alreadyLocked=!0,a.data.success=!1}else{let g=`${n} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;console.error(g),a.data.success=!1,a.data.errorMsg=g}}else a.data.success=!0;else{let h=`${n} there was an error putting the lock in the space: ${p.data?.errors?.join("|")}`;a.data.success=!1,a.data.errorMsg=h,console.error(h)}}return a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{x&&console.log(`${n} complete.`)}}b(nc,"lockSpace");async function ac({space:o,scope:t,instanceId:e}){let r=`[${ac.name}]`;try{if(x&&console.log(`${r} starting...`),!o)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!t)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=Oa({space:o,scope:t}),a=await Na({addr:n,space:o,force:!0});if(a.success){let{ib:s,gib:i}=J({ibGibAddr:n});return{ib:s,gib:i,data:{success:!0,instanceId:e,scope:t}}}else{let s=`Delete lock in space failed. delete errorMsg: ${a.errorMsg}`;if(s.includes("not implemented"))throw new Error(s);if(s.toLowerCase().includes("does not exist")||s.toLowerCase().includes("doesn't exist")||s.toLowerCase().includes("not found")){x&&console.log(`${r} ${s} (I: b647916fd0f3e5366e9387131be21c22)`);let{ib:i,gib:c}=J({ibGibAddr:n});return{ib:i,gib:c,data:{action:"unlock",success:!0,instanceId:e,scope:t}}}else console.warn(`${r} ${s} (W: 14c84fcac15944bd9a417099964d5d9d)`)}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{x&&console.log(`${r} complete.`)}}b(ac,"unlockSpace");async function hf({space:o,zeroSpace:t,setSpaceAsDefault:e,createIfNotFound:r}){let n=`[${hf.name}]`;try{if(x&&console.log(`${n} starting...`),!o)throw new Error("space required. (E: 6fc19548fa7d1d5219e19871f280a322)");if(!o.data?.uuid)throw new Error("space.data.uuid required (E: 6483188ca6f2ed2085fd355595f3ab22)");if(!t)throw new Error("zeroSpace required. (E: abbf156e18b1018d96273e22a260f122)");let a=o.data.uuid,s=y({ibGib:o}),i=await en({zeroSpace:t});if(i){if(x&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),i.data.spaceIds.includes(a)){x&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let d=i.rel8ns[a][0];d===s?x&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(x&&console.log(`${n} updating rel8ns[${a}] with newSpaceAddr (${s}). (Old address: ${d})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),i.rel8ns[a]=[s])}else x&&console.log(`${n} new space being rel8d. adding spaceId to data.spaceIds and amending rel8ns (I: 40903d71719aa1d56e498299f5699a22)`),i.data.spaceIds.push(a),i.rel8ns[a]=[s];e&&(x&&console.log(`${n} setting spaceId (${a}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),i.data[Tt]=a)}else{if(!r){x&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}x&&console.log(`${n} creating new bootstrap ibgib for spaceId (${a}) with address of (${s}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:d,gib:f}=J({ibGibAddr:yr});i=B.primitive({ib:d}),i.gib=f,i.data={[Tt]:a,[$i]:[a]},i.rel8ns={[a]:[s]}}if(!i)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");x&&console.log(`${n} saving bootstrapIbGib: ${F(i)} (I: 3cceca0b98dde90e4a58a734be252322)`);let c=await t.argy({ibMetadata:i.ib,argData:{cmd:"put",force:!0,ibGibAddrs:[y({ibGib:i})]},ibGibs:[i]});x&&console.log(`${n} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let l=await t.witness(c);if(l?.data?.success)x&&console.log(`${n} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`);else throw new Error(`${l?.data?.errors?.join("|")||"There was a problem with zeroSpace witnessing the bootstrap^gib primitive pointing to the new user space"}`);x&&console.log(`${n} complete.`)}catch(a){throw console.error(`${n} ${a.message}`),a}}b(hf,"updateBootstrapIbGib");function Ht({space:o}){return`${o.ib} ${rt()}`}b(Ht,"getSpaceArgMetadata");function pm({space:o}){return`${o.ib} ${rt()}`}b(pm,"getSpaceResultMetadata");function uf({space:o,spaceData:t,classname:e}){let r=`[${uf.name}]`;try{if(!o&&!t)throw new Error("either space or spaceData required (E: 4dabec34ee77d67c9cc30ee3c3049622)");if(o&&!o.data)throw new Error("(UNEXPECTED) given space has falsy space.data? (E: 058d298876ebbeada7bbddb9e3da2f23)");if(o&&t){if(o.data.uuid!==t.uuid)throw new Error("(UNEXPECTED) both space and spaceData given, but uuid don't match? (E: efdd4603cba93a17340a76811fe56b24)");if(o.data.n!==t.n)throw new Error("(UNEXPECTED) both space and spaceData given, but n don't match? (E: e51278a707c9bccc57a08a4b86524524)")}if(t??=o.data,!t)throw new Error("(UNEXPECTED) spaceData falsy? (thought this was a compiler problem that this was even possible.) (E: b3c7ffedcae4b1f45b263b3825930b24)");if(e&&t.classname&&e!==t.classname)throw new Error(`both classname arg (${e}) and spaceData.classname (${t.classname}) are different truthy values. (E: f98f012ee876eb8fbe7403f7b53e4624)`);if(e||=t.classname,!e)throw new Error("classname required (E: fa3af4613ad56742dab51d1b0d839322)");if(e.includes(" "))throw new Error(`invalid classname (${e}). cannot contain spaces (E: 243adbf720dcce7904e2665933208b22)`);let n=t?.name||di;if(n.includes(" "))throw new Error("invalid space name. cannot contain spaces (E: a8450e1651081412c8ac018520182422)");let a=t?.uuid||void 0;if(!a)throw new Error("invalid space, spaceData.uuid falsy (E: 50ae723a9ab24f4fc7132613e65faf23)");if(a.includes(" "))throw new Error("invalid space id. cannot contain spaces (E: 8696830fe7f54bfa85e670a063f3e089)");let s=t.type??void 0,i=t.subtype??void 0;if(s&&!i)throw new Error(`spaceType (${s}) is set but spaceSubtype is falsy. (E: 878ab960d7987ae2331103b4a00d0d24)`);return`${Jo} ${Fo} ${e} ${n} ${a} ${s} ${i}`}catch(n){throw console.error(`${r} ${n.message}`),n}}b(uf,"getSpaceIb");function gf({ib:o}){let t=`[${gf.name}]`;if(!o){let e=`${t} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(e),new Error(e)}return o.startsWith(`${Jo} ${Fo} `)}b(gf,"isSpaceIb");function mf({spaceIb:o}){let t=`[${mf.name}]`;try{if(!o)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[e,r,n,a,s,i,c]=o.split(" ");if(e!==Jo)throw new Error(`invalid spaceIb (${o}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(r!==Fo)throw new Error(`invalid spaceIb (${o}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`);if(!n)throw new Error(`invalid spaceIb (${o}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`);if(!a)throw new Error(`invalid spaceIb (${o}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`);if(!s)throw new Error(`invalid spaceIb (${o}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`);let l;if(i&&i!=="undefined")if(Ia.includes(i))l=i;else throw new Error(`invalid spaceIb (${o}). spaceType (${i}) is set but not a valid type. valid types: ${Ia.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let d;if(c&&c!=="undefined")if(_a.includes(c))d=c;else throw new Error(`invalid spaceIb (${o}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${_a.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:a,spaceId:s,spaceType:l,spaceSubtype:d}}catch(e){throw console.error(`${t} ${e.message}`),e}}b(mf,"parseSpaceIb");async function Me({ibGibs:o,addrs:t,tjps:e,tjpAddrs:r,space:n}){let a=`[${Me.name}]`;try{if(x&&console.log(`${a} starting...`),!n)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(o=o??[],t=t??[],e=e??[],r=r??[],t.length===0&&o.length===0&&e.length===0&&r.length===0)throw new Error("Either addrs, ibGibs, tjps, or tjpAddrs required. (E: 7c6ebfbab98d4d21a431b144457fd991)");let s=new Set(r.concat(e.map(l=>y({ibGib:l})))),i=Array.from(s).map(l=>J({ibGibAddr:l}).gib);o.map(l=>y({ibGib:l})).concat(t).forEach(l=>{let{gib:d}=J({ibGibAddr:l});i.some(p=>d.includes(p))||s.add(l)}),x&&console.log(`${a}[testing] ${n.data?.name||n.ib} (${n.data?.uuid||"[space.data.uuid falsy]"}) addrsToQuery: ${Array.from(s)} (I: 8a2202912c364238b6d6eb09577bc246)`);let c=await n.argy({ibMetadata:Ht({space:n}),argData:{cmd:"get",cmdModifiers:["latest","addrs"],ibGibAddrs:Array.from(s)}});return await n.witness(c)}catch(s){throw console.error(`${a} ${s.message}`),s}}b(Me,"getLatestAddrs");function La({ibGib_Context:o}){let t=`[${La.name}]`;try{if(x&&console.log(`${t} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!go({ibGib:o}))return;if(["roots","autosyncs"].some(r=>o.ib.includes(r)))throw new Error("cannot perform a modification of this type on this special ibgib (E: b8fb718a7323fc54454464b973412722)")}catch(e){throw console.error(`${t} ${e.message}`),e}finally{x&&console.log(`${t} complete.`)}}b(La,"throwIfContextIsSpecial");async function Ef({ibGib_Context:o,rel8nName_Context:t,addr:e,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Ef.name}]`;try{if(x&&console.log(`${i} starting... (I: 2dc486bb2d516e4534f437aaf5ec7f22)`),!o)throw new Error("ibGib_Context required (E: 75f7bfa93145d6dffe85d488443ca722)");if(!t)throw new Error("rel8nName_Context required (E: 12aaa43de9e34b68b25dc9a2a68ad6b9)");if(!e)throw new Error("addr required (E: e27df3bdc5a2554697cc9597afc4e422)");if(!r)throw new Error("space required (E: 2e3562486ed2956a770ed9e8d77a3f22)");let c=go({ibGib:o});c&&La({ibGib_Context:o});let l=await He({src:o,rel8nsToAddByAddr:{[Ei]:[e]},rel8nsToRemoveByAddr:{[t]:[e]},dna:!0,nCounter:!0});if(await ge({resTransform:l,space:r}),c){let d=y({ibGib:l.newIbGib}),f=on({ib:o.ib}),p=Ge({type:f});await ke({key:p,addr:d,space:r,zeroSpace:n,fnUpdateBootstrap:a})}await Te({ibGib:l.newIbGib,fnBroadcast:s,space:r})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{x&&console.log(`${i} complete.`)}}b(Ef,"trash");async function wf({ibGib_Context:o,rel8nName_Context:t,addr:e,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${wf.name}]`;try{if(x&&console.log(`${i} starting... (I: 38098552b830495187299bb24fcddff0)`),!o)throw new Error("ibGib_Context required (E: d819e8c4db5b4c0bb721300ba434cd40)");if(!t)throw new Error("rel8nName_Context required (E: de061adff8c04429a211aa09116a532d)");if(!e)throw new Error("addr required (E: 7059ebb8ef6149ea94e22f961d6b5c81)");if(!r)throw new Error("space required (E: e19566f2d42347798621447edcae312e)");let c=go({ibGib:o});c&&La({ibGib_Context:o});let l=await He({src:o,rel8nsToAddByAddr:{[mi]:[e]},rel8nsToRemoveByAddr:{[t]:[e]},dna:!0,nCounter:!0});if(await ge({resTransform:l,space:r}),c){let d=y({ibGib:l.newIbGib}),f=on({ib:o.ib}),p=Ge({type:f});await ke({key:p,addr:d,space:r,zeroSpace:n,fnUpdateBootstrap:a})}await Te({ibGib:l.newIbGib,fnBroadcast:s,space:r})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{x&&console.log(`${i} complete.`)}}b(wf,"archive");function yf(o){let t=`[${yf.name}]`;try{if(!o)return console.error(`${t} name is falsy`),!1;let e=/[\w-]+/,r=o.match(e);if(r?.length!==1||r[0].length!==o.length)return console.error(`${t} name can only contain letters, numbers, underscores, hyphens`),!1;let n=/[a-zA-Z\d]/;return o[0].match(n)?!0:(console.error(`${t} name must start with a letter or number`),!1)}catch(e){return console.error(`${t} ${e.message}`),!1}}b(yf,"spaceNameIsValid");var Le=!1;async function ka({ibGib:o,rel8nNames:t,space:e}){let r=`[${ka.name}]`;try{if(!o)throw new Error("ibGib required (E: a3c1b2d4e5f6a7b8c9d0e1f2a3b4c5d6)");if(!e)throw new Error("space required (E: b4d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6)");t||(t=Object.keys(o.rel8ns||{}));let n={};for(let a of t){let s=o.rel8ns?.[a]||[];if(s.length>0){let i=await W({addrs:s,space:e});if(i.success&&i.ibGibs?.length===s.length)n[a]=i.ibGibs.concat();else throw new Error(`Problem getting rel8d ibgibs for rel8nName: ${a}. ${i.errorMsg||"Unknown error"} (E: c5e3d4f5a6b7c8d9e0f1a2b3c4d5e6)`)}else n[a]=[]}return n}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(ka,"getRel8dIbGibs");async function mt({parentPrimitiveIb:o,ib:t,ibRegExpPattern:e,data:r,rel8ns:n}){let a=`[${mt.name}]`;try{if(!o)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(Fr({ib:o})!==null)throw new Error(`Invalid parentPrimitiveIb: ${o}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`);if(!t)throw new Error("ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)");let s=e?new RegExp(e):ci;if(!t.match(s))throw new Error(`invalid ib. does not match regexp (${s})`);let i=Object.keys(n??{}),c=[...Er,"tjp"];if(i.some(p=>c.includes(p)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let f=(await B.firstGen({ib:t,parentIbGib:B.primitive({ib:o}),data:r,rel8ns:n,dna:!1,noTimestamp:!0,nCounter:!1})).newIbGib;return f?.rel8ns?.past&&delete f.rel8ns.past,f?.rel8ns?.tjp&&delete f.rel8ns.tjp,f?.rel8ns?.identity&&delete f.rel8ns.identity,f.gib=await ce({ibGib:{ib:f.ib,data:f.data,rel8ns:f.rel8ns},hasTjp:!1}),f}catch(s){throw console.error(`${a} ${s.message}`),s}}b(mt,"constantIbGib");function vm({addr:o}){return sc({addr:o})}b(vm,"getBinHashAndExt");function sc({addr:o}){let t=`[${sc.name}]`;try{if(!po({addr:o}))throw new Error("not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)");let{ib:e}=J({ibGibAddr:o}),r=e.split(" ");if(r.length===2)return{binHash:r[1],binExt:""};if(r.length===3)return r[2].startsWith("enc=")?{binHash:r[1],binExt:"",binEncoding:r[2].substring(4)}:{binHash:r[1],binExt:r[2]};if(r.length===4){if(!r[3].startsWith("enc="))throw new Error(`bin ib (${e}) has 4 space-delimited pieces. we expect therefore the form to be bin \${binHash} \${binExt} enc=\${binEncoding}. but ibPieces[3] doesn't start with "enc=". (E: 87196d7cdd7c12d982cc8204a1163524)`);return{binHash:r[1],binExt:r[2],binEncoding:r[3].substring(4)}}else throw new Error('(UNEXPECTED) ibPieces.length not 2, 3, or 4? atow (01/2024) the only components of a bin ib are: atom, binHash, binExt, binEncoding. binExt and binEncoding are optional, with binEncoding being prefixed with "enc=". (E: b05df3c1b3949f76464a83c9fd1c4f24)')}catch(e){throw console.error(`${t} ${e.message}`),e}}b(sc,"parseBinIb");function po({ibGib:o,addr:t}){let e=`[${po.name}]`;try{if(!o&&!t)throw new Error("either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)");if(o&&!o.data)return!1;t=t||y({ibGib:o});let{ib:r,gib:n}=J({ibGibAddr:t});if(!r||!n||!r.startsWith("bin "))return!1;if(n.length!==64)throw new Error('ib starts with "bin " but gib length is not 64, so return false. Two things: 1) bin ibgibs are expected to be stones, i.e., have no temporal junction point and only a single punctiliar hash for the gib. the default hash used atow (01/2024) is sha-256, so the length should be 64. But this may not be true if using another hash algorithm. need to change this function when this becomes the case. (W: 60725d65d13c4b4fbb7b96d7feb19d67)');let a=r.split(" ");if(a.length===2){if(!a[1].match(Ie))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)')}else if(a.length===3){if(!a[1].match(Ie))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)')}else if(a.length===4){if(!a[1].match(Ie))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)');if(!a[3].startsWith("enc="))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[3].startsWith("enc=")? (E: 4c8a0c3b07a90d30e3d1a4373d57d824)')}else throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited ibPieces length is not 2, 3 or 4? (E: c7eccf88518304997c7e42b32e08d224)');return!0}catch(r){throw console.error(`${e} ${r.message}`),r}}b(po,"isBinary");function Pa({type:o}){if(!o.match(ha))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${ha.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${o}`}b(Pa,"getSpecialIbGibIb");function on({ib:o}){let t=`[${on.name}]`;try{if(Le&&console.log(`${t} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!o)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!go({ib:o}))throw new Error("ib is not special (E: 174aff63b992adff3ac2394643735922)");let e=o.split(" ");if(e.length<3)throw new Error('invalid ib. should be space-delimited in form of "meta special [type]" (E: ffd89e2cbe63427f98634ab897aab222)');let r=e[2];return Object.values(Uo).some(n=>n===r)||console.warn(`unknown special type (${r}). This may be expected, but atow I am adding special types to the SpecialIbGibType enum-like. (W: f4e26c3ebb57fe49d69014a4ba32a922)`),r}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Le&&console.log(`${t} complete.`)}}b(on,"getSpecialTypeFromIb");function $f({type:o}){return`${Pa({type:o})}^${z}`}b($f,"getSpecialIbGibAddr");function Ge({type:o}){return`${yi} ${$f({type:o})}`}b(Ge,"getSpecialConfigKey");function go({ib:o,ibGib:t}){if(!o&&!t?.ib)throw new Error("either ib or ibGib.ib required (E: b4cf539638d7966c2e351987f55e1a23)");return(o??t?.ib)?.startsWith("meta special")}b(go,"isSpecial");function Ra(o){let t=`[${Ra.name}]`;if(!o)throw new Error(`${t} text required.`);return`root ${o}`}b(Ra,"getRootIb");function $r(o){let t=`[${$r.name}]`;if(!o)throw new Error(`${t} tag required.`);return`tag ${o}`}b($r,"tagTextToIb");function Nt({ibGibs:o,filterPrimitives:t}){let e=`[${Nt.name}]`;try{let r={},n={},a={};return(t?o.filter(i=>i.gib??i.gib!==z):o).forEach(i=>{ic({ibGib:i})?(i.rel8ns?.dna??[]).length>0?r[i.gib]=i:n[i.gib]=i:a[i.gib]=i}),{mapWithTjp_YesDna:r,mapWithTjp_NoDna:n,mapWithoutTjps:a}}catch(r){throw console.error(`${e} ${r.message}`),r}}b(Nt,"splitPerTjpAndOrDna");function ft({ibGibs:o}){let t=`[${ft.name}]`;try{Le&&console.log(`${t} starting...`);let{mapWithTjp_YesDna:e,mapWithTjp_NoDna:r}=Nt({ibGibs:o,filterPrimitives:!0}),n={...e,...r},a=Object.values(n),s=Qn({items:a,keyFn:b(i=>i.data?.isTjp?y({ibGib:i}):i.rel8ns?.tjp?i.rel8ns?.tjp[0]??"":(Le&&console.log(`${t} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return Le&&console.log(`${t} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${F(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),Object.entries(s).forEach(([i,c])=>{c.some(l=>l.data?.n===void 0)&&console.warn(`${t} timeline includes ibgibs with ibGib.data?.n === undefined (W: cab9a6b64a38c4279fe82c3569bbab22)`),c.sort((l,d)=>(l.data?.n??-1)>(d.data?.n??-1)?1:-1)}),Le&&console.log(`${t} after sort ibGibsWithTjpGroupedByTjpAddr: ${F(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),s}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Le&&console.log(`${t} complete.`)}}b(ft,"getTimelinesGroupedByTjp");function ic({ibGib:o}){let t=`[${ic.name}]`;if(!o)throw new Error("(UNEXPECTED) ibGib falsy? (E: ce3a59f9db14e6158bb2c438ca1a3823)");if((o.rel8ns?.tjp?.length??0)>0||o.data?.isTjp)return!0;let e=["fork^gib","mut8^gib","rel8^gib"];return(o.rel8ns?.ancestor??[]).some(n=>e.includes(n))?!1:o.gib?o.gib.includes(At)?!0:o.gib===z?!1:!!Oe({ibGibAddr:y({ibGib:o})}).tjpGib:(console.warn(`${t} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}b(ic,"hasTjp");function ee({ibGib:o,defaultIfNone:t="undefined"}){let e=`[${ee.name}]`;try{let r=cc({ibGibs:[o],defaultIfNone:t});return r&&Object.keys(r).length===1?Object.values(r)[0]:void 0}catch(r){throw console.error(`${e} ${r.message}`),r}}b(ee,"getTjpAddr");function cc({ibGibs:o,defaultIfNone:t="undefined"}){let e=`[${cc.name}]`;try{let r={};return o.forEach(n=>{let a=y({ibGib:n}),s;n.rel8ns?.tjp?.length??!1?s=n.rel8ns.tjp[n.rel8ns.tjp.length-1]:n.data?.isTjp||t==="incomingAddr"?s=a:s=void 0,r[a]=s}),r}catch(r){throw console.error(`${e} ${r.message}`),r}}b(cc,"getTjpAddrs");async function Ba({ibGib:o,naive:t=!0}){let e=`[${Ba.name}]`;try{if(!o)throw new Error("ibGib required.");if(t){if(o.data)return o.data.isTjp?!0:o.rel8ns?o.rel8ns.past&&o.rel8ns.past.length>0?!1:!!(o.rel8ns.past&&o.rel8ns.past.length===0):(Le&&console.log(`${e} ibGib.rel8ns falsy (I: c69c9e78b34845311ce7c674d7195622)`),!1);throw new Error("loaded ibGib required (data).")}else throw new Error("only naive implemented right now.")}catch(r){throw console.error(`${e} ${r.message}`),r}}b(Ba,"isTjp_Naive");function qe({ibGib:o}){let t=`[${qe.name}]`;o.ib||console.warn(`${t} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),o.gib||console.warn(`${t} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let e={ib:(o.ib||"").slice()};return o.gib&&(e.gib=o.gib.slice()),o.data&&(po({ibGib:o})?e.data=o.data.slice():e.data=U(o.data)),o.rel8ns&&(e.rel8ns=U(o.rel8ns)),e}b(qe,"toDto");function mo(o){let t=`[${mo.name}]`;try{return Le&&console.log(`${t} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!o&&typeof o.ib=="string"}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Le&&console.log(`${t} complete.`)}}b(mo,"isIbGib");function tr({ibGib:o,data:t,timestamp:e}){let r=`[${tr.name}]`;try{Le&&console.log(`${r} starting... (I: 35cb68744bcf6139d78e37de644fad23)`),e=e||t?.timestamp||o?.data?.timestamp;let n=o?.data?.timestampMs||t?.timestampMs;if(!e){let a=`${r} timestamp is falsy. (W: 5f1f1182c8804807b886a3d922ac3dcf)`;return console.warn(a),{valid:!1,emsg:a}}if(typeof e=="string")if(Number.isInteger(Number.parseInt(e))){let a=Number.parseInt(e),s=new Date;if(s.setTime(a),s.toString()!==jo)return Le&&console.log(`${r} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`),{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${r} data.timestamp (${e}) is an integer string but not a valid timestampInTicks string. (produces invalid date) (E: f49fbb600fe1426c8805dfc8afbe5cf3)`;return console.error(i),{valid:!1,emsg:i}}}else{let a=new Date(e);if(a.toString()!==jo)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${r} data.timestamp is a non-integer string but not a valid date timestamp string (new date instantiated produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(s),{valid:!1,emsg:s}}}else if(typeof e=="number")if(Number.isInteger(e)){console.warn(`${r} expected data.timestamp to be a string but is a number (W: 9d786f4d4e8d4279b5af7bee19bf721b)`);let a=new Date;if(a.setTime(e),a.toString()!==jo)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${r} timestamp (${e}) is an integer number but not a valid timestampInTicks (new date setTime produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(s),{valid:!1,emsg:s}}}else{let a=`${r} timestamp (${e}) is a non-integer number (supposed to be a string either timestamp string or ticks). (E: 2963d95f8d3b464c992b0bff948b4479)`;return console.error(a),{valid:!1,emsg:a}}else{let a=`${r} unknown typeof timestamp (${typeof e}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;return console.error(a),{valid:!1,emsg:a}}}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{Le&&console.log(`${r} complete.`)}}b(tr,"getTimestampInfo");async function at({addrs:o,readCache_graph:t,readCache_array:e,space:r}){let n=`[${at.name}]`;try{Le&&console.log(`${n} starting... (I: 5db66871239dfa05182277f886a20926)`),t??={},e??=[];let a={...t};e.forEach(l=>a[y({ibGib:l})]=l);let s=Object.keys(t),i=o.filter(l=>!s.includes(l));if(i.length>0){Le&&console.log(`${n} ${i.length} addrsNotFoundInCache: ${i} (I: fccbd18116ffb849f813aaebfc6c0826)`);let l=[r],d=i.concat();for(let f of l){let p=await W({addrs:d,space:f});if(p.success&&p.ibGibs&&p.ibGibs.length===d.length)p.ibGibs.forEach(h=>a[y({ibGib:h})]=h),d=[];else if(p.ibGibs&&p.ibGibs.length>0){if(d=d.filter(h=>!p.ibGibs.some(g=>y({ibGib:g})===h)),d.length===0)break}else Le&&console.log(`${n} no addrs found in space (${f.ib}). trying next space. (I: 4f99d8bacbb10ab3f8737a752564b326)`)}if(d.length>0)throw new Error(`could not get all addrs from cache or spaces. addrsStillNotFound: ${d}. spaces: ${l.map(f=>f.ib).join("|")} (E: 0c6418f83dd85bda886e56f5b98f3126)`)}let c=[];for(let l of o){let d=a[l];if(!d)throw new Error(`(UNEXPECTED) allIbGibs_graph doesn't have addr? We're expecting logic to preclude this at this point. addr: ${l} (E: f68e1d236ae5e3eb08da9933c8230626)`);c.push(d)}return c}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Le&&console.log(`${n} complete.`)}}b(at,"getIbGibsFromCache_fallbackToSpaces");var Eo=!1,If="space_gib_db",_f="space_gib_store",Sf="space_gib_api_key";var Af="agent";var Om=$r(Af);var Lm={dbName:If,storeName:_f,additionalStoreNames:[li],apiKeyName:Sf};var lc="0.0.8";var rr=!1,km="[web^gib timer]",Ma="ibgib";var Tf="agent",Mm="body-outline",Um="This tag tracks the active agents for the current local user space.",Fm=$r(Tf),dc="#78f87e88",fc="#78f87e10",bc="#ffffff";var jm="AUTOMATED_TEXT";var Et=!1;function pc(o){return new Promise((t,e)=>{let r=new Blob([o],{type:"application/octet-stream"}),n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1];t(s)},n.onerror=a=>e(a),n.readAsDataURL(r)})}b(pc,"uint8ArrayToBase64");async function hc(o){let t=`data:application/octet-stream;base64,${o}`,n=await(await(await fetch(t)).blob()).arrayBuffer();return new Uint8Array(n)}b(hc,"base64ToUint8Array");async function nn({graph:o}){let t=`[${nn.name}]`;try{Et&&console.log(`${t} starting... (I: 4ddb8803cf68e1d3d35f60680cb69825)`);let e=JSON.parse(JSON.stringify(o));for(let n in e)o[n].data instanceof Uint8Array&&(e[n].data={_dataType:"Uint8Array_Base64",value:await pc(o[n].data)});let r=JSON.stringify(e);return Et&&console.log(`${t} jsonString.length: ${r.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),r}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Et&&console.log(`${t} complete.`)}}b(nn,"serializeGraphToString");async function an({jsonString:o}){let t=`[${an.name}]`;try{Et&&console.log(`${t} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`);let r=JSON.parse(o,b((n,a)=>(a&&a._dataType==="Uint8Array_Base64",a),"reviver"));for(let n in r){let a=r[n].data;a&&a._dataType==="Uint8Array_Base64"&&(r[n].data=await hc(a.value))}return r}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Et&&console.log(`${t} complete.`)}}b(an,"deserializeStringToGraph");async function uc(o){let t=`[${uc.name}]`;try{Et&&console.log(`${t} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let e=await nn({graph:o}),r=new TextEncoder().encode(e),a=new Response(r).body.pipeThrough(new CompressionStream("gzip"));return await new Response(a).blob()}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Et&&console.log(`${t} complete.`)}}b(uc,"compressIbGibToBlob");async function Gf(o){let t=o.stream().pipeThrough(new DecompressionStream("gzip")),e=await new Response(t).text();return await an({jsonString:e})}b(Gf,"decompressIbGibFromBlob");async function Ua({graph:o}){let t=`[${Ua.name}]`;try{Et&&console.log(`${t} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let r=await(await uc(o)).arrayBuffer(),n=new Uint8Array(r);return await pc(n)}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Et&&console.log(`${t} complete.`)}}b(Ua,"compressIbGibGraphToString");async function Fa({compressedBase64:o}){let t=`[${Fa.name}]`;try{Et&&console.log(`${t} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let e=await hc(o),r=new Blob([e],{type:"application/gzip"});return await Gf(r)}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Et&&console.log(`${t} complete.`)}}b(Fa,"decompressIbGibGraphFromString");var gc="export";var wo=!1;function mc({data:o}){let t=`[${mc.name}]`;try{wo&&console.log(`${t} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:e,dependencyGraphAsString:r,timestamp:n}=o,a=r.length,s=rt(n),i=o.compression==="gzip"?"gzip":"raw";if(!o.timestamp)throw new Error("(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)");let c=new Date(o.timestamp),{ib:l,gib:d}=J({ibGibAddr:o.contextIbGibAddr}),p=Oe({gib:d}).tjpGib??d,h=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${gc} ${h} ${i} ${e} ${a} ${p}`}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{wo&&console.log(`${t} complete.`)}}b(mc,"getRawExportIb");async function ja({ibGib:o,metaspace:t,space:e,compress:r,live:n,ignoreErrors:a}){let s=`[${ja.name}]`;try{if(wo&&console.log(`${s} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!o)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let i=y({ibGib:o}),c=[],l=await le({ibGib:o})??[];if(l.length>0){let S=`ibGib had validation errors: ${l} (E: 84890bbc0598192498178a98ae299825)`;if(a)c.push({errorMsg:S,ibGibAddr:i});else throw new Error(S)}let d=await t.getDependencyGraph({ibGib:o,live:n,space:e}),f=r?await Ua({graph:d}):await nn({graph:d}),p=ee({ibGib:o,defaultIfNone:"incomingAddr"})??i,h=new Date,g={contextIbGibAddr:i,tjpAddr:p,dependencyGraphAsString:f,graphSize:Object.keys(d).length,timestamp:Ce(h),timestampMs:h.getMilliseconds()};r&&(g.compression="gzip");let m={ib:mc({data:g}),data:g},E=await ce({ibGib:m,hasTjp:!1});return m.gib=E,console.log(`${s} JSON.stringify(exportIbGib).length: ${JSON.stringify(m).length} (I: db3a8d913a91d8fc5d6e45981e034822)`),{rawExportIbGib:m,manifest:Object.keys(d),errors:c.length>0?c:void 0}}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{wo&&console.log(`${s} complete.`)}}b(ja,"getRawExportIbGib");var aE="ibgib-shell-ready",sE="ibgib-ui-busy",iE="ibgib-ui-message",cE="ibgib-identity-request-change",lE="ibgib-identity-changed";var Ec=rr;async function Kr({title:o,msg:t,prompt:e,showInput:r,defaultValue:n,okButtonTitle:a,cancelButtonTitle:s,isPassword:i,isBusy:c,animationEmoji:l}){let d=`[${Kr.name}]`;try{Ec&&console.log(`${d} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let f=document.getElementById("fullscreen-dialog"),p=document.getElementById("fullscreen-dialog-body"),h=document.getElementById("fullscreen-dialog-title"),g=document.getElementById("fullscreen-dialog-message"),m=document.getElementById("fullscreen-dialog-prompt-input"),E=document.getElementById("fullscreen-dialog-ok-button"),S=document.getElementById("fullscreen-dialog-cancel-button");if(!f||!p||!h||!g||!m||!E||!S)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(h.textContent=o||"",[...g.childNodes].forEach($=>g.removeChild($)),(t||"").split(`
9
+ `).forEach($=>{let T=document.createElement("p");T.textContent=$,g.appendChild(T)}),l){let $=document.createElement("div");$.id="fullscreen-dialog-animation-emoji",$.textContent=l,$.style.fontSize="3.5rem",$.style.textAlign="center",$.style.margin="1.5rem 0",$.style.animation="spin-bounce 5s infinite ease-in-out",g.appendChild($)}m.classList.remove("collapsed"),S.classList.remove("collapsed"),S.style.display="inline-block",E.style.display="inline-block",E.textContent=a||"OK";let _=b($=>{($.key==="Enter"||$.key===`
10
+ `)&&$.ctrlKey&&E.click()},"onKeypress");return c?(m.classList.add("collapsed"),S.style.display="none",E.style.display="none"):e||r?(m.addEventListener("keypress",_),r?(m.autofocus=!0,m.value=n??"",m.addEventListener("keypress",$=>{$.key==="Enter"&&E.click()}),i?(m.type="password",m.autocomplete="off",m.required=!0):(m.type="text",m.autocomplete="on",m.required=!1,m.attributes["auto-complete"]="on")):(m.autofocus=!1,m.classList.add("collapsed")),S.textContent=s||"Cancel"):(m.classList.add("collapsed"),S.style.display="none"),new Promise($=>{if(c){let N=b(R=>{R.preventDefault()},"onCancelEvent");f.addEventListener("cancel",N);let O=b(()=>{f.removeEventListener("cancel",N),f.close()},"close"),P=b(({title:R,msg:k,animationEmoji:H})=>{if(R!==void 0&&(h.textContent=R),k!==void 0){[...g.childNodes].forEach(ie=>{ie.id!=="fullscreen-dialog-animation-emoji"&&g.removeChild(ie)});let K=k.split(`
11
+ `),ye=document.getElementById("fullscreen-dialog-animation-emoji");K.forEach(ie=>{let Ke=document.createElement("p");Ke.textContent=ie,ye?g.insertBefore(Ke,ye):g.appendChild(Ke)})}if(H!==void 0){let K=document.getElementById("fullscreen-dialog-animation-emoji");H?(K||(K=document.createElement("div"),K.id="fullscreen-dialog-animation-emoji",K.style.fontSize="3.5rem",K.style.textAlign="center",K.style.margin="1.5rem 0",K.style.animation="spin-bounce 5s infinite ease-in-out",g.appendChild(K)),K.textContent=H):K&&K.remove()}},"update");f.open||f.showModal(),Se(1e3).then(()=>{p.scrollTo({top:0,behavior:"smooth"})}),$({close:O,update:P});return}let T=b(()=>{(e||r)&&m.removeEventListener("keypress",_),E.removeEventListener("click",I),S.removeEventListener("click",G),f.removeEventListener("close",v)},"removeEventListeners"),I=b(()=>{T();let N=r?m.value??"":"true";m&&(m.value=""),f.close(N),$(N)},"onOK"),G=b(()=>{T(),m&&(m.value=""),f.close(void 0),$(void 0)},"onCancel"),v=b(()=>{T(),m&&(m.value=""),f.close(void 0),$(void 0)},"onClose");E.addEventListener("click",I),S.addEventListener("click",G),f.addEventListener("close",v),f.open||f.showModal(),Se(1e3).then(()=>{p.scrollTo({top:0,behavior:"smooth"})})})}catch(f){throw console.error(`${d} ${w(f)}`),f}finally{Ec&&console.log(`${d} complete.`)}}b(Kr,"showFullscreenDialog");var xe=rr;async function vf({metaspace:o,space:t}){let e=`[${vf.name}]`;try{xe&&console.log(`${e} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let r=await o.getSpecialIbGib({type:Uo.tags,space:t});if(!r)throw new Error(`tagsIbGib not found in metaspace. space: ${t?t.ib:"default local user space"} (E: 4734c510a411274315c0add8f70e1925)`);return r}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{xe&&console.log(`${e} complete.`)}}b(vf,"getTagsIbGib");function Ka({scope:o,ibGib:t,ibGibAddr:e,defaultNameIfError:r}){let n=`[${Ka.name}]`;try{if(!t&&!e)throw new Error(`${n} Must provide either ibGib or ibGibAddr. (E: genuuid)`);o.includes(" ")&&(console.warn(`${n} scope includes one or more spaces. These will be converted to double underscores. (W: 1554a81454e8ae0a6858ea5dd17f8925)`),o=o.replace(/ /g,"__"));let a,s,i;if(t){if(!t.data)throw new Error("(UNEXPECTED) ibGib.data falsy? (E: genuuid)");if(!t.rel8ns)throw new Error("(UNEXPECTED) ibGib.rel8ns falsy? (E: genuuid)");if(!t.rel8ns.ancestor)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor falsy? (E: genuuid)");if(t.rel8ns.ancestor.length===0)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor.length === 0? there should be at least one ancestor (E: genuuid)");if(t&&e&&y({ibGib:t})!==e)throw new Error("(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: genuuid)");let d=t.rel8ns.ancestor.filter(p=>ue({gib:J({ibGibAddr:p}).gib}));if(d.length===0){debugger;console.error(`${n} ibGib has no primitive ancestor addrs? Still going to work off of the ib then, which should have the atom as the first space-delimited term. (E: genuuid)`)}let f=d.at(-1);a=J({ibGibAddr:f}).ib,i=a}e??=y({ibGib:t});let{ib:c}=J({ibGibAddr:e});if(s=c.split(" ").at(0)??"",s=s.replace(/\W/g,"_"),a??=s,a=a.replace(/\W/g,"_"),!a&&!s)throw new Error("(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: genuuid)");i=s.toLowerCase(),xe&&console.log(`${n} ancestorIbOrAtom: ${i} (I: genuuid)`);let l=`${i}_${o}index`;return xe&&console.log(`${n} indexName: ${l} (I: genuuid)`),l}catch(a){if(r)return console.warn(`${n} error happened but defaultNameIfError (${r}) provided. So will return this value. error that was thrown: ${w(a)}`),r;throw console.error(`${n} ${w(a)}`),a}}b(Ka,"getIndexNameFromIbGib");async function Cf({scope:o,ibGib:t,metaspace:e,space:r,skipGetLatest:n}){let a=`[${Cf.name}]`;try{if(xe&&console.log(`${a} starting... (I: f19dc86aab380fe809aef27ccc7a7425)`),!o)throw new Error("scope required to be a non-empty string (E: 73e702495c38c7d8747d1cf8850af825)");if(!t)throw new Error("ibGib required (E: genuuid)");let s=Ka({scope:o,ibGib:t}),i=ee({ibGib:t,defaultIfNone:"incomingAddr"}),c=b(async()=>{let d=await e.getSpecialIbGib({type:s,space:r,initialize:!1,dontWarnIfNotExist:!0,lock:!0});if(!d||!d.data){xe&&console.log(`${a} special ${o} index ibGib not found for indexSpecialIbGibType (${s}). No coupled ibgib registered, returning undefined. (I: genuuid)`);return}let p=(d.data.coupleMap??d.data.agentMap??{})[i];if(!p){xe&&console.log(`${a} No coupled ${o} ibgib address found for domain ${i} in the coupled index map. indexSpecialIbGibType: ${s}. returning undefined. (I: genuuid)`);return}let h=n?p:await e.getLatestAddr({addr:p,space:r})??p,g=await e.get({addrs:[h],space:r});if(g.errorMsg||(g.ibGibs??[]).length!==1)throw new Error(`couldn't get latest coupled ibgib (${h}) for domain ${i}. (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);return g.ibGibs[0]},"fn");return await Ct({scope:s,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:r,callerInstanceId:a+rt(),fn:c})}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{xe&&console.log(`${a} complete.`)}}b(Cf,"getLocalCoupledIbGibForDomainIbGib");async function xf({scope:o,domainIbGib:t,localIbGib:e,metaspace:r,space:n}){let a=`[${xf.name}]`;try{xe&&console.log(`${a} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let s=Ka({scope:o,ibGib:t}),i=ee({ibGib:t}),c=y({ibGib:e});if(!i)throw new Error(`${a} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`);if(!c)throw new Error(`${a} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`);await Ct({scope:s,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:b(async()=>{let d=await r.getSpecialIbGib({type:s,space:n,initialize:!0,dontWarnIfNotExist:!0,lock:!1});if(!d)throw new Error(`${a} Could not get or create agent index ibGib.`);if(!d.data)throw new Error("(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)");let f=d.data.coupleMap??d.data.agentMap,p=f?U(f):{},h=p[i];if(h)if(h===c){xe&&console.log(`${a} domain ibGib (${i}) already mapped to agent (${c}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`);return}else console.warn(`${a} domainTjpAddr (${i}) already assigned to existingMappedAgentAddr (${h}). We will be changing to new localAddr (${c}). (W: eb993e33f7731e570fa76f24a2d80625)`);p[i]=c;let g=await ot({src:d,dataToAddOrPatch:{coupleMap:p},dna:!1,linkedRel8ns:[pe.past],nCounter:!0}),m=g.newIbGib;await ge({resTransform:g,space:n});let E=Ge({type:s});await r.setConfigAddr({key:E,addr:y({ibGib:m}),space:n}),await r.registerNewIbGib({ibGib:m,space:n})},"fn")}),xe&&console.log(`${a} Registered domain ${i} with agent ${c}`)}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{xe&&console.log(`${a} complete.`)}}b(xf,"coupleDomainIbGibWithLocalIbGibViaIndex");function Ir(){let o=`[${Ir.name}]`;try{xe&&console.log(`${o} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let t=globalThis[Ma];return t||(console.log(`${o} initializing globalThis.${Ma}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),t={}),t}catch(t){throw console.error(`${o} ${w(t)}`),t}finally{xe&&console.log(`${o} complete.`)}}b(Ir,"getIbGibGlobalThis_IbGib");async function M({delayIntervalMs:o=50}={delayIntervalMs:50}){let t=`[${M.name}]`;try{xe&&console.log(`${t} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let e;for(;!e;)Ir().metaspace&&(e=Ir().metaspace),e||(console.log(`${t} metaspace still not initialized. delayIntervalMs: ${o} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await Se(o));return e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{xe&&console.log(`${t} complete.`)}}b(M,"getGlobalMetaspace_waitIfNeeded");function Nf({ibGibAddr:o,gib:t,ibGib:e,translucentAlpha:r=10}){let n=`[${Nf.name}]`;try{xe&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!o&&!t&&!e&&(t=z),t??=e?.gib??J({ibGibAddr:o}).gib;let a=Oe({gib:t});r??=10;let s="";if(a.isPrimitive)return{gib:t,gibInfo:a,punctiliarColor:dc,punctiliarColorTranslucent:fc,punctiliarColorContrast:bc};s=a.tjpGib??a.punctiliarHash??t;let[i,c,l]=wc(r,a.punctiliarHash??t),[d,f,p]=a.tjpGib?wc(r,a.tjpGib):[void 0,void 0,void 0];return{gib:t,gibInfo:a,punctiliarColor:i,punctiliarColorTranslucent:c,punctiliarColorContrast:l,tjpColor:d,tjpColorTranslucent:f,tjpColorContrast:p}}catch(a){let s=`${n} ${w(a)}`;return console.error(s),{gib:t??z,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:s}}finally{xe&&console.log(`${n} complete.`)}}b(Nf,"getDeterministicColorInfo");function Df(o,t,e){e/=100;let r=t*Math.min(e,1-e)/100,n=b(a=>{let s=(a+o/30)%12,i=e-r*Math.max(Math.min(s-3,9-s,1),-1);return Math.round(255*i).toString(16).padStart(2,"0")},"f");return`#${n(0)}${n(8)}${n(4)}`}b(Df,"hslToHex");function wc(o,t){let r=(parseInt(t.substring(0,8),16)||0)%360,n=Df(r,65,62),a=parseInt(n.substring(1,3),16),s=parseInt(n.substring(3,5),16),i=parseInt(n.substring(5,7),16),l=(a*299+s*587+i*114)/1e3>=128?"#11111b":"#ffffff",d=Math.min(100,Math.max(0,o)),f=Math.round(d/100*255).toString(16).padStart(2,"0"),p=`${n}${f}`;return[n,p,l]}b(wc,"getColorStrings");var Je=rr;function $c(o){return new TextDecoder().decode(o)}b($c,"uint8ArrayToString");var yc=class o{static{b(this,"PathUtilsHelper")}lc=`[${o.name}]`;constructor(){}isAbsolute(t){if(!t)throw new Error("(UNEXPECTED) path falsy? (E: dcb92e11770ba06205c0afe3e6560b24)");return t.startsWith("/")}isRelative(t){return!this.isAbsolute(t)}join(...t){let e=`${this.lc}[${this.join.name}]`;if(t.length===0)return console.log(`${e} paths.length === 0. returning '.' per node convention. (I: 153da80765ff6160675fae895ebac225)`),".";if(t.length===1&&t[0]==="..")return console.log(`${e} paths.length === 1 && paths[0] === '..'. returning '..' per node convention. (I: 9af242b7615430a8c6899b1a332e9925)`),"..";let r="";for(let n=0;n<t.length;n++){let a=t[n];a===".."?r=r.split("/").slice(0,-1).join("/"):(a.startsWith("/")&&(a=a.slice(1)),a.endsWith("/")&&(a=a.slice(0,-1)),r+=(n>0?"/":"")+a)}return r}dirname(t){return t.split("/").slice(0,-1).join("/")}basename(t,e){return t.split("/").pop()??""}};async function Of({msg:o,title:t,confirm:e,noNewLine:r,rl:n,defaultValue:a,dontCloseRl:s,cancelable:i}){let c=`[${Of.name}]`;try{if(!o)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let l,d=0,f=5;do{if(d++,d>=f)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await Se(50),l=await Kr({title:t||"Prompt for Info",msg:o,prompt:!0,showInput:!0,isPassword:!1,defaultValue:a})}while(l===void 0&&!i);return l??""}catch(l){debugger;throw console.error(`${c} ${w(l)}`),l}}b(Of,"promptForText");async function Lf({msg:o,confirm:t}){let e=`[${Lf.name}]`;try{Je&&console.log(`${e} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let r,n=!0,a=0,s=5;do{if(a++,a>=s)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await Se(50),r=await Kr({title:n?"Shh...":"Secrets didn't match, try again...",msg:o||"Enter Your Secret...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0}),r===void 0)throw new Error("user cancelled (E: 91519d04378e84106f3df8eb36d99725)");if(t){await Se(250);let i=await Kr({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});i===void 0&&(r=void 0),r!==i&&(r=void 0,n=!1,await Se(250))}}while(r===void 0);return r}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Je&&console.log(`${e} complete.`)}}b(Lf,"promptForSecret");async function Pf({msg:o,title:t,skipHitEnterToContinue:e}){let r=`[${Pf.name}]`;try{if(!o)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{t??="",await Se(50),await Kr({title:t,msg:o})}catch(n){throw n}}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(Pf,"alertUser");async function Rf({exportIbGibJsonString:o,metaspace:t}){let e=`[${Rf.name}]`;try{debugger;if(Je&&console.log(`${e} starting... (I: genuuid)`),!t)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");if(!await t.getLocalUserSpace({lock:!1}))throw new Error("(UNEXPECTED) couldn't get default local user space? (E: genuuid)");let n,a;try{n=JSON.parse(o)}catch(l){let d=`Error during parse JSON. error: ${w(l)} (E: genuuid)`,f=new Error(d);throw f.cause=l,f}try{let l=await le({ibGib:n})??[];if(l.length>0)throw new Error(`validation errors when validating the parsed ibgib that should be a RawExportIbGib_V1: ${l} (E: 8ba178d3b26e8eca28a67c182fe16825)`);if(a=n,!a.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)")}catch(l){let d=`Error during parse JSON. error: ${w(l)} (E: genuuid)`,f=new Error(d);throw f.cause=l,f}let s;if(a.data.compression)switch(a.data.compression){case"gzip":s=await Fa({compressedBase64:a.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${a.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else s=await an({jsonString:a.data.dependencyGraphAsString});let i={};for(let[l,d]of Object.entries(s)){let f=await le({ibGib:d})??[];f.length>0&&(i[l]=f)}if(Object.keys(i).length>0)throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:
12
+ ${F({validationErrorMap:i})} (E: e63f38b182a84122d83a55befb369825)`);return[a,s]}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Je&&console.log(`${e} complete.`)}}b(Rf,"getRawExportIbGibAndGraphFromJsonString");async function Bf({ibGib:o,compress:t,metaspace:e,space:r}){let n=`[${Bf.name}]`;try{if(Je&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),ue({ibGib:o}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let a=await ja({ibGib:o,live:!0,compress:t,metaspace:e,space:r}),{rawExportIbGib:s,errors:i}=a;if((i??[]).length>0)throw new Error(`Export had errors: ${i} (E: 05faf83f25d3449ab809dfd24eeaf825)`);let c=JSON.stringify(s),l="data:text/json;charset=utf-8,"+encodeURIComponent(c),f=`${y({ibGib:s})}.json`,p=document.createElement("a");p.setAttribute("style","none"),p.setAttribute("href",l),p.setAttribute("download",f);let h=document.getElementsByTagName("div")[0];h.appendChild(p),p.click(),h.removeChild(p)}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Je&&console.log(`${n} complete.`)}}b(Bf,"exportIbGib");function kf(){let o=`[${kf.name}]`;try{Je&&console.log(`${o} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let t=Ir();if(!t.storeName_hack)throw new Error("(UNEXPECTED) global store name falsy? (E: 3b9b680f6a980debbb877c9a13fb2625)");return t.storeName_hack}catch(t){throw console.error(`${o} ${w(t)}`),t}finally{Je&&console.log(`${o} complete.`)}}b(kf,"getGlobalStoreName");function Mf(){let o=`[${Mf.name}]`;try{Je&&console.log(`${o} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let t=Ir();if(!t.dbName_hack)throw new Error("(UNEXPECTED) global db name falsy? (E: 3aa028d5e4088f3f3841aae94ac02825)");return t.dbName_hack}catch(t){throw console.error(`${o} ${w(t)}`),t}finally{Je&&console.log(`${o} complete.`)}}b(Mf,"getGlobalDbName");function Uf(){let o=`[${Uf.name}]`;try{Je&&console.log(`${o} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let t=Ir();if(!t.apiKeyName_hack)throw new Error("(UNEXPECTED) global api key name falsy? (E: 1782e812f0c87f54b8059468a5b60125)");return t.apiKeyName_hack}catch(t){throw console.error(`${o} ${w(t)}`),t}finally{Je&&console.log(`${o} complete.`)}}b(Uf,"getGlobalIndexedDbKey_APIKey");async function Ha({infos:o}){let t=`[${Ha.name}]`;try{Je&&console.log(`${t} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let e of o){let{dbName:r,storeNames:n}=e;await qa({dbName:r})||await cn({dbName:r});for(let s of n)await Xa({dbName:r,storeName:s})}}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Je&&console.log(`${t} complete.`)}}b(Ha,"initAppStorage");var Ze=rr,Ic=0;async function cn({dbName:o,storeName:t,version:e,logalot:r=!1}){let n=`[${cn.name}][${o}][${t??"no store name"}]`,a=crypto.randomUUID();r&&console.time(n+a);let s;try{r&&console.log(`${n} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`),await new Promise((c,l)=>{try{r&&console.log(`${n} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`),r&&console.timeLog(n+a,"opening... (I: e748b4ddb445d77cb10a7ba158b49125)");let d=indexedDB.open(o,e);Ic++,console.log(`${n} initRequestCount: ${Ic} (I: 294d5f0b12ffe5512bacebe891824d25)`);let f;d.onupgradeneeded=p=>{try{s=p.target.result,r&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),t&&(s.objectStoreNames.contains(t)?f=!0:(f=!1,s.createObjectStore(t,{keyPath:"key"})))}catch(h){console.error(`${n}[openDBRequest.onupgradeneeded] ${w(h)} (E: 4a5fa1b0850be47e28bee653da287325)`),l(h)}},d.onblocked=p=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${p.oldVersion} -> ${p.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(p)},d.onsuccess=p=>{try{r&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),r&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),s=p.target.result,t&&(f??=s.objectStoreNames.contains(t),r&&console.log(`${n} ${o} store "${t}" ${f?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(h){console.error(`${n}[openDBRequest.onsuccess] ${w(h)}`),l(h)}},d.onerror=p=>{debugger;console.error(`${n}[initRequest.onerror] ${w(d.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`),l(d.error)}}catch(d){console.error(`${n} ${w(d)}`);debugger;l(d)}finally{r&&console.log(`${n} complete.`)}})}catch(i){throw console.error(`${n} ${w(i)}`),i}finally{s&&(r&&console.log(`${n} closing db ${o}... (I: 3f1c18eec567ea63f3927eef0f038925)`),s.close(),r&&(console.log(`${n} closing db ${o} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`),console.timeLog(n+a,"db closed. (I: e748b4ddb445d77cb10a7ba158b49125)"))),r&&(console.log(`${n} complete.`),console.timeEnd(n+a))}}b(cn,"initializeStorage");async function _c({dbName:o,logalot:t=!1}){let e=`[${_c.name}]`,r=crypto.randomUUID();t&&console.time(e+r);try{return t&&console.log(`${e} starting... (I: 8516795b20529d19eb6923defd7a0f24)`),(await indexedDB.databases()).filter(a=>a.name===o).at(0)}catch(n){console.error(`${e} ${w(n)}`)}finally{t&&console.timeEnd(e+r),t&&console.log(`${e} complete.`)}}b(_c,"storageGetDBInfo");async function Xa({dbName:o,storeName:t,logalot:e=!1}){let r=`[${Xa.name}]`,n=crypto.randomUUID();e&&console.time(r+n);let a;try{if(e&&console.log(`${r} starting... (I: 029f7caa8ea5ea08a865f3924c82b624)`),!(await indexedDB.databases()).filter(f=>f.name===o).at(0))throw new Error(`db (${o}) does not exist. can't create store (${t}) (E: 5b15f7aed6f7068d077b2c7ebcbe8524)`);let i=!1;if(e&&console.timeLog(r+n),await new Promise((f,p)=>{let h=indexedDB.open(o);h.onsuccess=g=>{a=g.target.result,i=a.objectStoreNames?.contains(t),e&&console.timeLog(r+n,"open db request"),f()},h.onerror=g=>{debugger;console.error(`${r}[openDBRequest.onerror] ${w(h.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),p(h.error)}}),e&&console.timeLog(r+n),i){e&&console.log(`${r} store ${t} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await _c({dbName:o,logalot:e});if(e&&console.timeLog(r+n,"storageGetDBInfo complete"),!c)throw new Error(`db (${o}) does not exist. can't create store (${t}) (E: c771db13fa28f67079aad45e1ab7e624)`);let l=c.version;if(!l)throw new Error(`db (${o}) has no version. can't create store (${t}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`);let d=l+1;if(e&&console.log(`${r} creating store ${t} with version ${d} (I: 312b79f28243c650cf38935114f21e24)`),a)a.close(),a=void 0;else throw new Error("(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)");await cn({dbName:o,storeName:t,version:d,logalot:e})}catch(s){throw console.error(`${r} ${w(s)}`),s}finally{a&&(e&&console.log(`${r} closing db ${o}... (I: 3f1c18eec567ea63f3927eef0f038925)`),a.close(),e&&console.log(`${r} closing db ${o} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`)),e&&console.timeLog(r+n),e&&console.log(`${r} complete.`)}}b(Xa,"storageCreateStoreIfNotExist");async function Va({dbName:o,version:t,storeName:e,key:r,value:n,logalot:a=!1}){let s=`[${Va.name}]`,i;try{a&&console.log(`${s} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((l,d)=>{try{a&&console.log(`${s} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let f=indexedDB.open(o,t);f.onsuccess=p=>{i=p.target.result;try{let h=i.transaction(e,"readwrite").objectStore(e),g={key:r,value:n};h.put(g),l()}catch(h){console.error(`${s}[putRequest.onsuccess] ${w(h)}`),d(h)}},f.onerror=p=>{debugger;console.error(`${s}[putRequest.onerror] ${w(f.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),d(f.error)}}catch(f){console.error(`${s} ${w(f)}`),d(f)}finally{a&&console.log(`${s} complete.`)}})}catch(c){throw console.error(`${s} ${w(c)}`),c}finally{i&&(a&&console.log(`${s} closing db ${o}... (I: 438c6edced94b83a3478c71b08c6c325)`),i.close(),a&&console.log(`${s} closing db ${o} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`)),a&&console.log(`${s} complete.`)}}b(Va,"storagePut");async function sn({dbName:o,version:t,storeName:e,key:r,logalot:n=!1}){let a=`[${sn.name}]`,s;try{return n&&console.log(`${a} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`),await new Promise((l,d)=>{try{n&&console.log(`${a} starting... (I: 24163c4a11c8712097db45febaf9c724)`);let f=indexedDB.open(o,t);f.onsuccess=p=>{s=p.target.result;let h;try{h=s.transaction(e).objectStore(e)}catch(m){debugger;console.error(`${a}[openDBRequest.onsuccess][objectStore] ${w(m)}`),d(m);return}let g=h.get(r);g.onsuccess=m=>{try{let E=m.target?.result?.value??void 0;if(!E){l(E);return}if(n&&console.log("Retrieved value:",E),E instanceof Uint8Array)l($c(E));else{if(typeof E!="string")throw new Error("(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)");l(E)}}catch(E){d(E)}},g.onerror=m=>{debugger;let E=g.error;console.error(`${a}[openDBRequest.onsuccess][getRequest.onerror] ${w(E)}`),d(E)}},f.onerror=p=>{debugger;console.error(`${a}[openDBRequest.onerror] ${w(f.error)} (E: 074963a908fa9a075f01c73cae829224)`),d(f.error)}}catch(f){console.error(`${a} ${w(f)}`),d(f)}finally{n&&console.log(`${a} complete.`)}})}catch(i){throw console.error(`${a} ${w(i)}`),i}finally{s&&(n&&console.log(`${a} closing db ${o}... (I: a938fc22dfdc76b15f6926bc4d458225)`),s.close(),n&&console.log(`${a} closing db ${o} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`)),n&&console.log(`${a} complete.`)}}b(sn,"storageGet");async function qa({dbName:o,store:t}){let e=`[${qa.name}]`,r;try{return Ze&&console.log(`${e} starting... (I: 2b4373affa3841220f0b7ca690406624)`),(await window.indexedDB.databases()).some(s=>s.name===o)?t?await new Promise((s,i)=>{let c=indexedDB.open(o);c.onsuccess=l=>{r=l.target.result;let d=r.objectStoreNames.contains(t);s(d)},c.onerror=l=>{debugger;r=c.result;let{error:d}=l.target;console.error(`${e}[openDBRequest.onerror] ${w(c.error)} (E: c783fe607451e46c1feae3a81e0f7924)`),i(d)}}):!0:!1}catch(n){throw console.error(`${e} ${w(n)}`),n}finally{r&&(Ze&&console.log(`${e} closing db ${o}... (I: 8782d9eea285cf9eb638d493a421a625)`),r.close(),Ze&&console.log(`${e} closing db ${o} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),Ze&&console.log(`${e} complete.`)}}b(qa,"storageDBExists");async function Ff({dbName:o,storeName:t,pathToRm:e}){let r=`[${Ff.name}]`,n=Ze;Ze&&console.log(`${r} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`);let a;return new Promise((s,i)=>{try{if(!o)throw new Error("(UNEXPECTED) dbName falsy? (E: ed336d88c9c4e8d4916b29356dc58324)");if(!t)throw new Error("(UNEXPECTED) storeName falsy? (E: ad493bb79b63a192524b14c59a706524)");if(!e)throw new Error("(UNEXPECTED) pathToRm falsy? (E: 88c9631d93467e17996946882254af24)");let c=indexedDB.open(o);c.onerror=()=>{debugger;c.result&&c.result.close(),console.error(`${r}[openDBRequest.onerror] ${w(c.error)} (E: 4c5ab71a765e61b4292008fd4fafe324)`),i(c.error)},c.onsuccess=()=>{a=c.result;let d=a.transaction(t,"readwrite").objectStore(t),f=IDBKeyRange.lowerBound(e),p=d.openCursor(f);p.onerror=()=>{debugger;console.error(`${r}[openCursorRequest.onerror] ${w(p.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),i(p.error)},p.onsuccess=()=>{try{let h=0,g=p.result;if(g)if(g.key.toString().startsWith(e)){let m=g.delete();h++,m.onerror=()=>{debugger;console.error(`${r}[deleteRequest.onerror] ${w(m.error)} (E: abc031c53e5387322cd8909b3ada9b24)`),i(m.error)},g.continue()}else Ze&&console.log(`${r} rmCount: ${h} (I: e4bc613a5514c0942484b79267e16724)`),s();else Ze&&console.log(`${r} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`),s()}catch(h){console.error(`${r}[openCursorRequest.onsuccess] ${w(h)}`),i(h)}}}}catch(c){debugger;console.error(`${r} ${w(c)}`),i(c)}}).finally(()=>{a&&(Ze&&console.log(`${r} closing db ${o}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),Ze&&console.log(`${r} closing db ${o} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),Ze&&console.log(`${r} complete.`),Ze=n})}b(Ff,"storageRmRF");async function jf({dbName:o,storeName:t,dirPath:e,withFileTypes:r=!1}){let n=`[${jf.name}]`,a;try{return await new Promise((c,l)=>{let d=indexedDB.open(o);d.onerror=()=>{debugger;l(d.error)},d.onsuccess=()=>{a=d.result;let p=a.transaction(t,"readonly").objectStore(t),h=e.endsWith("/")?e:e+"/",g=IDBKeyRange.lowerBound(h),m=p.openCursor(g),E=new Set,S=[];m.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${w(m.error)}`),l(m.error)},m.onsuccess=()=>{try{let A=m.result;if(A){let _=A.key.toString();if(_.startsWith(h)&&_!==h){let $=_.substring(h.length),T=$.split("/")[0];if(r){let I=$.substring(T.length).startsWith("/");S.push({name:T,isDirectory:b(()=>I,"isDirectory"),isFile:b(()=>!I,"isFile"),isBlockDevice:b(()=>!1,"isBlockDevice"),isCharacterDevice:b(()=>!1,"isCharacterDevice"),isSymbolicLink:b(()=>!1,"isSymbolicLink"),isFIFO:b(()=>!1,"isFIFO"),isSocket:b(()=>!1,"isSocket")})}else E.add(T);A.continue()}else _.startsWith(h)?A.continue():c(r?S:Array.from(E))}else c(r?S:Array.from(E))}catch(A){console.error(`${n}[openCursorRequest.onsuccess] ${w(A)}`),l(A)}}}})}catch(s){throw console.error(`${n} ${w(s)}`),s}finally{a&&(Ze&&console.log(`${n} closing db ${o}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),Ze&&console.log(`${n} closing db ${o} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}b(jf,"storageReaddir");var Hr=Eo;async function Vf(o){let t=`[${Vf.name}]`;try{Hr&&console.log(`${t} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await Ha({infos:[{dbName:o.dbName,storeNames:[o.storeName,...o.additionalStoreNames??[]]}]})}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Hr&&console.log(`${t} complete.`)}}b(Vf,"initIbGibStorage");function Sc(o){let t=`[${Sc.name}]`;try{Hr&&console.log(`${t} starting... (I: 7be20d161bb14a498c44a42d3193bec1)`),globalThis.ibgib||(globalThis.ibgib={dbName_hack:o.dbName,apiKeyName_hack:o.apiKeyName,storeName_hack:o.storeName}),globalThis.ibgib.spaceGib||(globalThis.ibgib.spaceGib={version:lc,spaceShim:{},fnDefaultGetAPIKey:b(async()=>await sn({dbName:o.dbName,storeName:o.storeName,key:o.apiKeyName})??"","fnDefaultGetAPIKey"),dbName_hack:o.dbName,apiKeyName_hack:o.apiKeyName,storeName_hack:o.storeName})}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Hr&&console.log(`${t} complete.`)}}b(Sc,"initIbGibGlobalThis");function Kf(o){if(!globalThis.ibgib?.spaceGib){if(!o)throw new Error("Global context not initialized and config not provided.");Sc(o)}return globalThis.ibgib.spaceGib}b(Kf,"getIbGibGlobalThis_SpaceGib");async function Hf(o){let t=`[${Hf.name}]`;try{Hr&&console.log(`${t} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(o)).bootstrapSpaceGibApp()}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Hr&&console.log(`${t} complete.`)}}b(Hf,"dynamicallyLoadBootstrapScript");function rw(){let o=b(async()=>M(),"fnGetMetaspace"),t=new Promise(async(e,r)=>{try{let n=1e5,a=0,s;do{if(s=Kf()?.bootstrapPromise,a++,a>n)break;await Se(10)}while(s===void 0);if(!s)throw new Error("Timed out waiting for bootstrapPromise. (E: ceb3ba5261994476900e4a623c0e9d10)");await s,e()}catch(n){r(n)}});return{fnGetMetaspace:o,bootstrapPromise:t}}b(rw,"getComponentCtorArg");var Xf="hash-reveal-v1",bt={hash_reveal_v1:Xf},Ac=Object.values(bt);var qf="top-up",Yf="replace-all",Wf="consume",zf="delete-all",$e={topUp:qf,replaceAll:Yf,consume:Wf,deleteAll:zf},Tc=Object.values($e);var Jf="add-pool",Zf="remove-pool",Qf="replace-pool",eb="change-password",Xr={add_pool:Jf,remove_pool:Zf,replace_pool:Qf,change_password:eb},aw=Object.values(Xr);var yo="keystone",Ya=/^\w[\w\-.]*$/,Wa=/^[a-zA-Z0-9\-_]{1,64}$/,za=/^[a-zA-Z0-9_\-.]{1,63}$/,Ja=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,Za=1e3,qr="revoke",Qe="manage",tb="sign",Pe="sync",or="connect",Qa={REVOKE:qr,MANAGE:Qe,SIGN:tb,SYNC:Pe,CONNECT:or},dw=Object.values(Qa);var Xt=Qe;var wt=or,_r=Pe;var Gc=200,vc=2,Cc=2,xc=5,Nc=$e.topUp,Dc=De.sha_256,Oc=1,Lc=2e3,Pc=5,Rc=5,Bc=16,kc=$e.replaceAll,Mc=De.sha_512,Uc=10,Sr=50;var ln=class{static{b(this,"KeystoneStrategy")}config;constructor(t){this.config=t}};var rb="recursive-salt-wrap",$o={recursive_salt_wrap:rb},Fc=Object.values($o);var dn=!1;async function es({masterSecret:o,kdfOpts:t}){let e=`[${es.name}]`;try{dn&&console.log(`${e} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let r=t.strategy;switch(r){case $o.recursive_salt_wrap:return await Io({masterSecret:o,salt:t.salt,rounds:t.rounds,algorithm:t.algorithm});default:throw new Error(`Unknown KDF strategy: ${r}. valid values: ${Fc.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{dn&&console.log(`${e} complete.`)}}b(es,"deriveKey");async function Io({masterSecret:o,salt:t,rounds:e,algorithm:r=De.sha_256}){let n=`[${Io.name}]`;try{dn&&console.log(`${n} starting... (I: 850868e50aba82ff28c77da8169e4c26)`);let a=o;for(let s=0;s<e;s++)a=await _e({s:`${t}${a}${t}`,algorithm:r});return a}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{dn&&console.log(`${n} complete.`)}}b(Io,"kdf_recursiveSaltWrap");var fn=class o extends ln{static{b(this,"KeystoneStrategy_HashRevealV1")}async derivePoolSecret({masterSecret:t}){let e=`[${o.name}.${this.derivePoolSecret.name}]`;try{let{salt:r,rounds:n,algo:a}=this.config;return await Io({masterSecret:t,salt:r,rounds:n,algorithm:a})}catch(r){throw console.error(`${e} Error deriving pool secret: ${r.message}`),r}}async generateSolution({poolSecret:t,poolId:e,challengeId:r}){let n=`[${o.name}.${this.generateSolution.name}]`;try{let{rounds:a,algo:s}=this.config,i=r,c=t;for(let l=0;l<a;l++)c=await _e({s:`${i}${c}${i}`,algorithm:s});return{type:"hash-reveal-v1",poolId:e,challengeId:r,value:c}}catch(a){throw console.error(`${n} ${a.message}`),a}}async generateChallenge({solution:t}){let e=`[${o.name}.${this.generateChallenge.name}]`;try{let{rounds:r,algo:n}=this.config,{challengeId:a,value:s}=t,i=a,c=s;for(let l=0;l<r;l++)c=await _e({s:`${i}${c}${i}`,algorithm:n});return{id:a,type:"hash-reveal-v1",hash:c}}catch(r){throw console.error(`${e} ${r.message}`),r}}async validateSolution({solution:t,challenge:e}){let r=`[${o.name}.${this.validateSolution.name}]`;try{return t.type!=="hash-reveal-v1"||e.type!=="hash-reveal-v1"?(console.warn(`${r} Mismatched types provided.`),!1):(await this.generateChallenge({solution:t})).hash===e.hash}catch(n){return console.error(`${r} ${n.message}`),!1}}};async function Aw({masterSecret:o}){let t=await _e({s:o,algorithm:De.sha_512});return await Io({masterSecret:o,salt:t,rounds:1e3,algorithm:De.sha_512})}b(Aw,"deriveDelegateSecret");var Dt=class o{static{b(this,"KeystoneStrategyFactory")}static create({config:t}){let e=`[${o.name}.create]`;try{switch(t.type){case"hash-reveal-v1":return new fn(t);default:throw new Error(`Unknown strategy type: ${t.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(r){throw console.error(`${e} ${r.message}`),r}}};var te=!1;async function Ot({ibGib:o,ibGibs:t,ibGibAddr:e,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${Ot.name}]`;try{te&&console.log(`${m} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let E=await _o({ibGib:o,ibGibs:t,ibGibAddr:e,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g});if(Object.values(E).filter(S=>S.ib.startsWith("comment ")).forEach(S=>{console.table(S)}),te){console.log(`${m} graph size: ${Object.keys(E).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let S=Object.values(E).filter(A=>A.ib.startsWith("comment ")||A.ib.startsWith("pic ")).map(A=>A.ib);Po(S).forEach(A=>console.log(A))}return E}catch(E){throw console.error(`${m} ${E.message}`),E}finally{te&&console.log(`${m} complete.`)}}b(Ot,"getDependencyGraph");async function jc({ibGib:o,ibGibs:t,ibGibAddr:e,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${jc.name}]`;try{if(te&&console.log(`${m} starting... (I: bd6807477f679345df9dddefe0b4e922)`),!p)throw new Error("space required. (E: 9f38166ab70340cb919174f8d26af909)");if(!o&&!e&&(t??[]).length===0&&(r??[]).length===0)throw new Error("either ibGib/s or ibGibAddr/s required. (E: b6d08699651f455697f0d05a41edb039)");return c=c||[],i=i||[],a=a||{},s=s||[],r=(r??[]).filter(E=>!ue({gib:J({ibGibAddr:E}).gib})).filter(E=>!i.includes(E)),t=(t??[]).filter(E=>!ue({ibGib:E})).filter(E=>!i.includes(y({ibGib:E}))),o&&!ue({ibGib:o})&&!t.some(E=>E.gib===o.gib)&&!i.includes(y({ibGib:o}))&&t.push(o),e&&!ue({gib:J({ibGibAddr:e}).gib})&&!r.includes(e)&&!i.includes(e)&&r.push(e),{ibGib:o,ibGibs:t,ibGibAddr:e,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}}catch(E){throw console.error(`${m} ${E.message}`),E}finally{te&&console.log(`${m} complete.`)}}b(jc,"getGraphProjection_initializeOpts");async function Vc({ibGibs:o,ibGibAddrs:t,gotten:e,skipAddrs:r,maxRetries:n,msBetweenRetries:a,timeLogName:s,space:i}){let c=`[${Vc.name}]`;try{te&&console.log(`${c} starting... (I: 67b2be37ff24393fff56e229304da122)`);let l=[];o??=[],t??=[],r??=[],e??={};let d=[],f=Object.keys(e??{}),p=o.map(h=>y({ibGib:h}));for(let h=0;h<t.length;h++){let g=t[h];r.includes(g)||p.includes(g)||(f.includes(g)?l.push(e[g]):d.push(t[h]))}if(te&&console.log(`${c}[analyze debugging] addrsToGetFromSpace (${d.length}):
13
+ ${d.join(`
14
+ `)} (I: b45a2614184b48b694becfd377c789f5)`),d.length>0){let h=d.concat(),g=0;for(n=n??0;g<=n&&h.length>0;){if(s&&g===0&&console.timeLog(s,`${c} FIRST try starting...`),s&&g>0&&console.timeLog(s,`${c} RETRY starting...`),g>0&&a&&(s&&console.timeLog(s,`${c} delaying ${a}ms for retry`),te&&console.log(`${c} retrying. addrsToGet (${h.length}): ${h} (I: 8460694cdd5518472680784c3b96a822)`),await Se(a)),s&&console.timeLog(s,`${c} getFromSpace (${h?.length}) starting...`),!i)throw new Error("(UNEXPECTED) space falsy? (E: aa9f657695717034b3581066932d7d23)");let m=await W({addrs:h,space:i});if(s&&console.timeLog(s,`${c} getFromSpace complete.`),m.success&&(m.ibGibs?.length??0)>0){m.ibGibs.forEach(S=>l.push(S));let E=m.ibGibs.map(S=>y({ibGib:S}));if(E.length===h.length){s&&console.timeLog(s,`${c} got all.`),h=[];break}else s&&console.timeLog(s,`${c} got some.`),h=h.filter(S=>!E.includes(S))}else{let E=m.rawResultIbGib.ibGibs??[];if(E.length>0){E.forEach(A=>l.push(A));let S=E.map(A=>y({ibGib:A}));s&&console.timeLog(s,`${c} got some.`),h=h.filter(A=>!S.includes(A))}else s&&console.timeLog(s,`${c} failed. addrs: ${h?.join(",")}`)}g++}if(h?.length>0)throw new Error(`unable to retrieve dependency ibgibs from space (ib: ${i?.ib}). addrsToGet: ${h.join(`
15
+ `)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}return l}catch(l){throw console.error(`${c} ${l.message}`),l}finally{te&&console.log(`${c} complete.`)}}b(Vc,"getGraphProjection_getIbGibsInIbGibAddrs");async function _o(o){let t=`[${_o.name}]`;try{if(te&&console.log(`${t} starting... (I: 70508d7a5c63eae1f22ae851b32b3d22)`),!o.ibGib&&!o.ibGibAddr&&(o.ibGibs??[]).length===0&&(o.ibGibAddrs??[]).length===0)return{};let{ibGibs:e,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}=await jc(o);if(h&&console.timeLog(h,`${t} starting...`),r?.length??!1){let E=await Vc({ibGibs:e,ibGibAddrs:r,gotten:a,skipAddrs:i,maxRetries:d,msBetweenRetries:f,timeLogName:h,space:p});e=e?[...e,...E]:[...E]}r=e.map(E=>y({ibGib:E}));let m=Po(e.map(E=>E.ib).filter(E=>E.startsWith("comment ")));return te&&console.log(`${t}[analyze debugging] ibGibs commentIbs: ${m.join(`
16
+ `)} (I: c89dc951315f746954f9bddbe8941122)`),n?Kc({ibGibs:e,ibGibAddrs:r,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}):Hc({ibGibs:e,ibGibAddrs:r,gotten:a,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:p,timeLogName:h})}catch(e){throw console.error(`${t} ${e.message}`),e}finally{te&&console.log(`${t} complete.`)}}b(_o,"getGraphProjection");async function Yr({ibGibAddr:o,latestCommonFrameAddr:t,live:e,space:r}){let n=`[${Yr.name}]`;try{if(te&&console.log(`${n} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`),o===t)return console.warn(`${n} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`),{};let a=await Ot({ibGibAddr:t,live:!1,space:r});return await Ot({ibGibAddr:o,live:e,skipAddrs:Object.keys(a),space:r})}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{te&&console.log(`${n} complete.`)}}b(Yr,"getDeltaDependencyGraph");async function Kc({ibGibs:o,ibGibAddrs:t,gotten:e,tjpAddrsAlreadyAnalyzed:r,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:l,space:d,timeLogName:f}){let p=`[${Kc.name}]`;try{n=n??{},r=r??[];let h={...e};(o??[]).forEach(_=>h[y({ibGib:_})]=_);let g=ft({ibGibs:Object.values(h)});te&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(g).length}): ${Object.keys(g)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let m={};Object.keys(g).forEach(_=>{r.includes(_)||(m[_]=g[_])}),te&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${F(m)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let E={},S={};Object.keys(g).filter(_=>!r.includes(_)).forEach(_=>{let $=g[_],T=$[$.length-1];E[_]=T;let I=y({ibGib:T});S[I]=_});let A=Object.keys(E).length;if(A>0){let _={};Object.keys(n).filter(N=>!r.includes(N)).forEach(N=>{let O=E[N];if(O){let P=y({ibGib:O});_[P]=n[N]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy`)}),te&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${F(_)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let $=Object.values(E),T={};if($.length>0){if(!d)throw new Error("(UNEXPECTED) space falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");let N=await Me({ibGibs:$,space:d});if(!N?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");if(T=N?.data?.latestAddrsMap,Object.keys(T).length!==A)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");te&&console.log(`${p} queriedLatestAddrsMap: ${F(T)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),_={...T,..._}}te&&console.log(`${p} combined latestAddrsMap: ${F(_)} (I: e3aedea63f29c5b06a79632f691aa522)`);let I=[],G={};Object.values(E).forEach(N=>{let O=y({ibGib:N}),P=S[O],R=_[O];if(!R)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");R===O?(te&&console.log(`${p} analyzed ${P}(I: afb7960900f04b8a87538f4c7bd903b7)`),r.push(P)):(I.push(R),G[R]=P)});let v=[];for(let N=0;N<(o??[]).length;N++){let P=o[N].rel8ns??{};Object.keys(P).filter(k=>!(s??[]).includes(k)).filter(k=>i?i.includes(k):!0).forEach(k=>{(P[k]??[]).forEach(K=>{!v.includes(K)&&!o.some(ye=>y({ibGib:ye})===K)&&!ue({gib:J({ibGibAddr:K}).gib})&&v.push(K)})})}return t=Po([...t??[],...v,...I]),await _o({ibGibs:o,ibGibAddrs:t,gotten:e,tjpAddrsAlreadyAnalyzed:r,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:l,space:d,timeLogName:f,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return o||(o=[]),Object.values(e??{}).forEach(_=>{let $=y({ibGib:_});o.some(T=>y({ibGib:_})===$)||o.push(_)}),await _o({ibGibs:o,ibGibAddrs:t,gotten:e,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:l,space:d,timeLogName:f,live:!1})}catch(h){let g=`${p} ${h.message}`;throw console.error(g),f&&console.timeLog(f,`${p} error: ${g}`),h}finally{f&&console.timeLog(f,`${p} complete.`)}}b(Kc,"getGraphProjection_Live");async function Hc({ibGibs:o,ibGibAddrs:t,gotten:e,skipAddrs:r,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c,timeLogName:l}){let d=`[${Hc.name}]`;try{let f=[];o??=[],e??={},r??=[],n??=[],l&&console.timeLog(l,`${d} analyzing next step starting...`);for(let p=0;p<o.length;p++){let h=o[p],g=y({ibGib:h}),{gib:m}=J({ibGib:h});if(m===z)throw new Error("cannot get dependency graph of primitive.");Object.keys(e).includes(g)||(e[g]=h);let E={},S=h.rel8ns||{},A=(Object.keys(S)||[]).filter($=>!n.includes($));a&&(A=A.filter($=>a.includes($)));let _=Object.keys(e);for(let $=0;$<A.length;$++){let T=A[$],I=S[T]??[],G=I.filter(N=>N===""||N===void 0||N===null||!N.includes(Ae));G.length>0&&console.warn(`${d} (UNEXPECTED) has falsyAddrs: ${G} (W: da9505cb0a4db68a4aff7f279ad2d322)`),I.filter(N=>!!N).filter(N=>!_.includes(N)).filter(N=>!r.includes(N)).filter(N=>J({ibGibAddr:N}).gib!==z).filter(N=>!f.includes(N)).forEach(N=>{let O=Ur({addr:N});(O||[]).length===0?f.push(N):E[N]=O})}if(Object.keys(E).length>0)throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(E).substring(0,1024)}`)}if(l&&console.timeLog(l,`${d} analyzing next step complete.`),f.length>0){if(l&&console.timeLog(l,`${d} get addrsWeDontHaveAlready_Rel8dAddrs starting...`),!c)throw new Error("(UNEXPECTED) space falsy? (E: 0ce327cf5d521bd798340333460f3423)");let p=await W({addrs:f,space:c});if(l&&console.timeLog(l,`${d} get addrsWeDontHaveAlready_Rel8dAddrs complete.`),p.success)if(p.ibGibs?.length===f.length){te&&console.log(`${d} got ALL of them (happy path)`),p.ibGibs.forEach(g=>e[y({ibGib:g})]=g),l&&console.timeLog(l,`${d} call getGraphProjection recursively starting...`);let h=await _o({ibGibs:p.ibGibs,live:!1,gotten:e,skipAddrs:r,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c});return l&&console.timeLog(l,`${d} call getGraphProjection recursively complete.`),h}else throw(p.ibGibs?.length??0)>0&&p.ibGibs.length<f.length?(te&&console.warn(`${d} got SOME of them (happy-ish path?). not sure what to do here... (W: e3458f61a1ae4979af9e6b18ac935c14)`),new Error("trouble getting dependency ibgibs (E: 8156bf65fd084ae4a4e8a0669db28b07)")):(p.ibGibs?.length??!1)&&p.ibGibs.length>f.length?new Error("(UNEXPECTED) got more ibGibs than addrs that we asked for. space not working properly. (E: 352219b3d18543bcbda957f2d60b78f3)"):new Error("couldn't get dependency ibgibs from space. (E: 225f26b7d7f84911bb033753a062209b)");else throw new Error(`failure getting addrs in space ${c?.data?.name||"[no name?]"} (id: ${c?.data?.uuid||"[no uuid?]"}). (E: 60404e6e389249d9bbecf0039cd51878) addrs:
17
+ ${f.join(`
18
+ `)} `)}else return e}catch(f){let p=`${d} ${f.message}`;throw console.error(p),l&&console.timeLog(l,`${d} error: ${p}`),f}finally{l&&console.timeLog(l,`${d} complete.`)}}b(Hc,"getGraphProjection_NonLive");function bn({ibGibs:o}){let t=`[${bn.name}]`;try{if(te&&console.log(`${t} starting... (I: 6019a812cff8597f79c12088e45cc226)`),o){let e={};return o.forEach(r=>{e[y({ibGib:r})]=r}),e}else return}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{te&&console.log(`${t} complete.`)}}b(bn,"toFlatGraph");function me({graphA:o,graphB:t,slowButThorough:e}){let r=`[${me.name}]`;try{if(te&&console.log(`${r} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(o).length===Object.keys(t).length))return te&&console.log(`${r} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let a of Object.keys(o))if(!t[a])return te&&console.log(`${r} addr (${a}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`),!1;if(e)for(let a of Object.keys(o)){let s=qe({ibGib:o[a]}),i=JSON.stringify(s),c=qe({ibGib:t[a]}),l=JSON.stringify(c);if(i!==l)return te&&console.log(`${r} jsonA !== jsonB for addr (${a}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{te&&console.log(`${r} complete.`)}}b(me,"graphsAreEquivalent");var Ee=!1;async function Xc({keystoneData:o}){let t=`[${Xc.name}]`;try{return Ee&&console.log(`${t} starting... (I: c3022a146faac9730154f34d1439a225)`),[yo].join(" ")}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Ee&&console.log(`${t} complete.`)}}b(Xc,"getKeystoneIb");async function ts({ib:o}){let t=`[${ts.name}]`;try{Ee&&console.log(`${t} starting... (I: 73cb6832984255ed48b2f44db6a21e25)`);let[e]=o.split(" ");if(e!==yo)throw new Error(`invalid keystone ib. atom found in ib (${e}) does not match keystone atom (${yo}) (E: 79b3d587824c4271b6e60acc76e0c825)`);return{atom:e}}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Ee&&console.log(`${t} complete.`)}}b(ts,"parseKeystoneIb");async function So({ib:o}){try{return await ts({ib:o}),!0}catch{return!1}}b(So,"validateKeystoneIb");async function qc({pool:o,requiredChallengeIds:t,targetAddr:e}){let r=o.config.behavior,n=new Set,a=Object.keys(o.challenges);if(t&&t.length>0){for(let s of t){if(!o.challenges[s])throw new Error(`(UNEXPECTED) Required challenge ID not found in pool: ${s} (E: 10c5619d80d8cf6cc84ffbf8be0dbc25)`);a.includes(s)&&n.add(s)}a=a.filter(s=>!n.has(s))}if(r.targetBindingCount>0&&e){let s=[...a].sort(),i=await _e({s:e});for(let c=0;c<r.targetBindingCount;c++){if(s.length===0)throw new Error("Entropy Exhaustion. Cannot satisfy target binding. Sorted available pool is empty. (E: 341b95dc3a58be3e083d1d9c4a0c4925)");let l=BigInt("0x"+i),d=Number(l%BigInt(s.length)),f=s[d];n.add(f),s.splice(d,1),a=a.filter(p=>p!==f),i=await _e({s:i})}}if(r.selectSequentially>0){if(a.length<r.selectSequentially)throw console.error(`[getDeterministicRequirements] Entropy Exhaustion! AvailableCount: ${a.length}, Required Seq: ${r.selectSequentially}. Available IDs: ${a.join(",")}`),new Error("Entropy Exhaustion. Insufficient challenges for FIFO requirement. (E: 9efa88003e1d5eccb837c85154ee5625)");a.slice(0,r.selectSequentially).forEach(i=>n.add(i)),a=a.slice(r.selectSequentially)}return{mandatoryIds:n,availableIds:a}}b(qc,"getDeterministicRequirements");function Ao({pools:o,poolId:t,poolFilter:e,verb:r}){let n="[resolveTargetPool]";try{let a;if(t){if(a=o.find(s=>s.id===t),!a)throw new Error(`Pool not found with ID: ${t} (E: 4a2b17428515c1e82813158581898125)`)}else if(e){let s=o.filter(e);if(s.length===0)throw new Error("No pool matched the provided filter. (E: 5b3c27428515c1e82813158581898125)");a=s[0]}else{if(!r)throw new Error("Cannot auto-resolve pool without a verb. (E: 6c4d37428515c1e82813158581898125)");if(a=o.find(s=>s.config.allowedVerbs&&s.config.allowedVerbs.includes(r)),a||(a=o.find(s=>!s.config.allowedVerbs||s.config.allowedVerbs.length===0)),!a)throw new Error(`No suitable pool found for verb: ${r} (E: 7d5e47428515c1e82813158581898125)`)}if(r&&a.config.allowedVerbs&&a.config.allowedVerbs.length>0&&!a.config.allowedVerbs.includes(r))throw new Error(`Pool ${a.id} is not authorized for verb: ${r} (E: 8e6f57428515c1e82813158581898125)`);return a}catch(a){throw console.error(`${n} ${w(a)}`),a}}b(Ao,"resolveTargetPool");async function Ar({pool:o,targetAddr:t,requiredChallengeIds:e}){let r="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:a}=await qc({pool:o,requiredChallengeIds:e,targetAddr:t}),s=o.config.behavior.selectRandomly,i=[];if(s>0){if(a.length<s)throw new Error(`Insufficient challenges for random requirement. Need ${s}, have ${a.length} (E: 9f7a67428515c1e82813158581898125)`);let c=[...a].sort(()=>.5-Math.random());i.push(...c.slice(0,s))}return[...n,...i]}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(Ar,"selectChallengeIds");async function Yc({salt:o,timestamp:t,index:e}){return(await _e({s:`${o}${t}${e}`})).substring(0,16)}b(Yc,"generateOpaqueChallengeId");async function ob({prevPools:o,targetPoolId:t,consumedIds:e,masterSecret:r,strategy:n,config:a,verb:s}){let i="[applyReplenishmentStrategy]";try{let c=JSON.parse(JSON.stringify(o)),l=c.findIndex(g=>g.id===t);if(l===-1)throw new Error(`Target pool ${t} not found in keystone data. (E: 75200388d22744838634524233772545)`);let d=c[l],f=await n.derivePoolSecret({masterSecret:r}),p=Date.now().toString(),h=a.behavior.replenish;if(s===qr&&(h=$e.deleteAll),h===$e.topUp){e.forEach(g=>delete d.challenges[g]);for(let g=0;g<e.length;g++){let m=await Yc({salt:a.salt,timestamp:p,index:g}),E=await n.generateSolution({poolSecret:f,poolId:d.id,challengeId:m});d.challenges[m]=await n.generateChallenge({solution:E})}}else if(h===$e.replaceAll)d.challenges=await un({config:a,masterSecret:r});else if(h===$e.consume)e.forEach(g=>delete d.challenges[g]);else if(h===$e.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${h}. Valid list: ${F(Tc)} (E: 0acf56f1e1486240080e11e8046d0825)`);return c}catch(c){throw console.error(`${i} ${w(c)}`),c}}b(ob,"applyReplenishmentStrategy");async function Tr({targetPoolId:o,prevPools:t,masterSecret:e,challengeIds:r,claim:n,requiredChallengeIds:a}){let s="[solveAndReplenish]";try{Ee&&console.log(`${s} starting... poolId: ${o}, ids: ${r.length}`);let i=t.find(g=>g.id===o);if(!i)throw new Error(`Target pool not found: ${o} (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);let c=Dt.create({config:i.config}),l=await c.derivePoolSecret({masterSecret:e});if(!await os({pool:i,signingSecret:e}))throw new Error(`Crypto Violation: Invalid signing secret for pool: ${i.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5f)`);let f=[];for(let g of r){let m=await c.generateSolution({poolSecret:l,poolId:i.id,challengeId:g});f.push(m)}let p={claim:n,solutions:f,requiredChallengeIds:a&&a.length>0?a:void 0},h=await ob({prevPools:t,targetPoolId:i.id,consumedIds:r,masterSecret:e,strategy:c,config:i.config,verb:n.verb});return{proof:p,nextPools:h}}catch(i){throw console.error(`${s} ${w(i)}`),i}}b(Tr,"solveAndReplenish");async function Wc({pool:o}){let t=`[${Wc.name}]`;try{if(Ee&&console.log(`${t} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!o.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(o.config.type!==bt.hash_reveal_v1)throw new Error("(UNEXPECTED) pool.config.type !== KeystoneChallengeType.hash_reveal_v1? (E: e205f8872909c37168a624a9df778c26)");let e=[],{algo:r,rounds:n,salt:a}=o.config,s=[De.sha_256,De.sha_512];return r?s.includes(r)||e.push(`${t} invalid hash algorithm (${r}). Must be one of ${s}. (E: a22399ca3a68e63ffcc7507699be5826)`):e.push(`${t} algorithm required. (E: 8cd6bfb0590862b9bae24d98d2cf3826)`),n&&typeof n=="number"&&Number.isInteger(n)?n>Za&&e.push(`${t} rounds too high. max rounds: ${Za} (E: 31ce082f7fd88d6b58ef08a816458826)`):e.push(`${t} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),a&&typeof a=="string"?Wa.test(a)||e.push(`${t} invalid salt (${a.substring(0,99)}). Must match regexp ${Wa}`):e.push(`${t} invalid salt (${a}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Ee&&console.log(`${t} complete.`)}}b(Wc,"validateChallengePool_typeHashRevealV1");async function zc({pool:o}){let t=`[${zc.name}]`;try{Ee&&console.log(`${t} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let e=[];if(o.config){if(o.config.id?Ya.test(o.config.id)||e.push(`${t} pool.config.id is not formatted correctly. must pass regexp: ${Ya.source}`):e.push(`${t} pool.config.id falsy (E: 31d7943d95f877326d5f4ea14463d626)`),o.config.behavior){let{size:n,selectSequentially:a,selectRandomly:s,targetBindingCount:i}=o.config.behavior;(!n||n===0)&&e.push(`${t} invalid pool.config.behavior.size (${n}). Must be positive integer. (E: b221e36ec102bdc944552248ce8fe626)`);let c=(a||0)+(s||0)+(i||0);c>=n&&e.push(`${t} Total requested challenges (${c}) cannot equal or exceed pool size (${n}) to prevent full pool exposure and selection exhaustion. (E: 81cb834f826315264bca81c15fca58f1)`)}else e.push(`${t} pool.config.behavior falsy (E: bede081c066c39732eefe2f92e296326)`);let r=o.config.type;switch(r){case bt.hash_reveal_v1:(await Wc({pool:o})).forEach(a=>e.push(a));break;default:throw new Error(`(UNEXPECTED) unknown pool.config.type (${r})? We only implement the following at this time: ${Ac} (E: cce5285cf7580b8bc82172488eba2826)`)}}else e.push(`${t} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Ee&&console.log(`${t} complete.`)}}b(zc,"validateChallengePool");function Jc({data:o}){let t="[validateKeystoneMetadata]",e=[],r=b((n,a)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!za.test(n.username))&&e.push(`${t} invalid username in ${a} (${n.username}). Must match ${za}`),n.description!==void 0&&(typeof n.description!="string"||!Ja.test(n.description))&&e.push(`${t} invalid description in ${a} (${n.description}). Must match ${Ja}`))},"checkDetails");return r(o.frameDetails,"frameDetails"),r(o.checkpointDetails,"checkpointDetails"),e}b(Jc,"validateKeystoneMetadata");async function pn({keystoneIbGib:o}){let t=`[${pn.name}]`;try{Ee&&console.log(`${t} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let e=[],{data:r,rel8ns:n}=o;await So({ib:o.ib})||e.push(`${t} invalid keystone ib (${o.ib}). (E: ad7a88bc38c290a184dfbd42be48f526)`),Jc({data:r}).forEach(i=>e.push(i)),r.proofs&&r.proofs.length>0&&e.push(`${t} proofs already exist on genesis keystone. (E: 7a5e15f20918f1bbd8ffb62857dcd526)`);for(let i of r.challengePools)(await zc({pool:i})).forEach(l=>e.push(l)),(!i.challenges||Object.keys(i.challenges).length===0)&&e.push(`${t} invalid pool (${i.id}). pool.challenges is falsy/empty. (E: 8cd16a5416ae62a058342828be465b26)`);return r.revocationInfo&&e.push(`${t} genesis keystone already has revocationInfo. (E: e11408d0c558d0fa948efbce611ec826)`),e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Ee&&console.log(`${t} complete.`)}}b(pn,"validateGenesisKeystone");function nb({currDelegates:o,prevDelegates:t}){let e=o||{},r=t||{},n=Object.keys(e),a=Object.keys(r);if(n.length!==a.length)return!0;for(let s of n){let i=e[s],c=r[s];if(!c||i.delegateTjpAddr!==c.delegateTjpAddr||i.delegateAddr!==c.delegateAddr||i.thisAddr!==c.thisAddr)return!0}return!1}b(nb,"isDelegatesChanged");async function ab({currDelegates:o,prevIbGib:t,lc:e,errors:r}){let n=Object.keys(o),a=y({ibGib:t});for(let s of n){let i=o[s];s!==i.delegateTjpAddr&&r.push(`${e} Invalid delegate mapping: Key '${s}' does not match delegateTjpAddr '${i.delegateTjpAddr}'. (E: 9c8da8bc38c290a184dfbd42be48f526)`);let[c,l,d]=await Promise.all([So({ib:i.delegateTjpAddr.split("^")[0]}),So({ib:i.delegateAddr.split("^")[0]}),So({ib:i.thisAddr.split("^")[0]})]);c||r.push(`${e} Delegate delegateTjpAddr '${i.delegateTjpAddr}' is not a valid keystone address. (E: 10d8a8bc38c290a184dfbd42be48f526)`),l||r.push(`${e} Delegate delegateAddr '${i.delegateAddr}' is not a valid keystone address. (E: 20d8a8bc38c290a184dfbd42be48f526)`),d||r.push(`${e} Delegate thisAddr '${i.thisAddr}' is not a valid keystone address. (E: 30d8a8bc38c290a184dfbd42be48f526)`),i.thisAddr===a||(t.rel8ns?.past||[]).includes(i.thisAddr)||r.push(`${e} Delegate thisAddr '${i.thisAddr}' is not a valid historical address in the parent keystone timeline. (E: 40d8a8bc38c290a184dfbd42be48f526)`)}}b(ab,"validateDelegates");async function To({currentIbGib:o,prevIbGib:t}){let e=`[${To.name}]`,r=[];try{if(!o)throw new Error("(UNEXPECTED) currentIbGib falsy? (E: 3c0f02655fa8279e386a079ebb604b25)");if(!t)throw new Error("(UNEXPECTED) prevIbGib falsy? (E: 0d07c812634d839c784f31b8848ba825)");let n=await le({ibGib:o});n&&n.length>0&&r.push(...n);let a=o.data,s=t.data;await So({ib:o.ib})||r.push(`${e} invalid keystone ib (${o.ib}). (E: a98dc8bc38c290a184dfbd42be48f526)`),Jc({data:a}).forEach(m=>r.push(m));let l=a.delegates||{},d=s.delegates||{};nb({currDelegates:l,prevDelegates:d})&&(a.proofs?.some(E=>E.claim?.verb===Qe)||r.push(`${e} Policy Violation: Delegates map was mutated but no proof for manage verb ('${Qe}') is present. (E: 819fa8cb28c9b60e68994511a5825)`)),await ab({currDelegates:l,prevIbGib:t,lc:e,errors:r});let p=a.n??-2,h=s.n??-2;p<0&&r.push("invalid keystone.currData.n is undefined or null. (E: 9fbe38704b68829d18ea1d0940d0aa26)"),h<0&&r.push("invalid keystone.prevData.n is undefined or null. (E: 6dc5aa9c87017db6080ed4268b07af26)"),p!==h+1&&r.push(`keystone data.n values are not sequential. prevData.n: ${h}, currData.n: ${p}. (E: 5ae12809f2c67216d38d8ba8d6c42826)`);for(let m of a.proofs){if(m.solutions.length===0){r.push(`Proof ${m.id||"unknown"} has no solutions. (E: e2b4683ce0ce30f798ec77841e88c826)`);continue}let E=m.solutions[0].poolId,S=s.challengePools.find(A=>A.id===E);if(!S){r.push(`Proof references unknown pool: ${E}`);continue}await Zc({proof:m,pool:S,errors:r})}if(a.revocationInfo){let m=a.revocationInfo.proof.claim.target,E=y({ibGib:t});m!==E&&r.push(`Revocation target mismatch. Expected ${E}, got ${m}`)}let g=new Set(a.proofs.map(m=>m.solutions?.[0]?.poolId).filter(Boolean));for(let m of a.proofs){let E=m.claim;if(E?.details){let S=E.details,A=S.type,_=S.info;if(A==="add-pool"){let $=_;if(!$||!Array.isArray($.add)||$.add.length===0){r.push(`details type is '${A}' but payload is invalid. (E: 1fa2a8cb28c9b60e68994511a5825)`);continue}let T=new Set(s.challengePools.map(G=>G.id)),I=new Set(a.challengePools.map(G=>G.id));for(let G of $.add)I.has(G)||r.push(`ClaimDetails_AddPool lists pool ${G} but it is missing in the evolved keystone. (E: 2fa2a8cb28c9b60e68994511a5825)`),T.has(G)&&r.push(`ClaimDetails_AddPool attempts to add existing pool ${G}. (E: 3fa2a8cb28c9b60e68994511a5825)`);a.challengePools.length!==s.challengePools.length+$.add.length&&r.push(`Structural mismatch: expected ${s.challengePools.length+$.add.length} pools, found ${a.challengePools.length}. (E: 4fa2a8cb28c9b60e68994511a5825)`);for(let G of s.challengePools){let v=a.challengePools.find(N=>N.id===G.id);if(!v){r.push(`Existing pool ${G.id} was removed during add-pool transition. (E: 5fa2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(G.config)!==JSON.stringify(v.config)&&r.push(`Existing pool config ${G.id} was mutated during add-pool transition. (E: 6fa2a8cb28c9b60e68994511a5825)`),!g.has(G.id)&&JSON.stringify(G.challenges)!==JSON.stringify(v.challenges)&&r.push(`Existing pool challenges ${G.id} were mutated during add-pool transition. (E: 7fa2a8cb28c9b60e68994511a5825)`)}}else if(A==="replace-pool"){let $=_;if(!$||typeof $.replace!="string"||!$.replace){r.push(`details type is '${A}' but payload is invalid. (E: 8fa2a8cb28c9b60e68994511a5825)`);continue}let T=$.replace,I=s.challengePools.map(O=>O.id).sort(),G=a.challengePools.map(O=>O.id).sort();JSON.stringify(I)!==JSON.stringify(G)&&r.push("replace-pool transition mutated the pool IDs set. (E: 9fa2a8cb28c9b60e68994511a5825)");let v=s.challengePools.find(O=>O.id===T),N=a.challengePools.find(O=>O.id===T);(!v||!N)&&r.push(`Replaced pool ${T} not found in keystone challenge pools. (E: afa2a8cb28c9b60e68994511a5825)`);for(let O of s.challengePools){if(O.id===T)continue;let P=a.challengePools.find(R=>R.id===O.id);P&&(JSON.stringify(O.config)!==JSON.stringify(P.config)&&r.push(`Unrelated pool config ${O.id} was mutated during replace-pool. (E: bfa2a8cb28c9b60e68994511a5825)`),!g.has(O.id)&&JSON.stringify(O.challenges)!==JSON.stringify(P.challenges)&&r.push(`Unrelated pool challenges ${O.id} were mutated during replace-pool. (E: cfa2a8cb28c9b60e68994511a5825)`))}}else if(A==="remove-pool"){let $=_;if(!$||!Array.isArray($.remove)||$.remove.length===0){r.push(`details type is '${A}' but payload is invalid. (E: b7a2a8cb28c9b60e68994511a5825)`);continue}let T=new Set($.remove),I=new Set(s.challengePools.map(v=>v.id)),G=new Set(a.challengePools.map(v=>v.id));for(let v of $.remove)I.has(v)||r.push(`ClaimDetails_RemovePool lists pool ${v} but it is missing in the previous keystone. (E: c7a2a8cb28c9b60e68994511a5825)`),G.has(v)&&r.push(`ClaimDetails_RemovePool lists pool ${v} but it is still present in the evolved keystone. (E: d7a2a8cb28c9b60e68994511a5825)`);a.challengePools.length!==s.challengePools.length-$.remove.length&&r.push(`Structural mismatch: expected ${s.challengePools.length-$.remove.length} pools, found ${a.challengePools.length}. (E: e7a2a8cb28c9b60e68994511a5825)`);for(let v of s.challengePools){if(T.has(v.id))continue;let N=a.challengePools.find(O=>O.id===v.id);if(!N){r.push(`Pool ${v.id} was unexpectedly removed. (E: f7a2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(v.config)!==JSON.stringify(N.config)&&r.push(`Remaining pool config ${v.id} was mutated during remove-pool. (E: 07a2a8cb28c9b60e68994511a5825)`),!g.has(v.id)&&JSON.stringify(v.challenges)!==JSON.stringify(N.challenges)&&r.push(`Remaining pool challenges ${v.id} were mutated during remove-pool. (E: 17a2a8cb28c9b60e68994511a5825)`)}}else if(A==="change-password"){let $=_;if(!$||!Array.isArray($.change)||$.change.length===0){r.push(`details type is '${A}' but payload is invalid. (E: dfa2a8cb28c9b60e68994511a5825)`);continue}let T=s.challengePools.map(v=>v.id).sort(),I=a.challengePools.map(v=>v.id).sort();JSON.stringify(T)!==JSON.stringify(I)&&r.push("change-password transition mutated the pool IDs set. (E: efa2a8cb28c9b60e68994511a5825)");let G=new Set($.change);for(let v of s.challengePools){let N=a.challengePools.find(O=>O.id===v.id);if(N)if(G.has(v.id)){v.isForeign&&r.push(`Security Violation: Password rotation attempted on foreign pool ${v.id}. (E: ffa2a8cb28c9b60e68994511a5825)`);let O={...v.config,salt:""},P={...N.config,salt:""};JSON.stringify(O)!==JSON.stringify(P)&&r.push(`Pool config metadata for rotated pool ${v.id} was mutated. (E: 00b2a8cb28c9b60e68994511a5825)`),v.config.salt===N.config.salt&&r.push(`Pool salt for rotated pool ${v.id} was not rotated. (E: 01b2a8cb28c9b60e68994511a5825)`)}else JSON.stringify(v.config)!==JSON.stringify(N.config)&&r.push(`Unrelated pool config ${v.id} was mutated during change-password. (E: 02b2a8cb28c9b60e68994511a5825)`),!g.has(v.id)&&JSON.stringify(v.challenges)!==JSON.stringify(N.challenges)&&r.push(`Unrelated pool challenges ${v.id} were mutated during change-password. (E: 03b2a8cb28c9b60e68994511a5825)`)}}else r.push(`Unknown claim details type: ${A}`)}}return r}catch(n){throw console.error(`${e} ${w(n)}`),n}finally{Ee&&console.log(`${e} complete.`)}}b(To,"validateKeystoneTransition");async function Zc({proof:o,pool:t,errors:e}){let r=`[${Zc.name}]`;try{Ee&&console.log(`${r} starting... (I: b8f9b6085888eea2258bf579ecd5e825)`),t.config.allowedVerbs&&t.config.allowedVerbs.length>0&&(!o.claim.verb||!t.config.allowedVerbs.includes(o.claim.verb))&&e.push(`Policy Violation: Pool ${t.id} used for unauthorized verb ${o.claim.verb}`);let{mandatoryIds:n,availableIds:a}=await qc({pool:t,requiredChallengeIds:o.requiredChallengeIds,targetAddr:o.claim.target}),s=new Set(o.solutions.map(d=>d.challengeId));for(let d of n)s.has(d)||e.push(`Policy Violation: Missing mandatory challenge ${d}`);let i=[...s].filter(d=>!n.has(d)),c=t.config.behavior.selectRandomly;i.length<c&&e.push(`Policy Violation: Insufficient random count. Need ${c}, got ${i.length}`);for(let d of i)a.includes(d)||e.push(`Policy Violation: ID ${d} is invalid or double-dipped.`);let l=Dt.create({config:t.config});for(let d of o.solutions){let f=t.challenges[d.challengeId];f?await l.validateSolution({solution:d,challenge:f})||e.push(`Crypto Violation: Solution for ${d.challengeId} is invalid.`):e.push(`Crypto Violation: Challenge ${d.challengeId} not found in pool.`)}}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{Ee&&console.log(`${r} complete.`)}}b(Zc,"verifyProofAgainstPool");async function nr({prevIbGib:o,newData:t,metaspace:e,space:r}){let n=`[${nr.name}]`;try{if(Ee&&console.log(`${n} starting... (I: 8b10e8920f08b7842803665834cf8925)`),!o.data)throw new Error("(UNEXPECTED) prevIbGib.data falsy? (E: 5e84875bf992c585b979e6c8ed5bf225)");if(o.data.revocationInfo)throw new Error(`Keystone has already been revoked (prevIbGib.data.revocationInfo truthy), so we cannot evolve the keystone. Keystone addr: ${y({ibGib:o})} (E: 45d7f846556829de6b2a701838c3f825)`);let a=o.data,s={};a.proofs&&(s.proofs=[]),a.challengePools&&(s.challengePools=[]),a.frameDetails&&(s.frameDetails={}),a.checkpointDetails&&(s.checkpointDetails={}),a.delegates&&(s.delegates="remove"),Object.keys(s).length===0&&(s=void 0);let i=await ot({src:o,dataToRemove:s,dataToAddOrPatch:t,nCounter:!0});if(i.intermediateIbGibs)throw new Error("(UNEXPECTED) resMut8.intermediateIbGibs truthy? I'm not sure if we expect there to be intermediateIbGibs, but I feel like we shouldn't. Pretty sure we shouldn't, definitely don't *want* them. (E: ba40d55d7c2d36d438c413886f148625)");if(i.dnas)throw new Error("(UNEXPECTED) resMut8.dnas truthy? We do not want dnas with keystones. (E: 49470513d018f97d28024f4e82da3b25)");let c=i.newIbGib,l=await To({currentIbGib:c,prevIbGib:o});if(l.length>0)throw console.error(`${n} Validation Failed:
19
+ ${l.join(`
20
+ `)}`),new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${l.join("; ")} (E: ae2c58406c1db7687879dfb89fc1f825)`);return await e.put({ibGib:c,space:r}),await e.registerNewIbGib({ibGib:c,space:r}),c}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Ee&&console.log(`${n} complete.`)}}b(nr,"evolvePersistAndRegisterKeystone");async function rs({data:o,metaspace:t,space:e}){let r=`[${rs.name}]`;try{if(Ee&&console.log(`${r} starting... (I: 5e32389700e9899e788cbefacef7c825)`),e??=await t.getLocalUserSpace({lock:!1}),!e)throw new Error("(UNEXPECTED) space was falsy and we couldn't get default local user space from metaspace? (E: 9a6498cf16a8801f19ec376749742225)");let a=(await B.firstGen({parentIbGib:B.primitive({ib:yo}),ib:await Xc({keystoneData:o}),data:o,dna:!1,nCounter:!0,tjp:{timestamp:!0,uuid:!0}})).newIbGib;if(!a.data)throw new Error("(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)");if(!a.rel8ns)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)");if(!a.rel8ns.past||a.rel8ns.past.length===0)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns.past falsy or empty? we expect the firstGen call to generate an interstitial ibgib that we will splice out. (E: 0fd8388d045ab9f37834c27d67e78825)");return a.data.n=0,a.data.isTjp=!0,delete a.rel8ns.tjp,delete a.rel8ns.past,a.gib=await ce({ibGib:a}),await t.put({ibGib:a,space:e}),await t.registerNewIbGib({ibGib:a,space:e}),a}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{Ee&&console.log(`${r} complete.`)}}b(rs,"createKeystoneIbGibImpl");async function hn({keystoneIbGib:o,dependencyGraph:t,getLatest:e,invalidIfMoreRecentKeystoneFoundInSpace:r,space:n}){let a=`[${hn.name}]`;try{if(Ee&&console.log(`${a} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!o)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let s=[];if(e){let f=y({ibGib:o}),p=await Me({ibGibs:[o],space:n});if(!p.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!p.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:h}=p.data;if(Object.keys(h).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let g=h[f];if(g)if(g!==f)if(r)s.push(`${a} more recent keystone (${g}) found than the one passed in (${f}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[m]=await at({addrs:[g],space:n});o=m}else Ee&&console.log(`${a} incoming keystone (${f}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${a} keystoneIbGib (${f}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}t??=await Ot({ibGib:o,space:n});let i=Object.values(t),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:l,mapWithoutTjps:d}=Nt({ibGibs:i});if(Object.keys(l).length>0&&s.push(`${a} DNA found. Keystones should NOT have DNA. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(d).length>0&&s.push(`${a} Non-tjp ibgibs found? Keystones are expected to have tjps. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(c).length>0){let f=Object.values(c),p=ft({ibGibs:f}),h=Object.keys(p);if(h.length===0)throw new Error("(UNEXPECTED) orderedKeystonesMap empty? (E: d437b80bef58e83a034b28af46278726)");if(h.length>1)throw new Error("(UNEXPECTED) more than one timeline in keystone graph? ATOW (02/19/2026) we are expecting only a single timeline. (E: 66085b14e3887a59c872afd240511f26)");let g=h[0],m=p[g];if(m.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await pn({keystoneIbGib:m[0]})).forEach(S=>s.push(S)),m.length!==1)for(let S=0;S<m.length-1;S++){let A=m[S],_=m[S+1],$=await To({prevIbGib:A,currentIbGib:_});$.length>0&&(s.push(`${a} keystone has ${$.length} transition errors. i: ${S}. prevIbGib addr: ${y({ibGib:A})}. currentIbGib addr: ${y({ibGib:_})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),$.forEach(T=>s.push(T)));break}}else if(s.length===0)throw new Error("(UNEXPECTED) mapWithTjp_NoDna empty (which is an error) but errors.length === 0? If we get here, we expect one of the other errors to have been populated. (E: 7bca2866b6f8fca318923de8c88e8826)");return s}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{Ee&&console.log(`${a} complete.`)}}b(hn,"validateKeystoneGraph");async function un({config:o,masterSecret:t}){let e=Dt.create({config:o}),r=await e.derivePoolSecret({masterSecret:t}),n={},a=o.behavior.size,s=Date.now().toString();for(let i=0;i<a;i++){let c=await Yc({salt:o.salt,timestamp:s,index:i}),l=await e.generateSolution({poolSecret:r,poolId:o.id,challengeId:c});n[c]=await e.generateChallenge({solution:l})}return n}b(un,"generatePoolChallenges");async function Qc({prevPool:o,newMasterSecret:t}){let e=o.config,r=(await V()).substring(0,16),n={...e,salt:r},a=await un({config:n,masterSecret:t});return{id:o.id,config:n,challenges:a,...o.isForeign!==void 0?{isForeign:o.isForeign}:{},...o.metadata?{metadata:o.metadata}:{}}}b(Qc,"rotatePoolChallenges");async function os({pool:o,signingSecret:t}){let e=Object.keys(o.challenges);if(e.length===0)return!1;try{let r=e[0],n=o.challenges[r],a=Dt.create({config:o.config}),s=await a.derivePoolSecret({masterSecret:t}),i=await a.generateSolution({poolSecret:s,poolId:o.id,challengeId:r});return await a.validateSolution({solution:i,challenge:n})}catch{return!1}}b(os,"verifyPoolSecret");var se=!1,Ue=class o{static{b(this,"KeystoneService_V1")}lc=`[${o.name}]`;async genesis({masterSecret:t,frameDetails:e,configs:r,metaspace:n,space:a,isPrimary:s}){let i=`${this.lc}[${this.genesis.name}]`;try{se&&console.log(`${i} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let c=[];for(let f of r){let p=await un({config:f,masterSecret:t});c.push({id:f.id,config:f,challenges:p})}if(c.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let l={challengePools:c,proofs:[]};return(e||s!==void 0)&&(l.frameDetails={...e||{}},s!==void 0&&(l.frameDetails.isPrimary=s)),await rs({data:l,metaspace:n,space:a})}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{se&&console.log(`${i} complete.`)}}async sign({latestKeystone:t,masterSecret:e,claim:r,poolId:n,poolFilter:a,requiredChallengeIds:s=[],frameDetails:i,metaspace:c,space:l,dataToPatch:d}){let f=`${this.lc}[${this.sign.name}]`;try{se&&console.log(`${f} starting...`);let p=t.data;if(p.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");let h=Ao({pools:p.challengePools,poolId:n,poolFilter:a,verb:r.verb});se&&console.log(`${f} Selected pool: ${h.id} (size: ${Object.keys(h.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let g=await Ar({pool:h,targetAddr:r.target,requiredChallengeIds:s}),{proof:m,nextPools:E}=await Tr({targetPoolId:h.id,prevPools:p.challengePools,masterSecret:e,challengeIds:g,claim:r,requiredChallengeIds:s}),S=(p.n??0)+1,A;if(S%Sr===0){let T={...t,data:{...p,frameDetails:i}};A=await this.getAggregateDetails({latestKeystone:T,metaspace:c,space:l})}let _={challengePools:E,proofs:[m],frameDetails:i,checkpointDetails:A,...p.delegates?{delegates:p.delegates}:{},...d};return await nr({prevIbGib:t,newData:_,metaspace:c,space:l})}catch(p){throw console.error(`${f} ${w(p)}`),p}finally{se&&console.log(`${f} complete.`)}}async validate({currentIbGib:t,prevIbGib:e}){return await To({currentIbGib:t,prevIbGib:e})}async registerDelegate({parentKeystone:t,delegateKeystone:e,masterSecret:r,frameDetails:n,metaspace:a,space:s,allowedVerbs:i}){let c=`${this.lc}[${this.registerDelegate.name}]`;try{se&&console.log(`${c} starting...`);let l=await hn({keystoneIbGib:e,getLatest:!0,invalidIfMoreRecentKeystoneFoundInSpace:!1,space:s});if(l.length>0)throw new Error(`Delegate keystone validation failed: ${l.join(", ")} (E: 88fa8ab28c9b60e68994511a5825)`);let d=t.data;if(!d.challengePools.some(E=>E.id===Xt))throw new Error("Parent keystone does not support delegation. Manage pool is required. (E: 818fa8ab28c9b60e68994511a5825)");let p=ee({ibGib:e});if(!p)throw new Error("(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)");let h={target:p,verb:Qe},g=d.delegates?{...d.delegates}:{};return g[p]={delegateTjpAddr:p,delegateAddr:y({ibGib:e}),thisAddr:y({ibGib:t}),allowedVerbs:i},await this.sign({latestKeystone:t,masterSecret:r,claim:h,poolId:Xt,frameDetails:n,metaspace:a,space:s,dataToPatch:{delegates:g}})}catch(l){throw console.error(`${c} ${w(l)}`),l}finally{se&&console.log(`${c} complete.`)}}async unregisterDelegate({parentKeystone:t,delegateTjpAddr:e,masterSecret:r,frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.unregisterDelegate.name}]`;try{se&&console.log(`${i} starting...`);let c=t.data;if(!c.challengePools.some(h=>h.id===Xt))throw new Error("Parent keystone does not support delegation. Manage pool is required. (E: 3889f8ab28c9b60e68994511a5825)");let d={target:e,verb:Qe},f=c.delegates?{...c.delegates}:{};if(!f[e])throw new Error(`Delegate ${e} is not registered on this parent. (E: 81d9f8ab28c9b60e68994511a5825)`);return delete f[e],await this.sign({latestKeystone:t,masterSecret:r,claim:d,poolId:Xt,frameDetails:n,metaspace:a,space:s,dataToPatch:{delegates:f}})}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{se&&console.log(`${i} complete.`)}}async getDelegateStatus({parentTjpAddr:t,delegateTjpAddr:e,metaspace:r,space:n}){let a=`${this.lc}[${this.getDelegateStatus.name}]`;try{se&&console.log(`${a} starting...`);let{ib:s,gib:i}=J({ibGibAddr:t}),l=await Me({ibGibs:[{ib:s,gib:i}],space:n});if(!l.data?.latestAddrsMap)return{registered:!1};let d=l.data.latestAddrsMap[t];if(!d)return{registered:!1};let p=(await r.get({addr:d,space:n})).ibGibs?.at(0);if(!p||!p.data)return{registered:!1};let g=(p.data.delegates||{})[e];return{registered:!!g,delegateInfo:g}}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{se&&console.log(`${a} complete.`)}}async validateGenesisKeystone({keystoneIbGib:t}){return await pn({keystoneIbGib:t})}async getLatestKeystone({addr:t,metaspace:e,space:r}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{se&&console.log(`${n} starting...`);let a=await e.getLatestAddr({tjpAddr:t,space:r});if(!a)throw new Error(`could not find latest addr for ${t}`);let s=await e.get({addr:a,space:r});if(s.success&&s.ibGibs&&s.ibGibs.length>0)return s.ibGibs[0];{let c=s.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find latest keystone at ${a}. addrsNotFound: ${c}? resGet.errorMsg: ${s.errorMsg}`)}}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{se&&console.log(`${n} complete.`)}}async validateKeystoneGraph({keystoneIbGib:t,dependencyGraph:e,getLatest:r,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a}){let s=`${this.lc}[${this.validateKeystoneGraph.name}]`;try{return se&&console.log(`${s} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await hn({keystoneIbGib:t,dependencyGraph:e,getLatest:r,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{se&&console.log(`${s} complete.`)}}async revoke({latestKeystone:t,masterSecret:e,reason:r="User initiated revocation",frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.revoke.name}]`;try{se&&console.log(`${i} starting...`);let c=t.data,l=Ao({pools:c.challengePools,verb:qr}),d={verb:qr,target:y({ibGib:t})},f=await Ar({pool:l,targetAddr:d.target,requiredChallengeIds:[]});if(f.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${l.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:p,nextPools:h}=await Tr({targetPoolId:l.id,prevPools:c.challengePools,masterSecret:e,challengeIds:f,claim:d,requiredChallengeIds:[]});h.find(_=>_.id===l.id&&Object.keys(_.challenges).length>0)&&console.warn(`${i} revocation pool ${l.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${$e.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let g={reason:r,proof:p},m=(c.n??0)+1,E;if(m%Sr===0){let _={...t,data:{...c,frameDetails:n,revocationInfo:g}};E=await this.getAggregateDetails({latestKeystone:_,metaspace:a,space:s})}let S={challengePools:h,proofs:[p],revocationInfo:g,frameDetails:n,checkpointDetails:E,...c.delegates?{delegates:c.delegates}:{}};return await nr({prevIbGib:t,newData:S,metaspace:a,space:s})}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{se&&console.log(`${i} complete.`)}}async addPools({latestKeystone:t,masterSecret:e,newPools:r,metaspace:n,space:a}){let s=`${this.lc}[${this.addPools.name}]`;try{if(se&&console.log(`${s} starting...`),!t.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let i=t.data;if(i.revocationInfo)throw new Error("Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)");if(r.length===0)throw new Error("No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)");let c=Ao({pools:i.challengePools,verb:Qe});se&&console.log(`${s} Authorized via pool: ${c.id}`);let l=y({ibGib:t}),d={verb:Qe,target:l,details:{type:Xr.add_pool,info:{add:r.map($=>$.id)}}},f=await Ar({pool:c,targetAddr:l}),{proof:p,nextPools:h}=await Tr({targetPoolId:c.id,prevPools:i.challengePools,masterSecret:e,challengeIds:f,claim:d}),g=new Set(h.map($=>$.id));for(let $ of r)if(g.has($.id))throw new Error(`Cannot add pool. ID collision: ${$.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5d)`);let m=[...h,...r],E=(i.n??0)+1,S;if(E%Sr===0){let $={...t,data:{...i,challengePools:m}};S=await this.getAggregateDetails({latestKeystone:$,metaspace:n,space:a})}let A={challengePools:m,proofs:[p],checkpointDetails:S,...i.delegates?{delegates:i.delegates}:{}};return await nr({prevIbGib:t,newData:A,metaspace:n,space:a})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{se&&console.log(`${s} complete.`)}}async removePools({latestKeystone:t,masterSecret:e,poolIds:r,metaspace:n,space:a}){let s=`${this.lc}[${this.removePools.name}]`;try{if(se&&console.log(`${s} starting...`),!t.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 8334c8faed128166a999d428c7805b25)");let i=t.data;if(i.revocationInfo)throw new Error("Keystone has been revoked. Cannot remove pools. (E: 9599f8f51c78d722252ddb2894fdbe25)");if(r.length===0)throw new Error("No pool IDs provided to remove. (E: 7599f8f51c78d722252ddb2894fdbe25)");let c=Ao({pools:i.challengePools,verb:Qe});se&&console.log(`${s} Authorized via pool: ${c.id}`);let l=y({ibGib:t}),d={verb:Qe,target:l,details:{type:Xr.remove_pool,info:{remove:r}}},f=await Ar({pool:c,targetAddr:l}),{proof:p,nextPools:h}=await Tr({targetPoolId:c.id,prevPools:i.challengePools,masterSecret:e,challengeIds:f,claim:d}),g=new Set(r),m=h.filter($=>!g.has($.id));if(m.length!==h.length-r.length){let $=r.filter(T=>!h.some(I=>I.id===T));throw new Error(`Cannot remove pool. Pool IDs not found in keystone: ${$.join(", ")} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5e)`)}let E=(i.n??0)+1,S;if(E%Sr===0){let $={...t,data:{...i,challengePools:m}};S=await this.getAggregateDetails({latestKeystone:$,metaspace:n,space:a})}let A={challengePools:m,proofs:[p],checkpointDetails:S,...i.delegates?{delegates:i.delegates}:{}};return await nr({prevIbGib:t,newData:A,metaspace:n,space:a})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{se&&console.log(`${s} complete.`)}}async getAggregateDetails({latestKeystone:t,metaspace:e,space:r}){let n=`${this.lc}[${this.getAggregateDetails.name}]`;try{let a={},s=t;for(;s;){let i=s.data;if(i.checkpointDetails){a=Br({dominant:a,recessive:i.checkpointDetails});break}if(i.frameDetails&&(a=Br({dominant:a,recessive:i.frameDetails})),i.n===0)break;let c=s.rel8ns?.past,l=c&&c.length>0?c[c.length-1]:void 0;if(!l)break;let d=await e.get({addr:l,space:r});if(!d.success||!d.ibGibs||d.ibGibs.length===0)throw new Error(`Could not find previous keystone frame at ${l} (E: e3d069b22e11e550e58844889ddb5325)`);s=d.ibGibs[0]}return a}catch(a){throw console.error(`${n} ${w(a)}`),a}}async getKeystoneCommonInfo({addr:t,ibGib:e,metaspace:r,space:n}){let a=`${this.lc}[getKeystoneCommonInfo]`;try{let s=t,i=e;if(!s){if(!i)return null;s=y({ibGib:i})}if(!i){let{ib:$,gib:T}=J({ibGibAddr:s});i={ib:$,gib:T}}let c=await Me({ibGibs:[i],space:n});if(!c.data?.latestAddrsMap)return null;let l=c.data.latestAddrsMap[s]||Object.values(c.data.latestAddrsMap)[0];if(!l)return null;let f=(await r.get({addr:l,space:n})).ibGibs?.at(0);if(!f||!f.data)return null;let p=await this.getAggregateDetails({latestKeystone:f,metaspace:r,space:n}),h=p?.username||p?.profile?.name||p?.name||"",g=p?.description||p?.profile?.description||"",m=!!p?.isPrimary||!!p?.profile?.isPrimary,E=f.data.frameDetails||{},S=f.data.n??0,A=E?.timestamp||p?.timestamp||"",_=E?.timestampMs||p?.timestampMs||void 0;return{name:h,description:g,isPrimary:m,aggregateDetails:p,latestFrameDetails:E,n:S,timestamp:A,timestampMs:_}}catch(s){return console.error(`${a} ${w(s)}`),null}}async replacePool({latestKeystone:t,newPool:e,signingSecret:r,signingPoolId:n=Xt,frameDetails:a,metaspace:s,space:i}){let c=`${this.lc}[${this.replacePool.name}]`;try{if(se&&console.log(`${c} starting... replacing pool: ${e.id}`),!t.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 1334c8faed128166a999d428c7805b25)");let l=t.data;if(l.revocationInfo)throw new Error("Keystone has been revoked. Cannot replace pool. (E: 2599f8f51c78d722252ddb2894fdbe25)");let d=l.challengePools,f=d.find(I=>I.id===n);if(!f)throw new Error(`Signing pool not found: ${n} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let p=y({ibGib:t}),h={verb:Qe,target:p,details:{type:Xr.replace_pool,info:{replace:e.id}}},g=await Ar({pool:f,targetAddr:p}),{proof:m,nextPools:E}=await Tr({targetPoolId:n,prevPools:d,masterSecret:r,challengeIds:g,claim:h}),S=E.findIndex(I=>I.id===e.id);if(S===-1)throw new Error(`Target pool to replace '${e.id}' not found in keystone challenge pools.`);E[S]=e;let A=(l.n??0)+1,_;if(A%Sr===0){let I={...t,data:{...l,frameDetails:a}};_=await this.getAggregateDetails({latestKeystone:I,metaspace:s,space:i})}let $={challengePools:E,proofs:[m],frameDetails:a,checkpointDetails:_,...l.delegates?{delegates:l.delegates}:{}};return await nr({prevIbGib:t,newData:$,metaspace:s,space:i})}catch(l){throw console.error(`${c} ${w(l)}`),l}finally{se&&console.log(`${c} complete.`)}}async changePassword({latestKeystone:t,newMasterSecret:e,signingSecret:r,signingPoolId:n=Xt,poolIds:a,frameDetails:s,metaspace:i,space:c}){let l=`${this.lc}[${this.changePassword.name}]`;try{if(se&&console.log(`${l} starting...`),!t.data)throw new Error("latestKeystone.data falsy");if(t.data.revocationInfo)throw new Error("Keystone has been revoked. Cannot change password. (E: 8599f8f51c78d722252ddb2894fdbe25)");let d=t.data.challengePools,f=d.find(I=>I.id===n);if(!f)throw new Error(`Signing pool not found: ${n} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let p=[];if(a&&a.length>0)for(let I of a){let G=d.find(v=>v.id===I);if(!G)throw new Error(`Target pool to rotate not found: ${I} (E: 4599f8f51c78d722252ddb2894fdbe25)`);p.push(G)}else if(p=d.filter(I=>!I.isForeign),p.length===0)throw new Error("No non-foreign pools found to rotate. (E: 5599f8f51c78d722252ddb2894fdbe25)");let h=[];for(let I of p){let G=await Qc({prevPool:I,newMasterSecret:e});h.push(G)}let g=y({ibGib:t}),m={verb:Qe,target:g,details:{type:Xr.change_password,info:{change:h.map(I=>I.id)}}},E=await Ar({pool:f,targetAddr:g}),{proof:S,nextPools:A}=await Tr({targetPoolId:n,prevPools:d,masterSecret:r,challengeIds:E,claim:m});for(let I of h){let G=A.findIndex(v=>v.id===I.id);if(G===-1)throw new Error(`Rotated pool ${I.id} not found in next pools list. (E: 6599f8f51c78d722252ddb2894fdbe25)`);A[G]=I}let _=(t.data.n??0)+1,$;if(_%Sr===0){let I={...t,data:{...t.data,challengePools:A}};$=await this.getAggregateDetails({latestKeystone:I,metaspace:i,space:c})}let T={challengePools:A,proofs:[S],frameDetails:s,checkpointDetails:$,...t.data.delegates?{delegates:t.data.delegates}:{}};return await nr({prevIbGib:t,newData:T,metaspace:i,space:c})}catch(d){throw console.error(`${l} ${w(d)}`),d}}async verifySigningSecret({keystoneIbGib:t,signingSecret:e,poolId:r}){let n=`${this.lc}[${this.verifySigningSecret.name}]`;try{if(!t.data)return!1;let a=t.data.challengePools.find(s=>s.id===r);return a?await os({pool:a,signingSecret:e}):!1}catch(a){return console.warn(`${n} Exception during verification: ${w(a)}`),!1}}};var gn="sync",Re="syncmsg",ns="@payloadAddrsDomain",sb="init",ib="ack",cb="delta",lb="commit",de={init:sb,ack:ib,delta:cb,commit:lb},f8=Object.values(de),db="abort",fb="optimistic-graft-longest-common-subsequence",st={abort:db,optimisticWithLCS:fb},Gr=Object.values(st);function mn(o){return Gr.includes(o)}b(mn,"isValidSyncConflictStrategy");var bb="push",pb="pull",hb="sync",as={push:bb,pull:pb,sync:hb},g8=Object.values(as);var ub="sender",gb="receiver",En={sender:ub,receiver:gb},m8=Object.values(En);var el=!1;function ss({base:o,extended:t,throwIfExtendedDoesntContainBase:e}){let r=`[${ss.name}]`;try{el&&console.log(`${r} starting... (I: 00d70d79a0249165c2a230389c962526)`);let n=!0;for(let s=0;s<o.length;s++)if(o[s]!==t[s]){n=!1;break}if(e&&!n)throw new Error(`base addrs do not correspond to extended addrs. We were expecting the base to be the exact start of the extended strand, e.g., base [a, b, c] with extended [a, b, c, d, e]. base: ${o}. extended: ${t}. (E: fb80b40003289bbf1aaedd4829fa1826)`);let a;if(n)a=t.slice(o.length);else{a=[];for(let s of t)o.includes(s)||a.push(s)}return a}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{el&&console.log(`${r} complete.`)}}b(ss,"getUniqueDnas");async function wn({src:o,createdIbGibs_Running:t,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:e,allLocalIbGibs:r}){let n=`[${wn.name}]`;try{if(e.length>0){let a=e.splice(0,1)[0],s=r.filter(d=>y({ibGib:d})===a),i;if(s.length>0)i=s[0];else throw new Error(`dna ibGib not found in supplied allLocalIbGibs. dnaAddr: ${a}. (E: 7f56826852cf48a79ab8af16bf27e284)`);let c=U(i.data);c.src=o,c.srcAddr=y({ibGib:o});let l;switch(c.type){case"mut8":l=await ot(c);break;case"rel8":l=await He(c);break;case"fork":throw new Error("fork transform not expected. atow only a single fork is expected at the beginning of the lifetime of a tjp ibgib. This fork defines the uniqueness of the tjp ibgib. When merging another tjp ibgib, we would only expect update transforms to be mut8 or rel8. (E: f8ad6996ac5545edad2d58a293d37d94)");default:throw new Error(`unknown dna argTransform.type (${c.type}) for dna address: ${a}. Expecting either mut8 or rel8. (fork transform is known but not expected either.) (E: 52a98db56e934e4cb42c64e2f45fa552)`)}if((l.intermediateIbGibs??[]).forEach(d=>t.push(d)),(l.dnas??[]).forEach(d=>t.push(d)),t.push(l.newIbGib),(l.dnas??[]).length>0){if(!l.dnas.some(d=>y(d)===a))throw new Error(`${n}(UNEXPECTED) Expected to generate exact dna that we applied in transform. dnaAddr: ${a} (E: 4a364c0b5d8d46c8af6bd540915fd973)`)}else console.warn(`${n}(UNEXPECTED) expected resTransform to include generated dna. dnaAddr: ${a}(W: 9648e2d5c40d42b7b9fb7efb09c5b13a)`);return await wn({src:l.newIbGib,createdIbGibs_Running:t,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:e,allLocalIbGibs:r})}else return t.length===0&&console.warn(`${n} no dna transforms to apply but createdIbGibs_Running is empty. Dna is expected to start with at least one transform, otherwise don't call this function. (W: 52c7f2f6bd7e4bd0b31f53611b90268b)(UNEXPECTED)`),o}catch(a){throw console.error(`${n} ${w(a)}`),a}}b(wn,"applyTransforms");var Wr="graftinfo",yt=Wr,tl="latestcommonaddr",ar="base",Lt="orphan",rl="dnaapplied",mb="longest-common-subsequence",is={lcs:mb},G8=Object.values(is);var et=!0;async function Eb({data:o}){if(!o.conflictStrategy)throw new Error("(UNEXPECTED) data.conflictStrategy required for GraftInfoIb (E: 2c0968a0dac8d0ab3d67da9756d6df26)");if(!mn(o.conflictStrategy))throw new Error(`invalid data.conflictStrategy (${o.conflictStrategy}). valid conflict strategies: ${Gr} (E: 41e2680089786d4d28046b4c0884bd26)`);return[Wr,o.conflictStrategy].join(" ")}b(Eb,"getGraftInfoIb");async function ol({conflictStrategy:o,details:t,addlGraftDetails:e,latestCommonFrameAddr:r,baseAddrsSinceLCA:n,orphanAddrsSinceLCA:a,dnaAddrsApplied:s}){let i=`[${ol.name}]`;try{if(et&&console.log(`${i} starting... (I: 0030f62cbae28cf5882f87981edc3826)`),n.length===0)throw new Error("(UNEXPECTED) baseAddrsSinceLCA empty? (E: 005f8449a9236d445902a148f59fc826)");if(a.length===0)throw new Error("(UNEXPECTED) orphanAddrsSinceLCA empty? (E: 19e4082e82c67759c880392aca186826)");let c={conflictStrategy:o,description:t};e&&(c.addlGraftDetails=e);let l={[tl]:[r],[ar]:n.concat(),[Lt]:a.concat(),[rl]:s.concat()},d=await Eb({data:c});return await B.stone({parentPrimitiveIb:Wr,ib:d,data:c,rel8ns:l,uuid:!0})}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{et&&console.log(`${i} complete.`)}}b(ol,"createGraftInfo");async function wb({textA:o,textB:t}){if(o===t)return o;if(o==="")return t;if(t==="")return o;function e(l,d){let f=l.length,p=d.length,h=Array(f+1).fill(0).map(()=>Array(p+1).fill(0));for(let S=1;S<=f;S++)for(let A=1;A<=p;A++)l[S-1]===d[A-1]?h[S][A]=h[S-1][A-1]+1:h[S][A]=Math.max(h[S-1][A],h[S][A-1]);let g=f,m=p,E=[];for(;g>0&&m>0;)l[g-1]===d[m-1]?(E.unshift({line:l[g-1],indexA:g-1,indexB:m-1}),g--,m--):h[g-1][m]>h[g][m-1]?g--:m--;return E}b(e,"longestCommonSubsequence");let r=o.split(`
21
+ `),n=t.split(`
22
+ `),a=e(r,n),s=[],i=0,c=0;for(let l of a){for(;i<l.indexA;)s.push(r[i]),i++;for(;c<l.indexB;)s.push(n[c]),c++;s.push(l.line),i++,c++}for(;i<r.length;)s.push(r[i]),i++;for(;c<n.length;)s.push(n[c]),c++;return s.join(`
23
+ `)}b(wb,"mergeTextByLongestCommonSubsequence");async function cs({timelineAddrsA:o,timelineAddrsB:t,latestCommonFrameAddr:e,conflictStrategy:r,ibGibReadCache:n,space:a}){let s=`[${cs.name}]`;try{let A=function(ve){let Bt=`${s}[${A.name}]`;for(let ze of ve){if(!ze.rel8ns)throw new Error(`(UNEXPECTED) ${Bt} someIbGib.rel8ns falsy? All ibgibs with mergeable timelines are expected to have rel8ns. addr: ${y({ibGib:ze})} (E: 5534a478cd183a5ee27b28487448b226)`);if(!ze.rel8ns.dna)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna falsy? We only have implemented grafting for dna. addr: ${y({ibGib:ze})} (there should be another route for merging for non-dna timelines) (E: d86b388c627afd613f897e3819d8ab26)`);if(ze.rel8ns.dna.length===0)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna.length === 0? We only have implemented grafting for dna. addr: ${y({ibGib:ze})} (there should be another route for merging for non-dna timelines) (E: bf973662a0689dd9089912b861af2826)`)}};var i=A;b(A,"throwIfUnexpected"),et&&console.log(`${s} starting... (I: 3b4c3e8e59c883d9d3c352efd6380826)`);let c=[],l=[];if(o.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(t.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");if(e){if(!o.includes(e))throw new Error(`timelineAddrsA does not include latestCommonFrameAddr (${e}). timelineAddrsA: ${o} (E: c5a9afe371888da2a79963983426e826)`);if(!t.includes(e))throw new Error(`timelineAddrsB does not include latestCommonFrameAddr (${e}). timelineAddrsB: ${t} (E: 7e641f67c452b67d582d78484a88c826)`)}else if(e=o.findLast(ve=>t.includes(ve)),!e)throw new Error(`timelines do not share a common frame. A: ${o}. B: ${t} (E: 4c0e78a88a375d8588736668573f1e26)`);if(o.at(-1)===e){debugger;throw new Error("timelineAddrsA.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 3796fc4074a8c5899d549bb8c2e68826)")}if(t.at(-1)===e)throw new Error("timelineAddrsB.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 66fbb86e9e98531549888bf10a344f26)");let d=o.lastIndexOf(e),f=o.slice(d+1),p=await at({readCache_graph:n,addrs:f,space:a}),h=p.at(-1),g=t.lastIndexOf(e),m=t.slice(g+1),E=await at({readCache_graph:n,addrs:m,space:a}),S=E.at(-1);A(p),A(E);let _,$,T,I,G=tr({ibGib:h}),v=G.valid?Number.parseInt(G.ticks):Number.MAX_SAFE_INTEGER,N=G.valid?G.ms??0:0,O=tr({ibGib:S}),P=O.valid?Number.parseInt(O.ticks):Number.MAX_SAFE_INTEGER,R=O.valid?O.ms??0:0;v<P?(_=h,$=p,T=S,I=E):v>P?(_=S,$=E,T=h,I=p):N<=R?(_=h,$=p,T=S,I=E):(_=S,$=E,T=h,I=p);let k=y({ibGib:_}),H=$.map(ve=>y({ibGib:ve})),K=y({ibGib:T}),ye=I.map(ve=>y({ibGib:ve}));et&&console.log(`${s} baseTipAddr: ${k} (I: 93353d9b9b68b17088f57958df85e826)`),et&&console.log(`${s} orphanTipAddr: ${K} (I: 14df8867adc5dab97ff3c1e989b40e26)`);let[ie]=await at({addrs:[e],space:a});if(!ie)throw new Error("(UNEXPECTED) latestCommonFrameIbGib falsy? (E: ead2020b7ab8e4c4f824573133e33826)");if(!ie.rel8ns)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns falsy? (E: b3f338032d19816fc87d3c78af255726)");if(!ie.rel8ns.dna||ie.rel8ns.dna.length===0)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns.dna falsy/empty? It should at least have the first fork transform. (E: 98fd8c725f484d85c8d23ceb181ce826)");let Ke=ie.rel8ns.dna.concat(),Ye=[];for(let ve of I){if(!ve.rel8ns)throw new Error("(UNEXPECTED) orphanFrame.rel8ns falsy? (E: ed910e3b930b1b5388d87c6f736a4826)");let Bt=ss({base:Ke,extended:ve.rel8ns.dna??[],throwIfExtendedDoesntContainBase:!0});if(Bt.forEach(ze=>Ke.push(ze)),Bt.length===0)throw new Error("(UNEXPECTED) orphanDnaAddrsToApply empty? (E: d44ed439e538e5b538d12d71063f0826)");Bt.forEach(ze=>Ye.push(ze))}let We=await at({addrs:Ye,readCache_graph:n,space:a}),ct=[],fe=await wn({src:_,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:Ye.concat(),allLocalIbGibs:We,createdIbGibs_Running:ct});if(!fe.data)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data falsy? (E: 4792f8e84fc84966e89220fae0657826)");if(!fe.data.n)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data.n falsy? (E: a2b3ca4cdec8d01f282dd3e4ff9eab26)");if(ct.length===0)throw new Error("(UNEXPECTED) applyTransforms called but createdIbGibs_Running is empty? This should contain all of the (E: 5b6c788488f5095b08eb8e31d55b1726)");console.warn(`${s} START...................... Do we get a bunch of "already had addr(s)" messages for dna ibgibs? I'm thinking we will already have the dna ibgibs stored in the space (temp space?) before we do this graft. Maybe it creates new dna, I don't know. remove this later when we decide something to do about it. space.ib: ${a.ib} (W: bb60481ecabaa6f49e14203891824a26)`),await Xe({space:a,ibGibs:ct}),console.warn(`${s} END........................ Do we get a bunch of "already had addr(s)" messages for dna ibgibs? I'm thinking we will already have the dna ibgibs stored in the space (temp space?) before we do this graft. Maybe it creates new dna, I don't know. remove this later when we decide something to do about it. space.ib: ${a.ib} (W: bb60481ecabaa6f49e14203891824a26)`);let{mapWithTjp_NoDna:ht,mapWithTjp_YesDna:It,mapWithoutTjps:be}=Nt({ibGibs:ct});if(Object.keys(ht).length>0)throw new Error("(UNEXPECTED) mapWithTjp_NoDna is populated? We've just applied the dna from the orphan branch which created ibgibs (and dnas). But we are expected to be executing on an ibgib timeline that has dna. The applyTransforms was not expected to create any other ibgibs than the one in our timeline (with dna) and any corresponding dnas. (E: 236e989fb5e8a4a498a21b98f718c826)");let ut=Object.values(It),_t=ft({ibGibs:ut});if(Object.keys(_t).length===0)throw new Error("(UNEXPECTED) newGraftedIbGibsByTjp has 0 timelines? we expect this to have a single timeline: the one we're grafting. (E: 2b7127bd0c6bfeaec8d66038ba208226)");if(Object.keys(_t).length>1)throw new Error("(UNEXPECTED) newGraftedIbGibsByTjp has more than one timeline? we expect this to have a single timeline: the one we're grafting. (E: 076758885b8ea7c89849a76334222326)");Object.values(_t)[0].forEach(ve=>c.push(ve));for(let ve of c)await Te({ibGib:ve,space:a});let gr;if(r===st.optimisticWithLCS){if(!_.data)throw new Error("(UNEXPECTED) baseTip.data falsy? (E: 92623857e19b9b4e081e8c8d9eb45526)");if(!T.data)throw new Error("(UNEXPECTED) orphanTip.data falsy? (E: 2e6828a4c9226ac917ab6fe833672826)");if((T.data.text||_.data.text)&&T.data.text!==_.data.text){et&&console.log(`${s} different data.text found. executing text merge for conflictStrategy ${r} (I: cfb5f9580832040388fc576eb71ac526)`);let ve=T.data.text??"",Bt=K,ze=_.data.text??"",Oo=k,oo=await wb({textA:ve,textB:ze}),St=await ot({src:fe,dataToAddOrPatch:{text:oo},dna:!0,nCounter:!!fe.data.n});if(St.intermediateIbGibs&&St.intermediateIbGibs.length>0)throw new Error("(UNEXPECTED) resMut8Text.intermediateIbGibs truthy/non-empty? This is expected to only create the newIbGib with no intermediates. (E: 7932a8964a3869accadc9b0d93d23826)");if(!St.dnas||St.dnas.length===0)throw new Error("(UNEXPECTED) resMut8Text.dnas falsy/empty? We're expected to generate dna from this merge text mut8. (E: fdf03754bf0f8661f80f59ea0701dd26)");if(St.dnas.length!==1)throw new Error("(UNEXPECTED) resMut8Text.dnas.length !== 1? we're expecting a single mut8 dna. (E: 9574d86a9108095cb454b049bcca5326)");if(l.push(St.dnas[0]),c.push(St.newIbGib),await ge({resTransform:St,space:a}),await Te({ibGib:St.newIbGib,space:a}),gr={mergeTextStrategy:is.lcs,textAAddr:Bt,textBAddr:Oo},fe=St.newIbGib,!fe.data)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data falsy after mut8 merge text? (E: 6b65d83df6681887686a0098144eea26)")}}let Wt=await ol({conflictStrategy:r,details:`Replayed ${Ye.length} transforms from orphan (${K}) onto base (${k}).`,addlGraftDetails:gr?[gr]:void 0,latestCommonFrameAddr:e,baseAddrsSinceLCA:H,orphanAddrsSinceLCA:ye,dnaAddrsApplied:Ye});et&&console.log(`${s} intrinsic graft complete. graftInfo to be appended to timeline:
24
+ ${F(Wt)} (I: ab9d1e73db9a3ff4f8241f38197bb826)`),await Xe({ibGib:Wt,space:a});let Lr=y({ibGib:Wt}),gt=await He({src:fe,rel8nsToAddByAddr:{[yt]:[Lr]},dna:!0,nCounter:!!fe.data.n});if(gt.intermediateIbGibs&&gt.intermediateIbGibs.length>0)throw new Error("(UNEXPECTED) resRel8GraftInfo.intermediateIbGibs truthy/non-empty? This is expected to only create the newIbGib with no intermediates. (E: 78b928ace4287b4dc82f413fdad60826)");if(!gt.dnas||gt.dnas.length===0)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas falsy/empty? We're expected to generate dna from this rel8. (E: 4c8fdde70368d643f86732dfa48c5526)");if(gt.dnas.length!==1)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas.length !== 1? we're expecting a single rel8 dna. (E: c2f5085c1718d7149e04f5c814027926)");l.push(gt.dnas[0]),await ge({resTransform:gt,space:a}),await Te({ibGib:gt.newIbGib,space:a});let No=gt.newIbGib;et&&console.log(`${s} finalGraftTip: ${F(No)} (I: 454e72957be8221b96931c289053fc26)`);let Do={dnasReplayed:We,dnasCreatedInGraft:l,intermediateIbGibsCreatedInGraft:c,newGraftTip:No,graftInfoCreated:Wt};return et&&console.log(`${s} result... (I: d6a02f95eb2564c621810ef855434226)`),et&&console.dir(Do),Do}catch(c){throw console.error(`${s} ${w(c)}`),c}finally{et&&console.log(`${s} complete.`)}}b(cs,"graftTimelines");function ls(o){let t=`[${ls.name}]`;try{if(et&&console.log(`${t} starting... (I: fe9adfe1a3175d87982507c8851f5826)`),!o)throw new Error("(UNEXPECTED) not a graft info, ibGib falsy? (E: bf06cdd700788e777f72fe5a5bdb0e26)");if(!o.data)throw new Error("not a graft info, ibGib.data falsy (E: 5e1b28843ec8571a7623046a06195826)");if(!o.ib.startsWith(Wr))throw new Error(`not graft info, ibgib.ib does not start with ${Wr} (E: cec6a8e25ff8746aef813e38cbebce26)`);return!0}catch(e){return et&&console.error(`${t} ${w(e)}`),!1}finally{et&&console.log(`${t} complete.`)}}b(ls,"isGraftInfo");var we=!1;async function ds({data:o}){let t=`[${ds.name}]`;try{return[gn,o.uuid].join(" ")}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(ds,"getSyncIb");async function nl(){return`tmp_sync_space_${(await V()).substring(0,8)}`}b(nl,"getTempSpaceName");async function zr({olderAddr:o,newerAddr:t,space:e}){let r=`[${zr.name}]`;try{if(we&&console.log(`${r} starting... (I: 4b3548cbc9a2eb749f447ed82fdcf826)`),o===t)return!0;let n,a=await W({space:e,addr:t});if(a.success&&a.ibGibs?.length===1)n=a.ibGibs[0];else throw new Error(`couldn't get newerAddr (${t}) from space (${e.ib}). (E: 36c758c22b181b2c89a1cd28937a6826)`);if(!n.rel8ns)return console.warn(`${r} newerIbGib.rel8ns falsy? newerAddr: ${t}. (W: 6f920811f7080281189f767813814826)`),!1;let s=n.rel8ns.past??[];if(s.length===0)return!1;if(s.includes(o))return!0;let i=s[0];return await zr({olderAddr:o,newerAddr:i,space:e})}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{we&&console.log(`${r} complete.`)}}b(zr,"isPastFrame");async function yn({sagaIbGib:o,localSpace:t}){let e=`[${yn.name}]`,r=b(async i=>{let c=await W({space:t,addrs:i});if(c.success&&c.ibGibs?.length===i.length)return c.ibGibs;{let l=c.rawResultIbGib;throw l.data?new Error(`(UNEXPECTED) couldn't find addrs? addrsNotFound: ${l.data.addrsNotFound}? space.ib: ${t.ib} (E: 43b7b5a6ad982715c8f3eed69bfa0d26)`):new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: c26c681d2f831fc537ba6f48fee36d26)")}},"fnGet"),n=await $n({sagaIbGib:o});if(n.length>0)throw new Error(`invalid sync sagaIbGib. validationErrors: ${n} (E: 19f9e8c9643858ff41312b62293d2126)`);if(!o.rel8ns)throw new Error("(UNEXPECTED) validated sagaIbGib.rel8ns falsy? (E: 73af48be8bbf271ec5cf78187ce8c826)");let a=o.rel8ns[Re],s=await r(a);return{sagaIbGib:o,msgStones:s}}b(yn,"getSyncSagaFrameDependencyGraph");async function Jr({sagaIbGib:o,space:t}){let e=`[${Jr.name}]`;try{if(we&&console.log(`${e} starting... (I: 1ea3f804dd07d1e917a2afaaad497826)`),!o.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: fe0a0d0965e87ac852fe7ba4710cc826)");if(!o.rel8ns)throw new Error("(UNEXPECTED) sagaIbGib.rel8ns falsy? (E: b79ff82a732346bdf8a9e1eb9ac96826)");let r=y({ibGib:o}),n=o.rel8ns.past&&o.rel8ns.past.length>0?[...o.rel8ns.past,r]:[r],a=[];for(let s of n){let i,c=await W({addr:s,space:t});if(c.success&&c.ibGibs&&c.ibGibs.length===1)i=c.ibGibs[0];else throw we&&console.log(`${e} failed getting full history of sagaIbGib:
25
+ ${F(o)} (I: 2a35685bfe038f63182c7db39b44c826)`),new Error(`couldn't get saga addr (${s}) from space (${t.ib}) (E: 865b78ecd918c244158813650bea7d26)`);let l=await yn({sagaIbGib:i,localSpace:t});a.push(l)}return we&&console.log(`${e} resGraphs:...
26
+ ${F(a).split(`
27
+ `).join(`
28
+ `)}
29
+ ...(I: d8e11827d88a3454d887ff05fb4ff526)`),a}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{we&&console.log(`${e} complete.`)}}b(Jr,"getFullSyncSagaHistory");async function $n({sagaIbGib:o}){let t=`[${$n.name}]`;try{we&&console.log(`${t} starting... (I: dac978e9ec5820f128fbbff817b82826)`);let e=await le({ibGib:o})??[];if(e.length>0)return e;if(o.data){let{data:r}=o;r.uuid||e.push("data.uuid required (E: aa24eeda7b88d22e5832a2e8083c0826)"),r.timestamp||e.push("data.timestamp required (E: 9c82a88548f4b63c38687428754b3826)"),r.timestampMs||r.timestampMs===0||e.push("data.timestampMs required (E: 9c82a88548f4b63c38687428754b3826)"),r.conflictStrategy?mn(r.conflictStrategy)||e.push(`data.conflictStrategy (${r.conflictStrategy}) is invalid. Must be one of "${Gr}". (E: 6223a8813b688fa2c8644fa8a491bf26)`):e.push("data.conflictStrategy required (E: 9c82a88548f4b63c38687428754b3826)"),r.expirationTimestamp,r.errors,r.successCount}else e.push("sagaIbGib.data falsy (E: 4de5e8de589d0af7245600fb4fe30926)");if(o.rel8ns){let r=o.rel8ns[Re];r&&r.length>0||e.push("sagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] required. (E: df648dc18148e718682acb4842ecf826)")}else e.push("sagaIbGib.rel8ns falsy (E: da37aa492a7275b68a5e1912c7a5e126)");return e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{we&&console.log(`${t} complete.`)}}b($n,"validateSyncSagaFrame");async function In({history:o}){let t=`[${In.name}]`;try{return we&&console.log(`${t} starting... (I: df02b802f6989096b8d8f728e2c0a526)`),console.error(`${t} NAG ERROR (NOT THROWN) need to implement more validation on full saga history. (E: 9bfcc9247a1c783fd361a4a8216fef26)`),[]}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{we&&console.log(`${t} complete.`)}}b(In,"validateFullSyncSagaHistory");async function _n({ibGibs:o,space:t}){let e=`[${_n.name}]`;try{we&&console.log(`${e} starting... (I: aa3ab828402836b3914800a8ffa1b826)`);let r=[],n=[];for(let a of o)ue({ibGib:a})||(oa({ibGib:a})?r.push(a):n.push(a));return r.length>0&&await Xe({ibGibs:r,isDna:!0,space:t}),n.length>0&&await Xe({ibGibs:n,isDna:!1,space:t}),{payload_Dnas:r,payload_NonDnas:n}}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{we&&console.log(`${e} complete.`)}}b(_n,"putInSpace_dnasThenNonDnas");function Zr({sagaFrame:o}){let t=`[${Zr.name}]`;try{if(we&&console.log(`${t} starting... (I: 93521332d0dd2f5e88398b7db95e8126)`),!o)throw new Error("(UNEXPECTED) sagaFrame falsy? (E: 01fb28be6668d88ea49bb298c739c926)");if(!o.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 998298eb17685bdb9a85b46488ccd826)");if(!o.data.n&&o.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 0394919d5b58300ceb09ba6a264ad826)");let e=o.data.n%2;if(e===0)return En.sender;if(e===1)return En.receiver;throw new Error("(UNEXPECTED) modulo is neither 0 nor 1? my logic sucks! This was way too defensive on my part... (E: 559488a2eef8d17b57079ca8886ee826)")}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{we&&console.log(`${t} complete.`)}}b(Zr,"getSyncSagaFrameOrigin");async function Sn({sagaHistory:o}){let t=`[${Sn.name}]`;try{we&&console.log(`${t} starting... (I: fe93a8f29e5d8ab2c8bd0e08e56f7826)`);let e=o.findLast(a=>a.msgStones.some(s=>s.data.stage===de.delta));if(!e)throw new Error("(UNEXPECTED) no delta frame? What are we calling this function for? (E: 9b3201207908f79868b93cd893a91626)");let r=e.msgStones.filter(a=>a.data.stage===de.delta);if(r.length>1)throw new Error("(UNEXPECTED) multiple delta stones in history slice? we're expecting a single delta stone per saga frame. (E: a4bd5860b4aa0743753d4798d3163826)");return r[0].data.conflicts}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{we&&console.log(`${t} complete.`)}}b(Sn,"getFinalConflictsInfo");async function fs({sagaHistory:o,myTempSpace:t}){let e=`[${fs.name}]`;try{we&&console.log(`${e} starting... (I: b755627e99c9a221566d86a81b0da526)`);let r=await Sn({sagaHistory:o});if(!r||r.length===0)return we&&console.log(`${e} no conflicts found. returning empty array (I: 5dce98010128a284c8ec92cd466a3826)`),[];let n=[];for(let a of r){if(!a.resolved)throw new Error("(UNEXPECTED) conflict.resolved falsy? we're expecting all conflicts to be resolved when getting orphaned addresses. (E: 3861e89a18c8ff405eb2117f6d4b9b26)");if(!a.graftInfoAddr)throw new Error("(UNEXPECTED) conflict.graftInfoAddr falsy? we're expecting a resolved conflict whose final ibgib (graft tip) was the graft info and for this addr to be in conflict.graftInfoAddr. (E: 80d86e333028585908f4757bc4d6f826)");let s=await at({addrs:[a.graftInfoAddr],space:t});if(s.length!==1)throw new Error(`(UNEXPECTED) couldn't get conflict.graftInfoAddr (${a.graftInfoAddr}) from myTempSpace (${t.ib})? (E: cf1fe87096f8ea22f84f250d7ab30226)`);let i=s[0];if(!ls(i))throw new Error(`(UNEXPECTED) graft info from conflict.graftInfoAddr (${a.graftInfoAddr}) does not pass the isGraftInfo guard? We're expecting this addr to point to a valid GraftInfoIbGib_V1 (E: 6aa9ecb9a428d92be8d1bdbe0696f826)`);let c=i.rel8ns[Lt];if(!c||c.length===0)throw new Error(`(UNEXPECTED) orphanedAddrs empty for conflict graftInfo (${a.graftInfoAddr})? we're expecting a graft to always necessarily orphan one or other branches, otherwise what are we "grafting"? (E: 3ed1284f6ca84754582801484d751926)`);c.forEach(l=>n.push(l))}return n}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{we&&console.log(`${e} complete.`)}}b(fs,"getAllOrphanedAddresses");async function vr({senderSecret:o,sagaId:t}){let e=`[${vr.name}]`;try{if(we&&console.log(`${e} starting... (I: 0de03f8dcd3e32f1fca244e8f2a8a826)`),!o)throw new Error("(UNEXPECTED) senderSecret falsy? (E: 8ce053fe59825a6678713128953b9d26)");if(!t)throw new Error("(UNEXPECTED) sagaId falsy? (E: 3a17e0c1b2f849de8a42cd15b8ee6826)");return await es({masterSecret:o,kdfOpts:{strategy:$o.recursive_salt_wrap,salt:t,rounds:1e4,algorithm:"SHA-256"}})}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{we&&console.log(`${e} complete.`)}}b(vr,"deriveSessionSecret");var al=!1,sr=class o{static{b(this,"LightWitnessBase_V1")}lc=`[${o.name}]`;instanceId="";ib="";gib;data;rel8ns;initialized;_isInitialized=!1;constructor(t,e){t&&(this.data=t),e&&(this.rel8ns=e),this.initialized=this.initialize().then(()=>{this._isInitialized=!0})}async initialize(){this.instanceId=await V(),this.gib=await ce({ibGib:this.toIbGibDto()})}toIbGibDto(){return qe({ibGib:this})}loadIbGibDto(t){let e=`${this.lc}[${this.loadIbGibDto.name}]`;try{return al&&console.log(`${e} starting...`),t.ib||console.warn(`${e} dto.ib is falsy.`),t.gib||console.warn(`${e} dto.gib is falsy.`),this.ib=U(t.ib),this.gib=U(t.gib),t.data?this.data=U(t.data):delete this.data,t.rel8ns?this.rel8ns=U(t.rel8ns):delete this.rel8ns,Promise.resolve()}catch(r){throw console.error(`${e} ${r.message}`),r}finally{al&&console.log(`${e} complete.`)}}async validateThis(){let t=`${this.lc}[${this.validateThis.name}]`,e=[];try{this.ib||e.push("this.ib is falsy."),this.gib||e.push("this.gib is falsy.")}catch(r){throw console.error(`${t} ${r.message}`),r}return e}};var An="subject",bs=/^[a-zA-Z0-9_\-.]{1,255}$/,sl="subject",il="",Tn="subject is a cool ibgib witness that has seriously fascinating behavior.";var cl="observable";var ir={subscribe:"subscribe"},ll=Object.values(ir);var dl={next:"next",error:"error",complete:"complete"};var cr={...ir,...dl};var Go={version:"1",uuid:il,name:sl,description:Tn,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ps=void 0;var lr=!1;function fl(o){let t=`[${fl.name}]`;try{let e=o?`${ho} ${o}`:ho;return lr&&console.log(`${t} ${e}`),e}catch(e){throw console.error(`${t} ${e.message}`),e}}b(fl,"getArgIb");function yb({ib:o,ibGib:t}){let e=`[${yb.name}]`;try{if(lr&&console.log(`${e} starting...`),!o)if(t)o=t.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return o.startsWith(ho)}catch(r){throw console.error(`${e} ${r.message}`),r}finally{lr&&console.log(`${e} complete.`)}}b(yb,"isArg");function bl(o){let t=`[${bl.name}]`;try{let e=o?`${Zo} ${o}`:Zo;return lr&&console.log(`${t} ${e}`),e}catch(e){throw console.error(`${t} ${e.message}`),e}}b(bl,"getResultIb");async function Cr({argData:o,ibMetadata:t,noTimestamp:e}){let r=`[${Cr.name}]`;try{let n=await B.firstGen({ib:fl(t),parentIbGib:B.primitive({ib:ho}),data:o,dna:!1,noTimestamp:e});if(n.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Jt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${r} ${n.message}`),n}}b(Cr,"argy_");async function xr({resultData:o,ibMetadata:t,noTimestamp:e}){let r=`[${xr.name}]`;try{let n=await B.firstGen({ib:bl(t),parentIbGib:B.primitive({ib:Zo}),data:o,dna:!1,noTimestamp:e});if(n?.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Jt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${r} ${n.message}`),n}}b(xr,"resulty_");function hs({ibGib:o}){let t=`[${hs.name}]`;try{if(lr&&console.log(`${t} starting...`),!o)throw new Error("ibGib required (E: e11cee2a6c59a5e7a4d39ea55751c423)");if(!o.data)return!1;let e=o.data;return e.cmd&&typeof e.cmd=="string"}catch(e){throw console.error(`${t} ${e.message}`),e}finally{lr&&console.log(`${t} complete.`)}}b(hs,"isCommand");function us({ibGib:o}){let t=`[${us.name}]`;try{return lr&&console.log(`${t} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof o.witness=="function"}catch(e){throw console.error(`${t} ${e.message}`),e}finally{lr&&console.log(`${t} complete.`)}}b(us,"isWitness");var pl=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var dr=!1;function ul({rawMsg:o}){let t=`[${ul.name}]`;try{dr&&console.log(`${t} starting...`);let e=gs({rawMsg:o}),r=e.body.replace(/\s/g,"_").replace(/\W/g,""),n;if(r.length>20)n=r.substring(0,20);else if(r.length>0)n=r;else throw new Error("(UNEXPECTED) error msg should have characters/alphanumerics... (E: a3b9cd11a44cc7892a748819c2885422)");return`error ${n} ${e.uuid??"undefined"}`}catch(e){throw console.error(`${t} ${e.message}`),e}finally{dr&&console.log(`${t} complete.`)}}b(ul,"getErrorIb");function gs({rawMsg:o}){let t=`[${gs.name}]`;try{if(dr&&console.log(`${t} starting...`),!o)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let e,r=o.match(Xs);if(r){let[n,a,s,i,c,l]=r;if(!i)throw new Error("invalid error msg body (E: a675e6855cca96519d33d44ea5400922)");e={success:!1,raw:o,body:i?.trim(),uuid:c.slice(4,36)},a&&(e.location=a),(s||l)&&(e.unexpected=!0)}else{e={success:!1,raw:o,body:o};let n=o.match(qs);if(n){let[a,s]=n;e.location=s}o.toLowerCase().includes("(unexpected)")&&(e.unexpected=!0)}return e}catch(e){throw console.error(`${t} ${e.message}`),e}finally{dr&&console.log(`${t} complete.`)}}b(gs,"parseRawErrorMsg");function Nr({rawMsg:o}){let t=`[${Nr.name}]`;try{return dr&&console.log(`${t} starting...`),mt({parentPrimitiveIb:"error",ib:ul({rawMsg:o}),data:gs({rawMsg:o}),ibRegExpPattern:pl.source})}catch(e){throw console.error(`${t} ${e.message}`),e}finally{dr&&console.log(`${t} complete.`)}}b(Nr,"getErrorIbGib");function qt({ibGib:o}){let t=`[${qt.name}]`;try{if(dr&&console.log(`${t} starting...`),!o)throw new Error("ibGib required (E: 1d756fbbd96f1734b97ba013537ed522)");return o.ib.startsWith("error ")}catch(e){throw console.error(`${t} ${e.message}`),e}finally{dr&&console.log(`${t} complete.`)}}b(qt,"isError");var Gn=class o{static{b(this,"WitnessFactoryBase")}lc=`[${o.name}]`};var ms=!1,Qr=class o extends Gn{static{b(this,"DynamicFormFactoryBase")}lc=`[${o.name}]`;patchDataFromItems({data:t,contextPath:e,items:r,pathDelimiter:n}){let a=`${this.lc}[${this.patchDataFromItems.name}]`;try{if(ms&&console.log(`${a} starting...`),!n)throw new Error("pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)");for(let s=0;s<r.length;s++){let i=r[s],c=e?e+n+i.name:i.name;if(!i.items)ra({obj:t,value:i.value,path:c,logalot:ms,pathDelimiter:n});else if(i.items.length>0)this.patchDataFromItems({data:t,contextPath:c,items:i.items,pathDelimiter:n});else throw new Error("invalid item. items is truthy but with a length of 0. items should either be falsy or have at least one child. (E: ee2765e0b920477f919fcb09e9d951b4)")}}catch(s){throw console.error(`${a} ${s.message}`),s}finally{ms&&console.log(`${a} complete.`)}}};var gl="subscription",Es=/^[a-zA-Z0-9_\-.]{1,255}$/,ml="",El="subscription",vn="subscription is a cool ibgib witness that has seriously fascinating behavior.";var vo={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var ws={version:"1",uuid:ml,name:El,description:vn,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},ys=void 0;var wl=!1;function $s({ibGib:o}){let t=`[${$s.name}]`;try{wl&&console.log(`${t} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:e}=o;return[cl,An].some(n=>e.includes(n))}catch(e){throw console.error(`${t} ${e.message}`),e}finally{wl&&console.log(`${t} complete.`)}}b($s,"isObservable");var Q=!1,Cn=class o extends sr{static{b(this,"Subscription_V1")}lc=`[${o.name}]`;metaspace;_subscribed;_unsubscribed;_srcObservable;constructor(t,e){super(t,e)}async initialize(){let t=`${this.lc}[${this.initialize.name}]`;try{if(Q&&console.log(`${t} starting... (I: 8097612cda5f43e5b38249d057b65b1e)`),await super.initialize(),!this.data)throw new Error("this.data required (E: 1af73af2d17a48ada42596ad395fd99c)");this.data.uuid=this.instanceId,this.ib=Nn({data:this.data,classname:"Subscription_V1"}),this.gib=await ce({ibGib:this})}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Q&&console.log(`${t} complete.`)}}async witness(t){let e=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:r}=t;if(!r)throw new Error("arg.ib required (E: 1fd9aebef07b4bdaacc0cd323c8ddf76)");if(Q&&console.log(`${e} ib: ${r} (I: 4de7771f477dc5b36933343b694ce223)`),r===vo.unsubscribe)return Q&&console.log(`${e} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(r===vo.unsubscribed)return Q&&console.log(`${e} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if($s({ibGib:t}))return Q&&console.log(`${e} routing observerable (I: 165b422cda9ec3052312243dc965cf23)`),this.witness_observable({ibGib:t});throw new Error("unknown arg. expect unsubscribe/unsubscribed primitive ibgib or Observable ibgib. (E: 132dc7cd8f7c4afc9ec4651e2c559c74)")}catch(r){throw console.error(`${e} ${w(r)??"unknown error (E: b0bbaab21833404a9420c3d273df7f21)"}`),r}}async witness_unsubscribe(){let t=`${this.lc}[${this.witness_unsubscribe.name}]`;try{if(Q&&console.log(`${t} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${t} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),j;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),j;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return Q&&(console.log(`${t} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),Q&&(console.log(`${t} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,Q&&console.log(`${t} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),j}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Q&&console.log(`${t} complete.`)}}async witness_observable({ibGib:t}){let e=`${this.lc}[${this.witness_observable.name}]`;try{if(Q&&console.log(`${e} starting... (I: faf248f372fc44a7bb0e70492e8284f9)`),this._subscribed!==void 0)throw new Error(`(UNEXPECTED) this._subscribed (${this._subscribed} is not undefined? (E: 09a0e926357676c2c93a173ccbe93923)`);if(this._srcObservable)throw new Error("(UNEXPECTED) this subscription isn't subscribed but this._observable is truthy? (E: acdf5198fb2ff3c8b2db95450bd55b23)");return this._srcObservable=t,Q&&console.log(`${e} this._srcObservable set to ibgib with ib: ${t.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,j}catch(r){throw console.error(`${e} ${r.message}`),r}finally{Q&&console.log(`${e} complete.`)}}async witness_unsubscribed(){let t=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(Q&&console.log(`${t} starting... (I: 1beac551253e4c5694b63e0d36d5d5c0)`),this._subscribed==null)throw new Error("subscription never subscribed in the first place (this._subscribed === undefined) (E: b2c1b21a0e876a4908339a976924b923)");if(this._subscribed&&this._unsubscribed)throw new Error("(UNEXPECTED) both this._subscribed and this._unsubscribed true (E: a967e49de657a43929a74703c656ad23)");let e=this._unsubscribed===!0?ua:wi;return Q&&console.log(`${t} result: ${F(e)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),e}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Q&&console.log(`${t} complete.`)}}async unsubscribe(){let t=`${this.lc}[${this.unsubscribe.name}]`;try{Q&&console.log(`${t} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let e=await this.witness(B.primitive({ib:vo.unsubscribe}));if(!e)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(qt({ibGib:e})){let r=e;throw new Error(`${r.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Q&&console.log(`${t} complete.`)}}async unsubscribed(){let t=`${this.lc}[${this.unsubscribed.name}]`;try{Q&&console.log(`${t} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let e=await this.witness(B.primitive({ib:vo.unsubscribed}));if(!e)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let r=e.ib===ua.ib;return Q&&console.log(`${t} resUnsubscribed: ${r} (I: b4800166c58d5ba2ca1dccaa53de2323)`),r}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Q&&console.log(`${t} complete.`)}}async validateThis(){let t=`${this.lc}[${this.validateThis.name}]`;try{return Q&&console.log(`${t} starting...`),this.data,[]}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Q&&console.log(`${t} complete.`)}}async argy({argData:t,ibMetadata:e,noTimestamp:r,ibGibs:n}){let a=await Cr({argData:t,ibMetadata:e,noTimestamp:r});return n&&(a.ibGibs=n),a}async resulty({resultData:t,ibGibs:e}){let r=await xr({resultData:t});return e&&(r.ibGibs=e),r}},xn=class o extends Qr{static{b(this,"Subscription_V1_Factory")}lc=`[${o.name}]`;getName(){return Cn.name}async newUp({data:t,rel8ns:e}){let r=`${this.lc}[${this.newUp.name}]`;try{Q&&console.log(`${r} starting...`),t??=U(ws),t=t,e=e??ys?U(ys):void 0,t.uuid||=await V();let{classname:n}=t,a=Nn({data:t}),s=await mt({parentPrimitiveIb:`witness ${n}`,ib:a,data:t,rel8ns:e}),i=new Cn(void 0,void 0);return await i.loadIbGibDto(s),Q&&console.log(`${r} witnessDto: ${F(s)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:i}}catch(n){throw console.error(`${r} ${w({error:n})}`),n}finally{Q&&console.log(`${r} complete.`)}}async witnessToForm({witness:t}){let e=`${this.lc}[${this.witnessToForm.name}]`;try{Q&&console.log(`${e} starting...`);let{data:r}=t;if(!r)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");Q&&console.log(`${e} data: ${F(r)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await no({n:100}),a=new Dn().with({idPool:n}).name({of:r.name,required:!1}).description({of:r.description??vn}).and().and().uuid({of:r.uuid,required:!0}).classname({of:r.classname}).and().commonWitnessFields({data:r}).outputForm({formName:"form",label:"subscription"});return Promise.resolve(a)}catch(r){throw console.error(`${e} ${w({error:r})}`),r}finally{Q&&console.log(`${e} complete.`)}}async formToWitness({form:t}){let e=U(ws);return this.patchDataFromItems({data:e,items:t.items,pathDelimiter:Pr}),await this.newUp({data:e})}};var On=!1;function yl({data:o}){let t=`[${yl.name}]`;try{if(On&&console.log(`${t} starting...`),!o)throw new Error("Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)");let e=[],{name:r,uuid:n,classname:a}=o;return r?r.match(Es)||e.push(`name must match regexp: ${Es} (E: 21bf77e398d47e9d035376510505eda2)`):e.push("name required."),n?n.match(Ie)||e.push(`uuid must match regexp: ${Ie} (E: e53fd08ae69e945b37ed895b864b6bd7)`):e.push("uuid required."),a&&(a.match(zt)||e.push(`classname must match regexp: ${zt}`)),e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{On&&console.log(`${t} complete.`)}}b(yl,"validateCommonSubscriptionData");function Nn({data:o,classname:t}){let e=`[${Nn.name}]`;try{let r=yl({data:o});if(r.length>0)throw new Error(`invalid Subscription data: ${r} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`);if(t){if(o.classname&&o.classname!==t)throw new Error("classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)")}else if(t=o.classname,!t)throw new Error("classname required (E: 040c1fd71853fa7874146999afb355c3)");let{uuid:n}=o;return`witness ${gl} ${t} ${n}`}catch(r){throw console.error(`${e} ${w(r)}`),r}}b(Nn,"getSubscriptionIb");var Dn=class o extends er{static{b(this,"SubscriptionFormBuilder")}lc=`[${o.name}]`;constructor(){super(),this.what="subscription"}};function Ln({ibGib:o}){let t=`[${Ln.name}]`;try{if(On&&console.log(`${t} starting... (I: 43df7e7f61f25e65662ce8aa5a105a23)`),!o)return!1;let e=o;return typeof e.witness=="function"&&typeof e.unsubscribe=="function"&&typeof e.unsubscribed=="function"}catch(e){throw console.error(`${t} ${e.message}`),e}finally{On&&console.log(`${t} complete.`)}}b(Ln,"isSubscription");async function $l(){return(await new xn().newUp({})).newIbGib}b($l,"newupSubscription");var Is="observable_event";var Il=!1;async function _s({eventType:o,srcObservable:t,payload:e}){let r=`[${_s.name}]`;try{if(Il&&console.log(`${r} starting... (I: e2290f2f46d1993d6893a24c19100823)`),!t)throw new Error("srcObservable required (E: 3470a97bbf3802cbc8dd64339f5ef623)");if(!t.data)throw new Error("srcObservable.data required (E: df1786585ba849c08e7f4f1fddd30a31)");if(!t.data.uuid)throw new Error("srcObservable.data.uuid required (E: 173a1a53f274bc1cef879bad2288ca23)");if(!t.data.uuid.match(Ie))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${Ie.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await V(),eventType:o,srcObservableId:t.data.uuid,"@srcObservableAddr":y({ibGib:t}),"@payloadAddr":y({ibGib:e})};return await mt({parentPrimitiveIb:Is,ib:_l({data:n}),data:n})}catch(n){throw console.error(`${r} ${n.message}`),n}finally{Il&&console.log(`${r} complete.`)}}b(_s,"getObservableEventIbGib");function _l({data:o,classname:t}){let e=`[${_l.name}]`;try{if(t){if(o.classname&&o.classname!==t)throw new Error("classname does not match data.classname (E: 523aabc53fb944789202a5f468abd338)")}else if(t=o.classname,!t)throw new Error("classname required (E: d4401ea682894c5fa824b38d4989aa76)");if(!o.uuid)throw new Error("data.uuid required (E: 204cc7c20efd8a55263cdea8b1223e23)");return`${Is} ${t} ${o.uuid}`}catch(r){throw console.error(`${e} ${w(r)}`),r}}b(_l,"getObservableEventIb");var he=!1,Pn=class o extends sr{static{b(this,"ObservableBase_V1")}lc=`[${o.name}]`;metaspace;_subscribers={};_isComplete=!1;_pastPayloads=[];_pastError;get isCompleteOrErrored(){return this._isComplete||!!this._pastError}get isComplete(){return this._isComplete}get isErrored(){return!!this._pastError}constructor(t,e){super(t,e)}async witness(t){let e=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:r}=t;if(!r)throw new Error("arg.ib required (E: 87659d093b82436ce2f7a87e402a5423)");if(hs({ibGib:t}))return this.witness_cmd({arg:t});if(us({ibGib:t}))return this.witness_otherWitness({arg:t});throw new Error("unknown arg. expect observable cmd or ibgib witness (E: dc2667cffac5b8d7b1bf2ea737c81a23)")}catch(r){throw console.error(`${e} ${w(r)??"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),r}}async witness_cmd({arg:t}){let e=`${this.lc}[${this.witness_cmd.name}]`;try{if(he&&console.log(`${e} starting... (I: 69257fac8328b9de9755fdd237b92723)`),t.data.cmd===ir.subscribe)return this.witness_subscribe_cmd({ibGib:t});throw new Error(`unknown command. must be of type ObservableCmd (${ll}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(r){throw console.error(`${e} ${r.message}`),r}finally{he&&console.log(`${e} complete.`)}}async witness_otherWitness({arg:t}){let e=`${this.lc}[${this.witness_otherWitness.name}]`;try{return he&&console.log(`${e} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),Ln({ibGib:t})?this.witness_subscriptionIbGib({arg:t}):this.witness_subscribe_nonCmdWitness({arg:t})}catch(r){throw console.error(`${e} ${r.message}`),r}finally{he&&console.log(`${e} complete.`)}}async witness_subscriptionIbGib({arg:t}){let e=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(he&&console.log(`${e} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`),!t.data)throw new Error("arg.data required (E: 764ae772727ceba95a18140fdd938323)");let r=this.getSubscriberKey({subscription:t}),[n,a]=this._subscribers[r];if(t===n)delete this._subscribers[r];else throw new Error("(UNEXPECTED) arg and subscription are two different instances? (E: aab5ef9bdc92abb9e816e2c443ab5723)");return j}catch(r){throw console.error(`${e} ${r.message}`),r}finally{he&&console.log(`${e} complete.`)}}async replayPastPayloads({observer:t,subscription:e}){let r=`${this.lc}[${this.replayPastPayloads.name}]`;try{he&&console.log(`${r} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`);let n=this.getSubscriberKey({subscription:e}),a=b(()=>!!this._subscribers[n],"fnStillSubscribed"),s=-1,i=!0;do if(s++,s<this._pastPayloads.length){if(!a()){he&&console.log(`${r} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`);return}try{let c=this._pastPayloads[s];await t.next(c)}catch{console.error(`${r} observer errored on payload (i: ${s}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`);return}}else i=!1;while(i);if(this.isErrored&&t.error&&a())try{await t.error(this._pastError)}catch{console.error(`${r} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`)}else if(this.isComplete&&t.complete&&a())try{await t.complete()}catch{console.error(`${r} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`)}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{he&&console.log(`${r} complete.`)}}async witness_subscribe_cmd({ibGib:t}){let e=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(he&&console.log(`${e} starting... (I: 0c4c75c3fae297af6449c1048ce55423)`),(t.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one ObserverWitness (E: 3ed99b32e22284573c497df788a9f923)");let r=t.ibGibs[0],n=await $l();return he&&console.log(`${e} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,he&&console.log(`${e} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,r],he&&console.log(`${e} stored subscriber (subscription, observer) (I: fb09660d885e33b80188dd0386ffc723)`),this.data.replay&&this._pastPayloads.length>0&&this.replayPastPayloads({observer:r,subscription:n}),n}catch(r){throw console.error(`${e} ${r.message}`),r}finally{he&&console.log(`${e} complete.`)}}async witness_subscribe_nonCmdWitness({arg:t}){let e=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw he&&console.log(`${e} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(r){throw console.error(`${e} ${r.message}`),r}finally{he&&console.log(`${e} complete.`)}}async subscribe(t){let e=`${this.lc}[${this.subscribe.name}]`;try{he&&console.log(`${e} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let r;if(Dr({ibGib:t})){let n=await this.argy({argData:{cmd:ir.subscribe,ibGibAddrs:[y({ibGib:t})]},ibGibs:[t]});r=await this.witness(n)}else r=await this.witness(t);if(!Ln({ibGib:r}))throw new Error("(UNEXPECTED) resSubscription is not a SubscriptionWitness? (E: c29bec4e3a48d6f1299143399ac55a23)");return r}catch(r){throw console.error(`${e} ${r.message}`),r}finally{he&&console.log(`${e} complete.`)}}getSubscriberKey({subscription:t}){if(t.data?.uuid)return t.data.uuid;throw new Error("(UNEXPECTED) subscription.data.uuid falsy? (E: 8d078e6f8155f7567fd9378557e91823)")}async dispatchToEachSubscriber({payload:t,fnForObserver:e,observableEventType:r}){let n=`${this.lc}[${this.dispatchToEachSubscriber.name}]`;try{he&&console.log(`${n} starting... (I: 0b990ce892f689d14458565717e66a23)`);let a=Object.values(this._subscribers);for(let s=0;s<a.length;s++){let[i,c]=a[s];if(Dr({ibGib:c})){let l=c;await e(l,t),l.complete?await i.unsubscribed()?console.warn(`${n} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`):await l.complete():he&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let l=await _s({eventType:r,srcObservable:this,payload:t});await c.witness(l)}}}catch(a){throw console.error(`${n} ${a.message}`),a}finally{he&&console.log(`${n} complete.`)}}async validateThis(){let t=`${this.lc}[${this.validateThis.name}]`;try{return he&&console.log(`${t} starting...`),this.data,[]}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{he&&console.log(`${t} complete.`)}}async argy({argData:t,ibMetadata:e,noTimestamp:r,ibGibs:n}){let a=await Cr({argData:t,ibMetadata:e,noTimestamp:r});return n&&(a.ibGibs=n),a}async resulty({resultData:t,ibGibs:e}){let r=await xr({resultData:t});return e&&(r.ibGibs=e),r}};var re=!1,Rn=class o extends Pn{static{b(this,"Subject_V1")}lc=`[${o.name}]`;constructor(t,e){super(t,e)}asObservable(){return this}async subscribe(t){let e=`${this.lc}[${this.subscribe.name}]`;try{re&&console.log(`${e} starting... (I: 8e47b752314870ec78eb14342621f723)`);let r=await this.argy({argData:{cmd:cr.subscribe,ibGibAddrs:[y({ibGib:t})]},ibGibs:[t]});return await this.witness(r)}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async next(t){let e=`${this.lc}[${this.next.name}]`;try{re&&console.log(`${e} starting... (I: b30363827c56450ca918c69aa15b0046)`);let r=await this.argy({argData:{cmd:cr.next,ibGibAddrs:[y({ibGib:t})]},ibGibs:[t]});await this.witness(r)}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async error(t){let e=`${this.lc}[${this.error.name}]`;try{re&&console.log(`${e} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let r;if(typeof t=="string")r=await Nr({rawMsg:t});else if(t instanceof Error||typeof t.message=="string")r=await Nr({rawMsg:w(t)});else if(t.ib&&qt({ibGib:t}))r=t;else throw new Error("unknown error type. shold either be ErrorIbGib_V1 or an Error instance or have error.message string property. (E: 2cfcab85439c3c845bfe18e8ecde3523)");let n=await this.argy({argData:{cmd:cr.error,ibGibAddrs:[y({ibGib:r})]},ibGibs:[r]});await this.witness(n)}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async complete(){let t=`${this.lc}[${this.complete.name}]`;try{re&&console.log(`${t} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let e=await this.argy({argData:{cmd:cr.complete}});await this.witness(e)}catch(e){throw console.error(`${t} ${e.message}`),e}finally{re&&console.log(`${t} complete.`)}}async witness_cmd({arg:t}){let e=`${this.lc}[${this.witness_cmd.name}]`;try{re&&console.log(`${e} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:r}=t.data;switch(r){case cr.next:return this.witness_next({ibGib:t});case cr.error:return this.witness_error({ibGib:t});case cr.complete:return this.witness_complete({ibGib:t});default:return super.witness_cmd({arg:t})}}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async witness_next({ibGib:t}){let e=`${this.lc}[${this.witness_next.name}]`;try{if(re&&console.log(`${e} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return re&&console.log(`${e} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),j;if((t.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one payload ibgib (E: 4046802ff96d4adfafcee7a74d96af5e)");let r=t.ibGibs[0];this.data.replay&&this._pastPayloads.push(r);let n=Object.values(this._subscribers);for(let a=0;a<n.length;a++){let[s,i]=n[a];if(re&&console.log(`${e} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await s.unsubscribed())re&&console.log(`${e} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`),await i.next(r);else{debugger;console.warn(`${e} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: c116e799f6b9483c97fd030eb0dd09ea)`)}}return j}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async witness_error({ibGib:t}){let e=`${this.lc}[${this.witness_error.name}]`;try{if(re&&console.log(`${e} starting... (I: 3367a73bc83c47f98d9ecfe426dc300e)`),(t.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one error ibgib (E: 905474b45bcb4f0abe7bd4618f08f32c)");let r=t.ibGibs[0];this._pastError=r;let n=Object.values(this._subscribers);for(let a=0;a<n.length;a++){let[s,i]=n[a];if(Dr({ibGib:i})){let c=i;c.error?await s.unsubscribed()?console.warn(`${e} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 8946e97f00fd4146a470064b490a4c29)`):await c.error(r):re&&console.log(`${e} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await i.witness(r)}return j}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async witness_complete({ibGib:t}){let e=`${this.lc}[${this.witness_complete.name}]`;try{re&&console.log(`${e} starting... (I: 4db180f465e24df9a4ded37fbd235558)`),this._isComplete=!0;let r=Object.values(this._subscribers);for(let n=0;n<r.length;n++){let[a,s]=r[n];if(Dr({ibGib:s})){let i=s;i.complete?await a.unsubscribed()?console.warn(`${e} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`):await i.complete():re&&console.log(`${e} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await s.witness(t)}return j}catch(r){throw console.error(`${e} ${r.message}`),r}finally{re&&console.log(`${e} complete.`)}}async validateThis(){let t=`${this.lc}[${this.validateThis.name}]`;try{return re&&console.log(`${t} starting...`),this.data,[]}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{re&&console.log(`${t} complete.`)}}async argy({argData:t,ibMetadata:e,noTimestamp:r,ibGibs:n}){if(t.cmd===ir.subscribe)return super.argy({argData:t,ibMetadata:e,noTimestamp:r,ibGibs:n});{let a=await Cr({argData:t,ibMetadata:e,noTimestamp:r});return n&&(a.ibGibs=n),a}}async resulty({resultData:t,ibGibs:e}){let r=await xr({resultData:t});return e&&(r.ibGibs=e),r}},Bn=class o extends Qr{static{b(this,"Subject_V1_Factory")}lc=`[${o.name}]`;getName(){return Rn.name}async newUp({data:t,rel8ns:e}){let r=`${this.lc}[${this.newUp.name}]`;try{re&&console.log(`${r} starting...`),t??=U(Go),t=t,e=e??ps?U(ps):void 0,t.uuid||=await V();let{classname:n}=t,a=Ss({data:t}),s=await mt({parentPrimitiveIb:`witness ${n}`,ib:a,data:t,rel8ns:e}),i=new Rn(void 0,void 0);return await i.loadIbGibDto(s),re&&console.log(`${r} witnessDto: ${F(s)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:i}}catch(n){throw console.error(`${r} ${w({error:n})}`),n}finally{re&&console.log(`${r} complete.`)}}async witnessToForm({witness:t}){let e=`${this.lc}[${this.witnessToForm.name}]`;try{re&&console.log(`${e} starting...`);let{data:r}=t;if(!r)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");re&&console.log(`${e} data: ${F(r)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await no({n:100}),a=new kn().with({idPool:n}).name({of:r.name,required:!1}).description({of:r.description??Tn}).and().and().uuid({of:r.uuid,required:!0}).classname({of:r.classname}).and().commonWitnessFields({data:r}).outputForm({formName:"form",label:"observable"});return Promise.resolve(a)}catch(r){throw console.error(`${e} ${w({error:r})}`),r}finally{re&&console.log(`${e} complete.`)}}async formToWitness({form:t}){let e=U(Go);return this.patchDataFromItems({data:e,items:t.items,pathDelimiter:Pr}),await this.newUp({data:e})}};var Mn=!1;function Sl({data:o}){let t=`[${Sl.name}]`;try{if(Mn&&console.log(`${t} starting...`),!o)throw new Error("Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)");let e=[],{name:r,uuid:n,classname:a}=o;return r?r.match(bs)||e.push(`name must match regexp: ${bs} (E: de987eb8fea0b6232f60abf31815095c)`):e.push("name required."),n?n.match(Ie)||e.push(`uuid must match regexp: ${Ie} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):e.push("uuid required."),a&&(a.match(zt)||e.push(`classname must match regexp: ${zt}`)),e}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Mn&&console.log(`${t} complete.`)}}b(Sl,"validateCommonSubjectData");function Ss({data:o,classname:t}){let e=`[${Ss.name}]`;try{let r=Sl({data:o});if(r.length>0)throw new Error(`invalid Subject data: ${r} (E: 55620ac1f17e30a30a92850219f894ac)`);if(t){if(o.classname&&o.classname!==t)throw new Error("classname does not match data.classname (E: 20e86cca70130839a49ad011c9a7aafa)")}else if(t=o.classname,!t)throw new Error("classname required (E: 74e29ae0f618fee7e7ef72a30c654a6c)");let{name:n,uuid:a}=o;return`witness ${An} ${t} ${n} ${a}`}catch(r){throw console.error(`${e} ${w(r)}`),r}}b(Ss,"getSubjectIb");var kn=class o extends er{static{b(this,"SubjectFormBuilder")}lc=`[${o.name}]`;constructor(){super(),this.what="subject"}};function Dr({ibGib:o}){let t=`[${Dr.name}]`;try{return Mn&&console.log(`${t} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof o.next=="function"}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Mn&&console.log(`${t} complete.`)}}b(Dr,"isObserver");async function Un({data:o,replay:t}={}){let e=new Bn;return o??=U(Go),t&&(o.replay=!0),(await e.newUp({data:o})).newIbGib}b(Un,"newupSubject");var Fn="sync_sagacontext";var Co=!1;async function As({data:o}){let t=`[${As.name}]`;try{if(!o)throw new Error("data required (E: 839d82138c234b3e89582855594191fe)");let e=o["@payloadAddrsDomain"]?o["@payloadAddrsDomain"].length:0;return[Fn,o.sagaN,e].join(" ")}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(As,"getSyncSagaContextIb");async function fr({context:o}){let t=`[${fr.name}]`;try{Co&&console.log(`${t} starting... (I: 7797f8294bd8f7e5089cb722ad468226)`);let e=[],r=await le({ibGib:o});if(r&&r.length>0)return r.forEach(n=>e.push(n)),e;if(o.sagaFrame?(await $n({sagaIbGib:o.sagaFrame})).forEach(a=>e.push(a)):e.push("context.sagaFrame is falsy. (E: b4edd88f4963f493789f83b29ba2df26)"),o.sagaFrameMsg){if((await le({ibGib:o.sagaFrameMsg})??[]).forEach(a=>e.push(a)),o.sagaFrame){let a=o.sagaFrame.rel8ns?.[Re]?.[0];if(a){let s=y({ibGib:o.sagaFrameMsg});s!==a&&e.push(`context.sagaFrameMsg address (${s}) does not match the stone address referenced in sagaFrame relations (${a}). (E: a983b271fcae46bbad7e82098bc24826)`)}else e.push(`context.sagaFrame is missing the message stone relation '${Re}'. (E: da872cf3a8d46dbbad89d0a68d712826)`)}}else e.push("context.sagaFrameMsg is falsy. (E: ed405a72ab0d8bbdca7b9605d8f9a26)");return e.length>0?e:(console.error(`${t} NAG ERROR MSG (NOT THROWN): not fully implemented yet (E: d574d85cb578637648ed403857f7a826)`),[])}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Co&&console.log(`${t} complete.`)}}b(fr,"validateContextAndSagaFrame");async function Ts({context:o,space:t}){let e=`[${Ts.name}]`;try{Co&&console.log(`${e} starting... (I: 3c34e8f1d6ef965f98725c88459ea926)`);let r=[];if(!o.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 3e4ddd0eb4b828ad489658d88d9a6326)");if(!o.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 8026589d4fed69c828334ee842074326)");let{sagaFrame:n,signedSessionIdentity:a}=o;if(!n.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: b61cc82d25984c92f75db74a5a855b26)");if(!a)return console.error(`${e}[NAG][not thrown] sagaFrame.data.sessionIdentityTjpAddr logic needs to be added in coordinator (E: 4fc47800a1086c917a47381824280826)`),n.data.sessionIdentityTjpAddr?(r.push("Context has no session identity, but sync saga frame shows a session identity (sagaFrame.data.sessionIdentityTjpAddr is truthy). (E: 69dd6cdc2e1859c0f3d62958c4339826)"),r):o.rel8ns.sessionIdentity?(r.push("Context has no signed session identity, but context.rel8ns.sessionIdentity is truthy. (E: 96a04a8a6c88ea8bf88118f89ad8e326)"),r):(Co&&console.log(`${e} context has no signedSessionIdentity and sync saga frame doesn't state there should be session identity. So nothing further to authenticate - returning early with no authentication errors. (I: d708735f9a2899ee98f762b8a09ed826)`),[]);let s=y({ibGib:a}),i=o.rel8ns?.sessionIdentity??[];if(i.length===0)return r.push("context.rel8ns.sessionIdentity is falsy/empty but context.signedSessionIdentity is present. (E: 66f906421eb2468c0b33f908a3cf2826)"),r;if(i.length>1)return r.push("context.rel8ns.sessionIdentity has multiple identity addrs. (E: 489428bfe6fdaa4cd885b938dc4c5826)"),r;let c=i[0],l=await Me({addrs:[c],space:t});if(!l)throw new Error(`(UNEXPECTED) resGetLatestAddr for prevSessionIdentityAddr in space (${t.ib}) falsy? (E: 7b207e5cbcec9037ea5adbe822ead826)`);if(!l.data)throw new Error(`(UNEXPECTED) resGetLatestAddr.data for prevSessionIdentityAddr in space (${t.ib}) falsy? (E: de4eb8d730c8c4dcb59c8b9c79277826)`);if(!l.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr.data.success falsy? (E: c94298dfd9684ad6a87eb748459aa826)");let{latestAddrsMap:d}=l.data;if(!d)throw new Error("(UNEXPECTED) resGetLatestAddr.data.latestAddrsMap falsy? (E: 19f1fd5fe798cf2e5fa923919169d826)");if(Object.keys(d).length!==1)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap).length !== 1? (E: fe526a0747589c6427a8bcc86da34a26)");let f=d[c];if(!f)return r.push(`prevSessionIdentityAddr (${c}) not found in space (${t.ib}). this should have been the incoming prevSessionIdentityAddr (E: f6d042bd6b54819998653228dee34226)`),r;if(c!==f&&f!==s)return r.push(`context.rel8ns.sessionIdentity does not point to the most recent in the space (${t.ib}). (E: 2f8288f53c87b6aa47bd2178d9df0c26)`),console.log(`context: ${F(qe({ibGib:o}))}`),console.log(`prevSessionIdentityAddr (context.rel8ns.sessionIdentity): ${c}`),console.log(`prevSessionIdentityAddr_latest: ${f}`),console.log(`currSessionIdentity (context.signedSessionIdentity): ${F(qe({ibGib:{ib:a.ib,gib:a.gib,rel8ns:a.rel8ns,data:{...a.data,challengePools:a.data.challengePools.map(H=>({...H,challenges:{}}))}}}))}`),console.log(`currSessionIdentityAddr: ${s}`),r;let p=await W({addr:c,space:t});if(!p.success||p.ibGibs?.length!==1)return r.push(`could not fetch latest sender identity ${c} from space (${t.ib}). (E: fd48c3e64c9fa4efd8a1f8280af18226)`),r;let h=p.ibGibs[0],g=await uo({ibGib:h,naive:!0,space:t});if(!g)throw new Error(`(UNEXPECTED) couldn't get sessionIdentityTjp in space (${t.ib})? we have already gotten the identity itself in the space, so we would expect the entire timeline to exist in it. (E: 9be0382ff1c8a0e77645ea38c096f826)`);let m=y({ibGib:g});if(m!==n.data.sessionIdentityTjpAddr)throw new Error("(UNEXPECTED) sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr? (E: c9a4ad5c2728fe38e86afc58e4abaf26)");let E=g.data.frameDetails;if(!E)return r.push("Invalid session identity tjp: sessionIdentityTjp.data.frameDetails is falsy. (E: 0187f8f804a84256281720586620b826)"),r;let{senderIdentityAddr:S,senderIdentityTjpAddr:A}=E;if(!S)throw new Error("sessionGenesisFrameDetails.senderIdentityAddr falsy (E: 02a0c80a3ead9e3af8af4cf3b156e826)");if(!A)throw new Error("sessionGenesisFrameDetails.senderIdentityTjpAddr falsy (E: 271928090ff5dc56d4bb63d8d5c68826)");let _=await Me({addrs:[A,S],space:t});if(!_)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity for prevSessionIdentityAddr in space (${t.ib}) falsy? (E: 2e4ae8083b6fb7cbb8fae2a519062926)`);if(!_.data)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data for prevSessionIdentityAddr in space (${t.ib}) falsy? (E: 2e231850c2a898cc282b4b2841056826)`);if(!_.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.success falsy? (E: e93508f03e0475925875b00746ffd826)");let{latestAddrsMap:$}=_.data;if(!$)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.latestAddrsMap falsy? (E: 87a91e3f9968ad9ba79cdfe8cd878326)");if(Object.keys($).length!==2&&A!==S)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr? (E: fe46bd584853d8e1e8e2d11f52012826)");let T=$[A],I=$[S];if(!I)throw new Error("(UNEXPECTED) senderIdentityAddr_latest falsy? (E: e151798ae2e9241578d09948937c4b26)");if(T!==I)throw new Error("senderIdentityTjpAddr_latest !== senderIdentityAddr_latest (E: 52478a1053589e72665031a853cc1826)");let G=await W({addr:I,space:t});if(!G.success||G.ibGibs?.length!==1)return r.push(`could not fetch latest sender identity ${c} from space (${t.ib}). (E: 3565ff0ed458f5a2384c40b16e849826)`),r;let v=G.ibGibs[0];if(!v.data.proofs)return r.push("Invalid sender identity. Proofs empty/falsy. (E: ebf488853061614d2b5b137828119526)"),r;let N=v.data.proofs.find(H=>H.claim.verb===Pe)?.claim;if(!N)return r.push(`Most recent senderIdentity has no proof whose claim.verb === ${Pe}. (E: b0f488ecccbbfe43d9a0b7c8a29d7826)`),r;if(N.target!==m)return r.push(`Most recent sender identity claim has claim.verb === ${Pe} but DOES NOT target expected session identity addr ${c}. (E: 3e7f18d99848969be8586423d5ccb826)`),r;let P=await new Ue().validate({currentIbGib:a,prevIbGib:h});P.length>0&&r.push(`Invalid session identity transition: ${P.join(", ")} (E: da1c81c6d3c86aec3254f48fe7514226)`);let R=y({ibGib:o});return a.data?.proofs?.some(H=>H.claim.target===R)||r.push(`Session identity signature does not target current context ibgib (${R}). (E: acae68938c287178c878d1b88bebb826)`),r}catch(r){let n=`${e} ${w(r)}`;return console.error(n),[`authentication produced an error: ${n} (E: 45e014b82af81993d936611ca6fc4d26)`]}finally{Co&&console.log(`${e} complete.`)}}b(Ts,"authenticateContextIntrinsically");var Be=!1,jn=class o extends sr{static{b(this,"SyncPeer_V1")}lc=`[${o.name}]`;opts;payloadIbGibsDomainReceived$;currentSessionIdentity;get currentSessionIdentityAddr(){return this.currentSessionIdentity?y({ibGib:this.currentSessionIdentity}):void 0}async signContext({contextAddr:t}){let e=`${this.lc}[${this.signContext.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:r,sagaId:n,localMetaspace:a,localSpace:s}=this.opts;if(!r)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!n)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let i=await r(),c=await vr({senderSecret:i,sagaId:n}),d=await new Ue().sign({latestKeystone:this.currentSessionIdentity,masterSecret:c,claim:{verb:Pe,target:t},metaspace:a,space:s});return this.currentSessionIdentity=d,d}catch(r){throw console.error(`${e} ${w(r)}`),r}}async signContextConnect({challengeUuid:t,demandedIds:e}){let r=`${this.lc}[${this.signContextConnect.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!n)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!a)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let c=await n(),l=await vr({senderSecret:c,sagaId:a}),f=await new Ue().sign({latestKeystone:this.currentSessionIdentity,masterSecret:l,poolId:wt,requiredChallengeIds:e,claim:{verb:or,target:t},metaspace:s,space:i});return this.currentSessionIdentity=f,f}catch(n){throw console.error(`${r} ${w(n)}`),n}}get classname(){if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 1ab1841e9338b54f3aa615fa37024826)");if(!this.data.classname)throw new Error("invalid peer. this.data.classname is falsy (E: b0ee28a0abb84a06588d9de7afcef826)");return this.data.classname}constructor(t,e){super(t,e)}async initialize(){this.payloadIbGibsDomainReceived$=await Un()}async connect(t){let e=`${this.lc}[${this.connect.name}]`;try{Be&&console.log(`${e} starting... (I: ad89d8137351662fb8a30114a1fa4826)`),await this.preConnectCheck(t),await this.connectImpl(t)}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Be&&console.log(`${e} complete.`)}}async establishSessionIdentity(){let t=`${this.lc}[${this.establishSessionIdentity.name}]`;try{if(Be&&console.log(`${t} starting... (I: f2a1b3c4d5e6f7a8b9c0d1e2f3a4b526)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Call initializeOpts first. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c526)");let{senderIdentity:e,fnSenderSecret:r,senderDomainAddr:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!e||!r){Be&&console.log(`${t} no senderIdentity/fnSenderSecret \u2014 skipping establish (I: f29348a77d1542326d14043ea4b69126)`);return}if(!n)throw new Error("(UNEXPECTED) senderDomainAddr falsy but senderIdentity/fnSenderSecret truthy? if identity is used, senderDomainAddr must be provided. (E: c288fa8e9d3d82fc)");let c=y({ibGib:e}),l=ee({ibGib:e});if(!l)throw new Error("(UNEXPECTED) senderIdentityTjpAddr falsy? (E: d5d8c3ab25a83a2c127904fe96de1526)");if(!a)throw new Error("(UNEXPECTED) sagaId falsy? Must be set in initializeOpts before calling establishSessionIdentity. (E: c6ba389d51b8af07d82458f875cf9826)");let d=await r();if(!d)throw new Error("senderSecret falsy. senderSecret required. (E: 1a8b0298bf78cbdf284b7988983b9826)");let f=await vr({senderSecret:d,sagaId:a}),p=new Ue;if(!this.opts.sessionConnectPoolConfig)throw new Error("(UNEXPECTED) opts.sessionConnectPoolConfig falsy? (E: 3351fd566eb8bbd2f821bb08c4419826)");if(!this.opts.sessionSyncPoolConfig)throw new Error("(UNEXPECTED) opts.sessionSyncPoolConfig falsy? (E: dbffa810d9e7ff6079088deb5b8e7826)");let h={senderIdentityAddr:c,senderIdentityTjpAddr:l};this.opts.targetAddrs&&(h.targetAddrs=this.opts.targetAddrs);let g=await p.genesis({masterSecret:f,configs:[this.opts.sessionConnectPoolConfig,this.opts.sessionSyncPoolConfig],frameDetails:h,metaspace:s,space:i}),m=y({ibGib:g}),E=await p.sign({latestKeystone:e,masterSecret:d,claim:{verb:Pe,target:m},metaspace:s,space:i});await this.postEstablishToReceiver({newSenderIdentity:E,sessionIdentity:g}),this.currentSessionIdentity=g}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Be&&console.log(`${t} complete.`)}}async initializeOpts(t){let e=`${this.lc}[${this.initializeOpts.name}]`;try{Be&&console.log(`${e} starting... (I: 31bd5fda37c89fa37fbaf14daf5fe726)`),this.opts=t}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Be&&console.log(`${e} complete.`)}}setOptionalOpts(t){let e=`${this.lc}[${this.setOptionalOpts.name}]`;try{if(Be&&console.log(`${e} starting... (I: ae5ddbd3577db267f84743175a736626)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0dd4d6080a6e2f31d86cf4d86e11b826)");Be&&console.log(`${e} updating opts. arg keys: ${Object.keys(t)} (I: 452d78a558f8fc3468c8e2e68c70b226)`),this.opts={...this.opts,...t}}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Be&&console.log(`${e} complete.`)}}async authenticateAndValidate({context:t}){let e=`${this.lc}[${this.authenticateAndValidate.name}]`;try{if(Be&&console.log(`${e} starting... (I: add238055cd84a222c5b8c89913af526)`),!this.opts)throw new Error("(UNEXPECTED) opts falsy in authenticateValidateAuthorize (E: b7e5a8ad99d84e1ba8d8f7facd288826)");let{localSpace:r}=this.opts,n=await Ts({context:t,space:r});if(n.length>0)throw new Error(`invalid context authentication. authenticationErrors: ${n} (E: da89da5ee1269aeb78952d475d607526)`);let a=await fr({context:t});if(a.length>0)throw new Error(`invalid context received. validationErrors: ${a} (E: 8b34c875c968af29bc433138e57a7826)`)}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Be&&console.log(`${e} complete.`)}}async witness(t){let e=`${this.lc}[${this.witness.name}]`;try{if(Be&&console.log(`${e} starting...`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Concrete class should have initialized sender opts by now. (E: 0b9e28287318fdf8bf9f5a6886a24826)");if(!t.sagaFrame)throw new Error("context.sagaFrame falsy. (E: a33dd88aa108e2bad9e885885731ce26)");await this.authenticateAndValidate({context:t});let r=await this.sendContextRequest(t);if(r){let n=await Jr({sagaIbGib:t.sagaFrame,space:this.opts.localSpace});return r}else{Be&&console.log(`${e} No response from peer. this may be normal if we just sent the very last commit frame. (I: 1855b7728c8898e1f9c001f8170ba826)`);return}}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Be&&console.log(`${e} complete.`)}}async getLocalIbGib(t){let e=`${this.lc}[${this.getLocalIbGib.name}]`;try{if(Be&&console.log(`${e} starting... (I: 27b248cb9801eeb2386b71485389a826)`),console.warn(`${e} possibly a bottleneck here, getLocalIbGib only gets a single ibgib... (W: 2fd448a435480e6b128f6b8bcbef4826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: cfb9431f2fb851f24a6c88e80c3b3326)");let r=await W({space:this.opts.localSpace,addr:t});if(r.success&&r.ibGibs&&r.ibGibs.length===1)return r.ibGibs[0];throw new Error(`couldn't get addr (${t}) from local space ${this.opts.localSpace}. reason: ${r.errorMsg??"unknown error (E: 926ef8bf4fcc299ab89dba34ea691a26)"} (E: d8a89807e471d3f8b938ab21df44cb26)`)}catch(r){throw console.error(`${e} ${w(r)}`),r}finally{Be&&console.log(`${e} complete.`)}}};var Al=!1,br={COMMON:{ALGO:De.sha_256,TYPE:bt.hash_reveal_v1,ROUNDS:2,REPLENISH:$e.topUp},CONNECT_POOL:{ID:wt,VERB:or,SIZE:10,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:0,SERVER_DEMAND_COUNT:3}};function Vn(o){let t=`[${Vn.name}]`;try{Al&&console.log(`${t} starting... (I: 3c791af2f978a00a087dfdde90884826)`);let e=(o.data?.challengePools??[]).find(s=>s.id===br.CONNECT_POOL.ID);if(!e)throw new Error(`Keystone missing "${br.CONNECT_POOL.ID}" pool (E: 6382e29260e4ddbac42ed18f49733526)`);let r=Object.keys(e.challenges).sort();if(r.length===0)throw new Error("Connect pool has no challenges (E: 1ef62fdbda182a790835c8c796475226)");let n=r[0],a=e.challenges[n];return{challengeId:n,challenge:a}}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Al&&console.log(`${t} complete.`)}}b(Vn,"getConnectChallenge");var $b="auth-challenge-init",Ib="auth-init",_b="auth-challenge",Sb="auth-proof",Ab="auth-ok",Tb="auth-fail",Gb="sync-frame",vb="sync-frame-response",Cb="sync-frame-authenticated",xb="sync-frame-response-authenticated",Nb="domain-payload",Db="sync-error",Z={auth_challenge_init:$b,auth_init:Ib,auth_challenge:_b,auth_proof:Sb,auth_ok:Ab,auth_fail:Tb,sync_frame:Gb,sync_frame_response:vb,sync_frame_authenticated:Cb,sync_frame_response_authenticated:xb,domain_payload:Nb,sync_error:Db},Kn=Object.values(Z);function Gs(o){return Kn.includes(o)}b(Gs,"isSyncWebSocketMsgType");function Tl(o){throw new Error(`Unhandled message type: ${o} (E: e928a3f82cd7469a98ef1bc248a3f826)`)}b(Tl,"assertUnreachable");var $t=!0,eo=class o extends jn{static{b(this,"SyncPeerWebSocketSender_V1")}lc=`[${o.name}]`;get classname(){return o.name}get isSocketOpen(){return this.ws!==void 0&&this.ws.readyState===WebSocket.OPEN}ws;activeResolve;activeReject;pendingPayloadsToSend=[];handshakeMessageListener;constructor(t,e){super(t,e)}async preConnectCheck(t){let e=`${this.lc}[${this.preConnectCheck.name}]`;if(!this.data?.wsUrl)throw new Error("Missing wsUrl in peer data (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c910)");if(!this.data?.httpEvolveUrl)throw new Error("Missing httpEvolveUrl in peer data (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c911)")}async postEstablishToReceiver({newSenderIdentity:t,sessionIdentity:e}){let r=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if($t&&console.log(`${r} posting evolved keystones to ${this.data.httpEvolveUrl}...`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d642e8a9af18b532c87c6f581aa53b26)");if(!this.data.httpEvolveUrl)throw new Error("(UNEXPECTED) this.data.httpEvolveUrl falsy? (E: 8589ddbb155914d85c09658881da2c26)");let n=await fetch(this.data.httpEvolveUrl,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t,relatedIbGibs:[e]})});if(!n.ok){let a=await n.json().catch(()=>({})),s=a.message||a.error||"Unknown error";throw new Error(`HTTP ${n.status} evolution post rejected. errorMsg: ${s} (E: e8a478291b88d05c68cf6b385684b826)`)}$t&&console.log(`${r} evolve post accepted by server.`)}catch(n){throw console.error(`${r} establish post failed: ${w(n)}`),n}}async connectImpl(t){let e=`${this.lc}[${this.connectImpl.name}]`;try{$t&&console.log(`${e} starting...`);let{senderIdentity:r,fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!r||!n||!a)throw new Error("Missing identity parameters in peer options (E: ed49b6711ac82efcdb42b8a28c5b6826)");let c=await n(),l=await vr({senderSecret:c,sagaId:a}),d=y({ibGib:r}),f=y({ibGib:(r.rel8ns?.past,r)}),p=await s.getLatestAddr({ibGib:r,space:i});if(!p)throw new Error("senderIdentityLatestAddr falsy. we should have a latest addr that is different than the sender identity at this point (done in the peer establish phase) (E: 225607318bef485d7821f82de97b6826)");let m=((await s.get({addrs:[p],space:i})).ibGibs?.[0]).data.proofs.at(0)?.claim.target;if(!m)throw new Error("Could not locate session keystone target from identity (E: 5ec4882f7e5e4c33fbd00ab8b3166726)");let S=(await s.get({addrs:[m],space:i})).ibGibs?.[0];if(!S)throw new Error(`Session keystone not found in local space: ${m} (E: 9ba818e6622808bb4ae749be31f80b26)`);let A=(S.data?.challengePools??[]).find(N=>N.id===br.CONNECT_POOL.ID);if(!A)throw new Error("Session keystone missing connect pool (E: f50968afca04b6d38ec19824ea201826)");let{challengeId:_}=Vn(S),$=Dt.create({config:A.config}),T=await $.derivePoolSecret({masterSecret:l}),I=await $.generateSolution({poolSecret:T,poolId:br.CONNECT_POOL.ID,challengeId:_}),G=`${this.data.wsUrl}?sAddr=${encodeURIComponent(m)}&solution=${encodeURIComponent(I.value)}`;$t&&console.log(`${e} connecting to WebSocket: ${G}`);let v=new WebSocket(G);return this.ws=v,new Promise((N,O)=>{let P=!1;v.addEventListener("open",()=>{$t&&console.log(`${e} WebSocket opened. Awaiting challenge...`)}),this.handshakeMessageListener=async R=>{try{let k=JSON.parse(R.data);$t&&console.log(`${e} received handshake frame: ${k.type}`);let H=k.type;if(!Gs(H)){let K=Kn.join(", ");throw new Error(`Unknown message type '${H}' received during connection handshake. Valid types are: ${K} (E: e983271bc84f46928e4695be2409826)`)}switch(H){case Z.auth_challenge_init:await this.handleHandshakeAuthChallengeInit(v,m);break;case Z.auth_challenge:await this.handleHandshakeAuthChallenge(v,k,S,l);break;case Z.auth_ok:P=!0,this.handleHandshakeAuthOk(v,N);break;case Z.auth_fail:this.handleHandshakeAuthFail(k,O);break;case Z.sync_error:this.handleHandshakeSyncError(k,O);break;case Z.auth_init:case Z.auth_proof:case Z.sync_frame:case Z.sync_frame_response:case Z.sync_frame_authenticated:case Z.sync_frame_response_authenticated:case Z.domain_payload:throw new Error(`Unexpected message type '${H}' during connection handshake (E: e3f80c68ab2a46c2b1858c8a1e2f8926)`);default:Tl(H)}}catch(k){console.error(`${e} ${w(k)}`),O(k)}},v.addEventListener("message",this.handshakeMessageListener),v.addEventListener("close",R=>{P||(this.disconnect(),O(new Error(`WebSocket closed before connect completed (code: ${R.code})`)))}),v.addEventListener("error",R=>{P||(this.disconnect(),O(new Error("WebSocket connection error")))})})}catch(r){throw console.error(`${e} connect failed: ${w(r)}`),r}}disconnect(){let t=`${this.lc}[${this.disconnect.name}]`;try{if($t&&console.log(`${t} starting... (I: 35c4b85fca0c6e9d042f5ff87cde3826)`),this.ws){this.handshakeMessageListener&&(this.ws.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0);try{this.ws.close()}catch(e){console.error(`${t} failed to close websocket: ${w(e)}`)}this.ws=void 0}}catch(e){console.error(`${t} ${w(e)}`)}finally{$t&&console.log(`${t} complete.`)}}async handleRuntimeMessage(t){let e=`${this.lc}[${this.handleRuntimeMessage.name}]`;try{let r=JSON.parse(t.data);$t&&console.log(`${e} received runtime frame: ${r.type}`);let n=r.type;if(!Gs(n)){let a=Kn.join(", ");throw new Error(`Unknown message type '${n}' received during active sync saga loop. Valid types are: ${a} (E: e23a8d10b74d47fb90518f8e3f4b826)`)}switch(n){case Z.sync_frame_response:await this.handleRuntimeSyncFrameResponse(r);break;case Z.sync_frame_authenticated:this.handleRuntimeSyncFrameAuthenticated();break;case Z.domain_payload:this.handleRuntimeDomainPayload(r);break;case Z.sync_error:this.handleRuntimeSyncError(r);break;case Z.auth_challenge_init:case Z.auth_init:case Z.auth_challenge:case Z.auth_proof:case Z.auth_ok:case Z.auth_fail:case Z.sync_frame:case Z.sync_frame_response_authenticated:throw new Error(`Unexpected message type '${n}' during active sync saga loop (E: e982b12cf92c448bbad0e84b7263c826)`);default:Tl(n)}}catch(r){if(console.error(`${e} failed parsing/handling runtime frame: ${w(r)}`),this.disconnect(),this.activeReject){let n=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,n(r)}}}async handleHandshakeAuthChallengeInit(t,e){t.send(JSON.stringify({type:Z.auth_init,sAddr:e}))}async handleHandshakeAuthChallenge(t,e,r,n){let{challengeUuid:a,demandedIds:s}=e;$t&&console.log(`${this.lc} solving demanded challenges: ${s.join(", ")}`);let i=await this.signContextConnect({challengeUuid:a,demandedIds:s});if(!i)throw new Error("Failed to sign connect challenge proof (E: e9807f28ae9248bbadd0a7f1a8e9826)");t.send(JSON.stringify({type:Z.auth_proof,proofFrame:i}))}handleHandshakeAuthOk(t,e){$t&&console.log(`${this.lc} WebSocket connect SUCCESS!`),this.handshakeMessageListener&&(t.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0),t.addEventListener("message",r=>this.handleRuntimeMessage(r)),e()}handleHandshakeAuthFail(t,e){this.disconnect(),e(new Error(`Handshake auth failed: ${t.message||"Unknown fail reason"} (E: f380b271a2be498db257bc8209fa8926)`))}handleHandshakeSyncError(t,e){this.disconnect(),e(new Error(`Handshake sync error: ${t.message||t.error||"Unknown sync error"} (E: f9208a01fe434cbbad83f210ea8f3426)`))}async handleRuntimeSyncFrameResponse(t){let e=t.context,r=await fr({context:e});if(r.length>0)throw new Error(`Invalid response context received: ${r.join(", ")} (E: d7b5a283cf4c43ba8659c803800cf826)`);let n=[qe({ibGib:e}),e.sagaFrame,e.sagaFrameMsg];e.signedSessionIdentity&&n.push(e.signedSessionIdentity);let{localSpace:a}=this.opts;for(let i of n)await Xe({space:a,ibGibs:[i]}),await Te({space:a,ibGib:i});if((e.data?.["@payloadAddrsDomain"]||[]).length>0&&this.ws.send(JSON.stringify({type:Z.sync_frame_response_authenticated,contextAddr:y({ibGib:e})})),this.activeResolve){let i=this.activeResolve;this.activeResolve=void 0,this.activeReject=void 0,i(e)}}handleRuntimeSyncFrameAuthenticated(){let t=this.pendingPayloadsToSend||[];this.pendingPayloadsToSend=[];for(let e of t)this.ws.send(JSON.stringify({type:Z.domain_payload,ibGib:e}))}handleRuntimeDomainPayload(t){let e=t.ibGib;this.payloadIbGibsDomainReceived$.next(e)}handleRuntimeSyncError(t){let e=t.message||t.error||"Unknown sync runtime error",r=new Error(`Sync runtime error from receiver: ${e} (E: e983bc1c828d447fa0581da2b8004f26)`);if(this.activeReject){let n=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,n(r)}else throw r}async sendContextRequest(t){let e=`${this.lc}[${this.sendContextRequest.name}]`;try{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected or open (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c915)");let r=t.payloadIbGibsDomain??[];this.pendingPayloadsToSend=[...r];let n={...t};return delete n.payloadIbGibsDomain,new Promise((a,s)=>{this.activeResolve=a,this.activeReject=s,this.ws.send(JSON.stringify({type:Z.sync_frame,context:n}))})}catch(r){throw console.error(`${e} sendContextRequest failed: ${w(r)}`),r}}};var Fe=!1;async function vs({timeline:o}){let t=`[${vs.name}]`;try{if(Fe&&console.log(`${t} starting...`),ue({ibGib:o}))return console.warn(`${t} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`),y({ibGib:o});{let e=Oe({gib:o.gib}),r=e.tjpGib??e.punctiliarHash;if(!r)throw new Error(`${t} (UNEXPECTED) Could not determine tjpGib or punctiliarHash from ibGib. (E: eb3b6472e9b335991a1b0869f772f7d3)`);return r}}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Fe&&console.log(`${t} complete.`)}}b(vs,"getLockScope");async function pr({timeline:o,rel8nInfos:t,rel8nRemovalInfos:e,timelineIndexInfo:r,metaspace:n,space:a,skipLock:s,noDna:i}){let c=`[${pr.name}]`;try{if(Fe&&console.log(`${c} starting... (I: fcdff10832215068019355265f4cbc25)`),a??=await n.getLocalUserSpace({lock:!1}),!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)");let l=await vs({timeline:o}),d=b(async()=>{if(!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let p=y({ibGib:o}),h=await n.getLatestAddr({addr:p,space:a});if(!h)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${y({ibGib:o})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let g=qe({ibGib:o});if(p!==h){let _=await n.get({addrs:[h],space:a});if(_.errorMsg||(_.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${h}) from space (${a.ib}). errorMsg: ${_.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);g=_.ibGibs.at(0)}let m;if(e&&e.length>0){m={};for(let _ of e){let{rel8nName:$,ibGibAddrs:T}=_;if(T.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${$}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}m[$]||(m[$]=[]),m[$]=m[$].concat(T)}}let E={};for(let _ of t){let{rel8nName:$,ibGibs:T}=_;if(T.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${$}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}E[$]||(E[$]=[]),E[$].push(...T.map(I=>y({ibGib:I})))}let S=await He({src:g,rel8nsToRemoveByAddr:m,rel8nsToAddByAddr:E,dna:!i,nCounter:!0}),A=S.newIbGib;return await n.persistTransformResult({resTransform:S,space:a}),r&&await Cs({type:r.type,rel8nInfos:[{rel8nName:r.rel8nName,ibGibs:[A]}],metaspace:n,space:a,skipLock:s}),await n.registerNewIbGib({ibGib:A,space:a}),A},"fn");return s?await d():await Ct({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:a,callerInstanceId:rt(),fn:d})}catch(l){throw console.error(`${c} ${w(l)}`),l}finally{Fe&&console.log(`${c} complete.`)}}b(pr,"appendToTimeline");async function Cs({type:o,rel8nInfos:t,dataToAddOrPatch:e,metaspace:r,space:n,skipLock:a}){let s=`[${Cs.name}]`;try{if(Fe&&console.log(`${s} starting... (I: 6e7d05fe916d813b71766e2eaa747c25)`),o==="latest")throw new Error('cannot update the "latest" special index by this function. The registerNewIbGib will do this automatically. (E: 231eb78a221ccdbcf56cd1899260a425)');if(n??=await r.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 43067821a4749a7648fe2612d25d7f25)");let i=b(async()=>{let c=b(async()=>{let l=await r.getSpecialIbGib({type:o,space:n,initialize:!0});if(!l)throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${o}. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);return l.rel8ns||console.warn(`${s} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`),l},"fnGetSpecialIndex");for(let l of t??[]){let{rel8nName:d,ibGibs:f}=l;f.length===0&&console.error(`${s} ibGibs empty. skipping rel8nName (${d}). (E: 150d74f73f97aea1b97d173d92c77125)`);let h=(await c()).rel8ns??{},g,m=h[d]??[];if(m.length>0){let E=new Set;f.forEach(S=>{let A=y({ibGib:S}),_=S.rel8ns?.past??[];m.filter($=>[..._,A].includes($)).forEach($=>E.add($))}),E.size>0&&(g=Array.from(E))}await r.rel8ToSpecialIbGib({type:o,rel8nName:d,ibGibsToRel8:f,addrsToUnRel8:g,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(e??{}).length>0){let l=await c(),d=await ot({src:l,dataToAddOrPatch:e,dna:!1,linkedRel8ns:[pe.past],nCounter:!0}),f=d.newIbGib;await ge({resTransform:d,space:n});let p=Ge({type:o});await r.setConfigAddr({key:p,addr:y({ibGib:f}),space:n}),await r.registerNewIbGib({ibGib:f,space:n})}},"fn");a?await i():await Ct({scope:o,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:i})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{Fe&&console.log(`${s} complete.`)}}b(Cs,"updateSpecialIndex");async function xs({timeline:o,timelineAddr:t,metaspace:e,space:r}){let n=`[${xs.name}]`;try{if(Fe&&console.log(`${n} starting... (I: f2b605361368e1956f6db878dbfeb825)`),!o&&!t)throw new Error("either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)");t??=y({ibGib:o});let a=await e.getLatestAddr({addr:t,space:r})??t;if(!a)throw new Error(`${n} (UNEXPECTED) Could not get latest address for timeline ${y({ibGib:o})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let s;if(t===a){if(!o){let i=await e.get({addrs:[a],space:r});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${r.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: 3fc767a594788a43a4ba18c87491a825)`);o=i.ibGibs.at(0)}s=qe({ibGib:o})}else{let i=await e.get({addrs:[a],space:r});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${r.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);s=i.ibGibs.at(0)}return s}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Fe&&console.log(`${n} complete.`)}}b(xs,"getLatestTimelineIbGibDto_nonLocking");async function Y({timeline:o,timelineAddr:t,mut8Opts:e,metaspace:r,space:n,skipLock:a,timelineIndexInfo:s,noDna:i}){let c=`[${Y.name}]`;try{if(Fe&&console.log(`${c} starting... (I: genuuid)`),!o&&!t)throw new Error("(UNEXPECTED) both timeline and timelineAddr falsy? either one is required. (E: a19d98c6acb87af3b876c1484f6ac825)");if(n??=await r.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: genuuid)");if(!o){let p=await r.get({addrs:[t],space:n});if(!p.success||p.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${t}) in space (${n?.ib??"undefined"}) (E: genuuid)`);o=p.ibGibs.at(0)}let l=await vs({timeline:o}),d=b(async()=>{if(!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");if(!o)throw new Error("(UNEXPECTED) timeline falsy? we should be ensured that it's truthy at this point. (E: 2e1758b2cc3820531f7ac7f5f6b3a825)");let p=await xs({timeline:o,metaspace:r,space:n}),h=await ot({...e,src:p,dna:!i,nCounter:!0}),g=h.newIbGib;return await r.persistTransformResult({resTransform:h,space:n}),s&&await Cs({type:s.type,rel8nInfos:[{rel8nName:s.rel8nName,ibGibs:[g]}],metaspace:r,space:n,skipLock:a}),await r.registerNewIbGib({ibGib:g,space:n}),g},"fn");return a?await d():await Ct({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:rt(),fn:d})}catch(l){throw console.error(`${c} ${w(l)}`),l}finally{Fe&&console.log(`${c} complete.`)}}b(Y,"mut8Timeline");async function Ns({ib:o,data:t,rel8ns:e,noDna:r,parentIb:n,parentIbGib:a,metaspace:s,space:i}){let c=`[${Ns.name}]`;try{if(Fe&&console.log(`${c} starting...`),i??=await s.getLocalUserSpace({lock:!1}),!i)throw new Error("(UNEXPECTED) space is required, but is falsy. (E: 252994a554224b17aa9816c7a765c925)");a??=n?a=B.primitive({ib:n}):a=j;let l=await B.firstGen({parentIbGib:a,ib:o,data:t,rel8ns:e,dna:!r,nCounter:!0,squash:!!r,tjp:{timestamp:!0,uuid:!t?.uuid}});return await s.persistTransformResult({resTransform:l,space:i}),await s.registerNewIbGib({ibGib:l.newIbGib,space:i}),l}catch(l){throw console.error(`${c} ${w(l)}`),l}}b(Ns,"createTimeline");async function Gl({ibGib:o,metaspace:t,space:e}){let r=`[${Gl.name}]`;try{if(Fe&&console.log(`${r} starting...`),e??=await t.getLocalUserSpace({lock:!1}),!e)throw new Error("(UNEXPECTED) space is required. (E: c1b9a9b8c7d6e5f4a3b2a1a0b9c8d7e6)");let n=o.rel8ns?.dna??[];if(n.length===0)return[];let a=await t.get({addrs:n,space:e});if(!a.success||(a.ibGibs??[]).length!==n.length){let s=n.filter(i=>!a.ibGibs?.some(c=>y({ibGib:c})===i));throw new Error(`Could not get all dna ibGibs for ${y({ibGib:o})}. Addrs not found: ${s.join(", ")}. Errors: ${a.errorMsg??"[unknown error (E: 92cf95774828d8a978331da859098625)]"} (E: d2c0b1a9a8b7c6d5e4f3a2b1a0b9c8d7)`)}return a.ibGibs}catch(n){throw console.error(`${r} ${w(n)}`),n}}b(Gl,"getDna");async function Hn({timeline:o,getLatest:t,includeDna:e,metaspace:r,space:n}){let a=`[${Hn.name}]`;try{if(Fe&&console.log(`${a} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await r.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: e3d1c0b1a9a8b7c6d5e4f3a2b1a0b9c8)");let s=t?await xs({timeline:o,metaspace:r,space:n}):qe({ibGib:o}),i=y({ibGib:s}),c={},l=e?bn({ibGibs:await Gl({ibGib:s,metaspace:r,space:n})}):void 0,d=o.rel8ns?.past??[];if(d.length===0)return{headIbGib:s,orderedPastIbGibs:[],pastIbGibMap:c,dnaMap:l};let f=await r.get({addrs:d,space:n});if(!f.success||(f.ibGibs??[]).length!==d.length){let h=d.filter(g=>!f.ibGibs?.some(m=>y({ibGib:m})===g));throw new Error(`Could not get all dna ibGibs for ${i}. Addrs not found: ${h.join(", ")}. Errors: ${f.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=bn({ibGibs:f.ibGibs})??{};let p=[];for(let h of d){let g=c[h];if(!g)throw new Error("(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)");p.push(g)}return{headIbGib:s,orderedPastIbGibs:p,pastIbGibMap:c,dnaMap:l}}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{Fe&&console.log(`${a} complete.`)}}b(Hn,"getHistory");async function Ds({timeline:o,getLatest:t,metaspace:e,space:r}){let n=`[${Ds.name}]`;try{return Fe&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await Hn({timeline:o,getLatest:t,includeDna:!1,metaspace:e,space:r})).orderedPastIbGibs.map(i=>y({ibGib:i}))}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Fe&&console.log(`${n} complete.`)}}b(Ds,"getHistoryAddrs");var Xn="sync_sagamsg";async function Os({data:o}){let t=`[${Os.name}]`;try{return[Xn,o.sagaId,o.stage].join(" ")}catch(e){throw console.error(`${t} ${w(e)}`),e}}b(Os,"getSyncSagaMessageIb");async function Ls({frameIbGib:o,space:t}){let e=`[${Ls.name}]`;try{let n=(await ka({ibGib:o,rel8nNames:[Re],space:t}))[Re];if(!n||n.length===0)throw new Error(`(UNEXPECTED) No sync message stone found found for frame: ${o.ib} (E: 8a4b2c1d3e5f6a9b7c8d9e0f1a2b3c4d)`);if(n.length>1)throw new Error(`(UNEXPECTED) Multiple sync message stones found (${n.length}) for frame: ${o.ib}. logic not currently equipped to handle multiple messages per frame. (E: 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d)`);return n[0]}catch(r){throw console.error(`${e} ${w(r)}`),r}}b(Ls,"getSyncSagaMessageFromFrame");var qn="anon_fn",vl={fnHash:""};var Cl=!1;function Ps({data:o}){let t=`[${Ps.name}]`;try{if(Cl&&console.log(`${t} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!o?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${qn} ${o.fnHash}`}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Cl&&console.log(`${t} complete.`)}}b(Ps,"getAnonymousFnIb");var hr=class{static{b(this,"AnonymousFnWitness_V1")}fn;ib=qn.concat();gib=z;data=U(vl);rel8ns;constructor(t){if(this.fn=t,!t)throw new Error("fn required (E: b1e1478f466a2a347b75e7c336f8d323)")}async witness(t){return this.data.fnHash=await _e({s:this.fn.toString()}),this.ib=Ps({data:this.data}),this.gib=await ce({ibGib:this}),this.fn(t)}};var Yn=!1;function Ob({err:o}){let t=`[${Ob.name}]`;try{if(Yn&&console.log(`${t} starting... (I: 96f8b767c50f24768ced7beebb291723)`),mo(o)){let e=o;if(!o.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(qt({ibGib:o}))return o.data.raw;throw new Error("(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)")}else return w(o)}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Yn&&console.log(`${t} complete.`)}}b(Ob,"extractObsErrMsg");function Rs(o){let t=`[${Rs.name}]`;try{Yn&&console.log(`${t} starting... (I: 3d2c3658a0fda83ece1f2b095a365823)`);let e;if(typeof o=="function"?e={next:o}:e=o,!e.next)throw new Error("observer.next required (typeof observerOrFn !== 'function') (E: da944e93b32ab5918f11751bcd651823)");let r=b(async d=>(await e.next(d),j),"fnNext"),n=b(async d=>(d.ib==="complete"?e.complete&&await e.complete():qt({ibGib:d})?e.error&&await e.error(d):await e.next(d),j),"fnWitness"),a=new hr(r),s=new hr(n),i={ib:"observer",witness:b(async d=>await s.witness(d),"witness"),next:b(async d=>{await a.witness(d)},"next")},c=e.error??(async d=>{let f;if(typeof d=="string")f=w(d);else if(d.ib)if(qt({ibGib:d}))f=w(d.data.raw);else throw new Error(`${t} (UNEXPECTED) first off, observer.error is falsy. secondly, error came down pipeline and has an "ib" property but is not an ErrorIbGib_V1? (E: 0a2a46b9620b4a6a84c7ba1100da537b)`);else d instanceof Error?f=w(d):typeof d.message=="string"?f=w(d.message):f="[unknown thing came down pipe that ain't an error]";console.error(`Error occurred but observer.error is falsy. error: ${f} (E: 822c60c7c4d542efacd5c2dea7e88062)`)}),l=new hr(async d=>(c(d),j));if(i.error=async d=>{typeof d=="string"?d=await Nr({rawMsg:d}):d instanceof Error&&(d=await Nr({rawMsg:d.message}));try{await l.witness(d)}catch{e.error?console.error(`${t} there was another error when executing errorAnonFnWitness.witness (wrapper of caller's observer.error) trapping this. (E: 8fa3c4e633df4491a82951e3b677d9a9)`):console.error(`${t} there was another error when executing errorAnonFnWitness.witness (caller's observer.error was falsy). trapping this. (E: f5ff2db0d762487287139a4175eb7689)`)}},e.complete){let d=e.complete,f=new hr(async p=>(await d(),j));i.complete=async()=>{try{await f.witness(j)}catch(p){console.error(`${t} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${w(p)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return i}catch(e){throw console.error(`${t} ${e.message}`),e}finally{Yn&&console.log(`${t} complete.`)}}b(Rs,"fnObs");var Wn=!1,Bs=class{static{b(this,"KeystoneConfigBuilderBase")}_id;_salt;_size;_replenish;_seq;_rand;_verbs=[];_targetBinding;withId(t){return this._id=t,this}withSalt(t){return this._salt=t,this}withSize(t){return this._size=t,this}withTargetBinding(t){return this._targetBinding=t,this}withFIFO(t){return this._seq=t,this._rand=0,this}withRandom(t){return this._seq=0,this._rand=t,this}withHybrid({seqCount:t,randCount:e}){return this._seq=t,this._rand=e,this}withReplenishStrategy(t){return this._replenish=t,this}buildBehavior(){if(this._size===void 0)throw new Error("size required (E: 68320865d9adb8477836485b20b08826)");if(this._replenish===void 0)throw new Error("replenish strategy required (E: 9f8798d1a568763a282e53c89185b826)");if(this._seq===void 0)throw new Error("sequential required (E: e0da08a24e9790d0a8c1a9322f8eb826)");if(this._rand===void 0)throw new Error("selectRandomly required (E: 7721d84d1a8b7d020d0ab33c3f811426)");if(this._targetBinding===void 0)throw new Error("targetBinding required (E: 9add64d7e8e8cba01d901727a8e9b826)");return{size:this._size,replenish:this._replenish,selectSequentially:this._seq,selectRandomly:this._rand,targetBindingCount:this._targetBinding}}forVerbs(t){return this._verbs=t,this}},ks=class o extends Bs{static{b(this,"KeystoneConfigBuilder_HashV1")}lc=`[${o}]`;_algo;_rounds;withHash({algo:t,rounds:e}){let r=`${this.lc}[${this.withHash.name}]`;try{return Wn&&console.log(`${r} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=t,this._rounds=e,this}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{Wn&&console.log(`${r} complete.`)}}build(){let t=`${this.lc}[${this.build.name}]`;try{if(Wn&&console.log(`${t} starting... (I: 5df568c63c4993bb98df0a319ee16826)`),!this._id)throw new Error("id required (E: b50d082adf38bcbf463552f80d2c3226)");if(!this._salt)throw new Error("salt required (E: b0f1926657b8d7d3a88fb9385ead5826)");if(!this._algo)throw new Error("algorithm required (E: cff228f9898fd6383ef752088dae6826)");if(this._rounds===void 0)throw new Error("rounds required (E: eb72580f3b014cda18cba3e399683c26)");return{id:this._id,type:bt.hash_reveal_v1,salt:this._salt,allowedVerbs:this._verbs,behavior:this.buildBehavior(),algo:this._algo,rounds:this._rounds}}catch(e){throw console.error(`${t} ${w(e)}`),e}finally{Wn&&console.log(`${t} complete.`)}}},xo=class{static{b(this,"KeystoneConfig")}static hash(){return new ks}};function Ms(o){if(o.type&&o.type!==bt.hash_reveal_v1)throw new Error(`invalid type (${o.type}). Only ${bt.hash_reveal_v1} currently implemented. (E: c38616cd7a459149f670418f88766526)`);let{salt:t,id:e,size:r,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:l,hashRounds:d}=o;return xo.hash().withId(e).withSalt(t).withSize(r??Gc).withHybrid({seqCount:n??vc,randCount:a??Cc}).withTargetBinding(s??xc).withReplenishStrategy(i??Nc).withHash({algo:l??Dc,rounds:d??Oc}).forVerbs(c??[]).build()}b(Ms,"createStandardPoolConfig");function Lb(o){if(o.type&&o.type!==bt.hash_reveal_v1)throw new Error(`invalid type (${o.type}). Only ${bt.hash_reveal_v1} currently implemented. (E: 09c1f7772bd2a7910f5562b4934d3826)`);let{salt:t,id:e,size:r,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:l,hashRounds:d}=o;return xo.hash().withId(e).withSalt(t).withSize(r??Lc).withHybrid({seqCount:n??Pc,randCount:a??Rc}).withTargetBinding(s??Bc).withReplenishStrategy(i??kc).withHash({algo:l??Mc,rounds:d??Uc}).forVerbs(c??[]).build()}b(Lb,"createHighSecurityPoolConfig");function xl(o){return Lb({...o,id:o.id??Xt,verbs:o.verbs??[Qa.MANAGE]})}b(xl,"createManagePoolConfig");function Nl({template:o,salt:t}){let e=o.behavior;return xo.hash().withId(o.id).withSalt(t).withSize(e.size).withHybrid({seqCount:e.selectSequentially,randCount:e.selectRandomly}).withTargetBinding(e.targetBindingCount).withReplenishStrategy(e.replenish).withHash({algo:o.algo,rounds:o.rounds}).forVerbs(o.allowedVerbs).build()}b(Nl,"createPoolConfigFromJson");var D=!0,zn=!0,it="[ControlDomain]",Ne=class o{static{b(this,"SyncSagaCoordinator")}lc=`[${o.name}]`;constructor(){}defaultSessionConnectPoolConfig(){return Ms({id:wt,salt:`session-connect-${Date.now()}`,verbs:[or],size:20,sequential:2,random:2,targetBinding:0,replenishStrategy:$e.deleteAll})}defaultSessionSyncPoolConfig(){return Ms({id:_r,salt:`session-sync-${Date.now()}`,verbs:[Pe],size:200,sequential:3,random:3,targetBinding:3,replenishStrategy:$e.topUp})}async sync({peer:t,domainIbGibs:e,senderIdentityInfo:r,fnSenderSecret:n,conflictStrategy:a=st.abort,metaspace:s,localSpace:i}){let c=`${this.lc}[${this.sync.name}]`;if(D&&console.log(`${c} starting...`),!i){debugger;throw new Error(`${c} source (or localSpace) required (E: 25df3761f7686a1099a552f83c95d326)`)}if(r||n){if(!r)throw new Error("(UNEXPECTED) senderIdentityInfo falsy but fnSenderSecret truthy? if either is used, both must be truthy. (E: e366628a4919c7d727d2cbd8e5b75e26)");if(!n)throw new Error("(UNEXPECTED) fnSenderSecret falsy but senderIdentityInfo truthy? if either is used, both must be truthy. (E: 7d55ce37ae482fec48e3398158161926)");let{senderIdentity:_,senderDomainAddr:$}=r;if(!_)throw new Error("(UNEXPECTED) senderIdentity falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: a3c17fae2978926d)");if(!$)throw new Error("(UNEXPECTED) senderDomainAddr falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: d288fae39b7d825c)")}let{senderIdentity:l,senderDomainAddr:d}=r??{},f=await V(),p=await Un();if(!p.next)throw new Error("(UNEXPECTED) updates$.next falsy? (E: d24cd82184aec130c89a320819b39126)");let h,g,m=new Promise((_,$)=>{h=_,g=$}),E=await nl(),S=await s.createNewLocalSpace({opts:{allowCancel:!1,spaceName:E,getFnPrompt:s.getFnPrompt,logalot:D}});if(!S)throw new Error("Failed to create temp space (E: 8f4e2f3d6c1b4b1a8f4e2f3d6c1b4b1a)");await S.initialized;let A=b(async()=>{},"cleanup");return(async()=>{try{let _=e?e.map(I=>y({ibGib:I})):void 0;t.setOptionalOpts({sagaId:f,senderIdentity:l,senderDomainAddr:d,fnSenderSecret:n,sessionConnectPoolConfig:this.defaultSessionConnectPoolConfig(),sessionSyncPoolConfig:this.defaultSessionSyncPoolConfig(),targetAddrs:_}),await t.establishSessionIdentity(),await t.connect({sagaId:f});let{initFrame:$,initDomainGraph:T}=await this.createInitFrame({sagaId:f,domainIbGibs:e,conflictStrategy:a,metaspace:s,localSpace:i,tempSpace:S,peer:t});if(await this.executeSagaLoop({initFrame:$,initDomainGraph:T,peer:t,updates$:p,localSpace:i,tempSpace:S,metaspace:s}),h(),!p.complete)throw new Error("(UNEXPECTED) updates$.complete falsy? (E: d24cd82184aec130c89a320819b39126)");p.complete()}catch(_){if(console.error(`${c} ${w(_)}`),g(_),!p.error)throw new Error("(UNEXPECTED) updates$.error falsy? (E: 392ce77c073272e4c398c3e86583ce26)");p.error(_)}finally{await A()}})(),{sagaId:f,updates$:p,done:m}}async continueSync({sagaContext:t,mySpace:e,myTempSpace:r,metaspace:n,peer:a}){let s=`${this.lc}[${this.continueSync.name}]`;try{D&&console.log(`${s} starting... (I: f64e08bf77d1425378601f380384ec26)`);let i=await this.handleResponseSagaContext({sagaContext:t,mySpace:e,myTempSpace:r,metaspace:n});if(i){if(i.nextFrameInfo?.sagaComplete)return null}else return D&&console.log(`${s} Handler returned null (Saga End). (I: 43da8bb6c846b1fe7766332643be0e26)`),null;if(i.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${i.errorMsg} (E: 7b41a183cf3cb58a5859c803800cf826)`);if(!i.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: 5740542f5eb8ccb41dfec188d87c1e26)");let{frame:c,payloadIbGibsDomain:l}=i.nextFrameInfo,d=await this.createSyncSagaContext({sagaFrame:c,localSpace:e,payloadIbGibsDomain:l,metaspace:n,sessionIdentityAddr:t.rel8ns?.sessionIdentity?.[0],peer:a,skipSign:!0}),f=await fr({context:d});if(f.length>0)throw new Error(`(UNEXPECTED) just created sync saga context () and there were immediateValidationErrors? immediateValidationErrors: ${f} (E: c120e8e0aa98673d685267a8a36e5826)`);return d}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{D&&console.log(`${s} complete.`)}}async executeSagaLoop({initFrame:t,initDomainGraph:e,peer:r,updates$:n,localSpace:a,tempSpace:s,metaspace:i}){let c=`${this.lc}[${this.executeSagaLoop.name}]`,l=t,d=[];for(;l;){let f=new Map,p=`${c}[peer.payloadIbGibsDomainReceived$]`,h=await r.payloadIbGibsDomainReceived$.subscribe(Rs({next:b(async g=>{D&&console.log(`${p} next fired. (I: 2b4bdf502a38a90ba33d9711e7cb7826)`);let m=y({ibGib:g});zn&&console.log(`${c}${it} DOMAIN STREAM RECEIVED <- observable: ${m} (I: d69ee80fcaece272483ec33b2d289826)`),f.set(m,g)},"next"),error:b(async g=>{mo(g)?console.error(`${p} error fired. error: ${JSON.stringify(g.data)} (E: 01cc08ba05ad99682831174fd7c31a26)`):(console.dir(g),console.error(`${p} error fired. error: ${w(g)} (E: 73d3d61464e8e4ce4cd6efd8b9675826)`))},"error"),complete:b(async()=>{D&&console.log(`${p} complete fired. (I: a47218aa9e4433fdb97c068880a45826)`),await h.unsubscribe()},"complete")}));try{let g=await this.createSyncSagaContext({sagaFrame:l,payloadIbGibsDomain:d,localSpace:a,metaspace:i,sessionIdentityAddr:r.currentSessionIdentityAddr,peer:r});if(zn){let I=d.map(G=>y({ibGib:G}));console.log(`${c}${it} SENDER TRANSMIT -> peer.witness (I: 5b0081803698770f0bf64992220b312)`),console.log(`${c}${it} Context: ${y({ibGib:g})}`),console.log(`${c}${it} Frame: ${y({ibGib:l})}`),console.log(`${c}${it} DOMAIN Payloads (${I.length}): ${I.join(", ")||"(none)"}`)}n.next(g),r.setOptionalOpts({localSpace:a,localTempSpace:s});let m=await r.witness(g);if(!m)if(l)if((await Ls({frameIbGib:l,space:a}))?.data?.stage===de.commit){D&&console.log(`${c} Sender sent Commit. Peer returned no response. Saga Complete. (I: 26f9ee073858ca78b8284753368b5226)`),l=null;break}else throw new Error("(UNEXPECTED) responseCtx falsy and currentFrame truthy, but we're not in the commit stage? This may be expected ultimately, but atow I am not seeing this as being expected. (E: cc34498962bd370deeff351fac939f26)");else throw new Error("(UNEXPECTED) no response and currentFrame falsy? (E: 8d1085ea2f28cfc3f9c922649864a826)");if(!m.data)throw new Error("(UNEXPECTED) responseCtx.data falsy? (E: a969992bae53ab18a827ec58aec15826)");n.next(m);let E=await fr({context:m});if(E.length>0)throw new Error(`contextAndSagaFrameValidationErrors: ${E} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`);let S=await this.validateReturnContext({requestCtx:g,responseCtx:m,localSpace:a});if(S.length>0)throw new Error(`validateReturnContext errors: ${S.join(", ")} (E: cb8a023b9d0728cceb09fa3da0bb8226)`);let A=m.data[ns]||[];if(A.length>0&&(m.payloadIbGibsDomain=await this.pollForDomainPayloads({expectedAddrs:A,pollIntervalMs:20,domainPayloadsMap:f,tempSpace:s})),!m.sagaFrame)throw new Error("(UNEXPECTED) responseCtx.sagaFrame falsy? the Peer should have set this when it got the response back from the remote. (E: e650adadf9a2063ec6764a1e31d3d826)");if(zn){let I=m.data?.["@payloadAddrsControl"]||[];console.log(`${c}${it} SENDER RECEIVED <- peer.witness (I: 3dc76a9744d89a4fc3e2f076c2be4826)`),console.log(`${c}${it} Response Context: ${y({ibGib:m})}`),console.log(`${c}${it} Response Saga Frame: ${y({ibGib:m.sagaFrame})}`),console.log(`${c}${it} CONTROL Payloads (${I.length}): ${I.join(", ")||"(none)"}`),console.log(`${c}${it} DOMAIN Payloads (${A.length}): ${A.join(", ")||"(none)"}`)}let _=await this.handleResponseSagaContext({sagaContext:m,initDomainGraph:e,mySpace:a,myTempSpace:s,metaspace:i});if(_){if(_.nextFrameInfo?.sagaComplete){D&&console.log(`${c} Handler returned null (Saga End). (I: 123bf9e7dca8886de72553a8d4f29e26)`);break}}else{console.error(`${c} NAG ERROR (DOES NOT THROW): does this ever hit now? (E: e04d02efc2a8e72a88b79f1f0f95ca26)`);break}if(_.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${_.errorMsg} (E: c948e81d513b2a0eb8b8afa878edc626)`);if(!_.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: c287a82e823e662a77923278e2418826)");let{frame:$,payloadIbGibsDomain:T}=_.nextFrameInfo;if(l=$,d=[...T||[]],zn){let I=d.map(G=>y({ibGib:G}));console.log(`${c}${it} HANDLER RESULT -> next iteration (I: 6b0d88c4c28857ccd812381515bd7826)`),console.log(`${c}${it} Next Frame: ${y({ibGib:l})}`),console.log(`${c}${it} DOMAIN for next (${I.length}): ${I.join(", ")||"(none)"}`)}}finally{await h.unsubscribe()}}}async createSyncSagaContext({sagaFrame:t,payloadIbGibsDomain:e,metaspace:r,localSpace:n,sessionIdentityAddr:a,peer:s,skipSign:i}){let c=`[${this.createSyncSagaContext.name}]`;try{if(D&&console.log(`${c} starting... (I: 6b87bee313e811d1d2fc90e87fbec826)`),!t.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 04c49b4cccba6842a8b52e4c6f570726)");if(!t.data.n&&t.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 45b508da64a8b28428b11765d684b826)");let l=new Date,d=Ce(l),f=l.getMilliseconds(),p={timestamp:d,timestampMs:f,sagaN:t.data.n},h=e?e?.map(T=>y({ibGib:T})):void 0;h&&h.length>0&&(p[ns]=h);let g={sagaFrame:[y({ibGib:t})]},m;if(a){a=await r.getLatestAddr({addr:a,space:n})??a;let T=await W({addr:a,space:n});if(T.success&&T.ibGibs?.length===1)m=T.ibGibs[0],g.sessionIdentity=[a];else{debugger;throw new Error(`Couldn't get sessionIdentityAddr (${a}) in space: ${n.ib} (E: 5c29e80d68dbd1749866c358be093826)`)}}let E=await As({data:p}),S=await B.stone({parentPrimitiveIb:Fn,ib:E,data:p,rel8ns:g}),A=y({ibGib:S}),_;m&&!i&&(_=await s.signContext({contextAddr:A})),await Xe({ibGib:S,space:n}),await Te({ibGib:S,space:n,fnBroadcast:void 0}),S.sagaFrame=t;let{msgStones:$}=await yn({sagaIbGib:t,localSpace:n});if($.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)");return S.sagaFrameMsg=$[0],e&&e.length>0&&(S.payloadIbGibsDomain=e),_&&(S.signedSessionIdentity=_),S}catch(l){throw console.error(`${c} ${w(l)}`),l}finally{D&&console.log(`${c} complete.`)}}async getKnowledgeMap({space:t,metaspace:e,domainIbGibs:r,tjpAddrs:n}){let a=`${this.lc}[${this.getKnowledgeMap.name}]`;try{if(D&&console.log(`${a} starting... (I: e184f8a7818666febfbbd2d841ed3826)`),!(r&&r.length>0)&&!(n&&n.length>0))throw new Error("(UNEXPECTED) domainIbGibs and tjpAddrs falsy/empty? we need one or the other (E: f674285111c8648398cd79d8c08ec826)");if(r&&r.length>0&&n&&n.length>0)throw new Error("(UNEXPECTED) both domainIbGibs and tjpAddrs truthy? only pass in one or the other. (E: f674285111c8648398cd79d8c08ec826)");let s=[];if(n)s=n;else if(r&&r.length>0){let{mapWithTjp_YesDna:c,mapWithTjp_NoDna:l}=Nt({ibGibs:r}),d=[...Object.values(c),...Object.values(l)],f=ft({ibGibs:d});s=Object.keys(f)}else return console.warn(`${a} No domainIbGibs or tjpAddrs provided. Returning empty Knowledge. (W: 2b0e115e7578a83d1b26f7c726bf9426)`),{};if(s.length===0)return{};let i=await Me({space:t,tjpAddrs:s});if(!i.data||!i.data.latestAddrsMap)throw new Error(`${a} Failed to get latest addrs. (E: 7d395940c0e1419165c5196c39c6c826)`);return i.data.latestAddrsMap}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{D&&console.log(`${a} complete.`)}}async analyzeDomainIbGibs({domainIbGibs:t,space:e}){let r=`${this.lc}[${this.analyzeDomainIbGibs.name}]`;if(t.length===0)throw new Error("invalid domainIbGibs. expected at least one, but array is empty. (E: 820a719bcac5a16878a2af697113b826)");let n=await Ot({ibGibs:t,live:!0,space:e}),a=n&&Object.keys(n).length>0;D&&console.log(`${r} graph generated. nodes: ${a?Object.keys(n).length:0}`);let s=a?Object.values(n):[],{mapWithTjp_YesDna:i,mapWithTjp_NoDna:c,mapWithoutTjps:l}=Nt({ibGibs:s}),d=Object.values(l),f=[...Object.values(i),...Object.values(c)],p=ft({ibGibs:f}),h=this.sortTimelinesTopologically(p);return{stones:d,timelinesMap:p,topologicallySortedTjpAddrs:h,fullGraph:n}}async createInitFrame({sagaId:t,domainIbGibs:e,conflictStrategy:r,metaspace:n,localSpace:a,tempSpace:s,peer:i}){let c=`${this.lc}[${this.createInitFrame.name}]`;try{D&&console.log(`${c} starting... (I: 551af8b411ae9be712ce3358d43ee726)`);let l=await this.analyzeDomainIbGibs({domainIbGibs:e,space:a}),{timelinesMap:d,fullGraph:f,stones:p}=l;await Xe({ibGibs:Object.values(f),space:s});let h={};Object.keys(d).forEach(S=>{let _=d[S].at(-1);h[S]=y({ibGib:_})});let g={sagaId:t,stage:de.init,knowledgeMap:h,mode:as.sync,stones:p.map(S=>y({ibGib:S}))};D&&(console.log(`${c} SyncStage.init: ${de.init}, SyncStage.commit: ${de.commit}`),console.log(`${c} initData.stage: ${g.stage}`));let m=await this.createSyncMsgStone({data:g,localSpace:a,metaspace:n}),E=await this.evolveSyncSagaIbGib({msgStones:[m],conflictStrategy:r,metaspace:n,localSpace:a,sessionIdentity:i.currentSessionIdentity});return D&&console.log(`${c} sagaFrame (init): ${F(E)} (I: b3d6a8be69248f18713cc3073cb08626)`),{initFrame:E,initDomainGraph:f}}catch(l){throw console.error(`${c} ${w(l)}`),l}finally{D&&console.log(`${c} complete.`)}}async validateReturnContext({requestCtx:t,responseCtx:e,localSpace:r}){let n=`${this.lc}[${this.validateReturnContext.name}]`,a=[];try{if(t.sagaFrame&&e.sagaFrame){let c=y({ibGib:t.sagaFrame}),l=y({ibGib:e.sagaFrame});await zr({olderAddr:c,newerAddr:l,space:r})||a.push(`Response saga frame (${l}) is not a valid continuation of request saga frame (${c}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`)}else a.push("Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)");let s=t.signedSessionIdentity?y({ibGib:t.signedSessionIdentity}):t.rel8ns?.sessionIdentity?.[0],i=e.rel8ns?.sessionIdentity?.[0];s!==i&&a.push(`Session identity mismatch. Expected ${s}, got ${i}. (E: ab98716bca88d2243cc822187768226)`)}catch(s){a.push(`Error during validateReturnContext: ${w(s)} (E: da878e1239aa88ee27bdfca005c28226)`)}return a}async pollForDomainPayloads({expectedAddrs:t,pollIntervalMs:e,domainPayloadsMap:r,tempSpace:n}){let a=`${this.lc}[${this.pollForDomainPayloads.name}]`;try{D&&console.log(`${a} starting... (I: 26dce86bfca572939885798802d6e926)`);let s=[],i=[...new Set(t)],c=[...i],l=Date.now(),d=5*60*1e3;for(;c.length>0;){if(Date.now()-l>d)throw new Error(`Timeout waiting for payloads: ${c.join(", ")} (E: 46e1683c9578095261aaf798bd5e1826)`);let f=[],p=[];for(let h of c)r.has(h)?(p.push(r.get(h)),r.delete(h)):f.push(h);p.length>0&&(await Xe({space:n,ibGibs:p}),p.forEach(h=>s.push(h))),c=f,c.length>0&&await Se(e)}if(i.length!==s.length)throw new Error("(UNEXPECTED) uniqueExpectedAddrs.length !== resultDomainPayloads.length? at this point, we expect all of the payload ibgibs to have been received. (E: 03749a7478c4b8b28bfc86951887a826)");return s}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{D&&console.log(`${a} complete.`)}}async handleResponseSagaContext({sagaContext:t,initDomainGraph:e,mySpace:r,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleResponseSagaContext.name}]`;try{D&&console.log(`${s} starting... (I: 5deec8a1f7a6d263c88cd458ad990826)`);let i=t.sagaFrame;if(!i.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 71b938adf1d87c2527bfd4f86dfd0826)");D&&console.log(`${s} sagaIbGib: ${F(i)} (I: 1b99d87d262e9d18d8a607a80b1a0126)`);let{stage:c,messageData:l}=await this.getStageAndPayloadFromFrame({sagaFrame:i,space:r});D&&console.log(`${s} handling frame stage: ${c}`);let d;switch(c){case de.init:d=await this.handleInitFrame({sagaIbGib:i,messageData:l,metaspace:a,mySpace:r,myTempSpace:n});break;case de.ack:if(!e)throw new Error("(UNEXPECTED) initDomainGraph falsy on the sender? (E: a3d758ad954829aba88663188eafc826)");d=await this.handleAckFrame({sagaContext:t,sagaIbGib:i,initDomainGraph:e,metaspace:a,mySpace:r,myTempSpace:n});break;case de.delta:d=await this.handleDeltaFrame({sagaContext:t,sagaIbGib:i,metaspace:a,mySpace:r,myTempSpace:n});break;case de.commit:D&&console.log(`${s}[${Zr({sagaFrame:i})}] mySpace.ib: ${r.ib} (I: 5b270996d848907238d817fffa64a126)`),d=await this.handleCommitFrame({sagaIbGib:i,metaspace:a,mySpace:r,myTempSpace:n});break;default:throw new Error(`${s} (UNEXPECTED) Unknown sync stage: ${c} (E: 9c2b4c8a6d34469f8263544710183355)`)}return D&&console.log(`${s} nextFrameInfo: ${d?F(d):"undefined"} (I: a8ad281ca8e89385686d18327a105726)`),{errorMsg:void 0,nextFrameInfo:d}}catch(i){let c=`${s} ${w(i)}`;return console.error(c),{errorMsg:c}}finally{D&&console.log(`${s} complete.`)}}async handleInitFrame({sagaIbGib:t,messageData:e,mySpace:r,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleInitFrame.name}]`;try{D&&console.log(`${s} starting... (I: 9d88dcad0408c029e898a4bcf3b08426)`),D&&console.log(`${s} [TEST DEBUG] Receiver mySpace: ${r.ib}`);let i=e;if(i.stage!==de.init)throw new Error(`${s} Invalid init frame: initData.stage !== SyncStage.init (E: c91be82970e4decc58f56bf8fc1ffc26)`);if(!i||!i.knowledgeMap)throw new Error(`${s} Invalid init frame: missing knowledgeMap (E: ed02c869e028d2d06841b9c7f80f2826)`);let c=t.data.conflictStrategy||st.abort,l=[],d=[],f=[],p=i.stones||[];if(p.length>0){D&&console.log(`${s} processing stones: ${p.length}`);let G=(await W({space:r,addrs:p})).rawResultIbGib;if(!G.data)throw new Error("(UNEXPECTED) rawResultIbGib.data falsy? (E: f3c40b492adc02c3f480b998fc7a5926)");let v=G.data.addrsNotFound;v&&v.length>0&&(D&&console.log(`${s} stones missing (requesting): ${v.length}`),v.forEach(N=>{d.some(O=>O.addr===N)||d.push({addr:N})}))}let h=i.knowledgeMap;D&&console.log(`${s} senderKnowledge: ${F(h)} (I: 9f957862356dfeae183c200854e86e26)`);let g=Object.keys(h);D&&console.log(`${s} [TEST DEBUG] senderTjpAddrs: ${JSON.stringify(g)}`),D&&console.log(`${s} senderTjpAddrs: ${F(g)} (I: 86ea4c53db0dc184c8b253386c402126)`);let m={};if(g.length>0){let I=await Me({space:r,tjpAddrs:g});if(!I.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: b180d813c088042b38e1e02e06a16926)");if(!I.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 16bc386dd51d0ff53a49620b1e641826)");m=I.data.latestAddrsMap,D&&console.log(`${s} [TEST DEBUG] receiverLatestAddrsMap: ${JSON.stringify(m)}`),D&&console.log(`${s} receiverLatestAddrsMap: ${F(m)} (I: 980975642cbccd8018cf0cd808d30826)`)}for(let I of g){let G=h[I],v=m[I];if(!v){D&&console.log(`${s} [TEST DEBUG] Missing receiver timeline for TJP: ${I}. Requesting remoteAddr: ${G}`),d.push({addr:G,tjpAddr:I});continue}if(v===G){D&&console.log(`${s} [TEST DEBUG] TJP ${I}: Synced (receiverTipAddr === remoteAddr)`);continue}if(D&&console.log(`${s} [TEST DEBUG] TJP ${I}: receiverTipAddr=${v}, remoteAddr=${G} - checking for divergence...`),await zr({olderAddr:G,newerAddr:v,space:r})){D&&console.log(`${s} [TEST DEBUG] TJP ${I}: Remote (sender) is in past - offering push`);let O=await Yr({ibGibAddr:v,live:!1,latestCommonFrameAddr:G,space:r});f.push({tjpAddr:I,addrs:Object.keys(O)})}else{let O=!1;try{O=await zr({olderAddr:v,newerAddr:G,space:r})}catch(P){D&&console.log(`${s} expected error if we don't have remote. verbose logging error though: ${w(P)} (I: 47ea08d0b418cf4aa8a502a7bcb80826)`)}if(O)D&&console.log(`${s} [TEST DEBUG] TJP ${I}: receiver is in past - requesting delta`),d.push({addr:G,tjpAddr:I,latestAddrAlreadyHave:v});else if(D&&console.log(`${s} [TEST DEBUG] TJP ${I}: DIVERGENCE DETECTED! conflictStrategy=${c}`),c==="abort")l.push({tjpAddr:I,receiverTipAddr:v,senderTipAddr:G,receiverKnowledgeTimelineAddrs:[],reason:"divergence",terminal:!0});else if(c===st.optimisticWithLCS){let P=await W({addr:v,space:r});if(!P.success||P.ibGibs?.length!==1)throw new Error(`couldn't get local tip (${v}) from space (${r.ib}). errorMsg: ${P.errorMsg??"[unknown error (E: b3c3d823276300aa384ebdba4a8eb826)]"} (E: 83cb88a767e22bbda99c6788bec50526)`);let R=P.ibGibs[0],k=await Ds({timeline:R,space:r,metaspace:a});l.push({tjpAddr:I,receiverTipAddr:v,senderTipAddr:G,receiverKnowledgeTimelineAddrs:[...k,v],reason:"divergence",terminal:!1})}else throw new Error(`${s} Unsupported conflict strategy: ${c}. Only these currently implemented: ${Gr} (E: 8f12384180f8a718a983a749fe0adf26)`)}}if(l.some(I=>I.terminal))throw D&&console.warn(`${s} ABORTING Sync Saga due to terminal conflicts: ${JSON.stringify(l)}`),new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify(l)} (E: f2edbe93cc07a63b38bfc013d2213b26)`);if(!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 24203af4600fb226ae6c1afbde442826)");let A={sagaId:t.data.uuid,stage:de.ack,deltaRequestAddrInfos:d,pushOfferInfos:f};l?.length>0&&(A.conflicts=l);let _=await this.createSyncMsgStone({data:A,localSpace:r,metaspace:a});D&&console.log(`${s} ackStone created: ${F(_)} (I: 313708132dd53ff946befb7833657826)`);let $=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:r,metaspace:a}),T;if(f.length>0){let I=[];T=[];let G=f.flatMap(R=>R.addrs),v=await W({addrs:G,space:r}),N=v.rawResultIbGib?.data;if(!N)throw new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: 1a2cc8cb99a1ffa60837e45a8229b826)");let O=N.addrsNotFound??[],P=N.addrsErrored??[];if(v.ibGibs&&v.ibGibs.length===G.length)v.ibGibs.forEach(R=>{T.push(R)});else if(v.ibGibs&&v.ibGibs.length>0)if(v.ibGibs.forEach(k=>{T.push(k)}),T.length+O.length+P.length===G.length)O.forEach(k=>I.push(k)),P.forEach(k=>I.push(k));else throw O.length===0&&P.length===0?new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored both empty? (E: ef1b2cf5bab8de2298ec507abe04e826)"):new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored don't contain the addrs not found? (E: ae9e015109f8c3c3a813da584cd98826)");else console.warn(`${s} we were expecting all domainAddrs in mySpace (${r.ib}) but we couldn't get all of them. addrsNotFound: ${O??[]}. addrsErrored: ${P??[]}. Trying temp space (${n.ib}). (W: f61908e264f8dddd2e3fb9084463d826)`),G.forEach(R=>I.push(R));if(I.length>0){D&&console.log(`${s} couldn't get all addrs in mySpace (${r.ib}). searchSecondSpaceAddrs: ${I} (I: 233fd954dbd84e51bca02fa8eed5f826)`);let R=await W({addrs:I,space:n});if(R.success&&R.ibGibs&&R.ibGibs.length===I.length)R.ibGibs.forEach(k=>T.push(k));else{R.ibGibs?.forEach(H=>T.push(H));let k=G.filter(H=>!T.map(K=>y({ibGib:K})).includes(H));throw new Error(`couldn't get some or all of addrs from either mySpace (${r.ib}) or myTempSpace (${n.ib}). addrsFailed: ${k} (E: 1394d412c4ffa4dd085f269b43338826)`)}}}return{frame:$,payloadIbGibsDomain:T}}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{D&&console.log(`${s} complete.`)}}async handleAckFrame({sagaContext:t,sagaIbGib:e,initDomainGraph:r,mySpace:n,myTempSpace:a,metaspace:s}){let i=`${this.lc}[${this.handleAckFrame.name}]`;try{D&&console.log(`${i} starting... (I: 605b6860e898267a5b50c6d85704be26)`);let{messageData:c}=await this.getStageAndPayloadFromFrame({sagaFrame:e,space:n}),l=c,d=!0;if(!l)throw new Error(`${i} ackData falsy (E: 3b8415edc876084c88a25b98e2d55826)`);if(l.stage!==de.ack)throw new Error(`${i} Invalid ack frame: ackData.stage !== SyncStage.ack (E: 2e8b0a94b5954a66a6a1a7a0b3f5b7a1)`);if(D&&console.log(`${i} ackData: ${F(l)} (I: b817c5571c5e916fe8f90b892b3e8e26)`),!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: e3f2e8f162484859787651b85c011826)");let f=l.conflicts?U(l.conflicts):[];D&&console.log(`${i} [CONFLICT DEBUG] Received conflicts from Ack: ${f.length}`),D&&f.length>0&&console.log(`${i} [CONFLICT DEBUG] Conflicts detail: ${JSON.stringify(f,null,2)}`);let p=f.filter(I=>I.terminal);if(p.length>0)throw D&&console.warn(`${i} Received terminal conflicts from Ack: ${JSON.stringify(p)}`),new Error(`${i} Peer reported terminal conflicts. (E: 23a0096ee05a2ccfa89334e8f156b426)`);let h=[],g=[];if(f.length>0){D&&console.log(`${i} [CONFLICT DEBUG] Processing ${f.length} non-terminal conflicts`);for(let I of f){let{receiverTipAddr:G,reason:v,senderTipAddr:N,terminal:O,receiverKnowledgeTimelineAddrs:P,tjpAddr:R}=I;if(O)throw new Error("(UNEXPECTED) conflict.terminal truthy? We expect this to already throw/abort the saga before this point in execution. (E: b42e982edca8b1156765de38f9e74626)");let k=r[N];if(!k)throw new Error(`(UNEXPECTED) senderTipIbGib falsy? initDomainGraph should have had the senderTipAddr (${N}) that was included in the ack frame conflicts. tjpAddr: ${R}. reason: ${v} (E: 3bd80f2054a924be98e6a7421bff4626)`);let{headIbGib:H,orderedPastIbGibs:K}=await Hn({timeline:k,getLatest:!0,metaspace:s,space:n}),ye=K.map(fe=>y({ibGib:fe})),ie=y({ibGib:H});if(I.senderKnowledgeTimelineAddrs=[...ye,ie],H.gib!==k.gib&&(I.senderTipAddr=ie,!Object.keys(r).includes(ie))){let fe=await Ot({ibGibAddr:ie,live:!0,space:n}),ht=Object.keys(fe);for(let It of ht)r[It]||(r[It]=fe[It])}let Ke=P.findLast(fe=>ye.includes(fe));if(!Ke)throw new Error(`(UNEXPECTED) no latestCommonFrameAddr in the conflicts.receiverKnowledgeTimelineAddrs (${P.join(`
30
+ `)})? This would mean that it doesn't even have the tjpAddr (${R}). So what are we doing here? (E: 8931d1bdd6d8e100bf55f7c8a6924826)`);let Ye=await Yr({ibGibAddr:ie,live:!0,latestCommonFrameAddr:Ke,space:n}),We=[];if(Object.keys(Ye).forEach(fe=>{We.push(fe);let ht=Ye[fe];h.push(ht)}),Ke===G)D&&console.log(`${i} [CONFLICT DEBUG] TJP ${R}: Fast-forward detected (receiver behind sender). Excluding from active conflicts and sending delta payload.`);else{if(I.accretivePayloadAddrs)throw new Error("(UNEXPECTED) conflict.accretivePayloadAddrs already truthy? This is expected to be falsy at this point in the sync. (E: 6b6b1846779867849cbde208f4374326)");I.accretivePayloadAddrs=We,g.push(I)}}g.length>0?d=!1:d=!0,D&&console.log(`${i} [CONFLICT DEBUG] Finished processing ${f.length} conflicts. Active (divergent) conflicts: ${g.length}. outgoingPayloadIbGibsDomain_conflicts.length (total outgoing payload ibgibs for ALL conflicts): ${h.length}`)}else D&&console.log(`${i} [CONFLICT DEBUG] No optimistic conflicts to process`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:l.deltaRequestAddrInfos||[],mySpace:n}),E=[...h,...m],S;E.length===0?E=void 0:S=E.map(I=>y({ibGib:I}));let A={sagaId:e.data.uuid,stage:de.delta,conflicts:g,payloadAddrsDomain:S,deltaRequestAddrInfos:void 0,proposeCommit:d},_;D&&console.log(`${i} Creating Delta Stone. Data stage: ${A.stage}`);let $=await this.createSyncMsgStone({data:A,rel8ns:_,localSpace:n,metaspace:s}),T=await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[$],localSpace:n,metaspace:s});return D&&console.log(`${i} Delta Frame created. Rel8ns: ${JSON.stringify(T.rel8ns)}`),{frame:T,payloadIbGibsDomain:E}}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{D&&console.log(`${i} complete.`)}}async handleDeltaFrame({sagaContext:t,sagaIbGib:e,mySpace:r,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleDeltaFrame.name}]`;try{D&&console.log(`${s} starting... (I: a1d0a85eb4189466f86dfd61e3df2626)`);let{messageData:i}=await this.getStageAndPayloadFromFrame({sagaFrame:e,space:r}),c=i;if(!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 8874e83e1a1b307938ee832862ec5826)");if(!e.data.conflictStrategy)throw new Error("(UNEXPECTED) sagaIbGib.data.conflictStrategy falsy? (E: 636205ab5b78fcb31d0cb1880770c826)");if(!c)throw new Error(`${s} deltaData falsy (E: 7c28c8d8f08a4421b8344e6727271421)`);if(c.stage!==de.delta)throw new Error(`${s} Invalid delta frame: deltaData.stage !== SyncStage.delta (E: 0c28c8d8f08a4421b8344e6727271421)`);D&&console.log(`${s} deltaData: ${F(c)} (I: a76008681df458cfbcdc4848f825a826)`),D&&console.log(`${s} [CONFLICT DEBUG] deltaData.payloadAddrsDomain count: ${c.payloadAddrsDomain?.length||0}`);let{conflictStrategy:l}=e.data,{deltaRequestAddrInfos:d,payloadAddrsDomain:f,proposeCommit:p}=c,h=c.proposeCommit??!1,g=t.payloadIbGibsDomain??[];D&&console.log(`${s} [CONFLICT DEBUG] Fulfilling ${(c.deltaRequestAddrInfos||[]).length} peer requests`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:c.deltaRequestAddrInfos||[],mySpace:r});D&&console.log(`${s} [CONFLICT DEBUG] Outgoing payload size (with deps): ${m.length}`);let E=c.conflicts?U(c.conflicts):[],S=E.filter(T=>!T.resolved);if(S.length>0){if(l!==st.optimisticWithLCS)throw new Error(`(UNEXPECTED) conflictStrategy (${l}) is not ${st.optimisticWithLCS}? right now, this is the only one we've implemented. (E: ba3e08d92a66b24075016208a0f83226)`);for(let T of S){let I={};for(let be of T.accretivePayloadAddrs??[]){let ut=g.find(_t=>y({ibGib:_t})===be);if(!ut)throw new Error("(UNEXPECTED) conflictPayloadIbGib falsy? At this time in dev (01/27/2026), we're expecting this to be populated because we're only expecting one iteration of conflict resolution. If dev is later, this may no longer be the case. (E: b197417e762639089827aa3edaece826)");I[be]=ut}T.latestCommonFrameAddr;let{receiverKnowledgeTimelineAddrs:G,senderKnowledgeTimelineAddrs:v,reason:N,receiverTipAddr:O,senderTipAddr:P,tjpAddr:R}=T;if(!v)throw new Error("(UNEXPECTED) senderKnowledgeTimelineAddrs falsy? (E: 2a608892d11bd848e8f0c7a8d676d826)");let k=await Ot({ibGibAddrs:[O],live:!0,space:r}),H=Object.values(k);await _n({ibGibs:H,space:n});for(let be of G){let ut=k[be];await Te({ibGib:ut,space:n})}let K=v.findLast(be=>G.includes(be));if(!K)throw new Error("(UNEXPECTED) latestCommonFrameAddr falsy? how we can have a conflict without a common point in history? (E: 53de0a181838b3e5bf98d0887994b826)");let ye=await Yr({ibGibAddr:T.receiverTipAddr,latestCommonFrameAddr:K,live:!0,space:r});Object.values(ye).forEach(be=>m.push(be));let ie=await cs({conflictStrategy:l,timelineAddrsA:v,timelineAddrsB:G,latestCommonFrameAddr:K,ibGibReadCache:I,space:n}),{dnasCreatedInGraft:Ke,dnasReplayed:Ye,intermediateIbGibsCreatedInGraft:We,newGraftTip:ct,graftInfoCreated:fe}=ie;if(T.createdDnaAddrs=Ke.map(be=>y({ibGib:be})),T.replayedDnaAddrs=Ye.map(be=>y({ibGib:be})),T.createdDomainAddrs=[...We.map(be=>y({ibGib:be})),y({ibGib:fe}),y({ibGib:ct})],!ct.rel8ns)throw new Error("(UNEXPECTED) newGraftTip.rel8ns falsy? we expect this to have graftinfo rel8ns, let alone dna (E: 718788f5a44e815618ac1ba621c8a826)");let ht=ct.rel8ns[yt];if(!ht||ht.length===0)throw new Error(`(UNEXPECTED) newGraftTip.rel8ns.${yt} falsy/empty? we expect to always have graft info attached to timelines that are grafted. (E: 45abf31654c8aa517df4d0882b996826)`);T.graftInfoAddr=ht.at(-1);let It=[Ke,Ye,We,[fe,ct]];for(let be of It.flat())if((await le({ibGib:be})??[]).length>0){console.dir(be);debugger;console.log(F(be))}T.accretivePayloadAddrs??=[],It.forEach(be=>be.forEach(ut=>{let _t=y({ibGib:ut});T.accretivePayloadAddrs.includes(_t)||T.accretivePayloadAddrs.push(_t),m.some(Lr=>y({ibGib:Lr})===_t)||m.push(ut)})),T.resolved=!0}}let A=[],_=m.length>0,$=A.length>0;if(_||$){let T={sagaId:c.sagaId,stage:de.delta,payloadAddrsDomain:m.map(v=>y({ibGib:v})),requests:$?A:void 0,conflicts:E},I=await this.createSyncMsgStone({data:T,localSpace:r,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[I],localSpace:r,metaspace:a}),payloadIbGibsDomain:m}}else if(h){let T=await Jr({sagaIbGib:e,space:r}),I=await In({history:T});return I.length>0?{frame:await this.createCommitFrame({sagaIbGib:e,errors:I,metaspace:a,mySpace:r})}:(await this.executeLocalCommit({sagaHistory:T,deltaFrame:e,localTempSpace:n,localSpace:r,metaspace:a}),{frame:await this.createCommitFrame({sagaIbGib:e,errors:void 0,metaspace:a,mySpace:r})})}else{let T={sagaId:c.sagaId,stage:de.delta,proposeCommit:!0,conflicts:E},I=await this.createSyncMsgStone({data:T,localSpace:r,metaspace:a}),G=await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[I],localSpace:r,metaspace:a});if(c.proposeCommit){D&&console.log(`${s} Peer proposed commit. Accepting & Committing.`);let v={sagaId:c.sagaId,stage:de.commit,success:!0},N=await this.createSyncMsgStone({data:v,localSpace:r,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:G,msgStones:[N],localSpace:r,metaspace:a})}}return{frame:G,payloadIbGibsDomain:m}}}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{D&&console.log(`${s} complete.`)}}async executeLocalCommit({deltaFrame:t,commitFrame:e,sagaHistory:r,metaspace:n,localSpace:a,localTempSpace:s}){let i=`${this.lc}[${this.executeLocalCommit.name}]`;try{if(D&&console.log(`${i} starting... (I: 6734980446b86a63c1af6e2e206de826)`),!t&&!e)throw new Error("(UNEXPECTED) !deltaFrame && !commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: 10cae319a2685a672866f5583514e326)");if(t&&e)throw new Error("(UNEXPECTED) deltaFrame && commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: b9037b1ed6d8684ac8a5d01328bad826)");let l=!!t?t:e;if(!l)throw new Error("(UNEXPECTED) !currentFrame? something wrong with my logic. (E: 4ec0ce6625cc1d677bc902c839ca1a26)");let d=Zr({sagaFrame:l});if(D&&console.log(`${i} currentFrameOrigin: ${d} (I: 3add8f8390c89743ae554bd3cc60b826)`),!l.data)throw new Error("(UNEXPECTED) currentFrame.data falsy? (E: a8be68d48668d93d992d793834823826)");let f=[],p=b(_=>{f.includes(_)||f.push(_)},"fnAddPayloadAddr"),h=r.filter(_=>{let $=Zr({sagaFrame:_.sagaIbGib});return d!==$});r.filter(_=>{let $=Zr({sagaFrame:_.sagaIbGib});return d===$}).forEach(_=>{if(!_.sagaIbGib.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 34d7f8cdee14717ce828878d98f89826)");_.msgStones.forEach($=>{if(!$.data)throw new Error("(UNEXPECTED) msgStone.data falsy? (E: 21406101f91847514cc759c8a7382f26)");if($.data.stage===de.ack){let T=$.data;T.pushOfferInfos&&T.pushOfferInfos.length>0&&T.pushOfferInfos.forEach(I=>{I.addrs.forEach(G=>p(G))})}else if($.data.stage===de.delta){let T=$.data;T.payloadAddrsDomain&&T.payloadAddrsDomain.length>0&&T.payloadAddrsDomain.forEach(I=>p(I))}})}),D&&console.log(`${i}[${d}] allPayloadAddrsDomainTransferred: ${f.length>0?f.join(", "):"none"} (I: a1950eb3ca95bdc9ec18a4b8823e9826)`);let m=[];if(f.length>0){let _=await W({addrs:f,space:s});if(_.success&&_.ibGibs&&_.ibGibs.length===f.length)m=_.ibGibs.concat();else{if(!_.rawResultIbGib)throw new Error("(UNEXPECTED) !resGetAllTransferred.rawResultIbGib falsy? (E: dc6cf8729668f4fbe8c024f887d97a26)");let{addrsNotFound:$,addrsErrored:T,errors:I}=_.rawResultIbGib.data;throw new Error(`(UNEXPECTED) we couldn't get all addrs transferred throughout the saga from the tempspace (${s.ib})? addrsNotFound: ${$??[]}. addrsErrored: ${T??[]}. errors: ${I??[]}(E: 222e341e634862b4d88ae7282584d826)`)}}let E=[],S=await Sn({sagaHistory:r});if(S)for(let _ of S){if(!_.resolved)throw new Error("(UNEXPECTED) finalConflict.resolved falsy? right now, we're expecting to resolve all conflicts. (E: a40ca8f1f54665407892ec21123a4f26)");if(!_.graftInfoAddr)throw new Error("(UNEXPECTED) finalConflict resolved but graftInfoAddr falsy? we're expecting all resolved conflicts to have a graftInfoAddr (E: d082488347570947b82008a835200126)");if(!(await at({addrs:[_.graftInfoAddr],space:s})).at(0))throw new Error(`(UNEXPECTED) couldn't get finalConflictGraftInfo from localTempSpace (${s})? (E: 35e3c8130608d991e8fb295807812826)`);let{createdDnaAddrs:I,replayedDnaAddrs:G,createdDomainAddrs:v}=_;if(!I||I.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDnaAddrs falsy/empty? (E: 9689f8be5bd19650b8d4a058b65db826)");if(!G||G.length===0)throw new Error("(UNEXPECTED) finalConflict.replayedDnaAddrs falsy/empty? (E: f42878ed1cee3e9828567c5ab8179526)");if(!v||v.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDomainAddrs falsy/empty? (E: cc41251d1acfe91a48d1b6080259ed26)");(await at({addrs:[...I,...G,...v],space:s})).forEach(O=>E.push(O))}let A=[];if(m.forEach(_=>A.push(_)),E.forEach(_=>A.push(_)),A.length===0)D&&console.log(`${i}[${d}] no changes on this end (I: fa30d18e83a87ee9e8487fbb5d632b26)`);else{D&&console.log(`${i}[${d}] ${A.length} changes detected (I: fa30d18e83a87ee9e8487fbb5d632b26)`),D&&console.log(`${i} put all into localSpace (${a.ib}) starting... (I: d5e0d9870e380b61e80c729660058826)`);let{payload_Dnas:_,payload_NonDnas:$}=await _n({ibGibs:A,space:a});D&&console.log(`${i} put all into localSpace (${a.ib}) complete. (I: d5e0d9870e380b61e80c729660058826)`);let T=await fs({sagaHistory:r,myTempSpace:s}),{mapWithTjp_NoDna:I,mapWithTjp_YesDna:G,mapWithoutTjps:v}=Nt({ibGibs:$,filterPrimitives:!0});D&&console.log(`${i} register mapWithoutTjps starting... (I: 2b84d8f8dda85adde88696d8419bf726)`);let N=Object.values(v);for(let H of N)D&&console.log(`${i} registering ${y({ibGib:H})} (I: 4647b4f42d27cffe0fbfce8846755826)`),await n.registerNewIbGib({ibGib:H,space:a});D&&console.log(`${i} mapWithoutTjps complete. (I: 2b84d8f8dda85adde88696d8419bf726)`),D&&console.log(`${i} register mapWithTjp_NoDna starting... (I: 96e648e4db382499b8bfaa1b37c24826)`);let O=ft({ibGibs:Object.values(I)}),P=Object.keys(O);for(let H of P){let K=O[H];for(let ye of K)await n.registerNewIbGib({ibGib:ye,space:a})}D&&console.log(`${i} register mapWithTjp_NoDna complete. (I: 96e648e4db382499b8bfaa1b37c24826)`),D&&console.log(`${i} register mapWithTjp_YesDna starting... (I: d54a820e9442dee4681f6228a6795926)`);let R=ft({ibGibs:Object.values(G)}),k=Object.keys(R);for(let H of k){let K=R[H];for(let ye of K)T.includes(y({ibGib:ye}))||await n.registerNewIbGib({ibGib:ye,space:a})}D&&console.log(`${i} register mapWithTjp_YesDna complete. (I: d54a820e9442dee4681f6228a6795926)`)}}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{D&&console.log(`${i} complete.`)}}async createCommitFrame({sagaIbGib:t,errors:e,metaspace:r,mySpace:n}){let a=`[${this.createCommitFrame.name}]`;try{D&&console.log(`${a} starting... (I: 48fc57c023f80122135a284855757526)`);let s=e&&e.length>0?{sagaId:t.data.uuid,stage:de.commit,success:!1,errors:e}:{sagaId:t.data.uuid,stage:de.commit,success:!0},i=await this.createSyncMsgStone({data:s,localSpace:n,metaspace:r});return await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[i],localSpace:n,metaspace:r})}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{D&&console.log(`${a} complete.`)}}async handleCommitFrame({sagaIbGib:t,mySpace:e,myTempSpace:r,metaspace:n}){let a=`${this.lc}[${this.handleCommitFrame.name}]`;try{if(D&&console.log(`${a} starting... (I: e179573bdd881202f8ba3168da1c3826)`),!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: cbc31dbb7d28b5b8c8cddb510d7d2826)");if(t.data.errors&&t.data.errors.length>0)throw new Error("not implemented...saga errored out on other end but we've already committed our changes. we need to implement undoing our changes, i.e., rollback commit, which basically is deleting all the payloads that we already put in in our previous commit. (E: e8eb789e0c08f0b3cf93607cb73e9f26)");{let s=await Jr({sagaIbGib:t,space:e}),i=await In({history:s});return i.length>0?{frame:await this.createCommitFrame({sagaIbGib:t,metaspace:n,mySpace:e,errors:i})}:(await this.executeLocalCommit({commitFrame:t,sagaHistory:s,localSpace:e,localTempSpace:r,metaspace:n}),console.error(`${a} NAG ERROR (NOT THROWN): implement cleanup logic, including add a cleanup method to the peer (E: 3a9a24befb98a981a88fbdbf52920e26)`),D&&console.log(`${a} Peer committed. Finalizing saga locally. Saga Complete.`),{sagaComplete:!0})}}catch(s){let i=`${a} ${w(s)}`;return console.error(i),{frame:await this.createCommitFrame({sagaIbGib:t,errors:[i],metaspace:n,mySpace:e})}}finally{D&&console.log(`${a} complete.`)}}async createSyncMsgStone({data:t,rel8ns:e,localSpace:r,metaspace:n}){let a=`${this.lc}[${this.createSyncMsgStone.name}]`;try{D&&console.log(`${a} starting... (I: 5f7f98e8ff980364f7191fcee4531e26)`);let s=await Os({data:t}),i=await B.stone({ib:s,parentPrimitiveIb:Xn,data:t,rel8ns:e,uuid:!0});return D&&console.log(`${a} Created stone: ${y({ibGib:i})}`),await n.put({ibGib:i,space:r}),await n.registerNewIbGib({ibGib:i}),i}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{D&&console.log(`${a} complete.`)}}async getPayloadsForRequestedInfos({deltaRequestAddrInfos:t,mySpace:e}){let r=`${this.lc}[${this.getPayloadsForRequestedInfos.name}]`;try{D&&console.log(`${r} starting... (I: 4fe13d0d80050f20a8b74ba80cee5826)`);let n={};for(let{addr:s,latestAddrAlreadyHave:i}of t){let c;if(i?c=await Yr({ibGibAddr:s,latestCommonFrameAddr:i,space:e,live:!0}):c=await Ot({ibGibAddr:s,space:e,live:!0}),Object.keys(c).length===0)throw new Error(`(UNEXPECTED) couldn't get requested addrs in mySpace (${e.ib})? How did the receiver know to ask for these addrs if they weren't in our original graph? (E: 281eaebcdf77dd73e8245b2872100826)`);Object.values(c).forEach(d=>{n[y({ibGib:d})]=d})}return Object.values(n)}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{D&&console.log(`${r} complete.`)}}async evolveSyncSagaIbGib({prevSagaIbGib:t,conflictStrategy:e,msgStones:r,localSpace:n,metaspace:a,sessionIdentity:s}){let i=`${this.lc}[${this.evolveSyncSagaIbGib.name}]`;try{if(!r||r.length===0)throw new Error(`${i} msgStones required (E: d13f8afcfb8816aeb26baae7df3ef726)`);let c=r[0].data;if(!c?.sagaId||!c?.stage)throw new Error(`${i} Invalid stone data (missing sagaId or stage) (E: c004f85ce8f8958b11839f8d68c38826)`);let l=c.sagaId,d=c.stage;for(let f of r){let p=f.data;if(p.sagaId!==l)throw new Error(`${i} Mismatched sagaId in stones. Expected ${l}, got ${p.sagaId} (E: 29e02719e426ecbbf8ee66887a2be226)`);if(p.stage!==d)throw new Error(`${i} Mismatched stage in stones. Expected ${d}, got ${p.stage} (E: d12c6571b0882f762921b60880c3f826)`)}if(t){let f=[{rel8nName:Re,ibGibs:r}];if(!t.rel8ns)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns falsy? (E: 81375841aff85b1e48ea42ca218e6826)");if(!t.rel8ns[Re]||t.rel8ns[Re].length===0)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] falsy/empty? (E: 15156baad26fcccda80aa3a31718c726)");let p=[{rel8nName:Re,ibGibAddrs:t.rel8ns[Re]}];return await pr({timeline:t,rel8nInfos:f,rel8nRemovalInfos:p,metaspace:a,space:n,noDna:!0})}else{let f={uuid:l,n:0,isTjp:!0,conflictStrategy:e};if(s){let E=ee({ibGib:s});if(!E)throw new Error("(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)");f.sessionIdentityTjpAddr=E}let p=await ds({data:f}),h=r.map(E=>y({ibGib:E})),g={[Re]:h},m=await Ns({space:n,metaspace:a,ib:p,data:f,rel8ns:g,parentIb:gn,noDna:!0});if(m.intermediateIbGibs)throw new Error("(UNEXPECTED) resNew.intermediateIbGibs? we were assuming we were creating a single frame. (E: 456818147235d991ccb4d10d0bbe4826)");return m.newIbGib}}catch(c){throw console.error(`${i} ${w(c)}`),c}}async getStageAndPayloadFromFrame({sagaFrame:t,space:e}){let r=`${this.lc}[${this.getStageAndPayloadFromFrame.name}]`;try{if(D&&console.log(`${r} starting... (I: fddc287bd4d55253dc50e519fd352226)`),!t.rel8ns)throw new Error("(UNEXPECTED) sagaFrame.rel8ns falsy? (E: 725bc8eb5dfe5c7058907ad8e3063826)");let n=t.rel8ns?.[Re];if(n&&n.length>0){let a=n[0],s=await W({addr:a,space:e});if(s.ibGibs&&s.ibGibs.length>0){let i=s.ibGibs[0];if(!i.data)throw new Error("(UNEXPECTED) message stone.data falsy? (E: 4d4abcea90d87ba1328434e83d0d0826)");if(!i.data.stage)throw new Error("(UNEXPECTED) message stone.data.stage falsy? (E: 72c8d22310996644ecdd2b5fdb288c26)");return{stage:i.data.stage,messageData:i.data}}else throw new Error(`couldn't get stoneAddr (${a}) from space (${e.ib}) (E: f3c826e756f8a5c358beb88aa4a65e26)`)}else throw new Error(`(UNEXPECTED) no stone addrs rel8d to sync saga ibgib frame? sagaFrame addr: ${y(t)} (E: 43eae8579e289d016741b5526052f226)`)}catch(n){throw console.error(`${r} ${w(n)}`),n}finally{D&&console.log(`${r} complete.`)}}sortTimelinesTopologically(t){let e=`${this.lc}[${this.sortTimelinesTopologically.name}]`,r=Object.keys(t);if(r.length===0)return[];let n={};r.forEach(d=>{t[d].forEach(f=>{let p=y({ibGib:f});n[p]=d})});let a={};r.forEach(d=>a[d]=new Set),r.forEach(d=>{t[d].forEach(f=>{f.rel8ns&&Object.values(f.rel8ns).flat().forEach(p=>{if(!p)return;let h=n[p];h&&h!==d&&a[d].add(h)})})});let s=new Set,i=new Set,c=[],l=b(d=>{if(i.has(d)){console.warn(`${e} Cycle detected involving ${d}. Ignoring edge to break cycle. (W: 7e7352347102431aa5318db962459929)`);return}s.has(d)||(i.add(d),a[d].forEach(f=>l(f)),s.add(d),i.delete(d),c.push(d))},"visit");return r.forEach(d=>{s.has(d)||l(d)}),c}};var Dl={$schema:"../../../../libs/core-gib/dist/keystone/policy/schemas/keystone.medium.schema.json",metadata:{name:"Space-Gib Default Identity Policy",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:200,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:5}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:20,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:3}}}};var Rb=Dl.pools;function Jn(o,t){let e=Rb[o];if(!e)throw new Error(`Pool template not found in space-gib JSON config: ${o}`);return Nl({template:e,salt:t})}b(Jn,"getSpaceGibPoolConfig");var ne={COMMON:br.COMMON,DEFAULT_POOL:{ID:"default",SIZE:20,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:3},CONNECT_POOL:br.CONNECT_POOL},ZI={MIN_DEFAULT_POOL_SIZE:50,ALLOWED_ALGORITHMS:[De.sha_256,De.sha_512]};var Us=Eo,q=class{static{b(this,"SpaceGibApiBridge")}lc="[SpaceGibApiBridge]";async postGenesisKeystone(t){let e=`${this.lc}[${this.postGenesisKeystone.name}]`;try{Us&&console.log(`${e} starting... (I: eecd082fc4a4381c8857928e8b090826)`);let r=await fetch("/api/keystone/genesis",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t})}),n=await r.json();if(!r.ok){let a=n.message||n.error||"Unknown error";return console.error(`${e} [NAG][ibgib-paradigm] server rejected genesis keystone: ${a}`),{success:!1,message:a,addr:n.addr}}return Us&&console.log(`${e} genesis keystone posted successfully.`),{success:!0,addr:n.addr}}catch(r){let n=w(r);return console.error(`${e} error: ${n}`),{success:!1,message:n}}finally{Us&&console.log(`${e} complete.`)}}async putEvolveKeystone(t,e,r=[],n){let a=`${this.lc}[${this.putEvolveKeystone.name}]`;try{console.log(`${a} posting evolved keystone...`);let s=`/api/keystone/evolve/${encodeURIComponent(t)}`,i=await fetch(s,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e,relatedIbGibs:r,revokeTokens:n})}),c=await i.json();if(!i.ok){let l=c.message||c.error||"Unknown error";return console.error(`${a} server rejected keystone evolution: ${l}`),{success:!1,message:l}}return console.log(`${a} keystone evolution accepted by server.`),{success:!0}}catch(s){let i=w(s);return console.error(`${a} fetch error: ${i}`),{success:!1,message:i}}}async getKeystoneGraph(t){let e=`${this.lc}[${this.getKeystoneGraph.name}]`;try{console.log(`${e} fetching keystone graph...`);let r=`/api/keystone/${encodeURIComponent(t)}?getLatest=true&getGraph=true`,n=await fetch(r,{method:"GET",headers:{Accept:"application/json"}}),a=await n.json();if(console.log(`${e} fetch keystone graph complete.`),!n.ok){let s=a.message||a.error||"Unknown error";return console.error(`${e} server rejected keystone graph get: ${s}`),{success:!1,message:s}}return{success:!0,graph:a.domainGraph}}catch(r){let n=w(r);return console.error(`${e} fetch error: ${n}`),{success:!1,message:n}}}async getIbGib(t,e,r=!1){let n=`${this.lc}[${this.getIbGib.name}]`;try{console.log(`${n} fetching single ibGib frame...`);let a=`/api/ibgib/${encodeURIComponent(t)}/${encodeURIComponent(e)}?getLatest=${r}&getGraph=false`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(console.log(`${n} fetching single ibGib frame complete.`),!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected ibGib get: ${c}`),{success:!1,message:c}}return{success:!0,ibGib:i}}catch(a){let s=w(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async getIbGibGraph(t,e,r=!1){let n=`${this.lc}[${this.getIbGibGraph.name}]`;try{console.log(`${n} fetching ibGib graph...`);let a=`/api/ibgib/${encodeURIComponent(t)}/${encodeURIComponent(e)}?getLatest=${r}&getGraph=true`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(console.log(`${n} fetching ibGib graph complete.`),!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected ibGib graph get: ${c}`),{success:!1,message:c}}return{success:!0,graph:i.graph,addr:i.addr}}catch(a){let s=w(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}},o1=new q;var ae="[dev-tools]",C={};window.ibgibDebugState=C;function u(o){let t=document.getElementById("dev-panel-log");if(!t)return;let e=new Date().toISOString().slice(11,23);t.textContent=`[${e}] ${o}
31
+ `+t.textContent}b(u,"devLog");async function Ol({domainI:o,masterSecret:t,syncSalt:e,metaspace:r,space:n,apiBridge:a}){let s=new Ue,i=await _e({s:`${t}-sync-delegate`}),c=await s.genesis({masterSecret:i,configs:[Jn("sync",`${e}-delegate`)],metaspace:r,space:n,frameDetails:{client:"space-gib-web-dev-delegate",timestamp:Ce()}}),l=await s.registerDelegate({parentKeystone:o,delegateKeystone:c,masterSecret:t,metaspace:r,space:n,allowedVerbs:[Pe]}),d=y({ibGib:o}),f=await a.putEvolveKeystone(d,l,[c]);if(!f.success)throw new Error(`Server rejected delegate evolution: ${f.message}`);return{evolvedDomainI:l,delegateKeystone:c,delegateSecret:i}}b(Ol,"createAndRegisterSyncDelegate");async function Fs({domainI:o,masterSecret:t,metaspace:e,space:r}){let n=o,a=b(async()=>t,"fnSenderSecret"),s=Object.values(o.data?.delegates??{}).find(i=>i.allowedVerbs?.includes(Pe));if(s){let i=s.delegateTjpAddr;if(i){let c=await e.getLatestAddr({addr:i,space:r});if(c){let l=await e.get({addr:c,space:r});if(l.success&&l.ibGibs&&l.ibGibs.length>0){n=l.ibGibs[0];let d=await _e({s:`${t}-sync-delegate`});a=b(async()=>d,"fnSenderSecret")}}}}return{senderIdentity:n,fnSenderSecret:a}}b(Fs,"getSenderIdentityInfo");async function Pt(o){let t=`${ae}[performPhaseSetup(${o.phaseText})]`,e=document.getElementById(o.btnId);if(e)try{e.disabled=!0,u(`${o.phaseText} Setup: Generating Alice's long-lived Domain Keystone (I) and Target (X)...`);let r=await M(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space found in metaspace.");let s=await new Ue().genesis({masterSecret:o.masterSecret,configs:[Jn("manage",o.manageSalt)],metaspace:r,space:n,frameDetails:{client:"space-gib-web-dev",timestamp:Ce()}});u(`${o.phaseText} Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:s})}`),u(`${o.phaseText} Setup: Starting postGenesisKeystone...`);let i=new q,c=await i.postGenesisKeystone(s);if(c.success)u(`${o.phaseText} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw u(`${o.phaseText} Setup: X postGenesisKeystone failed: ${c.message}.`),new Error(`${o.phaseText} Setup: Server rejected genesis domain keystone: ${c.message}`);u(`${o.phaseText} Setup: Generating and registering sync delegate...`);let{evolvedDomainI:l,delegateKeystone:d}=await Ol({domainI:s,masterSecret:o.masterSecret,syncSalt:o.syncSalt,metaspace:r,space:n,apiBridge:i});C.domainI=l,C.domainIMasterSecret=o.masterSecret,u(`${o.phaseText} Setup: \u2713 Registered Sync Delegate: ${y({ibGib:d})}`);let f=await B.firstGen({parentIbGib:j,ib:o.ib,data:o.data,dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=f.newIbGib;await r.persistTransformResult({resTransform:f,space:n}),await r.registerNewIbGib({ibGib:p}),C.targetX=p,u(`${o.phaseText} Setup: \u2713 Target (X) created and persisted locally: ${y({ibGib:p})}`),u(`\u2713 ${o.phaseText} Setup Complete! Ready for ${o.phaseText} Sync.`),e.textContent=`\u2713 ${o.phaseText} Setup Complete`;let h=document.getElementById(o.nextBtnId);h&&(h.disabled=!1)}catch(r){u(`\u2717 ${o.phaseText} Setup FAILED: ${w(r)}`),console.error(`${t} ${o.phaseText} Setup error:`,r),e.disabled=!1}}b(Pt,"performPhaseSetup");async function ur(o){let t=`${ae}[performPhaseSync(${o.phaseText})]`,e=document.getElementById(o.btnId);if(e)try{e.disabled=!0,u(`${o.phaseText} Sync: Executing senderCoordinator.sync(...) using WebSocket Peer...`);let r=C.domainI,n=C.targetX;if(!r||!n){u(`\u26A0 ${o.phaseText} Sync: Missing setup state. Please run Setup first.`),e.disabled=!1;return}let a=y({ibGib:r}),s=await M(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",l=new eo({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(a)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(a)}`}),d=new Ne,f=await V();C.sagaId=f,C.senderPeer=l;let{senderIdentity:p,fnSenderSecret:h}=await Fs({domainI:r,masterSecret:C.domainIMasterSecret,metaspace:s,space:i});await l.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:p,fnSenderSecret:h,sagaId:f,sessionConnectPoolConfig:ne.CONNECT_POOL,sessionSyncPoolConfig:ne.DEFAULT_POOL,targetAddrs:[a]});try{await(await d.sync({domainIbGibs:[n],senderIdentityInfo:{senderIdentity:p,senderDomainAddr:a},fnSenderSecret:h,peer:l,localSpace:i,metaspace:s,conflictStrategy:st.optimisticWithLCS})).done}catch(m){if(o.expectSyncFailure)u(`${o.phaseText} Sync: Coordinator sync executed (${o.failureMessageSuffix??"errors expected"}): ${w(m)}`);else throw m}u(`\u2713 ${o.phaseText} Sync Execution Complete! Ready for State Checks.`),e.textContent=`\u2713 ${o.phaseText} Sync Run`;let g=document.getElementById(o.nextBtnId);g&&(g.disabled=!1)}catch(r){u(`\u2717 ${o.phaseText} Sync FAILED: ${w(r)}`),console.error(`${t} ${o.phaseText} Sync error:`,r),e.disabled=!1}}b(ur,"performPhaseSync");async function js({localI:o,metaspace:t,space:e}){let r=Object.values(o.data?.delegates??{}).find(d=>d.allowedVerbs?.includes(Pe));if(!r)return{};let n=r.delegateTjpAddr;if(!n)return{};let a=await t.getLatestAddr({addr:n,space:e});if(!a)return{delegateTjpAddr:n};let i=(await t.get({addrs:[a],space:e})).ibGibs?.[0];if(!i)return{delegateTjpAddr:n,latestLocalDelegateAddr:a};let l=i.data?.proofs?.find(d=>d.claim?.verb==="sync")?.claim?.target;return{delegateTjpAddr:n,latestLocalDelegateAddr:a,localDelegate:i,sessionIdentityTjpAddr:l}}b(js,"getDelegateAndSessionInfo");async function oe({domainIbGibs:o,passLabel:t,metaspace:e,space:r}){let n=C.domainI,a=C.domainIMasterSecret;if(!n||!a)throw new Error(`runSyncPass[${t}]: Missing domain identity or secret in debugState. Run Setup first.`);let s=y({ibGib:n}),i=location.protocol==="https:"?"wss:":"ws:",{senderIdentity:c,fnSenderSecret:l}=await Fs({domainI:n,masterSecret:a,metaspace:e,space:r});u(`Sync: ${t} \u2014 using sender: ${y({ibGib:c}).slice(0,40)}...`);let d=new eo({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(s)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(s)}`}),f=new Ne,p=await V();C.sagaId=p,C.senderPeer=d,await d.initializeOpts({localMetaspace:e,localSpace:r,senderIdentity:c,fnSenderSecret:l,sagaId:p,sessionConnectPoolConfig:ne.CONNECT_POOL,sessionSyncPoolConfig:ne.DEFAULT_POOL,targetAddrs:[s]}),await(await f.sync({domainIbGibs:o,senderIdentityInfo:{senderIdentity:c,senderDomainAddr:s},fnSenderSecret:l,peer:d,localSpace:r,metaspace:e,conflictStrategy:st.optimisticWithLCS})).done;let g=await e.getLatestAddr({addr:s,space:r});if(g&&g!==y({ibGib:n})){let m=await e.get({addrs:[g],space:r});m.ibGibs?.[0]&&(C.domainI=m.ibGibs[0])}}b(oe,"runSyncPass");async function tt({domainIbGibs:o,passLabel:t,metaspace:e,space:r,primarySpace:n,domainI:a,masterSecret:s}){let i=y({ibGib:a}),c=location.protocol==="https:"?"wss:":"ws:",{senderIdentity:l,fnSenderSecret:d}=await Fs({domainI:a,masterSecret:s,metaspace:e,space:r});u(`Sync: ${t} \u2014 using sender: ${y({ibGib:l}).slice(0,40)}...`);let f=new eo({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),p=new Ne,h=await V();C.sagaId=h,C.senderPeer=f,await f.initializeOpts({localMetaspace:e,localSpace:r,senderIdentity:l,fnSenderSecret:d,sagaId:h,sessionConnectPoolConfig:ne.CONNECT_POOL,sessionSyncPoolConfig:ne.DEFAULT_POOL,targetAddrs:[i]}),await(await p.sync({domainIbGibs:o,senderIdentityInfo:{senderIdentity:l,senderDomainAddr:i},fnSenderSecret:d,peer:f,localSpace:r,metaspace:e,conflictStrategy:st.optimisticWithLCS})).done;let m=await e.getLatestAddr({addr:i,space:r});if(m){let S=(await e.get({addrs:[m],space:r})).ibGibs?.[0];S&&(C.domainI=S,n&&await Ve({domainI:S,metaspace:e,fromSpace:r,toSpace:n}))}}b(tt,"runSyncPassFromSpace");async function je({masterSecret:o,syncSalt:t,manageSalt:e,metaspace:r,space:n,apiBridge:a,phaseText:s}){let c=await new Ue().genesis({masterSecret:o,configs:[Jn("manage",e)],metaspace:r,space:n,frameDetails:{client:"space-gib-web-dev",timestamp:Ce()}});u(`${s} Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:c})}`),u(`${s} Setup: Starting postGenesisKeystone...`);let l=await a.postGenesisKeystone(c);if(l.success)u(`${s} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw u(`${s} Setup: X postGenesisKeystone failed: ${l.message}.`),new Error(`${s} Setup: Server rejected genesis domain keystone: ${l.message}`);u(`${s} Setup: Generating and registering sync delegate...`);let{evolvedDomainI:d,delegateKeystone:f}=await Ol({domainI:c,masterSecret:o,syncSalt:t,metaspace:r,space:n,apiBridge:a});return C.domainI=d,C.domainIMasterSecret=o,{domainI:d,delegateKeystone:f}}b(je,"setupDomainAndDelegateIdentities");async function to({localI:o,metaspace:t,space:e,apiBridge:r,domainAddr:n}){let a=await t.getLatestAddr({addr:n,space:e});if(!a)throw new Error("Evolved domain keystone tip NOT found in local space!");u("\u2713 Check: Evolved Domain Keystone exists locally.");let{latestLocalDelegateAddr:s,sessionIdentityTjpAddr:i}=await js({localI:o,metaspace:t,space:e});if(!s)throw new Error("Evolved delegate keystone tip NOT found in local space!");if(!i)throw new Error("Delegate sync claim does not target a session keystone.");u("\u2713 Check: Delegate Keystone and Sync Claim to Session verified locally.");let c=await r.getIbGib(n,s);if(!c.success||!c.ibGib)throw new Error("Evolved Delegate Keystone NOT found on server!");u("\u2713 Check: Evolved Delegate Keystone exists on server.");let l=await r.getIbGib(n,a);if(!l.success||!l.ibGib)throw new Error("Evolved Domain Keystone NOT found on server!");return u("\u2713 Check: Evolved Domain Keystone exists on server."),{latestLocalIAddr:a,latestLocalDelegateAddr:s,sessionIdentityTjpAddr:i}}b(to,"verifyIdentitiesOnServer");async function Ve({domainI:o,metaspace:t,fromSpace:e,toSpace:r}){let n=y({ibGib:o}),a=await t.getLatestAddr({addr:n,space:e});if(!a)throw new Error("Could not find latest domain I address.");let i=(await t.get({addrs:[a],space:e})).ibGibs?.[0];if(!i)throw new Error("Could not get latest domain I.");let c=await t.getDependencyGraph({ibGibAddr:a,space:e});await t.put({ibGibs:Object.values(c),space:r}),await t.registerNewIbGib({ibGib:i,space:r});let l=Object.values(i.data?.delegates??{}).find(d=>d.allowedVerbs?.includes(Pe));if(l){let d=l.delegateTjpAddr;if(d){let f=await t.getLatestAddr({addr:d,space:e});if(f){let h=(await t.get({addrs:[f],space:e})).ibGibs?.[0];if(h){let g=await t.getDependencyGraph({ibGibAddr:f,space:e});await t.put({ibGibs:Object.values(g),space:r}),await t.registerNewIbGib({ibGib:h,space:r})}}}}}b(Ve,"copyIdentitiesToSpace");var Yt=null;function Ll(){let o=`${ae}[initWsTestButton]`,t=document.getElementById("btn-test-ws");if(!t){console.warn(`${o} btn-test-ws not found \u2014 skipping`);return}t.addEventListener("click",()=>{try{if(Yt&&Yt.readyState===WebSocket.OPEN){Yt.send(JSON.stringify({ping:"hello from client",ts:Date.now()})),u("\u2192 sent ping on existing connection");return}let r=`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/debug/ws-echo`;u(`\u2192 connecting to ${r}`),Yt=new WebSocket(r),Yt.addEventListener("open",()=>{u("\u2713 WebSocket connected"),t.textContent="Send WS Ping"}),Yt.addEventListener("message",n=>{u(`\u2190 ${n.data}`)}),Yt.addEventListener("close",n=>{u(`\u2717 WebSocket closed (code ${n.code})`),t.textContent="Test WebSocket",Yt=null}),Yt.addEventListener("error",n=>{u("\u2717 WebSocket error \u2014 check console"),console.error(`${o} WebSocket error`,n)})}catch(e){u(`\u2717 ${w(e)}`),console.error(`${o} ${w(e)}`)}})}b(Ll,"initWsTestButton");function Pl(){let o=document.getElementById("btn-print-dev-state");o&&o.addEventListener("click",()=>{u("Printing debug state to console..."),console.dir(C)})}b(Pl,"initPrintStateButton");function Rl(){let o=`${ae}[initCreateDomainKeystoneButton]`,t=document.getElementById("btn-create-domain-keystone");t&&t.addEventListener("click",async()=>{try{t.disabled=!0,u("Generating dummy Domain Keystone (I)...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space found in metaspace.");let n="password",s=await new Ue().genesis({masterSecret:n,configs:[xl({id:"default",salt:await V(),replenishStrategy:$e.topUp})],metaspace:e,space:r,frameDetails:{client:"space-gib-web-dev",timestamp:Ce()}}),i=y({ibGib:s});u(`\u2713 Local genesis complete: ${i}`),C.domainI=s,C.domainIMasterSecret=n,u("Posting genesis keystone to server...");let l=await new q().postGenesisKeystone(s);if(!l.success){u(`\u2717 Server rejected genesis keystone: ${l.message}`),t.disabled=!1;return}u("\u2713 Server accepted Domain Keystone (I)"),t.textContent="\u2713 Domain Keystone Created";let d=document.getElementById("btn-create-test-ibgib");d&&(d.disabled=!1)}catch(e){u(`\u2717 ${w(e)}`),console.error(`${o} ${w(e)}`),t.disabled=!1}})}b(Rl,"initCreateDomainKeystoneButton");function Bl(){let o=`${ae}[initCreateTestIbGibButton]`,t=document.getElementById("btn-create-test-ibgib");if(!t){console.warn(`${o} btn-create-test-ibgib not found \u2014 skipping`);return}t.addEventListener("click",async()=>{try{u("Generating dummy X^Xtjp ibgib...");let r=(await B.firstGen({parentIbGib:j,ib:"test data",data:{hello:"world",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}})).newIbGib,n=y({ibGib:r});C.targetX=r,u(`\u2713 Created X: ${n}`),t.textContent="\u2713 Test IbGib (X) Created";let a=document.getElementById("btn-create-session-keystone");a&&(a.disabled=!1)}catch(e){u(`\u2717 ${w(e)}`),console.error(`${o} ${w(e)}`)}})}b(Bl,"initCreateTestIbGibButton");function kl(){let o=`${ae}[initCreateSessionKeystoneButton]`,t=document.getElementById("btn-create-session-keystone");if(!t){console.warn(`${o} btn-create-session-keystone not found \u2014 skipping`);return}t.addEventListener("click",async()=>{try{u("Generating Session Keystone (S^Stjp)...");let e=C.domainI,r=C.targetX;if(!e){u("\u26A0 No domain keystone (I) found in state. Please Create Domain Keystone first.");return}if(!r){u("\u26A0 No target ibgib (X) found in state. Please Create Test IbGib first.");return}let n=await M(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let s="ephemeral-"+Math.random().toString(),i=new Ue;console.warn(`${ae}[NAG] placeholder genesis keystone config right now (W: 69b108687cf8bec0f9a8e148bcca8d26)`);let c=await i.genesis({masterSecret:s,configs:[{id:ne.DEFAULT_POOL.ID,salt:await V(),type:ne.COMMON.TYPE,algo:ne.COMMON.ALGO,rounds:ne.COMMON.ROUNDS,behavior:{size:ne.DEFAULT_POOL.SIZE,replenish:ne.COMMON.REPLENISH,selectSequentially:ne.DEFAULT_POOL.SELECT_SEQUENTIALLY,selectRandomly:ne.DEFAULT_POOL.SELECT_RANDOMLY,targetBindingCount:ne.DEFAULT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[]},{id:ne.CONNECT_POOL.ID,salt:await V(),type:ne.COMMON.TYPE,algo:ne.COMMON.ALGO,rounds:ne.COMMON.ROUNDS,behavior:{size:ne.CONNECT_POOL.SIZE,replenish:ne.COMMON.REPLENISH,selectSequentially:ne.CONNECT_POOL.SELECT_SEQUENTIALLY,selectRandomly:ne.CONNECT_POOL.SELECT_RANDOMLY,targetBindingCount:ne.CONNECT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[ne.CONNECT_POOL.VERB]}],metaspace:n,space:a,frameDetails:{client:"space-gib-web-session",target_I:e?y({ibGib:e}):void 0,target_X:r?y({ibGib:r}):void 0}}),l=y({ibGib:c});C.sessionS=c,C.sessionSecret=s,u(`\u2713 Created Session Keystone: ${l}`),t.textContent="\u2713 Session Keystone Created"}catch(e){u(`\u2717 ${w(e)}`),console.error(`${o} ${w(e)}`)}})}b(kl,"initCreateSessionKeystoneButton");function Ml(){let o=document.getElementById("btn-1b-setup");o&&o.addEventListener("click",()=>{Pt({phaseText:"1B",btnId:"btn-1b-setup",nextBtnId:"btn-1b-sync",masterSecret:"test-sender-secret-phase1",syncSalt:"senderidentitysyncsaltphase1",manageSalt:"senderidentitymanagesaltphase1",ib:"test data",data:{hello:"world",random:Math.random()}})})}b(Ml,"init1bSetupButton");function Ul(){let o=document.getElementById("btn-1b-sync");o&&o.addEventListener("click",()=>{ur({phaseText:"1B",btnId:"btn-1b-sync",nextBtnId:"btn-1b-check",expectSyncFailure:!0,failureMessageSuffix:"establish phase successfully run; connection/sync errors expected in 1B"})})}b(Ul,"init1bSyncButton");function Fl(){let o=`${ae}[init1bCheckButton]`,t=document.getElementById("btn-1b-check");t&&t.addEventListener("click",async()=>{try{u("1B Check: Asserting cryptographic and durable state expectations from respec...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=C.targetX,s=await e.getLatestAddr({addr:y({ibGib:n}),space:r});if(!s){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await e.get({addrs:[s],space:r})).ibGibs?.[0];if(!c){u("\u2717 Check: Failed to load I1 from local space.");return}let l=c.data?.proofs?.find(G=>G.claim?.verb==="sync");l?u("\u2713 Check: I1 contains valid sync-verb claim proof."):u("\u2717 Check: I1 is missing sync-verb claim proof!");let d=l?.claim?.target;if(!d){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}u(`\u2713 Check: Sync claim targets session keystone: ${d}`);let p=(await e.get({addrs:[d],space:r})).ibGibs?.[0];if(!p){u("\u2717 Check: Session Keystone (S) NOT found in local space.");return}u("\u2713 Check: Session Keystone (S) successfully created locally.");let h=p.data?.challengePools??[],g=h.some(G=>G.id===wt),m=h.some(G=>G.id===_r);g&&m?u("\u2713 Check: S contains both connect and sync challenge pools."):u(`\u2717 Check: S is missing challenge pools! (connect: ${g}, sync: ${m})`),u("Check: Verifying registrations on server (receiver metaspace)...");let E=new q,S=!1,A=!1,_=!1,$=y({ibGib:n}),T=await E.getKeystoneGraph($);if(T.success&&T.graph){let G=T.graph;S=G[$]!==void 0,A=G[s]!==void 0}else u(`\u2717 Check Server: Failed to fetch keystone graph from server: ${T.message}`);let I=await E.getIbGib($,d);if(I.success&&I.ibGib?_=!0:u(`\u2717 Check Server: Failed to fetch session keystone from server: ${I.message}`),S?u("\u2713 Check Server: Genesis Domain Keystone (I) registered on server."):u("\u2717 Check Server: Genesis Domain Keystone (I) missing on server!"),A?u("\u2713 Check Server: Evolved Domain Keystone (I1) accepted and stored on server."):u("\u2717 Check Server: Evolved Domain Keystone (I1) missing on server!"),_?u("\u2713 Check Server: Session Keystone (S) accepted and stored on server."):u("\u2717 Check Server: Session Keystone (S) missing on server!"),S&&A&&_){u("\u{1F389} ALL PHASE 1B ESTABLISH CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 1B All Passed";let G=document.getElementById("btn-2b-setup");G&&(G.disabled=!1)}}catch(e){u(`\u2717 1B Check FAILED: ${w(e)}`),console.error(`${o} 1B Check error:`,e)}})}b(Fl,"init1bCheckButton");function jl(){let o=document.getElementById("btn-2b-setup");o&&o.addEventListener("click",()=>{Pt({phaseText:"2B",btnId:"btn-2b-setup",nextBtnId:"btn-2b-sync",masterSecret:"test-sender-secret-phase2",syncSalt:"senderidentitysyncsaltphase2",manageSalt:"senderidentitymanagesaltphase2",ib:"test data",data:{hello:"world2",random:Math.random()}})})}b(jl,"init2bSetupButton");function Vl(){let o=document.getElementById("btn-2b-sync");o&&o.addEventListener("click",()=>{ur({phaseText:"2B",btnId:"btn-2b-sync",nextBtnId:"btn-2b-check",expectSyncFailure:!0,failureMessageSuffix:"connect phase successfully run; subsequent sync errors expected in 2B"})})}b(Vl,"init2bSyncButton");function Kl(){let o=`${ae}[init2bCheckButton]`,t=document.getElementById("btn-2b-check");t&&t.addEventListener("click",async()=>{try{u("2B Check: Asserting cryptographic and WebSocket state expectations...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=y({ibGib:n}),s=await e.getLatestAddr({addr:a,space:r});if(!s){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await e.get({addrs:[s],space:r})).ibGibs?.[0];if(!c){u("\u2717 Check: Failed to load I1 from local space.");return}let d=c.data?.proofs?.find(_=>_.claim?.verb==="sync")?.claim?.target;if(!d){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}u(`\u2713 Check: Sync claim targets session keystone: ${d}`);let f=await e.getLatestAddr({addr:d,space:r});if(!f){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u("\u2713 Check: Found latest session keystone (S) locally.");let h=(await e.get({addrs:[f],space:r})).ibGibs?.[0];if(!h){u("\u2717 Check: Failed to load latest Session Keystone (S).");return}let g=h.data?.challengePools??[],m=g.find(_=>_.id===wt),E=g.find(_=>_.id===_r);if(m&&E)u("\u2713 Check: S contains both connect and sync challenge pools.");else{u(`\u2717 Check: S is missing challenge pools! (connect: ${!!m}, sync: ${!!E})`);return}let S=Object.keys(m.challenges).length;if(S===0)u("\u2713 Check: S connect pool successfully depleted (0 challenges remaining).");else{u(`\u2717 Check: S connect pool not depleted! (${S} challenges remaining)`);return}if(C.senderPeer&&C.senderPeer.isSocketOpen)u("\u2713 Check: WebSocket connection is active and OPEN.");else{u("\u2717 Check: WebSocket connection is NOT open or peer is missing!");return}u("\u{1F389} ALL PHASE 2B CONNECT CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 2B All Passed";let A=document.getElementById("btn-3b-setup");A&&(A.disabled=!1)}catch(e){u(`\u2717 2B Check FAILED: ${w(e)}`),console.error(`${o} 2B Check error:`,e)}})}b(Kl,"init2bCheckButton");function Hl(){let o=document.getElementById("btn-3b-setup");o&&o.addEventListener("click",()=>{Pt({phaseText:"3B",btnId:"btn-3b-setup",nextBtnId:"btn-3b-sync",masterSecret:"test-sender-secret-phase3",syncSalt:"senderidentitysyncsaltphase3",manageSalt:"senderidentitymanagesaltphase3",ib:"test data 3b",data:{hello:"world3",random:Math.random()}})})}b(Hl,"init3bSetupButton");function Xl(){let o=document.getElementById("btn-3b-sync");o&&o.addEventListener("click",()=>{ur({phaseText:"3B",btnId:"btn-3b-sync",nextBtnId:"btn-3b-check"})})}b(Xl,"init3bSyncButton");function ql(){let o=`${ae}[init3bCheckButton]`,t=document.getElementById("btn-3b-check");t&&t.addEventListener("click",async()=>{try{u("3B Check: Asserting cryptographic and WebSocket state expectations...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=C.targetX,s=y({ibGib:a}),i=y({ibGib:n}),c=await e.getLatestAddr({addr:s,space:r});if(!c){u("\u2717 Check: Evolved target X NOT found in local space!");return}u(`\u2713 Check: Evolved target X found locally at: ${c}`);let l=await e.getDependencyGraph({ibGibAddr:c,space:r});if(!l||Object.keys(l).length===0){u("\u2717 Check: Failed to load target X dependency graph locally.");return}u(`\u2713 Check: Target X local graph loaded (${Object.keys(l).length} nodes).`);let d=new q,f=await d.getIbGibGraph(i,s,!0);if(!f.success||!f.graph){u(`\u2717 Check: Failed to fetch target X graph from server: ${f.message}`);return}let p=f.graph;if(u(`\u2713 Check: Target X server graph loaded (${Object.keys(p).length} nodes).`),me({graphA:l,graphB:p}))u("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await e.getLatestAddr({addr:i,space:r});if(!g){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let E=(await e.get({addrs:[g],space:r})).ibGibs?.[0];if(!E){u("\u2717 Check: Failed to load I1 from local space.");return}let A=E.data?.proofs?.find(k=>k.claim?.verb==="sync")?.claim?.target;if(!A){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}let _=await d.getIbGib(i,g);if(!_.success||!_.ibGib){u("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let $=await e.getLatestAddr({addr:A,space:r});if(!$){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let I=(await e.get({addrs:[$],space:r})).ibGibs?.[0];if(!I){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let G=I.data?.n;u(`\u2713 Check: S tip evolved to n = ${G}.`),G!==3&&G!==4&&u(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${G}. Continuing anyway...`);let v=await d.getIbGib(i,$);if(!v.success||!v.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await e.getDependencyGraph({ibGibAddr:$,space:r}),O=await d.getIbGibGraph(i,A,!0);if(!O.success||!O.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${O.message}`);return}let P=O.graph;if(me({graphA:N,graphB:P}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 3B All Passed"}catch(e){u(`\u2717 3B Check FAILED: ${w(e)}`),console.error(`${o} 3B Check error:`,e)}})}b(ql,"init3bCheckButton");function Yl(){let o=document.getElementById("btn-4-1b-setup");o&&o.addEventListener("click",()=>{Pt({phaseText:"4.1B",btnId:"btn-4-1b-setup",nextBtnId:"btn-4-1b-sync",masterSecret:"test-sender-secret-phase4-1",syncSalt:"senderidentitysyncsaltphase4-1",manageSalt:"senderidentitymanagesaltphase4-1",ib:"test data 4.1b",data:{hello:"world4_1",random:Math.random()}})})}b(Yl,"init4_1bSetupButton");function Wl(){let o=document.getElementById("btn-4-1b-sync");o&&o.addEventListener("click",()=>{ur({phaseText:"4.1B",btnId:"btn-4-1b-sync",nextBtnId:"btn-4-1b-check"})})}b(Wl,"init4_1bSyncButton");function zl(){let o=`${ae}[init4_1bCheckButton]`,t=document.getElementById("btn-4-1b-check");t&&t.addEventListener("click",async()=>{try{u("4.1B Check: Asserting cryptographic and WebSocket state expectations...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=C.targetX,s=y({ibGib:a}),i=y({ibGib:n}),c=await e.getLatestAddr({addr:s,space:r});if(!c){u("\u2717 Check: Evolved target X NOT found in local space!");return}u(`\u2713 Check: Evolved target X found locally at: ${c}`);let l=await e.getDependencyGraph({ibGibAddr:c,space:r});if(!l||Object.keys(l).length===0){u("\u2717 Check: Failed to load target X dependency graph locally.");return}u(`\u2713 Check: Target X local graph loaded (${Object.keys(l).length} nodes).`);let d=new q,f=await d.getIbGibGraph(i,s,!0);if(!f.success||!f.graph){u(`\u2717 Check: Failed to fetch target X graph from server: ${f.message}`);return}let p=f.graph;if(u(`\u2713 Check: Target X server graph loaded (${Object.keys(p).length} nodes).`),me({graphA:l,graphB:p}))u("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await e.getLatestAddr({addr:i,space:r});if(!g){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let E=(await e.get({addrs:[g],space:r})).ibGibs?.[0];if(!E){u("\u2717 Check: Failed to load I1 from local space.");return}let{latestLocalDelegateAddr:S,sessionIdentityTjpAddr:A}=await js({localI:E,metaspace:e,space:r});if(!S){u("\u2717 Check: Evolved delegate keystone tip NOT found in local space!");return}if(!A){u("\u2717 Check: Delegate sync claim does not target a session keystone.");return}u("\u2713 Check: Delegate Keystone and Sync Claim to Session verified locally.");let _=await d.getIbGib(i,S);if(!_.success||!_.ibGib){u("\u2717 Check: Evolved Delegate Keystone NOT found on server!");return}u("\u2713 Check: Evolved Delegate Keystone exists on server.");let $=await d.getIbGib(i,g);if(!$.success||!$.ibGib){u("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let T=await e.getLatestAddr({addr:A,space:r});if(!T){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${T}`);let G=(await e.get({addrs:[T],space:r})).ibGibs?.[0];if(!G){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let v=G.data?.n;u(`\u2713 Check: S tip evolved to n = ${v}.`),v!==3&&v!==4&&u(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${v}. Continuing anyway...`);let N=await d.getIbGib(i,T);if(!N.success||!N.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let O=await e.getDependencyGraph({ibGibAddr:T,space:r}),P=await d.getIbGibGraph(i,A,!0);if(!P.success||!P.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${P.message}`);return}let R=P.graph;if(me({graphA:O,graphB:R}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 4.1B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 4.1B All Passed"}catch(e){u(`\u2717 4.1B Check FAILED: ${w(e)}`),console.error(`${o} 4.1B Check error:`,e)}})}b(zl,"init4_1bCheckButton");function Jl(){let o=document.getElementById("btn-4-2b-setup");o&&o.addEventListener("click",()=>{Pt({phaseText:"4.2B",btnId:"btn-4-2b-setup",nextBtnId:"btn-4-2b-sync",masterSecret:"test-sender-secret-phase4-2",syncSalt:"senderidentitysyncsaltphase4-2",manageSalt:"senderidentitymanagesaltphase4-2",ib:"dummy target 4.2b",data:{hello:"dummy"}})})}b(Jl,"init4_2bSetupButton");async function Bb(){let o=`${ae}[performPhaseSync4_2b]`,t=document.getElementById("btn-4-2b-sync");if(t)try{if(t.disabled=!0,u("4.2B Sync: Creating Constants and executing three-pass WebSocket Sync..."),!C.domainI){u("\u26A0 4.2B Sync: Missing setup state. Please run Setup first."),t.disabled=!1;return}let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=await B.constant({parentPrimitiveIb:"root",ib:"constant_c1_"+(await V()).slice(0,8),data:{some:"data_4_2b",random:Math.random()}}),a=y({ibGib:n});await e.put({ibGib:n,space:r}),await e.registerNewIbGib({ibGib:n}),C.targetC1=n,u(`4.2B Sync: \u2713 Constant C1 created: ${a}`),u("4.2B Sync: Starting Pass 1 (Sync C1)..."),await oe({domainIbGibs:[n],passLabel:"Pass 1 (Sync C1)",metaspace:e,space:r}),u("4.2B Sync: \u2713 Pass 1 Complete."),u("4.2B Sync: Starting Pass 2 (Sync C1 - Idempotent)..."),await oe({domainIbGibs:[n],passLabel:"Pass 2 (Sync C1 idempotent)",metaspace:e,space:r}),u("4.2B Sync: \u2713 Pass 2 Complete.");let s=await B.constant({ib:"constant_c2_"+(await V()).slice(0,8),parentPrimitiveIb:"root",rel8ns:{link:[a]}}),i=y({ibGib:s});await e.put({ibGib:s,space:r}),await e.registerNewIbGib({ibGib:s}),C.targetC2=s,u(`4.2B Sync: \u2713 Constant C2 created linking to C1: ${i}`),u("4.2B Sync: Starting Pass 3 (Sync C2)..."),await oe({domainIbGibs:[s],passLabel:"Pass 3 (Sync C2)",metaspace:e,space:r}),u("4.2B Sync: \u2713 Pass 3 Complete."),u("\u2713 4.2B Sync Sequence Complete! Ready for State Checks."),t.textContent="\u2713 4.2B Sync Run";let c=document.getElementById("btn-4-2b-check");c&&(c.disabled=!1)}catch(e){u(`\u2717 4.2B Sync FAILED: ${w(e)}`),console.error(`${o} 4.2B Sync error:`,e),t.disabled=!1}}b(Bb,"performPhaseSync4_2b");function Zl(){let o=document.getElementById("btn-4-2b-sync");o&&o.addEventListener("click",()=>{Bb()})}b(Zl,"init4_2bSyncButton");function Ql(){let o=`${ae}[init4_2bCheckButton]`,t=document.getElementById("btn-4-2b-check");t&&t.addEventListener("click",async()=>{try{u("4.2B Check: Asserting cryptographic and WebSocket state expectations...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=C.targetC1,s=C.targetC2,i=y({ibGib:a}),c=y({ibGib:s}),l=y({ibGib:n}),d=new q,f=await e.get({addrs:[i],space:r}),p=await e.get({addrs:[c],space:r});if(!f.success||!f.ibGibs?.[0]){u("\u2717 Check: Constant C1 NOT found locally.");return}if(!p.success||!p.ibGibs?.[0]){u("\u2717 Check: Constant C2 NOT found locally.");return}u("\u2713 Check: Constants C1 and C2 exist locally.");let h=await d.getIbGib(l,i),g=await d.getIbGib(l,c);if(!h.success||!h.ibGib){u(`\u2717 Check: Constant C1 NOT found on server: ${h.message}`);return}if(!g.success||!g.ibGib){u(`\u2717 Check: Constant C2 NOT found on server: ${g.message}`);return}u("\u2713 Check: Constants C1 and C2 exist on server.");let m=await e.getDependencyGraph({ibGibAddr:c,space:r}),E=await d.getIbGibGraph(l,c,!0);if(!E.success||!E.graph){u(`\u2717 Check: Failed to fetch C2 graph from server: ${E.message}`);return}if(!me({graphA:m,graphB:E.graph})){u("\u2717 Check: C2 dependency graphs mismatch between client and server!");return}u("\u2713 Check: C2 dependency graphs are equivalent on client and server.");let S=await e.getLatestAddr({addr:l,space:r});if(!S){u("\u2717 Check: Domain keystone tip not found locally!");return}let _=(await e.get({addrs:[S],space:r})).ibGibs?.[0];if(!_){u("\u2717 Check: Failed to load domain keystone!");return}let $=_.data?.n;if(u(`\u2713 Check: Evolved I tip is at n = ${$}.`),$!==1){u(`\u2717 Check: Expected I to evolve to n = 1 (delegate registration only), got n = ${$}.`);return}let{sessionIdentityTjpAddr:T}=await to({localI:_,metaspace:e,space:r,apiBridge:d,domainAddr:l}),I=await e.getLatestAddr({addr:T,space:r});if(!I){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${I}`);let v=(await e.get({addrs:[I],space:r})).ibGibs?.[0];if(!v){u("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let N=v.data?.n;if(u(`\u2713 Check: Latest session S tip evolved to n = ${N}.`),N!==3){u(`\u2717 Check: Expected latest session S to evolve to n = 3 (connect+sync+disconnect), got n = ${N}.`);return}let O=await d.getIbGib(l,I);if(!O.success||!O.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let P=await e.getDependencyGraph({ibGibAddr:I,space:r}),R=await d.getIbGibGraph(l,T,!0);if(!R.success||!R.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${R.message}`);return}if(!me({graphA:P,graphB:R.graph})){u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),u("\u{1F389} ALL PHASE 4.2B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 4.2B All Passed"}catch(e){u(`\u2717 4.2B Check FAILED: ${w(e)}`),console.error(`${o} 4.2B Check error:`,e)}})}b(Ql,"init4_2bCheckButton");function ed(){let o=document.getElementById("btn-4-3b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.3B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:"test-sender-secret-phase4-3",syncSalt:"senderidentitysyncsaltphase4-3",manageSalt:"senderidentitymanagesaltphase4-3",metaspace:t,space:e,apiBridge:r,phaseText:"4.3B"});let n=await B.firstGen({parentIbGib:j,ib:"timeline_root_partial_4_3b",data:{type:"root",label:"Root4_3b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),a=n.newIbGib;await t.persistTransformResult({resTransform:n,space:e}),await t.registerNewIbGib({ibGib:a});let s=await Y({timeline:a,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_3b"}},metaspace:t,space:e});C.targetC1=s,C.targetX=s,u(`4.3B Setup: \u2713 Timeline V0 -> V1 created and stored locally. V1: ${y({ibGib:s})}`),u("\u2713 4.3B Setup Complete! Ready for 4.3B Sync."),o.textContent="\u2713 4.3B Setup Complete";let i=document.getElementById("btn-4-3b-sync");i&&(i.disabled=!1)}catch(t){u(`\u2717 4.3B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(ed,"init4_3bSetupButton");async function kb(){let o=`${ae}[performPhaseSync4_3b]`,t=document.getElementById("btn-4-3b-sync");if(t)try{t.disabled=!0;let e=C.targetX;if(!C.domainI||!e){u("\u26A0 4.3B Sync: Missing setup state. Please run Setup first."),t.disabled=!1;return}let r=await M(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space.");u("4.3B Sync: Starting Pass 1 (Sync V1 to server)..."),await oe({domainIbGibs:[e],passLabel:"Pass 1 (Sync V1)",metaspace:r,space:n}),u("4.3B Sync: \u2713 Pass 1 Complete (V1 synced)."),u("4.3B Sync: Mutating V1 to V2 locally...");let a=await Y({timeline:e,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_3b"}},metaspace:r,space:n});C.targetX=a,u(`4.3B Sync: \u2713 V2 created locally: ${y({ibGib:a})}`),u("4.3B Sync: Starting Pass 2 (Sync V2 delta to server)..."),await oe({domainIbGibs:[a],passLabel:"Pass 2 (Sync V2)",metaspace:r,space:n}),u("4.3B Sync: \u2713 Pass 2 Complete (V2 synced)."),u("\u2713 4.3B Sync Sequence Complete! Ready for State Checks."),t.textContent="\u2713 4.3B Sync Run";let s=document.getElementById("btn-4-3b-check");s&&(s.disabled=!1)}catch(e){u(`\u2717 4.3B Sync FAILED: ${w(e)}`),console.error(e),t.disabled=!1}}b(kb,"performPhaseSync4_3b");function td(){let o=document.getElementById("btn-4-3b-sync");o&&o.addEventListener("click",()=>{kb()})}b(td,"init4_3bSyncButton");function rd(){let o=`${ae}[init4_3bCheckButton]`,t=document.getElementById("btn-4-3b-check");t&&t.addEventListener("click",async()=>{try{u("4.3B Check: Asserting cryptographic and WebSocket state expectations...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=C.targetC1,s=C.targetX,i=y({ibGib:a}),c=y({ibGib:s}),l=y({ibGib:n}),d=new q,f=await e.get({addrs:[i],space:r}),p=await e.get({addrs:[c],space:r});if(!f.success||!f.ibGibs?.[0]){u("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!p.success||!p.ibGibs?.[0]){u("\u2717 Check: Timeline frame V2 NOT found locally.");return}u("\u2713 Check: Timeline frames V1 and V2 exist locally.");let h=await d.getIbGib(l,c);if(!h.success||!h.ibGib){u(`\u2717 Check: Timeline frame V2 NOT found on server: ${h.message}`);return}u("\u2713 Check: Timeline frame V2 exists on server.");let g=h.ibGib.rel8ns?.past?.at(-1);if(g===i)u("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{u(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${g}`);return}let m=await e.getDependencyGraph({ibGibAddr:c,space:r}),E=await d.getIbGibGraph(l,c,!0);if(!E.success||!E.graph){u(`\u2717 Check: Failed to fetch V2 graph from server: ${E.message}`);return}if(!me({graphA:m,graphB:E.graph})){u("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}u("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");let S=await e.getLatestAddr({addr:l,space:r});if(!S){u("\u2717 Check: Domain keystone tip not found locally!");return}let _=(await e.get({addrs:[S],space:r})).ibGibs?.[0];if(!_){u("\u2717 Check: Failed to load domain keystone!");return}let $=_.data?.n;if(u(`\u2713 Check: Evolved I tip is at n = ${$}.`),$!==1){u(`\u2717 Check: Expected I to evolve to n = 1 (delegate registration only), got n = ${$}.`);return}let{sessionIdentityTjpAddr:T}=await to({localI:_,metaspace:e,space:r,apiBridge:d,domainAddr:l}),I=await e.getLatestAddr({addr:T,space:r});if(!I){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${I}`);let v=(await e.get({addrs:[I],space:r})).ibGibs?.[0];if(!v){u("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let N=v.data?.n;if(u(`\u2713 Check: Latest session S tip evolved to n = ${N}.`),N!==3){u(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${N}.`);return}let O=await d.getIbGib(l,I);if(!O.success||!O.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let P=await e.getDependencyGraph({ibGibAddr:I,space:r}),R=await d.getIbGibGraph(l,T,!0);if(!R.success||!R.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${R.message}`);return}if(!me({graphA:P,graphB:R.graph})){u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),u("\u{1F389} ALL PHASE 4.3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 4.3B All Passed"}catch(e){u(`\u2717 4.3B Check FAILED: ${w(e)}`),console.error(`${o} 4.3B Check error:`,e)}})}b(rd,"init4_3bCheckButton");function od(){let o=document.getElementById("btn-4-4b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.4B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 -> V2...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:"test-sender-secret-phase4-4",syncSalt:"senderidentitysyncsaltphase4-4",manageSalt:"senderidentitymanagesaltphase4-4",metaspace:t,space:e,apiBridge:r,phaseText:"4.4B"});let n=await B.firstGen({parentIbGib:j,ib:"timeline_root_deep_4_4b",data:{type:"root",label:"Root4_4b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),a=n.newIbGib;await t.persistTransformResult({resTransform:n,space:e}),await t.registerNewIbGib({ibGib:a}),C.targetC1=a;let s=await Y({timeline:a,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_4b"}},metaspace:t,space:e});C.targetC2=s;let i=await Y({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_4b"}},metaspace:t,space:e});C.targetX=i,u(`4.4B Setup: \u2713 Timeline V0 -> V1 -> V2 created locally. V2 Tip: ${y({ibGib:i})}`),u("\u2713 4.4B Setup Complete! Ready for 4.4B Sync."),o.textContent="\u2713 4.4B Setup Complete";let c=document.getElementById("btn-4-4b-sync");c&&(c.disabled=!1)}catch(t){u(`\u2717 4.4B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(od,"init4_4bSetupButton");async function Mb(){let o=`${ae}[performPhaseSync4_4b]`,t=document.getElementById("btn-4-4b-sync");if(t)try{t.disabled=!0,u("4.4B Sync: Initiating WebSocket Sync of V2 Tip...");let e=C.targetX;if(!C.domainI||!e){u("\u26A0 4.4B Sync: Missing setup state. Please run Setup first."),t.disabled=!1;return}let r=await M(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space.");await oe({domainIbGibs:[e],passLabel:"Pass 1 (Sync V2 tip)",metaspace:r,space:n}),u("4.4B Sync: \u2713 WebSocket Sync completed."),u("\u2713 4.4B Sync Sequence Complete! Ready for State Checks."),t.textContent="\u2713 4.4B Sync Run";let a=document.getElementById("btn-4-4b-check");a&&(a.disabled=!1)}catch(e){u(`\u2717 4.4B Sync FAILED: ${w(e)}`),console.error(e),t.disabled=!1}}b(Mb,"performPhaseSync4_4b");function nd(){let o=document.getElementById("btn-4-4b-sync");o&&o.addEventListener("click",()=>{Mb()})}b(nd,"init4_4bSyncButton");function ad(){let o=`${ae}[init4_4bCheckButton]`,t=document.getElementById("btn-4-4b-check");t&&t.addEventListener("click",async()=>{try{u("4.4B Check: Asserting cryptographic and WebSocket state expectations...");let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");let n=C.domainI,a=C.targetC1,s=C.targetC2,i=C.targetX,c=y({ibGib:a}),l=y({ibGib:s}),d=y({ibGib:i}),f=y({ibGib:n}),p=new q,h=await e.get({addrs:[c],space:r}),g=await e.get({addrs:[l],space:r}),m=await e.get({addrs:[d],space:r});if(!h.success||!h.ibGibs?.[0]){u("\u2717 Check: Timeline frame V0 NOT found locally.");return}if(!g.success||!g.ibGibs?.[0]){u("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!m.success||!m.ibGibs?.[0]){u("\u2717 Check: Timeline frame V2 NOT found locally.");return}u("\u2713 Check: Timeline frames V0, V1, and V2 exist locally.");let E=await p.getIbGib(f,d);if(!E.success||!E.ibGib){u(`\u2717 Check: Timeline frame V2 NOT found on server: ${E.message}`);return}u("\u2713 Check: Timeline frame V2 exists on server.");let S=E.ibGib.rel8ns?.past?.at(-1);if(S===l)u("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{u(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${S}`);return}let A=await p.getIbGib(f,l);if(!A.success||!A.ibGib){u(`\u2717 Check: Timeline frame V1 NOT found on server: ${A.message}`);return}u("\u2713 Check: Timeline frame V1 exists on server.");let _=A.ibGib.rel8ns?.past?.at(-1);if(_===c)u("\u2713 Check: Server V1 correctly references V0 in its past relation.");else{u(`\u2717 Check: Server V1 does not reference V0 in past relation! got: ${_}`);return}let $=await e.getDependencyGraph({ibGibAddr:d,space:r}),T=await p.getIbGibGraph(f,d,!0);if(!T.success||!T.graph){u(`\u2717 Check: Failed to fetch V2 graph from server: ${T.message}`);return}if(!me({graphA:$,graphB:T.graph})){u("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}u("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");let I=await e.getLatestAddr({addr:f,space:r});if(!I){u("\u2717 Check: Domain keystone tip not found locally!");return}let v=(await e.get({addrs:[I],space:r})).ibGibs?.[0];if(!v){u("\u2717 Check: Failed to load domain keystone!");return}u(`\u2713 Check: Evolved Domain Keystone exists locally: ${I}`);let N=v.data?.n;if(u(`\u2713 Check: Evolved I tip is at n = ${N}.`),N!==1){u(`\u2717 Check: Expected I to evolve to n = 1, got n = ${N}.`);return}let{sessionIdentityTjpAddr:O}=await to({localI:v,metaspace:e,space:r,apiBridge:p,domainAddr:f}),P=await e.getLatestAddr({addr:O,space:r});if(!P){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${P}`);let k=(await e.get({addrs:[P],space:r})).ibGibs?.[0];if(!k){u("\u2717 Check: Failed to load Session Keystone (S) locally.");return}let H=k.data?.n;if(u(`\u2713 Check: Latest session S tip evolved to n = ${H}.`),H!==3){u(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${H}.`);return}let K=await p.getIbGib(f,P);if(!K.success||!K.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let ye=await e.getDependencyGraph({ibGibAddr:P,space:r}),ie=await p.getIbGibGraph(f,O,!0);if(!ie.success||!ie.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${ie.message}`);return}if(!me({graphA:ye,graphB:ie.graph})){u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server."),u("\u{1F389} ALL PHASE 4.4B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),t.textContent="\u2713 4.4B All Passed"}catch(e){u(`\u2717 4.4B Check FAILED: ${w(e)}`),console.error(`${o} 4.4B Check error:`,e)}})}b(ad,"init4_4bCheckButton");var id={},sd="test-sender-secret-phase4-5b";function cd(){let o=document.getElementById("btn-4-5b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.5B Setup: Generating Domain Keystone (I), target timeline, and seeding server from two spaces...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:sd,syncSalt:"senderidentitysyncsaltphase4-5b",manageSalt:"senderidentitymanagesaltphase4-5b",metaspace:t,space:e,apiBridge:r,phaseText:"4.5B"});let n=await B.firstGen({parentIbGib:j,ib:"timeline_root_partial_4_5b",data:{type:"root",label:"Root4_5b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),a=n.newIbGib;await t.persistTransformResult({resTransform:n,space:e}),await t.registerNewIbGib({ibGib:a,space:e});let s=await Y({timeline:a,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_5b"}},metaspace:t,space:e});C.targetC1=s,u(`4.5B Setup: \u2713 Local timeline V0 -> V1 created. V1 Tip: ${y({ibGib:s})}`),u("4.5B Setup: Seeding V1 to the server via WebSocket..."),await oe({domainIbGibs:[s],passLabel:"Seed V1 to server",metaspace:t,space:e}),u("4.5B Setup: \u2713 Pass 1 Sync (V1 to server) complete."),u('4.5B Setup: Creating secondary local space simulating "remote" client...');let i=`remote-${await V()}`,c=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:i,getFnPrompt:t.getFnPrompt}});if(!c)throw new Error("Failed to create remote space");await c.initialized;let l=await t.getDependencyGraph({ibGibAddr:y({ibGib:s}),space:e});await t.put({ibGibs:Object.values(l),space:c}),await t.registerNewIbGib({ibGib:s,space:c});let d=C.domainI;await Ve({domainI:d,metaspace:t,fromSpace:e,toSpace:c}),u("4.5B Setup: \u2713 Copied V1 and identities (domain and delegate) to remoteSpace."),u("4.5B Setup: Mutating V1 -> V2 in remoteSpace...");let f=await Y({timeline:s,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_5b"}},metaspace:t,space:c});id.targetV2=f,u(`4.5B Setup: \u2713 Mutated to V2 in remoteSpace: ${y({ibGib:f})}`),u("4.5B Setup: Syncing V2 from remoteSpace to the server..."),await tt({domainIbGibs:[f],passLabel:"Seed V2 from remoteSpace",metaspace:t,space:c,primarySpace:e,domainI:d,masterSecret:sd}),u("4.5B Setup: \u2713 Pass 2 Sync (V2 to server) complete. debugState.domainI updated."),u("\u2713 4.5B Setup Complete! Server has V2, default local space has V1. Ready for 4.5B Sync."),o.textContent="\u2713 4.5B Setup Complete";let p=document.getElementById("btn-4-5b-sync");p&&(p.disabled=!1)}catch(t){u(`\u2717 4.5B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(cd,"init4_5bSetupButton");function ld(){let o=document.getElementById("btn-4-5b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.5B Sync: Initiating WebSocket Sync from default local space (which has V1, server has V2)...");let t=C.targetC1;if(!C.domainI||!t){u("\u26A0 4.5B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");await oe({domainIbGibs:[t],passLabel:"Pull V2 from server",metaspace:e,space:r}),u("\u2713 4.5B Sync Execution Complete! Ready for 4.5B Check."),o.textContent="\u2713 4.5B Sync Run";let n=document.getElementById("btn-4-5b-check");n&&(n.disabled=!1)}catch(t){u(`\u2717 4.5B Sync FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(ld,"init4_5bSyncButton");function dd(){let o=document.getElementById("btn-4-5b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.5B Check: Verifying that V2 was pulled down to default local space...");let t=id.targetV2;if(!t||!C.domainI){u("\u26A0 4.5B Check: Missing target V2 in state. Did Setup run?"),o.disabled=!1;return}let e=y({ibGib:t}),r=y({ibGib:C.domainI}),n=await M(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=await n.get({addr:e,space:a});if(!s.success||s.ibGibs?.length!==1)throw new Error(`V2 tip (${e}) is NOT present in local space!`);let i=s.ibGibs[0];u(`4.5B Check: \u2713 V2 Tip found locally. Label: "${i.data?.label}"`);let c=await n.getDependencyGraph({ibGibAddr:e,space:a});u("4.5B Check: Fetching V2 dependency graph from server...");let d=await new q().getIbGibGraph(r,e,!0);if(!d.success||!d.graph)throw new Error(`Failed to fetch V2 graph from server: ${d.message}`);if(me({graphA:c,graphB:d.graph}))u("\u2713 4.5B Check SUCCESS: V2 and all dependencies are fully equivalent on client and server!"),o.textContent="\u2713 4.5B Check Success";else throw new Error("Dependency graphs on local space and server are NOT equivalent.")}catch(t){u(`\u2717 4.5B Check FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(dd,"init4_5bCheckButton");var ro={},Ub="test-sender-secret-phase4-6b";function fd(){let o=document.getElementById("btn-4-6b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.6B Setup: Generating Domain Keystone (I) and two independent target timelines (Alpha and Beta)...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:Ub,syncSalt:"senderidentitysyncsaltphase4-6b",manageSalt:"senderidentitymanagesaltphase4-6b",metaspace:t,space:e,apiBridge:r,phaseText:"4.6B"});let n=await B.firstGen({parentIbGib:j,ib:"timeline_root_alpha_4_6b",data:{type:"root",label:"Alpha4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),a=n.newIbGib;await t.persistTransformResult({resTransform:n,space:e}),await t.registerNewIbGib({ibGib:a,space:e});let s=await Y({timeline:a,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"A1_4_6b"}},metaspace:t,space:e});ro.targetAlphaV1=s,C.targetC1=s,u(`4.6B Setup: \u2713 Local Timeline A created. A1 Tip: ${y({ibGib:s})}`);let i=await B.firstGen({parentIbGib:j,ib:"timeline_root_beta_4_6b",data:{type:"root",label:"Beta4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await t.persistTransformResult({resTransform:i,space:e}),await t.registerNewIbGib({ibGib:c,space:e});let l=await Y({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B1_4_6b"}},metaspace:t,space:e}),d=await Y({timeline:l,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B2_4_6b"}},metaspace:t,space:e});ro.targetBetaV2=d,C.targetC2=d,u(`4.6B Setup: \u2713 Local Timeline B created. B2 Tip: ${y({ibGib:d})}`),u("\u2713 4.6B Setup Complete! Timelines created locally. Ready for 4.6B Sync."),o.textContent="\u2713 4.6B Setup Complete";let f=document.getElementById("btn-4-6b-sync");f&&(f.disabled=!1)}catch(t){u(`\u2717 4.6B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(fd,"init4_6bSetupButton");function bd(){let o=document.getElementById("btn-4-6b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.6B Sync: Initiating WebSocket Sync for both Timeline A and Timeline B in one call...");let t=ro.targetAlphaV1,e=ro.targetBetaV2;if(!C.domainI||!t||!e){u("\u26A0 4.6B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let r=await M(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space.");await oe({domainIbGibs:[t,e],passLabel:"Sync Alpha A1 + Beta B2",metaspace:r,space:n}),u("\u2713 4.6B Sync Execution Complete! Ready for 4.6B Check."),o.textContent="\u2713 4.6B Sync Run";let a=document.getElementById("btn-4-6b-check");a&&(a.disabled=!1)}catch(t){u(`\u2717 4.6B Sync FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(bd,"init4_6bSyncButton");function pd(){let o=document.getElementById("btn-4-6b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.6B Check: Verifying both Timeline A and Timeline B exist on the server with matching dependency graphs...");let t=ro.targetAlphaV1,e=ro.targetBetaV2;if(!C.domainI||!t||!e){u("\u26A0 4.6B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let r=y({ibGib:C.domainI}),n=y({ibGib:t}),a=y({ibGib:e}),s=await M(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=new q;u("4.6B Check: Fetching Timeline A dependency graph from server...");let l=await c.getIbGibGraph(r,n,!0);if(!l.success||!l.graph)throw new Error(`Failed to fetch Timeline A graph from server: ${l.message}`);let d=await s.getDependencyGraph({ibGibAddr:n,space:i});if(!me({graphA:d,graphB:l.graph}))throw new Error("Timeline A dependency graphs on local space and server are NOT equivalent.");u("4.6B Check: \u2713 Timeline A graphs are equivalent."),u("4.6B Check: Fetching Timeline B dependency graph from server...");let f=await c.getIbGibGraph(r,a,!0);if(!f.success||!f.graph)throw new Error(`Failed to fetch Timeline B graph from server: ${f.message}`);let p=await s.getDependencyGraph({ibGibAddr:a,space:i});if(!me({graphA:p,graphB:f.graph}))throw new Error("Timeline B dependency graphs on local space and server are NOT equivalent.");u("4.6B Check: \u2713 Timeline B graphs are equivalent."),u("\u2713 4.6B Check SUCCESS: Both independent timelines are fully synced and identical on client and server!"),o.textContent="\u2713 4.6B Check Success"}catch(t){u(`\u2717 4.6B Check FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(pd,"init4_6bCheckButton");var Or={},hd="test-sender-secret-phase4-7b";function ud(){let o=document.getElementById("btn-4-7b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.7B Setup: Setting up identities, seeding history, and creating divergent branches...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:hd,syncSalt:"senderidentitysyncsaltphase4-7b",manageSalt:"senderidentitymanagesaltphase4-7b",metaspace:t,space:e,apiBridge:r,phaseText:"4.7B"});let n=C.domainI,a=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_7b",getFnPrompt:t.getFnPrompt}});await a.initialized,await t.put({ibGib:n,space:a}),await t.registerNewIbGib({ibGib:n,space:a});let s=await B.firstGen({parentIbGib:j,ib:"timeline_root_conflict_4_7b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),i=s.newIbGib;await t.persistTransformResult({resTransform:s,space:e}),await t.registerNewIbGib({ibGib:i,space:e}),Or.testRoot=i;let c=await Y({timeline:i,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:t,space:e}),l=await t.getDependencyGraph({ibGibAddr:y({ibGib:i}),space:e}),d=await t.getDependencyGraph({ibGibAddr:y({ibGib:c}),space:e});await t.put({ibGibs:Object.values({...l,...d}),space:a}),await t.registerNewIbGib({ibGib:i,space:a}),await t.registerNewIbGib({ibGib:c,space:a}),u("4.7B Setup: Syncing v1_common to server..."),await oe({domainIbGibs:[c],passLabel:"Seed v1_common",metaspace:t,space:e}),u("4.7B Setup: \u2713 Seeding complete on server.");let f=C.domainI;await Ve({domainI:f,metaspace:t,fromSpace:e,toSpace:a});let p=await Y({timeline:c,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:t,space:e});Or.targetAlphaV2a=p,u(`4.7B Setup: \u2713 Created client divergent edit V2a: ${y({ibGib:p})}`);let h=await Y({timeline:c,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:t,space:a});Or.targetBetaV2b=h,u(`4.7B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:h})}`),u("4.7B Setup: Pushing V2b from remote space to server..."),await tt({domainIbGibs:[h],passLabel:"Push V2b from remoteSpace",metaspace:t,space:a,primarySpace:e,domainI:f,masterSecret:hd}),u("4.7B Setup: \u2713 Server tip is now V2b."),u("\u2713 4.7B Setup Complete! Ready for 4.7B Sync."),o.textContent="\u2713 4.7B Setup Complete";let g=document.getElementById("btn-4-7b-sync");g&&(g.disabled=!1)}catch(t){u(`\u2717 4.7B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(ud,"init4_7bSetupButton");function gd(){let o=document.getElementById("btn-4-7b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.7B Sync: Initiating WebSocket Sync for divergent edit V2a...");let t=Or.targetAlphaV2a;if(!C.domainI||!t){u("\u26A0 4.7B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let e=await M(),r=await e.getLocalUserSpace({});if(!r)throw new Error("No default space.");await oe({domainIbGibs:[t],passLabel:"Sync V2a (conflict merge)",metaspace:e,space:r}),u("\u2713 4.7B Sync Execution Complete! Ready for 4.7B Check."),o.textContent="\u2713 4.7B Sync Run";let n=document.getElementById("btn-4-7b-check");n&&(n.disabled=!1)}catch(t){u(`\u2717 4.7B Sync FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(gd,"init4_7bSyncButton");function md(){let o=document.getElementById("btn-4-7b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.7B Check: Verifying merged tip (V3) contains both edits on client and server...");let t=Or.testRoot,e=Or.targetAlphaV2a,r=Or.targetBetaV2b;if(!C.domainI||!t||!e||!r){u("\u26A0 4.7B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let n=y({ibGib:C.domainI}),a=ee({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),s=await M(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let l=(await s.getLocalUserSpace({}).then(A=>new Ne().getKnowledgeMap({space:A,metaspace:s,domainIbGibs:[t]})))[a];if(u(`4.7B Check: Client tip address: ${l}`),!l)throw new Error("Client default space is missing the timeline tip.");let d=await s.get({addr:l,space:i});if(!d.success||!d.ibGibs?.length)throw new Error("Client tip not found in default local space.");let f=d.ibGibs[0];if(!f.data?.fieldA||!f.data?.fieldB)throw new Error(`Merged client tip missing edits: fieldA: ${f.data?.fieldA}, fieldB: ${f.data?.fieldB}`);u("4.7B Check: \u2713 Client tip has both fieldA and fieldB edits.");let p=f.rel8ns?.[yt];if(!p?.[0])throw new Error("Client tip is missing graftinfo relations.");let h=await s.get({addr:p[0],space:i});if(!h.success||!h.ibGibs?.length)throw new Error("GraftInfo not found in local space.");let g=h.ibGibs[0];if(!g.rel8ns?.[ar]||!g.rel8ns?.[Lt])throw new Error("GraftInfo is missing graftbase or graftorphan relations.");u("4.7B Check: \u2713 Client graft base and orphan relations are correctly set.");let E=await new q().getIbGibGraph(n,l,!0);if(!E.success||!E.graph)throw new Error(`Failed to fetch merged graph from server: ${E.message}`);let S=E.graph[l];if(!S)throw new Error("Merged V3 tip is not present on the server!");if(S.data?.fieldA!=="source_edit"||S.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");u("4.7B Check: \u2713 Server tip has matching merged edits."),u("\u2713 4.7B Check SUCCESS: Divergent branches merged successfully via optimistic graft!"),o.textContent="\u2713 4.7B Check Success"}catch(t){u(`\u2717 4.7B Check FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(md,"init4_7bCheckButton");var pt={};function Ed(){let o=document.getElementById("btn-4-8b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.8B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:"test-sender-secret-phase4-8b",syncSalt:"senderidentitysyncsaltphase4-8b",manageSalt:"senderidentitymanagesaltphase4-8b",metaspace:t,space:e,apiBridge:r,phaseText:"4.8B"});let n=C.domainI;pt.domainI_latest=n;let a=y({ibGib:n});u("4.8B Setup: Creating temporary remote space...");let s=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_8b",getFnPrompt:t.getFnPrompt}});await s.initialized,await Ve({domainI:n,metaspace:t,fromSpace:e,toSpace:s});let i=await B.firstGen({parentIbGib:j,ib:"timeline_root_conflict_4_8b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await t.persistTransformResult({resTransform:i,space:e}),await t.registerNewIbGib({ibGib:c,space:e}),pt.testRoot=c;let l=await Y({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:t,space:e}),d=await t.getDependencyGraph({ibGibAddr:y({ibGib:c}),space:e}),f=await t.getDependencyGraph({ibGibAddr:y({ibGib:l}),space:e}),p={...d,...f};await t.put({ibGibs:Object.values(p),space:s}),await t.registerNewIbGib({ibGib:c,space:s}),await t.registerNewIbGib({ibGib:l,space:s}),u("4.8B Setup: Syncing v1_common to server..."),await oe({domainIbGibs:[l],passLabel:"Seed v1_common",metaspace:t,space:e}),u("4.8B Setup: \u2713 Seeding complete on server."),await Ve({domainI:C.domainI,metaspace:t,fromSpace:e,toSpace:s});let h=await B.firstGen({parentIbGib:j,ib:"beta_multitimelines_withid_4_8b",data:{fieldA:"beta field A created on source"},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),g=h.newIbGib;await t.persistTransformResult({resTransform:h,space:e}),await t.registerNewIbGib({ibGib:g,space:e}),pt.targetBetaV0=g,u(`4.8B Setup: \u2713 Created client independent related timeline Beta: ${y({ibGib:g})}`);let m=await Y({timeline:l,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:t,space:e}),E=await pr({timeline:m,metaspace:t,space:e,rel8nInfos:[{rel8nName:"testrel8n",ibGibs:[g]}]});pt.targetAlphaV3a=E,u(`4.8B Setup: \u2713 Created client divergent edit V3a: ${y({ibGib:E})}`);let S=await Y({timeline:l,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:t,space:s});u(`4.8B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:S})}`),u("4.8B Setup: Pushing V2b from remote space to server..."),await tt({domainIbGibs:[S],passLabel:"Push V2b from remoteSpace",metaspace:t,space:s,primarySpace:e,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-8b"}),pt.domainI_latest=C.domainI,u("4.8B Setup: \u2713 Server tip is now V2b. Evolved identity copied back."),u("\u2713 4.8B Setup Complete! Ready for 4.8B Sync."),o.textContent="\u2713 4.8B Setup Complete";let A=document.getElementById("btn-4-8b-sync");A&&(A.disabled=!1)}catch(t){u(`\u2717 4.8B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(Ed,"init4_8bSetupButton");function wd(){let o=document.getElementById("btn-4-8b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.8B Sync: Initiating WebSocket Sync for divergent edit V3a (with related timeline Beta)...");let t=pt.domainI_latest,e=pt.targetAlphaV3a;if(!t||!e){u("\u26A0 4.8B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let r=await M(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space.");await oe({domainIbGibs:[e],passLabel:"Sync V3a and merge",metaspace:r,space:n}),pt.domainI_latest=C.domainI,u("\u2713 4.8B Sync Execution Complete! Ready for 4.8B Check."),o.textContent="\u2713 4.8B Sync Run";let a=document.getElementById("btn-4-8b-check");a&&(a.disabled=!1)}catch(t){u(`\u2717 4.8B Sync FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(wd,"init4_8bSyncButton");function yd(){let o=document.getElementById("btn-4-8b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.8B Check: Verifying merged tip (V4) contains both edits on client and server...");let t=pt.domainI_latest,e=pt.testRoot,r=pt.targetAlphaV3a,n=pt.targetBetaV0;if(!t||!e||!r||!n){u("\u26A0 4.8B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let a=y({ibGib:t}),s=ee({ibGib:e,defaultIfNone:"incomingAddr"})??y({ibGib:e}),i=y({ibGib:n}),c=await M(),l=await c.getLocalUserSpace({});if(!l)throw new Error("No default space.");let f=(await c.getLocalUserSpace({}).then(G=>new Ne().getKnowledgeMap({space:G,metaspace:c,domainIbGibs:[e]})))[s];if(u(`4.8B Check: Client tip address: ${f}`),!f)throw new Error("Client default space is missing the timeline tip.");let p=await c.get({addr:f,space:l});if(!p.success||!p.ibGibs||p.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let h=p.ibGibs[0];if(!h.data||!h.data.fieldA||!h.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${h.data?.fieldA}, fieldB: ${h.data?.fieldB}`);u("4.8B Check: \u2713 Client tip has both fieldA and fieldB edits.");let g=h.rel8ns?.[yt];if(!g?.[0])throw new Error("Client tip is missing graftinfo relations.");let m=await c.get({addr:g[0],space:l});if(!m.success||!m.ibGibs||m.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let E=m.ibGibs[0],S=E.rel8ns?.[ar],A=E.rel8ns?.[Lt];if(!S||!A)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");u("4.8B Check: \u2713 Client graft base and orphan relations are correctly set.");let _=new q;u("4.8B Check: Fetching server timeline graph...");let $=await _.getIbGibGraph(a,f,!0);if(!$.success||!$.graph)throw new Error(`Failed to fetch merged graph from server: ${$.message}`);let T=$.graph[f];if(!T)throw new Error("Merged V4 tip is not present on the server!");if(T.data?.fieldA!=="source_edit"||T.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");u("4.8B Check: \u2713 Server tip has matching merged edits."),u("4.8B Check: Verifying related timeline Beta is present on the server...");let I=await _.getIbGibGraph(a,i,!0);if(!I.success||!I.graph||!I.graph[i])throw new Error(`Related timeline Beta (${i}) is missing from the server!`);u("4.8B Check: \u2713 Related timeline Beta successfully verified on the server."),u("\u2713 4.8B Check SUCCESS: Divergent branches merged successfully and related timeline synced on server!"),o.textContent="\u2713 4.8B Check Success"}catch(t){u(`\u2717 4.8B Check FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(yd,"init4_8bCheckButton");var Rt={},Zn=`This is the initial quiz question.
32
+ It has multiple lines.
33
+ Students will answer this.`,$d=`
34
+ Instructor added hint.`,Id=`Student note: Confusing!
35
+ `;function _d(){let o=document.getElementById("btn-4-9b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.9B Setup: Setting up identities, seeding text history, and creating divergent branches...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:"test-sender-secret-phase4-9b",syncSalt:"senderidentitysyncsaltphase4-9b",manageSalt:"senderidentitymanagesaltphase4-9b",metaspace:t,space:e,apiBridge:r,phaseText:"4.9B"});let n=C.domainI;Rt.domainI_latest=n;let a=y({ibGib:n});u("4.9B Setup: Creating temporary remote space...");let s=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_9b",getFnPrompt:t.getFnPrompt}});await s.initialized,await Ve({domainI:n,metaspace:t,fromSpace:e,toSpace:s});let i=await B.firstGen({parentIbGib:j,ib:"timeline_root_text_conflict_4_9b",data:{text:Zn,label:"TextRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await t.persistTransformResult({resTransform:i,space:e}),await t.registerNewIbGib({ibGib:c,space:e}),Rt.testRoot=c;let l=await t.getDependencyGraph({ibGibAddr:y({ibGib:c}),space:e});await t.put({ibGibs:Object.values(l),space:s}),await t.registerNewIbGib({ibGib:c,space:s}),u("4.9B Setup: Syncing testRoot to server..."),await oe({domainIbGibs:[c],passLabel:"Seed testRoot",metaspace:t,space:e}),u("4.9B Setup: \u2713 Seeding complete on server."),await Ve({domainI:C.domainI,metaspace:t,fromSpace:e,toSpace:s});let d=await Y({timeline:c,mut8Opts:{mut8Ib:c.ib+"_appended",dataToAddOrPatch:{text:Zn+$d}},metaspace:t,space:e});Rt.targetAlphaV1Source=d,u(`4.9B Setup: \u2713 Created client appended edit: ${y({ibGib:d})}`);let f=await Y({timeline:c,mut8Opts:{mut8Ib:c.ib+"_prepended",dataToAddOrPatch:{text:Id+Zn}},metaspace:t,space:s});u(`4.9B Setup: \u2713 Created remote prepended edit: ${y({ibGib:f})}`),u("4.9B Setup: Pushing remote prepended edit to server..."),await tt({domainIbGibs:[f],passLabel:"Push remote prepended edit",metaspace:t,space:s,primarySpace:e,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-9b"}),Rt.domainI_latest=C.domainI,u("4.9B Setup: \u2713 Server tip is now the prepended edit. Evolved identity copied back."),u("\u2713 4.9B Setup Complete! Ready for 4.9B Sync."),o.textContent="\u2713 4.9B Setup Complete";let p=document.getElementById("btn-4-9b-sync");p&&(p.disabled=!1)}catch(t){u(`\u2717 4.9B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(_d,"init4_9bSetupButton");function Sd(){let o=document.getElementById("btn-4-9b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.9B Sync: Initiating WebSocket Sync for divergent edit (LCS text merge)...");let t=Rt.domainI_latest,e=Rt.targetAlphaV1Source;if(!t||!e){u("\u26A0 4.9B Sync: Missing setup state. Please run Setup first."),o.disabled=!1;return}let r=await M(),n=await r.getLocalUserSpace({});if(!n)throw new Error("No default space.");await oe({domainIbGibs:[e],passLabel:"Sync divergent edit and merge",metaspace:r,space:n}),Rt.domainI_latest=C.domainI,u("\u2713 4.9B Sync Execution Complete! Ready for 4.9B Check."),o.textContent="\u2713 4.9B Sync Run";let a=document.getElementById("btn-4-9b-check");a&&(a.disabled=!1)}catch(t){u(`\u2717 4.9B Sync FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(Sd,"init4_9bSyncButton");function Ad(){let o=document.getElementById("btn-4-9b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.9B Check: Verifying LCS merged text on client and server...");let t=Rt.domainI_latest,e=Rt.testRoot,r=Rt.targetAlphaV1Source;if(!t||!e||!r){u("\u26A0 4.9B Check: Missing state. Did Setup and Sync run?"),o.disabled=!1;return}let n=y({ibGib:t}),a=ee({ibGib:e,defaultIfNone:"incomingAddr"})??y({ibGib:e}),s=await M(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let l=(await s.getLocalUserSpace({}).then(T=>new Ne().getKnowledgeMap({space:T,metaspace:s,domainIbGibs:[e]})))[a];if(u(`4.9B Check: Client tip address: ${l}`),!l)throw new Error("Client default space is missing the timeline tip.");let d=await s.get({addr:l,space:i});if(!d.success||!d.ibGibs||d.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let f=d.ibGibs[0],p=Id+Zn+$d;if(f.data?.text!==p)throw new Error(`Merged client tip text mismatch! Expected:
36
+ ${p}
37
+ Actual:
38
+ ${f.data?.text}`);u("4.9B Check: \u2713 Client tip text contains both prepend and append edits merged correctly.");let h=f.rel8ns?.[yt];if(!h?.[0])throw new Error("Client tip is missing graftinfo relations.");let g=await s.get({addr:h[0],space:i});if(!g.success||!g.ibGibs||g.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let m=g.ibGibs[0],E=m.rel8ns?.[ar],S=m.rel8ns?.[Lt];if(!E||!S)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");u("4.9B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new q;u("4.9B Check: Fetching server timeline graph...");let _=await A.getIbGibGraph(n,l,!0);if(!_.success||!_.graph)throw new Error(`Failed to fetch merged graph from server: ${_.message}`);let $=_.graph[l];if(!$)throw new Error("Merged tip is not present on the server!");if($.data?.text!==p)throw new Error(`Server tip text mismatch! Expected:
39
+ ${p}
40
+ Actual:
41
+ ${$.data?.text}`);u("4.9B Check: \u2713 Server tip text matches the client-side merged text."),u("\u2713 4.9B Check SUCCESS: LCS text field merge conflict resolved and verified on both client and server!"),o.textContent="\u2713 4.9B Check Success"}catch(t){u(`\u2717 4.9B Check FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(Ad,"init4_9bCheckButton");var X={},Hs="testrel8n";function Td(){let o=document.getElementById("btn-4-10b-setup");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.10B Setup: Setting up identities and preparing Round 1 & Round 2 divergence...");let t=await M(),e=await t.getLocalUserSpace({});if(!e)throw new Error("No default space.");let r=new q;await je({masterSecret:"test-sender-secret-phase4-10b",syncSalt:"senderidentitysyncsaltphase4-10b",manageSalt:"senderidentitymanagesaltphase4-10b",metaspace:t,space:e,apiBridge:r,phaseText:"4.10B"});let n=C.domainI;X.domainI_initial=n,X.domainI_latest=n;let a=y({ibGib:n});u("4.10B Setup: Creating temporary remote space...");let s=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_10b",getFnPrompt:t.getFnPrompt}});await s.initialized,X.remoteSpace=s,await Ve({domainI:n,metaspace:t,fromSpace:e,toSpace:s}),u("4.10B Setup: Creating common history for alpha...");let i=await B.firstGen({parentIbGib:j,ib:"timeline_root_alpha_4_10b",data:{commonField:"common field R1 val",label:"AlphaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;X.alpha_v0=c,await t.persistTransformResult({resTransform:i,space:e}),await t.registerNewIbGib({ibGib:c,space:e});let l=ee({ibGib:c,defaultIfNone:"incomingAddr"});X.alpha_tjpAddr=l,await t.persistTransformResult({resTransform:i,space:s}),await t.registerNewIbGib({ibGib:c,space:s}),u("4.10B Setup: Seeding alpha_v0 to server..."),await oe({domainIbGibs:[c],passLabel:"Seed alpha_v0",metaspace:t,space:e}),X.domainI_latest=C.domainI,u("4.10B Setup: \u2713 alpha_v0 seeded on server."),await Ve({domainI:C.domainI,metaspace:t,fromSpace:e,toSpace:s});let d=await B.firstGen({parentIbGib:j,ib:"timeline_root_beta_4_10b",data:{fieldA:"beta field A created on source",label:"BetaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),f=d.newIbGib;await t.persistTransformResult({resTransform:d,space:e}),await t.registerNewIbGib({ibGib:f,space:e}),X.r2_beta_v0_source=f;let p=ee({ibGib:f,defaultIfNone:"incomingAddr"});X.beta_tjpAddr=p;let h=await Y({timeline:c,mut8Opts:{mut8Ib:c.ib+"_r2client",dataToAddOrPatch:{fieldA:"source_edit_r2"}},metaspace:t,space:e});u(`r2_alpha_v1_source_sansBeta.gib: ${h.gib}`),Ks=y({ibGib:f});let g=await pr({timeline:h,metaspace:t,space:e,rel8nInfos:[{rel8nName:Hs,ibGibs:[f]}]});X.r2_alpha_v3_source_rel8beta=g,u(`r2_alpha_v2_source_rel8dBeta.gib: ${g.gib}`),u("4.10B Setup: \u2713 Created client Round 2 edits (alpha fieldA edit + relate beta).");let m=await Y({timeline:c,mut8Opts:{mut8Ib:c.ib+"_r2remote",dataToAddOrPatch:{fieldB:"remote_edit_r2"}},metaspace:t,space:s});console.log(`alpha_v0: ${F(c)}`),console.log(`r2_alpha_v1_remote: ${F(m)}`),u(`r2_alpha_v1_remote.gib: ${m.gib}`),u("4.10B Setup: Pushing remote Round 2 edit to server..."),await tt({domainIbGibs:[m],passLabel:"Push remote Round 2 edit",metaspace:t,space:s,primarySpace:e,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-10b"}),X.domainI_latest=C.domainI,u("\u2713 4.10B Setup Complete! Ready for 4.10B Sync (which runs Round 2, 3, and 4 in succession)."),o.textContent="\u2713 4.10B Setup Complete";let E=document.getElementById("btn-4-10b-sync");E&&(E.disabled=!1)}catch(t){u(`\u2717 4.10B Setup FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(Td,"init4_10bSetupButton");var Vs,Ks;function Gd(){let o=document.getElementById("btn-4-10b-sync");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.10B Sync: Initiating WebSocket Sync for Round 2, 3, and 4 sequential evolution...");let t=X.domainI_latest,e=X.remoteSpace,r=X.alpha_tjpAddr,n=X.beta_tjpAddr,a=X.alpha_v0,s=await M(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",l=y({ibGib:X.domainI_initial});u("4.10B Sync: Running Round 2 Sync (merging divergent alpha edits)..."),await oe({domainIbGibs:[X.r2_alpha_v3_source_rel8beta],passLabel:"Sync divergent alpha edits R2",metaspace:s,space:i}),X.domainI_latest=C.domainI,u("4.10B Sync: \u2713 Round 2 Sync complete."),await Ve({domainI:C.domainI,metaspace:s,fromSpace:i,toSpace:e}),u("4.10B Sync: Preparing Round 3 divergence (multiple conflicting timelines)...");let d=await new Ne().getKnowledgeMap({domainIbGibs:[X.r2_alpha_v3_source_rel8beta,X.r2_beta_v0_source],space:i,metaspace:s}),f=d[r],p=d[n],h=await s.get({addr:f,space:i}),g=await s.get({addr:p,space:i}),m=await Y({timeline:h.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r3client",dataToAddOrPatch:{fieldC:"source_edit_r3"}},metaspace:s,space:i}),E=await Y({timeline:g.ibGibs[0],mut8Opts:{mut8Ib:X.r2_beta_v0_source.ib+"_r3client",dataToAddOrPatch:{betaFieldA:"source_beta_edit_r3"}},metaspace:s,space:i});u("4.10B Sync: Updating remote space to latest merged tips...");let S=await s.getLatestAddr({addr:r,space:e}),$=[(await s.get({addr:S,space:e})).ibGibs[0]],T=await s.getLatestAddr({addr:n,space:e});if(T){let oo=await s.get({addr:T,space:e});$.push(oo.ibGibs[0])}await tt({domainIbGibs:$,passLabel:"Pull merged R2 tips to remoteSpace",metaspace:s,space:e,primarySpace:i,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-10b"}),X.domainI_latest=C.domainI;let I=await new Ne().getKnowledgeMap({space:e,metaspace:s,domainIbGibs:[a,X.r2_beta_v0_source]}),G=I[r],v=I[n],N=await s.get({addr:G,space:e}),O=await s.get({addr:v,space:e}),P=await Y({timeline:N.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r3remote",dataToAddOrPatch:{fieldD:"remote_edit_r3"}},metaspace:s,space:e}),R=await Y({timeline:O.ibGibs[0],mut8Opts:{mut8Ib:X.r2_beta_v0_source.ib+"_r3remote",dataToAddOrPatch:{betaFieldB:"remote_beta_edit_r3"}},metaspace:s,space:e});u("4.10B Sync: Pushing remote Round 3 edits to server..."),await tt({domainIbGibs:[P,R],passLabel:"Push remote Round 3 edits",metaspace:s,space:e,primarySpace:i,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-10b"}),X.domainI_latest=C.domainI,u("4.10B Sync: Running Round 3 Client Sync (merging alpha & beta divergence)..."),await oe({domainIbGibs:[m,E],passLabel:"Sync Client Round 3 edits",metaspace:s,space:i}),X.domainI_latest=C.domainI,u("4.10B Sync: \u2713 Round 3 Sync complete."),await Ve({domainI:C.domainI,metaspace:s,fromSpace:i,toSpace:e}),u("4.10B Sync: Preparing Round 4 divergence (post-graft chain edits & new timeline)...");let k=await new Ne().getKnowledgeMap({space:i,metaspace:s,domainIbGibs:[a,X.r2_beta_v0_source]}),H=k[r],K=k[n],ye=await s.get({addr:H,space:i}),ie=await s.get({addr:K,space:i}),Ke=await Y({timeline:ye.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r4client_v5",dataToAddOrPatch:{fieldE:"source_edit_r4_v5"}},metaspace:s,space:i}),Ye=await B.firstGen({parentIbGib:j,ib:"timeline_root_gamma_4_10b",data:{gammaField:"gamma created on client",label:"GammaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),We=Ye.newIbGib;await s.persistTransformResult({resTransform:Ye,space:i}),await s.registerNewIbGib({ibGib:We,space:i});let ct=ee({ibGib:We,defaultIfNone:"incomingAddr"});X.gamma_tjpAddr=ct,Vs=y({ibGib:We});let fe=await pr({timeline:Ke,metaspace:s,space:i,rel8nInfos:[{rel8nName:Hs,ibGibs:[We]}]}),ht=await Y({timeline:fe,mut8Opts:{mut8Ib:a.ib+"_r4client_v7",dataToAddOrPatch:{fieldF:"source_edit_r4_v7"}},metaspace:s,space:i}),It=await Y({timeline:ie.ibGibs[0],mut8Opts:{mut8Ib:X.r2_beta_v0_source.ib+"_r4client_v2",dataToAddOrPatch:{betaFieldD:"source_beta_edit_r4_v2"}},metaspace:s,space:i});u("4.10B Sync: Updating remote space to Round 3 merged tips...");let be=await s.getLatestAddr({addr:r,space:e}),gr=[(await s.get({addr:be,space:e})).ibGibs[0]],Wt=await s.getLatestAddr({addr:n,space:e});if(Wt){let oo=await s.get({addr:Wt,space:e});gr.push(oo.ibGibs[0])}await tt({domainIbGibs:gr,passLabel:"Pull merged R3 tips to remoteSpace",metaspace:s,space:e,primarySpace:i,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-10b"}),X.domainI_latest=C.domainI;let Lr=await new Ne().getKnowledgeMap({space:e,metaspace:s,domainIbGibs:[a,X.r2_beta_v0_source]}),gt=Lr[r],No=Lr[n],Do=await s.get({addr:gt,space:e}),ve=await s.get({addr:No,space:e}),Bt=await Y({timeline:Do.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r4remote_v5",dataToAddOrPatch:{fieldG:"remote_edit_r4_v5"}},metaspace:s,space:e}),ze=await Y({timeline:ve.ibGibs[0],mut8Opts:{mut8Ib:X.r2_beta_v0_source.ib+"_r4remote_v2",dataToAddOrPatch:{betaFieldC:"remote_beta_edit_r4_v2"}},metaspace:s,space:e});u("4.10B Sync: Pushing remote Round 4 edits to server..."),await tt({domainIbGibs:[Bt,ze],passLabel:"Push remote Round 4 edits",metaspace:s,space:e,primarySpace:i,domainI:C.domainI,masterSecret:"test-sender-secret-phase4-10b"}),X.domainI_latest=C.domainI,u("4.10B Sync: Running final Round 4 Client Sync (merging alpha, beta, and propagating gamma)..."),await oe({domainIbGibs:[ht,It,We],passLabel:"Sync final Round 4 edits",metaspace:s,space:i}),X.domainI_latest=C.domainI,u("\u2713 4.10B Sync: All rounds of divergent edits and merges complete!"),o.textContent="\u2713 4.10B Sync Complete";let Oo=document.getElementById("btn-4-10b-check");Oo&&(Oo.disabled=!1)}catch(t){u(`\u2717 4.10B Sync FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(Gd,"init4_10bSyncButton");function vd(){let o=document.getElementById("btn-4-10b-check");o&&o.addEventListener("click",async()=>{try{o.disabled=!0,u("4.10B Check: Verifying multi-round merged timelines on client and server...");let t=X.domainI_latest,e=X.alpha_tjpAddr,r=X.beta_tjpAddr,n=X.gamma_tjpAddr,a=await M(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=y({ibGib:X.domainI_initial}),c=await new Ne().getKnowledgeMap({space:s,metaspace:a,domainIbGibs:[X.domainI_initial]}),l=await a.getLatestAddr({addr:e,space:s}),d=await a.getLatestAddr({addr:r,space:s}),f=await a.getLatestAddr({addr:n,space:s});if(!l||!d||!f)throw new Error("Client space is missing timeline tips for Alpha, Beta, or Gamma.");let p=await a.get({addr:l,space:s}),h=await a.get({addr:d,space:s}),g=p.ibGibs[0],m=h.ibGibs[0];if(g.data?.fieldA!=="source_edit_r2")throw new Error(`Alpha fieldA mismatch! Expected 'source_edit_r2', got '${g.data?.fieldA}'`);if(g.data?.fieldB!=="remote_edit_r2")throw new Error(`Alpha fieldB mismatch! Expected 'remote_edit_r2', got '${g.data?.fieldB}'`);if(g.data?.fieldC!=="source_edit_r3")throw new Error(`Alpha fieldC mismatch! Expected 'source_edit_r3', got '${g.data?.fieldC}'`);if(g.data?.fieldD!=="remote_edit_r3")throw new Error(`Alpha fieldD mismatch! Expected 'remote_edit_r3', got '${g.data?.fieldD}'`);if(g.data?.fieldE!=="source_edit_r4_v5")throw new Error(`Alpha fieldE mismatch! Expected 'source_edit_r4_v5', got '${g.data?.fieldE}'`);if(g.data?.fieldF!=="source_edit_r4_v7")throw new Error(`Alpha fieldF mismatch! Expected 'source_edit_r4_v7', got '${g.data?.fieldF}'`);if(g.data?.fieldG!=="remote_edit_r4_v5")throw new Error(`Alpha fieldG mismatch! Expected 'remote_edit_r4_v5', got '${g.data?.fieldG}'`);if(u("4.10B Check: \u2713 Client Alpha merged tip contains all Round 2, 3, and 4 edits."),m.data?.betaFieldA!=="source_beta_edit_r3")throw new Error(`Beta betaFieldA mismatch! Expected 'source_beta_edit_r3', got '${m.data?.betaFieldA}'`);if(m.data?.betaFieldB!=="remote_beta_edit_r3")throw new Error(`Beta betaFieldB mismatch! Expected 'remote_beta_edit_r3', got '${m.data?.betaFieldB}'`);if(m.data?.betaFieldC!=="remote_beta_edit_r4_v2")throw new Error(`Beta betaFieldC mismatch! Expected 'remote_beta_edit_r4_v2', got '${m.data?.betaFieldC}'`);if(m.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error(`Beta betaFieldD mismatch! Expected 'source_beta_edit_r4_v2', got '${m.data?.betaFieldD}'`);u("4.10B Check: \u2713 Client Beta merged tip contains all Round 3 and 4 edits.");let E=g.rel8ns?.[Hs]||[];if(!Ks)throw new Error("(UNEXPECTED) betaAddr falsy? (E: 81c032ae7a93bddfd8eed6664d314826)");if(!E.includes(Ks))throw new Error("Client Alpha tip is missing relation to Beta timeline.");if(!Vs)throw new Error("(UNEXPECTED) gammaAddr falsy? (E: 12220a81d3b86385d1683d5a6bae5826)");if(!E.includes(Vs))throw new Error("Client Alpha tip is missing relation to Gamma timeline.");u("4.10B Check: \u2713 Client Alpha tip retains relation to Gamma.");let S=new q;u("4.10B Check: Fetching server timeline graphs...");let A=await S.getIbGibGraph(i,l,!0),_=await S.getIbGibGraph(i,d,!0);if(!A.success||!A.graph||!_.success||!_.graph)throw new Error("Failed to fetch merged graphs from server.");let $=A.graph[l],T=_.graph[d];if(!$||!T)throw new Error("Server is missing the final merged tips for Alpha or Beta.");if($.data?.fieldF!=="source_edit_r4_v7"||$.data?.fieldG!=="remote_edit_r4_v5")throw new Error("Server Alpha tip does not match final client merged state.");if(T.data?.betaFieldC!=="remote_beta_edit_r4_v2"||T.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error("Server Beta tip does not match final client merged state.");u("4.10B Check: \u2713 Server tips match client merged states perfectly."),u("\u2713 4.10B Check SUCCESS: Advanced multi-round/timeline conflict resolved and verified on both client and server!"),o.textContent="\u2713 4.10B Check Success"}catch(t){u(`\u2717 4.10B Check FAILED: ${w(t)}`),console.error(t),o.disabled=!1}})}b(vd,"init4_10bCheckButton");function B6(){let o=`${ae}[initDevTools]`;try{let t=document.getElementById("dev-tools-row-select");t&&(t.addEventListener("change",()=>{let e=t.value;document.querySelectorAll(".dev-panel-row-container").forEach(n=>{let a=n.getAttribute("data-row-id");e==="all"||a===e?n.style.display="flex":n.style.display="none"})}),t.dispatchEvent(new Event("change"))),Pl(),Rl(),Ll(),Bl(),kl(),Ml(),Ul(),Fl(),jl(),Vl(),Kl(),Hl(),Xl(),ql(),Yl(),Wl(),zl(),Jl(),Zl(),Ql(),ed(),td(),rd(),od(),nd(),ad(),cd(),ld(),dd(),fd(),bd(),pd(),ud(),gd(),md(),Ed(),wd(),yd(),_d(),Sd(),Ad(),Td(),Gd(),vd()}catch(t){console.error(`${o} ${w(t)}`)}}b(B6,"initDevTools");export{b as a,Ie as b,U as c,Ce as d,_e as e,V as f,F as g,Se as h,w as i,Qn as j,rt as k,Po as l,Dd as m,Zs as n,kr as o,z as p,j as q,Ae as r,At as s,ni as t,Jt as u,y as v,J as w,pe as x,oa as y,ue as z,ce as A,Oe as B,ot as C,He as D,le as E,Ur as F,Fr as G,Mr as H,B as I,Jp as J,Zp as K,Qp as L,Uo as M,kd as N,li as O,di as P,uh as Q,gh as R,mh as S,Md as T,Eh as U,ca as V,pa as W,Ud as X,Gh as Y,Vo as Z,yr as _,$i as $,Ti as aa,Ko as ba,Vd as ca,Kd as da,Hu as ea,Xu as fa,qu as ga,Yu as ha,Wu as ia,zu as ja,zd as ka,Jd as la,Ni as ma,Sa as na,Qd as oa,ef as pa,Vr as qa,bo as ra,Mi as sa,df as ta,ji as ua,Bg as va,Ug as wa,W as xa,Xe as ya,Na as za,ge as Aa,ff as Ba,tn as Ca,rn as Da,ke as Ea,Da as Fa,Ki as Ga,Te as Ha,jr as Ia,uo as Ja,qi as Ka,Ct as La,en as Ma,pf as Na,hf as Oa,Ht as Pa,pm as Qa,uf as Ra,gf as Sa,mf as Ta,Me as Ua,Ef as Va,wf as Wa,yf as Xa,mt as Ya,vm as Za,sc as _a,po as $a,Nt as ab,ft as bb,ic as cb,ee as db,qe as eb,rr as fb,km as gb,Tf as hb,Mm as ib,Um as jb,Fm as kb,jm as lb,Eo as mb,Lm as nb,aE as ob,sE as pb,iE as qb,cE as rb,lE as sb,Kr as tb,vf as ub,Cf as vb,xf as wb,Ir as xb,M as yb,Nf as zb,$c as Ab,yc as Bb,Of as Cb,Lf as Db,Pf as Eb,Rf as Fb,Bf as Gb,kf as Hb,Mf as Ib,Uf as Jb,Xa as Kb,Va as Lb,sn as Mb,Ff as Nb,jf as Ob,lc as Pb,Vf as Qb,Sc as Rb,Kf as Sb,Hf as Tb,rw as Ub,yo as Vb,za as Wb,Ja as Xb,Pe as Yb,or as Zb,Aw as _b,Ot as $b,Ue as ac,Nl as bc,Nr as cc,Ob as dc,Rs as ec,pr as fc,Cs as gc,Y as hc,yb as ic,Cr as jc,xr as kc,hs as lc,sr as mc,Un as nc,o1 as oc,u as pc,B6 as qc};
42
+ //# sourceMappingURL=chunk-SUQ5QJH4.mjs.map