@ibgib/space-gib 0.0.19 → 0.0.21

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,22 @@
1
+ var uc=Object.defineProperty;var f=(r,e)=>uc(r,"name",{value:e,configurable:!0});var Q=/^[a-zA-Z0-9_\-.]{1,256}$/,We=/^[a-zA-Z0-9_]{1,255}$/,hs=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,gs=/^(\[.+\]).+$/,ms=/^[0-9a-fA-F]{32}$/,Es=/^[0-9a-fA-F]{64}$/;var xt="/",ws="_nonalphanumerics_";var Gt=!1,Uo=globalThis.crypto,{subtle:hc}=Uo,Ee={sha_256:"SHA-256",sha_512:"SHA-512"};function C(r){return JSON.parse(JSON.stringify(r))}f(C,"clone");function Oe(r){return(r??new Date).toUTCString()}f(Oe,"getTimestamp");var gc=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));async function X({s:r,algorithm:e="SHA-256"}){if(!r)return"";try{let t=Object.values(Ee);if(!t.includes(e))throw new Error(`Only ${t} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let o=new TextEncoder().encode(r),n=await hc.digest(e,o),s=new Uint8Array(n),i="";for(let a=0;a<s.length;a++)i+=gc[s[a]];return i}catch(t){throw console.error(E(t.message)),t}}f(X,"hash");async function j(r){if(!globalThis.crypto)throw new Error("globalThis.crypto falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)");let e;if(r&&r>16||!globalThis.crypto.randomUUID){if(!globalThis.crypto.getRandomValues)throw new Error("globalThis.crypto.getRandomValues falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: d2fa34b26d0808adc8184d98cc767d26)");r||=32;let t=Uo.getRandomValues(new Uint8Array(r)),o="";for(let n=0;n<t.length;n++)o+=String.fromCharCode(t[n]);e=await X({s:o})}else{if(!globalThis.crypto.randomUUID)throw new Error("globalThis.crypto.randomUUID falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: e30da81f5c284d6a389930b5e7daa826)");let t=Uo.randomUUID();e=await X({s:t})}if(!e)throw new Error("(UNEXPECTED) uuid falsy? could not create uuid? (E: 5276bcc4e8f75aa2c82a54a8c8b2d626)");return e}f(j,"getUUID");function H(r){return JSON.stringify(r,null,2)}f(H,"pretty");async function de(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}f(de,"delay");function E(r){return!r&&r!==0?"[error is falsy]":typeof r=="string"?r:typeof r.message=="string"?r.message:typeof r=="number"?JSON.stringify(r):r.error?(console.warn(`[${E.name}] this fn takes the raw error object. no destructure required. change your call from extractErrorMsg({error}) to extractErrorMsg(error). (W: ea49af5fd76d4b80a55a108d73a3e9b4)`),E(r.error)):`[error is not a string and error.message is not a string. typeof error: ${typeof r} (E: d5a7723ca59646838308bc9e53a43134)]`}f(E,"extractErrorMsg");function ko({items:r,keyFn:e}){let t=`[${ko.name}]`;try{let o={};for(let n=0;n<r.length;n++){let s=r[n],i=e(s);o[i]=[...o[i]??[],s]}return o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(ko,"groupBy");function yr({min:r,max:e,chars:t,noSpaces:o}){return r=r??1,e=e??999999999999,t=t??"",o?new RegExp(`^[\\w${t}]{${r},${e}}$`):new RegExp(`^[\\w\\s${t}]{${r},${e}}$`)}f(yr,"getRegExp");function we(r){let e;if(r){if(e=new Date(r),e.toString()==="Invalid Date")throw new Error(`invalid date created by timestamp (${r}) (E: cbd6aeefe00708184e276ea3c2532b22)`)}else e=new Date;return e.getTime().toString()}f(we,"getTimestampInTicks");function Mo({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}){let i=`[${Mo.name}]`;try{return bt({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}).toUTCString()}catch(a){throw console.log(`${i} ${a.message}`),a}}f(Mo,"getExpirationUTCString");function bt({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}){let i=`[${bt.name}]`;try{if(!r&&!e&&!t&&!o&&!n&&!s)throw new Error("either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)");r=r?new Date(r):new Date;let a,c;return e?(a=r.getFullYear()+e,c=r.setFullYear(a),bt({startDate:new Date(c),months:t,days:o,hours:n,seconds:s})):t?(a=r.getMonth()+t,c=r.setMonth(a),bt({startDate:new Date(c),years:e,days:o,hours:n,seconds:s})):o?(a=r.getDate()+o,c=r.setDate(a),bt({startDate:new Date(c),years:e,months:t,hours:n,seconds:s})):n?(a=r.getHours()+n,c=r.setHours(a),bt({startDate:new Date(c),years:e,months:t,days:o,seconds:s})):s?(a=r.getSeconds()+s,c=r.setSeconds(a),bt({startDate:new Date(c),years:e,months:t,days:o,hours:n})):r}catch(a){throw console.log(`${i} ${a.message}`),a}}f(bt,"addTimeToDate");function jo({expirationTimestampUTC:r}){let e=`[${jo.name}]`;try{if(!r)throw new Error("expirationTimestampUTC required (E: 5eeb1e29f93d64f70c71a8112080a222)");let t=new Date(r);if(t.toUTCString()==="Invalid Date")throw new Error(`invalid expirationTimestampUTC: ${r} (E: 66a1a165bcf1f9336fe78856ab777822)`);return t<new Date}catch(t){throw console.error(`${e} ${t.message}`),t}}f(jo,"isExpired");function Ir(r){return Array.from(new Set(r))}f(Ir,"unique");function Bo({obj:r,value:e,path:t,pathDelimiter:o,logalot:n}){let s=`[${Bo.name}]`;try{if(n&&console.log(`${s} starting...`),!r)throw new Error("obj required (E: 6a9dd32a361476e80b1bf7b91ec50522)");if(typeof r!="object")throw new Error("obj must be type 'object' (E: 66fdc289b32c06492bd95f5d266e6a22)");if(!t)throw new Error("path required (at the very least should be the key in the root obj.) (E: fc779e7794ead8a0b44e5f2e776b0e22)");o=o||xt;let i=r,a=t.split(o).filter(l=>!!l),c=a.pop();a.forEach(l=>{let d=i[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 i[l]={};i=i[l]}),i[c]=e}catch(i){throw console.error(`${s} ${i.message}`),i}finally{n&&console.log(`${s} complete.`)}}f(Bo,"patchObject");async function Ht({n:r}){let e=`[${Ht.name}]`;try{Gt&&console.log(`${e} starting...`);let t=[];for(let o=0;o<r;o++){let n=await j();t.push(n.substring(0,16))}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Gt&&console.log(`${e} complete.`)}}f(Ht,"getIdPool");function Ne({text:r,length:e,keepLiterals:t=["-"],replaceMap:o}){let n=`[${Ne.name}]`;try{if(Gt&&console.log(`${n} starting... (I: 27437e312e5aa621adfebb84e059c822)`),!r)throw new Error("text required (E: 87e0493613c8b30dfade83e1d2862a22)");let s=r,i={};t=t??[];for(let c=0;c<t.length;c++){let l=t[c],d;do d=$s({count:10});while(d.includes(l)||l.includes(d)||r.includes(d));if(s.includes(l))for(i[d]=l;s.includes(l);)s=s.replace(l,d)}if(o&&Object.keys(o).length>0)for(let c=0;c<Object.keys(o).length;c++){let l=Object.keys(o)[c],d=o[l];for(;s.includes(l);)s=s.replace(l,d)}s=s.replace(/\W/g,"");let a=Object.keys(i);for(let c=0;c<a.length;c++){let l=a[c];for(;s.includes(l);)s=s.replace(l,i[l])}return e&&e>0&&s.length>e&&(Gt&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),s=s.substring(0,e)),s.length===0&&(s=ws),s}catch(s){throw console.error(`${n} ${s.message}`),s}finally{Gt&&console.log(`${n} complete.`)}}f(Ne,"getSaferSubstring");function mc({x:r}){if((r??[]).length===0)return;let e=Math.floor(Math.random()*r.length);return r[e]}f(mc,"pickRandom");function $s({count:r}){let e=`${$s.name}]`;try{if(!Number.isInteger(r))throw new Error("count required to be a number. (E: c0a21d884ebd9afc4b2e8025207e0522)");let t="";for(let o=0;o<r;o++)t+=mc({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(t.length!==r)throw new Error(`${e} (UNEXPECTED) result.length !== count ? (E: 9bec4ec8f78610d8055e565415392a22)`);return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Gt&&console.log(`${e} complete.`)}}f($s,"pickRandom_Letters");function vt({dominant:r,recessive:e}){let t=`[${vt.name}]`;try{if(Array.isArray(r)&&Array.isArray(e)){let o=C(r),n=!1;return e.forEach(s=>{if(typeof s=="string")o.includes(s)||o.push(s);else{n||(console.warn(`${t} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`),n=!0);let i=JSON.stringify(s);o.some(a=>JSON.stringify(a)===i)||o.push(s)}}),o}else if(typeof r=="object"&&typeof e=="object"){let o={...e},n=Object.keys(r),s=Object.keys(e);return n.forEach(i=>{s.includes(i)?Array.isArray(r[i])&&Array.isArray(e[i])?o[i]=vt({dominant:r[i],recessive:e[i]}):r[i]&&!Array.isArray(r[i])&&typeof r[i]=="object"&&e[i]&&!Array.isArray(e[i])&&typeof e[i]=="object"?o[i]=vt({dominant:r[i],recessive:e[i]}):o[i]=r[i]:o[i]=r[i]}),o}else return console.warn(`${t} 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)`),r}catch(o){throw console.error(`${t} ${o.message}`),o}}f(vt,"mergeMapsOrArrays_Naive");var Ec=globalThis.crypto,{subtle:_s}=Ec,Ts=new Array(256);for(let r=0;r<256;++r)Ts[r]=r.toString(16).padStart(2,"0");function As(r){let e=new Uint8Array(r),t="";for(let o=0;o<e.length;o++)t+=Ts[e[o]];return t}f(As,"bufToHex");function Vt(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(o=>Vt(o));let e={},t=Object.keys(r).sort();for(let o of t){let n=r[o];n!==void 0&&(e[o]=Vt(n))}return e}f(Vt,"toNormalizedForHashing");async function Kt(r){if(!r)return"";let e=new TextEncoder().encode(r),t=await _s.digest("SHA-256",e);return As(t)}f(Kt,"hashToHex");async function wc(r,e){let t;if(r){let n=new TextEncoder().encode(r);t=new Uint8Array(n.length+e.length),t.set(n),t.set(e,n.length)}else t=e;let o=await _s.digest("SHA-256",t);return As(o)}f(wc,"hashToHex_Uint8Array");var $c=!1,_r=0,ys=0;async function Is(r,e=""){let t=e||"",o=r.ib,n=r.data,s=r.rel8ns,i=Object.keys(s||{}).length>0&&Object.keys(s||{}).some(u=>s[u]&&s[u].length>0),a=!!n;a&&(typeof n=="string"?a=n.length>0:n instanceof Uint8Array?a=!0:typeof n=="object"?a=Object.keys(n||{}).length>0:a=!0);let c=(await Kt(t?t+o:o)).toUpperCase(),l="";if(i){let u=Vt(s),p=JSON.stringify(u);l=(await Kt(t?t+p:p)).toUpperCase()}let d="";if(a)if(n instanceof Uint8Array)d=(await wc(t,n)).toUpperCase();else{let u=Vt(n),p=JSON.stringify(u);d=(await Kt(t?t+p:p)).toUpperCase()}let b;if(i||a){let u=c+l+d;b=(await Kt(t?t+u:u)).toUpperCase()}else b=(await Kt(t?t+c:c)).toUpperCase();return b}f(Is,"sha256v1_Internal");async function ze(r,e=""){if($c){let t=globalThis.performance?globalThis.performance.now():Date.now(),o=await Is(r,e),n=(globalThis.performance?globalThis.performance.now():Date.now())-t;return _r++,ys+=n,_r%1e3===0&&console.log(`[sha256v1 Profile] Total Runs: ${_r} | Average Duration: ${(ys/_r).toFixed(4)} ms`),o}return Is(r,e)}f(ze,"sha256v1");function _({ib:r,gib:e,ibGib:t,delimiter:o="^"}){return r=r||t?.ib||"",e=e||t?.gib||"",r+o+e}f(_,"getIbGibAddr");function L({ibGib:r,ibGibAddr:e,delimiter:t="^"}){let o="[getIbAndGib]";if(!e)if(r)e=_({ibGib:r});else throw new Error(`${o} We need either an address or an ibGib object`);if(!e)throw new Error(`${o} Couldn't get ibGibAddr. ibGib invalid?`);t||(t="^");let n=e.split(t);return n.length===2?{ib:n[0],gib:n[1]}:n.length===1&&e.endsWith(t)?{ib:n[0],gib:""}:n.length===1&&e.startsWith(t)?{ib:"",gib:n[0]}:n.length===2&&n[0]===""&&n[1]===""?{ib:t,gib:""}:(console.warn(`${o} multiple delimiters found in ibGibAddr. Considering last delimiter as the demarcation of gib hash`),{ib:n.slice(0,n.length-1).join(t),gib:n.slice(n.length-1)[0]})}f(L,"getIbAndGib");var Y;(function(r){r.past="past",r.ancestor="ancestor",r.dna="dna",r.identity="identity",r.tjp="tjp",r.secret="secret",r.encryption="encryption"})(Y||(Y={}));var Dt="ib",R="gib",z={ib:Dt,gib:R},ee="^",Ce=".",Ss="ib^gib",Je=["past","ancestor","dna","tjp"],yc=155,xs=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${yc}}$`);async function ut(r){let e=C(r),t=`[${ut.name}]`;e.srcAddr&&delete e.srcAddr,delete e.src;let o={ib:e.type,data:e,rel8ns:{ancestor:[`${e.type.toString()}${ee}${R}`]}};return o.gib=await ze(o),o}f(ut,"buildDna");function Ic({ibGib:r}){let e=`[${Ic.name}]`;try{if(!r)throw new Error("ibGib required.");let t=["fork","mut8","rel8","plan"].map(n=>`${n}^${R}`);return r.rel8ns&&r.rel8ns.ancestor&&Array.isArray(r.rel8ns.ancestor)&&r.rel8ns.ancestor.some(n=>t.includes(n))||!1}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Ic,"isDna");function te({ibGib:r,gib:e}){return r?te({gib:r.gib}):e?e===R:!0}f(te,"isPrimitive");async function K({ibGib:r,hasTjp:e,tjpAddr:t,gibDelimiter:o,isPrimitive:n,hashAlgorithm:s}){let i=`[${K.name}]`;try{if(!r)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return R;let a=await ze(r,""),c=r.rel8ns??{},l=r.data??{};if(o=o||Ce,e||(e=(c.tjp??[]).length>0||l.isTjp||!1),e){let d;if(c.tjp)if(c.tjp.length===1)if(c.tjp[0])t=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(`${i} found more than one tjp addr...only expecting 1 ATOW. (W: 10ed43f716e743e0afd1954f1ab46789)`),t=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)t=_({ib:r.ib,gib:a});else throw new Error("hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)");if(d=t?L({ibGibAddr:t}).gib:void 0,d)return l.isTjp?a:`${a}${Ce}${d}`;throw new Error("hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)")}else return a}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(K,"getGib");function ie({ibGibAddr:r,gib:e,gibDelimiter:t}){let o=`[${ie.name}]`;try{if(!r&&!e)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(e=e||L({ibGibAddr:r}).gib,e===R)return{isPrimitive:!0};if(t=t??Ce,e.includes(t)){let n=e.split(t);if(n.some(a=>a===""))throw new Error(`unexpected gib that contains gibDelimiter (${t}) but has at least one piece with empty string. (E: 75a94280045541009ee68182d12d3449)`);let s=n.length;return s>2&&console.warn(`${o} gib only expected to have two pieces ATOW. re-examine please. (W: aa4283ac5a5747a386a69966ecdad39d)`),{punctiliarHash:n.splice(0,1)[0],tjpGib:n.join(t),piecesCount:s,delimiter:t}}else return{punctiliarHash:e,piecesCount:1,delimiter:t}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(ie,"getGibInfo");async function Tr(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,destIb:n,uuid:s,tjp:i,cloneRel8ns:a,cloneData:c,type:l="fork"}=r,d=r.src,b="[fork_v1]";if(l!=="fork")throw new Error(`${b} not a fork transform.`);if(r.type||(r.type="fork"),!d)throw new Error(`${b} src required to fork.`);if(!d.ib)throw new Error(`${b} src.ib required.`);if(n&&n.includes(ee))throw new Error(`${b} destIb can't contain (hardcoded) delimiter right now.`);if(!d.gib)throw new Error(`${b} src.gib required.`);let u={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(u.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(u.rel8ns=d.rel8ns),d=u;let p=_({ib:d.ib,gib:d.gib});r.srcAddr=p;let h=a&&d.rel8ns&&Object.keys(d.rel8ns).length>0?C(d.rel8ns):{};delete h.past;let g=c&&d?.data?C(d.data):{};r.nCounter&&(g.n=0);let m=o?.includes(Y.ancestor)?[p]:(h.ancestor||[]).concat([p]);h.ancestor=m,h.tjp&&delete h.tjp;let y=C(d);if(e&&i?.timestamp)throw new Error(`${b} both noTimestamp and tjp.timestamp selected.`);if(!e||i?.timestamp){let A=new Date;g.timestamp=Oe(A),g.timestampMs=A.getMilliseconds()}(i?.uuid||s)&&(g.uuid=await j()),i?.uuid||i?.timestamp?g.isTjp=!0:g.isTjp&&delete g.isTjp,y.ib=n||"ib",p!==Ss&&(y.rel8ns=h),Object.keys(g).length>0&&(y.data=g);let w=null;if(t){w=await ut(r);let A=_({ibGib:w});h.dna=o?.includes(Y.dna)?h.dna=[A]:h.dna=(h.dna||[]).concat(A)}y.gib=await ze(y,"");let T={newIbGib:y};return w&&(T.dnas=[w]),T}f(Tr,"fork");async function je(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,dataToRename:n,dataToRemove:s,dataToAddOrPatch:i,mut8Ib:a,type:c="mut8"}=r,l=r.src,d="[mut8_v1]";if(c!=="mut8")throw new Error(`${d} not a mut8 transform.`);if(r.type||(r.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(ee))throw new Error(`${d} ib can't contain hardcoded delimiter (${ee}) right now.`);if(!l.gib)throw new Error(`${d} src.gib required.`);if(!a&&!n&&!s&&!i)throw new Error(`${d} gotta provide either a mut8Ib or some data to change.`);let b=_({ib:l.ib,gib:l.gib});if(r.srcAddr&&b!==r.srcAddr)throw new Error(`${d} srcAddr from src does not equal opts.srcAddr`);if(r.srcAddr=b,te({ibGib:l}))throw new Error(`${d} cannot mutate primitive ibgib`);let u={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(u.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(u.rel8ns=l.rel8ns),l=u;let p=C(l),h=l.rel8ns?l.rel8ns:{},g=C(h);g.past=o?.includes(Y.past)?[b]:(g.past||[]).concat([b]);let m=l?.data?C(l.data):{};if(n&&(m=Fo(m,n,"rename")),s&&(m=Fo(m,s,"remove")),i&&(m=Gs(m,i)),!e){let x=new Date;m.timestamp=Oe(x),m.timestampMs=x.getMilliseconds()}if(r.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(`${d} 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(m.isTjp){let x=g.tjp??[];x.push(b),g.tjp=x,delete m.isTjp}let w=null;if(t){w=await ut(r);let x=_({ibGib:w});g.dna=o?.includes(Y.dna)?g.dna=[x]:g.dna=(g.dna||[]).concat(x)}p.ib=a||p.ib,p.rel8ns=g,Object.keys(m).length>0?p.data=m:delete p.data;let T=(g.tjp?.length??0)>0;p.gib=await K({ibGib:p,hasTjp:T});let A={newIbGib:p};return w&&(A.dnas=[w]),A}f(je,"mut8");function Fo(r,e,t){let o="[renameOrRemove]",n=["timestamp"];return Object.keys(e).forEach(s=>{if(n.includes(s))throw new Error(`${o} Cannot rename to ${s}.`);if(Object.keys(r).includes(s)){let i=e[s];if(typeof i=="string"){if(n.includes(i))throw new Error(`${o} Cannot rename to ${i}.`);t==="rename"&&(r[i]=r[s]),delete r[s]}else r[s]=Fo(r[s],i,t)}else console.log(`${o} key to ${t} does not exist`)}),r}f(Fo,"renameOrRemove");function Gs(r,e){return Object.keys(e).forEach(t=>{let o=e[t],n=r[t];n?Array.isArray(o)||Array.isArray(n)?r[t]=o:typeof o=="object"&&typeof n=="object"?r[t]=Gs(n,o):r[t]=o:r[t]=o}),r}f(Gs,"patch");async function Ie(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,rel8nsToAddByAddr:n,rel8nsToRemoveByAddr:s,rel8nsToReplaceByAddr:i,type:a="rel8"}=r,c=r.src,l="[rel8_v1]";if(a!=="rel8")throw new Error(`${l} not a rel8 transform.`);if(r.type||(r.type="rel8"),a!=="rel8")throw new Error(`${l} not a rel8 transform.`);if(r.type||(r.type="rel8"),!c)throw new Error(`${l} src required.`);if(!c.ib)throw new Error(`${l} src.ib required.`);if(c.ib.includes(ee))throw new Error(`${l} ib can't contain hardcoded delimiter (${ee}) right now.`);if(!c.gib)throw new Error(`${l} src.gib required.`);if(te({ibGib:c}))throw new Error(`${l} cannot relate/unrelate primitive ibgib`);let d=n&&Object.keys(n).length>0,b=s&&Object.keys(s).length>0,u=i&&Object.keys(i).length>0;if(!(d||b||u))throw new Error(`${l} gotta provide relations to add, remove, or replace.`);let p=_({ib:c.ib,gib:c.gib});if(r.srcAddr&&p!==r.srcAddr)throw new Error(`${l} srcAddr from src does not equal opts.srcAddr`);r.srcAddr=p;let h=f($=>$&&typeof $=="string"&&$.length>=2&&$.includes("^")&&$.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map($=>(n||{})[$]).forEach($=>{if(!($&&$.every(I=>h(I))))throw new Error(`${l} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(s||{}).map($=>(s||{})[$]).forEach($=>{if(!($&&$.every(I=>h(I))))throw new Error(`${l} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(i||{}).map($=>(i||{})[$]).forEach($=>{if(!($&&$.every(I=>I&&h(I.oldAddr)&&h(I.newAddr))))throw new Error(`${l} Invalid replace rel8n attempt. Must be valid ibGibs with oldAddr and newAddr. Did you include a delimiter (^)?`)});let g={ib:c.ib,gib:c.gib};c.data&&Object.keys(c.data).length>0&&(g.data=c.data),c.rel8ns&&Object.keys(c.rel8ns).length>0&&(g.rel8ns=c.rel8ns),c=g;let m=C(c),y=C(c.data||{});if(r.nCounter||Object.keys(y).includes("n"))if(Object.keys(y).includes("n"))if(Number.isInteger(y.n))y.n>=0?y.n=y.n+1:(console.warn(`${l} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),y.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else y.n=0;if(!e){let $=new Date;y.timestamp=Oe($),y.timestampMs=$.getMilliseconds()}let w=C(c.rel8ns||{});if(Object.keys(i||{}).forEach($=>{if(Je.includes($))throw new Error(`${l} Cannot manually replace relationship: ${$}.`);let I=w[$]||[],G=i[$]||[],N=[...I];for(let v of G){let{oldAddr:P,newAddr:D}=v,U=!1;for(let V=0;V<N.length;V++)N[V]===P&&(N[V]=D,U=!0);if(!U)throw new Error(`${l} Cannot replace oldAddr '${P}' in rel8n '${$}' - oldAddr not found in existing relationships.`)}w[$]=N}),Object.keys(n||{}).forEach($=>{if(Je.includes($))throw new Error(`${l} Cannot manually add relationship: ${$}.`);let I=w[$]||[],N=n[$].filter(v=>!I.includes(v));w[$]=I.concat(N)}),Object.keys(s||{}).forEach($=>{if(Je.includes($))throw new Error(`${l} Cannot manually remove relationship: ${$}.`);let I=w[$]||[],G=s[$]||[],N=I.filter(v=>!G.includes(v));N.length>0?w[$]=N:delete w[$]}),w.past=(w.past||[]).concat([p]),(o||[]).filter($=>Object.keys(w).includes($)).filter($=>(w[$]||[]).length>1).forEach($=>{let I=w[$].length;w[$]=[w[$][I-1]]}),y.isTjp){let $=w.tjp||[];$.push(p),w.tjp=$,delete y.isTjp}m.data=y,m.rel8ns=w;let T=(w.tjp?.length??0)>0,A=null;if(t){A=await ut(r);let $=_({ibGib:A});w.dna=o?.includes(Y.dna)?w.dna=[$]:w.dna=(w.dna||[]).concat($)}m.gib=await K({ibGib:m,hasTjp:T});let x={newIbGib:m};return A&&(x.dnas=[A]),x}f(Ie,"rel8");function Ar({ibGib:r}){let e=`[${Ar.name}]`;if(!r)return console.warn(`${e} ibGib falsy. (W: 884178562f5b4f15933ac4d98db74cc6)`),!1;if(r.data?.isTjp||r.rel8ns?.tjp?.length>0)return!0;let t=["fork^gib","mut8^gib","rel8^gib"];return(r.rel8ns?.ancestor??[]).some(n=>t.includes(n))?!1:r.gib?r.gib.includes(Ce)?!0:r.gib===R?!1:!!ie({ibGibAddr:_({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(Ar,"hasTjp");function Sr({ibGib:r}){let e=`[${Sr.name}]`;r.ib||console.warn(`${e} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),r.gib||console.warn(`${e} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let t={ib:(r.ib||"").slice()};return r.gib&&(t.gib=r.gib.slice()),r.data&&(t.data=r.data instanceof Uint8Array?r.data:C(r.data)),r.rel8ns&&(t.rel8ns=C(r.rel8ns)),t}f(Sr,"toDto");var qo=!1;async function ae({ibGib:r}){let e=`[${ae.name}]`;try{let t=[];if(r){let o=_({ibGib:r});if(t=Xt({addr:o})??[],t.length>0)return console.error(`${e} errors found in addr: ${o}`),t;if(te({gib:r.gib}))return null;let n=await K({ibGib:Sr({ibGib:r}),hasTjp:Ar({ibGib:r})});return n!==r.gib&&(r.data?.src&&r.data.srcAddr&&r.ib==="rel8"?(delete r.data.src,delete r.data.srcAddr,n=await K({ibGib:Sr({ibGib:r}),hasTjp:Ar({ibGib:r})}),n!==r.gib&&t.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${r.gib}). (E: 020b71479e944b2198fe436e7e137786)`)):t.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${r.gib}). (E: 7416db016878430ca3c5b20697f164ed)`)),t.length>0?t:null}else return t.push("ibGib is itself falsy. (E: 4fb98caf6ed24ef7b35a19cef56e2d7e)"),t}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(ae,"validateIbGibIntrinsically");function Xt({addr:r,delimiter:e,version:t}){let o=`[${Xt.name}]`;try{let n=[];if(t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 2d19db16ec0c4766b5d35248787671f3)`),!r)return n.push("addr required. (E: e9a54041aa0b41c1bb2324d9d2d42c7f)"),n;e=e||ee,r.includes(e)||n.push(`No delimiter (${e}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`),r.startsWith(e)&&n.push("addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)");let{ib:s,gib:i}=L({ibGibAddr:r,delimiter:e}),a=Nt({ib:s,ibGibAddrDelimiter:e,version:t});a&&(n=n.concat(a));let c=Ot({gib:i,ibGibAddrDelimiter:e,version:t});return c&&(n=n.concat(c)),n.length>0&&qo&&console.log(`${o} errors.length > 0. errors: ${n.join("|")} (I: 9c18f993e138f15613e4c6a340d41722)`),n.length>0?n:null}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Xt,"validateIbGibAddr");function Nt({ib:r,ibGibAddrDelimiter:e,version:t}){let o=`[${Nt.name}]`;try{let n=[];return t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),r?r===Dt?null:(e=e||ee,r.includes(e)&&n.push(`ib contains ibGibAddrDelimiter (${e}) (E: 09e61b46c3e84874bc02b6918f1f2c39)`),n.length>0?n:null):(n.push("ib required. (E: a76d06c7b9c24db3a731a91dbe46acd5)"),n)}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Nt,"validateIb");function Ot({gib:r,gibDelimiter:e,ibGibAddrDelimiter:t,version:o}){let n=`[${Ot.name}]`;try{let s=[];if(o&&console.warn(`${n} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`),!r)return s.push("gib required. (E: e217de4035b04086827199f4bace189c)"),s;t=t||ee;let i=[t],a=[];i.forEach(p=>{r.includes(p)&&a.push(p)}),a.length>0&&s.push(`gib (${r}}) contains invalid characters: (${JSON.stringify(a.join(","))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);let{punctiliarHash:c,tjpGib:l,isPrimitive:d}=ie({gib:r,gibDelimiter:e||Ce});if(d)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let b=c.match(ms),u=c.match(Es);if(!b&&!u&&s.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),l){let p=Ot({gib:l});(p??[]).length>0&&s.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${p.join(". ")}`)}return s.length>0?s:null}catch(s){throw console.error(`${n} ${E(s)}`),s}}f(Ot,"validateGib");function Ho({rel8ns:r}){let e=`[${Ho.name}]`;try{qo&&console.log(`${e} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`);let t=[],o=Object.keys(r);for(let n=0;n<o.length;n++){let s=Object.keys(r)[n];typeof s!="string"&&t.push("non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)");let i=r[s]??[];for(let a=0;a<i.length;a++){let c=i[a],l=Xt({addr:c})??[];l.length>0&&t.push(`invalid addr found for rel8nName (${s}). addr errors: ${l.join("|")} (E: 56809a746c4f462db426e90395b80364)`)}}return t.length>0?t:null}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{qo&&console.log(`${e} complete.`)}}f(Ho,"validateRel8nsIntrinsically");var vs=!1,B=class r{static{f(this,"Factory_V1")}static root(){return r.primitive({ib:Dt})}static primitive({ib:e}){return{ib:e,gib:R}}static primitives({ibs:e}){return e.map(t=>r.primitive({ib:t}))}static async firstGen({ib:e=Dt,parentIbGib:t=r.root(),data:o,rel8ns:n,dna:s,tjp:i,linkedRel8ns:a,noTimestamp:c,nCounter:l,squash:d}){let b=`[${r.name}][${r.firstGen.name}]`;try{if(vs&&console.log(`${b} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),s&&d)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let u=[],p=t||z,h=await Tr({src:p,destIb:e,tjp:i,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});if(u.push(h),p=h.newIbGib,o){let g=await je({src:p,dataToAddOrPatch:o,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});u.push(g),p=g.newIbGib}if(n){let g=await Ie({src:p,rel8nsToAddByAddr:n,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});u.push(g)}if(u.length>1){let g=u.slice(u.length-1)[0].newIbGib,m={newIbGib:g,intermediateIbGibs:u.slice(0,u.length-1).map(y=>y.newIbGib)};if(s){d&&`${b}`;let y=[];return u.forEach(w=>{y=y.concat(w.dnas)}),m.dnas=y,m}else if(d){if(!g.rel8ns)throw new Error("(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)");return delete g.rel8ns.past,g.rel8ns.tjp&&(delete g.rel8ns.tjp,g.data??={},g.data.isTjp=!0),l&&(g.data??={},g.data.n=0),g.gib=await K({ibGib:g}),{newIbGib:g}}else return m}else{if(u.length===1)return u[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(u){throw console.error(`${b} ${E(u)}`),u}finally{vs&&console.log(`${b} complete.`)}}static async stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:s,noTimestamp:i,uuid:a}){let c=`[${r.name}][${r.stone.name}]`;try{if(!e)throw new Error("parentPrimitiveIb required. (E: genuuid)");if(Nt({ib:e})!==null)throw new Error(`Invalid parentPrimitiveIb: ${e}. (E: genuuid)`);if(!t)throw new Error("ib required. (E: genuuid)");let l=o?new RegExp(o):xs;if(!t.match(l))throw new Error(`invalid ib. does not match regexp (${l}) (E: genuuid)`);let d=Object.keys(s??{}),b=[...Je,"tjp"];if(d.some(g=>b.includes(g)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${b}. rel8ns keys: ${Object.keys(s??{})}. (E: genuuid)`);let h=(await r.firstGen({ib:t,parentIbGib:r.primitive({ib:e}),data:n,rel8ns:s,dna:!1,noTimestamp:i,nCounter:!1})).newIbGib;return a&&(h.data||(h.data={}),h.data.uuid=await j()),h.rel8ns?.past&&delete h.rel8ns.past,h.rel8ns?.tjp&&delete h.rel8ns.tjp,h.gib=await K({ibGib:{ib:h.ib,data:h.data,rel8ns:h.rel8ns},hasTjp:!1}),h}catch(l){throw console.error(`${c} ${l.message}`),l}}static async constant({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:s}){let i=`[${r.name}][${r.constant.name}]`;try{return await r.stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:s,noTimestamp:!0,uuid:!1})}catch(a){throw console.error(`${i} ${a.message}`),a}}};var _f="[core^gib timer]";var Ko=`.'",!?-`;var Ds=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var Tf=/^[a-zA-Z0-9_\-.]{1,255}$/,Af=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var xr={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var _c="robbot";var Os="zero",Ns="zerospace";var Bf=!1,Ff="This is a local space. There are many like it, but this one is mine.";var qf=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,Tc="syncSpace";var Hf=3e4;var Gr="space";var Cs="space_lock",Ps=100,Rs=100,Kf=60*2,vr=30;var Vo="root",Xo="x",Ls="root",Yo="analytics-outline",Wo='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var zo="tag",Ac="target";var Us="pricetag-outline",ks="This is a tag used for organizing data.";var Qf="always",Ms="archive",js="trash";var Jo=/^\w{1,32}$/,Dr="Invalid Date";var Zo={ib:"true",gib:R};var Bs={ib:"false",gib:R};var Fs="config_key";var Yt=/^[a-zA-Z0-9_\-.]{1,32}$/,Or="app";var Ze=`bootstrap^${R}`,Ae="defaultSpaceId",Nr="spaceIds";var Pe={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},Qe=Object.values(Pe),$e={sha_256:"SHA-256",sha_512:"SHA-512"},ib=Object.values($e),Sc={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},Be=Object.values(Sc);function Wt(r){let e=`[${Wt.name}]`;return new Promise((t,o)=>{try{let n=qs(r),s=Hs(n);t(s)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(Wt,"encodeStringToHexString");function qs(r){let e=`[${qs.name}]`;try{return new TextEncoder().encode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(qs,"stringToUTF8Bytes");function Hs(r){let e=`[${Hs.name}]`;try{return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Hs,"bytesToHexString");function Fe(r){let e=`[${Fe.name}]`;return new Promise((t,o)=>{try{let n=Ks(r),s=Vs(n);t(s)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(Fe,"decodeHexStringToString");function Ks(r){let e=`[${Ks.name}]`;try{if(r.length%2!==0)throw new Error("invalid hex string. length %2 !== 0");let t=r.length/2,o=new Uint8Array(t);for(let n=0;n<t;n++)o[n]=parseInt(r.substr(n*2,2),16);return o}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Ks,"hexStringToBytes");function Vs(r){let e=`[${Vs.name}]`;try{return new TextDecoder().decode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Vs,"utf8BytesToString");var qe=Pe.appendPerHash,He="SHA-512",Ke=1024,Re=2e4,Ve=1,Xs="indexOf",Cr="lastIndexOf",Pr=5e6,Rr=4,et=",";function xc({secret:r,prevHash:e,salt:t,saltStrategy:o}){if(!(e||r))throw new Error("Either secret or prevHash is required, but both are falsy (E: bee2849729ff410081d963777dcedb49))");switch(o){case Pe.prependPerHash:return t+(e||r);case Pe.appendPerHash:return(e||r)+t;case Pe.initialPrepend:return e||t+r;case Pe.initialAppend:return e||r+t;default:throw new Error(`Unknown saltStrategy: ${o} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}f(xc,"getPreHash");async function _e({secret:r,prevHash:e,count:t,salt:o,saltStrategy:n,hashAlgorithm:s}){let i=`[${_e.name}]`;try{let a=e||void 0;for(let c=0;c<t;c++){let l=xc({secret:r,prevHash:a,salt:o,saltStrategy:n});a=await X({s:l,algorithm:s})}if(!a)throw new Error("hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)");return a}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(_e,"execRound_getNextHash");async function Xe({secret:r,initialRecursions:e,salt:t,saltStrategy:o,hashAlgorithm:n}){let s=`[${Xe.name}]`;try{return await _e({secret:r,count:e,salt:t,saltStrategy:o,hashAlgorithm:n})}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(Xe,"doInitialRecursions_keystretch");async function Qo({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:c}){let l=`[${Qo.name}]`;try{let d=await Xe({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),b=c==="indexOf"?(h,g)=>h.indexOf(g):(h,g)=>h.lastIndexOf(g),u=[];for(let h=0;h<r.length;h++){let g=r[h],m="",y;for(;!m.includes(g);)y=await _e({count:t,prevHash:d,salt:o,saltStrategy:n,hashAlgorithm:i}),m+=y,d=y;let w=b(m,g);u.push(w)}return u.join(a)}catch(d){throw console.error(`${l} ${E(d)}`),d}}f(Qo,"encryptFromHex_stream");async function en({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a}){let c=`[${en.name}]`;try{let l=await Xe({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),d=r.split(a).map(p=>parseInt(p)),b=[];for(let p=0;p<d.length;p++){let h=d[p],g="",m;for(;h>=g.length;)m=await _e({count:t,prevHash:l,salt:o,saltStrategy:n,hashAlgorithm:i}),g+=m,l=m;let y=g[h];b.push(y)}return b.join("")}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(en,"decryptToHex_stream");async function zt({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a}){let c=`[${zt.name}]`,l=[],d=[];e=e||Re,t=t||Ve,n=n||qe,i=i||He,o=o||await j(Ke),a=a||et;let b="[validation]";if(!e||e<1){let h=`${b} initialRecursions required, and greater than 0`;console.error(h),l.push(h)}if(!t||t<1){let h=`${b} recursionsPerHash required, and greater than 0`;console.error(h),l.push(h)}if(!r){let h=`${b} encryptedData required`;console.error(h),l.push(h)}if(!o){let h=`${b} salt required`;console.error(h),l.push(h)}if(!n){let h=`${b} saltStrategy required`;console.error(h),l.push(h)}if(!s){let h=`${b} secret required`;console.error(h),l.push(h)}if(!a){let h=`${b} encryptedDataDelimiter required`;console.error(h),l.push(h)}if(!Object.values($e).includes(i)){let h=`${b} only ${Object.values($e)} hash algorithms implemented`;console.error(h),l.push(h)}if(n&&!Qe.includes(n)){let h=`${b} unknown saltStrategy: ${n}`;console.error(h),l.push(h)}if(l.length>0)return{errors:l,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};let u=await en({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a});return{decryptedData:await Fe(u),initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a,warnings:d.length>0?d:void 0}}f(zt,"decryptImpl_stream");async function tn({dataToEncrypt:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,confirm:c,indexingMode:l}){let d=`[${tn.name}]`,b=[],u=[];e||(console.warn(`${d} initial recursions required. defaulting to ${Re}`),e=Re),t=t||Ve,n=n||qe,i=i||He,o=o||await j(Ke),a=a||et,l=l||Xs;let p="[validation]";if(!e||e<1){let m=`${p} initialRecursions required, and greater than 0`;console.error(m),b.push(m)}if(!t||t<1){let m=`${p} recursionsPerHash required, and greater than 0`;console.error(m),b.push(m)}if(!r){let m=`${p} dataToEncrypt required`;console.error(m),b.push(m)}if(!o){let m=`${p} salt required`;console.error(m),b.push(m)}if(!n){let m=`${p} saltStrategy required`;console.error(m),b.push(m)}if(!s){let m=`${p} secret required`;console.error(m),b.push(m)}if(!a){let m=`${p} encryptedDataDelimiter required`;console.error(m),b.push(m)}if(!Be.includes(l)){let m=`${p} invalid indexingMode (${l}). Must be one of ${Be} (E: 5955c46755434982982823c97adcf076)`;console.error(m),b.push(m)}if(!Object.values($e).includes(i)){let m=`${p} only ${Object.values($e)} hash algorithms implemented`;console.error(m),b.push(m)}if(n&&!Qe.includes(n)){let m=`${p} unknown saltStrategy: ${n}`;console.error(m),b.push(m)}if(b.length>0)return{errors:b,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};let h=await Wt(r);if(c&&await Fe(h)!==r)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let g=await Qo({hexEncodedData:h,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:"indexOf"});if(c){let m=await zt({encryptedData:g,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a});if((m.errors||[]).length>0)return{errors:["Confirm check found that decrypt had errors.",...m.errors],initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};if(m.decryptedData){if(m.decryptedData!==r)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");(m.warnings||[]).length>0&&(u=u.concat(["Confirm check call to decrypt had warnings.",...m.warnings]))}return{encryptedData:g,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a,warnings:u.length>0?u:void 0}}f(tn,"encryptImpl_stream");async function rn({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:c,maxBlockSize:l,numOfPasses:d}){let b=`[${rn.name}]`;try{let u=await Xe({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),p=c==="indexOf"?(x,$)=>x.indexOf($):(x,$)=>x.lastIndexOf($),h=[],g=r.length,m=l;m>g&&(m=g);let y=Math.ceil(g/m),w=g%m||m,T=0;for(let x=0;x<y;x++){x===y-1&&(m=w);let I=await Ys({blockSize:m,indexHexEncodedDataAtStartOfPass:T,numOfPasses:d,hexEncodedData:r,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:u,hashAlgorithm:i}),G=I.alphabetsThisBlock;u=I.prevHash;let N=await Ws({alphabetsThisBlock:G,blockSize:m,indexHexEncodedDataAtStartOfPass:T,hexEncodedData:r,getIndexOfCharInAlphabet:p});h=h.concat(N),T+=m}return h.join(a)}catch(u){throw console.error(`${b} ${E(u)}`),u}}f(rn,"encryptFromHex_blockMode");async function Ys({blockSize:r,numOfPasses:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,recursionsPerHash:n,salt:s,saltStrategy:i,prevHash:a,hashAlgorithm:c}){let l=`[${Ys.name}]`;try{let d=[],b,u;for(let p=0;p<e;p++)for(let h=0;h<r;h++){b=t+h;let g=d[h]??"";u=await _e({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u,d[h]=g}for(let p=0;p<r;p++){b=t+p;let h=o[b],g=d[p];for(;!g.includes(h);)u=await _e({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u;d[p]=g}return{alphabetsThisBlock:d,prevHash:a}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}f(Ys,"getAlphabetsThisBlock");async function Ws({alphabetsThisBlock:r,blockSize:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,getIndexOfCharInAlphabet:n}){let s=`[${Ws.name}]`;try{let i=[];for(let a=0;a<e;a++){let c=t+a,l=r[a],d=n(l,o[c]);i.push(d)}return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(Ws,"getEncryptedIndexesThisBlock");async function on({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,maxBlockSize:c,numOfPasses:l}){let d=`[${on.name}]`;try{let b=await Xe({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),u=r.split(a).map(A=>parseInt(A)),p=[],h=u.length,g=c;g>h&&(g=h);let m=Math.ceil(h/g),y=h%g||g,w=0;for(let A=0;A<m;A++){A===m-1&&(g=y);let $=await zs({blockSize:g,indexEncryptedDataIndexesAtStartOfPass:w,numOfPasses:l,encryptedDataIndexes:u,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:b,hashAlgorithm:i}),I=$.alphabetsThisBlock;b=$.prevHash;let G=await Js({alphabetsThisBlock:I,blockSize:g,indexEncryptedDataIndexesAtStartOfPass:w,encryptedDataIndexes:u});p=p.concat(G),w+=g}return p.join("")}catch(b){throw console.error(`${d} ${E(b)}`),b}}f(on,"decryptToHex_blockMode");async function zs({blockSize:r,numOfPasses:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o,recursionsPerHash:n,salt:s,saltStrategy:i,prevHash:a,hashAlgorithm:c}){let l=`[${zs.name}]`;try{let d=[],b,u;for(let p=0;p<e;p++)for(let h=0;h<r;h++){b=t+h;let g=d[h]??"";u=await _e({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u,d[h]=g}for(let p=0;p<r;p++){b=t+p;let h=o[b],g=d[p];for(;g.at(h)===void 0;)u=await _e({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u;d[p]=g}return{alphabetsThisBlock:d,prevHash:a}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}f(zs,"getAlphabetsThisBlock");async function Js({alphabetsThisBlock:r,blockSize:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o}){let n=`[${Js.name}]`;try{let s=[];for(let i=0;i<e;i++){let a=t+i,c=o[a],d=r[i][c];s.push(d)}return s}catch(s){throw console.error(`${n} ${E(s)}`),s}}f(Js,"getDecryptedDataArrayThisBlock");async function Jt(r){let e=`[${Jt.name}]`,{encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:d,blockMode:b,multipass:u}=r,p=[],h=[];if(b&&u)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(!b&&u&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),b=u),!b)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");o=o||Re,n=n||Ve,i=i||qe,c=c||He,s=s||await j(Ke),l=l||et,d=d||Cr;let{maxBlockSize:g,maxPassSectionLength:m,numOfPasses:y}=b;!g&&m&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`),g=m),g=g||Pr,y=y||Rr;let w="[validation]";if(!o||o<1){let $=`${w} initialRecursions required, and greater than 0`;console.error($),p.push($)}if(!n||n<1){let $=`${w} recursionsPerHash required, and greater than 0`;console.error($),p.push($)}if(!t){let $=`${w} encryptedData required`;console.error($),p.push($)}if(!s){let $=`${w} salt required`;console.error($),p.push($)}if(!i){let $=`${w} saltStrategy required`;console.error($),p.push($)}if(!a){let $=`${w} secret required`;console.error($),p.push($)}if(!l){let $=`${w} encryptedDataDelimiter required`;console.error($),p.push($)}if(!d){let $=`${w} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error($),p.push($)}if(!Be.includes(d)){let $=`${w} invalid indexingMode (${d}). Must be one of ${Be} (E: 17435268651444e0b7a594135635fc58)`;console.error($),p.push($)}if(g<1){let $=`${w} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error($),p.push($)}if(y<1){let $=`${w} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error($),p.push($)}if(!Object.values($e).includes(c)){let $=`${w} only ${Object.values($e)} hash algorithms implemented`;console.error($),p.push($)}if(i&&!Qe.includes(i)){let $=`${w} unknown saltStrategy: ${i}`;console.error($),p.push($)}if(p.length>0){let $={...r,errors:p};return delete $.encryptedData,delete $.secret,$}let T=await on({encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,maxBlockSize:g,numOfPasses:y}),A=await Fe(T),x={...r,decryptedData:A,warnings:h.length>0?h:void 0};return delete x.encryptedData,delete x.secret,x}f(Jt,"decryptImpl_blockMode");async function nn(r){let e=`[${nn.name}]`,{dataToEncrypt:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,confirm:d,indexingMode:b,blockMode:u,multipass:p}=r,h=[],g=[];if(u&&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: bde5efd1a3e449dca549c5bff147f09b)");if(!u&&p&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),u=p),!u)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 0b87871f81d849ef8f0263b7775bd3e3)");o||(console.warn(`${e} initial recursions required. defaulting to ${Re}`),o=Re),l=l||et,b=b||Cr;let{maxBlockSize:m,maxPassSectionLength:y,numOfPasses:w}=u;!m&&y&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`),m=y),m=m||Pr,w=w||Rr;let T="[validation]";if(!o||o<1){let I=`${T} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(I),h.push(I)}if(!n||n<1){let I=`${T} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(I),h.push(I)}if(!s){let I=`${T} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(I),h.push(I)}if(!i){let I=`${T} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(I),h.push(I)}if(!a){let I=`${T} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(I),h.push(I)}if(!l){let I=`${T} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(I),h.push(I)}if(!b){let I=`${T} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(I),h.push(I)}if(!Be.includes(b)){let I=`${T} invalid indexingMode (${b}). Must be one of ${Be} (E: 17435268651444e0b7a594135635fc58)`;console.error(I),h.push(I)}if(m<1){let I=`${T} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(I),h.push(I)}if(w<1){let I=`${T} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(I),h.push(I)}if(!Object.values($e).includes(c)){let I=`${T} only ${Object.values($e)} hash algorithms implemented`;console.error(I),h.push(I)}if(i&&!Qe.includes(i)){let I=`${T} unknown saltStrategy: ${i}`;console.error(I),h.push(I)}if(h.length>0){let I={...r,errors:h};return delete I.dataToEncrypt,delete I.secret,I}let A=await Wt(t);if(d&&await Fe(A)!==t)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let x=await rn({hexEncodedData:A,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:b,maxBlockSize:m,numOfPasses:w});if(d)try{let I=await Jt({encryptedData:x,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:b,blockMode:u});if(I.decryptedData){if(I.decryptedData!==t)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)");(I.warnings||[]).length>0&&(g=g.concat(["Confirm check call to decrypt had warnings.",...I.warnings]))}catch(I){throw new Error(`${e} confirm failed. decrypt error: ${E(I)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let $={...r,encryptedData:x,warnings:g.length>0?g:void 0};return delete $.dataToEncrypt,delete $.secret,$}f(nn,"encryptImpl_blockMode");async function Gc(r){let e=`[${Gc.name}]`;try{if(!r)throw new Error("args required (E: 22e58e03c78f4c27bf18295b8d2cdd3a)");if(!r.dataToEncrypt)throw new Error("dataToEncrypt required (E: 168c9076e5434c83ba81e3485ee6f3e4)");r.salt=r.salt||await j(Ke),r.saltStrategy=r.saltStrategy||qe,r.hashAlgorithm=r.hashAlgorithm||He,r.recursionsPerHash=r.recursionsPerHash||Ve;let t;return r.blockMode?t=await nn(r):t=await tn(r),(t.errors??[]).length>0&&t.errors.forEach(o=>console.warn(`${e} ${o}`)),(t.warnings??[]).length>0&&t.warnings.forEach(o=>console.warn(`${e} ${o}`)),t}catch(t){throw console.error(`${e}${t.message}`),t}}f(Gc,"encrypt");async function vc(r){let e=`[${vc.name}]`;try{if(!r)throw new Error("args required (E: fcd9b4aad85c4deba5fe5fde0b9ecb30)");if(!r.encryptedData)throw new Error("encryptedData required (E: f879f612428b4283bae089acee929a58)");r.salt=r.salt||await j(Ke),r.saltStrategy=r.saltStrategy||qe,r.hashAlgorithm=r.hashAlgorithm||He,r.recursionsPerHash=r.recursionsPerHash||Ve;let t;return r.blockMode||r.multipass?t=await Jt(r):t=await zt(r),(t.warnings??[]).length>0&&t.warnings.forEach(o=>console.warn(`${e} ${o}`)),(t.errors??[]).length>0&&t.errors.forEach(o=>console.warn(`${e} ${o}`)),t}catch(t){throw console.error(`${e}${t.message}`),t}}f(vc,"decrypt");var mu=5e4;var Eu=Pe.appendPerHash,wu=10,$u="SHA-256";var yu="encryption",Iu="ciphertext";var Dc={local:"local",outerspace:"outerspace",innerspace:"innerspace"},Su=Object.values(Dc).concat(),Oc={user:"user",sync:"sync"},sn=Object.values(Oc).concat(),Nc={node_filesystem:"node-filesystem"},Cc={aws_dynamodb:"aws-dynamodb"},Pc={...Nc,...Cc},an=Object.values(Pc).concat(),Rc={get:"get",put:"put",delete:"delete"},Lc={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var Uc=!1,Ur=class r{static{f(this,"DynamicFormBuilder")}lc=`[${r.name}]`;items=[];what="";idPool=[];getNewId(){let e=`${this.lc}[${this.getNewId.name}]`;if(this.idPool?.length>0)return this.idPool.pop()??"";{let t=[],o="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n=o.length;for(let i=0;i<32;i++){let a=Math.floor(Math.random()*n);t.push(o[a])}let s=t.join("");return Uc&&console.log(`${e} id: ${s} (I: c6591ffee6d5bbea79ed19cfa6630422)`),s}}forA({what:e}){return this.what=e||"thingy",this}addItem(e){e.uuid||(e.uuid=this.getNewId()),this.items.push(e)}with({idPool:e}){return e&&(this.idPool=e),this}and(){return this}name({of:e,required:t=!0,defaultValue:o}){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:yr({min:1,max:32,noSpaces:!0}),regexpErrorMsg:"1 to 32 characters, no spaces, underscores allowed.",required:t,dataType:"text",value:e,defaultValue:o}),this}description({of:e,required:t,defaultValue:o}){return this.addItem({name:"description",description:`Description/notes for this ${this.what}.`,label:"Description",placeholder:`Describe these ${this.what} settings here...`,regexp:yr({min:0,max:155,chars:Ko}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${Ko}`,dataType:"textarea",required:t,value:e,defaultValue:o}),this}classname({of:e,required:t=!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:yr({min:1,max:128,noSpaces:!0}),regexpErrorMsg:"1 to 128 alphanumerics or underscores without spaces",dataType:"text",value:e,readonly:!0,required:t}),this}uuid({of:e,label:t,required:o}){return this.addItem({name:"uuid",description:`Unique(ish) id of the ${this.what}.`,label:t??"ID",dataType:"text",value:e,regexp:Q,regexpErrorMsg:"1 to 256 alphanumerics, underscores, dots, hyphens allowed.",readonly:!0,required:o}),this}version({of:e,required:t}){return this.addItem({name:"version",description:`Technical setting indicating the version of the ${this.what}.`,label:"Version",dataType:"text",value:e||"",readonly:!0,required:t}),this}customItem(e){return this.addItem(e),this}outputItems(){return this.items}outputForm({formName:e,label:t}){return{name:e,description:`This is a form for a ${this.what}`,label:t??this.what,items:this.items}}};var tt=class r extends Ur{static{f(this,"WitnessFormBuilder")}lc=`[${r.name}]`;allowPrimitiveArgs({of:e,required:t=!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:e??!0,readonly:!0,required:t}),this}catchAllErrors({of:e,required:t=!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:e??!0,readonly:!0,required:t}),this}persistOptsAndResultIbGibs({of:e,required:t=!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:e??!1,readonly:!0,required:t}),this}trace({of:e,required:t}){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:e??!1,readonly:!0,required:t}),this}commonWitnessFields({data:e,allowPrimitiveArgs:t=!0,catchAllErrors:o=!0,persistOptsAndResultIbGibs:n=!0,trace:s=!0,version:i=!0}){return t&&this.allowPrimitiveArgs({of:e.allowPrimitiveArgs}),o&&this.catchAllErrors({of:e.catchAllErrors}),n&&this.persistOptsAndResultIbGibs({of:e.persistOptsAndResultIbGibs}),s&&this.trace({of:e.trace}),i&&this.version({of:e.version}),this}};var kr=!1;function Zs({appData:r}){let e=`[${Zs.name}]`;try{if(kr&&console.log(`${e} starting...`),!r)throw new Error("appData required (E: 3df782b29bc4406a87e4895cfcea28ed)");let t=[],{name:o,uuid:n,classname:s}=r;return o?o.match(Yt)||t.push(`name must match regexp: ${Yt}`):t.push("name required."),n?n.match(Q)||t.push(`uuid must match regexp: ${Q}`):t.push("uuid required."),s&&(s.match(Yt)||t.push(`classname must match regexp: ${Yt}`)),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{kr&&console.log(`${e} complete.`)}}f(Zs,"validateCommonAppData");function cn({appData:r,classname:e}){let t=`[${cn.name}]`;try{let o=Zs({appData:r});if(o.length>0)throw new Error(`invalid appData: ${o} (E: 9aff04f0cfc54a5188ca8bc40764160d)`);if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match appData.classname (E: 66f1447eef97485fba521c40980f5eb5)")}else if(e=r.classname,!e)throw new Error("classname required (E: 5f6ffb4317044125b94f662070e1f40b)");let{name:n,uuid:s}=r;return`app ${e} ${n} ${s}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(cn,"getAppIb");function kc({appIb:r}){let e=`[${kc.name}]`;try{if(!r)throw new Error("appIb required (E: 6b065aee67e641ba9f9c6db367ebb0fb)");let t=r.split(" ");return{appClassname:t[1],appName:t[2],appId:t[3]}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(kc,"getInfoFromAppIb");async function Mc({fnPromptApp:r,ibgibs:e,space:t}){let o=`[${Mc.name}]`;try{if(kr&&console.log(`${o} starting...`),!e)throw new Error("ibgibs all powerful service required. (E: b24e78de0d204dc78909022bee296b30)");t=t??await e.getLocalUserSpace({lock:!0});let n=await r(t,null);if(!n)throw new Error("resApp falsy after prompt for app. (E: 2225a567abcd680a5e957e81fbb64123)");let s=n.newIbGib,i=[];i.push(s),n.intermediateIbGibs?.forEach(d=>i.push(d)),n.dnas?.forEach(d=>i.push(d));for(let d=0;d<i.length;d++){let b=i[d],u=await ae({ibGib:b});if((u??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${u}. app: ${H(s.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await re({resTransform:n,space:t});let{zeroSpace:a,fnBroadcast:c,fnUpdateBootstrap:l}=e;return await Se({ibGib:s,space:t,fnBroadcast:f(d=>c(d),"fnBroadcast")}),await Ct({type:"apps",rel8nName:Or,ibGibsToRel8:[s],space:t,zeroSpace:a,fnUpdateBootstrap:l,fnBroadcast:c}),s}catch(n){debugger;console.error(`${o} ${n.message}`);return}finally{kr&&console.log(`${o} complete.`)}}f(Mc,"createNewApp");var jc="0",Bc="chat_gib",Fc="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",Qs={version:"1",uuid:jc,name:Bc,description:Fc,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ei=void 0;var qc="0",Hc="raw_gib",Kc="Explorer app for navigating raw ibgib data.",ti={version:"1",uuid:qc,name:Hc,description:Kc,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ri=void 0;var ln="0",Vc="todo_gib",Xc="Todo app for viewing and interacting with ibgibs like they're checklists.",oi={version:"1",uuid:ln,name:Vc,description:Xc,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ni=void 0;async function dn(r){let e=`[${dn.name}]`,t=[];try{_({ibGib:r})!==Ze&&t.push(`invalid bootstrapSpace addr. Should equal "${Ze}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await ae({ibGib:r});(n?.length??!1)&&n.forEach(a=>t.push(a));let s=r.data,i=r.rel8ns;return Object.keys(s||{}).length===0&&t.push("invalid bootstrapSpace data. data required (E: 5a9bd15dd0644f9b93cafbbba660cfdf)"),(s.spaceIds??[]).length===0&&t.push("invalid bootstrapSpace, data.spaceIds required. (E: 6b91ddc12cfd41e59ded7d7502c1909f)"),Object.keys(r.rel8ns||{}).length===0&&t.push("invalid bootstrapSpace rel8ns (empty). Should have at least one rel8n, with rel8nName corresponding to the spaceId (E: b188ce4ae25e49f794f35e141bc2ecde)"),s.spaceIds.forEach(a=>{(i[a]??[]).length===0&&t.push(`invalid bootstrap. Each spaceId listed in data should have a corresponding address in rel8ns. spaceId (${a}) missing. (E: 62dd0d76e29a415a98b4b27deb8db17e)`)}),s[Ae]?(i[s[Ae]]??[]).length===0&&t.push(`invalid bootstrap. data.${Ae} (${s[Ae]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):t.push(`invalid bootstrap. data.${Ae} required. (E: f763af2e275f445cbf1db5801bacafad)`),t.length===0?!0:(console.error(`${e} errors: ${t.join("|")}`),!1)}catch(o){return console.error(`${e} ${o.message}`),!1}}f(dn,"validateBootstrapIbGib");var Pt="meta_stone";var fn="undefined",Zt="target",Mr="targetTjp";var Te=!1;function ii({ib:r}){let e=`[${ii.name}]`;try{Te&&console.log(`${e} starting...`);let t=[],o=r.split(" ");o[0]!==Pt&&t.push(`${e} invalid ib. atom is expected to be META_STONE_ATOM: ${Pt} (E: a9812bffc18f44418aa091fb0ed260bd)`);let s=o[1],i=Ot({gib:s})??[];i.length>0&&t.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${i} (E: 233db2babfbe4d28a80f98261f1c0e01)`);let a=o[2],c=Number.parseInt(a);isNaN(c)&&t.push("invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)");let l=o[3];if(l!=="undefined"){let d=Qt({timestamp:l});d.valid||t.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${d.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`)}return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Te&&console.log(`${e} complete.`)}}f(ii,"validateCommonMetaStoneIb");function bn({data:r}){let e=`[${bn.name}]`;try{if(Te&&console.log(`${e} starting...`),!r)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let t=[],{targetData:o,timestamp:n}=r;Qt({timestamp:n}).valid||t.push("invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)");let{tjpGib:i,n:a,timestamp:c}=o;if(i&&i!=="undefined"){let d=Ot({gib:i})??[];d.length>0&&t.push(`invalid data (targetTjpGib). validation errors: ${d} (E: d216b12eb75544ef8c5ffb27cd132e2e)`)}if(typeof a!="number"&&t.push("invalid n. should be valid integer. if target.data.n is falsy, targetN should be -1 (E: 8f234967b388ad80776c8054d71fbc23)"),c&&c!=="undefined"){let d=Qt({timestamp:c});d.valid||t.push(`invalid targetTimestamp. emsg: ${d.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`)}let l=new Date(n);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Te&&console.log(`${e} complete.`)}}f(bn,"validateCommonMetaStoneData");function ai({rel8ns:r}){let e=`[${ai.name}]`;try{if(Te&&console.log(`${e} starting...`),!r)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let t=[],o=Ho({rel8ns:r??{}})??[];o.length>0&&t.push(`invalid rel8ns intrinsically. errors: ${o.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=r[Zt]??[];n.length===0?t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Zt}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Zt}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let s=r[Mr]??[];return s.length>1&&t.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${Mr}. has ${s.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Te&&console.log(`${e} complete.`)}}f(ai,"validateCommonMetaStoneRel8ns");async function Yc({ibGib:r}){let e=`[${Yc.name}]`;try{Te&&console.log(`${e} starting... (I: f32249d08105b997871a06cdee006311)`);let t=await ae({ibGib:r})??[];if(!r.data)throw new Error("MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)");let o=[];try{let{atom:a,tjpGib:c,n:l,timestampInTicks:d}=li({ib:r.ib})}catch(a){o.push(E(a))}let n=bn({data:r.data}),s=ai({rel8ns:r.rel8ns}),i=[...t??[],...o??[],...n??[],...s??[]];return i.length>0?i:void 0}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Te&&console.log(`${e} complete.`)}}f(Yc,"validateCommonMetaStoneIbGib");function ci({data:r,classname:e}){let t=`[${ci.name}]`;try{let o=bn({data:r});if(o.length>0)throw new Error(`invalid MetaStone data: ${o} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);e&&Te&&console.log(`${t} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`);let n=r.targetData.timestamp,s=n&&n!=="undefined"?we(n):fn;return`${Pt} ${r.targetData.tjpGib} ${r.targetData.n} ${s}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(ci,"getMetaStoneIb");function li({ib:r}){let e=`[${li.name}]`;try{if(!r)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let t=ii({ib:r});if(t.length>0)throw new Error(`invalid ib. validationErrors: ${t} (E: a6107f62200eb943e523f70f51300623)`);let o=r.split(" ");return{atom:o[0],tjpGib:o[1],n:Number.parseInt(o[2]),timestampInTicks:o[3]}}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(li,"parseMetaStoneIb");function lp({addr:r,ibGib:e}){if(r||=_({ibGib:e}),!r)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return r.startsWith(`${Pt} `)}f(lp,"isMetaStone");async function un({targetIbGib:r}){let e=`[${un.name}]`;try{Te&&console.log(`${e} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let t=_({ibGib:r}),o=he({ibGib:r,defaultIfNone:"incomingAddr"}),n,s={[Zt]:[t],[Mr]:[o]};if(!r.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let i=r.data?.isTjp?r.gib:ie({ibGibAddr:t}).tjpGib??r.gib;if(i===R)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let a=new Date,c=Oe(a),l=a.getMilliseconds();r.data?er({ibGib:r})?n={targetData:{n:-1,tjpGib:i},timestamp:c,timestampMs:l}:(n={targetData:{n:r.data.n??-1,tjpGib:i,timestamp:r.data.timestamp??fn},timestamp:c,timestampMs:l},r.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:i},timestamp:c,timestampMs:l};let d=ci({data:n}),b=await xe({parentPrimitiveIb:Pt,ib:d,data:n,rel8ns:s});return Te&&(console.log(`${e} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(b)),b}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Te&&console.log(`${e} complete.`)}}f(un,"newUpMetaStone");var jr="witness",tr="witness_arg",Br="witness_result",bp="context";var S=!1;async function ce({addr:r,addrs:e,isDna:t,space:o,force:n}){let s=`[${ce.name}]`;try{if(S&&console.log(`${s} starting...`),!o)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(!r&&(e??[]).length===0)throw new Error("addr or addrs required. (E: 1a0b92564ba942f1ba91a089ac1a2125)");r&&(e?.length??0)>0&&(console.warn(`${s} both addr and addrs provided, but supposed to be used one or the other. (W: 87226c2ac50e4ea28211334a7b58782f)`),e.includes(r)||e.push(r)),e=(e??[]).length>0?e:[r];let i=await o.argy({ibMetadata:ve({space:o}),argData:{cmd:"get",ibGibAddrs:e,isDna:t}}),a=await o.witness(i);return a?.data?.success?(S&&console.log(`${s} got.`),{success:!0,ibGibs:a.ibGibs,rawResultIbGib:a}):(S&&console.log(`${s} didn't get.`),{success:!1,errorMsg:a.data?.errors?.join("|")||`${s} something went wrong. addrs: ${e.join(`
2
+ `)} (E: b9e9d5ce0cde4122bfb74f7688db85e0)`,rawResultIbGib:a})}catch(i){return console.error(`${s} ${i.message}`),{errorMsg:i.message}}}f(ce,"getFromSpace");async function gn({ibGib:r,ibGibs:e,isDna:t,force:o,space:n}){let s=`[${gn.name}]`;try{if(!r&&(e??[]).length===0)throw new Error("ibGib or ibGibs required. (E: e59c4de3695f4dd28c8fe82dbb9c4e90)");if(!n)throw new Error("space required. (E: dd0b7189c67c43c586b905a8ed6f51c9)");r&&(e??[]).length>0&&(console.warn(`${s} Both ibGib and ibGibs is assigned, whereas this is intended to be exclusive one or the other. (W: 4c797835b620445f88e4cba6b5aa3460)`),e.some(c=>c.gib===r.gib)||(e=e.concat([r]))),e=e??[r],S&&console.log(`${s} ibGibs.length: ${e.length}`);let i=await n.argy({ibMetadata:ve({space:n}),argData:{cmd:"put",force:o,isDna:t,ibGibAddrs:e.map(c=>_({ibGib:c}))},ibGibs:e.concat()}),a=await n.witness(i);if(a.data?.success)return(a.data.warnings??[]).length>0&&a.data.warnings.forEach(c=>console.warn(`${s} ${c}`)),{success:!0};{let c=a?.data?.errors?.length>0?`Error(s) putting in local space:
3
+ ${a.data.errors.join(`
4
+ `)}`:"(UNEXPECTED) unknown error putting ibGibs (E: 3d7426d4527243b79c5e55eb25f3fa73)";throw new Error(c)}}catch(i){return console.error(`${s} ${i.message}`),{errorMsg:i.message}}}f(gn,"putInSpace");async function mn({addr:r,isDna:e,space:t}){let o=`[${mn.name}]`;try{if(!t)throw new Error("space required. (E: 40ab3b51e91c4b5eb4f215baeefbcef0)");if(!t.data)throw new Error("space.data required. (E: 0d02c8e85ee143b8bd6a1a1db0d9af1b)");o=`${o}[${t.data.name||"noname?"}][${t.data.uuid||"nouuid?"}]`;let n=await t.argy({ibMetadata:ve({space:t}),argData:{cmd:"delete",ibGibAddrs:[r],isDna:e}}),s=await t.witness(n);if(s.data?.success)return{success:!0};{s.data?.warnings?.length>0&&console.warn(`${o} warnings with delete (${r}): ${s.data.warnings.join("|")}`),s.data?.addrs?.length>0&&console.warn(`${o} partial addrs deleted: ${s.data.addrs.join("|")}`);let i=s.data?.errors?.join("|")||`${o} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;return i.includes("File does not exist")&&S&&console.log(`${o} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`),{errorMsg:i}}}catch(n){return console.error(`${o} ${n.message}`),{errorMsg:n.message}}}f(mn,"deleteFromSpace");async function re({resTransform:r,space:e,force:t}){let o=`[${re.name}]`;try{if(S&&console.log(`${o} starting... (I: dc6835614ff1a1b82b179225023ae823)`),!e)throw new Error("space required. (E: cf94f1d74f1c4561bb88025a2095965b)");let{newIbGib:n,intermediateIbGibs:s,dnas:i}=r,a=[n,...s||[]],c=await e.argy({ibMetadata:ve({space:e}),argData:{cmd:"put",force:t,ibGibAddrs:a.map(d=>_({ibGib:d}))},ibGibs:a.concat()}),l=await e.witness(c);if(l.data?.success)l.data.warnings?.length>0&&l.data.warnings.forEach(d=>console.warn(`${o} ${d}`));else{let d=l?.data?.errors?.length>0?l.data.errors.join(`
5
+ `):"unknown error putting ibGibs";throw new Error(d)}if(i?.length??!1){let d=await e.argy({ibMetadata:ve({space:e}),argData:{cmd:"put",isDna:!0,force:t,ibGibAddrs:i.map(u=>_({ibGib:u}))},ibGibs:i.concat()}),b=await e.witness(d);if(b.data?.success)b.data.warnings?.length>0&&b.data.warnings.forEach(u=>console.warn(`${o} ${u}`));else{let u=b?.data?.errors?.length>0?b.data.errors.join(`
6
+ `):"unknown error putting dna ibGibs";throw new Error(u)}}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{S&&console.log(`${o} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}f(re,"persistTransformResult");async function Wc({type:r,rel8nName:e,space:t}){let o=`[${Wc.name}]`;try{if(!t)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await qr({type:r,space:t});if(!n)throw new Error(`couldn't get special (${r}) (E: a65bef190416479697605be486846731)`);let s=n.rel8ns?n.rel8ns[e]||[]:[],i=[];for(let a=0;a<s.length;a++){let c=s[a],l=await ce({addr:c,space:t});if(l.success&&l.ibGibs?.length===1)i.push(l.ibGibs[0]);else throw new Error(`couldn't get addr: ${c} (E: 76ef256ee80149ab860c5786484b0e89)`)}return i}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Wc,"getSpecialRel8dIbGibs");async function qr({type:r,initialize:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s,fnGetInitializing:i,fnSetInitializing:a,dontWarnIfNotExist:c}){let l=`[${qr.name}]`;try{if(!t)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let d=oe({type:r}),b=await Hr({key:d,space:t,dontWarn:c||!!e});if(!b){if(e&&(!i||!a))throw new Error("if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)");if(e&&!i()){a(!0);try{if(!o)throw new Error("zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)");b=await bi({type:r,space:t,zeroSpace:o,fnBroadcast:s,fnUpdateBootstrap:n})??void 0}catch(g){console.error(`${l} error initializing: ${g.message}`)}finally{a(!1)}}if(!b){if(i&&i())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)")}}S&&console.log(`${l} getting addr: ${b}`);let u=await ce({addr:b,space:t});if(u.success||(u=await ce({addr:b,space:t}),u.success&&(console.warn(`${l} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await gn({ibGib:u.ibGibs[0],space:t})).success||console.warn(`${l} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!u.success)throw new Error(u.errorMsg);if(u.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let p=u.ibGibs[0],h=await Ue({ibGibs:[p],space:t});if(h?.data?.success&&h.data.addrs?.length===1){let g=_({ibGib:p}),m=h.data.addrs[0];m!==g&&console.warn(`${l} latest addr is not the one associated with the local space.
7
+ specialAddr: ${g}
8
+ latestAddr: ${m} (W: 141b69dc3c414efc9645bb76fcf12df9)`)}return p}catch(d){let b=`${l} ${d.message}`;return b.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(b),null}}f(qr,"getSpecialIbGib");async function Hr({key:r,space:e,dontWarn:t}){let o=`[${Hr.name}](${r})`;try{if(S&&console.log(`${o} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!e)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!e.rel8ns){(S||!t)&&console.warn(`${o} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!e.rel8ns[r]){(S||!t)&&console.warn(`${o} space.rel8ns[${r}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(e.rel8ns[r].length===1)return S&&console.log(`${o} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),e.rel8ns[r][0];if(e.rel8ns[r].length>1)return(S||!t)&&console.warn(`${o} more than one config addr with ${r} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),e.rel8ns[r][0];S&&console.log(`${o} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${o} ${n.message}`);return}}f(Hr,"getConfigAddr");async function fe({key:r,addr:e,space:t,zeroSpace:o,fnUpdateBootstrap:n}){let s=`[${fe.name}]`;try{if(!t)throw new Error("space required. (E: c28b663c991d44419aef1026cc689636)");if(!o)throw new Error("zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)");let i={[r]:[e]},a=await Ie({src:t.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",r],rel8nsToAddByAddr:i,nCounter:!0});if(!a.newIbGib)throw new Error("create new space failed.");await re({resTransform:a,space:o}),await re({resTransform:a,space:t});let c=a.newIbGib;return await t.loadIbGibDto(c),n?await n(c):console.warn(`${s} fnUpdateBootstrap is falsy. (W: 9fb874de2b19454dac18645e61ac463f)`),c}catch(i){throw console.error(`${s} ${i.message}`),i}}f(fe,"setConfigAddr");async function di({space:r}){let e=`[${di.name}]`;try{if(!r)throw new Error("space required. (E: f0d546101fba4c169256158114ab3c56)");let t=await qr({type:"roots",space:r});if(!t)throw new Error("Roots not initialized. (E: 89b1ba12ed12416aac41cef9fdaf1fc2)");if(!t.rel8ns)throw new Error("Roots not initialized properly. No rel8ns. (E: 8513a07cf530484db9521a2a3a27b7f6)");if(!t.rel8ns.current)throw new Error("Roots not initialized properly. No current root. (E: 459c3a007a30486d96fb8d83f696e239)");if(t.rel8ns.current.length===0)throw new Error("Invalid Roots: empty current root rel8n. (E: bede5864090440bca01ea7ab7fd107d6)");if(t.rel8ns.current.length>1)throw new Error("Invalid Roots: multiple current roots selected. (E: 97561acbf63a48ecaa037697bd26555a)");let o=t.rel8ns.current[0],n=await ce({addr:o,space:r});if(n.ibGibs?.length===1)return n.ibGibs[0];throw new Error(`could not get current root. addr: ${o}`)}catch(t){console.error(`${e} ${t.message}`);return}}f(di,"getCurrentRoot");async function En({root:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${En.name}]`;try{if(S&&console.log(`${s} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`),!r)throw new Error("root required.");if(!e)throw new Error("space required. (E: 186af2731c5342a78b063a0a4346f3db)");let i=_({ibGib:r}),a=await qr({type:"roots",space:e});if(!a)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let l=await Ie({src:a,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[i]},nCounter:!0});await re({resTransform:l,space:e});let d=oe({type:"roots"}),b=l.newIbGib,u=_({ibGib:b});await fe({key:d,addr:u,space:e,zeroSpace:t,fnUpdateBootstrap:o}),await Se({ibGib:b,space:e,fnBroadcast:n})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{S&&console.log(`${s} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}f(En,"setCurrentRoot");async function fi({ibGib:r,linked:e,rel8nName:t,space:o,fnBroadcast:n,zeroSpace:s,fnUpdateBootstrap:i}){let a=`[${fi.name}]`;try{if(!o)throw new Error("space required. (E: f2758eab3bb844d2b749515672d9e392)");if(!r)throw new Error("ibGib required (E: f1bfd67754a7271553f4af544d30bc22)");let c=await di({space:o});if(!c)throw new Error("currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750");let l=he({ibGib:r,defaultIfNone:"incomingAddr"}),d=_({ibGib:r});if(t&&l&&c.rel8ns&&c.rel8ns[t]&&c.rel8ns[t].includes(l))return;t=t||Xo;let b=await Ie({src:c,dna:!1,linkedRel8ns:e?["past","ancestor",t]:["past","ancestor"],rel8nsToAddByAddr:{[t]:[d]},nCounter:!0});await re({resTransform:b,space:o});let u=b.newIbGib,p=_({ibGib:u});S&&console.log(`${a} updating _currentRoot root. newRootAddr: ${p}`),await Se({ibGib:u,space:o,fnBroadcast:n}),await En({root:u,space:o,zeroSpace:s,fnUpdateBootstrap:i,fnBroadcast:n})}catch(c){console.error(`${a} ${c.message}`);return}}f(fi,"rel8ToCurrentRoot");async function pn({targetIbGib:r,space:e}){let t=`[${pn.name}]`;try{S&&console.log(`${t} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let o=await un({targetIbGib:r}),n=await gn({ibGib:o,space:e});if(!n.success)throw new Error(`error putting metaStone in space. error: ${n.errorMsg??"[unknown error (E: 45f700f4f1ff463ca8f5353c8e796ac7)]"} (E: 4c25379e66365055e3e423561a7d6123)`)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{S&&console.log(`${t} complete.`)}}f(pn,"createAndSaveNewMetaStone");async function Se({ibGib:r,space:e,fnBroadcast:t}){let o=`[${Se.name}]`,n=S;try{let s=_({ibGib:r});if(o=`${o}[${s}]`,!e)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(S&&console.log(`${o} starting...`),!ie({ibGibAddr:s}).tjpGib&&!r.data?.isTjp){S&&console.log(`${o} incoming ibGib has no timeline, so no broadcast. still going to create a metastone for it and return early. (I: 649752e3b1be0e0ceb078e0ec2a84f23)`),await pn({targetIbGib:r,space:e});return}let a=he({ibGib:r,defaultIfNone:"undefined"});if(!a){let h=r.data?.isTjp?r:await hn({ibGib:r,space:e});h||(console.warn(`${o} tjp not found for ${s}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`),h=r),a=_({ibGib:h})}if(!a)throw new Error("(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)");let c=f(async()=>{S&&console.log(`${o} adding/replacing latest. tjp: ${a} (I: 7f848da003a2436089fd6f044d96bb42)`),await pn({targetIbGib:r,space:e}),t&&(S&&console.log(`${o} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{S&&console.log(`${o} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),t({ib:"IbGibTimelineUpdateInfo",tjpAddr:a,latestAddr:s,latestIbGib:r})}))},"replaceLatest");if(r.data?.isTjp){S&&console.log(`${o} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}S&&console.log(`${o} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let l=await Ue({ibGibs:[r],space:e});if(!l.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:d,latestAddrsMap:b}=l.data;if(!d){let{errors:h}=l.data;throw h??=["[unknown error (E: 344857f1853641aa842cea3931f90428)]"],new Error(`resLatest.success falsy. errors: ${H(h)}. addr: ${s} (E: b66721da6e1ef9ac4f4089e86c059323)`)}if(!b)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let u=Object.keys(b);if(u.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(u[0]!==s)throw new Error(`(UNEXPECTED) latestAddrsMap has 1 key (correct) but the key isn't the incoming ibGibAddr? (incorrect). incoming ibGibAddr: ${s}. key found: ${u[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);S&&(console.log(`${o} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(b));let p=b[s];if(p)if(p===s){S&&console.log(`${o} no other found. possible idempotent replacement. addr: ${s} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{S&&console.log(`${o} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${p}. incoming addr: ${s} (I: 6cadf13f82aabeb71d76babf1813e623)`);let h=await ce({addr:p,space:e});if(!h.success||h.ibGibs?.length!==1){console.error(`Didn't find existing latest ibGib (${p}). 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 g=h.ibGibs[0];if(typeof r.data?.n=="number"&&r.data.n>=0){S&&console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${r.data.n}`);let y=r.data.n;if(typeof g.data?.n=="number"&&g.data.n>=0){let T=g.data.n;if(y>T)S&&console.log(`${o} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{S&&console.log("is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)"),console.warn(`${o} incoming ibGib (${s}) is NOT NEWER than existing latest (${p}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${y}. n_existingLatest: ${T}. space.ib: ${e.ib} (W: 057baadca494473dabb26fb4fb879774)`);return}}else g.data?.isTjp&&r.data.n===0?await c():(console.warn(`${o} (UNEXPECTED) only existingLatestIbGib (isTjp: ${g.data?.isTjp}) has a data.n counter? ibGib.data.n: ${r.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(`${o} console.dir(existingLatestIbGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(g),console.log(`${o} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(r),await c())}else if(S&&console.log(`${o} no nCounter found. Trying brute force method.`),await Ti({ibGib:r,ibGibAddr:s,existingLatest:g,existingLatestAddr:p,tjpAddr:a,space:e})===s)await c();else return}else if(p===null){S&&console.log(`${o} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${s} (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(s){throw console.error(`${o} ${s.message}`),s}finally{S&&console.log(`${o} complete.`),S=n}}f(Se,"registerNewIbGib");async function Ct({type:r,rel8nName:e,ibGibsToRel8:t,ibGibsToUnRel8:o,addrsToUnRel8:n,linked:s,severPast:i,deletePreviousSpecialIbGib:a,space:c,zeroSpace:l,fnUpdateBootstrap:d,fnBroadcast:b}){let u=`[${Ct.name}](type:${r},rel8nName:${e})`;try{if(!c)throw new Error("space required. (E: 956192eea28047eba6dad81620bb96fb)");if((t??[]).length===0&&(o??[]).length===0&&(n??[]).length===0)throw new Error("either ibGibsToRel8 or ibGibsToUnRel8 required. (E: 5add49c8e46a54e2c6b057c22646a822)");if((o??[]).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 p=t?.map($=>_({ibGib:$}));n??=o?.map($=>_({ibGib:$}));let h=oe({type:r}),g=await Hr({key:h,space:c});if(!g)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let m=await ce({addr:g,space:c});if(!m.success)throw new Error("couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)");if(!m.ibGibs)throw new Error("resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)");if(m.ibGibs.length!==1)throw new Error(`resGetSpecial.ibGibs count is not 1 (${m.ibGibs.length}) (E: b4547789016a4729af30cd972a4ca4ab)`);let y=m.ibGibs[0],w=await Ie({src:y,rel8nsToAddByAddr:p?{[e]:p}:void 0,rel8nsToRemoveByAddr:n?{[e]:n}:void 0,dna:!1,linkedRel8ns:s?[Y.past,e]:[Y.past],nCounter:!0}),T=w.newIbGib;if(i){if(w.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");T.rel8ns.past=[],T.gib=await K({ibGib:T})}await re({resTransform:w,space:c});let A=_({ibGib:T}),x=he({ibGib:T});return await fe({key:h,addr:A,space:c,zeroSpace:l,fnUpdateBootstrap:d}),a&&await mn({addr:g,space:c}),await Se({ibGib:T,fnBroadcast:b,space:c}),A}catch(p){throw console.error(`${u} ${p.message}`),p}}f(Ct,"rel8ToSpecialIbGib");async function hn({ibGib:r,naive:e=!0,space:t}){let o=`[${hn.name}]`;try{if(!t)throw new Error("space required. (E: 941f973d50e84415b58724af173f52c2)");if(!r)throw new Error("ibGib required.");let n=_({ibGib:r}),{gib:s}=L({ibGibAddr:n});if(s===R||await Tn({ibGib:r,naive:e}))return r;if(!r.rel8ns){S&&console.log(`${o} ibgib not tjp in data, and rel8ns is falsy. so tjp is undefined (I: acdadb76a7568807db7a68f6f866de22)`);return}if(r.rel8ns.tjp&&r.rel8ns.tjp.length>0){let b=r.rel8ns.tjp[0],u=await ce({addr:b,space:t});if(u.success&&u.ibGibs?.length===1)return u.ibGibs[0];{let p=u.errorMsg??"[unspecified error in get result]";throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${p} (E: 94f0340706ad48c794c6a62c1b235a22)`)}}let a=r.rel8ns.past||[];if(a.length===0){console.warn(`${o} past.length === 0, so there is no tjp.`),S&&console.log(`${o} ibgib is not tjp in data, not in tjp rel8n, and past is empty. so tjp is undefined (I: bf06f664917dcf4492fb9c4c106a6222)`);return}let c=a[a.length-1],l=await ce({addr:c,space:t});if(!l.success||l.ibGibs?.length!==1)throw new Error(`get past failed. addr: ${c}`);let d=l.ibGibs[0];return await hn({ibGib:d,naive:e,space:t})}catch(n){throw console.error(`${o} ${n.message}`),n}}f(hn,"getTjpIbGib");async function bi({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${bi.name}]`;try{if(!e)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(r){case"roots":return hi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"tags":return ui({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"secrets":return mi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"encryptions":return Ei({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"outerspaces":return wi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"autosyncs":return $i({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"robbots":return yi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"apps":return Ii({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});default:return _i({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o})}}catch(i){throw console.error(`${s} ${i.message}`),i}}f(bi,"createSpecial");async function Le({type:r,skipRel8ToRoot:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s}){let i=`[${Le.name}][${r||"falsy type?"}]`;try{S&&console.log(`${i} starting...`);let a=In({type:r}),c=B.primitive({ib:a}),l=await Tr({src:c,destIb:a,linkedRel8ns:[Y.past,Y.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await re({resTransform:l,space:t}),r!=="roots"&&r!=="latest"&&!e&&await fi({ibGib:l.newIbGib,linked:!0,space:t,zeroSpace:o,fnBroadcast:s,fnUpdateBootstrap:n}),S&&console.log(`${i} complete.`),l.newIbGib}catch(a){throw console.error(`${i} ${a.message}`),a}}f(Le,"createSpecialIbGib");async function ui({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ui.name}]`;try{if(!r)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let s=oe({type:"tags"}),i=await Le({type:"tags",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),a=_({ibGib:i});await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});let c=[{text:"home",icon:"home-outline"},{text:"favorite",icon:"heart-outline"}];for(let l of c)a=(await pi({...l,space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t})).newTagsAddr,await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});return a}catch(s){return console.error(`${n} ${s.message}`),null}}f(ui,"createSpecial_Tags");async function pi({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${pi.name}]`;try{if(S&&console.log(`${a} starting...`),!o)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!r)throw new Error(`${a} text required`);e=e||Us,t=t||ks;let c=pt(r),l=B.primitive({ib:"tag"}),d=await B.firstGen({parentIbGib:l,ib:c,data:{text:r,icon:e,description:t},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),b=d.newIbGib;await re({resTransform:d,space:o}),await Se({ibGib:b,space:o,fnBroadcast:i});let u=await zc({tagIbGib:b,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i});return{newTagIbGib:b,newTagsAddr:u}}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(pi,"createTagIbGibAndSundry");async function hi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${hi.name}]`;try{if(!r)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let s=oe({type:"roots"}),i=await Le({type:"roots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),a=_({ibGib:i});await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});let l=["A","B","C","D","E","F","G"].map(b=>({text:`${b}root`,icon:Yo,description:Wo})),d;for(let b=0;b<l.length;b++){let u=l[b],p=await gi({...u,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o});if(d||(d=p.newRootIbGib),!p.newRootIbGib)throw new Error("(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)");a=p.newRootsAddr,await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t})}if(!d)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await En({root:d,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Hr({key:s,space:r}),!a)throw new Error("(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)");return a}catch(s){return console.error(`${n} ${s.message}`),null}}f(hi,"createSpecial_Roots");async function gi({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${gi.name}]`;try{if(!o)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");r=r||Ls,e=e||Yo,t=t||Wo;let c=_n(r),l=B.primitive({ib:"root"}),d=await B.firstGen({parentIbGib:l,ib:c,data:{text:r,icon:e,description:t},linkedRel8ns:[Y.past,Y.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:b}=d;await re({resTransform:d,space:o});let u=await Ct({type:"roots",rel8nName:Vo,ibGibsToRel8:[b],space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i});return{newRootIbGib:b,newRootsAddr:u}}catch(c){throw console.error(`${a} ${c.message}`),c}}f(gi,"createRootIbGib");async function mi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${mi.name}]`;try{if(!r)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let s,i=oe({type:"secrets"}),a=await Le({type:"secrets",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(mi,"createSpecial_Secrets");async function Ei({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ei.name}]`;try{if(!r)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let s,i=oe({type:"encryptions"}),a=await Le({type:"encryptions",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Ei,"createSpecial_Encryptions");async function wi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${wi.name}]`;try{if(!r)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let s,i=oe({type:"outerspaces"}),a=await Le({type:"outerspaces",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(wi,"createSpecial_OuterSpaces");async function $i({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${$i.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=oe({type:"autosyncs"}),a=await Le({type:"autosyncs",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f($i,"createSpecial_Autosyncs");async function yi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${yi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=oe({type:"robbots"}),a=await Le({type:"robbots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(yi,"createSpecial_Robbots");async function Ii({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ii.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=oe({type:"apps"}),a=await Le({type:"apps",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s=await Fr({defaultAppData:Qs,defaultAppRel8ns:ei,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s=await Fr({defaultAppData:ti,defaultAppRel8ns:ri,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s=await Fr({defaultAppData:oi,defaultAppRel8ns:ni,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Ii,"createSpecial_Apps");async function Fr({defaultAppData:r,defaultAppRel8ns:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s}){let i=`[${Fr.name}]`;try{S&&console.log(`${i} starting... (I: 677f68789abdc7316887e8f38c764e22)`),S&&console.log(`${i} starting...`);let a=C(r),c=e?C(e):void 0;a.uuid=!a.uuid||a.uuid===ln?await j():a.uuid;let{classname:l}=a,d=cn({appData:a,classname:l}),b=await B.firstGen({ib:d,parentIbGib:B.primitive({ib:`app ${l}`}),data:a,rel8ns:c,dna:!0,linkedRel8ns:[Y.ancestor,Y.past],nCounter:!0,tjp:{timestamp:!0}});return await re({resTransform:b,space:t}),await Se({ibGib:b.newIbGib,fnBroadcast:s,space:t}),await Ct({type:"apps",rel8nName:Or,ibGibsToRel8:[b.newIbGib],fnBroadcast:s,fnUpdateBootstrap:n,space:t,zeroSpace:o})}catch(a){throw console.error(`${i} ${a.message}`),a}finally{S&&console.log(`${i} complete.`)}}f(Fr,"createApp");async function _i({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${_i.name}]`;try{if(!e)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");S&&console.log(`${s} creating special of type: ${r} (I: 283c8bb30ed6f9698b74b886c6078622)`);let i,a=oe({type:r}),c=await Le({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});return i=_({ibGib:c}),await fe({key:a,addr:i,space:e,zeroSpace:t,fnUpdateBootstrap:o}),i}catch(i){return console.error(`${s} ${i.message}`),null}}f(_i,"createSpecial_Default");async function Ti({ibGib:r,ibGibAddr:e,existingLatest:t,existingLatestAddr:o,tjpAddr:n,space:s}){let i=`[${Ti.name}][${e}]`;try{if(S&&console.log(`${i} starting...`),!s)throw new Error("space required. (E: 64eb9a271f5d43deadec30b9638746c8)");let a=r.rel8ns?.past||[],c=t.rel8ns?.past||[];if(a.length===1&&c.length===0)return S&&console.log(`prospective has a past, so it "must" be newer. (won't quote "must" anymore)`),e;if(c.length===1&&a.length===0)return S&&console.log("existing has a past, so it must be newer."),o;if(c.length===0&&a.length===0)return console.warn(`${i} neither existing latest nor prospective new ibGib has a past, so keeping existing.`),o;if(c.includes(e))return S&&console.log("existing by definition is newer"),o;if(a.includes(o))return S&&console.log("ibGib by definition is newer"),e;if(o===e)return S&&console.log("they're the same!"),o;if(o===n&&t.rel8ns?.tjp?.length===1)return S&&console.log("ibGib must be newer because the existingLatestAddr is the tjp, which is by definition first in unique past."),e;if(e===n&&r.rel8ns?.tjp?.length===1)return S&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),o;S&&console.log(`${i} brute forcing through iterating the pasts.`);let l,d=-1,b=f(async(h,g,m)=>{let y=h.rel8ns?.past||[];if(y.includes(m))return l=_({ibGib:h}),-1;if(y.length===0)return g;let w=g+y.length;if(d!==-1&&w>d)return l=_({ibGib:h}),-1;let T=await ce({addr:y[0],space:s});if(!T.success||T.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${y[0]}`);return b(T.ibGibs[0],g+y.length,m)},"getPastCount");S&&console.log(`${i} doing ibGibPastCount`);let u=await b(r,0,o);if(l)return l;S&&console.log(`${i} Doing existingPastCount`),d=u;let p=await b(t,0,e);return l||(u>p?(S&&console.log(`${i} ibGibPastCount (${u}) is longer than existingPastCount (${p}), so ibGib is newer.`),l=e):(S&&console.log(`${i} existingPastCount (${p}) is longer than ibGibPastCount (${u}), so ibGib is newer.`),l=o),l)}catch(a){throw console.error(`${i} ${a.message}`),a}finally{S&&console.log(`${i} complete.`)}}f(Ti,"getLatestAddr_Brute");function zc({tagIbGib:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){return Ct({type:"tags",rel8nName:zo,ibGibsToRel8:[r],space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n})}f(zc,"rel8TagToTagsIbGib");function wn({space:r,scope:e}){let t=`[${wn.name}]`;try{if(S&&console.log(`${t} starting...`),!r)throw new Error("space required. (E: 3ba16e6c3e5e47948b0e63448da11752)");if(!r.data?.uuid)throw new Error("invalid space (space.data.uuid falsy) (E: 273262b32f2ef27b2e690bc699f33822)");if(!e)throw new Error("scope required. (E: f47801d6c45e2247b42a53d9b604b522)");for(;e.includes(ee);)S&&console.log(`${t} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),e=e.replace(ee,"_");let o=r.data.uuid,n=`${Cs} ${o} ${e}`;return _({ib:n,gib:R})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{S&&console.log(`${t} complete.`)}}f(wn,"getSpaceLockAddr");async function Ge({space:r,scope:e,secondsValid:t,maxDelayMs:o,fn:n,callerInstanceId:s,maxLockAttempts:i}){let a=`[${Ge.name}]`;try{if(S&&console.log(`${a} starting...`),!r)throw new Error("space required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");if(!t)throw new Error("secondsValid required. (E: 92c5610e57ceede5ce83cff86d5c2a22)");if(t<0)throw new Error("secondsValid must be positive. (E: 970a7510c517235d7a355a843d18d222)");if(!n)throw new Error("fn required (E: 7022e280252ec2faf756b6db05c56e22)");let c;S&&console.log(`${a} attempting to acquire lock with scope ${e} (I: fed36d42a975b1c52897a4df804ac722)`);let l;o=(o??0)>0?o:Ps;let d=0;i=i??!1?i:Rs;do{if(l=await Ai({space:r,scope:e,secondsValid:t,instanceId:s}),l?.data?.success)break;let u=Math.ceil(Math.random()*o);await de(u),d++}while(d<i);if(l?.data?.success)S&&console.log(`${a} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`);else throw new Error(`could not acquire lock after ${d} attempts with intermittent delays of ${o} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);let b=`${a}[fn]`;try{S&&console.log(`${b} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(u){throw console.error(`${b} ${u.message}`),u}finally{S&&console.log(`${b} unlocking space with scope: ${e} (I: 21034d9c3395499756e9000e40417d22)`),await Si({space:r,scope:e,instanceId:s}),S&&console.log(`${b} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(Ge,"execInSpaceWithLocking");async function rr({zeroSpace:r}){let e=`[${rr.name}]`;try{if(S&&console.log(`${e} starting...`),!r)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let t=Ze;S&&console.log(`${e} getting from zeroSpace...`);let o=await r.argy({ibMetadata:ve({space:r}),argData:{cmd:"get",ibGibAddrs:[t]}}),n=await r.witness(o);if(n?.data?.success&&n.ibGibs?.length===1){let s=n.ibGibs[0];return S&&console.log(`${e} bootstrapibGib found: ${H(s)}`),await dn(s)?s:(S&&console.log(`${e} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return S&&console.log(`${e} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(t){throw console.error(`${e} ${t.message}`),t}finally{S&&console.log(`${e} complete.`)}}f(rr,"getValidatedBootstrapIbGib");async function Jc({zeroSpace:r,bootstrapIbGib:e,localSpaceId:t,lock:o,callerInstanceId:n,fnDtoToSpace:s,localSpaceCacheSvc:i}){let a=`[${Jc.name}]`;try{if(!r)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!e)if(S&&console.log(`${a} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),o){let d=Ze;S&&console.log(`${a} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),e=await Ge({space:r,scope:d,fn:f(async()=>{let b=await rr({zeroSpace:r});if(b)return b;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:vr})}else S&&console.log(`${a} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),e=await rr({zeroSpace:r})??void 0;if(!e)throw new Error("bootstrapIbGib falsy. not initialized? (E: 91f5c82b5e124178d958701ebcb09822)");if(!e.data)throw new Error("(UNEXPECTED) bootstrapIbGib.data required. invalid bootstrap? (E: 568c6b837c1a39f7a25d188a90167423)");t=t??e.data[Ae];let c=e.rel8ns[t][0],l=f(async()=>{let d=await r.argy({ibMetadata:ve({space:r}),argData:{cmd:"get",ibGibAddrs:[c]}}),b=await r.witness(d);if(b?.data?.success&&b.ibGibs?.length===1){let u=b.ibGibs[0],p=await s(u);return i&&(p.cacheSvc=i),p}else throw new Error(`Could not get local space addr (${c}) specified in bootstrap space (${_({ibGib:e})}). (E: 6d6b45e7eae4472697ddc971438e4922)`)},"fnGet");return o?(S&&console.log(`${a} getting localSpaceId (${t}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await Ge({space:r,scope:t,fn:f(()=>l(),"fn"),callerInstanceId:n,secondsValid:vr})):(S&&console.log(`${a} getting localSpaceId (${t}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),l())}catch(c){throw console.error(`${a} ${c.message}`),c}}f(Jc,"getLocalSpace");async function Ai({space:r,scope:e,secondsValid:t,instanceId:o}){let n=`[${Ai.name}]`;try{if(S&&console.log(`${n} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");if(!t)throw new Error("secondsValid required and positive (E: b42b6733638b46c06c9aff59a6c49822)");if(t<0)throw new Error("secondsValid must be positive (E: bbe3b6d567583bfb35a1c0825eb29622)");let s,i=wn({space:r,scope:e}),a,c=await ce({addr:i,space:r,force:!0});if(c.success&&c.ibGibs?.length===1?(a=c.ibGibs[0],a?.data?.expirationUTC?jo({expirationTimestampUTC:a.data.expirationUTC})&&(console.warn(`${n} ignoring expired existing lock in space at ${i}. Should be overwritten (W: 7421c5b051724b189f88cecbbd449b22)`),a=void 0):(console.error(`${n} (UNEXPECTED) exisingLock.data.expirationUTC falsy? (E: 218dc0e935534a149d0be153c532cf25)`),a=void 0)):S&&console.log(`${n} existing lock not found for ${i} (I: 191af56ec4e2db3d19084e46bf949222)`),a){if(!a.data)throw new Error("(UNEXPECTED) existingLock.data falsy? (E: 00069b4662e5566d971760d15e293723)");s=C(a),s.data.alreadyLocked=!0,s.data.success=!1}else{let{ib:l,gib:d}=L({ibGibAddr:i});s={ib:l,gib:d,data:{scope:e,secondsValid:t,instanceId:o,expirationUTC:Mo({seconds:t})}};let b=await r.argy({ibMetadata:ve({space:r}),argData:{cmd:"put",force:!0,ibGibAddrs:[i]},ibGibs:[s]}),u=await r.witness(b);if(u.data?.success)if((u.data.addrsAlreadyHave??[]).includes(i)){S&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${i}) (I: 2e8a1562947c40698110b64251141753)`);let p=await ce({addr:i,space:r,force:!0});if(p.success&&p.ibGibs?.length===1){let h=p.ibGibs[0];s=C(h),s.data.alreadyLocked=!0,s.data.success=!1}else{let h=`${n} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;console.error(h),s.data.success=!1,s.data.errorMsg=h}}else s.data.success=!0;else{let p=`${n} there was an error putting the lock in the space: ${u.data?.errors?.join("|")}`;s.data.success=!1,s.data.errorMsg=p,console.error(p)}}return s}catch(s){throw console.error(`${n} ${s.message}`),s}finally{S&&console.log(`${n} complete.`)}}f(Ai,"lockSpace");async function Si({space:r,scope:e,instanceId:t}){let o=`[${Si.name}]`;try{if(S&&console.log(`${o} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=wn({space:r,scope:e}),s=await mn({addr:n,space:r,force:!0});if(s.success){let{ib:i,gib:a}=L({ibGibAddr:n});return{ib:i,gib:a,data:{success:!0,instanceId:t,scope:e}}}else{let i=`Delete lock in space failed. delete errorMsg: ${s.errorMsg}`;if(i.includes("not implemented"))throw new Error(i);if(i.toLowerCase().includes("does not exist")||i.toLowerCase().includes("doesn't exist")||i.toLowerCase().includes("not found")){S&&console.log(`${o} ${i} (I: b647916fd0f3e5366e9387131be21c22)`);let{ib:a,gib:c}=L({ibGibAddr:n});return{ib:a,gib:c,data:{action:"unlock",success:!0,instanceId:t,scope:e}}}else console.warn(`${o} ${i} (W: 14c84fcac15944bd9a417099964d5d9d)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{S&&console.log(`${o} complete.`)}}f(Si,"unlockSpace");async function Zc({space:r,zeroSpace:e,setSpaceAsDefault:t,createIfNotFound:o}){let n=`[${Zc.name}]`;try{if(S&&console.log(`${n} starting...`),!r)throw new Error("space required. (E: 6fc19548fa7d1d5219e19871f280a322)");if(!r.data?.uuid)throw new Error("space.data.uuid required (E: 6483188ca6f2ed2085fd355595f3ab22)");if(!e)throw new Error("zeroSpace required. (E: abbf156e18b1018d96273e22a260f122)");let s=r.data.uuid,i=_({ibGib:r}),a=await rr({zeroSpace:e});if(a){if(S&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),a.data.spaceIds.includes(s)){S&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let c=a.rel8ns[s][0];c===i?S&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(S&&console.log(`${n} updating rel8ns[${s}] with newSpaceAddr (${i}). (Old address: ${c})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),a.rel8ns[s]=[i])}else S&&console.log(`${n} new space being rel8d. adding spaceId to data.spaceIds and amending rel8ns (I: 40903d71719aa1d56e498299f5699a22)`),a.data.spaceIds.push(s),a.rel8ns[s]=[i];t&&(S&&console.log(`${n} setting spaceId (${s}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),a.data[Ae]=s)}else{if(!o){S&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}S&&console.log(`${n} creating new bootstrap ibgib for spaceId (${s}) with address of (${i}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:c,gib:l}=L({ibGibAddr:Ze});a=B.primitive({ib:c}),a.gib=l,a.data={[Ae]:s,[Nr]:[s]},a.rel8ns={[s]:[i]}}if(!a)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");S&&console.log(`${n} saving bootstrapIbGib: ${H(a)} (I: 3cceca0b98dde90e4a58a734be252322)`),await $n({zeroSpace:e,bootstrapIbGib:a}),S&&console.log(`${n} complete.`)}catch(s){throw console.error(`${n} ${s.message}`),s}}f(Zc,"updateBootstrapIbGib");async function $n({zeroSpace:r,bootstrapIbGib:e}){let t=`[${$n.name}]`;if(!r)throw new Error("zeroSpace required. (E: 818fa8430b8040dca1917f9db0972b22)");if(!e)throw new Error("bootstrapIbGib required. (E: cf21d7f1756710a66aa0e6a28d762723)");let o=await r.argy({ibMetadata:e.ib,argData:{cmd:"put",force:!0,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});S&&console.log(`${t} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let n=await r.witness(o);if(n?.data?.success)S&&console.log(`${t} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`);else throw new Error(`${n?.data?.errors?.join("|")||"There was a problem with zeroSpace witnessing the bootstrap^gib primitive."}`)}f($n,"persistBootstrapIbGibInZeroSpace");async function Qc({spaceId:r,zeroSpace:e}){let t=`[${Qc.name}]`;if(!r)throw new Error("spaceId required. (E: 52f9c31405e24c2999e5a1b32d201a23)");if(!e)throw new Error("zeroSpace required. (E: a115f4007b2c4819a58cf093d5823b23)");await Ge({space:e,scope:Ze,fn:f(async()=>{let n=await rr({zeroSpace:e});if(!n)throw new Error("bootstrapIbGib falsy in zeroSpace (E: e36a512781b0467ba1bf1d927a7c1d23)");if(!n.data)throw new Error("bootstrapIbGib.data falsy in zeroSpace (E: 8f92104192b44d71891b092481029ab0)");let s=n.data,i=s[Nr]??[];if(i.length<=1)throw new Error(`Cannot delete space (${r}). It is the only remaining local space. (E: 9c27f71120014b08b5e9f89993380e23)`);if(r===s[Ae])throw new Error(`Cannot delete space (${r}). It is the default local space. Please select a new default space before deleting. (E: f3c30a5170d14b4fb2478d102e3b2e23)`);if(!i.includes(r))throw new Error(`Space (${r}) not found in bootstrap spaceIds. (E: 61fa940e79124430a618e470bc551d23)`);s[Nr]=i.filter(a=>a!==r),n.rel8ns&&delete n.rel8ns[r],await $n({zeroSpace:e,bootstrapIbGib:n})},"fn"),secondsValid:vr})}f(Qc,"deregisterLocalSpaceFromBootstrap");async function el({spaceId:r,zeroSpace:e}){let t=`[${el.name}]`;if(!r)throw new Error("spaceId required. (E: 7c2a10529a1b412a8069e22e5190b623)");if(!e)throw new Error("zeroSpace required. (E: f112a512019c41a590b512a8e0915623)");let o=await e.argy({ibMetadata:ve({space:e}),argData:{cmd:"get",ibGibAddrs:[r]}}),n=await e.witness(o);if(n?.data?.success&&(n.ibGibs?.length??0)>0){let s=_({ibGib:n.ibGibs[0]}),i=await e.argy({ibMetadata:ve({space:e}),argData:{cmd:"delete",ibGibAddrs:[s]}});await e.witness(i)}}f(el,"deleteSpaceRecordFromZeroSpace");function ve({space:r}){return`${r.ib} ${we()}`}f(ve,"getSpaceArgMetadata");function Mp({space:r}){return`${r.ib} ${we()}`}f(Mp,"getSpaceResultMetadata");function tl({space:r,spaceData:e,classname:t}){let o=`[${tl.name}]`;try{if(!r&&!e)throw new Error("either space or spaceData required (E: 4dabec34ee77d67c9cc30ee3c3049622)");if(r&&!r.data)throw new Error("(UNEXPECTED) given space has falsy space.data? (E: 058d298876ebbeada7bbddb9e3da2f23)");if(r&&e){if(r.data.uuid!==e.uuid)throw new Error("(UNEXPECTED) both space and spaceData given, but uuid don't match? (E: efdd4603cba93a17340a76811fe56b24)");if(r.data.n!==e.n)throw new Error("(UNEXPECTED) both space and spaceData given, but n don't match? (E: e51278a707c9bccc57a08a4b86524524)")}if(e??=r.data,!e)throw new Error("(UNEXPECTED) spaceData falsy? (thought this was a compiler problem that this was even possible.) (E: b3c7ffedcae4b1f45b263b3825930b24)");if(t&&e.classname&&t!==e.classname)throw new Error(`both classname arg (${t}) and spaceData.classname (${e.classname}) are different truthy values. (E: f98f012ee876eb8fbe7403f7b53e4624)`);if(t||=e.classname,!t)throw new Error("classname required (E: fa3af4613ad56742dab51d1b0d839322)");if(t.includes(" "))throw new Error(`invalid classname (${t}). cannot contain spaces (E: 243adbf720dcce7904e2665933208b22)`);let n=e?.name||Ns;if(n.includes(" "))throw new Error("invalid space name. cannot contain spaces (E: a8450e1651081412c8ac018520182422)");let s=e?.uuid||void 0;if(!s)throw new Error("invalid space, spaceData.uuid falsy (E: 50ae723a9ab24f4fc7132613e65faf23)");if(s.includes(" "))throw new Error("invalid space id. cannot contain spaces (E: 8696830fe7f54bfa85e670a063f3e089)");let i=e.type??void 0,a=e.subtype??void 0;if(i&&!a)throw new Error(`spaceType (${i}) is set but spaceSubtype is falsy. (E: 878ab960d7987ae2331103b4a00d0d24)`);return`${jr} ${Gr} ${t} ${n} ${s} ${i} ${a}`}catch(n){throw console.error(`${o} ${n.message}`),n}}f(tl,"getSpaceIb");function rl({ib:r}){let e=`[${rl.name}]`;if(!r){let t=`${e} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(t),new Error(t)}return r.startsWith(`${jr} ${Gr} `)}f(rl,"isSpaceIb");function Kr({spaceIb:r}){let e=`[${Kr.name}]`;try{if(!r)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[t,o,n,s,i,a,c]=r.split(" ");if(t!==jr)throw new Error(`invalid spaceIb (${r}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(o!==Gr)throw new Error(`invalid spaceIb (${r}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`);if(!n)throw new Error(`invalid spaceIb (${r}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`);if(!s)throw new Error(`invalid spaceIb (${r}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`);if(!i)throw new Error(`invalid spaceIb (${r}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`);let l;if(a&&a!=="undefined")if(sn.includes(a))l=a;else throw new Error(`invalid spaceIb (${r}). spaceType (${a}) is set but not a valid type. valid types: ${sn.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let d;if(c&&c!=="undefined")if(an.includes(c))d=c;else throw new Error(`invalid spaceIb (${r}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${an.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:s,spaceId:i,spaceType:l,spaceSubtype:d}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Kr,"parseSpaceIb");async function Ue({ibGibs:r,addrs:e,tjps:t,tjpAddrs:o,space:n}){let s=`[${Ue.name}]`;try{if(S&&console.log(`${s} starting...`),!n)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(r=r??[],e=e??[],t=t??[],o=o??[],e.length===0&&r.length===0&&t.length===0&&o.length===0)throw new Error("Either addrs, ibGibs, tjps, or tjpAddrs required. (E: 7c6ebfbab98d4d21a431b144457fd991)");let i=new Set(o.concat(t.map(l=>_({ibGib:l})))),a=Array.from(i).map(l=>L({ibGibAddr:l}).gib);r.map(l=>_({ibGib:l})).concat(e).forEach(l=>{let{gib:d}=L({ibGibAddr:l});a.some(u=>d.includes(u))||i.add(l)}),S&&console.log(`${s}[testing] ${n.data?.name||n.ib} (${n.data?.uuid||"[space.data.uuid falsy]"}) addrsToQuery: ${Array.from(i)} (I: 8a2202912c364238b6d6eb09577bc246)`);let c=await n.argy({ibMetadata:ve({space:n}),argData:{cmd:"get",cmdModifiers:["latest","addrs"],ibGibAddrs:Array.from(i)}});return await n.witness(c)}catch(i){throw console.error(`${s} ${i.message}`),i}}f(Ue,"getLatestAddrs");function yn({ibGib_Context:r}){let e=`[${yn.name}]`;try{if(S&&console.log(`${e} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!or({ibGib:r}))return;if(["roots","autosyncs"].some(o=>r.ib.includes(o)))throw new Error("cannot perform a modification of this type on this special ibgib (E: b8fb718a7323fc54454464b973412722)")}catch(t){throw console.error(`${e} ${t.message}`),t}finally{S&&console.log(`${e} complete.`)}}f(yn,"throwIfContextIsSpecial");async function ol({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${ol.name}]`;try{if(S&&console.log(`${a} starting... (I: 2dc486bb2d516e4534f437aaf5ec7f22)`),!r)throw new Error("ibGib_Context required (E: 75f7bfa93145d6dffe85d488443ca722)");if(!e)throw new Error("rel8nName_Context required (E: 12aaa43de9e34b68b25dc9a2a68ad6b9)");if(!t)throw new Error("addr required (E: e27df3bdc5a2554697cc9597afc4e422)");if(!o)throw new Error("space required (E: 2e3562486ed2956a770ed9e8d77a3f22)");let c=or({ibGib:r});c&&yn({ibGib_Context:r});let l=await Ie({src:r,rel8nsToAddByAddr:{[js]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await re({resTransform:l,space:o}),c){let d=_({ibGib:l.newIbGib}),b=Vr({ib:r.ib}),u=oe({type:b});await fe({key:u,addr:d,space:o,zeroSpace:n,fnUpdateBootstrap:s})}await Se({ibGib:l.newIbGib,fnBroadcast:i,space:o})}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(ol,"trash");async function nl({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${nl.name}]`;try{if(S&&console.log(`${a} starting... (I: 38098552b830495187299bb24fcddff0)`),!r)throw new Error("ibGib_Context required (E: d819e8c4db5b4c0bb721300ba434cd40)");if(!e)throw new Error("rel8nName_Context required (E: de061adff8c04429a211aa09116a532d)");if(!t)throw new Error("addr required (E: 7059ebb8ef6149ea94e22f961d6b5c81)");if(!o)throw new Error("space required (E: e19566f2d42347798621447edcae312e)");let c=or({ibGib:r});c&&yn({ibGib_Context:r});let l=await Ie({src:r,rel8nsToAddByAddr:{[Ms]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await re({resTransform:l,space:o}),c){let d=_({ibGib:l.newIbGib}),b=Vr({ib:r.ib}),u=oe({type:b});await fe({key:u,addr:d,space:o,zeroSpace:n,fnUpdateBootstrap:s})}await Se({ibGib:l.newIbGib,fnBroadcast:i,space:o})}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(nl,"archive");function sl(r){let e=`[${sl.name}]`;try{if(!r)return console.error(`${e} name is falsy`),!1;let t=/[\w-]+/,o=r.match(t);if(o?.length!==1||o[0].length!==r.length)return console.error(`${e} name can only contain letters, numbers, underscores, hyphens`),!1;let n=/[a-zA-Z\d]/;return r[0].match(n)?!0:(console.error(`${e} name must start with a letter or number`),!1)}catch(t){return console.error(`${e} ${t.message}`),!1}}f(sl,"spaceNameIsValid");var le=!1;async function il({ibGib:r,rel8nNames:e,space:t}){let o=`[${il.name}]`;try{if(!r)throw new Error("ibGib required (E: a3c1b2d4e5f6a7b8c9d0e1f2a3b4c5d6)");if(!t)throw new Error("space required (E: b4d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6)");e||(e=Object.keys(r.rel8ns||{}));let n={};for(let s of e){let i=r.rel8ns?.[s]||[];if(i.length>0){let a=await ce({addrs:i,space:t});if(a.success&&a.ibGibs?.length===i.length)n[s]=a.ibGibs.concat();else throw new Error(`Problem getting rel8d ibgibs for rel8nName: ${s}. ${a.errorMsg||"Unknown error"} (E: c5e3d4f5a6b7c8d9e0f1a2b3c4d5e6)`)}else n[s]=[]}return n}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(il,"getRel8dIbGibs");async function xe({parentPrimitiveIb:r,ib:e,ibRegExpPattern:t,data:o,rel8ns:n}){let s=`[${xe.name}]`;try{if(!r)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(Nt({ib:r})!==null)throw new Error(`Invalid parentPrimitiveIb: ${r}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`);if(!e)throw new Error("ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)");let i=t?new RegExp(t):Ds;if(!e.match(i))throw new Error(`invalid ib. does not match regexp (${i})`);let a=Object.keys(n??{}),c=[...Je,"tjp"];if(a.some(u=>c.includes(u)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let b=(await B.firstGen({ib:e,parentIbGib:B.primitive({ib:r}),data:o,rel8ns:n,dna:!1,noTimestamp:!0,nCounter:!1})).newIbGib;return b?.rel8ns?.past&&delete b.rel8ns.past,b?.rel8ns?.tjp&&delete b.rel8ns.tjp,b?.rel8ns?.identity&&delete b.rel8ns.identity,b.gib=await K({ibGib:{ib:b.ib,data:b.data,rel8ns:b.rel8ns},hasTjp:!1}),b}catch(i){throw console.error(`${s} ${i.message}`),i}}f(xe,"constantIbGib");function eh({addr:r}){return xi({addr:r})}f(eh,"getBinHashAndExt");function xi({addr:r}){let e=`[${xi.name}]`;try{if(!er({addr:r}))throw new Error("not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)");let{ib:t}=L({ibGibAddr:r}),o=t.split(" ");if(o.length===2)return{binHash:o[1],binExt:""};if(o.length===3)return o[2].startsWith("enc=")?{binHash:o[1],binExt:"",binEncoding:o[2].substring(4)}:{binHash:o[1],binExt:o[2]};if(o.length===4){if(!o[3].startsWith("enc="))throw new Error(`bin ib (${t}) 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:o[1],binExt:o[2],binEncoding:o[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(t){throw console.error(`${e} ${t.message}`),t}}f(xi,"parseBinIb");function er({ibGib:r,addr:e}){let t=`[${er.name}]`;try{if(!r&&!e)throw new Error("either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)");if(r&&!r.data)return!1;e=e||_({ibGib:r});let{ib:o,gib:n}=L({ibGibAddr:e});if(!o||!n||!o.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 s=o.split(" ");if(s.length===2){if(!s[1].match(Q))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)')}else if(s.length===3){if(!s[1].match(Q))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)')}else if(s.length===4){if(!s[1].match(Q))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)');if(!s[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(o){throw console.error(`${t} ${o.message}`),o}}f(er,"isBinary");function In({type:r}){if(!r.match(Jo))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${Jo.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${r}`}f(In,"getSpecialIbGibIb");function Vr({ib:r}){let e=`[${Vr.name}]`;try{if(le&&console.log(`${e} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!r)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!or({ib:r}))throw new Error("ib is not special (E: 174aff63b992adff3ac2394643735922)");let t=r.split(" ");if(t.length<3)throw new Error('invalid ib. should be space-delimited in form of "meta special [type]" (E: ffd89e2cbe63427f98634ab897aab222)');let o=t[2];return Object.values(xr).some(n=>n===o)||console.warn(`unknown special type (${o}). This may be expected, but atow I am adding special types to the SpecialIbGibType enum-like. (W: f4e26c3ebb57fe49d69014a4ba32a922)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{le&&console.log(`${e} complete.`)}}f(Vr,"getSpecialTypeFromIb");function al({type:r}){return`${In({type:r})}^${R}`}f(al,"getSpecialIbGibAddr");function oe({type:r}){return`${Fs} ${al({type:r})}`}f(oe,"getSpecialConfigKey");function or({ib:r,ibGib:e}){if(!r&&!e?.ib)throw new Error("either ib or ibGib.ib required (E: b4cf539638d7966c2e351987f55e1a23)");return(r??e?.ib)?.startsWith("meta special")}f(or,"isSpecial");function _n(r){let e=`[${_n.name}]`;if(!r)throw new Error(`${e} text required.`);return`root ${r}`}f(_n,"getRootIb");function pt(r){let e=`[${pt.name}]`;if(!r)throw new Error(`${e} tag required.`);return`tag ${r}`}f(pt,"tagTextToIb");function Xr({ibGibs:r,filterPrimitives:e}){let t=`[${Xr.name}]`;try{let o={},n={},s={};return(e?r.filter(a=>a.gib??a.gib!==R):r).forEach(a=>{Gi({ibGib:a})?(a.rel8ns?.dna??[]).length>0?o[a.gib]=a:n[a.gib]=a:s[a.gib]=a}),{mapWithTjp_YesDna:o,mapWithTjp_NoDna:n,mapWithoutTjps:s}}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Xr,"splitPerTjpAndOrDna");function nr({ibGibs:r}){let e=`[${nr.name}]`;try{le&&console.log(`${e} starting...`);let{mapWithTjp_YesDna:t,mapWithTjp_NoDna:o}=Xr({ibGibs:r,filterPrimitives:!0}),n={...t,...o},s=Object.values(n),i=ko({items:s,keyFn:f(a=>a.data?.isTjp?_({ibGib:a}):a.rel8ns?.tjp?a.rel8ns?.tjp[0]??"":(le&&console.log(`${e} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return le&&console.log(`${e} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${H(i)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),Object.entries(i).forEach(([a,c])=>{c.some(l=>l.data?.n===void 0)&&console.warn(`${e} 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(`${e} after sort ibGibsWithTjpGroupedByTjpAddr: ${H(i)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),i}catch(t){throw console.error(`${e} ${t.message}`),t}finally{le&&console.log(`${e} complete.`)}}f(nr,"getTimelinesGroupedByTjp");function Gi({ibGib:r}){let e=`[${Gi.name}]`;if(!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: ce3a59f9db14e6158bb2c438ca1a3823)");if((r.rel8ns?.tjp?.length??0)>0||r.data?.isTjp)return!0;let t=["fork^gib","mut8^gib","rel8^gib"];return(r.rel8ns?.ancestor??[]).some(n=>t.includes(n))?!1:r.gib?r.gib.includes(Ce)?!0:r.gib===R?!1:!!ie({ibGibAddr:_({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(Gi,"hasTjp");function he({ibGib:r,defaultIfNone:e="undefined"}){let t=`[${he.name}]`;try{let o=vi({ibGibs:[r],defaultIfNone:e});return o&&Object.keys(o).length===1?Object.values(o)[0]:void 0}catch(o){throw console.error(`${t} ${o.message}`),o}}f(he,"getTjpAddr");function vi({ibGibs:r,defaultIfNone:e="undefined"}){let t=`[${vi.name}]`;try{let o={};return r.forEach(n=>{let s=_({ibGib:n}),i;n.rel8ns?.tjp?.length??!1?i=n.rel8ns.tjp[n.rel8ns.tjp.length-1]:n.data?.isTjp||e==="incomingAddr"?i=s:i=void 0,o[s]=i}),o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(vi,"getTjpAddrs");async function Tn({ibGib:r,naive:e=!0}){let t=`[${Tn.name}]`;try{if(!r)throw new Error("ibGib required.");if(e){if(r.data)return r.data.isTjp?!0:r.rel8ns?r.rel8ns.past&&r.rel8ns.past.length>0?!1:!!(r.rel8ns.past&&r.rel8ns.past.length===0):(le&&console.log(`${t} ibGib.rel8ns falsy (I: c69c9e78b34845311ce7c674d7195622)`),!1);throw new Error("loaded ibGib required (data).")}else throw new Error("only naive implemented right now.")}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Tn,"isTjp_Naive");function ke({ibGib:r}){let e=`[${ke.name}]`;r.ib||console.warn(`${e} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),r.gib||console.warn(`${e} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let t={ib:(r.ib||"").slice()};return r.gib&&(t.gib=r.gib.slice()),r.data&&(er({ibGib:r})?t.data=r.data.slice():t.data=C(r.data)),r.rel8ns&&(t.rel8ns=C(r.rel8ns)),t}f(ke,"toDto");function An(r){let e=`[${An.name}]`;try{return le&&console.log(`${e} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!r&&typeof r.ib=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{le&&console.log(`${e} complete.`)}}f(An,"isIbGib");function Qt({ibGib:r,data:e,timestamp:t}){let o=`[${Qt.name}]`;try{le&&console.log(`${o} starting... (I: 35cb68744bcf6139d78e37de644fad23)`),t=t||e?.timestamp||r?.data?.timestamp;let n=r?.data?.timestampMs||e?.timestampMs;if(!t){let s=`${o} timestamp is falsy. (W: 5f1f1182c8804807b886a3d922ac3dcf)`;return console.warn(s),{valid:!1,emsg:s}}if(typeof t=="string")if(Number.isInteger(Number.parseInt(t))){let s=Number.parseInt(t),i=new Date;if(i.setTime(s),i.toString()!==Dr)return le&&console.log(`${o} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`),{valid:!0,date:i,utc:i.toUTCString(),ticks:i.getTime().toString(),ms:n};{let a=`${o} data.timestamp (${t}) is an integer string but not a valid timestampInTicks string. (produces invalid date) (E: f49fbb600fe1426c8805dfc8afbe5cf3)`;return console.error(a),{valid:!1,emsg:a}}}else{let s=new Date(t);if(s.toString()!==Dr)return{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${o} 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(i),{valid:!1,emsg:i}}}else if(typeof t=="number")if(Number.isInteger(t)){console.warn(`${o} expected data.timestamp to be a string but is a number (W: 9d786f4d4e8d4279b5af7bee19bf721b)`);let s=new Date;if(s.setTime(t),s.toString()!==Dr)return{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${o} timestamp (${t}) is an integer number but not a valid timestampInTicks (new date setTime produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(i),{valid:!1,emsg:i}}}else{let s=`${o} timestamp (${t}) is a non-integer number (supposed to be a string either timestamp string or ticks). (E: 2963d95f8d3b464c992b0bff948b4479)`;return console.error(s),{valid:!1,emsg:s}}else{let s=`${o} unknown typeof timestamp (${typeof t}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;return console.error(s),{valid:!1,emsg:s}}}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{le&&console.log(`${o} complete.`)}}f(Qt,"getTimestampInfo");async function Sn({addrs:r,readCache_graph:e,readCache_array:t,space:o}){let n=`[${Sn.name}]`;try{le&&console.log(`${n} starting... (I: 5db66871239dfa05182277f886a20926)`),e??={},t??=[];let s={...e};t.forEach(l=>s[_({ibGib:l})]=l);let i=Object.keys(e),a=r.filter(l=>!i.includes(l));if(a.length>0){le&&console.log(`${n} ${a.length} addrsNotFoundInCache: ${a} (I: fccbd18116ffb849f813aaebfc6c0826)`);let l=[o],d=a.concat();for(let b of l){let u=await ce({addrs:d,space:b});if(u.success&&u.ibGibs&&u.ibGibs.length===d.length)u.ibGibs.forEach(p=>s[_({ibGib:p})]=p),d=[];else if(u.ibGibs&&u.ibGibs.length>0){if(d=d.filter(p=>!u.ibGibs.some(h=>_({ibGib:h})===p)),d.length===0)break}else le&&console.log(`${n} no addrs found in space (${b.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(b=>b.ib).join("|")} (E: 0c6418f83dd85bda886e56f5b98f3126)`)}let c=[];for(let l of r){let d=s[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(s){throw console.error(`${n} ${E(s)}`),s}finally{le&&console.log(`${n} complete.`)}}f(Sn,"getIbGibsFromCache_fallbackToSpaces");var Di=!1,cl="space_gib_db",ll="space_gib_store",dl="space_gib_api_key";var fl="agent";var sh=pt(fl);var ih={dbName:cl,storeName:ll,additionalStoreNames:[Os],apiKeyName:dl};var Oi="0.0.21";var rt=!1,dh="[web^gib timer]",Yr="ibgib";var bl="agent",fh="body-outline",bh="This tag tracks the active agents for the current local user space.",uh=pt(bl),Ni="#78f87e88",Ci="#78f87e10",Pi="#ffffff";var ph="AUTOMATED_TEXT";var De=!1;function Ri(r){return new Promise((e,t)=>{let o=new Blob([r],{type:"application/octet-stream"}),n=new FileReader;n.onload=()=>{let i=n.result.split(",")[1];e(i)},n.onerror=s=>t(s),n.readAsDataURL(o)})}f(Ri,"uint8ArrayToBase64");async function Li(r){let e=`data:application/octet-stream;base64,${r}`,n=await(await(await fetch(e)).blob()).arrayBuffer();return new Uint8Array(n)}f(Li,"base64ToUint8Array");async function Wr({graph:r}){let e=`[${Wr.name}]`;try{De&&console.log(`${e} starting... (I: 4ddb8803cf68e1d3d35f60680cb69825)`);let t=JSON.parse(JSON.stringify(r));for(let n in t)r[n].data instanceof Uint8Array&&(t[n].data={_dataType:"Uint8Array_Base64",value:await Ri(r[n].data)});let o=JSON.stringify(t);return De&&console.log(`${e} jsonString.length: ${o.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{De&&console.log(`${e} complete.`)}}f(Wr,"serializeGraphToString");async function zr({jsonString:r}){let e=`[${zr.name}]`;try{De&&console.log(`${e} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`);let o=JSON.parse(r,f((n,s)=>(s&&s._dataType==="Uint8Array_Base64",s),"reviver"));for(let n in o){let s=o[n].data;s&&s._dataType==="Uint8Array_Base64"&&(o[n].data=await Li(s.value))}return o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{De&&console.log(`${e} complete.`)}}f(zr,"deserializeStringToGraph");async function Ui(r){let e=`[${Ui.name}]`;try{De&&console.log(`${e} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let t=await Wr({graph:r}),o=new TextEncoder().encode(t),s=new Response(o).body.pipeThrough(new CompressionStream("gzip"));return await new Response(s).blob()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{De&&console.log(`${e} complete.`)}}f(Ui,"compressIbGibToBlob");async function ul(r){let e=r.stream().pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).text();return await zr({jsonString:t})}f(ul,"decompressIbGibFromBlob");async function xn({graph:r}){let e=`[${xn.name}]`;try{De&&console.log(`${e} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let o=await(await Ui(r)).arrayBuffer(),n=new Uint8Array(o);return await Ri(n)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{De&&console.log(`${e} complete.`)}}f(xn,"compressIbGibGraphToString");async function Gn({compressedBase64:r}){let e=`[${Gn.name}]`;try{De&&console.log(`${e} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let t=await Li(r),o=new Blob([t],{type:"application/gzip"});return await ul(o)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{De&&console.log(`${e} complete.`)}}f(Gn,"decompressIbGibGraphFromString");var ki="export";var sr=!1;function Mi({data:r}){let e=`[${Mi.name}]`;try{sr&&console.log(`${e} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:t,dependencyGraphAsString:o,timestamp:n}=r,s=o.length,i=we(n),a=r.compression==="gzip"?"gzip":"raw";if(!r.timestamp)throw new Error("(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)");let c=new Date(r.timestamp),{ib:l,gib:d}=L({ibGibAddr:r.contextIbGibAddr}),u=ie({gib:d}).tjpGib??d,p=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${ki} ${p} ${a} ${t} ${s} ${u}`}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{sr&&console.log(`${e} complete.`)}}f(Mi,"getRawExportIb");async function vn({ibGib:r,metaspace:e,space:t,compress:o,live:n,ignoreErrors:s}){let i=`[${vn.name}]`;try{if(sr&&console.log(`${i} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let a=_({ibGib:r}),c=[],l=await ae({ibGib:r})??[];if(l.length>0){let y=`ibGib had validation errors: ${l} (E: 84890bbc0598192498178a98ae299825)`;if(s)c.push({errorMsg:y,ibGibAddr:a});else throw new Error(y)}let d=await e.getDependencyGraph({ibGib:r,live:n,space:t}),b=o?await xn({graph:d}):await Wr({graph:d}),u=he({ibGib:r,defaultIfNone:"incomingAddr"})??a,p=new Date,h={contextIbGibAddr:a,tjpAddr:u,dependencyGraphAsString:b,graphSize:Object.keys(d).length,timestamp:Oe(p),timestampMs:p.getMilliseconds()};o&&(h.compression="gzip");let g={ib:Mi({data:h}),data:h},m=await K({ibGib:g,hasTjp:!1});return g.gib=m,sr&&console.log(`${i} JSON.stringify(exportIbGib).length: ${JSON.stringify(g).length} (I: db3a8d913a91d8fc5d6e45981e034822)`),{rawExportIbGib:g,manifest:Object.keys(d),errors:c.length>0?c:void 0}}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{sr&&console.log(`${i} complete.`)}}f(vn,"getRawExportIbGib");var Oh="ibgib-shell-ready",Nh="ibgib-ui-busy",Ch="ibgib-ui-message",Ph="ibgib-identity-request-change",Rh="ibgib-identity-changed",Lh="ibgib-identity-update-available",Uh="ibgib-identity-renewal-required";var ji=rt;async function ht({title:r,msg:e,prompt:t,showInput:o,defaultValue:n,okButtonTitle:s,cancelButtonTitle:i,isPassword:a,isBusy:c,animationEmoji:l,passkeys:d,passkeyButtonTitle:b,onPasskeyAuth:u}){let p=`[${ht.name}]`;try{ji&&console.log(`${p} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let h=document.getElementById("fullscreen-dialog"),g=document.getElementById("fullscreen-dialog-body"),m=document.getElementById("fullscreen-dialog-title"),y=document.getElementById("fullscreen-dialog-message"),w=document.getElementById("fullscreen-dialog-prompt-input"),T=document.getElementById("fullscreen-dialog-ok-button"),A=document.getElementById("fullscreen-dialog-cancel-button");if(!h||!g||!m||!y||!w||!T||!A)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(m.textContent=r||"",[...y.childNodes].forEach(D=>y.removeChild(D)),(e||"").split(`
9
+ `).forEach(D=>{let U=document.createElement("p");U.textContent=D,y.appendChild(U)}),l){let D=document.createElement("div");D.id="fullscreen-dialog-animation-emoji",D.textContent=l,D.style.fontSize="3.5rem",D.style.textAlign="center",D.style.margin="1.5rem 0",D.style.animation="spin-bounce 5s infinite ease-in-out",y.appendChild(D)}let $=document.getElementById("fullscreen-dialog-passkey-container");$&&$.remove();let I=null,G=null,N=null,v=Object.values(d||{}).filter(D=>D!=null);if(v.length>0&&u&&!c){I=document.createElement("div"),I.id="fullscreen-dialog-passkey-container",I.style.margin="1rem 0",I.style.textAlign="center",G=document.createElement("button"),G.id="fullscreen-dialog-btn-passkey",G.type="button",G.className="action-btn",G.style.width="100%",G.style.padding="0.75rem 1rem",G.style.background="linear-gradient(135deg, #1b5e20, #2e7d32)",G.style.color="#ffffff",G.style.fontWeight="bold",G.style.borderRadius="8px",G.style.border="1px solid rgba(255,255,255,0.2)",G.style.cursor="pointer",G.style.fontSize="0.95rem",G.style.marginBottom="0.75rem",G.textContent=b||"\u{1F6E1}\uFE0F Touch ID / Security Key",v.length>1&&(N=document.createElement("select"),N.style.width="100%",N.style.padding="0.4rem",N.style.marginBottom="0.5rem",N.style.borderRadius="4px",N.style.background="rgba(0,0,0,0.3)",N.style.color="inherit",N.style.border="1px solid rgba(255,255,255,0.2)",v.forEach((U,V)=>{let Z=document.createElement("option");Z.value=V.toString(),Z.textContent=`${U.name||"Key"} (${U.credentialId?.substring(0,8)}...)`,N.appendChild(Z)}),I.appendChild(N)),I.appendChild(G);let D=document.createElement("div");D.style.display="flex",D.style.alignItems="center",D.style.justifyContent="center",D.style.gap="0.5rem",D.style.fontSize="0.8rem",D.style.color="var(--clr-text-secondary, #b3b3b3)",D.style.margin="0.5rem 0",D.innerHTML=`
10
+ <span style="flex: 1; height: 1px; background: rgba(255,255,255,0.15);"></span>
11
+ <span>OR enter Password below</span>
12
+ <span style="flex: 1; height: 1px; background: rgba(255,255,255,0.15);"></span>
13
+ `,I.appendChild(D),w.parentElement?.insertBefore(I,w)}w.classList.remove("collapsed"),A.classList.remove("collapsed"),A.style.display="inline-block",T.style.display="inline-block",T.textContent=s||"OK";let P=f(D=>{(D.key==="Enter"||D.key===`
14
+ `)&&D.ctrlKey&&T.click()},"onKeypress");return c?(w.classList.add("collapsed"),A.style.display="none",T.style.display="none"):t||o?(w.addEventListener("keypress",P),o?(w.autofocus=!0,w.value=n??"",w.addEventListener("keypress",D=>{D.key==="Enter"&&T.click()}),a?(w.type="password",w.autocomplete="off",w.required=!0):(w.type="text",w.autocomplete="on",w.required=!1,w.attributes["auto-complete"]="on")):(w.autofocus=!1,w.classList.add("collapsed")),A.textContent=i||"Cancel"):(w.classList.add("collapsed"),A.style.display="none"),new Promise(D=>{if(c){let pe=f(wr=>{wr.preventDefault()},"onCancelEvent");h.addEventListener("cancel",pe);let qt=f(()=>{h.removeEventListener("cancel",pe),h.close()},"close"),Po=f(({title:wr,msg:us,animationEmoji:Ro})=>{if(wr!==void 0&&(m.textContent=wr),us!==void 0){[...y.childNodes].forEach($r=>{$r.id!=="fullscreen-dialog-animation-emoji"&&y.removeChild($r)});let me=us.split(`
15
+ `),ps=document.getElementById("fullscreen-dialog-animation-emoji");me.forEach($r=>{let Lo=document.createElement("p");Lo.textContent=$r,ps?y.insertBefore(Lo,ps):y.appendChild(Lo)})}if(Ro!==void 0){let me=document.getElementById("fullscreen-dialog-animation-emoji");Ro?(me||(me=document.createElement("div"),me.id="fullscreen-dialog-animation-emoji",me.style.fontSize="3.5rem",me.style.textAlign="center",me.style.margin="1.5rem 0",me.style.animation="spin-bounce 5s infinite ease-in-out",y.appendChild(me)),me.textContent=Ro):me&&me.remove()}},"update");h.open||h.showModal(),de(1e3).then(()=>{g.scrollTo({top:0,behavior:"smooth"})}),D({close:qt,update:Po});return}let U=f(()=>{(t||o)&&w.removeEventListener("keypress",P),G&&G.removeEventListener("click",Z),I&&I.remove(),T.removeEventListener("click",V),A.removeEventListener("click",St),h.removeEventListener("close",ft)},"removeEventListeners"),V=f(()=>{U();let pe=o?w.value??"":"true";w&&(w.value=""),h.close(pe),v.length>0?D({secret:pe,poolId:"manage"}):D(pe)},"onOK"),Z=f(async()=>{try{if(!u)return;G.disabled=!0,G.textContent="Waiting for biometrics / security key...";let pe=v[0];if(N){let Po=parseInt(N.value,10);pe=v[Po]||v[0]}let qt=await u(pe);qt?(U(),w&&(w.value=""),h.close(qt),D({secret:qt,poolId:pe.poolId||"passkey-manage"})):(G.disabled=!1,G.textContent=b||"\u{1F6E1}\uFE0F Touch ID / Security Key")}catch(pe){console.warn("Passkey assertion in dialog failed/cancelled:",pe),G.disabled=!1,G.textContent=b||"\u{1F6E1}\uFE0F Touch ID / Security Key"}},"onPasskeyClick");G&&G.addEventListener("click",Z);let St=f(()=>{U(),w&&(w.value=""),h.close(void 0),D(void 0)},"onCancel"),ft=f(()=>{U(),w&&(w.value=""),h.close(void 0),D(void 0)},"onClose");T.addEventListener("click",V),A.addEventListener("click",St),h.addEventListener("close",ft),h.open||h.showModal(),de(1e3).then(()=>{g.scrollTo({top:0,behavior:"smooth"})})})}catch(h){throw console.error(`${p} ${E(h)}`),h}finally{ji&&console.log(`${p} complete.`)}}f(ht,"showFullscreenDialog");var se=rt;async function pl({metaspace:r,space:e}){let t=`[${pl.name}]`;try{se&&console.log(`${t} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let o=await r.getSpecialIbGib({type:xr.tags,space:e});if(!o)throw new Error(`tagsIbGib not found in metaspace. space: ${e?e.ib:"default local user space"} (E: 4734c510a411274315c0add8f70e1925)`);return o}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{se&&console.log(`${t} complete.`)}}f(pl,"getTagsIbGib");function Dn({scope:r,ibGib:e,ibGibAddr:t,defaultNameIfError:o}){let n=`[${Dn.name}]`;try{if(!e&&!t)throw new Error(`${n} Must provide either ibGib or ibGibAddr. (E: genuuid)`);r.includes(" ")&&(console.warn(`${n} scope includes one or more spaces. These will be converted to double underscores. (W: 1554a81454e8ae0a6858ea5dd17f8925)`),r=r.replace(/ /g,"__"));let s,i,a;if(e){if(!e.data)throw new Error("(UNEXPECTED) ibGib.data falsy? (E: genuuid)");if(!e.rel8ns)throw new Error("(UNEXPECTED) ibGib.rel8ns falsy? (E: genuuid)");if(!e.rel8ns.ancestor)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor falsy? (E: genuuid)");if(e.rel8ns.ancestor.length===0)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor.length === 0? there should be at least one ancestor (E: genuuid)");if(e&&t&&_({ibGib:e})!==t)throw new Error("(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: genuuid)");let d=e.rel8ns.ancestor.filter(u=>te({gib:L({ibGibAddr:u}).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 b=d.at(-1);s=L({ibGibAddr:b}).ib,a=s}t??=_({ibGib:e});let{ib:c}=L({ibGibAddr:t});if(i=c.split(" ").at(0)??"",i=i.replace(/\W/g,"_"),s??=i,s=s.replace(/\W/g,"_"),!s&&!i)throw new Error("(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: genuuid)");a=i.toLowerCase(),se&&console.log(`${n} ancestorIbOrAtom: ${a} (I: genuuid)`);let l=`${a}_${r}index`;return se&&console.log(`${n} indexName: ${l} (I: genuuid)`),l}catch(s){if(o)return console.warn(`${n} error happened but defaultNameIfError (${o}) provided. So will return this value. error that was thrown: ${E(s)}`),o;throw console.error(`${n} ${E(s)}`),s}}f(Dn,"getIndexNameFromIbGib");async function hl({scope:r,ibGib:e,metaspace:t,space:o,skipGetLatest:n}){let s=`[${hl.name}]`;try{if(se&&console.log(`${s} starting... (I: f19dc86aab380fe809aef27ccc7a7425)`),!r)throw new Error("scope required to be a non-empty string (E: 73e702495c38c7d8747d1cf8850af825)");if(!e)throw new Error("ibGib required (E: genuuid)");let i=Dn({scope:r,ibGib:e}),a=he({ibGib:e,defaultIfNone:"incomingAddr"}),c=f(async()=>{let d=await t.getSpecialIbGib({type:i,space:o,initialize:!1,dontWarnIfNotExist:!0,lock:!0});if(!d||!d.data){se&&console.log(`${s} special ${r} index ibGib not found for indexSpecialIbGibType (${i}). No coupled ibgib registered, returning undefined. (I: genuuid)`);return}let u=(d.data.coupleMap??d.data.agentMap??{})[a];if(!u){se&&console.log(`${s} No coupled ${r} ibgib address found for domain ${a} in the coupled index map. indexSpecialIbGibType: ${i}. returning undefined. (I: genuuid)`);return}let p=n?u:await t.getLatestAddr({addr:u,space:o})??u,h=await t.get({addrs:[p],space:o});if(h.errorMsg||(h.ibGibs??[]).length!==1)throw new Error(`couldn't get latest coupled ibgib (${p}) for domain ${a}. (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);return h.ibGibs[0]},"fn");return await Ge({scope:i,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:s+we(),fn:c})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{se&&console.log(`${s} complete.`)}}f(hl,"getLocalCoupledIbGibForDomainIbGib");async function gl({scope:r,domainIbGib:e,localIbGib:t,metaspace:o,space:n}){let s=`[${gl.name}]`;try{se&&console.log(`${s} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let i=Dn({scope:r,ibGib:e}),a=he({ibGib:e}),c=_({ibGib:t});if(!a)throw new Error(`${s} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`);if(!c)throw new Error(`${s} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`);await Ge({scope:i,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:f(async()=>{let d=await o.getSpecialIbGib({type:i,space:n,initialize:!0,dontWarnIfNotExist:!0,lock:!1});if(!d)throw new Error(`${s} Could not get or create agent index ibGib.`);if(!d.data)throw new Error("(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)");let b=d.data.coupleMap??d.data.agentMap,u=b?C(b):{},p=u[a];if(p)if(p===c){se&&console.log(`${s} domain ibGib (${a}) already mapped to agent (${c}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`);return}else console.warn(`${s} domainTjpAddr (${a}) already assigned to existingMappedAgentAddr (${p}). We will be changing to new localAddr (${c}). (W: eb993e33f7731e570fa76f24a2d80625)`);u[a]=c;let h=await je({src:d,dataToAddOrPatch:{coupleMap:u},dna:!1,linkedRel8ns:[Y.past],nCounter:!0}),g=h.newIbGib;await re({resTransform:h,space:n});let m=oe({type:i});await o.setConfigAddr({key:m,addr:_({ibGib:g}),space:n}),await o.registerNewIbGib({ibGib:g,space:n})},"fn")}),se&&console.log(`${s} Registered domain ${a} with agent ${c}`)}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{se&&console.log(`${s} complete.`)}}f(gl,"coupleDomainIbGibWithLocalIbGibViaIndex");function gt(){let r=`[${gt.name}]`;try{se&&console.log(`${r} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let e=globalThis[Yr];return e||(console.log(`${r} initializing globalThis.${Yr}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),e={},globalThis[Yr]=e),e}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{se&&console.log(`${r} complete.`)}}f(gt,"getIbGibGlobalThis_IbGib");async function Fi({delayIntervalMs:r=50}={delayIntervalMs:50}){let e=`[${Fi.name}]`;try{se&&console.log(`${e} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let t;for(;!t;)gt().metaspace&&(t=gt().metaspace),t||(console.log(`${e} metaspace still not initialized. delayIntervalMs: ${r} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await de(r));return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{se&&console.log(`${e} complete.`)}}f(Fi,"getGlobalMetaspace_waitIfNeeded");function ml({ibGibAddr:r,gib:e,ibGib:t,translucentAlpha:o=10}){let n=`[${ml.name}]`;try{se&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!r&&!e&&!t&&(e=R),e??=t?.gib??L({ibGibAddr:r}).gib;let s=ie({gib:e});o??=10;let i="";if(s.isPrimitive)return{gib:e,gibInfo:s,punctiliarColor:Ni,punctiliarColorTranslucent:Ci,punctiliarColorContrast:Pi};i=s.tjpGib??s.punctiliarHash??e;let[a,c,l]=Bi(o,s.punctiliarHash??e),[d,b,u]=s.tjpGib?Bi(o,s.tjpGib):[void 0,void 0,void 0];return{gib:e,gibInfo:s,punctiliarColor:a,punctiliarColorTranslucent:c,punctiliarColorContrast:l,tjpColor:d,tjpColorTranslucent:b,tjpColorContrast:u}}catch(s){let i=`${n} ${E(s)}`;return console.error(i),{gib:e??R,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:i}}finally{se&&console.log(`${n} complete.`)}}f(ml,"getDeterministicColorInfo");function El(r,e,t){t/=100;let o=e*Math.min(t,1-t)/100,n=f(s=>{let i=(s+r/30)%12,a=t-o*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")},"f");return`#${n(0)}${n(8)}${n(4)}`}f(El,"hslToHex");function Bi(r,e){let o=(parseInt(e.substring(0,8),16)||0)%360,n=El(o,65,62),s=parseInt(n.substring(1,3),16),i=parseInt(n.substring(3,5),16),a=parseInt(n.substring(5,7),16),l=(s*299+i*587+a*114)/1e3>=128?"#11111b":"#ffffff",d=Math.min(100,Math.max(0,r)),b=Math.round(d/100*255).toString(16).padStart(2,"0"),u=`${n}${b}`;return[n,u,l]}f(Bi,"getColorStrings");var wl="recursive-salt-wrap",On={recursive_salt_wrap:wl},qi=Object.values(On);var Jr=!1;async function $l({masterSecret:r,kdfOpts:e}){let t=`[${$l.name}]`;try{Jr&&console.log(`${t} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let o=e.strategy;switch(o){case On.recursive_salt_wrap:return await Lt({masterSecret:r,salt:e.salt,rounds:e.rounds,algorithm:e.algorithm});default:throw new Error(`Unknown KDF strategy: ${o}. valid values: ${qi.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Jr&&console.log(`${t} complete.`)}}f($l,"deriveKey");async function Lt({masterSecret:r,salt:e,rounds:t,algorithm:o=Ee.sha_256}){let n=`[${Lt.name}]`;try{Jr&&console.log(`${n} starting... (I: 850868e50aba82ff28c77da8169e4c26)`);let s=r;for(let i=0;i<t;i++)s=await X({s:`${e}${s}${e}`,algorithm:o});return s}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{Jr&&console.log(`${n} complete.`)}}f(Lt,"kdf_recursiveSaltWrap");var yl="hash-reveal-v1",Me={hash_reveal_v1:yl},Hi=Object.values(Me);var Il="top-up",_l="replace-all",Tl="consume",Al="delete-all",ye={topUp:Il,replaceAll:_l,consume:Tl,deleteAll:Al},Ki=Object.values(ye);var Sl="add-pool",xl="remove-pool",Gl="replace-pool",vl="change-password",Ut={add_pool:Sl,remove_pool:xl,replace_pool:Gl,change_password:vl},fg=Object.values(Ut);var ar="keystone",Nn=/^\w[\w\-.]*$/,Cn=/^[a-zA-Z0-9\-_]{1,64}$/,Pn=/^[a-zA-Z0-9_\-.]{1,63}$/,Rn=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,Vi=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ln=1e3,kt="revoke",ne="manage",Dl="sign",Zr="sync",Xi="connect",Un={REVOKE:kt,MANAGE:ne,SIGN:Dl,SYNC:Zr,CONNECT:Xi},mg=Object.values(Un);var cr=ne;var Ol=Xi,Nl=Zr;var Yi=200,Wi=2,zi=2,Ji=5,Zi=ye.topUp,Qi=Ee.sha_256,ea=1,ta=2e3,ra=5,oa=5,na=16,sa=ye.replaceAll,ia=Ee.sha_512,aa=10,mt=50;var Qr=!1,kn=class{static{f(this,"KeystoneConfigBuilderBase")}_id;_salt;_size;_replenish;_seq;_rand;_verbs=[];_targetBinding;withId(e){return this._id=e,this}withSalt(e){return this._salt=e,this}withSize(e){return this._size=e,this}withTargetBinding(e){return this._targetBinding=e,this}withFIFO(e){return this._seq=e,this._rand=0,this}withRandom(e){return this._seq=0,this._rand=e,this}withHybrid({seqCount:e,randCount:t}){return this._seq=e,this._rand=t,this}withReplenishStrategy(e){return this._replenish=e,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(e){return this._verbs=e,this}},Mn=class r extends kn{static{f(this,"KeystoneConfigBuilder_HashV1")}lc=`[${r}]`;_algo;_rounds;withHash({algo:e,rounds:t}){let o=`${this.lc}[${this.withHash.name}]`;try{return Qr&&console.log(`${o} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=e,this._rounds=t,this}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{Qr&&console.log(`${o} complete.`)}}build(){let e=`${this.lc}[${this.build.name}]`;try{if(Qr&&console.log(`${e} 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:Me.hash_reveal_v1,salt:this._salt,allowedVerbs:this._verbs,behavior:this.buildBehavior(),algo:this._algo,rounds:this._rounds}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Qr&&console.log(`${e} complete.`)}}},lr=class{static{f(this,"KeystoneConfig")}static hash(){return new Mn}};function Ag(r){if(r.type&&r.type!==Me.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${Me.hash_reveal_v1} currently implemented. (E: c38616cd7a459149f670418f88766526)`);let{salt:e,id:t,size:o,sequential:n,random:s,targetBinding:i,replenishStrategy:a,verbs:c,hashAlgorithm:l,hashRounds:d}=r;return lr.hash().withId(t).withSalt(e).withSize(o??Yi).withHybrid({seqCount:n??Wi,randCount:s??zi}).withTargetBinding(i??Ji).withReplenishStrategy(a??Zi).withHash({algo:l??Qi,rounds:d??ea}).forVerbs(c??[]).build()}f(Ag,"createStandardPoolConfig");function Cl(r){if(r.type&&r.type!==Me.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${Me.hash_reveal_v1} currently implemented. (E: 09c1f7772bd2a7910f5562b4934d3826)`);let{salt:e,id:t,size:o,sequential:n,random:s,targetBinding:i,replenishStrategy:a,verbs:c,hashAlgorithm:l,hashRounds:d}=r;return lr.hash().withId(t).withSalt(e).withSize(o??ta).withHybrid({seqCount:n??ra,randCount:s??oa}).withTargetBinding(i??na).withReplenishStrategy(a??sa).withHash({algo:l??ia,rounds:d??aa}).forVerbs(c??[]).build()}f(Cl,"createHighSecurityPoolConfig");function Sg(r){return Cl({...r,id:r.id??cr,verbs:r.verbs??[Un.MANAGE]})}f(Sg,"createManagePoolConfig");function ca({template:r,salt:e}){let t=r.behavior;return lr.hash().withId(r.id).withSalt(e).withSize(t.size).withHybrid({seqCount:t.selectSequentially,randCount:t.selectRandomly}).withTargetBinding(t.targetBindingCount).withReplenishStrategy(t.replenish).withHash({algo:r.algo,rounds:r.rounds}).forVerbs(r.allowedVerbs).build()}f(ca,"createPoolConfigFromJson");var la={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Dev)",securityLevel:"low"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var da={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Staging)",securityLevel:"medium"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:3,behavior:{size:500,replenish:"replace-all",selectSequentially:4,selectRandomly:4,targetBindingCount:6}}}};var fa={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Prod)",securityLevel:"high"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:2e3,replenish:"replace-all",selectSequentially:12,selectRandomly:12,targetBindingCount:16}}}};var eo={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Dev)",securityLevel:"low",defaultTtlSeconds:86400},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var ba={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Staging)",securityLevel:"medium",defaultTtlSeconds:604800},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:3,behavior:{size:250,replenish:"replace-all",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}}}};var ua={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Prod)",securityLevel:"high",defaultTtlSeconds:2592e3},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:1e3,replenish:"replace-all",selectSequentially:8,selectRandomly:8,targetBindingCount:10}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}}}};var pa={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Session/Saga Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"replace-all",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:50,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}}}};var to=new Map,dr=class r{static{f(this,"KeystoneProfileBuilder")}_template;_username;_emails;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static registerCustomProfile({name:e,template:t}){if(!e||typeof e!="string")throw new Error("Profile name is required to register a custom profile. (E: 7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d)");if(!t||typeof t!="object")throw new Error(`Valid KeystonePolicyConfigTemplate is required to register custom profile '${e}'. (E: 8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e)`);to.set(e,JSON.parse(JSON.stringify(t)))}static clearCustomProfiles(){to.clear()}static fromTemplate(e){if(!e||typeof e!="object")throw new Error("Valid KeystonePolicyConfigTemplate is required for KeystoneProfileBuilder.fromTemplate. (E: 9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f)");return new r(e)}static buildKeystone(e){if(!e||typeof e!="string")throw new Error("Profile name is required for KeystoneProfileBuilder. (E: 9a8b7c6d5e4f3210987654321fedcba0)");if(e.endsWith(".dev")||e.startsWith("test")||e.includes("test"))throw new Error(`Security Violation: Development keystone profile '${e}' is prohibited when NODE_ENV=production. (E: 8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d)`);if(to.has(e))return new r(to.get(e));let o;switch(e){case"primary-profile.dev":o=la;break;case"primary-profile.staging":o=da;break;case"primary-profile.prod":o=fa;break;case"sync-profile.dev":o=eo;break;case"sync-profile.staging":o=ba;break;case"sync-profile.prod":o=ua;break;case"sync-profile.test-short-ttl":o={...JSON.parse(JSON.stringify(eo)),metadata:{...eo.metadata,name:"sync-profile.test-short-ttl",description:"Short 10-second TTL sync profile for testing session expiration and renewal.",defaultTtlSeconds:10}};break;case"session":o=pa;break;default:throw new Error(`Unknown keystone profile name: '${e}' (E: fc10a8ad482ef2bda871ac567d268d26)`)}return new r(o)}withUsername(e){return this._username=e,this}withEmail(e){return this._emails?this._emails.includes(e)||this._emails.push(e):this._emails=[e],this}withEmails(e){return this._emails=[...e],this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}_expirationUTC;withExpiration(e){return this._expirationUTC=e,this}getDefaultTtlSeconds(){return this._template.metadata?.defaultTtlSeconds}customizePool(e,t){let{behavior:o,...n}=t;return this._customizations[e]={template:n,behavior:o},this}getFrameDetails(){let e={...this._details};if(this._username&&(e.username=this._username),this._emails&&this._emails.length>0&&(e.emails=[...this._emails]),this._description&&(e.description=this._description),this._expirationUTC)e.expirationUTC=this._expirationUTC;else{let t=this.getDefaultTtlSeconds();t&&t>0&&(e.expirationUTC=new Date(Date.now()+t*1e3).toISOString())}return e}async compileConfigs(){let e=[],t="";if(this._username||this._emails&&this._emails.length>0){let o=this._emails?.[0]??"",n=`${this._username||""}:${o}`;t=await X({s:n})}else t=await X({s:"default-keystone-salt"});for(let[o,n]of Object.entries(this._template.pools)){let s=this._customizations[n.id];s&&(s.template&&Object.assign(n,s.template),s.behavior&&n.behavior&&Object.assign(n.behavior,s.behavior));let i=`${t}-${n.id}`,a=await X({s:i}),c=ca({template:n,salt:a});e.push(c)}return e}};var ro=class{static{f(this,"KeystoneStrategy")}config;constructor(e){this.config=e}};var oo=class r extends ro{static{f(this,"KeystoneStrategy_HashRevealV1")}async derivePoolSecret({masterSecret:e}){let t=`[${r.name}.${this.derivePoolSecret.name}]`;try{let{salt:o,rounds:n,algo:s}=this.config;return await Lt({masterSecret:e,salt:o,rounds:n,algorithm:s})}catch(o){throw console.error(`${t} Error deriving pool secret: ${o.message}`),o}}async generateSolution({poolSecret:e,poolId:t,challengeId:o}){let n=`[${r.name}.${this.generateSolution.name}]`;try{let{rounds:s,algo:i}=this.config,a=o,c=e;for(let l=0;l<s;l++)c=await X({s:`${a}${c}${a}`,algorithm:i});return{type:"hash-reveal-v1",poolId:t,challengeId:o,value:c}}catch(s){throw console.error(`${n} ${s.message}`),s}}async generateChallenge({solution:e}){let t=`[${r.name}.${this.generateChallenge.name}]`;try{let{rounds:o,algo:n}=this.config,{challengeId:s,value:i}=e,a=s,c=i;for(let l=0;l<o;l++)c=await X({s:`${a}${c}${a}`,algorithm:n});return{id:s,type:"hash-reveal-v1",hash:c}}catch(o){throw console.error(`${t} ${o.message}`),o}}async validateSolution({solution:e,challenge:t}){let o=`[${r.name}.${this.validateSolution.name}]`;try{return e.type!=="hash-reveal-v1"||t.type!=="hash-reveal-v1"?(console.warn(`${o} Mismatched types provided.`),!1):(await this.generateChallenge({solution:e})).hash===t.hash}catch(n){return console.error(`${o} ${n.message}`),!1}}};var Et=class r{static{f(this,"KeystoneStrategyFactory")}static create({config:e}){let t=`[${r.name}.create]`;try{switch(e.type){case"hash-reveal-v1":return new oo(e);default:throw new Error(`Unknown strategy type: ${e.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(o){throw console.error(`${t} ${o.message}`),o}}};var q=!1;async function fr({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${fr.name}]`;try{q&&console.log(`${m} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let y=await br({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g});if(Object.values(y).filter(w=>w.ib.startsWith("comment ")).forEach(w=>{console.table(w)}),q){console.log(`${m} graph size: ${Object.keys(y).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let w=Object.values(y).filter(T=>T.ib.startsWith("comment ")||T.ib.startsWith("pic ")).map(T=>T.ib);Ir(w).forEach(T=>console.log(T))}return y}catch(y){throw console.error(`${m} ${y.message}`),y}finally{q&&console.log(`${m} complete.`)}}f(fr,"getDependencyGraph");async function ha({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${ha.name}]`;try{if(q&&console.log(`${m} starting... (I: bd6807477f679345df9dddefe0b4e922)`),u&&(p??[]).length>0)throw new Error("space and spaces parameters are mutually exclusive. Pass either space or spaces, not both. (E: 994a5323e4214f4e95d5bb2b89f89090)");let y=u?[u]:(p??[]).filter(w=>!!w);if(y.length===0)throw new Error("space or spaces required. (E: 9f38166ab70340cb919174f8d26af909)");if(!r&&!t&&(e??[]).length===0&&(o??[]).length===0)throw new Error("either ibGib/s or ibGibAddr/s required. (E: b6d08699651f455697f0d05a41edb039)");return c=c||[],a=a||[],s=s||{},i=i||[],o=(o??[]).filter(w=>!te({gib:L({ibGibAddr:w}).gib})).filter(w=>!a.includes(w)),e=(e??[]).filter(w=>!te({ibGib:w})).filter(w=>!a.includes(_({ibGib:w}))),r&&!te({ibGib:r})&&!e.some(w=>w.gib===r.gib)&&!a.includes(_({ibGib:r}))&&e.push(r),t&&!te({gib:L({ibGibAddr:t}).gib})&&!o.includes(t)&&!a.includes(t)&&o.push(t),{ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:void 0,spaces:y,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}}catch(y){throw console.error(`${m} ${y.message}`),y}finally{q&&console.log(`${m} complete.`)}}f(ha,"getGraphProjection_initializeOpts");async function jn({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,maxRetries:n,msBetweenRetries:s,timeLogName:i,space:a,spaces:c}){let l=`[${jn.name}]`;try{q&&console.log(`${l} starting... (I: 67b2be37ff24393fff56e229304da122)`);let d=c??(a?[a]:[]);if(d.length===0)throw new Error("(UNEXPECTED) spaces empty? (E: aa9f657695717034b3581066932d7d23)");let b=[];r??=[],e??=[],o??=[],t??={};let u=[],p=Object.keys(t??{}),h=r.map(g=>_({ibGib:g}));for(let g=0;g<e.length;g++){let m=e[g];o.includes(m)||h.includes(m)||(p.includes(m)?b.push(t[m]):u.push(e[g]))}if(q&&console.log(`${l}[analyze debugging] addrsToGetFromSpace (${u.length}):
16
+ ${u.join(`
17
+ `)} (I: b45a2614184b48b694becfd377c789f5)`),u.length>0){let g=u.concat(),m=0;for(n=n??0;m<=n&&g.length>0;){i&&m===0&&console.timeLog(i,`${l} FIRST try starting...`),i&&m>0&&console.timeLog(i,`${l} RETRY starting...`),m>0&&s&&(i&&console.timeLog(i,`${l} delaying ${s}ms for retry`),q&&console.log(`${l} retrying. addrsToGet (${g.length}): ${g} (I: 8460694cdd5518472680784c3b96a822)`),await de(s));for(let y of d){if(g.length===0)break;i&&console.timeLog(i,`${l} getFromSpace (${g.length}) starting...`);let w=await ce({addrs:g,space:y});if(i&&console.timeLog(i,`${l} getFromSpace complete.`),w.success&&(w.ibGibs?.length??0)>0){w.ibGibs.forEach(A=>b.push(A));let T=w.ibGibs.map(A=>_({ibGib:A}));g=g.filter(A=>!T.includes(A))}else{let T=w.rawResultIbGib?.ibGibs??[];if(T.length>0){T.forEach(x=>b.push(x));let A=T.map(x=>_({ibGib:x}));g=g.filter(x=>!A.includes(x))}}}m++}if(g.length>0){let y=d.map(w=>w?.ib).join(", ");throw new Error(`unable to retrieve dependency ibgibs from space/s (ib/s: ${y}). addrsToGet: ${g.join(`
18
+ `)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}}return b}catch(d){throw console.error(`${l} ${d.message}`),d}finally{q&&console.log(`${l} complete.`)}}f(jn,"getGraphProjection_getIbGibsInIbGibAddrs");async function br(r){let e=`[${br.name}]`;try{if(q&&console.log(`${e} starting... (I: 70508d7a5c63eae1f22ae851b32b3d22)`),!r.ibGib&&!r.ibGibAddr&&(r.ibGibs??[]).length===0&&(r.ibGibAddrs??[]).length===0)return{};let{ibGibs:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}=await ha(r);if(h&&console.timeLog(h,`${e} starting...`),o?.length??!1){let y=await jn({ibGibs:t,ibGibAddrs:o,gotten:s,skipAddrs:a,maxRetries:d,msBetweenRetries:b,timeLogName:h,space:u,spaces:p});t=t?[...t,...y]:[...y]}o=t.map(y=>_({ibGib:y}));let m=Ir(t.map(y=>y.ib).filter(y=>y.startsWith("comment ")));return q&&console.log(`${e}[analyze debugging] ibGibs commentIbs: ${m.join(`
19
+ `)} (I: c89dc951315f746954f9bddbe8941122)`),n?ga({ibGibs:t,ibGibAddrs:o,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}):ma({ibGibs:t,ibGibAddrs:o,gotten:s,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{q&&console.log(`${e} complete.`)}}f(br,"getGraphProjection");async function Bl({ibGibAddr:r,latestCommonFrameAddr:e,live:t,space:o,spaces:n}){let s=`[${Bl.name}]`;try{if(q&&console.log(`${s} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`),r===e)return console.warn(`${s} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`),{};let i=await fr({ibGibAddr:e,live:!1,space:o,spaces:n});return await fr({ibGibAddr:r,live:t,skipAddrs:Object.keys(i),space:o,spaces:n})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{q&&console.log(`${s} complete.`)}}f(Bl,"getDeltaDependencyGraph");async function ga({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:b,timeLogName:u}){let p=`[${ga.name}]`;try{let h=b??(d?[d]:[]);n=n??{},o=o??[];let g={...t};(r??[]).forEach(x=>g[_({ibGib:x})]=x);let m=nr({ibGibs:Object.values(g)});q&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(m).length}): ${Object.keys(m)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let y={};Object.keys(m).forEach(x=>{o.includes(x)||(y[x]=m[x])}),q&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${H(y)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let w={},T={};Object.keys(m).filter(x=>!o.includes(x)).forEach(x=>{let $=m[x],I=$[$.length-1];w[x]=I;let G=_({ibGib:I});T[G]=x});let A=Object.keys(w).length;if(A>0){let x={};Object.keys(n).filter(P=>!o.includes(P)).forEach(P=>{let D=w[P];if(D){let U=_({ibGib:D});x[U]=n[P]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy (E: 8a5d3f2e1c4b90876543210fe89abcdf)`)}),q&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${H(x)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let $=Object.values(w),I={};if($.length>0){if(h.length===0)throw new Error("(UNEXPECTED) space/s falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");for(let P of h){let D=await Ue({ibGibs:$,space:P});if(!D?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");let U=D.data.latestAddrsMap;Object.keys(U).forEach(V=>{let Z=U[V];Z?I[V]=Z:I[V]||(I[V]=null)})}if($.forEach(P=>{let D=_({ibGib:P});I[D]||(I[D]=D)}),Object.keys(I).length!==A)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");q&&console.log(`${p} queriedLatestAddrsMap: ${H(I)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),x={...I,...x}}q&&console.log(`${p} combined latestAddrsMap: ${H(x)} (I: e3aedea63f29c5b06a79632f691aa522)`);let G=[],N={};Object.values(w).forEach(P=>{let D=_({ibGib:P}),U=T[D],V=x[D];if(!V)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");V===D?(q&&console.log(`${p} analyzed ${U} (I: afb7960900f04b8a87538f4c7bd903b7)`),o.push(U)):(G.push(V),N[V]=U)});let v=[];for(let P=0;P<(r??[]).length;P++){let U=r[P].rel8ns??{};Object.keys(U).filter(Z=>!(i??[]).includes(Z)).filter(Z=>a?a.includes(Z):!0).forEach(Z=>{(U[Z]??[]).forEach(ft=>{!v.includes(ft)&&!r.some(pe=>_({ibGib:pe})===ft)&&!te({gib:L({ibGibAddr:ft}).gib})&&v.push(ft)})})}return e=Ir([...e??[],...v,...G]),await br({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:h,timeLogName:u,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return r||(r=[]),Object.values(t??{}).forEach(x=>{let $=_({ibGib:x});r.some(I=>_({ibGib:x})===$)||r.push(x)}),await br({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:h,timeLogName:u,live:!1})}catch(h){let g=`${p} ${h.message}`;throw console.error(g),u&&console.timeLog(u,`${p} error: ${g}`),h}finally{u&&console.timeLog(u,`${p} complete.`)}}f(ga,"getGraphProjection_Live");async function ma({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:s,maxRetries:i,msBetweenRetries:a,space:c,spaces:l,timeLogName:d}){let b=`[${ma.name}]`;try{let u=[];r??=[],t??={},o??=[],n??=[],d&&console.timeLog(d,`${b} analyzing next step starting...`);for(let p=0;p<r.length;p++){let h=r[p],g=_({ibGib:h}),{gib:m}=L({ibGib:h});if(m===R)throw new Error("cannot get dependency graph of primitive. (E: 5493b8908d134bdf887e91122a6a57e3)");Object.keys(t).includes(g)||(t[g]=h);let y={},w=h.rel8ns||{},T=(Object.keys(w)||[]).filter(x=>!n.includes(x));s&&(T=T.filter(x=>s.includes(x)));let A=Object.keys(t);for(let x=0;x<T.length;x++){let $=T[x],I=w[$]??[],G=I.filter(v=>v===""||v===void 0||v===null||!v.includes(ee));G.length>0&&console.warn(`${b} (UNEXPECTED) has falsyAddrs: ${G} (W: da9505cb0a4db68a4aff7f279ad2d322)`),I.filter(v=>!!v).filter(v=>!A.includes(v)).filter(v=>!o.includes(v)).filter(v=>L({ibGibAddr:v}).gib!==R).filter(v=>!u.includes(v)).forEach(v=>{let P=Xt({addr:v});(P||[]).length===0?u.push(v):y[v]=P})}if(Object.keys(y).length>0)throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(y).substring(0,1024)} (E: d2416b9b23fa4d178e6c7104b40ee78c)`)}if(d&&console.timeLog(d,`${b} analyzing next step complete.`),u.length>0){d&&console.timeLog(d,`${b} get addrsWeDontHaveAlready_Rel8dAddrs starting...`);let p=await jn({ibGibAddrs:u,gotten:t,skipAddrs:o,maxRetries:i,msBetweenRetries:a,timeLogName:d,space:c,spaces:l});p.forEach(g=>t[_({ibGib:g})]=g),d&&console.timeLog(d,`${b} call getGraphProjection recursively starting...`);let h=await br({ibGibs:p,live:!1,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:s,maxRetries:i,msBetweenRetries:a,space:c,spaces:l});return d&&console.timeLog(d,`${b} call getGraphProjection recursively complete.`),h}else return t}catch(u){let p=`${b} ${u.message}`;throw console.error(`${p} (E: 8a42e56616014e7a8848aa6bb6f2722b)`),d&&console.timeLog(d,`${b} error: ${p}`),new Error(`${p} (E: a21b0682121746a480572b83413cf2d0)`)}finally{d&&console.timeLog(d,`${b} complete.`)}}f(ma,"getGraphProjection_NonLive");function no({ibGibs:r}){let e=`[${no.name}]`;try{if(q&&console.log(`${e} starting... (I: 6019a812cff8597f79c12088e45cc226)`),r){let t={};return r.forEach(o=>{t[_({ibGib:o})]=o}),t}else return}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{q&&console.log(`${e} complete.`)}}f(no,"toFlatGraph");function Fl({graphA:r,graphB:e,slowButThorough:t}){let o=`[${Fl.name}]`;try{if(q&&console.log(`${o} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(r).length===Object.keys(e).length))return q&&console.log(`${o} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let s of Object.keys(r))if(!e[s])return q&&console.log(`${o} addr (${s}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`),!1;if(t)for(let s of Object.keys(r)){let i=ke({ibGib:r[s]}),a=JSON.stringify(i),c=ke({ibGib:e[s]}),l=JSON.stringify(c);if(a!==l)return q&&console.log(`${o} jsonA !== jsonB for addr (${s}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{q&&console.log(`${o} complete.`)}}f(Fl,"graphsAreEquivalent");var J=!1;async function Ea({keystoneData:r}){let e=`[${Ea.name}]`;try{return J&&console.log(`${e} starting... (I: c3022a146faac9730154f34d1439a225)`),[ar].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(Ea,"getKeystoneIb");async function wa({ib:r}){let e=`[${wa.name}]`;try{J&&console.log(`${e} starting... (I: 73cb6832984255ed48b2f44db6a21e25)`);let[t]=r.split(" ");if(t!==ar)throw new Error(`invalid keystone ib. atom found in ib (${t}) does not match keystone atom (${ar}) (E: 79b3d587824c4271b6e60acc76e0c825)`);return{atom:t}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(wa,"parseKeystoneIb");async function ur({ib:r}){try{return await wa({ib:r}),!0}catch{return!1}}f(ur,"validateKeystoneIb");function xm(r){if(!r||typeof r!="string")return!1;let e=r.trim();return e.length<3||e.length>254?!1:Vi.test(e)}f(xm,"validateEmail");async function $a({pool:r,requiredChallengeIds:e,targetAddr:t}){let o=r.config.behavior,n=new Set,s=Object.keys(r.challenges);if(e&&e.length>0){for(let i of e){if(!r.challenges[i])throw new Error(`(UNEXPECTED) Required challenge ID not found in pool: ${i} (E: 10c5619d80d8cf6cc84ffbf8be0dbc25)`);s.includes(i)&&n.add(i)}s=s.filter(i=>!n.has(i))}if(o.targetBindingCount>0&&t){let i=[...s].sort(),a=await X({s:t});for(let c=0;c<o.targetBindingCount;c++){if(i.length===0)throw new Error("Entropy Exhaustion. Cannot satisfy target binding. Sorted available pool is empty. (E: 341b95dc3a58be3e083d1d9c4a0c4925)");let l=BigInt("0x"+a),d=Number(l%BigInt(i.length)),b=i[d];n.add(b),i.splice(d,1),s=s.filter(u=>u!==b),a=await X({s:a})}}if(o.selectSequentially>0){if(s.length<o.selectSequentially)throw console.error(`[getDeterministicRequirements] Entropy Exhaustion! AvailableCount: ${s.length}, Required Seq: ${o.selectSequentially}. Available IDs: ${s.join(",")}`),new Error("Entropy Exhaustion. Insufficient challenges for FIFO requirement. (E: 9efa88003e1d5eccb837c85154ee5625)");s.slice(0,o.selectSequentially).forEach(a=>n.add(a)),s=s.slice(o.selectSequentially)}return{mandatoryIds:n,availableIds:s}}f($a,"getDeterministicRequirements");function pr({pools:r,poolId:e,poolFilter:t,verb:o}){let n="[resolveTargetPool]";try{let s;if(e){if(s=r.find(i=>i.id===e),!s)throw new Error(`Pool not found with ID: ${e} (E: 4a2b17428515c1e82813158581898125)`)}else if(t){let i=r.filter(t);if(i.length===0)throw new Error("No pool matched the provided filter. (E: 5b3c27428515c1e82813158581898125)");s=i[0]}else{if(!o)throw new Error("Cannot auto-resolve pool without a verb. (E: 6c4d37428515c1e82813158581898125)");if(s=r.find(i=>i.config.allowedVerbs&&i.config.allowedVerbs.includes(o)),s||(s=r.find(i=>!i.config.allowedVerbs||i.config.allowedVerbs.length===0)),!s)throw new Error(`No suitable pool found for verb: ${o} (E: 7d5e47428515c1e82813158581898125)`)}if(o&&s.config.allowedVerbs&&s.config.allowedVerbs.length>0&&!s.config.allowedVerbs.includes(o))throw new Error(`Pool ${s.id} is not authorized for verb: ${o} (E: 8e6f57428515c1e82813158581898125)`);return s}catch(s){throw console.error(`${n} ${E(s)}`),s}}f(pr,"resolveTargetPool");async function wt({pool:r,targetAddr:e,requiredChallengeIds:t}){let o="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:s}=await $a({pool:r,requiredChallengeIds:t,targetAddr:e}),i=r.config.behavior.selectRandomly,a=[];if(i>0){if(s.length<i)throw new Error(`Insufficient challenges for random requirement. Need ${i}, have ${s.length} (E: 9f7a67428515c1e82813158581898125)`);let c=[...s].sort(()=>.5-Math.random());a.push(...c.slice(0,i))}return[...n,...a]}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(wt,"selectChallengeIds");async function ya({salt:r,timestamp:e,index:t}){return(await X({s:`${r}${e}${t}`})).substring(0,16)}f(ya,"generateOpaqueChallengeId");async function ql({prevPools:r,targetPoolId:e,consumedIds:t,masterSecret:o,strategy:n,config:s,verb:i}){let a="[applyReplenishmentStrategy]";try{let c=JSON.parse(JSON.stringify(r)),l=c.findIndex(h=>h.id===e);if(l===-1)throw new Error(`Target pool ${e} not found in keystone data. (E: 75200388d22744838634524233772545)`);let d=c[l],b=await n.derivePoolSecret({masterSecret:o}),u=Date.now().toString(),p=s.behavior.replenish;if(i===kt&&(p=ye.deleteAll),p===ye.topUp){t.forEach(h=>delete d.challenges[h]);for(let h=0;h<t.length;h++){let g=await ya({salt:s.salt,timestamp:u,index:h}),m=await n.generateSolution({poolSecret:b,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===ye.replaceAll)d.challenges=await ao({config:s,masterSecret:o});else if(p===ye.consume)t.forEach(h=>delete d.challenges[h]);else if(p===ye.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${p}. Valid list: ${H(Ki)} (E: 0acf56f1e1486240080e11e8046d0825)`);return c}catch(c){throw console.error(`${a} ${E(c)}`),c}}f(ql,"applyReplenishmentStrategy");async function $t({targetPoolId:r,prevPools:e,masterSecret:t,challengeIds:o,claim:n,requiredChallengeIds:s}){let i="[solveAndReplenish]";try{J&&console.log(`${i} starting... poolId: ${r}, ids: ${o.length}`);let a=e.find(h=>h.id===r);if(!a)throw new Error(`Target pool not found: ${r} (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);let c=Et.create({config:a.config}),l=await c.derivePoolSecret({masterSecret:t});if(!await co({pool:a,signingSecret:t}))throw new Error(`Crypto Violation: Invalid signing secret for pool: ${a.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5f)`);let b=[];for(let h of o){let g=await c.generateSolution({poolSecret:l,poolId:a.id,challengeId:h});b.push(g)}let u={claim:n,solutions:b,requiredChallengeIds:s&&s.length>0?s:void 0},p=await ql({prevPools:e,targetPoolId:a.id,consumedIds:o,masterSecret:t,strategy:c,config:a.config,verb:n.verb});return{proof:u,nextPools:p}}catch(a){throw console.error(`${i} ${E(a)}`),a}}f($t,"solveAndReplenish");async function Ia({pool:r}){let e=`[${Ia.name}]`;try{if(J&&console.log(`${e} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!r.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(r.config.type!==Me.hash_reveal_v1)throw new Error("(UNEXPECTED) pool.config.type !== KeystoneChallengeType.hash_reveal_v1? (E: e205f8872909c37168a624a9df778c26)");let t=[],{algo:o,rounds:n,salt:s}=r.config,i=[Ee.sha_256,Ee.sha_512];return o?i.includes(o)||t.push(`${e} invalid hash algorithm (${o}). Must be one of ${i}. (E: a22399ca3a68e63ffcc7507699be5826)`):t.push(`${e} algorithm required. (E: 8cd6bfb0590862b9bae24d98d2cf3826)`),n&&typeof n=="number"&&Number.isInteger(n)?n>Ln&&t.push(`${e} rounds too high. max rounds: ${Ln} (E: 31ce082f7fd88d6b58ef08a816458826)`):t.push(`${e} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),s&&typeof s=="string"?Cn.test(s)||t.push(`${e} invalid salt (${s.substring(0,99)}). Must match regexp ${Cn}`):t.push(`${e} invalid salt (${s}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(Ia,"validateChallengePool_typeHashRevealV1");async function _a({pool:r}){let e=`[${_a.name}]`;try{J&&console.log(`${e} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let t=[];if(r.config){if(r.config.id?Nn.test(r.config.id)||t.push(`${e} pool.config.id is not formatted correctly. must pass regexp: ${Nn.source}`):t.push(`${e} pool.config.id falsy (E: 31d7943d95f877326d5f4ea14463d626)`),r.config.behavior){let{size:n,selectSequentially:s,selectRandomly:i,targetBindingCount:a}=r.config.behavior;(!n||n===0)&&t.push(`${e} invalid pool.config.behavior.size (${n}). Must be positive integer. (E: b221e36ec102bdc944552248ce8fe626)`);let c=(s||0)+(i||0)+(a||0);c>=n&&t.push(`${e} Total requested challenges (${c}) cannot equal or exceed pool size (${n}) to prevent full pool exposure and selection exhaustion. (E: 81cb834f826315264bca81c15fca58f1)`)}else t.push(`${e} pool.config.behavior falsy (E: bede081c066c39732eefe2f92e296326)`);let o=r.config.type;switch(o){case Me.hash_reveal_v1:(await Ia({pool:r})).forEach(s=>t.push(s));break;default:throw new Error(`(UNEXPECTED) unknown pool.config.type (${o})? We only implement the following at this time: ${Hi} (E: cce5285cf7580b8bc82172488eba2826)`)}}else t.push(`${e} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(_a,"validateChallengePool");function Ta({data:r}){let e="[validateKeystoneMetadata]",t=[],o=f((n,s)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!Pn.test(n.username))&&t.push(`${e} invalid username in ${s} (${n.username}). Must match ${Pn}`),n.description!==void 0&&(typeof n.description!="string"||!Rn.test(n.description))&&t.push(`${e} invalid description in ${s} (${n.description}). Must match ${Rn}`),n.expirationUTC!==void 0&&(typeof n.expirationUTC!="string"||isNaN(Date.parse(n.expirationUTC)))&&t.push(`${e} invalid expirationUTC in ${s} (${n.expirationUTC}). Must be a valid ISO-8601 string`))},"checkDetails");return o(r.frameDetails,"frameDetails"),o(r.checkpointDetails,"checkpointDetails"),t}f(Ta,"validateKeystoneMetadata");async function so({keystoneIbGib:r}){let e=`[${so.name}]`;try{J&&console.log(`${e} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let t=[],{data:o,rel8ns:n}=r;await ur({ib:r.ib})||t.push(`${e} invalid keystone ib (${r.ib}). (E: ad7a88bc38c290a184dfbd42be48f526)`),Ta({data:o}).forEach(a=>t.push(a)),o.proofs&&o.proofs.length>0&&t.push(`${e} proofs already exist on genesis keystone. (E: 7a5e15f20918f1bbd8ffb62857dcd526)`);for(let a of o.challengePools)(await _a({pool:a})).forEach(l=>t.push(l)),(!a.challenges||Object.keys(a.challenges).length===0)&&t.push(`${e} invalid pool (${a.id}). pool.challenges is falsy/empty. (E: 8cd16a5416ae62a058342828be465b26)`);return o.revocationInfo&&t.push(`${e} genesis keystone already has revocationInfo. (E: e11408d0c558d0fa948efbce611ec826)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(so,"validateGenesisKeystone");function Hl({currDelegates:r,prevDelegates:e}){let t=r||{},o=e||{},n=Object.keys(t),s=Object.keys(o);if(n.length!==s.length)return!0;for(let i of n){let a=t[i],c=o[i];if(!c||a.delegateTjpAddr!==c.delegateTjpAddr||a.delegateAddr!==c.delegateAddr||a.thisAddr!==c.thisAddr)return!0}return!1}f(Hl,"isDelegatesChanged");async function Kl({currDelegates:r,prevIbGib:e,lc:t,errors:o}){let n=Object.keys(r),s=_({ibGib:e});for(let i of n){let a=r[i];i!==a.delegateTjpAddr&&o.push(`${t} Invalid delegate mapping: Key '${i}' does not match delegateTjpAddr '${a.delegateTjpAddr}'. (E: 9c8da8bc38c290a184dfbd42be48f526)`);let[c,l,d]=await Promise.all([ur({ib:a.delegateTjpAddr.split("^")[0]}),ur({ib:a.delegateAddr.split("^")[0]}),ur({ib:a.thisAddr.split("^")[0]})]);c||o.push(`${t} Delegate delegateTjpAddr '${a.delegateTjpAddr}' is not a valid keystone address. (E: 10d8a8bc38c290a184dfbd42be48f526)`),l||o.push(`${t} Delegate delegateAddr '${a.delegateAddr}' is not a valid keystone address. (E: 20d8a8bc38c290a184dfbd42be48f526)`),d||o.push(`${t} Delegate thisAddr '${a.thisAddr}' is not a valid keystone address. (E: 30d8a8bc38c290a184dfbd42be48f526)`),a.thisAddr===s||(e.rel8ns?.past||[]).includes(a.thisAddr)||o.push(`${t} Delegate thisAddr '${a.thisAddr}' is not a valid historical address in the parent keystone timeline. (E: 40d8a8bc38c290a184dfbd42be48f526)`);let u=a.allowedVerbs||[];(a.role==="sync-delegate"||u.includes("sync")||u.includes(Zr))&&!a.spaceId&&o.push(`${t} Sync delegate '${a.delegateTjpAddr}' missing required spaceId. (E: 50d8a8bc38c290a184dfbd42be48f526)`),a.expirationUTC&&isNaN(Date.parse(a.expirationUTC))&&o.push(`${t} Delegate expirationUTC '${a.expirationUTC}' is not a valid ISO-8601 timestamp. (E: 60d8a8bc38c290a184dfbd42be48f526)`)}}f(Kl,"validateDelegates");async function hr({currentIbGib:r,prevIbGib:e}){let t=`[${hr.name}]`,o=[];try{if(!r)throw new Error("(UNEXPECTED) currentIbGib falsy? (E: 3c0f02655fa8279e386a079ebb604b25)");if(!e)throw new Error("(UNEXPECTED) prevIbGib falsy? (E: 0d07c812634d839c784f31b8848ba825)");let n=await ae({ibGib:r});n&&n.length>0&&o.push(...n);let s=r.data,i=e.data;await ur({ib:r.ib})||o.push(`${t} invalid keystone ib (${r.ib}). (E: a98dc8bc38c290a184dfbd42be48f526)`),Ta({data:s}).forEach(g=>o.push(g));let l=s.delegates||{},d=i.delegates||{};Hl({currDelegates:l,prevDelegates:d})&&(s.proofs?.some(m=>m.claim?.verb===ne)||o.push(`${t} Policy Violation: Delegates map was mutated but no proof for manage verb ('${ne}') is present. (E: 819fa8cb28c9b60e68994511a5825)`)),await Kl({currDelegates:l,prevIbGib:e,lc:t,errors:o});let u=s.n??-2,p=i.n??-2;u<0&&o.push("invalid keystone.currData.n is undefined or null. (E: 9fbe38704b68829d18ea1d0940d0aa26)"),p<0&&o.push("invalid keystone.prevData.n is undefined or null. (E: 6dc5aa9c87017db6080ed4268b07af26)"),u!==p+1&&o.push(`keystone data.n values are not sequential. prevData.n: ${p}, currData.n: ${u}. (E: 5ae12809f2c67216d38d8ba8d6c42826)`);for(let g of s.proofs){if(g.solutions.length===0){o.push(`Proof ${g.id||"unknown"} has no solutions. (E: e2b4683ce0ce30f798ec77841e88c826)`);continue}let m=g.solutions[0].poolId,y=i.challengePools.find(w=>w.id===m);if(!y){o.push(`Proof references unknown pool: ${m}`);continue}await Aa({proof:g,pool:y,errors:o})}if(s.revocationInfo){let g=s.revocationInfo.proof.claim.target,m=_({ibGib:e});g!==m&&o.push(`Revocation target mismatch. Expected ${m}, got ${g}`)}let h=new Set(s.proofs.map(g=>g.solutions?.[0]?.poolId).filter(Boolean));for(let g of s.proofs){let m=g.claim;if(m?.details){let y=m.details,w=y.type,T=y.info;if(w==="add-pool"){let A=T;if(!A||!Array.isArray(A.add)||A.add.length===0){o.push(`details type is '${w}' but payload is invalid. (E: 1fa2a8cb28c9b60e68994511a5825)`);continue}let x=new Set(i.challengePools.map(I=>I.id)),$=new Set(s.challengePools.map(I=>I.id));for(let I of A.add)$.has(I)||o.push(`ClaimDetails_AddPool lists pool ${I} but it is missing in the evolved keystone. (E: 2fa2a8cb28c9b60e68994511a5825)`),x.has(I)&&o.push(`ClaimDetails_AddPool attempts to add existing pool ${I}. (E: 3fa2a8cb28c9b60e68994511a5825)`);s.challengePools.length!==i.challengePools.length+A.add.length&&o.push(`Structural mismatch: expected ${i.challengePools.length+A.add.length} pools, found ${s.challengePools.length}. (E: 4fa2a8cb28c9b60e68994511a5825)`);for(let I of i.challengePools){let G=s.challengePools.find(N=>N.id===I.id);if(!G){o.push(`Existing pool ${I.id} was removed during add-pool transition. (E: 5fa2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(I.config)!==JSON.stringify(G.config)&&o.push(`Existing pool config ${I.id} was mutated during add-pool transition. (E: 6fa2a8cb28c9b60e68994511a5825)`),!h.has(I.id)&&JSON.stringify(I.challenges)!==JSON.stringify(G.challenges)&&o.push(`Existing pool challenges ${I.id} were mutated during add-pool transition. (E: 7fa2a8cb28c9b60e68994511a5825)`)}}else if(w==="replace-pool"){let A=T;if(!A||typeof A.replace!="string"||!A.replace){o.push(`details type is '${w}' but payload is invalid. (E: 8fa2a8cb28c9b60e68994511a5825)`);continue}let x=A.replace,$=i.challengePools.map(v=>v.id).sort(),I=s.challengePools.map(v=>v.id).sort();JSON.stringify($)!==JSON.stringify(I)&&o.push("replace-pool transition mutated the pool IDs set. (E: 9fa2a8cb28c9b60e68994511a5825)");let G=i.challengePools.find(v=>v.id===x),N=s.challengePools.find(v=>v.id===x);(!G||!N)&&o.push(`Replaced pool ${x} not found in keystone challenge pools. (E: afa2a8cb28c9b60e68994511a5825)`);for(let v of i.challengePools){if(v.id===x)continue;let P=s.challengePools.find(D=>D.id===v.id);P&&(JSON.stringify(v.config)!==JSON.stringify(P.config)&&o.push(`Unrelated pool config ${v.id} was mutated during replace-pool. (E: bfa2a8cb28c9b60e68994511a5825)`),!h.has(v.id)&&JSON.stringify(v.challenges)!==JSON.stringify(P.challenges)&&o.push(`Unrelated pool challenges ${v.id} were mutated during replace-pool. (E: cfa2a8cb28c9b60e68994511a5825)`))}}else if(w==="remove-pool"){let A=T;if(!A||!Array.isArray(A.remove)||A.remove.length===0){o.push(`details type is '${w}' but payload is invalid. (E: b7a2a8cb28c9b60e68994511a5825)`);continue}let x=new Set(A.remove),$=new Set(i.challengePools.map(G=>G.id)),I=new Set(s.challengePools.map(G=>G.id));for(let G of A.remove)$.has(G)||o.push(`ClaimDetails_RemovePool lists pool ${G} but it is missing in the previous keystone. (E: c7a2a8cb28c9b60e68994511a5825)`),I.has(G)&&o.push(`ClaimDetails_RemovePool lists pool ${G} but it is still present in the evolved keystone. (E: d7a2a8cb28c9b60e68994511a5825)`);s.challengePools.length!==i.challengePools.length-A.remove.length&&o.push(`Structural mismatch: expected ${i.challengePools.length-A.remove.length} pools, found ${s.challengePools.length}. (E: e7a2a8cb28c9b60e68994511a5825)`);for(let G of i.challengePools){if(x.has(G.id))continue;let N=s.challengePools.find(v=>v.id===G.id);if(!N){o.push(`Pool ${G.id} was unexpectedly removed. (E: f7a2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(G.config)!==JSON.stringify(N.config)&&o.push(`Remaining pool config ${G.id} was mutated during remove-pool. (E: 07a2a8cb28c9b60e68994511a5825)`),!h.has(G.id)&&JSON.stringify(G.challenges)!==JSON.stringify(N.challenges)&&o.push(`Remaining pool challenges ${G.id} were mutated during remove-pool. (E: 17a2a8cb28c9b60e68994511a5825)`)}}else if(w==="change-password"){let A=T;if(!A||!Array.isArray(A.change)||A.change.length===0){o.push(`details type is '${w}' but payload is invalid. (E: dfa2a8cb28c9b60e68994511a5825)`);continue}let x=i.challengePools.map(G=>G.id).sort(),$=s.challengePools.map(G=>G.id).sort();JSON.stringify(x)!==JSON.stringify($)&&o.push("change-password transition mutated the pool IDs set. (E: efa2a8cb28c9b60e68994511a5825)");let I=new Set(A.change);for(let G of i.challengePools){let N=s.challengePools.find(v=>v.id===G.id);if(N)if(I.has(G.id)){G.isForeign&&o.push(`Security Violation: Password rotation attempted on foreign pool ${G.id}. (E: ffa2a8cb28c9b60e68994511a5825)`);let v={...G.config,salt:""},P={...N.config,salt:""};JSON.stringify(v)!==JSON.stringify(P)&&o.push(`Pool config metadata for rotated pool ${G.id} was mutated. (E: 00b2a8cb28c9b60e68994511a5825)`),G.config.salt===N.config.salt&&o.push(`Pool salt for rotated pool ${G.id} was not rotated. (E: 01b2a8cb28c9b60e68994511a5825)`)}else JSON.stringify(G.config)!==JSON.stringify(N.config)&&o.push(`Unrelated pool config ${G.id} was mutated during change-password. (E: 02b2a8cb28c9b60e68994511a5825)`),!h.has(G.id)&&JSON.stringify(G.challenges)!==JSON.stringify(N.challenges)&&o.push(`Unrelated pool challenges ${G.id} were mutated during change-password. (E: 03b2a8cb28c9b60e68994511a5825)`)}}else o.push(`Unknown claim details type: ${w}`)}}return o}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{J&&console.log(`${t} complete.`)}}f(hr,"validateKeystoneTransition");async function Aa({proof:r,pool:e,errors:t}){let o=`[${Aa.name}]`;try{J&&console.log(`${o} starting... (I: b8f9b6085888eea2258bf579ecd5e825)`),e.config.allowedVerbs&&e.config.allowedVerbs.length>0&&(!r.claim.verb||!e.config.allowedVerbs.includes(r.claim.verb))&&t.push(`Policy Violation: Pool ${e.id} used for unauthorized verb ${r.claim.verb}`);let{mandatoryIds:n,availableIds:s}=await $a({pool:e,requiredChallengeIds:r.requiredChallengeIds,targetAddr:r.claim.target}),i=new Set(r.solutions.map(d=>d.challengeId));for(let d of n)i.has(d)||t.push(`Policy Violation: Missing mandatory challenge ${d}`);let a=[...i].filter(d=>!n.has(d)),c=e.config.behavior.selectRandomly;a.length<c&&t.push(`Policy Violation: Insufficient random count. Need ${c}, got ${a.length}`);for(let d of a)s.includes(d)||t.push(`Policy Violation: ID ${d} is invalid or double-dipped.`);let l=Et.create({config:e.config});for(let d of r.solutions){let b=e.challenges[d.challengeId];b?await l.validateSolution({solution:d,challenge:b})||t.push(`Crypto Violation: Solution for ${d.challengeId} is invalid.`):t.push(`Crypto Violation: Challenge ${d.challengeId} not found in pool.`)}}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{J&&console.log(`${o} complete.`)}}f(Aa,"verifyProofAgainstPool");async function nt({prevIbGib:r,newData:e,metaspace:t,space:o}){let n=`[${nt.name}]`;try{if(J&&console.log(`${n} starting... (I: 8b10e8920f08b7842803665834cf8925)`),!r.data)throw new Error("(UNEXPECTED) prevIbGib.data falsy? (E: 5e84875bf992c585b979e6c8ed5bf225)");if(r.data.revocationInfo)throw new Error(`Keystone has already been revoked (prevIbGib.data.revocationInfo truthy), so we cannot evolve the keystone. Keystone addr: ${_({ibGib:r})} (E: 45d7f846556829de6b2a701838c3f825)`);let s=r.data,i={};s.proofs&&(i.proofs=[]),s.challengePools&&(i.challengePools=[]),s.frameDetails&&(i.frameDetails={}),s.checkpointDetails&&(i.checkpointDetails={}),s.delegates&&(i.delegates="remove"),Object.keys(i).length===0&&(i=void 0);let a=await je({src:r,dataToRemove:i,dataToAddOrPatch:e,nCounter:!0});if(a.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(a.dnas)throw new Error("(UNEXPECTED) resMut8.dnas truthy? We do not want dnas with keystones. (E: 49470513d018f97d28024f4e82da3b25)");let c=a.newIbGib,l=await hr({currentIbGib:c,prevIbGib:r});if(l.length>0)throw console.error(`${n} Validation Failed:
20
+ ${l.join(`
21
+ `)}`),new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${l.join("; ")} (E: ae2c58406c1db7687879dfb89fc1f825)`);return await t.put({ibGib:c,space:o}),await t.registerNewIbGib({ibGib:c,space:o}),c}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{J&&console.log(`${n} complete.`)}}f(nt,"evolvePersistAndRegisterKeystone");async function Bn({data:r,metaspace:e,space:t}){let o=`[${Bn.name}]`;try{if(J&&console.log(`${o} starting... (I: 5e32389700e9899e788cbefacef7c825)`),t??=await e.getLocalUserSpace({lock:!1}),!t)throw new Error("(UNEXPECTED) space was falsy and we couldn't get default local user space from metaspace? (E: 9a6498cf16a8801f19ec376749742225)");let s=(await B.firstGen({parentIbGib:B.primitive({ib:ar}),ib:await Ea({keystoneData:r}),data:r,dna:!1,nCounter:!0,tjp:{timestamp:!0,uuid:!0}})).newIbGib;if(!s.data)throw new Error("(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)");if(!s.rel8ns)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)");if(!s.rel8ns.past||s.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 s.data.n=0,s.data.isTjp=!0,delete s.rel8ns.tjp,delete s.rel8ns.past,s.gib=await K({ibGib:s}),await e.put({ibGib:s,space:t}),await e.registerNewIbGib({ibGib:s,space:t}),s}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{J&&console.log(`${o} complete.`)}}f(Bn,"createKeystoneIbGibImpl");async function io({keystoneIbGib:r,dependencyGraph:e,getLatest:t,invalidIfMoreRecentKeystoneFoundInSpace:o,space:n}){let s=`[${io.name}]`;try{if(J&&console.log(`${s} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!r)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let i=[];if(t){let b=_({ibGib:r}),u=await Ue({ibGibs:[r],space:n});if(!u.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!u.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:p}=u.data;if(Object.keys(p).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let h=p[b];if(h)if(h!==b)if(o)i.push(`${s} more recent keystone (${h}) found than the one passed in (${b}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[g]=await Sn({addrs:[h],space:n});r=g}else J&&console.log(`${s} incoming keystone (${b}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${s} keystoneIbGib (${b}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}e??=await fr({ibGib:r,space:n});let a=Object.values(e),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:l,mapWithoutTjps:d}=Xr({ibGibs:a});if(Object.keys(l).length>0&&i.push(`${s} DNA found. Keystones should NOT have DNA. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(d).length>0&&i.push(`${s} Non-tjp ibgibs found? Keystones are expected to have tjps. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(c).length>0){let b=Object.values(c),u=nr({ibGibs:b}),p=Object.keys(u);if(p.length===0)throw new Error("(UNEXPECTED) orderedKeystonesMap empty? (E: d437b80bef58e83a034b28af46278726)");if(p.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 h=p[0],g=u[h];if(g.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await so({keystoneIbGib:g[0]})).forEach(y=>i.push(y)),g.length!==1)for(let y=0;y<g.length-1;y++){let w=g[y],T=g[y+1],A=await hr({prevIbGib:w,currentIbGib:T});A.length>0&&(i.push(`${s} keystone has ${A.length} transition errors. i: ${y}. prevIbGib addr: ${_({ibGib:w})}. currentIbGib addr: ${_({ibGib:T})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),A.forEach(x=>i.push(x)));break}}else if(i.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 i}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{J&&console.log(`${s} complete.`)}}f(io,"validateKeystoneGraph");async function ao({config:r,masterSecret:e}){let t=Et.create({config:r}),o=await t.derivePoolSecret({masterSecret:e}),n={},s=r.behavior.size,i=Date.now().toString();for(let a=0;a<s;a++){let c=await ya({salt:r.salt,timestamp:i,index:a}),l=await t.generateSolution({poolSecret:o,poolId:r.id,challengeId:c});n[c]=await t.generateChallenge({solution:l})}return n}f(ao,"generatePoolChallenges");async function Sa({prevPool:r,newMasterSecret:e}){let t=r.config,o=(await j()).substring(0,16),n={...t,salt:o},s=await ao({config:n,masterSecret:e});return{id:r.id,config:n,challenges:s,...r.isForeign!==void 0?{isForeign:r.isForeign}:{},...r.metadata?{metadata:r.metadata}:{}}}f(Sa,"rotatePoolChallenges");async function co({pool:r,signingSecret:e}){let t=Object.keys(r.challenges);if(t.length===0)return!1;try{let o=t[0],n=r.challenges[o],s=Et.create({config:r.config}),i=await s.derivePoolSecret({masterSecret:e}),a=await s.generateSolution({poolSecret:i,poolId:r.id,challengeId:o});return await s.validateSolution({solution:a,challenge:n})}catch{return!1}}f(co,"verifyPoolSecret");var F=!1,lo=class r{static{f(this,"KeystoneService_V1")}lc=`[${r.name}]`;async genesis({masterSecret:e,emails:t,frameDetails:o,credentialIds:n,dataToPatch:s,configs:i,metaspace:a,space:c,isPrimary:l}){let d=`${this.lc}[${this.genesis.name}]`;try{F&&console.log(`${d} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let b=[];for(let h of i){let g=await ao({config:h,masterSecret:e});b.push({id:h.id,config:h,challenges:g})}if(b.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let u={challengePools:b,proofs:[]};return t&&t.length>0&&(u.emails=[...t]),n&&n.length>0&&(u.credentialIds=[...n]),(o||l!==void 0)&&(u.frameDetails={...o||{}},l!==void 0&&(u.frameDetails.isPrimary=l)),s&&Object.assign(u,s),await Bn({data:u,metaspace:a,space:c})}catch(b){throw console.error(`${d} ${E(b)}`),b}finally{F&&console.log(`${d} complete.`)}}async sign({latestKeystone:e,masterSecret:t,claim:o,poolId:n,poolFilter:s,requiredChallengeIds:i=[],frameDetails:a,metaspace:c,space:l,dataToPatch:d}){let b=`${this.lc}[${this.sign.name}]`;try{F&&console.log(`${b} starting...`);let u=e.data;if(u.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");if(Fn({keystone:e}))throw new Error(`Keystone is expired (${u.frameDetails?.expirationUTC}). Cannot sign. (E: 7f2198c39116d15c48ba191940316825)`);let p=pr({pools:u.challengePools,poolId:n,poolFilter:s,verb:o.verb});F&&console.log(`${b} Selected pool: ${p.id} (size: ${Object.keys(p.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let h=await wt({pool:p,targetAddr:o.target,requiredChallengeIds:i}),{proof:g,nextPools:m}=await $t({targetPoolId:p.id,prevPools:u.challengePools,masterSecret:t,challengeIds:h,claim:o,requiredChallengeIds:i}),y=(u.n??0)+1,w;if(y%mt===0){let x={...e,data:{...u,frameDetails:a}};w=await this.getAggregateDetails({latestKeystone:x,metaspace:c,space:l})}let T={challengePools:m,proofs:[g],frameDetails:a,checkpointDetails:w,...u.delegates?{delegates:u.delegates}:{},...d};return await nt({prevIbGib:e,newData:T,metaspace:c,space:l})}catch(u){throw console.error(`${b} ${E(u)}`),u}finally{F&&console.log(`${b} complete.`)}}async validate({currentIbGib:e,prevIbGib:t}){return await hr({currentIbGib:e,prevIbGib:t})}async registerDelegate({parentKeystone:e,delegateKeystone:t,masterSecret:o,signingPoolId:n,frameDetails:s,metaspace:i,space:a,allowedVerbs:c,deviceName:l,expirationUTC:d,ttlSeconds:b}){let u=`${this.lc}[${this.registerDelegate.name}]`;try{if(F&&console.log(`${u} starting...`),!n)throw new Error("signingPoolId is required (E: a1b2c3d4e5f6818fa8ab28c9b60e6899)");let p=await io({keystoneIbGib:t,getLatest:!0,invalidIfMoreRecentKeystoneFoundInSpace:!1,space:a});if(p.length>0)throw new Error(`Delegate keystone validation failed: ${p.join(", ")} (E: 88fa8ab28c9b60e68994511a5825)`);let h=e.data,g=h.challengePools.find($=>$.id===n);if(!g)throw new Error(`Parent keystone does not contain signing pool: ${n} (E: 818fa8ab28c9b60e68994511a5825)`);if(g.config.allowedVerbs&&g.config.allowedVerbs.length>0&&!g.config.allowedVerbs.includes(ne))throw new Error(`Signing pool ${n} is not authorized for verb: ${ne} (E: 918fa8ab28c9b60e68994511a5825)`);let m=he({ibGib:t});if(!m)throw new Error("(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)");let y={target:m,verb:ne},w=h.delegates?{...h.delegates}:{},T=Kr({spaceIb:a.ib}).spaceId,A=d??(b?new Date(Date.now()+b*1e3).toISOString():void 0)??t.data?.frameDetails?.expirationUTC;return w[m]={delegateTjpAddr:m,delegateAddr:_({ibGib:t}),thisAddr:_({ibGib:e}),deviceName:l,allowedVerbs:c,spaceId:T,expirationUTC:A,role:t.data?.frameDetails?.role},await this.sign({latestKeystone:e,masterSecret:o,claim:y,poolId:n,frameDetails:s,metaspace:i,space:a,dataToPatch:{delegates:w}})}catch(p){throw console.error(`${u} ${E(p)}`),p}finally{F&&console.log(`${u} complete.`)}}async unregisterDelegate({parentKeystone:e,delegateTjpAddr:t,masterSecret:o,signingPoolId:n,frameDetails:s,metaspace:i,space:a}){let c=`${this.lc}[${this.unregisterDelegate.name}]`;try{if(F&&console.log(`${c} starting...`),!n)throw new Error("signingPoolId is required (E: b2c3d4e5f6a13889f8ab28c9b60e6899)");let l=e.data,d=l.challengePools.find(h=>h.id===n);if(!d)throw new Error(`Parent keystone does not contain signing pool: ${n} (E: 3889f8ab28c9b60e68994511a5825)`);if(d.config.allowedVerbs&&d.config.allowedVerbs.length>0&&!d.config.allowedVerbs.includes(ne))throw new Error(`Signing pool ${n} is not authorized for verb: ${ne} (E: 4889f8ab28c9b60e68994511a5825)`);let b={target:t,verb:ne},u=l.delegates?{...l.delegates}:{};if(!u[t])throw new Error(`Delegate ${t} is not registered on this parent. (E: 81d9f8ab28c9b60e68994511a5825)`);return delete u[t],await this.sign({latestKeystone:e,masterSecret:o,claim:b,poolId:n,frameDetails:s,metaspace:i,space:a,dataToPatch:{delegates:u}})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{F&&console.log(`${c} complete.`)}}async getDelegateStatus({parentTjpAddr:e,delegateTjpAddr:t,metaspace:o,space:n}){let s=`${this.lc}[${this.getDelegateStatus.name}]`;try{F&&console.log(`${s} starting...`);let{ib:i,gib:a}=L({ibGibAddr:e}),l=await Ue({ibGibs:[{ib:i,gib:a}],space:n});if(!l.data?.latestAddrsMap)return{registered:!1};let d=l.data.latestAddrsMap[e];if(!d)return{registered:!1};let u=(await o.get({addr:d,space:n})).ibGibs?.at(0);if(!u||!u.data)return{registered:!1};let h=(u.data.delegates||{})[t];return{registered:!!h&&!xa({delegateInfo:h}),delegateInfo:h}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{F&&console.log(`${s} complete.`)}}async validateGenesisKeystone({keystoneIbGib:e}){return await so({keystoneIbGib:e})}async getLatestKeystone({addr:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{F&&console.log(`${n} starting...`);let s=await t.getLatestAddr({addr:e,space:o});if(!s)throw new Error(`could not find latest addr for ${e}`);let i=await t.get({addr:s,space:o});if(i.success&&i.ibGibs&&i.ibGibs.length>0)return i.ibGibs[0];{let c=i.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find latest keystone at ${s}. addrsNotFound: ${c}? resGet.errorMsg: ${i.errorMsg}`)}}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{F&&console.log(`${n} complete.`)}}async validateKeystoneGraph({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:s}){let i=`${this.lc}[${this.validateKeystoneGraph.name}]`;try{return F&&console.log(`${i} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await io({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:s})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{F&&console.log(`${i} complete.`)}}async revoke({latestKeystone:e,masterSecret:t,reason:o="User initiated revocation",frameDetails:n,metaspace:s,space:i}){let a=`${this.lc}[${this.revoke.name}]`;try{F&&console.log(`${a} starting...`);let c=e.data,l=pr({pools:c.challengePools,verb:kt}),d={verb:kt,target:_({ibGib:e})},b=await wt({pool:l,targetAddr:d.target,requiredChallengeIds:[]});if(b.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${l.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:u,nextPools:p}=await $t({targetPoolId:l.id,prevPools:c.challengePools,masterSecret:t,challengeIds:b,claim:d,requiredChallengeIds:[]});p.find(T=>T.id===l.id&&Object.keys(T.challenges).length>0)&&console.warn(`${a} revocation pool ${l.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${ye.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let h={reason:o,proof:u},g=(c.n??0)+1,m;if(g%mt===0){let T={...e,data:{...c,frameDetails:n,revocationInfo:h}};m=await this.getAggregateDetails({latestKeystone:T,metaspace:s,space:i})}let y={challengePools:p,proofs:[u],revocationInfo:h,frameDetails:n,checkpointDetails:m,...c.delegates?{delegates:c.delegates}:{}};return await nt({prevIbGib:e,newData:y,metaspace:s,space:i})}catch(c){throw console.error(`${a} ${E(c)}`),c}finally{F&&console.log(`${a} complete.`)}}async addPools({latestKeystone:e,masterSecret:t,signingPoolId:o,newPools:n,frameDetails:s,dataToPatch:i,metaspace:a,space:c}){let l=`${this.lc}[${this.addPools.name}]`;try{if(F&&console.log(`${l} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let d=e.data;if(d.revocationInfo)throw new Error("Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)");if(n.length===0)throw new Error("No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)");let b=pr({pools:d.challengePools,poolId:o,verb:ne});F&&console.log(`${l} Authorized via pool: ${b.id}`);let u=_({ibGib:e}),p={verb:ne,target:u,details:{type:Ut.add_pool,info:{add:n.map(I=>I.id)}}},h=await wt({pool:b,targetAddr:u}),{proof:g,nextPools:m}=await $t({targetPoolId:b.id,prevPools:d.challengePools,masterSecret:t,challengeIds:h,claim:p}),y=new Set(m.map(I=>I.id));for(let I of n)if(y.has(I.id))throw new Error(`Cannot add pool. ID collision: ${I.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5d)`);let w=[...m,...n],T=(d.n??0)+1,A;if(T%mt===0){let I={...e,data:{...d,challengePools:w,frameDetails:s}};A=await this.getAggregateDetails({latestKeystone:I,metaspace:a,space:c})}let x={challengePools:w,proofs:[g],frameDetails:s,checkpointDetails:A,...d.delegates?{delegates:d.delegates}:{},...i};return await nt({prevIbGib:e,newData:x,metaspace:a,space:c})}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{F&&console.log(`${l} complete.`)}}async removePools({latestKeystone:e,masterSecret:t,signingPoolId:o,poolIds:n,frameDetails:s,dataToPatch:i,metaspace:a,space:c}){let l=`${this.lc}[${this.removePools.name}]`;try{if(F&&console.log(`${l} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 8334c8faed128166a999d428c7805b25)");let d=e.data;if(d.revocationInfo)throw new Error("Keystone has been revoked. Cannot remove pools. (E: 9599f8f51c78d722252ddb2894fdbe25)");if(n.length===0)throw new Error("No pool IDs provided to remove. (E: 7599f8f51c78d722252ddb2894fdbe25)");let b=pr({pools:d.challengePools,poolId:o,verb:ne});F&&console.log(`${l} Authorized via pool: ${b.id}`);let u=_({ibGib:e}),p={verb:ne,target:u,details:{type:Ut.remove_pool,info:{remove:n}}},h=await wt({pool:b,targetAddr:u}),{proof:g,nextPools:m}=await $t({targetPoolId:b.id,prevPools:d.challengePools,masterSecret:t,challengeIds:h,claim:p}),y=new Set(n),w=m.filter(I=>!y.has(I.id));if(w.length!==m.length-n.length){let I=n.filter(G=>!m.some(N=>N.id===G));throw new Error(`Cannot remove pool. Pool IDs not found in keystone: ${I.join(", ")} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5e)`)}let T=(d.n??0)+1,A;if(T%mt===0){let I={...e,data:{...d,challengePools:w,frameDetails:s}};A=await this.getAggregateDetails({latestKeystone:I,metaspace:a,space:c})}let x={challengePools:w,proofs:[g],frameDetails:s,checkpointDetails:A,...d.delegates?{delegates:d.delegates}:{},...i};return await nt({prevIbGib:e,newData:x,metaspace:a,space:c})}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{F&&console.log(`${l} complete.`)}}async getAggregateDetails({latestKeystone:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getAggregateDetails.name}]`;try{let s={},i=e;for(;i;){let a=i.data;if(a.checkpointDetails){s=vt({dominant:s,recessive:a.checkpointDetails});break}if(a.frameDetails&&(s=vt({dominant:s,recessive:a.frameDetails})),a.n===0)break;let c=i.rel8ns?.past,l=c&&c.length>0?c[c.length-1]:void 0;if(!l)break;let d=await t.get({addr:l,space:o});if(!d.success||!d.ibGibs||d.ibGibs.length===0){console.warn(`${n} Could not find previous keystone frame at ${l} (W: e3d069b22e11e550e58844889ddb5325). Returning aggregated details collected so far.`);break}i=d.ibGibs[0]}return this.pruneTombstoneNulls(s),s}catch(s){throw console.error(`${n} ${E(s)}`),s}}async getKeystoneCommonInfo({addr:e,ibGib:t,metaspace:o,space:n}){let s=`${this.lc}[getKeystoneCommonInfo]`;try{let i=e,a=t;if(!i){if(!a)throw new Error("Both addr and ibGib are falsy. Expected at least one parameter to resolve keystone info. (E: 3a2890b1c28f7449c5d8693a7d4a2828)");i=_({ibGib:a})}if(!a){let{ib:A,gib:x}=L({ibGibAddr:i});a={ib:A,gib:x}}let c=await Ue({ibGibs:[a],space:n});if(!c.data?.latestAddrsMap)throw new Error(`Could not get latest address map for keystone ${i} in local space. (E: 4a2890b1c28f7449c5d8693a7d4a2829)`);let l=c.data.latestAddrsMap[i]||Object.values(c.data.latestAddrsMap)[0];if(!l)throw new Error(`No latest address found in map for keystone ${i} in local space. (E: 5a2890b1c28f7449c5d8693a7d4a2830)`);let b=(await o.get({addr:l,space:n})).ibGibs?.at(0);if(!b||!b.data)throw new Error(`Keystone ${l} not found or missing data in local space. (E: 6a2890b1c28f7449c5d8693a7d4a2831)`);let u=b.data.frameDetails||{},p=await this.getAggregateDetails({latestKeystone:b,metaspace:o,space:n}),h=p?.username||p?.name||p?.profile?.name||u?.username||u?.name||"",g=p?.description||p?.profile?.description||u?.description||"",m=!!p?.isPrimary||!!p?.profile?.isPrimary||!!u?.isPrimary,y=b.data.n??0,w=u?.timestamp||p?.timestamp||"",T=u?.timestampMs||p?.timestampMs||void 0;return{name:h,description:g,isPrimary:m,aggregateDetails:p,latestFrameDetails:u,n:y,timestamp:w,timestampMs:T}}catch(i){throw console.error(`${s} ${E(i)}`),i}}async replacePool({latestKeystone:e,newPool:t,signingSecret:o,signingPoolId:n=cr,frameDetails:s,metaspace:i,space:a}){let c=`${this.lc}[${this.replacePool.name}]`;try{if(F&&console.log(`${c} starting... replacing pool: ${t.id}`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 1334c8faed128166a999d428c7805b25)");let l=e.data;if(l.revocationInfo)throw new Error("Keystone has been revoked. Cannot replace pool. (E: 2599f8f51c78d722252ddb2894fdbe25)");let d=l.challengePools,b=d.find($=>$.id===n);if(!b)throw new Error(`Signing pool not found: ${n} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let u=_({ibGib:e}),p={verb:ne,target:u,details:{type:Ut.replace_pool,info:{replace:t.id}}},h=await wt({pool:b,targetAddr:u}),{proof:g,nextPools:m}=await $t({targetPoolId:n,prevPools:d,masterSecret:o,challengeIds:h,claim:p}),y=m.findIndex($=>$.id===t.id);if(y===-1)throw new Error(`Target pool to replace '${t.id}' not found in keystone challenge pools.`);m[y]=t;let w=(l.n??0)+1,T;if(w%mt===0){let $={...e,data:{...l,frameDetails:s}};T=await this.getAggregateDetails({latestKeystone:$,metaspace:i,space:a})}let A={challengePools:m,proofs:[g],frameDetails:s,checkpointDetails:T,...l.delegates?{delegates:l.delegates}:{}};return await nt({prevIbGib:e,newData:A,metaspace:i,space:a})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{F&&console.log(`${c} complete.`)}}async changePassword({keystoneIbGib:e,keystoneAddr:t,newMasterSecret:o,signingSecret:n,signingPoolId:s=cr,poolIds:i,frameDetails:a,metaspace:c,space:l}){let d=`${this.lc}[${this.changePassword.name}]`;try{if(F&&console.log(`${d} starting... (I: 9e3ff83ebd74511f9dad784a1020d926)`),!e&&!t)throw new Error("Either keystoneIbGib or keystoneAddr required. (E: d1b8c8cb75f2c022284e69b8c30af826)");if(e&&t){let v=_({ibGib:e});if(v!==t)throw new Error(`(UNEXPECTED) both keystoneIbGib (addr: ${v}) and keystoneAddr (${t}) provided, but the addrs are unequal? Note that only one is required for this function, but if both are provided the addrs must match exactly. (E: c5574f7e353a48b0bba94a1862af4e26)`)}t??=_({ibGib:e});let b=await this.getLatestKeystone({addr:t,metaspace:c,space:l});if(!b.data)throw new Error("latestKeystone.data falsy (E: 22e498eb8308a33e68b812d8d3905826)");if(b.data.revocationInfo)throw new Error("Keystone has been revoked. Cannot change password. (E: 726298617e8508b3c83b5e985a03e826)");let u=b.data.challengePools,p=u.find(v=>v.id===s);if(!p)throw new Error(`Signing pool not found: ${s} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let h=[];if(i&&i.length>0)for(let v of i){let P=u.find(D=>D.id===v);if(!P)throw new Error(`Target pool to rotate not found: ${v} (E: 4599f8f51c78d722252ddb2894fdbe25)`);h.push(P)}else if(h=u.filter(v=>!v.isForeign),h.length===0)throw new Error("No non-foreign pools found to rotate. (E: 5599f8f51c78d722252ddb2894fdbe25)");let g=[];for(let v of h){let P=await Sa({prevPool:v,newMasterSecret:o});g.push(P)}let m=_({ibGib:b}),y={verb:ne,target:m,details:{type:Ut.change_password,info:{change:g.map(v=>v.id)}}},w=await wt({pool:p,targetAddr:m}),{proof:T,nextPools:A}=await $t({targetPoolId:s,prevPools:u,masterSecret:n,challengeIds:w,claim:y});for(let v of g){let P=A.findIndex(D=>D.id===v.id);if(P===-1)throw new Error(`Rotated pool ${v.id} not found in next pools list. (E: 6599f8f51c78d722252ddb2894fdbe25)`);A[P]=v}let x=(b.data.n??0)+1,$;if(x%mt===0){let v={...b,data:{...b.data,challengePools:A}};$=await this.getAggregateDetails({latestKeystone:v,metaspace:c,space:l})}let I={challengePools:A,proofs:[T],frameDetails:a,checkpointDetails:$,...b.data.delegates?{delegates:b.data.delegates}:void 0},G=await nt({prevIbGib:b,newData:I,metaspace:c,space:l}),N=[];if((i??[]).length===0){let v=await ot({masterSecret:n}),P=await ot({masterSecret:o}),D=b.data.delegates??{};for(let[U,V]of Object.entries(D)){if(Ga({delegateInfo:V})){F&&console.log(`${d} Skipping custodial delegate rotation for ${U} (${V.deviceName})`);continue}try{let{newKeystone:Z,newDelegates:St}=await this.changePassword({keystoneAddr:U,metaspace:c,space:l,newMasterSecret:P,signingSecret:v,signingPoolId:s,poolIds:void 0,frameDetails:a});if(St&&St.length>0)throw new Error("(UNEXPECTED) Delegate keystone has its own delegate(s)? ATOW (07/20/2026) second order delegates are not supported. (E: de45a7b7d9b8f61f6e58158269acba26)");N.push(Z)}catch(Z){console.warn(`${d} Error rotating user delegate ${U}: ${E(Z)}. Continuing.`)}}}return{newKeystone:G,newDelegates:N.length>0?N:void 0}}catch(b){throw console.error(`${d} ${E(b)}`),b}finally{F&&console.log(`${d} complete.`)}}async verifySigningSecret({keystoneIbGib:e,signingSecret:t,poolId:o,verb:n=ne}){let s=`${this.lc}[${this.verifySigningSecret.name}]`;try{if(!e.data)return!1;let i=e.data.challengePools;if(o){let c=i.find(l=>l.id===o);return c?await co({pool:c,signingSecret:t}):!1}let a=i.filter(c=>c.id==="manage"||c.id.startsWith("passkey-manage-")||c.config.allowedVerbs&&n&&c.config.allowedVerbs.includes(n));for(let c of a)if(await co({pool:c,signingSecret:t}))return!0;return!1}catch(i){return console.warn(`${s} Exception during verification: ${E(i)}`),!1}}pruneTombstoneNulls(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.filter(t=>t!==null).map(t=>this.pruneTombstoneNulls(t));for(let t of Object.keys(e))e[t]===null?delete e[t]:typeof e[t]=="object"&&this.pruneTombstoneNulls(e[t]);return e}};var va="sync-delegate",Da="custodial-sync";var fo="custodian-manage-";var Oa=!1;async function ot({masterSecret:r}){let e=await X({s:r,algorithm:Ee.sha_512});return await Lt({masterSecret:r,salt:e,rounds:1e3,algorithm:Ee.sha_512})}f(ot,"deriveDelegateSecret");async function Na({primaryTjpAddr:r,deviceTag:e}){if(!r)throw new Error("primaryTjpAddr is required to derive device delegate secret (E: a1b2c3d4e5f67890123456789a000101)");let t=await j(32),o=`${r}_${e||""}_${t}`;return await X({s:o,algorithm:Ee.sha_512})}f(Na,"deriveDeviceDelegateSecret");async function yt({profileName:r,profileTemplate:e,username:t,deviceTag:o,primaryTjpAddr:n,delegateSecret:s,custodianReqs:i,expirationUTC:a,additionalFrameDetails:c,metaspace:l,space:d}){let b=`[${yt.name}]`;try{if(!r&&!e)throw new Error("profileName or profileTemplate is required (E: a1b2c3d4e5f67890123456789a000102)");if(!n)throw new Error("primaryTjpAddr is required (E: a1b2c3d4e5f67890123456789a000104)");if(!s)throw new Error("delegateSecret is required (E: a1b2c3d4e5f67890123456789a000105)");let u=o||"primary-device",p=e?dr.fromTemplate(e):dr.buildKeystone(r),h=Ne({text:u,keepLiterals:["-"]})||"device",g=Ne({text:t,keepLiterals:["-"]})||"user";p.withUsername(`${g}-sync-${h}`.slice(0,60)).withDescription(`Sync Delegate for ${t} on ${u}`).withDetails({client:"space-gib-web",role:va,deviceTag:u,primaryTjpAddr:n,...i?{custodianReqs:i}:{},...c||{}}),a&&p.withExpiration(a);let m=await p.compileConfigs(),y=p.getFrameDetails();return await new lo().genesis({masterSecret:s,configs:m,metaspace:l,space:d,frameDetails:y,isPrimary:!1})}catch(u){throw console.error(`${b} ${E(u)}`),u}}f(yt,"createSyncDelegateKeystone");function Fn({keystone:r,nowUTC:e}){if(!r||!r.data?.frameDetails?.expirationUTC)return!1;let t=Date.parse(r.data.frameDetails.expirationUTC);return isNaN(t)?!1:(e!==void 0?typeof e=="number"?e:e instanceof Date?e.getTime():Date.parse(e):Date.now())>t}f(Fn,"isKeystoneExpired");function xa({delegateInfo:r,delegateKeystone:e,nowUTC:t}){if(!r&&!e)throw new Error("either delegateInfo or delegateKeystone required. (E: d1baa55ca8d23b26f8562a28179d2126)");if(e)return Fn({keystone:e,nowUTC:t});if(!r||!r.expirationUTC)return!1;let o=Date.parse(r.expirationUTC);return isNaN(o)?!1:(t!==void 0?typeof t=="number"?t:t instanceof Date?t.getTime():Date.parse(t):Date.now())>o}f(xa,"isDelegateExpired");function Vl({keystone:r,aggregatedDetails:e,providerId:t}){let o=`[${Vl.name}]`;try{Oa&&console.log(`${o} starting... (I: 1db5581127983918ff303dd8370daf26)`);let n=`${fo}${t}`;if(r.data?.challengePools?.some(i=>i.id===n))return!0;if(!(r.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||r.data?.custodyMode==="hybrid")){let i=e?.custodianProvider||r.data?.frameDetails?.custodianProvider||r.data?.custodianProvider;if(i&&String(i).toLowerCase()===String(t).toLowerCase())return!0}return!1}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{Oa&&console.log(`${o} complete.`)}}f(Vl,"isSsoProviderLinked");function Ga({delegateInfo:r,delegateKeystone:e,providerId:t}){if(!r&&!e)return!1;let o=r?.role||e?.data?.frameDetails?.role,n=r?.deviceName||e?.data?.frameDetails?.deviceTag,s=r?.metadata?.provider||e?.data?.frameDetails?.custodianProvider||e?.data?.frameDetails?.metadata?.provider,i=o===Da||o==="custodial-sync";if(s)return t?String(s).toLowerCase()===String(t).toLowerCase():!0;if(n){let a=n.toLowerCase();if(t){let c=String(t).toLowerCase();return a.includes(c)||i&&a.includes("custodian")}if(a.includes("custodian")||a.includes("oauth2")||a.includes("google")||a.includes("github")||a.startsWith("email-")||a.includes("@"))return!0}return!!(!t&&i)}f(Ga,"isCustodialDelegate");function Ym({keystone:r,aggregatedDetails:e}){if(!r)return{isSovereign:!1,isCustodial:!1,isHybrid:!1,providers:[],emails:[]};let t=e?.emails||r.data?.frameDetails?.emails||[],o=r.data?.challengePools||[],n=e?.custodianProvider||r.data?.frameDetails?.custodianProvider||r.data?.custodianProvider,i=!(r.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||r.data?.custodyMode==="hybrid")&&(!!n||r.data?.frameDetails?.custodyMode==="full"||e?.custodyMode==="full"||r.data?.custodyMode==="full"),a=new Set;for(let w of o)if(w.id.startsWith(fo)){let T=w.id.substring(fo.length);T&&a.add(T)}i&&n&&a.add(n);let c=Array.from(a),l=c.length>0||i,d=o.some(w=>w.id==="manage"),u=o.filter(w=>w.id.startsWith("passkey-manage-")).length||(r.data?.credentialIds?r.data.credentialIds.length:0),p=u>0,h=d&&!i,g=(d||p)&&!i,m=l;return{isSovereign:g,isCustodial:m,isHybrid:g&&m,providers:c,emails:t,hasPasskeys:p,passkeyCount:u,hasPassword:h}}f(Ym,"getKeystoneCapabilities");function Mt(r){let e=(r?.userAgent??(typeof navigator<"u"?navigator.userAgent:"")??"").toLowerCase(),t=r?.userAgentData??(typeof navigator<"u"?navigator.userAgentData:void 0),o=r?.maxTouchPoints??(typeof navigator<"u"?navigator.maxTouchPoints:0)??0,n=r?.screenWidth??(typeof window<"u"?window.innerWidth:1024)??1024,s="",i=t?.mobile,a=/mobile|iphone|ipod|android.*mobile|windows phone/i.test(e);/ipad|tablet|(android(?!.*mobile))/i.test(e)||o>1&&/macintosh/i.test(e)&&n<=1366?s="tablet":(i||a)&&(s="mobile");let l="",d=(t?.platform||"").toLowerCase();d.includes("win")||e.includes("windows")?l="win":d.includes("ios")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?l="ios":d.includes("mac")||e.includes("macintosh")||e.includes("mac os")?l="mac":d.includes("android")||e.includes("android")?l="android":(d.includes("linux")||e.includes("linux"))&&(l="linux");let b="";e.includes("edg/")||e.includes("edge/")?b="edge":e.includes("chrome/")||e.includes("crios/")?b="chrome":e.includes("firefox/")||e.includes("fxios/")?b="firefox":e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&(b="safari");let u=r?.randomSuffix;if(!u){let h="0123456789abcdef";u="";for(let g=0;g<4;g++)u+=h.charAt(Math.floor(Math.random()*h.length))}u=u.toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,8);let p=[];return s&&p.push(s),b&&p.push(b),l&&p.push(l),p.length===0&&p.push("device"),p.push(u),p.join("-")}f(Mt,"generateDefaultDeviceTag");var Xl="ibgib_device_delegate_secret_";function Ca({primaryTjpAddr:r}){if(!r)throw new Error("primaryTjpAddr is required to get device delegate secret key (E: 1a2b3c4d5e6f7890123456789a000101)");return`${Xl}${r}`}f(Ca,"getDeviceDelegateSecretKey");async function Pa({primaryTjpAddr:r}){let e=`[${Pa.name}]`;try{if(!r)throw new Error("primaryTjpAddr is required to get device delegate secret (E: 2a2b3c4d5e6f7890123456789a000102)");let t=uo(),o=bo(),n=Ca({primaryTjpAddr:r});return await Rt({dbName:t,storeName:o,key:n})}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Pa,"getDeviceDelegateSecret");async function gr({primaryTjpAddr:r,delegateSecret:e}){let t=`[${gr.name}]`;try{if(!r)throw new Error("primaryTjpAddr is required to set device delegate secret (E: 3a2b3c4d5e6f7890123456789a000103)");if(!e)throw new Error("delegateSecret is required to set device delegate secret (E: 4a2b3c4d5e6f7890123456789a000104)");let o=uo(),n=bo(),s=Ca({primaryTjpAddr:r});await ir({dbName:o,storeName:n,key:s,value:e})}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(gr,"setDeviceDelegateSecret");async function qn({primaryTjpAddr:r,deviceTag:e}){let t=`[${qn.name}]`;try{if(!r)throw new Error("primaryTjpAddr is required to get or create device delegate secret (E: 5a2b3c4d5e6f7890123456789a000105)");let o=await Pa({primaryTjpAddr:r});if(o)return o;let n=await Na({primaryTjpAddr:r,deviceTag:e});return await gr({primaryTjpAddr:r,delegateSecret:n}),n}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(qn,"getOrCreateDeviceDelegateSecret");async function nE({username:r,primaryTjpAddr:e,masterSecret:t,metaspace:o,space:n}){let s=await ot({masterSecret:t});await gr({primaryTjpAddr:e,delegateSecret:s});let i=Ne({text:r,length:8,keepLiterals:["-"]})||"user",a=Mt(),c=`pwd-${i}-${a}`,l="sync-profile.dev";if(!l||!l.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing.");return{delegateKeystone:await yt({profileName:l.trim(),username:r,deviceTag:c,primaryTjpAddr:e,delegateSecret:s,additionalFrameDetails:{client:"space-gib-web"},metaspace:o,space:n}),deviceTag:c,delegateSecret:s}}f(nE,"createSovereignDeviceSyncDelegate");async function sE({providerId:r,username:e="user",primaryTjpAddr:t,custodianReqs:o,metaspace:n,space:s}){let i=await qn({primaryTjpAddr:t}),a=Mt(),c=`oauth2-${r}-${a}`,l="sync-profile.dev";if(!l||!l.trim())throw new Error("KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing.");return{delegateKeystone:await yt({profileName:l.trim(),username:e,deviceTag:c,primaryTjpAddr:t,delegateSecret:i,custodianReqs:o,additionalFrameDetails:{client:"space-gib-web"},metaspace:n,space:s}),deviceTag:c,delegateSecret:i}}f(sE,"createOAuth2DeviceSyncDelegate");async function iE({email:r,primaryTjpAddr:e,custodianReqs:t,metaspace:o,space:n}){let s=await qn({primaryTjpAddr:e}),i=Mt(),[a="",c=""]=(r||"").split("@"),l=Ne({text:a,length:8,keepLiterals:["-"]})||"user",d=c.split(".")[0]||"",b=d?Ne({text:d,length:8,keepLiterals:["-"]}):"",p=`email-${b?`${l}@${b}`:l}-${i}`,h=l,g="sync-profile.dev";if(!g||!g.trim())throw new Error("KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing.");return{delegateKeystone:await yt({profileName:g.trim(),username:h,deviceTag:p,primaryTjpAddr:e,delegateSecret:s,custodianReqs:t,additionalFrameDetails:{client:"space-gib-web"},metaspace:o,space:n}),deviceTag:p,delegateSecret:s}}f(iE,"createEmailDeviceSyncDelegate");async function Hn(){try{if(typeof window>"u"||!window.PublicKeyCredential)return!1;if(typeof window.PublicKeyCredential.getClientCapabilities=="function"){let r=await window.PublicKeyCredential.getClientCapabilities();if(r&&r.prf)return!0}return typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable=="function"?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1}catch{return!1}}f(Hn,"isPasskeyPrfSupported");function po(r){return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}f(po,"bufferToHex");function Ra(r){let e=r.replace(/[^0-9a-fA-F]/g,""),t=new Uint8Array(Math.floor(e.length/2));for(let o=0;o<t.length;o++)t[o]=parseInt(e.substr(o*2,2),16);return t}f(Ra,"hexToUint8Array");function La(r){if(r instanceof Uint8Array){if(r.length===32)return r;let o=new Uint8Array(32);return o.set(r.subarray(0,32)),o}if(/^[0-9a-fA-F]{64}$/.test(r))return Ra(r);let e=new TextEncoder().encode(r),t=new Uint8Array(32);return t.set(e.subarray(0,32)),t}f(La,"normalizeSaltTo32Bytes");async function uE({username:r,displayName:e=r,rpName:t="ibgib",rpId:o,salt:n,userVerification:s="preferred",authenticatorAttachment:i,hints:a=["security-key","client-device","hybrid"]}){let c="[registerPasskeyCredential]";try{if(typeof window>"u"||!navigator.credentials?.create)throw new Error("WebAuthn is not supported in this browser environment.");let l=o||(typeof window<"u"?window.location.hostname:void 0),d=crypto.getRandomValues(new Uint8Array(32)),b=new TextEncoder().encode(r.slice(0,64)),u=n?La(n):void 0,p=u?{eval:{first:u}}:{},h=await navigator.credentials.create({publicKey:{challenge:d,rp:{name:t,...l?{id:l}:{}},user:{id:b,name:r,displayName:e},pubKeyCredParams:[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"},{alg:-8,type:"public-key"}],authenticatorSelection:{residentKey:"required",userVerification:s,...i?{authenticatorAttachment:i}:{}},...a&&a.length>0?{hints:a}:{},extensions:{prf:p}}});if(!h)throw new Error("Passkey creation was cancelled or failed.");let g=po(h.rawId),m=h.response,y=typeof m.getTransports=="function"?m.getTransports():[],w=h.getClientExtensionResults?.()||{};console.log(`${c} WebAuthn registration clientExtensionResults:`,w);let T;return w.prf?.results?.first&&(T=po(w.prf.results.first),console.log(`${c} Evaluated PRF directly during create!`)),{credentialId:g,rawId:h.rawId,transports:y,passkeySecret:T}}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(uE,"registerPasskeyCredential");async function Kn({salt:r,credentialId:e,transports:t,rpId:o,userVerification:n="preferred",hints:s=["security-key","client-device","hybrid"]}){let i="[evaluatePasskeyPrf]";try{if(typeof window>"u"||!navigator.credentials?.get)throw new Error("WebAuthn is not supported in this browser environment.");let a=o||(typeof window<"u"?window.location.hostname:void 0),c=crypto.getRandomValues(new Uint8Array(32)),l=La(r),d,b;if(e){let w=Ra(e);b=[{id:w.buffer,type:"public-key",...t&&t.length>0?{transports:t}:{}}];let T="";for(let A=0;A<w.byteLength;A++)T+=String.fromCharCode(w[A]);d=btoa(T).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}let u={eval:{first:l}};d&&(u.evalByCredential={[d]:{first:l}});let p=await navigator.credentials.get({publicKey:{challenge:c,...a?{rpId:a}:{},allowCredentials:b,userVerification:n,...s&&s.length>0?{hints:s}:{},extensions:{prf:u}}});if(!p)throw new Error("Passkey authentication was cancelled or failed.");let h=po(p.rawId),g=p.getClientExtensionResults?.()||{};console.log(`${i} WebAuthn assertion clientExtensionResults:`,JSON.stringify(g),g);let m=g.prf?.results?.first;if(!m&&d&&g.prf?.resultsByCredential?.[d]?.first&&(m=g.prf.resultsByCredential[d].first,console.log(`${i} Extracted PRF result from resultsByCredential!`)),!m)throw console.error(`${i} Extension results did not contain PRF evaluation:`,JSON.stringify(g),g),new Error("Authenticator did not return a PRF evaluation. PRF extension may not be supported on this authenticator.");return{passkeySecret:po(m),credentialId:h}}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(Kn,"evaluatePasskeyPrf");async function pE({username:r,primaryTjpAddr:e,passkeySecret:t,transports:o,metaspace:n,space:s}){let i=await ot({masterSecret:t});await gr({primaryTjpAddr:e,delegateSecret:i});let a=Ne({text:r,length:8,keepLiterals:["-"]})||"user",c=Mt(),l=`passkey-${a}-${c}`,d="sync-profile.dev";if(!d||!d.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing.");return{delegateKeystone:await yt({profileName:d.trim(),username:r,deviceTag:l,primaryTjpAddr:e,delegateSecret:i,additionalFrameDetails:{client:"space-gib-web",role:"passkey-sync",...o&&o.length>0?{transports:o}:{}},metaspace:n,space:s}),deviceTag:l,delegateSecret:i}}f(pE,"createPasskeyDeviceSyncDelegate");var be=rt;function ka(r){return new TextDecoder().decode(r)}f(ka,"uint8ArrayToString");var Ua=class r{static{f(this,"PathUtilsHelper")}lc=`[${r.name}]`;constructor(){}isAbsolute(e){if(!e)throw new Error("(UNEXPECTED) path falsy? (E: dcb92e11770ba06205c0afe3e6560b24)");return e.startsWith("/")}isRelative(e){return!this.isAbsolute(e)}join(...e){let t=`${this.lc}[${this.join.name}]`;if(e.length===0)return console.log(`${t} paths.length === 0. returning '.' per node convention. (I: 153da80765ff6160675fae895ebac225)`),".";if(e.length===1&&e[0]==="..")return console.log(`${t} paths.length === 1 && paths[0] === '..'. returning '..' per node convention. (I: 9af242b7615430a8c6899b1a332e9925)`),"..";let o="";for(let n=0;n<e.length;n++){let s=e[n];s===".."?o=o.split("/").slice(0,-1).join("/"):(s.startsWith("/")&&(s=s.slice(1)),s.endsWith("/")&&(s=s.slice(0,-1)),o+=(n>0?"/":"")+s)}return o}dirname(e){return e.split("/").slice(0,-1).join("/")}basename(e,t){return e.split("/").pop()??""}};async function Yl({msg:r,title:e,confirm:t,noNewLine:o,rl:n,defaultValue:s,dontCloseRl:i,cancelable:a}){let c=`[${Yl.name}]`;try{if(!r)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let l,d=0,b=5;do{if(d++,d>=b)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await de(50),l=await ht({title:e||"Prompt for Info",msg:r,prompt:!0,showInput:!0,isPassword:!1,defaultValue:s})}while(l===void 0&&!a);return l??""}catch(l){debugger;throw console.error(`${c} ${E(l)}`),l}}f(Yl,"promptForText");async function Wl({msg:r,confirm:e,passkeys:t}){let o=`[${Wl.name}]`;try{be&&console.log(`${o} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let n,s=!0,i=0,a=5,l=await Hn().catch(()=>!1)&&t&&Object.keys(t).length>0?async d=>{if(!d)return;let{passkeySecret:b}=await Kn({credentialId:d.credentialId,salt:d.salt,transports:d.transports,userVerification:"preferred"});return b}:void 0;do{if(i++,i>=a)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await de(50),n=await ht({title:s?"Shh...":"Secrets didn't match, try again...",msg:r||"Enter Your Secret...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0,passkeys:t,onPasskeyAuth:l}),n===void 0)throw new Error("user cancelled (E: 91519d04378e84106f3df8eb36d99725)");if(typeof n=="object"&&n?.secret!==void 0&&(n=n.secret),e){await de(250);let d=await ht({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});d===void 0&&(n=void 0),typeof d=="object"&&d?.secret!==void 0&&(d=d.secret),n!==d&&(n=void 0,s=!1,await de(250))}}while(n===void 0);return n}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{be&&console.log(`${o} complete.`)}}f(Wl,"promptForSecret");async function zl({keystone:r,aggregatedDetails:e,title:t,msg:o,verb:n="manage"}){let s=`[${zl.name}]`;try{let i=e?.passkeys||r.data?.frameDetails?.passkeys||r.data?.passkeys||{},c=await Hn().catch(()=>!1)&&i&&Object.keys(i).length>0?async u=>{if(!u)return;let{passkeySecret:p}=await Kn({credentialId:u.credentialId,salt:u.salt,transports:u.transports,userVerification:"preferred"});return p}:void 0,d=(r.data?.challengePools||[]).filter(u=>u.id==="manage"||u.id.startsWith("passkey-manage-")||u.config?.allowedVerbs&&n&&u.config.allowedVerbs.includes(n)).some(u=>u.id==="manage"),b=await ht({title:t||"Authorize Action",msg:o||"Authorize this action with your master password or passkey:",prompt:!0,showInput:d,isPassword:!0,defaultValue:void 0,passkeys:i,onPasskeyAuth:c});if(!b)throw new Error("Action cancelled by user.");return typeof b=="object"&&b.secret!==void 0?{secret:b.secret,poolId:b.poolId||"manage"}:{secret:String(b),poolId:"manage"}}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(zl,"promptForAuthoritySecret");async function Jl({msg:r,title:e,skipHitEnterToContinue:t}){let o=`[${Jl.name}]`;try{if(!r)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{e??="",await de(50),await ht({title:e,msg:r})}catch(n){throw n}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Jl,"alertUser");async function Zl({exportIbGibJsonString:r,metaspace:e}){let t=`[${Zl.name}]`;try{debugger;if(be&&console.log(`${t} starting... (I: genuuid)`),!e)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");if(!await e.getLocalUserSpace({lock:!1}))throw new Error("(UNEXPECTED) couldn't get default local user space? (E: genuuid)");let n,s;try{n=JSON.parse(r)}catch(l){let d=`Error during parse JSON. error: ${E(l)} (E: genuuid)`,b=new Error(d);throw b.cause=l,b}try{let l=await ae({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(s=n,!s.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)")}catch(l){let d=`Error during parse JSON. error: ${E(l)} (E: genuuid)`,b=new Error(d);throw b.cause=l,b}let i;if(s.data.compression)switch(s.data.compression){case"gzip":i=await Gn({compressedBase64:s.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${s.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else i=await zr({jsonString:s.data.dependencyGraphAsString});let a={};for(let[l,d]of Object.entries(i)){let b=await ae({ibGib:d})??[];b.length>0&&(a[l]=b)}if(Object.keys(a).length>0)throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:
22
+ ${H({validationErrorMap:a})} (E: e63f38b182a84122d83a55befb369825)`);return[s,i]}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{be&&console.log(`${t} complete.`)}}f(Zl,"getRawExportIbGibAndGraphFromJsonString");async function Ql({ibGib:r,compress:e,metaspace:t,space:o}){let n=`[${Ql.name}]`;try{if(be&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),te({ibGib:r}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let s=await vn({ibGib:r,live:!0,compress:e,metaspace:t,space:o}),{rawExportIbGib:i,errors:a}=s;if((a??[]).length>0)throw new Error(`Export had errors: ${a} (E: 05faf83f25d3449ab809dfd24eeaf825)`);let c=JSON.stringify(i),l="data:text/json;charset=utf-8,"+encodeURIComponent(c),b=`${_({ibGib:i})}.json`,u=document.createElement("a");u.setAttribute("style","none"),u.setAttribute("href",l),u.setAttribute("download",b);let p=document.getElementsByTagName("div")[0];p.appendChild(u),u.click(),p.removeChild(u)}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{be&&console.log(`${n} complete.`)}}f(Ql,"exportIbGib");function Ma({id:r,shadowRoot:e}){let t=`[${Ma.name}]`;try{be&&console.log(`${t} starting... (I: 18a338c6dab8690c72b8759b8d952925)`);let o=e?e.getElementById(r):document.getElementById(r);if(o)return o;throw new Error(`${e?"shadowRoot":"document"}.getElementById(${r}) returned null. So...Element was not found. (E: 5e501f6835cc74cd4c2faf0d9e387825)`)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{be&&console.log(`${t} complete.`)}}f(Ma,"getElementById_throwsIfFalsy");function DE(r,e){return Ma({id:e,shadowRoot:r})}f(DE,"shadowRoot_getElementById");function bo(){let r=`[${bo.name}]`;try{be&&console.log(`${r} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let e=gt();if(!e.storeName_hack)throw new Error("(UNEXPECTED) global store name falsy? (E: 3b9b680f6a980debbb877c9a13fb2625)");return e.storeName_hack}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{be&&console.log(`${r} complete.`)}}f(bo,"getGlobalStoreName");function uo(){let r=`[${uo.name}]`;try{be&&console.log(`${r} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let e=gt();if(!e.dbName_hack)throw new Error("(UNEXPECTED) global db name falsy? (E: 3aa028d5e4088f3f3841aae94ac02825)");return e.dbName_hack}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{be&&console.log(`${r} complete.`)}}f(uo,"getGlobalDbName");function ed(){let r=`[${ed.name}]`;try{be&&console.log(`${r} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let e=gt();if(!e.apiKeyName_hack)throw new Error("(UNEXPECTED) global api key name falsy? (E: 1782e812f0c87f54b8059468a5b60125)");return e.apiKeyName_hack}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{be&&console.log(`${r} complete.`)}}f(ed,"getGlobalIndexedDbKey_APIKey");async function Vn({infos:r}){let e=`[${Vn.name}]`;try{be&&console.log(`${e} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let t of r){let{dbName:o,storeNames:n}=t;await Yn({dbName:o})||await ho({dbName:o});for(let i of n)await Xn({dbName:o,storeName:i})}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{be&&console.log(`${e} complete.`)}}f(Vn,"initAppStorage");var ge=rt,ja=0;async function ho({dbName:r,storeName:e,version:t,logalot:o=!1}){let n=`[${ho.name}][${r}][${e??"no store name"}]`,s=crypto.randomUUID();o&&console.time(n+s);let i;try{o&&console.log(`${n} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`),await new Promise((c,l)=>{try{o&&console.log(`${n} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`),o&&console.timeLog(n+s,"opening... (I: e748b4ddb445d77cb10a7ba158b49125)");let d=indexedDB.open(r,t);ja++,console.log(`${n} initRequestCount: ${ja} (I: 294d5f0b12ffe5512bacebe891824d25)`);let b;d.onupgradeneeded=u=>{try{i=u.target.result,o&&console.timeLog(n+s,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),e&&(i.objectStoreNames.contains(e)?b=!0:(b=!1,i.createObjectStore(e,{keyPath:"key"})))}catch(p){console.error(`${n}[openDBRequest.onupgradeneeded] ${E(p)} (E: 4a5fa1b0850be47e28bee653da287325)`),l(p)}},d.onblocked=u=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${u.oldVersion} -> ${u.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(u)},d.onsuccess=u=>{try{o&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),o&&console.timeLog(n+s,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),i=u.target.result,e&&(b??=i.objectStoreNames.contains(e),o&&console.log(`${n} ${r} store "${e}" ${b?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(p){console.error(`${n}[openDBRequest.onsuccess] ${E(p)}`),l(p)}},d.onerror=u=>{debugger;console.error(`${n}[initRequest.onerror] ${E(d.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`),l(d.error)}}catch(d){console.error(`${n} ${E(d)}`);debugger;l(d)}finally{o&&console.log(`${n} complete.`)}})}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{i&&(o&&console.log(`${n} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),i.close(),o&&(console.log(`${n} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`),console.timeLog(n+s,"db closed. (I: e748b4ddb445d77cb10a7ba158b49125)"))),o&&(console.log(`${n} complete.`),console.timeEnd(n+s))}}f(ho,"initializeStorage");async function Ba({dbName:r,logalot:e=!1}){let t=`[${Ba.name}]`,o=crypto.randomUUID();e&&console.time(t+o);try{return e&&console.log(`${t} starting... (I: 8516795b20529d19eb6923defd7a0f24)`),(await indexedDB.databases()).filter(s=>s.name===r).at(0)}catch(n){console.error(`${t} ${E(n)}`)}finally{e&&console.timeEnd(t+o),e&&console.log(`${t} complete.`)}}f(Ba,"storageGetDBInfo");async function Xn({dbName:r,storeName:e,logalot:t=!1}){let o=`[${Xn.name}]`,n=crypto.randomUUID();t&&console.time(o+n);let s;try{if(t&&console.log(`${o} starting... (I: 029f7caa8ea5ea08a865f3924c82b624)`),!(await indexedDB.databases()).filter(b=>b.name===r).at(0))throw new Error(`db (${r}) does not exist. can't create store (${e}) (E: 5b15f7aed6f7068d077b2c7ebcbe8524)`);let a=!1;if(t&&console.timeLog(o+n),await new Promise((b,u)=>{let p=indexedDB.open(r);p.onsuccess=h=>{s=h.target.result,a=s.objectStoreNames?.contains(e),t&&console.timeLog(o+n,"open db request"),b()},p.onerror=h=>{debugger;console.error(`${o}[openDBRequest.onerror] ${E(p.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),u(p.error)}}),t&&console.timeLog(o+n),a){t&&console.log(`${o} store ${e} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await Ba({dbName:r,logalot:t});if(t&&console.timeLog(o+n,"storageGetDBInfo complete"),!c)throw new Error(`db (${r}) does not exist. can't create store (${e}) (E: c771db13fa28f67079aad45e1ab7e624)`);let l=c.version;if(!l)throw new Error(`db (${r}) has no version. can't create store (${e}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`);let d=l+1;if(t&&console.log(`${o} creating store ${e} with version ${d} (I: 312b79f28243c650cf38935114f21e24)`),s)s.close(),s=void 0;else throw new Error("(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)");await ho({dbName:r,storeName:e,version:d,logalot:t})}catch(i){throw console.error(`${o} ${E(i)}`),i}finally{s&&(t&&console.log(`${o} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),s.close(),t&&console.log(`${o} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`)),t&&console.timeLog(o+n),t&&console.log(`${o} complete.`)}}f(Xn,"storageCreateStoreIfNotExist");async function ir({dbName:r,version:e,storeName:t,key:o,value:n,logalot:s=!1}){let i=`[${ir.name}]`,a;try{s&&console.log(`${i} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((l,d)=>{try{s&&console.log(`${i} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let b=indexedDB.open(r,e);b.onsuccess=u=>{a=u.target.result;try{let p=a.transaction(t,"readwrite").objectStore(t),h={key:o,value:n};p.put(h),l()}catch(p){console.error(`${i}[putRequest.onsuccess] ${E(p)}`),d(p)}},b.onerror=u=>{debugger;console.error(`${i}[putRequest.onerror] ${E(b.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),d(b.error)}}catch(b){console.error(`${i} ${E(b)}`),d(b)}finally{s&&console.log(`${i} complete.`)}})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{a&&(s&&console.log(`${i} closing db ${r}... (I: 438c6edced94b83a3478c71b08c6c325)`),a.close(),s&&console.log(`${i} closing db ${r} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`)),s&&console.log(`${i} complete.`)}}f(ir,"storagePut");async function Rt({dbName:r,version:e,storeName:t,key:o,logalot:n=!1}){let s=`[${Rt.name}]`,i;try{return n&&console.log(`${s} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`),await new Promise((l,d)=>{try{n&&console.log(`${s} starting... (I: 24163c4a11c8712097db45febaf9c724)`);let b=indexedDB.open(r,e);b.onsuccess=u=>{i=u.target.result;let p;try{p=i.transaction(t).objectStore(t)}catch(g){debugger;console.error(`${s}[openDBRequest.onsuccess][objectStore] ${E(g)}`),d(g);return}let h=p.get(o);h.onsuccess=g=>{try{let m=g.target?.result?.value??void 0;if(!m){l(m);return}if(n&&console.log("Retrieved value:",m),m instanceof Uint8Array)l(ka(m));else{if(typeof m!="string")throw new Error("(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)");l(m)}}catch(m){d(m)}},h.onerror=g=>{debugger;let m=h.error;console.error(`${s}[openDBRequest.onsuccess][getRequest.onerror] ${E(m)}`),d(m)}},b.onerror=u=>{debugger;console.error(`${s}[openDBRequest.onerror] ${E(b.error)} (E: 074963a908fa9a075f01c73cae829224)`),d(b.error)}}catch(b){console.error(`${s} ${E(b)}`),d(b)}finally{n&&console.log(`${s} complete.`)}})}catch(a){throw console.error(`${s} ${E(a)}`),a}finally{i&&(n&&console.log(`${s} closing db ${r}... (I: a938fc22dfdc76b15f6926bc4d458225)`),i.close(),n&&console.log(`${s} closing db ${r} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`)),n&&console.log(`${s} complete.`)}}f(Rt,"storageGet");async function Yn({dbName:r,store:e}){let t=`[${Yn.name}]`,o;try{return ge&&console.log(`${t} starting... (I: 2b4373affa3841220f0b7ca690406624)`),(await window.indexedDB.databases()).some(i=>i.name===r)?e?await new Promise((i,a)=>{let c=indexedDB.open(r);c.onsuccess=l=>{o=l.target.result;let d=o.objectStoreNames.contains(e);i(d)},c.onerror=l=>{debugger;o=c.result;let{error:d}=l.target;console.error(`${t}[openDBRequest.onerror] ${E(c.error)} (E: c783fe607451e46c1feae3a81e0f7924)`),a(d)}}):!0:!1}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{o&&(ge&&console.log(`${t} closing db ${r}... (I: 8782d9eea285cf9eb638d493a421a625)`),o.close(),ge&&console.log(`${t} closing db ${r} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),ge&&console.log(`${t} complete.`)}}f(Yn,"storageDBExists");async function td({dbName:r,storeName:e,pathToRm:t}){let o=`[${td.name}]`,n=ge;ge&&console.log(`${o} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`);let s;return new Promise((i,a)=>{try{if(!r)throw new Error("(UNEXPECTED) dbName falsy? (E: ed336d88c9c4e8d4916b29356dc58324)");if(!e)throw new Error("(UNEXPECTED) storeName falsy? (E: ad493bb79b63a192524b14c59a706524)");if(!t)throw new Error("(UNEXPECTED) pathToRm falsy? (E: 88c9631d93467e17996946882254af24)");let c=indexedDB.open(r);c.onerror=()=>{debugger;c.result&&c.result.close(),console.error(`${o}[openDBRequest.onerror] ${E(c.error)} (E: 4c5ab71a765e61b4292008fd4fafe324)`),a(c.error)},c.onsuccess=()=>{s=c.result;let d=s.transaction(e,"readwrite").objectStore(e),b=IDBKeyRange.lowerBound(t),u=d.openCursor(b);u.onerror=()=>{debugger;console.error(`${o}[openCursorRequest.onerror] ${E(u.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),a(u.error)},u.onsuccess=()=>{try{let p=0,h=u.result;if(h)if(h.key.toString().startsWith(t)){let g=h.delete();p++,g.onerror=()=>{debugger;console.error(`${o}[deleteRequest.onerror] ${E(g.error)} (E: abc031c53e5387322cd8909b3ada9b24)`),a(g.error)},h.continue()}else ge&&console.log(`${o} rmCount: ${p} (I: e4bc613a5514c0942484b79267e16724)`),i();else ge&&console.log(`${o} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`),i()}catch(p){console.error(`${o}[openCursorRequest.onsuccess] ${E(p)}`),a(p)}}}}catch(c){debugger;console.error(`${o} ${E(c)}`),a(c)}}).finally(()=>{s&&(ge&&console.log(`${o} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),s.close(),ge&&console.log(`${o} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),ge&&console.log(`${o} complete.`),ge=n})}f(td,"storageRmRF");async function rd({dbName:r,storeName:e,dirPath:t,withFileTypes:o=!1}){let n=`[${rd.name}]`,s;try{return await new Promise((c,l)=>{let d=indexedDB.open(r);d.onerror=()=>{debugger;l(d.error)},d.onsuccess=()=>{s=d.result;let u=s.transaction(e,"readonly").objectStore(e),p=t.endsWith("/")?t:t+"/",h=IDBKeyRange.lowerBound(p),g=u.openCursor(h),m=new Set,y=[];g.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${E(g.error)}`),l(g.error)},g.onsuccess=()=>{try{let w=g.result;if(w){let T=w.key.toString();if(T.startsWith(p)&&T!==p){let A=T.substring(p.length),x=A.split("/")[0];if(o){let $=A.substring(x.length).startsWith("/");y.push({name:x,isDirectory:f(()=>$,"isDirectory"),isFile:f(()=>!$,"isFile"),isBlockDevice:f(()=>!1,"isBlockDevice"),isCharacterDevice:f(()=>!1,"isCharacterDevice"),isSymbolicLink:f(()=>!1,"isSymbolicLink"),isFIFO:f(()=>!1,"isFIFO"),isSocket:f(()=>!1,"isSocket")})}else m.add(x);w.continue()}else T.startsWith(p)?w.continue():c(o?y:Array.from(m))}else c(o?y:Array.from(m))}catch(w){console.error(`${n}[openCursorRequest.onsuccess] ${E(w)}`),l(w)}}}})}catch(i){throw console.error(`${n} ${E(i)}`),i}finally{s&&(ge&&console.log(`${n} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),s.close(),ge&&console.log(`${n} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}f(rd,"storageReaddir");var jt=Di;async function od(r){let e=`[${od.name}]`;try{jt&&console.log(`${e} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await Vn({infos:[{dbName:r.dbName,storeNames:[r.storeName,...r.additionalStoreNames??[]]}]})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{jt&&console.log(`${e} complete.`)}}f(od,"initIbGibStorage");function Fa(r){let e=`[${Fa.name}]`;try{jt&&console.log(`${e} starting... (I: 7be20d161bb14a498c44a42d3193bec1)`),globalThis.ibgib||(globalThis.ibgib={dbName_hack:r.dbName,apiKeyName_hack:r.apiKeyName,storeName_hack:r.storeName}),globalThis.ibgib.spaceGib||(globalThis.ibgib.spaceGib={version:Oi,spaceShim:{},fnDefaultGetAPIKey:f(async()=>await Rt({dbName:r.dbName,storeName:r.storeName,key:r.apiKeyName})??"","fnDefaultGetAPIKey"),dbName_hack:r.dbName,apiKeyName_hack:r.apiKeyName,storeName_hack:r.storeName})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{jt&&console.log(`${e} complete.`)}}f(Fa,"initIbGibGlobalThis");function KE(r){if(!globalThis.ibgib?.spaceGib){if(!r)throw new Error("Global context not initialized and config not provided.");Fa(r)}return globalThis.ibgib.spaceGib}f(KE,"getIbGibGlobalThis_SpaceGib");async function nd(r){let e=`[${nd.name}]`;try{jt&&console.log(`${e} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(r)).bootstrapSpaceGibApp()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{jt&&console.log(`${e} complete.`)}}f(nd,"dynamicallyLoadBootstrapScript");var ue=!1;async function Wn({timeline:r}){let e=`[${Wn.name}]`;try{if(ue&&console.log(`${e} starting...`),te({ibGib:r}))return console.warn(`${e} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`),_({ibGib:r});{let t=ie({gib:r.gib}),o=t.tjpGib??t.punctiliarHash;if(!o)throw new Error(`${e} (UNEXPECTED) Could not determine tjpGib or punctiliarHash from ibGib. (E: eb3b6472e9b335991a1b0869f772f7d3)`);return o}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ue&&console.log(`${e} complete.`)}}f(Wn,"getLockScope");async function sd({timeline:r,rel8nInfos:e,rel8nRemovalInfos:t,timelineIndexInfo:o,metaspace:n,space:s,skipLock:i,noDna:a}){let c=`[${sd.name}]`;try{if(ue&&console.log(`${c} starting... (I: fcdff10832215068019355265f4cbc25)`),s??=await n.getLocalUserSpace({lock:!1}),!s)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)");let l=await Wn({timeline:r}),d=f(async()=>{if(!s)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let u=_({ibGib:r}),p=await n.getLatestAddr({addr:u,space:s});if(!p)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${_({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let h=ke({ibGib:r});if(u!==p){let T=await n.get({addrs:[p],space:s});if(T.errorMsg||(T.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${p}) from space (${s.ib}). errorMsg: ${T.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);h=T.ibGibs.at(0)}let g;if(t&&t.length>0){g={};for(let T of t){let{rel8nName:A,ibGibAddrs:x}=T;if(x.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${A}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}g[A]||(g[A]=[]),g[A]=g[A].concat(x)}}let m={};for(let T of e){let{rel8nName:A,ibGibs:x}=T;if(x.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${A}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}m[A]||(m[A]=[]),m[A].push(...x.map($=>_({ibGib:$})))}let y=await Ie({src:h,rel8nsToRemoveByAddr:g,rel8nsToAddByAddr:m,dna:!a,nCounter:!0}),w=y.newIbGib;return await n.persistTransformResult({resTransform:y,space:s}),o&&await zn({type:o.type,rel8nInfos:[{rel8nName:o.rel8nName,ibGibs:[w]}],metaspace:n,space:s,skipLock:i}),await n.registerNewIbGib({ibGib:w,space:s}),w},"fn");return i?await d():await Ge({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:s,callerInstanceId:we(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{ue&&console.log(`${c} complete.`)}}f(sd,"appendToTimeline");async function zn({type:r,rel8nInfos:e,dataToAddOrPatch:t,metaspace:o,space:n,skipLock:s}){let i=`[${zn.name}]`;try{if(ue&&console.log(`${i} starting... (I: 6e7d05fe916d813b71766e2eaa747c25)`),r==="latest")throw new Error('cannot update the "latest" special index by this function. The registerNewIbGib will do this automatically. (E: 231eb78a221ccdbcf56cd1899260a425)');if(n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 43067821a4749a7648fe2612d25d7f25)");let a=f(async()=>{let c=f(async()=>{let l=await o.getSpecialIbGib({type:r,space:n,initialize:!0});if(!l)throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${r}. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);return l.rel8ns||console.warn(`${i} 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 e??[]){let{rel8nName:d,ibGibs:b}=l;b.length===0&&console.error(`${i} ibGibs empty. skipping rel8nName (${d}). (E: 150d74f73f97aea1b97d173d92c77125)`);let p=(await c()).rel8ns??{},h,g=p[d]??[];if(g.length>0){let m=new Set;b.forEach(y=>{let w=_({ibGib:y}),T=y.rel8ns?.past??[];g.filter(A=>[...T,w].includes(A)).forEach(A=>m.add(A))}),m.size>0&&(h=Array.from(m))}await o.rel8ToSpecialIbGib({type:r,rel8nName:d,ibGibsToRel8:b,addrsToUnRel8:h,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(t??{}).length>0){let l=await c(),d=await je({src:l,dataToAddOrPatch:t,dna:!1,linkedRel8ns:[Y.past],nCounter:!0}),b=d.newIbGib;await re({resTransform:d,space:n});let u=oe({type:r});await o.setConfigAddr({key:u,addr:_({ibGib:b}),space:n}),await o.registerNewIbGib({ibGib:b,space:n})}},"fn");s?await a():await Ge({scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:a})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{ue&&console.log(`${i} complete.`)}}f(zn,"updateSpecialIndex");async function Jn({timeline:r,timelineAddr:e,metaspace:t,space:o}){let n=`[${Jn.name}]`;try{if(ue&&console.log(`${n} starting... (I: f2b605361368e1956f6db878dbfeb825)`),!r&&!e)throw new Error("either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)");e??=_({ibGib:r});let s=await t.getLatestAddr({addr:e,space:o})??e;if(!s)throw new Error(`${n} (UNEXPECTED) Could not get latest address for timeline ${_({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let i;if(e===s){if(!r){let a=await t.get({addrs:[s],space:o});if(a.errorMsg||(a.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${s}) from space (${o.ib}). errorMsg: ${a.errorMsg??"[unknown error]"} (E: 3fc767a594788a43a4ba18c87491a825)`);r=a.ibGibs.at(0)}i=ke({ibGib:r})}else{let a=await t.get({addrs:[s],space:o});if(a.errorMsg||(a.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${s}) from space (${o.ib}). errorMsg: ${a.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);i=a.ibGibs.at(0)}return i}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{ue&&console.log(`${n} complete.`)}}f(Jn,"getLatestTimelineIbGibDto_nonLocking");async function id({timeline:r,timelineAddr:e,mut8Opts:t,metaspace:o,space:n,skipLock:s,timelineIndexInfo:i,noDna:a}){let c=`[${id.name}]`;try{if(ue&&console.log(`${c} starting... (I: genuuid)`),!r&&!e)throw new Error("(UNEXPECTED) both timeline and timelineAddr falsy? either one is required. (E: a19d98c6acb87af3b876c1484f6ac825)");if(n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: genuuid)");if(!r){let u=await o.get({addrs:[e],space:n});if(!u.success||u.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${e}) in space (${n?.ib??"undefined"}) (E: genuuid)`);r=u.ibGibs.at(0)}let l=await Wn({timeline:r}),d=f(async()=>{if(!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");if(!r)throw new Error("(UNEXPECTED) timeline falsy? we should be ensured that it's truthy at this point. (E: 2e1758b2cc3820531f7ac7f5f6b3a825)");let u=await Jn({timeline:r,metaspace:o,space:n}),p=await je({...t,src:u,dna:!a,nCounter:!0}),h=p.newIbGib;return await o.persistTransformResult({resTransform:p,space:n}),i&&await zn({type:i.type,rel8nInfos:[{rel8nName:i.rel8nName,ibGibs:[h]}],metaspace:o,space:n,skipLock:s}),await o.registerNewIbGib({ibGib:h,space:n}),h},"fn");return s?await d():await Ge({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:we(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{ue&&console.log(`${c} complete.`)}}f(id,"mut8Timeline");async function ad({ib:r,data:e,rel8ns:t,noDna:o,parentIb:n,parentIbGib:s,metaspace:i,space:a}){let c=`[${ad.name}]`;try{if(ue&&console.log(`${c} starting...`),a??=await i.getLocalUserSpace({lock:!1}),!a)throw new Error("(UNEXPECTED) space is required, but is falsy. (E: 252994a554224b17aa9816c7a765c925)");s??=n?s=B.primitive({ib:n}):s=z;let l=await B.firstGen({parentIbGib:s,ib:r,data:e,rel8ns:t,dna:!o,nCounter:!0,squash:!!o,tjp:{timestamp:!0,uuid:!e?.uuid}});return await i.persistTransformResult({resTransform:l,space:a}),await i.registerNewIbGib({ibGib:l.newIbGib,space:a}),l}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(ad,"createTimeline");async function qa({ibGib:r,metaspace:e,space:t}){let o=`[${qa.name}]`;try{if(ue&&console.log(`${o} starting...`),t??=await e.getLocalUserSpace({lock:!1}),!t)throw new Error("(UNEXPECTED) space is required. (E: c1b9a9b8c7d6e5f4a3b2a1a0b9c8d7e6)");let n=r.rel8ns?.dna??[];if(n.length===0)return[];let s=await e.get({addrs:n,space:t});if(!s.success||(s.ibGibs??[]).length!==n.length){let i=n.filter(a=>!s.ibGibs?.some(c=>_({ibGib:c})===a));throw new Error(`Could not get all dna ibGibs for ${_({ibGib:r})}. Addrs not found: ${i.join(", ")}. Errors: ${s.errorMsg??"[unknown error (E: 92cf95774828d8a978331da859098625)]"} (E: d2c0b1a9a8b7c6d5e4f3a2b1a0b9c8d7)`)}return s.ibGibs}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(qa,"getDna");async function Ha({timeline:r,getLatest:e,includeDna:t,metaspace:o,space:n}){let s=`[${Ha.name}]`;try{if(ue&&console.log(`${s} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: e3d1c0b1a9a8b7c6d5e4f3a2b1a0b9c8)");let i=e?await Jn({timeline:r,metaspace:o,space:n}):ke({ibGib:r}),a=_({ibGib:i}),c={},l=t?no({ibGibs:await qa({ibGib:i,metaspace:o,space:n})}):void 0,d=r.rel8ns?.past??[];if(d.length===0)return{headIbGib:i,orderedPastIbGibs:[],pastIbGibMap:c,dnaMap:l};let b=await o.get({addrs:d,space:n});if(!b.success||(b.ibGibs??[]).length!==d.length){let p=d.filter(h=>!b.ibGibs?.some(g=>_({ibGib:g})===h));throw new Error(`Could not get all dna ibGibs for ${a}. Addrs not found: ${p.join(", ")}. Errors: ${b.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=no({ibGibs:b.ibGibs})??{};let u=[];for(let p of d){let h=c[p];if(!h)throw new Error("(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)");u.push(h)}return{headIbGib:i,orderedPastIbGibs:u,pastIbGibMap:c,dnaMap:l}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{ue&&console.log(`${s} complete.`)}}f(Ha,"getHistory");async function cd({timeline:r,getLatest:e,metaspace:t,space:o}){let n=`[${cd.name}]`;try{return ue&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await Ha({timeline:r,getLatest:e,includeDna:!1,metaspace:t,space:o})).orderedPastIbGibs.map(a=>_({ibGib:a}))}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{ue&&console.log(`${n} complete.`)}}f(cd,"getHistoryAddrs");var st=!1,Zn=class r{static{f(this,"IbGibApiBridge")}lc=`[${r.name}]`;async parseResponseJson(e,t){let o=e.headers.get("content-type")||"";if(!o.includes("application/json")){let n=await e.text();throw n.trim().toLowerCase().startsWith("<!doctype html")||n.includes("<html")?new Error(`API request to '${t}' failed (${e.status} ${e.statusText}): Received HTML fallback instead of JSON. Check API route matching and parameters.`):new Error(`API request to '${t}' failed (${e.status} ${e.statusText}): Returned non-JSON content type '${o}': ${n.slice(0,150)}`)}return await e.json()}async postGenesisKeystone(e){let t=`${this.lc}[${this.postGenesisKeystone.name}]`;try{st&&console.log(`${t} starting... (I: eecd082fc4a4381c8857928e8b090826)`);let o="/api/keystone/genesis",n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e})}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Unknown error";return console.error(`${t} server rejected genesis keystone: ${i}`),{success:!1,message:i,addr:s.addr,statusCode:n.status}}return st&&console.log(`${t} genesis keystone posted successfully. pending: ${s.pending}`),{success:!0,pending:!!s.pending,statusCode:n.status,addr:s.addr,message:s.message}}catch(o){let n=E(o);return console.error(`${t} error: ${n}`),{success:!1,message:n}}}async putEvolveKeystone({domainAddr:e,keystoneIbGib:t,relatedKeystoneIbGibs:o=[],revokeTokens:n}){let s=`${this.lc}[${this.putEvolveKeystone.name}]`;try{st&&console.log(`${s} posting evolved keystone...`);let i=`/api/keystone/evolve/${encodeURIComponent(e)}`,a=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t,relatedKeystoneIbGibs:o,revokeTokens:n})}),c=await this.parseResponseJson(a,i);if(!a.ok){let l=c.message||c.error||"Unknown error";return console.error(`${s} server rejected keystone evolution: ${l}`),{success:!1,message:l}}return st&&console.log(`${s} keystone evolution accepted by server.`),{success:!0}}catch(i){let a=E(i);return console.error(`${s} fetch error: ${a}`),{success:!1,message:a}}}async lookupPrimaryKeystone({identifier:e}){let t=`${this.lc}[${this.lookupPrimaryKeystone.name}]`;try{let o="/api/keystone/lookup",n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:e})}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Identity not found";return console.error(`${t} server lookup failed: ${i}`),{success:!1,message:i}}return{success:!0,tjpAddr:s.tjpAddr,primaryKeystoneIbGib:s.primaryKeystoneIbGib}}catch(o){let n=E(o);return console.error(`${t} lookup fetch error: ${n}`),{success:!1,message:n}}}async checkEmailAvailability({email:e}){let t=`${this.lc}[${this.checkEmailAvailability.name}]`;try{let o=`/api/keystone/check-email?email=${encodeURIComponent(e)}`,n=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json"}}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Server check failed";return console.error(`${t} email check failed: ${i}`),{available:!1,message:i}}return{available:s.available??!0,message:s.message}}catch(o){let n=E(o);return console.error(`${t} check email error: ${n}`),{available:!0}}}async getKeystoneGraph(e){let t=`${this.lc}[${this.getKeystoneGraph.name}]`;try{st&&console.log(`${t} fetching keystone graph...`);let o=`/api/keystone/${encodeURIComponent(e)}?getLatest=true&getGraph=true`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json"}}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Unknown error";return console.error(`${t} server rejected keystone graph get: ${i}`),{success:!1,message:i}}return{success:!0,graph:s.domainGraph}}catch(o){let n=E(o);return console.error(`${t} fetch error: ${n}`),{success:!1,message:n}}}async getIbGib(e,t,o=!1){let n=`${this.lc}[${this.getIbGib.name}]`;try{st&&console.log(`${n} fetching single ibGib frame...`);let s=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=false`,i=await fetch(s,{method:"GET",headers:{Accept:"application/json"}}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"Unknown error";return console.error(`${n} server rejected ibGib get: ${c}`),{success:!1,message:c}}return{success:!0,ibGib:a}}catch(s){let i=E(s);return console.error(`${n} fetch error: ${i}`),{success:!1,message:i}}}async getIbGibGraph(e,t,o=!1){let n=`${this.lc}[${this.getIbGibGraph.name}]`;try{st&&console.log(`${n} fetching ibGib graph...`);let s=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=true`,i=await fetch(s,{method:"GET",headers:{Accept:"application/json"}}),a=await i.json();if(!i.ok){let c=a.message||a.error||"Unknown error";return console.error(`${n} server rejected ibGib graph get: ${c}`),{success:!1,message:c}}return{success:!0,graph:a.graph,addr:a.addr}}catch(s){let i=E(s);return console.error(`${n} fetch error: ${i}`),{success:!1,message:i}}}async postVerificationCode({email:e,primaryTjpAddr:t}){let o=`${this.lc}[${this.postVerificationCode.name}]`;try{let n="/api/email/verification-code",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,primaryTjpAddr:t})}),i=await this.parseResponseJson(s,n);if(!s.ok){let a=i.message||i.error||"Verification code request failed";return console.error(`${o} server verification code post failed: ${a}`),{success:!1,message:a}}return{success:!0,message:i.message}}catch(n){let s=E(n);return console.error(`${o} post verification code error: ${s}`),{success:!1,message:s}}}async postMagicLink(e){return this.postVerificationCode(e)}async postVerifyCode({email:e,primaryTjpAddr:t,code:o}){let n=`${this.lc}[${this.postVerifyCode.name}]`;try{let s="/api/email/verify-code",i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,primaryTjpAddr:t,code:o})}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"Code verification failed";return console.error(`${n} server verify-code failed: ${c}`),{success:!1,message:c}}return st&&console.log(`${n} verification code accepted.`),{success:!0,message:a.message}}catch(s){let i=E(s);return console.error(`${n} fetch error: ${i}`),{success:!1,message:i}}}async postCustodianGenesis({email:e,code:t,username:o}){let n=`${this.lc}[${this.postCustodianGenesis.name}]`;try{let s="/api/identity/custodian/genesis",i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,code:t,username:o})}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"Custodian genesis failed";return console.error(`${n} custodian genesis failed: ${c}`),{success:!1,message:c}}return{success:!0,isNewIdentity:!!a.isNewIdentity,primaryTjpAddr:a.primaryTjpAddr,primaryKeystone:a.primaryKeystone,primaryGraph:a.primaryGraph,custodianReqs:a.custodianReqs,message:a.message}}catch(s){let i=E(s);return console.error(`${n} post custodian genesis error: ${i}`),{success:!1,message:i}}}async postCustodianRegisterDelegate({delegateKeystone:e}){let t=`${this.lc}[${this.postCustodianRegisterDelegate.name}]`;try{let o="/api/identity/custodian/register-delegate",n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({delegateKeystone:e})}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Custodian delegate registration failed";return console.error(`${t} custodian delegate registration failed: ${i}`),{success:!1,message:i}}return{success:!0,primaryTjpAddr:s.primaryTjpAddr,evolvedPrimaryKeystone:s.evolvedPrimaryKeystone,primaryGraph:s.primaryGraph,message:s.message}}catch(o){let n=E(o);return console.error(`${t} post custodian register delegate error: ${n}`),{success:!1,message:n}}}async getSsoConfig(){let e=`${this.lc}[${this.getSsoConfig.name}]`;try{let t="/api/identity/sso/config",o=await fetch(t,{method:"GET"}),n=await this.parseResponseJson(o,t);return o.ok?{success:!0,providers:n.providers}:{success:!1,message:n.message||n.error||"Failed to fetch SSO config"}}catch(t){let o=E(t);return console.error(`${e} fetch SSO config error: ${o}`),{success:!1,message:o}}}async postSsoLogin({code:e,providerId:t,redirectUri:o}){let n=`${this.lc}[${this.postSsoLogin.name}]`;try{let s="/api/identity/sso/login",i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,providerId:t,redirectUri:o})}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"SSO login code exchange failed";return console.error(`${n} SSO login code exchange failed: ${c}`),{success:!1,message:c}}return{success:!0,isNewIdentity:!!a.isNewIdentity,primaryTjpAddr:a.primaryTjpAddr,primaryKeystone:a.primaryKeystone,primaryGraph:a.primaryGraph,custodianReqs:a.custodianReqs,userInfo:a.userInfo,message:a.message}}catch(s){let i=E(s);return console.error(`${n} post SSO login error: ${i}`),{success:!1,message:i}}}},go;function lw(){return go||(go=new Zn),go}f(lw,"getApiBridge");function dw(r){go=r}f(dw,"setApiBridge");var Ka=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var it=!1;function Xa({rawMsg:r}){let e=`[${Xa.name}]`;try{it&&console.log(`${e} starting...`);let t=Qn({rawMsg:r}),o=t.body.replace(/\s/g,"_").replace(/\W/g,""),n;if(o.length>20)n=o.substring(0,20);else if(o.length>0)n=o;else throw new Error("(UNEXPECTED) error msg should have characters/alphanumerics... (E: a3b9cd11a44cc7892a748819c2885422)");return`error ${n} ${t.uuid??"undefined"}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{it&&console.log(`${e} complete.`)}}f(Xa,"getErrorIb");function Qn({rawMsg:r}){let e=`[${Qn.name}]`;try{if(it&&console.log(`${e} starting...`),!r)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let t,o=r.match(hs);if(o){let[n,s,i,a,c,l]=o;if(!a)throw new Error("invalid error msg body (E: a675e6855cca96519d33d44ea5400922)");t={success:!1,raw:r,body:a?.trim(),uuid:c.slice(4,36)},s&&(t.location=s),(i||l)&&(t.unexpected=!0)}else{t={success:!1,raw:r,body:r};let n=r.match(gs);if(n){let[s,i]=n;t.location=i}r.toLowerCase().includes("(unexpected)")&&(t.unexpected=!0)}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{it&&console.log(`${e} complete.`)}}f(Qn,"parseRawErrorMsg");function It({rawMsg:r}){let e=`[${It.name}]`;try{return it&&console.log(`${e} starting...`),xe({parentPrimitiveIb:"error",ib:Xa({rawMsg:r}),data:Qn({rawMsg:r}),ibRegExpPattern:Ka.source})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{it&&console.log(`${e} complete.`)}}f(It,"getErrorIbGib");function Ye({ibGib:r}){let e=`[${Ye.name}]`;try{if(it&&console.log(`${e} starting...`),!r)throw new Error("ibGib required (E: 1d756fbbd96f1734b97ba013537ed522)");return r.ib.startsWith("error ")}catch(t){throw console.error(`${e} ${t.message}`),t}finally{it&&console.log(`${e} complete.`)}}f(Ye,"isError");var at=!1;function Ya(r){let e=`[${Ya.name}]`;try{let t=r?`${tr} ${r}`:tr;return at&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Ya,"getArgIb");function ld({ib:r,ibGib:e}){let t=`[${ld.name}]`;try{if(at&&console.log(`${t} starting...`),!r)if(e)r=e.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return r.startsWith(tr)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{at&&console.log(`${t} complete.`)}}f(ld,"isArg");function Wa(r){let e=`[${Wa.name}]`;try{let t=r?`${Br} ${r}`:Br;return at&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Wa,"getResultIb");async function _t({argData:r,ibMetadata:e,noTimestamp:t}){let o=`[${_t.name}]`;try{let n=await B.firstGen({ib:Ya(e),parentIbGib:B.primitive({ib:tr}),data:r,dna:!1,noTimestamp:t});if(n.newIbGib){let{newIbGib:s}=n;return s.rel8ns.past=[],s.gib=await ze(s),s}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(_t,"argy_");async function Tt({resultData:r,ibMetadata:e,noTimestamp:t}){let o=`[${Tt.name}]`;try{let n=await B.firstGen({ib:Wa(e),parentIbGib:B.primitive({ib:Br}),data:r,dna:!1,noTimestamp:t});if(n?.newIbGib){let{newIbGib:s}=n;return s.rel8ns.past=[],s.gib=await ze(s),s}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Tt,"resulty_");function es({ibGib:r}){let e=`[${es.name}]`;try{if(at&&console.log(`${e} starting...`),!r)throw new Error("ibGib required (E: e11cee2a6c59a5e7a4d39ea55751c423)");if(!r.data)return!1;let t=r.data;return t.cmd&&typeof t.cmd=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{at&&console.log(`${e} complete.`)}}f(es,"isCommand");function ts({ibGib:r}){let e=`[${ts.name}]`;try{return at&&console.log(`${e} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof r.witness=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{at&&console.log(`${e} complete.`)}}f(ts,"isWitness");var mo="subject",rs=/^[a-zA-Z0-9_\-.]{1,255}$/,za="subject",Ja="",Eo="subject is a cool ibgib witness that has seriously fascinating behavior.";var Za="observable";var ct={subscribe:"subscribe"},Qa=Object.values(ct);var ec={next:"next",error:"error",complete:"complete"};var lt={...ct,...ec};var mr={version:"1",uuid:Ja,name:za,description:Eo,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},os=void 0;var wo=class r{static{f(this,"WitnessFactoryBase")}lc=`[${r.name}]`};var ns=!1,Bt=class r extends wo{static{f(this,"DynamicFormFactoryBase")}lc=`[${r.name}]`;patchDataFromItems({data:e,contextPath:t,items:o,pathDelimiter:n}){let s=`${this.lc}[${this.patchDataFromItems.name}]`;try{if(ns&&console.log(`${s} starting...`),!n)throw new Error("pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)");for(let i=0;i<o.length;i++){let a=o[i],c=t?t+n+a.name:a.name;if(!a.items)Bo({obj:e,value:a.value,path:c,logalot:ns,pathDelimiter:n});else if(a.items.length>0)this.patchDataFromItems({data:e,contextPath:c,items:a.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(i){throw console.error(`${s} ${i.message}`),i}finally{ns&&console.log(`${s} complete.`)}}};var tc=!1,Ft=class r{static{f(this,"LightWitnessBase_V1")}lc=`[${r.name}]`;instanceId="";ib="";gib;data;rel8ns;initialized;_isInitialized=!1;constructor(e,t){e&&(this.data=e),t&&(this.rel8ns=t),this.initialized=this.initialize().then(()=>{this._isInitialized=!0})}async initialize(){this.instanceId=await j(),this.gib=await K({ibGib:this.toIbGibDto()})}toIbGibDto(){return ke({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return tc&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=C(e.ib),this.gib=C(e.gib),e.data?this.data=C(e.data):delete this.data,e.rel8ns?this.rel8ns=C(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{tc&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`,t=[];try{this.ib||t.push("this.ib is falsy."),this.gib||t.push("this.gib is falsy.")}catch(o){throw console.error(`${e} ${o.message}`),o}return t}};var rc="subscription",ss=/^[a-zA-Z0-9_\-.]{1,255}$/,oc="",nc="subscription",$o="subscription is a cool ibgib witness that has seriously fascinating behavior.";var Er={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var is={version:"1",uuid:oc,name:nc,description:$o,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},as=void 0;var sc=!1;function cs({ibGib:r}){let e=`[${cs.name}]`;try{sc&&console.log(`${e} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:t}=r;return[Za,mo].some(n=>t.includes(n))}catch(t){throw console.error(`${e} ${t.message}`),t}finally{sc&&console.log(`${e} complete.`)}}f(cs,"isObservable");var k=!1,yo=class r extends Ft{static{f(this,"Subscription_V1")}lc=`[${r.name}]`;metaspace;_subscribed;_unsubscribed;_srcObservable;constructor(e,t){super(e,t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{if(k&&console.log(`${e} starting... (I: 8097612cda5f43e5b38249d057b65b1e)`),await super.initialize(),!this.data)throw new Error("this.data required (E: 1af73af2d17a48ada42596ad395fd99c)");this.data.uuid=this.instanceId,this.ib=_o({data:this.data,classname:"Subscription_V1"}),this.gib=await K({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{k&&console.log(`${e} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:o}=e;if(!o)throw new Error("arg.ib required (E: 1fd9aebef07b4bdaacc0cd323c8ddf76)");if(k&&console.log(`${t} ib: ${o} (I: 4de7771f477dc5b36933343b694ce223)`),o===Er.unsubscribe)return k&&console.log(`${t} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(o===Er.unsubscribed)return k&&console.log(`${t} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if(cs({ibGib:e}))return k&&console.log(`${t} routing observerable (I: 165b422cda9ec3052312243dc965cf23)`),this.witness_observable({ibGib:e});throw new Error("unknown arg. expect unsubscribe/unsubscribed primitive ibgib or Observable ibgib. (E: 132dc7cd8f7c4afc9ec4651e2c559c74)")}catch(o){throw console.error(`${t} ${E(o)??"unknown error (E: b0bbaab21833404a9420c3d273df7f21)"}`),o}}async witness_unsubscribe(){let e=`${this.lc}[${this.witness_unsubscribe.name}]`;try{if(k&&console.log(`${e} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${e} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),z;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),z;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return k&&(console.log(`${e} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),k&&(console.log(`${e} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,k&&console.log(`${e} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),z}catch(t){throw console.error(`${e} ${t.message}`),t}finally{k&&console.log(`${e} complete.`)}}async witness_observable({ibGib:e}){let t=`${this.lc}[${this.witness_observable.name}]`;try{if(k&&console.log(`${t} 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=e,k&&console.log(`${t} this._srcObservable set to ibgib with ib: ${e.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{k&&console.log(`${t} complete.`)}}async witness_unsubscribed(){let e=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(k&&console.log(`${e} 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 t=this._unsubscribed===!0?Zo:Bs;return k&&console.log(`${e} result: ${H(t)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{k&&console.log(`${e} complete.`)}}async unsubscribe(){let e=`${this.lc}[${this.unsubscribe.name}]`;try{k&&console.log(`${e} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let t=await this.witness(B.primitive({ib:Er.unsubscribe}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(Ye({ibGib:t})){let o=t;throw new Error(`${o.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{k&&console.log(`${e} complete.`)}}async unsubscribed(){let e=`${this.lc}[${this.unsubscribed.name}]`;try{k&&console.log(`${e} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let t=await this.witness(B.primitive({ib:Er.unsubscribed}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let o=t.ib===Zo.ib;return k&&console.log(`${e} resUnsubscribed: ${o} (I: b4800166c58d5ba2ca1dccaa53de2323)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{k&&console.log(`${e} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return k&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{k&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let s=await _t({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}async resulty({resultData:e,ibGibs:t}){let o=await Tt({resultData:e});return t&&(o.ibGibs=t),o}},Io=class r extends Bt{static{f(this,"Subscription_V1_Factory")}lc=`[${r.name}]`;getName(){return yo.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{k&&console.log(`${o} starting...`),e??=C(is),e=e,t=t??as?C(as):void 0,e.uuid||=await j();let{classname:n}=e,s=_o({data:e}),i=await xe({parentPrimitiveIb:`witness ${n}`,ib:s,data:e,rel8ns:t}),a=new yo(void 0,void 0);return await a.loadIbGibDto(i),k&&console.log(`${o} witnessDto: ${H(i)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:a}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{k&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{k&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");k&&console.log(`${t} data: ${H(o)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await Ht({n:100}),s=new To().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??$o}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"subscription"});return Promise.resolve(s)}catch(o){throw console.error(`${t} ${E({error:o})}`),o}finally{k&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=C(is);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:xt}),await this.newUp({data:t})}};var Ao=!1;function ic({data:r}){let e=`[${ic.name}]`;try{if(Ao&&console.log(`${e} starting...`),!r)throw new Error("Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)");let t=[],{name:o,uuid:n,classname:s}=r;return o?o.match(ss)||t.push(`name must match regexp: ${ss} (E: 21bf77e398d47e9d035376510505eda2)`):t.push("name required."),n?n.match(Q)||t.push(`uuid must match regexp: ${Q} (E: e53fd08ae69e945b37ed895b864b6bd7)`):t.push("uuid required."),s&&(s.match(We)||t.push(`classname must match regexp: ${We}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ao&&console.log(`${e} complete.`)}}f(ic,"validateCommonSubscriptionData");function _o({data:r,classname:e}){let t=`[${_o.name}]`;try{let o=ic({data:r});if(o.length>0)throw new Error(`invalid Subscription data: ${o} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`);if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)")}else if(e=r.classname,!e)throw new Error("classname required (E: 040c1fd71853fa7874146999afb355c3)");let{uuid:n}=r;return`witness ${rc} ${e} ${n}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(_o,"getSubscriptionIb");var To=class r extends tt{static{f(this,"SubscriptionFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subscription"}};function So({ibGib:r}){let e=`[${So.name}]`;try{if(Ao&&console.log(`${e} starting... (I: 43df7e7f61f25e65662ce8aa5a105a23)`),!r)return!1;let t=r;return typeof t.witness=="function"&&typeof t.unsubscribe=="function"&&typeof t.unsubscribed=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ao&&console.log(`${e} complete.`)}}f(So,"isSubscription");async function ac(){return(await new Io().newUp({})).newIbGib}f(ac,"newupSubscription");var ls="observable_event";var cc=!1;async function ds({eventType:r,srcObservable:e,payload:t}){let o=`[${ds.name}]`;try{if(cc&&console.log(`${o} starting... (I: e2290f2f46d1993d6893a24c19100823)`),!e)throw new Error("srcObservable required (E: 3470a97bbf3802cbc8dd64339f5ef623)");if(!e.data)throw new Error("srcObservable.data required (E: df1786585ba849c08e7f4f1fddd30a31)");if(!e.data.uuid)throw new Error("srcObservable.data.uuid required (E: 173a1a53f274bc1cef879bad2288ca23)");if(!e.data.uuid.match(Q))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${Q.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await j(),eventType:r,srcObservableId:e.data.uuid,"@srcObservableAddr":_({ibGib:e}),"@payloadAddr":_({ibGib:t})};return await xe({parentPrimitiveIb:ls,ib:lc({data:n}),data:n})}catch(n){throw console.error(`${o} ${n.message}`),n}finally{cc&&console.log(`${o} complete.`)}}f(ds,"getObservableEventIbGib");function lc({data:r,classname:e}){let t=`[${lc.name}]`;try{if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match data.classname (E: 523aabc53fb944789202a5f468abd338)")}else if(e=r.classname,!e)throw new Error("classname required (E: d4401ea682894c5fa824b38d4989aa76)");if(!r.uuid)throw new Error("data.uuid required (E: 204cc7c20efd8a55263cdea8b1223e23)");return`${ls} ${e} ${r.uuid}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(lc,"getObservableEventIb");var W=!1,xo=class r extends Ft{static{f(this,"ObservableBase_V1")}lc=`[${r.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(e,t){super(e,t)}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:o}=e;if(!o)throw new Error("arg.ib required (E: 87659d093b82436ce2f7a87e402a5423)");if(es({ibGib:e}))return this.witness_cmd({arg:e});if(ts({ibGib:e}))return this.witness_otherWitness({arg:e});throw new Error("unknown arg. expect observable cmd or ibgib witness (E: dc2667cffac5b8d7b1bf2ea737c81a23)")}catch(o){throw console.error(`${t} ${E(o)??"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),o}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{if(W&&console.log(`${t} starting... (I: 69257fac8328b9de9755fdd237b92723)`),e.data.cmd===ct.subscribe)return this.witness_subscribe_cmd({ibGib:e});throw new Error(`unknown command. must be of type ObservableCmd (${Qa}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{W&&console.log(`${t} complete.`)}}async witness_otherWitness({arg:e}){let t=`${this.lc}[${this.witness_otherWitness.name}]`;try{return W&&console.log(`${t} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),So({ibGib:e})?this.witness_subscriptionIbGib({arg:e}):this.witness_subscribe_nonCmdWitness({arg:e})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{W&&console.log(`${t} complete.`)}}async witness_subscriptionIbGib({arg:e}){let t=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(W&&console.log(`${t} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`),!e.data)throw new Error("arg.data required (E: 764ae772727ceba95a18140fdd938323)");let o=this.getSubscriberKey({subscription:e}),[n,s]=this._subscribers[o];if(e===n)delete this._subscribers[o];else throw new Error("(UNEXPECTED) arg and subscription are two different instances? (E: aab5ef9bdc92abb9e816e2c443ab5723)");return z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{W&&console.log(`${t} complete.`)}}async replayPastPayloads({observer:e,subscription:t}){let o=`${this.lc}[${this.replayPastPayloads.name}]`;try{W&&console.log(`${o} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`);let n=this.getSubscriberKey({subscription:t}),s=f(()=>!!this._subscribers[n],"fnStillSubscribed"),i=-1,a=!0;do if(i++,i<this._pastPayloads.length){if(!s()){W&&console.log(`${o} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`);return}try{let c=this._pastPayloads[i];await e.next(c)}catch{console.error(`${o} observer errored on payload (i: ${i}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`);return}}else a=!1;while(a);if(this.isErrored&&e.error&&s())try{await e.error(this._pastError)}catch{console.error(`${o} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`)}else if(this.isComplete&&e.complete&&s())try{await e.complete()}catch{console.error(`${o} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{W&&console.log(`${o} complete.`)}}async witness_subscribe_cmd({ibGib:e}){let t=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(W&&console.log(`${t} starting... (I: 0c4c75c3fae297af6449c1048ce55423)`),(e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one ObserverWitness (E: 3ed99b32e22284573c497df788a9f923)");let o=e.ibGibs[0],n=await ac();return W&&console.log(`${t} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,W&&console.log(`${t} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,o],W&&console.log(`${t} stored subscriber (subscription, observer) (I: fb09660d885e33b80188dd0386ffc723)`),this.data.replay&&this._pastPayloads.length>0&&this.replayPastPayloads({observer:o,subscription:n}),n}catch(o){throw console.error(`${t} ${o.message}`),o}finally{W&&console.log(`${t} complete.`)}}async witness_subscribe_nonCmdWitness({arg:e}){let t=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw W&&console.log(`${t} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(o){throw console.error(`${t} ${o.message}`),o}finally{W&&console.log(`${t} complete.`)}}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{W&&console.log(`${t} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let o;if(At({ibGib:e})){let n=await this.argy({argData:{cmd:ct.subscribe,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});o=await this.witness(n)}else o=await this.witness(e);if(!So({ibGib:o}))throw new Error("(UNEXPECTED) resSubscription is not a SubscriptionWitness? (E: c29bec4e3a48d6f1299143399ac55a23)");return o}catch(o){throw console.error(`${t} ${o.message}`),o}finally{W&&console.log(`${t} complete.`)}}getSubscriberKey({subscription:e}){if(e.data?.uuid)return e.data.uuid;throw new Error("(UNEXPECTED) subscription.data.uuid falsy? (E: 8d078e6f8155f7567fd9378557e91823)")}async dispatchToEachSubscriber({payload:e,fnForObserver:t,observableEventType:o}){let n=`${this.lc}[${this.dispatchToEachSubscriber.name}]`;try{W&&console.log(`${n} starting... (I: 0b990ce892f689d14458565717e66a23)`);let s=Object.values(this._subscribers);for(let i=0;i<s.length;i++){let[a,c]=s[i];if(At({ibGib:c})){let l=c;await t(l,e),l.complete?await a.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():W&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let l=await ds({eventType:o,srcObservable:this,payload:e});await c.witness(l)}}}catch(s){throw console.error(`${n} ${s.message}`),s}finally{W&&console.log(`${n} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return W&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{W&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let s=await _t({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}async resulty({resultData:e,ibGibs:t}){let o=await Tt({resultData:e});return t&&(o.ibGibs=t),o}};var M=!1,Go=class r extends xo{static{f(this,"Subject_V1")}lc=`[${r.name}]`;constructor(e,t){super(e,t)}asObservable(){return this}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{M&&console.log(`${t} starting... (I: 8e47b752314870ec78eb14342621f723)`);let o=await this.argy({argData:{cmd:lt.subscribe,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});return await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async next(e){let t=`${this.lc}[${this.next.name}]`;try{M&&console.log(`${t} starting... (I: b30363827c56450ca918c69aa15b0046)`);let o=await this.argy({argData:{cmd:lt.next,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async error(e){let t=`${this.lc}[${this.error.name}]`;try{M&&console.log(`${t} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let o;if(typeof e=="string")o=await It({rawMsg:e});else if(e instanceof Error||typeof e.message=="string")o=await It({rawMsg:E(e)});else if(e.ib&&Ye({ibGib:e}))o=e;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:lt.error,ibGibAddrs:[_({ibGib:o})]},ibGibs:[o]});await this.witness(n)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async complete(){let e=`${this.lc}[${this.complete.name}]`;try{M&&console.log(`${e} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let t=await this.argy({argData:{cmd:lt.complete}});await this.witness(t)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{M&&console.log(`${e} complete.`)}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{M&&console.log(`${t} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:o}=e.data;switch(o){case lt.next:return this.witness_next({ibGib:e});case lt.error:return this.witness_error({ibGib:e});case lt.complete:return this.witness_complete({ibGib:e});default:return super.witness_cmd({arg:e})}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async witness_next({ibGib:e}){let t=`${this.lc}[${this.witness_next.name}]`;try{if(M&&console.log(`${t} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return M&&console.log(`${t} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),z;if((e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one payload ibgib (E: 4046802ff96d4adfafcee7a74d96af5e)");let o=e.ibGibs[0];this.data.replay&&this._pastPayloads.push(o);let n=Object.values(this._subscribers);for(let s=0;s<n.length;s++){let[i,a]=n[s];if(M&&console.log(`${t} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await i.unsubscribed())M&&console.log(`${t} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`),await a.next(o);else{debugger;console.warn(`${t} (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 z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async witness_error({ibGib:e}){let t=`${this.lc}[${this.witness_error.name}]`;try{if(M&&console.log(`${t} starting... (I: 3367a73bc83c47f98d9ecfe426dc300e)`),(e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one error ibgib (E: 905474b45bcb4f0abe7bd4618f08f32c)");let o=e.ibGibs[0];this._pastError=o;let n=Object.values(this._subscribers);for(let s=0;s<n.length;s++){let[i,a]=n[s];if(At({ibGib:a})){let c=a;c.error?await i.unsubscribed()?console.warn(`${t} (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(o):M&&console.log(`${t} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await a.witness(o)}return z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async witness_complete({ibGib:e}){let t=`${this.lc}[${this.witness_complete.name}]`;try{M&&console.log(`${t} starting... (I: 4db180f465e24df9a4ded37fbd235558)`),this._isComplete=!0;let o=Object.values(this._subscribers);for(let n=0;n<o.length;n++){let[s,i]=o[n];if(At({ibGib:i})){let a=i;a.complete?await s.unsubscribed()?console.warn(`${t} (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 a.complete():M&&console.log(`${t} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await i.witness(e)}return z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return M&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{M&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){if(e.cmd===ct.subscribe)return super.argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n});{let s=await _t({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}}async resulty({resultData:e,ibGibs:t}){let o=await Tt({resultData:e});return t&&(o.ibGibs=t),o}},vo=class r extends Bt{static{f(this,"Subject_V1_Factory")}lc=`[${r.name}]`;getName(){return Go.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{M&&console.log(`${o} starting...`),e??=C(mr),e=e,t=t??os?C(os):void 0,e.uuid||=await j();let{classname:n}=e,s=fs({data:e}),i=await xe({parentPrimitiveIb:`witness ${n}`,ib:s,data:e,rel8ns:t}),a=new Go(void 0,void 0);return await a.loadIbGibDto(i),M&&console.log(`${o} witnessDto: ${H(i)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:a}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{M&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{M&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");M&&console.log(`${t} data: ${H(o)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await Ht({n:100}),s=new Do().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??Eo}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"observable"});return Promise.resolve(s)}catch(o){throw console.error(`${t} ${E({error:o})}`),o}finally{M&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=C(mr);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:xt}),await this.newUp({data:t})}};var Oo=!1;function dc({data:r}){let e=`[${dc.name}]`;try{if(Oo&&console.log(`${e} starting...`),!r)throw new Error("Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)");let t=[],{name:o,uuid:n,classname:s}=r;return o?o.match(rs)||t.push(`name must match regexp: ${rs} (E: de987eb8fea0b6232f60abf31815095c)`):t.push("name required."),n?n.match(Q)||t.push(`uuid must match regexp: ${Q} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):t.push("uuid required."),s&&(s.match(We)||t.push(`classname must match regexp: ${We}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Oo&&console.log(`${e} complete.`)}}f(dc,"validateCommonSubjectData");function fs({data:r,classname:e}){let t=`[${fs.name}]`;try{let o=dc({data:r});if(o.length>0)throw new Error(`invalid Subject data: ${o} (E: 55620ac1f17e30a30a92850219f894ac)`);if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match data.classname (E: 20e86cca70130839a49ad011c9a7aafa)")}else if(e=r.classname,!e)throw new Error("classname required (E: 74e29ae0f618fee7e7ef72a30c654a6c)");let{name:n,uuid:s}=r;return`witness ${mo} ${e} ${n} ${s}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(fs,"getSubjectIb");var Do=class r extends tt{static{f(this,"SubjectFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subject"}};function At({ibGib:r}){let e=`[${At.name}]`;try{return Oo&&console.log(`${e} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof r.next=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Oo&&console.log(`${e} complete.`)}}f(At,"isObserver");async function v2({data:r,replay:e}={}){let t=new vo;return r??=C(mr),e&&(r.replay=!0),(await t.newUp({data:r})).newIbGib}f(v2,"newupSubject");var No="anon_fn",fc={fnHash:""};var bc=!1;function bs({data:r}){let e=`[${bs.name}]`;try{if(bc&&console.log(`${e} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!r?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${No} ${r.fnHash}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{bc&&console.log(`${e} complete.`)}}f(bs,"getAnonymousFnIb");var dt=class{static{f(this,"AnonymousFnWitness_V1")}fn;ib=No.concat();gib=R;data=C(fc);rel8ns;constructor(e){if(this.fn=e,!e)throw new Error("fn required (E: b1e1478f466a2a347b75e7c336f8d323)")}async witness(e){return this.data.fnHash=await X({s:this.fn.toString()}),this.ib=bs({data:this.data}),this.gib=await K({ibGib:this}),this.fn(e)}};var Co=!1;function dd({err:r}){let e=`[${dd.name}]`;try{if(Co&&console.log(`${e} starting... (I: 96f8b767c50f24768ced7beebb291723)`),An(r)){let t=r;if(!r.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(Ye({ibGib:r}))return r.data.raw;throw new Error("(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)")}else return E(r)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Co&&console.log(`${e} complete.`)}}f(dd,"extractObsErrMsg");function fd(r){let e=`[${fd.name}]`;try{Co&&console.log(`${e} starting... (I: 3d2c3658a0fda83ece1f2b095a365823)`);let t;if(typeof r=="function"?t={next:r}:t=r,!t.next)throw new Error("observer.next required (typeof observerOrFn !== 'function') (E: da944e93b32ab5918f11751bcd651823)");let o=f(async d=>(await t.next(d),z),"fnNext"),n=f(async d=>(d.ib==="complete"?t.complete&&await t.complete():Ye({ibGib:d})?t.error&&await t.error(d):await t.next(d),z),"fnWitness"),s=new dt(o),i=new dt(n),a={ib:"observer",witness:f(async d=>await i.witness(d),"witness"),next:f(async d=>{await s.witness(d)},"next")},c=t.error??(async d=>{let b;if(typeof d=="string")b=E(d);else if(d.ib)if(Ye({ibGib:d}))b=E(d.data.raw);else throw new Error(`${e} (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?b=E(d):typeof d.message=="string"?b=E(d.message):b="[unknown thing came down pipe that ain't an error]";console.error(`Error occurred but observer.error is falsy. error: ${b} (E: 822c60c7c4d542efacd5c2dea7e88062)`)}),l=new dt(async d=>(c(d),z));if(a.error=async d=>{typeof d=="string"?d=await It({rawMsg:d}):d instanceof Error&&(d=await It({rawMsg:d.message}));try{await l.witness(d)}catch{t.error?console.error(`${e} there was another error when executing errorAnonFnWitness.witness (wrapper of caller's observer.error) trapping this. (E: 8fa3c4e633df4491a82951e3b677d9a9)`):console.error(`${e} there was another error when executing errorAnonFnWitness.witness (caller's observer.error was falsy). trapping this. (E: f5ff2db0d762487287139a4175eb7689)`)}},t.complete){let d=t.complete,b=new dt(async u=>(await d(),z));a.complete=async()=>{try{await b.witness(z)}catch(u){console.error(`${e} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${E(u)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return a}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Co&&console.log(`${e} complete.`)}}f(fd,"fnObs");export{f as a,Q as b,Ee as c,C as d,Oe as e,X as f,j as g,H as h,de as i,E as j,ko as k,we as l,Ir as m,Ne as n,$s as o,Dt as p,R as q,z as r,ee as s,Ce as t,Ss as u,ze as v,_ as w,L as x,Y as y,Ic as z,te as A,K as B,ie as C,je as D,Ie as E,ae as F,Xt as G,Nt as H,Ot as I,B as J,_f as K,Tf as L,Af as M,xr as N,_c as O,Os as P,Ns as Q,Bf as R,Ff as S,qf as T,Tc as U,Hf as V,vr as W,zo as X,Ac as Y,Qf as Z,Or as _,Ze as $,Nr as aa,Xs as ba,Cr as ca,Gc as da,vc as ea,mu as fa,Eu as ga,wu as ha,$u as ia,yu as ja,Iu as ka,Rc as la,Lc as ma,Zs as na,cn as oa,kc as pa,Mc as qa,Pt as ra,Zt as sa,ii as ta,Yc as ua,li as va,lp as wa,bp as xa,ce as ya,gn as za,mn as Aa,re as Ba,Wc as Ca,qr as Da,Hr as Ea,fe as Fa,En as Ga,fi as Ha,Se as Ia,Ct as Ja,hn as Ka,pi as La,Ge as Ma,rr as Na,Jc as Oa,Zc as Pa,Qc as Qa,el as Ra,ve as Sa,Mp as Ta,tl as Ua,rl as Va,Kr as Wa,Ue as Xa,ol as Ya,nl as Za,sl as _a,il as $a,xe as ab,eh as bb,xi as cb,er as db,Xr as eb,nr as fb,Gi as gb,he as hb,ke as ib,An as jb,Qt as kb,Sn as lb,rt as mb,dh as nb,bl as ob,fh as pb,bh as qb,uh as rb,ph as sb,Di as tb,ih as ub,Oh as vb,Nh as wb,Ch as xb,Ph as yb,Rh as zb,Lh as Ab,Uh as Bb,ht as Cb,pl as Db,hl as Eb,gl as Fb,gt as Gb,Fi as Hb,ml as Ib,On as Jb,$l as Kb,Me as Lb,ye as Mb,ar as Nb,Pn as Ob,Rn as Pb,ne as Qb,Zr as Rb,Xi as Sb,cr as Tb,Ol as Ub,Nl as Vb,Ag as Wb,Sg as Xb,ca as Yb,dr as Zb,Et as _b,fr as $b,Bl as ac,Fl as bc,xm as cc,ao as dc,lo as ec,ot as fc,yt as gc,xa as hc,Vl as ic,Ga as jc,Ym as kc,Mt as lc,Pa as mc,gr as nc,qn as oc,nE as pc,sE as qc,iE as rc,Hn as sc,po as tc,uE as uc,Kn as vc,pE as wc,ka as xc,Ua as yc,Yl as zc,Wl as Ac,zl as Bc,Jl as Cc,Zl as Dc,Ql as Ec,DE as Fc,bo as Gc,uo as Hc,ed as Ic,Xn as Jc,ir as Kc,Rt as Lc,td as Mc,rd as Nc,Oi as Oc,od as Pc,Fa as Qc,KE as Rc,nd as Sc,sd as Tc,zn as Uc,id as Vc,ad as Wc,Ha as Xc,cd as Yc,Zn as Zc,lw as _c,dw as $c,It as ad,dd as bd,fd as cd,ld as dd,_t as ed,Tt as fd,es as gd,Ft as hd,v2 as id};