@ibgib/space-gib 0.0.3 → 0.0.4
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.
- package/CHANGELOG.md +4 -0
- package/IMPLEMENTATION.md +9 -13
- package/dist/client/bootstrap.mjs +1 -1
- package/dist/client/bootstrap.mjs.map +1 -1
- package/dist/client/chunk-NCXKCVYS.mjs +42 -0
- package/dist/client/chunk-NCXKCVYS.mjs.map +7 -0
- package/dist/client/chunk-ZUEU37Z5.mjs +1920 -0
- package/dist/client/chunk-ZUEU37Z5.mjs.map +7 -0
- package/dist/client/index.html +103 -5
- package/dist/client/index.mjs +1 -1
- package/dist/client/script.mjs +1 -1
- package/dist/client/style.css +466 -61
- package/dist/respec-gib.node.mjs +5 -0
- package/dist/server/server.mjs +294 -225
- package/dist/server/server.mjs.map +2 -2
- package/package.json +6 -6
- package/src/client/AUTO-GENERATED-version.mts +1 -1
- package/src/client/components/identity-header/IMPLEMENTATION.md +45 -0
- package/src/client/components/identity-header/identity-header.css +74 -0
- package/src/client/components/identity-header/identity-header.html +10 -0
- package/src/client/components/identity-header/identity-header.mts +361 -0
- package/src/client/components/identity-manager/IMPLEMENTATION.md +100 -0
- package/src/client/components/identity-manager/identity-manager.css +467 -0
- package/src/client/components/identity-manager/identity-manager.html +113 -0
- package/src/client/components/identity-manager/identity-manager.mts +767 -0
- package/src/client/components/keystone-creator/keystone-creator.css +2 -76
- package/src/client/components/keystone-creator/keystone-creator.html +41 -26
- package/src/client/components/keystone-creator/keystone-creator.mts +178 -41
- package/src/client/dev-tools/base-tools.mts +252 -0
- package/src/client/dev-tools/common.mts +217 -0
- package/src/client/dev-tools/phase-1.mts +156 -0
- package/src/client/dev-tools/phase-2.mts +143 -0
- package/src/client/dev-tools/phase-3.mts +189 -0
- package/src/client/dev-tools/phase-4-1.mts +197 -0
- package/src/client/dev-tools/phase-4-10.mts +884 -0
- package/src/client/dev-tools/phase-4-2.mts +388 -0
- package/src/client/dev-tools/phase-4-3.mts +391 -0
- package/src/client/dev-tools/phase-4-4.mts +374 -0
- package/src/client/dev-tools/phase-4-5.mts +376 -0
- package/src/client/dev-tools/phase-4-6.mts +273 -0
- package/src/client/dev-tools/phase-4-7.mts +399 -0
- package/src/client/dev-tools/phase-4-8.mts +430 -0
- package/src/client/dev-tools/phase-4-9.mts +398 -0
- package/src/client/dev-tools/phase-4.mts +1302 -0
- package/src/client/dev-tools.mts +52 -1194
- package/src/client/index.html +103 -5
- package/src/client/style.css +466 -61
- package/src/client/ui/shell/space-gib-shell-constants.mts +0 -2
- package/src/client/ui/shell/space-gib-shell-service.mts +82 -10
- package/src/common/common-constants.mts +0 -0
- package/src/common/keystone-policies.json +40 -43
- package/src/common/keystone-policies.mts +3 -5
- package/src/server/path-helper.respec.mts +99 -94
- package/src/server/serve-gib/README.md +9 -0
- package/src/server/serve-gib/handlers/api/keystone/keystone-genesis.handler.mts +1 -1
- package/src/server/serve-gib/handlers/api/keystone/keystone-get.respec.mts +1 -1
- package/src/server/serve-gib/handlers/ws/sync-upgrade-handler-base.mts +31 -3
- package/src/server/serve-gib/handlers/ws/ws-helper.mts +73 -45
- package/dist/client/chunk-2KJC5XKE.mjs +0 -31
- package/dist/client/chunk-2KJC5XKE.mjs.map +0 -7
- package/dist/client/chunk-QNIXTRFO.mjs +0 -235
- package/dist/client/chunk-QNIXTRFO.mjs.map +0 -7
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
var _d=Object.defineProperty;var f=(r,e)=>_d(r,"name",{value:e,configurable:!0});var Ge=/^[a-zA-Z0-9_\-.]{1,256}$/,qt=/^[a-zA-Z0-9_]{1,255}$/,Fs=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,js=/^(\[.+\]).+$/,Vs=/^[0-9a-fA-F]{32}$/,Hs=/^[0-9a-fA-F]{64}$/;var Cr="/",Ks="_nonalphanumerics_";var vr=!1,Xs=globalThis.crypto,{subtle:Td}=Xs,Ye={sha_256:"SHA-256",sha_512:"SHA-512"};function H(r){return JSON.parse(JSON.stringify(r))}f(H,"clone");function oe(r){return(r??new Date).toUTCString()}f(oe,"getTimestamp");async function He({s:r,algorithm:e="SHA-256"}){if(!r)return"";try{let t=Object.values(Ye);if(!t.includes(e))throw new Error(`Only ${t} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let o=new TextEncoder().encode(r),n=await Td.digest(e,o);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(w(t.message)),t}}f(He,"hash");async function U(r=64){let e="";if(r<32)throw new Error("Seed size must be at least 32");if(!globalThis.crypto)throw new Error("Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)");let t=Xs.getRandomValues(new Uint8Array(16));if(e=await He({s:t.join("")}),!e)throw new Error("Did not create UUID...hmm...");return e}f(U,"getUUID");function K(r){return JSON.stringify(r,null,2)}f(K,"pretty");async function Ce(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}f(Ce,"delay");function w(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(`[${w.name}] this fn takes the raw error object. no destructure required. change your call from extractErrorMsg({error}) to extractErrorMsg(error). (W: ea49af5fd76d4b80a55a108d73a3e9b4)`),w(r.error)):`[error is not a string and error.message is not a string. typeof error: ${typeof r} (E: d5a7723ca59646838308bc9e53a43134)]`}f(w,"extractErrorMsg");function jn({items:r,keyFn:e}){let t=`[${jn.name}]`;try{let o={};for(let n=0;n<r.length;n++){let a=r[n],s=e(a);o[s]=[...o[s]??[],a]}return o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(jn,"groupBy");function mo({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(mo,"getRegExp");function ot(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(ot,"getTimestampInTicks");function Vn({startDate:r,years:e,months:t,days:o,hours:n,seconds:a}){let s=`[${Vn.name}]`;try{return pr({startDate:r,years:e,months:t,days:o,hours:n,seconds:a}).toUTCString()}catch(i){throw console.log(`${s} ${i.message}`),i}}f(Vn,"getExpirationUTCString");function pr({startDate:r,years:e,months:t,days:o,hours:n,seconds:a}){let s=`[${pr.name}]`;try{if(!r&&!e&&!t&&!o&&!n&&!a)throw new Error("either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)");r=r?new Date(r):new Date;let i,c;return e?(i=r.getFullYear()+e,c=r.setFullYear(i),pr({startDate:new Date(c),months:t,days:o,hours:n,seconds:a})):t?(i=r.getMonth()+t,c=r.setMonth(i),pr({startDate:new Date(c),years:e,days:o,hours:n,seconds:a})):o?(i=r.getDate()+o,c=r.setDate(i),pr({startDate:new Date(c),years:e,months:t,hours:n,seconds:a})):n?(i=r.getHours()+n,c=r.setHours(i),pr({startDate:new Date(c),years:e,months:t,days:o,seconds:a})):a?(i=r.getSeconds()+a,c=r.setSeconds(i),pr({startDate:new Date(c),years:e,months:t,days:o,hours:n})):r}catch(i){throw console.log(`${s} ${i.message}`),i}}f(pr,"addTimeToDate");function Hn({expirationTimestampUTC:r}){let e=`[${Hn.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(Hn,"isExpired");function Eo(r){return Array.from(new Set(r))}f(Eo,"unique");function Kn({obj:r,value:e,path:t,pathDelimiter:o,logalot:n}){let a=`[${Kn.name}]`;try{if(n&&console.log(`${a} 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||Cr;let s=r,i=t.split(o).filter(d=>!!d),c=i.pop();i.forEach(d=>{let l=s[d];if(l){if(typeof l!="object")throw new Error(`invalid path into object. Each step along the path must be typeof === 'object', but typeof targetObj["${d}"] === ${typeof l}. (value: ${l}) (E: 38cf29c5f624a40b4b56502c2ec39d22)`)}else s[d]={};s=s[d]}),s[c]=e}catch(s){throw console.error(`${a} ${s.message}`),s}finally{n&&console.log(`${a} complete.`)}}f(Kn,"patchObject");async function qr({n:r}){let e=`[${qr.name}]`;try{vr&&console.log(`${e} starting...`);let t=[];for(let o=0;o<r;o++){let n=await U();t.push(n.substring(0,16))}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{vr&&console.log(`${e} complete.`)}}f(qr,"getIdPool");function Gd({text:r,length:e,keepLiterals:t=["-"],replaceMap:o}){let n=`[${Gd.name}]`;try{if(vr&&console.log(`${n} starting... (I: 27437e312e5aa621adfebb84e059c822)`),!r)throw new Error("text required (E: 87e0493613c8b30dfade83e1d2862a22)");let a=r,s={};t=t??[];for(let c=0;c<t.length;c++){let d=t[c],l;do l=qs({count:10});while(l.includes(d)||d.includes(l)||r.includes(l));if(a.includes(d))for(s[l]=d;a.includes(d);)a=a.replace(d,l)}if(o&&Object.keys(o).length>0)for(let c=0;c<Object.keys(o).length;c++){let d=Object.keys(o)[c],l=o[d];for(;a.includes(d);)a=a.replace(d,l)}a=a.replace(/\W/g,"");let i=Object.keys(s);for(let c=0;c<i.length;c++){let d=i[c];for(;a.includes(d);)a=a.replace(d,s[d])}return e&&e>0&&a.length>e&&(vr&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),a=a.substring(0,e)),a.length===0&&(a=Ks),a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{vr&&console.log(`${n} complete.`)}}f(Gd,"getSaferSubstring");function Cd({x:r}){if((r??[]).length===0)return;let e=Math.floor(Math.random()*r.length);return r[e]}f(Cd,"pickRandom");function qs({count:r}){let e=`${qs.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+=Cd({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{vr&&console.log(`${e} complete.`)}}f(qs,"pickRandom_Letters");function Or({dominant:r,recessive:e}){let t=`[${Or.name}]`;try{if(Array.isArray(r)&&Array.isArray(e)){let o=H(r),n=!1;return e.forEach(a=>{if(typeof a=="string")o.includes(a)||o.push(a);else{n||(console.warn(`${t} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`),n=!0);let s=JSON.stringify(a);o.some(i=>JSON.stringify(i)===s)||o.push(a)}}),o}else if(typeof r=="object"&&typeof e=="object"){let o={...e},n=Object.keys(r),a=Object.keys(e);return n.forEach(s=>{a.includes(s)?Array.isArray(r[s])&&Array.isArray(e[s])?o[s]=Or({dominant:r[s],recessive:e[s]}):r[s]&&!Array.isArray(r[s])&&typeof r[s]=="object"&&e[s]&&!Array.isArray(e[s])&&typeof e[s]=="object"?o[s]=Or({dominant:r[s],recessive:e[s]}):o[s]=r[s]:o[s]=r[s]}),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(Or,"mergeMapsOrArrays_Naive");function y({ib:r,gib:e,ibGib:t,delimiter:o="^"}){return r=r||t?.ib||"",e=e||t?.gib||"",r+o+e}f(y,"getIbGibAddr");function ae({ibGib:r,ibGibAddr:e,delimiter:t="^"}){let o="[getIbAndGib]";if(!e)if(r)e=y({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(ae,"getIbAndGib");var vd=globalThis.crypto,{subtle:Ws}=vd;function Wt(r,e=""){e||(e="");let t=f(async s=>{if(!s)return"";let i=new TextEncoder().encode(s),c=await Ws.digest("SHA-256",i);return Array.from(new Uint8Array(c)).map(l=>l.toString(16).padStart(2,"0")).join("")},"hashToHex"),o=f(async(s,i)=>{let c;if(s){let b=new TextEncoder().encode(s);c=new Uint8Array(b.length+i.length),c.set(b),c.set(i,b.length)}else c=i;let d=await Ws.digest("SHA-256",c);return Array.from(new Uint8Array(d)).map(b=>b.toString(16).padStart(2,"0")).join("")},"hashToHex_Uint8Array"),n=f(s=>{if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(d=>n(d));let i={},c=Object.keys(s).sort();for(let d of c){let l=s[d];l!==void 0&&(i[d]=n(l))}return i},"toNormalizedForHashing"),a;return e?a=f(async(s,i,c)=>{let d=Object.keys(c||{}).length>0&&Object.keys(c||{}).some(m=>c[m]&&c[m].length>0),l=!!i;l&&(typeof i=="string"?l=i.length>0:i instanceof Uint8Array?l=!0:typeof i=="object"?l=Object.keys(i||{}).length>0:l=!0);let b=(await t(e+s)).toUpperCase(),p=d?(await t(e+JSON.stringify(n(c)))).toUpperCase():"",u="";return l&&(i instanceof Uint8Array?u=(await o(e,i)).toUpperCase():u=(await t(e+JSON.stringify(n(i)))).toUpperCase()),d||l?(await t(e+b+p+u)).toUpperCase():(await t(e+b)).toUpperCase()},"hashFields"):a=f(async(s,i,c)=>{let d=Object.keys(c||{}).length>0&&Object.keys(c||{}).some(m=>c[m]&&c[m].length>0),l=!!i;l&&(typeof i=="string"?l=i.length>0:i instanceof Uint8Array?l=!0:typeof i=="object"?l=Object.keys(i||{}).length>0:l=!0);let b=(await t(s)).toUpperCase(),p=d?(await t(JSON.stringify(n(c)))).toUpperCase():"",u="";return l&&(i instanceof Uint8Array?u=(await o("",i)).toUpperCase():u=(await t(JSON.stringify(n(i)))).toUpperCase()),d||l?(await t(b+p+u)).toUpperCase():(await t(b)).toUpperCase()},"hashFields"),a(r.ib,r?.data,r?.rel8ns)}f(Wt,"sha256v1");var Ee;(function(r){r.past="past",r.ancestor="ancestor",r.dna="dna",r.identity="identity",r.tjp="tjp",r.secret="secret",r.encryption="encryption"})(Ee||(Ee={}));var Nr="ib",re="gib",q={ib:Nr,gib:re},ve="^",St=".",Ys="ib^gib",hr=["past","ancestor","dna","tjp"],Od=155,zs=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${Od}}$`);async function ur(r){let e=H(r),t=`[${ur.name}]`;e.srcAddr&&delete e.srcAddr,delete e.src;let o={ib:e.type,data:e,rel8ns:{ancestor:[`${e.type.toString()}${ve}${re}`]}};return o.gib=await Wt(o),o}f(ur,"buildDna");function Xn({ibGib:r}){let e=`[${Xn.name}]`;try{if(!r)throw new Error("ibGib required.");let t=["fork","mut8","rel8","plan"].map(n=>`${n}^${re}`);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} ${w(t)}`),t}}f(Xn,"isDna");function $e({ibGib:r,gib:e}){return r?$e({gib:r.gib}):e?e===re:!0}f($e,"isPrimitive");async function ue({ibGib:r,hasTjp:e,tjpAddr:t,gibDelimiter:o,isPrimitive:n,hashAlgorithm:a}){let s=`[${ue.name}]`;try{if(!r)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return re;let i=await Wt(r,""),c=r.rel8ns??{},d=r.data??{};if(o=o||St,e||(e=(c.tjp??[]).length>0||d.isTjp||!1),e){let l;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(`${s} 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(d.isTjp)t=y({ib:r.ib,gib:i});else throw new Error("hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)");if(l=t?ae({ibGibAddr:t}).gib:void 0,l)return d.isTjp?i:`${i}${St}${l}`;throw new Error("hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)")}else return i}catch(i){throw console.error(`${s} ${w(i)}`),i}}f(ue,"getGib");function De({ibGibAddr:r,gib:e,gibDelimiter:t}){let o=`[${De.name}]`;try{if(!r&&!e)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(e=e||ae({ibGibAddr:r}).gib,e===re)return{isPrimitive:!0};if(t=t??St,e.includes(t)){let n=e.split(t);if(n.some(i=>i===""))throw new Error(`unexpected gib that contains gibDelimiter (${t}) but has at least one piece with empty string. (E: 75a94280045541009ee68182d12d3449)`);let a=n.length;return a>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:a,delimiter:t}}else return{punctiliarHash:e,piecesCount:1,delimiter:t}}catch(n){throw console.error(`${o} ${w(n)}`),n}}f(De,"getGibInfo");async function wo(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,destIb:n,uuid:a,tjp:s,cloneRel8ns:i,cloneData:c,type:d="fork"}=r,l=r.src,b="[fork_v1]";if(d!=="fork")throw new Error(`${b} not a fork transform.`);if(r.type||(r.type="fork"),!l)throw new Error(`${b} src required to fork.`);if(!l.ib)throw new Error(`${b} src.ib required.`);if(n&&n.includes(ve))throw new Error(`${b} destIb can't contain (hardcoded) delimiter right now.`);if(!l.gib)throw new Error(`${b} src.gib required.`);let p={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(p.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(p.rel8ns=l.rel8ns),l=p;let u=y({ib:l.ib,gib:l.gib});r.srcAddr=u;let g=i&&l.rel8ns&&Object.keys(l.rel8ns).length>0?H(l.rel8ns):{};delete g.past;let m=c&&l?.data?H(l.data):{};r.nCounter&&(m.n=0);let E=o?.includes(Ee.ancestor)?[u]:(g.ancestor||[]).concat([u]);g.ancestor=E,g.tjp&&delete g.tjp;let S=H(l);if(e&&s?.timestamp)throw new Error(`${b} both noTimestamp and tjp.timestamp selected.`);if(!e||s?.timestamp){let $=new Date;m.timestamp=oe($),m.timestampMs=$.getMilliseconds()}(s?.uuid||a)&&(m.uuid=await U()),s?.uuid||s?.timestamp?m.isTjp=!0:m.isTjp&&delete m.isTjp,S.ib=n||"ib",u!==Ys&&(S.rel8ns=g),Object.keys(m).length>0&&(S.data=m);let A=null;if(t){A=await ur(r);let $=y({ibGib:A});g.dna=o?.includes(Ee.dna)?g.dna=[$]:g.dna=(g.dna||[]).concat($)}S.gib=await Wt(S,"");let I={newIbGib:S};return A&&(I.dnas=[A]),I}f(wo,"fork");async function nt(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,dataToRename:n,dataToRemove:a,dataToAddOrPatch:s,mut8Ib:i,type:c="mut8"}=r,d=r.src,l="[mut8_v1]";if(c!=="mut8")throw new Error(`${l} not a mut8 transform.`);if(r.type||(r.type="mut8"),!d)throw new Error(`${l} src required to mut8.`);if(!d.ib)throw new Error(`${l} src.ib required.`);if(d.ib.includes(ve))throw new Error(`${l} ib can't contain hardcoded delimiter (${ve}) right now.`);if(!d.gib)throw new Error(`${l} src.gib required.`);if(!i&&!n&&!a&&!s)throw new Error(`${l} gotta provide either a mut8Ib or some data to change.`);let b=y({ib:d.ib,gib:d.gib});if(r.srcAddr&&b!==r.srcAddr)throw new Error(`${l} srcAddr from src does not equal opts.srcAddr`);if(r.srcAddr=b,$e({ibGib:d}))throw new Error(`${l} cannot mutate primitive ibgib`);let p={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(p.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(p.rel8ns=d.rel8ns),d=p;let u=H(d),g=d.rel8ns?d.rel8ns:{},m=H(g);m.past=o?.includes(Ee.past)?[b]:(m.past||[]).concat([b]);let E=d?.data?H(d.data):{};if(n&&(E=qn(E,n,"rename")),a&&(E=qn(E,a,"remove")),s&&(E=Js(E,s)),!e){let T=new Date;E.timestamp=oe(T),E.timestampMs=T.getMilliseconds()}if(r.nCounter||Object.keys(E).includes("n"))if(Object.keys(E).includes("n"))if(Number.isInteger(E.n))E.n>=0?E.n=E.n+1:(console.warn(`${l} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),E.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else E.n=0;if(E.isTjp){let T=m.tjp??[];T.push(b),m.tjp=T,delete E.isTjp}let A=null;if(t){A=await ur(r);let T=y({ibGib:A});m.dna=o?.includes(Ee.dna)?m.dna=[T]:m.dna=(m.dna||[]).concat(T)}u.ib=i||u.ib,u.rel8ns=m,Object.keys(E).length>0?u.data=E:delete u.data;let I=(m.tjp?.length??0)>0;u.gib=await ue({ibGib:u,hasTjp:I});let $={newIbGib:u};return A&&($.dnas=[A]),$}f(nt,"mut8");function qn(r,e,t){let o="[renameOrRemove]",n=["timestamp"];return Object.keys(e).forEach(a=>{if(n.includes(a))throw new Error(`${o} Cannot rename to ${a}.`);if(Object.keys(r).includes(a)){let s=e[a];if(typeof s=="string"){if(n.includes(s))throw new Error(`${o} Cannot rename to ${s}.`);t==="rename"&&(r[s]=r[a]),delete r[a]}else r[a]=qn(r[a],s,t)}else console.log(`${o} key to ${t} does not exist`)}),r}f(qn,"renameOrRemove");function Js(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]=Js(n,o):r[t]=o:r[t]=o}),r}f(Js,"patch");async function Ke(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,rel8nsToAddByAddr:n,rel8nsToRemoveByAddr:a,type:s="rel8"}=r,i=r.src,c="[rel8_v1]";if(s!=="rel8")throw new Error(`${c} not a rel8 transform.`);if(r.type||(r.type="rel8"),s!=="rel8")throw new Error(`${c} not a rel8 transform.`);if(r.type||(r.type="rel8"),!i)throw new Error(`${c} src required.`);if(!i.ib)throw new Error(`${c} src.ib required.`);if(i.ib.includes(ve))throw new Error(`${c} ib can't contain hardcoded delimiter (${ve}) right now.`);if(!i.gib)throw new Error(`${c} src.gib required.`);if($e({ibGib:i}))throw new Error(`${c} cannot relate/unrelate primitive ibgib`);let d=n&&Object.keys(n).length>0,l=a&&Object.keys(a).length>0;if(!(d||l))throw new Error(`${c} gotta provide relations to either add or remove.`);let b=y({ib:i.ib,gib:i.gib});if(r.srcAddr&&b!==r.srcAddr)throw new Error(`${c} srcAddr from src does not equal opts.srcAddr`);r.srcAddr=b;let p=f($=>$&&typeof $=="string"&&$.length>=2&&$.includes("^")&&$.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map($=>(n||{})[$]).forEach($=>{if(!($&&$.every(T=>p(T))))throw new Error(`${c} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(a||{}).map($=>(a||{})[$]).forEach($=>{if(!($&&$.every(T=>p(T))))throw new Error(`${c} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)});let u={ib:i.ib,gib:i.gib};i.data&&Object.keys(i.data).length>0&&(u.data=i.data),i.rel8ns&&Object.keys(i.rel8ns).length>0&&(u.rel8ns=i.rel8ns),i=u;let g=H(i),m=H(i.data||{});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(`${c} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),m.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else m.n=0;if(!e){let $=new Date;m.timestamp=oe($),m.timestampMs=$.getMilliseconds()}let E=H(i.rel8ns||{});if(Object.keys(n||{}).forEach($=>{if(hr.includes($))throw new Error(`${c} Cannot manually add relationship: ${$}.`);let T=E[$]||[],G=n[$].filter(v=>!T.includes(v));E[$]=T.concat(G)}),Object.keys(a||{}).forEach($=>{if(hr.includes($))throw new Error(`${c} Cannot manually remove relationship: ${$}.`);let T=E[$]||[],_=a[$]||[],G=T.filter(v=>!_.includes(v));G.length>0?E[$]=G:delete E[$]}),E.past=(E.past||[]).concat([b]),(o||[]).filter($=>Object.keys(E).includes($)).filter($=>(E[$]||[]).length>1).forEach($=>{let T=E[$].length;E[$]=[E[$][T-1]]}),m.isTjp){let $=E.tjp||[];$.push(b),E.tjp=$,delete m.isTjp}g.data=m,g.rel8ns=E;let S=(E.tjp?.length??0)>0,A=null;if(t){A=await ur(r);let $=y({ibGib:A});E.dna=o?.includes(Ee.dna)?E.dna=[$]:E.dna=(E.dna||[]).concat($)}g.gib=await ue({ibGib:g,hasTjp:S});let I={newIbGib:g};return A&&(I.dnas=[A]),I}f(Ke,"rel8");function yo({ibGib:r}){let e=`[${yo.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(St)?!0:r.gib===re?!1:!!De({ibGibAddr:y({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(yo,"hasTjp");function $o({ibGib:r}){let e=`[${$o.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:H(r.data)),r.rel8ns&&(t.rel8ns=H(r.rel8ns)),t}f($o,"toDto");var Wn=!1;async function ge({ibGib:r}){let e=`[${ge.name}]`;try{let t=[];if(r){let o=y({ibGib:r});if(t=Lr({addr:o})??[],t.length>0)return console.error(`${e} errors found in addr: ${o}`),t;if($e({gib:r.gib}))return null;let n=await ue({ibGib:$o({ibGib:r}),hasTjp:yo({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 ue({ibGib:$o({ibGib:r}),hasTjp:yo({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} ${w(t)}`),t}}f(ge,"validateIbGibIntrinsically");function Lr({addr:r,delimiter:e,version:t}){let o=`[${Lr.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||ve,r.includes(e)||n.push(`No delimiter (${e}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`),r.startsWith(e)&&n.push("addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)");let{ib:a,gib:s}=ae({ibGibAddr:r,delimiter:e}),i=Dr({ib:a,ibGibAddrDelimiter:e,version:t});i&&(n=n.concat(i));let c=xr({gib:s,ibGibAddrDelimiter:e,version:t});return c&&(n=n.concat(c)),n.length>0&&Wn&&console.log(`${o} errors.length > 0. errors: ${n.join("|")} (I: 9c18f993e138f15613e4c6a340d41722)`),n.length>0?n:null}catch(n){throw console.error(`${o} ${w(n)}`),n}}f(Lr,"validateIbGibAddr");function Dr({ib:r,ibGibAddrDelimiter:e,version:t}){let o=`[${Dr.name}]`;try{let n=[];return t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),r?r===Nr?null:(e=e||ve,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} ${w(n)}`),n}}f(Dr,"validateIb");function xr({gib:r,gibDelimiter:e,ibGibAddrDelimiter:t,version:o}){let n=`[${xr.name}]`;try{let a=[];if(o&&console.warn(`${n} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`),!r)return a.push("gib required. (E: e217de4035b04086827199f4bace189c)"),a;t=t||ve;let s=[t],i=[];s.forEach(u=>{r.includes(u)&&i.push(u)}),i.length>0&&a.push(`gib (${r}}) contains invalid characters: (${JSON.stringify(i.join(","))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);let{punctiliarHash:c,tjpGib:d,isPrimitive:l}=De({gib:r,gibDelimiter:e||St});if(l)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let b=c.match(Vs),p=c.match(Hs);if(!b&&!p&&a.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),d){let u=xr({gib:d});(u??[]).length>0&&a.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${u.join(". ")}`)}return a.length>0?a:null}catch(a){throw console.error(`${n} ${w(a)}`),a}}f(xr,"validateGib");function Yn({rel8ns:r}){let e=`[${Yn.name}]`;try{Wn&&console.log(`${e} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`);let t=[],o=Object.keys(r);for(let n=0;n<o.length;n++){let a=Object.keys(r)[n];typeof a!="string"&&t.push("non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)");let s=r[a]??[];for(let i=0;i<s.length;i++){let c=s[i],d=Lr({addr:c})??[];d.length>0&&t.push(`invalid addr found for rel8nName (${a}). addr errors: ${d.join("|")} (E: 56809a746c4f462db426e90395b80364)`)}}return t.length>0?t:null}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Wn&&console.log(`${e} complete.`)}}f(Yn,"validateRel8nsIntrinsically");var Zs=!1,F=class r{static{f(this,"Factory_V1")}static root(){return r.primitive({ib:Nr})}static primitive({ib:e}){return{ib:e,gib:re}}static primitives({ibs:e}){return e.map(t=>r.primitive({ib:t}))}static async firstGen({ib:e=Nr,parentIbGib:t=r.root(),data:o,rel8ns:n,dna:a,tjp:s,linkedRel8ns:i,noTimestamp:c,nCounter:d,squash:l}){let b=`[${r.name}][${r.firstGen.name}]`;try{if(Zs&&console.log(`${b} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),a&&l)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let p=[],u=t||q,g=await wo({src:u,destIb:e,tjp:s,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:d});if(p.push(g),u=g.newIbGib,o){let m=await nt({src:u,dataToAddOrPatch:o,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:d});p.push(m),u=m.newIbGib}if(n){let m=await Ke({src:u,rel8nsToAddByAddr:n,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:d});p.push(m)}if(p.length>1){let m=p.slice(p.length-1)[0].newIbGib,E={newIbGib:m,intermediateIbGibs:p.slice(0,p.length-1).map(S=>S.newIbGib)};if(a){l&&`${b}`;let S=[];return p.forEach(A=>{S=S.concat(A.dnas)}),E.dnas=S,E}else if(l){if(!m.rel8ns)throw new Error("(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)");return delete m.rel8ns.past,m.rel8ns.tjp&&(delete m.rel8ns.tjp,m.data??={},m.data.isTjp=!0),d&&(m.data??={},m.data.n=0),m.gib=await ue({ibGib:m}),{newIbGib:m}}else return E}else{if(p.length===1)return p[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(p){throw console.error(`${b} ${w(p)}`),p}finally{Zs&&console.log(`${b} complete.`)}}static async stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:a,noTimestamp:s,uuid:i}){let c=`[${r.name}][${r.stone.name}]`;try{if(!e)throw new Error("parentPrimitiveIb required. (E: genuuid)");if(Dr({ib:e})!==null)throw new Error(`Invalid parentPrimitiveIb: ${e}. (E: genuuid)`);if(!t)throw new Error("ib required. (E: genuuid)");let d=o?new RegExp(o):zs;if(!t.match(d))throw new Error(`invalid ib. does not match regexp (${d}) (E: genuuid)`);let l=Object.keys(a??{}),b=[...hr,"tjp"];if(l.some(m=>b.includes(m)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${b}. rel8ns keys: ${Object.keys(a??{})}. (E: genuuid)`);let g=(await r.firstGen({ib:t,parentIbGib:r.primitive({ib:e}),data:n,rel8ns:a,dna:!1,noTimestamp:s,nCounter:!1})).newIbGib;return i&&(g.data||(g.data={}),g.data.uuid=await U()),g.rel8ns?.past&&delete g.rel8ns.past,g.rel8ns?.tjp&&delete g.rel8ns.tjp,g.gib=await ue({ibGib:{ib:g.ib,data:g.data,rel8ns:g.rel8ns},hasTjp:!1}),g}catch(d){throw console.error(`${c} ${d.message}`),d}}static async constant({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:a}){let s=`[${r.name}][${r.constant.name}]`;try{return await r.stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:a,noTimestamp:!0,uuid:!1})}catch(i){throw console.error(`${s} ${i.message}`),i}}};var Fp="[core^gib timer]";var zn=`.'",!?-`;var Qs=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var jp=/^[a-zA-Z0-9_\-.]{1,255}$/,Vp=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var Io={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var Nd="robbot";var ei="zero",ti="zerospace";var ah=!1,sh="This is a local space. There are many like it, but this one is mine.";var ih=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,xd="syncSpace";var ch=3e4;var So="space";var ri="space_lock",oi=100,ni=100,lh=60*2,Jn=30;var Zn="root",Qn="x",ai="root",ea="analytics-outline",ta='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var ra="tag",Ld="target";var si="pricetag-outline",ii="This is a tag used for organizing data.";var mh="always",ci="archive",li="trash";var oa=/^\w{1,32}$/,_o="Invalid Date";var na={ib:"true",gib:re};var di={ib:"false",gib:re};var fi="config_key";var Wr=/^[a-zA-Z0-9_\-.]{1,32}$/,Ao="app";var gr=`bootstrap^${re}`,_t="defaultSpaceId",bi="spaceIds";var At={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},Yt=Object.values(At),at={sha_256:"SHA-256",sha_512:"SHA-512"},_h=Object.values(at),Dd={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},Pt=Object.values(Dd);function Yr(r){let e=`[${Yr.name}]`;return new Promise((t,o)=>{try{let n=pi(r),a=hi(n);t(a)}catch(n){console.error(`${e} ${w(n)}`),o(n)}})}f(Yr,"encodeStringToHexString");function pi(r){let e=`[${pi.name}]`;try{return new TextEncoder().encode(r)}catch(t){throw console.error(`${e} ${w(t)}`),t}}f(pi,"stringToUTF8Bytes");function hi(r){let e=`[${hi.name}]`;try{return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(`${e} ${w(t)}`),t}}f(hi,"bytesToHexString");function kt(r){let e=`[${kt.name}]`;return new Promise((t,o)=>{try{let n=ui(r),a=gi(n);t(a)}catch(n){console.error(`${e} ${w(n)}`),o(n)}})}f(kt,"decodeHexStringToString");function ui(r){let e=`[${ui.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} ${w(t)}`),t}}f(ui,"hexStringToBytes");function gi(r){let e=`[${gi.name}]`;try{return new TextDecoder().decode(r)}catch(t){throw console.error(`${e} ${w(t)}`),t}}f(gi,"utf8BytesToString");var Bt=At.appendPerHash,Ut="SHA-512",Mt=1024,Tt=2e4,Ft=1,mi="indexOf",To="lastIndexOf",Go=5e6,Co=4,zt=",";function Rd({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 At.prependPerHash:return t+(e||r);case At.appendPerHash:return(e||r)+t;case At.initialPrepend:return e||t+r;case At.initialAppend:return e||r+t;default:throw new Error(`Unknown saltStrategy: ${o} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}f(Rd,"getPreHash");async function dt({secret:r,prevHash:e,count:t,salt:o,saltStrategy:n,hashAlgorithm:a}){let s=`[${dt.name}]`;try{let i=e||void 0;for(let c=0;c<t;c++){let d=Rd({secret:r,prevHash:i,salt:o,saltStrategy:n});i=await He({s:d,algorithm:a})}if(!i)throw new Error("hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)");return i}catch(i){throw console.error(`${s} ${w(i)}`),i}}f(dt,"execRound_getNextHash");async function jt({secret:r,initialRecursions:e,salt:t,saltStrategy:o,hashAlgorithm:n}){let a=`[${jt.name}]`;try{return await dt({secret:r,count:e,salt:t,saltStrategy:o,hashAlgorithm:n})}catch(s){throw console.error(`${a} ${w(s)}`),s}}f(jt,"doInitialRecursions_keystretch");async function aa({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c}){let d=`[${aa.name}]`;try{let l=await jt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),b=c==="indexOf"?(g,m)=>g.indexOf(m):(g,m)=>g.lastIndexOf(m),p=[];for(let g=0;g<r.length;g++){let m=r[g],E="",S;for(;!E.includes(m);)S=await dt({count:t,prevHash:l,salt:o,saltStrategy:n,hashAlgorithm:s}),E+=S,l=S;let A=b(E,m);p.push(A)}return p.join(i)}catch(l){throw console.error(`${d} ${w(l)}`),l}}f(aa,"encryptFromHex_stream");async function sa({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${sa.name}]`;try{let d=await jt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),l=r.split(i).map(u=>parseInt(u)),b=[];for(let u=0;u<l.length;u++){let g=l[u],m="",E;for(;g>=m.length;)E=await dt({count:t,prevHash:d,salt:o,saltStrategy:n,hashAlgorithm:s}),m+=E,d=E;let S=m[g];b.push(S)}return b.join("")}catch(d){throw console.error(`${c} ${w(d)}`),d}}f(sa,"decryptToHex_stream");async function zr({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${zr.name}]`,d=[],l=[];e=e||Tt,t=t||Ft,n=n||Bt,s=s||Ut,o=o||await U(Mt),i=i||zt;let b="[validation]";if(!e||e<1){let g=`${b} initialRecursions required, and greater than 0`;console.error(g),d.push(g)}if(!t||t<1){let g=`${b} recursionsPerHash required, and greater than 0`;console.error(g),d.push(g)}if(!r){let g=`${b} encryptedData required`;console.error(g),d.push(g)}if(!o){let g=`${b} salt required`;console.error(g),d.push(g)}if(!n){let g=`${b} saltStrategy required`;console.error(g),d.push(g)}if(!a){let g=`${b} secret required`;console.error(g),d.push(g)}if(!i){let g=`${b} encryptedDataDelimiter required`;console.error(g),d.push(g)}if(!Object.values(at).includes(s)){let g=`${b} only ${Object.values(at)} hash algorithms implemented`;console.error(g),d.push(g)}if(n&&!Yt.includes(n)){let g=`${b} unknown saltStrategy: ${n}`;console.error(g),d.push(g)}if(d.length>0)return{errors:d,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let p=await sa({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});return{decryptedData:await kt(p),initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:l.length>0?l:void 0}}f(zr,"decryptImpl_stream");async function ia({dataToEncrypt:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,confirm:c,indexingMode:d}){let l=`[${ia.name}]`,b=[],p=[];e||(console.warn(`${l} initial recursions required. defaulting to ${Tt}`),e=Tt),t=t||Ft,n=n||Bt,s=s||Ut,o=o||await U(Mt),i=i||zt,d=d||mi;let u="[validation]";if(!e||e<1){let E=`${u} initialRecursions required, and greater than 0`;console.error(E),b.push(E)}if(!t||t<1){let E=`${u} recursionsPerHash required, and greater than 0`;console.error(E),b.push(E)}if(!r){let E=`${u} dataToEncrypt required`;console.error(E),b.push(E)}if(!o){let E=`${u} salt required`;console.error(E),b.push(E)}if(!n){let E=`${u} saltStrategy required`;console.error(E),b.push(E)}if(!a){let E=`${u} secret required`;console.error(E),b.push(E)}if(!i){let E=`${u} encryptedDataDelimiter required`;console.error(E),b.push(E)}if(!Pt.includes(d)){let E=`${u} invalid indexingMode (${d}). Must be one of ${Pt} (E: 5955c46755434982982823c97adcf076)`;console.error(E),b.push(E)}if(!Object.values(at).includes(s)){let E=`${u} only ${Object.values(at)} hash algorithms implemented`;console.error(E),b.push(E)}if(n&&!Yt.includes(n)){let E=`${u} unknown saltStrategy: ${n}`;console.error(E),b.push(E)}if(b.length>0)return{errors:b,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let g=await Yr(r);if(c&&await kt(g)!==r)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let m=await aa({hexEncodedData:g,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:"indexOf"});if(c){let E=await zr({encryptedData:m,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});if((E.errors||[]).length>0)return{errors:["Confirm check found that decrypt had errors.",...E.errors],initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};if(E.decryptedData){if(E.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");(E.warnings||[]).length>0&&(p=p.concat(["Confirm check call to decrypt had warnings.",...E.warnings]))}return{encryptedData:m,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:p.length>0?p:void 0}}f(ia,"encryptImpl_stream");async function ca({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c,maxBlockSize:d,numOfPasses:l}){let b=`[${ca.name}]`;try{let p=await jt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),u=c==="indexOf"?(T,_)=>T.indexOf(_):(T,_)=>T.lastIndexOf(_),g=[],m=r.length,E=d;E>m&&(E=m);let S=Math.ceil(m/E),A=m%E||E,I=0;for(let T=0;T<S;T++){T===S-1&&(E=A);let G=await Ei({blockSize:E,indexHexEncodedDataAtStartOfPass:I,numOfPasses:l,hexEncodedData:r,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:p,hashAlgorithm:s}),v=G.alphabetsThisBlock;p=G.prevHash;let N=await wi({alphabetsThisBlock:v,blockSize:E,indexHexEncodedDataAtStartOfPass:I,hexEncodedData:r,getIndexOfCharInAlphabet:u});g=g.concat(N),I+=E}return g.join(i)}catch(p){throw console.error(`${b} ${w(p)}`),p}}f(ca,"encryptFromHex_blockMode");async function Ei({blockSize:r,numOfPasses:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let d=`[${Ei.name}]`;try{let l=[],b,p;for(let u=0;u<e;u++)for(let g=0;g<r;g++){b=t+g;let m=l[g]??"";p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p,l[g]=m}for(let u=0;u<r;u++){b=t+u;let g=o[b],m=l[u];for(;!m.includes(g);)p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p;l[u]=m}return{alphabetsThisBlock:l,prevHash:i}}catch(l){throw console.error(`${d} error: ${w(l)}`),l}}f(Ei,"getAlphabetsThisBlock");async function wi({alphabetsThisBlock:r,blockSize:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,getIndexOfCharInAlphabet:n}){let a=`[${wi.name}]`;try{let s=[];for(let i=0;i<e;i++){let c=t+i,d=r[i],l=n(d,o[c]);s.push(l)}return s}catch(s){throw console.error(`${a} ${w(s)}`),s}}f(wi,"getEncryptedIndexesThisBlock");async function la({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,maxBlockSize:c,numOfPasses:d}){let l=`[${la.name}]`;try{let b=await jt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),p=r.split(i).map($=>parseInt($)),u=[],g=p.length,m=c;m>g&&(m=g);let E=Math.ceil(g/m),S=g%m||m,A=0;for(let $=0;$<E;$++){$===E-1&&(m=S);let _=await yi({blockSize:m,indexEncryptedDataIndexesAtStartOfPass:A,numOfPasses:d,encryptedDataIndexes:p,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:b,hashAlgorithm:s}),G=_.alphabetsThisBlock;b=_.prevHash;let v=await $i({alphabetsThisBlock:G,blockSize:m,indexEncryptedDataIndexesAtStartOfPass:A,encryptedDataIndexes:p});u=u.concat(v),A+=m}return u.join("")}catch(b){throw console.error(`${l} ${w(b)}`),b}}f(la,"decryptToHex_blockMode");async function yi({blockSize:r,numOfPasses:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let d=`[${yi.name}]`;try{let l=[],b,p;for(let u=0;u<e;u++)for(let g=0;g<r;g++){b=t+g;let m=l[g]??"";p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p,l[g]=m}for(let u=0;u<r;u++){b=t+u;let g=o[b],m=l[u];for(;m.at(g)===void 0;)p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p;l[u]=m}return{alphabetsThisBlock:l,prevHash:i}}catch(l){throw console.error(`${d} error: ${w(l)}`),l}}f(yi,"getAlphabetsThisBlock");async function $i({alphabetsThisBlock:r,blockSize:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o}){let n=`[${$i.name}]`;try{let a=[];for(let s=0;s<e;s++){let i=t+s,c=o[i],l=r[s][c];a.push(l)}return a}catch(a){throw console.error(`${n} ${w(a)}`),a}}f($i,"getDecryptedDataArrayThisBlock");async function Jr(r){let e=`[${Jr.name}]`,{encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,indexingMode:l,blockMode:b,multipass:p}=r,u=[],g=[];if(b&&p)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: b9b3cd1f701c700835c0419260278223)");if(!b&&p&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),b=p),!b)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");o=o||Tt,n=n||Ft,s=s||Bt,c=c||Ut,a=a||await U(Mt),d=d||zt,l=l||To;let{maxBlockSize:m,maxPassSectionLength:E,numOfPasses:S}=b;!m&&E&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`),m=E),m=m||Go,S=S||Co;let A="[validation]";if(!o||o<1){let _=`${A} initialRecursions required, and greater than 0`;console.error(_),u.push(_)}if(!n||n<1){let _=`${A} recursionsPerHash required, and greater than 0`;console.error(_),u.push(_)}if(!t){let _=`${A} encryptedData required`;console.error(_),u.push(_)}if(!a){let _=`${A} salt required`;console.error(_),u.push(_)}if(!s){let _=`${A} saltStrategy required`;console.error(_),u.push(_)}if(!i){let _=`${A} secret required`;console.error(_),u.push(_)}if(!d){let _=`${A} encryptedDataDelimiter required`;console.error(_),u.push(_)}if(!l){let _=`${A} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error(_),u.push(_)}if(!Pt.includes(l)){let _=`${A} invalid indexingMode (${l}). Must be one of ${Pt} (E: 17435268651444e0b7a594135635fc58)`;console.error(_),u.push(_)}if(m<1){let _=`${A} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error(_),u.push(_)}if(S<1){let _=`${A} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error(_),u.push(_)}if(!Object.values(at).includes(c)){let _=`${A} only ${Object.values(at)} hash algorithms implemented`;console.error(_),u.push(_)}if(s&&!Yt.includes(s)){let _=`${A} unknown saltStrategy: ${s}`;console.error(_),u.push(_)}if(u.length>0){let _={...r,errors:u};return delete _.encryptedData,delete _.secret,_}let I=await la({encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,maxBlockSize:m,numOfPasses:S}),$=await kt(I),T={...r,decryptedData:$,warnings:g.length>0?g:void 0};return delete T.encryptedData,delete T.secret,T}f(Jr,"decryptImpl_blockMode");async function da(r){let e=`[${da.name}]`,{dataToEncrypt:t,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,confirm:l,indexingMode:b,blockMode:p,multipass:u}=r,g=[],m=[];if(p&&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: bde5efd1a3e449dca549c5bff147f09b)");if(!p&&u&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),p=u),!p)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 ${Tt}`),o=Tt),d=d||zt,b=b||To;let{maxBlockSize:E,maxPassSectionLength:S,numOfPasses:A}=p;!E&&S&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`),E=S),E=E||Go,A=A||Co;let I="[validation]";if(!o||o<1){let G=`${I} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(G),g.push(G)}if(!n||n<1){let G=`${I} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(G),g.push(G)}if(!a){let G=`${I} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(G),g.push(G)}if(!s){let G=`${I} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(G),g.push(G)}if(!i){let G=`${I} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(G),g.push(G)}if(!d){let G=`${I} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(G),g.push(G)}if(!b){let G=`${I} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(G),g.push(G)}if(!Pt.includes(b)){let G=`${I} invalid indexingMode (${b}). Must be one of ${Pt} (E: 17435268651444e0b7a594135635fc58)`;console.error(G),g.push(G)}if(E<1){let G=`${I} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(G),g.push(G)}if(A<1){let G=`${I} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(G),g.push(G)}if(!Object.values(at).includes(c)){let G=`${I} only ${Object.values(at)} hash algorithms implemented`;console.error(G),g.push(G)}if(s&&!Yt.includes(s)){let G=`${I} unknown saltStrategy: ${s}`;console.error(G),g.push(G)}if(g.length>0){let G={...r,errors:g};return delete G.dataToEncrypt,delete G.secret,G}let $=await Yr(t);if(l&&await kt($)!==t)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let T=await ca({hexEncodedData:$,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,indexingMode:b,maxBlockSize:E,numOfPasses:A});if(l)try{let G=await Jr({encryptedData:T,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,indexingMode:b,blockMode:p});if(G.decryptedData){if(G.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)");(G.warnings||[]).length>0&&(m=m.concat(["Confirm check call to decrypt had warnings.",...G.warnings]))}catch(G){throw new Error(`${e} confirm failed. decrypt error: ${w(G)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let _={...r,encryptedData:T,warnings:m.length>0?m:void 0};return delete _.dataToEncrypt,delete _.secret,_}f(da,"encryptImpl_blockMode");async function Pd(r){let e=`[${Pd.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 U(Mt),r.saltStrategy=r.saltStrategy||Bt,r.hashAlgorithm=r.hashAlgorithm||Ut,r.recursionsPerHash=r.recursionsPerHash||Ft;let t;return r.blockMode?t=await da(r):t=await ia(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(Pd,"encrypt");async function kd(r){let e=`[${kd.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 U(Mt),r.saltStrategy=r.saltStrategy||Bt,r.hashAlgorithm=r.hashAlgorithm||Ut,r.recursionsPerHash=r.recursionsPerHash||Ft;let t;return r.blockMode||r.multipass?t=await Jr(r):t=await zr(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(kd,"decrypt");var Ru=5e4;var Pu=At.appendPerHash,ku=10,Bu="SHA-256";var Uu="encryption",Mu="ciphertext";var Bd={local:"local",outerspace:"outerspace",innerspace:"innerspace"},Hu=Object.values(Bd).concat(),Ud={user:"user",sync:"sync"},fa=Object.values(Ud).concat(),Md={node_filesystem:"node-filesystem"},Fd={aws_dynamodb:"aws-dynamodb"},jd={...Md,...Fd},ba=Object.values(jd).concat(),Vd={get:"get",put:"put",delete:"delete"},Hd={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var Kd=!1,Oo=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 s=0;s<32;s++){let i=Math.floor(Math.random()*n);t.push(o[i])}let a=t.join("");return Kd&&console.log(`${e} id: ${a} (I: c6591ffee6d5bbea79ed19cfa6630422)`),a}}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:mo({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:mo({min:0,max:155,chars:zn}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${zn}`,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:mo({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:Ge,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 Jt=class r extends Oo{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:a=!0,version:s=!0}){return t&&this.allowPrimitiveArgs({of:e.allowPrimitiveArgs}),o&&this.catchAllErrors({of:e.catchAllErrors}),n&&this.persistOptsAndResultIbGibs({of:e.persistOptsAndResultIbGibs}),a&&this.trace({of:e.trace}),s&&this.version({of:e.version}),this}};var No=!1;function Ii({appData:r}){let e=`[${Ii.name}]`;try{if(No&&console.log(`${e} starting...`),!r)throw new Error("appData required (E: 3df782b29bc4406a87e4895cfcea28ed)");let t=[],{name:o,uuid:n,classname:a}=r;return o?o.match(Wr)||t.push(`name must match regexp: ${Wr}`):t.push("name required."),n?n.match(Ge)||t.push(`uuid must match regexp: ${Ge}`):t.push("uuid required."),a&&(a.match(Wr)||t.push(`classname must match regexp: ${Wr}`)),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{No&&console.log(`${e} complete.`)}}f(Ii,"validateCommonAppData");function pa({appData:r,classname:e}){let t=`[${pa.name}]`;try{let o=Ii({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:a}=r;return`app ${e} ${n} ${a}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(pa,"getAppIb");function Xd({appIb:r}){let e=`[${Xd.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(Xd,"getInfoFromAppIb");async function qd({fnPromptApp:r,ibgibs:e,space:t}){let o=`[${qd.name}]`;try{if(No&&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 a=n.newIbGib,s=[];s.push(a),n.intermediateIbGibs?.forEach(l=>s.push(l)),n.dnas?.forEach(l=>s.push(l));for(let l=0;l<s.length;l++){let b=s[l],p=await ge({ibGib:b});if((p??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${p}. app: ${K(a.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await Ie({resTransform:n,space:t});let{zeroSpace:i,fnBroadcast:c,fnUpdateBootstrap:d}=e;return await Oe({ibGib:a,space:t,fnBroadcast:f(l=>c(l),"fnBroadcast")}),await Rr({type:"apps",rel8nName:Ao,ibGibsToRel8:[a],space:t,zeroSpace:i,fnUpdateBootstrap:d,fnBroadcast:c}),a}catch(n){debugger;console.error(`${o} ${n.message}`);return}finally{No&&console.log(`${o} complete.`)}}f(qd,"createNewApp");var Wd="0",Yd="chat_gib",zd="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",Si={version:"1",uuid:Wd,name:Yd,description:zd,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},_i=void 0;var Jd="0",Zd="raw_gib",Qd="Explorer app for navigating raw ibgib data.",Ai={version:"1",uuid:Jd,name:Zd,description:Qd,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Ti=void 0;var ha="0",ef="todo_gib",tf="Todo app for viewing and interacting with ibgibs like they're checklists.",Gi={version:"1",uuid:ha,name:ef,description:tf,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Ci=void 0;async function ua(r){let e=`[${ua.name}]`,t=[];try{y({ibGib:r})!==gr&&t.push(`invalid bootstrapSpace addr. Should equal "${gr}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await ge({ibGib:r});(n?.length??!1)&&n.forEach(i=>t.push(i));let a=r.data,s=r.rel8ns;return Object.keys(a||{}).length===0&&t.push("invalid bootstrapSpace data. data required (E: 5a9bd15dd0644f9b93cafbbba660cfdf)"),(a.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)"),a.spaceIds.forEach(i=>{(s[i]??[]).length===0&&t.push(`invalid bootstrap. Each spaceId listed in data should have a corresponding address in rel8ns. spaceId (${i}) missing. (E: 62dd0d76e29a415a98b4b27deb8db17e)`)}),a[_t]?(s[a[_t]]??[]).length===0&&t.push(`invalid bootstrap. data.${_t} (${a[_t]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):t.push(`invalid bootstrap. data.${_t} required. (E: f763af2e275f445cbf1db5801bacafad)`),t.length===0?!0:(console.error(`${e} errors: ${t.join("|")}`),!1)}catch(o){return console.error(`${e} ${o.message}`),!1}}f(ua,"validateBootstrapIbGib");var Pr="meta_stone";var ga="undefined",Zr="target",xo="targetTjp";var ft=!1;function Oi({ib:r}){let e=`[${Oi.name}]`;try{ft&&console.log(`${e} starting...`);let t=[],o=r.split(" ");o[0]!==Pr&&t.push(`${e} invalid ib. atom is expected to be META_STONE_ATOM: ${Pr} (E: a9812bffc18f44418aa091fb0ed260bd)`);let a=o[1],s=xr({gib:a})??[];s.length>0&&t.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${s} (E: 233db2babfbe4d28a80f98261f1c0e01)`);let i=o[2],c=Number.parseInt(i);isNaN(c)&&t.push("invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)");let d=o[3];if(d!=="undefined"){let l=Zt({timestamp:d});l.valid||t.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${l.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`)}return t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(Oi,"validateCommonMetaStoneIb");function ma({data:r}){let e=`[${ma.name}]`;try{if(ft&&console.log(`${e} starting...`),!r)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let t=[],{targetData:o,timestamp:n}=r;Zt({timestamp:n}).valid||t.push("invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)");let{tjpGib:s,n:i,timestamp:c}=o;if(s&&s!=="undefined"){let l=xr({gib:s})??[];l.length>0&&t.push(`invalid data (targetTjpGib). validation errors: ${l} (E: d216b12eb75544ef8c5ffb27cd132e2e)`)}if(typeof i!="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 l=Zt({timestamp:c});l.valid||t.push(`invalid targetTimestamp. emsg: ${l.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`)}let d=new Date(n);return t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(ma,"validateCommonMetaStoneData");function Ni({rel8ns:r}){let e=`[${Ni.name}]`;try{if(ft&&console.log(`${e} starting...`),!r)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let t=[],o=Yn({rel8ns:r??{}})??[];o.length>0&&t.push(`invalid rel8ns intrinsically. errors: ${o.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=r[Zr]??[];n.length===0?t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Zr}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Zr}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let a=r[xo]??[];return a.length>1&&t.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${xo}. has ${a.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(Ni,"validateCommonMetaStoneRel8ns");async function rf({ibGib:r}){let e=`[${rf.name}]`;try{ft&&console.log(`${e} starting... (I: f32249d08105b997871a06cdee006311)`);let t=await ge({ibGib:r})??[];if(!r.data)throw new Error("MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)");let o=[];try{let{atom:i,tjpGib:c,n:d,timestampInTicks:l}=Li({ib:r.ib})}catch(i){o.push(w(i))}let n=ma({data:r.data}),a=Ni({rel8ns:r.rel8ns}),s=[...t??[],...o??[],...n??[],...a??[]];return s.length>0?s:void 0}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(rf,"validateCommonMetaStoneIbGib");function xi({data:r,classname:e}){let t=`[${xi.name}]`;try{let o=ma({data:r});if(o.length>0)throw new Error(`invalid MetaStone data: ${o} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);e&&ft&&console.log(`${t} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`);let n=r.targetData.timestamp,a=n&&n!=="undefined"?ot(n):ga;return`${Pr} ${r.targetData.tjpGib} ${r.targetData.n} ${a}`}catch(o){throw console.error(`${t} ${w(o)}`),o}}f(xi,"getMetaStoneIb");function Li({ib:r}){let e=`[${Li.name}]`;try{if(!r)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let t=Oi({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} ${w(t)}`),t}}f(Li,"parseMetaStoneIb");function Gg({addr:r,ibGib:e}){if(r||=y({ibGib:e}),!r)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return r.startsWith(`${Pr} `)}f(Gg,"isMetaStone");async function Ea({targetIbGib:r}){let e=`[${Ea.name}]`;try{ft&&console.log(`${e} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let t=y({ibGib:r}),o=be({ibGib:r,defaultIfNone:"incomingAddr"}),n,a={[Zr]:[t],[xo]:[o]};if(!r.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let s=r.data?.isTjp?r.gib:De({ibGibAddr:t}).tjpGib??r.gib;if(s===re)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let i=new Date,c=oe(i),d=i.getMilliseconds();r.data?Qr({ibGib:r})?n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:d}:(n={targetData:{n:r.data.n??-1,tjpGib:s,timestamp:r.data.timestamp??ga},timestamp:c,timestampMs:d},r.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:d};let l=xi({data:n}),b=await mt({parentPrimitiveIb:Pr,ib:l,data:n,rel8ns:a});return ft&&(console.log(`${e} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(b)),b}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(Ea,"newUpMetaStone");var Lo="witness",eo="witness_arg",Do="witness_result",Og="context";var C=!1;async function te({addr:r,addrs:e,isDna:t,space:o,force:n}){let a=`[${te.name}]`;try{if(C&&console.log(`${a} 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(`${a} 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 s=await o.argy({ibMetadata:Vt({space:o}),argData:{cmd:"get",ibGibAddrs:e,isDna:t}}),i=await o.witness(s);return i?.data?.success?(C&&console.log(`${a} got.`),{success:!0,ibGibs:i.ibGibs,rawResultIbGib:i}):(C&&console.log(`${a} didn't get.`),{success:!1,errorMsg:i.data?.errors?.join("|")||`${a} something went wrong. addrs: ${e.join(`
|
|
2
|
+
`)} (E: b9e9d5ce0cde4122bfb74f7688db85e0)`,rawResultIbGib:i})}catch(s){return console.error(`${a} ${s.message}`),{errorMsg:s.message}}}f(te,"getFromSpace");async function Xe({ibGib:r,ibGibs:e,isDna:t,force:o,space:n}){let a=`[${Xe.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(`${a} 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],C&&console.log(`${a} ibGibs.length: ${e.length}`);let s=await n.argy({ibMetadata:Vt({space:n}),argData:{cmd:"put",force:o,isDna:t,ibGibAddrs:e.map(c=>y({ibGib:c}))},ibGibs:e.concat()}),i=await n.witness(s);if(i.data?.success)return(i.data.warnings??[]).length>0&&i.data.warnings.forEach(c=>console.warn(`${a} ${c}`)),{success:!0};{let c=i?.data?.errors?.length>0?`Error(s) putting in local space:
|
|
3
|
+
${i.data.errors.join(`
|
|
4
|
+
`)}`:"(UNEXPECTED) unknown error putting ibGibs (E: 3d7426d4527243b79c5e55eb25f3fa73)";throw new Error(c)}}catch(s){return console.error(`${a} ${s.message}`),{errorMsg:s.message}}}f(Xe,"putInSpace");async function ya({addr:r,isDna:e,space:t}){let o=`[${ya.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:Vt({space:t}),argData:{cmd:"delete",ibGibAddrs:[r],isDna:e}}),a=await t.witness(n);if(a.data?.success)return{success:!0};{a.data?.warnings?.length>0&&console.warn(`${o} warnings with delete (${r}): ${a.data.warnings.join("|")}`),a.data?.addrs?.length>0&&console.warn(`${o} partial addrs deleted: ${a.data.addrs.join("|")}`);let s=a.data?.errors?.join("|")||`${o} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;return s.includes("File does not exist")&&C&&console.log(`${o} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`),{errorMsg:s}}}catch(n){return console.error(`${o} ${n.message}`),{errorMsg:n.message}}}f(ya,"deleteFromSpace");async function Ie({resTransform:r,space:e,force:t}){let o=`[${Ie.name}]`;try{if(C&&console.log(`${o} starting... (I: dc6835614ff1a1b82b179225023ae823)`),!e)throw new Error("space required. (E: cf94f1d74f1c4561bb88025a2095965b)");let{newIbGib:n,intermediateIbGibs:a,dnas:s}=r,i=[n,...a||[]],c=await e.argy({ibMetadata:Vt({space:e}),argData:{cmd:"put",force:t,ibGibAddrs:i.map(l=>y({ibGib:l}))},ibGibs:i.concat()}),d=await e.witness(c);if(d.data?.success)d.data.warnings?.length>0&&d.data.warnings.forEach(l=>console.warn(`${o} ${l}`));else{let l=d?.data?.errors?.length>0?d.data.errors.join(`
|
|
5
|
+
`):"unknown error putting ibGibs";throw new Error(l)}if(s?.length??!1){let l=await e.argy({ibMetadata:Vt({space:e}),argData:{cmd:"put",isDna:!0,force:t,ibGibAddrs:s.map(p=>y({ibGib:p}))},ibGibs:s.concat()}),b=await e.witness(l);if(b.data?.success)b.data.warnings?.length>0&&b.data.warnings.forEach(p=>console.warn(`${o} ${p}`));else{let p=b?.data?.errors?.length>0?b.data.errors.join(`
|
|
6
|
+
`):"unknown error putting dna ibGibs";throw new Error(p)}}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{C&&console.log(`${o} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}f(Ie,"persistTransformResult");async function of({type:r,rel8nName:e,space:t}){let o=`[${of.name}]`;try{if(!t)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await ko({type:r,space:t});if(!n)throw new Error(`couldn't get special (${r}) (E: a65bef190416479697605be486846731)`);let a=n.rel8ns?n.rel8ns[e]||[]:[],s=[];for(let i=0;i<a.length;i++){let c=a[i],d=await te({addr:c,space:t});if(d.success&&d.ibGibs?.length===1)s.push(d.ibGibs[0]);else throw new Error(`couldn't get addr: ${c} (E: 76ef256ee80149ab860c5786484b0e89)`)}return s}catch(n){throw console.error(`${o} ${n.message}`),n}}f(of,"getSpecialRel8dIbGibs");async function ko({type:r,initialize:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:a,fnGetInitializing:s,fnSetInitializing:i,dontWarnIfNotExist:c}){let d=`[${ko.name}]`;try{if(!t)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let l=Ne({type:r}),b=await Bo({key:l,space:t,dontWarn:c||!!e});if(!b){if(e&&(!s||!i))throw new Error("if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)");if(e&&!s()){i(!0);try{if(!o)throw new Error("zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)");b=await Pi({type:r,space:t,zeroSpace:o,fnBroadcast:a,fnUpdateBootstrap:n})??void 0}catch(m){console.error(`${d} error initializing: ${m.message}`)}finally{i(!1)}}if(!b){if(s&&s())return console.warn(`${d} 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)")}}C&&console.log(`${d} getting addr: ${b}`);let p=await te({addr:b,space:t});if(p.success||(p=await te({addr:b,space:t}),p.success&&(console.warn(`${d} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await Xe({ibGib:p.ibGibs[0],space:t})).success||console.warn(`${d} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!p.success)throw new Error(p.errorMsg);if(p.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let u=p.ibGibs[0],g=await st({ibGibs:[u],space:t});if(g?.data?.success&&g.data.addrs?.length===1){let m=y({ibGib:u}),E=g.data.addrs[0];E!==m&&console.warn(`${d} latest addr is not the one associated with the local space.
|
|
7
|
+
specialAddr: ${m}
|
|
8
|
+
latestAddr: ${E} (W: 141b69dc3c414efc9645bb76fcf12df9)`)}return u}catch(l){let b=`${d} ${l.message}`;return b.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(b),null}}f(ko,"getSpecialIbGib");async function Bo({key:r,space:e,dontWarn:t}){let o=`[${Bo.name}](${r})`;try{if(C&&console.log(`${o} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!e)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!e.rel8ns){(C||!t)&&console.warn(`${o} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!e.rel8ns[r]){(C||!t)&&console.warn(`${o} space.rel8ns[${r}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(e.rel8ns[r].length===1)return C&&console.log(`${o} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),e.rel8ns[r][0];if(e.rel8ns[r].length>1)return(C||!t)&&console.warn(`${o} more than one config addr with ${r} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),e.rel8ns[r][0];C&&console.log(`${o} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${o} ${n.message}`);return}}f(Bo,"getConfigAddr");async function Fe({key:r,addr:e,space:t,zeroSpace:o,fnUpdateBootstrap:n}){let a=`[${Fe.name}]`;try{if(!t)throw new Error("space required. (E: c28b663c991d44419aef1026cc689636)");if(!o)throw new Error("zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)");let s={[r]:[e]},i=await Ke({src:t.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",r],rel8nsToAddByAddr:s,nCounter:!0});if(!i.newIbGib)throw new Error("create new space failed.");await Ie({resTransform:i,space:o}),await Ie({resTransform:i,space:t});let c=i.newIbGib;return await t.loadIbGibDto(c),n?await n(c):console.warn(`${a} fnUpdateBootstrap is falsy. (W: 9fb874de2b19454dac18645e61ac463f)`),c}catch(s){throw console.error(`${a} ${s.message}`),s}}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 ko({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 te({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 $a({root:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let a=`[${$a.name}]`;try{if(C&&console.log(`${a} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`),!r)throw new Error("root required.");if(!e)throw new Error("space required. (E: 186af2731c5342a78b063a0a4346f3db)");let s=y({ibGib:r}),i=await ko({type:"roots",space:e});if(!i)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let d=await Ke({src:i,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[s]},nCounter:!0});await Ie({resTransform:d,space:e});let l=Ne({type:"roots"}),b=d.newIbGib,p=y({ibGib:b});await Fe({key:l,addr:p,space:e,zeroSpace:t,fnUpdateBootstrap:o}),await Oe({ibGib:b,space:e,fnBroadcast:n})}catch(s){throw console.error(`${a} ${s.message}`),s}finally{C&&console.log(`${a} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}f($a,"setCurrentRoot");async function Ri({ibGib:r,linked:e,rel8nName:t,space:o,fnBroadcast:n,zeroSpace:a,fnUpdateBootstrap:s}){let i=`[${Ri.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 d=be({ibGib:r,defaultIfNone:"incomingAddr"}),l=y({ibGib:r});if(t&&d&&c.rel8ns&&c.rel8ns[t]&&c.rel8ns[t].includes(d))return;t=t||Qn;let b=await Ke({src:c,dna:!1,linkedRel8ns:e?["past","ancestor",t]:["past","ancestor"],rel8nsToAddByAddr:{[t]:[l]},nCounter:!0});await Ie({resTransform:b,space:o});let p=b.newIbGib,u=y({ibGib:p});C&&console.log(`${i} updating _currentRoot root. newRootAddr: ${u}`),await Oe({ibGib:p,space:o,fnBroadcast:n}),await $a({root:p,space:o,zeroSpace:a,fnUpdateBootstrap:s,fnBroadcast:n})}catch(c){console.error(`${i} ${c.message}`);return}}f(Ri,"rel8ToCurrentRoot");async function wa({targetIbGib:r,space:e}){let t=`[${wa.name}]`;try{C&&console.log(`${t} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let o=await Ea({targetIbGib:r}),n=await Xe({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} ${w(o)}`),o}finally{C&&console.log(`${t} complete.`)}}f(wa,"createAndSaveNewMetaStone");async function Oe({ibGib:r,space:e,fnBroadcast:t}){let o=`[${Oe.name}]`,n=C;try{let a=y({ibGib:r});if(o=`${o}[${a}]`,!e)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(C&&console.log(`${o} starting...`),!De({ibGibAddr:a}).tjpGib&&!r.data?.isTjp){C&&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 wa({targetIbGib:r,space:e});return}let i=be({ibGib:r,defaultIfNone:"undefined"});if(!i){let g=r.data?.isTjp?r:await to({ibGib:r,space:e});g||(console.warn(`${o} tjp not found for ${a}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`),g=r),i=y({ibGib:g})}if(!i)throw new Error("(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)");let c=f(async()=>{C&&console.log(`${o} adding/replacing latest. tjp: ${i} (I: 7f848da003a2436089fd6f044d96bb42)`),await wa({targetIbGib:r,space:e}),t&&(C&&console.log(`${o} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{C&&console.log(`${o} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),t({ib:"IbGibTimelineUpdateInfo",tjpAddr:i,latestAddr:a,latestIbGib:r})}))},"replaceLatest");if(r.data?.isTjp){C&&console.log(`${o} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}C&&console.log(`${o} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let d=await st({ibGibs:[r],space:e});if(!d.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:l,latestAddrsMap:b}=d.data;if(!l){let{errors:g}=d.data;throw g??=["[unknown error (E: 344857f1853641aa842cea3931f90428)]"],new Error(`resLatest.success falsy. errors: ${K(g)}. addr: ${a} (E: b66721da6e1ef9ac4f4089e86c059323)`)}if(!b)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let p=Object.keys(b);if(p.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(p[0]!==a)throw new Error(`(UNEXPECTED) latestAddrsMap has 1 key (correct) but the key isn't the incoming ibGibAddr? (incorrect). incoming ibGibAddr: ${a}. key found: ${p[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);C&&(console.log(`${o} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(b));let u=b[a];if(u)if(u===a){C&&console.log(`${o} no other found. possible idempotent replacement. addr: ${a} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{C&&console.log(`${o} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${u}. incoming addr: ${a} (I: 6cadf13f82aabeb71d76babf1813e623)`);let g=await te({addr:u,space:e});if(!g.success||g.ibGibs?.length!==1){console.error(`Didn't find existing latest ibGib (${u}). I haven't implemented more robust multi-node/distributed strategies for this scenario yet. so we are going ahead with setting the incoming ibgib as the latest in the timeline. (E: 10f6cca6e5ef45bfacbfe48f652e2102)`),await c();return}let m=g.ibGibs[0];if(typeof r.data?.n=="number"&&r.data.n>=0){C&&console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${r.data.n}`);let S=r.data.n;if(typeof m.data?.n=="number"&&m.data.n>=0){let I=m.data.n;if(S>I)C&&console.log(`${o} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{C&&console.log("is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)"),console.warn(`${o} incoming ibGib (${a}) is NOT NEWER than existing latest (${u}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${S}. n_existingLatest: ${I}. space.ib: ${e.ib} (W: 057baadca494473dabb26fb4fb879774)`);return}}else m.data?.isTjp&&r.data.n===0?await c():(console.warn(`${o} (UNEXPECTED) only existingLatestIbGib (isTjp: ${m.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(m),console.log(`${o} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(r),await c())}else if(C&&console.log(`${o} no nCounter found. Trying brute force method.`),await Wi({ibGib:r,ibGibAddr:a,existingLatest:m,existingLatestAddr:u,tjpAddr:i,space:e})===a)await c();else return}else if(u===null){C&&console.log(`${o} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${a} (I: 4f2bbc32b31e4fa982d95b3a785db82f)`),await c();return}else throw new Error("(UNEXPECTED) latestAddr is falsy but not null? the getLatestAddrs impl in the space should be guaranteed to provide either the incoming ibgib addr, the latest addr (if exists), or null if not found. (E: 3159dd531c0bc0efc1ece116adf28923)")}catch(a){throw console.error(`${o} ${a.message}`),a}finally{C&&console.log(`${o} complete.`),C=n}}f(Oe,"registerNewIbGib");async function Rr({type:r,rel8nName:e,ibGibsToRel8:t,ibGibsToUnRel8:o,addrsToUnRel8:n,linked:a,severPast:s,deletePreviousSpecialIbGib:i,space:c,zeroSpace:d,fnUpdateBootstrap:l,fnBroadcast:b}){let p=`[${Rr.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 u=t?.map(_=>y({ibGib:_}));n??=o?.map(_=>y({ibGib:_}));let g=Ne({type:r}),m=await Bo({key:g,space:c});if(!m)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let E=await te({addr:m,space:c});if(!E.success)throw new Error("couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)");if(!E.ibGibs)throw new Error("resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)");if(E.ibGibs.length!==1)throw new Error(`resGetSpecial.ibGibs count is not 1 (${E.ibGibs.length}) (E: b4547789016a4729af30cd972a4ca4ab)`);let S=E.ibGibs[0],A=await Ke({src:S,rel8nsToAddByAddr:u?{[e]:u}:void 0,rel8nsToRemoveByAddr:n?{[e]:n}:void 0,dna:!1,linkedRel8ns:a?[Ee.past,e]:[Ee.past],nCounter:!0}),I=A.newIbGib;if(s){if(A.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");I.rel8ns.past=[],I.gib=await ue({ibGib:I})}await Ie({resTransform:A,space:c});let $=y({ibGib:I}),T=be({ibGib:I});return await Fe({key:g,addr:$,space:c,zeroSpace:d,fnUpdateBootstrap:l}),i&&await ya({addr:m,space:c}),await Oe({ibGib:I,fnBroadcast:b,space:c}),$}catch(u){throw console.error(`${p} ${u.message}`),u}}f(Rr,"rel8ToSpecialIbGib");async function to({ibGib:r,naive:e=!0,space:t}){let o=`[${to.name}]`;try{if(!t)throw new Error("space required. (E: 941f973d50e84415b58724af173f52c2)");if(!r)throw new Error("ibGib required.");let n=y({ibGib:r}),{gib:a}=ae({ibGibAddr:n});if(a===re||await Ta({ibGib:r,naive:e}))return r;if(!r.rel8ns){C&&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],p=await te({addr:b,space:t});if(p.success&&p.ibGibs?.length===1)return p.ibGibs[0];{let u=p.errorMsg??"[unspecified error in get result]";throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${u} (E: 94f0340706ad48c794c6a62c1b235a22)`)}}let i=r.rel8ns.past||[];if(i.length===0){console.warn(`${o} past.length === 0, so there is no tjp.`),C&&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=i[i.length-1],d=await te({addr:c,space:t});if(!d.success||d.ibGibs?.length!==1)throw new Error(`get past failed. addr: ${c}`);let l=d.ibGibs[0];return await to({ibGib:l,naive:e,space:t})}catch(n){throw console.error(`${o} ${n.message}`),n}}f(to,"getTjpIbGib");async function Pi({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let a=`[${Pi.name}]`;try{if(!e)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(r){case"roots":return Ui({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"tags":return ki({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"secrets":return Fi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"encryptions":return ji({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"outerspaces":return Vi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"autosyncs":return Hi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"robbots":return Ki({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"apps":return Xi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});default:return qi({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o})}}catch(s){throw console.error(`${a} ${s.message}`),s}}f(Pi,"createSpecial");async function Ct({type:r,skipRel8ToRoot:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${Ct.name}][${r||"falsy type?"}]`;try{C&&console.log(`${s} starting...`);let i=_a({type:r}),c=F.primitive({ib:i}),d=await wo({src:c,destIb:i,linkedRel8ns:[Ee.past,Ee.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await Ie({resTransform:d,space:t}),r!=="roots"&&r!=="latest"&&!e&&await Ri({ibGib:d.newIbGib,linked:!0,space:t,zeroSpace:o,fnBroadcast:a,fnUpdateBootstrap:n}),C&&console.log(`${s} complete.`),d.newIbGib}catch(i){throw console.error(`${s} ${i.message}`),i}}f(Ct,"createSpecialIbGib");async function ki({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ki.name}]`;try{if(!r)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let a=Ne({type:"tags"}),s=await Ct({type:"tags",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),i=y({ibGib:s});await Fe({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t});let c=[{text:"home",icon:"home-outline"},{text:"favorite",icon:"heart-outline"}];for(let d of c)i=(await Bi({...d,space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t})).newTagsAddr,await Fe({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t});return i}catch(a){return console.error(`${n} ${a.message}`),null}}f(ki,"createSpecial_Tags");async function Bi({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Bi.name}]`;try{if(C&&console.log(`${i} starting...`),!o)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!r)throw new Error(`${i} text required`);e=e||si,t=t||ii;let c=mr(r),d=F.primitive({ib:"tag"}),l=await F.firstGen({parentIbGib:d,ib:c,data:{text:r,icon:e,description:t},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),b=l.newIbGib;await Ie({resTransform:l,space:o}),await Oe({ibGib:b,space:o,fnBroadcast:s});let p=await nf({tagIbGib:b,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newTagIbGib:b,newTagsAddr:p}}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(Bi,"createTagIbGibAndSundry");async function Ui({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ui.name}]`;try{if(!r)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let a=Ne({type:"roots"}),s=await Ct({type:"roots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),i=y({ibGib:s});await Fe({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t});let d=["A","B","C","D","E","F","G"].map(b=>({text:`${b}root`,icon:ea,description:ta})),l;for(let b=0;b<d.length;b++){let p=d[b],u=await Mi({...p,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o});if(l||(l=u.newRootIbGib),!u.newRootIbGib)throw new Error("(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)");i=u.newRootsAddr,await Fe({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t})}if(!l)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await $a({root:l,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),i=await Bo({key:a,space:r}),!i)throw new Error("(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)");return i}catch(a){return console.error(`${n} ${a.message}`),null}}f(Ui,"createSpecial_Roots");async function Mi({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Mi.name}]`;try{if(!o)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");r=r||ai,e=e||ea,t=t||ta;let c=Aa(r),d=F.primitive({ib:"root"}),l=await F.firstGen({parentIbGib:d,ib:c,data:{text:r,icon:e,description:t},linkedRel8ns:[Ee.past,Ee.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:b}=l;await Ie({resTransform:l,space:o});let p=await Rr({type:"roots",rel8nName:Zn,ibGibsToRel8:[b],space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newRootIbGib:b,newRootsAddr:p}}catch(c){throw console.error(`${i} ${c.message}`),c}}f(Mi,"createRootIbGib");async function Fi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Fi.name}]`;try{if(!r)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let a,s=Ne({type:"secrets"}),i=await Ct({type:"secrets",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await Fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Fi,"createSpecial_Secrets");async function ji({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ji.name}]`;try{if(!r)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let a,s=Ne({type:"encryptions"}),i=await Ct({type:"encryptions",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await Fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(ji,"createSpecial_Encryptions");async function Vi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Vi.name}]`;try{if(!r)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let a,s=Ne({type:"outerspaces"}),i=await Ct({type:"outerspaces",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await Fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Vi,"createSpecial_OuterSpaces");async function Hi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Hi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Ne({type:"autosyncs"}),i=await Ct({type:"autosyncs",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await Fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Hi,"createSpecial_Autosyncs");async function Ki({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ki.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Ne({type:"robbots"}),i=await Ct({type:"robbots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await Fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Ki,"createSpecial_Robbots");async function Xi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Xi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Ne({type:"apps"}),i=await Ct({type:"apps",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await Fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a=await Ro({defaultAppData:Si,defaultAppRel8ns:_i,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Ro({defaultAppData:Ai,defaultAppRel8ns:Ti,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Ro({defaultAppData:Gi,defaultAppRel8ns:Ci,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Xi,"createSpecial_Apps");async function Ro({defaultAppData:r,defaultAppRel8ns:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${Ro.name}]`;try{C&&console.log(`${s} starting... (I: 677f68789abdc7316887e8f38c764e22)`),C&&console.log(`${s} starting...`);let i=H(r),c=e?H(e):void 0;i.uuid=!i.uuid||i.uuid===ha?await U():i.uuid;let{classname:d}=i,l=pa({appData:i,classname:d}),b=await F.firstGen({ib:l,parentIbGib:F.primitive({ib:`app ${d}`}),data:i,rel8ns:c,dna:!0,linkedRel8ns:[Ee.ancestor,Ee.past],nCounter:!0,tjp:{timestamp:!0}});return await Ie({resTransform:b,space:t}),await Oe({ibGib:b.newIbGib,fnBroadcast:a,space:t}),await Rr({type:"apps",rel8nName:Ao,ibGibsToRel8:[b.newIbGib],fnBroadcast:a,fnUpdateBootstrap:n,space:t,zeroSpace:o})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{C&&console.log(`${s} complete.`)}}f(Ro,"createApp");async function qi({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let a=`[${qi.name}]`;try{if(!e)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");C&&console.log(`${a} creating special of type: ${r} (I: 283c8bb30ed6f9698b74b886c6078622)`);let s,i=Ne({type:r}),c=await Ct({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});return s=y({ibGib:c}),await Fe({key:i,addr:s,space:e,zeroSpace:t,fnUpdateBootstrap:o}),s}catch(s){return console.error(`${a} ${s.message}`),null}}f(qi,"createSpecial_Default");async function Wi({ibGib:r,ibGibAddr:e,existingLatest:t,existingLatestAddr:o,tjpAddr:n,space:a}){let s=`[${Wi.name}][${e}]`;try{if(C&&console.log(`${s} starting...`),!a)throw new Error("space required. (E: 64eb9a271f5d43deadec30b9638746c8)");let i=r.rel8ns?.past||[],c=t.rel8ns?.past||[];if(i.length===1&&c.length===0)return C&&console.log(`prospective has a past, so it "must" be newer. (won't quote "must" anymore)`),e;if(c.length===1&&i.length===0)return C&&console.log("existing has a past, so it must be newer."),o;if(c.length===0&&i.length===0)return console.warn(`${s} neither existing latest nor prospective new ibGib has a past, so keeping existing.`),o;if(c.includes(e))return C&&console.log("existing by definition is newer"),o;if(i.includes(o))return C&&console.log("ibGib by definition is newer"),e;if(o===e)return C&&console.log("they're the same!"),o;if(o===n&&t.rel8ns?.tjp?.length===1)return C&&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 C&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),o;C&&console.log(`${s} brute forcing through iterating the pasts.`);let d,l=-1,b=f(async(g,m,E)=>{let S=g.rel8ns?.past||[];if(S.includes(E))return d=y({ibGib:g}),-1;if(S.length===0)return m;let A=m+S.length;if(l!==-1&&A>l)return d=y({ibGib:g}),-1;let I=await te({addr:S[0],space:a});if(!I.success||I.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${S[0]}`);return b(I.ibGibs[0],m+S.length,E)},"getPastCount");C&&console.log(`${s} doing ibGibPastCount`);let p=await b(r,0,o);if(d)return d;C&&console.log(`${s} Doing existingPastCount`),l=p;let u=await b(t,0,e);return d||(p>u?(C&&console.log(`${s} ibGibPastCount (${p}) is longer than existingPastCount (${u}), so ibGib is newer.`),d=e):(C&&console.log(`${s} existingPastCount (${u}) is longer than ibGibPastCount (${p}), so ibGib is newer.`),d=o),d)}catch(i){throw console.error(`${s} ${i.message}`),i}finally{C&&console.log(`${s} complete.`)}}f(Wi,"getLatestAddr_Brute");function nf({tagIbGib:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){return Rr({type:"tags",rel8nName:ra,ibGibsToRel8:[r],space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n})}f(nf,"rel8TagToTagsIbGib");function Ia({space:r,scope:e}){let t=`[${Ia.name}]`;try{if(C&&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(ve);)C&&console.log(`${t} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),e=e.replace(ve,"_");let o=r.data.uuid,n=`${ri} ${o} ${e}`;return y({ib:n,gib:re})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{C&&console.log(`${t} complete.`)}}f(Ia,"getSpaceLockAddr");async function Gt({space:r,scope:e,secondsValid:t,maxDelayMs:o,fn:n,callerInstanceId:a,maxLockAttempts:s}){let i=`[${Gt.name}]`;try{if(C&&console.log(`${i} 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;C&&console.log(`${i} attempting to acquire lock with scope ${e} (I: fed36d42a975b1c52897a4df804ac722)`);let d;o=(o??0)>0?o:oi;let l=0;s=s??!1?s:ni;do{if(d=await Yi({space:r,scope:e,secondsValid:t,instanceId:a}),d?.data?.success)break;let p=Math.ceil(Math.random()*o);await Ce(p),l++}while(l<s);if(d?.data?.success)C&&console.log(`${i} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`);else throw new Error(`could not acquire lock after ${l} attempts with intermittent delays of ${o} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);let b=`${i}[fn]`;try{C&&console.log(`${b} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(p){throw console.error(`${b} ${p.message}`),p}finally{C&&console.log(`${b} unlocking space with scope: ${e} (I: 21034d9c3395499756e9000e40417d22)`),await zi({space:r,scope:e,instanceId:a}),C&&console.log(`${b} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(Gt,"execInSpaceWithLocking");async function Po({zeroSpace:r}){let e=`[${Po.name}]`;try{if(C&&console.log(`${e} starting...`),!r)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let t=gr;C&&console.log(`${e} getting from zeroSpace...`);let o=await r.argy({ibMetadata:Vt({space:r}),argData:{cmd:"get",ibGibAddrs:[t]}}),n=await r.witness(o);if(n?.data?.success&&n.ibGibs?.length===1){let a=n.ibGibs[0];return C&&console.log(`${e} bootstrapibGib found: ${K(a)}`),await ua(a)?a:(C&&console.log(`${e} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return C&&console.log(`${e} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(t){throw console.error(`${e} ${t.message}`),t}finally{C&&console.log(`${e} complete.`)}}f(Po,"getValidatedBootstrapIbGib");async function af({zeroSpace:r,bootstrapIbGib:e,localSpaceId:t,lock:o,callerInstanceId:n,fnDtoToSpace:a,localSpaceCacheSvc:s}){let i=`[${af.name}]`;try{if(!r)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!e)if(C&&console.log(`${i} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),o){let l=gr;C&&console.log(`${i} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),e=await Gt({space:r,scope:l,fn:f(async()=>{let b=await Po({zeroSpace:r});if(b)return b;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:Jn})}else C&&console.log(`${i} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),e=await Po({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[_t];let c=e.rel8ns[t][0],d=f(async()=>{let l=await r.argy({ibMetadata:Vt({space:r}),argData:{cmd:"get",ibGibAddrs:[c]}}),b=await r.witness(l);if(b?.data?.success&&b.ibGibs?.length===1){let p=b.ibGibs[0],u=await a(p);return s&&(u.cacheSvc=s),u}else throw new Error(`Could not get local space addr (${c}) specified in bootstrap space (${y({ibGib:e})}). (E: 6d6b45e7eae4472697ddc971438e4922)`)},"fnGet");return o?(C&&console.log(`${i} getting localSpaceId (${t}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await Gt({space:r,scope:t,fn:f(()=>d(),"fn"),callerInstanceId:n,secondsValid:Jn})):(C&&console.log(`${i} getting localSpaceId (${t}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),d())}catch(c){throw console.error(`${i} ${c.message}`),c}}f(af,"getLocalSpace");async function Yi({space:r,scope:e,secondsValid:t,instanceId:o}){let n=`[${Yi.name}]`;try{if(C&&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 a,s=Ia({space:r,scope:e}),i,c=await te({addr:s,space:r,force:!0});if(c.success&&c.ibGibs?.length===1?(i=c.ibGibs[0],i?.data?.expirationUTC?Hn({expirationTimestampUTC:i.data.expirationUTC})&&(console.warn(`${n} ignoring expired existing lock in space at ${s}. Should be overwritten (W: 7421c5b051724b189f88cecbbd449b22)`),i=void 0):(console.error(`${n} (UNEXPECTED) exisingLock.data.expirationUTC falsy? (E: 218dc0e935534a149d0be153c532cf25)`),i=void 0)):C&&console.log(`${n} existing lock not found for ${s} (I: 191af56ec4e2db3d19084e46bf949222)`),i){if(!i.data)throw new Error("(UNEXPECTED) existingLock.data falsy? (E: 00069b4662e5566d971760d15e293723)");a=H(i),a.data.alreadyLocked=!0,a.data.success=!1}else{let{ib:d,gib:l}=ae({ibGibAddr:s});a={ib:d,gib:l,data:{scope:e,secondsValid:t,instanceId:o,expirationUTC:Vn({seconds:t})}};let b=await r.argy({ibMetadata:Vt({space:r}),argData:{cmd:"put",force:!0,ibGibAddrs:[s]},ibGibs:[a]}),p=await r.witness(b);if(p.data?.success)if((p.data.addrsAlreadyHave??[]).includes(s)){C&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${s}) (I: 2e8a1562947c40698110b64251141753)`);let u=await te({addr:s,space:r,force:!0});if(u.success&&u.ibGibs?.length===1){let g=u.ibGibs[0];a=H(g),a.data.alreadyLocked=!0,a.data.success=!1}else{let g=`${n} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;console.error(g),a.data.success=!1,a.data.errorMsg=g}}else a.data.success=!0;else{let u=`${n} there was an error putting the lock in the space: ${p.data?.errors?.join("|")}`;a.data.success=!1,a.data.errorMsg=u,console.error(u)}}return a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{C&&console.log(`${n} complete.`)}}f(Yi,"lockSpace");async function zi({space:r,scope:e,instanceId:t}){let o=`[${zi.name}]`;try{if(C&&console.log(`${o} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=Ia({space:r,scope:e}),a=await ya({addr:n,space:r,force:!0});if(a.success){let{ib:s,gib:i}=ae({ibGibAddr:n});return{ib:s,gib:i,data:{success:!0,instanceId:t,scope:e}}}else{let s=`Delete lock in space failed. delete errorMsg: ${a.errorMsg}`;if(s.includes("not implemented"))throw new Error(s);if(s.toLowerCase().includes("does not exist")||s.toLowerCase().includes("doesn't exist")||s.toLowerCase().includes("not found")){C&&console.log(`${o} ${s} (I: b647916fd0f3e5366e9387131be21c22)`);let{ib:i,gib:c}=ae({ibGibAddr:n});return{ib:i,gib:c,data:{action:"unlock",success:!0,instanceId:t,scope:e}}}else console.warn(`${o} ${s} (W: 14c84fcac15944bd9a417099964d5d9d)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{C&&console.log(`${o} complete.`)}}f(zi,"unlockSpace");async function sf({space:r,zeroSpace:e,setSpaceAsDefault:t,createIfNotFound:o}){let n=`[${sf.name}]`;try{if(C&&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 a=r.data.uuid,s=y({ibGib:r}),i=await Po({zeroSpace:e});if(i){if(C&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),i.data.spaceIds.includes(a)){C&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let l=i.rel8ns[a][0];l===s?C&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(C&&console.log(`${n} updating rel8ns[${a}] with newSpaceAddr (${s}). (Old address: ${l})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),i.rel8ns[a]=[s])}else C&&console.log(`${n} new space being rel8d. adding spaceId to data.spaceIds and amending rel8ns (I: 40903d71719aa1d56e498299f5699a22)`),i.data.spaceIds.push(a),i.rel8ns[a]=[s];t&&(C&&console.log(`${n} setting spaceId (${a}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),i.data[_t]=a)}else{if(!o){C&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}C&&console.log(`${n} creating new bootstrap ibgib for spaceId (${a}) with address of (${s}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:l,gib:b}=ae({ibGibAddr:gr});i=F.primitive({ib:l}),i.gib=b,i.data={[_t]:a,[bi]:[a]},i.rel8ns={[a]:[s]}}if(!i)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");C&&console.log(`${n} saving bootstrapIbGib: ${K(i)} (I: 3cceca0b98dde90e4a58a734be252322)`);let c=await e.argy({ibMetadata:i.ib,argData:{cmd:"put",force:!0,ibGibAddrs:[y({ibGib:i})]},ibGibs:[i]});C&&console.log(`${n} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let d=await e.witness(c);if(d?.data?.success)C&&console.log(`${n} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`);else throw new Error(`${d?.data?.errors?.join("|")||"There was a problem with zeroSpace witnessing the bootstrap^gib primitive pointing to the new user space"}`);C&&console.log(`${n} complete.`)}catch(a){throw console.error(`${n} ${a.message}`),a}}f(sf,"updateBootstrapIbGib");function Vt({space:r}){return`${r.ib} ${ot()}`}f(Vt,"getSpaceArgMetadata");function om({space:r}){return`${r.ib} ${ot()}`}f(om,"getSpaceResultMetadata");function cf({space:r,spaceData:e,classname:t}){let o=`[${cf.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||ti;if(n.includes(" "))throw new Error("invalid space name. cannot contain spaces (E: a8450e1651081412c8ac018520182422)");let a=e?.uuid||void 0;if(!a)throw new Error("invalid space, spaceData.uuid falsy (E: 50ae723a9ab24f4fc7132613e65faf23)");if(a.includes(" "))throw new Error("invalid space id. cannot contain spaces (E: 8696830fe7f54bfa85e670a063f3e089)");let s=e.type??void 0,i=e.subtype??void 0;if(s&&!i)throw new Error(`spaceType (${s}) is set but spaceSubtype is falsy. (E: 878ab960d7987ae2331103b4a00d0d24)`);return`${Lo} ${So} ${t} ${n} ${a} ${s} ${i}`}catch(n){throw console.error(`${o} ${n.message}`),n}}f(cf,"getSpaceIb");function lf({ib:r}){let e=`[${lf.name}]`;if(!r){let t=`${e} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(t),new Error(t)}return r.startsWith(`${Lo} ${So} `)}f(lf,"isSpaceIb");function df({spaceIb:r}){let e=`[${df.name}]`;try{if(!r)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[t,o,n,a,s,i,c]=r.split(" ");if(t!==Lo)throw new Error(`invalid spaceIb (${r}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(o!==So)throw new Error(`invalid spaceIb (${r}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`);if(!n)throw new Error(`invalid spaceIb (${r}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`);if(!a)throw new Error(`invalid spaceIb (${r}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`);if(!s)throw new Error(`invalid spaceIb (${r}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`);let d;if(i&&i!=="undefined")if(fa.includes(i))d=i;else throw new Error(`invalid spaceIb (${r}). spaceType (${i}) is set but not a valid type. valid types: ${fa.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let l;if(c&&c!=="undefined")if(ba.includes(c))l=c;else throw new Error(`invalid spaceIb (${r}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${ba.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:a,spaceId:s,spaceType:d,spaceSubtype:l}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(df,"parseSpaceIb");async function st({ibGibs:r,addrs:e,tjps:t,tjpAddrs:o,space:n}){let a=`[${st.name}]`;try{if(C&&console.log(`${a} 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 s=new Set(o.concat(t.map(d=>y({ibGib:d})))),i=Array.from(s).map(d=>ae({ibGibAddr:d}).gib);r.map(d=>y({ibGib:d})).concat(e).forEach(d=>{let{gib:l}=ae({ibGibAddr:d});i.some(p=>l.includes(p))||s.add(d)}),C&&console.log(`${a}[testing] ${n.data?.name||n.ib} (${n.data?.uuid||"[space.data.uuid falsy]"}) addrsToQuery: ${Array.from(s)} (I: 8a2202912c364238b6d6eb09577bc246)`);let c=await n.argy({ibMetadata:Vt({space:n}),argData:{cmd:"get",cmdModifiers:["latest","addrs"],ibGibAddrs:Array.from(s)}});return await n.witness(c)}catch(s){throw console.error(`${a} ${s.message}`),s}}f(st,"getLatestAddrs");function Sa({ibGib_Context:r}){let e=`[${Sa.name}]`;try{if(C&&console.log(`${e} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!ro({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{C&&console.log(`${e} complete.`)}}f(Sa,"throwIfContextIsSpecial");async function ff({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${ff.name}]`;try{if(C&&console.log(`${i} 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=ro({ibGib:r});c&&Sa({ibGib_Context:r});let d=await Ke({src:r,rel8nsToAddByAddr:{[li]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await Ie({resTransform:d,space:o}),c){let l=y({ibGib:d.newIbGib}),b=Uo({ib:r.ib}),p=Ne({type:b});await Fe({key:p,addr:l,space:o,zeroSpace:n,fnUpdateBootstrap:a})}await Oe({ibGib:d.newIbGib,fnBroadcast:s,space:o})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(ff,"trash");async function bf({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${bf.name}]`;try{if(C&&console.log(`${i} 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=ro({ibGib:r});c&&Sa({ibGib_Context:r});let d=await Ke({src:r,rel8nsToAddByAddr:{[ci]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await Ie({resTransform:d,space:o}),c){let l=y({ibGib:d.newIbGib}),b=Uo({ib:r.ib}),p=Ne({type:b});await Fe({key:p,addr:l,space:o,zeroSpace:n,fnUpdateBootstrap:a})}await Oe({ibGib:d.newIbGib,fnBroadcast:s,space:o})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(bf,"archive");function pf(r){let e=`[${pf.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(pf,"spaceNameIsValid");var Pe=!1;async function Ga({ibGib:r,rel8nNames:e,space:t}){let o=`[${Ga.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 a of e){let s=r.rel8ns?.[a]||[];if(s.length>0){let i=await te({addrs:s,space:t});if(i.success&&i.ibGibs?.length===s.length)n[a]=i.ibGibs.concat();else throw new Error(`Problem getting rel8d ibgibs for rel8nName: ${a}. ${i.errorMsg||"Unknown error"} (E: c5e3d4f5a6b7c8d9e0f1a2b3c4d5e6)`)}else n[a]=[]}return n}catch(n){throw console.error(`${o} ${w(n)}`),n}}f(Ga,"getRel8dIbGibs");async function mt({parentPrimitiveIb:r,ib:e,ibRegExpPattern:t,data:o,rel8ns:n}){let a=`[${mt.name}]`;try{if(!r)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(Dr({ib:r})!==null)throw new Error(`Invalid parentPrimitiveIb: ${r}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`);if(!e)throw new Error("ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)");let s=t?new RegExp(t):Qs;if(!e.match(s))throw new Error(`invalid ib. does not match regexp (${s})`);let i=Object.keys(n??{}),c=[...hr,"tjp"];if(i.some(p=>c.includes(p)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let b=(await F.firstGen({ib:e,parentIbGib:F.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 ue({ibGib:{ib:b.ib,data:b.data,rel8ns:b.rel8ns},hasTjp:!1}),b}catch(s){throw console.error(`${a} ${s.message}`),s}}f(mt,"constantIbGib");function Em({addr:r}){return Ji({addr:r})}f(Em,"getBinHashAndExt");function Ji({addr:r}){let e=`[${Ji.name}]`;try{if(!Qr({addr:r}))throw new Error("not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)");let{ib:t}=ae({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(Ji,"parseBinIb");function Qr({ibGib:r,addr:e}){let t=`[${Qr.name}]`;try{if(!r&&!e)throw new Error("either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)");if(r&&!r.data)return!1;e=e||y({ibGib:r});let{ib:o,gib:n}=ae({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 a=o.split(" ");if(a.length===2){if(!a[1].match(Ge))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)')}else if(a.length===3){if(!a[1].match(Ge))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)')}else if(a.length===4){if(!a[1].match(Ge))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)');if(!a[3].startsWith("enc="))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[3].startsWith("enc=")? (E: 4c8a0c3b07a90d30e3d1a4373d57d824)')}else throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited ibPieces length is not 2, 3 or 4? (E: c7eccf88518304997c7e42b32e08d224)');return!0}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Qr,"isBinary");function _a({type:r}){if(!r.match(oa))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${oa.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${r}`}f(_a,"getSpecialIbGibIb");function Uo({ib:r}){let e=`[${Uo.name}]`;try{if(Pe&&console.log(`${e} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!r)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!ro({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(Io).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{Pe&&console.log(`${e} complete.`)}}f(Uo,"getSpecialTypeFromIb");function hf({type:r}){return`${_a({type:r})}^${re}`}f(hf,"getSpecialIbGibAddr");function Ne({type:r}){return`${fi} ${hf({type:r})}`}f(Ne,"getSpecialConfigKey");function ro({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(ro,"isSpecial");function Aa(r){let e=`[${Aa.name}]`;if(!r)throw new Error(`${e} text required.`);return`root ${r}`}f(Aa,"getRootIb");function mr(r){let e=`[${mr.name}]`;if(!r)throw new Error(`${e} tag required.`);return`tag ${r}`}f(mr,"tagTextToIb");function vt({ibGibs:r,filterPrimitives:e}){let t=`[${vt.name}]`;try{let o={},n={},a={};return(e?r.filter(i=>i.gib??i.gib!==re):r).forEach(i=>{Zi({ibGib:i})?(i.rel8ns?.dna??[]).length>0?o[i.gib]=i:n[i.gib]=i:a[i.gib]=i}),{mapWithTjp_YesDna:o,mapWithTjp_NoDna:n,mapWithoutTjps:a}}catch(o){throw console.error(`${t} ${o.message}`),o}}f(vt,"splitPerTjpAndOrDna");function bt({ibGibs:r}){let e=`[${bt.name}]`;try{Pe&&console.log(`${e} starting...`);let{mapWithTjp_YesDna:t,mapWithTjp_NoDna:o}=vt({ibGibs:r,filterPrimitives:!0}),n={...t,...o},a=Object.values(n),s=jn({items:a,keyFn:f(i=>i.data?.isTjp?y({ibGib:i}):i.rel8ns?.tjp?i.rel8ns?.tjp[0]??"":(Pe&&console.log(`${e} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return Pe&&console.log(`${e} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${K(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),Object.entries(s).forEach(([i,c])=>{c.some(d=>d.data?.n===void 0)&&console.warn(`${e} timeline includes ibgibs with ibGib.data?.n === undefined (W: cab9a6b64a38c4279fe82c3569bbab22)`),c.sort((d,l)=>(d.data?.n??-1)>(l.data?.n??-1)?1:-1)}),Pe&&console.log(`${e} after sort ibGibsWithTjpGroupedByTjpAddr: ${K(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),s}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(bt,"getTimelinesGroupedByTjp");function Zi({ibGib:r}){let e=`[${Zi.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(St)?!0:r.gib===re?!1:!!De({ibGibAddr:y({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(Zi,"hasTjp");function be({ibGib:r,defaultIfNone:e="undefined"}){let t=`[${be.name}]`;try{let o=Qi({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(be,"getTjpAddr");function Qi({ibGibs:r,defaultIfNone:e="undefined"}){let t=`[${Qi.name}]`;try{let o={};return r.forEach(n=>{let a=y({ibGib:n}),s;n.rel8ns?.tjp?.length??!1?s=n.rel8ns.tjp[n.rel8ns.tjp.length-1]:n.data?.isTjp||e==="incomingAddr"?s=a:s=void 0,o[a]=s}),o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Qi,"getTjpAddrs");async function Ta({ibGib:r,naive:e=!0}){let t=`[${Ta.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):(Pe&&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(Ta,"isTjp_Naive");function qe({ibGib:r}){let e=`[${qe.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&&(Qr({ibGib:r})?t.data=r.data.slice():t.data=H(r.data)),r.rel8ns&&(t.rel8ns=H(r.rel8ns)),t}f(qe,"toDto");function oo(r){let e=`[${oo.name}]`;try{return Pe&&console.log(`${e} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!r&&typeof r.ib=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(oo,"isIbGib");function Zt({ibGib:r,data:e,timestamp:t}){let o=`[${Zt.name}]`;try{Pe&&console.log(`${o} starting... (I: 35cb68744bcf6139d78e37de644fad23)`),t=t||e?.timestamp||r?.data?.timestamp;let n=r?.data?.timestampMs||e?.timestampMs;if(!t){let a=`${o} timestamp is falsy. (W: 5f1f1182c8804807b886a3d922ac3dcf)`;return console.warn(a),{valid:!1,emsg:a}}if(typeof t=="string")if(Number.isInteger(Number.parseInt(t))){let a=Number.parseInt(t),s=new Date;if(s.setTime(a),s.toString()!==_o)return Pe&&console.log(`${o} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`),{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${o} data.timestamp (${t}) is an integer string but not a valid timestampInTicks string. (produces invalid date) (E: f49fbb600fe1426c8805dfc8afbe5cf3)`;return console.error(i),{valid:!1,emsg:i}}}else{let a=new Date(t);if(a.toString()!==_o)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${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(s),{valid:!1,emsg:s}}}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 a=new Date;if(a.setTime(t),a.toString()!==_o)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${o} timestamp (${t}) is an integer number but not a valid timestampInTicks (new date setTime produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(s),{valid:!1,emsg:s}}}else{let a=`${o} timestamp (${t}) is a non-integer number (supposed to be a string either timestamp string or ticks). (E: 2963d95f8d3b464c992b0bff948b4479)`;return console.error(a),{valid:!1,emsg:a}}else{let a=`${o} unknown typeof timestamp (${typeof t}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;return console.error(a),{valid:!1,emsg:a}}}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{Pe&&console.log(`${o} complete.`)}}f(Zt,"getTimestampInfo");async function it({addrs:r,readCache_graph:e,readCache_array:t,space:o}){let n=`[${it.name}]`;try{Pe&&console.log(`${n} starting... (I: 5db66871239dfa05182277f886a20926)`),e??={},t??=[];let a={...e};t.forEach(d=>a[y({ibGib:d})]=d);let s=Object.keys(e),i=r.filter(d=>!s.includes(d));if(i.length>0){Pe&&console.log(`${n} ${i.length} addrsNotFoundInCache: ${i} (I: fccbd18116ffb849f813aaebfc6c0826)`);let d=[o],l=i.concat();for(let b of d){let p=await te({addrs:l,space:b});if(p.success&&p.ibGibs&&p.ibGibs.length===l.length)p.ibGibs.forEach(u=>a[y({ibGib:u})]=u),l=[];else if(p.ibGibs&&p.ibGibs.length>0){if(l=l.filter(u=>!p.ibGibs.some(g=>y({ibGib:g})===u)),l.length===0)break}else Pe&&console.log(`${n} no addrs found in space (${b.ib}). trying next space. (I: 4f99d8bacbb10ab3f8737a752564b326)`)}if(l.length>0)throw new Error(`could not get all addrs from cache or spaces. addrsStillNotFound: ${l}. spaces: ${d.map(b=>b.ib).join("|")} (E: 0c6418f83dd85bda886e56f5b98f3126)`)}let c=[];for(let d of r){let l=a[d];if(!l)throw new Error(`(UNEXPECTED) allIbGibs_graph doesn't have addr? We're expecting logic to preclude this at this point. addr: ${d} (E: f68e1d236ae5e3eb08da9933c8230626)`);c.push(l)}return c}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Pe&&console.log(`${n} complete.`)}}f(it,"getIbGibsFromCache_fallbackToSpaces");var no=!1,uf="space_gib_db",gf="space_gib_store",mf="space_gib_api_key";var Ef="agent";var Sm=mr(Ef);var _m={dbName:uf,storeName:gf,additionalStoreNames:[ei],apiKeyName:mf};var ec="0.0.4";var Qt=!1,Cm="[web^gib timer]",Ca="ibgib";var wf="agent",vm="body-outline",Om="This tag tracks the active agents for the current local user space.",Nm=mr(wf),tc="#78f87e88",rc="#78f87e10",oc="#ffffff";var xm="AUTOMATED_TEXT";var Et=!1;function nc(r){return new Promise((e,t)=>{let o=new Blob([r],{type:"application/octet-stream"}),n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1];e(s)},n.onerror=a=>t(a),n.readAsDataURL(o)})}f(nc,"uint8ArrayToBase64");async function ac(r){let e=`data:application/octet-stream;base64,${r}`,n=await(await(await fetch(e)).blob()).arrayBuffer();return new Uint8Array(n)}f(ac,"base64ToUint8Array");async function Mo({graph:r}){let e=`[${Mo.name}]`;try{Et&&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 nc(r[n].data)});let o=JSON.stringify(t);return Et&&console.log(`${e} jsonString.length: ${o.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),o}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(Mo,"serializeGraphToString");async function Fo({jsonString:r}){let e=`[${Fo.name}]`;try{Et&&console.log(`${e} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`);let o=JSON.parse(r,f((n,a)=>(a&&a._dataType==="Uint8Array_Base64",a),"reviver"));for(let n in o){let a=o[n].data;a&&a._dataType==="Uint8Array_Base64"&&(o[n].data=await ac(a.value))}return o}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(Fo,"deserializeStringToGraph");async function sc(r){let e=`[${sc.name}]`;try{Et&&console.log(`${e} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let t=await Mo({graph:r}),o=new TextEncoder().encode(t),a=new Response(o).body.pipeThrough(new CompressionStream("gzip"));return await new Response(a).blob()}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(sc,"compressIbGibToBlob");async function yf(r){let e=r.stream().pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).text();return await Fo({jsonString:t})}f(yf,"decompressIbGibFromBlob");async function va({graph:r}){let e=`[${va.name}]`;try{Et&&console.log(`${e} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let o=await(await sc(r)).arrayBuffer(),n=new Uint8Array(o);return await nc(n)}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(va,"compressIbGibGraphToString");async function Oa({compressedBase64:r}){let e=`[${Oa.name}]`;try{Et&&console.log(`${e} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let t=await ac(r),o=new Blob([t],{type:"application/gzip"});return await yf(o)}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(Oa,"decompressIbGibGraphFromString");var ic="export";var ao=!1;function cc({data:r}){let e=`[${cc.name}]`;try{ao&&console.log(`${e} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:t,dependencyGraphAsString:o,timestamp:n}=r,a=o.length,s=ot(n),i=r.compression==="gzip"?"gzip":"raw";if(!r.timestamp)throw new Error("(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)");let c=new Date(r.timestamp),{ib:d,gib:l}=ae({ibGibAddr:r.contextIbGibAddr}),p=De({gib:l}).tjpGib??l,u=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${ic} ${u} ${i} ${t} ${a} ${p}`}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ao&&console.log(`${e} complete.`)}}f(cc,"getRawExportIb");async function Na({ibGib:r,metaspace:e,space:t,compress:o,live:n,ignoreErrors:a}){let s=`[${Na.name}]`;try{if(ao&&console.log(`${s} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let i=y({ibGib:r}),c=[],d=await ge({ibGib:r})??[];if(d.length>0){let S=`ibGib had validation errors: ${d} (E: 84890bbc0598192498178a98ae299825)`;if(a)c.push({errorMsg:S,ibGibAddr:i});else throw new Error(S)}let l=await e.getDependencyGraph({ibGib:r,live:n,space:t}),b=o?await va({graph:l}):await Mo({graph:l}),p=be({ibGib:r,defaultIfNone:"incomingAddr"})??i,u=new Date,g={contextIbGibAddr:i,tjpAddr:p,dependencyGraphAsString:b,graphSize:Object.keys(l).length,timestamp:oe(u),timestampMs:u.getMilliseconds()};o&&(g.compression="gzip");let m={ib:cc({data:g}),data:g},E=await ue({ibGib:m,hasTjp:!1});return m.gib=E,console.log(`${s} JSON.stringify(exportIbGib).length: ${JSON.stringify(m).length} (I: db3a8d913a91d8fc5d6e45981e034822)`),{rawExportIbGib:m,manifest:Object.keys(l),errors:c.length>0?c:void 0}}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{ao&&console.log(`${s} complete.`)}}f(Na,"getRawExportIbGib");var Ym="ibgib-shell-ready",zm="ibgib-ui-busy",Jm="ibgib-ui-message",Zm="ibgib-identity-request-change",Qm="ibgib-identity-changed";var lc=Qt;async function kr({title:r,msg:e,prompt:t,showInput:o,defaultValue:n,okButtonTitle:a,cancelButtonTitle:s,isPassword:i,isBusy:c,animationEmoji:d}){let l=`[${kr.name}]`;try{lc&&console.log(`${l} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let b=document.getElementById("fullscreen-dialog"),p=document.getElementById("fullscreen-dialog-body"),u=document.getElementById("fullscreen-dialog-title"),g=document.getElementById("fullscreen-dialog-message"),m=document.getElementById("fullscreen-dialog-prompt-input"),E=document.getElementById("fullscreen-dialog-ok-button"),S=document.getElementById("fullscreen-dialog-cancel-button");if(!b||!p||!u||!g||!m||!E||!S)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(u.textContent=r||"",[...g.childNodes].forEach($=>g.removeChild($)),(e||"").split(`
|
|
9
|
+
`).forEach($=>{let T=document.createElement("p");T.textContent=$,g.appendChild(T)}),d){let $=document.createElement("div");$.id="fullscreen-dialog-animation-emoji",$.textContent=d,$.style.fontSize="3.5rem",$.style.textAlign="center",$.style.margin="1.5rem 0",$.style.animation="spin-bounce 5s infinite ease-in-out",g.appendChild($)}m.classList.remove("collapsed"),S.classList.remove("collapsed"),S.style.display="inline-block",E.style.display="inline-block",E.textContent=a||"OK";let I=f($=>{($.key==="Enter"||$.key===`
|
|
10
|
+
`)&&$.ctrlKey&&E.click()},"onKeypress");return c?(m.classList.add("collapsed"),S.style.display="none",E.style.display="none"):t||o?(m.addEventListener("keypress",I),o?(m.autofocus=!0,m.value=n??"",m.addEventListener("keypress",$=>{$.key==="Enter"&&E.click()}),i?(m.type="password",m.autocomplete="off",m.required=!0):(m.type="text",m.autocomplete="on",m.required=!1,m.attributes["auto-complete"]="on")):(m.autofocus=!1,m.classList.add("collapsed")),S.textContent=s||"Cancel"):(m.classList.add("collapsed"),S.style.display="none"),new Promise($=>{if(c){let N=f(R=>{R.preventDefault()},"onCancelEvent");b.addEventListener("cancel",N);let D=f(()=>{b.removeEventListener("cancel",N),b.close()},"close"),B=f(({title:R,msg:k,animationEmoji:M})=>{if(R!==void 0&&(u.textContent=R),k!==void 0){[...g.childNodes].forEach(ee=>{ee.id!=="fullscreen-dialog-animation-emoji"&&g.removeChild(ee)});let j=k.split(`
|
|
11
|
+
`),Q=document.getElementById("fullscreen-dialog-animation-emoji");j.forEach(ee=>{let Ae=document.createElement("p");Ae.textContent=ee,Q?g.insertBefore(Ae,Q):g.appendChild(Ae)})}if(M!==void 0){let j=document.getElementById("fullscreen-dialog-animation-emoji");M?(j||(j=document.createElement("div"),j.id="fullscreen-dialog-animation-emoji",j.style.fontSize="3.5rem",j.style.textAlign="center",j.style.margin="1.5rem 0",j.style.animation="spin-bounce 5s infinite ease-in-out",g.appendChild(j)),j.textContent=M):j&&j.remove()}},"update");b.open||b.showModal(),Ce(1e3).then(()=>{p.scrollTo({top:0,behavior:"smooth"})}),$({close:D,update:B});return}let T=f(()=>{(t||o)&&m.removeEventListener("keypress",I),E.removeEventListener("click",_),S.removeEventListener("click",G),b.removeEventListener("close",v)},"removeEventListeners"),_=f(()=>{T();let N=o?m.value??"":"true";m&&(m.value=""),b.close(N),$(N)},"onOK"),G=f(()=>{T(),m&&(m.value=""),b.close(void 0),$(void 0)},"onCancel"),v=f(()=>{T(),m&&(m.value=""),b.close(void 0),$(void 0)},"onClose");E.addEventListener("click",_),S.addEventListener("click",G),b.addEventListener("close",v),b.open||b.showModal(),Ce(1e3).then(()=>{p.scrollTo({top:0,behavior:"smooth"})})})}catch(b){throw console.error(`${l} ${w(b)}`),b}finally{lc&&console.log(`${l} complete.`)}}f(kr,"showFullscreenDialog");var Re=Qt;async function $f({metaspace:r,space:e}){let t=`[${$f.name}]`;try{Re&&console.log(`${t} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let o=await r.getSpecialIbGib({type:Io.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} ${w(o)}`),o}finally{Re&&console.log(`${t} complete.`)}}f($f,"getTagsIbGib");function La({scope:r,ibGib:e,ibGibAddr:t,defaultNameIfError:o}){let n=`[${La.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 a,s,i;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&&y({ibGib:e})!==t)throw new Error("(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: genuuid)");let l=e.rel8ns.ancestor.filter(p=>$e({gib:ae({ibGibAddr:p}).gib}));if(l.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=l.at(-1);a=ae({ibGibAddr:b}).ib,i=a}t??=y({ibGib:e});let{ib:c}=ae({ibGibAddr:t});if(s=c.split(" ").at(0)??"",s=s.replace(/\W/g,"_"),a??=s,a=a.replace(/\W/g,"_"),!a&&!s)throw new Error("(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: genuuid)");i=s.toLowerCase(),Re&&console.log(`${n} ancestorIbOrAtom: ${i} (I: genuuid)`);let d=`${i}_${r}index`;return Re&&console.log(`${n} indexName: ${d} (I: genuuid)`),d}catch(a){if(o)return console.warn(`${n} error happened but defaultNameIfError (${o}) provided. So will return this value. error that was thrown: ${w(a)}`),o;throw console.error(`${n} ${w(a)}`),a}}f(La,"getIndexNameFromIbGib");async function If({scope:r,ibGib:e,metaspace:t,space:o,skipGetLatest:n}){let a=`[${If.name}]`;try{if(Re&&console.log(`${a} 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 s=La({scope:r,ibGib:e}),i=be({ibGib:e,defaultIfNone:"incomingAddr"}),c=f(async()=>{let l=await t.getSpecialIbGib({type:s,space:o,initialize:!1,dontWarnIfNotExist:!0,lock:!0});if(!l||!l.data){Re&&console.log(`${a} special ${r} index ibGib not found for indexSpecialIbGibType (${s}). No coupled ibgib registered, returning undefined. (I: genuuid)`);return}let p=(l.data.coupleMap??l.data.agentMap??{})[i];if(!p){Re&&console.log(`${a} No coupled ${r} ibgib address found for domain ${i} in the coupled index map. indexSpecialIbGibType: ${s}. returning undefined. (I: genuuid)`);return}let u=n?p:await t.getLatestAddr({addr:p,space:o})??p,g=await t.get({addrs:[u],space:o});if(g.errorMsg||(g.ibGibs??[]).length!==1)throw new Error(`couldn't get latest coupled ibgib (${u}) for domain ${i}. (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);return g.ibGibs[0]},"fn");return await Gt({scope:s,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:a+ot(),fn:c})}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{Re&&console.log(`${a} complete.`)}}f(If,"getLocalCoupledIbGibForDomainIbGib");async function Sf({scope:r,domainIbGib:e,localIbGib:t,metaspace:o,space:n}){let a=`[${Sf.name}]`;try{Re&&console.log(`${a} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let s=La({scope:r,ibGib:e}),i=be({ibGib:e}),c=y({ibGib:t});if(!i)throw new Error(`${a} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`);if(!c)throw new Error(`${a} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`);await Gt({scope:s,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:f(async()=>{let l=await o.getSpecialIbGib({type:s,space:n,initialize:!0,dontWarnIfNotExist:!0,lock:!1});if(!l)throw new Error(`${a} Could not get or create agent index ibGib.`);if(!l.data)throw new Error("(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)");let b=l.data.coupleMap??l.data.agentMap,p=b?H(b):{},u=p[i];if(u)if(u===c){Re&&console.log(`${a} domain ibGib (${i}) already mapped to agent (${c}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`);return}else console.warn(`${a} domainTjpAddr (${i}) already assigned to existingMappedAgentAddr (${u}). We will be changing to new localAddr (${c}). (W: eb993e33f7731e570fa76f24a2d80625)`);p[i]=c;let g=await nt({src:l,dataToAddOrPatch:{coupleMap:p},dna:!1,linkedRel8ns:[Ee.past],nCounter:!0}),m=g.newIbGib;await Ie({resTransform:g,space:n});let E=Ne({type:s});await o.setConfigAddr({key:E,addr:y({ibGib:m}),space:n}),await o.registerNewIbGib({ibGib:m,space:n})},"fn")}),Re&&console.log(`${a} Registered domain ${i} with agent ${c}`)}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{Re&&console.log(`${a} complete.`)}}f(Sf,"coupleDomainIbGibWithLocalIbGibViaIndex");function Er(){let r=`[${Er.name}]`;try{Re&&console.log(`${r} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let e=globalThis[Ca];return e||(console.log(`${r} initializing globalThis.${Ca}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),e={}),e}catch(e){throw console.error(`${r} ${w(e)}`),e}finally{Re&&console.log(`${r} complete.`)}}f(Er,"getIbGibGlobalThis_IbGib");async function V({delayIntervalMs:r=50}={delayIntervalMs:50}){let e=`[${V.name}]`;try{Re&&console.log(`${e} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let t;for(;!t;)Er().metaspace&&(t=Er().metaspace),t||(console.log(`${e} metaspace still not initialized. delayIntervalMs: ${r} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await Ce(r));return t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Re&&console.log(`${e} complete.`)}}f(V,"getGlobalMetaspace_waitIfNeeded");function _f({ibGibAddr:r,gib:e,ibGib:t,translucentAlpha:o=10}){let n=`[${_f.name}]`;try{Re&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!r&&!e&&!t&&(e=re),e??=t?.gib??ae({ibGibAddr:r}).gib;let a=De({gib:e});o??=10;let s="";if(a.isPrimitive)return{gib:e,gibInfo:a,punctiliarColor:tc,punctiliarColorTranslucent:rc,punctiliarColorContrast:oc};s=a.tjpGib??a.punctiliarHash??e;let[i,c,d]=dc(o,a.punctiliarHash??e),[l,b,p]=a.tjpGib?dc(o,a.tjpGib):[void 0,void 0,void 0];return{gib:e,gibInfo:a,punctiliarColor:i,punctiliarColorTranslucent:c,punctiliarColorContrast:d,tjpColor:l,tjpColorTranslucent:b,tjpColorContrast:p}}catch(a){let s=`${n} ${w(a)}`;return console.error(s),{gib:e??re,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:s}}finally{Re&&console.log(`${n} complete.`)}}f(_f,"getDeterministicColorInfo");function Af(r,e,t){t/=100;let o=e*Math.min(t,1-t)/100,n=f(a=>{let s=(a+r/30)%12,i=t-o*Math.max(Math.min(s-3,9-s,1),-1);return Math.round(255*i).toString(16).padStart(2,"0")},"f");return`#${n(0)}${n(8)}${n(4)}`}f(Af,"hslToHex");function dc(r,e){let o=(parseInt(e.substring(0,8),16)||0)%360,n=Af(o,65,62),a=parseInt(n.substring(1,3),16),s=parseInt(n.substring(3,5),16),i=parseInt(n.substring(5,7),16),d=(a*299+s*587+i*114)/1e3>=128?"#11111b":"#ffffff",l=Math.min(100,Math.max(0,r)),b=Math.round(l/100*255).toString(16).padStart(2,"0"),p=`${n}${b}`;return[n,p,d]}f(dc,"getColorStrings");var ze=Qt;function bc(r){return new TextDecoder().decode(r)}f(bc,"uint8ArrayToString");var fc=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 a=e[n];a===".."?o=o.split("/").slice(0,-1).join("/"):(a.startsWith("/")&&(a=a.slice(1)),a.endsWith("/")&&(a=a.slice(0,-1)),o+=(n>0?"/":"")+a)}return o}dirname(e){return e.split("/").slice(0,-1).join("/")}basename(e,t){return e.split("/").pop()??""}};async function Tf({msg:r,title:e,confirm:t,noNewLine:o,rl:n,defaultValue:a,dontCloseRl:s,cancelable:i}){let c=`[${Tf.name}]`;try{if(!r)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let d,l=0,b=5;do{if(l++,l>=b)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await Ce(50),d=await kr({title:e||"Prompt for Info",msg:r,prompt:!0,showInput:!0,isPassword:!1,defaultValue:a})}while(d===void 0&&!i);return d??""}catch(d){debugger;throw console.error(`${c} ${w(d)}`),d}}f(Tf,"promptForText");async function Gf({msg:r,confirm:e}){let t=`[${Gf.name}]`;try{ze&&console.log(`${t} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let o,n=!0,a=0,s=5;do{if(a++,a>=s)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await Ce(50),o=await kr({title:n?"Shh...":"Secrets didn't match, try again...",msg:r||"Enter Your Secret...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0}),o===void 0)throw new Error("user cancelled (E: 91519d04378e84106f3df8eb36d99725)");if(e){await Ce(250);let i=await kr({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});i===void 0&&(o=void 0),o!==i&&(o=void 0,n=!1,await Ce(250))}}while(o===void 0);return o}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{ze&&console.log(`${t} complete.`)}}f(Gf,"promptForSecret");async function Cf({msg:r,title:e,skipHitEnterToContinue:t}){let o=`[${Cf.name}]`;try{if(!r)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{e??="",await Ce(50),await kr({title:e,msg:r})}catch(n){throw n}}catch(n){throw console.error(`${o} ${w(n)}`),n}}f(Cf,"alertUser");async function vf({exportIbGibJsonString:r,metaspace:e}){let t=`[${vf.name}]`;try{debugger;if(ze&&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,a;try{n=JSON.parse(r)}catch(d){let l=`Error during parse JSON. error: ${w(d)} (E: genuuid)`,b=new Error(l);throw b.cause=d,b}try{let d=await ge({ibGib:n})??[];if(d.length>0)throw new Error(`validation errors when validating the parsed ibgib that should be a RawExportIbGib_V1: ${d} (E: 8ba178d3b26e8eca28a67c182fe16825)`);if(a=n,!a.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)")}catch(d){let l=`Error during parse JSON. error: ${w(d)} (E: genuuid)`,b=new Error(l);throw b.cause=d,b}let s;if(a.data.compression)switch(a.data.compression){case"gzip":s=await Oa({compressedBase64:a.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${a.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else s=await Fo({jsonString:a.data.dependencyGraphAsString});let i={};for(let[d,l]of Object.entries(s)){let b=await ge({ibGib:l})??[];b.length>0&&(i[d]=b)}if(Object.keys(i).length>0)throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:
|
|
12
|
+
${K({validationErrorMap:i})} (E: e63f38b182a84122d83a55befb369825)`);return[a,s]}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{ze&&console.log(`${t} complete.`)}}f(vf,"getRawExportIbGibAndGraphFromJsonString");async function Of({ibGib:r,compress:e,metaspace:t,space:o}){let n=`[${Of.name}]`;try{if(ze&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),$e({ibGib:r}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let a=await Na({ibGib:r,live:!0,compress:e,metaspace:t,space:o}),{rawExportIbGib:s,errors:i}=a;if((i??[]).length>0)throw new Error(`Export had errors: ${i} (E: 05faf83f25d3449ab809dfd24eeaf825)`);let c=JSON.stringify(s),d="data:text/json;charset=utf-8,"+encodeURIComponent(c),b=`${y({ibGib:s})}.json`,p=document.createElement("a");p.setAttribute("style","none"),p.setAttribute("href",d),p.setAttribute("download",b);let u=document.getElementsByTagName("div")[0];u.appendChild(p),p.click(),u.removeChild(p)}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{ze&&console.log(`${n} complete.`)}}f(Of,"exportIbGib");function Nf(){let r=`[${Nf.name}]`;try{ze&&console.log(`${r} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let e=Er();if(!e.storeName_hack)throw new Error("(UNEXPECTED) global store name falsy? (E: 3b9b680f6a980debbb877c9a13fb2625)");return e.storeName_hack}catch(e){throw console.error(`${r} ${w(e)}`),e}finally{ze&&console.log(`${r} complete.`)}}f(Nf,"getGlobalStoreName");function xf(){let r=`[${xf.name}]`;try{ze&&console.log(`${r} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let e=Er();if(!e.dbName_hack)throw new Error("(UNEXPECTED) global db name falsy? (E: 3aa028d5e4088f3f3841aae94ac02825)");return e.dbName_hack}catch(e){throw console.error(`${r} ${w(e)}`),e}finally{ze&&console.log(`${r} complete.`)}}f(xf,"getGlobalDbName");function Lf(){let r=`[${Lf.name}]`;try{ze&&console.log(`${r} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let e=Er();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} ${w(e)}`),e}finally{ze&&console.log(`${r} complete.`)}}f(Lf,"getGlobalIndexedDbKey_APIKey");async function Da({infos:r}){let e=`[${Da.name}]`;try{ze&&console.log(`${e} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let t of r){let{dbName:o,storeNames:n}=t;await Pa({dbName:o})||await Vo({dbName:o});for(let s of n)await Ra({dbName:o,storeName:s})}}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ze&&console.log(`${e} complete.`)}}f(Da,"initAppStorage");var Je=Qt,pc=0;async function Vo({dbName:r,storeName:e,version:t,logalot:o=!1}){let n=`[${Vo.name}][${r}][${e??"no store name"}]`,a=crypto.randomUUID();o&&console.time(n+a);let s;try{o&&console.log(`${n} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`),await new Promise((c,d)=>{try{o&&console.log(`${n} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`),o&&console.timeLog(n+a,"opening... (I: e748b4ddb445d77cb10a7ba158b49125)");let l=indexedDB.open(r,t);pc++,console.log(`${n} initRequestCount: ${pc} (I: 294d5f0b12ffe5512bacebe891824d25)`);let b;l.onupgradeneeded=p=>{try{s=p.target.result,o&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),e&&(s.objectStoreNames.contains(e)?b=!0:(b=!1,s.createObjectStore(e,{keyPath:"key"})))}catch(u){console.error(`${n}[openDBRequest.onupgradeneeded] ${w(u)} (E: 4a5fa1b0850be47e28bee653da287325)`),d(u)}},l.onblocked=p=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${p.oldVersion} -> ${p.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(p)},l.onsuccess=p=>{try{o&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),o&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),s=p.target.result,e&&(b??=s.objectStoreNames.contains(e),o&&console.log(`${n} ${r} store "${e}" ${b?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(u){console.error(`${n}[openDBRequest.onsuccess] ${w(u)}`),d(u)}},l.onerror=p=>{debugger;console.error(`${n}[initRequest.onerror] ${w(l.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`),d(l.error)}}catch(l){console.error(`${n} ${w(l)}`);debugger;d(l)}finally{o&&console.log(`${n} complete.`)}})}catch(i){throw console.error(`${n} ${w(i)}`),i}finally{s&&(o&&console.log(`${n} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),s.close(),o&&(console.log(`${n} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`),console.timeLog(n+a,"db closed. (I: e748b4ddb445d77cb10a7ba158b49125)"))),o&&(console.log(`${n} complete.`),console.timeEnd(n+a))}}f(Vo,"initializeStorage");async function hc({dbName:r,logalot:e=!1}){let t=`[${hc.name}]`,o=crypto.randomUUID();e&&console.time(t+o);try{return e&&console.log(`${t} starting... (I: 8516795b20529d19eb6923defd7a0f24)`),(await indexedDB.databases()).filter(a=>a.name===r).at(0)}catch(n){console.error(`${t} ${w(n)}`)}finally{e&&console.timeEnd(t+o),e&&console.log(`${t} complete.`)}}f(hc,"storageGetDBInfo");async function Ra({dbName:r,storeName:e,logalot:t=!1}){let o=`[${Ra.name}]`,n=crypto.randomUUID();t&&console.time(o+n);let a;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 i=!1;if(t&&console.timeLog(o+n),await new Promise((b,p)=>{let u=indexedDB.open(r);u.onsuccess=g=>{a=g.target.result,i=a.objectStoreNames?.contains(e),t&&console.timeLog(o+n,"open db request"),b()},u.onerror=g=>{debugger;console.error(`${o}[openDBRequest.onerror] ${w(u.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),p(u.error)}}),t&&console.timeLog(o+n),i){t&&console.log(`${o} store ${e} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await hc({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 d=c.version;if(!d)throw new Error(`db (${r}) has no version. can't create store (${e}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`);let l=d+1;if(t&&console.log(`${o} creating store ${e} with version ${l} (I: 312b79f28243c650cf38935114f21e24)`),a)a.close(),a=void 0;else throw new Error("(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)");await Vo({dbName:r,storeName:e,version:l,logalot:t})}catch(s){throw console.error(`${o} ${w(s)}`),s}finally{a&&(t&&console.log(`${o} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),a.close(),t&&console.log(`${o} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`)),t&&console.timeLog(o+n),t&&console.log(`${o} complete.`)}}f(Ra,"storageCreateStoreIfNotExist");async function xa({dbName:r,version:e,storeName:t,key:o,value:n,logalot:a=!1}){let s=`[${xa.name}]`,i;try{a&&console.log(`${s} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((d,l)=>{try{a&&console.log(`${s} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let b=indexedDB.open(r,e);b.onsuccess=p=>{i=p.target.result;try{let u=i.transaction(t,"readwrite").objectStore(t),g={key:o,value:n};u.put(g),d()}catch(u){console.error(`${s}[putRequest.onsuccess] ${w(u)}`),l(u)}},b.onerror=p=>{debugger;console.error(`${s}[putRequest.onerror] ${w(b.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),l(b.error)}}catch(b){console.error(`${s} ${w(b)}`),l(b)}finally{a&&console.log(`${s} complete.`)}})}catch(c){throw console.error(`${s} ${w(c)}`),c}finally{i&&(a&&console.log(`${s} closing db ${r}... (I: 438c6edced94b83a3478c71b08c6c325)`),i.close(),a&&console.log(`${s} closing db ${r} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`)),a&&console.log(`${s} complete.`)}}f(xa,"storagePut");async function jo({dbName:r,version:e,storeName:t,key:o,logalot:n=!1}){let a=`[${jo.name}]`,s;try{return n&&console.log(`${a} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`),await new Promise((d,l)=>{try{n&&console.log(`${a} starting... (I: 24163c4a11c8712097db45febaf9c724)`);let b=indexedDB.open(r,e);b.onsuccess=p=>{s=p.target.result;let u;try{u=s.transaction(t).objectStore(t)}catch(m){debugger;console.error(`${a}[openDBRequest.onsuccess][objectStore] ${w(m)}`),l(m);return}let g=u.get(o);g.onsuccess=m=>{try{let E=m.target?.result?.value??void 0;if(!E){d(E);return}if(n&&console.log("Retrieved value:",E),E instanceof Uint8Array)d(bc(E));else{if(typeof E!="string")throw new Error("(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)");d(E)}}catch(E){l(E)}},g.onerror=m=>{debugger;let E=g.error;console.error(`${a}[openDBRequest.onsuccess][getRequest.onerror] ${w(E)}`),l(E)}},b.onerror=p=>{debugger;console.error(`${a}[openDBRequest.onerror] ${w(b.error)} (E: 074963a908fa9a075f01c73cae829224)`),l(b.error)}}catch(b){console.error(`${a} ${w(b)}`),l(b)}finally{n&&console.log(`${a} complete.`)}})}catch(i){throw console.error(`${a} ${w(i)}`),i}finally{s&&(n&&console.log(`${a} closing db ${r}... (I: a938fc22dfdc76b15f6926bc4d458225)`),s.close(),n&&console.log(`${a} closing db ${r} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`)),n&&console.log(`${a} complete.`)}}f(jo,"storageGet");async function Pa({dbName:r,store:e}){let t=`[${Pa.name}]`,o;try{return Je&&console.log(`${t} starting... (I: 2b4373affa3841220f0b7ca690406624)`),(await window.indexedDB.databases()).some(s=>s.name===r)?e?await new Promise((s,i)=>{let c=indexedDB.open(r);c.onsuccess=d=>{o=d.target.result;let l=o.objectStoreNames.contains(e);s(l)},c.onerror=d=>{debugger;o=c.result;let{error:l}=d.target;console.error(`${t}[openDBRequest.onerror] ${w(c.error)} (E: c783fe607451e46c1feae3a81e0f7924)`),i(l)}}):!0:!1}catch(n){throw console.error(`${t} ${w(n)}`),n}finally{o&&(Je&&console.log(`${t} closing db ${r}... (I: 8782d9eea285cf9eb638d493a421a625)`),o.close(),Je&&console.log(`${t} closing db ${r} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),Je&&console.log(`${t} complete.`)}}f(Pa,"storageDBExists");async function Df({dbName:r,storeName:e,pathToRm:t}){let o=`[${Df.name}]`,n=Je;Je&&console.log(`${o} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`);let a;return new Promise((s,i)=>{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] ${w(c.error)} (E: 4c5ab71a765e61b4292008fd4fafe324)`),i(c.error)},c.onsuccess=()=>{a=c.result;let l=a.transaction(e,"readwrite").objectStore(e),b=IDBKeyRange.lowerBound(t),p=l.openCursor(b);p.onerror=()=>{debugger;console.error(`${o}[openCursorRequest.onerror] ${w(p.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),i(p.error)},p.onsuccess=()=>{try{let u=0,g=p.result;if(g)if(g.key.toString().startsWith(t)){let m=g.delete();u++,m.onerror=()=>{debugger;console.error(`${o}[deleteRequest.onerror] ${w(m.error)} (E: abc031c53e5387322cd8909b3ada9b24)`),i(m.error)},g.continue()}else Je&&console.log(`${o} rmCount: ${u} (I: e4bc613a5514c0942484b79267e16724)`),s();else Je&&console.log(`${o} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`),s()}catch(u){console.error(`${o}[openCursorRequest.onsuccess] ${w(u)}`),i(u)}}}}catch(c){debugger;console.error(`${o} ${w(c)}`),i(c)}}).finally(()=>{a&&(Je&&console.log(`${o} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),Je&&console.log(`${o} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),Je&&console.log(`${o} complete.`),Je=n})}f(Df,"storageRmRF");async function Rf({dbName:r,storeName:e,dirPath:t,withFileTypes:o=!1}){let n=`[${Rf.name}]`,a;try{return await new Promise((c,d)=>{let l=indexedDB.open(r);l.onerror=()=>{debugger;d(l.error)},l.onsuccess=()=>{a=l.result;let p=a.transaction(e,"readonly").objectStore(e),u=t.endsWith("/")?t:t+"/",g=IDBKeyRange.lowerBound(u),m=p.openCursor(g),E=new Set,S=[];m.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${w(m.error)}`),d(m.error)},m.onsuccess=()=>{try{let A=m.result;if(A){let I=A.key.toString();if(I.startsWith(u)&&I!==u){let $=I.substring(u.length),T=$.split("/")[0];if(o){let _=$.substring(T.length).startsWith("/");S.push({name:T,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 E.add(T);A.continue()}else I.startsWith(u)?A.continue():c(o?S:Array.from(E))}else c(o?S:Array.from(E))}catch(A){console.error(`${n}[openCursorRequest.onsuccess] ${w(A)}`),d(A)}}}})}catch(s){throw console.error(`${n} ${w(s)}`),s}finally{a&&(Je&&console.log(`${n} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),Je&&console.log(`${n} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}f(Rf,"storageReaddir");var Br=no;async function Pf(r){let e=`[${Pf.name}]`;try{Br&&console.log(`${e} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await Da({infos:[{dbName:r.dbName,storeNames:[r.storeName,...r.additionalStoreNames??[]]}]})}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Br&&console.log(`${e} complete.`)}}f(Pf,"initIbGibStorage");function uc(r){let e=`[${uc.name}]`;try{Br&&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:ec,spaceShim:{},fnDefaultGetAPIKey:f(async()=>await jo({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} ${w(t)}`),t}finally{Br&&console.log(`${e} complete.`)}}f(uc,"initIbGibGlobalThis");function kf(r){if(!globalThis.ibgib?.spaceGib){if(!r)throw new Error("Global context not initialized and config not provided.");uc(r)}return globalThis.ibgib.spaceGib}f(kf,"getIbGibGlobalThis_SpaceGib");async function Bf(r){let e=`[${Bf.name}]`;try{Br&&console.log(`${e} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(r)).bootstrapSpaceGibApp()}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Br&&console.log(`${e} complete.`)}}f(Bf,"dynamicallyLoadBootstrapScript");function XE(){let r=f(async()=>V(),"fnGetMetaspace"),e=new Promise(async(t,o)=>{try{let n=1e5,a=0,s;do{if(s=kf()?.bootstrapPromise,a++,a>n)break;await Ce(10)}while(s===void 0);if(!s)throw new Error("Timed out waiting for bootstrapPromise. (E: ceb3ba5261994476900e4a623c0e9d10)");await s,t()}catch(n){o(n)}});return{fnGetMetaspace:r,bootstrapPromise:e}}f(XE,"getComponentCtorArg");var Uf="hash-reveal-v1",pt={hash_reveal_v1:Uf},gc=Object.values(pt);var Mf="top-up",Ff="replace-all",jf="consume",Vf="delete-all",xe={topUp:Mf,replaceAll:Ff,consume:jf,deleteAll:Vf},mc=Object.values(xe);var Ho=class{static{f(this,"KeystoneStrategy")}config;constructor(e){this.config=e}};var Hf="recursive-salt-wrap",so={recursive_salt_wrap:Hf},Ec=Object.values(so);var Ko=!1;async function ka({masterSecret:r,kdfOpts:e}){let t=`[${ka.name}]`;try{Ko&&console.log(`${t} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let o=e.strategy;switch(o){case so.recursive_salt_wrap:return await Xo({masterSecret:r,salt:e.salt,rounds:e.rounds,algorithm:e.algorithm});default:throw new Error(`Unknown KDF strategy: ${o}. valid values: ${Ec.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Ko&&console.log(`${t} complete.`)}}f(ka,"deriveKey");async function Xo({masterSecret:r,salt:e,rounds:t,algorithm:o=Ye.sha_256}){let n=`[${Xo.name}]`;try{Ko&&console.log(`${n} starting... (I: 850868e50aba82ff28c77da8169e4c26)`);let a=r;for(let s=0;s<t;s++)a=await He({s:`${e}${a}${e}`,algorithm:o});return a}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Ko&&console.log(`${n} complete.`)}}f(Xo,"kdf_recursiveSaltWrap");var qo=class r extends Ho{static{f(this,"KeystoneStrategy_HashRevealV1")}async derivePoolSecret({masterSecret:e}){let t=`[${r.name}.${this.derivePoolSecret.name}]`;try{let{salt:o,rounds:n,algo:a}=this.config;return await Xo({masterSecret:e,salt:o,rounds:n,algorithm:a})}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:a,algo:s}=this.config,i=o,c=e;for(let d=0;d<a;d++)c=await He({s:`${i}${c}${i}`,algorithm:s});return{type:"hash-reveal-v1",poolId:t,challengeId:o,value:c}}catch(a){throw console.error(`${n} ${a.message}`),a}}async generateChallenge({solution:e}){let t=`[${r.name}.${this.generateChallenge.name}]`;try{let{rounds:o,algo:n}=this.config,{challengeId:a,value:s}=e,i=a,c=s;for(let d=0;d<o;d++)c=await He({s:`${i}${c}${i}`,algorithm:n});return{id:a,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 Ot=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 qo(e);default:throw new Error(`Unknown strategy type: ${e.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(o){throw console.error(`${t} ${o.message}`),o}}};var Ba="keystone",Ua=/^\w[\w\-.]*$/,Ma=/^[a-zA-Z0-9\-_]{1,64}$/,Fa=/^[a-zA-Z0-9_\-.]{1,63}$/,ja=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,Va=1e3,Wo="revoke",io="manage",Kf="sign",wt="sync",er="connect",Ha={REVOKE:Wo,MANAGE:io,SIGN:Kf,SYNC:wt,CONNECT:er},gw=Object.values(Ha);var Ka=Wo,wc=io;var yt=er,wr=wt;var yc=200,$c=2,Ic=2,Sc=5,_c=xe.topUp,Ac=Ye.sha_256,Tc=1,Gc=2e3,Cc=5,vc=5,Oc=16,Nc=xe.replaceAll,xc=Ye.sha_512,Lc=10,Yo=50;var ce=!1;async function Nt({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${Nt.name}]`;try{ce&&console.log(`${m} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let E=await co({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:g});if(Object.values(E).filter(S=>S.ib.startsWith("comment ")).forEach(S=>{console.table(S)}),ce){console.log(`${m} graph size: ${Object.keys(E).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let S=Object.values(E).filter(A=>A.ib.startsWith("comment ")||A.ib.startsWith("pic ")).map(A=>A.ib);Eo(S).forEach(A=>console.log(A))}return E}catch(E){throw console.error(`${m} ${E.message}`),E}finally{ce&&console.log(`${m} complete.`)}}f(Nt,"getDependencyGraph");async function Dc({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${Dc.name}]`;try{if(ce&&console.log(`${m} starting... (I: bd6807477f679345df9dddefe0b4e922)`),!p)throw new Error("space 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||[],i=i||[],a=a||{},s=s||[],o=(o??[]).filter(E=>!$e({gib:ae({ibGibAddr:E}).gib})).filter(E=>!i.includes(E)),e=(e??[]).filter(E=>!$e({ibGib:E})).filter(E=>!i.includes(y({ibGib:E}))),r&&!$e({ibGib:r})&&!e.some(E=>E.gib===r.gib)&&!i.includes(y({ibGib:r}))&&e.push(r),t&&!$e({gib:ae({ibGibAddr:t}).gib})&&!o.includes(t)&&!i.includes(t)&&o.push(t),{ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:g}}catch(E){throw console.error(`${m} ${E.message}`),E}finally{ce&&console.log(`${m} complete.`)}}f(Dc,"getGraphProjection_initializeOpts");async function Rc({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,maxRetries:n,msBetweenRetries:a,timeLogName:s,space:i}){let c=`[${Rc.name}]`;try{ce&&console.log(`${c} starting... (I: 67b2be37ff24393fff56e229304da122)`);let d=[];r??=[],e??=[],o??=[],t??={};let l=[],b=Object.keys(t??{}),p=r.map(u=>y({ibGib:u}));for(let u=0;u<e.length;u++){let g=e[u];o.includes(g)||p.includes(g)||(b.includes(g)?d.push(t[g]):l.push(e[u]))}if(ce&&console.log(`${c}[analyze debugging] addrsToGetFromSpace (${l.length}):
|
|
13
|
+
${l.join(`
|
|
14
|
+
`)} (I: b45a2614184b48b694becfd377c789f5)`),l.length>0){let u=l.concat(),g=0;for(n=n??0;g<=n&&u.length>0;){if(s&&g===0&&console.timeLog(s,`${c} FIRST try starting...`),s&&g>0&&console.timeLog(s,`${c} RETRY starting...`),g>0&&a&&(s&&console.timeLog(s,`${c} delaying ${a}ms for retry`),ce&&console.log(`${c} retrying. addrsToGet (${u.length}): ${u} (I: 8460694cdd5518472680784c3b96a822)`),await Ce(a)),s&&console.timeLog(s,`${c} getFromSpace (${u?.length}) starting...`),!i)throw new Error("(UNEXPECTED) space falsy? (E: aa9f657695717034b3581066932d7d23)");let m=await te({addrs:u,space:i});if(s&&console.timeLog(s,`${c} getFromSpace complete.`),m.success&&(m.ibGibs?.length??0)>0){m.ibGibs.forEach(S=>d.push(S));let E=m.ibGibs.map(S=>y({ibGib:S}));if(E.length===u.length){s&&console.timeLog(s,`${c} got all.`),u=[];break}else s&&console.timeLog(s,`${c} got some.`),u=u.filter(S=>!E.includes(S))}else{let E=m.rawResultIbGib.ibGibs??[];if(E.length>0){E.forEach(A=>d.push(A));let S=E.map(A=>y({ibGib:A}));s&&console.timeLog(s,`${c} got some.`),u=u.filter(A=>!S.includes(A))}else s&&console.timeLog(s,`${c} failed. addrs: ${u?.join(",")}`)}g++}if(u?.length>0)throw new Error(`unable to retrieve dependency ibgibs from space (ib: ${i?.ib}). addrsToGet: ${u.join(`
|
|
15
|
+
`)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}return d}catch(d){throw console.error(`${c} ${d.message}`),d}finally{ce&&console.log(`${c} complete.`)}}f(Rc,"getGraphProjection_getIbGibsInIbGibAddrs");async function co(r){let e=`[${co.name}]`;try{if(ce&&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:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:g}=await Dc(r);if(u&&console.timeLog(u,`${e} starting...`),o?.length??!1){let E=await Rc({ibGibs:t,ibGibAddrs:o,gotten:a,skipAddrs:i,maxRetries:l,msBetweenRetries:b,timeLogName:u,space:p});t=t?[...t,...E]:[...E]}o=t.map(E=>y({ibGib:E}));let m=Eo(t.map(E=>E.ib).filter(E=>E.startsWith("comment ")));return ce&&console.log(`${e}[analyze debugging] ibGibs commentIbs: ${m.join(`
|
|
16
|
+
`)} (I: c89dc951315f746954f9bddbe8941122)`),n?Pc({ibGibs:t,ibGibAddrs:o,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:g}):kc({ibGibs:t,ibGibAddrs:o,gotten:a,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:u})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ce&&console.log(`${e} complete.`)}}f(co,"getGraphProjection");async function Ur({ibGibAddr:r,latestCommonFrameAddr:e,live:t,space:o}){let n=`[${Ur.name}]`;try{if(ce&&console.log(`${n} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`),r===e)return console.warn(`${n} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`),{};let a=await Nt({ibGibAddr:e,live:!1,space:o});return await Nt({ibGibAddr:r,live:t,skipAddrs:Object.keys(a),space:o})}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{ce&&console.log(`${n} complete.`)}}f(Ur,"getDeltaDependencyGraph");async function Pc({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:d,space:l,timeLogName:b}){let p=`[${Pc.name}]`;try{n=n??{},o=o??[];let u={...t};(r??[]).forEach(I=>u[y({ibGib:I})]=I);let g=bt({ibGibs:Object.values(u)});ce&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(g).length}): ${Object.keys(g)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let m={};Object.keys(g).forEach(I=>{o.includes(I)||(m[I]=g[I])}),ce&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${K(m)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let E={},S={};Object.keys(g).filter(I=>!o.includes(I)).forEach(I=>{let $=g[I],T=$[$.length-1];E[I]=T;let _=y({ibGib:T});S[_]=I});let A=Object.keys(E).length;if(A>0){let I={};Object.keys(n).filter(N=>!o.includes(N)).forEach(N=>{let D=E[N];if(D){let B=y({ibGib:D});I[B]=n[N]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy`)}),ce&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${K(I)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let $=Object.values(E),T={};if($.length>0){if(!l)throw new Error("(UNEXPECTED) space falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");let N=await st({ibGibs:$,space:l});if(!N?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");if(T=N?.data?.latestAddrsMap,Object.keys(T).length!==A)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");ce&&console.log(`${p} queriedLatestAddrsMap: ${K(T)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),I={...T,...I}}ce&&console.log(`${p} combined latestAddrsMap: ${K(I)} (I: e3aedea63f29c5b06a79632f691aa522)`);let _=[],G={};Object.values(E).forEach(N=>{let D=y({ibGib:N}),B=S[D],R=I[D];if(!R)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");R===D?(ce&&console.log(`${p} analyzed ${B}(I: afb7960900f04b8a87538f4c7bd903b7)`),o.push(B)):(_.push(R),G[R]=B)});let v=[];for(let N=0;N<(r??[]).length;N++){let B=r[N].rel8ns??{};Object.keys(B).filter(k=>!(s??[]).includes(k)).filter(k=>i?i.includes(k):!0).forEach(k=>{(B[k]??[]).forEach(j=>{!v.includes(j)&&!r.some(Q=>y({ibGib:Q})===j)&&!$e({gib:ae({ibGibAddr:j}).gib})&&v.push(j)})})}return e=Eo([...e??[],...v,..._]),await co({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:d,space:l,timeLogName:b,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return r||(r=[]),Object.values(t??{}).forEach(I=>{let $=y({ibGib:I});r.some(T=>y({ibGib:I})===$)||r.push(I)}),await co({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:d,space:l,timeLogName:b,live:!1})}catch(u){let g=`${p} ${u.message}`;throw console.error(g),b&&console.timeLog(b,`${p} error: ${g}`),u}finally{b&&console.timeLog(b,`${p} complete.`)}}f(Pc,"getGraphProjection_Live");async function kc({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c,timeLogName:d}){let l=`[${kc.name}]`;try{let b=[];r??=[],t??={},o??=[],n??=[],d&&console.timeLog(d,`${l} analyzing next step starting...`);for(let p=0;p<r.length;p++){let u=r[p],g=y({ibGib:u}),{gib:m}=ae({ibGib:u});if(m===re)throw new Error("cannot get dependency graph of primitive.");Object.keys(t).includes(g)||(t[g]=u);let E={},S=u.rel8ns||{},A=(Object.keys(S)||[]).filter($=>!n.includes($));a&&(A=A.filter($=>a.includes($)));let I=Object.keys(t);for(let $=0;$<A.length;$++){let T=A[$],_=S[T]??[],G=_.filter(N=>N===""||N===void 0||N===null||!N.includes(ve));G.length>0&&console.warn(`${l} (UNEXPECTED) has falsyAddrs: ${G} (W: da9505cb0a4db68a4aff7f279ad2d322)`),_.filter(N=>!!N).filter(N=>!I.includes(N)).filter(N=>!o.includes(N)).filter(N=>ae({ibGibAddr:N}).gib!==re).filter(N=>!b.includes(N)).forEach(N=>{let D=Lr({addr:N});(D||[]).length===0?b.push(N):E[N]=D})}if(Object.keys(E).length>0)throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(E).substring(0,1024)}`)}if(d&&console.timeLog(d,`${l} analyzing next step complete.`),b.length>0){if(d&&console.timeLog(d,`${l} get addrsWeDontHaveAlready_Rel8dAddrs starting...`),!c)throw new Error("(UNEXPECTED) space falsy? (E: 0ce327cf5d521bd798340333460f3423)");let p=await te({addrs:b,space:c});if(d&&console.timeLog(d,`${l} get addrsWeDontHaveAlready_Rel8dAddrs complete.`),p.success)if(p.ibGibs?.length===b.length){ce&&console.log(`${l} got ALL of them (happy path)`),p.ibGibs.forEach(g=>t[y({ibGib:g})]=g),d&&console.timeLog(d,`${l} call getGraphProjection recursively starting...`);let u=await co({ibGibs:p.ibGibs,live:!1,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c});return d&&console.timeLog(d,`${l} call getGraphProjection recursively complete.`),u}else throw(p.ibGibs?.length??0)>0&&p.ibGibs.length<b.length?(ce&&console.warn(`${l} got SOME of them (happy-ish path?). not sure what to do here... (W: e3458f61a1ae4979af9e6b18ac935c14)`),new Error("trouble getting dependency ibgibs (E: 8156bf65fd084ae4a4e8a0669db28b07)")):(p.ibGibs?.length??!1)&&p.ibGibs.length>b.length?new Error("(UNEXPECTED) got more ibGibs than addrs that we asked for. space not working properly. (E: 352219b3d18543bcbda957f2d60b78f3)"):new Error("couldn't get dependency ibgibs from space. (E: 225f26b7d7f84911bb033753a062209b)");else throw new Error(`failure getting addrs in space ${c?.data?.name||"[no name?]"} (id: ${c?.data?.uuid||"[no uuid?]"}). (E: 60404e6e389249d9bbecf0039cd51878) addrs:
|
|
17
|
+
${b.join(`
|
|
18
|
+
`)} `)}else return t}catch(b){let p=`${l} ${b.message}`;throw console.error(p),d&&console.timeLog(d,`${l} error: ${p}`),b}finally{d&&console.timeLog(d,`${l} complete.`)}}f(kc,"getGraphProjection_NonLive");function zo({ibGibs:r}){let e=`[${zo.name}]`;try{if(ce&&console.log(`${e} starting... (I: 6019a812cff8597f79c12088e45cc226)`),r){let t={};return r.forEach(o=>{t[y({ibGib:o})]=o}),t}else return}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ce&&console.log(`${e} complete.`)}}f(zo,"toFlatGraph");function Se({graphA:r,graphB:e,slowButThorough:t}){let o=`[${Se.name}]`;try{if(ce&&console.log(`${o} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(r).length===Object.keys(e).length))return ce&&console.log(`${o} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let a of Object.keys(r))if(!e[a])return ce&&console.log(`${o} addr (${a}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`),!1;if(t)for(let a of Object.keys(r)){let s=qe({ibGib:r[a]}),i=JSON.stringify(s),c=qe({ibGib:e[a]}),d=JSON.stringify(c);if(i!==d)return ce&&console.log(`${o} jsonA !== jsonB for addr (${a}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{ce&&console.log(`${o} complete.`)}}f(Se,"graphsAreEquivalent");var Le=!1;async function Bc({keystoneData:r}){let e=`[${Bc.name}]`;try{return Le&&console.log(`${e} starting... (I: c3022a146faac9730154f34d1439a225)`),[Ba].join(" ")}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}f(Bc,"getKeystoneIb");async function Uc({pool:r,requiredChallengeIds:e,targetAddr:t}){let o=r.config.behavior,n=new Set,a=Object.keys(r.challenges);if(e&&e.length>0){for(let s of e){if(!r.challenges[s])throw new Error(`(UNEXPECTED) Required challenge ID not found in pool: ${s} (E: 10c5619d80d8cf6cc84ffbf8be0dbc25)`);a.includes(s)&&n.add(s)}a=a.filter(s=>!n.has(s))}if(o.targetBindingCount>0&&t){let s=[...a].sort(),i=await He({s:t});for(let c=0;c<o.targetBindingCount;c++){if(s.length===0)throw new Error("Entropy Exhaustion. Cannot satisfy target binding. Sorted available pool is empty. (E: 341b95dc3a58be3e083d1d9c4a0c4925)");let d=BigInt("0x"+i),l=Number(d%BigInt(s.length)),b=s[l];n.add(b),s.splice(l,1),a=a.filter(p=>p!==b),i=await He({s:i})}}if(o.selectSequentially>0){if(a.length<o.selectSequentially)throw console.error(`[getDeterministicRequirements] Entropy Exhaustion! AvailableCount: ${a.length}, Required Seq: ${o.selectSequentially}. Available IDs: ${a.join(",")}`),new Error("Entropy Exhaustion. Insufficient challenges for FIFO requirement. (E: 9efa88003e1d5eccb837c85154ee5625)");a.slice(0,o.selectSequentially).forEach(i=>n.add(i)),a=a.slice(o.selectSequentially)}return{mandatoryIds:n,availableIds:a}}f(Uc,"getDeterministicRequirements");function Zo({pools:r,poolId:e,poolFilter:t,verb:o}){let n="[resolveTargetPool]";try{let a;if(e){if(a=r.find(s=>s.id===e),!a)throw new Error(`Pool not found with ID: ${e} (E: 4a2b17428515c1e82813158581898125)`)}else if(t){let s=r.filter(t);if(s.length===0)throw new Error("No pool matched the provided filter. (E: 5b3c27428515c1e82813158581898125)");a=s[0]}else{if(!o)throw new Error("Cannot auto-resolve pool without a verb. (E: 6c4d37428515c1e82813158581898125)");if(a=r.find(s=>s.config.allowedVerbs&&s.config.allowedVerbs.includes(o)),a||(a=r.find(s=>!s.config.allowedVerbs||s.config.allowedVerbs.length===0)),!a)throw new Error(`No suitable pool found for verb: ${o} (E: 7d5e47428515c1e82813158581898125)`)}if(o&&a.config.allowedVerbs&&a.config.allowedVerbs.length>0&&!a.config.allowedVerbs.includes(o))throw new Error(`Pool ${a.id} is not authorized for verb: ${o} (E: 8e6f57428515c1e82813158581898125)`);return a}catch(a){throw console.error(`${n} ${w(a)}`),a}}f(Zo,"resolveTargetPool");async function Qo({pool:r,targetAddr:e,requiredChallengeIds:t}){let o="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:a}=await Uc({pool:r,requiredChallengeIds:t,targetAddr:e}),s=r.config.behavior.selectRandomly,i=[];if(s>0){if(a.length<s)throw new Error(`Insufficient challenges for random requirement. Need ${s}, have ${a.length} (E: 9f7a67428515c1e82813158581898125)`);let c=[...a].sort(()=>.5-Math.random());i.push(...c.slice(0,s))}return[...n,...i]}catch(n){throw console.error(`${o} ${w(n)}`),n}}f(Qo,"selectChallengeIds");async function Jo({salt:r,timestamp:e,index:t}){return(await He({s:`${r}${e}${t}`})).substring(0,16)}f(Jo,"generateOpaqueChallengeId");async function Xf({prevPools:r,targetPoolId:e,consumedIds:t,masterSecret:o,strategy:n,config:a}){let s="[applyReplenishmentStrategy]";try{let i=JSON.parse(JSON.stringify(r)),c=i.findIndex(u=>u.id===e);if(c===-1)throw new Error(`Target pool ${e} not found in keystone data. (E: 75200388d22744838634524233772545)`);let d=i[c],l=await n.derivePoolSecret({masterSecret:o}),b=Date.now().toString(),p=a.behavior.replenish;if(p===xe.topUp){t.forEach(u=>delete d.challenges[u]);for(let u=0;u<t.length;u++){let g=await Jo({salt:a.salt,timestamp:b,index:u}),m=await n.generateSolution({poolSecret:l,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===xe.replaceAll){d.challenges={};for(let u=0;u<a.behavior.size;u++){let g=await Jo({salt:a.salt,timestamp:b,index:u}),m=await n.generateSolution({poolSecret:l,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===xe.consume)t.forEach(u=>delete d.challenges[u]);else if(p===xe.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${p}. Valid list: ${K(mc)} (E: 0acf56f1e1486240080e11e8046d0825)`);return i}catch(i){throw console.error(`${s} ${w(i)}`),i}}f(Xf,"applyReplenishmentStrategy");async function en({targetPoolId:r,prevPools:e,masterSecret:t,challengeIds:o,claim:n,requiredChallengeIds:a}){let s="[solveAndReplenish]";try{Le&&console.log(`${s} starting... poolId: ${r}, ids: ${o.length}`);let i=e.find(u=>u.id===r);if(!i)throw new Error(`Target pool not found: ${r} (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);let c=Ot.create({config:i.config}),d=await c.derivePoolSecret({masterSecret:t}),l=[];for(let u of o){let g=await c.generateSolution({poolSecret:d,poolId:i.id,challengeId:u});l.push(g)}let b={claim:n,solutions:l,requiredChallengeIds:a&&a.length>0?a:void 0},p=await Xf({prevPools:e,targetPoolId:i.id,consumedIds:o,masterSecret:t,strategy:c,config:i.config});return{proof:b,nextPools:p}}catch(i){throw console.error(`${s} ${w(i)}`),i}}f(en,"solveAndReplenish");async function Mc({pool:r}){let e=`[${Mc.name}]`;try{if(Le&&console.log(`${e} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!r.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(r.config.type!==pt.hash_reveal_v1)throw new Error("(UNEXPECTED) pool.config.type !== KeystoneChallengeType.hash_reveal_v1? (E: e205f8872909c37168a624a9df778c26)");let t=[],{algo:o,rounds:n,salt:a}=r.config,s=[Ye.sha_256,Ye.sha_512];return o?s.includes(o)||t.push(`${e} invalid hash algorithm (${o}). Must be one of ${s}. (E: a22399ca3a68e63ffcc7507699be5826)`):t.push(`${e} algorithm required. (E: 8cd6bfb0590862b9bae24d98d2cf3826)`),n&&typeof n=="number"&&Number.isInteger(n)?n>Va&&t.push(`${e} rounds too high. max rounds: ${Va} (E: 31ce082f7fd88d6b58ef08a816458826)`):t.push(`${e} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),a&&typeof a=="string"?Ma.test(a)||t.push(`${e} invalid salt (${a.substring(0,99)}). Must match regexp ${Ma}`):t.push(`${e} invalid salt (${a}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}f(Mc,"validateChallengePool_typeHashRevealV1");async function Fc({pool:r}){let e=`[${Fc.name}]`;try{Le&&console.log(`${e} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let t=[];if(r.config){if(r.config.id?Ua.test(r.config.id)||t.push(`${e} pool.config.id is not formatted correctly. must pass regexp: ${Ua.source}`):t.push(`${e} pool.config.id falsy (E: 31d7943d95f877326d5f4ea14463d626)`),r.config.behavior){let{size:n,selectSequentially:a,selectRandomly:s,targetBindingCount:i}=r.config.behavior;(!n||n===0)&&t.push(`${e} invalid pool.config.behavior.size (${n}). Must be positive integer. (E: b221e36ec102bdc944552248ce8fe626)`);let c=(a||0)+(s||0)+(i||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 pt.hash_reveal_v1:(await Mc({pool:r})).forEach(a=>t.push(a));break;default:throw new Error(`(UNEXPECTED) unknown pool.config.type (${o})? We only implement the following at this time: ${gc} (E: cce5285cf7580b8bc82172488eba2826)`)}}else t.push(`${e} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}f(Fc,"validateChallengePool");function jc({data:r}){let e="[validateKeystoneMetadata]",t=[],o=f((n,a)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!Fa.test(n.username))&&t.push(`${e} invalid username in ${a} (${n.username}). Must match ${Fa}`),n.description!==void 0&&(typeof n.description!="string"||!ja.test(n.description))&&t.push(`${e} invalid description in ${a} (${n.description}). Must match ${ja}`))},"checkDetails");return o(r.frameDetails,"frameDetails"),o(r.checkpointDetails,"checkpointDetails"),t}f(jc,"validateKeystoneMetadata");async function tn({keystoneIbGib:r}){let e=`[${tn.name}]`;try{Le&&console.log(`${e} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let t=[],{data:o,rel8ns:n}=r;jc({data:o}).forEach(s=>t.push(s)),o.proofs&&o.proofs.length>0&&t.push(`${e} proofs already exist on genesis keystone. (E: 7a5e15f20918f1bbd8ffb62857dcd526)`);for(let s of o.challengePools)(await Fc({pool:s})).forEach(c=>t.push(c)),(!s.challenges||Object.keys(s.challenges).length===0)&&t.push(`${e} invalid pool (${s.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} ${w(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}f(tn,"validateGenesisKeystone");async function lo({currentIbGib:r,prevIbGib:e}){let t=`[${lo.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 ge({ibGib:r});n&&n.length>0&&o.push(...n);let a=r.data,s=e.data;jc({data:a}).forEach(l=>o.push(l));let c=a.n??-2,d=s.n??-2;c<0&&o.push("invalid keystone.currData.n is undefined or null."),d<0&&o.push("invalid keystone.prevData.n is undefined or null."),c!==d+1&&o.push(`keystone data.n values are not sequential. prevData.n: ${d}, currData.n: ${c}. `);for(let l of a.proofs){if(l.solutions.length===0){o.push(`Proof ${l.id||"unknown"} has no solutions.`);continue}let b=l.solutions[0].poolId,p=s.challengePools.find(u=>u.id===b);if(!p){o.push(`Proof references unknown pool: ${b}`);continue}await Vc({proof:l,pool:p,errors:o})}if(a.revocationInfo){let l=a.revocationInfo.proof.claim.target,b=y({ibGib:e});l!==b&&o.push(`Revocation target mismatch. Expected ${b}, got ${l}`)}return o}catch(n){throw console.error(`${t} ${w(n)}`),n}finally{Le&&console.log(`${t} complete.`)}}f(lo,"validateKeystoneTransition");async function Vc({proof:r,pool:e,errors:t}){let o=`[${Vc.name}]`;try{Le&&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:a}=await Uc({pool:e,requiredChallengeIds:r.requiredChallengeIds,targetAddr:r.claim.target}),s=new Set(r.solutions.map(l=>l.challengeId));for(let l of n)s.has(l)||t.push(`Policy Violation: Missing mandatory challenge ${l}`);let i=[...s].filter(l=>!n.has(l)),c=e.config.behavior.selectRandomly;i.length<c&&t.push(`Policy Violation: Insufficient random count. Need ${c}, got ${i.length}`);for(let l of i)a.includes(l)||t.push(`Policy Violation: ID ${l} is invalid or double-dipped.`);let d=Ot.create({config:e.config});for(let l of r.solutions){let b=e.challenges[l.challengeId];b?await d.validateSolution({solution:l,challenge:b})||t.push(`Crypto Violation: Solution for ${l.challengeId} is invalid.`):t.push(`Crypto Violation: Challenge ${l.challengeId} not found in pool.`)}}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{Le&&console.log(`${o} complete.`)}}f(Vc,"verifyProofAgainstPool");async function fo({prevIbGib:r,newData:e,metaspace:t,space:o}){let n=`[${fo.name}]`;try{if(Le&&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: ${y({ibGib:r})} (E: 45d7f846556829de6b2a701838c3f825)`);let a=r.data,s={};a.proofs&&(s.proofs=[]),a.challengePools&&(s.challengePools=[]),a.frameDetails&&(s.frameDetails={}),a.checkpointDetails&&(s.checkpointDetails={}),Object.keys(s).length===0&&(s=void 0);let i=await nt({src:r,dataToRemove:s,dataToAddOrPatch:e,nCounter:!0});if(i.intermediateIbGibs)throw new Error("(UNEXPECTED) resMut8.intermediateIbGibs truthy? I'm not sure if we expect there to be intermediateIbGibs, but I feel like we shouldn't. Pretty sure we shouldn't, definitely don't *want* them. (E: ba40d55d7c2d36d438c413886f148625)");if(i.dnas)throw new Error("(UNEXPECTED) resMut8.dnas truthy? We do not want dnas with keystones. (E: 49470513d018f97d28024f4e82da3b25)");let c=i.newIbGib,d=await lo({currentIbGib:c,prevIbGib:r});if(d.length>0)throw console.error(`${n} Validation Failed:
|
|
19
|
+
${d.join(`
|
|
20
|
+
`)}`),new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${d.join("; ")} (E: ae2c58406c1db7687879dfb89fc1f825)`);return await t.put({ibGib:c,space:o}),await t.registerNewIbGib({ibGib:c,space:o}),c}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Le&&console.log(`${n} complete.`)}}f(fo,"evolvePersistAndRegisterKeystone");async function Xa({data:r,metaspace:e,space:t}){let o=`[${Xa.name}]`;try{if(Le&&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 a=(await F.firstGen({parentIbGib:F.primitive({ib:Ba}),ib:await Bc({keystoneData:r}),data:r,dna:!1,nCounter:!0,tjp:{timestamp:!0,uuid:!0}})).newIbGib;if(!a.data)throw new Error("(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)");if(!a.rel8ns)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)");if(!a.rel8ns.past||a.rel8ns.past.length===0)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns.past falsy or empty? we expect the firstGen call to generate an interstitial ibgib that we will splice out. (E: 0fd8388d045ab9f37834c27d67e78825)");return a.data.n=0,a.data.isTjp=!0,delete a.rel8ns.tjp,delete a.rel8ns.past,a.gib=await ue({ibGib:a}),await e.put({ibGib:a,space:t}),await e.registerNewIbGib({ibGib:a,space:t}),a}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{Le&&console.log(`${o} complete.`)}}f(Xa,"createKeystoneIbGibImpl");async function qa({keystoneIbGib:r,dependencyGraph:e,getLatest:t,invalidIfMoreRecentKeystoneFoundInSpace:o,space:n}){let a=`[${qa.name}]`;try{if(Le&&console.log(`${a} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!r)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let s=[];if(t){let b=y({ibGib:r}),p=await st({ibGibs:[r],space:n});if(!p.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!p.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:u}=p.data;if(Object.keys(u).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let g=u[b];if(g)if(g!==b)if(o)s.push(`${a} more recent keystone (${g}) found than the one passed in (${b}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[m]=await it({addrs:[g],space:n});r=m}else Le&&console.log(`${a} incoming keystone (${b}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${a} keystoneIbGib (${b}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}e??=await Nt({ibGib:r,space:n});let i=Object.values(e),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:d,mapWithoutTjps:l}=vt({ibGibs:i});if(Object.keys(d).length>0&&s.push(`${a} DNA found. Keystones should NOT have DNA. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(l).length>0&&s.push(`${a} Non-tjp ibgibs found? Keystones are expected to have tjps. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(c).length>0){let b=Object.values(c),p=bt({ibGibs:b}),u=Object.keys(p);if(u.length===0)throw new Error("(UNEXPECTED) orderedKeystonesMap empty? (E: d437b80bef58e83a034b28af46278726)");if(u.length>1)throw new Error("(UNEXPECTED) more than one timeline in keystone graph? ATOW (02/19/2026) we are expecting only a single timeline. (E: 66085b14e3887a59c872afd240511f26)");let g=u[0],m=p[g];if(m.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await tn({keystoneIbGib:m[0]})).forEach(S=>s.push(S)),m.length!==1)for(let S=0;S<m.length-1;S++){let A=m[S],I=m[S+1],$=await lo({prevIbGib:A,currentIbGib:I});$.length>0&&(s.push(`${a} keystone has ${$.length} transition errors. i: ${S}. prevIbGib addr: ${y({ibGib:A})}. currentIbGib addr: ${y({ibGib:I})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),$.forEach(T=>s.push(T)));break}}else if(s.length===0)throw new Error("(UNEXPECTED) mapWithTjp_NoDna empty (which is an error) but errors.length === 0? If we get here, we expect one of the other errors to have been populated. (E: 7bca2866b6f8fca318923de8c88e8826)");return s}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{Le&&console.log(`${a} complete.`)}}f(qa,"validateKeystoneGraph");var Ze=!1,se=class r{static{f(this,"KeystoneService_V1")}lc=`[${r.name}]`;async genesis({masterSecret:e,frameDetails:t,configs:o,metaspace:n,space:a}){let s=`${this.lc}[${this.genesis.name}]`;try{Ze&&console.log(`${s} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let i=[];for(let l of o){let b=Ot.create({config:l}),p=await b.derivePoolSecret({masterSecret:e}),u={},g=l.behavior.size,m=Date.now().toString();for(let E=0;E<g;E++){let S=await Jo({salt:l.salt,timestamp:m,index:E}),A=await b.generateSolution({poolSecret:p,poolId:l.id,challengeId:S}),I=await b.generateChallenge({solution:A});u[S]=I}i.push({id:l.id,config:l,challenges:u})}if(i.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let c={challengePools:i,proofs:[]};return t&&(c.frameDetails=t),await Xa({data:c,metaspace:n,space:a})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{Ze&&console.log(`${s} complete.`)}}async sign({latestKeystone:e,masterSecret:t,claim:o,poolId:n,poolFilter:a,requiredChallengeIds:s=[],frameDetails:i,metaspace:c,space:d}){let l=`${this.lc}[${this.sign.name}]`;try{Ze&&console.log(`${l} starting...`);let b=e.data;if(b.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");let p=Zo({pools:b.challengePools,poolId:n,poolFilter:a,verb:o.verb});Ze&&console.log(`${l} Selected pool: ${p.id} (size: ${Object.keys(p.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let u=await Qo({pool:p,targetAddr:o.target,requiredChallengeIds:s}),{proof:g,nextPools:m}=await en({targetPoolId:p.id,prevPools:b.challengePools,masterSecret:t,challengeIds:u,claim:o,requiredChallengeIds:s}),E=(b.n??0)+1,S;if(E%Yo===0){let $={...e,data:{...b,frameDetails:i}};S=await this.getAggregateDetails({latestKeystone:$,metaspace:c,space:d})}return await fo({prevIbGib:e,newData:{challengePools:m,proofs:[g],frameDetails:i,checkpointDetails:S},metaspace:c,space:d})}catch(b){throw console.error(`${l} ${w(b)}`),b}finally{Ze&&console.log(`${l} complete.`)}}async validate({currentIbGib:e,prevIbGib:t}){return await lo({currentIbGib:e,prevIbGib:t})}async validateGenesisKeystone({keystoneIbGib:e}){return await tn({keystoneIbGib:e})}async getLatestKeystone({addr:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{Ze&&console.log(`${n} starting...`);let a=await t.getLatestAddr({tjpAddr:e,space:o});if(!a)throw new Error(`could not find latest addr for ${e}`);let s=await t.get({addr:a,space:o});if(s.success&&s.ibGibs&&s.ibGibs.length>0)return s.ibGibs[0];{let c=s.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find latest keystone at ${a}. addrsNotFound: ${c}? resGet.errorMsg: ${s.errorMsg}`)}}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{Ze&&console.log(`${n} complete.`)}}async validateKeystoneGraph({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a}){let s=`${this.lc}[${this.validateKeystoneGraph.name}]`;try{return Ze&&console.log(`${s} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await qa({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{Ze&&console.log(`${s} complete.`)}}async revoke({latestKeystone:e,masterSecret:t,reason:o="User initiated revocation",frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.revoke.name}]`;try{Ze&&console.log(`${i} starting...`);let c=e.data,d=Zo({pools:c.challengePools,poolId:Ka}),l={verb:Wo,target:y({ibGib:e})},b=await Qo({pool:d,targetAddr:l.target,requiredChallengeIds:[]});if(b.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${d.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:p,nextPools:u}=await en({targetPoolId:d.id,prevPools:c.challengePools,masterSecret:t,challengeIds:b,claim:l,requiredChallengeIds:[]});u.find(I=>I.id===d.id&&Object.keys(I.challenges).length>0)&&console.warn(`${i} revocation pool ${d.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${xe.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let g={reason:o,proof:p},m=(c.n??0)+1,E;if(m%Yo===0){let I={...e,data:{...c,frameDetails:n,revocationInfo:g}};E=await this.getAggregateDetails({latestKeystone:I,metaspace:a,space:s})}return await fo({prevIbGib:e,newData:{challengePools:u,proofs:[p],revocationInfo:g,frameDetails:n,checkpointDetails:E},metaspace:a,space:s})}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{Ze&&console.log(`${i} complete.`)}}async addPools({latestKeystone:e,masterSecret:t,newPools:o,metaspace:n,space:a}){let s=`${this.lc}[${this.addPools.name}]`;try{if(Ze&&console.log(`${s} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let i=e.data;if(i.revocationInfo)throw new Error("Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)");if(o.length===0)throw new Error("No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)");let c=Zo({pools:i.challengePools,verb:io});Ze&&console.log(`${s} Authorized via pool: ${c.id}`);let d=y({ibGib:e}),l={verb:io,target:d,scope:JSON.stringify({add:o.map($=>$.id)})},b=await Qo({pool:c,targetAddr:d}),{proof:p,nextPools:u}=await en({targetPoolId:c.id,prevPools:i.challengePools,masterSecret:t,challengeIds:b,claim:l}),g=new Set(u.map($=>$.id));for(let $ of o)if(g.has($.id))throw new Error(`Cannot add pool. ID collision: ${$.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5d)`);let m=[...u,...o],E=(i.n??0)+1,S;if(E%Yo===0){let $={...e,data:{...i,challengePools:m}};S=await this.getAggregateDetails({latestKeystone:$,metaspace:n,space:a})}return await fo({prevIbGib:e,newData:{challengePools:m,proofs:[p],checkpointDetails:S},metaspace:n,space:a})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{Ze&&console.log(`${s} complete.`)}}async getAggregateDetails({latestKeystone:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getAggregateDetails.name}]`;try{let a={},s=e;for(;s;){let i=s.data;if(i.checkpointDetails){a=Or({dominant:a,recessive:i.checkpointDetails});break}if(i.frameDetails&&(a=Or({dominant:a,recessive:i.frameDetails})),i.n===0)break;let c=s.rel8ns?.past,d=c&&c.length>0?c[c.length-1]:void 0;if(!d)break;let l=await t.get({addr:d,space:o});if(!l.success||!l.ibGibs||l.ibGibs.length===0)throw new Error(`Could not find previous keystone frame at ${d} (E: e3d069b22e11e550e58844889ddb5325)`);s=l.ibGibs[0]}return a}catch(a){throw console.error(`${n} ${w(a)}`),a}}};var rn="sync",ke="syncmsg",Wa="@payloadAddrsDomain",qf="init",Wf="ack",Yf="delta",zf="commit",me={init:qf,ack:Wf,delta:Yf,commit:zf},Zw=Object.values(me),Jf="abort",Zf="optimistic-graft-longest-common-subsequence",X={abort:Jf,optimisticWithLCS:Zf},yr=Object.values(X);function on(r){return yr.includes(r)}f(on,"isValidSyncConflictStrategy");var Qf="push",eb="pull",tb="sync",Ya={push:Qf,pull:eb,sync:tb},oy=Object.values(Ya);var rb="sender",ob="receiver",nn={sender:rb,receiver:ob},ny=Object.values(nn);var Hc=!1;function za({base:r,extended:e,throwIfExtendedDoesntContainBase:t}){let o=`[${za.name}]`;try{Hc&&console.log(`${o} starting... (I: 00d70d79a0249165c2a230389c962526)`);let n=!0;for(let s=0;s<r.length;s++)if(r[s]!==e[s]){n=!1;break}if(t&&!n)throw new Error(`base addrs do not correspond to extended addrs. We were expecting the base to be the exact start of the extended strand, e.g., base [a, b, c] with extended [a, b, c, d, e]. base: ${r}. extended: ${e}. (E: fb80b40003289bbf1aaedd4829fa1826)`);let a;if(n)a=e.slice(r.length);else{a=[];for(let s of e)r.includes(s)||a.push(s)}return a}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{Hc&&console.log(`${o} complete.`)}}f(za,"getUniqueDnas");async function an({src:r,createdIbGibs_Running:e,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:t,allLocalIbGibs:o}){let n=`[${an.name}]`;try{if(t.length>0){let a=t.splice(0,1)[0],s=o.filter(l=>y({ibGib:l})===a),i;if(s.length>0)i=s[0];else throw new Error(`dna ibGib not found in supplied allLocalIbGibs. dnaAddr: ${a}. (E: 7f56826852cf48a79ab8af16bf27e284)`);let c=H(i.data);c.src=r,c.srcAddr=y({ibGib:r});let d;switch(c.type){case"mut8":d=await nt(c);break;case"rel8":d=await Ke(c);break;case"fork":throw new Error("fork transform not expected. atow only a single fork is expected at the beginning of the lifetime of a tjp ibgib. This fork defines the uniqueness of the tjp ibgib. When merging another tjp ibgib, we would only expect update transforms to be mut8 or rel8. (E: f8ad6996ac5545edad2d58a293d37d94)");default:throw new Error(`unknown dna argTransform.type (${c.type}) for dna address: ${a}. Expecting either mut8 or rel8. (fork transform is known but not expected either.) (E: 52a98db56e934e4cb42c64e2f45fa552)`)}if((d.intermediateIbGibs??[]).forEach(l=>e.push(l)),(d.dnas??[]).forEach(l=>e.push(l)),e.push(d.newIbGib),(d.dnas??[]).length>0){if(!d.dnas.some(l=>y(l)===a))throw new Error(`${n}(UNEXPECTED) Expected to generate exact dna that we applied in transform. dnaAddr: ${a} (E: 4a364c0b5d8d46c8af6bd540915fd973)`)}else console.warn(`${n}(UNEXPECTED) expected resTransform to include generated dna. dnaAddr: ${a}(W: 9648e2d5c40d42b7b9fb7efb09c5b13a)`);return await an({src:d.newIbGib,createdIbGibs_Running:e,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:t,allLocalIbGibs:o})}else return e.length===0&&console.warn(`${n} no dna transforms to apply but createdIbGibs_Running is empty. Dna is expected to start with at least one transform, otherwise don't call this function. (W: 52c7f2f6bd7e4bd0b31f53611b90268b)(UNEXPECTED)`),r}catch(a){throw console.error(`${n} ${w(a)}`),a}}f(an,"applyTransforms");var Mr="graftinfo",$t=Mr,Kc="latestcommonaddr",tr="base",xt="orphan",Xc="dnaapplied",nb="longest-common-subsequence",Ja={lcs:nb},hy=Object.values(Ja);var Qe=!0;async function ab({data:r}){if(!r.conflictStrategy)throw new Error("(UNEXPECTED) data.conflictStrategy required for GraftInfoIb (E: 2c0968a0dac8d0ab3d67da9756d6df26)");if(!on(r.conflictStrategy))throw new Error(`invalid data.conflictStrategy (${r.conflictStrategy}). valid conflict strategies: ${yr} (E: 41e2680089786d4d28046b4c0884bd26)`);return[Mr,r.conflictStrategy].join(" ")}f(ab,"getGraftInfoIb");async function qc({conflictStrategy:r,details:e,addlGraftDetails:t,latestCommonFrameAddr:o,baseAddrsSinceLCA:n,orphanAddrsSinceLCA:a,dnaAddrsApplied:s}){let i=`[${qc.name}]`;try{if(Qe&&console.log(`${i} starting... (I: 0030f62cbae28cf5882f87981edc3826)`),n.length===0)throw new Error("(UNEXPECTED) baseAddrsSinceLCA empty? (E: 005f8449a9236d445902a148f59fc826)");if(a.length===0)throw new Error("(UNEXPECTED) orphanAddrsSinceLCA empty? (E: 19e4082e82c67759c880392aca186826)");let c={conflictStrategy:r,description:e};t&&(c.addlGraftDetails=t);let d={[Kc]:[o],[tr]:n.concat(),[xt]:a.concat(),[Xc]:s.concat()},l=await ab({data:c});return await F.stone({parentPrimitiveIb:Mr,ib:l,data:c,rel8ns:d,uuid:!0})}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{Qe&&console.log(`${i} complete.`)}}f(qc,"createGraftInfo");async function sb({textA:r,textB:e}){if(r===e)return r;if(r==="")return e;if(e==="")return r;function t(d,l){let b=d.length,p=l.length,u=Array(b+1).fill(0).map(()=>Array(p+1).fill(0));for(let S=1;S<=b;S++)for(let A=1;A<=p;A++)d[S-1]===l[A-1]?u[S][A]=u[S-1][A-1]+1:u[S][A]=Math.max(u[S-1][A],u[S][A-1]);let g=b,m=p,E=[];for(;g>0&&m>0;)d[g-1]===l[m-1]?(E.unshift({line:d[g-1],indexA:g-1,indexB:m-1}),g--,m--):u[g-1][m]>u[g][m-1]?g--:m--;return E}f(t,"longestCommonSubsequence");let o=r.split(`
|
|
21
|
+
`),n=e.split(`
|
|
22
|
+
`),a=t(o,n),s=[],i=0,c=0;for(let d of a){for(;i<d.indexA;)s.push(o[i]),i++;for(;c<d.indexB;)s.push(n[c]),c++;s.push(d.line),i++,c++}for(;i<o.length;)s.push(o[i]),i++;for(;c<n.length;)s.push(n[c]),c++;return s.join(`
|
|
23
|
+
`)}f(sb,"mergeTextByLongestCommonSubsequence");async function Za({timelineAddrsA:r,timelineAddrsB:e,latestCommonFrameAddr:t,conflictStrategy:o,ibGibReadCache:n,space:a}){let s=`[${Za.name}]`;try{let A=function(ye){let Rt=`${s}[${A.name}]`;for(let We of ye){if(!We.rel8ns)throw new Error(`(UNEXPECTED) ${Rt} someIbGib.rel8ns falsy? All ibgibs with mergeable timelines are expected to have rel8ns. addr: ${y({ibGib:We})} (E: 5534a478cd183a5ee27b28487448b226)`);if(!We.rel8ns.dna)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna falsy? We only have implemented grafting for dna. addr: ${y({ibGib:We})} (there should be another route for merging for non-dna timelines) (E: d86b388c627afd613f897e3819d8ab26)`);if(We.rel8ns.dna.length===0)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna.length === 0? We only have implemented grafting for dna. addr: ${y({ibGib:We})} (there should be another route for merging for non-dna timelines) (E: bf973662a0689dd9089912b861af2826)`)}};var i=A;f(A,"throwIfUnexpected"),Qe&&console.log(`${s} starting... (I: 3b4c3e8e59c883d9d3c352efd6380826)`);let c=[],d=[];if(r.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(e.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");if(t){if(!r.includes(t))throw new Error(`timelineAddrsA does not include latestCommonFrameAddr (${t}). timelineAddrsA: ${r} (E: c5a9afe371888da2a79963983426e826)`);if(!e.includes(t))throw new Error(`timelineAddrsB does not include latestCommonFrameAddr (${t}). timelineAddrsB: ${e} (E: 7e641f67c452b67d582d78484a88c826)`)}else if(t=r.findLast(ye=>e.includes(ye)),!t)throw new Error(`timelines do not share a common frame. A: ${r}. B: ${e} (E: 4c0e78a88a375d8588736668573f1e26)`);if(r.at(-1)===t){debugger;throw new Error("timelineAddrsA.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 3796fc4074a8c5899d549bb8c2e68826)")}if(e.at(-1)===t)throw new Error("timelineAddrsB.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 66fbb86e9e98531549888bf10a344f26)");let l=r.lastIndexOf(t),b=r.slice(l+1),p=await it({readCache_graph:n,addrs:b,space:a}),u=p.at(-1),g=e.lastIndexOf(t),m=e.slice(g+1),E=await it({readCache_graph:n,addrs:m,space:a}),S=E.at(-1);A(p),A(E);let I,$,T,_,G=Zt({ibGib:u}),v=G.valid?Number.parseInt(G.ticks):Number.MAX_SAFE_INTEGER,N=G.valid?G.ms??0:0,D=Zt({ibGib:S}),B=D.valid?Number.parseInt(D.ticks):Number.MAX_SAFE_INTEGER,R=D.valid?D.ms??0:0;v<B?(I=u,$=p,T=S,_=E):v>B?(I=S,$=E,T=u,_=p):N<=R?(I=u,$=p,T=S,_=E):(I=S,$=E,T=u,_=p);let k=y({ibGib:I}),M=$.map(ye=>y({ibGib:ye})),j=y({ibGib:T}),Q=_.map(ye=>y({ibGib:ye}));Qe&&console.log(`${s} baseTipAddr: ${k} (I: 93353d9b9b68b17088f57958df85e826)`),Qe&&console.log(`${s} orphanTipAddr: ${j} (I: 14df8867adc5dab97ff3c1e989b40e26)`);let[ee]=await it({addrs:[t],space:a});if(!ee)throw new Error("(UNEXPECTED) latestCommonFrameIbGib falsy? (E: ead2020b7ab8e4c4f824573133e33826)");if(!ee.rel8ns)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns falsy? (E: b3f338032d19816fc87d3c78af255726)");if(!ee.rel8ns.dna||ee.rel8ns.dna.length===0)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns.dna falsy/empty? It should at least have the first fork transform. (E: 98fd8c725f484d85c8d23ceb181ce826)");let Ae=ee.rel8ns.dna.concat(),Te=[];for(let ye of _){if(!ye.rel8ns)throw new Error("(UNEXPECTED) orphanFrame.rel8ns falsy? (E: ed910e3b930b1b5388d87c6f736a4826)");let Rt=za({base:Ae,extended:ye.rel8ns.dna??[],throwIfExtendedDoesntContainBase:!0});if(Rt.forEach(We=>Ae.push(We)),Rt.length===0)throw new Error("(UNEXPECTED) orphanDnaAddrsToApply empty? (E: d44ed439e538e5b538d12d71063f0826)");Rt.forEach(We=>Te.push(We))}let Ue=await it({addrs:Te,readCache_graph:n,space:a}),Me=[],pe=await an({src:I,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:Te.concat(),allLocalIbGibs:Ue,createdIbGibs_Running:Me});if(!pe.data)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data falsy? (E: 4792f8e84fc84966e89220fae0657826)");if(!pe.data.n)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data.n falsy? (E: a2b3ca4cdec8d01f282dd3e4ff9eab26)");if(Me.length===0)throw new Error("(UNEXPECTED) applyTransforms called but createdIbGibs_Running is empty? This should contain all of the (E: 5b6c788488f5095b08eb8e31d55b1726)");console.warn(`${s} START...................... Do we get a bunch of "already had addr(s)" messages for dna ibgibs? I'm thinking we will already have the dna ibgibs stored in the space (temp space?) before we do this graft. Maybe it creates new dna, I don't know. remove this later when we decide something to do about it. space.ib: ${a.ib} (W: bb60481ecabaa6f49e14203891824a26)`),await Xe({space:a,ibGibs:Me}),console.warn(`${s} END........................ Do we get a bunch of "already had addr(s)" messages for dna ibgibs? I'm thinking we will already have the dna ibgibs stored in the space (temp space?) before we do this graft. Maybe it creates new dna, I don't know. remove this later when we decide something to do about it. space.ib: ${a.ib} (W: bb60481ecabaa6f49e14203891824a26)`);let{mapWithTjp_NoDna:Ve,mapWithTjp_YesDna:et,mapWithoutTjps:he}=vt({ibGibs:Me});if(Object.keys(Ve).length>0)throw new Error("(UNEXPECTED) mapWithTjp_NoDna is populated? We've just applied the dna from the orphan branch which created ibgibs (and dnas). But we are expected to be executing on an ibgib timeline that has dna. The applyTransforms was not expected to create any other ibgibs than the one in our timeline (with dna) and any corresponding dnas. (E: 236e989fb5e8a4a498a21b98f718c826)");let tt=Object.values(et),lt=bt({ibGibs:tt});if(Object.keys(lt).length===0)throw new Error("(UNEXPECTED) newGraftedIbGibsByTjp has 0 timelines? we expect this to have a single timeline: the one we're grafting. (E: 2b7127bd0c6bfeaec8d66038ba208226)");if(Object.keys(lt).length>1)throw new Error("(UNEXPECTED) newGraftedIbGibsByTjp has more than one timeline? we expect this to have a single timeline: the one we're grafting. (E: 076758885b8ea7c89849a76334222326)");Object.values(lt)[0].forEach(ye=>c.push(ye));for(let ye of c)await Oe({ibGib:ye,space:a});let Gr;if(o===X.optimisticWithLCS){if(!I.data)throw new Error("(UNEXPECTED) baseTip.data falsy? (E: 92623857e19b9b4e081e8c8d9eb45526)");if(!T.data)throw new Error("(UNEXPECTED) orphanTip.data falsy? (E: 2e6828a4c9226ac917ab6fe833672826)");if((T.data.text||I.data.text)&&T.data.text!==I.data.text){Qe&&console.log(`${s} different data.text found. executing text merge for conflictStrategy ${o} (I: cfb5f9580832040388fc576eb71ac526)`);let ye=T.data.text??"",Rt=j,We=I.data.text??"",Un=k,Mn=await sb({textA:ye,textB:We}),rt=await nt({src:pe,dataToAddOrPatch:{text:Mn},dna:!0,nCounter:!!pe.data.n});if(rt.intermediateIbGibs&&rt.intermediateIbGibs.length>0)throw new Error("(UNEXPECTED) resMut8Text.intermediateIbGibs truthy/non-empty? This is expected to only create the newIbGib with no intermediates. (E: 7932a8964a3869accadc9b0d93d23826)");if(!rt.dnas||rt.dnas.length===0)throw new Error("(UNEXPECTED) resMut8Text.dnas falsy/empty? We're expected to generate dna from this merge text mut8. (E: fdf03754bf0f8661f80f59ea0701dd26)");if(rt.dnas.length!==1)throw new Error("(UNEXPECTED) resMut8Text.dnas.length !== 1? we're expecting a single mut8 dna. (E: 9574d86a9108095cb454b049bcca5326)");if(d.push(rt.dnas[0]),c.push(rt.newIbGib),await Ie({resTransform:rt,space:a}),await Oe({ibGib:rt.newIbGib,space:a}),Gr={mergeTextStrategy:Ja.lcs,textAAddr:Rt,textBAddr:Un},pe=rt.newIbGib,!pe.data)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data falsy after mut8 merge text? (E: 6b65d83df6681887686a0098144eea26)")}}let br=await qc({conflictStrategy:o,details:`Replayed ${Te.length} transforms from orphan (${j}) onto base (${k}).`,addlGraftDetails:Gr?[Gr]:void 0,latestCommonFrameAddr:t,baseAddrsSinceLCA:M,orphanAddrsSinceLCA:Q,dnaAddrsApplied:Te});Qe&&console.log(`${s} intrinsic graft complete. graftInfo to be appended to timeline:
|
|
24
|
+
${K(br)} (I: ab9d1e73db9a3ff4f8241f38197bb826)`),await Xe({ibGib:br,space:a});let Kr=y({ibGib:br}),gt=await Ke({src:pe,rel8nsToAddByAddr:{[$t]:[Kr]},dna:!0,nCounter:!!pe.data.n});if(gt.intermediateIbGibs&>.intermediateIbGibs.length>0)throw new Error("(UNEXPECTED) resRel8GraftInfo.intermediateIbGibs truthy/non-empty? This is expected to only create the newIbGib with no intermediates. (E: 78b928ace4287b4dc82f413fdad60826)");if(!gt.dnas||gt.dnas.length===0)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas falsy/empty? We're expected to generate dna from this rel8. (E: 4c8fdde70368d643f86732dfa48c5526)");if(gt.dnas.length!==1)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas.length !== 1? we're expecting a single rel8 dna. (E: c2f5085c1718d7149e04f5c814027926)");d.push(gt.dnas[0]),await Ie({resTransform:gt,space:a}),await Oe({ibGib:gt.newIbGib,space:a});let go=gt.newIbGib;Qe&&console.log(`${s} finalGraftTip: ${K(go)} (I: 454e72957be8221b96931c289053fc26)`);let Xr={dnasReplayed:Ue,dnasCreatedInGraft:d,intermediateIbGibsCreatedInGraft:c,newGraftTip:go,graftInfoCreated:br};return Qe&&console.log(`${s} result... (I: d6a02f95eb2564c621810ef855434226)`),Qe&&console.dir(Xr),Xr}catch(c){throw console.error(`${s} ${w(c)}`),c}finally{Qe&&console.log(`${s} complete.`)}}f(Za,"graftTimelines");function Qa(r){let e=`[${Qa.name}]`;try{if(Qe&&console.log(`${e} starting... (I: fe9adfe1a3175d87982507c8851f5826)`),!r)throw new Error("(UNEXPECTED) not a graft info, ibGib falsy? (E: bf06cdd700788e777f72fe5a5bdb0e26)");if(!r.data)throw new Error("not a graft info, ibGib.data falsy (E: 5e1b28843ec8571a7623046a06195826)");if(!r.ib.startsWith(Mr))throw new Error(`not graft info, ibgib.ib does not start with ${Mr} (E: cec6a8e25ff8746aef813e38cbebce26)`);return!0}catch(t){return Qe&&console.error(`${e} ${w(t)}`),!1}finally{Qe&&console.log(`${e} complete.`)}}f(Qa,"isGraftInfo");var _e=!1;async function es({data:r}){let e=`[${es.name}]`;try{return[rn,r.uuid].join(" ")}catch(t){throw console.error(`${e} ${w(t)}`),t}}f(es,"getSyncIb");async function Wc(){return`tmp_sync_space_${(await U()).substring(0,8)}`}f(Wc,"getTempSpaceName");async function Fr({olderAddr:r,newerAddr:e,space:t}){let o=`[${Fr.name}]`;try{if(_e&&console.log(`${o} starting... (I: 4b3548cbc9a2eb749f447ed82fdcf826)`),r===e)return!0;let n,a=await te({space:t,addr:e});if(a.success&&a.ibGibs?.length===1)n=a.ibGibs[0];else throw new Error(`couldn't get newerAddr (${e}) from space (${t.ib}). (E: 36c758c22b181b2c89a1cd28937a6826)`);if(!n.rel8ns)return console.warn(`${o} newerIbGib.rel8ns falsy? newerAddr: ${e}. (W: 6f920811f7080281189f767813814826)`),!1;let s=n.rel8ns.past??[];if(s.length===0)return!1;if(s.includes(r))return!0;let i=s[0];return await Fr({olderAddr:r,newerAddr:i,space:t})}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{_e&&console.log(`${o} complete.`)}}f(Fr,"isPastFrame");async function sn({sagaIbGib:r,localSpace:e}){let t=`[${sn.name}]`,o=f(async i=>{let c=await te({space:e,addrs:i});if(c.success&&c.ibGibs?.length===i.length)return c.ibGibs;{let d=c.rawResultIbGib;throw d.data?new Error(`(UNEXPECTED) couldn't find addrs? addrsNotFound: ${d.data.addrsNotFound}? space.ib: ${e.ib} (E: 43b7b5a6ad982715c8f3eed69bfa0d26)`):new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: c26c681d2f831fc537ba6f48fee36d26)")}},"fnGet"),n=await cn({sagaIbGib:r});if(n.length>0)throw new Error(`invalid sync sagaIbGib. validationErrors: ${n} (E: 19f9e8c9643858ff41312b62293d2126)`);if(!r.rel8ns)throw new Error("(UNEXPECTED) validated sagaIbGib.rel8ns falsy? (E: 73af48be8bbf271ec5cf78187ce8c826)");let a=r.rel8ns[ke],s=await o(a);return{sagaIbGib:r,msgStones:s}}f(sn,"getSyncSagaFrameDependencyGraph");async function jr({sagaIbGib:r,space:e}){let t=`[${jr.name}]`;try{if(_e&&console.log(`${t} starting... (I: 1ea3f804dd07d1e917a2afaaad497826)`),!r.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: fe0a0d0965e87ac852fe7ba4710cc826)");if(!r.rel8ns)throw new Error("(UNEXPECTED) sagaIbGib.rel8ns falsy? (E: b79ff82a732346bdf8a9e1eb9ac96826)");let o=y({ibGib:r}),n=r.rel8ns.past&&r.rel8ns.past.length>0?[...r.rel8ns.past,o]:[o],a=[];for(let s of n){let i,c=await te({addr:s,space:e});if(c.success&&c.ibGibs&&c.ibGibs.length===1)i=c.ibGibs[0];else throw _e&&console.log(`${t} failed getting full history of sagaIbGib:
|
|
25
|
+
${K(r)} (I: 2a35685bfe038f63182c7db39b44c826)`),new Error(`couldn't get saga addr (${s}) from space (${e.ib}) (E: 865b78ecd918c244158813650bea7d26)`);let d=await sn({sagaIbGib:i,localSpace:e});a.push(d)}return _e&&console.log(`${t} resGraphs:...
|
|
26
|
+
${K(a).split(`
|
|
27
|
+
`).join(`
|
|
28
|
+
`)}
|
|
29
|
+
...(I: d8e11827d88a3454d887ff05fb4ff526)`),a}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{_e&&console.log(`${t} complete.`)}}f(jr,"getFullSyncSagaHistory");async function cn({sagaIbGib:r}){let e=`[${cn.name}]`;try{_e&&console.log(`${e} starting... (I: dac978e9ec5820f128fbbff817b82826)`);let t=await ge({ibGib:r})??[];if(t.length>0)return t;if(r.data){let{data:o}=r;o.uuid||t.push("data.uuid required (E: aa24eeda7b88d22e5832a2e8083c0826)"),o.timestamp||t.push("data.timestamp required (E: 9c82a88548f4b63c38687428754b3826)"),o.timestampMs||o.timestampMs===0||t.push("data.timestampMs required (E: 9c82a88548f4b63c38687428754b3826)"),o.conflictStrategy?on(o.conflictStrategy)||t.push(`data.conflictStrategy (${o.conflictStrategy}) is invalid. Must be one of "${yr}". (E: 6223a8813b688fa2c8644fa8a491bf26)`):t.push("data.conflictStrategy required (E: 9c82a88548f4b63c38687428754b3826)"),o.expirationTimestamp,o.errors,o.successCount}else t.push("sagaIbGib.data falsy (E: 4de5e8de589d0af7245600fb4fe30926)");if(r.rel8ns){let o=r.rel8ns[ke];o&&o.length>0||t.push("sagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] required. (E: df648dc18148e718682acb4842ecf826)")}else t.push("sagaIbGib.rel8ns falsy (E: da37aa492a7275b68a5e1912c7a5e126)");return t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(cn,"validateSyncSagaFrame");async function ln({history:r}){let e=`[${ln.name}]`;try{return _e&&console.log(`${e} starting... (I: df02b802f6989096b8d8f728e2c0a526)`),console.error(`${e} NAG ERROR (NOT THROWN) need to implement more validation on full saga history. (E: 9bfcc9247a1c783fd361a4a8216fef26)`),[]}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(ln,"validateFullSyncSagaHistory");async function dn({ibGibs:r,space:e}){let t=`[${dn.name}]`;try{_e&&console.log(`${t} starting... (I: aa3ab828402836b3914800a8ffa1b826)`);let o=[],n=[];for(let a of r)$e({ibGib:a})||(Xn({ibGib:a})?o.push(a):n.push(a));return o.length>0&&await Xe({ibGibs:o,isDna:!0,space:e}),n.length>0&&await Xe({ibGibs:n,isDna:!1,space:e}),{payload_Dnas:o,payload_NonDnas:n}}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{_e&&console.log(`${t} complete.`)}}f(dn,"putInSpace_dnasThenNonDnas");function Vr({sagaFrame:r}){let e=`[${Vr.name}]`;try{if(_e&&console.log(`${e} starting... (I: 93521332d0dd2f5e88398b7db95e8126)`),!r)throw new Error("(UNEXPECTED) sagaFrame falsy? (E: 01fb28be6668d88ea49bb298c739c926)");if(!r.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 998298eb17685bdb9a85b46488ccd826)");if(!r.data.n&&r.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 0394919d5b58300ceb09ba6a264ad826)");let t=r.data.n%2;if(t===0)return nn.sender;if(t===1)return nn.receiver;throw new Error("(UNEXPECTED) modulo is neither 0 nor 1? my logic sucks! This was way too defensive on my part... (E: 559488a2eef8d17b57079ca8886ee826)")}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(Vr,"getSyncSagaFrameOrigin");async function fn({sagaHistory:r}){let e=`[${fn.name}]`;try{_e&&console.log(`${e} starting... (I: fe93a8f29e5d8ab2c8bd0e08e56f7826)`);let t=r.findLast(a=>a.msgStones.some(s=>s.data.stage===me.delta));if(!t)throw new Error("(UNEXPECTED) no delta frame? What are we calling this function for? (E: 9b3201207908f79868b93cd893a91626)");let o=t.msgStones.filter(a=>a.data.stage===me.delta);if(o.length>1)throw new Error("(UNEXPECTED) multiple delta stones in history slice? we're expecting a single delta stone per saga frame. (E: a4bd5860b4aa0743753d4798d3163826)");return o[0].data.conflicts}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(fn,"getFinalConflictsInfo");async function ts({sagaHistory:r,myTempSpace:e}){let t=`[${ts.name}]`;try{_e&&console.log(`${t} starting... (I: b755627e99c9a221566d86a81b0da526)`);let o=await fn({sagaHistory:r});if(!o||o.length===0)return _e&&console.log(`${t} no conflicts found. returning empty array (I: 5dce98010128a284c8ec92cd466a3826)`),[];let n=[];for(let a of o){if(!a.resolved)throw new Error("(UNEXPECTED) conflict.resolved falsy? we're expecting all conflicts to be resolved when getting orphaned addresses. (E: 3861e89a18c8ff405eb2117f6d4b9b26)");if(!a.graftInfoAddr)throw new Error("(UNEXPECTED) conflict.graftInfoAddr falsy? we're expecting a resolved conflict whose final ibgib (graft tip) was the graft info and for this addr to be in conflict.graftInfoAddr. (E: 80d86e333028585908f4757bc4d6f826)");let s=await it({addrs:[a.graftInfoAddr],space:e});if(s.length!==1)throw new Error(`(UNEXPECTED) couldn't get conflict.graftInfoAddr (${a.graftInfoAddr}) from myTempSpace (${e.ib})? (E: cf1fe87096f8ea22f84f250d7ab30226)`);let i=s[0];if(!Qa(i))throw new Error(`(UNEXPECTED) graft info from conflict.graftInfoAddr (${a.graftInfoAddr}) does not pass the isGraftInfo guard? We're expecting this addr to point to a valid GraftInfoIbGib_V1 (E: 6aa9ecb9a428d92be8d1bdbe0696f826)`);let c=i.rel8ns[xt];if(!c||c.length===0)throw new Error(`(UNEXPECTED) orphanedAddrs empty for conflict graftInfo (${a.graftInfoAddr})? we're expecting a graft to always necessarily orphan one or other branches, otherwise what are we "grafting"? (E: 3ed1284f6ca84754582801484d751926)`);c.forEach(d=>n.push(d))}return n}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{_e&&console.log(`${t} complete.`)}}f(ts,"getAllOrphanedAddresses");async function $r({senderSecret:r,sagaId:e}){let t=`[${$r.name}]`;try{if(_e&&console.log(`${t} starting... (I: 0de03f8dcd3e32f1fca244e8f2a8a826)`),!r)throw new Error("(UNEXPECTED) senderSecret falsy? (E: 8ce053fe59825a6678713128953b9d26)");if(!e)throw new Error("(UNEXPECTED) sagaId falsy? (E: 3a17e0c1b2f849de8a42cd15b8ee6826)");return await ka({masterSecret:r,kdfOpts:{strategy:so.recursive_salt_wrap,salt:e,rounds:1e4,algorithm:"SHA-256"}})}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{_e&&console.log(`${t} complete.`)}}f($r,"deriveSessionSecret");var Yc=!1,rr=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 U(),this.gib=await ue({ibGib:this.toIbGibDto()})}toIbGibDto(){return qe({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return Yc&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=H(e.ib),this.gib=H(e.gib),e.data?this.data=H(e.data):delete this.data,e.rel8ns?this.rel8ns=H(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Yc&&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 bn="subject",rs=/^[a-zA-Z0-9_\-.]{1,255}$/,zc="subject",Jc="",pn="subject is a cool ibgib witness that has seriously fascinating behavior.";var Zc="observable";var or={subscribe:"subscribe"},Qc=Object.values(or);var el={next:"next",error:"error",complete:"complete"};var nr={...or,...el};var bo={version:"1",uuid:Jc,name:zc,description:pn,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},os=void 0;var ar=!1;function tl(r){let e=`[${tl.name}]`;try{let t=r?`${eo} ${r}`:eo;return ar&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(tl,"getArgIb");function ib({ib:r,ibGib:e}){let t=`[${ib.name}]`;try{if(ar&&console.log(`${t} starting...`),!r)if(e)r=e.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return r.startsWith(eo)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{ar&&console.log(`${t} complete.`)}}f(ib,"isArg");function rl(r){let e=`[${rl.name}]`;try{let t=r?`${Do} ${r}`:Do;return ar&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(rl,"getResultIb");async function Ir({argData:r,ibMetadata:e,noTimestamp:t}){let o=`[${Ir.name}]`;try{let n=await F.firstGen({ib:tl(e),parentIbGib:F.primitive({ib:eo}),data:r,dna:!1,noTimestamp:t});if(n.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Wt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Ir,"argy_");async function Sr({resultData:r,ibMetadata:e,noTimestamp:t}){let o=`[${Sr.name}]`;try{let n=await F.firstGen({ib:rl(e),parentIbGib:F.primitive({ib:Do}),data:r,dna:!1,noTimestamp:t});if(n?.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Wt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Sr,"resulty_");function ns({ibGib:r}){let e=`[${ns.name}]`;try{if(ar&&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{ar&&console.log(`${e} complete.`)}}f(ns,"isCommand");function as({ibGib:r}){let e=`[${as.name}]`;try{return ar&&console.log(`${e} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof r.witness=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ar&&console.log(`${e} complete.`)}}f(as,"isWitness");var ol=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var sr=!1;function al({rawMsg:r}){let e=`[${al.name}]`;try{sr&&console.log(`${e} starting...`);let t=ss({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{sr&&console.log(`${e} complete.`)}}f(al,"getErrorIb");function ss({rawMsg:r}){let e=`[${ss.name}]`;try{if(sr&&console.log(`${e} starting...`),!r)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let t,o=r.match(Fs);if(o){let[n,a,s,i,c,d]=o;if(!i)throw new Error("invalid error msg body (E: a675e6855cca96519d33d44ea5400922)");t={success:!1,raw:r,body:i?.trim(),uuid:c.slice(4,36)},a&&(t.location=a),(s||d)&&(t.unexpected=!0)}else{t={success:!1,raw:r,body:r};let n=r.match(js);if(n){let[a,s]=n;t.location=s}r.toLowerCase().includes("(unexpected)")&&(t.unexpected=!0)}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{sr&&console.log(`${e} complete.`)}}f(ss,"parseRawErrorMsg");function _r({rawMsg:r}){let e=`[${_r.name}]`;try{return sr&&console.log(`${e} starting...`),mt({parentPrimitiveIb:"error",ib:al({rawMsg:r}),data:ss({rawMsg:r}),ibRegExpPattern:ol.source})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{sr&&console.log(`${e} complete.`)}}f(_r,"getErrorIbGib");function Ht({ibGib:r}){let e=`[${Ht.name}]`;try{if(sr&&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{sr&&console.log(`${e} complete.`)}}f(Ht,"isError");var hn=class r{static{f(this,"WitnessFactoryBase")}lc=`[${r.name}]`};var is=!1,Hr=class r extends hn{static{f(this,"DynamicFormFactoryBase")}lc=`[${r.name}]`;patchDataFromItems({data:e,contextPath:t,items:o,pathDelimiter:n}){let a=`${this.lc}[${this.patchDataFromItems.name}]`;try{if(is&&console.log(`${a} starting...`),!n)throw new Error("pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)");for(let s=0;s<o.length;s++){let i=o[s],c=t?t+n+i.name:i.name;if(!i.items)Kn({obj:e,value:i.value,path:c,logalot:is,pathDelimiter:n});else if(i.items.length>0)this.patchDataFromItems({data:e,contextPath:c,items:i.items,pathDelimiter:n});else throw new Error("invalid item. items is truthy but with a length of 0. items should either be falsy or have at least one child. (E: ee2765e0b920477f919fcb09e9d951b4)")}}catch(s){throw console.error(`${a} ${s.message}`),s}finally{is&&console.log(`${a} complete.`)}}};var sl="subscription",cs=/^[a-zA-Z0-9_\-.]{1,255}$/,il="",cl="subscription",un="subscription is a cool ibgib witness that has seriously fascinating behavior.";var po={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var ls={version:"1",uuid:il,name:cl,description:un,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},ds=void 0;var ll=!1;function fs({ibGib:r}){let e=`[${fs.name}]`;try{ll&&console.log(`${e} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:t}=r;return[Zc,bn].some(n=>t.includes(n))}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ll&&console.log(`${e} complete.`)}}f(fs,"isObservable");var ie=!1,gn=class r extends rr{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(ie&&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=En({data:this.data,classname:"Subscription_V1"}),this.gib=await ue({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&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(ie&&console.log(`${t} ib: ${o} (I: 4de7771f477dc5b36933343b694ce223)`),o===po.unsubscribe)return ie&&console.log(`${t} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(o===po.unsubscribed)return ie&&console.log(`${t} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if(fs({ibGib:e}))return ie&&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} ${w(o)??"unknown error (E: b0bbaab21833404a9420c3d273df7f21)"}`),o}}async witness_unsubscribe(){let e=`${this.lc}[${this.witness_unsubscribe.name}]`;try{if(ie&&console.log(`${e} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${e} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),q;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),q;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return ie&&(console.log(`${e} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),ie&&(console.log(`${e} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,ie&&console.log(`${e} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),q}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async witness_observable({ibGib:e}){let t=`${this.lc}[${this.witness_observable.name}]`;try{if(ie&&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,ie&&console.log(`${t} this._srcObservable set to ibgib with ib: ${e.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{ie&&console.log(`${t} complete.`)}}async witness_unsubscribed(){let e=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(ie&&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?na:di;return ie&&console.log(`${e} result: ${K(t)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async unsubscribe(){let e=`${this.lc}[${this.unsubscribe.name}]`;try{ie&&console.log(`${e} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let t=await this.witness(F.primitive({ib:po.unsubscribe}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(Ht({ibGib:t})){let o=t;throw new Error(`${o.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async unsubscribed(){let e=`${this.lc}[${this.unsubscribed.name}]`;try{ie&&console.log(`${e} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let t=await this.witness(F.primitive({ib:po.unsubscribed}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let o=t.ib===na.ib;return ie&&console.log(`${e} resUnsubscribed: ${o} (I: b4800166c58d5ba2ca1dccaa53de2323)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return ie&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ie&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let a=await Ir({argData:e,ibMetadata:t,noTimestamp:o});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let o=await Sr({resultData:e});return t&&(o.ibGibs=t),o}},mn=class r extends Hr{static{f(this,"Subscription_V1_Factory")}lc=`[${r.name}]`;getName(){return gn.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{ie&&console.log(`${o} starting...`),e??=H(ls),e=e,t=t??ds?H(ds):void 0,e.uuid||=await U();let{classname:n}=e,a=En({data:e}),s=await mt({parentPrimitiveIb:`witness ${n}`,ib:a,data:e,rel8ns:t}),i=new gn(void 0,void 0);return await i.loadIbGibDto(s),ie&&console.log(`${o} witnessDto: ${K(s)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:i}}catch(n){throw console.error(`${o} ${w({error:n})}`),n}finally{ie&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{ie&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");ie&&console.log(`${t} data: ${K(o)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await qr({n:100}),a=new wn().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??un}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"subscription"});return Promise.resolve(a)}catch(o){throw console.error(`${t} ${w({error:o})}`),o}finally{ie&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=H(ls);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:Cr}),await this.newUp({data:t})}};var yn=!1;function dl({data:r}){let e=`[${dl.name}]`;try{if(yn&&console.log(`${e} starting...`),!r)throw new Error("Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)");let t=[],{name:o,uuid:n,classname:a}=r;return o?o.match(cs)||t.push(`name must match regexp: ${cs} (E: 21bf77e398d47e9d035376510505eda2)`):t.push("name required."),n?n.match(Ge)||t.push(`uuid must match regexp: ${Ge} (E: e53fd08ae69e945b37ed895b864b6bd7)`):t.push("uuid required."),a&&(a.match(qt)||t.push(`classname must match regexp: ${qt}`)),t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{yn&&console.log(`${e} complete.`)}}f(dl,"validateCommonSubscriptionData");function En({data:r,classname:e}){let t=`[${En.name}]`;try{let o=dl({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 ${sl} ${e} ${n}`}catch(o){throw console.error(`${t} ${w(o)}`),o}}f(En,"getSubscriptionIb");var wn=class r extends Jt{static{f(this,"SubscriptionFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subscription"}};function $n({ibGib:r}){let e=`[${$n.name}]`;try{if(yn&&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{yn&&console.log(`${e} complete.`)}}f($n,"isSubscription");async function fl(){return(await new mn().newUp({})).newIbGib}f(fl,"newupSubscription");var bs="observable_event";var bl=!1;async function ps({eventType:r,srcObservable:e,payload:t}){let o=`[${ps.name}]`;try{if(bl&&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(Ge))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${Ge.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await U(),eventType:r,srcObservableId:e.data.uuid,"@srcObservableAddr":y({ibGib:e}),"@payloadAddr":y({ibGib:t})};return await mt({parentPrimitiveIb:bs,ib:pl({data:n}),data:n})}catch(n){throw console.error(`${o} ${n.message}`),n}finally{bl&&console.log(`${o} complete.`)}}f(ps,"getObservableEventIbGib");function pl({data:r,classname:e}){let t=`[${pl.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`${bs} ${e} ${r.uuid}`}catch(o){throw console.error(`${t} ${w(o)}`),o}}f(pl,"getObservableEventIb");var we=!1,In=class r extends rr{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(ns({ibGib:e}))return this.witness_cmd({arg:e});if(as({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} ${w(o)??"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),o}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{if(we&&console.log(`${t} starting... (I: 69257fac8328b9de9755fdd237b92723)`),e.data.cmd===or.subscribe)return this.witness_subscribe_cmd({ibGib:e});throw new Error(`unknown command. must be of type ObservableCmd (${Qc}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async witness_otherWitness({arg:e}){let t=`${this.lc}[${this.witness_otherWitness.name}]`;try{return we&&console.log(`${t} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),$n({ibGib:e})?this.witness_subscriptionIbGib({arg:e}):this.witness_subscribe_nonCmdWitness({arg:e})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async witness_subscriptionIbGib({arg:e}){let t=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(we&&console.log(`${t} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`),!e.data)throw new Error("arg.data required (E: 764ae772727ceba95a18140fdd938323)");let o=this.getSubscriberKey({subscription:e}),[n,a]=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 q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async replayPastPayloads({observer:e,subscription:t}){let o=`${this.lc}[${this.replayPastPayloads.name}]`;try{we&&console.log(`${o} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`);let n=this.getSubscriberKey({subscription:t}),a=f(()=>!!this._subscribers[n],"fnStillSubscribed"),s=-1,i=!0;do if(s++,s<this._pastPayloads.length){if(!a()){we&&console.log(`${o} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`);return}try{let c=this._pastPayloads[s];await e.next(c)}catch{console.error(`${o} observer errored on payload (i: ${s}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`);return}}else i=!1;while(i);if(this.isErrored&&e.error&&a())try{await e.error(this._pastError)}catch{console.error(`${o} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`)}else if(this.isComplete&&e.complete&&a())try{await e.complete()}catch{console.error(`${o} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{we&&console.log(`${o} complete.`)}}async witness_subscribe_cmd({ibGib:e}){let t=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(we&&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 fl();return we&&console.log(`${t} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,we&&console.log(`${t} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,o],we&&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{we&&console.log(`${t} complete.`)}}async witness_subscribe_nonCmdWitness({arg:e}){let t=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw we&&console.log(`${t} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{we&&console.log(`${t} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let o;if(Ar({ibGib:e})){let n=await this.argy({argData:{cmd:or.subscribe,ibGibAddrs:[y({ibGib:e})]},ibGibs:[e]});o=await this.witness(n)}else o=await this.witness(e);if(!$n({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{we&&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{we&&console.log(`${n} starting... (I: 0b990ce892f689d14458565717e66a23)`);let a=Object.values(this._subscribers);for(let s=0;s<a.length;s++){let[i,c]=a[s];if(Ar({ibGib:c})){let d=c;await t(d,e),d.complete?await i.unsubscribed()?console.warn(`${n} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`):await d.complete():we&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let d=await ps({eventType:o,srcObservable:this,payload:e});await c.witness(d)}}}catch(a){throw console.error(`${n} ${a.message}`),a}finally{we&&console.log(`${n} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return we&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{we&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let a=await Ir({argData:e,ibMetadata:t,noTimestamp:o});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let o=await Sr({resultData:e});return t&&(o.ibGibs=t),o}};var le=!1,Sn=class r extends In{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{le&&console.log(`${t} starting... (I: 8e47b752314870ec78eb14342621f723)`);let o=await this.argy({argData:{cmd:nr.subscribe,ibGibAddrs:[y({ibGib:e})]},ibGibs:[e]});return await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async next(e){let t=`${this.lc}[${this.next.name}]`;try{le&&console.log(`${t} starting... (I: b30363827c56450ca918c69aa15b0046)`);let o=await this.argy({argData:{cmd:nr.next,ibGibAddrs:[y({ibGib:e})]},ibGibs:[e]});await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async error(e){let t=`${this.lc}[${this.error.name}]`;try{le&&console.log(`${t} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let o;if(typeof e=="string")o=await _r({rawMsg:e});else if(e instanceof Error||typeof e.message=="string")o=await _r({rawMsg:w(e)});else if(e.ib&&Ht({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:nr.error,ibGibAddrs:[y({ibGib:o})]},ibGibs:[o]});await this.witness(n)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async complete(){let e=`${this.lc}[${this.complete.name}]`;try{le&&console.log(`${e} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let t=await this.argy({argData:{cmd:nr.complete}});await this.witness(t)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{le&&console.log(`${e} complete.`)}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{le&&console.log(`${t} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:o}=e.data;switch(o){case nr.next:return this.witness_next({ibGib:e});case nr.error:return this.witness_error({ibGib:e});case nr.complete:return this.witness_complete({ibGib:e});default:return super.witness_cmd({arg:e})}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async witness_next({ibGib:e}){let t=`${this.lc}[${this.witness_next.name}]`;try{if(le&&console.log(`${t} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return le&&console.log(`${t} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),q;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 a=0;a<n.length;a++){let[s,i]=n[a];if(le&&console.log(`${t} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await s.unsubscribed())le&&console.log(`${t} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`),await i.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 q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async witness_error({ibGib:e}){let t=`${this.lc}[${this.witness_error.name}]`;try{if(le&&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 a=0;a<n.length;a++){let[s,i]=n[a];if(Ar({ibGib:i})){let c=i;c.error?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: 8946e97f00fd4146a470064b490a4c29)`):await c.error(o):le&&console.log(`${t} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await i.witness(o)}return q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async witness_complete({ibGib:e}){let t=`${this.lc}[${this.witness_complete.name}]`;try{le&&console.log(`${t} starting... (I: 4db180f465e24df9a4ded37fbd235558)`),this._isComplete=!0;let o=Object.values(this._subscribers);for(let n=0;n<o.length;n++){let[a,s]=o[n];if(Ar({ibGib:s})){let i=s;i.complete?await a.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 i.complete():le&&console.log(`${t} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await s.witness(e)}return q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return le&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{le&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){if(e.cmd===or.subscribe)return super.argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n});{let a=await Ir({argData:e,ibMetadata:t,noTimestamp:o});return n&&(a.ibGibs=n),a}}async resulty({resultData:e,ibGibs:t}){let o=await Sr({resultData:e});return t&&(o.ibGibs=t),o}},_n=class r extends Hr{static{f(this,"Subject_V1_Factory")}lc=`[${r.name}]`;getName(){return Sn.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{le&&console.log(`${o} starting...`),e??=H(bo),e=e,t=t??os?H(os):void 0,e.uuid||=await U();let{classname:n}=e,a=hs({data:e}),s=await mt({parentPrimitiveIb:`witness ${n}`,ib:a,data:e,rel8ns:t}),i=new Sn(void 0,void 0);return await i.loadIbGibDto(s),le&&console.log(`${o} witnessDto: ${K(s)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:i}}catch(n){throw console.error(`${o} ${w({error:n})}`),n}finally{le&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{le&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");le&&console.log(`${t} data: ${K(o)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await qr({n:100}),a=new An().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??pn}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"observable"});return Promise.resolve(a)}catch(o){throw console.error(`${t} ${w({error:o})}`),o}finally{le&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=H(bo);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:Cr}),await this.newUp({data:t})}};var Tn=!1;function hl({data:r}){let e=`[${hl.name}]`;try{if(Tn&&console.log(`${e} starting...`),!r)throw new Error("Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)");let t=[],{name:o,uuid:n,classname:a}=r;return o?o.match(rs)||t.push(`name must match regexp: ${rs} (E: de987eb8fea0b6232f60abf31815095c)`):t.push("name required."),n?n.match(Ge)||t.push(`uuid must match regexp: ${Ge} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):t.push("uuid required."),a&&(a.match(qt)||t.push(`classname must match regexp: ${qt}`)),t}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Tn&&console.log(`${e} complete.`)}}f(hl,"validateCommonSubjectData");function hs({data:r,classname:e}){let t=`[${hs.name}]`;try{let o=hl({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:a}=r;return`witness ${bn} ${e} ${n} ${a}`}catch(o){throw console.error(`${t} ${w(o)}`),o}}f(hs,"getSubjectIb");var An=class r extends Jt{static{f(this,"SubjectFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subject"}};function Ar({ibGib:r}){let e=`[${Ar.name}]`;try{return Tn&&console.log(`${e} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof r.next=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Tn&&console.log(`${e} complete.`)}}f(Ar,"isObserver");async function Gn({data:r,replay:e}={}){let t=new _n;return r??=H(bo),e&&(r.replay=!0),(await t.newUp({data:r})).newIbGib}f(Gn,"newupSubject");var Cn="sync_sagacontext";var ho=!1;async function us({data:r}){let e=`[${us.name}]`;try{if(!r)throw new Error("data required (E: 839d82138c234b3e89582855594191fe)");let t=r["@payloadAddrsDomain"]?r["@payloadAddrsDomain"].length:0;return[Cn,r.sagaN,t].join(" ")}catch(t){throw console.error(`${e} ${w(t)}`),t}}f(us,"getSyncSagaContextIb");async function ir({context:r}){let e=`[${ir.name}]`;try{ho&&console.log(`${e} starting... (I: 7797f8294bd8f7e5089cb722ad468226)`);let t=[],o=await ge({ibGib:r});if(o&&o.length>0)return o.forEach(n=>t.push(n)),t;if(r.sagaFrame?(await cn({sagaIbGib:r.sagaFrame})).forEach(a=>t.push(a)):t.push("context.sagaFrame is falsy. (E: b4edd88f4963f493789f83b29ba2df26)"),r.sagaFrameMsg){if((await ge({ibGib:r.sagaFrameMsg})??[]).forEach(a=>t.push(a)),r.sagaFrame){let a=r.sagaFrame.rel8ns?.[ke]?.[0];if(a){let s=y({ibGib:r.sagaFrameMsg});s!==a&&t.push(`context.sagaFrameMsg address (${s}) does not match the stone address referenced in sagaFrame relations (${a}). (E: a983b271fcae46bbad7e82098bc24826)`)}else t.push(`context.sagaFrame is missing the message stone relation '${ke}'. (E: da872cf3a8d46dbbad89d0a68d712826)`)}}else t.push("context.sagaFrameMsg is falsy. (E: ed405a72ab0d8bbdca7b9605d8f9a26)");return t.length>0?t:(console.error(`${e} NAG ERROR MSG (NOT THROWN): not fully implemented yet (E: d574d85cb578637648ed403857f7a826)`),[])}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ho&&console.log(`${e} complete.`)}}f(ir,"validateContextAndSagaFrame");async function gs({context:r,space:e}){let t=`[${gs.name}]`;try{ho&&console.log(`${t} starting... (I: 3c34e8f1d6ef965f98725c88459ea926)`);let o=[];if(!r.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 3e4ddd0eb4b828ad489658d88d9a6326)");if(!r.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 8026589d4fed69c828334ee842074326)");let{sagaFrame:n,signedSessionIdentity:a}=r;if(!n.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: b61cc82d25984c92f75db74a5a855b26)");if(!a)return console.error(`${t}[NAG][not thrown] sagaFrame.data.sessionIdentityTjpAddr logic needs to be added in coordinator (E: 4fc47800a1086c917a47381824280826)`),n.data.sessionIdentityTjpAddr?(o.push("Context has no session identity, but sync saga frame shows a session identity (sagaFrame.data.sessionIdentityTjpAddr is truthy). (E: 69dd6cdc2e1859c0f3d62958c4339826)"),o):r.rel8ns.sessionIdentity?(o.push("Context has no signed session identity, but context.rel8ns.sessionIdentity is truthy. (E: 96a04a8a6c88ea8bf88118f89ad8e326)"),o):(ho&&console.log(`${t} context has no signedSessionIdentity and sync saga frame doesn't state there should be session identity. So nothing further to authenticate - returning early with no authentication errors. (I: d708735f9a2899ee98f762b8a09ed826)`),[]);let s=y({ibGib:a}),i=r.rel8ns?.sessionIdentity??[];if(i.length===0)return o.push("context.rel8ns.sessionIdentity is falsy/empty but context.signedSessionIdentity is present. (E: 66f906421eb2468c0b33f908a3cf2826)"),o;if(i.length>1)return o.push("context.rel8ns.sessionIdentity has multiple identity addrs. (E: 489428bfe6fdaa4cd885b938dc4c5826)"),o;let c=i[0],d=await st({addrs:[c],space:e});if(!d)throw new Error(`(UNEXPECTED) resGetLatestAddr for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 7b207e5cbcec9037ea5adbe822ead826)`);if(!d.data)throw new Error(`(UNEXPECTED) resGetLatestAddr.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: de4eb8d730c8c4dcb59c8b9c79277826)`);if(!d.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr.data.success falsy? (E: c94298dfd9684ad6a87eb748459aa826)");let{latestAddrsMap:l}=d.data;if(!l)throw new Error("(UNEXPECTED) resGetLatestAddr.data.latestAddrsMap falsy? (E: 19f1fd5fe798cf2e5fa923919169d826)");if(Object.keys(l).length!==1)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap).length !== 1? (E: fe526a0747589c6427a8bcc86da34a26)");let b=l[c];if(!b)return o.push(`prevSessionIdentityAddr (${c}) not found in space (${e.ib}). this should have been the incoming prevSessionIdentityAddr (E: f6d042bd6b54819998653228dee34226)`),o;if(c!==b&&b!==s)return o.push(`context.rel8ns.sessionIdentity does not point to the most recent in the space (${e.ib}). (E: 2f8288f53c87b6aa47bd2178d9df0c26)`),console.log(`context: ${K(qe({ibGib:r}))}`),console.log(`prevSessionIdentityAddr (context.rel8ns.sessionIdentity): ${c}`),console.log(`prevSessionIdentityAddr_latest: ${b}`),console.log(`currSessionIdentity (context.signedSessionIdentity): ${K(qe({ibGib:{ib:a.ib,gib:a.gib,rel8ns:a.rel8ns,data:{...a.data,challengePools:a.data.challengePools.map(M=>({...M,challenges:{}}))}}}))}`),console.log(`currSessionIdentityAddr: ${s}`),o;let p=await te({addr:c,space:e});if(!p.success||p.ibGibs?.length!==1)return o.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: fd48c3e64c9fa4efd8a1f8280af18226)`),o;let u=p.ibGibs[0],g=await to({ibGib:u,naive:!0,space:e});if(!g)throw new Error(`(UNEXPECTED) couldn't get sessionIdentityTjp in space (${e.ib})? we have already gotten the identity itself in the space, so we would expect the entire timeline to exist in it. (E: 9be0382ff1c8a0e77645ea38c096f826)`);let m=y({ibGib:g});if(m!==n.data.sessionIdentityTjpAddr)throw new Error("(UNEXPECTED) sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr? (E: c9a4ad5c2728fe38e86afc58e4abaf26)");let E=g.data.frameDetails;if(!E)return o.push("Invalid session identity tjp: sessionIdentityTjp.data.frameDetails is falsy. (E: 0187f8f804a84256281720586620b826)"),o;let{senderIdentityAddr:S,senderIdentityTjpAddr:A}=E;if(!S)throw new Error("sessionGenesisFrameDetails.senderIdentityAddr falsy (E: 02a0c80a3ead9e3af8af4cf3b156e826)");if(!A)throw new Error("sessionGenesisFrameDetails.senderIdentityTjpAddr falsy (E: 271928090ff5dc56d4bb63d8d5c68826)");let I=await st({addrs:[A,S],space:e});if(!I)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e4ae8083b6fb7cbb8fae2a519062926)`);if(!I.data)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e231850c2a898cc282b4b2841056826)`);if(!I.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.success falsy? (E: e93508f03e0475925875b00746ffd826)");let{latestAddrsMap:$}=I.data;if(!$)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.latestAddrsMap falsy? (E: 87a91e3f9968ad9ba79cdfe8cd878326)");if(Object.keys($).length!==2&&A!==S)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr? (E: fe46bd584853d8e1e8e2d11f52012826)");let T=$[A],_=$[S];if(!_)throw new Error("(UNEXPECTED) senderIdentityAddr_latest falsy? (E: e151798ae2e9241578d09948937c4b26)");if(T!==_)throw new Error("senderIdentityTjpAddr_latest !== senderIdentityAddr_latest (E: 52478a1053589e72665031a853cc1826)");let G=await te({addr:_,space:e});if(!G.success||G.ibGibs?.length!==1)return o.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: 3565ff0ed458f5a2384c40b16e849826)`),o;let v=G.ibGibs[0];if(!v.data.proofs)return o.push("Invalid sender identity. Proofs empty/falsy. (E: ebf488853061614d2b5b137828119526)"),o;let N=v.data.proofs.find(M=>M.claim.verb===wt)?.claim;if(!N)return o.push(`Most recent senderIdentity has no proof whose claim.verb === ${wt}. (E: b0f488ecccbbfe43d9a0b7c8a29d7826)`),o;if(N.target!==m)return o.push(`Most recent sender identity claim has claim.verb === ${wt} but DOES NOT target expected session identity addr ${c}. (E: 3e7f18d99848969be8586423d5ccb826)`),o;let B=await new se().validate({currentIbGib:a,prevIbGib:u});B.length>0&&o.push(`Invalid session identity transition: ${B.join(", ")} (E: da1c81c6d3c86aec3254f48fe7514226)`);let R=y({ibGib:r});return a.data?.proofs?.some(M=>M.claim.target===R)||o.push(`Session identity signature does not target current context ibgib (${R}). (E: acae68938c287178c878d1b88bebb826)`),o}catch(o){let n=`${t} ${w(o)}`;return console.error(n),[`authentication produced an error: ${n} (E: 45e014b82af81993d936611ca6fc4d26)`]}finally{ho&&console.log(`${t} complete.`)}}f(gs,"authenticateContextIntrinsically");var Be=!1,vn=class r extends rr{static{f(this,"SyncPeer_V1")}lc=`[${r.name}]`;opts;payloadIbGibsDomainReceived$;currentSessionIdentity;get currentSessionIdentityAddr(){return this.currentSessionIdentity?y({ibGib:this.currentSessionIdentity}):void 0}async signContext({contextAddr:e}){let t=`${this.lc}[${this.signContext.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:o,sagaId:n,localMetaspace:a,localSpace:s}=this.opts;if(!o)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!n)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let i=await o(),c=await $r({senderSecret:i,sagaId:n}),l=await new se().sign({latestKeystone:this.currentSessionIdentity,masterSecret:c,claim:{verb:wt,target:e},metaspace:a,space:s});return this.currentSessionIdentity=l,l}catch(o){throw console.error(`${t} ${w(o)}`),o}}async signContextConnect({challengeUuid:e,demandedIds:t}){let o=`${this.lc}[${this.signContextConnect.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!n)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!a)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let c=await n(),d=await $r({senderSecret:c,sagaId:a}),b=await new se().sign({latestKeystone:this.currentSessionIdentity,masterSecret:d,poolId:yt,requiredChallengeIds:t,claim:{verb:er,target:e},metaspace:s,space:i});return this.currentSessionIdentity=b,b}catch(n){throw console.error(`${o} ${w(n)}`),n}}get classname(){if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 1ab1841e9338b54f3aa615fa37024826)");if(!this.data.classname)throw new Error("invalid peer. this.data.classname is falsy (E: b0ee28a0abb84a06588d9de7afcef826)");return this.data.classname}constructor(e,t){super(e,t)}async initialize(){this.payloadIbGibsDomainReceived$=await Gn()}async connect(e){let t=`${this.lc}[${this.connect.name}]`;try{Be&&console.log(`${t} starting... (I: ad89d8137351662fb8a30114a1fa4826)`),await this.preConnectCheck(e),await this.connectImpl(e)}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}async establishSessionIdentity(){let e=`${this.lc}[${this.establishSessionIdentity.name}]`;try{if(Be&&console.log(`${e} starting... (I: f2a1b3c4d5e6f7a8b9c0d1e2f3a4b526)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Call initializeOpts first. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c526)");let{senderIdentity:t,fnSenderSecret:o,sagaId:n,localMetaspace:a,localSpace:s}=this.opts;if(!t||!o){Be&&console.log(`${e} no senderIdentity/fnSenderSecret \u2014 skipping establish (I: f29348a77d1542326d14043ea4b69126)`);return}let i=y({ibGib:t}),c=be({ibGib:t});if(!c)throw new Error("(UNEXPECTED) senderIdentityTjpAddr falsy? (E: d5d8c3ab25a83a2c127904fe96de1526)");if(!n)throw new Error("(UNEXPECTED) sagaId falsy? Must be set in initializeOpts before calling establishSessionIdentity. (E: c6ba389d51b8af07d82458f875cf9826)");let d=await o();if(!d)throw new Error("senderSecret falsy. senderSecret required. (E: 1a8b0298bf78cbdf284b7988983b9826)");let l=await $r({senderSecret:d,sagaId:n}),b=new se;if(!this.opts.sessionConnectPoolConfig)throw new Error("(UNEXPECTED) opts.sessionConnectPoolConfig falsy? (E: 3351fd566eb8bbd2f821bb08c4419826)");if(!this.opts.sessionSyncPoolConfig)throw new Error("(UNEXPECTED) opts.sessionSyncPoolConfig falsy? (E: dbffa810d9e7ff6079088deb5b8e7826)");let p={senderIdentityAddr:i,senderIdentityTjpAddr:c};this.opts.targetAddrs&&(p.targetAddrs=this.opts.targetAddrs);let u=await b.genesis({masterSecret:l,configs:[this.opts.sessionConnectPoolConfig,this.opts.sessionSyncPoolConfig],frameDetails:p,metaspace:a,space:s}),g=y({ibGib:u}),m=await b.sign({latestKeystone:t,masterSecret:d,claim:{verb:wt,target:g},metaspace:a,space:s});await this.postEstablishToReceiver({newSenderIdentity:m,sessionIdentity:u}),this.currentSessionIdentity=u}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Be&&console.log(`${e} complete.`)}}async initializeOpts(e){let t=`${this.lc}[${this.initializeOpts.name}]`;try{Be&&console.log(`${t} starting... (I: 31bd5fda37c89fa37fbaf14daf5fe726)`),this.opts=e}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}setOptionalOpts(e){let t=`${this.lc}[${this.setOptionalOpts.name}]`;try{if(Be&&console.log(`${t} starting... (I: ae5ddbd3577db267f84743175a736626)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0dd4d6080a6e2f31d86cf4d86e11b826)");Be&&console.log(`${t} updating opts. arg keys: ${Object.keys(e)} (I: 452d78a558f8fc3468c8e2e68c70b226)`),this.opts={...this.opts,...e}}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}async authenticateAndValidate({context:e}){let t=`${this.lc}[${this.authenticateAndValidate.name}]`;try{if(Be&&console.log(`${t} starting... (I: add238055cd84a222c5b8c89913af526)`),!this.opts)throw new Error("(UNEXPECTED) opts falsy in authenticateValidateAuthorize (E: b7e5a8ad99d84e1ba8d8f7facd288826)");let{localSpace:o}=this.opts,n=await gs({context:e,space:o});if(n.length>0)throw new Error(`invalid context authentication. authenticationErrors: ${n} (E: da89da5ee1269aeb78952d475d607526)`);let a=await ir({context:e});if(a.length>0)throw new Error(`invalid context received. validationErrors: ${a} (E: 8b34c875c968af29bc433138e57a7826)`)}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{if(Be&&console.log(`${t} starting...`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Concrete class should have initialized sender opts by now. (E: 0b9e28287318fdf8bf9f5a6886a24826)");if(!e.sagaFrame)throw new Error("context.sagaFrame falsy. (E: a33dd88aa108e2bad9e885885731ce26)");await this.authenticateAndValidate({context:e});let o=await this.sendContextRequest(e);if(o){let n=await jr({sagaIbGib:e.sagaFrame,space:this.opts.localSpace});return o}else{Be&&console.log(`${t} No response from peer. this may be normal if we just sent the very last commit frame. (I: 1855b7728c8898e1f9c001f8170ba826)`);return}}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}async getLocalIbGib(e){let t=`${this.lc}[${this.getLocalIbGib.name}]`;try{if(Be&&console.log(`${t} starting... (I: 27b248cb9801eeb2386b71485389a826)`),console.warn(`${t} possibly a bottleneck here, getLocalIbGib only gets a single ibgib... (W: 2fd448a435480e6b128f6b8bcbef4826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: cfb9431f2fb851f24a6c88e80c3b3326)");let o=await te({space:this.opts.localSpace,addr:e});if(o.success&&o.ibGibs&&o.ibGibs.length===1)return o.ibGibs[0];throw new Error(`couldn't get addr (${e}) from local space ${this.opts.localSpace}. reason: ${o.errorMsg??"unknown error (E: 926ef8bf4fcc299ab89dba34ea691a26)"} (E: d8a89807e471d3f8b938ab21df44cb26)`)}catch(o){throw console.error(`${t} ${w(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}};var ul=!1,cr={COMMON:{ALGO:Ye.sha_256,TYPE:pt.hash_reveal_v1,ROUNDS:2,REPLENISH:xe.topUp},CONNECT_POOL:{ID:yt,VERB:er,SIZE:10,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:0,SERVER_DEMAND_COUNT:3}};function On(r){let e=`[${On.name}]`;try{ul&&console.log(`${e} starting... (I: 3c791af2f978a00a087dfdde90884826)`);let t=(r.data?.challengePools??[]).find(s=>s.id===cr.CONNECT_POOL.ID);if(!t)throw new Error(`Keystone missing "${cr.CONNECT_POOL.ID}" pool (E: 6382e29260e4ddbac42ed18f49733526)`);let o=Object.keys(t.challenges).sort();if(o.length===0)throw new Error("Connect pool has no challenges (E: 1ef62fdbda182a790835c8c796475226)");let n=o[0],a=t.challenges[n];return{challengeId:n,challenge:a}}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{ul&&console.log(`${e} complete.`)}}f(On,"getConnectChallenge");var cb="auth-challenge-init",lb="auth-init",db="auth-challenge",fb="auth-proof",bb="auth-ok",pb="auth-fail",hb="sync-frame",ub="sync-frame-response",gb="sync-frame-authenticated",mb="sync-frame-response-authenticated",Eb="domain-payload",wb="sync-error",ne={auth_challenge_init:cb,auth_init:lb,auth_challenge:db,auth_proof:fb,auth_ok:bb,auth_fail:pb,sync_frame:hb,sync_frame_response:ub,sync_frame_authenticated:gb,sync_frame_response_authenticated:mb,domain_payload:Eb,sync_error:wb},Nn=Object.values(ne);function ms(r){return Nn.includes(r)}f(ms,"isSyncWebSocketMsgType");function gl(r){throw new Error(`Unhandled message type: ${r} (E: e928a3f82cd7469a98ef1bc248a3f826)`)}f(gl,"assertUnreachable");var It=!0,Y=class r extends vn{static{f(this,"SyncPeerWebSocketSender_V1")}lc=`[${r.name}]`;get classname(){return r.name}get isSocketOpen(){return this.ws!==void 0&&this.ws.readyState===WebSocket.OPEN}ws;activeResolve;activeReject;pendingPayloadsToSend=[];handshakeMessageListener;constructor(e,t){super(e,t)}async preConnectCheck(e){let t=`${this.lc}[${this.preConnectCheck.name}]`;if(!this.data?.wsUrl)throw new Error("Missing wsUrl in peer data (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c910)");if(!this.data?.httpEvolveUrl)throw new Error("Missing httpEvolveUrl in peer data (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c911)")}async postEstablishToReceiver({newSenderIdentity:e,sessionIdentity:t}){let o=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if(It&&console.log(`${o} posting evolved keystones to ${this.data.httpEvolveUrl}...`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d642e8a9af18b532c87c6f581aa53b26)");if(!this.data.httpEvolveUrl)throw new Error("(UNEXPECTED) this.data.httpEvolveUrl falsy? (E: 8589ddbb155914d85c09658881da2c26)");let n=await fetch(this.data.httpEvolveUrl,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e,relatedIbGibs:[t]})});if(!n.ok){let a=await n.json().catch(()=>({})),s=a.message||a.error||"Unknown error";throw new Error(`HTTP ${n.status} evolution post rejected. errorMsg: ${s} (E: e8a478291b88d05c68cf6b385684b826)`)}It&&console.log(`${o} evolve post accepted by server.`)}catch(n){throw console.error(`${o} establish post failed: ${w(n)}`),n}}async connectImpl(e){let t=`${this.lc}[${this.connectImpl.name}]`;try{It&&console.log(`${t} starting...`);let{senderIdentity:o,fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!o||!n||!a)throw new Error("Missing identity parameters in peer options (E: ed49b6711ac82efcdb42b8a28c5b6826)");let c=await n(),d=await $r({senderSecret:c,sagaId:a}),l=y({ibGib:o}),b=y({ibGib:(o.rel8ns?.past,o)}),p=await s.getLatestAddr({ibGib:o,space:i});if(!p)throw new Error("senderIdentityLatestAddr falsy. we should have a latest addr that is different than the sender identity at this point (done in the peer establish phase) (E: 225607318bef485d7821f82de97b6826)");let m=((await s.get({addrs:[p],space:i})).ibGibs?.[0]).data.proofs.at(0)?.claim.target;if(!m)throw new Error("Could not locate session keystone target from identity (E: 5ec4882f7e5e4c33fbd00ab8b3166726)");let S=(await s.get({addrs:[m],space:i})).ibGibs?.[0];if(!S)throw new Error(`Session keystone not found in local space: ${m} (E: 9ba818e6622808bb4ae749be31f80b26)`);let A=(S.data?.challengePools??[]).find(N=>N.id===cr.CONNECT_POOL.ID);if(!A)throw new Error("Session keystone missing connect pool (E: f50968afca04b6d38ec19824ea201826)");let{challengeId:I}=On(S),$=Ot.create({config:A.config}),T=await $.derivePoolSecret({masterSecret:d}),_=await $.generateSolution({poolSecret:T,poolId:cr.CONNECT_POOL.ID,challengeId:I}),G=`${this.data.wsUrl}?sAddr=${encodeURIComponent(m)}&solution=${encodeURIComponent(_.value)}`;It&&console.log(`${t} connecting to WebSocket: ${G}`);let v=new WebSocket(G);return this.ws=v,new Promise((N,D)=>{let B=!1;v.addEventListener("open",()=>{It&&console.log(`${t} WebSocket opened. Awaiting challenge...`)}),this.handshakeMessageListener=async R=>{try{let k=JSON.parse(R.data);It&&console.log(`${t} received handshake frame: ${k.type}`);let M=k.type;if(!ms(M)){let j=Nn.join(", ");throw new Error(`Unknown message type '${M}' received during connection handshake. Valid types are: ${j} (E: e983271bc84f46928e4695be2409826)`)}switch(M){case ne.auth_challenge_init:await this.handleHandshakeAuthChallengeInit(v,m);break;case ne.auth_challenge:await this.handleHandshakeAuthChallenge(v,k,S,d);break;case ne.auth_ok:B=!0,this.handleHandshakeAuthOk(v,N);break;case ne.auth_fail:this.handleHandshakeAuthFail(k,D);break;case ne.sync_error:this.handleHandshakeSyncError(k,D);break;case ne.auth_init:case ne.auth_proof:case ne.sync_frame:case ne.sync_frame_response:case ne.sync_frame_authenticated:case ne.sync_frame_response_authenticated:case ne.domain_payload:throw new Error(`Unexpected message type '${M}' during connection handshake (E: e3f80c68ab2a46c2b1858c8a1e2f8926)`);default:gl(M)}}catch(k){console.error(`${t} ${w(k)}`),D(k)}},v.addEventListener("message",this.handshakeMessageListener),v.addEventListener("close",R=>{B||(this.disconnect(),D(new Error(`WebSocket closed before connect completed (code: ${R.code})`)))}),v.addEventListener("error",R=>{B||(this.disconnect(),D(new Error("WebSocket connection error")))})})}catch(o){throw console.error(`${t} connect failed: ${w(o)}`),o}}disconnect(){let e=`${this.lc}[${this.disconnect.name}]`;try{if(It&&console.log(`${e} starting... (I: 35c4b85fca0c6e9d042f5ff87cde3826)`),this.ws){this.handshakeMessageListener&&(this.ws.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0);try{this.ws.close()}catch(t){console.error(`${e} failed to close websocket: ${w(t)}`)}this.ws=void 0}}catch(t){console.error(`${e} ${w(t)}`)}finally{It&&console.log(`${e} complete.`)}}async handleRuntimeMessage(e){let t=`${this.lc}[${this.handleRuntimeMessage.name}]`;try{let o=JSON.parse(e.data);It&&console.log(`${t} received runtime frame: ${o.type}`);let n=o.type;if(!ms(n)){let a=Nn.join(", ");throw new Error(`Unknown message type '${n}' received during active sync saga loop. Valid types are: ${a} (E: e23a8d10b74d47fb90518f8e3f4b826)`)}switch(n){case ne.sync_frame_response:await this.handleRuntimeSyncFrameResponse(o);break;case ne.sync_frame_authenticated:this.handleRuntimeSyncFrameAuthenticated();break;case ne.domain_payload:this.handleRuntimeDomainPayload(o);break;case ne.sync_error:this.handleRuntimeSyncError(o);break;case ne.auth_challenge_init:case ne.auth_init:case ne.auth_challenge:case ne.auth_proof:case ne.auth_ok:case ne.auth_fail:case ne.sync_frame:case ne.sync_frame_response_authenticated:throw new Error(`Unexpected message type '${n}' during active sync saga loop (E: e982b12cf92c448bbad0e84b7263c826)`);default:gl(n)}}catch(o){if(console.error(`${t} failed parsing/handling runtime frame: ${w(o)}`),this.disconnect(),this.activeReject){let n=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,n(o)}}}async handleHandshakeAuthChallengeInit(e,t){e.send(JSON.stringify({type:ne.auth_init,sAddr:t}))}async handleHandshakeAuthChallenge(e,t,o,n){let{challengeUuid:a,demandedIds:s}=t;It&&console.log(`${this.lc} solving demanded challenges: ${s.join(", ")}`);let i=await this.signContextConnect({challengeUuid:a,demandedIds:s});if(!i)throw new Error("Failed to sign connect challenge proof (E: e9807f28ae9248bbadd0a7f1a8e9826)");e.send(JSON.stringify({type:ne.auth_proof,proofFrame:i}))}handleHandshakeAuthOk(e,t){It&&console.log(`${this.lc} WebSocket connect SUCCESS!`),this.handshakeMessageListener&&(e.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0),e.addEventListener("message",o=>this.handleRuntimeMessage(o)),t()}handleHandshakeAuthFail(e,t){this.disconnect(),t(new Error(`Handshake auth failed: ${e.message||"Unknown fail reason"} (E: f380b271a2be498db257bc8209fa8926)`))}handleHandshakeSyncError(e,t){this.disconnect(),t(new Error(`Handshake sync error: ${e.message||e.error||"Unknown sync error"} (E: f9208a01fe434cbbad83f210ea8f3426)`))}async handleRuntimeSyncFrameResponse(e){let t=e.context,o=await ir({context:t});if(o.length>0)throw new Error(`Invalid response context received: ${o.join(", ")} (E: d7b5a283cf4c43ba8659c803800cf826)`);let n=[qe({ibGib:t}),t.sagaFrame,t.sagaFrameMsg];t.signedSessionIdentity&&n.push(t.signedSessionIdentity);let{localSpace:a}=this.opts;for(let i of n)await Xe({space:a,ibGibs:[i]}),await Oe({space:a,ibGib:i});if((t.data?.["@payloadAddrsDomain"]||[]).length>0&&this.ws.send(JSON.stringify({type:ne.sync_frame_response_authenticated,contextAddr:y({ibGib:t})})),this.activeResolve){let i=this.activeResolve;this.activeResolve=void 0,this.activeReject=void 0,i(t)}}handleRuntimeSyncFrameAuthenticated(){let e=this.pendingPayloadsToSend||[];this.pendingPayloadsToSend=[];for(let t of e)this.ws.send(JSON.stringify({type:ne.domain_payload,ibGib:t}))}handleRuntimeDomainPayload(e){let t=e.ibGib;this.payloadIbGibsDomainReceived$.next(t)}handleRuntimeSyncError(e){let t=e.message||e.error||"Unknown sync runtime error",o=new Error(`Sync runtime error from receiver: ${t} (E: e983bc1c828d447fa0581da2b8004f26)`);if(this.activeReject){let n=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,n(o)}else throw o}async sendContextRequest(e){let t=`${this.lc}[${this.sendContextRequest.name}]`;try{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected or open (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c915)");let o=e.payloadIbGibsDomain??[];this.pendingPayloadsToSend=[...o];let n={...e};return delete n.payloadIbGibsDomain,new Promise((a,s)=>{this.activeResolve=a,this.activeReject=s,this.ws.send(JSON.stringify({type:ne.sync_frame,context:n}))})}catch(o){throw console.error(`${t} sendContextRequest failed: ${w(o)}`),o}}};var je=!1;async function Es({timeline:r}){let e=`[${Es.name}]`;try{if(je&&console.log(`${e} starting...`),$e({ibGib:r}))return console.warn(`${e} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`),y({ibGib:r});{let t=De({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} ${w(t)}`),t}finally{je&&console.log(`${e} complete.`)}}f(Es,"getLockScope");async function lr({timeline:r,rel8nInfos:e,rel8nRemovalInfos:t,timelineIndexInfo:o,metaspace:n,space:a,skipLock:s,noDna:i}){let c=`[${lr.name}]`;try{if(je&&console.log(`${c} starting... (I: fcdff10832215068019355265f4cbc25)`),a??=await n.getLocalUserSpace({lock:!1}),!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)");let d=await Es({timeline:r}),l=f(async()=>{if(!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let p=y({ibGib:r}),u=await n.getLatestAddr({addr:p,space:a});if(!u)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${y({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let g=qe({ibGib:r});if(p!==u){let I=await n.get({addrs:[u],space:a});if(I.errorMsg||(I.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${u}) from space (${a.ib}). errorMsg: ${I.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);g=I.ibGibs.at(0)}let m;if(t&&t.length>0){m={};for(let I of t){let{rel8nName:$,ibGibAddrs:T}=I;if(T.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${$}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}m[$]||(m[$]=[]),m[$]=m[$].concat(T)}}let E={};for(let I of e){let{rel8nName:$,ibGibs:T}=I;if(T.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${$}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}E[$]||(E[$]=[]),E[$].push(...T.map(_=>y({ibGib:_})))}let S=await Ke({src:g,rel8nsToRemoveByAddr:m,rel8nsToAddByAddr:E,dna:!i,nCounter:!0}),A=S.newIbGib;return await n.persistTransformResult({resTransform:S,space:a}),o&&await ws({type:o.type,rel8nInfos:[{rel8nName:o.rel8nName,ibGibs:[A]}],metaspace:n,space:a,skipLock:s}),await n.registerNewIbGib({ibGib:A,space:a}),A},"fn");return s?await l():await Gt({scope:d,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:a,callerInstanceId:ot(),fn:l})}catch(d){throw console.error(`${c} ${w(d)}`),d}finally{je&&console.log(`${c} complete.`)}}f(lr,"appendToTimeline");async function ws({type:r,rel8nInfos:e,dataToAddOrPatch:t,metaspace:o,space:n,skipLock:a}){let s=`[${ws.name}]`;try{if(je&&console.log(`${s} 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 i=f(async()=>{let c=f(async()=>{let d=await o.getSpecialIbGib({type:r,space:n,initialize:!0});if(!d)throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${r}. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);return d.rel8ns||console.warn(`${s} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`),d},"fnGetSpecialIndex");for(let d of e??[]){let{rel8nName:l,ibGibs:b}=d;b.length===0&&console.error(`${s} ibGibs empty. skipping rel8nName (${l}). (E: 150d74f73f97aea1b97d173d92c77125)`);let u=(await c()).rel8ns??{},g,m=u[l]??[];if(m.length>0){let E=new Set;b.forEach(S=>{let A=y({ibGib:S}),I=S.rel8ns?.past??[];m.filter($=>[...I,A].includes($)).forEach($=>E.add($))}),E.size>0&&(g=Array.from(E))}await o.rel8ToSpecialIbGib({type:r,rel8nName:l,ibGibsToRel8:b,addrsToUnRel8:g,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(t??{}).length>0){let d=await c(),l=await nt({src:d,dataToAddOrPatch:t,dna:!1,linkedRel8ns:[Ee.past],nCounter:!0}),b=l.newIbGib;await Ie({resTransform:l,space:n});let p=Ne({type:r});await o.setConfigAddr({key:p,addr:y({ibGib:b}),space:n}),await o.registerNewIbGib({ibGib:b,space:n})}},"fn");a?await i():await Gt({scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:i})}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{je&&console.log(`${s} complete.`)}}f(ws,"updateSpecialIndex");async function ys({timeline:r,timelineAddr:e,metaspace:t,space:o}){let n=`[${ys.name}]`;try{if(je&&console.log(`${n} starting... (I: f2b605361368e1956f6db878dbfeb825)`),!r&&!e)throw new Error("either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)");e??=y({ibGib:r});let a=await t.getLatestAddr({addr:e,space:o})??e;if(!a)throw new Error(`${n} (UNEXPECTED) Could not get latest address for timeline ${y({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let s;if(e===a){if(!r){let i=await t.get({addrs:[a],space:o});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${o.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: 3fc767a594788a43a4ba18c87491a825)`);r=i.ibGibs.at(0)}s=qe({ibGib:r})}else{let i=await t.get({addrs:[a],space:o});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${o.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);s=i.ibGibs.at(0)}return s}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{je&&console.log(`${n} complete.`)}}f(ys,"getLatestTimelineIbGibDto_nonLocking");async function Z({timeline:r,timelineAddr:e,mut8Opts:t,metaspace:o,space:n,skipLock:a,timelineIndexInfo:s,noDna:i}){let c=`[${Z.name}]`;try{if(je&&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 p=await o.get({addrs:[e],space:n});if(!p.success||p.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${e}) in space (${n?.ib??"undefined"}) (E: genuuid)`);r=p.ibGibs.at(0)}let d=await Es({timeline:r}),l=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 p=await ys({timeline:r,metaspace:o,space:n}),u=await nt({...t,src:p,dna:!i,nCounter:!0}),g=u.newIbGib;return await o.persistTransformResult({resTransform:u,space:n}),s&&await ws({type:s.type,rel8nInfos:[{rel8nName:s.rel8nName,ibGibs:[g]}],metaspace:o,space:n,skipLock:a}),await o.registerNewIbGib({ibGib:g,space:n}),g},"fn");return a?await l():await Gt({scope:d,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:ot(),fn:l})}catch(d){throw console.error(`${c} ${w(d)}`),d}finally{je&&console.log(`${c} complete.`)}}f(Z,"mut8Timeline");async function $s({ib:r,data:e,rel8ns:t,noDna:o,parentIb:n,parentIbGib:a,metaspace:s,space:i}){let c=`[${$s.name}]`;try{if(je&&console.log(`${c} starting...`),i??=await s.getLocalUserSpace({lock:!1}),!i)throw new Error("(UNEXPECTED) space is required, but is falsy. (E: 252994a554224b17aa9816c7a765c925)");a??=n?a=F.primitive({ib:n}):a=q;let d=await F.firstGen({parentIbGib:a,ib:r,data:e,rel8ns:t,dna:!o,nCounter:!0,squash:!!o,tjp:{timestamp:!0,uuid:!e?.uuid}});return await s.persistTransformResult({resTransform:d,space:i}),await s.registerNewIbGib({ibGib:d.newIbGib,space:i}),d}catch(d){throw console.error(`${c} ${w(d)}`),d}}f($s,"createTimeline");async function ml({ibGib:r,metaspace:e,space:t}){let o=`[${ml.name}]`;try{if(je&&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 a=await e.get({addrs:n,space:t});if(!a.success||(a.ibGibs??[]).length!==n.length){let s=n.filter(i=>!a.ibGibs?.some(c=>y({ibGib:c})===i));throw new Error(`Could not get all dna ibGibs for ${y({ibGib:r})}. Addrs not found: ${s.join(", ")}. Errors: ${a.errorMsg??"[unknown error (E: 92cf95774828d8a978331da859098625)]"} (E: d2c0b1a9a8b7c6d5e4f3a2b1a0b9c8d7)`)}return a.ibGibs}catch(n){throw console.error(`${o} ${w(n)}`),n}}f(ml,"getDna");async function xn({timeline:r,getLatest:e,includeDna:t,metaspace:o,space:n}){let a=`[${xn.name}]`;try{if(je&&console.log(`${a} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: e3d1c0b1a9a8b7c6d5e4f3a2b1a0b9c8)");let s=e?await ys({timeline:r,metaspace:o,space:n}):qe({ibGib:r}),i=y({ibGib:s}),c={},d=t?zo({ibGibs:await ml({ibGib:s,metaspace:o,space:n})}):void 0,l=r.rel8ns?.past??[];if(l.length===0)return{headIbGib:s,orderedPastIbGibs:[],pastIbGibMap:c,dnaMap:d};let b=await o.get({addrs:l,space:n});if(!b.success||(b.ibGibs??[]).length!==l.length){let u=l.filter(g=>!b.ibGibs?.some(m=>y({ibGib:m})===g));throw new Error(`Could not get all dna ibGibs for ${i}. Addrs not found: ${u.join(", ")}. Errors: ${b.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=zo({ibGibs:b.ibGibs})??{};let p=[];for(let u of l){let g=c[u];if(!g)throw new Error("(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)");p.push(g)}return{headIbGib:s,orderedPastIbGibs:p,pastIbGibMap:c,dnaMap:d}}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{je&&console.log(`${a} complete.`)}}f(xn,"getHistory");async function Is({timeline:r,getLatest:e,metaspace:t,space:o}){let n=`[${Is.name}]`;try{return je&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await xn({timeline:r,getLatest:e,includeDna:!1,metaspace:t,space:o})).orderedPastIbGibs.map(i=>y({ibGib:i}))}catch(a){throw console.error(`${n} ${w(a)}`),a}finally{je&&console.log(`${n} complete.`)}}f(Is,"getHistoryAddrs");var Ln="sync_sagamsg";async function Ss({data:r}){let e=`[${Ss.name}]`;try{return[Ln,r.sagaId,r.stage].join(" ")}catch(t){throw console.error(`${e} ${w(t)}`),t}}f(Ss,"getSyncSagaMessageIb");async function _s({frameIbGib:r,space:e}){let t=`[${_s.name}]`;try{let n=(await Ga({ibGib:r,rel8nNames:[ke],space:e}))[ke];if(!n||n.length===0)throw new Error(`(UNEXPECTED) No sync message stone found found for frame: ${r.ib} (E: 8a4b2c1d3e5f6a9b7c8d9e0f1a2b3c4d)`);if(n.length>1)throw new Error(`(UNEXPECTED) Multiple sync message stones found (${n.length}) for frame: ${r.ib}. logic not currently equipped to handle multiple messages per frame. (E: 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d)`);return n[0]}catch(o){throw console.error(`${t} ${w(o)}`),o}}f(_s,"getSyncSagaMessageFromFrame");var Dn="anon_fn",El={fnHash:""};var wl=!1;function As({data:r}){let e=`[${As.name}]`;try{if(wl&&console.log(`${e} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!r?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${Dn} ${r.fnHash}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{wl&&console.log(`${e} complete.`)}}f(As,"getAnonymousFnIb");var dr=class{static{f(this,"AnonymousFnWitness_V1")}fn;ib=Dn.concat();gib=re;data=H(El);rel8ns;constructor(e){if(this.fn=e,!e)throw new Error("fn required (E: b1e1478f466a2a347b75e7c336f8d323)")}async witness(e){return this.data.fnHash=await He({s:this.fn.toString()}),this.ib=As({data:this.data}),this.gib=await ue({ibGib:this}),this.fn(e)}};var Rn=!1;function yb({err:r}){let e=`[${yb.name}]`;try{if(Rn&&console.log(`${e} starting... (I: 96f8b767c50f24768ced7beebb291723)`),oo(r)){let t=r;if(!r.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(Ht({ibGib:r}))return r.data.raw;throw new Error("(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)")}else return w(r)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Rn&&console.log(`${e} complete.`)}}f(yb,"extractObsErrMsg");function Ts(r){let e=`[${Ts.name}]`;try{Rn&&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 l=>(await t.next(l),q),"fnNext"),n=f(async l=>(l.ib==="complete"?t.complete&&await t.complete():Ht({ibGib:l})?t.error&&await t.error(l):await t.next(l),q),"fnWitness"),a=new dr(o),s=new dr(n),i={ib:"observer",witness:f(async l=>await s.witness(l),"witness"),next:f(async l=>{await a.witness(l)},"next")},c=t.error??(async l=>{let b;if(typeof l=="string")b=w(l);else if(l.ib)if(Ht({ibGib:l}))b=w(l.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 l instanceof Error?b=w(l):typeof l.message=="string"?b=w(l.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)`)}),d=new dr(async l=>(c(l),q));if(i.error=async l=>{typeof l=="string"?l=await _r({rawMsg:l}):l instanceof Error&&(l=await _r({rawMsg:l.message}));try{await d.witness(l)}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 l=t.complete,b=new dr(async p=>(await l(),q));i.complete=async()=>{try{await b.witness(q)}catch(p){console.error(`${e} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${w(p)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return i}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Rn&&console.log(`${e} complete.`)}}f(Ts,"fnObs");var Pn=!1,Gs=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}},Cs=class r extends Gs{static{f(this,"KeystoneConfigBuilder_HashV1")}lc=`[${r}]`;_algo;_rounds;withHash({algo:e,rounds:t}){let o=`${this.lc}[${this.withHash.name}]`;try{return Pn&&console.log(`${o} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=e,this._rounds=t,this}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{Pn&&console.log(`${o} complete.`)}}build(){let e=`${this.lc}[${this.build.name}]`;try{if(Pn&&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:pt.hash_reveal_v1,salt:this._salt,allowedVerbs:this._verbs,behavior:this.buildBehavior(),algo:this._algo,rounds:this._rounds}}catch(t){throw console.error(`${e} ${w(t)}`),t}finally{Pn&&console.log(`${e} complete.`)}}},uo=class{static{f(this,"KeystoneConfig")}static hash(){return new Cs}};function vs(r){if(r.type&&r.type!==pt.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${pt.hash_reveal_v1} currently implemented. (E: c38616cd7a459149f670418f88766526)`);let{salt:e,id:t,size:o,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:d,hashRounds:l}=r;return uo.hash().withId(t).withSalt(e).withSize(o??yc).withHybrid({seqCount:n??$c,randCount:a??Ic}).withTargetBinding(s??Sc).withReplenishStrategy(i??_c).withHash({algo:d??Ac,rounds:l??Tc}).forVerbs(c??[]).build()}f(vs,"createStandardPoolConfig");function $b(r){if(r.type&&r.type!==pt.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${pt.hash_reveal_v1} currently implemented. (E: 09c1f7772bd2a7910f5562b4934d3826)`);let{salt:e,id:t,size:o,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:d,hashRounds:l}=r;return uo.hash().withId(t).withSalt(e).withSize(o??Gc).withHybrid({seqCount:n??Cc,randCount:a??vc}).withTargetBinding(s??Oc).withReplenishStrategy(i??Nc).withHash({algo:d??xc,rounds:l??Lc}).forVerbs(c??[]).build()}f($b,"createHighSecurityPoolConfig");function yl(r){return $b({...r,id:r.id??wc,verbs:r.verbs??[Ha.MANAGE]})}f(yl,"createManagePoolConfig");function $l({template:r,salt:e}){let t=r.behavior;return uo.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($l,"createPoolConfigFromJson");var x=!0,kn=!0,ct="[ControlDomain]",W=class r{static{f(this,"SyncSagaCoordinator")}lc=`[${r.name}]`;constructor(){}defaultSessionConnectPoolConfig(){return vs({id:yt,salt:`session-connect-${Date.now()}`,verbs:[er],size:20,sequential:2,random:2,targetBinding:0,replenishStrategy:xe.deleteAll})}defaultSessionSyncPoolConfig(){return vs({id:wr,salt:`session-sync-${Date.now()}`,verbs:[wt],size:200,sequential:3,random:3,targetBinding:3,replenishStrategy:xe.topUp})}async sync({peer:e,domainIbGibs:t,senderIdentity:o,fnSenderSecret:n,conflictStrategy:a=X.abort,metaspace:s,localSpace:i}){let c=`${this.lc}[${this.sync.name}]`;if(x&&console.log(`${c} starting...`),!i){debugger;throw new Error(`${c} source (or localSpace) required (E: 25df3761f7686a1099a552f83c95d326)`)}if(o||n){if(!o)throw new Error("(UNEXPECTED) senderIdentity falsy but fnSenderSecret truthy? if either is used, both must be truthy. (E: e366628a4919c7d727d2cbd8e5b75e26)");if(!n)throw new Error("(UNEXPECTED) fnSenderSecret falsy but senderIdentity truthy? if either is used, both must be truthy. (E: 7d55ce37ae482fec48e3398158161926)")}let d=await U(),l=await Gn();if(!l.next)throw new Error("(UNEXPECTED) updates$.next falsy? (E: d24cd82184aec130c89a320819b39126)");let b,p,u=new Promise((S,A)=>{b=S,p=A}),g=await Wc(),m=await s.createNewLocalSpace({opts:{allowCancel:!1,spaceName:g,getFnPrompt:s.getFnPrompt,logalot:x}});if(!m)throw new Error("Failed to create temp space (E: 8f4e2f3d6c1b4b1a8f4e2f3d6c1b4b1a)");await m.initialized;let E=f(async()=>{},"cleanup");return(async()=>{try{let S=t?t.map($=>y({ibGib:$})):void 0;e.setOptionalOpts({sagaId:d,senderIdentity:o,fnSenderSecret:n,sessionConnectPoolConfig:this.defaultSessionConnectPoolConfig(),sessionSyncPoolConfig:this.defaultSessionSyncPoolConfig(),targetAddrs:S}),await e.establishSessionIdentity(),await e.connect({sagaId:d});let{initFrame:A,initDomainGraph:I}=await this.createInitFrame({sagaId:d,domainIbGibs:t,conflictStrategy:a,metaspace:s,localSpace:i,tempSpace:m,peer:e});if(await this.executeSagaLoop({initFrame:A,initDomainGraph:I,peer:e,updates$:l,localSpace:i,tempSpace:m,metaspace:s}),b(),!l.complete)throw new Error("(UNEXPECTED) updates$.complete falsy? (E: d24cd82184aec130c89a320819b39126)");l.complete()}catch(S){if(console.error(`${c} ${w(S)}`),p(S),!l.error)throw new Error("(UNEXPECTED) updates$.error falsy? (E: 392ce77c073272e4c398c3e86583ce26)");l.error(S)}finally{await E()}})(),{sagaId:d,updates$:l,done:u}}async continueSync({sagaContext:e,mySpace:t,myTempSpace:o,metaspace:n,peer:a}){let s=`${this.lc}[${this.continueSync.name}]`;try{x&&console.log(`${s} starting... (I: f64e08bf77d1425378601f380384ec26)`);let i=await this.handleResponseSagaContext({sagaContext:e,mySpace:t,myTempSpace:o,metaspace:n});if(i){if(i.nextFrameInfo?.sagaComplete)return null}else return x&&console.log(`${s} Handler returned null (Saga End). (I: 43da8bb6c846b1fe7766332643be0e26)`),null;if(i.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${i.errorMsg} (E: 7b41a183cf3cb58a5859c803800cf826)`);if(!i.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: 5740542f5eb8ccb41dfec188d87c1e26)");let{frame:c,payloadIbGibsDomain:d}=i.nextFrameInfo,l=await this.createSyncSagaContext({sagaFrame:c,localSpace:t,payloadIbGibsDomain:d,metaspace:n,sessionIdentityAddr:e.rel8ns?.sessionIdentity?.[0],peer:a,skipSign:!0}),b=await ir({context:l});if(b.length>0)throw new Error(`(UNEXPECTED) just created sync saga context () and there were immediateValidationErrors? immediateValidationErrors: ${b} (E: c120e8e0aa98673d685267a8a36e5826)`);return l}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{x&&console.log(`${s} complete.`)}}async executeSagaLoop({initFrame:e,initDomainGraph:t,peer:o,updates$:n,localSpace:a,tempSpace:s,metaspace:i}){let c=`${this.lc}[${this.executeSagaLoop.name}]`,d=e,l=[];for(;d;){let b=new Map,p=`${c}[peer.payloadIbGibsDomainReceived$]`,u=await o.payloadIbGibsDomainReceived$.subscribe(Ts({next:f(async g=>{x&&console.log(`${p} next fired. (I: 2b4bdf502a38a90ba33d9711e7cb7826)`);let m=y({ibGib:g});kn&&console.log(`${c}${ct} DOMAIN STREAM RECEIVED <- observable: ${m} (I: d69ee80fcaece272483ec33b2d289826)`),b.set(m,g)},"next"),error:f(async g=>{oo(g)?console.error(`${p} error fired. error: ${JSON.stringify(g.data)} (E: 01cc08ba05ad99682831174fd7c31a26)`):(console.dir(g),console.error(`${p} error fired. error: ${w(g)} (E: 73d3d61464e8e4ce4cd6efd8b9675826)`))},"error"),complete:f(async()=>{x&&console.log(`${p} complete fired. (I: a47218aa9e4433fdb97c068880a45826)`),await u.unsubscribe()},"complete")}));try{let g=await this.createSyncSagaContext({sagaFrame:d,payloadIbGibsDomain:l,localSpace:a,metaspace:i,sessionIdentityAddr:o.currentSessionIdentityAddr,peer:o});if(kn){let _=l.map(G=>y({ibGib:G}));console.log(`${c}${ct} SENDER TRANSMIT -> peer.witness (I: 5b0081803698770f0bf64992220b312)`),console.log(`${c}${ct} Context: ${y({ibGib:g})}`),console.log(`${c}${ct} Frame: ${y({ibGib:d})}`),console.log(`${c}${ct} DOMAIN Payloads (${_.length}): ${_.join(", ")||"(none)"}`)}n.next(g),o.setOptionalOpts({localSpace:a,localTempSpace:s});let m=await o.witness(g);if(!m)if(d)if((await _s({frameIbGib:d,space:a}))?.data?.stage===me.commit){x&&console.log(`${c} Sender sent Commit. Peer returned no response. Saga Complete. (I: 26f9ee073858ca78b8284753368b5226)`),d=null;break}else throw new Error("(UNEXPECTED) responseCtx falsy and currentFrame truthy, but we're not in the commit stage? This may be expected ultimately, but atow I am not seeing this as being expected. (E: cc34498962bd370deeff351fac939f26)");else throw new Error("(UNEXPECTED) no response and currentFrame falsy? (E: 8d1085ea2f28cfc3f9c922649864a826)");if(!m.data)throw new Error("(UNEXPECTED) responseCtx.data falsy? (E: a969992bae53ab18a827ec58aec15826)");n.next(m);let E=await ir({context:m});if(E.length>0)throw new Error(`contextAndSagaFrameValidationErrors: ${E} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`);let S=await this.validateReturnContext({requestCtx:g,responseCtx:m,localSpace:a});if(S.length>0)throw new Error(`validateReturnContext errors: ${S.join(", ")} (E: cb8a023b9d0728cceb09fa3da0bb8226)`);let A=m.data[Wa]||[];if(A.length>0&&(m.payloadIbGibsDomain=await this.pollForDomainPayloads({expectedAddrs:A,pollIntervalMs:20,domainPayloadsMap:b,tempSpace:s})),!m.sagaFrame)throw new Error("(UNEXPECTED) responseCtx.sagaFrame falsy? the Peer should have set this when it got the response back from the remote. (E: e650adadf9a2063ec6764a1e31d3d826)");if(kn){let _=m.data?.["@payloadAddrsControl"]||[];console.log(`${c}${ct} SENDER RECEIVED <- peer.witness (I: 3dc76a9744d89a4fc3e2f076c2be4826)`),console.log(`${c}${ct} Response Context: ${y({ibGib:m})}`),console.log(`${c}${ct} Response Saga Frame: ${y({ibGib:m.sagaFrame})}`),console.log(`${c}${ct} CONTROL Payloads (${_.length}): ${_.join(", ")||"(none)"}`),console.log(`${c}${ct} DOMAIN Payloads (${A.length}): ${A.join(", ")||"(none)"}`)}let I=await this.handleResponseSagaContext({sagaContext:m,initDomainGraph:t,mySpace:a,myTempSpace:s,metaspace:i});if(I){if(I.nextFrameInfo?.sagaComplete){x&&console.log(`${c} Handler returned null (Saga End). (I: 123bf9e7dca8886de72553a8d4f29e26)`);break}}else{console.error(`${c} NAG ERROR (DOES NOT THROW): does this ever hit now? (E: e04d02efc2a8e72a88b79f1f0f95ca26)`);break}if(I.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${I.errorMsg} (E: c948e81d513b2a0eb8b8afa878edc626)`);if(!I.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: c287a82e823e662a77923278e2418826)");let{frame:$,payloadIbGibsDomain:T}=I.nextFrameInfo;if(d=$,l=[...T||[]],kn){let _=l.map(G=>y({ibGib:G}));console.log(`${c}${ct} HANDLER RESULT -> next iteration (I: 6b0d88c4c28857ccd812381515bd7826)`),console.log(`${c}${ct} Next Frame: ${y({ibGib:d})}`),console.log(`${c}${ct} DOMAIN for next (${_.length}): ${_.join(", ")||"(none)"}`)}}finally{await u.unsubscribe()}}}async createSyncSagaContext({sagaFrame:e,payloadIbGibsDomain:t,metaspace:o,localSpace:n,sessionIdentityAddr:a,peer:s,skipSign:i}){let c=`[${this.createSyncSagaContext.name}]`;try{if(x&&console.log(`${c} starting... (I: 6b87bee313e811d1d2fc90e87fbec826)`),!e.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 04c49b4cccba6842a8b52e4c6f570726)");if(!e.data.n&&e.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 45b508da64a8b28428b11765d684b826)");let d=new Date,l=oe(d),b=d.getMilliseconds(),p={timestamp:l,timestampMs:b,sagaN:e.data.n},u=t?t?.map(T=>y({ibGib:T})):void 0;u&&u.length>0&&(p[Wa]=u);let g={sagaFrame:[y({ibGib:e})]},m;if(a){a=await o.getLatestAddr({addr:a,space:n})??a;let T=await te({addr:a,space:n});if(T.success&&T.ibGibs?.length===1)m=T.ibGibs[0],g.sessionIdentity=[a];else{debugger;throw new Error(`Couldn't get sessionIdentityAddr (${a}) in space: ${n.ib} (E: 5c29e80d68dbd1749866c358be093826)`)}}let E=await us({data:p}),S=await F.stone({parentPrimitiveIb:Cn,ib:E,data:p,rel8ns:g}),A=y({ibGib:S}),I;m&&!i&&(I=await s.signContext({contextAddr:A})),await Xe({ibGib:S,space:n}),await Oe({ibGib:S,space:n,fnBroadcast:void 0}),S.sagaFrame=e;let{msgStones:$}=await sn({sagaIbGib:e,localSpace:n});if($.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)");return S.sagaFrameMsg=$[0],t&&t.length>0&&(S.payloadIbGibsDomain=t),I&&(S.signedSessionIdentity=I),S}catch(d){throw console.error(`${c} ${w(d)}`),d}finally{x&&console.log(`${c} complete.`)}}async getKnowledgeMap({space:e,metaspace:t,domainIbGibs:o,tjpAddrs:n}){let a=`${this.lc}[${this.getKnowledgeMap.name}]`;try{if(x&&console.log(`${a} starting... (I: e184f8a7818666febfbbd2d841ed3826)`),!(o&&o.length>0)&&!(n&&n.length>0))throw new Error("(UNEXPECTED) domainIbGibs and tjpAddrs falsy/empty? we need one or the other (E: f674285111c8648398cd79d8c08ec826)");if(o&&o.length>0&&n&&n.length>0)throw new Error("(UNEXPECTED) both domainIbGibs and tjpAddrs truthy? only pass in one or the other. (E: f674285111c8648398cd79d8c08ec826)");let s=[];if(n)s=n;else if(o&&o.length>0){let{mapWithTjp_YesDna:c,mapWithTjp_NoDna:d}=vt({ibGibs:o}),l=[...Object.values(c),...Object.values(d)],b=bt({ibGibs:l});s=Object.keys(b)}else return console.warn(`${a} No domainIbGibs or tjpAddrs provided. Returning empty Knowledge. (W: 2b0e115e7578a83d1b26f7c726bf9426)`),{};if(s.length===0)return{};let i=await st({space:e,tjpAddrs:s});if(!i.data||!i.data.latestAddrsMap)throw new Error(`${a} Failed to get latest addrs. (E: 7d395940c0e1419165c5196c39c6c826)`);return i.data.latestAddrsMap}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async analyzeDomainIbGibs({domainIbGibs:e,space:t}){let o=`${this.lc}[${this.analyzeDomainIbGibs.name}]`;if(e.length===0)throw new Error("invalid domainIbGibs. expected at least one, but array is empty. (E: 820a719bcac5a16878a2af697113b826)");let n=await Nt({ibGibs:e,live:!0,space:t}),a=n&&Object.keys(n).length>0;x&&console.log(`${o} graph generated. nodes: ${a?Object.keys(n).length:0}`);let s=a?Object.values(n):[],{mapWithTjp_YesDna:i,mapWithTjp_NoDna:c,mapWithoutTjps:d}=vt({ibGibs:s}),l=Object.values(d),b=[...Object.values(i),...Object.values(c)],p=bt({ibGibs:b}),u=this.sortTimelinesTopologically(p);return{stones:l,timelinesMap:p,topologicallySortedTjpAddrs:u,fullGraph:n}}async createInitFrame({sagaId:e,domainIbGibs:t,conflictStrategy:o,metaspace:n,localSpace:a,tempSpace:s,peer:i}){let c=`${this.lc}[${this.createInitFrame.name}]`;try{x&&console.log(`${c} starting... (I: 551af8b411ae9be712ce3358d43ee726)`);let d=await this.analyzeDomainIbGibs({domainIbGibs:t,space:a}),{timelinesMap:l,fullGraph:b,stones:p}=d;await Xe({ibGibs:Object.values(b),space:s});let u={};Object.keys(l).forEach(S=>{let I=l[S].at(-1);u[S]=y({ibGib:I})});let g={sagaId:e,stage:me.init,knowledgeMap:u,mode:Ya.sync,stones:p.map(S=>y({ibGib:S}))};x&&(console.log(`${c} SyncStage.init: ${me.init}, SyncStage.commit: ${me.commit}`),console.log(`${c} initData.stage: ${g.stage}`));let m=await this.createSyncMsgStone({data:g,localSpace:a,metaspace:n}),E=await this.evolveSyncSagaIbGib({msgStones:[m],conflictStrategy:o,metaspace:n,localSpace:a,sessionIdentity:i.currentSessionIdentity});return x&&console.log(`${c} sagaFrame (init): ${K(E)} (I: b3d6a8be69248f18713cc3073cb08626)`),{initFrame:E,initDomainGraph:b}}catch(d){throw console.error(`${c} ${w(d)}`),d}finally{x&&console.log(`${c} complete.`)}}async validateReturnContext({requestCtx:e,responseCtx:t,localSpace:o}){let n=`${this.lc}[${this.validateReturnContext.name}]`,a=[];try{if(e.sagaFrame&&t.sagaFrame){let c=y({ibGib:e.sagaFrame}),d=y({ibGib:t.sagaFrame});await Fr({olderAddr:c,newerAddr:d,space:o})||a.push(`Response saga frame (${d}) is not a valid continuation of request saga frame (${c}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`)}else a.push("Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)");let s=e.signedSessionIdentity?y({ibGib:e.signedSessionIdentity}):e.rel8ns?.sessionIdentity?.[0],i=t.rel8ns?.sessionIdentity?.[0];s!==i&&a.push(`Session identity mismatch. Expected ${s}, got ${i}. (E: ab98716bca88d2243cc822187768226)`)}catch(s){a.push(`Error during validateReturnContext: ${w(s)} (E: da878e1239aa88ee27bdfca005c28226)`)}return a}async pollForDomainPayloads({expectedAddrs:e,pollIntervalMs:t,domainPayloadsMap:o,tempSpace:n}){let a=`${this.lc}[${this.pollForDomainPayloads.name}]`;try{x&&console.log(`${a} starting... (I: 26dce86bfca572939885798802d6e926)`);let s=[],i=[...new Set(e)],c=[...i],d=Date.now(),l=5*60*1e3;for(;c.length>0;){if(Date.now()-d>l)throw new Error(`Timeout waiting for payloads: ${c.join(", ")} (E: 46e1683c9578095261aaf798bd5e1826)`);let b=[],p=[];for(let u of c)o.has(u)?(p.push(o.get(u)),o.delete(u)):b.push(u);p.length>0&&(await Xe({space:n,ibGibs:p}),p.forEach(u=>s.push(u))),c=b,c.length>0&&await Ce(t)}if(i.length!==s.length)throw new Error("(UNEXPECTED) uniqueExpectedAddrs.length !== resultDomainPayloads.length? at this point, we expect all of the payload ibgibs to have been received. (E: 03749a7478c4b8b28bfc86951887a826)");return s}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async handleResponseSagaContext({sagaContext:e,initDomainGraph:t,mySpace:o,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleResponseSagaContext.name}]`;try{x&&console.log(`${s} starting... (I: 5deec8a1f7a6d263c88cd458ad990826)`);let i=e.sagaFrame;if(!i.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 71b938adf1d87c2527bfd4f86dfd0826)");x&&console.log(`${s} sagaIbGib: ${K(i)} (I: 1b99d87d262e9d18d8a607a80b1a0126)`);let{stage:c,messageData:d}=await this.getStageAndPayloadFromFrame({sagaFrame:i,space:o});x&&console.log(`${s} handling frame stage: ${c}`);let l;switch(c){case me.init:l=await this.handleInitFrame({sagaIbGib:i,messageData:d,metaspace:a,mySpace:o,myTempSpace:n});break;case me.ack:if(!t)throw new Error("(UNEXPECTED) initDomainGraph falsy on the sender? (E: a3d758ad954829aba88663188eafc826)");l=await this.handleAckFrame({sagaContext:e,sagaIbGib:i,initDomainGraph:t,metaspace:a,mySpace:o,myTempSpace:n});break;case me.delta:l=await this.handleDeltaFrame({sagaContext:e,sagaIbGib:i,metaspace:a,mySpace:o,myTempSpace:n});break;case me.commit:x&&console.log(`${s}[${Vr({sagaFrame:i})}] mySpace.ib: ${o.ib} (I: 5b270996d848907238d817fffa64a126)`),l=await this.handleCommitFrame({sagaIbGib:i,metaspace:a,mySpace:o,myTempSpace:n});break;default:throw new Error(`${s} (UNEXPECTED) Unknown sync stage: ${c} (E: 9c2b4c8a6d34469f8263544710183355)`)}return x&&console.log(`${s} nextFrameInfo: ${l?K(l):"undefined"} (I: a8ad281ca8e89385686d18327a105726)`),{errorMsg:void 0,nextFrameInfo:l}}catch(i){let c=`${s} ${w(i)}`;return console.error(c),{errorMsg:c}}finally{x&&console.log(`${s} complete.`)}}async handleInitFrame({sagaIbGib:e,messageData:t,mySpace:o,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleInitFrame.name}]`;try{x&&console.log(`${s} starting... (I: 9d88dcad0408c029e898a4bcf3b08426)`),x&&console.log(`${s} [TEST DEBUG] Receiver mySpace: ${o.ib}`);let i=t;if(i.stage!==me.init)throw new Error(`${s} Invalid init frame: initData.stage !== SyncStage.init (E: c91be82970e4decc58f56bf8fc1ffc26)`);if(!i||!i.knowledgeMap)throw new Error(`${s} Invalid init frame: missing knowledgeMap (E: ed02c869e028d2d06841b9c7f80f2826)`);let c=e.data.conflictStrategy||X.abort,d=[],l=[],b=[],p=i.stones||[];if(p.length>0){x&&console.log(`${s} processing stones: ${p.length}`);let G=(await te({space:o,addrs:p})).rawResultIbGib;if(!G.data)throw new Error("(UNEXPECTED) rawResultIbGib.data falsy? (E: f3c40b492adc02c3f480b998fc7a5926)");let v=G.data.addrsNotFound;v&&v.length>0&&(x&&console.log(`${s} stones missing (requesting): ${v.length}`),v.forEach(N=>{l.some(D=>D.addr===N)||l.push({addr:N})}))}let u=i.knowledgeMap;x&&console.log(`${s} senderKnowledge: ${K(u)} (I: 9f957862356dfeae183c200854e86e26)`);let g=Object.keys(u);x&&console.log(`${s} [TEST DEBUG] senderTjpAddrs: ${JSON.stringify(g)}`),x&&console.log(`${s} senderTjpAddrs: ${K(g)} (I: 86ea4c53db0dc184c8b253386c402126)`);let m={};if(g.length>0){let _=await st({space:o,tjpAddrs:g});if(!_.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: b180d813c088042b38e1e02e06a16926)");if(!_.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 16bc386dd51d0ff53a49620b1e641826)");m=_.data.latestAddrsMap,x&&console.log(`${s} [TEST DEBUG] receiverLatestAddrsMap: ${JSON.stringify(m)}`),x&&console.log(`${s} receiverLatestAddrsMap: ${K(m)} (I: 980975642cbccd8018cf0cd808d30826)`)}for(let _ of g){let G=u[_],v=m[_];if(!v){x&&console.log(`${s} [TEST DEBUG] Missing receiver timeline for TJP: ${_}. Requesting remoteAddr: ${G}`),l.push({addr:G,tjpAddr:_});continue}if(v===G){x&&console.log(`${s} [TEST DEBUG] TJP ${_}: Synced (receiverTipAddr === remoteAddr)`);continue}if(x&&console.log(`${s} [TEST DEBUG] TJP ${_}: receiverTipAddr=${v}, remoteAddr=${G} - checking for divergence...`),await Fr({olderAddr:G,newerAddr:v,space:o})){x&&console.log(`${s} [TEST DEBUG] TJP ${_}: Remote (sender) is in past - offering push`);let D=await Ur({ibGibAddr:v,live:!1,latestCommonFrameAddr:G,space:o});b.push({tjpAddr:_,addrs:Object.keys(D)})}else{let D=!1;try{D=await Fr({olderAddr:v,newerAddr:G,space:o})}catch(B){x&&console.log(`${s} expected error if we don't have remote. verbose logging error though: ${w(B)} (I: 47ea08d0b418cf4aa8a502a7bcb80826)`)}if(D)x&&console.log(`${s} [TEST DEBUG] TJP ${_}: receiver is in past - requesting delta`),l.push({addr:G,tjpAddr:_,latestAddrAlreadyHave:v});else if(x&&console.log(`${s} [TEST DEBUG] TJP ${_}: DIVERGENCE DETECTED! conflictStrategy=${c}`),c==="abort")d.push({tjpAddr:_,receiverTipAddr:v,senderTipAddr:G,receiverKnowledgeTimelineAddrs:[],reason:"divergence",terminal:!0});else if(c===X.optimisticWithLCS){let B=await te({addr:v,space:o});if(!B.success||B.ibGibs?.length!==1)throw new Error(`couldn't get local tip (${v}) from space (${o.ib}). errorMsg: ${B.errorMsg??"[unknown error (E: b3c3d823276300aa384ebdba4a8eb826)]"} (E: 83cb88a767e22bbda99c6788bec50526)`);let R=B.ibGibs[0],k=await Is({timeline:R,space:o,metaspace:a});d.push({tjpAddr:_,receiverTipAddr:v,senderTipAddr:G,receiverKnowledgeTimelineAddrs:[...k,v],reason:"divergence",terminal:!1})}else throw new Error(`${s} Unsupported conflict strategy: ${c}. Only these currently implemented: ${yr} (E: 8f12384180f8a718a983a749fe0adf26)`)}}if(d.some(_=>_.terminal))throw x&&console.warn(`${s} ABORTING Sync Saga due to terminal conflicts: ${JSON.stringify(d)}`),new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify(d)} (E: f2edbe93cc07a63b38bfc013d2213b26)`);if(!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 24203af4600fb226ae6c1afbde442826)");let A={sagaId:e.data.uuid,stage:me.ack,deltaRequestAddrInfos:l,pushOfferInfos:b};d?.length>0&&(A.conflicts=d);let I=await this.createSyncMsgStone({data:A,localSpace:o,metaspace:a});x&&console.log(`${s} ackStone created: ${K(I)} (I: 313708132dd53ff946befb7833657826)`);let $=await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[I],localSpace:o,metaspace:a}),T;if(b.length>0){let _=[];T=[];let G=b.flatMap(R=>R.addrs),v=await te({addrs:G,space:o}),N=v.rawResultIbGib?.data;if(!N)throw new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: 1a2cc8cb99a1ffa60837e45a8229b826)");let D=N.addrsNotFound??[],B=N.addrsErrored??[];if(v.ibGibs&&v.ibGibs.length===G.length)v.ibGibs.forEach(R=>{T.push(R)});else if(v.ibGibs&&v.ibGibs.length>0)if(v.ibGibs.forEach(k=>{T.push(k)}),T.length+D.length+B.length===G.length)D.forEach(k=>_.push(k)),B.forEach(k=>_.push(k));else throw D.length===0&&B.length===0?new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored both empty? (E: ef1b2cf5bab8de2298ec507abe04e826)"):new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored don't contain the addrs not found? (E: ae9e015109f8c3c3a813da584cd98826)");else console.warn(`${s} we were expecting all domainAddrs in mySpace (${o.ib}) but we couldn't get all of them. addrsNotFound: ${D??[]}. addrsErrored: ${B??[]}. Trying temp space (${n.ib}). (W: f61908e264f8dddd2e3fb9084463d826)`),G.forEach(R=>_.push(R));if(_.length>0){x&&console.log(`${s} couldn't get all addrs in mySpace (${o.ib}). searchSecondSpaceAddrs: ${_} (I: 233fd954dbd84e51bca02fa8eed5f826)`);let R=await te({addrs:_,space:n});if(R.success&&R.ibGibs&&R.ibGibs.length===_.length)R.ibGibs.forEach(k=>T.push(k));else{R.ibGibs?.forEach(M=>T.push(M));let k=G.filter(M=>!T.map(j=>y({ibGib:j})).includes(M));throw new Error(`couldn't get some or all of addrs from either mySpace (${o.ib}) or myTempSpace (${n.ib}). addrsFailed: ${k} (E: 1394d412c4ffa4dd085f269b43338826)`)}}}return{frame:$,payloadIbGibsDomain:T}}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{x&&console.log(`${s} complete.`)}}async handleAckFrame({sagaContext:e,sagaIbGib:t,initDomainGraph:o,mySpace:n,myTempSpace:a,metaspace:s}){let i=`${this.lc}[${this.handleAckFrame.name}]`;try{x&&console.log(`${i} starting... (I: 605b6860e898267a5b50c6d85704be26)`);let{messageData:c}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:n}),d=c,l=!0;if(!d)throw new Error(`${i} ackData falsy (E: 3b8415edc876084c88a25b98e2d55826)`);if(d.stage!==me.ack)throw new Error(`${i} Invalid ack frame: ackData.stage !== SyncStage.ack (E: 2e8b0a94b5954a66a6a1a7a0b3f5b7a1)`);if(x&&console.log(`${i} ackData: ${K(d)} (I: b817c5571c5e916fe8f90b892b3e8e26)`),!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: e3f2e8f162484859787651b85c011826)");let b=d.conflicts?H(d.conflicts):[];x&&console.log(`${i} [CONFLICT DEBUG] Received conflicts from Ack: ${b.length}`),x&&b.length>0&&console.log(`${i} [CONFLICT DEBUG] Conflicts detail: ${JSON.stringify(b,null,2)}`);let p=b.filter(_=>_.terminal);if(p.length>0)throw x&&console.warn(`${i} Received terminal conflicts from Ack: ${JSON.stringify(p)}`),new Error(`${i} Peer reported terminal conflicts. (E: 23a0096ee05a2ccfa89334e8f156b426)`);let u=[],g=[];if(b.length>0){x&&console.log(`${i} [CONFLICT DEBUG] Processing ${b.length} non-terminal conflicts`);for(let _ of b){let{receiverTipAddr:G,reason:v,senderTipAddr:N,terminal:D,receiverKnowledgeTimelineAddrs:B,tjpAddr:R}=_;if(D)throw new Error("(UNEXPECTED) conflict.terminal truthy? We expect this to already throw/abort the saga before this point in execution. (E: b42e982edca8b1156765de38f9e74626)");let k=o[N];if(!k)throw new Error(`(UNEXPECTED) senderTipIbGib falsy? initDomainGraph should have had the senderTipAddr (${N}) that was included in the ack frame conflicts. tjpAddr: ${R}. reason: ${v} (E: 3bd80f2054a924be98e6a7421bff4626)`);let{headIbGib:M,orderedPastIbGibs:j}=await xn({timeline:k,getLatest:!0,metaspace:s,space:n}),Q=j.map(pe=>y({ibGib:pe})),ee=y({ibGib:M});if(_.senderKnowledgeTimelineAddrs=[...Q,ee],M.gib!==k.gib&&(_.senderTipAddr=ee,!Object.keys(o).includes(ee))){let pe=await Nt({ibGibAddr:ee,live:!0,space:n}),Ve=Object.keys(pe);for(let et of Ve)o[et]||(o[et]=pe[et])}let Ae=B.findLast(pe=>Q.includes(pe));if(!Ae)throw new Error(`(UNEXPECTED) no latestCommonFrameAddr in the conflicts.receiverKnowledgeTimelineAddrs (${B.join(`
|
|
30
|
+
`)})? This would mean that it doesn't even have the tjpAddr (${R}). So what are we doing here? (E: 8931d1bdd6d8e100bf55f7c8a6924826)`);let Te=await Ur({ibGibAddr:ee,live:!0,latestCommonFrameAddr:Ae,space:n}),Ue=[];if(Object.keys(Te).forEach(pe=>{Ue.push(pe);let Ve=Te[pe];u.push(Ve)}),Ae===G)x&&console.log(`${i} [CONFLICT DEBUG] TJP ${R}: Fast-forward detected (receiver behind sender). Excluding from active conflicts and sending delta payload.`);else{if(_.accretivePayloadAddrs)throw new Error("(UNEXPECTED) conflict.accretivePayloadAddrs already truthy? This is expected to be falsy at this point in the sync. (E: 6b6b1846779867849cbde208f4374326)");_.accretivePayloadAddrs=Ue,g.push(_)}}g.length>0?l=!1:l=!0,x&&console.log(`${i} [CONFLICT DEBUG] Finished processing ${b.length} conflicts. Active (divergent) conflicts: ${g.length}. outgoingPayloadIbGibsDomain_conflicts.length (total outgoing payload ibgibs for ALL conflicts): ${u.length}`)}else x&&console.log(`${i} [CONFLICT DEBUG] No optimistic conflicts to process`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:d.deltaRequestAddrInfos||[],mySpace:n}),E=[...u,...m],S;E.length===0?E=void 0:S=E.map(_=>y({ibGib:_}));let A={sagaId:t.data.uuid,stage:me.delta,conflicts:g,payloadAddrsDomain:S,deltaRequestAddrInfos:void 0,proposeCommit:l},I;x&&console.log(`${i} Creating Delta Stone. Data stage: ${A.stage}`);let $=await this.createSyncMsgStone({data:A,rel8ns:I,localSpace:n,metaspace:s}),T=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[$],localSpace:n,metaspace:s});return x&&console.log(`${i} Delta Frame created. Rel8ns: ${JSON.stringify(T.rel8ns)}`),{frame:T,payloadIbGibsDomain:E}}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{x&&console.log(`${i} complete.`)}}async handleDeltaFrame({sagaContext:e,sagaIbGib:t,mySpace:o,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleDeltaFrame.name}]`;try{x&&console.log(`${s} starting... (I: a1d0a85eb4189466f86dfd61e3df2626)`);let{messageData:i}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:o}),c=i;if(!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 8874e83e1a1b307938ee832862ec5826)");if(!t.data.conflictStrategy)throw new Error("(UNEXPECTED) sagaIbGib.data.conflictStrategy falsy? (E: 636205ab5b78fcb31d0cb1880770c826)");if(!c)throw new Error(`${s} deltaData falsy (E: 7c28c8d8f08a4421b8344e6727271421)`);if(c.stage!==me.delta)throw new Error(`${s} Invalid delta frame: deltaData.stage !== SyncStage.delta (E: 0c28c8d8f08a4421b8344e6727271421)`);x&&console.log(`${s} deltaData: ${K(c)} (I: a76008681df458cfbcdc4848f825a826)`),x&&console.log(`${s} [CONFLICT DEBUG] deltaData.payloadAddrsDomain count: ${c.payloadAddrsDomain?.length||0}`);let{conflictStrategy:d}=t.data,{deltaRequestAddrInfos:l,payloadAddrsDomain:b,proposeCommit:p}=c,u=c.proposeCommit??!1,g=e.payloadIbGibsDomain??[];x&&console.log(`${s} [CONFLICT DEBUG] Fulfilling ${(c.deltaRequestAddrInfos||[]).length} peer requests`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:c.deltaRequestAddrInfos||[],mySpace:o});x&&console.log(`${s} [CONFLICT DEBUG] Outgoing payload size (with deps): ${m.length}`);let E=c.conflicts?H(c.conflicts):[],S=E.filter(T=>!T.resolved);if(S.length>0){if(d!==X.optimisticWithLCS)throw new Error(`(UNEXPECTED) conflictStrategy (${d}) is not ${X.optimisticWithLCS}? right now, this is the only one we've implemented. (E: ba3e08d92a66b24075016208a0f83226)`);for(let T of S){let _={};for(let he of T.accretivePayloadAddrs??[]){let tt=g.find(lt=>y({ibGib:lt})===he);if(!tt)throw new Error("(UNEXPECTED) conflictPayloadIbGib falsy? At this time in dev (01/27/2026), we're expecting this to be populated because we're only expecting one iteration of conflict resolution. If dev is later, this may no longer be the case. (E: b197417e762639089827aa3edaece826)");_[he]=tt}T.latestCommonFrameAddr;let{receiverKnowledgeTimelineAddrs:G,senderKnowledgeTimelineAddrs:v,reason:N,receiverTipAddr:D,senderTipAddr:B,tjpAddr:R}=T;if(!v)throw new Error("(UNEXPECTED) senderKnowledgeTimelineAddrs falsy? (E: 2a608892d11bd848e8f0c7a8d676d826)");let k=await Nt({ibGibAddrs:[D],live:!0,space:o}),M=Object.values(k);await dn({ibGibs:M,space:n});for(let he of G){let tt=k[he];await Oe({ibGib:tt,space:n})}let j=v.findLast(he=>G.includes(he));if(!j)throw new Error("(UNEXPECTED) latestCommonFrameAddr falsy? how we can have a conflict without a common point in history? (E: 53de0a181838b3e5bf98d0887994b826)");let Q=await Ur({ibGibAddr:T.receiverTipAddr,latestCommonFrameAddr:j,live:!0,space:o});Object.values(Q).forEach(he=>m.push(he));let ee=await Za({conflictStrategy:d,timelineAddrsA:v,timelineAddrsB:G,latestCommonFrameAddr:j,ibGibReadCache:_,space:n}),{dnasCreatedInGraft:Ae,dnasReplayed:Te,intermediateIbGibsCreatedInGraft:Ue,newGraftTip:Me,graftInfoCreated:pe}=ee;if(T.createdDnaAddrs=Ae.map(he=>y({ibGib:he})),T.replayedDnaAddrs=Te.map(he=>y({ibGib:he})),T.createdDomainAddrs=[...Ue.map(he=>y({ibGib:he})),y({ibGib:pe}),y({ibGib:Me})],!Me.rel8ns)throw new Error("(UNEXPECTED) newGraftTip.rel8ns falsy? we expect this to have graftinfo rel8ns, let alone dna (E: 718788f5a44e815618ac1ba621c8a826)");let Ve=Me.rel8ns[$t];if(!Ve||Ve.length===0)throw new Error(`(UNEXPECTED) newGraftTip.rel8ns.${$t} falsy/empty? we expect to always have graft info attached to timelines that are grafted. (E: 45abf31654c8aa517df4d0882b996826)`);T.graftInfoAddr=Ve.at(-1);let et=[Ae,Te,Ue,[pe,Me]];for(let he of et.flat())if((await ge({ibGib:he})??[]).length>0){console.dir(he);debugger;console.log(K(he))}T.accretivePayloadAddrs??=[],et.forEach(he=>he.forEach(tt=>{let lt=y({ibGib:tt});T.accretivePayloadAddrs.includes(lt)||T.accretivePayloadAddrs.push(lt),m.some(Kr=>y({ibGib:Kr})===lt)||m.push(tt)})),T.resolved=!0}}let A=[],I=m.length>0,$=A.length>0;if(I||$){let T={sagaId:c.sagaId,stage:me.delta,payloadAddrsDomain:m.map(v=>y({ibGib:v})),requests:$?A:void 0,conflicts:E},_=await this.createSyncMsgStone({data:T,localSpace:o,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:o,metaspace:a}),payloadIbGibsDomain:m}}else if(u){let T=await jr({sagaIbGib:t,space:o}),_=await ln({history:T});return _.length>0?{frame:await this.createCommitFrame({sagaIbGib:t,errors:_,metaspace:a,mySpace:o})}:(await this.executeLocalCommit({sagaHistory:T,deltaFrame:t,localTempSpace:n,localSpace:o,metaspace:a}),{frame:await this.createCommitFrame({sagaIbGib:t,errors:void 0,metaspace:a,mySpace:o})})}else{let T={sagaId:c.sagaId,stage:me.delta,proposeCommit:!0,conflicts:E},_=await this.createSyncMsgStone({data:T,localSpace:o,metaspace:a}),G=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:o,metaspace:a});if(c.proposeCommit){x&&console.log(`${s} Peer proposed commit. Accepting & Committing.`);let v={sagaId:c.sagaId,stage:me.commit,success:!0},N=await this.createSyncMsgStone({data:v,localSpace:o,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:G,msgStones:[N],localSpace:o,metaspace:a})}}return{frame:G,payloadIbGibsDomain:m}}}catch(i){throw console.error(`${s} ${w(i)}`),i}finally{x&&console.log(`${s} complete.`)}}async executeLocalCommit({deltaFrame:e,commitFrame:t,sagaHistory:o,metaspace:n,localSpace:a,localTempSpace:s}){let i=`${this.lc}[${this.executeLocalCommit.name}]`;try{if(x&&console.log(`${i} starting... (I: 6734980446b86a63c1af6e2e206de826)`),!e&&!t)throw new Error("(UNEXPECTED) !deltaFrame && !commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: 10cae319a2685a672866f5583514e326)");if(e&&t)throw new Error("(UNEXPECTED) deltaFrame && commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: b9037b1ed6d8684ac8a5d01328bad826)");let d=!!e?e:t;if(!d)throw new Error("(UNEXPECTED) !currentFrame? something wrong with my logic. (E: 4ec0ce6625cc1d677bc902c839ca1a26)");let l=Vr({sagaFrame:d});if(x&&console.log(`${i} currentFrameOrigin: ${l} (I: 3add8f8390c89743ae554bd3cc60b826)`),!d.data)throw new Error("(UNEXPECTED) currentFrame.data falsy? (E: a8be68d48668d93d992d793834823826)");let b=[],p=f(I=>{b.includes(I)||b.push(I)},"fnAddPayloadAddr"),u=o.filter(I=>{let $=Vr({sagaFrame:I.sagaIbGib});return l!==$});o.filter(I=>{let $=Vr({sagaFrame:I.sagaIbGib});return l===$}).forEach(I=>{if(!I.sagaIbGib.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 34d7f8cdee14717ce828878d98f89826)");I.msgStones.forEach($=>{if(!$.data)throw new Error("(UNEXPECTED) msgStone.data falsy? (E: 21406101f91847514cc759c8a7382f26)");if($.data.stage===me.ack){let T=$.data;T.pushOfferInfos&&T.pushOfferInfos.length>0&&T.pushOfferInfos.forEach(_=>{_.addrs.forEach(G=>p(G))})}else if($.data.stage===me.delta){let T=$.data;T.payloadAddrsDomain&&T.payloadAddrsDomain.length>0&&T.payloadAddrsDomain.forEach(_=>p(_))}})}),x&&console.log(`${i}[${l}] allPayloadAddrsDomainTransferred: ${b.length>0?b.join(", "):"none"} (I: a1950eb3ca95bdc9ec18a4b8823e9826)`);let m=[];if(b.length>0){let I=await te({addrs:b,space:s});if(I.success&&I.ibGibs&&I.ibGibs.length===b.length)m=I.ibGibs.concat();else{if(!I.rawResultIbGib)throw new Error("(UNEXPECTED) !resGetAllTransferred.rawResultIbGib falsy? (E: dc6cf8729668f4fbe8c024f887d97a26)");let{addrsNotFound:$,addrsErrored:T,errors:_}=I.rawResultIbGib.data;throw new Error(`(UNEXPECTED) we couldn't get all addrs transferred throughout the saga from the tempspace (${s.ib})? addrsNotFound: ${$??[]}. addrsErrored: ${T??[]}. errors: ${_??[]}(E: 222e341e634862b4d88ae7282584d826)`)}}let E=[],S=await fn({sagaHistory:o});if(S)for(let I of S){if(!I.resolved)throw new Error("(UNEXPECTED) finalConflict.resolved falsy? right now, we're expecting to resolve all conflicts. (E: a40ca8f1f54665407892ec21123a4f26)");if(!I.graftInfoAddr)throw new Error("(UNEXPECTED) finalConflict resolved but graftInfoAddr falsy? we're expecting all resolved conflicts to have a graftInfoAddr (E: d082488347570947b82008a835200126)");if(!(await it({addrs:[I.graftInfoAddr],space:s})).at(0))throw new Error(`(UNEXPECTED) couldn't get finalConflictGraftInfo from localTempSpace (${s})? (E: 35e3c8130608d991e8fb295807812826)`);let{createdDnaAddrs:_,replayedDnaAddrs:G,createdDomainAddrs:v}=I;if(!_||_.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDnaAddrs falsy/empty? (E: 9689f8be5bd19650b8d4a058b65db826)");if(!G||G.length===0)throw new Error("(UNEXPECTED) finalConflict.replayedDnaAddrs falsy/empty? (E: f42878ed1cee3e9828567c5ab8179526)");if(!v||v.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDomainAddrs falsy/empty? (E: cc41251d1acfe91a48d1b6080259ed26)");(await it({addrs:[..._,...G,...v],space:s})).forEach(D=>E.push(D))}let A=[];if(m.forEach(I=>A.push(I)),E.forEach(I=>A.push(I)),A.length===0)x&&console.log(`${i}[${l}] no changes on this end (I: fa30d18e83a87ee9e8487fbb5d632b26)`);else{x&&console.log(`${i}[${l}] ${A.length} changes detected (I: fa30d18e83a87ee9e8487fbb5d632b26)`),x&&console.log(`${i} put all into localSpace (${a.ib}) starting... (I: d5e0d9870e380b61e80c729660058826)`);let{payload_Dnas:I,payload_NonDnas:$}=await dn({ibGibs:A,space:a});x&&console.log(`${i} put all into localSpace (${a.ib}) complete. (I: d5e0d9870e380b61e80c729660058826)`);let T=await ts({sagaHistory:o,myTempSpace:s}),{mapWithTjp_NoDna:_,mapWithTjp_YesDna:G,mapWithoutTjps:v}=vt({ibGibs:$,filterPrimitives:!0});x&&console.log(`${i} register mapWithoutTjps starting... (I: 2b84d8f8dda85adde88696d8419bf726)`);let N=Object.values(v);for(let M of N)x&&console.log(`${i} registering ${y({ibGib:M})} (I: 4647b4f42d27cffe0fbfce8846755826)`),await n.registerNewIbGib({ibGib:M,space:a});x&&console.log(`${i} mapWithoutTjps complete. (I: 2b84d8f8dda85adde88696d8419bf726)`),x&&console.log(`${i} register mapWithTjp_NoDna starting... (I: 96e648e4db382499b8bfaa1b37c24826)`);let D=bt({ibGibs:Object.values(_)}),B=Object.keys(D);for(let M of B){let j=D[M];for(let Q of j)await n.registerNewIbGib({ibGib:Q,space:a})}x&&console.log(`${i} register mapWithTjp_NoDna complete. (I: 96e648e4db382499b8bfaa1b37c24826)`),x&&console.log(`${i} register mapWithTjp_YesDna starting... (I: d54a820e9442dee4681f6228a6795926)`);let R=bt({ibGibs:Object.values(G)}),k=Object.keys(R);for(let M of k){let j=R[M];for(let Q of j)T.includes(y({ibGib:Q}))||await n.registerNewIbGib({ibGib:Q,space:a})}x&&console.log(`${i} register mapWithTjp_YesDna complete. (I: d54a820e9442dee4681f6228a6795926)`)}}catch(c){throw console.error(`${i} ${w(c)}`),c}finally{x&&console.log(`${i} complete.`)}}async createCommitFrame({sagaIbGib:e,errors:t,metaspace:o,mySpace:n}){let a=`[${this.createCommitFrame.name}]`;try{x&&console.log(`${a} starting... (I: 48fc57c023f80122135a284855757526)`);let s=t&&t.length>0?{sagaId:e.data.uuid,stage:me.commit,success:!1,errors:t}:{sagaId:e.data.uuid,stage:me.commit,success:!0},i=await this.createSyncMsgStone({data:s,localSpace:n,metaspace:o});return await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[i],localSpace:n,metaspace:o})}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async handleCommitFrame({sagaIbGib:e,mySpace:t,myTempSpace:o,metaspace:n}){let a=`${this.lc}[${this.handleCommitFrame.name}]`;try{if(x&&console.log(`${a} starting... (I: e179573bdd881202f8ba3168da1c3826)`),!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: cbc31dbb7d28b5b8c8cddb510d7d2826)");if(e.data.errors&&e.data.errors.length>0)throw new Error("not implemented...saga errored out on other end but we've already committed our changes. we need to implement undoing our changes, i.e., rollback commit, which basically is deleting all the payloads that we already put in in our previous commit. (E: e8eb789e0c08f0b3cf93607cb73e9f26)");{let s=await jr({sagaIbGib:e,space:t}),i=await ln({history:s});return i.length>0?{frame:await this.createCommitFrame({sagaIbGib:e,metaspace:n,mySpace:t,errors:i})}:(await this.executeLocalCommit({commitFrame:e,sagaHistory:s,localSpace:t,localTempSpace:o,metaspace:n}),console.error(`${a} NAG ERROR (NOT THROWN): implement cleanup logic, including add a cleanup method to the peer (E: 3a9a24befb98a981a88fbdbf52920e26)`),x&&console.log(`${a} Peer committed. Finalizing saga locally. Saga Complete.`),{sagaComplete:!0})}}catch(s){let i=`${a} ${w(s)}`;return console.error(i),{frame:await this.createCommitFrame({sagaIbGib:e,errors:[i],metaspace:n,mySpace:t})}}finally{x&&console.log(`${a} complete.`)}}async createSyncMsgStone({data:e,rel8ns:t,localSpace:o,metaspace:n}){let a=`${this.lc}[${this.createSyncMsgStone.name}]`;try{x&&console.log(`${a} starting... (I: 5f7f98e8ff980364f7191fcee4531e26)`);let s=await Ss({data:e}),i=await F.stone({ib:s,parentPrimitiveIb:Ln,data:e,rel8ns:t,uuid:!0});return x&&console.log(`${a} Created stone: ${y({ibGib:i})}`),await n.put({ibGib:i,space:o}),await n.registerNewIbGib({ibGib:i}),i}catch(s){throw console.error(`${a} ${w(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async getPayloadsForRequestedInfos({deltaRequestAddrInfos:e,mySpace:t}){let o=`${this.lc}[${this.getPayloadsForRequestedInfos.name}]`;try{x&&console.log(`${o} starting... (I: 4fe13d0d80050f20a8b74ba80cee5826)`);let n={};for(let{addr:s,latestAddrAlreadyHave:i}of e){let c;if(i?c=await Ur({ibGibAddr:s,latestCommonFrameAddr:i,space:t,live:!0}):c=await Nt({ibGibAddr:s,space:t,live:!0}),Object.keys(c).length===0)throw new Error(`(UNEXPECTED) couldn't get requested addrs in mySpace (${t.ib})? How did the receiver know to ask for these addrs if they weren't in our original graph? (E: 281eaebcdf77dd73e8245b2872100826)`);Object.values(c).forEach(l=>{n[y({ibGib:l})]=l})}return Object.values(n)}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{x&&console.log(`${o} complete.`)}}async evolveSyncSagaIbGib({prevSagaIbGib:e,conflictStrategy:t,msgStones:o,localSpace:n,metaspace:a,sessionIdentity:s}){let i=`${this.lc}[${this.evolveSyncSagaIbGib.name}]`;try{if(!o||o.length===0)throw new Error(`${i} msgStones required (E: d13f8afcfb8816aeb26baae7df3ef726)`);let c=o[0].data;if(!c?.sagaId||!c?.stage)throw new Error(`${i} Invalid stone data (missing sagaId or stage) (E: c004f85ce8f8958b11839f8d68c38826)`);let d=c.sagaId,l=c.stage;for(let b of o){let p=b.data;if(p.sagaId!==d)throw new Error(`${i} Mismatched sagaId in stones. Expected ${d}, got ${p.sagaId} (E: 29e02719e426ecbbf8ee66887a2be226)`);if(p.stage!==l)throw new Error(`${i} Mismatched stage in stones. Expected ${l}, got ${p.stage} (E: d12c6571b0882f762921b60880c3f826)`)}if(e){let b=[{rel8nName:ke,ibGibs:o}];if(!e.rel8ns)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns falsy? (E: 81375841aff85b1e48ea42ca218e6826)");if(!e.rel8ns[ke]||e.rel8ns[ke].length===0)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] falsy/empty? (E: 15156baad26fcccda80aa3a31718c726)");let p=[{rel8nName:ke,ibGibAddrs:e.rel8ns[ke]}];return await lr({timeline:e,rel8nInfos:b,rel8nRemovalInfos:p,metaspace:a,space:n,noDna:!0})}else{let b={uuid:d,n:0,isTjp:!0,conflictStrategy:t};if(s){let E=be({ibGib:s});if(!E)throw new Error("(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)");b.sessionIdentityTjpAddr=E}let p=await es({data:b}),u=o.map(E=>y({ibGib:E})),g={[ke]:u},m=await $s({space:n,metaspace:a,ib:p,data:b,rel8ns:g,parentIb:rn,noDna:!0});if(m.intermediateIbGibs)throw new Error("(UNEXPECTED) resNew.intermediateIbGibs? we were assuming we were creating a single frame. (E: 456818147235d991ccb4d10d0bbe4826)");return m.newIbGib}}catch(c){throw console.error(`${i} ${w(c)}`),c}}async getStageAndPayloadFromFrame({sagaFrame:e,space:t}){let o=`${this.lc}[${this.getStageAndPayloadFromFrame.name}]`;try{if(x&&console.log(`${o} starting... (I: fddc287bd4d55253dc50e519fd352226)`),!e.rel8ns)throw new Error("(UNEXPECTED) sagaFrame.rel8ns falsy? (E: 725bc8eb5dfe5c7058907ad8e3063826)");let n=e.rel8ns?.[ke];if(n&&n.length>0){let a=n[0],s=await te({addr:a,space:t});if(s.ibGibs&&s.ibGibs.length>0){let i=s.ibGibs[0];if(!i.data)throw new Error("(UNEXPECTED) message stone.data falsy? (E: 4d4abcea90d87ba1328434e83d0d0826)");if(!i.data.stage)throw new Error("(UNEXPECTED) message stone.data.stage falsy? (E: 72c8d22310996644ecdd2b5fdb288c26)");return{stage:i.data.stage,messageData:i.data}}else throw new Error(`couldn't get stoneAddr (${a}) from space (${t.ib}) (E: f3c826e756f8a5c358beb88aa4a65e26)`)}else throw new Error(`(UNEXPECTED) no stone addrs rel8d to sync saga ibgib frame? sagaFrame addr: ${y(e)} (E: 43eae8579e289d016741b5526052f226)`)}catch(n){throw console.error(`${o} ${w(n)}`),n}finally{x&&console.log(`${o} complete.`)}}sortTimelinesTopologically(e){let t=`${this.lc}[${this.sortTimelinesTopologically.name}]`,o=Object.keys(e);if(o.length===0)return[];let n={};o.forEach(l=>{e[l].forEach(b=>{let p=y({ibGib:b});n[p]=l})});let a={};o.forEach(l=>a[l]=new Set),o.forEach(l=>{e[l].forEach(b=>{b.rel8ns&&Object.values(b.rel8ns).flat().forEach(p=>{if(!p)return;let u=n[p];u&&u!==l&&a[l].add(u)})})});let s=new Set,i=new Set,c=[],d=f(l=>{if(i.has(l)){console.warn(`${t} Cycle detected involving ${l}. Ignoring edge to break cycle. (W: 7e7352347102431aa5318db962459929)`);return}s.has(l)||(i.add(l),a[l].forEach(b=>d(b)),s.add(l),i.delete(l),c.push(l))},"visit");return o.forEach(l=>{s.has(l)||d(l)}),c}};var Il={$schema:"../../../../libs/core-gib/dist/keystone/policy/schemas/keystone.medium.schema.json",metadata:{name:"Space-Gib Default Identity Policy",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:200,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:5}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:20,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:3}}}};var Sb=Il.pools;function de(r,e){let t=Sb[r];if(!t)throw new Error(`Pool template not found in space-gib JSON config: ${r}`);return $l({template:t,salt:e})}f(de,"getSpaceGibPoolConfig");var L={COMMON:cr.COMMON,DEFAULT_POOL:{ID:"default",SIZE:20,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:3},CONNECT_POOL:cr.CONNECT_POOL},U4={MIN_DEFAULT_POOL_SIZE:50,ALLOWED_ALGORITHMS:[Ye.sha_256,Ye.sha_512]};var Os=no,J=class{static{f(this,"SpaceGibApiBridge")}lc="[SpaceGibApiBridge]";async postGenesisKeystone(e){let t=`${this.lc}[${this.postGenesisKeystone.name}]`;try{Os&&console.log(`${t} starting... (I: eecd082fc4a4381c8857928e8b090826)`);let o=await fetch("/api/keystone/genesis",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e})}),n=await o.json();if(!o.ok){let a=n.message||n.error||"Unknown error";return console.error(`${t} [NAG][ibgib-paradigm] server rejected genesis keystone: ${a}`),{success:!1,message:a,addr:n.addr}}return Os&&console.log(`${t} genesis keystone posted successfully.`),{success:!0,addr:n.addr}}catch(o){let n=w(o);return console.error(`${t} error: ${n}`),{success:!1,message:n}}finally{Os&&console.log(`${t} complete.`)}}async putEvolveKeystone(e,t,o=[]){let n=`${this.lc}[${this.putEvolveKeystone.name}]`;try{console.log(`${n} posting evolved keystone...`);let a=`/api/keystone/evolve/${encodeURIComponent(e)}`,s=await fetch(a,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t,relatedIbGibs:o})}),i=await s.json();if(!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected keystone evolution: ${c}`),{success:!1,message:c}}return console.log(`${n} keystone evolution accepted by server.`),{success:!0}}catch(a){let s=w(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async getKeystoneGraph(e){let t=`${this.lc}[${this.getKeystoneGraph.name}]`;try{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"}}),a=await n.json();if(console.log(`${t} fetch keystone graph complete.`),!n.ok){let s=a.message||a.error||"Unknown error";return console.error(`${t} server rejected keystone graph get: ${s}`),{success:!1,message:s}}return{success:!0,graph:a.domainGraph}}catch(o){let n=w(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{console.log(`${n} fetching single ibGib frame...`);let a=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=false`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(console.log(`${n} fetching single ibGib frame complete.`),!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected ibGib get: ${c}`),{success:!1,message:c}}return{success:!0,ibGib:i}}catch(a){let s=w(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async getIbGibGraph(e,t,o=!1){let n=`${this.lc}[${this.getIbGibGraph.name}]`;try{console.log(`${n} fetching ibGib graph...`);let a=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=true`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(console.log(`${n} fetching ibGib graph complete.`),!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected ibGib graph get: ${c}`),{success:!1,message:c}}return{success:!0,graph:i.graph,addr:i.addr}}catch(a){let s=w(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}},H4=new J;var fe="[dev-tools]",O={};window.ibgibDebugState=O;function h(r){let e=document.getElementById("dev-panel-log");if(!e)return;let t=new Date().toISOString().slice(11,23);e.textContent=`[${t}] ${r}
|
|
31
|
+
`+e.textContent}f(h,"devLog");async function Lt(r){let e=`${fe}[performPhaseSetup(${r.phaseText})]`,t=document.getElementById(r.btnId);if(t)try{t.disabled=!0,h(`${r.phaseText} Setup: Generating Alice's long-lived Domain Keystone (I) and Target (X)...`);let o=await V(),n=await o.getLocalUserSpace({});if(!n)throw new Error("No default space found in metaspace.");let s=await new se().genesis({masterSecret:r.masterSecret,configs:[de("sync",r.syncSalt),de("manage",r.manageSalt)],metaspace:o,space:n,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=s,O.domainIMasterSecret=r.masterSecret,h(`${r.phaseText} Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:s})}`),h(`${r.phaseText} Setup: Starting postGenesisKeystone...`);let c=await new J().postGenesisKeystone(s);if(c.success)h(`${r.phaseText} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw h(`${r.phaseText} Setup: X postGenesisKeystone failed: ${c.message}.`),new Error(`${r.phaseText} Setup: Server rejected genesis domain keystone: ${c.message}`);let d=await F.firstGen({parentIbGib:q,ib:r.ib,data:r.data,dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),l=d.newIbGib;await o.persistTransformResult({resTransform:d,space:n}),await o.registerNewIbGib({ibGib:l}),O.targetX=l,h(`${r.phaseText} Setup: \u2713 Target (X) created and persisted locally: ${y({ibGib:l})}`),h(`\u2713 ${r.phaseText} Setup Complete! Ready for ${r.phaseText} Sync.`),t.textContent=`\u2713 ${r.phaseText} Setup Complete`;let b=document.getElementById(r.nextBtnId);b&&(b.disabled=!1)}catch(o){h(`\u2717 ${r.phaseText} Setup FAILED: ${w(o)}`),console.error(`${e} ${r.phaseText} Setup error:`,o),t.disabled=!1}}f(Lt,"performPhaseSetup");async function fr(r){let e=`${fe}[performPhaseSync(${r.phaseText})]`,t=document.getElementById(r.btnId);if(t)try{t.disabled=!0,h(`${r.phaseText} Sync: Executing senderCoordinator.sync(...) using WebSocket Peer...`);let o=O.domainI,n=O.targetX;if(!o||!n){h(`\u26A0 ${r.phaseText} Sync: Missing setup state. Please run Setup first.`),t.disabled=!1;return}let a=y({ibGib:o}),s=await V(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(a)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(a)}`}),l=new W,b=await U();O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:o,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[a]});try{await(await l.sync({domainIbGibs:[n],senderIdentity:o,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done}catch(u){if(r.expectSyncFailure)h(`${r.phaseText} Sync: Coordinator sync executed (${r.failureMessageSuffix??"errors expected"}): ${w(u)}`);else throw u}h(`\u2713 ${r.phaseText} Sync Execution Complete! Ready for State Checks.`),t.textContent=`\u2713 ${r.phaseText} Sync Run`;let p=document.getElementById(r.nextBtnId);p&&(p.disabled=!1)}catch(o){h(`\u2717 ${r.phaseText} Sync FAILED: ${w(o)}`),console.error(`${e} ${r.phaseText} Sync error:`,o),t.disabled=!1}}f(fr,"performPhaseSync");var Kt=null;function Sl(){let r=`${fe}[initWsTestButton]`,e=document.getElementById("btn-test-ws");if(!e){console.warn(`${r} btn-test-ws not found \u2014 skipping`);return}e.addEventListener("click",()=>{try{if(Kt&&Kt.readyState===WebSocket.OPEN){Kt.send(JSON.stringify({ping:"hello from client",ts:Date.now()})),h("\u2192 sent ping on existing connection");return}let o=`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/debug/ws-echo`;h(`\u2192 connecting to ${o}`),Kt=new WebSocket(o),Kt.addEventListener("open",()=>{h("\u2713 WebSocket connected"),e.textContent="Send WS Ping"}),Kt.addEventListener("message",n=>{h(`\u2190 ${n.data}`)}),Kt.addEventListener("close",n=>{h(`\u2717 WebSocket closed (code ${n.code})`),e.textContent="Test WebSocket",Kt=null}),Kt.addEventListener("error",n=>{h("\u2717 WebSocket error \u2014 check console"),console.error(`${r} WebSocket error`,n)})}catch(t){h(`\u2717 ${w(t)}`),console.error(`${r} ${w(t)}`)}})}f(Sl,"initWsTestButton");function _l(){let r=document.getElementById("btn-print-dev-state");r&&r.addEventListener("click",()=>{h("Printing debug state to console..."),console.dir(O)})}f(_l,"initPrintStateButton");function Al(){let r=`${fe}[initCreateDomainKeystoneButton]`,e=document.getElementById("btn-create-domain-keystone");e&&e.addEventListener("click",async()=>{try{e.disabled=!0,h("Generating dummy Domain Keystone (I)...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space found in metaspace.");let n="password",s=await new se().genesis({masterSecret:n,configs:[yl({id:"default",salt:await U(),replenishStrategy:xe.topUp})],metaspace:t,space:o,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}}),i=y({ibGib:s});h(`\u2713 Local genesis complete: ${i}`),O.domainI=s,O.domainIMasterSecret=n,h("Posting genesis keystone to server...");let d=await new J().postGenesisKeystone(s);if(!d.success){h(`\u2717 Server rejected genesis keystone: ${d.message}`),e.disabled=!1;return}h("\u2713 Server accepted Domain Keystone (I)"),e.textContent="\u2713 Domain Keystone Created";let l=document.getElementById("btn-create-test-ibgib");l&&(l.disabled=!1)}catch(t){h(`\u2717 ${w(t)}`),console.error(`${r} ${w(t)}`),e.disabled=!1}})}f(Al,"initCreateDomainKeystoneButton");function Tl(){let r=`${fe}[initCreateTestIbGibButton]`,e=document.getElementById("btn-create-test-ibgib");if(!e){console.warn(`${r} btn-create-test-ibgib not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{h("Generating dummy X^Xtjp ibgib...");let o=(await F.firstGen({parentIbGib:q,ib:"test data",data:{hello:"world",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}})).newIbGib,n=y({ibGib:o});O.targetX=o,h(`\u2713 Created X: ${n}`),e.textContent="\u2713 Test IbGib (X) Created";let a=document.getElementById("btn-create-session-keystone");a&&(a.disabled=!1)}catch(t){h(`\u2717 ${w(t)}`),console.error(`${r} ${w(t)}`)}})}f(Tl,"initCreateTestIbGibButton");function Gl(){let r=`${fe}[initCreateSessionKeystoneButton]`,e=document.getElementById("btn-create-session-keystone");if(!e){console.warn(`${r} btn-create-session-keystone not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{h("Generating Session Keystone (S^Stjp)...");let t=O.domainI,o=O.targetX;if(!t){h("\u26A0 No domain keystone (I) found in state. Please Create Domain Keystone first.");return}if(!o){h("\u26A0 No target ibgib (X) found in state. Please Create Test IbGib first.");return}let n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let s="ephemeral-"+Math.random().toString(),i=new se;console.warn(`${fe}[NAG] placeholder genesis keystone config right now (W: 69b108687cf8bec0f9a8e148bcca8d26)`);let c=await i.genesis({masterSecret:s,configs:[{id:L.DEFAULT_POOL.ID,salt:await U(),type:L.COMMON.TYPE,algo:L.COMMON.ALGO,rounds:L.COMMON.ROUNDS,behavior:{size:L.DEFAULT_POOL.SIZE,replenish:L.COMMON.REPLENISH,selectSequentially:L.DEFAULT_POOL.SELECT_SEQUENTIALLY,selectRandomly:L.DEFAULT_POOL.SELECT_RANDOMLY,targetBindingCount:L.DEFAULT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[]},{id:L.CONNECT_POOL.ID,salt:await U(),type:L.COMMON.TYPE,algo:L.COMMON.ALGO,rounds:L.COMMON.ROUNDS,behavior:{size:L.CONNECT_POOL.SIZE,replenish:L.COMMON.REPLENISH,selectSequentially:L.CONNECT_POOL.SELECT_SEQUENTIALLY,selectRandomly:L.CONNECT_POOL.SELECT_RANDOMLY,targetBindingCount:L.CONNECT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[L.CONNECT_POOL.VERB]}],metaspace:n,space:a,frameDetails:{client:"space-gib-web-session",target_I:t?y({ibGib:t}):void 0,target_X:o?y({ibGib:o}):void 0}}),d=y({ibGib:c});O.sessionS=c,O.sessionSecret=s,h(`\u2713 Created Session Keystone: ${d}`),e.textContent="\u2713 Session Keystone Created"}catch(t){h(`\u2717 ${w(t)}`),console.error(`${r} ${w(t)}`)}})}f(Gl,"initCreateSessionKeystoneButton");function Cl(){let r=document.getElementById("btn-1b-setup");r&&r.addEventListener("click",()=>{Lt({phaseText:"1B",btnId:"btn-1b-setup",nextBtnId:"btn-1b-sync",masterSecret:"test-sender-secret-phase1",syncSalt:"senderidentitysyncsaltphase1",manageSalt:"senderidentitymanagesaltphase1",ib:"test data",data:{hello:"world",random:Math.random()}})})}f(Cl,"init1bSetupButton");function vl(){let r=document.getElementById("btn-1b-sync");r&&r.addEventListener("click",()=>{fr({phaseText:"1B",btnId:"btn-1b-sync",nextBtnId:"btn-1b-check",expectSyncFailure:!0,failureMessageSuffix:"establish phase successfully run; connection/sync errors expected in 1B"})})}f(vl,"init1bSyncButton");function Ol(){let r=`${fe}[init1bCheckButton]`,e=document.getElementById("btn-1b-check");e&&e.addEventListener("click",async()=>{try{h("1B Check: Asserting cryptographic and durable state expectations from respec...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetX,s=await t.getLatestAddr({addr:y({ibGib:n}),space:o});if(!s){h("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}h("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await t.get({addrs:[s],space:o})).ibGibs?.[0];if(!c){h("\u2717 Check: Failed to load I1 from local space.");return}let d=c.data?.proofs?.find(G=>G.claim?.verb==="sync");d?h("\u2713 Check: I1 contains valid sync-verb claim proof."):h("\u2717 Check: I1 is missing sync-verb claim proof!");let l=d?.claim?.target;if(!l){h("\u2717 Check: I1 sync claim does not target a session keystone.");return}h(`\u2713 Check: Sync claim targets session keystone: ${l}`);let p=(await t.get({addrs:[l],space:o})).ibGibs?.[0];if(!p){h("\u2717 Check: Session Keystone (S) NOT found in local space.");return}h("\u2713 Check: Session Keystone (S) successfully created locally.");let u=p.data?.challengePools??[],g=u.some(G=>G.id===yt),m=u.some(G=>G.id===wr);g&&m?h("\u2713 Check: S contains both connect and sync challenge pools."):h(`\u2717 Check: S is missing challenge pools! (connect: ${g}, sync: ${m})`),h("Check: Verifying registrations on server (receiver metaspace)...");let E=new J,S=!1,A=!1,I=!1,$=y({ibGib:n}),T=await E.getKeystoneGraph($);if(T.success&&T.graph){let G=T.graph;S=G[$]!==void 0,A=G[s]!==void 0}else h(`\u2717 Check Server: Failed to fetch keystone graph from server: ${T.message}`);let _=await E.getIbGib($,l);if(_.success&&_.ibGib?I=!0:h(`\u2717 Check Server: Failed to fetch session keystone from server: ${_.message}`),S?h("\u2713 Check Server: Genesis Domain Keystone (I) registered on server."):h("\u2717 Check Server: Genesis Domain Keystone (I) missing on server!"),A?h("\u2713 Check Server: Evolved Domain Keystone (I1) accepted and stored on server."):h("\u2717 Check Server: Evolved Domain Keystone (I1) missing on server!"),I?h("\u2713 Check Server: Session Keystone (S) accepted and stored on server."):h("\u2717 Check Server: Session Keystone (S) missing on server!"),S&&A&&I){h("\u{1F389} ALL PHASE 1B ESTABLISH CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 1B All Passed";let G=document.getElementById("btn-2b-setup");G&&(G.disabled=!1)}}catch(t){h(`\u2717 1B Check FAILED: ${w(t)}`),console.error(`${r} 1B Check error:`,t)}})}f(Ol,"init1bCheckButton");function Nl(){let r=document.getElementById("btn-2b-setup");r&&r.addEventListener("click",()=>{Lt({phaseText:"2B",btnId:"btn-2b-setup",nextBtnId:"btn-2b-sync",masterSecret:"test-sender-secret-phase2",syncSalt:"senderidentitysyncsaltphase2",manageSalt:"senderidentitymanagesaltphase2",ib:"test data",data:{hello:"world2",random:Math.random()}})})}f(Nl,"init2bSetupButton");function xl(){let r=document.getElementById("btn-2b-sync");r&&r.addEventListener("click",()=>{fr({phaseText:"2B",btnId:"btn-2b-sync",nextBtnId:"btn-2b-check",expectSyncFailure:!0,failureMessageSuffix:"connect phase successfully run; subsequent sync errors expected in 2B"})})}f(xl,"init2bSyncButton");function Ll(){let r=`${fe}[init2bCheckButton]`,e=document.getElementById("btn-2b-check");e&&e.addEventListener("click",async()=>{try{h("2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=y({ibGib:n}),s=await t.getLatestAddr({addr:a,space:o});if(!s){h("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}h("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await t.get({addrs:[s],space:o})).ibGibs?.[0];if(!c){h("\u2717 Check: Failed to load I1 from local space.");return}let l=c.data?.proofs?.find(I=>I.claim?.verb==="sync")?.claim?.target;if(!l){h("\u2717 Check: I1 sync claim does not target a session keystone.");return}h(`\u2713 Check: Sync claim targets session keystone: ${l}`);let b=await t.getLatestAddr({addr:l,space:o});if(!b){h("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}h("\u2713 Check: Found latest session keystone (S) locally.");let u=(await t.get({addrs:[b],space:o})).ibGibs?.[0];if(!u){h("\u2717 Check: Failed to load latest Session Keystone (S).");return}let g=u.data?.challengePools??[],m=g.find(I=>I.id===yt),E=g.find(I=>I.id===wr);if(m&&E)h("\u2713 Check: S contains both connect and sync challenge pools.");else{h(`\u2717 Check: S is missing challenge pools! (connect: ${!!m}, sync: ${!!E})`);return}let S=Object.keys(m.challenges).length;if(S===0)h("\u2713 Check: S connect pool successfully depleted (0 challenges remaining).");else{h(`\u2717 Check: S connect pool not depleted! (${S} challenges remaining)`);return}if(O.senderPeer&&O.senderPeer.isSocketOpen)h("\u2713 Check: WebSocket connection is active and OPEN.");else{h("\u2717 Check: WebSocket connection is NOT open or peer is missing!");return}h("\u{1F389} ALL PHASE 2B CONNECT CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 2B All Passed";let A=document.getElementById("btn-3b-setup");A&&(A.disabled=!1)}catch(t){h(`\u2717 2B Check FAILED: ${w(t)}`),console.error(`${r} 2B Check error:`,t)}})}f(Ll,"init2bCheckButton");function Dl(){let r=document.getElementById("btn-3b-setup");r&&r.addEventListener("click",()=>{Lt({phaseText:"3B",btnId:"btn-3b-setup",nextBtnId:"btn-3b-sync",masterSecret:"test-sender-secret-phase3",syncSalt:"senderidentitysyncsaltphase3",manageSalt:"senderidentitymanagesaltphase3",ib:"test data 3b",data:{hello:"world3",random:Math.random()}})})}f(Dl,"init3bSetupButton");function Rl(){let r=document.getElementById("btn-3b-sync");r&&r.addEventListener("click",()=>{fr({phaseText:"3B",btnId:"btn-3b-sync",nextBtnId:"btn-3b-check"})})}f(Rl,"init3bSyncButton");function Pl(){let r=`${fe}[init3bCheckButton]`,e=document.getElementById("btn-3b-check");e&&e.addEventListener("click",async()=>{try{h("3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetX,s=y({ibGib:a}),i=y({ibGib:n}),c=await t.getLatestAddr({addr:s,space:o});if(!c){h("\u2717 Check: Evolved target X NOT found in local space!");return}h(`\u2713 Check: Evolved target X found locally at: ${c}`);let d=await t.getDependencyGraph({ibGibAddr:c,space:o});if(!d||Object.keys(d).length===0){h("\u2717 Check: Failed to load target X dependency graph locally.");return}h(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let l=new J,b=await l.getIbGibGraph(i,s,!0);if(!b.success||!b.graph){h(`\u2717 Check: Failed to fetch target X graph from server: ${b.message}`);return}let p=b.graph;if(h(`\u2713 Check: Target X server graph loaded (${Object.keys(p).length} nodes).`),Se({graphA:d,graphB:p}))h("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await t.getLatestAddr({addr:i,space:o});if(!g){h("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}h("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let E=(await t.get({addrs:[g],space:o})).ibGibs?.[0];if(!E){h("\u2717 Check: Failed to load I1 from local space.");return}let A=E.data?.proofs?.find(k=>k.claim?.verb==="sync")?.claim?.target;if(!A){h("\u2717 Check: I1 sync claim does not target a session keystone.");return}let I=await l.getIbGib(i,g);if(!I.success||!I.ibGib){h("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}h("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let $=await t.getLatestAddr({addr:A,space:o});if(!$){h("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}h(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let _=(await t.get({addrs:[$],space:o})).ibGibs?.[0];if(!_){h("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let G=_.data?.n;h(`\u2713 Check: S tip evolved to n = ${G}.`),G!==3&&G!==4&&h(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${G}. Continuing anyway...`);let v=await l.getIbGib(i,$);if(!v.success||!v.ibGib){h("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}h("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await t.getDependencyGraph({ibGibAddr:$,space:o}),D=await l.getIbGibGraph(i,A,!0);if(!D.success||!D.graph){h(`\u2717 Check: Failed to fetch session S graph from server: ${D.message}`);return}let B=D.graph;if(Se({graphA:N,graphB:B}))h("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}h("\u{1F389} ALL PHASE 3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 3B All Passed"}catch(t){h(`\u2717 3B Check FAILED: ${w(t)}`),console.error(`${r} 3B Check error:`,t)}})}f(Pl,"init3bCheckButton");function kl(){let r=document.getElementById("btn-4-1b-setup");r&&r.addEventListener("click",()=>{Lt({phaseText:"4.1B",btnId:"btn-4-1b-setup",nextBtnId:"btn-4-1b-sync",masterSecret:"test-sender-secret-phase4-1",syncSalt:"senderidentitysyncsaltphase4-1",manageSalt:"senderidentitymanagesaltphase4-1",ib:"test data 4.1b",data:{hello:"world4_1",random:Math.random()}})})}f(kl,"init4_1bSetupButton");function Bl(){let r=document.getElementById("btn-4-1b-sync");r&&r.addEventListener("click",()=>{fr({phaseText:"4.1B",btnId:"btn-4-1b-sync",nextBtnId:"btn-4-1b-check"})})}f(Bl,"init4_1bSyncButton");function Ul(){let r=`${fe}[init4_1bCheckButton]`,e=document.getElementById("btn-4-1b-check");e&&e.addEventListener("click",async()=>{try{h("4.1B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetX,s=y({ibGib:a}),i=y({ibGib:n}),c=await t.getLatestAddr({addr:s,space:o});if(!c){h("\u2717 Check: Evolved target X NOT found in local space!");return}h(`\u2713 Check: Evolved target X found locally at: ${c}`);let d=await t.getDependencyGraph({ibGibAddr:c,space:o});if(!d||Object.keys(d).length===0){h("\u2717 Check: Failed to load target X dependency graph locally.");return}h(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let l=new J,b=await l.getIbGibGraph(i,s,!0);if(!b.success||!b.graph){h(`\u2717 Check: Failed to fetch target X graph from server: ${b.message}`);return}let p=b.graph;if(h(`\u2713 Check: Target X server graph loaded (${Object.keys(p).length} nodes).`),Se({graphA:d,graphB:p}))h("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await t.getLatestAddr({addr:i,space:o});if(!g){h("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}h("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let E=(await t.get({addrs:[g],space:o})).ibGibs?.[0];if(!E){h("\u2717 Check: Failed to load I1 from local space.");return}let A=E.data?.proofs?.find(k=>k.claim?.verb==="sync")?.claim?.target;if(!A){h("\u2717 Check: I1 sync claim does not target a session keystone.");return}let I=await l.getIbGib(i,g);if(!I.success||!I.ibGib){h("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}h("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let $=await t.getLatestAddr({addr:A,space:o});if(!$){h("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}h(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let _=(await t.get({addrs:[$],space:o})).ibGibs?.[0];if(!_){h("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let G=_.data?.n;h(`\u2713 Check: S tip evolved to n = ${G}.`),G!==3&&G!==4&&h(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${G}. Continuing anyway...`);let v=await l.getIbGib(i,$);if(!v.success||!v.ibGib){h("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}h("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await t.getDependencyGraph({ibGibAddr:$,space:o}),D=await l.getIbGibGraph(i,A,!0);if(!D.success||!D.graph){h(`\u2717 Check: Failed to fetch session S graph from server: ${D.message}`);return}let B=D.graph;if(Se({graphA:N,graphB:B}))h("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}h("\u{1F389} ALL PHASE 4.1B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.1B All Passed"}catch(t){h(`\u2717 4.1B Check FAILED: ${w(t)}`),console.error(`${r} 4.1B Check error:`,t)}})}f(Ul,"init4_1bCheckButton");function Ml(){let r=document.getElementById("btn-4-2b-setup");r&&r.addEventListener("click",()=>{Lt({phaseText:"4.2B",btnId:"btn-4-2b-setup",nextBtnId:"btn-4-2b-sync",masterSecret:"test-sender-secret-phase4-2",syncSalt:"senderidentitysyncsaltphase4-2",manageSalt:"senderidentitymanagesaltphase4-2",ib:"dummy target 4.2b",data:{hello:"dummy"}})})}f(Ml,"init4_2bSetupButton");async function _b(){let r=`${fe}[performPhaseSync4_2b]`,e=document.getElementById("btn-4-2b-sync");if(e)try{e.disabled=!0,h("4.2B Sync: Creating Constants and executing three-pass WebSocket Sync...");let t=O.domainI;if(!t){h("\u26A0 4.2B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let o=y({ibGib:t}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=await F.constant({parentPrimitiveIb:"root",ib:"constant_c1_"+(await U()).slice(0,8),data:{some:"data_4_2b",random:Math.random()}}),i=y({ibGib:s});await n.put({ibGib:s,space:a}),await n.registerNewIbGib({ibGib:s}),O.targetC1=s,h(`4.2B Sync: \u2713 Constant C1 created: ${i}`),h("4.2B Sync: Starting Pass 1 (Sync C1)...");let c=location.protocol==="https:"?"wss:":"ws:",d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),l=new W,b=await U();O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]});let p=await l.sync({domainIbGibs:[s],senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS});await p.done,h("4.2B Sync: \u2713 Pass 1 Complete.");let u=await n.getLatestAddr({addr:y({ibGib:t}),space:a}),m=(await n.get({addrs:[u],space:a})).ibGibs[0];h("4.2B Sync: Starting Pass 2 (Sync C1 - Idempotent)..."),d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),l=new W,b=await U(),O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:m,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),p=await l.sync({domainIbGibs:[s],senderIdentity:m,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS}),await p.done,h("4.2B Sync: \u2713 Pass 2 Complete.");let E=await n.getLatestAddr({addr:y({ibGib:t}),space:a}),A=(await n.get({addrs:[E],space:a})).ibGibs[0],I=await F.constant({ib:"constant_c2_"+(await U()).slice(0,8),parentPrimitiveIb:"root",rel8ns:{link:[i]}}),$=y({ibGib:I});await n.put({ibGib:I,space:a}),await n.registerNewIbGib({ibGib:I}),O.targetC2=I,h(`4.2B Sync: \u2713 Constant C2 created linking to C1: ${$}`),h("4.2B Sync: Starting Pass 3 (Sync C2)..."),d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),l=new W,b=await U(),O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:A,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),p=await l.sync({domainIbGibs:[I],senderIdentity:A,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS}),await p.done,h("4.2B Sync: \u2713 Pass 3 Complete."),h("\u2713 4.2B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.2B Sync Run";let T=document.getElementById("btn-4-2b-check");T&&(T.disabled=!1)}catch(t){h(`\u2717 4.2B Sync FAILED: ${w(t)}`),console.error(`${r} 4.2B Sync error:`,t),e.disabled=!1}}f(_b,"performPhaseSync4_2b");function Fl(){let r=document.getElementById("btn-4-2b-sync");r&&r.addEventListener("click",()=>{_b()})}f(Fl,"init4_2bSyncButton");function jl(){let r=`${fe}[init4_2bCheckButton]`,e=document.getElementById("btn-4-2b-check");e&&e.addEventListener("click",async()=>{try{h("4.2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetC1,s=O.targetC2,i=y({ibGib:a}),c=y({ibGib:s}),d=y({ibGib:n}),l=await t.get({addrs:[i],space:o}),b=await t.get({addrs:[c],space:o});if(!l.success||!l.ibGibs?.[0]){h("\u2717 Check: Constant C1 NOT found locally.");return}if(!b.success||!b.ibGibs?.[0]){h("\u2717 Check: Constant C2 NOT found locally.");return}h("\u2713 Check: Constants C1 and C2 exist locally.");let p=new J,u=await p.getIbGib(d,i),g=await p.getIbGib(d,c);if(!u.success||!u.ibGib){h(`\u2717 Check: Constant C1 NOT found on server: ${u.message}`);return}if(!g.success||!g.ibGib){h(`\u2717 Check: Constant C2 NOT found on server: ${g.message}`);return}h("\u2713 Check: Constants C1 and C2 exist on server.");let m=await t.getDependencyGraph({ibGibAddr:c,space:o}),E=await p.getIbGibGraph(d,c,!0);if(!E.success||!E.graph){h(`\u2717 Check: Failed to fetch C2 graph from server: ${E.message}`);return}let S=E.graph;if(Se({graphA:m,graphB:S}))h("\u2713 Check: C2 dependency graphs are equivalent on client and server.");else{h("\u2717 Check: C2 dependency graphs mismatch between client and server!");return}let I=await t.getLatestAddr({addr:d,space:o});if(!I){h("\u2717 Check: Evolved domain keystone tip I3 NOT found in local space!");return}let T=(await t.get({addrs:[I],space:o})).ibGibs?.[0];if(!T){h("\u2717 Check: Failed to load evolved I from local space.");return}h(`\u2713 Check: Evolved Domain Keystone exists locally: ${I}`);let _=T.data?.n;if(h(`\u2713 Check: Evolved I tip is at n = ${_}.`),_!==3){h(`\u2717 Check: Expected I to evolve to n = 3, got n = ${_}.`);return}let G=await p.getIbGib(d,I);if(!G.success||!G.ibGib){h("\u2717 Check: Evolved Domain Keystone tip NOT found on server!");return}h("\u2713 Check: Evolved Domain Keystone tip exists on server.");let N=T.data?.proofs?.find(Te=>Te.claim?.verb==="sync")?.claim?.target;if(!N){h("\u2717 Check: Evolved I sync claim does not target a session keystone.");return}let D=await t.getLatestAddr({addr:N,space:o});if(!D){h("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}h(`\u2713 Check: Found latest session keystone (S) locally: ${D}`);let R=(await t.get({addrs:[D],space:o})).ibGibs?.[0];if(!R){h("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let k=R.data?.n;if(h(`\u2713 Check: Latest session S tip evolved to n = ${k}.`),k!==3){h(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${k}.`);return}let M=await p.getIbGib(d,D);if(!M.success||!M.ibGib){h("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}h("\u2713 Check: Latest Session Keystone (S) exists on server.");let j=await t.getDependencyGraph({ibGibAddr:D,space:o}),Q=await p.getIbGibGraph(d,N,!0);if(!Q.success||!Q.graph){h(`\u2717 Check: Failed to fetch session S graph from server: ${Q.message}`);return}let ee=Q.graph;if(Se({graphA:j,graphB:ee}))h("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}h("\u{1F389} ALL PHASE 4.2B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.2B All Passed"}catch(t){h(`\u2717 4.2B Check FAILED: ${w(t)}`),console.error(`${r} 4.2B Check error:`,t)}})}f(jl,"init4_2bCheckButton");function Vl(){let r=document.getElementById("btn-4-3b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.3B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-3",configs:[de("sync","senderidentitysyncsaltphase4-3"),de("manage","senderidentitymanagesaltphase4-3")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-3",h(`4.3B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)h("4.3B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_partial_4_3b",data:{type:"root",label:"Root4_3b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c});let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_3b"}},metaspace:e,space:t});O.targetC1=d,O.targetX=d,h(`4.3B Setup: \u2713 Timeline V0 -> V1 created and stored locally. V1: ${y({ibGib:d})}`),h("\u2713 4.3B Setup Complete! Ready for 4.3B Sync."),r.textContent="\u2713 4.3B Setup Complete";let l=document.getElementById("btn-4-3b-sync");l&&(l.disabled=!1)}catch(e){h(`\u2717 4.3B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(Vl,"init4_3bSetupButton");async function Ab(){let r=`${fe}[performPhaseSync4_3b]`,e=document.getElementById("btn-4-3b-sync");if(e)try{e.disabled=!0,h("4.3B Sync: Starting Pass 1 (Sync V1 to server)...");let t=O.domainI,o=O.targetX;if(!t||!o){h("\u26A0 4.3B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let n=y({ibGib:t}),a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=location.protocol==="https:"?"wss:":"ws:",c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U();O.sagaId=l,O.senderPeer=c,await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]});let b=await d.sync({domainIbGibs:[o],senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS});await b.done,h("4.3B Sync: \u2713 Pass 1 Complete (V1 synced).");let p=await a.getLatestAddr({addr:y({ibGib:t}),space:s}),g=(await a.get({addrs:[p],space:s})).ibGibs[0];h("4.3B Sync: Mutating V1 to V2 locally...");let m=await Z({timeline:o,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_3b"}},metaspace:a,space:s});O.targetX=m,h(`4.3B Sync: \u2713 V2 created locally: ${y({ibGib:m})}`),h("4.3B Sync: Starting Pass 2 (Sync V2 delta to server)..."),c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U(),O.sagaId=l,O.senderPeer=c,await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:g,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]}),b=await d.sync({domainIbGibs:[m],senderIdentity:g,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS}),await b.done,h("4.3B Sync: \u2713 Pass 2 Complete (V2 synced)."),h("\u2713 4.3B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.3B Sync Run";let E=document.getElementById("btn-4-3b-check");E&&(E.disabled=!1)}catch(t){h(`\u2717 4.3B Sync FAILED: ${w(t)}`),console.error(t),e.disabled=!1}}f(Ab,"performPhaseSync4_3b");function Hl(){let r=document.getElementById("btn-4-3b-sync");r&&r.addEventListener("click",()=>{Ab()})}f(Hl,"init4_3bSyncButton");function Kl(){let r=`${fe}[init4_3bCheckButton]`,e=document.getElementById("btn-4-3b-check");e&&e.addEventListener("click",async()=>{try{h("4.3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetC1,s=O.targetX,i=y({ibGib:a}),c=y({ibGib:s}),d=y({ibGib:n}),l=await t.get({addrs:[i],space:o}),b=await t.get({addrs:[c],space:o});if(!l.success||!l.ibGibs?.[0]){h("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!b.success||!b.ibGibs?.[0]){h("\u2717 Check: Timeline frame V2 NOT found locally.");return}h("\u2713 Check: Timeline frames V1 and V2 exist locally.");let p=new J,u=await p.getIbGib(d,c);if(!u.success||!u.ibGib){h(`\u2717 Check: Timeline frame V2 NOT found on server: ${u.message}`);return}h("\u2713 Check: Timeline frame V2 exists on server.");let m=u.ibGib.rel8ns?.past?.at(-1);if(m===i)h("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{h(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${m}`);return}let E=await t.getDependencyGraph({ibGibAddr:c,space:o}),S=await p.getIbGibGraph(d,c,!0);if(!S.success||!S.graph){h(`\u2717 Check: Failed to fetch V2 graph from server: ${S.message}`);return}let A=S.graph;if(Se({graphA:E,graphB:A}))h("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");else{h("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}let $=await t.getLatestAddr({addr:d,space:o});if(!$){h("\u2717 Check: Evolved domain keystone tip NOT found in local space!");return}let _=(await t.get({addrs:[$],space:o})).ibGibs?.[0];if(!_){h("\u2717 Check: Failed to load evolved I from local space.");return}h(`\u2713 Check: Evolved Domain Keystone exists locally: ${$}`);let G=_.data?.n;if(h(`\u2713 Check: Evolved I tip is at n = ${G}.`),G!==2){h(`\u2717 Check: Expected I to evolve to n = 2, got n = ${G}.`);return}let v=await p.getIbGib(d,$);if(!v.success||!v.ibGib){h("\u2717 Check: Evolved Domain Keystone tip NOT found on server!");return}h("\u2713 Check: Evolved Domain Keystone tip exists on server.");let D=_.data?.proofs?.find(Ue=>Ue.claim?.verb==="sync")?.claim?.target;if(!D){h("\u2717 Check: Evolved I sync claim does not target a session keystone.");return}let B=await t.getLatestAddr({addr:D,space:o});if(!B){h("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}h(`\u2713 Check: Found latest session keystone (S) locally: ${B}`);let k=(await t.get({addrs:[B],space:o})).ibGibs?.[0];if(!k){h("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let M=k.data?.n;if(h(`\u2713 Check: Latest session S tip evolved to n = ${M}.`),M!==3){h(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${M}.`);return}let j=await p.getIbGib(d,B);if(!j.success||!j.ibGib){h("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}h("\u2713 Check: Latest Session Keystone (S) exists on server.");let Q=await t.getDependencyGraph({ibGibAddr:B,space:o}),ee=await p.getIbGibGraph(d,D,!0);if(!ee.success||!ee.graph){h(`\u2717 Check: Failed to fetch session S graph from server: ${ee.message}`);return}let Ae=ee.graph;if(Se({graphA:Q,graphB:Ae}))h("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}h("\u{1F389} ALL PHASE 4.3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.3B All Passed"}catch(t){h(`\u2717 4.3B Check FAILED: ${w(t)}`),console.error(`${r} 4.3B Check error:`,t)}})}f(Kl,"init4_3bCheckButton");function Xl(){let r=document.getElementById("btn-4-4b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.4B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 -> V2...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-4",configs:[de("sync","senderidentitysyncsaltphase4-4"),de("manage","senderidentitymanagesaltphase4-4")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-4",h(`4.4B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)h("4.4B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_deep_4_4b",data:{type:"root",label:"Root4_4b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c}),O.targetC1=c;let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_4b"}},metaspace:e,space:t});O.targetC2=d;let l=await Z({timeline:d,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_4b"}},metaspace:e,space:t});O.targetX=l,h(`4.4B Setup: \u2713 Timeline V0 -> V1 -> V2 created locally. V2 Tip: ${y({ibGib:l})}`),h("\u2713 4.4B Setup Complete! Ready for 4.4B Sync."),r.textContent="\u2713 4.4B Setup Complete";let b=document.getElementById("btn-4-4b-sync");b&&(b.disabled=!1)}catch(e){h(`\u2717 4.4B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(Xl,"init4_4bSetupButton");async function Tb(){let r=`${fe}[performPhaseSync4_4b]`,e=document.getElementById("btn-4-4b-sync");if(e)try{e.disabled=!0,h("4.4B Sync: Initiating WebSocket Sync of V2 Tip...");let t=O.domainI,o=O.targetX;if(!t||!o){h("\u26A0 4.4B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let n=y({ibGib:t}),a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=location.protocol==="https:"?"wss:":"ws:",c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U();O.sagaId=l,O.senderPeer=c,await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]}),await(await d.sync({domainIbGibs:[o],senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS})).done,h("4.4B Sync: \u2713 WebSocket Sync completed."),h("\u2713 4.4B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.4B Sync Run";let p=document.getElementById("btn-4-4b-check");p&&(p.disabled=!1)}catch(t){h(`\u2717 4.4B Sync FAILED: ${w(t)}`),console.error(t),e.disabled=!1}}f(Tb,"performPhaseSync4_4b");function ql(){let r=document.getElementById("btn-4-4b-sync");r&&r.addEventListener("click",()=>{Tb()})}f(ql,"init4_4bSyncButton");function Wl(){let r=`${fe}[init4_4bCheckButton]`,e=document.getElementById("btn-4-4b-check");e&&e.addEventListener("click",async()=>{try{h("4.4B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetC1,s=O.targetC2,i=O.targetX,c=y({ibGib:a}),d=y({ibGib:s}),l=y({ibGib:i}),b=y({ibGib:n}),p=await t.get({addrs:[c],space:o}),u=await t.get({addrs:[d],space:o}),g=await t.get({addrs:[l],space:o});if(!p.success||!p.ibGibs?.[0]){h("\u2717 Check: Timeline frame V0 NOT found locally.");return}if(!u.success||!u.ibGibs?.[0]){h("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!g.success||!g.ibGibs?.[0]){h("\u2717 Check: Timeline frame V2 NOT found locally.");return}h("\u2713 Check: Timeline frames V0, V1, and V2 exist locally.");let m=new J,E=await m.getIbGib(b,l);if(!E.success||!E.ibGib){h(`\u2717 Check: Timeline frame V2 NOT found on server: ${E.message}`);return}h("\u2713 Check: Timeline frame V2 exists on server.");let A=E.ibGib.rel8ns?.past?.at(-1);if(A===d)h("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{h(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${A}`);return}let I=await m.getIbGib(b,d);if(!I.success||!I.ibGib){h(`\u2717 Check: Timeline frame V1 NOT found on server: ${I.message}`);return}h("\u2713 Check: Timeline frame V1 exists on server.");let T=I.ibGib.rel8ns?.past?.at(-1);if(T===c)h("\u2713 Check: Server V1 correctly references V0 in its past relation.");else{h(`\u2717 Check: Server V1 does not reference V0 in past relation! got: ${T}`);return}let _=await t.getDependencyGraph({ibGibAddr:l,space:o}),G=await m.getIbGibGraph(b,l,!0);if(!G.success||!G.graph){h(`\u2717 Check: Failed to fetch V2 graph from server: ${G.message}`);return}let v=G.graph;if(Se({graphA:_,graphB:v}))h("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");else{h("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}let D=await t.getLatestAddr({addr:b,space:o});if(!D){h("\u2717 Check: Evolved domain keystone tip NOT found in local space!");return}let R=(await t.get({addrs:[D],space:o})).ibGibs?.[0];if(!R){h("\u2717 Check: Failed to load evolved I from local space.");return}h(`\u2713 Check: Evolved Domain Keystone exists locally: ${D}`);let k=R.data?.n;if(h(`\u2713 Check: Evolved I tip is at n = ${k}.`),k!==1){h(`\u2717 Check: Expected I to evolve to n = 1, got n = ${k}.`);return}let M=await m.getIbGib(b,D);if(!M.success||!M.ibGib){h("\u2717 Check: Evolved Domain Keystone tip NOT found on server!");return}h("\u2713 Check: Evolved Domain Keystone tip exists on server.");let Q=R.data?.proofs?.find(tt=>tt.claim?.verb==="sync")?.claim?.target;if(!Q){h("\u2717 Check: Evolved I sync claim does not target a session keystone.");return}let ee=await t.getLatestAddr({addr:Q,space:o});if(!ee){h("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}h(`\u2713 Check: Found latest session keystone (S) locally: ${ee}`);let Te=(await t.get({addrs:[ee],space:o})).ibGibs?.[0];if(!Te){h("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let Ue=Te.data?.n;if(h(`\u2713 Check: Latest session S tip evolved to n = ${Ue}.`),Ue!==3){h(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${Ue}.`);return}let Me=await m.getIbGib(b,ee);if(!Me.success||!Me.ibGib){h("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}h("\u2713 Check: Latest Session Keystone (S) exists on server.");let pe=await t.getDependencyGraph({ibGibAddr:ee,space:o}),Ve=await m.getIbGibGraph(b,Q,!0);if(!Ve.success||!Ve.graph){h(`\u2717 Check: Failed to fetch session S graph from server: ${Ve.message}`);return}let et=Ve.graph;if(Se({graphA:pe,graphB:et}))h("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{h("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}h("\u{1F389} ALL PHASE 4.4B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.4B All Passed"}catch(t){h(`\u2717 4.4B Check FAILED: ${w(t)}`),console.error(`${r} 4.4B Check error:`,t)}})}f(Wl,"init4_4bCheckButton");var Tr={};function Yl(){let r=document.getElementById("btn-4-5b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.5B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 in default local space...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-5b",configs:[de("sync","senderidentitysyncsaltphase4-5b"),de("manage","senderidentitymanagesaltphase4-5b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-5b",h(`4.5B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)h("4.5B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_partial_4_5b",data:{type:"root",label:"Root4_5b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t});let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_5b"}},metaspace:e,space:t});Tr.targetV1=d,h(`4.5B Setup: \u2713 Local timeline V0 -> V1 created. V1 Tip: ${y({ibGib:d})}`),h("4.5B Setup: Seeding V1 to the server via WebSocket...");let l=location.protocol==="https:"?"wss:":"ws:",b=y({ibGib:n}),p=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(b)}`,wsUrl:`${l}//${location.host}/api/sync/ws/${encodeURIComponent(b)}`}),u=new W,g=await U();await p.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:n,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),sagaId:g,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[b]}),await(await u.sync({domainIbGibs:[d],senderIdentity:n,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),peer:p,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.5B Setup: \u2713 Pass 1 Sync (V1 to server) complete.");let E=await e.getLatestAddr({addr:b,space:t});if(!E)throw new Error("Could not get latest sender address from default space.");let A=(await e.get({addrs:[E],space:t})).ibGibs[0];h('4.5B Setup: Creating secondary local space simulating "remote" client...');let I=`remote-${await U()}`,$=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:I,getFnPrompt:e.getFnPrompt}});if(!$)throw new Error("Failed to create remote space");await $.initialized;let T=await e.getDependencyGraph({ibGibAddr:y({ibGib:d}),space:t});await e.put({ibGibs:Object.values(T),space:$}),await e.registerNewIbGib({ibGib:d,space:$});let _=await e.getDependencyGraph({ibGibAddr:E,space:t});await e.put({ibGibs:Object.values(_),space:$}),await e.registerNewIbGib({ibGib:A,space:$}),h("4.5B Setup: \u2713 Copied V1 and identity I to remoteSpace."),h("4.5B Setup: Mutating V1 -> V2 in remoteSpace...");let G=await Z({timeline:d,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_5b"}},metaspace:e,space:$});Tr.targetV2=G,h(`4.5B Setup: \u2713 Mutated to V2 in remoteSpace: ${y({ibGib:G})}`),h("4.5B Setup: Syncing V2 from remoteSpace to the server...");let v=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(b)}`,wsUrl:`${l}//${location.host}/api/sync/ws/${encodeURIComponent(b)}`}),N=new W,D=await U();await v.initializeOpts({localMetaspace:e,localSpace:$,senderIdentity:A,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),sagaId:D,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[b]}),await(await N.sync({domainIbGibs:[G],senderIdentity:A,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),peer:v,localSpace:$,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.5B Setup: \u2713 Pass 2 Sync (V2 to server) complete.");let R=await e.getLatestAddr({addr:b,space:$});if(!R)throw new Error("Could not get latest sender address from remoteSpace.");let M=(await e.get({addrs:[R],space:$})).ibGibs[0];Tr.domainI_latest=M;let j=await e.getDependencyGraph({ibGibAddr:R,space:$});await e.put({ibGibs:Object.values(j),space:t}),await e.registerNewIbGib({ibGib:M,space:t}),h("\u2713 4.5B Setup Complete! Server has V2, default local space has V1. Ready for 4.5B Sync."),r.textContent="\u2713 4.5B Setup Complete";let Q=document.getElementById("btn-4-5b-sync");Q&&(Q.disabled=!1)}catch(e){h(`\u2717 4.5B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(Yl,"init4_5bSetupButton");function zl(){let r=document.getElementById("btn-4-5b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.5B Sync: Initiating WebSocket Sync from default local space (which has V1, server has V2)...");let e=Tr.domainI_latest,t=Tr.targetV1;if(!e||!t){h("\u26A0 4.5B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,h("\u2713 4.5B Sync Execution Complete! Ready for 4.5B Check."),r.textContent="\u2713 4.5B Sync Run";let b=document.getElementById("btn-4-5b-check");b&&(b.disabled=!1)}catch(e){h(`\u2717 4.5B Sync FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(zl,"init4_5bSyncButton");function Jl(){let r=document.getElementById("btn-4-5b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.5B Check: Verifying that V2 was pulled down to default local space...");let e=Tr.targetV2;if(!e){h("\u26A0 4.5B Check: Missing target V2 in state. Did Setup run?"),r.disabled=!1;return}let t=y({ibGib:e}),o=await V(),n=await o.getLocalUserSpace({});if(!n)throw new Error("No default space.");let a=await o.get({addr:t,space:n});if(!a.success||a.ibGibs?.length!==1)throw new Error(`V2 tip (${t}) is NOT present in local space!`);let s=a.ibGibs[0];h(`4.5B Check: \u2713 V2 Tip found locally. Label: "${s.data?.label}"`);let i=await o.getDependencyGraph({ibGibAddr:t,space:n});h("4.5B Check: Fetching V2 dependency graph from server...");let c=y({ibGib:Tr.domainI_latest}),l=await new J().getIbGibGraph(c,t,!0);if(!l.success||!l.graph)throw new Error(`Failed to fetch V2 graph from server: ${l.message}`);if(Se({graphA:i,graphB:l.graph}))h("\u2713 4.5B Check SUCCESS: V2 and all dependencies are fully equivalent on client and server!"),r.textContent="\u2713 4.5B Check Success";else throw new Error("Dependency graphs on local space and server are NOT equivalent.")}catch(e){h(`\u2717 4.5B Check FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(Jl,"init4_5bCheckButton");var Xt={};function Zl(){let r=document.getElementById("btn-4-6b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.6B Setup: Generating Domain Keystone (I) and two independent target timelines (Alpha and Beta) in default local space...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-6b",configs:[de("sync","senderidentitysyncsaltphase4-6b"),de("manage","senderidentitymanagesaltphase4-6b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});Xt.domainI_latest=n,O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-6b",h(`4.6B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)h("4.6B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_alpha_4_6b",data:{type:"root",label:"Alpha4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t});let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"A1_4_6b"}},metaspace:e,space:t});Xt.targetAlphaV1=d,h(`4.6B Setup: \u2713 Local Timeline A created. A1 Tip: ${y({ibGib:d})}`);let l=await F.firstGen({parentIbGib:q,ib:"timeline_root_beta_4_6b",data:{type:"root",label:"Beta4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),b=l.newIbGib;await e.persistTransformResult({resTransform:l,space:t}),await e.registerNewIbGib({ibGib:b,space:t});let p=await Z({timeline:b,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B1_4_6b"}},metaspace:e,space:t}),u=await Z({timeline:p,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B2_4_6b"}},metaspace:e,space:t});Xt.targetBetaV2=u,h(`4.6B Setup: \u2713 Local Timeline B created. B2 Tip: ${y({ibGib:u})}`),h("\u2713 4.6B Setup Complete! Timelines created locally. Ready for 4.6B Sync."),r.textContent="\u2713 4.6B Setup Complete";let g=document.getElementById("btn-4-6b-sync");g&&(g.disabled=!1)}catch(e){h(`\u2717 4.6B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(Zl,"init4_6bSetupButton");function Ql(){let r=document.getElementById("btn-4-6b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.6B Sync: Initiating WebSocket Sync for both Timeline A and Timeline B in one call...");let e=Xt.domainI_latest,t=Xt.targetAlphaV1,o=Xt.targetBetaV2;if(!e||!t||!o){h("\u26A0 4.6B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let n=y({ibGib:e}),a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=location.protocol==="https:"?"wss:":"ws:",c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U();await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-6b","fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]}),await(await d.sync({domainIbGibs:[t,o],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-6b","fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS})).done,h("\u2713 4.6B Sync Execution Complete! Ready for 4.6B Check."),r.textContent="\u2713 4.6B Sync Run";let p=document.getElementById("btn-4-6b-check");p&&(p.disabled=!1)}catch(e){h(`\u2717 4.6B Sync FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(Ql,"init4_6bSyncButton");function ed(){let r=document.getElementById("btn-4-6b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.6B Check: Verifying both Timeline A and Timeline B exist on the server with matching dependency graphs...");let e=Xt.domainI_latest,t=Xt.targetAlphaV1,o=Xt.targetBetaV2;if(!e||!t||!o){h("\u26A0 4.6B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let n=y({ibGib:e}),a=y({ibGib:t}),s=y({ibGib:o}),i=await V(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let d=new J;h("4.6B Check: Fetching Timeline A dependency graph from server...");let l=await d.getIbGibGraph(n,a,!0);if(!l.success||!l.graph)throw new Error(`Failed to fetch Timeline A graph from server: ${l.message}`);let b=await i.getDependencyGraph({ibGibAddr:a,space:c});if(!Se({graphA:b,graphB:l.graph}))throw new Error("Timeline A dependency graphs on local space and server are NOT equivalent.");h("4.6B Check: \u2713 Timeline A graphs are equivalent."),h("4.6B Check: Fetching Timeline B dependency graph from server...");let u=await d.getIbGibGraph(n,s,!0);if(!u.success||!u.graph)throw new Error(`Failed to fetch Timeline B graph from server: ${u.message}`);let g=await i.getDependencyGraph({ibGibAddr:s,space:c});if(!Se({graphA:g,graphB:u.graph}))throw new Error("Timeline B dependency graphs on local space and server are NOT equivalent.");h("4.6B Check: \u2713 Timeline B graphs are equivalent."),h("\u2713 4.6B Check SUCCESS: Both independent timelines are fully synced and identical on client and server!"),r.textContent="\u2713 4.6B Check Success"}catch(e){h(`\u2717 4.6B Check FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(ed,"init4_6bCheckButton");var ht={};function td(){let r=document.getElementById("btn-4-7b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.7B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-7b",configs:[de("sync","senderidentitysyncsaltphase4-7b"),de("manage","senderidentitymanagesaltphase4-7b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});ht.domainI_latest=a;let s=a,i=y({ibGib:a});h(`4.7B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);h("4.7B Setup: \u2713 Identity registered on server."),h("4.7B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_7b",getFnPrompt:e.getFnPrompt}});await l.initialized,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l});let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_conflict_4_7b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t}),ht.testRoot=p;let u=await Z({timeline:p,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),g=await e.getDependencyGraph({ibGibAddr:y({ibGib:p}),space:t}),m=await e.getDependencyGraph({ibGibAddr:y({ibGib:u}),space:t}),E={...g,...m};await e.put({ibGibs:Object.values(E),space:l}),await e.registerNewIbGib({ibGib:p,space:l}),await e.registerNewIbGib({ibGib:u,space:l}),h("4.7B Setup: Syncing v1_common to server...");let S=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),A=new W;await S.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await A.sync({domainIbGibs:[u],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),peer:S,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.7B Setup: \u2713 Seeding complete on server.");let $=await e.getLatestAddr({ibGib:a,space:t});if(!$)throw new Error("Could not find latest evolved identity address in local space.");let T=await e.get({addr:$,space:t});if(!T.success||!T.ibGibs||T.ibGibs.length===0)throw new Error("Could not find latest evolved identity in local space.");s=T.ibGibs[0],ht.domainI_latest=s,h(`4.7B Setup: \u2713 Fetched evolved identity: ${$}`),await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let _=await Z({timeline:u,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t});ht.targetAlphaV2a=_,h(`4.7B Setup: \u2713 Created client divergent edit V2a: ${y({ibGib:_})}`);let G=await Z({timeline:u,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:l});ht.targetBetaV2b=G,h(`4.7B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:G})}`),h("4.7B Setup: Pushing V2b from remote space to server...");let v=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),N=new W;await v.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await N.sync({domainIbGibs:[G],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),peer:v,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.7B Setup: \u2713 Server tip is now V2b.");let B=await e.getLatestAddr({ibGib:a,space:l});if(!B)throw new Error("Could not find latest evolved identity address in remote space.");let R=await e.get({addr:B,space:l});if(!R.success||!R.ibGibs||R.ibGibs.length===0)throw new Error("Could not find latest evolved identity in remote space.");let k=R.ibGibs[0];await e.put({ibGib:k,space:t}),await e.registerNewIbGib({ibGib:k,space:t}),ht.domainI_latest=k,h(`4.7B Setup: \u2713 Copied evolved identity tip (n=3) back to default space: ${B}`),h("\u2713 4.7B Setup Complete! Ready for 4.7B Sync."),r.textContent="\u2713 4.7B Setup Complete";let M=document.getElementById("btn-4-7b-sync");M&&(M.disabled=!1)}catch(e){h(`\u2717 4.7B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(td,"init4_7bSetupButton");function rd(){let r=document.getElementById("btn-4-7b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.7B Sync: Initiating WebSocket Sync for divergent edit V2a...");let e=ht.domainI_latest,t=ht.targetAlphaV2a;if(!e||!t){h("\u26A0 4.7B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,h("\u2713 4.7B Sync Execution Complete! Ready for 4.7B Check."),r.textContent="\u2713 4.7B Sync Run";let b=document.getElementById("btn-4-7b-check");b&&(b.disabled=!1)}catch(e){h(`\u2717 4.7B Sync FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(rd,"init4_7bSyncButton");function od(){let r=document.getElementById("btn-4-7b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.7B Check: Verifying merged tip (V3) contains both edits on client and server...");let e=ht.domainI_latest,t=ht.testRoot,o=ht.targetAlphaV2a,n=ht.targetBetaV2b;if(!e||!t||!o||!n){h("\u26A0 4.7B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let a=y({ibGib:e}),s=be({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),i=await V(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let l=(await i.getLocalUserSpace({}).then(T=>new W().getKnowledgeMap({space:T,metaspace:i,domainIbGibs:[t]})))[s];if(h(`4.7B Check: Client tip address: ${l}`),!l)throw new Error("Client default space is missing the timeline tip.");let b=await i.get({addr:l,space:c});if(!b.success||!b.ibGibs||b.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let p=b.ibGibs[0];if(!p.data||!p.data.fieldA||!p.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${p.data?.fieldA}, fieldB: ${p.data?.fieldB}`);h("4.7B Check: \u2713 Client tip has both fieldA and fieldB edits.");let u=p.rel8ns?.[$t];if(!u?.[0])throw new Error("Client tip is missing graftinfo relations.");let g=await i.get({addr:u[0],space:c});if(!g.success||!g.ibGibs||g.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let m=g.ibGibs[0],E=m.rel8ns?.[tr],S=m.rel8ns?.[xt];if(!E||!S)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");h("4.7B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new J;h("4.7B Check: Fetching server timeline graph...");let I=await A.getIbGibGraph(a,l,!0);if(!I.success||!I.graph)throw new Error(`Failed to fetch merged graph from server: ${I.message}`);let $=I.graph[l];if(!$)throw new Error("Merged V3 tip is not present on the server!");if($.data?.fieldA!=="source_edit"||$.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");h("4.7B Check: \u2713 Server tip has matching merged edits."),h("\u2713 4.7B Check SUCCESS: Divergent branches merged successfully on both client and server via optimistic graft!"),r.textContent="\u2713 4.7B Check Success"}catch(e){h(`\u2717 4.7B Check FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(od,"init4_7bCheckButton");var ut={};function nd(){let r=document.getElementById("btn-4-8b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.8B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-8b",configs:[de("sync","senderidentitysyncsaltphase4-8b"),de("manage","senderidentitymanagesaltphase4-8b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});ut.domainI_latest=a;let s=a,i=y({ibGib:a});h(`4.8B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);h("4.8B Setup: \u2713 Identity registered on server."),h("4.8B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_8b",getFnPrompt:e.getFnPrompt}});await l.initialized,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l});let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_conflict_4_8b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t}),ut.testRoot=p;let u=await Z({timeline:p,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),g=await e.getDependencyGraph({ibGibAddr:y({ibGib:p}),space:t}),m=await e.getDependencyGraph({ibGibAddr:y({ibGib:u}),space:t}),E={...g,...m};await e.put({ibGibs:Object.values(E),space:l}),await e.registerNewIbGib({ibGib:p,space:l}),await e.registerNewIbGib({ibGib:u,space:l}),h("4.8B Setup: Syncing v1_common to server...");let S=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),A=new W;await S.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await A.sync({domainIbGibs:[u],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),peer:S,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.8B Setup: \u2713 Seeding complete on server.");let $=await e.getLatestAddr({ibGib:a,space:t});if(!$)throw new Error("Could not find latest evolved identity address in local space.");let T=await e.get({addr:$,space:t});if(!T.success||!T.ibGibs||T.ibGibs.length===0)throw new Error("Could not find latest evolved identity in local space.");s=T.ibGibs[0],ut.domainI_latest=s,h(`4.8B Setup: \u2713 Fetched evolved identity: ${$}`),await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let _=await F.firstGen({parentIbGib:q,ib:"beta_multitimelines_withid_4_8b",data:{fieldA:"beta field A created on source"},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),G=_.newIbGib;await e.persistTransformResult({resTransform:_,space:t}),await e.registerNewIbGib({ibGib:G,space:t}),ut.targetBetaV0=G,h(`4.8B Setup: \u2713 Created client independent related timeline Beta: ${y({ibGib:G})}`);let v=await Z({timeline:u,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t}),N=await lr({timeline:v,metaspace:e,space:t,rel8nInfos:[{rel8nName:"testrel8n",ibGibs:[G]}]});ut.targetAlphaV3a=N,h(`4.8B Setup: \u2713 Created client divergent edit V3a: ${y({ibGib:N})}`);let D=await Z({timeline:u,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:l});h(`4.8B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:D})}`),h("4.8B Setup: Pushing V2b from remote space to server...");let B=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),R=new W;await B.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await R.sync({domainIbGibs:[D],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),peer:B,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.8B Setup: \u2713 Server tip is now V2b.");let M=await e.getLatestAddr({ibGib:a,space:l});if(!M)throw new Error("Could not find latest evolved identity address in remote space.");let j=await e.get({addr:M,space:l});if(!j.success||!j.ibGibs||j.ibGibs.length===0)throw new Error("Could not find latest evolved identity in remote space.");let Q=j.ibGibs[0];await e.put({ibGib:Q,space:t}),await e.registerNewIbGib({ibGib:Q,space:t}),ut.domainI_latest=Q,h(`4.8B Setup: \u2713 Copied evolved identity tip (n=3) back to default space: ${M}`),h("\u2713 4.8B Setup Complete! Ready for 4.8B Sync."),r.textContent="\u2713 4.8B Setup Complete";let ee=document.getElementById("btn-4-8b-sync");ee&&(ee.disabled=!1)}catch(e){h(`\u2717 4.8B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(nd,"init4_8bSetupButton");function ad(){let r=document.getElementById("btn-4-8b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.8B Sync: Initiating WebSocket Sync for divergent edit V3a (with related timeline Beta)...");let e=ut.domainI_latest,t=ut.targetAlphaV3a;if(!e||!t){h("\u26A0 4.8B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,h("\u2713 4.8B Sync Execution Complete! Ready for 4.8B Check."),r.textContent="\u2713 4.8B Sync Run";let b=document.getElementById("btn-4-8b-check");b&&(b.disabled=!1)}catch(e){h(`\u2717 4.8B Sync FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(ad,"init4_8bSyncButton");function sd(){let r=document.getElementById("btn-4-8b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.8B Check: Verifying merged tip (V4) contains both edits on client and server...");let e=ut.domainI_latest,t=ut.testRoot,o=ut.targetAlphaV3a,n=ut.targetBetaV0;if(!e||!t||!o||!n){h("\u26A0 4.8B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let a=y({ibGib:e}),s=be({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),i=y({ibGib:n}),c=await V(),d=await c.getLocalUserSpace({});if(!d)throw new Error("No default space.");let b=(await c.getLocalUserSpace({}).then(G=>new W().getKnowledgeMap({space:G,metaspace:c,domainIbGibs:[t]})))[s];if(h(`4.8B Check: Client tip address: ${b}`),!b)throw new Error("Client default space is missing the timeline tip.");let p=await c.get({addr:b,space:d});if(!p.success||!p.ibGibs||p.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let u=p.ibGibs[0];if(!u.data||!u.data.fieldA||!u.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${u.data?.fieldA}, fieldB: ${u.data?.fieldB}`);h("4.8B Check: \u2713 Client tip has both fieldA and fieldB edits.");let g=u.rel8ns?.[$t];if(!g?.[0])throw new Error("Client tip is missing graftinfo relations.");let m=await c.get({addr:g[0],space:d});if(!m.success||!m.ibGibs||m.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let E=m.ibGibs[0],S=E.rel8ns?.[tr],A=E.rel8ns?.[xt];if(!S||!A)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");h("4.8B Check: \u2713 Client graft base and orphan relations are correctly set.");let I=new J;h("4.8B Check: Fetching server timeline graph...");let $=await I.getIbGibGraph(a,b,!0);if(!$.success||!$.graph)throw new Error(`Failed to fetch merged graph from server: ${$.message}`);let T=$.graph[b];if(!T)throw new Error("Merged V4 tip is not present on the server!");if(T.data?.fieldA!=="source_edit"||T.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");h("4.8B Check: \u2713 Server tip has matching merged edits."),h("4.8B Check: Verifying related timeline Beta is present on the server...");let _=await I.getIbGibGraph(a,i,!0);if(!_.success||!_.graph||!_.graph[i])throw new Error(`Related timeline Beta (${i}) is missing from the server!`);h("4.8B Check: \u2713 Related timeline Beta successfully verified on the server."),h("\u2713 4.8B Check SUCCESS: Divergent branches merged successfully and related timeline synced on server!"),r.textContent="\u2713 4.8B Check Success"}catch(e){h(`\u2717 4.8B Check FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(sd,"init4_8bCheckButton");var Dt={},Bn=`This is the initial quiz question.
|
|
32
|
+
It has multiple lines.
|
|
33
|
+
Students will answer this.`,id=`
|
|
34
|
+
Instructor added hint.`,cd=`Student note: Confusing!
|
|
35
|
+
`;function ld(){let r=document.getElementById("btn-4-9b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.9B Setup: Setting up identities, seeding text history, and creating divergent branches...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-9b",configs:[de("sync","senderidentitysyncsaltphase4-9b"),de("manage","senderidentitymanagesaltphase4-9b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});Dt.domainI_latest=a;let s=a,i=y({ibGib:a});h(`4.9B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);h("4.9B Setup: \u2713 Identity registered on server."),h("4.9B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_9b",getFnPrompt:e.getFnPrompt}});await l.initialized,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l});let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_text_conflict_4_9b",data:{text:Bn,label:"TextRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t}),Dt.testRoot=p;let u=await e.getDependencyGraph({ibGibAddr:y({ibGib:p}),space:t});await e.put({ibGibs:Object.values(u),space:l}),await e.registerNewIbGib({ibGib:p,space:l}),h("4.9B Setup: Syncing testRoot to server...");let g=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),m=new W;await g.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await m.sync({domainIbGibs:[p],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),peer:g,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.9B Setup: \u2713 Seeding complete on server.");let S=await e.getLatestAddr({ibGib:a,space:t});if(!S)throw new Error("Could not find latest evolved identity address in local space.");let A=await e.get({addr:S,space:t});if(!A.success||!A.ibGibs||A.ibGibs.length===0)throw new Error("Could not find latest evolved identity in local space.");s=A.ibGibs[0],Dt.domainI_latest=s,h(`4.9B Setup: \u2713 Fetched evolved identity: ${S}`),await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let I=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_appended",dataToAddOrPatch:{text:Bn+id}},metaspace:e,space:t});Dt.targetAlphaV1Source=I,h(`4.9B Setup: \u2713 Created client appended edit: ${y({ibGib:I})}`);let $=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_prepended",dataToAddOrPatch:{text:cd+Bn}},metaspace:e,space:l});h(`4.9B Setup: \u2713 Created remote prepended edit: ${y({ibGib:$})}`),h("4.9B Setup: Pushing remote prepended edit to server...");let T=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),_=new W;await T.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await _.sync({domainIbGibs:[$],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),peer:T,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.9B Setup: \u2713 Server tip is now the prepended edit.");let v=await e.getLatestAddr({ibGib:a,space:l});if(!v)throw new Error("Could not find latest evolved identity address in remote space.");let N=await e.get({addr:v,space:l});if(!N.success||!N.ibGibs||N.ibGibs.length===0)throw new Error("Could not find latest evolved identity in remote space.");let D=N.ibGibs[0];await e.put({ibGib:D,space:t}),await e.registerNewIbGib({ibGib:D,space:t}),Dt.domainI_latest=D,h(`4.9B Setup: \u2713 Copied evolved identity tip (n=3) back to default space: ${v}`),h("\u2713 4.9B Setup Complete! Ready for 4.9B Sync."),r.textContent="\u2713 4.9B Setup Complete";let B=document.getElementById("btn-4-9b-sync");B&&(B.disabled=!1)}catch(e){h(`\u2717 4.9B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(ld,"init4_9bSetupButton");function dd(){let r=document.getElementById("btn-4-9b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.9B Sync: Initiating WebSocket Sync for divergent edit (LCS text merge)...");let e=Dt.domainI_latest,t=Dt.targetAlphaV1Source;if(!e||!t){h("\u26A0 4.9B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,h("\u2713 4.9B Sync Execution Complete! Ready for 4.9B Check."),r.textContent="\u2713 4.9B Sync Run";let b=document.getElementById("btn-4-9b-check");b&&(b.disabled=!1)}catch(e){h(`\u2717 4.9B Sync FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(dd,"init4_9bSyncButton");function fd(){let r=document.getElementById("btn-4-9b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.9B Check: Verifying LCS merged text on client and server...");let e=Dt.domainI_latest,t=Dt.testRoot,o=Dt.targetAlphaV1Source;if(!e||!t||!o){h("\u26A0 4.9B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let n=y({ibGib:e}),a=be({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),s=await V(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let d=(await s.getLocalUserSpace({}).then(T=>new W().getKnowledgeMap({space:T,metaspace:s,domainIbGibs:[t]})))[a];if(h(`4.9B Check: Client tip address: ${d}`),!d)throw new Error("Client default space is missing the timeline tip.");let l=await s.get({addr:d,space:i});if(!l.success||!l.ibGibs||l.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let b=l.ibGibs[0],p=cd+Bn+id;if(b.data?.text!==p)throw new Error(`Merged client tip text mismatch! Expected:
|
|
36
|
+
${p}
|
|
37
|
+
Actual:
|
|
38
|
+
${b.data?.text}`);h("4.9B Check: \u2713 Client tip text contains both prepend and append edits merged correctly.");let u=b.rel8ns?.[$t];if(!u?.[0])throw new Error("Client tip is missing graftinfo relations.");let g=await s.get({addr:u[0],space:i});if(!g.success||!g.ibGibs||g.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let m=g.ibGibs[0],E=m.rel8ns?.[tr],S=m.rel8ns?.[xt];if(!E||!S)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");h("4.9B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new J;h("4.9B Check: Fetching server timeline graph...");let I=await A.getIbGibGraph(n,d,!0);if(!I.success||!I.graph)throw new Error(`Failed to fetch merged graph from server: ${I.message}`);let $=I.graph[d];if(!$)throw new Error("Merged tip is not present on the server!");if($.data?.text!==p)throw new Error(`Server tip text mismatch! Expected:
|
|
39
|
+
${p}
|
|
40
|
+
Actual:
|
|
41
|
+
${$.data?.text}`);h("4.9B Check: \u2713 Server tip text matches the client-side merged text."),h("\u2713 4.9B Check SUCCESS: LCS text field merge conflict resolved and verified on both client and server!"),r.textContent="\u2713 4.9B Check Success"}catch(e){h(`\u2717 4.9B Check FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(fd,"init4_9bCheckButton");var z={},Ls="testrel8n";function bd(){let r=document.getElementById("btn-4-10b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.10B Setup: Setting up identities and preparing Round 1 & Round 2 divergence...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-10b",configs:[de("sync","senderidentitysyncsaltphase4-10b"),de("manage","senderidentitymanagesaltphase4-10b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});z.domainI_initial=a,z.domainI_latest=a;let s=a,i=y({ibGib:a});h(`4.10B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);h("4.10B Setup: \u2713 Identity registered on server."),h("4.10B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_10b",getFnPrompt:e.getFnPrompt}});await l.initialized,z.remoteSpace=l,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l}),h("4.10B Setup: Creating common history for alpha...");let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_alpha_4_10b",data:{commonField:"common field R1 val",label:"AlphaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;z.alpha_v0=p,await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t});let u=be({ibGib:p,defaultIfNone:"incomingAddr"});z.alpha_tjpAddr=u,await e.persistTransformResult({resTransform:b,space:l}),await e.registerNewIbGib({ibGib:p,space:l}),h("4.10B Setup: Seeding alpha_v0 to server...");let g=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),m=new W;await g.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await m.sync({domainIbGibs:[p],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:g,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.10B Setup: \u2713 alpha_v0 seeded on server.");let S=await e.getLatestAddr({ibGib:a,space:t});if(!S)throw new Error("Could not find latest evolved identity address in local space.");s=(await e.get({addr:S,space:t})).ibGibs[0],z.domainI_latest=s,await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let I=await F.firstGen({parentIbGib:q,ib:"timeline_root_beta_4_10b",data:{fieldA:"beta field A created on source",label:"BetaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),$=I.newIbGib;await e.persistTransformResult({resTransform:I,space:t}),await e.registerNewIbGib({ibGib:$,space:t}),z.r2_beta_v0_source=$;let T=be({ibGib:$,defaultIfNone:"incomingAddr"});z.beta_tjpAddr=T;let _=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_r2client",dataToAddOrPatch:{fieldA:"source_edit_r2"}},metaspace:e,space:t});h(`r2_alpha_v1_source_sansBeta.gib: ${_.gib}`),xs=y({ibGib:$});let G=await lr({timeline:_,metaspace:e,space:t,rel8nInfos:[{rel8nName:Ls,ibGibs:[$]}]});z.r2_alpha_v3_source_rel8beta=G,h(`r2_alpha_v2_source_rel8dBeta.gib: ${G.gib}`),h("4.10B Setup: \u2713 Created client Round 2 edits (alpha fieldA edit + relate beta).");let v=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_r2remote",dataToAddOrPatch:{fieldB:"remote_edit_r2"}},metaspace:e,space:l});console.log(`alpha_v0: ${K(p)}`),console.log(`r2_alpha_v1_remote: ${K(v)}`),h(`r2_alpha_v1_remote.gib: ${v.gib}`),h("4.10B Setup: Pushing remote Round 2 edit to server...");let N=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),D=new W;await N.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await D.sync({domainIbGibs:[v],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:N,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,h("4.10B Setup: \u2713 Server tip is now remote Round 2 edit.");let R=await e.getLatestAddr({ibGib:a,space:l});if(!R)throw new Error("Could not find latest evolved identity address in remote space.");let M=(await e.get({addr:R,space:l})).ibGibs[0];await e.put({ibGib:M,space:t}),await e.registerNewIbGib({ibGib:M,space:t}),z.domainI_latest=M,h("\u2713 4.10B Setup Complete! Ready for 4.10B Sync (which runs Round 2, 3, and 4 in succession)."),r.textContent="\u2713 4.10B Setup Complete";let j=document.getElementById("btn-4-10b-sync");j&&(j.disabled=!1)}catch(e){h(`\u2717 4.10B Setup FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(bd,"init4_10bSetupButton");var Ns,xs;function pd(){let r=document.getElementById("btn-4-10b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.10B Sync: Initiating WebSocket Sync for Round 2, 3, and 4 sequential evolution...");let e=z.domainI_latest,t=z.remoteSpace,o=z.alpha_tjpAddr,n=z.beta_tjpAddr,a=z.alpha_v0,s=await V(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",d=y({ibGib:z.domainI_initial});h("4.10B Sync: Running Round 2 Sync (merging divergent alpha edits)...");let l=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),b=new W;await l.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await b.sync({domainIbGibs:[z.r2_alpha_v3_source_rel8beta],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:l,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h("4.10B Sync: \u2713 Round 2 Sync complete.");let u=await s.getLatestAddr({ibGib:z.domainI_initial,space:i}),g=await s.get({addr:u,space:i});e=g.ibGibs[0],await s.put({ibGib:e,space:t}),await s.registerNewIbGib({ibGib:e,space:t}),h("4.10B Sync: Preparing Round 3 divergence (multiple conflicting timelines)...");let m=await b.getKnowledgeMap({domainIbGibs:[z.r2_alpha_v3_source_rel8beta,z.r2_beta_v0_source],space:i,metaspace:s}),E=m[o],S=m[n],A=await s.get({addr:E,space:i}),I=await s.get({addr:S,space:i}),$=await Z({timeline:A.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r3client",dataToAddOrPatch:{fieldC:"source_edit_r3"}},metaspace:s,space:i}),T=await Z({timeline:I.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r3client",dataToAddOrPatch:{betaFieldA:"source_beta_edit_r3"}},metaspace:s,space:i});h("4.10B Sync: Updating remote space to latest merged tips...");let _=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),G=new W;await _.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]});let v=await s.getLatestAddr({addr:o,space:t}),B=[(await s.get({addr:v,space:t})).ibGibs[0]],R=await s.getLatestAddr({addr:n,space:t});if(R){let Fn=await s.get({addr:R,space:t});B.push(Fn.ibGibs[0])}await(await G.sync({domainIbGibs:B,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:_,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:u,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i});let M=await G.getKnowledgeMap({space:t,metaspace:s,domainIbGibs:[a,z.r2_beta_v0_source]}),j=M[o],Q=M[n],ee=await s.get({addr:j,space:t}),Ae=await s.get({addr:Q,space:t}),Te=await Z({timeline:ee.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r3remote",dataToAddOrPatch:{fieldD:"remote_edit_r3"}},metaspace:s,space:t}),Ue=await Z({timeline:Ae.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r3remote",dataToAddOrPatch:{betaFieldB:"remote_beta_edit_r3"}},metaspace:s,space:t});h("4.10B Sync: Pushing remote Round 3 edits to server...");let Me=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),pe=new W;await Me.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await pe.sync({domainIbGibs:[Te,Ue],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:Me,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:u,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i}),h("4.10B Sync: Running Round 3 Client Sync (merging alpha & beta divergence)...");let et=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),he=new W;await et.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await he.sync({domainIbGibs:[$,T],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:et,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h("4.10B Sync: \u2713 Round 3 Sync complete."),u=await s.getLatestAddr({ibGib:z.domainI_initial,space:i}),g=await s.get({addr:u,space:i}),e=g.ibGibs[0],await s.put({ibGib:e,space:t}),await s.registerNewIbGib({ibGib:e,space:t}),h("4.10B Sync: Preparing Round 4 divergence (post-graft chain edits & new timeline)...");let lt=await he.getKnowledgeMap({space:i,metaspace:s,domainIbGibs:[a,z.r2_beta_v0_source]}),Gr=lt[o],br=lt[n],Kr=await s.get({addr:Gr,space:i}),gt=await s.get({addr:br,space:i}),go=await Z({timeline:Kr.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r4client_v5",dataToAddOrPatch:{fieldE:"source_edit_r4_v5"}},metaspace:s,space:i}),Xr=await F.firstGen({parentIbGib:q,ib:"timeline_root_gamma_4_10b",data:{gammaField:"gamma created on client",label:"GammaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),ye=Xr.newIbGib;await s.persistTransformResult({resTransform:Xr,space:i}),await s.registerNewIbGib({ibGib:ye,space:i});let Rt=be({ibGib:ye,defaultIfNone:"incomingAddr"});z.gamma_tjpAddr=Rt,Ns=y({ibGib:ye});let We=await lr({timeline:go,metaspace:s,space:i,rel8nInfos:[{rel8nName:Ls,ibGibs:[ye]}]}),Un=await Z({timeline:We,mut8Opts:{mut8Ib:a.ib+"_r4client_v7",dataToAddOrPatch:{fieldF:"source_edit_r4_v7"}},metaspace:s,space:i}),Mn=await Z({timeline:gt.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r4client_v2",dataToAddOrPatch:{betaFieldD:"source_beta_edit_r4_v2"}},metaspace:s,space:i});h("4.10B Sync: Updating remote space to Round 3 merged tips...");let rt=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),Ds=new W;await rt.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]});let ud=await s.getLatestAddr({addr:o,space:t}),Rs=[(await s.get({addr:ud,space:t})).ibGibs[0]],Ps=await s.getLatestAddr({addr:n,space:t});if(Ps){let Fn=await s.get({addr:Ps,space:t});Rs.push(Fn.ibGibs[0])}await(await Ds.sync({domainIbGibs:Rs,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:rt,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:u,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i});let ks=await Ds.getKnowledgeMap({space:t,metaspace:s,domainIbGibs:[a,z.r2_beta_v0_source]}),gd=ks[o],md=ks[n],Ed=await s.get({addr:gd,space:t}),wd=await s.get({addr:md,space:t}),yd=await Z({timeline:Ed.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r4remote_v5",dataToAddOrPatch:{fieldG:"remote_edit_r4_v5"}},metaspace:s,space:t}),$d=await Z({timeline:wd.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r4remote_v2",dataToAddOrPatch:{betaFieldC:"remote_beta_edit_r4_v2"}},metaspace:s,space:t});h("4.10B Sync: Pushing remote Round 4 edits to server...");let Bs=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),Id=new W;await Bs.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await Id.sync({domainIbGibs:[yd,$d],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:Bs,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:u,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i}),h("4.10B Sync: Running final Round 4 Client Sync (merging alpha, beta, and propagating gamma)...");let Us=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),Sd=new W;await Us.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await Sd.sync({domainIbGibs:[Un,Mn,ye],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:Us,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u=await s.getLatestAddr({ibGib:z.domainI_initial,space:i}),g=await s.get({addr:u,space:i}),e=g.ibGibs[0],z.domainI_latest=e,h("\u2713 4.10B Sync: All rounds of divergent edits and merges complete!"),r.textContent="\u2713 4.10B Sync Complete";let Ms=document.getElementById("btn-4-10b-check");Ms&&(Ms.disabled=!1)}catch(e){h(`\u2717 4.10B Sync FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(pd,"init4_10bSyncButton");function hd(){let r=document.getElementById("btn-4-10b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,h("4.10B Check: Verifying multi-round merged timelines on client and server...");let e=z.domainI_latest,t=z.alpha_tjpAddr,o=z.beta_tjpAddr,n=z.gamma_tjpAddr,a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=y({ibGib:z.domainI_initial}),c=await new W().getKnowledgeMap({space:s,metaspace:a,domainIbGibs:[z.domainI_initial]}),d=await a.getLatestAddr({addr:t,space:s}),l=await a.getLatestAddr({addr:o,space:s}),b=await a.getLatestAddr({addr:n,space:s});if(!d||!l||!b)throw new Error("Client space is missing timeline tips for Alpha, Beta, or Gamma.");let p=await a.get({addr:d,space:s}),u=await a.get({addr:l,space:s}),g=p.ibGibs[0],m=u.ibGibs[0];if(g.data?.fieldA!=="source_edit_r2")throw new Error(`Alpha fieldA mismatch! Expected 'source_edit_r2', got '${g.data?.fieldA}'`);if(g.data?.fieldB!=="remote_edit_r2")throw new Error(`Alpha fieldB mismatch! Expected 'remote_edit_r2', got '${g.data?.fieldB}'`);if(g.data?.fieldC!=="source_edit_r3")throw new Error(`Alpha fieldC mismatch! Expected 'source_edit_r3', got '${g.data?.fieldC}'`);if(g.data?.fieldD!=="remote_edit_r3")throw new Error(`Alpha fieldD mismatch! Expected 'remote_edit_r3', got '${g.data?.fieldD}'`);if(g.data?.fieldE!=="source_edit_r4_v5")throw new Error(`Alpha fieldE mismatch! Expected 'source_edit_r4_v5', got '${g.data?.fieldE}'`);if(g.data?.fieldF!=="source_edit_r4_v7")throw new Error(`Alpha fieldF mismatch! Expected 'source_edit_r4_v7', got '${g.data?.fieldF}'`);if(g.data?.fieldG!=="remote_edit_r4_v5")throw new Error(`Alpha fieldG mismatch! Expected 'remote_edit_r4_v5', got '${g.data?.fieldG}'`);if(h("4.10B Check: \u2713 Client Alpha merged tip contains all Round 2, 3, and 4 edits."),m.data?.betaFieldA!=="source_beta_edit_r3")throw new Error(`Beta betaFieldA mismatch! Expected 'source_beta_edit_r3', got '${m.data?.betaFieldA}'`);if(m.data?.betaFieldB!=="remote_beta_edit_r3")throw new Error(`Beta betaFieldB mismatch! Expected 'remote_beta_edit_r3', got '${m.data?.betaFieldB}'`);if(m.data?.betaFieldC!=="remote_beta_edit_r4_v2")throw new Error(`Beta betaFieldC mismatch! Expected 'remote_beta_edit_r4_v2', got '${m.data?.betaFieldC}'`);if(m.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error(`Beta betaFieldD mismatch! Expected 'source_beta_edit_r4_v2', got '${m.data?.betaFieldD}'`);h("4.10B Check: \u2713 Client Beta merged tip contains all Round 3 and 4 edits.");let E=g.rel8ns?.[Ls]||[];if(!xs)throw new Error("(UNEXPECTED) betaAddr falsy? (E: 81c032ae7a93bddfd8eed6664d314826)");if(!E.includes(xs))throw new Error("Client Alpha tip is missing relation to Beta timeline.");if(!Ns)throw new Error("(UNEXPECTED) gammaAddr falsy? (E: 12220a81d3b86385d1683d5a6bae5826)");if(!E.includes(Ns))throw new Error("Client Alpha tip is missing relation to Gamma timeline.");h("4.10B Check: \u2713 Client Alpha tip retains relation to Gamma.");let S=new J;h("4.10B Check: Fetching server timeline graphs...");let A=await S.getIbGibGraph(i,d,!0),I=await S.getIbGibGraph(i,l,!0);if(!A.success||!A.graph||!I.success||!I.graph)throw new Error("Failed to fetch merged graphs from server.");let $=A.graph[d],T=I.graph[l];if(!$||!T)throw new Error("Server is missing the final merged tips for Alpha or Beta.");if($.data?.fieldF!=="source_edit_r4_v7"||$.data?.fieldG!=="remote_edit_r4_v5")throw new Error("Server Alpha tip does not match final client merged state.");if(T.data?.betaFieldC!=="remote_beta_edit_r4_v2"||T.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error("Server Beta tip does not match final client merged state.");h("4.10B Check: \u2713 Server tips match client merged states perfectly."),h("\u2713 4.10B Check SUCCESS: Advanced multi-round/timeline conflict resolved and verified on both client and server!"),r.textContent="\u2713 4.10B Check Success"}catch(e){h(`\u2717 4.10B Check FAILED: ${w(e)}`),console.error(e),r.disabled=!1}})}f(hd,"init4_10bCheckButton");function i6(){let r=`${fe}[initDevTools]`;try{_l(),Al(),Sl(),Tl(),Gl(),Cl(),vl(),Ol(),Nl(),xl(),Ll(),Dl(),Rl(),Pl(),kl(),Bl(),Ul(),Ml(),Fl(),jl(),Vl(),Hl(),Kl(),Xl(),ql(),Wl(),Yl(),zl(),Jl(),Zl(),Ql(),ed(),td(),rd(),od(),nd(),ad(),sd(),ld(),dd(),fd(),bd(),pd(),hd()}catch(e){console.error(`${r} ${w(e)}`)}}f(i6,"initDevTools");export{f as a,Ge as b,H as c,oe as d,He as e,U as f,K as g,Ce as h,w as i,jn as j,ot as k,Eo as l,Gd as m,qs as n,Nr as o,re as p,q,ve as r,St as s,Ys as t,y as u,ae as v,Wt as w,Ee as x,Xn as y,$e as z,ue as A,De as B,nt as C,Ke as D,ge as E,Lr as F,Dr as G,xr as H,F as I,Fp as J,jp as K,Vp as L,Io as M,Nd as N,ei as O,ti as P,ah as Q,sh as R,ih as S,xd as T,ch as U,Jn as V,ra as W,Ld as X,mh as Y,Ao as Z,gr as _,bi as $,mi as aa,To as ba,Pd as ca,kd as da,Ru as ea,Pu as fa,ku as ga,Bu as ha,Uu as ia,Mu as ja,Vd as ka,Hd as la,Ii as ma,pa as na,Xd as oa,qd as pa,Pr as qa,Zr as ra,Oi as sa,rf as ta,Li as ua,Gg as va,Og as wa,te as xa,Xe as ya,ya as za,Ie as Aa,of as Ba,ko as Ca,Bo as Da,Fe as Ea,$a as Fa,Ri as Ga,Oe as Ha,Rr as Ia,to as Ja,Bi as Ka,Gt as La,Po as Ma,af as Na,sf as Oa,Vt as Pa,om as Qa,cf as Ra,lf as Sa,df as Ta,st as Ua,ff as Va,bf as Wa,pf as Xa,mt as Ya,Em as Za,Ji as _a,Qr as $a,vt as ab,bt as bb,Zi as cb,be as db,qe as eb,Qt as fb,Cm as gb,wf as hb,vm as ib,Om as jb,Nm as kb,xm as lb,no as mb,_m as nb,Ym as ob,zm as pb,Jm as qb,Zm as rb,Qm as sb,kr as tb,$f as ub,If as vb,Sf as wb,Er as xb,V as yb,_f as zb,bc as Ab,fc as Bb,Tf as Cb,Gf as Db,Cf as Eb,vf as Fb,Of as Gb,Nf as Hb,xf as Ib,Lf as Jb,Ra as Kb,xa as Lb,jo as Mb,Df as Nb,Rf as Ob,ec as Pb,Pf as Qb,uc as Rb,kf as Sb,Bf as Tb,XE as Ub,Fa as Vb,ja as Wb,Nt as Xb,se as Yb,$l as Zb,_r as _b,yb as $b,Ts as ac,lr as bc,ws as cc,Z as dc,ib as ec,Ir as fc,Sr as gc,ns as hc,rr as ic,Gn as jc,H4 as kc,h as lc,i6 as mc};
|
|
42
|
+
//# sourceMappingURL=chunk-NCXKCVYS.mjs.map
|