@ibgib/space-gib 0.0.34 → 0.0.36
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/dist/client/bootstrap.mjs +1 -1
- package/dist/client/{chunk-25PXC4HP.mjs → chunk-5DTAUY3E.mjs} +1586 -464
- package/dist/client/chunk-J7X3XTAI.mjs +53 -0
- package/dist/client/css/activity-bar.css +21 -3
- package/dist/client/css/layout.css +126 -5
- package/dist/client/css/tutorial.css +327 -0
- package/dist/client/index.html +6 -0
- package/dist/client/index.mjs +22 -45
- package/dist/client/privacy.html +22 -22
- package/dist/client/script.mjs +1 -1
- package/dist/client/style.css +1 -0
- package/dist/server/server.mjs +3 -3
- package/package.json +6 -6
- package/src/client/AUTO-GENERATED-version.mts +1 -1
- package/src/client/cosmos/seed-cosmos-workspace.mts +20 -6
- package/src/client/css/activity-bar.css +21 -3
- package/src/client/css/layout.css +126 -5
- package/src/client/css/tutorial.css +327 -0
- package/src/client/dev-tools/vcs-workspace.mts +4 -4
- package/src/client/index.html +6 -0
- package/src/client/privacy.html +22 -22
- package/src/client/style.css +1 -0
- package/src/client/ui/component/changes/changes.css +413 -0
- package/src/client/ui/component/changes/changes.html +37 -0
- package/src/client/ui/component/changes/changes.mts +766 -0
- package/src/client/ui/component/changes/index.mts +9 -0
- package/src/client/ui/component/chat-view/chat-view.html +6 -58
- package/src/client/ui/component/chat-view/chat-view.mts +13 -26
- package/src/client/ui/component/clone/clone.mts +67 -39
- package/src/client/ui/component/code-editor/code-editor.css +91 -9
- package/src/client/ui/component/code-editor/code-editor.html +58 -45
- package/src/client/ui/component/code-editor/code-editor.mts +265 -49
- package/src/client/ui/component/cosmos-navigator/cosmos-navigator.css +1 -1
- package/src/client/ui/component/cosmos-navigator/cosmos-navigator.html +5 -10
- package/src/client/ui/component/cosmos-navigator/cosmos-navigator.mts +328 -64
- package/src/client/ui/component/file-explorer/file-explorer.css +475 -11
- package/src/client/ui/component/file-explorer/file-explorer.html +45 -65
- package/src/client/ui/component/file-explorer/file-explorer.mts +1164 -98
- package/src/client/ui/component/nested-chat/chat/chat.mts +5 -90
- package/src/client/ui/component/nested-chat/nested-chat.mts +10 -8
- package/src/client/ui/component/timeline/timeline.css +16 -1
- package/src/client/ui/component/timeline/timeline.mts +37 -93
- package/src/client/ui/component/tutorial/index.mts +9 -0
- package/src/client/ui/component/tutorial/scripts/pitch-tour-script.mts +265 -0
- package/src/client/ui/component/tutorial/tutorial-controller.mts +622 -0
- package/src/client/ui/component/tutorial/tutorial-types.mts +45 -0
- package/src/client/ui/component/tutorial/tutorial.css +260 -0
- package/src/client/ui/router/space-gib-router-helpers.mts +33 -233
- package/src/client/ui/router/space-gib-router-helpers.respec.mts +298 -122
- package/src/client/ui/router/space-gib-router-service.mts +28 -151
- package/src/client/ui/router/space-gib-router-types.mts +32 -76
- package/src/client/ui/shell/cosmic-big-bang.mts +12 -3
- package/src/client/ui/shell/space-gib-shell-service.mts +715 -143
- package/dist/client/chunk-RXWLL2AI.mjs +0 -30
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
var rh=Object.defineProperty;var h=(o,e)=>rh(o,"name",{value:e,configurable:!0});var Ie=/^[a-zA-Z0-9_\-.]{1,256}$/,ar=/^[a-zA-Z0-9_]{1,255}$/,rl=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,ol=/^(\[.+\]).+$/,nl=/^[0-9a-fA-F]{32}$/,al=/^[0-9a-fA-F]{64}$/;var to="/",sl="_nonalphanumerics_";var ro=!1,Ms=globalThis.crypto,{subtle:nh}=Ms,dt={sha_256:"SHA-256",sha_512:"SHA-512"};function B(o){return JSON.parse(JSON.stringify(o))}h(B,"clone");function rt(o){return(o??new Date).toUTCString()}h(rt,"getTimestamp");var ah=Array.from({length:256},(o,e)=>e.toString(16).padStart(2,"0"));async function te({s:o,algorithm:e="SHA-256"}){if(o==null)return"";try{let t=Object.values(dt);if(!t.includes(e))throw new Error(`Only ${t} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let r=new TextEncoder().encode(o),n=await nh.digest(e,r),a=new Uint8Array(n),s="";for(let i=0;i<a.length;i++)s+=ah[a[i]];return s}catch(t){throw console.error(E(t.message)),t}}h(te,"hash");async function q(o){if(!globalThis.crypto)throw new Error("globalThis.crypto falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)");let e;if(o&&o>16||!globalThis.crypto.randomUUID){if(!globalThis.crypto.getRandomValues)throw new Error("globalThis.crypto.getRandomValues falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: d2fa34b26d0808adc8184d98cc767d26)");o||=32;let t=Ms.getRandomValues(new Uint8Array(o)),r="";for(let n=0;n<t.length;n++)r+=String.fromCharCode(t[n]);e=await te({s:r})}else{if(!globalThis.crypto.randomUUID)throw new Error("globalThis.crypto.randomUUID falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: e30da81f5c284d6a389930b5e7daa826)");let t=Ms.randomUUID();e=await te({s:t})}if(!e)throw new Error("(UNEXPECTED) uuid falsy? could not create uuid? (E: 5276bcc4e8f75aa2c82a54a8c8b2d626)");return e}h(q,"getUUID");function X(o){return JSON.stringify(o,null,2)}h(X,"pretty");async function De(o){return new Promise(e=>{setTimeout(()=>{e()},o)})}h(De,"delay");function E(o){return!o&&o!==0?"[error is falsy]":typeof o=="string"?o:typeof o.message=="string"?o.message:typeof o=="number"?JSON.stringify(o):o.error?(console.warn(`[${E.name}] this fn takes the raw error object. no destructure required. change your call from extractErrorMsg({error}) to extractErrorMsg(error). (W: ea49af5fd76d4b80a55a108d73a3e9b4)`),E(o.error)):`[error is not a string and error.message is not a string. typeof error: ${typeof o} (E: d5a7723ca59646838308bc9e53a43134)]`}h(E,"extractErrorMsg");function Uo({items:o,keyFn:e}){let t=`[${Uo.name}]`;try{let r={};for(let n=0;n<o.length;n++){let a=o[n],s=e(a);r[s]=[...r[s]??[],a]}return r}catch(r){throw console.error(`${t} ${r.message}`),r}}h(Uo,"groupBy");function On({min:o,max:e,chars:t,noSpaces:r}){return o=o??1,e=e??999999999999,t=t??"",r?new RegExp(`^[\\w${t}]{${o},${e}}$`):new RegExp(`^[\\w\\s${t}]{${o},${e}}$`)}h(On,"getRegExp");function ft(o){let e;if(o){if(e=new Date(o),e.toString()==="Invalid Date")throw new Error(`invalid date created by timestamp (${o}) (E: cbd6aeefe00708184e276ea3c2532b22)`)}else e=new Date;return e.getTime().toString()}h(ft,"getTimestampInTicks");function Fs({startDate:o,years:e,months:t,days:r,hours:n,seconds:a}){let s=`[${Fs.name}]`;try{return Dr({startDate:o,years:e,months:t,days:r,hours:n,seconds:a}).toUTCString()}catch(i){throw console.log(`${s} ${i.message}`),i}}h(Fs,"getExpirationUTCString");function Dr({startDate:o,years:e,months:t,days:r,hours:n,seconds:a}){let s=`[${Dr.name}]`;try{if(!o&&!e&&!t&&!r&&!n&&!a)throw new Error("either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)");o=o?new Date(o):new Date;let i,c;return e?(i=o.getFullYear()+e,c=o.setFullYear(i),Dr({startDate:new Date(c),months:t,days:r,hours:n,seconds:a})):t?(i=o.getMonth()+t,c=o.setMonth(i),Dr({startDate:new Date(c),years:e,days:r,hours:n,seconds:a})):r?(i=o.getDate()+r,c=o.setDate(i),Dr({startDate:new Date(c),years:e,months:t,hours:n,seconds:a})):n?(i=o.getHours()+n,c=o.setHours(i),Dr({startDate:new Date(c),years:e,months:t,days:r,seconds:a})):a?(i=o.getSeconds()+a,c=o.setSeconds(i),Dr({startDate:new Date(c),years:e,months:t,days:r,hours:n})):o}catch(i){throw console.log(`${s} ${i.message}`),i}}h(Dr,"addTimeToDate");function Bs({expirationTimestampUTC:o}){let e=`[${Bs.name}]`;try{if(!o)throw new Error("expirationTimestampUTC required (E: 5eeb1e29f93d64f70c71a8112080a222)");let t=new Date(o);if(t.toUTCString()==="Invalid Date")throw new Error(`invalid expirationTimestampUTC: ${o} (E: 66a1a165bcf1f9336fe78856ab777822)`);return t<new Date}catch(t){throw console.error(`${e} ${t.message}`),t}}h(Bs,"isExpired");function jt(o){return Array.from(new Set(o))}h(jt,"unique");function ks({obj:o,value:e,path:t,pathDelimiter:r,logalot:n}){let a=`[${ks.name}]`;try{if(n&&console.log(`${a} starting...`),!o)throw new Error("obj required (E: 6a9dd32a361476e80b1bf7b91ec50522)");if(typeof o!="object")throw new Error("obj must be type 'object' (E: 66fdc289b32c06492bd95f5d266e6a22)");if(!t)throw new Error("path required (at the very least should be the key in the root obj.) (E: fc779e7794ead8a0b44e5f2e776b0e22)");r=r||to;let s=o,i=t.split(r).filter(l=>!!l),c=i.pop();i.forEach(l=>{let d=s[l];if(d){if(typeof d!="object")throw new Error(`invalid path into object. Each step along the path must be typeof === 'object', but typeof targetObj["${l}"] === ${typeof d}. (value: ${d}) (E: 38cf29c5f624a40b4b56502c2ec39d22)`)}else s[l]={};s=s[l]}),s[c]=e}catch(s){throw console.error(`${a} ${s.message}`),s}finally{n&&console.log(`${a} complete.`)}}h(ks,"patchObject");async function Mo({n:o}){let e=`[${Mo.name}]`;try{ro&&console.log(`${e} starting...`);let t=[];for(let r=0;r<o;r++){let n=await q();t.push(n.substring(0,16))}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ro&&console.log(`${e} complete.`)}}h(Mo,"getIdPool");function bt({text:o,length:e,keepLiterals:t=["-"],replaceMap:r}){let n=`[${bt.name}]`;try{if(ro&&console.log(`${n} starting... (I: 27437e312e5aa621adfebb84e059c822)`),!o)throw new Error("text required (E: 87e0493613c8b30dfade83e1d2862a22)");let a=o,s={};t=t??[];for(let c=0;c<t.length;c++){let l=t[c],d;do d=il({count:10});while(d.includes(l)||l.includes(d)||o.includes(d));if(a.includes(l))for(s[d]=l;a.includes(l);)a=a.replace(l,d)}if(r&&Object.keys(r).length>0)for(let c=0;c<Object.keys(r).length;c++){let l=Object.keys(r)[c],d=r[l];for(;a.includes(l);)a=a.replace(l,d)}a=a.replace(/\W/g,"");let i=Object.keys(s);for(let c=0;c<i.length;c++){let l=i[c];for(;a.includes(l);)a=a.replace(l,s[l])}return e&&e>0&&a.length>e&&(ro&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),a=a.substring(0,e)),a.length===0&&(a=sl),a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{ro&&console.log(`${n} complete.`)}}h(bt,"getSaferSubstring");function sh({x:o}){if((o??[]).length===0)return;let e=Math.floor(Math.random()*o.length);return o[e]}h(sh,"pickRandom");function il({count:o}){let e=`${il.name}]`;try{if(!Number.isInteger(o))throw new Error("count required to be a number. (E: c0a21d884ebd9afc4b2e8025207e0522)");let t="";for(let r=0;r<o;r++)t+=sh({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!==o)throw new Error(`${e} (UNEXPECTED) result.length !== count ? (E: 9bec4ec8f78610d8055e565415392a22)`);return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ro&&console.log(`${e} complete.`)}}h(il,"pickRandom_Letters");function oo({dominant:o,recessive:e}){let t=`[${oo.name}]`;try{if(Array.isArray(o)&&Array.isArray(e)){let r=B(o),n=!1;return e.forEach(a=>{if(typeof a=="string")r.includes(a)||r.push(a);else{n||(console.warn(`${t} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`),n=!0);let s=JSON.stringify(a);r.some(i=>JSON.stringify(i)===s)||r.push(a)}}),r}else if(typeof o=="object"&&typeof e=="object"){let r={...e},n=Object.keys(o),a=Object.keys(e);return n.forEach(s=>{a.includes(s)?Array.isArray(o[s])&&Array.isArray(e[s])?r[s]=oo({dominant:o[s],recessive:e[s]}):o[s]&&!Array.isArray(o[s])&&typeof o[s]=="object"&&e[s]&&!Array.isArray(e[s])&&typeof e[s]=="object"?r[s]=oo({dominant:o[s],recessive:e[s]}):r[s]=o[s]:r[s]=o[s]}),r}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)`),o}catch(r){throw console.error(`${t} ${r.message}`),r}}h(oo,"mergeMapsOrArrays_Naive");var ih=globalThis.crypto,{subtle:dl}=ih,fl=new Array(256);for(let o=0;o<256;++o)fl[o]=o.toString(16).padStart(2,"0");function bl(o){let e=new Uint8Array(o),t="";for(let r=0;r<e.length;r++)t+=fl[e[r]];return t}h(bl,"bufToHex");function Bo(o){if(o===null||typeof o!="object")return o;if(Array.isArray(o))return o.map(r=>Bo(r));let e={},t=Object.keys(o).sort();for(let r of t){let n=o[r];n!==void 0&&(e[r]=Bo(n))}return e}h(Bo,"toNormalizedForHashing");async function Fo(o){if(!o)return"";let e=new TextEncoder().encode(o),t=await dl.digest("SHA-256",e);return bl(t)}h(Fo,"hashToHex");async function ch(o,e){let t;if(o){let n=new TextEncoder().encode(o);t=new Uint8Array(n.length+e.length),t.set(n),t.set(e,n.length)}else t=e;let r=await dl.digest("SHA-256",t);return bl(r)}h(ch,"hashToHex_Uint8Array");var lh=!1,Ln=0,cl=0;async function ll(o,e=""){let t=e||"",r=o.ib,n=o.data,a=o.rel8ns,s=Object.keys(a||{}).length>0&&Object.keys(a||{}).some(b=>a[b]&&a[b].length>0),i=!!n;i&&(typeof n=="string"?i=n.length>0:n instanceof Uint8Array?i=!0:typeof n=="object"?i=Object.keys(n||{}).length>0:i=!0);let c=(await Fo(t?t+r:r)).toUpperCase(),l="";if(s){let b=Bo(a),p=JSON.stringify(b);l=(await Fo(t?t+p:p)).toUpperCase()}let d="";if(i)if(n instanceof Uint8Array)d=(await ch(t,n)).toUpperCase();else{let b=Bo(n),p=JSON.stringify(b);d=(await Fo(t?t+p:p)).toUpperCase()}let f;if(s||i){let b=c+l+d;f=(await Fo(t?t+b:b)).toUpperCase()}else f=(await Fo(t?t+c:c)).toUpperCase();return f}h(ll,"sha256v1_Internal");async function Dt(o,e=""){if(lh){let t=globalThis.performance?globalThis.performance.now():Date.now(),r=await ll(o,e),n=(globalThis.performance?globalThis.performance.now():Date.now())-t;return Ln++,cl+=n,Ln%1e3===0&&console.log(`[sha256v1 Profile] Total Runs: ${Ln} | Average Duration: ${(cl/Ln).toFixed(4)} ms`),r}return ll(o,e)}h(Dt,"sha256v1");function I({ib:o,gib:e,ibGib:t,delimiter:r="^"}){return o=o||t?.ib||"",e=e||t?.gib||"",o+r+e}h(I,"getIbGibAddr");function K({ibGib:o,ibGibAddr:e,delimiter:t="^"}){let r="[getIbAndGib]";if(!e)if(o)e=I({ibGib:o});else throw new Error(`${r} We need either an address or an ibGib object`);if(!e)throw new Error(`${r} 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(`${r} 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]})}h(K,"getIbAndGib");var Se;(function(o){o.past="past",o.ancestor="ancestor",o.dna="dna",o.identity="identity",o.tjp="tjp",o.secret="secret",o.encryption="encryption"})(Se||(Se={}));var no="ib",Q="gib",ue={ib:no,gib:Q},Ue="^",vt=".",hl="ib^gib",sr=["past","ancestor","dna","tjp"],dh=155,pl=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${dh}}$`);async function vr(o){let e=B(o),t=`[${vr.name}]`;e.srcAddr&&delete e.srcAddr,delete e.src;let r={ib:e.type,data:e,rel8ns:{ancestor:[`${e.type.toString()}${Ue}${Q}`]}};return r.gib=await Dt(r),r}h(vr,"buildDna");function ko({ibGib:o}){let e=`[${ko.name}]`;try{if(!o)throw new Error("ibGib required.");let t=["fork","mut8","rel8","plan"].map(n=>`${n}^${Q}`);return o.rel8ns&&o.rel8ns.ancestor&&Array.isArray(o.rel8ns.ancestor)&&o.rel8ns.ancestor.some(n=>t.includes(n))||!1}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(ko,"isDna");function Ce({ibGib:o,gib:e}){return o?Ce({gib:o.gib}):e?e===Q:!0}h(Ce,"isPrimitive");async function ee({ibGib:o,hasTjp:e,tjpAddr:t,gibDelimiter:r,isPrimitive:n,hashAlgorithm:a}){let s=`[${ee.name}]`;try{if(!o)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return Q;let i=await Dt(o,""),c=o.rel8ns??{},l=o.data??{};if(r=r||vt,e||(e=(c.tjp??[]).length>0||l.isTjp||!1),e){let d;if(c.tjp)if(c.tjp.length===1)if(c.tjp[0])t=c.tjp[0];else throw new Error("rel8ns.tjp[0] is falsy. (E: ed879d2b039543f8b1902e8b7b5a5a7b)");else if(c.tjp.length>1)if(c.tjp[c.tjp.length-1])console.warn(`${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(l.isTjp)t=I({ib:o.ib,gib:i});else throw new Error("hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)");if(d=t?K({ibGibAddr:t}).gib:void 0,d)return l.isTjp?i:`${i}${vt}${d}`;throw new Error("hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)")}else return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}h(ee,"getGib");function Ne({ibGibAddr:o,gib:e,gibDelimiter:t}){let r=`[${Ne.name}]`;try{if(!o&&!e)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(e=e||K({ibGibAddr:o}).gib,e===Q)return{isPrimitive:!0};if(t=t??vt,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(`${r} 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(`${r} ${E(n)}`),n}}h(Ne,"getGibInfo");async function Rn(o){let{noTimestamp:e,dna:t,linkedRel8ns:r,destIb:n,uuid:a,tjp:s,cloneRel8ns:i,cloneData:c,type:l="fork"}=o,d=o.src,f="[fork_v1]";if(l!=="fork")throw new Error(`${f} not a fork transform.`);if(o.type||(o.type="fork"),!d)throw new Error(`${f} src required to fork.`);if(!d.ib)throw new Error(`${f} src.ib required.`);if(n&&n.includes(Ue))throw new Error(`${f} destIb can't contain (hardcoded) delimiter right now.`);if(!d.gib)throw new Error(`${f} src.gib required.`);let b={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(b.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(b.rel8ns=d.rel8ns),d=b;let p=I({ib:d.ib,gib:d.gib});o.srcAddr=p;let u=i&&d.rel8ns&&Object.keys(d.rel8ns).length>0?B(d.rel8ns):{};delete u.past;let m=c&&d?.data?B(d.data):{};o.nCounter&&(m.n=0);let g=r?.includes(Se.ancestor)?[p]:(u.ancestor||[]).concat([p]);u.ancestor=g,u.tjp&&delete u.tjp;let y=B(d);if(e&&s?.timestamp)throw new Error(`${f} both noTimestamp and tjp.timestamp selected.`);if(!e||s?.timestamp){let G=new Date;m.timestamp=rt(G),m.timestampMs=G.getMilliseconds()}(s?.uuid||a)&&(m.uuid=await q()),s?.uuid||s?.timestamp?m.isTjp=!0:m.isTjp&&delete m.isTjp,y.ib=n||"ib",p!==hl&&(y.rel8ns=u),Object.keys(m).length>0&&(y.data=m);let w=null;if(t){w=await vr(o);let G=I({ibGib:w});u.dna=r?.includes(Se.dna)?u.dna=[G]:u.dna=(u.dna||[]).concat(G)}y.gib=await Dt(y,"");let A={newIbGib:y};return w&&(A.dnas=[w]),A}h(Rn,"fork");async function Ae(o){let{noTimestamp:e,dna:t,linkedRel8ns:r,dataToRename:n,dataToRemove:a,dataToAddOrPatch:s,mut8Ib:i,type:c="mut8"}=o,l=o.src,d="[mut8_v1]";if(c!=="mut8")throw new Error(`${d} not a mut8 transform.`);if(o.type||(o.type="mut8"),!l)throw new Error(`${d} src required to mut8.`);if(!l.ib)throw new Error(`${d} src.ib required.`);if(l.ib.includes(Ue))throw new Error(`${d} ib can't contain hardcoded delimiter (${Ue}) right now.`);if(!l.gib)throw new Error(`${d} src.gib required.`);if(!i&&!n&&!a&&!s)throw new Error(`${d} gotta provide either a mut8Ib or some data to change.`);let f=I({ib:l.ib,gib:l.gib});if(o.srcAddr&&f!==o.srcAddr)throw new Error(`${d} srcAddr from src does not equal opts.srcAddr`);if(o.srcAddr=f,Ce({ibGib:l}))throw new Error(`${d} cannot mutate primitive ibgib`);let b={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(b.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(b.rel8ns=l.rel8ns),l=b;let p=B(l),u=l.rel8ns?l.rel8ns:{},m=B(u);m.past=r?.includes(Se.past)?[f]:(m.past||[]).concat([f]);let g=l?.data?B(l.data):{};if(n&&(g=js(g,n,"rename")),a&&(g=js(g,a,"remove")),s&&(g=ul(g,s)),!e){let T=new Date;g.timestamp=rt(T),g.timestampMs=T.getMilliseconds()}if(o.nCounter||Object.keys(g).includes("n"))if(Object.keys(g).includes("n"))if(Number.isInteger(g.n))g.n>=0?g.n=g.n+1:(console.warn(`${d} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),g.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else g.n=0;if(g.isTjp){let T=m.tjp??[];T.push(f),m.tjp=T,delete g.isTjp}let w=null;if(t){w=await vr(o);let T=I({ibGib:w});m.dna=r?.includes(Se.dna)?m.dna=[T]:m.dna=(m.dna||[]).concat(T)}p.ib=i||p.ib,p.rel8ns=m,Object.keys(g).length>0?p.data=g:delete p.data;let A=(m.tjp?.length??0)>0;p.gib=await ee({ibGib:p,hasTjp:A});let G={newIbGib:p};return w&&(G.dnas=[w]),G}h(Ae,"mut8");function js(o,e,t){let r="[renameOrRemove]",n=["timestamp"];return Object.keys(e).forEach(a=>{if(n.includes(a))throw new Error(`${r} Cannot rename to ${a}.`);if(Object.keys(o).includes(a)){let s=e[a];if(typeof s=="string"){if(n.includes(s))throw new Error(`${r} Cannot rename to ${s}.`);t==="rename"&&(o[s]=o[a]),delete o[a]}else o[a]=js(o[a],s,t)}else console.log(`${r} key to ${t} does not exist`)}),o}h(js,"renameOrRemove");function ul(o,e){return Object.keys(e).forEach(t=>{let r=e[t],n=o[t];n?Array.isArray(r)||Array.isArray(n)?o[t]=r:typeof r=="object"&&typeof n=="object"?o[t]=ul(n,r):o[t]=r:o[t]=r}),o}h(ul,"patch");async function ie(o){let{noTimestamp:e,dna:t,linkedRel8ns:r,rel8nsToAddByAddr:n,rel8nsToRemoveByAddr:a,rel8nsToReplaceByAddr:s,type:i="rel8"}=o,c=o.src,l="[rel8_v1]";if(i!=="rel8")throw new Error(`${l} not a rel8 transform.`);if(o.type||(o.type="rel8"),i!=="rel8")throw new Error(`${l} not a rel8 transform.`);if(o.type||(o.type="rel8"),!c)throw new Error(`${l} src required.`);if(!c.ib)throw new Error(`${l} src.ib required.`);if(c.ib.includes(Ue))throw new Error(`${l} ib can't contain hardcoded delimiter (${Ue}) right now.`);if(!c.gib)throw new Error(`${l} src.gib required.`);if(Ce({ibGib:c}))throw new Error(`${l} cannot relate/unrelate primitive ibgib`);let d=n&&Object.keys(n).length>0,f=a&&Object.keys(a).length>0,b=s&&Object.keys(s).length>0;if(!(d||f||b))throw new Error(`${l} gotta provide relations to add, remove, or replace.`);let p=I({ib:c.ib,gib:c.gib});if(o.srcAddr&&p!==o.srcAddr)throw new Error(`${l} srcAddr from src does not equal opts.srcAddr`);o.srcAddr=p;let u=h($=>$&&typeof $=="string"&&$.length>=2&&$.includes("^")&&$.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map($=>(n||{})[$]).forEach($=>{if(!($&&$.every(_=>u(_))))throw new Error(`${l} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(a||{}).map($=>(a||{})[$]).forEach($=>{if(!($&&$.every(_=>u(_))))throw new Error(`${l} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(s||{}).map($=>(s||{})[$]).forEach($=>{if(!($&&$.every(_=>_&&u(_.oldAddr)&&u(_.newAddr))))throw new Error(`${l} Invalid replace rel8n attempt. Must be valid ibGibs with oldAddr and newAddr. Did you include a delimiter (^)?`)});let m={ib:c.ib,gib:c.gib};c.data&&Object.keys(c.data).length>0&&(m.data=c.data),c.rel8ns&&Object.keys(c.rel8ns).length>0&&(m.rel8ns=c.rel8ns),c=m;let g=B(c),y=B(c.data||{});if(o.nCounter||Object.keys(y).includes("n"))if(Object.keys(y).includes("n"))if(Number.isInteger(y.n))y.n>=0?y.n=y.n+1:(console.warn(`${l} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),y.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else y.n=0;if(!e){let $=new Date;y.timestamp=rt($),y.timestampMs=$.getMilliseconds()}let w=B(c.rel8ns||{});if(Object.keys(s||{}).forEach($=>{if(sr.includes($))throw new Error(`${l} Cannot manually replace relationship: ${$}.`);let _=w[$]||[],S=s[$]||[],D=[..._];for(let C of S){let{oldAddr:N,newAddr:x}=C,L=!1;for(let U=0;U<D.length;U++)D[U]===N&&(D[U]=x,L=!0);if(!L)throw new Error(`${l} Cannot replace oldAddr '${N}' in rel8n '${$}' - oldAddr not found in existing relationships.`)}w[$]=D}),Object.keys(n||{}).forEach($=>{if(sr.includes($))throw new Error(`${l} Cannot manually add relationship: ${$}.`);let _=w[$]||[],D=n[$].filter(C=>!_.includes(C));w[$]=_.concat(D)}),Object.keys(a||{}).forEach($=>{if(sr.includes($))throw new Error(`${l} Cannot manually remove relationship: ${$}.`);let _=w[$]||[],S=a[$]||[],D=_.filter(C=>!S.includes(C));D.length>0?w[$]=D:delete w[$]}),w.past=(w.past||[]).concat([p]),(r||[]).filter($=>Object.keys(w).includes($)).filter($=>(w[$]||[]).length>1).forEach($=>{let _=w[$].length;w[$]=[w[$][_-1]]}),y.isTjp){let $=w.tjp||[];$.push(p),w.tjp=$,delete y.isTjp}g.data=y,g.rel8ns=w;let A=(w.tjp?.length??0)>0,G=null;if(t){G=await vr(o);let $=I({ibGib:G});w.dna=r?.includes(Se.dna)?w.dna=[$]:w.dna=(w.dna||[]).concat($)}g.gib=await ee({ibGib:g,hasTjp:A});let T={newIbGib:g};return G&&(T.dnas=[G]),T}h(ie,"rel8");function Un({ibGib:o}){let e=`[${Un.name}]`;if(!o)return console.warn(`${e} ibGib falsy. (W: 884178562f5b4f15933ac4d98db74cc6)`),!1;if(o.data?.isTjp||o.rel8ns?.tjp?.length>0)return!0;let t=["fork^gib","mut8^gib","rel8^gib"];return(o.rel8ns?.ancestor??[]).some(n=>t.includes(n))?!1:o.gib?o.gib.includes(vt)?!0:o.gib===Q?!1:!!Ne({ibGibAddr:I({ibGib:o})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}h(Un,"hasTjp");function Mn({ibGib:o}){let e=`[${Mn.name}]`;o.ib||console.warn(`${e} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),o.gib||console.warn(`${e} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let t={ib:(o.ib||"").slice()};return o.gib&&(t.gib=o.gib.slice()),o.data&&(t.data=o.data instanceof Uint8Array?o.data:B(o.data)),o.rel8ns&&(t.rel8ns=B(o.rel8ns)),t}h(Mn,"toDto");var qs=!1;async function ne({ibGib:o}){let e=`[${ne.name}]`;try{let t=[];if(o){let r=I({ibGib:o});if(t=qt({addr:r})??[],t.length>0)return console.error(`${e} errors found in addr: ${r}`),t;if(Ce({gib:o.gib}))return null;let n=await ee({ibGib:Mn({ibGib:o}),hasTjp:Un({ibGib:o})});return n!==o.gib&&(o.data?.src&&o.data.srcAddr&&o.ib==="rel8"?(delete o.data.src,delete o.data.srcAddr,n=await ee({ibGib:Mn({ibGib:o}),hasTjp:Un({ibGib:o})}),n!==o.gib&&t.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${o.gib}). (E: 020b71479e944b2198fe436e7e137786)`)):t.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${o.gib}). (E: 7416db016878430ca3c5b20697f164ed)`)),t.length>0?t:null}else return t.push("ibGib is itself falsy. (E: 4fb98caf6ed24ef7b35a19cef56e2d7e)"),t}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(ne,"validateIbGibIntrinsically");function qt({addr:o,delimiter:e,version:t}){let r=`[${qt.name}]`;try{let n=[];if(t&&console.warn(`${r} version not implemented yet. Ignoring. (W: 2d19db16ec0c4766b5d35248787671f3)`),!o)return n.push("addr required. (E: e9a54041aa0b41c1bb2324d9d2d42c7f)"),n;e=e||Ue,o.includes(e)||n.push(`No delimiter (${e}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`),o.startsWith(e)&&n.push("addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)");let{ib:a,gib:s}=K({ibGibAddr:o,delimiter:e}),i=cr({ib:a,ibGibAddrDelimiter:e,version:t});i&&(n=n.concat(i));let c=ir({gib:s,ibGibAddrDelimiter:e,version:t});return c&&(n=n.concat(c)),n.length>0&&qs&&console.log(`${r} errors.length > 0. errors: ${n.join("|")} (I: 9c18f993e138f15613e4c6a340d41722)`),n.length>0?n:null}catch(n){throw console.error(`${r} ${E(n)}`),n}}h(qt,"validateIbGibAddr");function cr({ib:o,ibGibAddrDelimiter:e,version:t}){let r=`[${cr.name}]`;try{let n=[];return t&&console.warn(`${r} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),o?o===no?null:(e=e||Ue,o.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(`${r} ${E(n)}`),n}}h(cr,"validateIb");function ir({gib:o,gibDelimiter:e,ibGibAddrDelimiter:t,version:r}){let n=`[${ir.name}]`;try{let a=[];if(r&&console.warn(`${n} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`),!o)return a.push("gib required. (E: e217de4035b04086827199f4bace189c)"),a;t=t||Ue;let s=[t],i=[];s.forEach(p=>{o.includes(p)&&i.push(p)}),i.length>0&&a.push(`gib (${o}}) contains invalid characters: (${JSON.stringify(i.join(","))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);let{punctiliarHash:c,tjpGib:l,isPrimitive:d}=Ne({gib:o,gibDelimiter:e||vt});if(d)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let f=c.match(nl),b=c.match(al);if(!f&&!b&&a.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),l){let p=ir({gib:l});(p??[]).length>0&&a.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${p.join(". ")}`)}return a.length>0?a:null}catch(a){throw console.error(`${n} ${E(a)}`),a}}h(ir,"validateGib");function Xs({rel8ns:o}){let e=`[${Xs.name}]`;try{qs&&console.log(`${e} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`);let t=[],r=Object.keys(o);for(let n=0;n<r.length;n++){let a=Object.keys(o)[n];typeof a!="string"&&t.push("non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)");let s=o[a]??[];for(let i=0;i<s.length;i++){let c=s[i],l=qt({addr:c})??[];l.length>0&&t.push(`invalid addr found for rel8nName (${a}). addr errors: ${l.join("|")} (E: 56809a746c4f462db426e90395b80364)`)}}return t.length>0?t:null}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{qs&&console.log(`${e} complete.`)}}h(Xs,"validateRel8nsIntrinsically");var ml=!1,H=class o{static{h(this,"Factory_V1")}static root(){return o.primitive({ib:no})}static primitive({ib:e}){return{ib:e,gib:Q}}static primitives({ibs:e}){return e.map(t=>o.primitive({ib:t}))}static async firstGen({ib:e=no,parentIbGib:t=o.root(),data:r,rel8ns:n,dna:a,tjp:s,linkedRel8ns:i,noTimestamp:c,nCounter:l,squash:d}){let f=`[${o.name}][${o.firstGen.name}]`;try{if(ml&&console.log(`${f} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),a&&d)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let b=[],p=t||ue,u=await Rn({src:p,destIb:e,tjp:s,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:l});if(b.push(u),p=u.newIbGib,r){let m=await Ae({src:p,dataToAddOrPatch:r,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:l});b.push(m),p=m.newIbGib}if(n){let m=await ie({src:p,rel8nsToAddByAddr:n,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:l});b.push(m)}if(b.length>1){let m=b.slice(b.length-1)[0].newIbGib,g={newIbGib:m,intermediateIbGibs:b.slice(0,b.length-1).map(y=>y.newIbGib)};if(a){d&&`${f}`;let y=[];return b.forEach(w=>{y=y.concat(w.dnas)}),g.dnas=y,g}else if(d){if(!m.rel8ns)throw new Error("(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)");return delete m.rel8ns.past,m.rel8ns.tjp&&(delete m.rel8ns.tjp,m.data??={},m.data.isTjp=!0),l&&(m.data??={},m.data.n=0),m.gib=await ee({ibGib:m}),{newIbGib:m}}else return g}else{if(b.length===1)return b[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(b){throw console.error(`${f} ${E(b)}`),b}finally{ml&&console.log(`${f} complete.`)}}static async stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:r,data:n,rel8ns:a,noTimestamp:s,uuid:i}){let c=`[${o.name}][${o.stone.name}]`;try{if(!e)throw new Error("parentPrimitiveIb required. (E: genuuid)");if(cr({ib:e})!==null)throw new Error(`Invalid parentPrimitiveIb: ${e}. (E: genuuid)`);if(!t)throw new Error("ib required. (E: genuuid)");let l=r?new RegExp(r):pl;if(!t.match(l))throw new Error(`invalid ib. does not match regexp (${l}) (E: genuuid)`);let d=Object.keys(a??{}),f=[...sr,"tjp"];if(d.some(m=>f.includes(m)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${f}. rel8ns keys: ${Object.keys(a??{})}. (E: genuuid)`);let u=(await o.firstGen({ib:t,parentIbGib:o.primitive({ib:e}),data:n,rel8ns:a,dna:!1,noTimestamp:s,nCounter:!1})).newIbGib;return i&&(u.data||(u.data={}),u.data.uuid=await q()),u.rel8ns?.past&&delete u.rel8ns.past,u.rel8ns?.tjp&&delete u.rel8ns.tjp,u.gib=await ee({ibGib:{ib:u.ib,data:u.data,rel8ns:u.rel8ns},hasTjp:!1}),u}catch(l){throw console.error(`${c} ${l.message}`),l}}static async constant({parentPrimitiveIb:e,ib:t,ibRegExpPattern:r,data:n,rel8ns:a}){let s=`[${o.name}][${o.constant.name}]`;try{return await o.stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:r,data:n,rel8ns:a,noTimestamp:!0,uuid:!1})}catch(i){throw console.error(`${s} ${i.message}`),i}}};var bg="[core^gib timer]";var Hs=`.'",!?-`;var gl=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var hg=/^[a-zA-Z0-9_\-.]{1,255}$/,pg=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var jo={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var fh="robbot";var Fn="zero",Bn="zerospace";var Ng=!1,Dg="This is a local space. There are many like it, but this one is mine.";var vg=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,El="syncSpace";var kn=3e4;var jn="space";var wl="0",yl="space_lock",$l=100,Il=100,Pg=60*2,qn=30;var Vs="root",Ws="x",Al="root",Ys="analytics-outline",Ks='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var zs="tag",bh="target";var _l="pricetag-outline",Tl="This is a tag used for organizing data.";var kg="always",Gl="archive",Sl="trash";var Js=/^\w{1,32}$/,Xn="Invalid Date";var Zs={ib:"true",gib:Q};var xl={ib:"false",gib:Q};var Cl="config_key",Hn=/^v:(\d+)\^spaceId:([^^]+)\^(.+)$/;var qo=/^[a-zA-Z0-9_\-.]{1,32}$/,Vn="app";var lr=`bootstrap^${Q}`,At="defaultSpaceId",Wn="spaceIds";var Pt={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},dr=Object.values(Pt),ht={sha_256:"SHA-256",sha_512:"SHA-512"},Yg=Object.values(ht),hh={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},Xt=Object.values(hh);function Xo(o){let e=`[${Xo.name}]`;return new Promise((t,r)=>{try{let n=Nl(o),a=Dl(n);t(a)}catch(n){console.error(`${e} ${E(n)}`),r(n)}})}h(Xo,"encodeStringToHexString");function Nl(o){let e=`[${Nl.name}]`;try{return new TextEncoder().encode(o)}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(Nl,"stringToUTF8Bytes");function Dl(o){let e=`[${Dl.name}]`;try{return Array.from(o,t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(Dl,"bytesToHexString");function Ht(o){let e=`[${Ht.name}]`;return new Promise((t,r)=>{try{let n=vl(o),a=Pl(n);t(a)}catch(n){console.error(`${e} ${E(n)}`),r(n)}})}h(Ht,"decodeHexStringToString");function vl(o){let e=`[${vl.name}]`;try{if(o.length%2!==0)throw new Error("invalid hex string. length %2 !== 0");let t=o.length/2,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=parseInt(o.substr(n*2,2),16);return r}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(vl,"hexStringToBytes");function Pl(o){let e=`[${Pl.name}]`;try{return new TextDecoder().decode(o)}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(Pl,"utf8BytesToString");var Vt=Pt.appendPerHash,Wt="SHA-512",Yt=1024,Ot=2e4,Kt=1,Ol="indexOf",Yn="lastIndexOf",Kn=5e6,zn=4,fr=",";function ph({secret:o,prevHash:e,salt:t,saltStrategy:r}){if(!(e||o))throw new Error("Either secret or prevHash is required, but both are falsy (E: bee2849729ff410081d963777dcedb49))");switch(r){case Pt.prependPerHash:return t+(e||o);case Pt.appendPerHash:return(e||o)+t;case Pt.initialPrepend:return e||t+o;case Pt.initialAppend:return e||o+t;default:throw new Error(`Unknown saltStrategy: ${r} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}h(ph,"getPreHash");async function wt({secret:o,prevHash:e,count:t,salt:r,saltStrategy:n,hashAlgorithm:a}){let s=`[${wt.name}]`;try{let i=e||void 0;for(let c=0;c<t;c++){let l=ph({secret:o,prevHash:i,salt:r,saltStrategy:n});i=await te({s:l,algorithm:a})}if(!i)throw new Error("hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)");return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}h(wt,"execRound_getNextHash");async function zt({secret:o,initialRecursions:e,salt:t,saltStrategy:r,hashAlgorithm:n}){let a=`[${zt.name}]`;try{return await wt({secret:o,count:e,salt:t,saltStrategy:r,hashAlgorithm:n})}catch(s){throw console.error(`${a} ${E(s)}`),s}}h(zt,"doInitialRecursions_keystretch");async function Qs({hexEncodedData:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c}){let l=`[${Qs.name}]`;try{let d=await zt({secret:a,initialRecursions:e,salt:r,saltStrategy:n,hashAlgorithm:s}),f=c==="indexOf"?(u,m)=>u.indexOf(m):(u,m)=>u.lastIndexOf(m),b=[];for(let u=0;u<o.length;u++){let m=o[u],g="",y;for(;!g.includes(m);)y=await wt({count:t,prevHash:d,salt:r,saltStrategy:n,hashAlgorithm:s}),g+=y,d=y;let w=f(g,m);b.push(w)}return b.join(i)}catch(d){throw console.error(`${l} ${E(d)}`),d}}h(Qs,"encryptFromHex_stream");async function ei({encryptedData:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${ei.name}]`;try{let l=await zt({secret:a,initialRecursions:e,salt:r,saltStrategy:n,hashAlgorithm:s}),d=o.split(i).map(p=>parseInt(p)),f=[];for(let p=0;p<d.length;p++){let u=d[p],m="",g;for(;u>=m.length;)g=await wt({count:t,prevHash:l,salt:r,saltStrategy:n,hashAlgorithm:s}),m+=g,l=g;let y=m[u];f.push(y)}return f.join("")}catch(l){throw console.error(`${c} ${E(l)}`),l}}h(ei,"decryptToHex_stream");async function Ho({encryptedData:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${Ho.name}]`,l=[],d=[];e=e||Ot,t=t||Kt,n=n||Vt,s=s||Wt,r=r||await q(Yt),i=i||fr;let f="[validation]";if(!e||e<1){let u=`${f} initialRecursions required, and greater than 0`;console.error(u),l.push(u)}if(!t||t<1){let u=`${f} recursionsPerHash required, and greater than 0`;console.error(u),l.push(u)}if(!o){let u=`${f} encryptedData required`;console.error(u),l.push(u)}if(!r){let u=`${f} salt required`;console.error(u),l.push(u)}if(!n){let u=`${f} saltStrategy required`;console.error(u),l.push(u)}if(!a){let u=`${f} secret required`;console.error(u),l.push(u)}if(!i){let u=`${f} encryptedDataDelimiter required`;console.error(u),l.push(u)}if(!Object.values(ht).includes(s)){let u=`${f} only ${Object.values(ht)} hash algorithms implemented`;console.error(u),l.push(u)}if(n&&!dr.includes(n)){let u=`${f} unknown saltStrategy: ${n}`;console.error(u),l.push(u)}if(l.length>0)return{errors:l,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let b=await ei({encryptedData:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});return{decryptedData:await Ht(b),initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:d.length>0?d:void 0}}h(Ho,"decryptImpl_stream");async function ti({dataToEncrypt:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,confirm:c,indexingMode:l}){let d=`[${ti.name}]`,f=[],b=[];e||(console.warn(`${d} initial recursions required. defaulting to ${Ot}`),e=Ot),t=t||Kt,n=n||Vt,s=s||Wt,r=r||await q(Yt),i=i||fr,l=l||Ol;let p="[validation]";if(!e||e<1){let g=`${p} initialRecursions required, and greater than 0`;console.error(g),f.push(g)}if(!t||t<1){let g=`${p} recursionsPerHash required, and greater than 0`;console.error(g),f.push(g)}if(!o){let g=`${p} dataToEncrypt required`;console.error(g),f.push(g)}if(!r){let g=`${p} salt required`;console.error(g),f.push(g)}if(!n){let g=`${p} saltStrategy required`;console.error(g),f.push(g)}if(!a){let g=`${p} secret required`;console.error(g),f.push(g)}if(!i){let g=`${p} encryptedDataDelimiter required`;console.error(g),f.push(g)}if(!Xt.includes(l)){let g=`${p} invalid indexingMode (${l}). Must be one of ${Xt} (E: 5955c46755434982982823c97adcf076)`;console.error(g),f.push(g)}if(!Object.values(ht).includes(s)){let g=`${p} only ${Object.values(ht)} hash algorithms implemented`;console.error(g),f.push(g)}if(n&&!dr.includes(n)){let g=`${p} unknown saltStrategy: ${n}`;console.error(g),f.push(g)}if(f.length>0)return{errors:f,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let u=await Xo(o);if(c&&await Ht(u)!==o)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let m=await Qs({hexEncodedData:u,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:"indexOf"});if(c){let g=await Ho({encryptedData:m,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});if((g.errors||[]).length>0)return{errors:["Confirm check found that decrypt had errors.",...g.errors],initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};if(g.decryptedData){if(g.decryptedData!==o)throw new Error("The ENCRYPTED data did not decrypt back to the original data.")}else throw new Error("Confirm check call to decrypt produced falsy decryptedData");(g.warnings||[]).length>0&&(b=b.concat(["Confirm check call to decrypt had warnings.",...g.warnings]))}return{encryptedData:m,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:b.length>0?b:void 0}}h(ti,"encryptImpl_stream");async function ri({hexEncodedData:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c,maxBlockSize:l,numOfPasses:d}){let f=`[${ri.name}]`;try{let b=await zt({secret:a,initialRecursions:e,salt:r,saltStrategy:n,hashAlgorithm:s}),p=c==="indexOf"?(T,$)=>T.indexOf($):(T,$)=>T.lastIndexOf($),u=[],m=o.length,g=l;g>m&&(g=m);let y=Math.ceil(m/g),w=m%g||g,A=0;for(let T=0;T<y;T++){T===y-1&&(g=w);let _=await Ll({blockSize:g,indexHexEncodedDataAtStartOfPass:A,numOfPasses:d,hexEncodedData:o,recursionsPerHash:t,salt:r,saltStrategy:n,prevHash:b,hashAlgorithm:s}),S=_.alphabetsThisBlock;b=_.prevHash;let D=await Rl({alphabetsThisBlock:S,blockSize:g,indexHexEncodedDataAtStartOfPass:A,hexEncodedData:o,getIndexOfCharInAlphabet:p});u=u.concat(D),A+=g}return u.join(i)}catch(b){throw console.error(`${f} ${E(b)}`),b}}h(ri,"encryptFromHex_blockMode");async function Ll({blockSize:o,numOfPasses:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:r,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let l=`[${Ll.name}]`;try{let d=[],f,b;for(let p=0;p<e;p++)for(let u=0;u<o;u++){f=t+u;let m=d[u]??"";b=await wt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=b,i=b,d[u]=m}for(let p=0;p<o;p++){f=t+p;let u=r[f],m=d[p];for(;!m.includes(u);)b=await wt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=b,i=b;d[p]=m}return{alphabetsThisBlock:d,prevHash:i}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}h(Ll,"getAlphabetsThisBlock");async function Rl({alphabetsThisBlock:o,blockSize:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:r,getIndexOfCharInAlphabet:n}){let a=`[${Rl.name}]`;try{let s=[];for(let i=0;i<e;i++){let c=t+i,l=o[i],d=n(l,r[c]);s.push(d)}return s}catch(s){throw console.error(`${a} ${E(s)}`),s}}h(Rl,"getEncryptedIndexesThisBlock");async function oi({encryptedData:o,initialRecursions:e,recursionsPerHash:t,salt:r,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,maxBlockSize:c,numOfPasses:l}){let d=`[${oi.name}]`;try{let f=await zt({secret:a,initialRecursions:e,salt:r,saltStrategy:n,hashAlgorithm:s}),b=o.split(i).map(G=>parseInt(G)),p=[],u=b.length,m=c;m>u&&(m=u);let g=Math.ceil(u/m),y=u%m||m,w=0;for(let G=0;G<g;G++){G===g-1&&(m=y);let $=await Ul({blockSize:m,indexEncryptedDataIndexesAtStartOfPass:w,numOfPasses:l,encryptedDataIndexes:b,recursionsPerHash:t,salt:r,saltStrategy:n,prevHash:f,hashAlgorithm:s}),_=$.alphabetsThisBlock;f=$.prevHash;let S=await Ml({alphabetsThisBlock:_,blockSize:m,indexEncryptedDataIndexesAtStartOfPass:w,encryptedDataIndexes:b});p=p.concat(S),w+=m}return p.join("")}catch(f){throw console.error(`${d} ${E(f)}`),f}}h(oi,"decryptToHex_blockMode");async function Ul({blockSize:o,numOfPasses:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:r,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let l=`[${Ul.name}]`;try{let d=[],f,b;for(let p=0;p<e;p++)for(let u=0;u<o;u++){f=t+u;let m=d[u]??"";b=await wt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=b,i=b,d[u]=m}for(let p=0;p<o;p++){f=t+p;let u=r[f],m=d[p];for(;m.at(u)===void 0;)b=await wt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=b,i=b;d[p]=m}return{alphabetsThisBlock:d,prevHash:i}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}h(Ul,"getAlphabetsThisBlock");async function Ml({alphabetsThisBlock:o,blockSize:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:r}){let n=`[${Ml.name}]`;try{let a=[];for(let s=0;s<e;s++){let i=t+s,c=r[i],d=o[s][c];a.push(d)}return a}catch(a){throw console.error(`${n} ${E(a)}`),a}}h(Ml,"getDecryptedDataArrayThisBlock");async function Vo(o){let e=`[${Vo.name}]`,{encryptedData:t,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:d,blockMode:f,multipass:b}=o,p=[],u=[];if(f&&b)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: b9b3cd1f701c700835c0419260278223)");if(!f&&b&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),f=b),!f)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");r=r||Ot,n=n||Kt,s=s||Vt,c=c||Wt,a=a||await q(Yt),l=l||fr,d=d||Yn;let{maxBlockSize:m,maxPassSectionLength:g,numOfPasses:y}=f;!m&&g&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`),m=g),m=m||Kn,y=y||zn;let w="[validation]";if(!r||r<1){let $=`${w} initialRecursions required, and greater than 0`;console.error($),p.push($)}if(!n||n<1){let $=`${w} recursionsPerHash required, and greater than 0`;console.error($),p.push($)}if(!t){let $=`${w} encryptedData required`;console.error($),p.push($)}if(!a){let $=`${w} salt required`;console.error($),p.push($)}if(!s){let $=`${w} saltStrategy required`;console.error($),p.push($)}if(!i){let $=`${w} secret required`;console.error($),p.push($)}if(!l){let $=`${w} encryptedDataDelimiter required`;console.error($),p.push($)}if(!d){let $=`${w} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error($),p.push($)}if(!Xt.includes(d)){let $=`${w} invalid indexingMode (${d}). Must be one of ${Xt} (E: 17435268651444e0b7a594135635fc58)`;console.error($),p.push($)}if(m<1){let $=`${w} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error($),p.push($)}if(y<1){let $=`${w} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error($),p.push($)}if(!Object.values(ht).includes(c)){let $=`${w} only ${Object.values(ht)} hash algorithms implemented`;console.error($),p.push($)}if(s&&!dr.includes(s)){let $=`${w} unknown saltStrategy: ${s}`;console.error($),p.push($)}if(p.length>0){let $={...o,errors:p};return delete $.encryptedData,delete $.secret,$}let A=await oi({encryptedData:t,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,maxBlockSize:m,numOfPasses:y}),G=await Ht(A),T={...o,decryptedData:G,warnings:u.length>0?u:void 0};return delete T.encryptedData,delete T.secret,T}h(Vo,"decryptImpl_blockMode");async function ni(o){let e=`[${ni.name}]`,{dataToEncrypt:t,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,confirm:d,indexingMode:f,blockMode:b,multipass:p}=o,u=[],m=[];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: bde5efd1a3e449dca549c5bff147f09b)");if(!b&&p&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),b=p),!b)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 0b87871f81d849ef8f0263b7775bd3e3)");r||(console.warn(`${e} initial recursions required. defaulting to ${Ot}`),r=Ot),l=l||fr,f=f||Yn;let{maxBlockSize:g,maxPassSectionLength:y,numOfPasses:w}=b;!g&&y&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`),g=y),g=g||Kn,w=w||zn;let A="[validation]";if(!r||r<1){let _=`${A} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(_),u.push(_)}if(!n||n<1){let _=`${A} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(_),u.push(_)}if(!a){let _=`${A} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(_),u.push(_)}if(!s){let _=`${A} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(_),u.push(_)}if(!i){let _=`${A} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(_),u.push(_)}if(!l){let _=`${A} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(_),u.push(_)}if(!f){let _=`${A} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(_),u.push(_)}if(!Xt.includes(f)){let _=`${A} invalid indexingMode (${f}). Must be one of ${Xt} (E: 17435268651444e0b7a594135635fc58)`;console.error(_),u.push(_)}if(g<1){let _=`${A} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(_),u.push(_)}if(w<1){let _=`${A} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(_),u.push(_)}if(!Object.values(ht).includes(c)){let _=`${A} only ${Object.values(ht)} hash algorithms implemented`;console.error(_),u.push(_)}if(s&&!dr.includes(s)){let _=`${A} unknown saltStrategy: ${s}`;console.error(_),u.push(_)}if(u.length>0){let _={...o,errors:u};return delete _.dataToEncrypt,delete _.secret,_}let G=await Xo(t);if(d&&await Ht(G)!==t)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let T=await ri({hexEncodedData:G,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:f,maxBlockSize:g,numOfPasses:w});if(d)try{let _=await Vo({encryptedData:T,initialRecursions:r,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:f,blockMode:b});if(_.decryptedData){if(_.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)");(_.warnings||[]).length>0&&(m=m.concat(["Confirm check call to decrypt had warnings.",..._.warnings]))}catch(_){throw new Error(`${e} confirm failed. decrypt error: ${E(_)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let $={...o,encryptedData:T,warnings:m.length>0?m:void 0};return delete $.dataToEncrypt,delete $.secret,$}h(ni,"encryptImpl_blockMode");async function uh(o){let e=`[${uh.name}]`;try{if(!o)throw new Error("args required (E: 22e58e03c78f4c27bf18295b8d2cdd3a)");if(!o.dataToEncrypt)throw new Error("dataToEncrypt required (E: 168c9076e5434c83ba81e3485ee6f3e4)");o.salt=o.salt||await q(Yt),o.saltStrategy=o.saltStrategy||Vt,o.hashAlgorithm=o.hashAlgorithm||Wt,o.recursionsPerHash=o.recursionsPerHash||Kt;let t;return o.blockMode?t=await ni(o):t=await ti(o),(t.errors??[]).length>0&&t.errors.forEach(r=>console.warn(`${e} ${r}`)),(t.warnings??[]).length>0&&t.warnings.forEach(r=>console.warn(`${e} ${r}`)),t}catch(t){throw console.error(`${e}${t.message}`),t}}h(uh,"encrypt");async function mh(o){let e=`[${mh.name}]`;try{if(!o)throw new Error("args required (E: fcd9b4aad85c4deba5fe5fde0b9ecb30)");if(!o.encryptedData)throw new Error("encryptedData required (E: f879f612428b4283bae089acee929a58)");o.salt=o.salt||await q(Yt),o.saltStrategy=o.saltStrategy||Vt,o.hashAlgorithm=o.hashAlgorithm||Wt,o.recursionsPerHash=o.recursionsPerHash||Kt;let t;return o.blockMode||o.multipass?t=await Vo(o):t=await Ho(o),(t.warnings??[]).length>0&&t.warnings.forEach(r=>console.warn(`${e} ${r}`)),(t.errors??[]).length>0&&t.errors.forEach(r=>console.warn(`${e} ${r}`)),t}catch(t){throw console.error(`${e}${t.message}`),t}}h(mh,"decrypt");var aE=5e4;var sE=Pt.appendPerHash,iE=10,cE="SHA-256";var lE="encryption",dE="ciphertext";var gh={local:"local",outerspace:"outerspace",innerspace:"innerspace"},pE=Object.values(gh).concat(),Eh={user:"user",sync:"sync"},Zn=Object.values(Eh).concat(),wh={node_filesystem:"node-filesystem"},yh={aws_dynamodb:"aws-dynamodb"},$h={...wh,...yh},Qn=Object.values($h).concat(),Lt={get:"get",put:"put",delete:"delete"},ai={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var Ih=!1,ea=class o{static{h(this,"DynamicFormBuilder")}lc=`[${o.name}]`;items=[];what="";idPool=[];getNewId(){let e=`${this.lc}[${this.getNewId.name}]`;if(this.idPool?.length>0)return this.idPool.pop()??"";{let t=[],r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n=r.length;for(let s=0;s<32;s++){let i=Math.floor(Math.random()*n);t.push(r[i])}let a=t.join("");return Ih&&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:r}){return this.addItem({name:"name",description:`What to call this ${this.what}. Doesn't have to be unique, no spaces, up to 32 alphanumerics/underscores in length.`,label:"Name",placeholder:'e.g. "bob_the_cool"',regexp:On({min:1,max:32,noSpaces:!0}),regexpErrorMsg:"1 to 32 characters, no spaces, underscores allowed.",required:t,dataType:"text",value:e,defaultValue:r}),this}description({of:e,required:t,defaultValue:r}){return this.addItem({name:"description",description:`Description/notes for this ${this.what}.`,label:"Description",placeholder:`Describe these ${this.what} settings here...`,regexp:On({min:0,max:155,chars:Hs}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${Hs}`,dataType:"textarea",required:t,value:e,defaultValue:r}),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:On({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:r}){return this.addItem({name:"uuid",description:`Unique(ish) id of the ${this.what}.`,label:t??"ID",dataType:"text",value:e,regexp:Ie,regexpErrorMsg:"1 to 256 alphanumerics, underscores, dots, hyphens allowed.",readonly:!0,required:r}),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 br=class o extends ea{static{h(this,"WitnessFormBuilder")}lc=`[${o.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:r=!0,persistOptsAndResultIbGibs:n=!0,trace:a=!0,version:s=!0}){return t&&this.allowPrimitiveArgs({of:e.allowPrimitiveArgs}),r&&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 ta=!1;function Fl({appData:o}){let e=`[${Fl.name}]`;try{if(ta&&console.log(`${e} starting...`),!o)throw new Error("appData required (E: 3df782b29bc4406a87e4895cfcea28ed)");let t=[],{name:r,uuid:n,classname:a}=o;return r?r.match(qo)||t.push(`name must match regexp: ${qo}`):t.push("name required."),n?n.match(Ie)||t.push(`uuid must match regexp: ${Ie}`):t.push("uuid required."),a&&(a.match(qo)||t.push(`classname must match regexp: ${qo}`)),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ta&&console.log(`${e} complete.`)}}h(Fl,"validateCommonAppData");function si({appData:o,classname:e}){let t=`[${si.name}]`;try{let r=Fl({appData:o});if(r.length>0)throw new Error(`invalid appData: ${r} (E: 9aff04f0cfc54a5188ca8bc40764160d)`);if(e){if(o.classname&&o.classname!==e)throw new Error("classname does not match appData.classname (E: 66f1447eef97485fba521c40980f5eb5)")}else if(e=o.classname,!e)throw new Error("classname required (E: 5f6ffb4317044125b94f662070e1f40b)");let{name:n,uuid:a}=o;return`app ${e} ${n} ${a}`}catch(r){throw console.error(`${t} ${r.message}`),r}}h(si,"getAppIb");function Ah({appIb:o}){let e=`[${Ah.name}]`;try{if(!o)throw new Error("appIb required (E: 6b065aee67e641ba9f9c6db367ebb0fb)");let t=o.split(" ");return{appClassname:t[1],appName:t[2],appId:t[3]}}catch(t){throw console.error(`${e} ${t.message}`),t}}h(Ah,"getInfoFromAppIb");async function _h({fnPromptApp:o,ibgibs:e,space:t}){let r=`[${_h.name}]`;try{if(ta&&console.log(`${r} starting...`),!e)throw new Error("ibgibs all powerful service required. (E: b24e78de0d204dc78909022bee296b30)");t=t??await e.getLocalUserSpace({lock:!0});let n=await o(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(d=>s.push(d)),n.dnas?.forEach(d=>s.push(d));for(let d=0;d<s.length;d++){let f=s[d],b=await ne({ibGib:f});if((b??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${b}. app: ${X(a.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await V({resTransform:n,space:t});let{zeroSpace:i,fnBroadcast:c,fnUpdateBootstrap:l}=e;return await J({ibGib:a,space:t,fnBroadcast:h(d=>c(d),"fnBroadcast")}),await ao({type:"apps",rel8nName:Vn,ibGibsToRel8:[a],space:t,zeroSpace:i,fnUpdateBootstrap:l,fnBroadcast:c}),a}catch(n){debugger;console.error(`${r} ${n.message}`);return}finally{ta&&console.log(`${r} complete.`)}}h(_h,"createNewApp");var Th="0",Gh="chat_gib",Sh="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",Bl={version:"1",uuid:Th,name:Gh,description:Sh,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},kl=void 0;var xh="0",Ch="raw_gib",Nh="Explorer app for navigating raw ibgib data.",jl={version:"1",uuid:xh,name:Ch,description:Nh,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ql=void 0;var ii="0",Dh="todo_gib",vh="Todo app for viewing and interacting with ibgibs like they're checklists.",Xl={version:"1",uuid:ii,name:Dh,description:vh,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Hl=void 0;async function ci(o){let e=`[${ci.name}]`,t=[];try{I({ibGib:o})!==lr&&t.push(`invalid bootstrapSpace addr. Should equal "${lr}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await ne({ibGib:o});(n?.length??!1)&&n.forEach(i=>t.push(i));let a=o.data,s=o.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(o.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[At]?(s[a[At]]??[]).length===0&&t.push(`invalid bootstrap. data.${At} (${a[At]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):t.push(`invalid bootstrap. data.${At} required. (E: f763af2e275f445cbf1db5801bacafad)`),t.length===0?!0:(console.error(`${e} errors: ${t.join("|")}`),!1)}catch(r){return console.error(`${e} ${r.message}`),!1}}h(ci,"validateBootstrapIbGib");var so="meta_stone";var li="undefined",Pr="target",ra="targetTjp";var yt=!1;function Wl({ib:o}){let e=`[${Wl.name}]`;try{yt&&console.log(`${e} starting...`);let t=[],r=o.split(" ");r[0]!==so&&t.push(`${e} invalid ib. atom is expected to be META_STONE_ATOM: ${so} (E: a9812bffc18f44418aa091fb0ed260bd)`);let a=r[1],s=ir({gib:a})??[];s.length>0&&t.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${s} (E: 233db2babfbe4d28a80f98261f1c0e01)`);let i=r[2],c=Number.parseInt(i);isNaN(c)&&t.push("invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)");let l=r[3];if(l!=="undefined"){let d=hr({timestamp:l});d.valid||t.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${d.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`)}return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{yt&&console.log(`${e} complete.`)}}h(Wl,"validateCommonMetaStoneIb");function di({data:o}){let e=`[${di.name}]`;try{if(yt&&console.log(`${e} starting...`),!o)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let t=[],{targetData:r,timestamp:n}=o;hr({timestamp:n}).valid||t.push("invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)");let{tjpGib:s,n:i,timestamp:c}=r;if(s&&s!=="undefined"){let d=ir({gib:s})??[];d.length>0&&t.push(`invalid data (targetTjpGib). validation errors: ${d} (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 d=hr({timestamp:c});d.valid||t.push(`invalid targetTimestamp. emsg: ${d.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`)}let l=new Date(n);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{yt&&console.log(`${e} complete.`)}}h(di,"validateCommonMetaStoneData");function Yl({rel8ns:o}){let e=`[${Yl.name}]`;try{if(yt&&console.log(`${e} starting...`),!o)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let t=[],r=Xs({rel8ns:o??{}})??[];r.length>0&&t.push(`invalid rel8ns intrinsically. errors: ${r.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=o[Pr]??[];n.length===0?t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Pr}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Pr}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let a=o[ra]??[];return a.length>1&&t.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${ra}. has ${a.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{yt&&console.log(`${e} complete.`)}}h(Yl,"validateCommonMetaStoneRel8ns");async function Ph({ibGib:o}){let e=`[${Ph.name}]`;try{yt&&console.log(`${e} starting... (I: f32249d08105b997871a06cdee006311)`);let t=await ne({ibGib:o})??[];if(!o.data)throw new Error("MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)");let r=[];try{let{atom:i,tjpGib:c,n:l,timestampInTicks:d}=oa({ib:o.ib})}catch(i){r.push(E(i))}let n=di({data:o.data}),a=Yl({rel8ns:o.rel8ns}),s=[...t??[],...r??[],...n??[],...a??[]];return s.length>0?s:void 0}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{yt&&console.log(`${e} complete.`)}}h(Ph,"validateCommonMetaStoneIbGib");function Kl({data:o,classname:e}){let t=`[${Kl.name}]`;try{let r=di({data:o});if(r.length>0)throw new Error(`invalid MetaStone data: ${r} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);e&&yt&&console.log(`${t} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`);let n=o.targetData.timestamp,a=n&&n!=="undefined"?ft(n):li;return`${so} ${o.targetData.tjpGib} ${o.targetData.n} ${a}`}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(Kl,"getMetaStoneIb");function oa({ib:o}){let e=`[${oa.name}]`;try{if(!o)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let t=Wl({ib:o});if(t.length>0)throw new Error(`invalid ib. validationErrors: ${t} (E: a6107f62200eb943e523f70f51300623)`);let r=o.split(" ");return{atom:r[0],tjpGib:r[1],n:Number.parseInt(r[2]),timestampInTicks:r[3]}}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(oa,"parseMetaStoneIb");function fi({addr:o,ibGib:e}){if(o||=I({ibGib:e}),!o)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return o.startsWith(`${so} `)}h(fi,"isMetaStone");async function bi({targetIbGib:o}){let e=`[${bi.name}]`;try{yt&&console.log(`${e} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let t=I({ibGib:o}),r=ye({ibGib:o,defaultIfNone:"incomingAddr"}),n,a={[Pr]:[t],[ra]:[r]};if(!o.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let s=o.data?.isTjp?o.gib:Ne({ibGibAddr:t}).tjpGib??o.gib;if(s===Q)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let i=new Date,c=rt(i),l=i.getMilliseconds();o.data?Wo({ibGib:o})?n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:l}:(n={targetData:{n:o.data.n??-1,tjpGib:s,timestamp:o.data.timestamp??li},timestamp:c,timestampMs:l},o.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:l};let d=Kl({data:n}),f=await _t({parentPrimitiveIb:so,ib:d,data:n,rel8ns:a});return yt&&(console.log(`${e} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(f)),f}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{yt&&console.log(`${e} complete.`)}}h(bi,"newUpMetaStone");var na="witness",Yo="witness_arg",aa="witness_result",QE="context";var P=!1;async function z({addr:o,addrs:e,isDna:t,space:r,force:n}){let a=`[${z.name}]`;try{if(P&&console.log(`${a} starting...`),!r)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(!o&&(e??[]).length===0)throw new Error("addr or addrs required. (E: 1a0b92564ba942f1ba91a089ac1a2125)");o&&(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(o)||e.push(o)),e=(e??[]).length>0?e:[o];let s=await r.argy({ibMetadata:Tt({space:r}),argData:{cmd:"get",ibGibAddrs:e,isDna:t}}),i=await r.witness(s);return i?.data?.success?(P&&console.log(`${a} got.`),{success:!0,ibGibs:i.ibGibs,rawResultIbGib:i}):(P&&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}}}h(z,"getFromSpace");async function ce({ibGib:o,ibGibs:e,isDna:t,force:r,space:n}){let a=`[${ce.name}]`;try{if(!o&&(e??[]).length===0)throw new Error("ibGib or ibGibs required. (E: e59c4de3695f4dd28c8fe82dbb9c4e90)");if(!n)throw new Error("space required. (E: dd0b7189c67c43c586b905a8ed6f51c9)");o&&(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===o.gib)||(e=e.concat([o]))),e=e??[o],P&&console.log(`${a} ibGibs.length: ${e.length}`);let s=await n.argy({ibMetadata:Tt({space:n}),argData:{cmd:"put",force:r,isDna:t,ibGibAddrs:e.map(c=>I({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}}}h(ce,"putInSpace");async function pi({addr:o,isDna:e,space:t}){let r=`[${pi.name}]`;try{if(!t)throw new Error("space required. (E: 40ab3b51e91c4b5eb4f215baeefbcef0)");if(!t.data)throw new Error("space.data required. (E: 0d02c8e85ee143b8bd6a1a1db0d9af1b)");r=`${r}[${t.data.name||"noname?"}][${t.data.uuid||"nouuid?"}]`;let n=await t.argy({ibMetadata:Tt({space:t}),argData:{cmd:"delete",ibGibAddrs:[o],isDna:e}}),a=await t.witness(n);if(a.data?.success)return{success:!0};{a.data?.warnings?.length>0&&console.warn(`${r} warnings with delete (${o}): ${a.data.warnings.join("|")}`),a.data?.addrs?.length>0&&console.warn(`${r} partial addrs deleted: ${a.data.addrs.join("|")}`);let s=a.data?.errors?.join("|")||`${r} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;return s.includes("File does not exist")&&P&&console.log(`${r} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`),{errorMsg:s}}}catch(n){return console.error(`${r} ${n.message}`),{errorMsg:n.message}}}h(pi,"deleteFromSpace");async function V({resTransform:o,space:e,force:t}){let r=`[${V.name}]`;try{if(P&&console.log(`${r} starting... (I: dc6835614ff1a1b82b179225023ae823)`),!e)throw new Error("space required. (E: cf94f1d74f1c4561bb88025a2095965b)");let{newIbGib:n,intermediateIbGibs:a,dnas:s}=o,i=[n,...a||[]],c=await e.argy({ibMetadata:Tt({space:e}),argData:{cmd:"put",force:t,ibGibAddrs:i.map(d=>I({ibGib:d}))},ibGibs:i.concat()}),l=await e.witness(c);if(l.data?.success)l.data.warnings?.length>0&&l.data.warnings.forEach(d=>console.warn(`${r} ${d}`));else{let d=l?.data?.errors?.length>0?l.data.errors.join(`
|
|
5
|
+
`):"unknown error putting ibGibs";throw new Error(d)}if(s?.length??!1){let d=await e.argy({ibMetadata:Tt({space:e}),argData:{cmd:"put",isDna:!0,force:t,ibGibAddrs:s.map(b=>I({ibGib:b}))},ibGibs:s.concat()}),f=await e.witness(d);if(f.data?.success)f.data.warnings?.length>0&&f.data.warnings.forEach(b=>console.warn(`${r} ${b}`));else{let b=f?.data?.errors?.length>0?f.data.errors.join(`
|
|
6
|
+
`):"unknown error putting dna ibGibs";throw new Error(b)}}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{P&&console.log(`${r} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}h(V,"persistTransformResult");async function zl({type:o,rel8nName:e,space:t}){let r=`[${zl.name}]`;try{if(!t)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await ia({type:o,space:t});if(!n)throw new Error(`couldn't get special (${o}) (E: a65bef190416479697605be486846731)`);let a=n.rel8ns?n.rel8ns[e]||[]:[],s=[];for(let i=0;i<a.length;i++){let c=a[i],l=await z({addr:c,space:t});if(l.success&&l.ibGibs?.length===1)s.push(l.ibGibs[0]);else throw new Error(`couldn't get addr: ${c} (E: 76ef256ee80149ab860c5786484b0e89)`)}return s}catch(n){throw console.error(`${r} ${n.message}`),n}}h(zl,"getSpecialRel8dIbGibs");async function ia({type:o,initialize:e,space:t,zeroSpace:r,fnUpdateBootstrap:n,fnBroadcast:a,fnGetInitializing:s,fnSetInitializing:i,dontWarnIfNotExist:c}){let l=`[${ia.name}]`;try{if(!t)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let d=Me({type:o}),f=await ca({key:d,space:t,dontWarn:c||!!e});if(!f){if(e&&(!s||!i))throw new Error("if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)");if(e&&!s()){i(!0);try{if(!r)throw new Error("zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)");f=await Ql({type:o,space:t,zeroSpace:r,fnBroadcast:a,fnUpdateBootstrap:n})??void 0}catch(m){console.error(`${l} error initializing: ${m.message}`)}finally{i(!1)}}if(!f){if(s&&s())return console.warn(`${l} couldn't get addr, but we're still initializing...`),null;throw new Error("Special address not in config and couldn't initialize it either. (E: d8ebdc9eaaa640b99cd206f132962c93)")}}P&&console.log(`${l} getting addr: ${f}`);let b=await z({addr:f,space:t});if(b.success||(b=await z({addr:f,space:t}),b.success&&(console.warn(`${l} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await ce({ibGib:b.ibGibs[0],space:t})).success||console.warn(`${l} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!b.success)throw new Error(b.errorMsg);if(b.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let p=b.ibGibs[0],u=await ve({ibGibs:[p],space:t});if(u?.data?.success&&u.data.addrs?.length===1){let m=I({ibGib:p}),g=u.data.addrs[0];g!==m&&console.warn(`${l} latest addr is not the one associated with the local space.
|
|
7
|
+
specialAddr: ${m}
|
|
8
|
+
latestAddr: ${g} (W: 141b69dc3c414efc9645bb76fcf12df9)`)}return p}catch(d){let f=`${l} ${d.message}`;return f.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(f),null}}h(ia,"getSpecialIbGib");async function ca({key:o,space:e,dontWarn:t}){let r=`[${ca.name}](${o})`;try{if(P&&console.log(`${r} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!e)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!e.rel8ns){(P||!t)&&console.warn(`${r} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!e.rel8ns[o]){(P||!t)&&console.warn(`${r} space.rel8ns[${o}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(e.rel8ns[o].length===1)return P&&console.log(`${r} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),e.rel8ns[o][0];if(e.rel8ns[o].length>1)return(P||!t)&&console.warn(`${r} more than one config addr with ${o} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),e.rel8ns[o][0];P&&console.log(`${r} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${r} ${n.message}`);return}}h(ca,"getConfigAddr");async function Je({key:o,addr:e,space:t,zeroSpace:r,fnUpdateBootstrap:n}){let a=`[${Je.name}]`;try{if(!t)throw new Error("space required. (E: c28b663c991d44419aef1026cc689636)");if(!r)throw new Error("zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)");let s={[o]:[e]},i=await ie({src:t.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",o],rel8nsToAddByAddr:s,nCounter:!0});if(!i.newIbGib)throw new Error("create new space failed.");await V({resTransform:i,space:r}),await V({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}}h(Je,"setConfigAddr");async function Jl({space:o}){let e=`[${Jl.name}]`;try{if(!o)throw new Error("space required. (E: f0d546101fba4c169256158114ab3c56)");let t=await ia({type:"roots",space:o});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 r=t.rel8ns.current[0],n=await z({addr:r,space:o});if(n.ibGibs?.length===1)return n.ibGibs[0];throw new Error(`could not get current root. addr: ${r}`)}catch(t){console.error(`${e} ${t.message}`);return}}h(Jl,"getCurrentRoot");async function ui({root:o,space:e,zeroSpace:t,fnUpdateBootstrap:r,fnBroadcast:n}){let a=`[${ui.name}]`;try{if(P&&console.log(`${a} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`),!o)throw new Error("root required.");if(!e)throw new Error("space required. (E: 186af2731c5342a78b063a0a4346f3db)");let s=I({ibGib:o}),i=await ia({type:"roots",space:e});if(!i)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let l=await ie({src:i,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[s]},nCounter:!0});await V({resTransform:l,space:e});let d=Me({type:"roots"}),f=l.newIbGib,b=I({ibGib:f});await Je({key:d,addr:b,space:e,zeroSpace:t,fnUpdateBootstrap:r}),await J({ibGib:f,space:e,fnBroadcast:n})}catch(s){throw console.error(`${a} ${s.message}`),s}finally{P&&console.log(`${a} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}h(ui,"setCurrentRoot");async function Zl({ibGib:o,linked:e,rel8nName:t,space:r,fnBroadcast:n,zeroSpace:a,fnUpdateBootstrap:s}){let i=`[${Zl.name}]`;try{if(!r)throw new Error("space required. (E: f2758eab3bb844d2b749515672d9e392)");if(!o)throw new Error("ibGib required (E: f1bfd67754a7271553f4af544d30bc22)");let c=await Jl({space:r});if(!c)throw new Error("currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750");let l=ye({ibGib:o,defaultIfNone:"incomingAddr"}),d=I({ibGib:o});if(t&&l&&c.rel8ns&&c.rel8ns[t]&&c.rel8ns[t].includes(l))return;t=t||Ws;let f=await ie({src:c,dna:!1,linkedRel8ns:e?["past","ancestor",t]:["past","ancestor"],rel8nsToAddByAddr:{[t]:[d]},nCounter:!0});await V({resTransform:f,space:r});let b=f.newIbGib,p=I({ibGib:b});P&&console.log(`${i} updating _currentRoot root. newRootAddr: ${p}`),await J({ibGib:b,space:r,fnBroadcast:n}),await ui({root:b,space:r,zeroSpace:a,fnUpdateBootstrap:s,fnBroadcast:n})}catch(c){console.error(`${i} ${c.message}`);return}}h(Zl,"rel8ToCurrentRoot");async function hi({targetIbGib:o,space:e}){let t=`[${hi.name}]`;try{P&&console.log(`${t} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let r=await bi({targetIbGib:o}),n=await ce({ibGib:r,space:e});if(!n.success)throw new Error(`error putting metaStone in space. error: ${n.errorMsg??"[unknown error (E: 45f700f4f1ff463ca8f5353c8e796ac7)]"} (E: 4c25379e66365055e3e423561a7d6123)`)}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{P&&console.log(`${t} complete.`)}}h(hi,"createAndSaveNewMetaStone");async function J({ibGib:o,space:e,fnBroadcast:t}){let r=`[${J.name}]`,n=P;try{let a=I({ibGib:o});if(r=`${r}[${a}]`,!e)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(P&&console.log(`${r} starting...`),!Ne({ibGibAddr:a}).tjpGib&&!o.data?.isTjp){P&&console.log(`${r} incoming ibGib has no timeline, so no broadcast. still going to create a metastone for it and return early. (I: 649752e3b1be0e0ceb078e0ec2a84f23)`),await hi({targetIbGib:o,space:e});return}let i=ye({ibGib:o,defaultIfNone:"undefined"});if(!i){let u=o.data?.isTjp?o:await Ko({ibGib:o,space:e});u||(console.warn(`${r} tjp not found for ${a}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`),u=o),i=I({ibGib:u})}if(!i)throw new Error("(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)");let c=h(async()=>{P&&console.log(`${r} adding/replacing latest. tjp: ${i} (I: 7f848da003a2436089fd6f044d96bb42)`),await hi({targetIbGib:o,space:e}),t&&(P&&console.log(`${r} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{P&&console.log(`${r} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),t({ib:"IbGibTimelineUpdateInfo",tjpAddr:i,latestAddr:a,latestIbGib:o})}))},"replaceLatest");if(o.data?.isTjp){P&&console.log(`${r} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}P&&console.log(`${r} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let l=await ve({ibGibs:[o],space:e});if(!l.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:d,latestAddrsMap:f}=l.data;if(!d){let{errors:u}=l.data;throw u??=["[unknown error (E: 344857f1853641aa842cea3931f90428)]"],new Error(`resLatest.success falsy. errors: ${X(u)}. addr: ${a} (E: b66721da6e1ef9ac4f4089e86c059323)`)}if(!f)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let b=Object.keys(f);if(b.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(b[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: ${b[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);P&&(console.log(`${r} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(f));let p=f[a];if(p)if(p===a){P&&console.log(`${r} no other found. possible idempotent replacement. addr: ${a} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{P&&console.log(`${r} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${p}. incoming addr: ${a} (I: 6cadf13f82aabeb71d76babf1813e623)`);let u=await z({addr:p,space:e});if(!u.success||u.ibGibs?.length!==1){console.error(`Didn't find existing latest ibGib (${p}). I haven't implemented more robust multi-node/distributed strategies for this scenario yet. so we are going ahead with setting the incoming ibgib as the latest in the timeline. (E: 10f6cca6e5ef45bfacbfe48f652e2102)`),await c();return}let m=u.ibGibs[0];if(typeof o.data?.n=="number"&&o.data.n>=0){P&&console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${o.data.n}`);let y=o.data.n;if(typeof m.data?.n=="number"&&m.data.n>=0){let A=m.data.n;if(P&&console.log(`[registerNewIbGib] n_ibGib (${y}) vs n_existingLatest (${A}) in space: ${e.data?.name||e.ib}`),y>A)P&&console.log(`${r} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{P&&console.log("is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)"),console.warn(`${r} incoming ibGib (${a}) is NOT NEWER than existing latest (${p}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${y}. n_existingLatest: ${A}. space.ib: ${e.ib} (W: 057baadca494473dabb26fb4fb879774)`);return}}else m.data?.isTjp&&o.data.n===0?await c():(console.warn(`${r} (UNEXPECTED) only existingLatestIbGib (isTjp: ${m.data?.isTjp}) has a data.n counter? ibGib.data.n: ${o.data.n}. usually this only happens when existing latest is a tjp and the new ibGib we are registering is n === 0. This is falsy in this instance though. We will go ahead and replace the latest with the new one, but this is an anomalous state. (W: 73d08aea17ad4e1481a5f97e2556a878)`),console.log(`${r} console.dir(existingLatestIbGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(m),console.log(`${r} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(o),await c())}else if(P&&console.log(`${r} no nCounter found. Trying brute force method.`),await fd({ibGib:o,ibGibAddr:a,existingLatest:m,existingLatestAddr:p,tjpAddr:i,space:e})===a)await c();else return}else if(p===null){P&&console.log(`${r} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${a} (I: 4f2bbc32b31e4fa982d95b3a785db82f)`),await c();return}else throw new Error("(UNEXPECTED) latestAddr is falsy but not null? the getLatestAddrs impl in the space should be guaranteed to provide either the incoming ibgib addr, the latest addr (if exists), or null if not found. (E: 3159dd531c0bc0efc1ece116adf28923)")}catch(a){throw console.error(`${r} ${a.message}`),a}finally{P&&console.log(`${r} complete.`),P=n}}h(J,"registerNewIbGib");async function ao({type:o,rel8nName:e,ibGibsToRel8:t,ibGibsToUnRel8:r,addrsToUnRel8:n,linked:a,severPast:s,deletePreviousSpecialIbGib:i,space:c,zeroSpace:l,fnUpdateBootstrap:d,fnBroadcast:f}){let b=`[${ao.name}](type:${o},rel8nName:${e})`;try{if(!c)throw new Error("space required. (E: 956192eea28047eba6dad81620bb96fb)");if((t??[]).length===0&&(r??[]).length===0&&(n??[]).length===0)throw new Error("either ibGibsToRel8 or ibGibsToUnRel8 required. (E: 5add49c8e46a54e2c6b057c22646a822)");if((r??[]).length>0&&(n??[]).length>0)throw new Error("can't provide both ibGibsToUnRel8 and addrsToUnRel8. There isn't a technical reason but I'm too tired right now to implement the overhead to enable this atow (05/2025). (E: 31ef66be26349cfe1b1f352389b99425)");let p=t?.map($=>I({ibGib:$}));n??=r?.map($=>I({ibGib:$}));let u=Me({type:o}),m=await ca({key:u,space:c});if(!m)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let g=await z({addr:m,space:c});if(!g.success)throw new Error("couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)");if(!g.ibGibs)throw new Error("resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)");if(g.ibGibs.length!==1)throw new Error(`resGetSpecial.ibGibs count is not 1 (${g.ibGibs.length}) (E: b4547789016a4729af30cd972a4ca4ab)`);let y=g.ibGibs[0],w=await ie({src:y,rel8nsToAddByAddr:p?{[e]:p}:void 0,rel8nsToRemoveByAddr:n?{[e]:n}:void 0,dna:!1,linkedRel8ns:a?[Se.past,e]:[Se.past],nCounter:!0}),A=w.newIbGib;if(s){if(w.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");A.rel8ns.past=[],A.gib=await ee({ibGib:A})}await V({resTransform:w,space:c});let G=I({ibGib:A}),T=ye({ibGib:A});return await Je({key:u,addr:G,space:c,zeroSpace:l,fnUpdateBootstrap:d}),i&&await pi({addr:m,space:c}),await J({ibGib:A,fnBroadcast:f,space:c}),G}catch(p){throw console.error(`${b} ${p.message}`),p}}h(ao,"rel8ToSpecialIbGib");async function Ko({ibGib:o,naive:e=!0,space:t}){let r=`[${Ko.name}]`;try{if(!t)throw new Error("space required. (E: 941f973d50e84415b58724af173f52c2)");if(!o)throw new Error("ibGib required.");let n=I({ibGib:o}),{gib:a}=K({ibGibAddr:n});if(a===Q||await Ii({ibGib:o,naive:e}))return o;if(!o.rel8ns){P&&console.log(`${r} ibgib not tjp in data, and rel8ns is falsy. so tjp is undefined (I: acdadb76a7568807db7a68f6f866de22)`);return}if(o.rel8ns.tjp&&o.rel8ns.tjp.length>0){let f=o.rel8ns.tjp[0],b=await z({addr:f,space:t});if(b.success&&b.ibGibs?.length===1)return b.ibGibs[0];{let p=b.errorMsg??"[unspecified error in get result]";throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${p} (E: 94f0340706ad48c794c6a62c1b235a22)`)}}let i=o.rel8ns.past||[];if(i.length===0){console.warn(`${r} past.length === 0, so there is no tjp.`),P&&console.log(`${r} ibgib is not tjp in data, not in tjp rel8n, and past is empty. so tjp is undefined (I: bf06f664917dcf4492fb9c4c106a6222)`);return}let c=i[i.length-1],l=await z({addr:c,space:t});if(!l.success||l.ibGibs?.length!==1)throw new Error(`get past failed. addr: ${c}`);let d=l.ibGibs[0];return await Ko({ibGib:d,naive:e,space:t})}catch(n){throw console.error(`${r} ${n.message}`),n}}h(Ko,"getTjpIbGib");async function Ql({type:o,space:e,zeroSpace:t,fnUpdateBootstrap:r,fnBroadcast:n}){let a=`[${Ql.name}]`;try{if(!e)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(o){case"roots":return rd({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"tags":return ed({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"secrets":return nd({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"encryptions":return ad({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"outerspaces":return sd({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"autosyncs":return id({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"robbots":return cd({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});case"apps":return ld({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});default:return dd({type:o,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r})}}catch(s){throw console.error(`${a} ${s.message}`),s}}h(Ql,"createSpecial");async function Rt({type:o,skipRel8ToRoot:e,space:t,zeroSpace:r,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${Rt.name}][${o||"falsy type?"}]`;try{P&&console.log(`${s} starting...`);let i=yi({type:o}),c=H.primitive({ib:i}),l=await Rn({src:c,destIb:i,linkedRel8ns:[Se.past,Se.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await V({resTransform:l,space:t}),o!=="roots"&&o!=="latest"&&!e&&await Zl({ibGib:l.newIbGib,linked:!0,space:t,zeroSpace:r,fnBroadcast:a,fnUpdateBootstrap:n}),P&&console.log(`${s} complete.`),l.newIbGib}catch(i){throw console.error(`${s} ${i.message}`),i}}h(Rt,"createSpecialIbGib");async function ed({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${ed.name}]`;try{if(!o)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let a=Me({type:"tags"}),s=await Rt({type:"tags",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t}),i=I({ibGib:s});await Je({key:a,addr:i,space:o,zeroSpace:e,fnUpdateBootstrap:t});let c=[{text:"home",icon:"home-outline"},{text:"favorite",icon:"heart-outline"}];for(let l of c)i=(await td({...l,space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t})).newTagsAddr,await Je({key:a,addr:i,space:o,zeroSpace:e,fnUpdateBootstrap:t});return i}catch(a){return console.error(`${n} ${a.message}`),null}}h(ed,"createSpecial_Tags");async function td({text:o,icon:e,description:t,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${td.name}]`;try{if(P&&console.log(`${i} starting...`),!r)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!o)throw new Error(`${i} text required`);e=e||_l,t=t||Tl;let c=Or(o),l=H.primitive({ib:"tag"}),d=await H.firstGen({parentIbGib:l,ib:c,data:{text:o,icon:e,description:t},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),f=d.newIbGib;await V({resTransform:d,space:r}),await J({ibGib:f,space:r,fnBroadcast:s});let b=await Oh({tagIbGib:f,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newTagIbGib:f,newTagsAddr:b}}catch(c){throw console.error(`${i} ${c.message}`),c}finally{P&&console.log(`${i} complete.`)}}h(td,"createTagIbGibAndSundry");async function rd({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${rd.name}]`;try{if(!o)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let a=Me({type:"roots"}),s=await Rt({type:"roots",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t}),i=I({ibGib:s});await Je({key:a,addr:i,space:o,zeroSpace:e,fnUpdateBootstrap:t});let l=["A","B","C","D","E","F","G"].map(f=>({text:`${f}root`,icon:Ys,description:Ks})),d;for(let f=0;f<l.length;f++){let b=l[f],p=await od({...b,space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r});if(d||(d=p.newRootIbGib),!p.newRootIbGib)throw new Error("(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)");i=p.newRootsAddr,await Je({key:a,addr:i,space:o,zeroSpace:e,fnUpdateBootstrap:t})}if(!d)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await ui({root:d,space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}),i=await ca({key:a,space:o}),!i)throw new Error("(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)");return i}catch(a){return console.error(`${n} ${a.message}`),null}}h(rd,"createSpecial_Roots");async function od({text:o,icon:e,description:t,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${od.name}]`;try{if(!r)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");o=o||Al,e=e||Ys,t=t||Ks;let c=$i(o),l=H.primitive({ib:"root"}),d=await H.firstGen({parentIbGib:l,ib:c,data:{text:o,icon:e,description:t},linkedRel8ns:[Se.past,Se.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:f}=d;await V({resTransform:d,space:r});let b=await ao({type:"roots",rel8nName:Vs,ibGibsToRel8:[f],space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newRootIbGib:f,newRootsAddr:b}}catch(c){throw console.error(`${i} ${c.message}`),c}}h(od,"createRootIbGib");async function nd({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${nd.name}]`;try{if(!o)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let a,s=Me({type:"secrets"}),i=await Rt({type:"secrets",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t});return a=I({ibGib:i}),await Je({key:s,addr:a,space:o,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}h(nd,"createSpecial_Secrets");async function ad({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${ad.name}]`;try{if(!o)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let a,s=Me({type:"encryptions"}),i=await Rt({type:"encryptions",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t});return a=I({ibGib:i}),await Je({key:s,addr:a,space:o,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}h(ad,"createSpecial_Encryptions");async function sd({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${sd.name}]`;try{if(!o)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let a,s=Me({type:"outerspaces"}),i=await Rt({type:"outerspaces",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t});return a=I({ibGib:i}),await Je({key:s,addr:a,space:o,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}h(sd,"createSpecial_OuterSpaces");async function id({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${id.name}]`;try{if(!o)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Me({type:"autosyncs"}),i=await Rt({type:"autosyncs",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t});return a=I({ibGib:i}),await Je({key:s,addr:a,space:o,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}h(id,"createSpecial_Autosyncs");async function cd({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${cd.name}]`;try{if(!o)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Me({type:"robbots"}),i=await Rt({type:"robbots",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t});return a=I({ibGib:i}),await Je({key:s,addr:a,space:o,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}h(cd,"createSpecial_Robbots");async function ld({space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}){let n=`[${ld.name}]`;try{if(!o)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Me({type:"apps"}),i=await Rt({type:"apps",space:o,zeroSpace:e,fnBroadcast:r,fnUpdateBootstrap:t});return a=I({ibGib:i}),await Je({key:s,addr:a,space:o,zeroSpace:e,fnUpdateBootstrap:t}),a=await sa({defaultAppData:Bl,defaultAppRel8ns:kl,space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}),a=await sa({defaultAppData:jl,defaultAppRel8ns:ql,space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}),a=await sa({defaultAppData:Xl,defaultAppRel8ns:Hl,space:o,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:r}),a}catch(a){return console.error(`${n} ${a.message}`),null}}h(ld,"createSpecial_Apps");async function sa({defaultAppData:o,defaultAppRel8ns:e,space:t,zeroSpace:r,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${sa.name}]`;try{P&&console.log(`${s} starting... (I: 677f68789abdc7316887e8f38c764e22)`),P&&console.log(`${s} starting...`);let i=B(o),c=e?B(e):void 0;i.uuid=!i.uuid||i.uuid===ii?await q():i.uuid;let{classname:l}=i,d=si({appData:i,classname:l}),f=await H.firstGen({ib:d,parentIbGib:H.primitive({ib:`app ${l}`}),data:i,rel8ns:c,dna:!0,linkedRel8ns:[Se.ancestor,Se.past],nCounter:!0,tjp:{timestamp:!0}});return await V({resTransform:f,space:t}),await J({ibGib:f.newIbGib,fnBroadcast:a,space:t}),await ao({type:"apps",rel8nName:Vn,ibGibsToRel8:[f.newIbGib],fnBroadcast:a,fnUpdateBootstrap:n,space:t,zeroSpace:r})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{P&&console.log(`${s} complete.`)}}h(sa,"createApp");async function dd({type:o,space:e,zeroSpace:t,fnUpdateBootstrap:r,fnBroadcast:n}){let a=`[${dd.name}]`;try{if(!e)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");P&&console.log(`${a} creating special of type: ${o} (I: 283c8bb30ed6f9698b74b886c6078622)`);let s,i=Me({type:o}),c=await Rt({type:o,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:r});return s=I({ibGib:c}),await Je({key:i,addr:s,space:e,zeroSpace:t,fnUpdateBootstrap:r}),s}catch(s){return console.error(`${a} ${s.message}`),null}}h(dd,"createSpecial_Default");async function fd({ibGib:o,ibGibAddr:e,existingLatest:t,existingLatestAddr:r,tjpAddr:n,space:a}){let s=`[${fd.name}][${e}]`;try{if(P&&console.log(`${s} starting...`),!a)throw new Error("space required. (E: 64eb9a271f5d43deadec30b9638746c8)");let i=o.rel8ns?.past||[],c=t.rel8ns?.past||[];if(i.length===1&&c.length===0)return P&&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 P&&console.log("existing has a past, so it must be newer."),r;if(c.length===0&&i.length===0)return console.warn(`${s} neither existing latest nor prospective new ibGib has a past, so keeping existing.`),r;if(c.includes(e))return P&&console.log("existing by definition is newer"),r;if(i.includes(r))return P&&console.log("ibGib by definition is newer"),e;if(r===e)return P&&console.log("they're the same!"),r;if(r===n&&t.rel8ns?.tjp?.length===1)return P&&console.log("ibGib must be newer because the existingLatestAddr is the tjp, which is by definition first in unique past."),e;if(e===n&&o.rel8ns?.tjp?.length===1)return P&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),r;P&&console.log(`${s} brute forcing through iterating the pasts.`);let l,d=-1,f=h(async(u,m,g)=>{let y=u.rel8ns?.past||[];if(y.includes(g))return l=I({ibGib:u}),-1;if(y.length===0)return m;let w=m+y.length;if(d!==-1&&w>d)return l=I({ibGib:u}),-1;let A=await z({addr:y[0],space:a});if(!A.success||A.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${y[0]}`);return f(A.ibGibs[0],m+y.length,g)},"getPastCount");P&&console.log(`${s} doing ibGibPastCount`);let b=await f(o,0,r);if(l)return l;P&&console.log(`${s} Doing existingPastCount`),d=b;let p=await f(t,0,e);return l||(b>p?(P&&console.log(`${s} ibGibPastCount (${b}) is longer than existingPastCount (${p}), so ibGib is newer.`),l=e):(P&&console.log(`${s} existingPastCount (${p}) is longer than ibGibPastCount (${b}), so ibGib is newer.`),l=r),l)}catch(i){throw console.error(`${s} ${i.message}`),i}finally{P&&console.log(`${s} complete.`)}}h(fd,"getLatestAddr_Brute");function Oh({tagIbGib:o,space:e,zeroSpace:t,fnUpdateBootstrap:r,fnBroadcast:n}){return ao({type:"tags",rel8nName:zs,ibGibsToRel8:[o],space:e,zeroSpace:t,fnUpdateBootstrap:r,fnBroadcast:n})}h(Oh,"rel8TagToTagsIbGib");function la({ibGibs:o,ibGibAddrs:e}){let t=`[${la.name}]`;try{if(!o&&!e)throw new Error("either ibGibs or ibGibAddrs required. (E: 37776788620f4966b0964945ce181fc6)");o&&e&&console.warn(`${t} both ibGibs and ibGibAddrs provided. You should only provide one. Only ibGibAddrs will be checked. (W: dc13f9e197834e2daaba3bcfd08418db)`);let r=e?e.concat():o.map(n=>I({ibGib:n}));for(let n=0;n<r.length;n++){let a=r[n];if(r.filter(s=>s===a).length>1)throw new Error(`duplicate addr found: ${a} (E: 70fbef040dd449c38c667d53b8092053)`)}}catch(r){throw console.error(`${t} ${r.message}`),r}}h(la,"throwIfDuplicates");function mi({space:o,scope:e}){let t=`[${mi.name}]`;try{if(P&&console.log(`${t} starting...`),!o)throw new Error("space required. (E: 3ba16e6c3e5e47948b0e63448da11752)");if(!o.data?.uuid)throw new Error("invalid space (space.data.uuid falsy) (E: 273262b32f2ef27b2e690bc699f33822)");if(!e)throw new Error("scope required. (E: f47801d6c45e2247b42a53d9b604b522)");for(;e.includes(Ue);)P&&console.log(`${t} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),e=e.replace(Ue,"_");let r=o.data.uuid,n=`${yl} ${r} ${e}`;return I({ib:n,gib:Q})}catch(r){throw console.error(`${t} ${r.message}`),r}finally{P&&console.log(`${t} complete.`)}}h(mi,"getSpaceLockAddr");async function pt({space:o,scope:e,secondsValid:t,maxDelayMs:r,fn:n,callerInstanceId:a,maxLockAttempts:s}){let i=`[${pt.name}]`;try{if(P&&console.log(`${i} starting...`),!o)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;P&&console.log(`${i} attempting to acquire lock with scope ${e} (I: fed36d42a975b1c52897a4df804ac722)`);let l;r=(r??0)>0?r:$l;let d=0;s=s??!1?s:Il;do{if(l=await bd({space:o,scope:e,secondsValid:t,instanceId:a}),l?.data?.success)break;let b=Math.ceil(Math.random()*r);await De(b),d++}while(d<s);if(l?.data?.success)P&&console.log(`${i} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`);else throw new Error(`could not acquire lock after ${d} attempts with intermittent delays of ${r} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);let f=`${i}[fn]`;try{P&&console.log(`${f} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(b){throw console.error(`${f} ${b.message}`),b}finally{P&&console.log(`${f} unlocking space with scope: ${e} (I: 21034d9c3395499756e9000e40417d22)`),await hd({space:o,scope:e,instanceId:a}),P&&console.log(`${f} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${i} ${c.message}`),c}finally{P&&console.log(`${i} complete.`)}}h(pt,"execInSpaceWithLocking");async function zo({zeroSpace:o}){let e=`[${zo.name}]`;try{if(P&&console.log(`${e} starting...`),!o)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let t=lr;P&&console.log(`${e} getting from zeroSpace...`);let r=await o.argy({ibMetadata:Tt({space:o}),argData:{cmd:"get",ibGibAddrs:[t]}}),n=await o.witness(r);if(n?.data?.success&&n.ibGibs?.length===1){let a=n.ibGibs[0];return P&&console.log(`${e} bootstrapibGib found: ${X(a)}`),await ci(a)?a:(P&&console.log(`${e} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return P&&console.log(`${e} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(t){throw console.error(`${e} ${t.message}`),t}finally{P&&console.log(`${e} complete.`)}}h(zo,"getValidatedBootstrapIbGib");async function Lh({zeroSpace:o,bootstrapIbGib:e,localSpaceId:t,lock:r,callerInstanceId:n,fnDtoToSpace:a,localSpaceCacheSvc:s}){let i=`[${Lh.name}]`;try{if(!o)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!e)if(P&&console.log(`${i} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),r){let d=lr;P&&console.log(`${i} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),e=await pt({space:o,scope:d,fn:h(async()=>{let f=await zo({zeroSpace:o});if(f)return f;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:qn})}else P&&console.log(`${i} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),e=await zo({zeroSpace:o})??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)");if(t=t??e.data[At],!e.rel8ns)throw new Error("(UNEXPECTED) bootstrapIbGib.rel8ns falsy? it should have been validated by now. (E: 817d9a2a0b98ec0c177cd7ab149b9426)");if(!e.rel8ns[t])throw new Error(`localSpaceId (${t}) not found in bootstrapIbGib.rel8ns (E: 8869884093984ec43f942fea24bd9926)`);let c=e.rel8ns[t][0],l=h(async()=>{let d=await o.argy({ibMetadata:Tt({space:o}),argData:{cmd:"get",ibGibAddrs:[c]}}),f=await o.witness(d);if(f?.data?.success&&f.ibGibs?.length===1){let b=f.ibGibs[0],p=await a(b);return s&&(p.cacheSvc=s),p}else throw new Error(`Could not get local space addr (${c}) specified in bootstrap space (${I({ibGib:e})}). (E: 6d6b45e7eae4472697ddc971438e4922)`)},"fnGet");return r?(P&&console.log(`${i} getting localSpaceId (${t}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await pt({space:o,scope:t,fn:h(()=>l(),"fn"),callerInstanceId:n,secondsValid:qn})):(P&&console.log(`${i} getting localSpaceId (${t}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),l())}catch(c){throw console.error(`${i} ${c.message}`),c}}h(Lh,"getLocalSpace");async function bd({space:o,scope:e,secondsValid:t,instanceId:r}){let n=`[${bd.name}]`;try{if(P&&console.log(`${n} starting...`),!o)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=mi({space:o,scope:e}),i,c=await z({addr:s,space:o,force:!0});if(c.success&&c.ibGibs?.length===1?(i=c.ibGibs[0],i?.data?.expirationUTC?Bs({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)):P&&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=B(i),a.data.alreadyLocked=!0,a.data.success=!1}else{let{ib:l,gib:d}=K({ibGibAddr:s});a={ib:l,gib:d,data:{scope:e,secondsValid:t,instanceId:r,expirationUTC:Fs({seconds:t})}};let f=await o.argy({ibMetadata:Tt({space:o}),argData:{cmd:"put",force:!0,ibGibAddrs:[s]},ibGibs:[a]}),b=await o.witness(f);if(b.data?.success)if((b.data.addrsAlreadyHave??[]).includes(s)){P&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${s}) (I: 2e8a1562947c40698110b64251141753)`);let p=await z({addr:s,space:o,force:!0});if(p.success&&p.ibGibs?.length===1){let u=p.ibGibs[0];a=B(u),a.data.alreadyLocked=!0,a.data.success=!1}else{let u=`${n} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;console.error(u),a.data.success=!1,a.data.errorMsg=u}}else a.data.success=!0;else{let p=`${n} there was an error putting the lock in the space: ${b.data?.errors?.join("|")}`;a.data.success=!1,a.data.errorMsg=p,console.error(p)}}return a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{P&&console.log(`${n} complete.`)}}h(bd,"lockSpace");async function hd({space:o,scope:e,instanceId:t}){let r=`[${hd.name}]`;try{if(P&&console.log(`${r} starting...`),!o)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=mi({space:o,scope:e}),a=await pi({addr:n,space:o,force:!0});if(a.success){let{ib:s,gib:i}=K({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")){P&&console.log(`${r} ${s} (I: b647916fd0f3e5366e9387131be21c22)`);let{ib:i,gib:c}=K({ibGibAddr:n});return{ib:i,gib:c,data:{action:"unlock",success:!0,instanceId:t,scope:e}}}else console.warn(`${r} ${s} (W: 14c84fcac15944bd9a417099964d5d9d)`)}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{P&&console.log(`${r} complete.`)}}h(hd,"unlockSpace");async function Rh({space:o,zeroSpace:e,setSpaceAsDefault:t,createIfNotFound:r}){let n=`[${Rh.name}]`;try{if(P&&console.log(`${n} starting...`),!o)throw new Error("space required. (E: 6fc19548fa7d1d5219e19871f280a322)");if(!o.data?.uuid)throw new Error("space.data.uuid required (E: 6483188ca6f2ed2085fd355595f3ab22)");if(!e)throw new Error("zeroSpace required. (E: abbf156e18b1018d96273e22a260f122)");let a=o.data.uuid,s=I({ibGib:o}),i=await zo({zeroSpace:e});if(i){if(P&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),i.data.spaceIds.includes(a)){P&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let c=i.rel8ns[a][0];c===s?P&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(P&&console.log(`${n} updating rel8ns[${a}] with newSpaceAddr (${s}). (Old address: ${c})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),i.rel8ns[a]=[s])}else P&&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&&(P&&console.log(`${n} setting spaceId (${a}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),i.data[At]=a)}else{if(!r){P&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}P&&console.log(`${n} creating new bootstrap ibgib for spaceId (${a}) with address of (${s}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:c,gib:l}=K({ibGibAddr:lr});i=H.primitive({ib:c}),i.gib=l,i.data={[At]:a,[Wn]:[a]},i.rel8ns={[a]:[s]}}if(!i)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");P&&console.log(`${n} saving bootstrapIbGib: ${X(i)} (I: 3cceca0b98dde90e4a58a734be252322)`),await gi({zeroSpace:e,bootstrapIbGib:i}),P&&console.log(`${n} complete.`)}catch(a){throw console.error(`${n} ${a.message}`),a}}h(Rh,"updateBootstrapIbGib");async function gi({zeroSpace:o,bootstrapIbGib:e}){let t=`[${gi.name}]`;if(!o)throw new Error("zeroSpace required. (E: 818fa8430b8040dca1917f9db0972b22)");if(!e)throw new Error("bootstrapIbGib required. (E: cf21d7f1756710a66aa0e6a28d762723)");let r=await o.argy({ibMetadata:e.ib,argData:{cmd:"put",force:!0,ibGibAddrs:[I({ibGib:e})]},ibGibs:[e]});P&&console.log(`${t} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let n=await o.witness(r);if(n?.data?.success)P&&console.log(`${t} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`);else throw new Error(`${n?.data?.errors?.join("|")||"There was a problem with zeroSpace witnessing the bootstrap^gib primitive."}`)}h(gi,"persistBootstrapIbGibInZeroSpace");async function Uh({spaceId:o,zeroSpace:e}){let t=`[${Uh.name}]`;if(!o)throw new Error("spaceId required. (E: 52f9c31405e24c2999e5a1b32d201a23)");if(!e)throw new Error("zeroSpace required. (E: a115f4007b2c4819a58cf093d5823b23)");await pt({space:e,scope:lr,fn:h(async()=>{let n=await zo({zeroSpace:e});if(!n)throw new Error("bootstrapIbGib falsy in zeroSpace (E: e36a512781b0467ba1bf1d927a7c1d23)");if(!n.data)throw new Error("bootstrapIbGib.data falsy in zeroSpace (E: 8f92104192b44d71891b092481029ab0)");let a=n.data,s=a[Wn]??[];if(s.length<=1)throw new Error(`Cannot delete space (${o}). It is the only remaining local space. (E: 9c27f71120014b08b5e9f89993380e23)`);if(o===a[At])throw new Error(`Cannot delete space (${o}). It is the default local space. Please select a new default space before deleting. (E: f3c30a5170d14b4fb2478d102e3b2e23)`);if(!s.includes(o))throw new Error(`Space (${o}) not found in bootstrap spaceIds. (E: 61fa940e79124430a618e470bc551d23)`);a[Wn]=s.filter(i=>i!==o),n.rel8ns&&delete n.rel8ns[o],await gi({zeroSpace:e,bootstrapIbGib:n})},"fn"),secondsValid:qn})}h(Uh,"deregisterLocalSpaceFromBootstrap");async function Mh({spaceId:o,zeroSpace:e}){let t=`[${Mh.name}]`;if(!o)throw new Error("spaceId required. (E: 7c2a10529a1b412a8069e22e5190b623)");if(!e)throw new Error("zeroSpace required. (E: f112a512019c41a590b512a8e0915623)");let r=await e.argy({ibMetadata:Tt({space:e}),argData:{cmd:"get",ibGibAddrs:[o]}}),n=await e.witness(r);if(n?.data?.success&&(n.ibGibs?.length??0)>0){let a=I({ibGib:n.ibGibs[0]}),s=await e.argy({ibMetadata:Tt({space:e}),argData:{cmd:"delete",ibGibAddrs:[a]}});await e.witness(s)}}h(Mh,"deleteSpaceRecordFromZeroSpace");function Tt({space:o}){return`${o.ib} ${ft()}`}h(Tt,"getSpaceArgMetadata");function pd({space:o}){return`${o.ib} ${ft()}`}h(pd,"getSpaceResultMetadata");function Ei({space:o,spaceData:e,classname:t}){let r=`[${Ei.name}]`;try{if(!o&&!e)throw new Error("either space or spaceData required (E: 4dabec34ee77d67c9cc30ee3c3049622)");if(o&&!o.data)throw new Error("(UNEXPECTED) given space has falsy space.data? (E: 058d298876ebbeada7bbddb9e3da2f23)");if(o&&e){if(o.data.uuid!==e.uuid)throw new Error("(UNEXPECTED) both space and spaceData given, but uuid don't match? (E: efdd4603cba93a17340a76811fe56b24)");if(o.data.n!==e.n)throw new Error("(UNEXPECTED) both space and spaceData given, but n don't match? (E: e51278a707c9bccc57a08a4b86524524)")}if(e??=o.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||Bn;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`${na} ${jn} ${t} ${n} ${a} ${s} ${i}`}catch(n){throw console.error(`${r} ${n.message}`),n}}h(Ei,"getSpaceIb");function Fh({ib:o}){let e=`[${Fh.name}]`;if(!o){let t=`${e} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(t),new Error(t)}return o.startsWith(`${na} ${jn} `)}h(Fh,"isSpaceIb");function da({spaceIb:o}){let e=`[${da.name}]`;try{if(!o)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[t,r,n,a,s,i,c]=o.split(" ");if(t!==na)throw new Error(`invalid spaceIb (${o}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(r!==jn)throw new Error(`invalid spaceIb (${o}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`);if(!n)throw new Error(`invalid spaceIb (${o}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`);if(!a)throw new Error(`invalid spaceIb (${o}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`);if(!s)throw new Error(`invalid spaceIb (${o}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`);let l;if(i&&i!=="undefined")if(Zn.includes(i))l=i;else throw new Error(`invalid spaceIb (${o}). spaceType (${i}) is set but not a valid type. valid types: ${Zn.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let d;if(c&&c!=="undefined")if(Qn.includes(c))d=c;else throw new Error(`invalid spaceIb (${o}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${Qn.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:a,spaceId:s,spaceType:l,spaceSubtype:d}}catch(t){throw console.error(`${e} ${t.message}`),t}}h(da,"parseSpaceIb");async function ve({ibGibs:o,addrs:e,tjps:t,tjpAddrs:r,space:n}){let a=`[${ve.name}]`;try{if(P&&console.log(`${a} starting...`),!n)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(o=o??[],e=e??[],t=t??[],r=r??[],e.length===0&&o.length===0&&t.length===0&&r.length===0)throw new Error("Either addrs, ibGibs, tjps, or tjpAddrs required. (E: 7c6ebfbab98d4d21a431b144457fd991)");let s=new Set(r.concat(t.map(l=>I({ibGib:l})))),i=Array.from(s).map(l=>K({ibGibAddr:l}).gib);o.map(l=>I({ibGib:l})).concat(e).forEach(l=>{let{gib:d}=K({ibGibAddr:l});i.some(b=>d.includes(b))||s.add(l)}),P&&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:Tt({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}}h(ve,"getLatestAddrs");function wi({ibGib_Context:o}){let e=`[${wi.name}]`;try{if(P&&console.log(`${e} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!Jo({ibGib:o}))return;if(["roots","autosyncs"].some(r=>o.ib.includes(r)))throw new Error("cannot perform a modification of this type on this special ibgib (E: b8fb718a7323fc54454464b973412722)")}catch(t){throw console.error(`${e} ${t.message}`),t}finally{P&&console.log(`${e} complete.`)}}h(wi,"throwIfContextIsSpecial");async function Bh({ibGib_Context:o,rel8nName_Context:e,addr:t,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Bh.name}]`;try{if(P&&console.log(`${i} starting... (I: 2dc486bb2d516e4534f437aaf5ec7f22)`),!o)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(!r)throw new Error("space required (E: 2e3562486ed2956a770ed9e8d77a3f22)");let c=Jo({ibGib:o});c&&wi({ibGib_Context:o});let l=await ie({src:o,rel8nsToAddByAddr:{[Sl]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await V({resTransform:l,space:r}),c){let d=I({ibGib:l.newIbGib}),f=ba({ib:o.ib}),b=Me({type:f});await Je({key:b,addr:d,space:r,zeroSpace:n,fnUpdateBootstrap:a})}await J({ibGib:l.newIbGib,fnBroadcast:s,space:r})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{P&&console.log(`${i} complete.`)}}h(Bh,"trash");async function kh({ibGib_Context:o,rel8nName_Context:e,addr:t,space:r,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${kh.name}]`;try{if(P&&console.log(`${i} starting... (I: 38098552b830495187299bb24fcddff0)`),!o)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(!r)throw new Error("space required (E: e19566f2d42347798621447edcae312e)");let c=Jo({ibGib:o});c&&wi({ibGib_Context:o});let l=await ie({src:o,rel8nsToAddByAddr:{[Gl]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await V({resTransform:l,space:r}),c){let d=I({ibGib:l.newIbGib}),f=ba({ib:o.ib}),b=Me({type:f});await Je({key:b,addr:d,space:r,zeroSpace:n,fnUpdateBootstrap:a})}await J({ibGib:l.newIbGib,fnBroadcast:s,space:r})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{P&&console.log(`${i} complete.`)}}h(kh,"archive");function fa(o){let e=`[${fa.name}]`;try{if(!o)return console.error(`${e} name is falsy`),!1;let t=/[\w~.-]+/,r=o.match(t);if(r?.length!==1||r[0].length!==o.length)return console.error(`${e} name can only contain letters, numbers, underscores, hyphens, dots, and tildes`),!1;let n=/[a-zA-Z\d]/;return o[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}}h(fa,"spaceNameIsValid");var ge=!1;function ot(o,e){return typeof o=="object"&&o!==null?`v:1^spaceId:${o.spaceId}^${o.ibGibAddr}`:`v:1^spaceId:${o}^${e}`}h(ot,"getSpaceQualifiedIbGibAddr");function ha(o){try{if(typeof o!="string"||!o.match(Hn))return!1;let t=Jt({sqAddr:o});return!0}catch{return!1}}h(ha,"isSpaceQualifiedAddr");function Jt({sqAddr:o}){let e=`[${Jt.name}]`;if(!o)throw new Error(`${e} sqAddr falsy (E: 3c7af8b05a68272478e830c89b617d26)`);if(typeof o!="string")throw new Error(`(UNEXPECTED) ${e} sqAddr not a string? (E: 172fd36b0e7d02905263bdef1374da26)`);let t=o.match(Hn);if(!t)throw new Error(`${e} invalid sqAddr (${o}). does not match SQ Addr regexp: ${Hn.source} (E: 71c93b63d4a82970c3bada8d92d4f826)`);let r=t[1],n=parseInt(r,10),a=t[2],s=t[3],i=qt({addr:s})??[];if(i.length>0)throw new Error(`${e} invalid sqAddr. ibGibAddr part is not a valid ibGibAddr. errors: ${i.join(",")} (E: 8e105870eb58c78978169d1d7b275526)`);let{ib:c,gib:l}=K({ibGibAddr:s});return{version:n,spaceId:a,ibGibAddr:s,ib:c,gib:l}}h(Jt,"parseSpaceQualifiedIbGibAddr");async function Ai({ibGib:o,rel8nNames:e,space:t}){let r=`[${Ai.name}]`;try{if(!o)throw new Error("ibGib required (E: 9764881f4c59113a98faabb87aba5826)");if(!t)throw new Error("space required (E: ee110894949865a8a9075938471e1826)");e||(e=Object.keys(o.rel8ns||{}));let n={};for(let a of e){let s=o.rel8ns?.[a]||[];if(s.length>0){let i=await z({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: 372b27ed859ca276fe132e7cd3cd1826)`)}else n[a]=[]}return n}catch(n){throw console.error(`${r} ${E(n)}`),n}}h(Ai,"getRel8dIbGibs");async function _t({parentPrimitiveIb:o,ib:e,ibRegExpPattern:t,data:r,rel8ns:n}){let a=`[${_t.name}]`;try{if(!o)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(cr({ib:o})!==null)throw new Error(`Invalid parentPrimitiveIb: ${o}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`);if(!e)throw new Error("ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)");let s=t?new RegExp(t):gl;if(!e.match(s))throw new Error(`invalid ib. does not match regexp (${s})`);let i=Object.keys(n??{}),c=[...sr,"tjp"];if(i.some(b=>c.includes(b)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let f=(await H.firstGen({ib:e,parentIbGib:H.primitive({ib:o}),data:r,rel8ns:n,dna:!1,noTimestamp:!0,nCounter:!1})).newIbGib;return f?.rel8ns?.past&&delete f.rel8ns.past,f?.rel8ns?.tjp&&delete f.rel8ns.tjp,f?.rel8ns?.identity&&delete f.rel8ns.identity,f.gib=await ee({ibGib:{ib:f.ib,data:f.data,rel8ns:f.rel8ns},hasTjp:!1}),f}catch(s){throw console.error(`${a} ${s.message}`),s}}h(_t,"constantIbGib");function pa({binHash:o,binExt:e,binEncoding:t}){return t?e?`bin ${o} ${e} enc=${t}`:`bin ${o} enc=${t}`:e?`bin ${o} ${e}`:`bin ${o}`}h(pa,"getBinIb");function Bw({addr:o}){return ud({addr:o})}h(Bw,"getBinHashAndExt");function ud({addr:o}){let e=`[${ud.name}]`;try{if(!Wo({addr:o}))throw new Error("not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)");let{ib:t}=K({ibGibAddr:o}),r=t.split(" ");if(r.length===2)return{binHash:r[1],binExt:""};if(r.length===3)return r[2].startsWith("enc=")?{binHash:r[1],binExt:"",binEncoding:r[2].substring(4)}:{binHash:r[1],binExt:r[2]};if(r.length===4){if(!r[3].startsWith("enc="))throw new Error(`bin ib (${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:r[1],binExt:r[2],binEncoding:r[3].substring(4)}}else throw new Error('(UNEXPECTED) ibPieces.length not 2, 3, or 4? atow (01/2024) the only components of a bin ib are: atom, binHash, binExt, binEncoding. binExt and binEncoding are optional, with binEncoding being prefixed with "enc=". (E: b05df3c1b3949f76464a83c9fd1c4f24)')}catch(t){throw console.error(`${e} ${t.message}`),t}}h(ud,"parseBinIb");function Wo({ibGib:o,addr:e}){let t=`[${Wo.name}]`;try{if(!o&&!e)throw new Error("either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)");if(o&&!o.data)return!1;e=e||I({ibGib:o});let{ib:r,gib:n}=K({ibGibAddr:e});if(!r||!n||!r.startsWith("bin "))return!1;if(n.length!==64)throw new Error('ib starts with "bin " but gib length is not 64, so return false. Two things: 1) bin ibgibs are expected to be stones, i.e., have no temporal junction point and only a single punctiliar hash for the gib. the default hash used atow (01/2024) is sha-256, so the length should be 64. But this may not be true if using another hash algorithm. need to change this function when this becomes the case. (W: 60725d65d13c4b4fbb7b96d7feb19d67)');let a=r.split(" ");if(a.length===2){if(!a[1].match(Ie))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)')}else if(a.length===3){if(!a[1].match(Ie))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)')}else if(a.length===4){if(!a[1].match(Ie))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)');if(!a[3].startsWith("enc="))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[3].startsWith("enc=")? (E: 4c8a0c3b07a90d30e3d1a4373d57d824)')}else throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited ibPieces length is not 2, 3 or 4? (E: c7eccf88518304997c7e42b32e08d224)');return!0}catch(r){throw console.error(`${t} ${r.message}`),r}}h(Wo,"isBinary");function yi({type:o}){if(!o.match(Js))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${Js.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${o}`}h(yi,"getSpecialIbGibIb");function ba({ib:o}){let e=`[${ba.name}]`;try{if(ge&&console.log(`${e} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!o)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!Jo({ib:o}))throw new Error("ib is not special (E: 174aff63b992adff3ac2394643735922)");let t=o.split(" ");if(t.length<3)throw new Error('invalid ib. should be space-delimited in form of "meta special [type]" (E: ffd89e2cbe63427f98634ab897aab222)');let r=t[2];return Object.values(jo).some(n=>n===r)||console.warn(`unknown special type (${r}). This may be expected, but atow I am adding special types to the SpecialIbGibType enum-like. (W: f4e26c3ebb57fe49d69014a4ba32a922)`),r}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ge&&console.log(`${e} complete.`)}}h(ba,"getSpecialTypeFromIb");function jh({type:o}){return`${yi({type:o})}^${Q}`}h(jh,"getSpecialIbGibAddr");function Me({type:o}){return`${Cl} ${jh({type:o})}`}h(Me,"getSpecialConfigKey");function Jo({ib:o,ibGib:e}){if(!o&&!e?.ib)throw new Error("either ib or ibGib.ib required (E: b4cf539638d7966c2e351987f55e1a23)");return(o??e?.ib)?.startsWith("meta special")}h(Jo,"isSpecial");function $i(o){let e=`[${$i.name}]`;if(!o)throw new Error(`${e} text required.`);return`root ${o}`}h($i,"getRootIb");function Or(o){let e=`[${Or.name}]`;if(!o)throw new Error(`${e} tag required.`);return`tag ${o}`}h(Or,"tagTextToIb");function nt({ibGibs:o,filterPrimitives:e}){let t=`[${nt.name}]`;try{let r={},n={},a={};return(e?o.filter(i=>i.gib??i.gib!==Q):o).forEach(i=>{md({ibGib:i})?(i.rel8ns?.dna??[]).length>0?r[i.gib]=i:n[i.gib]=i:a[i.gib]=i}),{mapWithTjp_YesDna:r,mapWithTjp_NoDna:n,mapWithoutTjps:a}}catch(r){throw console.error(`${t} ${r.message}`),r}}h(nt,"splitPerTjpAndOrDna");function at({ibGibs:o}){let e=`[${at.name}]`;try{ge&&console.log(`${e} starting...`);let{mapWithTjp_YesDna:t,mapWithTjp_NoDna:r}=nt({ibGibs:o,filterPrimitives:!0}),n={...t,...r},a=Object.values(n),s=Uo({items:a,keyFn:h(i=>i.data?.isTjp?I({ibGib:i}):i.rel8ns?.tjp?i.rel8ns?.tjp[0]??"":(ge&&console.log(`${e} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return ge&&console.log(`${e} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${X(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),Object.entries(s).forEach(([i,c])=>{c.some(l=>l.data?.n===void 0)&&console.warn(`${e} timeline includes ibgibs with ibGib.data?.n === undefined (W: cab9a6b64a38c4279fe82c3569bbab22)`),c.sort((l,d)=>(l.data?.n??-1)>(d.data?.n??-1)?1:-1)}),ge&&console.log(`${e} after sort ibGibsWithTjpGroupedByTjpAddr: ${X(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),s}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ge&&console.log(`${e} complete.`)}}h(at,"getTimelinesGroupedByTjp");function md({ibGib:o}){let e=`[${md.name}]`;if(!o)throw new Error("(UNEXPECTED) ibGib falsy? (E: ce3a59f9db14e6158bb2c438ca1a3823)");if((o.rel8ns?.tjp?.length??0)>0||o.data?.isTjp)return!0;let t=["fork^gib","mut8^gib","rel8^gib"];return(o.rel8ns?.ancestor??[]).some(n=>t.includes(n))?!1:o.gib?o.gib.includes(vt)?!0:o.gib===Q?!1:!!Ne({ibGibAddr:I({ibGib:o})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}h(md,"hasTjp");function ye({ibGib:o,defaultIfNone:e="undefined"}){let t=`[${ye.name}]`;try{let r=gd({ibGibs:[o],defaultIfNone:e});return r&&Object.keys(r).length===1?Object.values(r)[0]:void 0}catch(r){throw console.error(`${t} ${r.message}`),r}}h(ye,"getTjpAddr");function gd({ibGibs:o,defaultIfNone:e="undefined"}){let t=`[${gd.name}]`;try{let r={};return o.forEach(n=>{let a=I({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,r[a]=s}),r}catch(r){throw console.error(`${t} ${r.message}`),r}}h(gd,"getTjpAddrs");async function Ii({ibGib:o,naive:e=!0}){let t=`[${Ii.name}]`;try{if(!o)throw new Error("ibGib required.");if(e){if(o.data)return o.data.isTjp?!0:o.rel8ns?o.rel8ns.past&&o.rel8ns.past.length>0?!1:!!(o.rel8ns.past&&o.rel8ns.past.length===0):(ge&&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(r){throw console.error(`${t} ${r.message}`),r}}h(Ii,"isTjp_Naive");function Fe({ibGib:o}){let e=`[${Fe.name}]`;o.ib||console.warn(`${e} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),o.gib||console.warn(`${e} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let t={ib:(o.ib||"").slice()};return o.gib&&(t.gib=o.gib.slice()),o.data&&(Wo({ibGib:o})?t.data=o.data.slice():t.data=B(o.data)),o.rel8ns&&(t.rel8ns=B(o.rel8ns)),t}h(Fe,"toDto");function Lr(o){let e=`[${Lr.name}]`;try{return ge&&console.log(`${e} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!o&&typeof o.ib=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ge&&console.log(`${e} complete.`)}}h(Lr,"isIbGib");function hr({ibGib:o,data:e,timestamp:t}){let r=`[${hr.name}]`;try{ge&&console.log(`${r} starting... (I: 35cb68744bcf6139d78e37de644fad23)`),t=t||e?.timestamp||o?.data?.timestamp;let n=o?.data?.timestampMs||e?.timestampMs;if(!t){let a=`${r} 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()!==Xn)return ge&&console.log(`${r} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`),{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${r} data.timestamp (${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()!==Xn)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${r} data.timestamp is a non-integer string but not a valid date timestamp string (new date instantiated produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(s),{valid:!1,emsg:s}}}else if(typeof t=="number")if(Number.isInteger(t)){console.warn(`${r} expected data.timestamp to be a string but is a number (W: 9d786f4d4e8d4279b5af7bee19bf721b)`);let a=new Date;if(a.setTime(t),a.toString()!==Xn)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${r} 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=`${r} 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=`${r} unknown typeof timestamp (${typeof t}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;return console.error(a),{valid:!1,emsg:a}}}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{ge&&console.log(`${r} complete.`)}}h(hr,"getTimestampInfo");async function Ve({addrs:o,readCache_graph:e,readCache_array:t,space:r}){let n=`[${Ve.name}]`;try{ge&&console.log(`${n} starting... (I: 5db66871239dfa05182277f886a20926)`),e??={},t??=[];let a={...e};t.forEach(l=>a[I({ibGib:l})]=l);let s=Object.keys(e),i=o.filter(l=>!s.includes(l));if(i.length>0){ge&&console.log(`${n} ${i.length} addrsNotFoundInCache: ${i} (I: fccbd18116ffb849f813aaebfc6c0826)`);let l=[r],d=i.concat();for(let f of l){let b=await z({addrs:d,space:f});if(b.success&&b.ibGibs&&b.ibGibs.length===d.length)b.ibGibs.forEach(p=>a[I({ibGib:p})]=p),d=[];else if(b.ibGibs&&b.ibGibs.length>0){if(d=d.filter(p=>!b.ibGibs.some(u=>I({ibGib:u})===p)),d.length===0)break}else ge&&console.log(`${n} no addrs found in space (${f.ib}). trying next space. (I: 4f99d8bacbb10ab3f8737a752564b326)`)}if(d.length>0)throw new Error(`could not get all addrs from cache or spaces. addrsStillNotFound: ${d}. spaces: ${l.map(f=>f.ib).join("|")} (E: 0c6418f83dd85bda886e56f5b98f3126)`)}let c=[];for(let l of o){let d=a[l];if(!d)throw new Error(`(UNEXPECTED) allIbGibs_graph doesn't have addr? We're expecting logic to preclude this at this point. addr: ${l} (E: f68e1d236ae5e3eb08da9933c8230626)`);c.push(d)}return c}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{ge&&console.log(`${n} complete.`)}}h(Ve,"getIbGibsFromCache_fallbackToSpaces");async function ae({addr:o,space:e,metaspace:t}){let r=`[${ae.name}]`;try{if(ge&&console.log(`${r} starting... (I: 9252059c96132637381b3be5486e6826)`),!o)throw new Error("(UNEXPECTED) addr falsy? (E: aeb9084d7f68dabb8a49fd68526ff826)");if(!e)throw new Error("(UNEXPECTED) space falsy? (E: 3ec9df4de82847e13f087bea6f98b826)");let n=ha(o)?Jt({sqAddr:o}).ibGibAddr:o,a=qt({addr:n})??[];if(a.length>0)throw new Error(`invalid incoming addr (${o}). (if space-qualified, then invalid extracted ibGibAddr). errors: ${a.join(", ")} (E: 040dbbcac39990abc8871a1d08b3d826)`);let s;try{let i=await z({space:e,addrs:[n]});if(!i.success||i.errorMsg)throw new Error(`resGet failed. resGet.success: ${i.success}.errorMsg: ${i.errorMsg} (E: 13f3d82381b87f8078583ad8b3676826)`);if(!i.ibGibs)throw new Error("(UNEXPECTED) resGet.success and no errorMsg, but resGet.ibGibs falsy? (E: f3a75e6fe96b07d288ba9b3976e84826)");if(i.ibGibs.length===0)throw new Error("(UNEXPECTED) resGet.success and no errorMsg, but resGet.ibGibs empty? (E: 4a06589d30050208284fef68adf20426)");if(i.ibGibs.length>1)throw new Error("(UNEXPECTED) resGet.success and no errorMsg, but resGet.ibGibs.length > 1? what in the world? (E: a4d01caa4a78a0a1581b3bb8748af826)");s=i.ibGibs[0]}catch(i){ge&&console.log(`${r} suppressing error: ${E(i)} (I: 1256ce73d8e8b567ff4fee4ea48c5d26)`)}return s}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{ge&&console.log(`${r} complete.`)}}h(ae,"getIbGibFromSpace");async function st({addrs:o,space:e}){let t=`[${st.name}]`;try{if(ge&&console.log(`${t} starting... (I: 648eb9b61718fbc1684aabc60cba6826)`),!o)throw new Error("(UNEXPECTED) addrs falsy? (E: 258e489345f1c4b5794e4618f4118c26)");if(!e)throw new Error("(UNEXPECTED) space falsy? (E: 9cb95bc39b41c1756c6e85384f766a26)");if(o.length===0)return[];let r=o.map(i=>ha(i)?Jt({sqAddr:i}).ibGibAddr:i);for(let i of r){let c=qt({addr:i})??[];if(c.length>0)throw new Error(`invalid incoming addr (${i}). errors: ${c.join(", ")} (E: 1674df15579c46cecd035ff637f41426)`)}let n=await z({space:e,addrs:r});if(!n.success||n.errorMsg)throw new Error(`resGet failed. resGet.success: ${n.success}. errorMsg: ${n.errorMsg} (E: 1a4c08eabeb957f388a79d7b42b60b26)`);if(!n.ibGibs||n.ibGibs.length!==r.length){let c=n.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find all addrs. addrsNotFound: ${c}? resGet.errorMsg: ${n.errorMsg} (E: 5ee272792fe8af335a8fd918c0971a26)`)}let a=new Map;for(let i of n.ibGibs||[]){let c=I({ibGib:i});a.set(c,i)}let s=[];for(let i of r){let c=a.get(i);c&&s.push(c)}return s}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ge&&console.log(`${t} complete.`)}}h(st,"getIbGibsFromSpace");async function ua({ibGib:o,space:e}){let t=`[${ua.name}]`;try{ge&&console.log(`${t} starting... (I: 64f6a8bd1248f8c3c8c86834431adb26)`);let r=I({ibGib:o}),n=ye({ibGib:o,defaultIfNone:"undefined"});if(!n)return ge&&console.log(`${t} tjpAddr falsy. returning incoming ibGib (no timeline means no latest tip possible) (I: 621528e00b6988f0abb8a161e7042226)`),o;let a=await ve({ibGibs:[o],space:e});if(!a)throw new Error("(UNEXPECTED) resLatest falsy? (E: 8ce878315ec4020c082ee7796084b826)");if(!a.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: 3af5a84dd1eba399fcca51e179b36826)");if(!a.data.latestAddrsMap)throw new Error("(UNEXPECTED) resLatest.data.latestAddrsMap falsy? (E: 37276c35ae58f65cb674389343c2fc26)");let{latestAddrsMap:s}=a.data,i=s[r]??s[n]??r;if(i&&i!==r){let c=await ae({addr:i,space:e});if(c&&(c.data?.n??0)>=(o.data?.n??0))return c;console.warn(`${t} did not find latest. using incoming ibGib (W: 1079fd20b9183fc8a8fef55a8ad2d826)`)}return o}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ge&&console.log(`${t} complete.`)}}h(ua,"resolveLatestIbGibInSpace");async function ma({ibGibs:o,space:e}){let t=`[${ma.name}]`;try{if(ge&&console.log(`${t} starting... (I: 8b0c418702fb42a6a12ee0153833f426)`),!e)throw new Error("space required. (E: b65c19273c524e9389271630af220926)");if(!o||o.length===0)return[];let r=[],n=[],a=[];for(let b of o){let p=I({ibGib:b}),u=ye({ibGib:b,defaultIfNone:"undefined"});n.push(p),a.push(u||""),u&&r.push(b)}if(r.length===0)return o;let s=await ve({ibGibs:r,space:e});if(!s||!s.data||!s.data.latestAddrsMap)throw new Error("(UNEXPECTED) resLatest or latestAddrsMap falsy? (E: a951d3820ff541c88ba46f7725902126)");let{latestAddrsMap:i}=s.data,c=[],l=[];for(let b=0;b<o.length;b++){let p=n[b],u=a[b],m=i[p]??i[u]??p;l.push(m),m&&m!==p&&c.push(m)}let d=new Map;if(c.length>0){let b=Array.from(new Set(c)),p=await st({addrs:b,space:e});for(let u of p){let m=I({ibGib:u});d.set(m,u)}}let f=[];for(let b=0;b<o.length;b++){let p=o[b],u=l[b];if(u&&u!==n[b]){let m=d.get(u);if(m&&(m.data?.n??0)>=(p.data?.n??0)){f.push(m);continue}}f.push(p)}return f}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ge&&console.log(`${t} complete.`)}}h(ma,"resolveLatestIbGibsInSpace");var Ed=!1,qh="space_gib_db",Xh="space_gib_store",Hh="space_gib_api_key";var Vh="agent";var Hw=Or(Vh);var Vw={dbName:qh,storeName:Xh,additionalStoreNames:[Fn],apiKeyName:Hh};var wd="0.0.36";var pr=!1,zw="[web^gib timer]",ga="ibgib";var Wh="agent",Jw="body-outline",Zw="This tag tracks the active agents for the current local user space.",Qw=Or(Wh),yd="#78f87e88",$d="#78f87e10",Id="#ffffff";var e2="AUTOMATED_TEXT";var Gt=!1;function Ad(o){return new Promise((e,t)=>{let r=new Blob([o],{type:"application/octet-stream"}),n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1];e(s)},n.onerror=a=>t(a),n.readAsDataURL(r)})}h(Ad,"uint8ArrayToBase64");async function _d(o){let e=`data:application/octet-stream;base64,${o}`,n=await(await(await fetch(e)).blob()).arrayBuffer();return new Uint8Array(n)}h(_d,"base64ToUint8Array");async function Ea({graph:o}){let e=`[${Ea.name}]`;try{Gt&&console.log(`${e} starting... (I: 4ddb8803cf68e1d3d35f60680cb69825)`);let t=JSON.parse(JSON.stringify(o));for(let n in t)o[n].data instanceof Uint8Array&&(t[n].data={_dataType:"Uint8Array_Base64",value:await Ad(o[n].data)});let r=JSON.stringify(t);return Gt&&console.log(`${e} jsonString.length: ${r.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),r}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Gt&&console.log(`${e} complete.`)}}h(Ea,"serializeGraphToString");async function wa({jsonString:o}){let e=`[${wa.name}]`;try{Gt&&console.log(`${e} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`);let r=JSON.parse(o,h((n,a)=>(a&&a._dataType==="Uint8Array_Base64",a),"reviver"));for(let n in r){let a=r[n].data;a&&a._dataType==="Uint8Array_Base64"&&(r[n].data=await _d(a.value))}return r}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Gt&&console.log(`${e} complete.`)}}h(wa,"deserializeStringToGraph");async function Td(o){let e=`[${Td.name}]`;try{Gt&&console.log(`${e} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let t=await Ea({graph:o}),r=new TextEncoder().encode(t),a=new Response(r).body.pipeThrough(new CompressionStream("gzip"));return await new Response(a).blob()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Gt&&console.log(`${e} complete.`)}}h(Td,"compressIbGibToBlob");async function Yh(o){let e=o.stream().pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).text();return await wa({jsonString:t})}h(Yh,"decompressIbGibFromBlob");async function _i({graph:o}){let e=`[${_i.name}]`;try{Gt&&console.log(`${e} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let r=await(await Td(o)).arrayBuffer(),n=new Uint8Array(r);return await Ad(n)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Gt&&console.log(`${e} complete.`)}}h(_i,"compressIbGibGraphToString");async function Ti({compressedBase64:o}){let e=`[${Ti.name}]`;try{Gt&&console.log(`${e} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let t=await _d(o),r=new Blob([t],{type:"application/gzip"});return await Yh(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Gt&&console.log(`${e} complete.`)}}h(Ti,"decompressIbGibGraphFromString");var Gd="export";var Zo=!1;function Sd({data:o}){let e=`[${Sd.name}]`;try{Zo&&console.log(`${e} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:t,dependencyGraphAsString:r,timestamp:n}=o,a=r.length,s=ft(n),i=o.compression==="gzip"?"gzip":"raw";if(!o.timestamp)throw new Error("(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)");let c=new Date(o.timestamp),{ib:l,gib:d}=K({ibGibAddr:o.contextIbGibAddr}),b=Ne({gib:d}).tjpGib??d,p=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${Gd} ${p} ${i} ${t} ${a} ${b}`}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Zo&&console.log(`${e} complete.`)}}h(Sd,"getRawExportIb");async function Gi({ibGib:o,metaspace:e,space:t,compress:r,live:n,ignoreErrors:a}){let s=`[${Gi.name}]`;try{if(Zo&&console.log(`${s} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!o)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let i=I({ibGib:o}),c=[],l=await ne({ibGib:o})??[];if(l.length>0){let y=`ibGib had validation errors: ${l} (E: 84890bbc0598192498178a98ae299825)`;if(a)c.push({errorMsg:y,ibGibAddr:i});else throw new Error(y)}let d=await e.getDependencyGraph({ibGib:o,live:n,space:t}),f=r?await _i({graph:d}):await Ea({graph:d}),b=ye({ibGib:o,defaultIfNone:"incomingAddr"})??i,p=new Date,u={contextIbGibAddr:i,tjpAddr:b,dependencyGraphAsString:f,graphSize:Object.keys(d).length,timestamp:rt(p),timestampMs:p.getMilliseconds()};r&&(u.compression="gzip");let m={ib:Sd({data:u}),data:u},g=await ee({ibGib:m,hasTjp:!1});return m.gib=g,Zo&&console.log(`${s} JSON.stringify(exportIbGib).length: ${JSON.stringify(m).length} (I: db3a8d913a91d8fc5d6e45981e034822)`),{rawExportIbGib:m,manifest:Object.keys(d),errors:c.length>0?c:void 0}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{Zo&&console.log(`${s} complete.`)}}h(Gi,"getRawExportIbGib");var g2="ibgib-shell-ready",E2="ibgib-ui-busy",w2="ibgib-ui-message",y2="ibgib-identity-request-change",$2="ibgib-identity-changed",I2="ibgib-identity-update-available",A2="ibgib-identity-renewal-required",_2="show-identity-manager",T2="show-keystone-creator",G2="show-add-device",S2="show-privacy-policy";var xd=pr;async function ur({title:o,msg:e,prompt:t,showInput:r,defaultValue:n,okButtonTitle:a,cancelButtonTitle:s,isPassword:i,isBusy:c,animationEmoji:l,passkeys:d,passkeyButtonTitle:f,onPasskeyAuth:b}){let p=`[${ur.name}]`;try{xd&&console.log(`${p} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let u=document.getElementById("fullscreen-dialog"),m=document.getElementById("fullscreen-dialog-body"),g=document.getElementById("fullscreen-dialog-title"),y=document.getElementById("fullscreen-dialog-message"),w=document.getElementById("fullscreen-dialog-prompt-input"),A=document.getElementById("fullscreen-dialog-ok-button"),G=document.getElementById("fullscreen-dialog-cancel-button");if(!u||!m||!g||!y||!w||!A||!G)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(g.textContent=o||"",[...y.childNodes].forEach(x=>y.removeChild(x)),(e||"").split(`
|
|
9
|
+
`).forEach(x=>{let L=document.createElement("p");L.textContent=x,y.appendChild(L)}),l){let x=document.createElement("div");x.id="fullscreen-dialog-animation-emoji",x.textContent=l,x.style.fontSize="3.5rem",x.style.textAlign="center",x.style.margin="1.5rem 0",x.style.animation="spin-bounce 5s infinite ease-in-out",y.appendChild(x)}let $=document.getElementById("fullscreen-dialog-passkey-container");$&&$.remove();let _=null,S=null,D=null,C=Object.values(d||{}).filter(x=>x!=null);if(C.length>0&&b&&!c){_=document.createElement("div"),_.id="fullscreen-dialog-passkey-container",_.style.margin="1rem 0",_.style.textAlign="center",S=document.createElement("button"),S.id="fullscreen-dialog-btn-passkey",S.type="button",S.className="action-btn",S.style.width="100%",S.style.padding="0.75rem 1rem",S.style.background="linear-gradient(135deg, #1b5e20, #2e7d32)",S.style.color="#ffffff",S.style.fontWeight="bold",S.style.borderRadius="8px",S.style.border="1px solid rgba(255,255,255,0.2)",S.style.cursor="pointer",S.style.fontSize="0.95rem",S.style.marginBottom="0.75rem",S.textContent=f||"\u{1F6E1}\uFE0F Touch ID / Security Key",C.length>1&&(D=document.createElement("select"),D.style.width="100%",D.style.padding="0.4rem",D.style.marginBottom="0.5rem",D.style.borderRadius="4px",D.style.background="rgba(0,0,0,0.3)",D.style.color="inherit",D.style.border="1px solid rgba(255,255,255,0.2)",C.forEach((L,U)=>{let O=document.createElement("option");O.value=U.toString(),O.textContent=`${L.name||"Key"} (${L.credentialId?.substring(0,8)}...)`,D.appendChild(O)}),_.appendChild(D)),_.appendChild(S);let x=document.createElement("div");x.style.display="flex",x.style.alignItems="center",x.style.justifyContent="center",x.style.gap="0.5rem",x.style.fontSize="0.8rem",x.style.color="var(--clr-text-secondary, #b3b3b3)",x.style.margin="0.5rem 0",x.innerHTML=`
|
|
10
|
+
<span style="flex: 1; height: 1px; background: rgba(255,255,255,0.15);"></span>
|
|
11
|
+
<span>OR enter Password below</span>
|
|
12
|
+
<span style="flex: 1; height: 1px; background: rgba(255,255,255,0.15);"></span>
|
|
13
|
+
`,_.appendChild(x),w.parentElement?.insertBefore(_,w)}w.classList.remove("collapsed"),G.classList.remove("collapsed"),G.style.display="inline-block",A.style.display="inline-block",A.textContent=a||"OK";let N=h(x=>{(x.key==="Enter"||x.key===`
|
|
14
|
+
`)&&x.ctrlKey&&A.click()},"onKeypress");return c?(w.classList.add("collapsed"),G.style.display="none",A.style.display="none"):t||r?(w.addEventListener("keypress",N),r?(w.autofocus=!0,w.value=n??"",w.addEventListener("keypress",x=>{x.key==="Enter"&&A.click()}),i?(w.type="password",w.autocomplete="off",w.required=!0):(w.type="text",w.autocomplete="on",w.required=!1,w.attributes["auto-complete"]="on")):(w.autofocus=!1,w.classList.add("collapsed")),G.textContent=s||"Cancel"):(w.classList.add("collapsed"),G.style.display="none"),new Promise(x=>{if(c){let k=h(oe=>{oe.preventDefault()},"onCancelEvent");u.addEventListener("cancel",k);let Ee=h(()=>{u.removeEventListener("cancel",k),u.close()},"close"),pe=h(({title:oe,msg:re,animationEmoji:fe})=>{if(oe!==void 0&&(g.textContent=oe),re!==void 0){[...y.childNodes].forEach(se=>{se.id!=="fullscreen-dialog-animation-emoji"&&y.removeChild(se)});let W=re.split(`
|
|
15
|
+
`),Z=document.getElementById("fullscreen-dialog-animation-emoji");W.forEach(se=>{let Y=document.createElement("p");Y.textContent=se,Z?y.insertBefore(Y,Z):y.appendChild(Y)})}if(fe!==void 0){let W=document.getElementById("fullscreen-dialog-animation-emoji");fe?(W||(W=document.createElement("div"),W.id="fullscreen-dialog-animation-emoji",W.style.fontSize="3.5rem",W.style.textAlign="center",W.style.margin="1.5rem 0",W.style.animation="spin-bounce 5s infinite ease-in-out",y.appendChild(W)),W.textContent=fe):W&&W.remove()}},"update");u.open||u.showModal(),De(1e3).then(()=>{m.scrollTo({top:0,behavior:"smooth"})}),x({close:Ee,update:pe});return}let L=h(()=>{(t||r)&&w.removeEventListener("keypress",N),S&&S.removeEventListener("click",O),_&&_.remove(),A.removeEventListener("click",U),G.removeEventListener("click",M),u.removeEventListener("close",F)},"removeEventListeners"),U=h(()=>{L();let k=r?w.value??"":"true";w&&(w.value=""),u.close(k),C.length>0?x({secret:k,poolId:"manage"}):x(k)},"onOK"),O=h(async()=>{try{if(!b)return;S.disabled=!0,S.textContent="Waiting for biometrics / security key...";let k=C[0];if(D){let pe=parseInt(D.value,10);k=C[pe]||C[0]}let Ee=await b(k);Ee?(L(),w&&(w.value=""),u.close(Ee),x({secret:Ee,poolId:k.poolId||"passkey-manage"})):(S.disabled=!1,S.textContent=f||"\u{1F6E1}\uFE0F Touch ID / Security Key")}catch(k){console.warn("Passkey assertion in dialog failed/cancelled:",k),S.disabled=!1,S.textContent=f||"\u{1F6E1}\uFE0F Touch ID / Security Key"}},"onPasskeyClick");S&&S.addEventListener("click",O);let M=h(()=>{L(),w&&(w.value=""),u.close(void 0),x(void 0)},"onCancel"),F=h(()=>{L(),w&&(w.value=""),u.close(void 0),x(void 0)},"onClose");A.addEventListener("click",U),G.addEventListener("click",M),u.addEventListener("close",F),u.open||u.showModal(),De(1e3).then(()=>{m.scrollTo({top:0,behavior:"smooth"})})})}catch(u){throw console.error(`${p} ${E(u)}`),u}finally{xd&&console.log(`${p} complete.`)}}h(ur,"showFullscreenDialog");var je=pr;async function Kh({metaspace:o,space:e}){let t=`[${Kh.name}]`;try{je&&console.log(`${t} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let r=await o.getSpecialIbGib({type:jo.tags,space:e});if(!r)throw new Error(`tagsIbGib not found in metaspace. space: ${e?e.ib:"default local user space"} (E: 4734c510a411274315c0add8f70e1925)`);return r}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{je&&console.log(`${t} complete.`)}}h(Kh,"getTagsIbGib");function Si({scope:o,ibGib:e,ibGibAddr:t,defaultNameIfError:r}){let n=`[${Si.name}]`;try{if(!e&&!t)throw new Error(`${n} Must provide either ibGib or ibGibAddr. (E: 6627e87b36f8c13748ba228800301726)`);o.includes(" ")&&(console.warn(`${n} scope includes one or more spaces. These will be converted to double underscores. (W: 1554a81454e8ae0a6858ea5dd17f8925)`),o=o.replace(/ /g,"__"));let a,s,i;if(e){if(!e.data)throw new Error("(UNEXPECTED) ibGib.data falsy? (E: 1dae78107356afa1385fde481f1adf26)");if(!e.rel8ns)throw new Error("(UNEXPECTED) ibGib.rel8ns falsy? (E: 4019f8c7a3d8e32cc8a4dab8b5556826)");if(!e.rel8ns.ancestor)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor falsy? (E: c02ec8806b9879d75ea2c9759b263826)");if(e.rel8ns.ancestor.length===0)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor.length === 0? there should be at least one ancestor (E: 6fa0a890a57412e9282efcc8f91da526)");if(e&&t&&I({ibGib:e})!==t)throw new Error("(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: 3db28445092a68cdc2ac58e857a8e826)");let d=e.rel8ns.ancestor.filter(b=>Ce({gib:K({ibGibAddr:b}).gib}));if(d.length===0){debugger;console.error(`${n} ibGib has no primitive ancestor addrs? Still going to work off of the ib then, which should have the atom as the first space-delimited term. (E: f043d1353b584f3cb8c822eeb0e8f826)`)}let f=d.at(-1);a=K({ibGibAddr:f}).ib,i=a}t??=I({ibGib:e});let{ib:c}=K({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: 9128b8f4a32831a7a807232b7ae14426)");i=s.toLowerCase(),je&&console.log(`${n} ancestorIbOrAtom: ${i} (I: 1ca518f4b3b3dc7fa8372f5f1fd72f26)`);let l=`${i}_${o}index`;return je&&console.log(`${n} indexName: ${l} (I: 1b7868b711684efa53a4def8cddf6826)`),l}catch(a){if(r)return console.warn(`${n} error happened but defaultNameIfError (${r}) provided. So will return this value. error that was thrown: ${E(a)}`),r;throw console.error(`${n} ${E(a)}`),a}}h(Si,"getIndexNameFromIbGib");async function zh({scope:o,ibGib:e,metaspace:t,space:r,skipGetLatest:n}){let a=`[${zh.name}]`;try{if(je&&console.log(`${a} starting... (I: f19dc86aab380fe809aef27ccc7a7425)`),!o)throw new Error("scope required to be a non-empty string (E: 73e702495c38c7d8747d1cf8850af825)");if(!e)throw new Error("ibGib required (E: 9f71a8c016daf9707ed9b098262ca826)");let s=Si({scope:o,ibGib:e}),i=ye({ibGib:e,defaultIfNone:"incomingAddr"}),c=h(async()=>{let d=await t.getSpecialIbGib({type:s,space:r,initialize:!1,dontWarnIfNotExist:!0,lock:!0});if(!d||!d.data){je&&console.log(`${a} special ${o} index ibGib not found for indexSpecialIbGibType (${s}). No coupled ibgib registered, returning undefined. (I: eb5f53cb78a22be4d819b3bd15e37b26)`);return}let b=(d.data.coupleMap??d.data.agentMap??{})[i];if(!b){je&&console.log(`${a} No coupled ${o} ibgib address found for domain ${i} in the coupled index map. indexSpecialIbGibType: ${s}. returning undefined. (I: 3f0966a72076241947446bb81dcca726)`);return}let p=n?b:await t.getLatestAddr({addr:b,space:r})??b,u=await t.get({addrs:[p],space:r});if(u.errorMsg||(u.ibGibs??[]).length!==1)throw new Error(`couldn't get latest coupled ibgib (${p}) for domain ${i}. (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);return u.ibGibs[0]},"fn");return await pt({scope:s,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:r,callerInstanceId:a+ft(),fn:c})}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{je&&console.log(`${a} complete.`)}}h(zh,"getLocalCoupledIbGibForDomainIbGib");async function Jh({scope:o,domainIbGib:e,localIbGib:t,metaspace:r,space:n}){let a=`[${Jh.name}]`;try{je&&console.log(`${a} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let s=Si({scope:o,ibGib:e}),i=ye({ibGib:e}),c=I({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 pt({scope:s,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:h(async()=>{let d=await r.getSpecialIbGib({type:s,space:n,initialize:!0,dontWarnIfNotExist:!0,lock:!1});if(!d)throw new Error(`${a} Could not get or create agent index ibGib.`);if(!d.data)throw new Error("(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)");let f=d.data.coupleMap??d.data.agentMap,b=f?B(f):{},p=b[i];if(p)if(p===c){je&&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 (${p}). We will be changing to new localAddr (${c}). (W: eb993e33f7731e570fa76f24a2d80625)`);b[i]=c;let u=await Ae({src:d,dataToAddOrPatch:{coupleMap:b},dna:!1,linkedRel8ns:[Se.past],nCounter:!0}),m=u.newIbGib;await V({resTransform:u,space:n});let g=Me({type:s});await r.setConfigAddr({key:g,addr:I({ibGib:m}),space:n}),await r.registerNewIbGib({ibGib:m,space:n})},"fn")}),je&&console.log(`${a} Registered domain ${i} with agent ${c}`)}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{je&&console.log(`${a} complete.`)}}h(Jh,"coupleDomainIbGibWithLocalIbGibViaIndex");function Rr(){let o=`[${Rr.name}]`;try{je&&console.log(`${o} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let e=globalThis[ga];return e||(console.log(`${o} initializing globalThis.${ga}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),e={},globalThis[ga]=e),e}catch(e){throw console.error(`${o} ${E(e)}`),e}finally{je&&console.log(`${o} complete.`)}}h(Rr,"getIbGibGlobalThis_IbGib");async function Nd({delayIntervalMs:o=50}={delayIntervalMs:50}){let e=`[${Nd.name}]`;try{je&&console.log(`${e} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let t;for(;!t;)Rr().metaspace&&(t=Rr().metaspace),t||(console.log(`${e} metaspace still not initialized. delayIntervalMs: ${o} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await De(o));return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{je&&console.log(`${e} complete.`)}}h(Nd,"getGlobalMetaspace_waitIfNeeded");function Zh({ibGibAddr:o,gib:e,ibGib:t,translucentAlpha:r=10}){let n=`[${Zh.name}]`;try{je&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!o&&!e&&!t&&(e=Q),e??=t?.gib??K({ibGibAddr:o}).gib;let a=Ne({gib:e});r??=10;let s="";if(a.isPrimitive)return{gib:e,gibInfo:a,punctiliarColor:yd,punctiliarColorTranslucent:$d,punctiliarColorContrast:Id};s=a.tjpGib??a.punctiliarHash??e;let[i,c,l]=Cd(r,a.punctiliarHash??e),[d,f,b]=a.tjpGib?Cd(r,a.tjpGib):[void 0,void 0,void 0];return{gib:e,gibInfo:a,punctiliarColor:i,punctiliarColorTranslucent:c,punctiliarColorContrast:l,tjpColor:d,tjpColorTranslucent:f,tjpColorContrast:b}}catch(a){let s=`${n} ${E(a)}`;return console.error(s),{gib:e??Q,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:s}}finally{je&&console.log(`${n} complete.`)}}h(Zh,"getDeterministicColorInfo");function Qh(o,e,t){t/=100;let r=e*Math.min(t,1-t)/100,n=h(a=>{let s=(a+o/30)%12,i=t-r*Math.max(Math.min(s-3,9-s,1),-1);return Math.round(255*i).toString(16).padStart(2,"0")},"f");return`#${n(0)}${n(8)}${n(4)}`}h(Qh,"hslToHex");function Cd(o,e){let r=(parseInt(e.substring(0,8),16)||0)%360,n=Qh(r,65,62),a=parseInt(n.substring(1,3),16),s=parseInt(n.substring(3,5),16),i=parseInt(n.substring(5,7),16),l=(a*299+s*587+i*114)/1e3>=128?"#11111b":"#ffffff",d=Math.min(100,Math.max(0,o)),f=Math.round(d/100*255).toString(16).padStart(2,"0"),b=`${n}${f}`;return[n,b,l]}h(Cd,"getColorStrings");var ep="recursive-salt-wrap",en={recursive_salt_wrap:ep},Dd=Object.values(en);var ya=!1;async function xi({masterSecret:o,kdfOpts:e}){let t=`[${xi.name}]`;try{ya&&console.log(`${t} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let r=e.strategy;switch(r){case en.recursive_salt_wrap:return await co({masterSecret:o,salt:e.salt,rounds:e.rounds,algorithm:e.algorithm});default:throw new Error(`Unknown KDF strategy: ${r}. valid values: ${Dd.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ya&&console.log(`${t} complete.`)}}h(xi,"deriveKey");async function co({masterSecret:o,salt:e,rounds:t,algorithm:r=dt.sha_256}){let n=`[${co.name}]`;try{ya&&console.log(`${n} starting... (I: 850868e50aba82ff28c77da8169e4c26)`);let a=o;for(let s=0;s<t;s++)a=await te({s:`${e}${a}${e}`,algorithm:r});return a}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{ya&&console.log(`${n} complete.`)}}h(co,"kdf_recursiveSaltWrap");var tp="hash-reveal-v1",Ut={hash_reveal_v1:tp},vd=Object.values(Ut);var rp="top-up",op="replace-all",np="consume",ap="delete-all",Ze={topUp:rp,replaceAll:op,consume:np,deleteAll:ap},Pd=Object.values(Ze);var sp="add-pool",ip="remove-pool",cp="replace-pool",lp="change-password",lo={add_pool:sp,remove_pool:ip,replace_pool:cp,change_password:lp},ty=Object.values(lo);var tn="keystone",Ci=/^\w[\w\-.]*$/,Ni=/^[a-zA-Z0-9\-_]{1,64}$/,Di=/^[a-zA-Z0-9_\-.]{1,63}$/,vi=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,Od=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Pi=1e3,fo="revoke",Be="manage",dp="sign",ut="sync",bo="connect",Ld="accept",Rd="reject",Oi={REVOKE:fo,MANAGE:Be,SIGN:dp,SYNC:ut,CONNECT:bo,ACCEPT:Ld,REJECT:Rd},iy=Object.values(Oi);var rn=Be;var on=bo,Li=ut,cy=Ld,ly=Rd;var Ud=200,Md=2,Fd=2,Bd=5,kd=Ze.topUp,jd=dt.sha_256,qd=1,Xd=2e3,Hd=5,Vd=5,Wd=16,Yd=Ze.replaceAll,Kd=dt.sha_512,zd=10,Ur=50;var $a=!1,Ri=class{static{h(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}},Ui=class o extends Ri{static{h(this,"KeystoneConfigBuilder_HashV1")}lc=`[${o}]`;_algo;_rounds;withHash({algo:e,rounds:t}){let r=`${this.lc}[${this.withHash.name}]`;try{return $a&&console.log(`${r} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=e,this._rounds=t,this}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{$a&&console.log(`${r} complete.`)}}build(){let e=`${this.lc}[${this.build.name}]`;try{if($a&&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:Ut.hash_reveal_v1,salt:this._salt,allowedVerbs:this._verbs,behavior:this.buildBehavior(),algo:this._algo,rounds:this._rounds}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{$a&&console.log(`${e} complete.`)}}},nn=class{static{h(this,"KeystoneConfig")}static hash(){return new Ui}};function Mi(o){if(o.type&&o.type!==Ut.hash_reveal_v1)throw new Error(`invalid type (${o.type}). Only ${Ut.hash_reveal_v1} currently implemented. (E: c38616cd7a459149f670418f88766526)`);let{salt:e,id:t,size:r,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:l,hashRounds:d}=o;return nn.hash().withId(t).withSalt(e).withSize(r??Ud).withHybrid({seqCount:n??Md,randCount:a??Fd}).withTargetBinding(s??Bd).withReplenishStrategy(i??kd).withHash({algo:l??jd,rounds:d??qd}).forVerbs(c??[]).build()}h(Mi,"createStandardPoolConfig");function fp(o){if(o.type&&o.type!==Ut.hash_reveal_v1)throw new Error(`invalid type (${o.type}). Only ${Ut.hash_reveal_v1} currently implemented. (E: 09c1f7772bd2a7910f5562b4934d3826)`);let{salt:e,id:t,size:r,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:l,hashRounds:d}=o;return nn.hash().withId(t).withSalt(e).withSize(r??Xd).withHybrid({seqCount:n??Hd,randCount:a??Vd}).withTargetBinding(s??Wd).withReplenishStrategy(i??Yd).withHash({algo:l??Kd,rounds:d??zd}).forVerbs(c??[]).build()}h(fp,"createHighSecurityPoolConfig");function gy(o){return fp({...o,id:o.id??rn,verbs:o.verbs??[Oi.MANAGE]})}h(gy,"createManagePoolConfig");function Jd({template:o,salt:e}){let t=o.behavior;return nn.hash().withId(o.id).withSalt(e).withSize(t.size).withHybrid({seqCount:t.selectSequentially,randCount:t.selectRandomly}).withTargetBinding(t.targetBindingCount).withReplenishStrategy(t.replenish).withHash({algo:o.algo,rounds:o.rounds}).forVerbs(o.allowedVerbs).build()}h(Jd,"createPoolConfigFromJson");var Zd={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Dev)",securityLevel:"low"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var Qd={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Staging)",securityLevel:"medium"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:3,behavior:{size:500,replenish:"replace-all",selectSequentially:4,selectRandomly:4,targetBindingCount:6}}}};var ef={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Prod)",securityLevel:"high"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:2e3,replenish:"replace-all",selectSequentially:12,selectRandomly:12,targetBindingCount:16}}}};var Ia={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Dev)",securityLevel:"low",defaultTtlSeconds:86400},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var tf={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Staging)",securityLevel:"medium",defaultTtlSeconds:604800},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:3,behavior:{size:250,replenish:"replace-all",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}}}};var rf={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Prod)",securityLevel:"high",defaultTtlSeconds:2592e3},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:1e3,replenish:"replace-all",selectSequentially:8,selectRandomly:8,targetBindingCount:10}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}}}};var of={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Session/Saga Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"replace-all",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:50,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}}}};var nf={metadata:{name:"admin-profile.dev",description:"Admin One-Off Challenge Profile (Dev)",securityLevel:"low"},pools:{accept:{id:"accept",allowedVerbs:["accept"],algo:"SHA-256",rounds:2,behavior:{size:3,replenish:"delete-all",selectSequentially:1,selectRandomly:1,targetBindingCount:0}},reject:{id:"reject",allowedVerbs:["reject"],algo:"SHA-256",rounds:1,behavior:{size:3,replenish:"delete-all",selectSequentially:1,selectRandomly:1,targetBindingCount:0}}}};var af={metadata:{name:"admin-profile.staging",description:"Admin One-Off Challenge Profile (Staging)",securityLevel:"high"},pools:{accept:{id:"accept",allowedVerbs:["accept"],algo:"SHA-256",rounds:1e3,behavior:{size:20,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:0}},reject:{id:"reject",allowedVerbs:["reject"],algo:"SHA-256",rounds:100,behavior:{size:10,replenish:"delete-all",selectSequentially:2,selectRandomly:2,targetBindingCount:0}}}};var sf={metadata:{name:"admin-profile.prod",description:"Admin One-Off Challenge Profile (Prod)",securityLevel:"high"},pools:{accept:{id:"accept",allowedVerbs:["accept"],algo:"SHA-256",rounds:1e3,behavior:{size:20,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:0}},reject:{id:"reject",allowedVerbs:["reject"],algo:"SHA-256",rounds:100,behavior:{size:10,replenish:"delete-all",selectSequentially:2,selectRandomly:2,targetBindingCount:0}}}};var Aa=new Map,an=class o{static{h(this,"KeystoneProfileBuilder")}_template;_username;_emails;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static registerCustomProfile({name:e,template:t}){if(!e||typeof e!="string")throw new Error("Profile name is required to register a custom profile. (E: 1e50081dba682977cf6091d85166e826)");if(!t||typeof t!="object")throw new Error(`Valid KeystonePolicyConfigTemplate is required to register custom profile '${e}'. (E: 7739b840ec780b84084435f8b6000826)`);Aa.set(e,JSON.parse(JSON.stringify(t)))}static clearCustomProfiles(){Aa.clear()}static fromTemplate(e){if(!e||typeof e!="object")throw new Error("Valid KeystonePolicyConfigTemplate is required for KeystoneProfileBuilder.fromTemplate. (E: d468882543687c8fbcf921c8d807e826)");return new o(e)}static buildKeystone(e){if(!e||typeof e!="string")throw new Error("Profile name is required for KeystoneProfileBuilder. (E: 98c4c89520359b6dd10461884385d826)");if(e.endsWith(".dev")||e.startsWith("test")||e.includes("test"))throw new Error(`Security Violation: Development keystone profile '${e}' is prohibited when NODE_ENV=production. (E: a940c7b1a88869b2e820aef89de41326)`);if(Aa.has(e))return new o(Aa.get(e));let r;switch(e){case"primary-profile.dev":r=Zd;break;case"primary-profile.staging":r=Qd;break;case"primary-profile.prod":r=ef;break;case"sync-profile.dev":r=Ia;break;case"sync-profile.staging":r=tf;break;case"sync-profile.prod":r=rf;break;case"sync-profile.test-short-ttl":r={...JSON.parse(JSON.stringify(Ia)),metadata:{...Ia.metadata,name:"sync-profile.test-short-ttl",description:"Short 10-second TTL sync profile for testing session expiration and renewal.",defaultTtlSeconds:10}};break;case"admin-profile.dev":r=nf;break;case"admin-profile.staging":r=af;break;case"admin-profile.prod":r=sf;break;case"session":r=of;break;default:throw new Error(`Unknown keystone profile name: '${e}' (E: fc10a8ad482ef2bda871ac567d268d26)`)}return new o(r)}withUsername(e){return this._username=e,this}withEmail(e){return this._emails?this._emails.includes(e)||this._emails.push(e):this._emails=[e],this}withEmails(e){return this._emails=[...e],this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}_expirationUTC;withExpiration(e){return this._expirationUTC=e,this}getDefaultTtlSeconds(){return this._template.metadata?.defaultTtlSeconds}customizePool(e,t){let{behavior:r,...n}=t;return this._customizations[e]={template:n,behavior:r},this}getFrameDetails(){let e={...this._details};if(this._username&&(e.username=this._username),this._emails&&this._emails.length>0&&(e.emails=[...this._emails]),this._description&&(e.description=this._description),this._expirationUTC)e.expirationUTC=this._expirationUTC;else{let t=this.getDefaultTtlSeconds();t&&t>0&&(e.expirationUTC=new Date(Date.now()+t*1e3).toISOString())}return e}async compileConfigs(){let e=[],t="";if(this._username||this._emails&&this._emails.length>0){let r=this._emails?.[0]??"",n=`${this._username||""}:${r}`;t=await te({s:n})}else t=await te({s:"default-keystone-salt"});for(let[r,n]of Object.entries(this._template.pools)){let a=this._customizations[n.id];a&&(a.template&&Object.assign(n,a.template),a.behavior&&n.behavior&&Object.assign(n.behavior,a.behavior));let s=`${t}-${n.id}`,i=await te({s}),c=Jd({template:n,salt:i});e.push(c)}return e}};var _a=class{static{h(this,"KeystoneStrategy")}config;constructor(e){this.config=e}};var Ta=class o extends _a{static{h(this,"KeystoneStrategy_HashRevealV1")}async derivePoolSecret({masterSecret:e}){let t=`[${o.name}.${this.derivePoolSecret.name}]`;try{let{salt:r,rounds:n,algo:a}=this.config;return await co({masterSecret:e,salt:r,rounds:n,algorithm:a})}catch(r){throw console.error(`${t} Error deriving pool secret: ${r.message}`),r}}async generateSolution({poolSecret:e,poolId:t,challengeId:r}){let n=`[${o.name}.${this.generateSolution.name}]`;try{let{rounds:a,algo:s}=this.config,i=r,c=e;for(let l=0;l<a;l++)c=await te({s:`${i}${c}${i}`,algorithm:s});return{type:"hash-reveal-v1",poolId:t,challengeId:r,value:c}}catch(a){throw console.error(`${n} ${a.message}`),a}}async generateChallenge({solution:e}){let t=`[${o.name}.${this.generateChallenge.name}]`;try{let{rounds:r,algo:n}=this.config,{challengeId:a,value:s}=e,i=a,c=s;for(let l=0;l<r;l++)c=await te({s:`${i}${c}${i}`,algorithm:n});return{id:a,type:"hash-reveal-v1",hash:c}}catch(r){throw console.error(`${t} ${r.message}`),r}}async validateSolution({solution:e,challenge:t}){let r=`[${o.name}.${this.validateSolution.name}]`;try{return e.type!=="hash-reveal-v1"||t.type!=="hash-reveal-v1"?(console.warn(`${r} Mismatched types provided.`),!1):(await this.generateChallenge({solution:e})).hash===t.hash}catch(n){return console.error(`${r} ${n.message}`),!1}}};var Mr=class o{static{h(this,"KeystoneStrategyFactory")}static create({config:e}){let t=`[${o.name}.create]`;try{switch(e.type){case"hash-reveal-v1":return new Ta(e);default:throw new Error(`Unknown strategy type: ${e.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(r){throw console.error(`${t} ${r.message}`),r}}};var le=!1;async function it({ibGib:o,ibGibs:e,ibGibAddr:t,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:b,spaces:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:m}){let g=`[${it.name}]`;try{le&&console.log(`${g} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let y=await sn({ibGib:o,ibGibs:e,ibGibAddr:t,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:b,spaces:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:m});if(le&&Object.values(y).filter(w=>w.ib.startsWith("comment ")).forEach(w=>{console.table(w)}),le){console.log(`${g} graph size: ${Object.keys(y).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let w=Object.values(y).filter(A=>A.ib.startsWith("comment ")||A.ib.startsWith("pic ")).map(A=>A.ib);jt(w).forEach(A=>console.log(A))}return y}catch(y){throw console.error(`${g} ${y.message}`),y}finally{le&&console.log(`${g} complete.`)}}h(it,"getDependencyGraph");async function df({ibGib:o,ibGibs:e,ibGibAddr:t,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:b,spaces:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:m}){let g=`[${df.name}]`;try{if(le&&console.log(`${g} starting... (I: bd6807477f679345df9dddefe0b4e922)`),b&&(p??[]).length>0)throw new Error("space and spaces parameters are mutually exclusive. Pass either space or spaces, not both. (E: 994a5323e4214f4e95d5bb2b89f89090)");let y=b?[b]:(p??[]).filter(w=>!!w);if(y.length===0)throw new Error("space or spaces required. (E: 9f38166ab70340cb919174f8d26af909)");if(!o&&!t&&(e??[]).length===0&&(r??[]).length===0)throw new Error("either ibGib/s or ibGibAddr/s required. (E: b6d08699651f455697f0d05a41edb039)");return c=c||[],i=i||[],a=a||{},s=s||[],r=(r??[]).filter(w=>!Ce({gib:K({ibGibAddr:w}).gib})).filter(w=>!i.includes(w)),e=(e??[]).filter(w=>!Ce({ibGib:w})).filter(w=>!i.includes(I({ibGib:w}))),o&&!Ce({ibGib:o})&&!e.some(w=>w.gib===o.gib)&&!i.includes(I({ibGib:o}))&&e.push(o),t&&!Ce({gib:K({ibGibAddr:t}).gib})&&!r.includes(t)&&!i.includes(t)&&r.push(t),{ibGib:o,ibGibs:e,ibGibAddr:t,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:void 0,spaces:y,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:m}}catch(y){throw console.error(`${g} ${y.message}`),y}finally{le&&console.log(`${g} complete.`)}}h(df,"getGraphProjection_initializeOpts");async function Fi({ibGibs:o,ibGibAddrs:e,gotten:t,skipAddrs:r,maxRetries:n,msBetweenRetries:a,timeLogName:s,space:i,spaces:c}){let l=`[${Fi.name}]`;try{le&&console.log(`${l} starting... (I: 67b2be37ff24393fff56e229304da122)`);let d=c??(i?[i]:[]);if(d.length===0)throw new Error("(UNEXPECTED) spaces empty? (E: aa9f657695717034b3581066932d7d23)");let f=[];o??=[],e??=[],r??=[],t??={};let b=[],p=Object.keys(t??{}),u=o.map(m=>I({ibGib:m}));for(let m=0;m<e.length;m++){let g=e[m];r.includes(g)||u.includes(g)||(p.includes(g)?f.push(t[g]):b.push(e[m]))}if(le&&console.log(`${l}[analyze debugging] addrsToGetFromSpace (${b.length}):
|
|
16
|
+
${b.join(`
|
|
17
|
+
`)} (I: b45a2614184b48b694becfd377c789f5)`),b.length>0){let m=b.concat(),g=0;for(n=n??0;g<=n&&m.length>0;){s&&g===0&&console.timeLog(s,`${l} FIRST try starting...`),s&&g>0&&console.timeLog(s,`${l} RETRY starting...`),g>0&&a&&(s&&console.timeLog(s,`${l} delaying ${a}ms for retry`),le&&console.log(`${l} retrying. addrsToGet (${m.length}): ${m} (I: 8460694cdd5518472680784c3b96a822)`),await De(a));for(let y of d){if(m.length===0)break;s&&console.timeLog(s,`${l} getFromSpace (${m.length}) starting...`);let w=await z({addrs:m,space:y});if(s&&console.timeLog(s,`${l} getFromSpace complete.`),w.success&&(w.ibGibs?.length??0)>0){w.ibGibs.forEach(G=>f.push(G));let A=w.ibGibs.map(G=>I({ibGib:G}));m=m.filter(G=>!A.includes(G))}else{let A=w.rawResultIbGib?.ibGibs??[];if(A.length>0){A.forEach(T=>f.push(T));let G=A.map(T=>I({ibGib:T}));m=m.filter(T=>!G.includes(T))}}}g++}if(m.length>0){let y=d.map(w=>w?.ib).join(", ");throw new Error(`unable to retrieve dependency ibgibs from space/s (ib/s: ${y}). addrsToGet: ${m.join(`
|
|
18
|
+
`)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}}return f}catch(d){throw console.error(`${l} ${d.message}`),d}finally{le&&console.log(`${l} complete.`)}}h(Fi,"getGraphProjection_getIbGibsInIbGibAddrs");async function sn(o){let e=`[${sn.name}]`;try{if(le&&console.log(`${e} starting... (I: 70508d7a5c63eae1f22ae851b32b3d22)`),!o.ibGib&&!o.ibGibAddr&&(o.ibGibs??[]).length===0&&(o.ibGibAddrs??[]).length===0)return{};let{ibGibs:t,ibGibAddrs:r,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:b,spaces:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:m}=await df(o);if(u&&console.timeLog(u,`${e} starting...`),r?.length??!1){let y=await Fi({ibGibs:t,ibGibAddrs:r,gotten:a,skipAddrs:i,maxRetries:d,msBetweenRetries:f,timeLogName:u,space:b,spaces:p});t=t?[...t,...y]:[...y]}r=t.map(y=>I({ibGib:y}));let g=jt(t.map(y=>y.ib).filter(y=>y.startsWith("comment ")));return le&&console.log(`${e}[analyze debugging] ibGibs commentIbs: ${g.join(`
|
|
19
|
+
`)} (I: c89dc951315f746954f9bddbe8941122)`),n?ff({ibGibs:t,ibGibAddrs:r,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:b,spaces:p,timeLogName:u,mapTjpAddrToLatestAddrsInSpace:m}):bf({ibGibs:t,ibGibAddrs:r,gotten:a,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:f,space:b,spaces:p,timeLogName:u})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{le&&console.log(`${e} complete.`)}}h(sn,"getGraphProjection");async function ho({ibGibAddr:o,latestCommonFrameAddr:e,live:t,space:r,spaces:n}){let a=`[${ho.name}]`;try{if(le&&console.log(`${a} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`),o===e)return console.warn(`${a} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`),{};let s=await it({ibGibAddr:e,live:!1,space:r,spaces:n});return await it({ibGibAddr:o,live:t,skipAddrs:Object.keys(s),space:r,spaces:n})}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{le&&console.log(`${a} complete.`)}}h(ho,"getDeltaDependencyGraph");async function ff({ibGibs:o,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:r,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:l,space:d,spaces:f,timeLogName:b}){let p=`[${ff.name}]`;try{let u=f??(d?[d]:[]);n=n??{},r=r??[];let m={...t};(o??[]).forEach(T=>m[I({ibGib:T})]=T);let g=at({ibGibs:Object.values(m)});le&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(g).length}): ${Object.keys(g)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let y={};Object.keys(g).forEach(T=>{r.includes(T)||(y[T]=g[T])}),le&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${X(y)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let w={},A={};Object.keys(g).filter(T=>!r.includes(T)).forEach(T=>{let $=g[T],_=$[$.length-1];w[T]=_;let S=I({ibGib:_});A[S]=T});let G=Object.keys(w).length;if(G>0){let T={};Object.keys(n).filter(N=>!r.includes(N)).forEach(N=>{let x=w[N];if(x){let L=I({ibGib:x});T[L]=n[N]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy (E: 8a5d3f2e1c4b90876543210fe89abcdf)`)}),le&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${X(T)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let $=Object.values(w),_={};if($.length>0){if(u.length===0)throw new Error("(UNEXPECTED) space/s falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");for(let N of u){let x=await ve({ibGibs:$,space:N});if(!x?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");let L=x.data.latestAddrsMap;Object.keys(L).forEach(U=>{let O=L[U];O?_[U]=O:_[U]||(_[U]=null)})}if($.forEach(N=>{let x=I({ibGib:N});_[x]||(_[x]=x)}),Object.keys(_).length!==G)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");le&&console.log(`${p} queriedLatestAddrsMap: ${X(_)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),T={..._,...T}}le&&console.log(`${p} combined latestAddrsMap: ${X(T)} (I: e3aedea63f29c5b06a79632f691aa522)`);let S=[],D={};Object.values(w).forEach(N=>{let x=I({ibGib:N}),L=A[x],U=T[x];if(!U)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");U===x?(le&&console.log(`${p} analyzed ${L} (I: afb7960900f04b8a87538f4c7bd903b7)`),r.push(L)):(S.push(U),D[U]=L)});let C=[];for(let N=0;N<(o??[]).length;N++){let L=o[N].rel8ns??{};Object.keys(L).filter(O=>!(s??[]).includes(O)).filter(O=>i?i.includes(O):!0).forEach(O=>{(L[O]??[]).forEach(F=>{!C.includes(F)&&!o.some(k=>I({ibGib:k})===F)&&!Ce({gib:K({ibGibAddr:F}).gib})&&C.push(F)})})}return e=jt([...e??[],...C,...S]),await sn({ibGibs:o,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:r,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:l,space:d,spaces:u,timeLogName:b,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return o||(o=[]),Object.values(t??{}).forEach(T=>{let $=I({ibGib:T});o.some(_=>I({ibGib:T})===$)||o.push(T)}),await sn({ibGibs:o,ibGibAddrs:e,gotten:t,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:l,space:d,spaces:u,timeLogName:b,live:!1})}catch(u){let m=`${p} ${u.message}`;throw console.error(m),b&&console.timeLog(b,`${p} error: ${m}`),u}finally{b&&console.timeLog(b,`${p} complete.`)}}h(ff,"getGraphProjection_Live");async function bf({ibGibs:o,ibGibAddrs:e,gotten:t,skipAddrs:r,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c,spaces:l,timeLogName:d}){let f=`[${bf.name}]`;try{let b=[];o??=[],t??={},r??=[],n??=[],d&&console.timeLog(d,`${f} analyzing next step starting...`);for(let p=0;p<o.length;p++){let u=o[p],m=I({ibGib:u}),{gib:g}=K({ibGib:u});if(g===Q)throw new Error("cannot get dependency graph of primitive. (E: 5493b8908d134bdf887e91122a6a57e3)");Object.keys(t).includes(m)||(t[m]=u);let y={},w=u.rel8ns||{},A=(Object.keys(w)||[]).filter(T=>!n.includes(T));a&&(A=A.filter(T=>a.includes(T)));let G=Object.keys(t);for(let T=0;T<A.length;T++){let $=A[T],_=w[$]??[],S=_.filter(C=>C===""||C===void 0||C===null||!C.includes(Ue));S.length>0&&console.warn(`${f} (UNEXPECTED) has falsyAddrs: ${S} (W: da9505cb0a4db68a4aff7f279ad2d322)`),_.filter(C=>!!C).filter(C=>!G.includes(C)).filter(C=>!r.includes(C)).filter(C=>K({ibGibAddr:C}).gib!==Q).filter(C=>!b.includes(C)).forEach(C=>{let N=qt({addr:C});(N||[]).length===0?b.push(C):y[C]=N})}if(Object.keys(y).length>0)throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(y).substring(0,1024)} (E: d2416b9b23fa4d178e6c7104b40ee78c)`)}if(d&&console.timeLog(d,`${f} analyzing next step complete.`),b.length>0){d&&console.timeLog(d,`${f} get addrsWeDontHaveAlready_Rel8dAddrs starting...`);let p=await Fi({ibGibAddrs:b,gotten:t,skipAddrs:r,maxRetries:s,msBetweenRetries:i,timeLogName:d,space:c,spaces:l});p.forEach(m=>t[I({ibGib:m})]=m),d&&console.timeLog(d,`${f} call getGraphProjection recursively starting...`);let u=await sn({ibGibs:p,live:!1,gotten:t,skipAddrs:r,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c,spaces:l});return d&&console.timeLog(d,`${f} call getGraphProjection recursively complete.`),u}else return t}catch(b){let p=`${f} ${b.message}`;throw console.error(`${p} (E: 8a42e56616014e7a8848aa6bb6f2722b)`),d&&console.timeLog(d,`${f} error: ${p}`),new Error(`${p} (E: a21b0682121746a480572b83413cf2d0)`)}finally{d&&console.timeLog(d,`${f} complete.`)}}h(bf,"getGraphProjection_NonLive");function Ga({ibGibs:o}){let e=`[${Ga.name}]`;try{if(le&&console.log(`${e} starting... (I: 6019a812cff8597f79c12088e45cc226)`),o){let t={};return o.forEach(r=>{t[I({ibGib:r})]=r}),t}else return}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{le&&console.log(`${e} complete.`)}}h(Ga,"toFlatGraph");function Ip({graphA:o,graphB:e,slowButThorough:t}){let r=`[${Ip.name}]`;try{if(le&&console.log(`${r} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(o).length===Object.keys(e).length))return le&&console.log(`${r} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let a of Object.keys(o))if(!e[a])return le&&console.log(`${r} addr (${a}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`),!1;if(t)for(let a of Object.keys(o)){let s=Fe({ibGib:o[a]}),i=JSON.stringify(s),c=Fe({ibGib:e[a]}),l=JSON.stringify(c);if(i!==l)return le&&console.log(`${r} jsonA !== jsonB for addr (${a}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{le&&console.log(`${r} complete.`)}}h(Ip,"graphsAreEquivalent");var cf=["past","dna","tjp","ancestor"];async function Bi({ibGib:o,ibGibAddr:e,onlyRel8nNames:t,skipRel8nNames:r,metaspace:n,space:a}){let s=`[${Bi.name}]`;try{if(le&&console.log(`${s} starting...`),!o&&!e)throw new Error("Either ibGib or ibGibAddr is required (E: 5ab00fed90d2c59638368b38643d5826)");if(o&&e)throw new Error("Cannot provide both ibGib and ibGibAddr (E: f4121894ae389c8f818d8d5657f1ad26)");if(!a)throw new Error("space is required (E: 8894680a77d8251bf886f3e83820ce26)");if(!n)throw new Error("metaspace is required (E: a5ac39b725b86a58386bd598be16d826)");if(t!==void 0){if(t.length===0)throw new Error("onlyRel8nNames cannot be empty (E: ddb968035e2856fb06b8fb283732f826)");let m=t.filter(g=>cf.includes(g));if(m.length>0)throw new Error(`onlyRel8nNames contains forbidden intrinsic relationship names: ${m.join(", ")} (E: 4f828ff5cb4d9daab86eaf787c9ff826)`)}let i=jt([...cf,...r??[]]),c=o;if(!c&&e&&(c=await ae({addr:e,space:a,metaspace:n}),!c))throw new Error(`Root ibGib '${e}' not found in space or metaspace (E: 2e36285dfacd5de4383b14085792b826)`);if(!c)throw new Error("(UNEXPECTED) rootNode falsy (E: 1828aca373bf289d06f6243847d5b526)");let l={},d=[],f=new Map,b=new Set;async function p(m){let g=I({ibGib:m});if(f.has(g))return f.get(g);if(b.has(g))return{reifiedIbGib:m,hasChanges:!1};b.add(g);try{let y=m,w=!1,A=m.rel8ns?.tjp?.at(0)??g,G=await ve({addrs:[A],space:a}),T=G?.data?.latestAddrsMap?.[A]??G?.data?.latestAddrsMap?.[g];if(T&&T!==g){let C=await lf({addr:T,space:a,metaspace:n});C&&(y=C,w=!0,l[g]=T)}let $=!1,_={},S=y.rel8ns??{},D=Object.keys(S).filter(C=>!i.includes(C));t&&(D=D.filter(C=>t.includes(C)));for(let C of D){let N=S[C]??[];for(let x of N){if(!x||Ce({gib:K({ibGibAddr:x}).gib}))continue;let L=await lf({addr:x,space:a,metaspace:n});if(!L)continue;let U=await p(L);if(U.hasChanges){let O=I({ibGib:U.reifiedIbGib});O!==x&&($=!0,_[C]??=[],_[C].some(M=>M.oldAddr===x)||_[C].push({oldAddr:x,newAddr:O}))}}}if($){let C=await ie({src:y,rel8nsToReplaceByAddr:_,dna:!0,nCounter:!0});await V({resTransform:C,space:a}),await J({ibGib:C.newIbGib,space:a});let N=C.newIbGib,x=I({ibGib:N});d.push(N),l[g]=x;let L={reifiedIbGib:N,hasChanges:!0};return f.set(g,L),L}else if(w){let C={reifiedIbGib:y,hasChanges:!0};return f.set(g,C),C}else{let C={reifiedIbGib:m,hasChanges:!1};return f.set(g,C),C}}finally{b.delete(g)}}h(p,"reifyNode");let u=await p(c);return{reifiedIbGib:u.reifiedIbGib,hasChanges:u.hasChanges,reifiedAddrsMap:l,evolvedIbGibs:d}}catch(i){throw console.error(`${s} ${E(i)} (E: bcafd7bc234892113c7f2658ac5feb26)`),i}finally{le&&console.log(`${s} complete.`)}}h(Bi,"reifyDependencyGraph");async function lf({addr:o,space:e,metaspace:t}){let r=await z({addrs:[o],space:e});if(r.success&&r.ibGibs&&r.ibGibs.length>0)return r.ibGibs[0];let n=r.rawResultIbGib?.ibGibs??[];if(n.length>0)return n[0];if(t){let a=await t.get({addrs:[o],space:e});if(a.success&&a.ibGibs&&a.ibGibs.length>0)return a.ibGibs[0]}}h(lf,"getIbGibFromSpaceOrMetaspace");var Pe=!1;async function hf({keystoneData:o}){let e=`[${hf.name}]`;try{return Pe&&console.log(`${e} starting... (I: c3022a146faac9730154f34d1439a225)`),[tn].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}h(hf,"getKeystoneIb");async function pf({ib:o}){let e=`[${pf.name}]`;try{Pe&&console.log(`${e} starting... (I: 73cb6832984255ed48b2f44db6a21e25)`);let[t]=o.split(" ");if(t!==tn)throw new Error(`invalid keystone ib. atom found in ib (${t}) does not match keystone atom (${tn}) (E: 79b3d587824c4271b6e60acc76e0c825)`);return{atom:t}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}h(pf,"parseKeystoneIb");async function cn({ib:o}){try{return await pf({ib:o}),!0}catch{return!1}}h(cn,"validateKeystoneIb");function _$(o){if(!o||typeof o!="string")return!1;let e=o.trim();return e.length<3||e.length>254?!1:Od.test(e)}h(_$,"validateEmail");async function uf({pool:o,requiredChallengeIds:e,targetAddr:t}){let r=o.config.behavior,n=new Set,a=Object.keys(o.challenges);if(e&&e.length>0){for(let s of e){if(!o.challenges[s])throw new Error(`(UNEXPECTED) Required challenge ID not found in pool: ${s} (E: 10c5619d80d8cf6cc84ffbf8be0dbc25)`);a.includes(s)&&n.add(s)}a=a.filter(s=>!n.has(s))}if(r.targetBindingCount>0&&t){let s=[...a].sort(),i=await te({s:t});for(let c=0;c<r.targetBindingCount;c++){if(s.length===0)throw new Error("Entropy Exhaustion. Cannot satisfy target binding. Sorted available pool is empty. (E: 341b95dc3a58be3e083d1d9c4a0c4925)");let l=BigInt("0x"+i),d=Number(l%BigInt(s.length)),f=s[d];n.add(f),s.splice(d,1),a=a.filter(b=>b!==f),i=await te({s:i})}}if(r.selectSequentially>0){if(a.length<r.selectSequentially)throw console.error(`[getDeterministicRequirements] Entropy Exhaustion! AvailableCount: ${a.length}, Required Seq: ${r.selectSequentially}. Available IDs: ${a.join(",")}`),new Error("Entropy Exhaustion. Insufficient challenges for FIFO requirement. (E: 9efa88003e1d5eccb837c85154ee5625)");a.slice(0,r.selectSequentially).forEach(i=>n.add(i)),a=a.slice(r.selectSequentially)}return{mandatoryIds:n,availableIds:a}}h(uf,"getDeterministicRequirements");function ln({pools:o,poolId:e,poolFilter:t,verb:r}){let n="[resolveTargetPool]";try{let a;if(e){if(a=o.find(s=>s.id===e),!a)throw new Error(`Pool not found with ID: ${e} (E: 4a2b17428515c1e82813158581898125)`)}else if(t){let s=o.filter(t);if(s.length===0)throw new Error("No pool matched the provided filter. (E: 5b3c27428515c1e82813158581898125)");a=s[0]}else{if(!r)throw new Error("Cannot auto-resolve pool without a verb. (E: 6c4d37428515c1e82813158581898125)");if(a=o.find(s=>s.config.allowedVerbs&&s.config.allowedVerbs.includes(r)),a||(a=o.find(s=>!s.config.allowedVerbs||s.config.allowedVerbs.length===0)),!a)throw new Error(`No suitable pool found for verb: ${r} (E: 7d5e47428515c1e82813158581898125)`)}if(r&&a.config.allowedVerbs&&a.config.allowedVerbs.length>0&&!a.config.allowedVerbs.includes(r))throw new Error(`Pool ${a.id} is not authorized for verb: ${r} (E: 8e6f57428515c1e82813158581898125)`);return a}catch(a){throw console.error(`${n} ${E(a)}`),a}}h(ln,"resolveTargetPool");async function Fr({pool:o,targetAddr:e,requiredChallengeIds:t}){let r="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:a}=await uf({pool:o,requiredChallengeIds:t,targetAddr:e}),s=o.config.behavior.selectRandomly,i=[];if(s>0){if(a.length<s)throw new Error(`Insufficient challenges for random requirement. Need ${s}, have ${a.length} (E: 9f7a67428515c1e82813158581898125)`);let c=[...a].sort(()=>.5-Math.random());i.push(...c.slice(0,s))}return[...n,...i]}catch(n){throw console.error(`${r} ${E(n)}`),n}}h(Fr,"selectChallengeIds");async function mf({salt:o,timestamp:e,index:t}){return(await te({s:`${o}${e}${t}`})).substring(0,16)}h(mf,"generateOpaqueChallengeId");async function Ap({prevPools:o,targetPoolId:e,consumedIds:t,masterSecret:r,strategy:n,config:a,verb:s}){let i="[applyReplenishmentStrategy]";try{let c=JSON.parse(JSON.stringify(o)),l=c.findIndex(u=>u.id===e);if(l===-1)throw new Error(`Target pool ${e} not found in keystone data. (E: 75200388d22744838634524233772545)`);let d=c[l],f=await n.derivePoolSecret({masterSecret:r}),b=Date.now().toString(),p=a.behavior.replenish;if(s===fo&&(p=Ze.deleteAll),p===Ze.topUp){t.forEach(u=>delete d.challenges[u]);for(let u=0;u<t.length;u++){let m=await mf({salt:a.salt,timestamp:b,index:u}),g=await n.generateSolution({poolSecret:f,poolId:d.id,challengeId:m});d.challenges[m]=await n.generateChallenge({solution:g})}}else if(p===Ze.replaceAll)d.challenges=await Ca({config:a,masterSecret:r});else if(p===Ze.consume)t.forEach(u=>delete d.challenges[u]);else if(p===Ze.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${p}. Valid list: ${X(Pd)} (E: 0acf56f1e1486240080e11e8046d0825)`);return c}catch(c){throw console.error(`${i} ${E(c)}`),c}}h(Ap,"applyReplenishmentStrategy");async function Br({targetPoolId:o,prevPools:e,masterSecret:t,challengeIds:r,claim:n,requiredChallengeIds:a}){let s="[solveAndReplenish]";try{Pe&&console.log(`${s} starting... poolId: ${o}, ids: ${r.length}`);let i=e.find(u=>u.id===o);if(!i)throw new Error(`Target pool not found: ${o} (E: 19a578d1def8d555487411e3cf43b126)`);let c=Mr.create({config:i.config}),l=await c.derivePoolSecret({masterSecret:t});if(!await Na({pool:i,signingSecret:t}))throw new Error(`Crypto Violation: Invalid signing secret for pool: ${i.id} (E: 6d377722e4d888c203a048e4729a7826)`);let f=[];for(let u of r){let m=await c.generateSolution({poolSecret:l,poolId:i.id,challengeId:u});f.push(m)}let b={claim:n,solutions:f,requiredChallengeIds:a&&a.length>0?a:void 0},p=await Ap({prevPools:e,targetPoolId:i.id,consumedIds:r,masterSecret:t,strategy:c,config:i.config,verb:n.verb});return{proof:b,nextPools:p}}catch(i){throw console.error(`${s} ${E(i)}`),i}}h(Br,"solveAndReplenish");async function gf({pool:o}){let e=`[${gf.name}]`;try{if(Pe&&console.log(`${e} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!o.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(o.config.type!==Ut.hash_reveal_v1)throw new Error("(UNEXPECTED) pool.config.type !== KeystoneChallengeType.hash_reveal_v1? (E: e205f8872909c37168a624a9df778c26)");let t=[],{algo:r,rounds:n,salt:a}=o.config,s=[dt.sha_256,dt.sha_512];return r?s.includes(r)||t.push(`${e} invalid hash algorithm (${r}). Must be one of ${s}. (E: a22399ca3a68e63ffcc7507699be5826)`):t.push(`${e} algorithm required. (E: 8cd6bfb0590862b9bae24d98d2cf3826)`),n&&typeof n=="number"&&Number.isInteger(n)?n>Pi&&t.push(`${e} rounds too high. max rounds: ${Pi} (E: 31ce082f7fd88d6b58ef08a816458826)`):t.push(`${e} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),a&&typeof a=="string"?Ni.test(a)||t.push(`${e} invalid salt (${a.substring(0,99)}). Must match regexp ${Ni}`):t.push(`${e} invalid salt (${a}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}h(gf,"validateChallengePool_typeHashRevealV1");async function Ef({pool:o}){let e=`[${Ef.name}]`;try{Pe&&console.log(`${e} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let t=[];if(o.config){if(o.config.id?Ci.test(o.config.id)||t.push(`${e} pool.config.id is not formatted correctly. must pass regexp: ${Ci.source}`):t.push(`${e} pool.config.id falsy (E: 31d7943d95f877326d5f4ea14463d626)`),o.config.behavior){let{size:n,selectSequentially:a,selectRandomly:s,targetBindingCount:i}=o.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 r=o.config.type;switch(r){case Ut.hash_reveal_v1:(await gf({pool:o})).forEach(a=>t.push(a));break;default:throw new Error(`(UNEXPECTED) unknown pool.config.type (${r})? We only implement the following at this time: ${vd} (E: cce5285cf7580b8bc82172488eba2826)`)}}else t.push(`${e} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}h(Ef,"validateChallengePool");function wf({data:o}){let e="[validateKeystoneMetadata]",t=[],r=h((n,a)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!Di.test(n.username))&&t.push(`${e} invalid username in ${a} (${n.username}). Must match ${Di}`),n.description!==void 0&&(typeof n.description!="string"||!vi.test(n.description))&&t.push(`${e} invalid description in ${a} (${n.description}). Must match ${vi}`),n.expirationUTC!==void 0&&(typeof n.expirationUTC!="string"||isNaN(Date.parse(n.expirationUTC)))&&t.push(`${e} invalid expirationUTC in ${a} (${n.expirationUTC}). Must be a valid ISO-8601 string`))},"checkDetails");return r(o.frameDetails,"frameDetails"),r(o.checkpointDetails,"checkpointDetails"),t}h(wf,"validateKeystoneMetadata");async function Sa({keystoneIbGib:o}){let e=`[${Sa.name}]`;try{Pe&&console.log(`${e} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let t=[],{data:r,rel8ns:n}=o;await cn({ib:o.ib})||t.push(`${e} invalid keystone ib (${o.ib}). (E: ad7a88bc38c290a184dfbd42be48f526)`),wf({data:r}).forEach(i=>t.push(i)),r.proofs&&r.proofs.length>0&&t.push(`${e} proofs already exist on genesis keystone. (E: 7a5e15f20918f1bbd8ffb62857dcd526)`);for(let i of r.challengePools)(await Ef({pool:i})).forEach(l=>t.push(l)),(!i.challenges||Object.keys(i.challenges).length===0)&&t.push(`${e} invalid pool (${i.id}). pool.challenges is falsy/empty. (E: 8cd16a5416ae62a058342828be465b26)`);return r.revocationInfo&&t.push(`${e} genesis keystone already has revocationInfo. (E: e11408d0c558d0fa948efbce611ec826)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}h(Sa,"validateGenesisKeystone");function _p({currDelegates:o,prevDelegates:e}){let t=o||{},r=e||{},n=Object.keys(t),a=Object.keys(r);if(n.length!==a.length)return!0;for(let s of n){let i=t[s],c=r[s];if(!c||i.delegateTjpAddr!==c.delegateTjpAddr||i.delegateAddr!==c.delegateAddr||i.thisAddr!==c.thisAddr)return!0}return!1}h(_p,"isDelegatesChanged");async function Tp({currDelegates:o,prevIbGib:e,lc:t,errors:r}){let n=Object.keys(o),a=I({ibGib:e});for(let s of n){let i=o[s];s!==i.delegateTjpAddr&&r.push(`${t} Invalid delegate mapping: Key '${s}' does not match delegateTjpAddr '${i.delegateTjpAddr}'. (E: 9c8da8bc38c290a184dfbd42be48f526)`);let[c,l,d]=await Promise.all([cn({ib:i.delegateTjpAddr.split("^")[0]}),cn({ib:i.delegateAddr.split("^")[0]}),cn({ib:i.thisAddr.split("^")[0]})]);c||r.push(`${t} Delegate delegateTjpAddr '${i.delegateTjpAddr}' is not a valid keystone address. (E: 10d8a8bc38c290a184dfbd42be48f526)`),l||r.push(`${t} Delegate delegateAddr '${i.delegateAddr}' is not a valid keystone address. (E: 20d8a8bc38c290a184dfbd42be48f526)`),d||r.push(`${t} Delegate thisAddr '${i.thisAddr}' is not a valid keystone address. (E: 30d8a8bc38c290a184dfbd42be48f526)`),i.thisAddr===a||(e.rel8ns?.past||[]).includes(i.thisAddr)||r.push(`${t} Delegate thisAddr '${i.thisAddr}' is not a valid historical address in the parent keystone timeline. (E: 40d8a8bc38c290a184dfbd42be48f526)`);let b=i.allowedVerbs||[];(i.role==="sync-delegate"||b.includes("sync")||b.includes(ut))&&!i.spaceId&&r.push(`${t} Sync delegate '${i.delegateTjpAddr}' missing required spaceId. (E: 50d8a8bc38c290a184dfbd42be48f526)`),i.expirationUTC&&isNaN(Date.parse(i.expirationUTC))&&r.push(`${t} Delegate expirationUTC '${i.expirationUTC}' is not a valid ISO-8601 timestamp. (E: 60d8a8bc38c290a184dfbd42be48f526)`)}}h(Tp,"validateDelegates");async function dn({currentIbGib:o,prevIbGib:e}){let t=`[${dn.name}]`,r=[];try{if(!o)throw new Error("(UNEXPECTED) currentIbGib falsy? (E: 3c0f02655fa8279e386a079ebb604b25)");if(!e)throw new Error("(UNEXPECTED) prevIbGib falsy? (E: 0d07c812634d839c784f31b8848ba825)");let n=await ne({ibGib:o});n&&n.length>0&&r.push(...n);let a=o.data,s=e.data;await cn({ib:o.ib})||r.push(`${t} invalid keystone ib (${o.ib}). (E: a98dc8bc38c290a184dfbd42be48f526)`),wf({data:a}).forEach(m=>r.push(m));let l=a.delegates||{},d=s.delegates||{};_p({currDelegates:l,prevDelegates:d})&&(a.proofs?.some(g=>g.claim?.verb===Be)||r.push(`${t} Policy Violation: Delegates map was mutated but no proof for manage verb ('${Be}') is present. (E: 819fa8cb28c9b60e68994511a5825)`)),await Tp({currDelegates:l,prevIbGib:e,lc:t,errors:r});let b=a.n??-2,p=s.n??-2;b<0&&r.push("invalid keystone.currData.n is undefined or null. (E: 9fbe38704b68829d18ea1d0940d0aa26)"),p<0&&r.push("invalid keystone.prevData.n is undefined or null. (E: 6dc5aa9c87017db6080ed4268b07af26)"),b!==p+1&&r.push(`keystone data.n values are not sequential. prevData.n: ${p}, currData.n: ${b}. (E: 5ae12809f2c67216d38d8ba8d6c42826)`);for(let m of a.proofs){if(m.solutions.length===0){r.push(`Proof ${m.id||"unknown"} has no solutions. (E: e2b4683ce0ce30f798ec77841e88c826)`);continue}let g=m.solutions[0].poolId,y=s.challengePools.find(w=>w.id===g);if(!y){r.push(`Proof references unknown pool: ${g}`);continue}await yf({proof:m,pool:y,errors:r})}if(a.revocationInfo){let m=a.revocationInfo.proof.claim.target,g=I({ibGib:e});m!==g&&r.push(`Revocation target mismatch. Expected ${g}, got ${m}`)}let u=new Set(a.proofs.map(m=>m.solutions?.[0]?.poolId).filter(Boolean));for(let m of a.proofs){let g=m.claim;if(g?.details){let y=g.details,w=y.type,A=y.info;if(w==="add-pool"){let G=A;if(!G||!Array.isArray(G.add)||G.add.length===0){r.push(`details type is '${w}' but payload is invalid. (E: 1fa2a8cb28c9b60e68994511a5825)`);continue}let T=new Set(s.challengePools.map(_=>_.id)),$=new Set(a.challengePools.map(_=>_.id));for(let _ of G.add)$.has(_)||r.push(`ClaimDetails_AddPool lists pool ${_} but it is missing in the evolved keystone. (E: 2fa2a8cb28c9b60e68994511a5825)`),T.has(_)&&r.push(`ClaimDetails_AddPool attempts to add existing pool ${_}. (E: 3fa2a8cb28c9b60e68994511a5825)`);a.challengePools.length!==s.challengePools.length+G.add.length&&r.push(`Structural mismatch: expected ${s.challengePools.length+G.add.length} pools, found ${a.challengePools.length}. (E: 4fa2a8cb28c9b60e68994511a5825)`);for(let _ of s.challengePools){let S=a.challengePools.find(D=>D.id===_.id);if(!S){r.push(`Existing pool ${_.id} was removed during add-pool transition. (E: 5fa2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(_.config)!==JSON.stringify(S.config)&&r.push(`Existing pool config ${_.id} was mutated during add-pool transition. (E: 6fa2a8cb28c9b60e68994511a5825)`),!u.has(_.id)&&JSON.stringify(_.challenges)!==JSON.stringify(S.challenges)&&r.push(`Existing pool challenges ${_.id} were mutated during add-pool transition. (E: 7fa2a8cb28c9b60e68994511a5825)`)}}else if(w==="replace-pool"){let G=A;if(!G||typeof G.replace!="string"||!G.replace){r.push(`details type is '${w}' but payload is invalid. (E: 8fa2a8cb28c9b60e68994511a5825)`);continue}let T=G.replace,$=s.challengePools.map(C=>C.id).sort(),_=a.challengePools.map(C=>C.id).sort();JSON.stringify($)!==JSON.stringify(_)&&r.push("replace-pool transition mutated the pool IDs set. (E: 9fa2a8cb28c9b60e68994511a5825)");let S=s.challengePools.find(C=>C.id===T),D=a.challengePools.find(C=>C.id===T);(!S||!D)&&r.push(`Replaced pool ${T} not found in keystone challenge pools. (E: afa2a8cb28c9b60e68994511a5825)`);for(let C of s.challengePools){if(C.id===T)continue;let N=a.challengePools.find(x=>x.id===C.id);N&&(JSON.stringify(C.config)!==JSON.stringify(N.config)&&r.push(`Unrelated pool config ${C.id} was mutated during replace-pool. (E: bfa2a8cb28c9b60e68994511a5825)`),!u.has(C.id)&&JSON.stringify(C.challenges)!==JSON.stringify(N.challenges)&&r.push(`Unrelated pool challenges ${C.id} were mutated during replace-pool. (E: cfa2a8cb28c9b60e68994511a5825)`))}}else if(w==="remove-pool"){let G=A;if(!G||!Array.isArray(G.remove)||G.remove.length===0){r.push(`details type is '${w}' but payload is invalid. (E: b7a2a8cb28c9b60e68994511a5825)`);continue}let T=new Set(G.remove),$=new Set(s.challengePools.map(S=>S.id)),_=new Set(a.challengePools.map(S=>S.id));for(let S of G.remove)$.has(S)||r.push(`ClaimDetails_RemovePool lists pool ${S} but it is missing in the previous keystone. (E: c7a2a8cb28c9b60e68994511a5825)`),_.has(S)&&r.push(`ClaimDetails_RemovePool lists pool ${S} but it is still present in the evolved keystone. (E: d7a2a8cb28c9b60e68994511a5825)`);a.challengePools.length!==s.challengePools.length-G.remove.length&&r.push(`Structural mismatch: expected ${s.challengePools.length-G.remove.length} pools, found ${a.challengePools.length}. (E: e7a2a8cb28c9b60e68994511a5825)`);for(let S of s.challengePools){if(T.has(S.id))continue;let D=a.challengePools.find(C=>C.id===S.id);if(!D){r.push(`Pool ${S.id} was unexpectedly removed. (E: f7a2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(S.config)!==JSON.stringify(D.config)&&r.push(`Remaining pool config ${S.id} was mutated during remove-pool. (E: 07a2a8cb28c9b60e68994511a5825)`),!u.has(S.id)&&JSON.stringify(S.challenges)!==JSON.stringify(D.challenges)&&r.push(`Remaining pool challenges ${S.id} were mutated during remove-pool. (E: 17a2a8cb28c9b60e68994511a5825)`)}}else if(w==="change-password"){let G=A;if(!G||!Array.isArray(G.change)||G.change.length===0){r.push(`details type is '${w}' but payload is invalid. (E: dfa2a8cb28c9b60e68994511a5825)`);continue}let T=s.challengePools.map(S=>S.id).sort(),$=a.challengePools.map(S=>S.id).sort();JSON.stringify(T)!==JSON.stringify($)&&r.push("change-password transition mutated the pool IDs set. (E: efa2a8cb28c9b60e68994511a5825)");let _=new Set(G.change);for(let S of s.challengePools){let D=a.challengePools.find(C=>C.id===S.id);if(D)if(_.has(S.id)){S.isForeign&&r.push(`Security Violation: Password rotation attempted on foreign pool ${S.id}. (E: ffa2a8cb28c9b60e68994511a5825)`);let C={...S.config,salt:""},N={...D.config,salt:""};JSON.stringify(C)!==JSON.stringify(N)&&r.push(`Pool config metadata for rotated pool ${S.id} was mutated. (E: 00b2a8cb28c9b60e68994511a5825)`),S.config.salt===D.config.salt&&r.push(`Pool salt for rotated pool ${S.id} was not rotated. (E: 01b2a8cb28c9b60e68994511a5825)`)}else JSON.stringify(S.config)!==JSON.stringify(D.config)&&r.push(`Unrelated pool config ${S.id} was mutated during change-password. (E: 02b2a8cb28c9b60e68994511a5825)`),!u.has(S.id)&&JSON.stringify(S.challenges)!==JSON.stringify(D.challenges)&&r.push(`Unrelated pool challenges ${S.id} were mutated during change-password. (E: 03b2a8cb28c9b60e68994511a5825)`)}}else r.push(`Unknown claim details type: ${w}`)}}return r}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{Pe&&console.log(`${t} complete.`)}}h(dn,"validateKeystoneTransition");async function yf({proof:o,pool:e,errors:t}){let r=`[${yf.name}]`;try{Pe&&console.log(`${r} starting... (I: b8f9b6085888eea2258bf579ecd5e825)`),e.config.allowedVerbs&&e.config.allowedVerbs.length>0&&(!o.claim.verb||!e.config.allowedVerbs.includes(o.claim.verb))&&t.push(`Policy Violation: Pool ${e.id} used for unauthorized verb ${o.claim.verb}`);let{mandatoryIds:n,availableIds:a}=await uf({pool:e,requiredChallengeIds:o.requiredChallengeIds,targetAddr:o.claim.target}),s=new Set(o.solutions.map(d=>d.challengeId));for(let d of n)s.has(d)||t.push(`Policy Violation: Missing mandatory challenge ${d}`);let i=[...s].filter(d=>!n.has(d)),c=e.config.behavior.selectRandomly;i.length<c&&t.push(`Policy Violation: Insufficient random count. Need ${c}, got ${i.length}`);for(let d of i)a.includes(d)||t.push(`Policy Violation: ID ${d} is invalid or double-dipped.`);let l=Mr.create({config:e.config});for(let d of o.solutions){let f=e.challenges[d.challengeId];f?await l.validateSolution({solution:d,challenge:f})||t.push(`Crypto Violation: Solution for ${d.challengeId} is invalid.`):t.push(`Crypto Violation: Challenge ${d.challengeId} not found in pool.`)}}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Pe&&console.log(`${r} complete.`)}}h(yf,"verifyProofAgainstPool");async function gr({prevIbGib:o,newData:e,metaspace:t,space:r}){let n=`[${gr.name}]`;try{if(Pe&&console.log(`${n} starting... (I: 8b10e8920f08b7842803665834cf8925)`),!o.data)throw new Error("(UNEXPECTED) prevIbGib.data falsy? (E: 5e84875bf992c585b979e6c8ed5bf225)");if(o.data.revocationInfo)throw new Error(`Keystone has already been revoked (prevIbGib.data.revocationInfo truthy), so we cannot evolve the keystone. Keystone addr: ${I({ibGib:o})} (E: 45d7f846556829de6b2a701838c3f825)`);let a=o.data,s={};a.proofs&&(s.proofs=[]),a.challengePools&&(s.challengePools=[]),a.frameDetails&&(s.frameDetails="true"),a.checkpointDetails&&(s.checkpointDetails={}),a.delegates&&(s.delegates="remove"),Object.keys(s).length===0&&(s=void 0);let i=await Ae({src:o,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,l=await dn({currentIbGib:c,prevIbGib:o});if(l.length>0)throw console.error(`${n} Validation Failed:
|
|
20
|
+
${l.join(`
|
|
21
|
+
`)}`),new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${l.join("; ")} (E: ae2c58406c1db7687879dfb89fc1f825)`);return await t.put({ibGib:c,space:r}),await t.registerNewIbGib({ibGib:c,space:r}),c}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{Pe&&console.log(`${n} complete.`)}}h(gr,"evolvePersistAndRegisterKeystone");async function ki({data:o,metaspace:e,space:t}){let r=`[${ki.name}]`;try{if(Pe&&console.log(`${r} 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 H.firstGen({parentIbGib:H.primitive({ib:tn}),ib:await hf({keystoneData:o}),data:o,dna:!1,nCounter:!0,tjp:{timestamp:!0,uuid:!0}})).newIbGib;if(!a.data)throw new Error("(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)");if(!a.rel8ns)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)");if(!a.rel8ns.past||a.rel8ns.past.length===0)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns.past falsy or empty? we expect the firstGen call to generate an interstitial ibgib that we will splice out. (E: 0fd8388d045ab9f37834c27d67e78825)");return a.data.n=0,a.data.isTjp=!0,delete a.rel8ns.tjp,delete a.rel8ns.past,a.gib=await ee({ibGib:a}),await e.put({ibGib:a,space:t}),await e.registerNewIbGib({ibGib:a,space:t}),a}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Pe&&console.log(`${r} complete.`)}}h(ki,"createKeystoneIbGibImpl");async function xa({keystoneIbGib:o,dependencyGraph:e,getLatest:t,invalidIfMoreRecentKeystoneFoundInSpace:r,space:n}){let a=`[${xa.name}]`;try{if(Pe&&console.log(`${a} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!o)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let s=[];if(t){let f=I({ibGib:o}),b=await ve({ibGibs:[o],space:n});if(!b.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!b.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:p}=b.data;if(Object.keys(p).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let u=p[f];if(u)if(u!==f)if(r)s.push(`${a} more recent keystone (${u}) found than the one passed in (${f}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[m]=await Ve({addrs:[u],space:n});o=m}else Pe&&console.log(`${a} incoming keystone (${f}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${a} keystoneIbGib (${f}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}e??=await it({ibGib:o,space:n});let i=Object.values(e),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:l,mapWithoutTjps:d}=nt({ibGibs:i});if(Object.keys(l).length>0&&s.push(`${a} DNA found. Keystones should NOT have DNA. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(d).length>0&&s.push(`${a} Non-tjp ibgibs found? Keystones are expected to have tjps. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(c).length>0){let f=Object.values(c),b=at({ibGibs:f}),p=Object.keys(b);if(p.length===0)throw new Error("(UNEXPECTED) orderedKeystonesMap empty? (E: d437b80bef58e83a034b28af46278726)");if(p.length>1)throw new Error("(UNEXPECTED) more than one timeline in keystone graph? ATOW (02/19/2026) we are expecting only a single timeline. (E: 66085b14e3887a59c872afd240511f26)");let u=p[0],m=b[u];if(m.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await Sa({keystoneIbGib:m[0]})).forEach(y=>s.push(y)),m.length!==1)for(let y=0;y<m.length-1;y++){let w=m[y],A=m[y+1],G=await dn({prevIbGib:w,currentIbGib:A});G.length>0&&(s.push(`${a} keystone has ${G.length} transition errors. i: ${y}. prevIbGib addr: ${I({ibGib:w})}. currentIbGib addr: ${I({ibGib:A})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),G.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} ${E(s)}`),s}finally{Pe&&console.log(`${a} complete.`)}}h(xa,"validateKeystoneGraph");async function Ca({config:o,masterSecret:e}){let t=Mr.create({config:o}),r=await t.derivePoolSecret({masterSecret:e}),n={},a=o.behavior.size,s=Date.now().toString();for(let i=0;i<a;i++){let c=await mf({salt:o.salt,timestamp:s,index:i}),l=await t.generateSolution({poolSecret:r,poolId:o.id,challengeId:c});n[c]=await t.generateChallenge({solution:l})}return n}h(Ca,"generatePoolChallenges");async function $f({prevPool:o,newMasterSecret:e}){let t=o.config,r=(await q()).substring(0,16),n={...t,salt:r},a=await Ca({config:n,masterSecret:e});return{id:o.id,config:n,challenges:a,...o.isForeign!==void 0?{isForeign:o.isForeign}:{},...o.metadata?{metadata:o.metadata}:{}}}h($f,"rotatePoolChallenges");async function Na({pool:o,signingSecret:e}){let t=Object.keys(o.challenges);if(t.length===0)return!1;try{let r=t[0],n=o.challenges[r],a=Mr.create({config:o.config}),s=await a.derivePoolSecret({masterSecret:e}),i=await a.generateSolution({poolSecret:s,poolId:o.id,challengeId:r});return await a.validateSolution({solution:i,challenge:n})}catch{return!1}}h(Na,"verifyPoolSecret");var me=!1,Mt=class o{static{h(this,"KeystoneService_V1")}lc=`[${o.name}]`;async genesis({masterSecret:e,emails:t,frameDetails:r,credentialIds:n,dataToPatch:a,configs:s,metaspace:i,space:c,isPrimary:l}){let d=`${this.lc}[${this.genesis.name}]`;try{me&&console.log(`${d} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let f=[];for(let u of s){let m=await Ca({config:u,masterSecret:e});f.push({id:u.id,config:u,challenges:m})}if(f.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let b={challengePools:f,proofs:[]};return t&&t.length>0&&(b.emails=[...t]),n&&n.length>0&&(b.credentialIds=[...n]),(r||l!==void 0)&&(b.frameDetails={...r||{}},l!==void 0&&(b.frameDetails.isPrimary=l)),a&&Object.assign(b,a),await ki({data:b,metaspace:i,space:c})}catch(f){throw console.error(`${d} ${E(f)}`),f}finally{me&&console.log(`${d} complete.`)}}async sign({latestKeystone:e,masterSecret:t,claim:r,poolId:n,poolFilter:a,requiredChallengeIds:s=[],frameDetails:i,metaspace:c,space:l,dataToPatch:d}){let f=`${this.lc}[${this.sign.name}]`;try{me&&console.log(`${f} starting...`);let b=e.data;if(b.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");if(ji({keystone:e}))throw new Error(`Keystone is expired (${b.frameDetails?.expirationUTC}). Cannot sign. (E: 7f2198c39116d15c48ba191940316825)`);let p=ln({pools:b.challengePools,poolId:n,poolFilter:a,verb:r.verb});me&&console.log(`${f} Selected pool: ${p.id} (size: ${Object.keys(p.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let u=await Fr({pool:p,targetAddr:r.target,requiredChallengeIds:s}),{proof:m,nextPools:g}=await Br({targetPoolId:p.id,prevPools:b.challengePools,masterSecret:t,challengeIds:u,claim:r,requiredChallengeIds:s}),y=(b.n??0)+1,w;if(y%Ur===0){let T={...e,data:{...b,frameDetails:i}};w=await this.getAggregateDetails({latestKeystone:T,metaspace:c,space:l})}let A={challengePools:g,proofs:[m],frameDetails:i,checkpointDetails:w,...b.delegates?{delegates:b.delegates}:{},...d};return await gr({prevIbGib:e,newData:A,metaspace:c,space:l})}catch(b){throw console.error(`${f} ${E(b)}`),b}finally{me&&console.log(`${f} complete.`)}}async validate({currentIbGib:e,prevIbGib:t}){return await dn({currentIbGib:e,prevIbGib:t})}async registerDelegate({parentKeystone:e,delegateKeystone:t,masterSecret:r,signingPoolId:n,frameDetails:a,metaspace:s,space:i,allowedVerbs:c,deviceName:l,expirationUTC:d,ttlSeconds:f}){let b=`${this.lc}[${this.registerDelegate.name}]`;try{if(me&&console.log(`${b} starting...`),!n)throw new Error("signingPoolId is required (E: ab8e7813123a2afd37703c2810e57c26)");let p=await xa({keystoneIbGib:t,getLatest:!0,invalidIfMoreRecentKeystoneFoundInSpace:!1,space:i});if(p.length>0)throw new Error(`Delegate keystone validation failed: ${p.join(", ")} (E: 88fa8ab28c9b60e68994511a5825)`);let u=e.data,m=u.challengePools.find($=>$.id===n);if(!m)throw new Error(`Parent keystone does not contain signing pool: ${n} (E: 818fa8ab28c9b60e68994511a5825)`);if(m.config.allowedVerbs&&m.config.allowedVerbs.length>0&&!m.config.allowedVerbs.includes(Be))throw new Error(`Signing pool ${n} is not authorized for verb: ${Be} (E: 918fa8ab28c9b60e68994511a5825)`);let g=ye({ibGib:t});if(!g)throw new Error("(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)");let y={target:g,verb:Be},w=u.delegates?{...u.delegates}:{},A=da({spaceIb:i.ib}).spaceId,G=d??(f?new Date(Date.now()+f*1e3).toISOString():void 0)??t.data?.frameDetails?.expirationUTC;return w[g]={delegateTjpAddr:g,delegateAddr:I({ibGib:t}),thisAddr:I({ibGib:e}),deviceName:l,allowedVerbs:c,spaceId:A,expirationUTC:G,role:t.data?.frameDetails?.role},await this.sign({latestKeystone:e,masterSecret:r,claim:y,poolId:n,frameDetails:a,metaspace:s,space:i,dataToPatch:{delegates:w}})}catch(p){throw console.error(`${b} ${E(p)}`),p}finally{me&&console.log(`${b} complete.`)}}async unregisterDelegate({parentKeystone:e,delegateTjpAddr:t,masterSecret:r,signingPoolId:n,frameDetails:a,metaspace:s,space:i}){let c=`${this.lc}[${this.unregisterDelegate.name}]`;try{if(me&&console.log(`${c} starting...`),!n)throw new Error("signingPoolId is required (E: b2c3d4e5f6a13889f8ab28c9b60e6899)");let l=e.data,d=l.challengePools.find(u=>u.id===n);if(!d)throw new Error(`Parent keystone does not contain signing pool: ${n} (E: 3889f8ab28c9b60e68994511a5825)`);if(d.config.allowedVerbs&&d.config.allowedVerbs.length>0&&!d.config.allowedVerbs.includes(Be))throw new Error(`Signing pool ${n} is not authorized for verb: ${Be} (E: 4889f8ab28c9b60e68994511a5825)`);let f={target:t,verb:Be},b=l.delegates?{...l.delegates}:{};if(!b[t])throw new Error(`Delegate ${t} is not registered on this parent. (E: 81d9f8ab28c9b60e68994511a5825)`);return delete b[t],await this.sign({latestKeystone:e,masterSecret:r,claim:f,poolId:n,frameDetails:a,metaspace:s,space:i,dataToPatch:{delegates:b}})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{me&&console.log(`${c} complete.`)}}async getDelegateStatus({parentTjpAddr:e,delegateTjpAddr:t,metaspace:r,space:n}){let a=`${this.lc}[${this.getDelegateStatus.name}]`;try{me&&console.log(`${a} starting...`);let{ib:s,gib:i}=K({ibGibAddr:e}),l=await ve({ibGibs:[{ib:s,gib:i}],space:n});if(!l.data?.latestAddrsMap)return{registered:!1};let d=l.data.latestAddrsMap[e];if(!d)return{registered:!1};let b=(await r.get({addr:d,space:n})).ibGibs?.at(0);if(!b||!b.data)return{registered:!1};let u=(b.data.delegates||{})[t];return{registered:!!u&&!If({delegateInfo:u}),delegateInfo:u}}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{me&&console.log(`${a} complete.`)}}async validateGenesisKeystone({keystoneIbGib:e}){return await Sa({keystoneIbGib:e})}async getLatestKeystone({addr:e,metaspace:t,space:r}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{me&&console.log(`${n} starting...`);let a=await t.getLatestAddr({addr:e,space:r});if(!a)throw new Error(`could not find latest addr for ${e}`);let s=await t.get({addr:a,space:r});if(s.success&&s.ibGibs&&s.ibGibs.length>0)return s.ibGibs[0];{let c=s.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find latest keystone at ${a}. addrsNotFound: ${c}? resGet.errorMsg: ${s.errorMsg}`)}}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{me&&console.log(`${n} complete.`)}}async validateKeystoneGraph({keystoneIbGib:e,dependencyGraph:t,getLatest:r,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a}){let s=`${this.lc}[${this.validateKeystoneGraph.name}]`;try{return me&&console.log(`${s} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await xa({keystoneIbGib:e,dependencyGraph:t,getLatest:r,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{me&&console.log(`${s} complete.`)}}async revoke({latestKeystone:e,masterSecret:t,reason:r="User initiated revocation",frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.revoke.name}]`;try{me&&console.log(`${i} starting...`);let c=e.data,l=ln({pools:c.challengePools,verb:fo}),d={verb:fo,target:I({ibGib:e})},f=await Fr({pool:l,targetAddr:d.target,requiredChallengeIds:[]});if(f.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${l.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:b,nextPools:p}=await Br({targetPoolId:l.id,prevPools:c.challengePools,masterSecret:t,challengeIds:f,claim:d,requiredChallengeIds:[]});p.find(A=>A.id===l.id&&Object.keys(A.challenges).length>0)&&console.warn(`${i} revocation pool ${l.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${Ze.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let u={reason:r,proof:b},m=(c.n??0)+1,g;if(m%Ur===0){let A={...e,data:{...c,frameDetails:n,revocationInfo:u}};g=await this.getAggregateDetails({latestKeystone:A,metaspace:a,space:s})}let y={challengePools:p,proofs:[b],revocationInfo:u,frameDetails:n,checkpointDetails:g,...c.delegates?{delegates:c.delegates}:{}};return await gr({prevIbGib:e,newData:y,metaspace:a,space:s})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{me&&console.log(`${i} complete.`)}}async addPools({latestKeystone:e,masterSecret:t,signingPoolId:r,newPools:n,frameDetails:a,dataToPatch:s,metaspace:i,space:c}){let l=`${this.lc}[${this.addPools.name}]`;try{if(me&&console.log(`${l} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let d=e.data;if(d.revocationInfo)throw new Error("Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)");if(n.length===0)throw new Error("No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)");let f=ln({pools:d.challengePools,poolId:r,verb:Be});me&&console.log(`${l} Authorized via pool: ${f.id}`);let b=I({ibGib:e}),p={verb:Be,target:b,details:{type:lo.add_pool,info:{add:n.map(_=>_.id)}}},u=await Fr({pool:f,targetAddr:b}),{proof:m,nextPools:g}=await Br({targetPoolId:f.id,prevPools:d.challengePools,masterSecret:t,challengeIds:u,claim:p}),y=new Set(g.map(_=>_.id));for(let _ of n)if(y.has(_.id))throw new Error(`Cannot add pool. ID collision: ${_.id} (E: 2b5388a28a935b61c8fbf3ce06c21b26)`);let w=[...g,...n],A=(d.n??0)+1,G;if(A%Ur===0){let _={...e,data:{...d,challengePools:w,frameDetails:a}};G=await this.getAggregateDetails({latestKeystone:_,metaspace:i,space:c})}let T={challengePools:w,proofs:[m],frameDetails:a,checkpointDetails:G,...d.delegates?{delegates:d.delegates}:{},...s};return await gr({prevIbGib:e,newData:T,metaspace:i,space:c})}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{me&&console.log(`${l} complete.`)}}async removePools({latestKeystone:e,masterSecret:t,signingPoolId:r,poolIds:n,frameDetails:a,dataToPatch:s,metaspace:i,space:c}){let l=`${this.lc}[${this.removePools.name}]`;try{if(me&&console.log(`${l} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 8334c8faed128166a999d428c7805b25)");let d=e.data;if(d.revocationInfo)throw new Error("Keystone has been revoked. Cannot remove pools. (E: 9599f8f51c78d722252ddb2894fdbe25)");if(n.length===0)throw new Error("No pool IDs provided to remove. (E: 7599f8f51c78d722252ddb2894fdbe25)");let f=ln({pools:d.challengePools,poolId:r,verb:Be});me&&console.log(`${l} Authorized via pool: ${f.id}`);let b=I({ibGib:e}),p={verb:Be,target:b,details:{type:lo.remove_pool,info:{remove:n}}},u=await Fr({pool:f,targetAddr:b}),{proof:m,nextPools:g}=await Br({targetPoolId:f.id,prevPools:d.challengePools,masterSecret:t,challengeIds:u,claim:p}),y=new Set(n),w=g.filter(_=>!y.has(_.id));if(w.length!==g.length-n.length){let _=n.filter(S=>!g.some(D=>D.id===S));throw new Error(`Cannot remove pool. Pool IDs not found in keystone: ${_.join(", ")} (E: d584889fbeb6c7c378fa38a596d13826)`)}let A=(d.n??0)+1,G;if(A%Ur===0){let _={...e,data:{...d,challengePools:w,frameDetails:a}};G=await this.getAggregateDetails({latestKeystone:_,metaspace:i,space:c})}let T={challengePools:w,proofs:[m],frameDetails:a,checkpointDetails:G,...d.delegates?{delegates:d.delegates}:{},...s};return await gr({prevIbGib:e,newData:T,metaspace:i,space:c})}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{me&&console.log(`${l} complete.`)}}async getAggregateDetails({latestKeystone:e,metaspace:t,space:r}){let n=`${this.lc}[${this.getAggregateDetails.name}]`;try{let a={},s=e;for(;s;){let i=s.data;if(i.checkpointDetails){a=oo({dominant:a,recessive:i.checkpointDetails});break}if(i.frameDetails&&(a=oo({dominant:a,recessive:i.frameDetails})),i.n===0)break;let c=s.rel8ns?.past,l=c&&c.length>0?c[c.length-1]:void 0;if(!l)break;let d=await t.get({addr:l,space:r});if(!d.success||!d.ibGibs||d.ibGibs.length===0){console.warn(`${n} Could not find previous keystone frame at ${l} (W: e3d069b22e11e550e58844889ddb5325). Returning aggregated details collected so far.`);break}s=d.ibGibs[0]}return this.pruneTombstoneNulls(a),a}catch(a){throw console.error(`${n} ${E(a)}`),a}}async getKeystoneCommonInfo({addr:e,ibGib:t,metaspace:r,space:n}){let a=`${this.lc}[getKeystoneCommonInfo]`;try{let s=e,i=t;if(!s){if(!i)throw new Error("Both addr and ibGib are falsy. Expected at least one parameter to resolve keystone info. (E: 3a2890b1c28f7449c5d8693a7d4a2828)");s=I({ibGib:i})}if(!i){let{ib:G,gib:T}=K({ibGibAddr:s});i={ib:G,gib:T}}let c=await ve({ibGibs:[i],space:n});if(!c.data?.latestAddrsMap)throw new Error(`Could not get latest address map for keystone ${s} in local space. (E: 4a2890b1c28f7449c5d8693a7d4a2829)`);let l=c.data.latestAddrsMap[s]||Object.values(c.data.latestAddrsMap)[0];if(!l)throw new Error(`No latest address found in map for keystone ${s} in local space. (E: 5a2890b1c28f7449c5d8693a7d4a2830)`);let f=(await r.get({addr:l,space:n})).ibGibs?.at(0);if(!f||!f.data)throw new Error(`Keystone ${l} not found or missing data in local space. (E: 6a2890b1c28f7449c5d8693a7d4a2831)`);let b=f.data.frameDetails||{},p=await this.getAggregateDetails({latestKeystone:f,metaspace:r,space:n}),u=p?.username||p?.name||p?.profile?.name||b?.username||b?.name||"",m=p?.description||p?.profile?.description||b?.description||"",g=!!p?.isPrimary||!!p?.profile?.isPrimary||!!b?.isPrimary,y=f.data.n??0,w=b?.timestamp||p?.timestamp||"",A=b?.timestampMs||p?.timestampMs||void 0;return{name:u,description:m,isPrimary:g,aggregateDetails:p,latestFrameDetails:b,n:y,timestamp:w,timestampMs:A}}catch(s){throw console.error(`${a} ${E(s)}`),s}}async replacePool({latestKeystone:e,newPool:t,signingSecret:r,signingPoolId:n=rn,frameDetails:a,metaspace:s,space:i}){let c=`${this.lc}[${this.replacePool.name}]`;try{if(me&&console.log(`${c} starting... replacing pool: ${t.id}`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 1334c8faed128166a999d428c7805b25)");let l=e.data;if(l.revocationInfo)throw new Error("Keystone has been revoked. Cannot replace pool. (E: 2599f8f51c78d722252ddb2894fdbe25)");let d=l.challengePools,f=d.find($=>$.id===n);if(!f)throw new Error(`Signing pool not found: ${n} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let b=I({ibGib:e}),p={verb:Be,target:b,details:{type:lo.replace_pool,info:{replace:t.id}}},u=await Fr({pool:f,targetAddr:b}),{proof:m,nextPools:g}=await Br({targetPoolId:n,prevPools:d,masterSecret:r,challengeIds:u,claim:p}),y=g.findIndex($=>$.id===t.id);if(y===-1)throw new Error(`Target pool to replace '${t.id}' not found in keystone challenge pools.`);g[y]=t;let w=(l.n??0)+1,A;if(w%Ur===0){let $={...e,data:{...l,frameDetails:a}};A=await this.getAggregateDetails({latestKeystone:$,metaspace:s,space:i})}let G={challengePools:g,proofs:[m],frameDetails:a,checkpointDetails:A,...l.delegates?{delegates:l.delegates}:{}};return await gr({prevIbGib:e,newData:G,metaspace:s,space:i})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{me&&console.log(`${c} complete.`)}}async changePassword({keystoneIbGib:e,keystoneAddr:t,newMasterSecret:r,signingSecret:n,signingPoolId:a=rn,poolIds:s,frameDetails:i,metaspace:c,space:l}){let d=`${this.lc}[${this.changePassword.name}]`;try{if(me&&console.log(`${d} starting... (I: 9e3ff83ebd74511f9dad784a1020d926)`),!e&&!t)throw new Error("Either keystoneIbGib or keystoneAddr required. (E: d1b8c8cb75f2c022284e69b8c30af826)");if(e&&t){let C=I({ibGib:e});if(C!==t)throw new Error(`(UNEXPECTED) both keystoneIbGib (addr: ${C}) and keystoneAddr (${t}) provided, but the addrs are unequal? Note that only one is required for this function, but if both are provided the addrs must match exactly. (E: c5574f7e353a48b0bba94a1862af4e26)`)}t??=I({ibGib:e});let f=await this.getLatestKeystone({addr:t,metaspace:c,space:l});if(!f.data)throw new Error("latestKeystone.data falsy (E: 22e498eb8308a33e68b812d8d3905826)");if(f.data.revocationInfo)throw new Error("Keystone has been revoked. Cannot change password. (E: 726298617e8508b3c83b5e985a03e826)");let b=f.data.challengePools,p=b.find(C=>C.id===a);if(!p)throw new Error(`Signing pool not found: ${a} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let u=[];if(s&&s.length>0)for(let C of s){let N=b.find(x=>x.id===C);if(!N)throw new Error(`Target pool to rotate not found: ${C} (E: 4599f8f51c78d722252ddb2894fdbe25)`);u.push(N)}else if(u=b.filter(C=>!C.isForeign),u.length===0)throw new Error("No non-foreign pools found to rotate. (E: 5599f8f51c78d722252ddb2894fdbe25)");let m=[];for(let C of u){let N=await $f({prevPool:C,newMasterSecret:r});m.push(N)}let g=I({ibGib:f}),y={verb:Be,target:g,details:{type:lo.change_password,info:{change:m.map(C=>C.id)}}},w=await Fr({pool:p,targetAddr:g}),{proof:A,nextPools:G}=await Br({targetPoolId:a,prevPools:b,masterSecret:n,challengeIds:w,claim:y});for(let C of m){let N=G.findIndex(x=>x.id===C.id);if(N===-1)throw new Error(`Rotated pool ${C.id} not found in next pools list. (E: 6599f8f51c78d722252ddb2894fdbe25)`);G[N]=C}let T=(f.data.n??0)+1,$;if(T%Ur===0){let C={...f,data:{...f.data,challengePools:G}};$=await this.getAggregateDetails({latestKeystone:C,metaspace:c,space:l})}let _={challengePools:G,proofs:[A],frameDetails:i,checkpointDetails:$,...f.data.delegates?{delegates:f.data.delegates}:void 0},S=await gr({prevIbGib:f,newData:_,metaspace:c,space:l}),D=[];if((s??[]).length===0){let C=await mr({masterSecret:n}),N=await mr({masterSecret:r}),x=f.data.delegates??{};for(let[L,U]of Object.entries(x)){if(Af({delegateInfo:U})){me&&console.log(`${d} Skipping custodial delegate rotation for ${L} (${U.deviceName})`);continue}try{let{newKeystone:O,newDelegates:M}=await this.changePassword({keystoneAddr:L,metaspace:c,space:l,newMasterSecret:N,signingSecret:C,signingPoolId:a,poolIds:void 0,frameDetails:i});if(M&&M.length>0)throw new Error("(UNEXPECTED) Delegate keystone has its own delegate(s)? ATOW (07/20/2026) second order delegates are not supported. (E: de45a7b7d9b8f61f6e58158269acba26)");D.push(O)}catch(O){console.warn(`${d} Error rotating user delegate ${L}: ${E(O)}. Continuing.`)}}}return{newKeystone:S,newDelegates:D.length>0?D:void 0}}catch(f){throw console.error(`${d} ${E(f)}`),f}finally{me&&console.log(`${d} complete.`)}}async verifySigningSecret({keystoneIbGib:e,signingSecret:t,poolId:r,verb:n=Be}){let a=`${this.lc}[${this.verifySigningSecret.name}]`;try{if(!e.data)return!1;let s=e.data.challengePools;if(r){let c=s.find(l=>l.id===r);return c?await Na({pool:c,signingSecret:t}):!1}let i=s.filter(c=>c.id==="manage"||c.id.startsWith("passkey-manage-")||c.config.allowedVerbs&&n&&c.config.allowedVerbs.includes(n));for(let c of i)if(await Na({pool:c,signingSecret:t}))return!0;return!1}catch(s){return console.warn(`${a} Exception during verification: ${E(s)}`),!1}}pruneTombstoneNulls(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.filter(t=>t!==null).map(t=>this.pruneTombstoneNulls(t));for(let t of Object.keys(e))e[t]===null?delete e[t]:e[t]!==null&&typeof e[t]=="object"&&this.pruneTombstoneNulls(e[t]);return e}};var _f="sync-delegate",Tf="custodial-sync";var Da="custodian-manage-";var Gf=!1;async function mr({masterSecret:o}){let e=await te({s:o,algorithm:dt.sha_512});return await co({masterSecret:o,salt:e,rounds:1e3,algorithm:dt.sha_512})}h(mr,"deriveDelegateSecret");async function Sf({primaryTjpAddr:o,deviceTag:e}){if(!o)throw new Error("primaryTjpAddr is required to derive device delegate secret (E: dc67084e43e8863ed8295e286a6c9826)");let t=await q(32),r=`${o}_${e||""}_${t}`;return await te({s:r,algorithm:dt.sha_512})}h(Sf,"deriveDeviceDelegateSecret");async function kr({profileName:o,profileTemplate:e,username:t,deviceTag:r,primaryTjpAddr:n,delegateSecret:a,custodianReqs:s,expirationUTC:i,additionalFrameDetails:c,metaspace:l,space:d}){let f=`[${kr.name}]`;try{if(!o&&!e)throw new Error("profileName or profileTemplate is required (E: 73c18f85c5280c7548a468d812f05826)");if(!n)throw new Error("primaryTjpAddr is required (E: 85efd879ee027c06384d7df88b460826)");if(!a)throw new Error("delegateSecret is required (E: ae4d5f261e3817e078cc9f984bbadb26)");let b=r||"primary-device",p=e?an.fromTemplate(e):an.buildKeystone(o),u=bt({text:b,keepLiterals:["-"]})||"device",m=bt({text:t,keepLiterals:["-"]})||"user";p.withUsername(`${m}-sync-${u}`.slice(0,60)).withDescription(`Sync Delegate for ${t} on ${b}`).withDetails({client:"space-gib-web",role:_f,deviceTag:b,primaryTjpAddr:n,...s?{custodianReqs:s}:{},...c||{}}),i&&p.withExpiration(i);let g=await p.compileConfigs(),y=p.getFrameDetails();return await new Mt().genesis({masterSecret:a,configs:g,metaspace:l,space:d,frameDetails:y,isPrimary:!1})}catch(b){throw console.error(`${f} ${E(b)}`),b}}h(kr,"createSyncDelegateKeystone");function ji({keystone:o,nowUTC:e}){if(!o||!o.data?.frameDetails?.expirationUTC)return!1;let t=Date.parse(o.data.frameDetails.expirationUTC);return isNaN(t)?!1:(e!==void 0?typeof e=="number"?e:e instanceof Date?e.getTime():Date.parse(e):Date.now())>t}h(ji,"isKeystoneExpired");function If({delegateInfo:o,delegateKeystone:e,nowUTC:t}){if(!o&&!e)throw new Error("either delegateInfo or delegateKeystone required. (E: d1baa55ca8d23b26f8562a28179d2126)");if(e)return ji({keystone:e,nowUTC:t});if(!o||!o.expirationUTC)return!1;let r=Date.parse(o.expirationUTC);return isNaN(r)?!1:(t!==void 0?typeof t=="number"?t:t instanceof Date?t.getTime():Date.parse(t):Date.now())>r}h(If,"isDelegateExpired");function Gp({keystone:o,aggregatedDetails:e,providerId:t}){let r=`[${Gp.name}]`;try{Gf&&console.log(`${r} starting... (I: 1db5581127983918ff303dd8370daf26)`);let n=`${Da}${t}`;if(o.data?.challengePools?.some(s=>s.id===n))return!0;if(!(o.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||o.data?.custodyMode==="hybrid")){let s=e?.custodianProvider||o.data?.frameDetails?.custodianProvider||o.data?.custodianProvider;if(s&&String(s).toLowerCase()===String(t).toLowerCase())return!0}return!1}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Gf&&console.log(`${r} complete.`)}}h(Gp,"isSsoProviderLinked");function Af({delegateInfo:o,delegateKeystone:e,providerId:t}){if(!o&&!e)return!1;let r=o?.role||e?.data?.frameDetails?.role,n=o?.deviceName||e?.data?.frameDetails?.deviceTag,a=o?.metadata?.provider||e?.data?.frameDetails?.custodianProvider||e?.data?.frameDetails?.metadata?.provider,s=r===Tf||r==="custodial-sync";if(a)return t?String(a).toLowerCase()===String(t).toLowerCase():!0;if(n){let i=n.toLowerCase();if(t){let c=String(t).toLowerCase();return i.includes(c)||s&&i.includes("custodian")}if(i.includes("custodian")||i.includes("oauth2")||i.includes("google")||i.includes("github")||i.startsWith("email-")||i.includes("@"))return!0}return!!(!t&&s)}h(Af,"isCustodialDelegate");function H$({keystone:o,aggregatedDetails:e}){if(!o)return{isSovereign:!1,isCustodial:!1,isHybrid:!1,providers:[],emails:[]};let t=e?.emails||o.data?.frameDetails?.emails||[],r=o.data?.challengePools||[],n=e?.custodianProvider||o.data?.frameDetails?.custodianProvider||o.data?.custodianProvider,s=!(o.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||o.data?.custodyMode==="hybrid")&&(!!n||o.data?.frameDetails?.custodyMode==="full"||e?.custodyMode==="full"||o.data?.custodyMode==="full"),i=new Set;for(let w of r)if(w.id.startsWith(Da)){let A=w.id.substring(Da.length);A&&i.add(A)}s&&n&&i.add(n);let c=Array.from(i),l=c.length>0||s,d=r.some(w=>w.id==="manage"),b=r.filter(w=>w.id.startsWith("passkey-manage-")).length||(o.data?.credentialIds?o.data.credentialIds.length:0),p=b>0,u=d&&!s,m=(d||p)&&!s,g=l;return{isSovereign:m,isCustodial:g,isHybrid:m&&g,providers:c,emails:t,hasPasskeys:p,passkeyCount:b,hasPassword:u}}h(H$,"getKeystoneCapabilities");function po(o){let e=(o?.userAgent??(typeof navigator<"u"?navigator.userAgent:"")??"").toLowerCase(),t=o?.userAgentData??(typeof navigator<"u"?navigator.userAgentData:void 0),r=o?.maxTouchPoints??(typeof navigator<"u"?navigator.maxTouchPoints:0)??0,n=o?.screenWidth??(typeof window<"u"?window.innerWidth:1024)??1024,a="",s=t?.mobile,i=/mobile|iphone|ipod|android.*mobile|windows phone/i.test(e);/ipad|tablet|(android(?!.*mobile))/i.test(e)||r>1&&/macintosh/i.test(e)&&n<=1366?a="tablet":(s||i)&&(a="mobile");let l="",d=(t?.platform||"").toLowerCase();d.includes("win")||e.includes("windows")?l="win":d.includes("ios")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?l="ios":d.includes("mac")||e.includes("macintosh")||e.includes("mac os")?l="mac":d.includes("android")||e.includes("android")?l="android":(d.includes("linux")||e.includes("linux"))&&(l="linux");let f="";e.includes("edg/")||e.includes("edge/")?f="edge":e.includes("chrome/")||e.includes("crios/")?f="chrome":e.includes("firefox/")||e.includes("fxios/")?f="firefox":e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&(f="safari");let b=o?.randomSuffix;if(!b){let u="0123456789abcdef";b="";for(let m=0;m<4;m++)b+=u.charAt(Math.floor(Math.random()*u.length))}b=b.toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,8);let p=[];return a&&p.push(a),f&&p.push(f),l&&p.push(l),p.length===0&&p.push("device"),p.push(b),p.join("-")}h(po,"generateDefaultDeviceTag");var Sp="ibgib_device_delegate_secret_";function xf({primaryTjpAddr:o}){if(!o)throw new Error("primaryTjpAddr is required to get device delegate secret key (E: ffded6bca518d51fb8365ad81cd81226)");return`${Sp}${o}`}h(xf,"getDeviceDelegateSecretKey");async function Cf({primaryTjpAddr:o}){let e=`[${Cf.name}]`;try{if(!o)throw new Error("primaryTjpAddr is required to get device delegate secret (E: f55d08cfb548e0fea8610d95b0befd26)");let t=Pa(),r=va(),n=xf({primaryTjpAddr:o});return await io({dbName:t,storeName:r,key:n})}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(Cf,"getDeviceDelegateSecret");async function fn({primaryTjpAddr:o,delegateSecret:e}){let t=`[${fn.name}]`;try{if(!o)throw new Error("primaryTjpAddr is required to set device delegate secret (E: cbc078280958c613d24bff8747537826)");if(!e)throw new Error("delegateSecret is required to set device delegate secret (E: 65ebf6395a1ee6b5c87e4448df61f926)");let r=Pa(),n=va(),a=xf({primaryTjpAddr:o});await Qo({dbName:r,storeName:n,key:a,value:e})}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(fn,"setDeviceDelegateSecret");async function qi({primaryTjpAddr:o,deviceTag:e}){let t=`[${qi.name}]`;try{if(!o)throw new Error("primaryTjpAddr is required to get or create device delegate secret (E: 846c4e72e12803c5bac83688b7f6f826)");let r=await Cf({primaryTjpAddr:o});if(r)return r;let n=await Sf({primaryTjpAddr:o,deviceTag:e});return await fn({primaryTjpAddr:o,delegateSecret:n}),n}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(qi,"getOrCreateDeviceDelegateSecret");async function t6({username:o,primaryTjpAddr:e,masterSecret:t,metaspace:r,space:n}){let a=await mr({masterSecret:t});await fn({primaryTjpAddr:e,delegateSecret:a});let s=bt({text:o,length:8,keepLiterals:["-"]})||"user",i=po(),c=`pwd-${s}-${i}`,l="sync-profile.dev";if(!l||!l.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing.");return{delegateKeystone:await kr({profileName:l.trim(),username:o,deviceTag:c,primaryTjpAddr:e,delegateSecret:a,additionalFrameDetails:{client:"space-gib-web"},metaspace:r,space:n}),deviceTag:c,delegateSecret:a}}h(t6,"createSovereignDeviceSyncDelegate");async function r6({providerId:o,username:e="user",primaryTjpAddr:t,custodianReqs:r,metaspace:n,space:a}){let s=await qi({primaryTjpAddr:t}),i=po(),c=`oauth2-${o}-${i}`,l="sync-profile.dev";if(!l||!l.trim())throw new Error("KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing.");return{delegateKeystone:await kr({profileName:l.trim(),username:e,deviceTag:c,primaryTjpAddr:t,delegateSecret:s,custodianReqs:r,additionalFrameDetails:{client:"space-gib-web"},metaspace:n,space:a}),deviceTag:c,delegateSecret:s}}h(r6,"createOAuth2DeviceSyncDelegate");async function o6({email:o,username:e,primaryTjpAddr:t,custodianReqs:r,metaspace:n,space:a}){let s=await qi({primaryTjpAddr:t}),i=po(),[c="",l=""]=(o||"").split("@"),d=bt({text:e||c,length:62,keepLiterals:[],replaceMap:{" ":"_"}}).toLowerCase()||"user",f=l.split(".")[0]||"",b=f?bt({text:f,length:8,keepLiterals:["-"]}):"",u=`email-${b?`${d.slice(0,8)}@${b}`:d.slice(0,8)}-${i}`,m=d,g="sync-profile.dev";if(!g||!g.trim())throw new Error("KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing.");return{delegateKeystone:await kr({profileName:g.trim(),username:m,deviceTag:u,primaryTjpAddr:t,delegateSecret:s,custodianReqs:r,additionalFrameDetails:{client:"space-gib-web"},metaspace:n,space:a}),deviceTag:u,delegateSecret:s}}h(o6,"createEmailDeviceSyncDelegate");async function Xi(){try{if(typeof window>"u"||!window.PublicKeyCredential)return!1;if(typeof window.PublicKeyCredential.getClientCapabilities=="function"){let o=await window.PublicKeyCredential.getClientCapabilities();if(o&&o.prf)return!0}return typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable=="function"?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1}catch{return!1}}h(Xi,"isPasskeyPrfSupported");function Oa(o){return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}h(Oa,"bufferToHex");function Nf(o){let e=o.replace(/[^0-9a-fA-F]/g,""),t=new Uint8Array(Math.floor(e.length/2));for(let r=0;r<t.length;r++)t[r]=parseInt(e.substr(r*2,2),16);return t}h(Nf,"hexToUint8Array");function Df(o){if(o instanceof Uint8Array){if(o.length===32)return o;let r=new Uint8Array(32);return r.set(o.subarray(0,32)),r}if(/^[0-9a-fA-F]{64}$/.test(o))return Nf(o);let e=new TextEncoder().encode(o),t=new Uint8Array(32);return t.set(e.subarray(0,32)),t}h(Df,"normalizeSaltTo32Bytes");async function d6({username:o,displayName:e=o,rpName:t="ibgib",rpId:r,salt:n,userVerification:a="preferred",authenticatorAttachment:s,hints:i=["security-key","client-device","hybrid"]}){let c="[registerPasskeyCredential]";try{if(typeof window>"u"||!navigator.credentials?.create)throw new Error("WebAuthn is not supported in this browser environment.");let l=r||(typeof window<"u"?window.location.hostname:void 0),d=crypto.getRandomValues(new Uint8Array(32)),f=new TextEncoder().encode(o.slice(0,64)),b=n?Df(n):void 0,p=b?{eval:{first:b}}:{},u=await navigator.credentials.create({publicKey:{challenge:d,rp:{name:t,...l?{id:l}:{}},user:{id:f,name:o,displayName:e},pubKeyCredParams:[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"},{alg:-8,type:"public-key"}],authenticatorSelection:{residentKey:"required",userVerification:a,...s?{authenticatorAttachment:s}:{}},...i&&i.length>0?{hints:i}:{},extensions:{prf:p}}});if(!u)throw new Error("Passkey creation was cancelled or failed.");let m=Oa(u.rawId),g=u.response,y=typeof g.getTransports=="function"?g.getTransports():[],w=u.getClientExtensionResults?.()||{};console.log(`${c} WebAuthn registration clientExtensionResults:`,w);let A;return w.prf?.results?.first&&(A=Oa(w.prf.results.first),console.log(`${c} Evaluated PRF directly during create!`)),{credentialId:m,rawId:u.rawId,transports:y,passkeySecret:A}}catch(l){throw console.error(`${c} ${E(l)}`),l}}h(d6,"registerPasskeyCredential");async function Hi({salt:o,credentialId:e,transports:t,rpId:r,userVerification:n="preferred",hints:a=["security-key","client-device","hybrid"]}){let s="[evaluatePasskeyPrf]";try{if(typeof window>"u"||!navigator.credentials?.get)throw new Error("WebAuthn is not supported in this browser environment.");let i=r||(typeof window<"u"?window.location.hostname:void 0),c=crypto.getRandomValues(new Uint8Array(32)),l=Df(o),d,f;if(e){let w=Nf(e);f=[{id:w.buffer,type:"public-key",...t&&t.length>0?{transports:t}:{}}];let A="";for(let G=0;G<w.byteLength;G++)A+=String.fromCharCode(w[G]);d=btoa(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}let b={eval:{first:l}};d&&(b.evalByCredential={[d]:{first:l}});let p=await navigator.credentials.get({publicKey:{challenge:c,...i?{rpId:i}:{},allowCredentials:f,userVerification:n,...a&&a.length>0?{hints:a}:{},extensions:{prf:b}}});if(!p)throw new Error("Passkey authentication was cancelled or failed.");let u=Oa(p.rawId),m=p.getClientExtensionResults?.()||{};console.log(`${s} WebAuthn assertion clientExtensionResults:`,JSON.stringify(m),m);let g=m.prf?.results?.first;if(!g&&d&&m.prf?.resultsByCredential?.[d]?.first&&(g=m.prf.resultsByCredential[d].first,console.log(`${s} Extracted PRF result from resultsByCredential!`)),!g)throw console.error(`${s} Extension results did not contain PRF evaluation:`,JSON.stringify(m),m),new Error("Authenticator did not return a PRF evaluation. PRF extension may not be supported on this authenticator.");return{passkeySecret:Oa(g),credentialId:u}}catch(i){throw console.error(`${s} ${E(i)}`),i}}h(Hi,"evaluatePasskeyPrf");async function f6({username:o,primaryTjpAddr:e,passkeySecret:t,transports:r,metaspace:n,space:a}){let s=await mr({masterSecret:t});await fn({primaryTjpAddr:e,delegateSecret:s});let i=bt({text:o,length:8,keepLiterals:["-"]})||"user",c=po(),l=`passkey-${i}-${c}`,d="sync-profile.dev";if(!d||!d.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing.");return{delegateKeystone:await kr({profileName:d.trim(),username:o,deviceTag:l,primaryTjpAddr:e,delegateSecret:s,additionalFrameDetails:{client:"space-gib-web",role:"passkey-sync",...r&&r.length>0?{transports:r}:{}},metaspace:n,space:a}),deviceTag:l,delegateSecret:s}}h(f6,"createPasskeyDeviceSyncDelegate");var We=pr;function Pf(o){return new TextDecoder().decode(o)}h(Pf,"uint8ArrayToString");var vf=class o{static{h(this,"PathUtilsHelper")}lc=`[${o.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 r="";for(let n=0;n<e.length;n++){let a=e[n];a===".."?r=r.split("/").slice(0,-1).join("/"):(a.startsWith("/")&&(a=a.slice(1)),a.endsWith("/")&&(a=a.slice(0,-1)),r+=(n>0?"/":"")+a)}return r}dirname(e){return e.split("/").slice(0,-1).join("/")}basename(e,t){return e.split("/").pop()??""}};async function xp({msg:o,title:e,confirm:t,noNewLine:r,rl:n,defaultValue:a,dontCloseRl:s,cancelable:i}){let c=`[${xp.name}]`;try{if(!o)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let l,d=0,f=5;do{if(d++,d>=f)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await De(50),l=await ur({title:e||"Prompt for Info",msg:o,prompt:!0,showInput:!0,isPassword:!1,defaultValue:a})}while(l===void 0&&!i);return l??""}catch(l){debugger;throw console.error(`${c} ${E(l)}`),l}}h(xp,"promptForText");async function Cp({msg:o,confirm:e,passkeys:t}){let r=`[${Cp.name}]`;try{We&&console.log(`${r} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let n,a=!0,s=0,i=5,l=await Xi().catch(()=>!1)&&t&&Object.keys(t).length>0?async d=>{if(!d)return;let{passkeySecret:f}=await Hi({credentialId:d.credentialId,salt:d.salt,transports:d.transports,userVerification:"preferred"});return f}:void 0;do{if(s++,s>=i)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await De(50),n=await ur({title:a?"Shh...":"Secrets didn't match, try again...",msg:o||"Enter Your Secret...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0,passkeys:t,onPasskeyAuth:l}),n===void 0)throw new Error("user cancelled (E: 91519d04378e84106f3df8eb36d99725)");if(typeof n=="object"&&n?.secret!==void 0&&(n=n.secret),e){await De(250);let d=await ur({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});d===void 0&&(n=void 0),typeof d=="object"&&d?.secret!==void 0&&(d=d.secret),n!==d&&(n=void 0,a=!1,await De(250))}}while(n===void 0);return n}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{We&&console.log(`${r} complete.`)}}h(Cp,"promptForSecret");async function Np({keystone:o,aggregatedDetails:e,title:t,msg:r,verb:n="manage"}){let a=`[${Np.name}]`;try{let s=e?.passkeys||o.data?.frameDetails?.passkeys||o.data?.passkeys||{},c=await Xi().catch(()=>!1)&&s&&Object.keys(s).length>0?async b=>{if(!b)return;let{passkeySecret:p}=await Hi({credentialId:b.credentialId,salt:b.salt,transports:b.transports,userVerification:"preferred"});return p}:void 0,d=(o.data?.challengePools||[]).filter(b=>b.id==="manage"||b.id.startsWith("passkey-manage-")||b.config?.allowedVerbs&&n&&b.config.allowedVerbs.includes(n)).some(b=>b.id==="manage"),f=await ur({title:t||"Authorize Action",msg:r||"Authorize this action with your master password or passkey:",prompt:!0,showInput:d,isPassword:!0,defaultValue:void 0,passkeys:s,onPasskeyAuth:c});if(!f)throw new Error("Action cancelled by user.");return typeof f=="object"&&f.secret!==void 0?{secret:f.secret,poolId:f.poolId||"manage"}:{secret:String(f),poolId:"manage"}}catch(s){throw console.error(`${a} ${E(s)}`),s}}h(Np,"promptForAuthoritySecret");async function Dp({msg:o,yesLabel:e,noLabel:t}){let r=`[${Dp.name}]`;try{return await De(50),!!await ur({title:"Confirm?",msg:o??"Confirm?",okButtonTitle:e||void 0,cancelButtonTitle:t||void 0,prompt:!0})}catch(n){throw console.error(`${r} ${n.message}`),n}finally{We&&console.log(`${r} complete.`)}}h(Dp,"promptForConfirm");async function vp({msg:o,title:e,skipHitEnterToContinue:t}){let r=`[${vp.name}]`;try{if(!o)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{e??="",await De(50),await ur({title:e,msg:o})}catch(n){throw n}}catch(n){throw console.error(`${r} ${E(n)}`),n}}h(vp,"alertUser");async function Pp({exportIbGibJsonString:o,metaspace:e}){let t=`[${Pp.name}]`;try{debugger;if(We&&console.log(`${t} starting... (I: b837df7fe8d1ee8831c1701210b55826)`),!e)throw new Error("(UNEXPECTED) metaspace falsy? (E: d2a16a6177a8d6aa6801a53bbce3e626)");if(!await e.getLocalUserSpace({lock:!1}))throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 109c7868b5a8a511e82391d8b91c9826)");let n,a;try{n=JSON.parse(o)}catch(l){let d=`Error during parse JSON. error: ${E(l)} (E: 24912680953c28e55dcf4784e4114826)`,f=new Error(d);throw f.cause=l,f}try{let l=await ne({ibGib:n})??[];if(l.length>0)throw new Error(`validation errors when validating the parsed ibgib that should be a RawExportIbGib_V1: ${l} (E: 8ba178d3b26e8eca28a67c182fe16825)`);if(a=n,!a.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)")}catch(l){let d=`Error during parse JSON. error: ${E(l)} (E: 9607589c692857f5280c4cc884624326)`,f=new Error(d);throw f.cause=l,f}let s;if(a.data.compression)switch(a.data.compression){case"gzip":s=await Ti({compressedBase64:a.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${a.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else s=await wa({jsonString:a.data.dependencyGraphAsString});let i={};for(let[l,d]of Object.entries(s)){let f=await ne({ibGib:d})??[];f.length>0&&(i[l]=f)}if(Object.keys(i).length>0)throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:
|
|
22
|
+
${X({validationErrorMap:i})} (E: e63f38b182a84122d83a55befb369825)`);return[a,s]}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{We&&console.log(`${t} complete.`)}}h(Pp,"getRawExportIbGibAndGraphFromJsonString");async function Op({ibGib:o,compress:e,metaspace:t,space:r}){let n=`[${Op.name}]`;try{if(We&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),Ce({ibGib:o}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let a=await Gi({ibGib:o,live:!0,compress:e,metaspace:t,space:r}),{rawExportIbGib:s,errors:i}=a;if((i??[]).length>0)throw new Error(`Export had errors: ${i} (E: 05faf83f25d3449ab809dfd24eeaf825)`);let c=JSON.stringify(s),l="data:text/json;charset=utf-8,"+encodeURIComponent(c),f=`${I({ibGib:s})}.json`,b=document.createElement("a");b.setAttribute("style","none"),b.setAttribute("href",l),b.setAttribute("download",f);let p=document.getElementsByTagName("div")[0];p.appendChild(b),b.click(),p.removeChild(b)}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{We&&console.log(`${n} complete.`)}}h(Op,"exportIbGib");function Of({id:o,shadowRoot:e}){let t=`[${Of.name}]`;try{We&&console.log(`${t} starting... (I: 18a338c6dab8690c72b8759b8d952925)`);let r=e?e.getElementById(o):document.getElementById(o);if(r)return r;throw new Error(`${e?"shadowRoot":"document"}.getElementById(${o}) returned null. So...Element was not found. (E: 5e501f6835cc74cd4c2faf0d9e387825)`)}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{We&&console.log(`${t} complete.`)}}h(Of,"getElementById_throwsIfFalsy");function S6(o,e){return Of({id:e,shadowRoot:o})}h(S6,"shadowRoot_getElementById");function va(){let o=`[${va.name}]`;try{We&&console.log(`${o} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let e=Rr();if(!e.storeName_hack)throw new Error("(UNEXPECTED) global store name falsy? (E: 3b9b680f6a980debbb877c9a13fb2625)");return e.storeName_hack}catch(e){throw console.error(`${o} ${E(e)}`),e}finally{We&&console.log(`${o} complete.`)}}h(va,"getGlobalStoreName");function Pa(){let o=`[${Pa.name}]`;try{We&&console.log(`${o} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let e=Rr();if(!e.dbName_hack)throw new Error("(UNEXPECTED) global db name falsy? (E: 3aa028d5e4088f3f3841aae94ac02825)");return e.dbName_hack}catch(e){throw console.error(`${o} ${E(e)}`),e}finally{We&&console.log(`${o} complete.`)}}h(Pa,"getGlobalDbName");function Lp(){let o=`[${Lp.name}]`;try{We&&console.log(`${o} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let e=Rr();if(!e.apiKeyName_hack)throw new Error("(UNEXPECTED) global api key name falsy? (E: 1782e812f0c87f54b8059468a5b60125)");return e.apiKeyName_hack}catch(e){throw console.error(`${o} ${E(e)}`),e}finally{We&&console.log(`${o} complete.`)}}h(Lp,"getGlobalIndexedDbKey_APIKey");async function Vi({infos:o}){let e=`[${Vi.name}]`;try{We&&console.log(`${e} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let t of o){let{dbName:r,storeNames:n}=t;await Yi({dbName:r})||await La({dbName:r});for(let s of n)await Wi({dbName:r,storeName:s})}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{We&&console.log(`${e} complete.`)}}h(Vi,"initAppStorage");var ct=pr,Lf=0;async function La({dbName:o,storeName:e,version:t,logalot:r=!1}){let n=`[${La.name}][${o}][${e??"no store name"}]`,a=crypto.randomUUID();r&&console.time(n+a);let s;try{r&&console.log(`${n} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`),await new Promise((c,l)=>{try{r&&console.log(`${n} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`),r&&console.timeLog(n+a,"opening... (I: e748b4ddb445d77cb10a7ba158b49125)");let d=indexedDB.open(o,t);Lf++,console.log(`${n} initRequestCount: ${Lf} (I: 294d5f0b12ffe5512bacebe891824d25)`);let f;d.onupgradeneeded=b=>{try{s=b.target.result,r&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),e&&(s.objectStoreNames.contains(e)?f=!0:(f=!1,s.createObjectStore(e,{keyPath:"key"})))}catch(p){console.error(`${n}[openDBRequest.onupgradeneeded] ${E(p)} (E: 4a5fa1b0850be47e28bee653da287325)`),l(p)}},d.onblocked=b=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${b.oldVersion} -> ${b.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(b)},d.onsuccess=b=>{try{r&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),r&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),s=b.target.result,e&&(f??=s.objectStoreNames.contains(e),r&&console.log(`${n} ${o} store "${e}" ${f?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(p){console.error(`${n}[openDBRequest.onsuccess] ${E(p)}`),l(p)}},d.onerror=b=>{debugger;console.error(`${n}[initRequest.onerror] ${E(d.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`),l(d.error)}}catch(d){console.error(`${n} ${E(d)}`);debugger;l(d)}finally{r&&console.log(`${n} complete.`)}})}catch(i){throw console.error(`${n} ${E(i)}`),i}finally{s&&(r&&console.log(`${n} closing db ${o}... (I: 3f1c18eec567ea63f3927eef0f038925)`),s.close(),r&&(console.log(`${n} closing db ${o} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`),console.timeLog(n+a,"db closed. (I: e748b4ddb445d77cb10a7ba158b49125)"))),r&&(console.log(`${n} complete.`),console.timeEnd(n+a))}}h(La,"initializeStorage");async function Rf({dbName:o,logalot:e=!1}){let t=`[${Rf.name}]`,r=crypto.randomUUID();e&&console.time(t+r);try{return e&&console.log(`${t} starting... (I: 8516795b20529d19eb6923defd7a0f24)`),(await indexedDB.databases()).filter(a=>a.name===o).at(0)}catch(n){console.error(`${t} ${E(n)}`)}finally{e&&console.timeEnd(t+r),e&&console.log(`${t} complete.`)}}h(Rf,"storageGetDBInfo");async function Wi({dbName:o,storeName:e,logalot:t=!1}){let r=`[${Wi.name}]`,n=crypto.randomUUID();t&&console.time(r+n);let a;try{if(t&&console.log(`${r} starting... (I: 029f7caa8ea5ea08a865f3924c82b624)`),!(await indexedDB.databases()).filter(f=>f.name===o).at(0))throw new Error(`db (${o}) does not exist. can't create store (${e}) (E: 5b15f7aed6f7068d077b2c7ebcbe8524)`);let i=!1;if(t&&console.timeLog(r+n),await new Promise((f,b)=>{let p=indexedDB.open(o);p.onsuccess=u=>{a=u.target.result,i=a.objectStoreNames?.contains(e),t&&console.timeLog(r+n,"open db request"),f()},p.onerror=u=>{debugger;console.error(`${r}[openDBRequest.onerror] ${E(p.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),b(p.error)}}),t&&console.timeLog(r+n),i){t&&console.log(`${r} store ${e} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await Rf({dbName:o,logalot:t});if(t&&console.timeLog(r+n,"storageGetDBInfo complete"),!c)throw new Error(`db (${o}) does not exist. can't create store (${e}) (E: c771db13fa28f67079aad45e1ab7e624)`);let l=c.version;if(!l)throw new Error(`db (${o}) has no version. can't create store (${e}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`);let d=l+1;if(t&&console.log(`${r} creating store ${e} with version ${d} (I: 312b79f28243c650cf38935114f21e24)`),a)a.close(),a=void 0;else throw new Error("(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)");await La({dbName:o,storeName:e,version:d,logalot:t})}catch(s){throw console.error(`${r} ${E(s)}`),s}finally{a&&(t&&console.log(`${r} closing db ${o}... (I: 3f1c18eec567ea63f3927eef0f038925)`),a.close(),t&&console.log(`${r} closing db ${o} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`)),t&&console.timeLog(r+n),t&&console.log(`${r} complete.`)}}h(Wi,"storageCreateStoreIfNotExist");async function Qo({dbName:o,version:e,storeName:t,key:r,value:n,logalot:a=!1}){let s=`[${Qo.name}]`,i;try{a&&console.log(`${s} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((l,d)=>{try{a&&console.log(`${s} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let f=indexedDB.open(o,e);f.onsuccess=b=>{i=b.target.result;try{let p=i.transaction(t,"readwrite").objectStore(t),u={key:r,value:n};p.put(u),l()}catch(p){console.error(`${s}[putRequest.onsuccess] ${E(p)}`),d(p)}},f.onerror=b=>{debugger;console.error(`${s}[putRequest.onerror] ${E(f.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),d(f.error)}}catch(f){console.error(`${s} ${E(f)}`),d(f)}finally{a&&console.log(`${s} complete.`)}})}catch(c){throw console.error(`${s} ${E(c)}`),c}finally{i&&(a&&console.log(`${s} closing db ${o}... (I: 438c6edced94b83a3478c71b08c6c325)`),i.close(),a&&console.log(`${s} closing db ${o} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`)),a&&console.log(`${s} complete.`)}}h(Qo,"storagePut");async function io({dbName:o,version:e,storeName:t,key:r,logalot:n=!1}){let a=`[${io.name}]`,s;try{return n&&console.log(`${a} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`),await new Promise((l,d)=>{try{n&&console.log(`${a} starting... (I: 24163c4a11c8712097db45febaf9c724)`);let f=indexedDB.open(o,e);f.onsuccess=b=>{s=b.target.result;let p;try{p=s.transaction(t).objectStore(t)}catch(m){debugger;console.error(`${a}[openDBRequest.onsuccess][objectStore] ${E(m)}`),d(m);return}let u=p.get(r);u.onsuccess=m=>{try{let g=m.target?.result?.value??void 0;if(!g){l(g);return}if(n&&console.log("Retrieved value:",g),g instanceof Uint8Array)l(Pf(g));else{if(typeof g!="string")throw new Error("(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)");l(g)}}catch(g){d(g)}},u.onerror=m=>{debugger;let g=u.error;console.error(`${a}[openDBRequest.onsuccess][getRequest.onerror] ${E(g)}`),d(g)}},f.onerror=b=>{debugger;console.error(`${a}[openDBRequest.onerror] ${E(f.error)} (E: 074963a908fa9a075f01c73cae829224)`),d(f.error)}}catch(f){console.error(`${a} ${E(f)}`),d(f)}finally{n&&console.log(`${a} complete.`)}})}catch(i){throw console.error(`${a} ${E(i)}`),i}finally{s&&(n&&console.log(`${a} closing db ${o}... (I: a938fc22dfdc76b15f6926bc4d458225)`),s.close(),n&&console.log(`${a} closing db ${o} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`)),n&&console.log(`${a} complete.`)}}h(io,"storageGet");async function Yi({dbName:o,store:e}){let t=`[${Yi.name}]`,r;try{return ct&&console.log(`${t} starting... (I: 2b4373affa3841220f0b7ca690406624)`),(await window.indexedDB.databases()).some(s=>s.name===o)?e?await new Promise((s,i)=>{let c=indexedDB.open(o);c.onsuccess=l=>{r=l.target.result;let d=r.objectStoreNames.contains(e);s(d)},c.onerror=l=>{debugger;r=c.result;let{error:d}=l.target;console.error(`${t}[openDBRequest.onerror] ${E(c.error)} (E: c783fe607451e46c1feae3a81e0f7924)`),i(d)}}):!0:!1}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{r&&(ct&&console.log(`${t} closing db ${o}... (I: 8782d9eea285cf9eb638d493a421a625)`),r.close(),ct&&console.log(`${t} closing db ${o} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),ct&&console.log(`${t} complete.`)}}h(Yi,"storageDBExists");async function Rp({dbName:o,storeName:e,pathToRm:t}){let r=`[${Rp.name}]`,n=ct;ct&&console.log(`${r} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`);let a;return new Promise((s,i)=>{try{if(!o)throw new Error("(UNEXPECTED) dbName falsy? (E: ed336d88c9c4e8d4916b29356dc58324)");if(!e)throw new Error("(UNEXPECTED) storeName falsy? (E: ad493bb79b63a192524b14c59a706524)");if(!t)throw new Error("(UNEXPECTED) pathToRm falsy? (E: 88c9631d93467e17996946882254af24)");let c=indexedDB.open(o);c.onerror=()=>{debugger;c.result&&c.result.close(),console.error(`${r}[openDBRequest.onerror] ${E(c.error)} (E: 4c5ab71a765e61b4292008fd4fafe324)`),i(c.error)},c.onsuccess=()=>{a=c.result;let d=a.transaction(e,"readwrite").objectStore(e),f=IDBKeyRange.lowerBound(t),b=d.openCursor(f);b.onerror=()=>{debugger;console.error(`${r}[openCursorRequest.onerror] ${E(b.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),i(b.error)},b.onsuccess=()=>{try{let p=0,u=b.result;if(u)if(u.key.toString().startsWith(t)){let m=u.delete();p++,m.onerror=()=>{debugger;console.error(`${r}[deleteRequest.onerror] ${E(m.error)} (E: abc031c53e5387322cd8909b3ada9b24)`),i(m.error)},u.continue()}else ct&&console.log(`${r} rmCount: ${p} (I: e4bc613a5514c0942484b79267e16724)`),s();else ct&&console.log(`${r} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`),s()}catch(p){console.error(`${r}[openCursorRequest.onsuccess] ${E(p)}`),i(p)}}}}catch(c){debugger;console.error(`${r} ${E(c)}`),i(c)}}).finally(()=>{a&&(ct&&console.log(`${r} closing db ${o}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),ct&&console.log(`${r} closing db ${o} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),ct&&console.log(`${r} complete.`),ct=n})}h(Rp,"storageRmRF");async function Up({dbName:o,storeName:e,dirPath:t,withFileTypes:r=!1}){let n=`[${Up.name}]`,a;try{return await new Promise((c,l)=>{let d=indexedDB.open(o);d.onerror=()=>{debugger;l(d.error)},d.onsuccess=()=>{a=d.result;let b=a.transaction(e,"readonly").objectStore(e),p=t.endsWith("/")?t:t+"/",u=IDBKeyRange.lowerBound(p),m=b.openCursor(u),g=new Set,y=[];m.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${E(m.error)}`),l(m.error)},m.onsuccess=()=>{try{let w=m.result;if(w){let A=w.key.toString();if(A.startsWith(p)&&A!==p){let G=A.substring(p.length),T=G.split("/")[0];if(r){let $=G.substring(T.length).startsWith("/");y.push({name:T,isDirectory:h(()=>$,"isDirectory"),isFile:h(()=>!$,"isFile"),isBlockDevice:h(()=>!1,"isBlockDevice"),isCharacterDevice:h(()=>!1,"isCharacterDevice"),isSymbolicLink:h(()=>!1,"isSymbolicLink"),isFIFO:h(()=>!1,"isFIFO"),isSocket:h(()=>!1,"isSocket")})}else g.add(T);w.continue()}else A.startsWith(p)?w.continue():c(r?y:Array.from(g))}else c(r?y:Array.from(g))}catch(w){console.error(`${n}[openCursorRequest.onsuccess] ${E(w)}`),l(w)}}}})}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{a&&(ct&&console.log(`${n} closing db ${o}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),ct&&console.log(`${n} closing db ${o} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}h(Up,"storageReaddir");var uo=Ed;async function Mp(o){let e=`[${Mp.name}]`;try{uo&&console.log(`${e} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await Vi({infos:[{dbName:o.dbName,storeNames:[o.storeName,...o.additionalStoreNames??[]]}]})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{uo&&console.log(`${e} complete.`)}}h(Mp,"initIbGibStorage");function Uf(o){let e=`[${Uf.name}]`;try{uo&&console.log(`${e} starting... (I: 7be20d161bb14a498c44a42d3193bec1)`),globalThis.ibgib||(globalThis.ibgib={dbName_hack:o.dbName,apiKeyName_hack:o.apiKeyName,storeName_hack:o.storeName}),globalThis.ibgib.spaceGib||(globalThis.ibgib.spaceGib={version:wd,spaceShim:{},fnDefaultGetAPIKey:h(async()=>await io({dbName:o.dbName,storeName:o.storeName,key:o.apiKeyName})??"","fnDefaultGetAPIKey"),dbName_hack:o.dbName,apiKeyName_hack:o.apiKeyName,storeName_hack:o.storeName})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{uo&&console.log(`${e} complete.`)}}h(Uf,"initIbGibGlobalThis");function j6(o){if(!globalThis.ibgib?.spaceGib){if(!o)throw new Error("Global context not initialized and config not provided.");Uf(o)}return globalThis.ibgib.spaceGib}h(j6,"getIbGibGlobalThis_SpaceGib");async function Fp(o){let e=`[${Fp.name}]`;try{uo&&console.log(`${e} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(o)).bootstrapSpaceGibApp()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{uo&&console.log(`${e} complete.`)}}h(Fp,"dynamicallyLoadBootstrapScript");var Mf="b2s_",Ki="~",Ra="b2tfs_branch",Te="main";var bn=!1,Ua=class o{static{h(this,"WitnessBase_V1")}lc=`[${o.name}]`;set trace(e){let t=`${this.lc}[set trace]`;e!==(this.data?.trace||!1)&&(this.data?(this.data.trace=e,delete this.gib):console.warn(`${t} data is falsy. Can't set.`))}get trace(){return this.data?.trace??!1}set catchAllErrors(e){let t=`${this.lc}[set catchAllErrors]`;e!==this.data?.catchAllErrors&&(this.data?(this.data.catchAllErrors=e,delete this.gib):console.error(`${t} data is falsy. Can't set value.`))}get catchAllErrors(){let e=`${this.lc}[catchAllErrors]`,t=this.data?.catchAllErrors||!1;return(bn||this.trace)&&console.log(`${e} result: ${t}`),t}ib="";gib;data;rel8ns;initialized;constructor(e,t){e&&(this.data=e),t&&(this.rel8ns=t),this.initialized=this.initialize()}initialize(){return Promise.resolve()}toIbGibDto(){return Fe({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return bn&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=B(e.ib),this.gib=B(e.gib),e.data?this.data=B(e.data):delete this.data,e.rel8ns?this.rel8ns=B(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(r){throw console.error(`${t} ${r.message}`),r}finally{bn&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{await this.initialized,this.gib||(this.gib=await Dt(this.toIbGibDto()));let r=await this.validateThis();if(r?.length>0){for(let s of r)console.error(`${t} ${s}`);throw new Error("internal witness validation failed. See `WitnessBase_V1.validateThis` (E: 2b5f73cadbfa416ba189346f3c31cd0c)")}let n=await this.validateWitnessArg(e);if(n?.length>0){for(let s of n)console.error(`${t} ${s}`);throw new Error("arg validation failed. See `WitnessBase_V1.validateWitnessArg` (E: 51531a1d928a485e8ffc277145ec44e9)")}(bn||this.trace)&&console.log(`${t} addr: ${I(e)}`),bn&&console.log(`${t} addr: ${I(e)} (I: f4cf13a44c4e4fc3903f14018e616c64)`);let a=await this.witnessImpl(e);return this.data?.persistOptsAndResultIbGibs&&await this.persistOptsAndResultIbGibs({arg:e,result:a}),a}catch(r){if(console.error(`${t} ${r.message||"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),this.catchAllErrors)return;throw r}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`;try{let r=[];e||r.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)");let n=cr({ib:e?.ib});(n?.length??!1)&&r.push(`invalid arg.ib (E: 2ae362ef274d4c3bb9716800f2106d28) errors: ${n.join(`
|
|
23
|
+
`)}`);let a=ir({gib:e?.gib});(a?.length??!1)&&r.push(`invalid arg.gib (E: 73be275058084d768a39299337f2ce34) errors: ${a.join(`
|
|
24
|
+
`)}`);let s=await ne({ibGib:e});return s?.length??!1?r.push(`arg ibgib invalid intrinsically (E: 73be275058084d768a39299337f2ce34) errors: ${s.join(`
|
|
25
|
+
`)}`):this.data?.allowPrimitiveArgs||Ne({gib:e.gib}).isPrimitive&&r.push('arg is primitive (i.e. gib === "gib") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)'),r}catch(r){throw console.error(`${t} ${r.message}`),r}}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(r){throw console.error(`${e} ${r.message}`),r}return t}persistOptsAndResultIbGibs({arg:e,result:t}){let r=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;return console.warn(`${r} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`),Promise.resolve()}};var Er=!1;function Ff(o){let e=`[${Ff.name}]`;try{let t=o?`${Yo} ${o}`:Yo;return Er&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}h(Ff,"getArgIb");function Bp({ib:o,ibGib:e}){let t=`[${Bp.name}]`;try{if(Er&&console.log(`${t} starting...`),!o)if(e)o=e.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return o.startsWith(Yo)}catch(r){throw console.error(`${t} ${r.message}`),r}finally{Er&&console.log(`${t} complete.`)}}h(Bp,"isArg");function Bf(o){let e=`[${Bf.name}]`;try{let t=o?`${aa} ${o}`:aa;return Er&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}h(Bf,"getResultIb");async function Zt({argData:o,ibMetadata:e,noTimestamp:t}){let r=`[${Zt.name}]`;try{let n=await H.firstGen({ib:Ff(e),parentIbGib:H.primitive({ib:Yo}),data:o,dna:!1,noTimestamp:t});if(n.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Dt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${r} ${n.message}`),n}}h(Zt,"argy_");async function Qt({resultData:o,ibMetadata:e,noTimestamp:t}){let r=`[${Qt.name}]`;try{let n=await H.firstGen({ib:Bf(e),parentIbGib:H.primitive({ib:aa}),data:o,dna:!1,noTimestamp:t});if(n?.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Dt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${r} ${n.message}`),n}}h(Qt,"resulty_");function zi({ibGib:o}){let e=`[${zi.name}]`;try{if(Er&&console.log(`${e} starting...`),!o)throw new Error("ibGib required (E: e11cee2a6c59a5e7a4d39ea55751c423)");if(!o.data)return!1;let t=o.data;return t.cmd&&typeof t.cmd=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Er&&console.log(`${e} complete.`)}}h(zi,"isCommand");function Ji({ibGib:o}){let e=`[${Ji.name}]`;try{return Er&&console.log(`${e} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof o.witness=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Er&&console.log(`${e} complete.`)}}h(Ji,"isWitness");var mo=!1,Ma=class o extends Ua{static{h(this,"SpaceBase_V1")}lc=`[${o.name}]`;cacheSvc;constructor(e,t){super(e,t),this.initialized=this.initialize()}async witnessImpl(e){let t=`${this.lc}[${this.witnessImpl.name}]`;return mo&&console.log(`${t}`),await this.routeAndDoCommand({cmd:e.data.cmd,cmdModifiers:e.data.cmdModifiers??[],arg:e})}routeAndDoCommand({cmd:e,cmdModifiers:t,arg:r}){let n=`${this.lc}[${this.routeAndDoCommand.name}]`;switch(e){case Lt.get:return(t??[]).length===0?this.get(r):t.includes("can")?this.canGet(r):t.includes("latest")?t.includes("addrs")?this.getLatestAddrs(r):this.getLatestIbGibs(r):t.includes("tjps")?t.includes("addrs")?this.getTjpAddrs(r):this.getTjpIbGibs(r):t.includes("addrs")?this.getAddrs(r):t.includes("dependency-graph")?this.getDependencyGraph(r):this.get(r);case Lt.put:return(t??[]).length===0?this.put(r):t.includes("can")?this.canPut(r):this.put(r);case Lt.delete:return(t??[]).length===0?this.delete(r):t.includes("can")?this.canDelete(r):this.delete(r);default:throw new Error(`${n} unknown cmd: ${e}. cmdModifiers: ${t}`)}}get(e){return this.getImpl(e)}put(e){return this.putImpl(e)}delete(e){return this.deleteImpl(e)}deleteImpl(e){let t=`${this.lc}[${this.deleteImpl.name}]`;throw new Error(`${t} not implemented in base class`)}getAddrs(e){return this.getAddrsImpl(e)}getAddrsImpl(e){let t=`${this.lc}[${this.getAddrsImpl.name}]`;throw new Error(`${t} not implemented in base class`)}getLatestIbGibs(e){return this.getLatestIbGibsImpl(e)}getLatestIbGibsImpl(e){let t=`${this.lc}[${this.getLatestIbGibsImpl.name}]`;throw new Error(`${t} not implemented in base class`)}getLatestAddrs(e){return this.getLatestAddrsImpl(e)}getLatestAddrsImpl(e){let t=`${this.lc}[${this.getLatestAddrsImpl.name}]`;throw new Error(`${t} not implemented in base class`)}getTjpIbGibs(e){return this.getTjpIbGibsImpl(e)}getTjpIbGibsImpl(e){let t=`${this.lc}[${this.getTjpIbGibsImpl.name}]`;throw new Error(`${t} not implemented in base class`)}getTjpAddrs(e){return this.getTjpAddrsImpl(e)}getTjpAddrsImpl(e){let t=`${this.lc}[${this.getTjpAddrsImpl.name}]`;throw new Error(`${t} not implemented in base class`)}canGet(e){return this.canGetImpl(e)}canGetImpl(e){let t=`${this.lc}[${this.canGetImpl.name}]`;throw new Error(`${t} not implemented in base class`)}canPut(e){return this.canPutImpl(e)}canPutImpl(e){let t=`${this.lc}[${this.canPutImpl.name}]`;throw new Error(`${t} not implemented in base class`)}canDelete(e){return this.canPutImpl(e)}canDeleteImpl(e){let t=`${this.lc}[${this.canDeleteImpl.name}]`;throw new Error(`${t} not implemented in base class`)}getDependencyGraph(e){return this.getDependencyGraphImpl(e)}async getDependencyGraphImpl(e){let t=`${this.lc}[${this.getDependencyGraphImpl.name}]`;try{if(mo&&console.log(`${t} starting... (I: 0e5fe807a0169224781f6c2833f34826)`),!e.data)throw new Error("(UNEXPECTED) arg.data falsy? (E: 45eba816295a97a0e55f981861a03f26)");if((e.data.ibGibAddrs??[]).length===0)throw new Error("arg.data.ibGibAddrs is falsy/empty (E: 70adc939c7b80c9938d8fa18fd7c5826)");let r={space:this,ibGibAddrs:e.data.ibGibAddrs,live:e.data.live||!0},n=await it(r),a=Object.values(n),s={optsAddr:I({ibGib:e}),count:a.length,addrs:Object.keys(n)};return this.resulty({resultData:s,ibGibs:a})}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{mo&&console.log(`${t} complete.`)}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`,r=[];try{if(r=await super.validateWitnessArg(e),!e.data)return r.push("arg.data required (E: 8ee544d7d88a45c6adcbc15838a283a7)"),r;if(!this.data)return r.push("this.data required (E: 64f80642d7de44329355d6f907e272c8)"),r;let{cmd:n,ibGibAddrs:a}=e.data,s=e.data.cmdModifiers??[],i=e.ibGibs;n||r.push("arg.data.cmd required (E: 72a11ee87a0d4896bcacd65a9c0284d9)"),Object.values(Lt).includes(n)||r.push(`unknown arg.data.cmd: ${n}. (E: 95282ce61e97429f8049e61ec9f14f0b)`);let c=a?.length??0;if(n===Lt.get&&!s?.includes("addrs")&&!s?.includes("latest")&&c===0&&r.push(`ibGibAddrs required when cmd is ${n}. (E: ee55a3f60b90423cbe054f27c34ab7d5)`),n===Lt.put){mo&&console.log(`${t} validate put cmd`);let l=i?.length??0;if(l===0)r.push(`ibGibs required when cmd is ${n}. (E: b3a422169f7344a48a1d44e7ad1ba44e)`);else if(this.data.validateIbGibAddrsMatchIbGibs)if(mo&&console.log(`${t} validateIbGibAddrsMatchIbGibs true, so doing so.`),l!==c)r.push("ibGibsLength !== ibGibAddrsLength and this.data.validateIbGibAddrsMatchIbGibs is true. (E: 6c6bf824ab32443aa4d6b8bf4f8113dd)");else{mo&&console.log(`${t} validateIbGibAddrsMatchIbGibs, lengths match. validating intrinsically`);let d=a.concat();for(let f=0;f<i.length;f++){let b=i[f],p=await ne({ibGib:b});if(p?.length??!1){let u=I({ibGib:b});p.forEach(m=>r.push(`(${u}) ERROR: ${m}`))}else{let u=I({ibGib:b}),m=d.indexOf(u);if(m===-1){r.push(`ibGibAddrs don't map to calculated ibGib addrs. calculated Addr: (${u}) (E: b21b3a7a74db43e5a8722acc97274646)`);break}else d.splice(m,1)}}}}return r}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{r?.length>0&&console.error(`${t} errors: ${r}`)}}async argy({argData:e,ibMetadata:t,noTimestamp:r,ibGibs:n}){let a=await Zt({argData:e,ibMetadata:t,noTimestamp:r});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let r=await Qt({ibMetadata:pd({space:this}),resultData:e});return t&&(r.ibGibs=t),r}};var $t={undefined:"undefined",preparing:"preparing",started:"started",inserted:"inserted",updated:"updated",merged_dna:"merged_dna",merged_state:"merged_state",already_synced:"already_synced",completed:"completed"},kp={...ai},$0={...kp,sync:"sync"};var kf=" ";var jf=!1;function go({sagaId:o,statusCode:e,spaceType:t,spaceSubtype:r,delimiter:n}){let a=`[${go.name}]`;try{if(!o)throw new Error("sagaId required. (E: cfc923bb29ee4aa788e947b6416740e6)");if(e==null)throw new Error("status code required. (E: 4e0d232a9955496695012623c2e17ca2)");if(!Object.values($t).includes(e))throw new Error(`invalid status code (${e}) (E: 91d7655424c44d9680fff099ee2b54d2)`);if(!t)throw new Error("spaceType required. (E: 86e98694a56a4f599e98e50abf0eed43)");if(!r)throw new Error("spaceSubtype required. (E: 4857d4677ee34e95aeb2251dd633909e)");return n=n||kf,`status ${o} ${e} ${t} ${r}`}catch(s){throw console.error(`${a} ${E(s)}`),s}}h(go,"getStatusIb");function jp({participants:o}){let e=`[${jp.name}]`;try{jf&&console.log(`${e} starting... (I: 43c9a4f1fa1bbc944b98f8eed2f81924)`);let t=o.filter(r=>r.s_d==="src");if(t.length!==1)throw new Error("(UNEXPECTED) participants_src.length !== 1? atow (03/2024) only one src participant is expected. (E: ed4b3ae15f5da34c77655553aaf82224)");return t.at(0).id}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{jf&&console.log(`${e} complete.`)}}h(jp,"getSrcLocalSpaceId");var qf=!1;function Zi({base:o,extended:e,throwIfExtendedDoesntContainBase:t}){let r=`[${Zi.name}]`;try{qf&&console.log(`${r} starting... (I: 00d70d79a0249165c2a230389c962526)`);let n=!0;for(let s=0;s<o.length;s++)if(o[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: ${o}. extended: ${e}. (E: fb80b40003289bbf1aaedd4829fa1826)`);let a;if(n)a=e.slice(o.length);else{a=[];for(let s of e)o.includes(s)||a.push(s)}return a}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{qf&&console.log(`${r} complete.`)}}h(Zi,"getUniqueDnas");async function jr({src:o,createdIbGibs_Running:e,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:t,allLocalIbGibs:r}){let n=`[${jr.name}]`;try{if(t.length>0){let a=t.splice(0,1)[0],s=r.filter(d=>I({ibGib:d})===a),i;if(s.length>0)i=s[0];else throw new Error(`dna ibGib not found in supplied allLocalIbGibs. dnaAddr: ${a}. (E: 7f56826852cf48a79ab8af16bf27e284)`);let c=B(i.data);c.src=o,c.srcAddr=I({ibGib:o});let l;switch(c.type){case"mut8":l=await Ae(c);break;case"rel8":l=await ie(c);break;case"fork":throw new Error("fork transform not expected. atow only a single fork is expected at the beginning of the lifetime of a tjp ibgib. This fork defines the uniqueness of the tjp ibgib. When merging another tjp ibgib, we would only expect update transforms to be mut8 or rel8. (E: f8ad6996ac5545edad2d58a293d37d94)");default:throw new Error(`unknown dna argTransform.type (${c.type}) for dna address: ${a}. Expecting either mut8 or rel8. (fork transform is known but not expected either.) (E: 52a98db56e934e4cb42c64e2f45fa552)`)}if((l.intermediateIbGibs??[]).forEach(d=>e.push(d)),(l.dnas??[]).forEach(d=>e.push(d)),e.push(l.newIbGib),(l.dnas??[]).length>0){if(!l.dnas.some(d=>I(d)===a))throw new Error(`${n}(UNEXPECTED) Expected to generate exact dna that we applied in transform. dnaAddr: ${a} (E: 4a364c0b5d8d46c8af6bd540915fd973)`)}else console.warn(`${n}(UNEXPECTED) expected resTransform to include generated dna. dnaAddr: ${a}(W: 9648e2d5c40d42b7b9fb7efb09c5b13a)`);return await jr({src:l.newIbGib,createdIbGibs_Running:e,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:t,allLocalIbGibs:r})}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)`),o}catch(a){throw console.error(`${n} ${E(a)}`),a}}h(jr,"applyTransforms");var qr=!1,Fa=class extends Ma{static{h(this,"ReconciliationSpaceBase")}lc="[ReconciliationSpaceBase]";async spinOffToCompleteSync({srcSpaceId:e,sagaId:t,ibGibs:r,statusStartIbGibs:n,syncStatusIbGib_Start:a,syncStatus$:s,errors:i,warnings:c}){let l=`${this.lc}[${this.spinOffToCompleteSync.name}]`;i=i??[],c=c??[];let d=qr,f=`[sync_log][${t}][${r.length}]`;d&&console.time(f);try{d&&console.timeLog(f,`${l} starting...`);let b=a;b.statusIbGibGraph=n,await this.saveInStoreIfConfigAndPublishStatus({statusIbGib:b,syncStatus$:s}),d&&console.timeLog(f,"saveInStoreAndPublishStatus complete");let p=[],u={};d&&console.timeLog(f,"_getLatestAddrsInStore starting...");let m=await this._getLatestAddrsInStore(r);d&&console.timeLog(f,"_getLatestAddrsInStore complete");let{mapWithTjp_YesDna:g,mapWithTjp_NoDna:y,mapWithoutTjps:w}=nt({ibGibs:r}),A={...g,...y},G=Object.values(w),T={};G.forEach(O=>{T[I({ibGib:O})]=O});let $=Object.keys(T),S=G.filter(O=>!m[I({ibGib:O})]).map(O=>I({ibGib:O})),D=Object.values(A),C=Uo({items:D,keyFn:h(O=>ye({ibGib:O}),"keyFn")}),N=Object.keys(C);qr&&console.timeLog(f,`tjpAddrs.length: ${N.length}`);let x=[...N];S.length>0?x.push(S.at(0)):$.length>0&&x.push($.at(0)),qr&&console.timeLog(f,`tjpOrStoneAddrs.length: ${x.length}`);for(let O=0;O<x.length;O++){let M,F=x[O],k=K({ibGibAddr:F}).gib;d&&console.timeLog(f,`execInSpaceWithLocking tjpGib: ${k.slice(0,16)} starting...`),await pt({space:this,scope:k,secondsValid:60*5,maxDelayMs:1e3*60,callerInstanceId:t,maxLockAttempts:5,fn:h(async()=>{let Ee=`${l}[fn][${k.slice(0,5)}]`,pe=[],oe=[],re=[],fe={},W=m[F],Z=N.includes(F)?C[F].filter($e=>($e.data?.n??-1)>=0).sort(($e,tt)=>($e.data?.n??-1)>(tt.data?.n??-1)?1:-1):[];if(W)if(N.includes(F)){let $e=Z.map(Nt=>I({ibGib:Nt})),tt=$e[$e.length-1];if(W===tt)M=$t.already_synced;else if($e.includes(W))this.reconcile_UpdateStoreWithMoreRecentLocal({tjpAddr:F,latestAddr_Store:W,tjpGroupAddrs_Local_Ascending:$e,tjpGroupIbGibs_Local_Ascending:Z,ibGibsToStore:pe,updates:u}),M=$t.updated;else{let Nt=Z.find(kt=>I({ibGib:kt})===tt),eo=(Nt.rel8ns?.dna??[]).length>0,Oo=(await this._getIbGibsFromStore([W]))[W];if(!Oo)throw new Error(`(UNEXPECTED) latestAddr_Store not found in store: ${W}`);let Ps=(Oo.rel8ns?.dna??[]).length>0;eo&&Ps?(await this.reconcile_MergeLocalWithStore_ViaDna({tjpAddr:F,latestAddr_Local:tt,latestIbGib_Local:Nt,latestAddr_Store:W,latestIbGib_Store:Oo,ibGibsCreated:oe,ibGibMergeMap:fe,ibGibsOnlyInStore:re,allLocalIbGibs:r,updates:u,timeLogName:f}),oe.forEach(kt=>pe.push(kt)),M=$t.merged_dna):(await this.reconcile_MergeLocalWithStore_ViaState({tjpAddr:F,latestIbGib_Local:Nt,latestAddr_Local:tt,latestAddr_Store:W,ibGibsCreated:oe,ibGibMergeMap:fe,updates:u}),oe.forEach(kt=>pe.push(kt)),M=$t.merged_state)}}else M=$t.already_synced;else N.includes(F)?this.reconcile_InsertFirstTimeIntoStore({tjpGroupIbGibs_Local_Ascending:Z,ibGibsToStore:pe}):S.forEach($e=>{pe.push(T[$e])}),M=$t.inserted;let se=Object.values(m);for(let $e=0;$e<pe.length;$e++){let tt=pe[$e],Nt=I({ibGib:tt});!se.includes(Nt)&&!p.some(eo=>I({ibGib:eo})===Nt)&&p.push(tt)}p.length>0&&await this._putIbGibsToStore(p);let Y=p.length>0?p.map($e=>I({ibGib:$e})):void 0,j=oe.length>0?oe.map($e=>I({ibGib:$e})):void 0,we=re.length>0?re.map($e=>I({ibGib:$e})):void 0,ke={};for(let[$e,tt]of Object.entries(fe))ke[$e]=I({ibGib:tt});let Ct=await Ae({src:b,mut8Ib:go({spaceType:"sync",spaceSubtype:"aws-dynamodb",statusCode:M,sagaId:t}),dataToAddOrPatch:{statusCode:M,success:!0,errors:(i??[]).length>0?i.concat():void 0,warnings:(c??[]).length>0?c.concat():void 0,didRx:Y?.concat(),didTx:we?.concat(),didCreate:j?.concat(),didMergeMap:ke},dna:!1});b=Ct.newIbGib,b.statusIbGibGraph=Ct.intermediateIbGibs?[b,...Ct.intermediateIbGibs]:[b],oe.length>0&&(b.createdIbGibs=oe.concat()),re.length>0&&(b.storeOnlyIbGibs=re.concat()),Object.keys(fe).length>0&&(b.ibGibsMergeMap=fe),await this.saveInStoreIfConfigAndPublishStatus({statusIbGib:b,syncStatus$:s})},"fn")}),d&&console.timeLog(f,`execInSpaceWithLocking tjpGib: ${k.slice(0,16)} complete.`)}d&&console.timeLog(f,"complete saga cleanup starting...");let L=$t.completed,U=await Ae({src:b,mut8Ib:go({spaceType:"sync",spaceSubtype:this.data.subtype,statusCode:L,sagaId:t}),dataToAddOrPatch:{statusCode:L,success:!0,errors:(i??[]).length>0?i.concat():void 0,warnings:(c??[]).length>0?c.concat():void 0},dna:!1});b=U.newIbGib,b.statusIbGibGraph=U.intermediateIbGibs?[b,...U.intermediateIbGibs]:[b],await this.saveInStoreIfConfigAndPublishStatus({statusIbGib:b,syncStatus$:s}),d&&console.timeLog(f,"complete saga cleanup complete."),s.complete&&!s.isCompleteOrErrored?(f&&(d&&console.timeEnd(f),f=""),await s.complete()):console.warn("(UNEXPECTED) !syncStatus$.complete? this complete handler is expected to be truthy (W: e706de7fa3289194e59bee9ecf96c224)")}catch(b){let p=`${l} ${E(b)}`;if(d&&console.timeLog(f,`errored. emsg: ${p}`),console.error(p),!s.isCompleteOrErrored){if(!s.error)throw new Error("(UNEXPECTED) !syncStatus$.error? (E: a26bfba7663301986c633c3c2c764824)");f&&(d&&console.timeEnd(f),f=""),await s.error(p)}}}async saveInStoreIfConfigAndPublishStatus({statusIbGib:e,syncStatus$:t}){let r=`${this.lc}[${this.saveInStoreIfConfigAndPublishStatus.name}]`;try{if(this.data?.dontStoreStatusUpdatesInSyncSpace)qr&&console.log(`${r} configured to NOT store status updates in this space. (I: 0166928761a34375b367b61f9d45398d)`);else{if((e.statusIbGibGraph??[]).length===0)throw new Error("statusIbGib.statusIbGibGraph required. (E: 2a11a84f501243799b66a5b28b76b88b)");await this._putIbGibsToStore(e.statusIbGibGraph)}t.next&&!t.isCompleteOrErrored?await t.next(e):console.warn(`${r} (UNEXPECTED) syncStatus$ subject either does not have a next handler or is already completed/errored. (W: 489a580a563b4f6990264177d6118d53)`)}catch(n){let a=`${r} ${E(n)}`;throw console.error(a),n}}reconcile_UpdateStoreWithMoreRecentLocal({tjpAddr:e,latestAddr_Store:t,tjpGroupAddrs_Local_Ascending:r,tjpGroupIbGibs_Local_Ascending:n,ibGibsToStore:a,updates:s}){let i=`${this.lc}[${this.reconcile_UpdateStoreWithMoreRecentLocal.name}]`;try{let c=r.indexOf(t);if(c===-1)throw new Error(`(UNEXPECTED) latestAddr_Store not found in local ibGibs. latestAddr_Store: ${t} (E: 8820c754d5d94ab4971d87af48a4369e)`);if(c===r.length-1){console.warn(`${i} (UNEXPECTED) lastSyncPoint_Local_Idx is latest local ibgib index. This means we are already synced, but somehow thought we weren't. (W: 4927cf51c76a4e2e8509c25f46a9a0f7)`);return}let l=n.slice(c+1);l.forEach(d=>a.push(d)),s[e]=I({ibGib:l[l.length-1]})}catch(c){let l=`${i} ${E(c)}`;throw console.error(l),c}}async getDna(e){let t=`${this.lc}[${this.getDna.name}]`,{ibGib:r,throwOnDnaFail:n=!0}=e;try{let a=r.rel8ns?.dna??[];if(a.length===0)return[];let s=await this._getIbGibsFromStore(a),i=a.map(c=>s[c]).filter(c=>!!c);if(i.length!==a.length){let c=`Mismatch in DNA. Requested ${a.length} addrs but only found ${i.length}. This may indicate a partial save or data loss. (E: 1ce346ba0fc88b71c6a399282d481825)`;if(n)throw new Error(c);console.warn(`${t} ${c}`)}return i}catch(a){let s=`${t} ${E(a)}`;throw console.error(s),a}}async reconcile_MergeLocalWithStore_ViaDna({tjpAddr:e,latestAddr_Local:t,latestIbGib_Local:r,latestAddr_Store:n,latestIbGib_Store:a,ibGibsCreated:s,ibGibMergeMap:i,ibGibsOnlyInStore:c,allLocalIbGibs:l,updates:d,timeLogName:f}){let b=`${this.lc}[${this.reconcile_MergeLocalWithStore_ViaDna.name}]`,p=qr;try{p&&console.timeLog(f,"getting full dna timeline for local and store...");let m=(await this.getDna({ibGib:r})).map(_=>I({ibGib:_})),y=(await this.getDna({ibGib:a})).map(_=>I({ibGib:_}));p&&console.timeLog(f,"getting full dna timeline for local and store...complete");let w;if(m.length<y.length)for(let _=m.length-1;_>=0;_--){let S=m[_];if(y.includes(S)){w=S;break}}else for(let _=y.length-1;_>=0;_--){let S=y[_];if(m.includes(S)){w=S;break}}if(!w)throw new Error(`Could not find common ancestor between local and store timelines. Local: ${t}, Store: ${n}. This timeline requires manual reconciliation. (E: 49219b101a9f4568bd740d046e30ea2d)`);let A=m.indexOf(w),G=y.indexOf(w),T=m.slice(A+1),$=y.slice(G+1);if($.length>0){p&&console.timeLog(f,`getting ${$.length} ibgibs from store that do not exist locally...`);let _=await this._getIbGibsFromStore($);Object.values(_).forEach(S=>c.push(S)),p&&console.timeLog(f,`getting ${$.length} ibgibs from store that do not exist locally...complete`)}if(T.length>0){p&&console.timeLog(f,`applying ${T.length} transforms from local that do not exist in store...`);let _=[],D=await jr({src:a,createdIbGibs_Running:_,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:T,allLocalIbGibs:l});p&&console.timeLog(f,`applying ${T.length} transforms from local that do not exist in store...complete`),p&&console.timeLog(f,`applying ${$.length} transforms from store that do not exist locally...`);let N=await jr({src:D,createdIbGibs_Running:_,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:$,allLocalIbGibs:c});p&&console.timeLog(f,`applying ${$.length} transforms from store that do not exist locally...complete`),_.forEach(L=>{let U=I({ibGib:L});s.some(O=>I({ibGib:O})===U)||s.push(L)});let x=I({ibGib:N});s.some(L=>I({ibGib:L})===x)||s.push(N),i[t]=N,i[n]=N,d[e]=x}}catch(u){let m=`${b} ${E(u)}`;throw console.error(m),u}}async reconcile_MergeLocalWithStore_ViaState({tjpAddr:e,latestIbGib_Local:t,latestAddr_Local:r,latestAddr_Store:n,ibGibsCreated:a,ibGibMergeMap:s,updates:i}){let c=`${this.lc}[${this.reconcile_MergeLocalWithStore_ViaState.name}]`;try{let l=await Ae({src:t,dataToAddOrPatch:{...t.data},noTimestamp:!0}),d=l.newIbGib,f=I({ibGib:d});l.intermediateIbGibs&&l.intermediateIbGibs.forEach(b=>a.push(b)),a.push(d),s[r]=d,s[n]=d,i[e]=f}catch(l){let d=`${c} ${E(l)}`;throw console.error(d),l}}async reconcile_InsertFirstTimeIntoStore({tjpGroupIbGibs_Local_Ascending:e,ibGibsToStore:t}){let r=`${this.lc}[${this.reconcile_InsertFirstTimeIntoStore.name}]`;try{e.forEach(n=>t.push(n))}catch(n){let a=`${r} ${E(n)}`;throw console.error(a),n}}async routeAndDoCommand({cmd:e,cmdModifiers:t,arg:r}){let n=`${this.lc}[${this.routeAndDoCommand.name}]`;if((t??[]).length===0||!t.includes("sync"))return super.routeAndDoCommand({cmd:e,cmdModifiers:t,arg:r});switch(e){case Lt.put:return t.includes("sync")?(qr&&console.log(`${n} cmd is put and modifier includes sync. Routing to putSync function. (I: 2dc358c88a1746329b379d4e8ba7e09e)`),await this.putSync(r)):super.routeAndDoCommand({cmd:e,cmdModifiers:t,arg:r});default:return super.routeAndDoCommand({cmd:e,cmdModifiers:t,arg:r})}}async putSync(e){let t=`${this.lc}[${this.putSync.name}]`,r={optsAddr:I({ibGib:e})},n=[],a=[],s=e?.syncSagaInfo,i=qr;try{if(!e.data)throw new Error("arg.data required. (E: 847a1506e7054d53b7bf5ff87a4b32da)");if((e.data.ibGibAddrs??[]).length===0)throw new Error("arg.data.ibGibAddrs required. (E: 6f2062572cc247f6a12b34759418c66b)");if(la({ibGibAddrs:e.data.ibGibAddrs}),!e.data.sagaId)throw new Error("sagaId required. (E: af30b1b3cf3a4676a89399514743da79)");let c=`[sync_log][${e.data.sagaId}]`;if(i&&console.timeLog(c,`${t} starting...`),(e.ibGibs??[]).length===0)throw new Error("no ibgibs given. (E: 62ae74eab0434b90b866caa285403143)");if(la({ibGibs:e.ibGibs}),!e.syncSagaInfo)throw new Error("arg.syncSagaInfo required. (E: 33efb28789ff40b9b340eedcba0017f7)");if(!e.syncSagaInfo.spaceId)throw new Error("arg.syncSagaInfo.spaceId required. (E: b20f6dbf3c4a466c9ff5aa7488e903ee)");if((e.data.participants??[]).length===0)throw new Error("arg.data.participants required. (E: 3e8121dc078342d18810a3e2c9671f98)");if(e.data.participants.filter(b=>b.s_d==="src").length===0)throw new Error("invalid participants. src required. (E: fbfcab1b8cf34d4a8d51a48a0a43e6af)");if(e.data.participants.filter(b=>b.s_d==="src").length>1)throw new Error("invalid participants. only 1 src allowed. (E: 9c2d76ab4dc141ce878de2649a68d4b6)");if(e.data.participants.filter(b=>b.s_d==="dest").length===0)throw new Error("invalid participants. at least 1 dest required. (E: 7d037be500844191b25655521eb4cde7)");let l=e.data.participants.filter(b=>b.s_d==="src")[0].id;if(!l)throw new Error("invalid participants. srcSpaceId required. (E: c55c96ebb1c9429fabb0e90adf5ce157)");if(!this.data)throw new Error("(UNEXPECTED) !this.data? (E: 77163b8ffc7f439a8ba8b410db0071e7)");let{statusIbGib:d,statusIbGibsGraph:f}=await this.getStatusIbGibs_Start({sagaId:e.data.sagaId,participants:e.data.participants,ibGibAddrs:e.data.ibGibAddrs});if(r.sagaId=e.data.sagaId,!d.rel8ns?.tjp?.at(0))throw new Error("(UNEXPECTED) !syncStatusIbGib_Start.rel8ns?.tjp?.at(0)? (E: 7ab2b8efb18a446d8695a01cada13c24)");r.statusTjpAddr=d.rel8ns.tjp[0],this.spinOffToCompleteSync({srcSpaceId:l,sagaId:e.data.sagaId,ibGibs:e.ibGibs.concat(),statusStartIbGibs:f,syncStatusIbGib_Start:d,syncStatus$:s.syncStatus$,errors:n,warnings:a})}catch(c){console.error(`${t} error: ${E(c)}`),r.errors=[E(c)]}try{let c=await this.resulty({resultData:r});return c.syncSagaInfo=s,c}catch(c){throw console.error(`${t} ${E(c)}`),c}}async getStatusIbGibs_Start({sagaId:e,participants:t,ibGibAddrs:r}){let n=`${this.lc}[${this.getStatusIbGibs_Start.name}]`;try{if((t??[]).length===0)throw new Error("participants required. (E: a707efcdd7594a4aa70599e84ffa43c4)");let a=go({spaceType:"sync",spaceSubtype:"aws-dynamodb",statusCode:$t.undefined,sagaId:wl}),s=H.primitive({ib:a}),i=$t.started,c=go({statusCode:i,spaceType:"sync",spaceSubtype:"aws-dynamodb",sagaId:e}),l={statusCode:i,participants:t,toTx:r},d=await H.firstGen({parentIbGib:s,ib:c,data:l,dna:!1,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),f=d.newIbGib,b=[f,...d.intermediateIbGibs??[]];return{statusIbGib:f,statusIbGibsGraph:b}}catch(a){let s=`${n} ${E(a)}`;throw console.error(s),a}}};var Xf="This is an in-memory innerspace.";var Hf={version:"1",uuid:Fn,name:Bn,classname:"InnerSpace_V1",persistOptsAndResultIbGibs:!1,validateIbGibAddrsMatchIbGibs:!1,longPollingIntervalMs:kn,allowPrimitiveArgs:!1,catchAllErrors:!0,description:Xf,trace:!1};var Oe=!1,hn=class o extends Fa{static{h(this,"InnerSpace_V1")}lc=`[${o.name}]`;ibGibs={};ibGibMetastones={};get metastoneAddrs(){let e=[];return Object.values(this.ibGibMetastones).forEach(t=>{Object.keys(t).forEach(r=>e.push(r))}),e}get metastoneIbGibs(){let e=[];return Object.values(this.ibGibMetastones).forEach(t=>{Object.values(t).forEach(r=>e.push(r))}),e}constructor(e,t){super(e,t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{Oe&&console.log(`${e} starting...`),this.data||(this.data=B(Hf),this.data=this.data),this.data.classname!==o.name&&(this.data.classname&&console.warn(`${e} this.data.classname (${this.data.classname}) !== ${o.name}. overriding this. (W: 4cac18140e58f0bd2890010a3639d225)`),this.data.classname=o.name),this.data.uuid??=await q(),this.ib=Ei({space:this,classname:this.data.classname}),this.gib=await ee({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Oe&&console.log(`${e} complete.`)}}async _getLatestAddrsInStore(e){let t=`${this.lc}[_getLatestAddrsInStore]`;try{Oe&&console.log(`${t} starting...`);let n={data:{ibGibAddrs:e.map(s=>I({ibGib:s}))}};return(await this.getLatestAddrsImpl(n)).data.latestAddrsMap}catch(r){throw console.error(`${t} ${E(r)}`),r}}async _getIbGibsFromStore(e){let t=`${this.lc}[_getIbGibsFromStore]`;try{Oe&&console.log(`${t} starting...`);let r={};for(let n of e)this.ibGibs[n]&&(r[n]=this.ibGibs[n]);return r}catch(r){throw console.error(`${t} ${E(r)}`),r}}async _putIbGibsToStore(e){let t=`${this.lc}[_putIbGibsToStore]`;try{Oe&&console.log(`${t} starting...`),await this.putIbGibsImpl({ibGibs:e,addrsAlreadyHave:[]})}catch(r){throw console.error(`${t} ${E(r)}`),r}}async _deleteIbGibsFromStore(e){let t=`${this.lc}[_deleteIbGibsFromStore]`;try{Oe&&console.log(`${t} starting...`);for(let r of e)delete this.ibGibs[r]}catch(r){throw console.error(`${t} ${E(r)}`),r}}async getImpl(e){let t=`${this.lc}[${this.getImpl.name}]`,r={optsAddr:I({ibGib:e})},n=[];try{Oe&&console.log(`${t} starting... (I: 2a2dd19a00f1f892e3b6d1372ab72c23)`);let{ibGibAddrs:s}=e.data;if(!s)throw new Error("(UNEXPECTED) arg.data.ibGibAddrs falsy? (E: 33dcc212788221c601bf2258eb1cd523)");let i;for(let c=0;c<s.length;c++){let l=s[c];Object.keys(this.ibGibs).includes(l)?n.push(this.ibGibs[l]):(i||(i=[]),i.push(l))}i&&i.length>0?(r.addrsNotFound=i,r.success=!1):r.success=!0}catch(s){console.error(`${t} error: ${s.message}`),r.errors=[s.message]}finally{Oe&&console.log(`${t} complete. (I: 2c3aeda2fcd6338b9ab89261b9237a23)`)}return await this.resulty({resultData:r,ibGibs:n})}async putImpl(e){let t=`${this.lc}[${this.putImpl.name}]`,r={optsAddr:I({ibGib:e})};try{let a=e.ibGibs||[],s=[];await this.putIbGibsImpl({ibGibs:a,addrsAlreadyHave:s}),s.length>0&&(r.addrsAlreadyHave=s,r.warnings=(r.warnings||[]).concat([`${t} space (${this.ib}) already had addr(s): ${s.join("|")}`,"(W: 7120c8267c2aaf8cad5d2f3850666826)"])),r.success=!0}catch(a){console.error(`${t} error: ${a.message}`),r.errors=[a.message],r.success=!1}return await this.resulty({resultData:r})}async putIbGibsImpl({ibGibs:e,addrsAlreadyHave:t}){let r=`${this.lc}[${this.putIbGibsImpl.name}]`;try{if(Oe&&console.log(`${r} starting...`),!e)throw new Error("ibGibs required. (E: cd479b15097d45a5bf0c8ca13c9f3487)");if(!t)throw new Error("addrsAlreadyHave required. (E: 18b2c8eef27bc267c55755e272367e22)");for(let n=0;n<e?.length;n++){let a=e[n],s=I({ibGib:a});if(fi({ibGib:a})){let i=a;if(!i.data)throw new Error("(UNEXPECTED) ibGib is a metastone, but metastone.data falsy? (E: f3a05815c68821d564cb101821b91326)");let{tjpGib:c}=i.data.targetData;this.ibGibMetastones[c]?Object.keys(this.ibGibMetastones[c]).includes(s)?t.push(s):this.ibGibMetastones[c][s]=i:this.ibGibMetastones[c]={[s]:i}}else Object.keys(this.ibGibs).includes(s)?t.push(s):this.ibGibs[s]=a}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{Oe&&console.log(`${r} complete.`)}}async deleteImpl(e){let t=`${this.lc}[${this.deleteImpl.name}]`,r={optsAddr:I({ibGib:e})};try{let n=[],a=[],s=e.data.ibGibAddrs||[];for(let i=0;i<s.length;i++){let c=s[i];Object.keys(this.ibGibs).includes(c)?(delete this.ibGibs[c],a.push(c)):n.push(c)}if(n.length>0){r.addrsNotFound=n.concat();let i=`${t} some addrs (${n.length}) not found: ${n}`;r.warnings=(r.warnings||[]).concat([i])}r.success=!0,r.addrs=a.concat()}catch(n){console.error(`${t} error: ${n.message}`),r.errors=[n.message],r.success=!1}try{return await this.resulty({resultData:r})}catch(n){throw console.error(`${t} error forming result ibGib. error: ${n.message}`),n}}async getAddrsImpl(e){let t=`${this.lc}[${this.getAddrs.name}]`,r={optsAddr:I({ibGib:e})};try{r.addrs=Object.keys(this.ibGibs).concat(),r.success=!0}catch(a){console.error(`${t} error: ${a.message}`),r.errors=[a.message],r.success=!1}return await this.resulty({resultData:r})}async getLatestAddrsImpl(e){let t=`${this.lc}[${this.getLatestAddrsImpl.name}]`;Oe&&console.log(`${t} starting... (I: 913548fe045270432ea96f2a59ca6625)`);let r={optsAddr:I({ibGib:e})};try{if(!e.data)throw new Error("(UNEXPECTED) !arg.data? (E: 60869288f3deeff5d1dd93be5f4b8624)");if(!e.data.ibGibAddrs)throw new Error("(UNEXPECTED) !arg.data.ibGibAddrs? (E: d62cfac462daacc5b2f50c7c3ae45d24)");let n={};for(let a of e.data.ibGibAddrs){if(fi({addr:a})){Oe&&console.log(`${t} localAddr not found: ${a} (I: 12c7668bbdb8e4a86ceb5f455eb00826)`),this.metastoneAddrs.includes(a)?n[a]=a:(Oe&&console.log(`${t} metastone addr NOT found...what are we getting latest on metastone anyway? (I: 0e71b8a9234fcc93b8259578eb491626)`),n[a]=null);continue}let s=this.ibGibs[a];if(!s){Oe&&console.log(`${t} localAddr not found: ${a} (I: 12c7668bbdb8e4a86ceb5f455eb00826)`),n[a]=null;continue}let i=ye({ibGib:s,defaultIfNone:"incomingAddr"})??I({ibGib:s}),{gib:c}=K({ibGibAddr:i}),l=this.ibGibMetastones[c];if(!l){n[a]=a;continue}let d=Object.keys(l);if(d.length===0)throw new Error("(UNEXPECTED) we have a metastoneMap but no addrs? (E: 82a448407c08585f685a9b2543923826)");let b=d.map(w=>[w,K({ibGibAddr:w}).ib]).map(([w,A])=>[w,oa({ib:A})]).sort((w,A)=>{let[G,T]=w,[$,_]=A;return T.n>_.n?-1:T.n<_.n?1:T.timestampInTicks>_.timestampInTicks?-1:T.timestampInTicks<_.timestampInTicks?1:0});if(Oe&&(console.log(`${t} console.dir(metaStoneAddrsAndIbInfos_descending)... (I: 5ce425f199283e2185a2cc0801264826)`),console.dir(b)),b.length===0)throw new Error("(UNEXPECTED) metaStoneAddrsAndIbInfos_descending is empty? earlier in the function there should have been a check. did getMetaStoneAddrs return a populated list but no stones were found? (E: 63c035ebed77741f2330c7a625823f23)");let[p,u]=b[0];Oe&&console.log(`${t} [latestMetaStoneAddr, latestMetaStoneInfo]: ${[p,u]} (I: 1307ca46b4abd62c7a30fe87c08fa923)`);let m;m=l[p];let y=m.rel8ns[Pr].at(0);if(!y)throw new Error("metastone passed validation but latestMetaStoneRel8ns[META_STONE_TARGET_REL8N_NAME].at(0) is empty? (E: c188ec0089ad86efe4d925c118599d23)");n[a]=y}r.latestAddrsMap=n,r.success=!0}catch(n){let a=`${t} ${E(n)}`;console.error(a),r.errors=[a]}try{return await this.resulty({resultData:r})}catch(n){throw console.error(`${t}[resulty] ${E(n)}`),n}finally{Oe&&console.log(`${t} complete. (I: 913548fe045270432ea96f2a59ca6625)`)}}async canGetImpl(e){let t=`${this.lc}[${this.canGetImpl.name}]`,r={optsAddr:I({ibGib:e})};try{let{ibGibAddrs:a}=e.data;if(!a)throw new Error("(UNEXPECTED) arg.data.ibGibAddrs falsy? (E: d94c64744037ca443589fca71e121123)");let s;for(let i=0;i<a.length;i++){let c=a[i];Object.keys(this.ibGibs).includes(c)||(s||(s=[]),s.push(c))}r.success=!0,s&&s.length>0?(r.addrsNotFound=s,r.can=!1):r.can=!0}catch(a){console.error(`${t} error: ${a.message}`),r.errors=[a.message]}return await this.resulty({resultData:r})}async canPutImpl(e){let t=`${this.lc}[${this.canPutImpl.name}]`,r={optsAddr:I({ibGib:e})};try{let a=e.ibGibs||[],s=[];for(let i=0;i<a?.length;i++){let c=a[i],l=I({ibGib:c});Object.keys(this.ibGibs).includes(l)&&s.push(l)}r.success=!0,s.length>0&&(r.addrsAlreadyHave=s,r.warnings=(r.warnings||[]).concat([`${t} already have addr(s).`])),r.can=a.length>s.length}catch(a){console.error(`${t} error: ${a.message}`),r.errors=[a.message]}return await this.resulty({resultData:r})}async canDeleteImpl(e){let t=`${this.lc}[${this.canDeleteImpl.name}]`,r={optsAddr:I({ibGib:e})};try{throw new Error("not implemented")}catch(n){console.error(`${t} error: ${n.message}`),r.errors=[n.message],r.success=!1}try{return await this.resulty({resultData:r})}catch(n){throw console.error(`${t} error forming result ibGib. error: ${n.message}`),n}}async persistOptsAndResultIbGibs({arg:e,result:t}){let r=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;try{(Oe||this.data?.trace)&&console.log(`${r} starting...`),(Oe||this.data?.trace)&&console.log(`${r} doing arg?.data?.cmd: ${e?.data?.cmd}, result?.data?.success: ${t?.data?.success}`);let n=await ne({ibGib:e});if(n&&n.length>0)throw new Error("invalid arg. cannot persist. (E: 015d38de71a3407f9d77fc4ed3404bf0)");let a=t?await ne({ibGib:t}):null;if(a&&a.length>0)throw new Error("invalid arg. cannot persist. (E: 015d38de71a3407f9d77fc4ed3404bf0)");let s=t?[e,t]:[e];await this.putIbGibsImpl({ibGibs:s,addrsAlreadyHave:[]})}catch(n){console.error(`${r} ${n.message}`)}finally{(Oe||this.data?.trace)&&console.log(`${r} complete.`)}}};var Qi={};function qe(o){if(!o)throw new Error("ib required. (E: 7c28c8e1a8a24345bb344155b4131422)");let e=o.split(" ");if(e.length<5)throw new Error(`invalid space ib format: ${o} (E: 14a84497e59648949822067786481223)`);return e[4]}h(qe,"getSpaceIdFromIb");var Vf=h(o=>{let e=qe(o.ib);Qi[e]=o},"registerInnerSpace"),T1=h(o=>{delete Qi[o]},"unregisterInnerSpace");var qp=h(async({allowCancel:o,spaceName:e,getFnPrompt:t,logalot:r})=>{let n=`[${qp.name}]`;try{if(r&&console.log(`${n} starting... (I: a9bc8c7d54cb4bafae4c4aa515d71580)`),e&&!fa(e))throw new Error(`spaceName (${e}) is invalid. (E: 7769ee9ed9874ff28548214efc3639c2)`);e||await h(async()=>{let l=await t()({title:"greetings program",msg:`all of your data is stored locally on your device's "local space".
|
|
26
|
+
|
|
27
|
+
so name your space with alphanumerics & underscores, like 'phone_alice' or 'web_bob_foo', or leave blank and get a random name.
|
|
28
|
+
|
|
29
|
+
Enter space name:
|
|
30
|
+
`});l===""&&!o?e="space_"+(await q()).slice(0,10):l&&fa(l)&&(e=l)},"promptName")();let a={version:"1",name:e||"in-memory-space_"+(await q()).slice(0,10),uuid:await q(),description:"ephemeral in-memory space",persistOptsAndResultIbGibs:!1,validateIbGibAddrsMatchIbGibs:!0,trace:!1,allowPrimitiveArgs:!1,catchAllErrors:!0,longPollingIntervalMs:kn},s=new hn(a,void 0);if(r&&console.log(`${n} localSpace.ib: ${s.ib}`),r&&console.log(`${n} localSpace.gib: ${s.gib} (before sha256v1)`),r&&console.log(`${n} localSpace.data: ${X(s.data||"falsy")}`),r&&console.log(`${n} localSpace.rel8ns: ${X(s.rel8ns||"falsy")}`),s.gib=await ee({ibGib:s,hasTjp:!1}),s.gib===Q)throw new Error("localSpace.gib not updated correctly.");return r&&console.log(`${n} localSpace.gib: ${s.gib} (after sha256v1)`),Vf(s),s}catch(a){throw console.error(`${n} ${a.message}`),a}finally{r&&console.log(`${n} complete.`)}},"fnCreateNewLocalSpace"),G1=h(async o=>{let e="[fnDtoToSpace]";try{if(o.ibGibs)return o;{if(!o.data)throw new Error("invalid spaceDto. InnerSpace_V1 should have truthy data. (E: d402fda7a6a53668b655c2885029a423)");let t=qe(o.ib),r=Qi[t];if(r)return r;{console.warn(`${e} in memory innerspace dto that isnt' the reference to the object itself in memory, and we don't have it in the inner spaces map? i guess we'll create a new one from the dto (W: b8973f3a43f546eeaf59f60331896e75)`);let n=new hn(o.data,o.rel8ns);return await n.initialized,Vf(n),n}}}catch(t){throw console.error(`${e} ${E(t)}`),t}},"fnDtoToSpace");var Eo="[branch-helper]",Qe=!1,Xp=/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/;function Wf(o){if(!o||!o.trim())return{isValid:!1,error:"Branch name cannot be empty."};let e=o.trim();return e.length>64?{isValid:!1,error:"Branch name cannot exceed 64 characters."}:e.includes("~")?{isValid:!1,error:"Branch name cannot contain tildes (~)."}:e.includes("..")?{isValid:!1,error:"Branch name cannot contain consecutive dots (..)."}:e.includes(" ")?{isValid:!1,error:"Branch name cannot contain spaces."}:Xp.test(e)?{isValid:!0}:{isValid:!1,error:"Branch name can only contain letters, numbers, hyphens (-), underscores (_), and dots (.), and must start and end with a letter or number."}}h(Wf,"validateBranchName");function Hp(o,e){if(e)return`b2s${Ki}${e}${Ki}${o}`;let t=o.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${Mf}${t}`}h(Hp,"getB2tFSBranchSpaceName");function Vp({branchName:o,uuid:e}){if(!o)throw new Error("branchName falsy (E: 61f048e02ea84a2276b3cd6d731fa826)");if(!e)throw new Error("uuid falsy (E: 3e54a910bb1815433822c78a9c48b826)");if(!Ie.test(e))throw new Error(`uuid (${e}) does not match UUID_REGEXP (${Ie.source}) (E: 64794844e948435c38f58a8891b6e126)`);return`${Ra} ${o} v1 ${e}`}h(Vp,"getBranchIb");function pn({ib:o}){let e=`[${pn.name}]`;try{Qe&&console.log(`${e} starting... (I: cbd009f57961884dd3024c18f7b01926)`);let[t,r,n,a]=o.split(" ");if(!t)throw new Error("atom falsy (E: 68fb989be1ebaeb6220570618ee53826)");if(t!==Ra)throw new Error(`atom !== ${Ra} (b2tfs branch atom) (E: 389d481f8ca86472f81eaa61c55fdc26)`);if(!r)throw new Error("branchName falsy (E: d698cb6dc8b8b307485305e1527f5826)");if(!n)throw new Error("version falsy (E: 37ccf82d9718c38678c3f271e675c826)");if(n!=="v1")throw new Error(`version (${n}) !== 'v1' (E: 1122d86884d8231dcb7fddd889c9e626)`);if(!a)throw new Error("uuid falsy (E: 9edca4d919a8d44188d002b807aab826)");if(!Ie.test(a))throw new Error(`uuid (${a}) does not match UUID_REGEXP (${Ie.source}) (E: b60587540c5ddf17482eb47804909426)`);return{atom:t,branchName:r,version:n,uuid:a}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Qe&&console.log(`${e} complete.`)}}h(pn,"parseBranchIb");async function Xr(o){let e=`${Eo}[${Xr.name}]`,{branchName:t,rootItem:r,space:n,metaspace:a,parentBranchSqAddr:s,parentBranchName:i,scopedItemPath:c}=o;if(!t||!r)throw new Error("branchName and rootItem required (E: c67bb2a61e6d4270d8056f0afb01d426)");let l=await q(),d=I({ibGib:r}),f={name:t,uuid:l,classname:"B2tFSBranchIbGib_V1",...s?{parentBranchSqAddr:s}:{},...i?{parentBranchName:i}:{},...c?{scopedItemPath:c}:{},"$@branch":[]},b={b2tfs_item:[d]},p=await H.firstGen({parentIbGib:ue,ib:Vp({branchName:t,uuid:l}),data:f,rel8ns:b,tjp:{timestamp:!0},dna:!0,nCounter:!0}),u=p.newIbGib;return await V({resTransform:p,space:n}),await J({ibGib:u,space:n}),Qe&&console.log(`${e} Created branch IbGib: ${u.ib}`),u}h(Xr,"createB2tFSBranchIbGib");async function ec(o){let e=`${Eo}[${ec.name}]`,{existingBranch:t,rootItem:r,space:n,metaspace:a}=o,s=I({ibGib:r}),i=await ie({src:t,rel8nsToAddByAddr:{b2tfs_item:[s]},dna:!0,nCounter:!0}),c=i.newIbGib;return await a.persistTransformResult({resTransform:i,space:n}),await a.registerNewIbGib({ibGib:c,space:n}),Qe&&console.log(`${e} Evolved branch IbGib: ${c.ib}`),c}h(ec,"evolveB2tFSBranchIbGib");async function tc({parentBranchIbGib:o,childBranchSqAddr:e,space:t,metaspace:r}){let n=`${Eo}[${tc.name}]`;try{if(!o)throw new Error("parentBranchIbGib required (E: a1b2c3d4e5f64718890123456789abcd)");if(!e)throw new Error("childBranchSqAddr required (E: b2c3d4e5f6a14718890123456789abcd)");if(!t)throw new Error("space required (E: c3d4e5f6a1b24718890123456789abcd)");if(!r)throw new Error("metaspace required (E: d4e5f6a1b2c34718890123456789abcd)");let a=o.data["$@branch"]||[];if(a.includes(e))return Qe&&console.warn(`${n} childBranchSqAddr already registered on parent: ${e}`),o;let s=[...a,e],i=await Ae({src:o,dataToRemove:o.data["$@branch"]?{"$@branch":""}:void 0,dataToAddOrPatch:{"$@branch":s},dna:!0,nCounter:!0}),c=i.newIbGib;return await r.persistTransformResult({resTransform:i,space:t}),await r.registerNewIbGib({ibGib:c,space:t}),Qe&&console.log(`${n} Registered sub-branch ${e} on parent ${o.data.name} (newAddr: ${I({ibGib:c})})`),c}catch(a){throw console.error(`${n} ${E(a)}`),a}}h(tc,"registerSubBranchOnParent");function It({targetDir:o,repoRoot:e,galaxyIbGib:t}){if(!e)throw new Error("(UNEXPECTED) repoRoot falsy when resolving contextual branch name (E: 71b3e819ac4092ad63e805da12480826)");if(!t)throw new Error("(UNEXPECTED) galaxyIbGib falsy when resolving contextual branch name (E: 83a04bc612984ea7c89f5d134b280826)");let r=(o||e).replace(/\\/g,"/").replace(/\/+$/,""),n=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(n)){let a=r.slice(n.length).replace(/^\/+/,"");if(a.startsWith("b/")||a==="b"){let s=a.split("/").filter(Boolean);if(s.length>=2&&s[0]==="b"){let i=s[1];if(i)return i}}}return t.data.policy?.defaultBranch||Te}h(It,"resolveContextualBranchName");async function un({metaspace:o,branchName:e,galaxyName:t}){let r=`${Eo}[${un.name}]`;try{if(Qe&&console.log(`${r} starting... (I: 237cfd38398851a997e0f399dc148826)`),!o||!e)throw new Error("metaspace and branchName are required (E: d223dc50b376e9b2d84c712fbb497826)");let n=Hp(e,t),s=(await o.getLocalUserSpaces({lock:!1})).find(i=>i.data?.name===n||i.ib===n);if(s){let i=qe(s.ib);return Qe&&console.log(`${r} Found existing branch space (name: ${n}, space.ib: ${s.ib}) (I: 58ef28a2eda5f501e78497381d596326)`),{space:s,spaceId:i,spaceName:n}}else{let i=await o.createLocalSpaceAndUpdateBootstrap({zeroSpace:o.zeroSpace,allowCancel:!1,createBootstrap:!1,spaceName:n});if(!i)throw new Error("(UNEXPECTED) newBranchSpace falsy? we just called the create function, so we could not create a local space and update bootstrap? But it didn't throw an exception? (E: 4b8be9dd6a182090680b60c8653f2826)");if(!i.data)throw new Error("(UNEXPECTED) newBranchSpace.data falsy? (E: dc3e78b7a3782e7dd80f4fb8609f8a26)");let c=qe(i.ib);return Qe&&console.log(`${r} Using branchName (${e}), created new branch space (ib: ${i.ib}) (I: fc08086f6cc73caa383bc72c662ee826)`),{space:i,spaceId:c,spaceName:n}}}catch(n){throw console.error(`${r} ${E(n)} (E: 091a2820de9a3eca833107883524c626)`),n}finally{Qe&&console.log(`${r} complete. (I: 8452386b1247d58618905a28cf692126)`)}}h(un,"getOrCreateBranchSpace");function Yf(o,e){if(o.branchInfo.branchName===e)return o;for(let t of o.children){let r=Yf(t,e);if(r)return r}}h(Yf,"findNodeInTree");function Kf(o,e,t=0){return e<=0?{...o,depth:t,children:[]}:{...o,depth:t,children:o.children.map(r=>Kf(r,e-1,t+1))}}h(Kf,"pruneTreeDepth");function Wp(o){let e=[],t=[o],r=new Set;for(;t.length>0;){let n=t.shift();if(!r.has(n.branchInfo.branchName)){r.add(n.branchInfo.branchName),e.push(n.branchInfo);for(let a of n.children)t.push(a)}}return e}h(Wp,"flattenCompositeBranchTree");async function Ba(o){let e=`${Eo}[${Ba.name}]`,{metaspace:t,depth:r,currentDepth:n=0}=o,{branchIbGib:a,branchSqAddr:s,branchSpace:i}=o;if(!t)throw new Error("metaspace required (E: e5f6a1b2c3d44718890123456789abcd)");if(!s&&a&&i){let m=qe(i.ib);s=ot({spaceId:m,ibGibAddr:I({ibGib:a})})}if(!s&&!a)throw new Error("branchSqAddr or branchIbGib required (E: f6a1b2c3d4e54718890123456789abcd)");let c=Jt({sqAddr:s}),{spaceId:l}=c;if(!i&&(i=await t.getLocalUserSpace({localSpaceId:l,lock:!1}),!i))throw new Error(`branchSpace not found for spaceId: ${l} (E: a1b2c3d4e5f64718890123456789abce)`);let d=await t.getLatestAddr({addr:c.ibGibAddr,space:i})||c.ibGibAddr;if(a=await ae({addr:d,space:i}),!a)throw new Error(`branchIbGib not found at addr ${d} in space ${i.ib} (E: b2c3d4e5f6a14718890123456789abce)`);let f=pn({ib:a.ib}),p={branchInfo:{branchName:a.data.name||f.branchName,branchId:a.data.uuid||f.uuid,branchIbInfo:f,branchAddr:d,branchSqAddr:s,branchSqAddrInfo:c},branchIbGib:a,parentBranchName:a.data.parentBranchName,parentBranchSqAddr:a.data.parentBranchSqAddr,scopedItemPath:a.data.scopedItemPath,depth:n,children:[]};if(r!==void 0&&r<=0)return p;let u=a.data["$@branch"]||[];for(let m of u)try{let g=await Ba({branchSqAddr:m,metaspace:t,depth:r!==void 0?r-1:void 0,currentDepth:n+1});p.children.push(g)}catch(g){console.error(`${e} Failed to traverse child branch ${m}: ${E(g)}`)}return p}h(Ba,"getCompositeBranchTreeFromBranch");async function rc(o){let e=`${Eo}[${rc.name}]`,{galaxyIbGib:t,metaspace:r,startBranchName:n,depth:a}=o;if(!t)throw new Error("galaxyIbGib required (E: c3d4e5f6a1b24718890123456789abcf)");if(!r)throw new Error("metaspace required (E: d4e5f6a1b2c34718890123456789abcf)");let s=t,i=s.data?.trunkBranchSqAddr;if(!i){let c=s.data?.["$@branch"]||[];c.length>0&&(i=c[0])}if(!i)throw new Error(`Galaxy [${t.data?.name}] has no trunk branch registered. (E: e5f6a1b2c3d44718890123456789abcf)`);if(n){let c=await Ba({branchSqAddr:i,metaspace:r,depth:void 0}),l=Yf(c,n);if(!l)throw new Error(`Branch [${n}] not found in galaxy composite tree. (E: f6a1b2c3d4e54718890123456789abcf)`);return a!==void 0?Kf(l,a):l}return Ba({branchSqAddr:i,metaspace:r,depth:a})}h(rc,"getCompositeBranchTreeFromGalaxy");async function ka({galaxyIbGib:o,metaspace:e,depth:t}){let r=`[${ka.name}]`;try{if(Qe&&console.log(`${r} starting... (I: 86f07281948470f89ae72308e1e92826)`),!o)throw new Error("(UNEXPECTED) galaxyIbGib falsy? (E: 52242814ae88f24442f0dc289505b826)");if(e){let s=await rc({galaxyIbGib:o,metaspace:e,depth:t});return Wp(s)}let n=o.data?.["$@branch"]||[],a=[];for(let s of n){let i=Jt({sqAddr:s}),c=pn({ib:i.ib});a.push({branchName:c.branchName,branchId:c.uuid,branchIbInfo:c,branchAddr:i.ibGibAddr,branchSqAddr:s,branchSqAddrInfo:i})}return a}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Qe&&console.log(`${r} complete.`)}}h(ka,"getAllBranchInfosFromGalaxy");async function oc({galaxyIbGib:o,branchName:e,metaspace:t}){let r=`[${oc.name}]`;try{Qe&&console.log(`${r} starting... (I: d63138d40debdb1a8b398b6135875326)`);let n=o.data?.["$@branch"]||[];for(let a of n){let s=Jt({sqAddr:a}),i=pn({ib:s.ib});if(i.branchName===e)return{branchName:e,branchId:i.uuid,branchIbInfo:i,branchAddr:s.ibGibAddr,branchSqAddr:a,branchSqAddrInfo:s}}if(t){let s=(await ka({galaxyIbGib:o,metaspace:t})).find(i=>i.branchName===e);if(s)return s}throw new Error(`branchName (${e}) not found in galaxyIbGib ${I({ibGib:o})} (E: 8c9cf891f118afafe853049883248826)`)}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Qe&&console.log(`${r} complete.`)}}h(oc,"getBranchInfoFromGalaxy");async function nc({galaxyIbGib:o,metaspace:e}){let t=`[${nc.name}]`;try{if(Qe&&console.log(`${t} starting... (I: 1b14785116888c37a8b3a03189811826)`),!o)throw new Error("(UNEXPECTED) galaxyIbGib falsy? (E: 52242814ae88f24442f0dc289505b826)");if(!e)throw new Error("(UNEXPECTED) metaspace falsy? (E: 1a7dc1b555bd5ee98a826da857a5c826)");let r=await rc({galaxyIbGib:o,metaspace:e}),n=[],a=[r],s=new Set;for(;a.length>0;){let i=a.shift();if(!s.has(i.branchInfo.branchName)){s.add(i.branchInfo.branchName),n.push(i.branchIbGib);for(let c of i.children)a.push(c)}}return n}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Qe&&console.log(`${t} complete.`)}}h(nc,"getAllBranchIbGibsFromGalaxy");var Yp=!1,Kp="[bin-helpers]";async function ja({data:o,ext:e,encoding:t,space:r,metaspace:n}){let a=`${Kp}[${ja.name}]`;try{if(o==null)throw new Error("data is required for createBinIbGib (E: 8a91c01b4d8349fa89e3bb8893d94b26)");let s,i;if(typeof o=="string")s=new TextEncoder().encode(o),i=await te({s:o});else{s=o;let b=s.byteOffset===0&&s.byteLength===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),p=await crypto.subtle.digest("SHA-256",b);i=Array.from(new Uint8Array(p)).map(u=>u.toString(16).padStart(2,"0")).join("")}let c=pa({binHash:i,binExt:e,binEncoding:t}),l=await ee({ibGib:{ib:c,data:s},hasTjp:!1}),d={ib:c,gib:l,data:s},f=I({ibGib:d});return r&&(n?(await n.put({ibGib:d,space:r}),await n.registerNewIbGib({ibGib:d,space:r})):(await ce({ibGib:d,space:r}),await J({ibGib:d,space:r}))),Yp&&console.log(`${a} Created BinIbGib stone at ${f}`),{binIbGib:d,binAddr:f,binHash:i}}catch(s){throw console.error(`${a} ${E(s)} (E: d2871f76bc0347efa2926be5e72d2426)`),s}}h(ja,"createBinIbGib");var wo="b2tfs_item",zp="v1";function Jp(o){return o?o.replace(/[^a-zA-Z0-9_\-\.]/g,"_").slice(0,32):"unnamed"}h(Jp,"getB2tFSItemSaferName");function zf(o,e,t){let r=Jp(e);return`${wo} ${o} ${r} ${zp} ${t}`}h(zf,"getB2tFSItemIb");var mn={file:"file",folder:"folder"},Q1=Object.values(mn),be="b2tfs_child",Hr="bin";var Zp=/^(\\\\|[/\\]{2})[^/\\]+[/\\]+[^/\\]+/,ac=class o{static{h(this,"DefaultPathHelper")}lc=`[${o.name}]`;toPosix(e){return e?e.replace(/\\/g,"/"):""}isAbsolute(e){return e?!!(e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:[/\\]/.test(e)||Zp.test(e)):!1}isRelative(e){return!this.isAbsolute(e)}normalize(e){if(!e||e.trim()==="")return".";let t=e.includes("\\")||/^[a-zA-Z]:/.test(e),r=t&&e.includes("\\")&&!e.includes("/")||t&&e.includes("\\")?"\\":"/",n="",a=e,s=e.match(/^[a-zA-Z]:[/\\]?/);if(s)n=s[0],n.length===2&&(n+=e.includes("\\")?"\\":"/"),a=e.slice(s[0].length);else if(e.startsWith("\\\\")||e.startsWith("//")){let f=e.match(/^(\\\\|[/\\]{2})[^/\\]+[/\\]+[^/\\]+[/\\]?/);f?(n=f[0],a=e.slice(f[0].length)):(n=e.startsWith("\\\\")?"\\\\":"//",a=e.slice(2))}else(e.startsWith("/")||e.startsWith("\\"))&&(n=e.startsWith("\\")&&!e.includes("/")?"\\":"/",a=e.slice(1));let i=(a.endsWith("/")||a.endsWith("\\")||e.endsWith("/")||e.endsWith("\\"))&&e.length>1,c=a.split(/[/\\]+/),l=[];for(let f of c)!f||f==="."||(f===".."?l.length>0&&l.at(-1)!==".."?l.pop():n||l.push(".."):l.push(f));let d=l.join(r);return n?d?n.endsWith("/")||n.endsWith("\\")?d=n+d:d=n+r+d:d=n:d||(d="."),i&&!d.endsWith("/")&&!d.endsWith("\\")&&d!=="."&&(d+=r),d}join(...e){let t=e.filter(i=>i&&typeof i=="string"&&i.trim()!=="");if(t.length===0)return".";let r=t.some(i=>i.includes("\\")),n=t.some(i=>/^[a-zA-Z]:/.test(i)),a=(r||n)&&r?"\\":"/",s="";for(let i=0;i<t.length;i++){let c=t[i];if(i===0)s=c;else{let l=c.replace(/^[/\\]+/,"");s.endsWith("/")||s.endsWith("\\")?s+=l:s+=a+l}}return this.normalize(s)}dirname(e){if(!e||e.trim()==="")return".";let t=this.normalize(e);if(t==="/"||t==="\\"||/^[a-zA-Z]:[/\\]?$/.test(t))return t;let r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));if(r===-1)return".";if(r===0)return t.slice(0,1);let n=t.slice(0,r);return/^[a-zA-Z]:$/.test(n)?t.slice(0,r+1):n}basename(e,t){if(!e||e.trim()==="")return"";let r=e.replace(/[/\\]+$/,""),n=Math.max(r.lastIndexOf("/"),r.lastIndexOf("\\")),a=n===-1?r:r.slice(n+1);return t&&a.endsWith(t)&&a.length>t.length&&(a=a.slice(0,a.length-t.length)),a}extname(e){if(!e)return"";let t=this.basename(e),r=t.lastIndexOf(".");return r<=0?"":t.slice(r)}relative(e,t){let r=this.normalize(e),n=this.normalize(t);if(r===n)return"";let a=r.match(/^[a-zA-Z]:/),s=n.match(/^[a-zA-Z]:/);if(a&&s&&a[0].toLowerCase()!==s[0].toLowerCase())return n;let c=r.includes("\\")||n.includes("\\")?"\\":"/",l=this.toPosix(r).split("/").filter(Boolean),d=this.toPosix(n).split("/").filter(Boolean),f=0;for(;f<l.length&&f<d.length&&l[f].toLowerCase()===d[f].toLowerCase();)f++;let b=l.length-f,p=[];for(let u=0;u<b;u++)p.push("..");return p.push(...d.slice(f)),p.join(c)||"."}},gn=new ac;function qa(o){return gn.toPosix(o)}h(qa,"toPosixPath");function Ge(...o){return gn.join(...o)}h(Ge,"joinPaths");function Jf(o){return gn.dirname(o)}h(Jf,"dirnamePath");function Zf(o,e){return gn.basename(o,e)}h(Zf,"basenamePath");function Qf(o){return gn.extname(o)}h(Qf,"extnamePath");var En="b2tfs_galaxy",Xa="b2tfs_galaxy";var Ha="galaxy",eb="galaxy",Va=/^[a-zA-Z0-9_\-.]{1,64}$/;var Qp="code",eu="notes",tu="curriculum",ru="telemetry",St={code:Qp,notes:eu,curriculum:tu,telemetry:ru},ou=Object.values(St);function nu(o){return ou.includes(o)}h(nu,"isGalaxyPresetType");var tb={[St.code]:{discriminator:St.code,defaultName:"code-1",label:"Code Space",icon:"</>",description:"Code Galaxy (Repositories / VCS)",policy:{topology:"branching",role:"intrinsic",storageMode:"text",defaultBranch:"main"}},[St.notes]:{discriminator:St.notes,defaultName:"notes-1",label:"Text Space",icon:"\u{1F4DD}",description:"Text Space (Metatext Discussions & Notes)",policy:{topology:"linear",role:"extrinsic",storageMode:"text"}},[St.curriculum]:{discriminator:St.curriculum,defaultName:"curriculum-1",label:"Curriculum Space",icon:"\u{1F4DA}",description:"Curriculum Registry (Lessons, Exercises & Mastery DAG)",policy:{topology:"linear",role:"intrinsic",storageMode:"text"}},[St.telemetry]:{discriminator:St.telemetry,defaultName:"telemetry-1",label:"Telemetry Space",icon:"\u{1F4CA}",description:"Telemetry & Audit Log (Append-only Event Stream)",policy:{topology:"linear",role:"extrinsic",storageMode:"text"}}};function rb(o){if(nu(o))return tb[o];for(let e of Object.values(tb))if(e.defaultName===o||o.startsWith(`${e.discriminator}-`))return e}h(rb,"getGalaxyPresetConfig");var au="[galaxy-helpers]",ob=!1;function nb(o){return!!(o&&Va.test(o))}h(nb,"validateGalaxyName");function sc({galaxyName:o,topology:e="branching",storageMode:t="text",concreteClassname:r="GalaxyIbGib_V1"}){if(!nb(o))throw new Error(`Invalid galaxy name: "${o}". Must match ${Va} (no whitespace or tildes). (E: 7a8b9c0d1e2f34567890123456789abc)`);return`${Ha} ${e} ${t} ${r} ${o}`}h(sc,"getGalaxyIb");async function su({galaxyName:o,discriminator:e,policy:t,description:r,icon:n,label:a,space:s,metaspace:i,customData:c}){let l=`${au}[${su.name}]`;try{if(ob&&console.log(`${l} starting for "${o}" (discriminator: ${e})...`),!nb(o))throw new Error(`Invalid galaxy name: "${o}". Must match ${Va}. (E: 0d1e2f3a4b5c67890123456789abcdef)`);let d=rb(e),f=t??d?.policy??{topology:"linear",role:"extrinsic",storageMode:"text"},b=n??d?.icon,p=a??d?.label??o,u=r??d?.description,m=s?.ib?qe(s.ib):void 0,g={galaxyName:o,discriminator:e,policy:f,uuid:await q(),classname:"GalaxyIbGib_V1",...u?{description:u}:{},...b?{icon:b}:{},...p?{label:p}:{},...m?{mySpaceId:m}:{},...f.topology==="branching"?{"$@branch":[]}:{"$@topic":[]},...c??{}},y=await H.firstGen({parentIbGib:ue,ib:sc({galaxyName:o,topology:f.topology,storageMode:f.storageMode??"text",concreteClassname:"GalaxyIbGib_V1"}),data:g,tjp:{timestamp:!0},dna:!0,nCounter:!0}),w=y.newIbGib;return i?(await i.persistTransformResult({resTransform:y,space:s}),await i.registerNewIbGib({ibGib:w,space:s}),await i.getSpecialIbGib({type:Ha,initialize:!0,space:s}),await i.rel8ToSpecialIbGib({type:Ha,rel8nName:eb,ibGibsToRel8:[w],space:s,linked:!0})):await ce({ibGib:w,space:s}),ob&&console.log(`${l} Created GalaxyIbGib: ${w.ib} (addr: ${I({ibGib:w})})`),w}catch(d){throw console.error(`${l} ${E(d)} (E: 1e2f3a4b5c6d7890123456789abcdef0)`),d}}h(su,"createGalaxyIbGib");var wn="[b2tfs-repo-helpers]",Ye=!1;function yo(o,e,t){let r=(o||"").replace(/\\/g,"/");if(t){let n=t.replace(/\\/g,"/").replace(/\/+$/,"");n&&r.startsWith(n)&&(r=r.slice(n.length).replace(/^\/+/,""))}if(e&&t&&e!==t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),a=t.replace(/\\/g,"/").replace(/\/+$/,"");if(n.startsWith(a)){let s=n.slice(a.length).replace(/^\/+/,"");r=s?Ge(s,r):r}}return r.replace(/^\/+/,"")}h(yo,"normalizeRepoRelPath");async function cc({galaxyName:o="code-1",defaultBranch:e=Te,space:t,metaspace:r,sqBranchAddr:n}){let a=`${wn}[${cc.name}]`;try{if(Ye&&console.log(`${a} starting... (I: 7b2118e6beeefd9658c9a94a89bb1826)`),!ha(n))throw new Error(`invalid sqBranchAddr (${n}) (E: d905089debc8983077b7172767f8c926)`);let s=qe(t.ib),i={galaxyName:o,discriminator:St.code,policy:{topology:"branching",role:"intrinsic",storageMode:"text",defaultBranch:e||Te},mySpaceId:s,uuid:await q(),classname:"B2tFSGalaxyIbGib_V1",trunkBranchSqAddr:n,"$@branch":[n],stagedPaths:{},staged_item:[]},c=await H.firstGen({parentIbGib:ue,ib:sc({galaxyName:o,topology:"branching",storageMode:"text",concreteClassname:"B2tFSGalaxyIbGib_V1"}),data:i,tjp:{timestamp:!0},dna:!0,nCounter:!0}),l=c.newIbGib;return await r.persistTransformResult({resTransform:c,space:t}),await r.registerNewIbGib({ibGib:l,space:t}),await r.getSpecialIbGib({type:En,initialize:!0,space:t}),await r.rel8ToSpecialIbGib({type:En,rel8nName:Xa,ibGibsToRel8:[l],space:t,linked:!0}),Ye&&console.log(`${a} Created galaxy IbGib: ${l.ib} (I: 039e9e584d6a11e1b85797b89a0c6826)`),l}catch(s){throw console.error(`${a} ${E(s)} (E: fa3da104817ebf8db14172884ff2c426)`),s}finally{Ye&&console.log(`${a} complete. (I: 40f5d280cfd8ec0ce39386a85ce8f826)`)}}h(cc,"createB2tFSGalaxyIbGib");async function yn({space:o,metaspace:e,galaxyAddr:t}){let r=`${wn}[${yn.name}]`;try{Ye&&console.log(`${r} starting... (I: bddb12b7b10ddc9b86e57cae9958f826)`);let n;if(t)n=await ae({addr:t,space:o});else if(e)n=(await e.getSpecialRel8dIbGibs({type:En,rel8nName:Xa,space:o}))?.at(0);else throw new Error("(UNEXPECTED) both galaxyAddr and metaspace falsy? one of these is required. (E: fd8e58f46f668ba605fc20186a5a1626)");if(!n){t?Ye&&console.log(`Could not get galaxyAddr (${t}) from space (${o.ib}). Not initialized? (I: d7da7f279a08d9c2a8971ac8d14e0826)`):Ye&&console.log(`Could not get galaxyIbGib via metaspace special anchor type ${En} and rel8nName ${Xa}. Not initialized? (I: a1a26c3ac9086522db895d783999e826)`);return}let a=I({ibGib:n}),s=ye({ibGib:n});Ye&&(console.log(`${r} baseGalaxyAddr: ${a}, tjpAddr: ${s} (I: 0640288ad6a6ca19b8578e6e841b4826)`),console.log(`${r} baseGalaxyIbGib stagedPaths: ${JSON.stringify(n.data.stagedPaths)}`));let i=await ua({ibGib:n,space:o});if(!i)throw new Error(`(UNEXPECTED) baseGalaxyIbGib (${a}) exists but we couldn't get the latest galaxy ibGib? (E: d1adc82a8cc82fe3f8aa8d136aede826)`);return Ye&&console.log(`${r} foundLatest stagedPaths: ${JSON.stringify(i.data.stagedPaths)}, latestAddr: ${I({ibGib:i})} (I: e7fcf8ebba68e907a8378935eb10d626)`),i}catch(n){throw console.error(`${r} ${E(n)} (E: 3d2b1875548836a2f18fc698abfbb326)`),n}finally{Ye&&console.log(`${r} complete. (I: e3822fa5a5085fcb52826018b4ca2826)`)}}h(yn,"getB2tFSGalaxyIbGib");async function mt({space:o,metaspace:e,galaxyIbGib:t,dataToUpdate:r}){let n=`${wn}[${mt.name}]`;try{Ye&&console.log(`${n} starting... (I: 5536885f77b88e42741b55c890efe826)`);let a={},s={...r};if(!r||Object.keys(r).length===0)throw new Error("(UNEXPECTED) no dataToUpdate? this may be correct, but atow (08/2026), I'm assuming this is the whole point of calling this function. I don't know why the agents made it optional, so if this error surfaces, re-examine this. (E: d0e06daa7748d6def7cd7a08b9d1d826)");r?.["$@branch"]&&t.data["$@branch"]&&(a["$@branch"]=""),r.stagedPaths&&(a.stagedPaths="");let i=await Ae({src:t,dataToRemove:Object.keys(a).length>0?a:void 0,dataToAddOrPatch:s,dna:!0,nCounter:!0}),c=i.newIbGib;if(Ye&&console.log(`[updateB2tFSGalaxyIbGib] immediately after mut8: newIbGib.data: ${JSON.stringify(c?.data)}, n: ${c?.data?.n}, addr: ${I({ibGib:c})}, srcAddr: ${I({ibGib:t})}`),await e.persistTransformResult({resTransform:i,space:o}),await e.registerNewIbGib({ibGib:c,space:o}),Ye)try{let l=await ua({ibGib:t,space:o}),d=I({ibGib:c}),f=I({ibGib:l});console.log(`[updateB2tFSGalaxyIbGib] after persist+register resolveLatestIbGibInSpace: resolvedAddr=${f}, newAddr=${d}, match=${f===d}, resolvedN=${l?.data?.n}`)}catch(l){console.error(`[updateB2tFSGalaxyIbGib] resolveLatestIbGibInSpace diagnostic error: ${l} (E: 8e2293ff521be749c46ad1255acb2826)`)}return c}catch(a){throw console.error(`${n} ${E(a)} (E: 480608b166b811f81334d59506bf4726)`),a}finally{Ye&&console.log(`${n} complete. (I: 7c77287267d81c503d9d814a1936de26)`)}}h(mt,"updateB2tFSGalaxyIbGib");async function $n({galaxyIbGib:o,paths:e=[],targetDir:t="",activeWorktreeDir:r,space:n,metaspace:a,all:s=!1}){let i=`${wn}[${$n.name}]`;try{Ye&&console.log(`${i} starting... (I: adf91a3648a734701d01b1010a8c4826)`);let c={...o.data?.stagedPaths||{}},l=[...o.data?.staged_item||[]],d=[],f=r||t;if(s||e.length===0||e.length===1&&(e[0]==="."||e[0]==="")){for(let u of Object.keys(c))d.push(u);return{updatedGalaxy:await mt({space:n,metaspace:a,galaxyIbGib:o,dataToUpdate:{stagedPaths:{},staged_item:[]}}),unstagedPaths:d}}for(let p of e){let u=yo(p,t,f),m=Object.keys(c).filter(g=>g===u||g.startsWith(u+"/"));for(let g of m){let y=c[g];y&&y.itemAddr&&(l=l.filter(w=>w!==y.itemAddr)),delete c[g],d.includes(g)||d.push(g)}}return{updatedGalaxy:await mt({space:n,metaspace:a,galaxyIbGib:o,dataToUpdate:{stagedPaths:c,staged_item:l}}),unstagedPaths:d}}catch(c){throw console.error(`${i} ${E(c)} (E: f839a88fb40ab2c808bf7f7807ba4826)`),c}finally{Ye&&console.log(`${i} complete. (I: 3d75881c0a3404fd73241bc3744dcc26)`)}}h($n,"unstagePathsFromGalaxy");async function lc({paths:o,targetDir:e,activeWorktreeDir:t,branchName:r,workspaceSpace:n,metaspace:a,galaxyIbGib:s}){let i=`${wn}[${lc.name}]`;try{Ye&&console.log(`${i} starting... (I: fa43a9fa775855dfd8378ca631417826)`);let{branchIbGib:c,branchInfo:l,branchSpace:d,rootItemAddr_latest:f,rootItemIbGib_latest:b}=await Xe({galaxyIbGib:s,branchName:r,metaspace:a}),p=new Map;await ic({item:b,parentRelPath:"",isRoot:!0,space:d,metaspace:a,outMap:p});let u=n;!u&&a&&(u=(await a.getLocalUserSpaces({lock:!1})||[]).find(y=>y.data?.classname?.includes("WorkspaceProjectionSpace")&&(!t||y.data?.workspaceRoot===t)));let m=[];if(o.length===0||o.length===1&&(o[0]==="."||o[0]==="")){u&&await ce({space:u,ibGib:b});for(let g of p.values())m.push(g.relPath)}else for(let g of o){let y=yo(g,e,t),w=0;for(let A of p.values())(A.relPath===y||A.relPath.startsWith(y+"/"))&&(u&&await u.witness({data:{cmd:"put",subPath:A.parentRelPath||void 0},ibGibs:[A.item]}),m.includes(A.relPath)||m.push(A.relPath),w++);if(w===0)throw new Error(`pathspec '${g}' did not match any committed file(s) in snapshot (E: eab774c126885663183fede7ec5d2926)`)}return{restoredPaths:m}}catch(c){throw console.error(`${i} ${E(c)} (E: f962a38c605a44d3251d3e8883b3c826)`),c}finally{Ye&&console.log(`${i} complete. (I: 93460761e9786170d861f75827a5c726)`)}}h(lc,"restoreWorktreePathsFromSnapshot");async function ic({item:o,parentRelPath:e,isRoot:t=!1,space:r,metaspace:n,outMap:a}){if(!o||!o.data)return;let{fsType:s,name:i}=o.data;if(t){let c=o.rel8ns?.[be]||[];for(let l of c){let d=await ae({addr:l,space:r,metaspace:n});d&&await ic({item:d,parentRelPath:"",isRoot:!1,space:r,metaspace:n,outMap:a})}}else{let c=e?Ge(e,i):i;if(a.set(c,{relPath:c,parentRelPath:e,item:o}),s==="folder"){let l=o.rel8ns?.[be]||[];for(let d of l){let f=await ae({addr:d,space:r,metaspace:n});f&&await ic({item:f,parentRelPath:c,isRoot:!1,space:r,metaspace:n,outMap:a})}}}}h(ic,"restoreCmd_collectCommittedItems");var lt=!1,Vr="[item-helpers]";function $o(o){return!o||!Lr(o)?!1:o.ib.startsWith(wo)||o.data?.classname==="B2tFSItemIbGib_V1"}h($o,"isB2tFSItemIbGib");async function er({fsType:o,name:e,data:t,rel8ns:r}){let n=`${Vr}[${er.name}]`;try{if(lt&&console.log(`${n} starting... (I: 9f7d189b5bbb4ad5a819c568ce0d7826)`),!o||!e)throw new Error("fsType and name are required (E: 488874f761040744a89ef772af873826)");let a=t?.nameHash||await te({s:e}),s=t?.uuid||await q(),i=t?.diffTransactionId||await q(),c,l;if(o==="file"){let p=e.lastIndexOf(".");p>0?(c=e.slice(0,p),l=e.slice(p+1)):(c=e,l="")}let d={name:e,nameHash:a,fsType:o,diffTransactionId:i,uuid:s,classname:"B2tFSItemIbGib_V1",...o==="file"?{fileNameSansExt:c,fileExt:l}:{},...t},f=zf(o,e,a),b=await H.firstGen({parentIbGib:H.primitive({ib:wo}),ib:f,data:d,rel8ns:r,tjp:{timestamp:!0,uuid:!0},dna:!0,nCounter:!0});return lt&&console.log(`${n} Created new B2tFSItemIbGib: ${b.newIbGib.ib}^${b.newIbGib.gib} (I: aaf52cddf678c29a25875843cf2fd826)`),b}catch(a){throw console.error(`${n} ${E(a)} (E: edcfc8414233fa9b6658558808c6a826)`),a}finally{lt&&console.log(`${n} complete. (I: 4927283a2dd82bc9abc4af0be0f2b826)`)}}h(er,"createB2tFSItemIbGib");async function Ft({existingItem:o,dataToUpdate:e,rel8nsToUpdate:t,rel8nsToRemove:r}){let n=`${Vr}[${Ft.name}]`;try{if(lt&&console.log(`${n} starting... (I: d35e11bfe428b5dfe1dfb7b74602c826)`),!o||!o.ib||!o.gib)throw new Error("existingItem with valid ib and gib is required (E: 258048f80f954dc9786434c8dc0e8b26)");let a=o,s=[],i=[];(!a.rel8ns?.ancestor||a.rel8ns.ancestor.length===0)&&(a={...a,rel8ns:{...a.rel8ns||{},ancestor:[`${wo}^gib`]}});let c=e&&Object.keys(e).length>0,l=t&&Object.keys(t).length>0||r&&Object.keys(r).length>0,d={...e||{},diffTransactionId:e?.diffTransactionId||await q()},f=await Ae({src:a,dataToAddOrPatch:d,dna:!0,nCounter:!d.n});if(a=f.newIbGib,f.dnas&&s.push(...f.dnas),l){i.push(a);let b=await ie({src:a,rel8nsToAddByAddr:t,rel8nsToRemoveByAddr:r,dna:!0,nCounter:!0});a=b.newIbGib,b.dnas&&s.push(...b.dnas)}return(!a.rel8ns?.ancestor||a.rel8ns.ancestor.length===0)&&(a.rel8ns={...a.rel8ns||{},ancestor:[`${wo}^gib`]}),lt&&console.log(`${n} Evolved B2tFSItemIbGib: ${a.ib}^${a.gib} (I: 5a5d21af206847cde30c2728bfdb3226)`),{newIbGib:a,intermediateIbGibs:i.length>0?i:void 0,dnas:s.length>0?s:void 0}}catch(a){throw console.error(`${n} ${E(a)} (E: 25eae258d173872aa8cc83dc2b7e6926)`),a}finally{lt&&console.log(`${n} complete. (I: fe33389c0ed1777ce89d3428a7419826)`)}}h(Ft,"evolveB2tFSItemIbGib");async function dc({rootItem:o,rootItemAddr:e,space:t,metaspace:r}){let n=`${Vr}[${dc.name}]`;try{lt&&console.log(`${n} starting... (I: 428138d15828380a13dfff9a51944826)`);let a=await Bi({ibGib:o,ibGibAddr:e,onlyRel8nNames:[be],space:t,metaspace:r});return{reifiedRootItem:a.reifiedIbGib,hasChanges:a.hasChanges,reifiedAddrsMap:a.reifiedAddrsMap,evolvedItems:a.evolvedIbGibs}}catch(a){throw console.error(`${n} ${E(a)} (E: f4ef9c7357e883019c09e84887ad3826)`),a}finally{lt&&console.log(`${n} complete. (I: 071471754e888273f8abcfe85d478826)`)}}h(dc,"reifyB2tFSHierarchy");async function ab({branchIbGib:o,addrOnly:e,branchSpace:t}){let r=`[${ab.name}]`;try{if(lt&&console.log(`${r} starting... (I: 92cc9882ded8da7128efcbd8b37ec826)`),!o.rel8ns)throw new Error("(UNEXPECTED) branchIbGib.rel8ns falsy? (E: 433b027e958503e648a0858807b85826)");if(!o.rel8ns.b2tfs_item)throw new Error("(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item falsy? (E: c5989d7fa2f836e6781a929d76958726)");if(o.rel8ns.b2tfs_item.length===0)throw new Error("(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item empty? (E: 2c634c54ec485ed638eb12083ea93826)");let n=o.rel8ns.b2tfs_item.at(-1),a;if(!e){if(!t)throw new Error("branchSpace required when addrOnly is false. (E: 51fa687228a82f3638517c7e4b249826)");a=await ae({addr:n,space:t})}return{rootItemAddr:n,rootItemIbGib:a}}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{lt&&console.log(`${r} complete.`)}}h(ab,"getRootItemFromBranchIbGib");async function Xe({galaxyIbGib:o,branchName:e,metaspace:t}){let r=`[${Xe.name}]`;try{lt&&console.log(`${r} starting... (I: acae374202688beed805e578fec3ea26)`);let n=await oc({galaxyIbGib:o,branchName:e,metaspace:t}),a=await t.getLocalUserSpace({localSpaceId:n.branchSqAddrInfo.spaceId,lock:!1});if(!a)throw new Error(`branchSpace not found from branchSqAddr: ${n.branchSqAddr} (E: 62dd9fb2a5b8cea6734a6038c8c6fb26)`);let{branchAddr:s}=n,i=await t.getLatestAddr({addr:s,space:a})||s,c=await ae({addr:i,space:a});if(!c)throw new Error(`(UNEXPECTED) branchAddr (${i}) not found in branchSpace (${a.ib})? (E: 8f9a48a0d5a88c99468b121edbc51826)`);let{rootItemAddr:l,rootItemIbGib:d}=await ab({branchIbGib:c,branchSpace:a,addrOnly:!1});if(!d)throw new Error("(UNEXPECTED) rootItemIbGib falsy? (E: 883d18f3c978a919a8f298b9d6971826)");let f=await t.getLatestAddr({addr:l,space:a})||l,b=d;if(f!==l&&(b=await ae({addr:f,space:a}),!b))throw new Error(`(UNEXPECTED) rootItemIbGib_latest falsy? We just got rootItemAddr_latest (${f}) from branchSpace (${a.ib}), so we should have been able to get the corresponding ibgib. (E: 86bd690fb143f0a1e80209387ff7c426)`);return{branchIbGib:c,branchInfo:n,branchSpace:a,rootItemAddr:l,rootItemAddr_latest:f,rootItemIbGib:d,rootItemIbGib_latest:b}}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{lt&&console.log(`${r} complete.`)}}h(Xe,"getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib");async function sb({name:o,content:e}){return(await er({fsType:"file",name:o,data:{isVirtual:!0,virtualFileContents:e}})).newIbGib}h(sb,"createVirtualItemIbGib");async function iu({branchSpace:o,fileItem:e}){let t=`${Vr}[${iu.name}]`;try{if(e.data?.virtualFileContents!==void 0)return e.data.virtualFileContents;let r=e.rel8ns?.[Hr]?.[0];if(r){let n=await ae({addr:r,space:o});if(n?.data){if(n.data instanceof Uint8Array)return new TextDecoder().decode(n.data);if(typeof n.data=="string")return n.data}}return""}catch(r){return console.error(`${t} Failed to get file content: ${E(r)}`),""}}h(iu,"getFileContent");async function Wa({branchSpace:o,rootItem:e,filePath:t}){let r=`${Vr}[${Wa.name}]`;try{let n=t.split("/").filter(Boolean);if(n.length===0)return e;let a=e;for(let s=0;s<n.length;s++){let i=n[s],c=a.rel8ns?.[be]||[],l;for(let d of c){let f=await ae({addr:d,space:o});if(f?.data?.name===i){l=f;break}}if(!l)return;if(s===n.length-1)return l;a=l}return}catch(n){console.error(`${r} Failed to resolve file item from path [${t}]: ${E(n)}`);return}}h(Wa,"getFileItemFromPath");async function cu({branchSpace:o,folderItem:e}){let t=`${Vr}[${cu.name}]`;try{let r=e.rel8ns?.[be]||[];if(r.length===0)return[];let a=await st({addrs:r,space:o})||[],s=new Map;for(let i of a)i?.data?.name&&s.set(i.data.name,i);return Array.from(s.values())}catch(r){return console.error(`${t} Failed to get folder children: ${E(r)}`),[]}}h(cu,"getFolderChildren");async function lu({metaspace:o,branchSpace:e,branchIbGib:t,rootFolderItem:r,changes:n,message:a,author:s="You",galaxyIbGib:i,localSpace:c}){let l=`${Vr}[${lu.name}]`;try{if(lt&&console.log(`${l} Committing ${n.length} change(s) to branch [${t.data.name}] with message: "${a}"...`),n.length===0)throw new Error("No changes provided to commit.");let d=r;for(let u of n){let m=u.path.split("/").filter(Boolean).pop()||u.path,g=u.content??"";if(u.status==="untracked"){let{binAddr:y,binHash:w}=await ja({data:g,space:e,metaspace:o}),A=await er({fsType:"file",name:m,data:{fileHash:w,virtualFileContents:g,isVirtual:!1},rel8ns:{[Hr]:[y]}}),G=A.newIbGib;await o.persistTransformResult({resTransform:A,space:e}),await o.registerNewIbGib({ibGib:G,space:e});let T=I({ibGib:G}),$=await Wa({branchSpace:e,rootItem:d,filePath:u.path}),_=$?I({ibGib:$}):void 0,S=await ie({src:d,rel8nsToAddByAddr:{[be]:[T]},..._?{rel8nsToRemoveByAddr:{[be]:[_]}}:{},dna:!0,nCounter:!0});d=S.newIbGib,await o.persistTransformResult({resTransform:S,space:e}),await o.registerNewIbGib({ibGib:d,space:e})}else if(u.status==="modified"){let y=await Wa({branchSpace:e,rootItem:d,filePath:u.path});if(!y)throw new Error(`Cannot modify file [${u.path}]: file item not found in branch.`);let w=I({ibGib:y}),{binAddr:A,binHash:G}=await ja({data:g,space:e,metaspace:o}),T=await Ft({existingItem:y,dataToUpdate:{fileHash:G,virtualFileContents:g},rel8nsToUpdate:{[Hr]:[A]}}),$=T.newIbGib;await o.persistTransformResult({resTransform:T,space:e}),await o.registerNewIbGib({ibGib:$,space:e});let _=I({ibGib:$}),S=await ie({src:d,rel8nsToAddByAddr:{[be]:[_]},rel8nsToRemoveByAddr:{[be]:[w]},dna:!0,nCounter:!0});d=S.newIbGib,await o.persistTransformResult({resTransform:S,space:e}),await o.registerNewIbGib({ibGib:d,space:e})}else if(u.status==="deleted"){let y=await Wa({branchSpace:e,rootItem:d,filePath:u.path});if(y){let w=I({ibGib:y}),A=await ie({src:d,rel8nsToRemoveByAddr:{[be]:[w]},dna:!0,nCounter:!0});d=A.newIbGib,await o.persistTransformResult({resTransform:A,space:e}),await o.registerNewIbGib({ibGib:d,space:e})}}}let f=await ec({existingBranch:t,rootItem:d,space:e,metaspace:o}),b=I({ibGib:f}),p=i;if(i&&c){let u=(i.data?.policy?.defaultBranch||Te).toLowerCase();if((t.data?.name||"").toLowerCase()===u){let g=qe(e.ib),y=ot({spaceId:g,ibGibAddr:b});p=await mt({space:c,metaspace:o,galaxyIbGib:i,dataToUpdate:{trunkBranchSqAddr:y,"$@branch":[y]}})}}return lt&&console.log(`${l} Successfully committed ${n.length} change(s) to branch [${t.data.name}]. New tip: ${b}`),{evolvedBranch:f,evolvedRootFolder:d,newTipAddr:b,committedCount:n.length,updatedGalaxy:p}}catch(d){throw console.error(`${l} Failed to commit changes to galaxy branch: ${E(d)}`),d}}h(lu,"commitChangesToGalaxyBranch");var Ya="sync",Ke="syncmsg",fc="@payloadAddrsDomain",du="init",fu="ack",bu="delta",hu="commit",_e={init:du,ack:fu,delta:bu,commit:hu},r4=Object.values(_e),pu="abort",uu="optimistic-graft-longest-common-subsequence",gt={abort:pu,optimisticWithLCS:uu},Wr=Object.values(gt);function Ka(o){return Wr.includes(o)}h(Ka,"isValidSyncConflictStrategy");var Io="graftinfo",Yr=Io,ib="latestcommonaddr",cb="base",za="orphan",lb="dnaapplied",mu="longest-common-subsequence",bc={lcs:mu},a4=Object.values(bc);var Bt;(function(o){o.timestamp="timestamp",o.receiver="receiver",o.sender="sender"})(Bt||(Bt={}));var et=!1;async function hc({timeline:o}){let e=`[${hc.name}]`;try{if(et&&console.log(`${e} starting...`),Ce({ibGib:o}))return console.warn(`${e} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`),I({ibGib:o});{let t=Ne({gib:o.gib}),r=t.tjpGib??t.punctiliarHash;if(!r)throw new Error(`${e} (UNEXPECTED) Could not determine tjpGib or punctiliarHash from ibGib. (E: eb3b6472e9b335991a1b0869f772f7d3)`);return r}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{et&&console.log(`${e} complete.`)}}h(hc,"getLockScope");async function pc({timeline:o,rel8nInfos:e,rel8nRemovalInfos:t,timelineIndexInfo:r,metaspace:n,space:a,skipLock:s,noDna:i}){let c=`[${pc.name}]`;try{if(et&&console.log(`${c} starting... (I: fcdff10832215068019355265f4cbc25)`),a??=await n.getLocalUserSpace({lock:!1}),!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)");let l=await hc({timeline:o}),d=h(async()=>{if(!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let b=I({ibGib:o}),p=await n.getLatestAddr({addr:b,space:a});if(!p)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${I({ibGib:o})}. (E: 42d0f681ec1371add2eeec983a326826)`);let u=Fe({ibGib:o});if(b!==p){let A=await n.get({addrs:[p],space:a});if(A.errorMsg||(A.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${p}) from space (${a.ib}). errorMsg: ${A.errorMsg??"[unknown error]"} (E: 96e7d709ba48d9d6949208f807acc826)`);u=A.ibGibs.at(0)}let m;if(t&&t.length>0){m={};for(let A of t){let{rel8nName:G,ibGibAddrs:T}=A;if(T.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${G}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}m[G]||(m[G]=[]),m[G]=m[G].concat(T)}}let g={};for(let A of e){let{rel8nName:G,ibGibs:T}=A;if(T.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${G}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}g[G]||(g[G]=[]),g[G].push(...T.map($=>I({ibGib:$})))}let y=await ie({src:u,rel8nsToRemoveByAddr:m,rel8nsToAddByAddr:g,dna:!i,nCounter:!0}),w=y.newIbGib;return await n.persistTransformResult({resTransform:y,space:a}),r&&await uc({type:r.type,rel8nInfos:[{rel8nName:r.rel8nName,ibGibs:[w]}],metaspace:n,space:a,skipLock:s}),await n.registerNewIbGib({ibGib:w,space:a}),w},"fn");return s?await d():await pt({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:a,callerInstanceId:ft(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{et&&console.log(`${c} complete.`)}}h(pc,"appendToTimeline");async function uc({type:o,rel8nInfos:e,dataToAddOrPatch:t,metaspace:r,space:n,skipLock:a}){let s=`[${uc.name}]`;try{if(et&&console.log(`${s} starting... (I: 6e7d05fe916d813b71766e2eaa747c25)`),o==="latest")throw new Error('cannot update the "latest" special index by this function. The registerNewIbGib will do this automatically. (E: 231eb78a221ccdbcf56cd1899260a425)');if(n??=await r.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 43067821a4749a7648fe2612d25d7f25)");let i=h(async()=>{let c=h(async()=>{let l=await r.getSpecialIbGib({type:o,space:n,initialize:!0});if(!l)throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${o}. (E: 41044cf0527850b2eb6a10f501be0a26)`);return l.rel8ns||console.warn(`${s} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`),l},"fnGetSpecialIndex");for(let l of e??[]){let{rel8nName:d,ibGibs:f}=l;f.length===0&&console.error(`${s} ibGibs empty. skipping rel8nName (${d}). (E: 150d74f73f97aea1b97d173d92c77125)`);let p=(await c()).rel8ns??{},u,m=p[d]??[];if(m.length>0){let g=new Set;f.forEach(y=>{let w=I({ibGib:y}),A=y.rel8ns?.past??[];m.filter(G=>[...A,w].includes(G)).forEach(G=>g.add(G))}),g.size>0&&(u=Array.from(g))}await r.rel8ToSpecialIbGib({type:o,rel8nName:d,ibGibsToRel8:f,addrsToUnRel8:u,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(t??{}).length>0){let l=await c(),d=await Ae({src:l,dataToAddOrPatch:t,dna:!1,linkedRel8ns:[Se.past],nCounter:!0}),f=d.newIbGib;await V({resTransform:d,space:n});let b=Me({type:o});await r.setConfigAddr({key:b,addr:I({ibGib:f}),space:n}),await r.registerNewIbGib({ibGib:f,space:n})}},"fn");a?await i():await pt({scope:o,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:i})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{et&&console.log(`${s} complete.`)}}h(uc,"updateSpecialIndex");async function mc({timeline:o,timelineAddr:e,metaspace:t,space:r}){let n=`[${mc.name}]`;try{if(et&&console.log(`${n} starting... (I: f2b605361368e1956f6db878dbfeb825)`),!o&&!e)throw new Error("either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)");e??=I({ibGib:o});let a=await t.getLatestAddr({addr:e,space:r})??e;if(!a)throw new Error(`${n} (UNEXPECTED) Could not get latest address for timeline ${I({ibGib:o})}. (E: 29111bb9f2297eb758c9c4995c75e326)`);let s;if(e===a){if(!o){let i=await t.get({addrs:[a],space:r});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${r.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: 3fc767a594788a43a4ba18c87491a825)`);o=i.ibGibs.at(0)}s=Fe({ibGib:o})}else{let i=await t.get({addrs:[a],space:r});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${r.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: 02a89b36329828a4688bb168b32e1826)`);s=i.ibGibs.at(0)}return s}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{et&&console.log(`${n} complete.`)}}h(mc,"getLatestTimelineIbGibDto_nonLocking");async function gu({timeline:o,timelineAddr:e,mut8Opts:t,metaspace:r,space:n,skipLock:a,timelineIndexInfo:s,noDna:i}){let c=`[${gu.name}]`;try{if(et&&console.log(`${c} starting... (I: d7a213762ad8c52bd9adb9d1f8c42826)`),!o&&!e)throw new Error("(UNEXPECTED) both timeline and timelineAddr falsy? either one is required. (E: a19d98c6acb87af3b876c1484f6ac825)");if(n??=await r.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: c862f9af3bd87c68c8bf19d8d5f2b926)");if(!o){let b=await r.get({addrs:[e],space:n});if(!b.success||b.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${e}) in space (${n?.ib??"undefined"}) (E: 36e9d8bbce886c832e5c88eb1d7fa926)`);o=b.ibGibs.at(0)}let l=await hc({timeline:o}),d=h(async()=>{if(!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");if(!o)throw new Error("(UNEXPECTED) timeline falsy? we should be ensured that it's truthy at this point. (E: 2e1758b2cc3820531f7ac7f5f6b3a825)");let b=await mc({timeline:o,metaspace:r,space:n}),p=await Ae({...t,src:b,dna:!i,nCounter:!0}),u=p.newIbGib;return await r.persistTransformResult({resTransform:p,space:n}),s&&await uc({type:s.type,rel8nInfos:[{rel8nName:s.rel8nName,ibGibs:[u]}],metaspace:r,space:n,skipLock:a}),await r.registerNewIbGib({ibGib:u,space:n}),u},"fn");return a?await d():await pt({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:ft(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{et&&console.log(`${c} complete.`)}}h(gu,"mut8Timeline");async function gc({ib:o,data:e,rel8ns:t,noDna:r,parentIb:n,parentIbGib:a,metaspace:s,space:i}){let c=`[${gc.name}]`;try{if(et&&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=H.primitive({ib:n}):a=ue;let l=await H.firstGen({parentIbGib:a,ib:o,data:e,rel8ns:t,dna:!r,nCounter:!0,squash:!!r,tjp:{timestamp:!0,uuid:!e?.uuid}});return await s.persistTransformResult({resTransform:l,space:i}),await s.registerNewIbGib({ibGib:l.newIbGib,space:i}),l}catch(l){throw console.error(`${c} ${E(l)}`),l}}h(gc,"createTimeline");async function db({ibGib:o,metaspace:e,space:t}){let r=`[${db.name}]`;try{if(et&&console.log(`${r} starting...`),t??=await e.getLocalUserSpace({lock:!1}),!t)throw new Error("(UNEXPECTED) space is required. (E: b2659c7f0dd88b7c2857c2186987ce26)");let n=o.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=>I({ibGib:c})===i));throw new Error(`Could not get all dna ibGibs for ${I({ibGib:o})}. Addrs not found: ${s.join(", ")}. Errors: ${a.errorMsg??"[unknown error (E: 92cf95774828d8a978331da859098625)]"} (E: e87cf84c86e326b0583fa048dc5ec826)`)}return a.ibGibs}catch(n){throw console.error(`${r} ${E(n)}`),n}}h(db,"getDna");async function Ja({timeline:o,getLatest:e,includeDna:t,metaspace:r,space:n}){let a=`[${Ja.name}]`;try{if(et&&console.log(`${a} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await r.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: af874893b9f6c6a1c8723098f235a826)");let s=e?await mc({timeline:o,metaspace:r,space:n}):Fe({ibGib:o}),i=I({ibGib:s}),c={},l=t?Ga({ibGibs:await db({ibGib:s,metaspace:r,space:n})}):void 0,d=o.rel8ns?.past??[];if(d.length===0)return{headIbGib:s,orderedPastIbGibs:[],pastIbGibMap:c,dnaMap:l};let f=await r.get({addrs:d,space:n});if(!f.success||(f.ibGibs??[]).length!==d.length){let p=d.filter(u=>!f.ibGibs?.some(m=>I({ibGib:m})===u));throw new Error(`Could not get all dna ibGibs for ${i}. Addrs not found: ${p.join(", ")}. Errors: ${f.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=Ga({ibGibs:f.ibGibs})??{};let b=[];for(let p of d){let u=c[p];if(!u)throw new Error("(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)");b.push(u)}return{headIbGib:s,orderedPastIbGibs:b,pastIbGibMap:c,dnaMap:l}}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{et&&console.log(`${a} complete.`)}}h(Ja,"getHistory");async function Ec({timeline:o,getLatest:e,metaspace:t,space:r}){let n=`[${Ec.name}]`;try{return et&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await Ja({timeline:o,getLatest:e,includeDna:!1,metaspace:t,space:r})).orderedPastIbGibs.map(i=>I({ibGib:i}))}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{et&&console.log(`${n} complete.`)}}h(Ec,"getHistoryAddrs");var Eu="push",wu="pull",yu="sync",wc={push:Eu,pull:wu,sync:yu},N4=Object.values(wc);var $u="sender",Iu="receiver",Za={sender:$u,receiver:Iu},D4=Object.values(Za);var In=!1;async function Au({data:o}){if(!o.conflictStrategy)throw new Error("(UNEXPECTED) data.conflictStrategy required for GraftInfoIb (E: 2c0968a0dac8d0ab3d67da9756d6df26)");if(!Ka(o.conflictStrategy))throw new Error(`invalid data.conflictStrategy (${o.conflictStrategy}). valid conflict strategies: ${Wr} (E: 41e2680089786d4d28046b4c0884bd26)`);return[Io,o.conflictStrategy].join(" ")}h(Au,"getGraftInfoIb");async function An({conflictStrategy:o,details:e,addlGraftDetails:t,latestCommonFrameAddr:r,baseAddrsSinceLCA:n,orphanAddrsSinceLCA:a,dnaAddrsApplied:s}){let i=`[${An.name}]`;try{if(In&&console.log(`${i} starting... (I: 0030f62cbae28cf5882f87981edc3826)`),n.length===0)throw new Error("(UNEXPECTED) baseAddrsSinceLCA empty? (E: 005f8449a9236d445902a148f59fc826)");if(a.length===0)throw new Error("(UNEXPECTED) orphanAddrsSinceLCA empty? (E: 19e4082e82c67759c880392aca186826)");let c={conflictStrategy:o,description:e};t&&(c.addlGraftDetails=t);let l={[ib]:[r],[cb]:n.concat(),[za]:a.concat(),[lb]:s.concat()},d=await Au({data:c});return await H.stone({parentPrimitiveIb:Io,ib:d,data:c,rel8ns:l,uuid:!0})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{In&&console.log(`${i} complete.`)}}h(An,"createGraftInfo");async function fb({textA:o,textB:e}){if(o===e)return o;if(o==="")return e;if(e==="")return o;function t(l,d){let f=l.length,b=d.length,p=Array(f+1).fill(0).map(()=>Array(b+1).fill(0));for(let y=1;y<=f;y++)for(let w=1;w<=b;w++)l[y-1]===d[w-1]?p[y][w]=p[y-1][w-1]+1:p[y][w]=Math.max(p[y-1][w],p[y][w-1]);let u=f,m=b,g=[];for(;u>0&&m>0;)l[u-1]===d[m-1]?(g.unshift({line:l[u-1],indexA:u-1,indexB:m-1}),u--,m--):p[u-1][m]>p[u][m-1]?u--:m--;return g}h(t,"longestCommonSubsequence");let r=o.split(`
|
|
31
|
+
`),n=e.split(`
|
|
32
|
+
`),a=t(r,n),s=[],i=0,c=0;for(let l of a){for(;i<l.indexA;)s.push(r[i]),i++;for(;c<l.indexB;)s.push(n[c]),c++;s.push(l.line),i++,c++}for(;i<r.length;)s.push(r[i]),i++;for(;c<n.length;)s.push(n[c]),c++;return s.join(`
|
|
33
|
+
`)}h(fb,"mergeTextByLongestCommonSubsequence");function yc(o){let e=`[${yc.name}]`;try{if(In&&console.log(`${e} starting... (I: fe9adfe1a3175d87982507c8851f5826)`),!o)throw new Error("(UNEXPECTED) not a graft info, ibGib falsy? (E: bf06cdd700788e777f72fe5a5bdb0e26)");if(!o.data)throw new Error("not a graft info, ibGib.data falsy (E: 5e1b28843ec8571a7623046a06195826)");if(!o.ib.startsWith(Io))throw new Error(`not graft info, ibgib.ib does not start with ${Io} (E: cec6a8e25ff8746aef813e38cbebce26)`);return!0}catch(t){return In&&console.error(`${e} ${E(t)}`),!1}finally{In&&console.log(`${e} complete.`)}}h(yc,"isGraftInfo");var Le=!1;async function $c({data:o}){let e=`[${$c.name}]`;try{return[Ya,o.uuid].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}}h($c,"getSyncIb");async function bb(){return`tmp_sync_space_${(await q()).substring(0,8)}`}h(bb,"getTempSpaceName");async function Ao({olderAddr:o,newerAddr:e,space:t}){let r=`[${Ao.name}]`;try{if(Le&&console.log(`${r} starting... (I: 4b3548cbc9a2eb749f447ed82fdcf826)`),o===e)return!0;let n,a=await z({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(`${r} newerIbGib.rel8ns falsy? newerAddr: ${e}. (W: 6f920811f7080281189f767813814826)`),!1;let s=n.rel8ns.past??[];if(s.length===0)return!1;if(s.includes(o))return!0;let i=s[0];return await Ao({olderAddr:o,newerAddr:i,space:t})}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Le&&console.log(`${r} complete.`)}}h(Ao,"isPastFrame");async function Kr({sagaIbGib:o,localSpace:e}){let t=`[${Kr.name}]`,r=h(async i=>{let c=await z({space:e,addrs:i});if(c.success&&c.ibGibs?.length===i.length)return c.ibGibs;{let l=c.rawResultIbGib;throw l.data?new Error(`(UNEXPECTED) couldn't find addrs? addrsNotFound: ${l.data.addrsNotFound}? space.ib: ${e.ib} (E: 43b7b5a6ad982715c8f3eed69bfa0d26)`):new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: c26c681d2f831fc537ba6f48fee36d26)")}},"fnGet"),n=await Qa({sagaIbGib:o});if(n.length>0)throw new Error(`invalid sync sagaIbGib. validationErrors: ${n} (E: 19f9e8c9643858ff41312b62293d2126)`);if(!o.rel8ns)throw new Error("(UNEXPECTED) validated sagaIbGib.rel8ns falsy? (E: 73af48be8bbf271ec5cf78187ce8c826)");let a=o.rel8ns[Ke],s=await r(a);return{sagaIbGib:o,msgStones:s}}h(Kr,"getSyncSagaFrameDependencyGraph");async function _o({sagaIbGib:o,space:e}){let t=`[${_o.name}]`;try{if(Le&&console.log(`${t} starting... (I: 1ea3f804dd07d1e917a2afaaad497826)`),!o.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: fe0a0d0965e87ac852fe7ba4710cc826)");if(!o.rel8ns)throw new Error("(UNEXPECTED) sagaIbGib.rel8ns falsy? (E: b79ff82a732346bdf8a9e1eb9ac96826)");let r=I({ibGib:o}),n=o.rel8ns.past&&o.rel8ns.past.length>0?[...o.rel8ns.past,r]:[r],a=[];for(let s of n){let i,c=await z({addr:s,space:e});if(c.success&&c.ibGibs&&c.ibGibs.length===1)i=c.ibGibs[0];else throw Le&&console.log(`${t} failed getting full history of sagaIbGib:
|
|
34
|
+
${X(o)} (I: 2a35685bfe038f63182c7db39b44c826)`),new Error(`couldn't get saga addr (${s}) from space (${e.ib}) (E: 865b78ecd918c244158813650bea7d26)`);let l=await Kr({sagaIbGib:i,localSpace:e});a.push(l)}return a}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Le&&console.log(`${t} complete.`)}}h(_o,"getFullSyncSagaHistory");async function Qa({sagaIbGib:o}){let e=`[${Qa.name}]`;try{Le&&console.log(`${e} starting... (I: dac978e9ec5820f128fbbff817b82826)`);let t=await ne({ibGib:o})??[];if(t.length>0)return t;if(o.data){let{data:r}=o;r.uuid||t.push("data.uuid required (E: aa24eeda7b88d22e5832a2e8083c0826)"),r.timestamp||t.push("data.timestamp required (E: 9c82a88548f4b63c38687428754b3826)"),r.timestampMs||r.timestampMs===0||t.push("data.timestampMs required (E: 9c82a88548f4b63c38687428754b3826)"),r.conflictStrategy?Ka(r.conflictStrategy)||t.push(`data.conflictStrategy (${r.conflictStrategy}) is invalid. Must be one of "${Wr}". (E: 6223a8813b688fa2c8644fa8a491bf26)`):t.push("data.conflictStrategy required (E: 9c82a88548f4b63c38687428754b3826)"),r.expirationTimestamp,r.errors,r.successCount}else t.push("sagaIbGib.data falsy (E: 4de5e8de589d0af7245600fb4fe30926)");if(o.rel8ns){let r=o.rel8ns[Ke];r&&r.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} ${E(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}h(Qa,"validateSyncSagaFrame");async function es({history:o}){let e=`[${es.name}]`;try{return Le&&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} ${E(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}h(es,"validateFullSyncSagaHistory");async function wr({ibGibs:o,space:e}){let t=`[${wr.name}]`;try{Le&&console.log(`${t} starting... (I: aa3ab828402836b3914800a8ffa1b826)`);let r=[],n=[];for(let a of o)Ce({ibGib:a})||(ko({ibGib:a})?r.push(a):n.push(a));return r.length>0&&await ce({ibGibs:r,isDna:!0,space:e}),n.length>0&&await ce({ibGibs:n,isDna:!1,space:e}),{payload_Dnas:r,payload_NonDnas:n}}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Le&&console.log(`${t} complete.`)}}h(wr,"putInSpace_dnasThenNonDnas");function To({sagaFrame:o}){let e=`[${To.name}]`;try{if(Le&&console.log(`${e} starting... (I: 93521332d0dd2f5e88398b7db95e8126)`),!o)throw new Error("(UNEXPECTED) sagaFrame falsy? (E: 01fb28be6668d88ea49bb298c739c926)");if(!o.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 998298eb17685bdb9a85b46488ccd826)");if(!o.data.n&&o.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 0394919d5b58300ceb09ba6a264ad826)");let t=o.data.n%2;if(t===0)return Za.sender;if(t===1)return Za.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} ${E(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}h(To,"getSyncSagaFrameOrigin");async function ts({sagaHistory:o}){let e=`[${ts.name}]`;try{Le&&console.log(`${e} starting... (I: fe93a8f29e5d8ab2c8bd0e08e56f7826)`);let t=o.findLast(a=>a.msgStones.some(s=>s.data.stage===_e.delta));if(!t)throw new Error("(UNEXPECTED) no delta frame? What are we calling this function for? (E: 9b3201207908f79868b93cd893a91626)");let r=t.msgStones.filter(a=>a.data.stage===_e.delta);if(r.length>1)throw new Error("(UNEXPECTED) multiple delta stones in history slice? we're expecting a single delta stone per saga frame. (E: a4bd5860b4aa0743753d4798d3163826)");return r[0].data.conflicts}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Le&&console.log(`${e} complete.`)}}h(ts,"getFinalConflictsInfo");async function Ic({sagaHistory:o,myTempSpace:e}){let t=`[${Ic.name}]`;try{Le&&console.log(`${t} starting... (I: b755627e99c9a221566d86a81b0da526)`);let r=await ts({sagaHistory:o});if(!r||r.length===0)return Le&&console.log(`${t} no conflicts found. returning empty array (I: 5dce98010128a284c8ec92cd466a3826)`),[];let n=[];for(let a of r){if(!a.resolved)throw new Error("(UNEXPECTED) conflict.resolved falsy? we're expecting all conflicts to be resolved when getting orphaned addresses. (E: 3861e89a18c8ff405eb2117f6d4b9b26)");if(!a.graftInfoAddr)throw new Error("(UNEXPECTED) conflict.graftInfoAddr falsy? we're expecting a resolved conflict whose final ibgib (graft tip) was the graft info and for this addr to be in conflict.graftInfoAddr. (E: 80d86e333028585908f4757bc4d6f826)");let s=await Ve({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(!yc(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[za];if(!c||c.length===0)throw new Error(`(UNEXPECTED) orphanedAddrs empty for conflict graftInfo (${a.graftInfoAddr})? we're expecting a graft to always necessarily orphan one or other branches, otherwise what are we "grafting"? (E: 3ed1284f6ca84754582801484d751926)`);c.forEach(l=>n.push(l))}return n}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Le&&console.log(`${t} complete.`)}}h(Ic,"getAllOrphanedAddresses");async function _n({senderSecret:o,sagaId:e}){let t=`[${_n.name}]`;try{if(Le&&console.log(`${t} starting... (I: 0de03f8dcd3e32f1fca244e8f2a8a826)`),!o)throw new Error("(UNEXPECTED) senderSecret falsy? (E: 8ce053fe59825a6678713128953b9d26)");if(!e)throw new Error("(UNEXPECTED) sagaId falsy? (E: 3a17e0c1b2f849de8a42cd15b8ee6826)");return await xi({masterSecret:o,kdfOpts:{strategy:en.recursive_salt_wrap,salt:e,rounds:1e4,algorithm:"SHA-256"}})}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Le&&console.log(`${t} complete.`)}}h(_n,"deriveSessionSecret");var rs="sync_sagamsg";async function Ac({data:o}){let e=`[${Ac.name}]`;try{return[rs,o.sagaId,o.stage].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(Ac,"getSyncSagaMessageIb");async function _c({frameIbGib:o,space:e}){let t=`[${_c.name}]`;try{let n=(await Ai({ibGib:o,rel8nNames:[Ke],space:e}))[Ke];if(!n||n.length===0)throw new Error(`(UNEXPECTED) No sync message stone found found for frame: ${o.ib} (E: f9fa2ec64bc84191687609080373c826)`);if(n.length>1)throw new Error(`(UNEXPECTED) Multiple sync message stones found (${n.length}) for frame: ${o.ib}. logic not currently equipped to handle multiple messages per frame. (E: a9876fdd114f0109cdafbb08f79ca826)`);return n[0]}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(_c,"getSyncSagaMessageFromFrame");var os="sync_sagacontext";var Tn=!1;async function Tc({data:o}){let e=`[${Tc.name}]`;try{if(!o)throw new Error("data required (E: 839d82138c234b3e89582855594191fe)");let t=o["@payloadAddrsDomain"]?o["@payloadAddrsDomain"].length:0;return[os,o.sagaN,t].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}}h(Tc,"getSyncSagaContextIb");async function Go({context:o}){let e=`[${Go.name}]`;try{Tn&&console.log(`${e} starting... (I: 7797f8294bd8f7e5089cb722ad468226)`);let t=[],r=await ne({ibGib:o});if(r&&r.length>0)return r.forEach(n=>t.push(n)),t;if(o.sagaFrame?(await Qa({sagaIbGib:o.sagaFrame})).forEach(a=>t.push(a)):t.push("context.sagaFrame is falsy. (E: b4edd88f4963f493789f83b29ba2df26)"),o.sagaFrameMsg){if((await ne({ibGib:o.sagaFrameMsg})??[]).forEach(a=>t.push(a)),o.sagaFrame){let a=o.sagaFrame.rel8ns?.[Ke]?.[0];if(a){let s=I({ibGib:o.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:[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Tn&&console.log(`${e} complete.`)}}h(Go,"validateContextAndSagaFrame");async function Gc({context:o,space:e}){let t=`[${Gc.name}]`;try{Tn&&console.log(`${t} starting... (I: 3c34e8f1d6ef965f98725c88459ea926)`);let r=[];if(!o.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 3e4ddd0eb4b828ad489658d88d9a6326)");if(!o.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 8026589d4fed69c828334ee842074326)");let{sagaFrame:n,signedSessionIdentity:a}=o;if(!n.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: b61cc82d25984c92f75db74a5a855b26)");if(!a)return console.error(`${t}[NAG] (NOT THROWN) sagaFrame.data.sessionIdentityTjpAddr logic needs to be added in coordinator (E: 4fc47800a1086c917a47381824280826)`),n.data.sessionIdentityTjpAddr?(r.push("Context has no session identity, but sync saga frame shows a session identity (sagaFrame.data.sessionIdentityTjpAddr is truthy). (E: 69dd6cdc2e1859c0f3d62958c4339826)"),r):o.rel8ns.sessionIdentity?(r.push("Context has no signed session identity, but context.rel8ns.sessionIdentity is truthy. (E: 96a04a8a6c88ea8bf88118f89ad8e326)"),r):(Tn&&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=I({ibGib:a}),i=o.rel8ns?.sessionIdentity??[];if(i.length===0)return r.push("context.rel8ns.sessionIdentity is falsy/empty but context.signedSessionIdentity is present. (E: 66f906421eb2468c0b33f908a3cf2826)"),r;if(i.length>1)return r.push("context.rel8ns.sessionIdentity has multiple identity addrs. (E: 489428bfe6fdaa4cd885b938dc4c5826)"),r;let c=i[0],l=await ve({addrs:[c],space:e});if(!l)throw new Error(`(UNEXPECTED) resGetLatestAddr for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 7b207e5cbcec9037ea5adbe822ead826)`);if(!l.data)throw new Error(`(UNEXPECTED) resGetLatestAddr.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: de4eb8d730c8c4dcb59c8b9c79277826)`);if(!l.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr.data.success falsy? (E: c94298dfd9684ad6a87eb748459aa826)");let{latestAddrsMap:d}=l.data;if(!d)throw new Error("(UNEXPECTED) resGetLatestAddr.data.latestAddrsMap falsy? (E: 19f1fd5fe798cf2e5fa923919169d826)");if(Object.keys(d).length!==1)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap).length !== 1? (E: fe526a0747589c6427a8bcc86da34a26)");let f=d[c];if(!f)return r.push(`prevSessionIdentityAddr (${c}) not found in space (${e.ib}). this should have been the incoming prevSessionIdentityAddr (E: f6d042bd6b54819998653228dee34226)`),r;if(c!==f&&f!==s)return r.push(`context.rel8ns.sessionIdentity does not point to the most recent in the space (${e.ib}). (E: 2f8288f53c87b6aa47bd2178d9df0c26)`),console.log(`context: ${X(Fe({ibGib:o}))}`),console.log(`prevSessionIdentityAddr (context.rel8ns.sessionIdentity): ${c}`),console.log(`prevSessionIdentityAddr_latest: ${f}`),console.log(`currSessionIdentity (context.signedSessionIdentity): ${X(Fe({ibGib:{ib:a.ib,gib:a.gib,rel8ns:a.rel8ns,data:{...a.data,challengePools:a.data.challengePools.map(U=>({...U,challenges:{}}))}}}))}`),console.log(`currSessionIdentityAddr: ${s}`),r;let b=await z({addr:c,space:e});if(!b.success||b.ibGibs?.length!==1)return r.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: fd48c3e64c9fa4efd8a1f8280af18226)`),r;let p=b.ibGibs[0],u=await Ko({ibGib:p,naive:!0,space:e});if(!u)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=I({ibGib:u});if(m!==n.data.sessionIdentityTjpAddr)throw new Error("(UNEXPECTED) sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr? (E: c9a4ad5c2728fe38e86afc58e4abaf26)");let g=u.data.frameDetails;if(!g)return r.push("Invalid session identity tjp: sessionIdentityTjp.data.frameDetails is falsy. (E: 0187f8f804a84256281720586620b826)"),r;let{senderIdentityAddr:y,senderIdentityTjpAddr:w}=g;if(!y)throw new Error("sessionGenesisFrameDetails.senderIdentityAddr falsy (E: 02a0c80a3ead9e3af8af4cf3b156e826)");if(!w)throw new Error("sessionGenesisFrameDetails.senderIdentityTjpAddr falsy (E: 271928090ff5dc56d4bb63d8d5c68826)");let A=await ve({addrs:[w,y],space:e});if(!A)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e4ae8083b6fb7cbb8fae2a519062926)`);if(!A.data)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e231850c2a898cc282b4b2841056826)`);if(!A.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.success falsy? (E: e93508f03e0475925875b00746ffd826)");let{latestAddrsMap:G}=A.data;if(!G)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.latestAddrsMap falsy? (E: 87a91e3f9968ad9ba79cdfe8cd878326)");if(Object.keys(G).length!==2&&w!==y)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr? (E: fe46bd584853d8e1e8e2d11f52012826)");let T=G[w],$=G[y];if(!$)throw new Error("(UNEXPECTED) senderIdentityAddr_latest falsy? (E: e151798ae2e9241578d09948937c4b26)");if(T!==$)throw new Error("senderIdentityTjpAddr_latest !== senderIdentityAddr_latest (E: 52478a1053589e72665031a853cc1826)");let _=await z({addr:$,space:e});if(!_.success||_.ibGibs?.length!==1)return r.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: 3565ff0ed458f5a2384c40b16e849826)`),r;let S=_.ibGibs[0];if(!S.data.proofs)return r.push("Invalid sender identity. Proofs empty/falsy. (E: ebf488853061614d2b5b137828119526)"),r;let D=S.data.proofs.find(U=>U.claim.verb===ut)?.claim;if(!D)return r.push(`Most recent senderIdentity has no proof whose claim.verb === ${ut}. (E: b0f488ecccbbfe43d9a0b7c8a29d7826)`),r;if(D.target!==m)return r.push(`Most recent sender identity claim has claim.verb === ${ut} but DOES NOT target expected session identity addr ${c}. (E: 3e7f18d99848969be8586423d5ccb826)`),r;let N=await new Mt().validate({currentIbGib:a,prevIbGib:p});N.length>0&&r.push(`Invalid session identity transition: ${N.join(", ")} (E: da1c81c6d3c86aec3254f48fe7514226)`);let x=I({ibGib:o});return a.data?.proofs?.some(U=>U.claim.target===x)||r.push(`Session identity signature does not target current context ibgib (${x}). (E: acae68938c287178c878d1b88bebb826)`),r}catch(r){let n=`${t} ${E(r)}`;return console.error(n),[`authentication produced an error: ${n} (E: 45e014b82af81993d936611ca6fc4d26)`]}finally{Tn&&console.log(`${t} complete.`)}}h(Gc,"authenticateContextIntrinsically");var ns="subject",Sc=/^[a-zA-Z0-9_\-.]{1,255}$/,hb="subject",pb="",as="subject is a cool ibgib witness that has seriously fascinating behavior.";var ub="observable";var yr={subscribe:"subscribe"},mb=Object.values(yr);var gb={next:"next",error:"error",complete:"complete"};var $r={...yr,...gb};var Gn={version:"1",uuid:pb,name:hb,description:as,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},xc=void 0;var Eb=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var Ir=!1;function yb({rawMsg:o}){let e=`[${yb.name}]`;try{Ir&&console.log(`${e} starting...`);let t=Cc({rawMsg:o}),r=t.body.replace(/\s/g,"_").replace(/\W/g,""),n;if(r.length>20)n=r.substring(0,20);else if(r.length>0)n=r;else throw new Error("(UNEXPECTED) error msg should have characters/alphanumerics... (E: a3b9cd11a44cc7892a748819c2885422)");return`error ${n} ${t.uuid??"undefined"}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ir&&console.log(`${e} complete.`)}}h(yb,"getErrorIb");function Cc({rawMsg:o}){let e=`[${Cc.name}]`;try{if(Ir&&console.log(`${e} starting...`),!o)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let t,r=o.match(rl);if(r){let[n,a,s,i,c,l]=r;if(!i)throw new Error("invalid error msg body (E: a675e6855cca96519d33d44ea5400922)");t={success:!1,raw:o,body:i?.trim(),uuid:c.slice(4,36)},a&&(t.location=a),(s||l)&&(t.unexpected=!0)}else{t={success:!1,raw:o,body:o};let n=o.match(ol);if(n){let[a,s]=n;t.location=s}o.toLowerCase().includes("(unexpected)")&&(t.unexpected=!0)}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ir&&console.log(`${e} complete.`)}}h(Cc,"parseRawErrorMsg");function zr({rawMsg:o}){let e=`[${zr.name}]`;try{return Ir&&console.log(`${e} starting...`),_t({parentPrimitiveIb:"error",ib:yb({rawMsg:o}),data:Cc({rawMsg:o}),ibRegExpPattern:Eb.source})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ir&&console.log(`${e} complete.`)}}h(zr,"getErrorIbGib");function tr({ibGib:o}){let e=`[${tr.name}]`;try{if(Ir&&console.log(`${e} starting...`),!o)throw new Error("ibGib required (E: 1d756fbbd96f1734b97ba013537ed522)");return o.ib.startsWith("error ")}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ir&&console.log(`${e} complete.`)}}h(tr,"isError");var ss=class o{static{h(this,"WitnessFactoryBase")}lc=`[${o.name}]`};var Nc=!1,So=class o extends ss{static{h(this,"DynamicFormFactoryBase")}lc=`[${o.name}]`;patchDataFromItems({data:e,contextPath:t,items:r,pathDelimiter:n}){let a=`${this.lc}[${this.patchDataFromItems.name}]`;try{if(Nc&&console.log(`${a} starting...`),!n)throw new Error("pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)");for(let s=0;s<r.length;s++){let i=r[s],c=t?t+n+i.name:i.name;if(!i.items)ks({obj:e,value:i.value,path:c,logalot:Nc,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{Nc&&console.log(`${a} complete.`)}}};var $b=!1,Ar=class o{static{h(this,"LightWitnessBase_V1")}lc=`[${o.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 q(),this.gib=await ee({ibGib:this.toIbGibDto()})}toIbGibDto(){return Fe({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return $b&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=B(e.ib),this.gib=B(e.gib),e.data?this.data=B(e.data):delete this.data,e.rel8ns?this.rel8ns=B(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(r){throw console.error(`${t} ${r.message}`),r}finally{$b&&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(r){throw console.error(`${e} ${r.message}`),r}return t}};var Ib="subscription",Dc=/^[a-zA-Z0-9_\-.]{1,255}$/,Ab="",_b="subscription",is="subscription is a cool ibgib witness that has seriously fascinating behavior.";var Sn={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var vc={version:"1",uuid:Ab,name:_b,description:is,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},Pc=void 0;var Tb=!1;function Oc({ibGib:o}){let e=`[${Oc.name}]`;try{Tb&&console.log(`${e} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:t}=o;return[ub,ns].some(n=>t.includes(n))}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Tb&&console.log(`${e} complete.`)}}h(Oc,"isObservable");var de=!1,cs=class o extends Ar{static{h(this,"Subscription_V1")}lc=`[${o.name}]`;metaspace;_subscribed;_unsubscribed;_srcObservable;constructor(e,t){super(e,t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{if(de&&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=ds({data:this.data,classname:"Subscription_V1"}),this.gib=await ee({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{de&&console.log(`${e} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:r}=e;if(!r)throw new Error("arg.ib required (E: 1fd9aebef07b4bdaacc0cd323c8ddf76)");if(de&&console.log(`${t} ib: ${r} (I: 4de7771f477dc5b36933343b694ce223)`),r===Sn.unsubscribe)return de&&console.log(`${t} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(r===Sn.unsubscribed)return de&&console.log(`${t} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if(Oc({ibGib:e}))return de&&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(r){throw console.error(`${t} ${E(r)??"unknown error (E: b0bbaab21833404a9420c3d273df7f21)"}`),r}}async witness_unsubscribe(){let e=`${this.lc}[${this.witness_unsubscribe.name}]`;try{if(de&&console.log(`${e} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${e} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),ue;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),ue;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return de&&(console.log(`${e} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),de&&(console.log(`${e} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,de&&console.log(`${e} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),ue}catch(t){throw console.error(`${e} ${t.message}`),t}finally{de&&console.log(`${e} complete.`)}}async witness_observable({ibGib:e}){let t=`${this.lc}[${this.witness_observable.name}]`;try{if(de&&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,de&&console.log(`${t} this._srcObservable set to ibgib with ib: ${e.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,ue}catch(r){throw console.error(`${t} ${r.message}`),r}finally{de&&console.log(`${t} complete.`)}}async witness_unsubscribed(){let e=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(de&&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?Zs:xl;return de&&console.log(`${e} result: ${X(t)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{de&&console.log(`${e} complete.`)}}async unsubscribe(){let e=`${this.lc}[${this.unsubscribe.name}]`;try{de&&console.log(`${e} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let t=await this.witness(H.primitive({ib:Sn.unsubscribe}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(tr({ibGib:t})){let r=t;throw new Error(`${r.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{de&&console.log(`${e} complete.`)}}async unsubscribed(){let e=`${this.lc}[${this.unsubscribed.name}]`;try{de&&console.log(`${e} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let t=await this.witness(H.primitive({ib:Sn.unsubscribed}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let r=t.ib===Zs.ib;return de&&console.log(`${e} resUnsubscribed: ${r} (I: b4800166c58d5ba2ca1dccaa53de2323)`),r}catch(t){throw console.error(`${e} ${t.message}`),t}finally{de&&console.log(`${e} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return de&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{de&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:r,ibGibs:n}){let a=await Zt({argData:e,ibMetadata:t,noTimestamp:r});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let r=await Qt({resultData:e});return t&&(r.ibGibs=t),r}},ls=class o extends So{static{h(this,"Subscription_V1_Factory")}lc=`[${o.name}]`;getName(){return cs.name}async newUp({data:e,rel8ns:t}){let r=`${this.lc}[${this.newUp.name}]`;try{de&&console.log(`${r} starting...`),e??=B(vc),e=e,t=t??Pc?B(Pc):void 0,e.uuid||=await q();let{classname:n}=e,a=ds({data:e}),s=await _t({parentPrimitiveIb:`witness ${n}`,ib:a,data:e,rel8ns:t}),i=new cs(void 0,void 0);return await i.loadIbGibDto(s),de&&console.log(`${r} witnessDto: ${X(s)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:i}}catch(n){throw console.error(`${r} ${E({error:n})}`),n}finally{de&&console.log(`${r} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{de&&console.log(`${t} starting...`);let{data:r}=e;if(!r)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");de&&console.log(`${t} data: ${X(r)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await Mo({n:100}),a=new fs().with({idPool:n}).name({of:r.name,required:!1}).description({of:r.description??is}).and().and().uuid({of:r.uuid,required:!0}).classname({of:r.classname}).and().commonWitnessFields({data:r}).outputForm({formName:"form",label:"subscription"});return Promise.resolve(a)}catch(r){throw console.error(`${t} ${E({error:r})}`),r}finally{de&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=B(vc);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:to}),await this.newUp({data:t})}};var bs=!1;function Gb({data:o}){let e=`[${Gb.name}]`;try{if(bs&&console.log(`${e} starting...`),!o)throw new Error("Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)");let t=[],{name:r,uuid:n,classname:a}=o;return r?r.match(Dc)||t.push(`name must match regexp: ${Dc} (E: 21bf77e398d47e9d035376510505eda2)`):t.push("name required."),n?n.match(Ie)||t.push(`uuid must match regexp: ${Ie} (E: e53fd08ae69e945b37ed895b864b6bd7)`):t.push("uuid required."),a&&(a.match(ar)||t.push(`classname must match regexp: ${ar}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{bs&&console.log(`${e} complete.`)}}h(Gb,"validateCommonSubscriptionData");function ds({data:o,classname:e}){let t=`[${ds.name}]`;try{let r=Gb({data:o});if(r.length>0)throw new Error(`invalid Subscription data: ${r} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`);if(e){if(o.classname&&o.classname!==e)throw new Error("classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)")}else if(e=o.classname,!e)throw new Error("classname required (E: 040c1fd71853fa7874146999afb355c3)");let{uuid:n}=o;return`witness ${Ib} ${e} ${n}`}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(ds,"getSubscriptionIb");var fs=class o extends br{static{h(this,"SubscriptionFormBuilder")}lc=`[${o.name}]`;constructor(){super(),this.what="subscription"}};function hs({ibGib:o}){let e=`[${hs.name}]`;try{if(bs&&console.log(`${e} starting... (I: 43df7e7f61f25e65662ce8aa5a105a23)`),!o)return!1;let t=o;return typeof t.witness=="function"&&typeof t.unsubscribe=="function"&&typeof t.unsubscribed=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{bs&&console.log(`${e} complete.`)}}h(hs,"isSubscription");async function Sb(){return(await new ls().newUp({})).newIbGib}h(Sb,"newupSubscription");var Lc="observable_event";var xb=!1;async function Rc({eventType:o,srcObservable:e,payload:t}){let r=`[${Rc.name}]`;try{if(xb&&console.log(`${r} 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(Ie))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${Ie.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await q(),eventType:o,srcObservableId:e.data.uuid,"@srcObservableAddr":I({ibGib:e}),"@payloadAddr":I({ibGib:t})};return await _t({parentPrimitiveIb:Lc,ib:Cb({data:n}),data:n})}catch(n){throw console.error(`${r} ${n.message}`),n}finally{xb&&console.log(`${r} complete.`)}}h(Rc,"getObservableEventIbGib");function Cb({data:o,classname:e}){let t=`[${Cb.name}]`;try{if(e){if(o.classname&&o.classname!==e)throw new Error("classname does not match data.classname (E: 523aabc53fb944789202a5f468abd338)")}else if(e=o.classname,!e)throw new Error("classname required (E: d4401ea682894c5fa824b38d4989aa76)");if(!o.uuid)throw new Error("data.uuid required (E: 204cc7c20efd8a55263cdea8b1223e23)");return`${Lc} ${e} ${o.uuid}`}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(Cb,"getObservableEventIb");var xe=!1,ps=class o extends Ar{static{h(this,"ObservableBase_V1")}lc=`[${o.name}]`;metaspace;_subscribers={};_isComplete=!1;_pastPayloads=[];_pastError;get isCompleteOrErrored(){return this._isComplete||!!this._pastError}get isComplete(){return this._isComplete}get isErrored(){return!!this._pastError}constructor(e,t){super(e,t)}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:r}=e;if(!r)throw new Error("arg.ib required (E: 87659d093b82436ce2f7a87e402a5423)");if(zi({ibGib:e}))return this.witness_cmd({arg:e});if(Ji({ibGib:e}))return this.witness_otherWitness({arg:e});throw new Error("unknown arg. expect observable cmd or ibgib witness (E: dc2667cffac5b8d7b1bf2ea737c81a23)")}catch(r){throw console.error(`${t} ${E(r)??"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),r}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{if(xe&&console.log(`${t} starting... (I: 69257fac8328b9de9755fdd237b92723)`),e.data.cmd===yr.subscribe)return this.witness_subscribe_cmd({ibGib:e});throw new Error(`unknown command. must be of type ObservableCmd (${mb}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(r){throw console.error(`${t} ${r.message}`),r}finally{xe&&console.log(`${t} complete.`)}}async witness_otherWitness({arg:e}){let t=`${this.lc}[${this.witness_otherWitness.name}]`;try{return xe&&console.log(`${t} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),hs({ibGib:e})?this.witness_subscriptionIbGib({arg:e}):this.witness_subscribe_nonCmdWitness({arg:e})}catch(r){throw console.error(`${t} ${r.message}`),r}finally{xe&&console.log(`${t} complete.`)}}async witness_subscriptionIbGib({arg:e}){let t=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(xe&&console.log(`${t} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`),!e.data)throw new Error("arg.data required (E: 764ae772727ceba95a18140fdd938323)");let r=this.getSubscriberKey({subscription:e}),[n,a]=this._subscribers[r];if(e===n)delete this._subscribers[r];else throw new Error("(UNEXPECTED) arg and subscription are two different instances? (E: aab5ef9bdc92abb9e816e2c443ab5723)");return ue}catch(r){throw console.error(`${t} ${r.message}`),r}finally{xe&&console.log(`${t} complete.`)}}async replayPastPayloads({observer:e,subscription:t}){let r=`${this.lc}[${this.replayPastPayloads.name}]`;try{xe&&console.log(`${r} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`);let n=this.getSubscriberKey({subscription:t}),a=h(()=>!!this._subscribers[n],"fnStillSubscribed"),s=-1,i=!0;do if(s++,s<this._pastPayloads.length){if(!a()){xe&&console.log(`${r} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`);return}try{let c=this._pastPayloads[s];await e.next(c)}catch{console.error(`${r} observer errored on payload (i: ${s}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`);return}}else i=!1;while(i);if(this.isErrored&&e.error&&a())try{await e.error(this._pastError)}catch{console.error(`${r} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`)}else if(this.isComplete&&e.complete&&a())try{await e.complete()}catch{console.error(`${r} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`)}}catch(n){throw console.error(`${r} ${n.message}`),n}finally{xe&&console.log(`${r} complete.`)}}async witness_subscribe_cmd({ibGib:e}){let t=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(xe&&console.log(`${t} starting... (I: 0c4c75c3fae297af6449c1048ce55423)`),(e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one ObserverWitness (E: 3ed99b32e22284573c497df788a9f923)");let r=e.ibGibs[0],n=await Sb();return xe&&console.log(`${t} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,xe&&console.log(`${t} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,r],xe&&console.log(`${t} stored subscriber (subscription, observer) (I: fb09660d885e33b80188dd0386ffc723)`),this.data.replay&&this._pastPayloads.length>0&&this.replayPastPayloads({observer:r,subscription:n}),n}catch(r){throw console.error(`${t} ${r.message}`),r}finally{xe&&console.log(`${t} complete.`)}}async witness_subscribe_nonCmdWitness({arg:e}){let t=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw xe&&console.log(`${t} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(r){throw console.error(`${t} ${r.message}`),r}finally{xe&&console.log(`${t} complete.`)}}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{xe&&console.log(`${t} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let r;if(Jr({ibGib:e})){let n=await this.argy({argData:{cmd:yr.subscribe,ibGibAddrs:[I({ibGib:e})]},ibGibs:[e]});r=await this.witness(n)}else r=await this.witness(e);if(!hs({ibGib:r}))throw new Error("(UNEXPECTED) resSubscription is not a SubscriptionWitness? (E: c29bec4e3a48d6f1299143399ac55a23)");return r}catch(r){throw console.error(`${t} ${r.message}`),r}finally{xe&&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:r}){let n=`${this.lc}[${this.dispatchToEachSubscriber.name}]`;try{xe&&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(Jr({ibGib:c})){let l=c;await t(l,e),l.complete?await i.unsubscribed()?console.warn(`${n} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`):await l.complete():xe&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let l=await Rc({eventType:r,srcObservable:this,payload:e});await c.witness(l)}}}catch(a){throw console.error(`${n} ${a.message}`),a}finally{xe&&console.log(`${n} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return xe&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:r,ibGibs:n}){let a=await Zt({argData:e,ibMetadata:t,noTimestamp:r});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let r=await Qt({resultData:e});return t&&(r.ibGibs=t),r}};var he=!1,us=class o extends ps{static{h(this,"Subject_V1")}lc=`[${o.name}]`;constructor(e,t){super(e,t)}asObservable(){return this}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{he&&console.log(`${t} starting... (I: 8e47b752314870ec78eb14342621f723)`);let r=await this.argy({argData:{cmd:$r.subscribe,ibGibAddrs:[I({ibGib:e})]},ibGibs:[e]});return await this.witness(r)}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async next(e){let t=`${this.lc}[${this.next.name}]`;try{he&&console.log(`${t} starting... (I: b30363827c56450ca918c69aa15b0046)`);let r=await this.argy({argData:{cmd:$r.next,ibGibAddrs:[I({ibGib:e})]},ibGibs:[e]});await this.witness(r)}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async error(e){let t=`${this.lc}[${this.error.name}]`;try{he&&console.log(`${t} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let r;if(typeof e=="string")r=await zr({rawMsg:e});else if(e instanceof Error||typeof e.message=="string")r=await zr({rawMsg:E(e)});else if(e.ib&&tr({ibGib:e}))r=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:$r.error,ibGibAddrs:[I({ibGib:r})]},ibGibs:[r]});await this.witness(n)}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async complete(){let e=`${this.lc}[${this.complete.name}]`;try{he&&console.log(`${e} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let t=await this.argy({argData:{cmd:$r.complete}});await this.witness(t)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{he&&console.log(`${e} complete.`)}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{he&&console.log(`${t} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:r}=e.data;switch(r){case $r.next:return this.witness_next({ibGib:e});case $r.error:return this.witness_error({ibGib:e});case $r.complete:return this.witness_complete({ibGib:e});default:return super.witness_cmd({arg:e})}}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async witness_next({ibGib:e}){let t=`${this.lc}[${this.witness_next.name}]`;try{if(he&&console.log(`${t} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return he&&console.log(`${t} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),ue;if((e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one payload ibgib (E: 4046802ff96d4adfafcee7a74d96af5e)");let r=e.ibGibs[0];this.data.replay&&this._pastPayloads.push(r);let n=Object.values(this._subscribers);for(let a=0;a<n.length;a++){let[s,i]=n[a];if(he&&console.log(`${t} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await s.unsubscribed())he&&console.log(`${t} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`),await i.next(r);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 ue}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async witness_error({ibGib:e}){let t=`${this.lc}[${this.witness_error.name}]`;try{if(he&&console.log(`${t} starting... (I: 3367a73bc83c47f98d9ecfe426dc300e)`),(e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one error ibgib (E: 905474b45bcb4f0abe7bd4618f08f32c)");let r=e.ibGibs[0];this._pastError=r;let n=Object.values(this._subscribers);for(let a=0;a<n.length;a++){let[s,i]=n[a];if(Jr({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(r):he&&console.log(`${t} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await i.witness(r)}return ue}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async witness_complete({ibGib:e}){let t=`${this.lc}[${this.witness_complete.name}]`;try{he&&console.log(`${t} starting... (I: 4db180f465e24df9a4ded37fbd235558)`),this._isComplete=!0;let r=Object.values(this._subscribers);for(let n=0;n<r.length;n++){let[a,s]=r[n];if(Jr({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():he&&console.log(`${t} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await s.witness(e)}return ue}catch(r){throw console.error(`${t} ${r.message}`),r}finally{he&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return he&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{he&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:r,ibGibs:n}){if(e.cmd===yr.subscribe)return super.argy({argData:e,ibMetadata:t,noTimestamp:r,ibGibs:n});{let a=await Zt({argData:e,ibMetadata:t,noTimestamp:r});return n&&(a.ibGibs=n),a}}async resulty({resultData:e,ibGibs:t}){let r=await Qt({resultData:e});return t&&(r.ibGibs=t),r}},ms=class o extends So{static{h(this,"Subject_V1_Factory")}lc=`[${o.name}]`;getName(){return us.name}async newUp({data:e,rel8ns:t}){let r=`${this.lc}[${this.newUp.name}]`;try{he&&console.log(`${r} starting...`),e??=B(Gn),e=e,t=t??xc?B(xc):void 0,e.uuid||=await q();let{classname:n}=e,a=Uc({data:e}),s=await _t({parentPrimitiveIb:`witness ${n}`,ib:a,data:e,rel8ns:t}),i=new us(void 0,void 0);return await i.loadIbGibDto(s),he&&console.log(`${r} witnessDto: ${X(s)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:i}}catch(n){throw console.error(`${r} ${E({error:n})}`),n}finally{he&&console.log(`${r} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{he&&console.log(`${t} starting...`);let{data:r}=e;if(!r)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");he&&console.log(`${t} data: ${X(r)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await Mo({n:100}),a=new gs().with({idPool:n}).name({of:r.name,required:!1}).description({of:r.description??as}).and().and().uuid({of:r.uuid,required:!0}).classname({of:r.classname}).and().commonWitnessFields({data:r}).outputForm({formName:"form",label:"observable"});return Promise.resolve(a)}catch(r){throw console.error(`${t} ${E({error:r})}`),r}finally{he&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=B(Gn);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:to}),await this.newUp({data:t})}};var Es=!1;function Nb({data:o}){let e=`[${Nb.name}]`;try{if(Es&&console.log(`${e} starting...`),!o)throw new Error("Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)");let t=[],{name:r,uuid:n,classname:a}=o;return r?r.match(Sc)||t.push(`name must match regexp: ${Sc} (E: de987eb8fea0b6232f60abf31815095c)`):t.push("name required."),n?n.match(Ie)||t.push(`uuid must match regexp: ${Ie} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):t.push("uuid required."),a&&(a.match(ar)||t.push(`classname must match regexp: ${ar}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Es&&console.log(`${e} complete.`)}}h(Nb,"validateCommonSubjectData");function Uc({data:o,classname:e}){let t=`[${Uc.name}]`;try{let r=Nb({data:o});if(r.length>0)throw new Error(`invalid Subject data: ${r} (E: 55620ac1f17e30a30a92850219f894ac)`);if(e){if(o.classname&&o.classname!==e)throw new Error("classname does not match data.classname (E: 20e86cca70130839a49ad011c9a7aafa)")}else if(e=o.classname,!e)throw new Error("classname required (E: 74e29ae0f618fee7e7ef72a30c654a6c)");let{name:n,uuid:a}=o;return`witness ${ns} ${e} ${n} ${a}`}catch(r){throw console.error(`${t} ${E(r)}`),r}}h(Uc,"getSubjectIb");var gs=class o extends br{static{h(this,"SubjectFormBuilder")}lc=`[${o.name}]`;constructor(){super(),this.what="subject"}};function Jr({ibGib:o}){let e=`[${Jr.name}]`;try{return Es&&console.log(`${e} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof o.next=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Es&&console.log(`${e} complete.`)}}h(Jr,"isObserver");async function ws({data:o,replay:e}={}){let t=new ms;return o??=B(Gn),e&&(o.replay=!0),(await t.newUp({data:o})).newIbGib}h(ws,"newupSubject");var ys="anon_fn",Db={fnHash:""};var vb=!1;function Mc({data:o}){let e=`[${Mc.name}]`;try{if(vb&&console.log(`${e} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!o?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${ys} ${o.fnHash}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{vb&&console.log(`${e} complete.`)}}h(Mc,"getAnonymousFnIb");var _r=class{static{h(this,"AnonymousFnWitness_V1")}fn;ib=ys.concat();gib=Q;data=B(Db);rel8ns;constructor(e){if(this.fn=e,!e)throw new Error("fn required (E: b1e1478f466a2a347b75e7c336f8d323)")}async witness(e){return this.data.fnHash=await te({s:this.fn.toString()}),this.ib=Mc({data:this.data}),this.gib=await ee({ibGib:this}),this.fn(e)}};var $s=!1;function _u({err:o}){let e=`[${_u.name}]`;try{if($s&&console.log(`${e} starting... (I: 96f8b767c50f24768ced7beebb291723)`),Lr(o)){let t=o;if(!o.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(tr({ibGib:o}))return o.data.raw;throw new Error("(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)")}else return E(o)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{$s&&console.log(`${e} complete.`)}}h(_u,"extractObsErrMsg");function Fc(o){let e=`[${Fc.name}]`;try{$s&&console.log(`${e} starting... (I: 3d2c3658a0fda83ece1f2b095a365823)`);let t;if(typeof o=="function"?t={next:o}:t=o,!t.next)throw new Error("observer.next required (typeof observerOrFn !== 'function') (E: da944e93b32ab5918f11751bcd651823)");let r=h(async d=>(await t.next(d),ue),"fnNext"),n=h(async d=>(d.ib==="complete"?t.complete&&await t.complete():tr({ibGib:d})?t.error&&await t.error(d):await t.next(d),ue),"fnWitness"),a=new _r(r),s=new _r(n),i={ib:"observer",witness:h(async d=>await s.witness(d),"witness"),next:h(async d=>{await a.witness(d)},"next")},c=t.error??(async d=>{let f;if(typeof d=="string")f=E(d);else if(d.ib)if(tr({ibGib:d}))f=E(d.data.raw);else throw new Error(`${e} (UNEXPECTED) first off, observer.error is falsy. secondly, error came down pipeline and has an "ib" property but is not an ErrorIbGib_V1? (E: 0a2a46b9620b4a6a84c7ba1100da537b)`);else d instanceof Error?f=E(d):typeof d.message=="string"?f=E(d.message):f="[unknown thing came down pipe that ain't an error]";console.error(`Error occurred but observer.error is falsy. error: ${f} (E: 822c60c7c4d542efacd5c2dea7e88062)`)}),l=new _r(async d=>(c(d),ue));if(i.error=async d=>{typeof d=="string"?d=await zr({rawMsg:d}):d instanceof Error&&(d=await zr({rawMsg:d.message}));try{await l.witness(d)}catch{t.error?console.error(`${e} there was another error when executing errorAnonFnWitness.witness (wrapper of caller's observer.error) trapping this. (E: 8fa3c4e633df4491a82951e3b677d9a9)`):console.error(`${e} there was another error when executing errorAnonFnWitness.witness (caller's observer.error was falsy). trapping this. (E: f5ff2db0d762487287139a4175eb7689)`)}},t.complete){let d=t.complete,f=new _r(async b=>(await d(),ue));i.complete=async()=>{try{await f.witness(ue)}catch(b){console.error(`${e} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${E(b)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return i}catch(t){throw console.error(`${e} ${t.message}`),t}finally{$s&&console.log(`${e} complete.`)}}h(Fc,"fnObs");var Pb=!1,xo=class{static{h(this,"GraftMergeStrategyBase_V1")}defaultGraftPreference;constructor(e){this.defaultGraftPreference=e?.defaultGraftPreference??Bt.timestamp}resolveBaseAndOrphan({graftPreference:e,tipA_sender:t,branchA_sender_sinceLCA:r,tipB_receiver:n,branchB_receiver_sinceLCA:a}){let s=e||this.defaultGraftPreference;if(s===Bt.receiver)return{baseTip:n,baseBranch:a,orphanTip:t,orphanBranch:r};if(s===Bt.sender)return{baseTip:t,baseBranch:r,orphanTip:n,orphanBranch:a};{let i=hr({ibGib:t}),c=i.valid?Number.parseInt(i.ticks):Number.MAX_SAFE_INTEGER,l=i.valid?i.ms??0:0,d=hr({ibGib:n}),f=d.valid?Number.parseInt(d.ticks):Number.MAX_SAFE_INTEGER,b=d.valid?d.ms??0:0;return c<f||c===f&&l<=b?{baseTip:t,baseBranch:r,orphanTip:n,orphanBranch:a}:{baseTip:n,baseBranch:a,orphanTip:t,orphanBranch:r}}}async applyTransformAndRegister({resTransform:e,space:t,newGraftDnaIbGibs:r,newGraftedIntermediateIbGibs_ordered:n}){let a=`[${this.constructor.name}][${this.applyTransformAndRegister.name}]`;try{if(Pb&&console.log(`${a} starting... (I: d4f66e62cbcc81636354e0583c15b826)`),!e)throw new Error("(UNEXPECTED) resTransform falsy (E: 83b27a8102f4423ab194e82f7c001826)");if(!e.newIbGib)throw new Error("(UNEXPECTED) resTransform.newIbGib falsy (E: a71823901bcf4502b4d9158bc7991826)");if(!e.dnas||e.dnas.length===0)throw new Error("(UNEXPECTED) resTransform.dnas falsy/empty (E: b65c19208a0d421297fb1c26b8911826)");for(let s of e.dnas)r.push(s);return n.push(e.newIbGib),t&&(await V({resTransform:e,space:t}),await J({ibGib:e.newIbGib,space:t})),e.newIbGib}catch(s){throw console.error(`${a} ${E(s)} (E: d2384a8b792e42429bc7891234567826)`),s}finally{Pb&&console.log(`${a} complete.`)}}};var Is=!1,xn=class extends xo{static{h(this,"DefaultDnaReplayGraftStrategy")}strategyId="DefaultDnaReplayGraftStrategy";canGraft(e){return!0}async graft(e){let t=`[${this.strategyId}][${this.graft.name}]`;try{let T=function(Z){let se=`${t}[${T.name}]`;for(let Y of Z){if(!Y.rel8ns)throw new Error(`(UNEXPECTED) ${se} someIbGib.rel8ns falsy? All ibgibs with mergeable timelines are expected to have rel8ns. addr: ${I({ibGib:Y})} (E: 5534a478cd183a5ee27b28487448b226)`);if(!Y.rel8ns.dna)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna falsy? We only have implemented grafting for dna. addr: ${I({ibGib:Y})} (E: d86b388c627afd613f897e3819d8ab26)`);if(Y.rel8ns.dna.length===0)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna.length === 0? We only have implemented grafting for dna. addr: ${I({ibGib:Y})} (E: bf973662a0689dd9089912b861af2826)`)}};var r=T;h(T,"throwIfUnexpected"),Is&&console.log(`${t} starting default DNA replay graft... (I: 66404c06d838a8c43886f128127bc826)`);let{conflictStrategy:n,timelineAddrsA:a,timelineAddrsB:s,latestCommonFrameAddr:i,ibGibReadCache:c,space:l,graftPreference:d}=e,f=[],b=[];if(a.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(s.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");let p=a.lastIndexOf(i),u=a.slice(p+1),m=await Ve({readCache_graph:c,addrs:u,space:l}),g=m.at(-1),y=s.lastIndexOf(i),w=s.slice(y+1),A=await Ve({readCache_graph:c,addrs:w,space:l}),G=A.at(-1);T(m),T(A);let{baseTip:$,baseBranch:_,orphanTip:S,orphanBranch:D}=this.resolveBaseAndOrphan({graftPreference:d,tipA_sender:g,branchA_sender_sinceLCA:m,tipB_receiver:G,branchB_receiver_sinceLCA:A}),C=I({ibGib:$}),N=_.map(Z=>I({ibGib:Z})),x=I({ibGib:S}),L=D.map(Z=>I({ibGib:Z}));Is&&console.log(`${t} baseTipAddr: ${C} (I: 93353d9b9b68b17088f57958df85e826)`),Is&&console.log(`${t} orphanTipAddr: ${x} (I: 14df8867adc5dab97ff3c1e989b40e26)`);let[U]=await Ve({addrs:[i],space:l});if(!U)throw new Error("(UNEXPECTED) latestCommonFrameIbGib falsy? (E: ead2020b7ab8e4c4f824573133e33826)");if(!U.rel8ns?.dna||U.rel8ns.dna.length===0)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns.dna falsy/empty? (E: 98fd8c725f484d85c8d23ceb181ce826)");let O=U.rel8ns.dna.concat(),M=[];for(let Z of D){if(!Z.rel8ns)throw new Error("(UNEXPECTED) orphanFrame.rel8ns falsy? (E: ed910e3b930b1b5388d87c6f736a4826)");let se=Zi({base:O,extended:Z.rel8ns.dna??[],throwIfExtendedDoesntContainBase:!0});se.forEach(Y=>O.push(Y)),se.forEach(Y=>M.push(Y))}let F=await Ve({addrs:M,readCache_graph:c,space:l}),k=[],Ee=await jr({src:$,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:M.concat(),allLocalIbGibs:F,createdIbGibs_Running:k});if(l&&k.length>0){await ce({space:l,ibGibs:k});let{mapWithTjp_YesDna:Z}=nt({ibGibs:k}),se=Object.values(Z),Y=at({ibGibs:se});if(Object.keys(Y).length>0){Object.values(Y)[0].forEach(j=>f.push(j));for(let j of f)await J({ibGib:j,space:l})}}let pe=[];if(n===gt.optimisticWithLCS){let Z=$.data?.text,se=S.data?.text;if(typeof Z=="string"&&typeof se=="string"&&Z!==se){let Y=await fb({textA:Z,textB:se});if(Y!==Ee.data?.text){let j=await Ae({src:Ee,dataToAddOrPatch:{text:Y},dna:!0,nCounter:!!Ee.data?.n});for(let ke of j.dnas??[])b.push(ke);f.push(j.newIbGib),l&&(await V({resTransform:j,space:l}),await J({ibGib:j.newIbGib,space:l})),Ee=j.newIbGib;let we={mergeTextStrategy:bc.lcs,textAAddr:I({ibGib:$}),textBAddr:I({ibGib:S})};pe.push(we)}}}let oe=await An({conflictStrategy:n,details:`Replayed ${M.length} transforms from orphan (${x}) onto base (${C}).`,addlGraftDetails:pe.length>0?pe:void 0,latestCommonFrameAddr:i,baseAddrsSinceLCA:N,orphanAddrsSinceLCA:L,dnaAddrsApplied:M});l&&await ce({ibGib:oe,space:l});let re=I({ibGib:oe}),fe=await ie({src:Ee,rel8nsToAddByAddr:{[Yr]:[re]},dna:!0,nCounter:!!Ee.data?.n});for(let Z of fe.dnas??[])b.push(Z);l&&(await V({resTransform:fe,space:l}),await J({ibGib:fe.newIbGib,space:l}));let W=fe.newIbGib;return{dnasReplayed:F,dnasCreatedInGraft:b,intermediateIbGibsCreatedInGraft:f,ancillaryIbGibsCreated:[],newGraftTip:W,graftInfoCreated:oe}}catch(n){throw console.error(`${t} ${E(n)} (E: 090d7445aa6aefd9a89dade8e834f826)`),n}finally{Is&&console.log(`${t} complete.`)}}};var Co=!1,Bc="[graft-strategy-service]",No=class o{static{h(this,"GraftStrategyService")}static _instance;static get instance(){return this._instance||(this._instance=new o),this._instance}_registeredStrategies=[];_fallbackStrategy=new xn;registerStrategy(e){let t=`${Bc}[${this.registerStrategy.name}]`;if(!e)throw new Error("(UNEXPECTED) strategy falsy (E: 777b77f4cf48e0c2b83159f8dbd06226)");this._registeredStrategies.some(r=>r.strategyId===e.strategyId)||(Co&&console.log(`${t} registering strategy ${e.strategyId} (I: ad6a7f678526d2991684cc2c1c16cd26)`),this._registeredStrategies.push(e))}setFallbackStrategy(e){let t=`${Bc}[${this.setFallbackStrategy.name}]`;if(!e)throw new Error("(UNEXPECTED) fallback strategy falsy (E: 09819876bb2ad7b788432518ce727826)");Co&&console.log(`${t} setting fallback strategy ${e.strategyId} (I: e7e4d88de1d8a7fbc8dfa021f2900826)`),this._fallbackStrategy=e}getFallbackStrategy(){return this._fallbackStrategy}getRegisteredStrategies(){return this._registeredStrategies.slice()}reset(){let e=`${Bc}[${this.reset.name}]`;Co&&console.log(`${e} resetting strategies to default fallback... (I: edc9e8c23808995ade1cc3c8da474f26)`),this._registeredStrategies=[],this._fallbackStrategy=new xn}async graftTimelines({timelineAddrsA:e,timelineAddrsB:t,latestCommonFrameAddr:r,conflictStrategy:n,ibGibReadCache:a,space:s,graftPreference:i}){let c=`[${this.graftTimelines.name}]`;try{if(Co&&console.log(`${c} starting... (I: 3b4c3e8e59c883d9d3c352efd6380826)`),e.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(t.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");if(r){if(!e.includes(r))throw new Error(`timelineAddrsA does not include latestCommonFrameAddr (${r}). timelineAddrsA: ${e} (E: c5a9afe371888da2a79963983426e826)`);if(!t.includes(r))throw new Error(`timelineAddrsB does not include latestCommonFrameAddr (${r}). timelineAddrsB: ${t} (E: 7e641f67c452b67d582d78484a88c826)`)}else if(r=e.findLast(p=>t.includes(p)),!r)throw new Error(`timelines do not share a common frame. A: ${e}. B: ${t} (E: 4c0e78a88a375d8588736668573f1e26)`);if(e.at(-1)===r)throw new Error("timelineAddrsA.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 3796fc4074a8c5899d549bb8c2e68826)");if(t.at(-1)===r)throw new Error("timelineAddrsB.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 66fbb86e9e98531549888bf10a344f26)");let l={conflictStrategy:n,timelineAddrsA:e,timelineAddrsB:t,latestCommonFrameAddr:r,ibGibReadCache:a,space:s,graftPreference:i},d=[],f=this.getRegisteredStrategies();if(f&&f.length>0)for(let p of f)await p.canGraft(l)&&d.push(p);if(d.push(o.instance.getFallbackStrategy()),d.length===0)throw new Error("(UNEXPECTED) strategyPipeline.length === 0? We should at least have the fallback strategy. (E: 1d9bef958b54f8d0d9498bc7fd597226)");let b;for(let p of d)if(Co&&console.log(`${c} executing graft strategy ${p.strategyId} (I: 066466905d08792d480c5f285fe4f826)`),b=await p.graft(l),b)break;if(!b)throw new Error("(UNEXPECTED) resGraft falsy? Our fallback strategy should have at least replayed the dna. (E: 6b2d78b52b39a7ff9853c0d8f8628826)");return b}catch(l){throw console.error(`${c} ${E(l)} (E: 05ed0ae869b6658d278fe1480fe19826)`),l}finally{Co&&console.log(`${c} complete.`)}}};var R=!1,As=!1,Et="[ControlDomain]",Tr=class o{static{h(this,"SyncSagaCoordinator")}lc=`[${o.name}]`;constructor(){}defaultSessionConnectPoolConfig(){return Mi({id:on,salt:`session-connect-${Date.now()}`,verbs:[bo],size:20,sequential:2,random:2,targetBinding:0,replenishStrategy:Ze.deleteAll})}defaultSessionSyncPoolConfig(){return Mi({id:Li,salt:`session-sync-${Date.now()}`,verbs:[ut],size:200,sequential:3,random:3,targetBinding:3,replenishStrategy:Ze.topUp})}async sync({peer:e,domainIbGibs:t,senderIdentityInfo:r,fnSenderSecret:n,conflictStrategy:a=gt.abort,graftPreference:s,metaspace:i,localSpace:c}){let l=`${this.lc}[${this.sync.name}]`;if(R&&console.log(`${l} starting...`),!c){debugger;throw new Error(`${l} source (or localSpace) required (E: 25df3761f7686a1099a552f83c95d326)`)}if(r||n){if(!r)throw new Error("(UNEXPECTED) senderIdentityInfo falsy but fnSenderSecret truthy? if either is used, both must be truthy. (E: e366628a4919c7d727d2cbd8e5b75e26)");if(!n)throw new Error("(UNEXPECTED) fnSenderSecret falsy but senderIdentityInfo truthy? if either is used, both must be truthy. (E: 7d55ce37ae482fec48e3398158161926)");let{senderIdentity:G,senderDomainAddr:T}=r;if(!G)throw new Error("(UNEXPECTED) senderIdentity falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: a3c17fae2978926d)");if(!T)throw new Error("(UNEXPECTED) senderDomainAddr falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: d288fae39b7d825c)")}let{senderIdentity:d,senderDomainAddr:f}=r??{},b=await q(),p=await ws();if(!p.next)throw new Error("(UNEXPECTED) updates$.next falsy? (E: d24cd82184aec130c89a320819b39126)");let u,m,g=new Promise((G,T)=>{u=G,m=T}),y=await bb(),w=await i.createNewLocalSpace({opts:{allowCancel:!1,spaceName:y,getFnPrompt:i.getFnPrompt,logalot:R}});if(!w)throw new Error("Failed to create temp space (E: 8f4e2f3d6c1b4b1a8f4e2f3d6c1b4b1a)");await w.initialized;let A=h(async()=>{},"cleanup");return(async()=>{try{let G=t?t.map(_=>I({ibGib:_})):void 0;e.setOptionalOpts({sagaId:b,senderIdentity:d,senderDomainAddr:f,fnSenderSecret:n,sessionConnectPoolConfig:this.defaultSessionConnectPoolConfig(),sessionSyncPoolConfig:this.defaultSessionSyncPoolConfig(),targetAddrs:G}),await e.establishSessionIdentity(),await e.connect({sagaId:b});let{initFrame:T,initDomainGraph:$}=await this.createInitFrame({sagaId:b,domainIbGibs:t,conflictStrategy:a,graftPreference:s,metaspace:i,localSpace:c,tempSpace:w,peer:e});if(await this.executeSagaLoop({initFrame:T,initDomainGraph:$,peer:e,updates$:p,localSpace:c,tempSpace:w,metaspace:i}),u(),!p.complete)throw new Error("(UNEXPECTED) updates$.complete falsy? (E: d24cd82184aec130c89a320819b39126)");p.complete()}catch(G){if(console.error(`${l} ${E(G)}`),m(G),!p.error)throw new Error("(UNEXPECTED) updates$.error falsy? (E: 392ce77c073272e4c398c3e86583ce26)");p.error(G)}finally{await A()}})(),{sagaId:b,updates$:p,done:g}}async continueSync({sagaContext:e,mySpace:t,myTempSpace:r,metaspace:n,peer:a}){let s=`${this.lc}[${this.continueSync.name}]`;try{R&&console.log(`${s} starting... (I: f64e08bf77d1425378601f380384ec26)`);let i=await this.handleResponseSagaContext({sagaContext:e,mySpace:t,myTempSpace:r,metaspace:n});if(i){if(i.nextFrameInfo?.sagaComplete)return null}else return R&&console.log(`${s} Handler returned null (Saga End). (I: 43da8bb6c846b1fe7766332643be0e26)`),null;if(i.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${i.errorMsg} (E: 7b41a183cf3cb58a5859c803800cf826)`);if(!i.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: 5740542f5eb8ccb41dfec188d87c1e26)");let{frame:c,payloadIbGibsDomain:l}=i.nextFrameInfo,d=await this.createSyncSagaContext({sagaFrame:c,localSpace:t,payloadIbGibsDomain:l,metaspace:n,sessionIdentityAddr:e.rel8ns?.sessionIdentity?.[0],peer:a,skipSign:!0}),f=await Go({context:d});if(f.length>0)throw new Error(`(UNEXPECTED) just created sync saga context () and there were immediateValidationErrors? immediateValidationErrors: ${f} (E: c120e8e0aa98673d685267a8a36e5826)`);return d}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{R&&console.log(`${s} complete.`)}}async executeSagaLoop({initFrame:e,initDomainGraph:t,peer:r,updates$:n,localSpace:a,tempSpace:s,metaspace:i}){let c=`${this.lc}[${this.executeSagaLoop.name}]`,l=e,d=[];for(;l;){let f=new Map,b=`${c}[peer.payloadIbGibsDomainReceived$]`,p=await r.payloadIbGibsDomainReceived$.subscribe(Fc({next:h(async u=>{R&&console.log(`${b} next fired. (I: 2b4bdf502a38a90ba33d9711e7cb7826)`);let m=I({ibGib:u});As&&console.log(`${c}${Et} DOMAIN STREAM RECEIVED <- observable: ${m} (I: d69ee80fcaece272483ec33b2d289826)`),f.set(m,u)},"next"),error:h(async u=>{Lr(u)?console.error(`${b} error fired. error: ${JSON.stringify(u.data)} (E: 01cc08ba05ad99682831174fd7c31a26)`):(console.dir(u),console.error(`${b} error fired. error: ${E(u)} (E: 73d3d61464e8e4ce4cd6efd8b9675826)`))},"error"),complete:h(async()=>{R&&console.log(`${b} complete fired. (I: a47218aa9e4433fdb97c068880a45826)`),await p.unsubscribe()},"complete")}));try{let u=await this.createSyncSagaContext({sagaFrame:l,payloadIbGibsDomain:d,localSpace:a,metaspace:i,sessionIdentityAddr:r.currentSessionIdentityAddr,peer:r});if(As){let $=d.map(_=>I({ibGib:_}));console.log(`${c}${Et} SENDER TRANSMIT -> peer.witness (I: 5b0081803698770f0bf64992220b312)`),console.log(`${c}${Et} Context: ${I({ibGib:u})}`),console.log(`${c}${Et} Frame: ${I({ibGib:l})}`),console.log(`${c}${Et} DOMAIN Payloads (${$.length}): ${$.join(", ")||"(none)"}`)}n.next(u),r.setOptionalOpts({localSpace:a,localTempSpace:s});let m=await r.witness(u);if(!m)if(l)if((await _c({frameIbGib:l,space:a}))?.data?.stage===_e.commit){R&&console.log(`${c} Sender sent Commit. Peer returned no response. Saga Complete. (I: 26f9ee073858ca78b8284753368b5226)`),l=null;break}else throw new Error("(UNEXPECTED) responseCtx falsy and currentFrame truthy, but we're not in the commit stage? This may be expected ultimately, but atow I am not seeing this as being expected. (E: cc34498962bd370deeff351fac939f26)");else throw new Error("(UNEXPECTED) no response and currentFrame falsy? (E: 8d1085ea2f28cfc3f9c922649864a826)");if(!m.data)throw new Error("(UNEXPECTED) responseCtx.data falsy? (E: a969992bae53ab18a827ec58aec15826)");n.next(m);let g=await Go({context:m});if(g.length>0)throw new Error(`contextAndSagaFrameValidationErrors: ${g} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`);let y=await this.validateReturnContext({requestCtx:u,responseCtx:m,localSpace:a});if(y.length>0)throw new Error(`validateReturnContext errors: ${y.join(", ")} (E: cb8a023b9d0728cceb09fa3da0bb8226)`);let w=m.data[fc]||[];if(w.length>0&&(m.payloadIbGibsDomain=await this.pollForDomainPayloads({expectedAddrs:w,pollIntervalMs:20,domainPayloadsMap:f,tempSpace:s})),!m.sagaFrame)throw new Error("(UNEXPECTED) responseCtx.sagaFrame falsy? the Peer should have set this when it got the response back from the remote. (E: e650adadf9a2063ec6764a1e31d3d826)");if(As){let $=m.data?.["@payloadAddrsControl"]||[];console.log(`${c}${Et} SENDER RECEIVED <- peer.witness (I: 3dc76a9744d89a4fc3e2f076c2be4826)`),console.log(`${c}${Et} Response Context: ${I({ibGib:m})}`),console.log(`${c}${Et} Response Saga Frame: ${I({ibGib:m.sagaFrame})}`),console.log(`${c}${Et} CONTROL Payloads (${$.length}): ${$.join(", ")||"(none)"}`),console.log(`${c}${Et} DOMAIN Payloads (${w.length}): ${w.join(", ")||"(none)"}`)}let A=await this.handleResponseSagaContext({sagaContext:m,initDomainGraph:t,mySpace:a,myTempSpace:s,metaspace:i});if(A){if(A.nextFrameInfo?.sagaComplete){R&&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(A.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${A.errorMsg} (E: c948e81d513b2a0eb8b8afa878edc626)`);if(!A.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: c287a82e823e662a77923278e2418826)");let{frame:G,payloadIbGibsDomain:T}=A.nextFrameInfo;if(l=G,d=[...T||[]],As){let $=d.map(_=>I({ibGib:_}));console.log(`${c}${Et} HANDLER RESULT -> next iteration (I: 6b0d88c4c28857ccd812381515bd7826)`),console.log(`${c}${Et} Next Frame: ${I({ibGib:l})}`),console.log(`${c}${Et} DOMAIN for next (${$.length}): ${$.join(", ")||"(none)"}`)}}finally{await p.unsubscribe()}}}async createSyncSagaContext({sagaFrame:e,payloadIbGibsDomain:t,metaspace:r,localSpace:n,sessionIdentityAddr:a,peer:s,skipSign:i}){let c=`[${this.createSyncSagaContext.name}]`;try{if(R&&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 l=new Date,d=rt(l),f=l.getMilliseconds(),b={timestamp:d,timestampMs:f,sagaN:e.data.n},p=t?t?.map(T=>I({ibGib:T})):void 0;p&&p.length>0&&(b[fc]=p);let u={sagaFrame:[I({ibGib:e})]},m;if(a){a=await r.getLatestAddr({addr:a,space:n})??a;let T=await z({addr:a,space:n});if(T.success&&T.ibGibs?.length===1)m=T.ibGibs[0],u.sessionIdentity=[a];else{debugger;throw new Error(`Couldn't get sessionIdentityAddr (${a}) in space: ${n.ib} (E: 5c29e80d68dbd1749866c358be093826)`)}}let g=await Tc({data:b}),y=await H.stone({parentPrimitiveIb:os,ib:g,data:b,rel8ns:u}),w=I({ibGib:y}),A;m&&!i&&(A=await s.signContext({contextAddr:w})),await ce({ibGib:y,space:n}),await J({ibGib:y,space:n,fnBroadcast:void 0}),y.sagaFrame=e;let{msgStones:G}=await Kr({sagaIbGib:e,localSpace:n});if(G.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)");return y.sagaFrameMsg=G[0],t&&t.length>0&&(y.payloadIbGibsDomain=t),A&&(y.signedSessionIdentity=A),y}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{R&&console.log(`${c} complete.`)}}async getKnowledgeMap({space:e,metaspace:t,domainIbGibs:r,tjpAddrs:n}){let a=`${this.lc}[${this.getKnowledgeMap.name}]`;try{if(R&&console.log(`${a} starting... (I: e184f8a7818666febfbbd2d841ed3826)`),!(r&&r.length>0)&&!(n&&n.length>0))throw new Error("(UNEXPECTED) domainIbGibs and tjpAddrs falsy/empty? we need one or the other (E: f674285111c8648398cd79d8c08ec826)");if(r&&r.length>0&&n&&n.length>0)throw new Error("(UNEXPECTED) both domainIbGibs and tjpAddrs truthy? only pass in one or the other. (E: f674285111c8648398cd79d8c08ec826)");let s=[];if(n)s=n;else if(r&&r.length>0){let{mapWithTjp_YesDna:c,mapWithTjp_NoDna:l}=nt({ibGibs:r}),d=[...Object.values(c),...Object.values(l)],f=at({ibGibs:d});s=Object.keys(f)}else return console.warn(`${a} No domainIbGibs or tjpAddrs provided. Returning empty Knowledge. (W: 2b0e115e7578a83d1b26f7c726bf9426)`),{};if(s.length===0)return{};let i=await ve({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} ${E(s)}`),s}finally{R&&console.log(`${a} complete.`)}}async analyzeDomainIbGibs({domainIbGibs:e,space:t}){let r=`${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 it({ibGibs:e,live:!0,space:t}),a=n&&Object.keys(n).length>0;R&&console.log(`${r} graph generated. nodes: ${a?Object.keys(n).length:0}`);let s=a?Object.values(n):[],{mapWithTjp_YesDna:i,mapWithTjp_NoDna:c,mapWithoutTjps:l}=nt({ibGibs:s}),d=Object.values(l),f=[...Object.values(i),...Object.values(c)],b=at({ibGibs:f}),p=this.sortTimelinesTopologically(b);return{stones:d,timelinesMap:b,topologicallySortedTjpAddrs:p,fullGraph:n}}async createInitFrame({sagaId:e,domainIbGibs:t,conflictStrategy:r,graftPreference:n,metaspace:a,localSpace:s,tempSpace:i,peer:c}){let l=`${this.lc}[${this.createInitFrame.name}]`;try{R&&console.log(`${l} starting... (I: 551af8b411ae9be712ce3358d43ee726)`);let d=await this.analyzeDomainIbGibs({domainIbGibs:t,space:s}),{timelinesMap:f,fullGraph:b,stones:p}=d;await ce({ibGibs:Object.values(b),space:i});let u={};Object.keys(f).forEach(w=>{let G=f[w].at(-1);u[w]=I({ibGib:G})});let m={sagaId:e,stage:_e.init,knowledgeMap:u,mode:wc.sync,stones:p.map(w=>I({ibGib:w}))};R&&(console.log(`${l} SyncStage.init: ${_e.init}, SyncStage.commit: ${_e.commit}`),console.log(`${l} initData.stage: ${m.stage}`));let g=await this.createSyncMsgStone({data:m,localSpace:s,metaspace:a}),y=await this.evolveSyncSagaIbGib({msgStones:[g],conflictStrategy:r,graftPreference:n,metaspace:a,localSpace:s,sessionIdentity:c.currentSessionIdentity});return R&&console.log(`${l} sagaFrame (init): ${X(y)} (I: b3d6a8be69248f18713cc3073cb08626)`),{initFrame:y,initDomainGraph:b}}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{R&&console.log(`${l} complete.`)}}async validateReturnContext({requestCtx:e,responseCtx:t,localSpace:r}){let n=`${this.lc}[${this.validateReturnContext.name}]`,a=[];try{if(e.sagaFrame&&t.sagaFrame){let c=I({ibGib:e.sagaFrame}),l=I({ibGib:t.sagaFrame});try{await Ao({olderAddr:c,newerAddr:l,space:r})||a.push(`Response saga frame (${l}) is not a valid continuation of request saga frame (${c}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`)}catch(d){throw console.error(`${n} isPastFrame just threw (E: 477888443fe89eca2c19fb684bf60126)`),d}}else a.push("Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)");let s=e.signedSessionIdentity?I({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: ${E(s)} (E: da878e1239aa88ee27bdfca005c28226)`)}return R&&a.length>0&&console.log(`${n} errors: ${a.join(`
|
|
35
|
+
`)} (I: cbc119df45aa13daa9009de392c4b226)`),a}async pollForDomainPayloads({expectedAddrs:e,pollIntervalMs:t,domainPayloadsMap:r,tempSpace:n}){let a=`${this.lc}[${this.pollForDomainPayloads.name}]`;try{R&&console.log(`${a} starting... (I: 26dce86bfca572939885798802d6e926)`);let s=[],i=[...new Set(e)],c=[...i],l=Date.now(),d=5*60*1e3;for(;c.length>0;){if(Date.now()-l>d)throw new Error(`Timeout waiting for payloads: ${c.join(", ")} (E: 46e1683c9578095261aaf798bd5e1826)`);let f=[],b=[];for(let p of c)r.has(p)?(b.push(r.get(p)),r.delete(p)):f.push(p);b.length>0&&(await ce({space:n,ibGibs:b}),b.forEach(p=>s.push(p))),c=f,c.length>0&&await De(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} ${E(s)}`),s}finally{R&&console.log(`${a} complete.`)}}async handleResponseSagaContext({sagaContext:e,initDomainGraph:t,mySpace:r,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleResponseSagaContext.name}]`;try{R&&console.log(`${s} starting... (I: 5deec8a1f7a6d263c88cd458ad990826)`);let i=e.sagaFrame;if(!i.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 71b938adf1d87c2527bfd4f86dfd0826)");R&&console.log(`${s} sagaIbGib: ${X(i)} (I: 1b99d87d262e9d18d8a607a80b1a0126)`);let{stage:c,messageData:l}=await this.getStageAndPayloadFromFrame({sagaFrame:i,space:r});R&&console.log(`${s} handling frame stage: ${c}`);let d;switch(c){case _e.init:d=await this.handleInitFrame({sagaIbGib:i,messageData:l,metaspace:a,mySpace:r,myTempSpace:n});break;case _e.ack:if(!t)throw new Error("(UNEXPECTED) initDomainGraph falsy on the sender? (E: a3d758ad954829aba88663188eafc826)");d=await this.handleAckFrame({sagaContext:e,sagaIbGib:i,initDomainGraph:t,metaspace:a,mySpace:r,myTempSpace:n});break;case _e.delta:d=await this.handleDeltaFrame({sagaContext:e,sagaIbGib:i,metaspace:a,mySpace:r,myTempSpace:n});break;case _e.commit:R&&console.log(`${s}[${To({sagaFrame:i})}] mySpace.ib: ${r.ib} (I: 5b270996d848907238d817fffa64a126)`),d=await this.handleCommitFrame({sagaIbGib:i,metaspace:a,mySpace:r,myTempSpace:n});break;default:throw new Error(`${s} (UNEXPECTED) Unknown sync stage: ${c} (E: 9c2b4c8a6d34469f8263544710183355)`)}return R&&console.log(`${s} nextFrameInfo: ${d?X(d):"undefined"} (I: a8ad281ca8e89385686d18327a105726)`),{errorMsg:void 0,nextFrameInfo:d}}catch(i){let c=`${s} ${E(i)}`;return console.error(c),{errorMsg:c}}finally{R&&console.log(`${s} complete.`)}}async handleInitFrame({sagaIbGib:e,messageData:t,mySpace:r,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleInitFrame.name}]`;try{R&&console.log(`${s} starting... (I: 9d88dcad0408c029e898a4bcf3b08426)`),R&&console.log(`${s} [TEST DEBUG] Receiver mySpace: ${r.ib}`);let i=t;if(i.stage!==_e.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||gt.abort,l=[],d=[],f=[],b=i.stones||[];if(b.length>0){R&&console.log(`${s} processing stones: ${b.length}`);let _=(await z({space:r,addrs:b})).rawResultIbGib;if(!_.data)throw new Error("(UNEXPECTED) rawResultIbGib.data falsy? (E: f3c40b492adc02c3f480b998fc7a5926)");let S=_.data.addrsNotFound;S&&S.length>0&&(R&&console.log(`${s} stones missing (requesting): ${S.length}`),S.forEach(D=>{d.some(C=>C.addr===D)||d.push({addr:D})}))}let p=i.knowledgeMap;R&&console.log(`${s} senderKnowledge: ${X(p)} (I: 9f957862356dfeae183c200854e86e26)`);let u=Object.keys(p);R&&console.log(`${s} [TEST DEBUG] senderTjpAddrs: ${JSON.stringify(u)}`),R&&console.log(`${s} senderTjpAddrs: ${X(u)} (I: 86ea4c53db0dc184c8b253386c402126)`);let m={};if(u.length>0){let $=await ve({space:r,tjpAddrs:u});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,R&&console.log(`${s} [TEST DEBUG] receiverLatestAddrsMap: ${JSON.stringify(m)}`),R&&console.log(`${s} receiverLatestAddrsMap: ${X(m)} (I: 980975642cbccd8018cf0cd808d30826)`)}for(let $ of u){let _=p[$],S=m[$];if(!S){R&&console.log(`${s} [TEST DEBUG] Missing receiver timeline for TJP: ${$}. Requesting remoteAddr: ${_}`),d.push({addr:_,tjpAddr:$});continue}if(S===_){R&&console.log(`${s} [TEST DEBUG] TJP ${$}: Synced (receiverTipAddr === remoteAddr)`);continue}R&&console.log(`${s} [TEST DEBUG] TJP ${$}: receiverTipAddr=${S}, remoteAddr=${_} - checking for divergence...`);let D;try{D=await Ao({olderAddr:_,newerAddr:S,space:r})}catch{console.log(`${s} isPastFrame just threw (E: b297244176e7380ffcaaef4861799326)`),D=!1}if(D){R&&console.log(`${s} [TEST DEBUG] TJP ${$}: Remote (sender) is in past - offering push`);let C=await ho({ibGibAddr:S,live:!1,latestCommonFrameAddr:_,space:r});f.push({tjpAddr:$,addrs:Object.keys(C)})}else{let C=!1;try{C=await Ao({olderAddr:S,newerAddr:_,space:r})}catch(N){R&&console.log(`${s} isPastFrame just threw, but is an expected error if we don't have remote. verbose logging error though: ${E(N)} (I: 47ea08d0b418cf4aa8a502a7bcb80826)`)}if(C)R&&console.log(`${s} [TEST DEBUG] TJP ${$}: receiver is in past - requesting delta`),d.push({addr:_,tjpAddr:$,latestAddrAlreadyHave:S});else if(R&&console.log(`${s} [TEST DEBUG] TJP ${$}: DIVERGENCE DETECTED! conflictStrategy=${c}`),c==="abort")l.push({tjpAddr:$,receiverTipAddr:S,senderTipAddr:_,receiverKnowledgeTimelineAddrs:[],reason:"divergence",terminal:!0});else if(c===gt.optimisticWithLCS){let N=await z({addr:S,space:r});if(!N.success||N.ibGibs?.length!==1)throw new Error(`couldn't get local tip (${S}) from space (${r.ib}). errorMsg: ${N.errorMsg??"[unknown error (E: b3c3d823276300aa384ebdba4a8eb826)]"} (E: 83cb88a767e22bbda99c6788bec50526)`);let x=N.ibGibs[0],L=await Ec({timeline:x,space:r,metaspace:a});l.push({tjpAddr:$,receiverTipAddr:S,senderTipAddr:_,receiverKnowledgeTimelineAddrs:[...L,S],reason:"divergence",terminal:!1})}else throw new Error(`${s} Unsupported conflict strategy: ${c}. Only these currently implemented: ${Wr} (E: 8f12384180f8a718a983a749fe0adf26)`)}}if(l.some($=>$.terminal))throw R&&console.warn(`${s} ABORTING Sync Saga due to terminal conflicts: ${JSON.stringify(l)}`),new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify(l)} (E: f2edbe93cc07a63b38bfc013d2213b26)`);if(!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 24203af4600fb226ae6c1afbde442826)");let w={sagaId:e.data.uuid,stage:_e.ack,deltaRequestAddrInfos:d,pushOfferInfos:f};l?.length>0&&(w.conflicts=l);let A=await this.createSyncMsgStone({data:w,localSpace:r,metaspace:a});R&&console.log(`${s} ackStone created: ${X(A)} (I: 313708132dd53ff946befb7833657826)`);let G=await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[A],localSpace:r,metaspace:a}),T;if(f.length>0){let $=[];T=[];let _=f.flatMap(x=>x.addrs),S=await z({addrs:_,space:r}),D=S.rawResultIbGib?.data;if(!D)throw new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: 1a2cc8cb99a1ffa60837e45a8229b826)");let C=D.addrsNotFound??[],N=D.addrsErrored??[];if(S.ibGibs&&S.ibGibs.length===_.length)S.ibGibs.forEach(x=>{T.push(x)});else if(S.ibGibs&&S.ibGibs.length>0)if(S.ibGibs.forEach(L=>{T.push(L)}),T.length+C.length+N.length===_.length)C.forEach(L=>$.push(L)),N.forEach(L=>$.push(L));else throw C.length===0&&N.length===0?new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored both empty? (E: ef1b2cf5bab8de2298ec507abe04e826)"):new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored don't contain the addrs not found? (E: ae9e015109f8c3c3a813da584cd98826)");else console.warn(`${s} we were expecting all domainAddrs in mySpace (${r.ib}) but we couldn't get all of them. addrsNotFound: ${C??[]}. addrsErrored: ${N??[]}. Trying temp space (${n.ib}). (W: f61908e264f8dddd2e3fb9084463d826)`),_.forEach(x=>$.push(x));if($.length>0){R&&console.log(`${s} couldn't get all addrs in mySpace (${r.ib}). searchSecondSpaceAddrs: ${$} (I: 233fd954dbd84e51bca02fa8eed5f826)`);let x=await z({addrs:$,space:n});if(x.success&&x.ibGibs&&x.ibGibs.length===$.length)x.ibGibs.forEach(L=>T.push(L));else{x.ibGibs?.forEach(U=>T.push(U));let L=_.filter(U=>!T.map(O=>I({ibGib:O})).includes(U));throw new Error(`couldn't get some or all of addrs from either mySpace (${r.ib}) or myTempSpace (${n.ib}). addrsFailed: ${L} (E: 1394d412c4ffa4dd085f269b43338826)`)}}}return{frame:G,payloadIbGibsDomain:T}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{R&&console.log(`${s} complete.`)}}async handleAckFrame({sagaContext:e,sagaIbGib:t,initDomainGraph:r,mySpace:n,myTempSpace:a,metaspace:s}){let i=`${this.lc}[${this.handleAckFrame.name}]`;try{R&&console.log(`${i} starting... (I: 605b6860e898267a5b50c6d85704be26)`);let{messageData:c}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:n}),l=c,d=!0;if(!l)throw new Error(`${i} ackData falsy (E: 3b8415edc876084c88a25b98e2d55826)`);if(l.stage!==_e.ack)throw new Error(`${i} Invalid ack frame: ackData.stage !== SyncStage.ack (E: 2e8b0a94b5954a66a6a1a7a0b3f5b7a1)`);if(R&&console.log(`${i} ackData: ${X(l)} (I: b817c5571c5e916fe8f90b892b3e8e26)`),!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: e3f2e8f162484859787651b85c011826)");let f=l.conflicts?B(l.conflicts):[];R&&console.log(`${i} [CONFLICT DEBUG] Received conflicts from Ack: ${f.length}`),R&&f.length>0&&console.log(`${i} [CONFLICT DEBUG] Conflicts detail: ${JSON.stringify(f,null,2)}`);let b=f.filter($=>$.terminal);if(b.length>0)throw R&&console.warn(`${i} Received terminal conflicts from Ack: ${JSON.stringify(b)}`),new Error(`${i} Peer reported terminal conflicts. (E: 23a0096ee05a2ccfa89334e8f156b426)`);let p=[],u=[];if(f.length>0){R&&console.log(`${i} [CONFLICT DEBUG] Processing ${f.length} non-terminal conflicts`);for(let $ of f){let{receiverTipAddr:_,reason:S,senderTipAddr:D,terminal:C,receiverKnowledgeTimelineAddrs:N,tjpAddr:x}=$;if(C)throw new Error("(UNEXPECTED) conflict.terminal truthy? We expect this to already throw/abort the saga before this point in execution. (E: b42e982edca8b1156765de38f9e74626)");let L=r[D];if(!L)throw new Error(`(UNEXPECTED) senderTipIbGib falsy? initDomainGraph should have had the senderTipAddr (${D}) that was included in the ack frame conflicts. tjpAddr: ${x}. reason: ${S} (E: 3bd80f2054a924be98e6a7421bff4626)`);let{headIbGib:U,orderedPastIbGibs:O}=await Ja({timeline:L,getLatest:!0,metaspace:s,space:n}),M=O.map(re=>I({ibGib:re})),F=I({ibGib:U});if($.senderKnowledgeTimelineAddrs=[...M,F],U.gib!==L.gib&&($.senderTipAddr=F,!Object.keys(r).includes(F))){let re=await it({ibGibAddr:F,live:!0,space:n}),fe=Object.keys(re);for(let W of fe)r[W]||(r[W]=re[W])}let k=N.findLast(re=>M.includes(re));if(!k)throw new Error(`(UNEXPECTED) no latestCommonFrameAddr in the conflicts.receiverKnowledgeTimelineAddrs (${N.join(`
|
|
36
|
+
`)})? This would mean that it doesn't even have the tjpAddr (${x}). So what are we doing here? (E: 8931d1bdd6d8e100bf55f7c8a6924826)`);let Ee=await ho({ibGibAddr:F,live:!0,latestCommonFrameAddr:k,space:n}),pe=[];if(Object.keys(Ee).forEach(re=>{pe.push(re);let fe=Ee[re];p.push(fe)}),k===_)R&&console.log(`${i} [CONFLICT DEBUG] TJP ${x}: 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=pe,u.push($)}}u.length>0?d=!1:d=!0,R&&console.log(`${i} [CONFLICT DEBUG] Finished processing ${f.length} conflicts. Active (divergent) conflicts: ${u.length}. outgoingPayloadIbGibsDomain_conflicts.length (total outgoing payload ibgibs for ALL conflicts): ${p.length}`)}else R&&console.log(`${i} [CONFLICT DEBUG] No optimistic conflicts to process`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:l.deltaRequestAddrInfos||[],mySpace:n}),g=[...p,...m],y;g.length===0?g=void 0:y=g.map($=>I({ibGib:$}));let w={sagaId:t.data.uuid,stage:_e.delta,conflicts:u,payloadAddrsDomain:y,deltaRequestAddrInfos:void 0,proposeCommit:d},A;R&&console.log(`${i} Creating Delta Stone. Data stage: ${w.stage}`);let G=await this.createSyncMsgStone({data:w,rel8ns:A,localSpace:n,metaspace:s}),T=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[G],localSpace:n,metaspace:s});return R&&console.log(`${i} Delta Frame created. Rel8ns: ${JSON.stringify(T.rel8ns)}`),{frame:T,payloadIbGibsDomain:g}}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{R&&console.log(`${i} complete.`)}}async handleDeltaFrame({sagaContext:e,sagaIbGib:t,mySpace:r,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleDeltaFrame.name}]`;try{R&&console.log(`${s} starting... (I: a1d0a85eb4189466f86dfd61e3df2626)`);let{messageData:i}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:r}),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!==_e.delta)throw new Error(`${s} Invalid delta frame: deltaData.stage !== SyncStage.delta (E: 0c28c8d8f08a4421b8344e6727271421)`);R&&console.log(`${s} deltaData: ${X(c)} (I: a76008681df458cfbcdc4848f825a826)`),R&&console.log(`${s} [CONFLICT DEBUG] deltaData.payloadAddrsDomain count: ${c.payloadAddrsDomain?.length||0}`);let{conflictStrategy:l,graftPreference:d}=t.data,{deltaRequestAddrInfos:f,payloadAddrsDomain:b,proposeCommit:p}=c,u=c.proposeCommit??!1,m=e.payloadIbGibsDomain??[];R&&console.log(`${s} [CONFLICT DEBUG] Fulfilling ${(c.deltaRequestAddrInfos||[]).length} peer requests`);let g=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:c.deltaRequestAddrInfos||[],mySpace:r});R&&console.log(`${s} [CONFLICT DEBUG] Outgoing payload size (with deps): ${g.length}`);let y=c.conflicts?B(c.conflicts):[],w=y.filter($=>!$.resolved);if(w.length>0){if(l!==gt.optimisticWithLCS)throw new Error(`(UNEXPECTED) conflictStrategy (${l}) is not ${gt.optimisticWithLCS}? right now, this is the only one we've implemented. (E: ba3e08d92a66b24075016208a0f83226)`);for(let $ of w){let _={};if(m.length>0){await wr({ibGibs:m,space:n});for(let j of m)_[I({ibGib:j})]=j}for(let j of $.accretivePayloadAddrs??[]){let we=m.find(ke=>I({ibGib:ke})===j);we&&(_[j]=we)}$.latestCommonFrameAddr;let{receiverKnowledgeTimelineAddrs:S,senderKnowledgeTimelineAddrs:D,reason:C,receiverTipAddr:N,senderTipAddr:x,tjpAddr:L}=$;if(!D)throw new Error("(UNEXPECTED) senderKnowledgeTimelineAddrs falsy? (E: 2a608892d11bd848e8f0c7a8d676d826)");let U=await it({ibGibAddrs:[N],live:!0,space:r}),O=Object.values(U);await wr({ibGibs:O,space:n});for(let j of S){let we=U[j];await J({ibGib:we,space:n})}for(let[j,we]of Object.entries(U))_[j]||(_[j]=we);let M=D.findLast(j=>S.includes(j));if(!M)throw new Error("(UNEXPECTED) latestCommonFrameAddr falsy? how we can have a conflict without a common point in history? (E: 53de0a181838b3e5bf98d0887994b826)");let F=await ho({ibGibAddr:$.receiverTipAddr,latestCommonFrameAddr:M,live:!0,space:r});Object.values(F).forEach(j=>g.push(j));let Ee=await No.instance.graftTimelines({conflictStrategy:l,timelineAddrsA:D,timelineAddrsB:S,latestCommonFrameAddr:M,ibGibReadCache:_,space:n,graftPreference:d||Bt.timestamp}),{dnasCreatedInGraft:pe,dnasReplayed:oe,intermediateIbGibsCreatedInGraft:re,ancillaryIbGibsCreated:fe,newGraftTip:W,graftInfoCreated:Z}=Ee;if($.createdDnaAddrs=pe.map(j=>I({ibGib:j})),$.replayedDnaAddrs=oe.map(j=>I({ibGib:j})),$.createdDomainAddrs=[...re.map(j=>I({ibGib:j})),...fe.map(j=>I({ibGib:j})),I({ibGib:Z}),I({ibGib:W})],!W.rel8ns)throw new Error("(UNEXPECTED) newGraftTip.rel8ns falsy? we expect this to have graftinfo rel8ns, let alone dna (E: 718788f5a44e815618ac1ba621c8a826)");let se=W.rel8ns[Yr];if(!se||se.length===0)throw new Error(`(UNEXPECTED) newGraftTip.rel8ns.${Yr} falsy/empty? we expect to always have graft info attached to timelines that are grafted. (E: 45abf31654c8aa517df4d0882b996826)`);$.graftInfoAddr=se.at(-1);let Y=[pe,oe,re,fe,[Z,W]];for(let j of Y.flat())if((await ne({ibGib:j})??[]).length>0){console.dir(j);debugger;console.log(X(j))}$.accretivePayloadAddrs??=[],Y.forEach(j=>j.forEach(we=>{let ke=I({ibGib:we});$.accretivePayloadAddrs.includes(ke)||$.accretivePayloadAddrs.push(ke),g.some(tt=>I({ibGib:tt})===ke)||g.push(we)})),$.resolved=!0}}let A=[],G=g.length>0,T=A.length>0;if(G||T){let $={sagaId:c.sagaId,stage:_e.delta,payloadAddrsDomain:g.map(D=>I({ibGib:D})),requests:T?A:void 0,conflicts:y},_=await this.createSyncMsgStone({data:$,localSpace:r,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:r,metaspace:a}),payloadIbGibsDomain:g}}else if(u){let $=await _o({sagaIbGib:t,space:r}),_=await es({history:$});return _.length>0?{frame:await this.createCommitFrame({sagaIbGib:t,errors:_,metaspace:a,mySpace:r})}:(await this.executeLocalCommit({sagaHistory:$,deltaFrame:t,localTempSpace:n,localSpace:r,metaspace:a}),{frame:await this.createCommitFrame({sagaIbGib:t,errors:void 0,metaspace:a,mySpace:r})})}else{let $={sagaId:c.sagaId,stage:_e.delta,proposeCommit:!0,conflicts:y},_=await this.createSyncMsgStone({data:$,localSpace:r,metaspace:a}),S=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:r,metaspace:a});if(c.proposeCommit){R&&console.log(`${s} Peer proposed commit. Accepting & Committing.`);let D={sagaId:c.sagaId,stage:_e.commit,success:!0},C=await this.createSyncMsgStone({data:D,localSpace:r,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:S,msgStones:[C],localSpace:r,metaspace:a})}}return{frame:S,payloadIbGibsDomain:g}}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{R&&console.log(`${s} complete.`)}}async executeLocalCommit({deltaFrame:e,commitFrame:t,sagaHistory:r,metaspace:n,localSpace:a,localTempSpace:s}){let i=`${this.lc}[${this.executeLocalCommit.name}]`;try{if(R&&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 l=!!e?e:t;if(!l)throw new Error("(UNEXPECTED) !currentFrame? something wrong with my logic. (E: 4ec0ce6625cc1d677bc902c839ca1a26)");let d=To({sagaFrame:l});if(R&&console.log(`${i} currentFrameOrigin: ${d} (I: 3add8f8390c89743ae554bd3cc60b826)`),!l.data)throw new Error("(UNEXPECTED) currentFrame.data falsy? (E: a8be68d48668d93d992d793834823826)");let f=[],b=h(A=>{f.includes(A)||f.push(A)},"fnAddPayloadAddr"),p=r.filter(A=>{let G=To({sagaFrame:A.sagaIbGib});return d!==G});r.filter(A=>{let G=To({sagaFrame:A.sagaIbGib});return d===G}).forEach(A=>{if(!A.sagaIbGib.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 34d7f8cdee14717ce828878d98f89826)");A.msgStones.forEach(G=>{if(!G.data)throw new Error("(UNEXPECTED) msgStone.data falsy? (E: 21406101f91847514cc759c8a7382f26)");if(G.data.stage===_e.ack){let T=G.data;T.pushOfferInfos&&T.pushOfferInfos.length>0&&T.pushOfferInfos.forEach($=>{$.addrs.forEach(_=>b(_))})}else if(G.data.stage===_e.delta){let T=G.data;T.payloadAddrsDomain&&T.payloadAddrsDomain.length>0&&T.payloadAddrsDomain.forEach($=>b($))}})}),R&&console.log(`${i}[${d}] allPayloadAddrsDomainTransferred: ${f.length>0?f.join(", "):"none"} (I: a1950eb3ca95bdc9ec18a4b8823e9826)`);let m=[];if(f.length>0){let A=await z({addrs:f,space:s});if(A.success&&A.ibGibs&&A.ibGibs.length===f.length)m=A.ibGibs.concat();else{if(!A.rawResultIbGib)throw new Error("(UNEXPECTED) !resGetAllTransferred.rawResultIbGib falsy? (E: dc6cf8729668f4fbe8c024f887d97a26)");let{addrsNotFound:G,addrsErrored:T,errors:$}=A.rawResultIbGib.data;throw new Error(`(UNEXPECTED) we couldn't get all addrs transferred throughout the saga from the tempspace (${s.ib})? addrsNotFound: ${G??[]}. addrsErrored: ${T??[]}. errors: ${$??[]}(E: 222e341e634862b4d88ae7282584d826)`)}}let g=[],y=await ts({sagaHistory:r});if(y)for(let A of y){if(!A.resolved)throw new Error("(UNEXPECTED) finalConflict.resolved falsy? right now, we're expecting to resolve all conflicts. (E: a40ca8f1f54665407892ec21123a4f26)");if(!A.graftInfoAddr)throw new Error("(UNEXPECTED) finalConflict resolved but graftInfoAddr falsy? we're expecting all resolved conflicts to have a graftInfoAddr (E: d082488347570947b82008a835200126)");if(!(await Ve({addrs:[A.graftInfoAddr],space:s})).at(0))throw new Error(`(UNEXPECTED) couldn't get finalConflictGraftInfo from localTempSpace (${s})? (E: 35e3c8130608d991e8fb295807812826)`);let{createdDnaAddrs:$,replayedDnaAddrs:_,createdDomainAddrs:S}=A;if(!$||$.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDnaAddrs falsy/empty? (E: 9689f8be5bd19650b8d4a058b65db826)");if((!_||_.length===0)&&R&&console.log(`${i} finalConflict.replayedDnaAddrs falsy/empty (I: e88eb8a76b5815e07f10cbb2fa2ab826)`),!S||S.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDomainAddrs falsy/empty? (E: cc41251d1acfe91a48d1b6080259ed26)");(await Ve({addrs:_&&_.length>0?[...$,..._,...S]:[...$,...S],space:s})).forEach(C=>g.push(C))}let w=[];if(m.forEach(A=>w.push(A)),g.forEach(A=>w.push(A)),w.length===0)R&&console.log(`${i}[${d}] no changes on this end (I: fa30d18e83a87ee9e8487fbb5d632b26)`);else{R&&console.log(`${i}[${d}] ${w.length} changes detected (I: fa30d18e83a87ee9e8487fbb5d632b26)`),R&&console.log(`${i} put all into localSpace (${a.ib}) starting... (I: d5e0d9870e380b61e80c729660058826)`);let{payload_Dnas:A,payload_NonDnas:G}=await wr({ibGibs:w,space:a});R&&console.log(`${i} put all into localSpace (${a.ib}) complete. (I: d5e0d9870e380b61e80c729660058826)`);let T=await Ic({sagaHistory:r,myTempSpace:s}),{mapWithTjp_NoDna:$,mapWithTjp_YesDna:_,mapWithoutTjps:S}=nt({ibGibs:G,filterPrimitives:!0});R&&console.log(`${i} register mapWithoutTjps starting... (I: 2b84d8f8dda85adde88696d8419bf726)`);let D=Object.values(S);for(let U of D)R&&console.log(`${i} registering ${I({ibGib:U})} (I: 4647b4f42d27cffe0fbfce8846755826)`),await n.registerNewIbGib({ibGib:U,space:a});R&&console.log(`${i} mapWithoutTjps complete. (I: 2b84d8f8dda85adde88696d8419bf726)`),R&&console.log(`${i} register mapWithTjp_NoDna starting... (I: 96e648e4db382499b8bfaa1b37c24826)`);let C=at({ibGibs:Object.values($)}),N=Object.keys(C);for(let U of N){let O=C[U];for(let M of O)await n.registerNewIbGib({ibGib:M,space:a})}R&&console.log(`${i} register mapWithTjp_NoDna complete. (I: 96e648e4db382499b8bfaa1b37c24826)`),R&&console.log(`${i} register mapWithTjp_YesDna starting... (I: d54a820e9442dee4681f6228a6795926)`);let x=at({ibGibs:Object.values(_)}),L=Object.keys(x);for(let U of L){let O=x[U];for(let M of O)T.includes(I({ibGib:M}))||await n.registerNewIbGib({ibGib:M,space:a})}R&&console.log(`${i} register mapWithTjp_YesDna complete. (I: d54a820e9442dee4681f6228a6795926)`)}}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{R&&console.log(`${i} complete.`)}}async createCommitFrame({sagaIbGib:e,errors:t,metaspace:r,mySpace:n}){let a=`[${this.createCommitFrame.name}]`;try{R&&console.log(`${a} starting... (I: 48fc57c023f80122135a284855757526)`);let s=t&&t.length>0?{sagaId:e.data.uuid,stage:_e.commit,success:!1,errors:t}:{sagaId:e.data.uuid,stage:_e.commit,success:!0},i=await this.createSyncMsgStone({data:s,localSpace:n,metaspace:r});return await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[i],localSpace:n,metaspace:r})}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{R&&console.log(`${a} complete.`)}}async handleCommitFrame({sagaIbGib:e,mySpace:t,myTempSpace:r,metaspace:n}){let a=`${this.lc}[${this.handleCommitFrame.name}]`;try{if(R&&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 _o({sagaIbGib:e,space:t}),i=await es({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:r,metaspace:n}),console.error(`${a} NAG ERROR (NOT THROWN): implement cleanup logic, including add a cleanup method to the peer (E: 3a9a24befb98a981a88fbdbf52920e26)`),R&&console.log(`${a} Peer committed. Finalizing saga locally. Saga Complete.`),{sagaComplete:!0})}}catch(s){let i=`${a} ${E(s)}`;return console.error(i),{frame:await this.createCommitFrame({sagaIbGib:e,errors:[i],metaspace:n,mySpace:t})}}finally{R&&console.log(`${a} complete.`)}}async createSyncMsgStone({data:e,rel8ns:t,localSpace:r,metaspace:n}){let a=`${this.lc}[${this.createSyncMsgStone.name}]`;try{R&&console.log(`${a} starting... (I: 5f7f98e8ff980364f7191fcee4531e26)`);let s=await Ac({data:e}),i=await H.stone({ib:s,parentPrimitiveIb:rs,data:e,rel8ns:t,uuid:!0});return R&&console.log(`${a} Created stone: ${I({ibGib:i})}`),await n.put({ibGib:i,space:r}),await n.registerNewIbGib({ibGib:i}),i}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{R&&console.log(`${a} complete.`)}}async getPayloadsForRequestedInfos({deltaRequestAddrInfos:e,mySpace:t}){let r=`${this.lc}[${this.getPayloadsForRequestedInfos.name}]`;try{R&&console.log(`${r} starting... (I: 4fe13d0d80050f20a8b74ba80cee5826)`);let n={};for(let{addr:s,latestAddrAlreadyHave:i}of e){let c;if(i?c=await ho({ibGibAddr:s,latestCommonFrameAddr:i,space:t,live:!0}):c=await it({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(d=>{n[I({ibGib:d})]=d})}return Object.values(n)}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{R&&console.log(`${r} complete.`)}}async evolveSyncSagaIbGib({prevSagaIbGib:e,conflictStrategy:t,graftPreference:r,msgStones:n,localSpace:a,metaspace:s,sessionIdentity:i}){let c=`${this.lc}[${this.evolveSyncSagaIbGib.name}]`;try{if(!n||n.length===0)throw new Error(`${c} msgStones required (E: d13f8afcfb8816aeb26baae7df3ef726)`);let l=n[0].data;if(!l?.sagaId||!l?.stage)throw new Error(`${c} Invalid stone data (missing sagaId or stage) (E: c004f85ce8f8958b11839f8d68c38826)`);let d=l.sagaId,f=l.stage;for(let b of n){let p=b.data;if(p.sagaId!==d)throw new Error(`${c} Mismatched sagaId in stones. Expected ${d}, got ${p.sagaId} (E: 29e02719e426ecbbf8ee66887a2be226)`);if(p.stage!==f)throw new Error(`${c} Mismatched stage in stones. Expected ${f}, got ${p.stage} (E: d12c6571b0882f762921b60880c3f826)`)}if(e){let b=[{rel8nName:Ke,ibGibs:n}];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 pc({timeline:e,rel8nInfos:b,rel8nRemovalInfos:p,metaspace:s,space:a,noDna:!0})}else{let b={uuid:d,n:0,isTjp:!0,conflictStrategy:t,graftPreference:r};if(i){let y=ye({ibGib:i});if(!y)throw new Error("(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)");b.sessionIdentityTjpAddr=y}let p=await $c({data:b}),u=n.map(y=>I({ibGib:y})),m={[Ke]:u},g=await gc({space:a,metaspace:s,ib:p,data:b,rel8ns:m,parentIb:Ya,noDna:!0});if(g.intermediateIbGibs)throw new Error("(UNEXPECTED) resNew.intermediateIbGibs? we were assuming we were creating a single frame. (E: 456818147235d991ccb4d10d0bbe4826)");return g.newIbGib}}catch(l){throw console.error(`${c} ${E(l)}`),l}}async getStageAndPayloadFromFrame({sagaFrame:e,space:t}){let r=`${this.lc}[${this.getStageAndPayloadFromFrame.name}]`;try{if(R&&console.log(`${r} 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 z({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: ${I(e)} (E: 43eae8579e289d016741b5526052f226)`)}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{R&&console.log(`${r} complete.`)}}sortTimelinesTopologically(e){let t=`${this.lc}[${this.sortTimelinesTopologically.name}]`,r=Object.keys(e);if(r.length===0)return[];let n={};r.forEach(d=>{e[d].forEach(f=>{let b=I({ibGib:f});n[b]=d})});let a={};r.forEach(d=>a[d]=new Set),r.forEach(d=>{e[d].forEach(f=>{f.rel8ns&&Object.values(f.rel8ns).flat().forEach(b=>{if(!b)return;let p=n[b];p&&p!==d&&a[d].add(p)})})});let s=new Set,i=new Set,c=[],l=h(d=>{if(i.has(d)){console.warn(`${t} Cycle detected involving ${d}. Ignoring edge to break cycle. (W: 7e7352347102431aa5318db962459929)`);return}s.has(d)||(i.add(d),a[d].forEach(f=>l(f)),s.add(d),i.delete(d),c.push(d))},"visit");return r.forEach(d=>{s.has(d)||l(d)}),c}};var ze=!1,_s=class o extends Ar{static{h(this,"SyncPeer_V1")}lc=`[${o.name}]`;opts;payloadIbGibsDomainReceived$;currentSessionIdentity;get currentSessionIdentityAddr(){return this.currentSessionIdentity?I({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:r,sagaId:n,localMetaspace:a,localSpace:s}=this.opts;if(!r)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!n)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let i=await r(),c=await _n({senderSecret:i,sagaId:n}),d=await new Mt().sign({latestKeystone:this.currentSessionIdentity,masterSecret:c,claim:{verb:ut,target:e},metaspace:a,space:s});return this.currentSessionIdentity=d,d}catch(r){throw console.error(`${t} ${E(r)}`),r}}async signContextConnect({challengeUuid:e,demandedIds:t}){let r=`${this.lc}[${this.signContextConnect.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!n)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!a)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let c=await n(),l=await _n({senderSecret:c,sagaId:a}),f=await new Mt().sign({latestKeystone:this.currentSessionIdentity,masterSecret:l,poolId:on,requiredChallengeIds:t,claim:{verb:bo,target:e},metaspace:s,space:i});return this.currentSessionIdentity=f,f}catch(n){throw console.error(`${r} ${E(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 ws()}async connect(e){let t=`${this.lc}[${this.connect.name}]`;try{ze&&console.log(`${t} starting... (I: ad89d8137351662fb8a30114a1fa4826)`),await this.preConnectCheck(e),await this.connectImpl(e)}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ze&&console.log(`${t} complete.`)}}async establishSessionIdentity(){let e=`${this.lc}[${this.establishSessionIdentity.name}]`;try{if(ze&&console.log(`${e} starting... (I: cdc208b8197f646e0abe05f101a0f126)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Call initializeOpts first. (E: 5c6a6bf6b872e4ce08055b71348e8a26)");let{senderIdentity:t,fnSenderSecret:r,senderDomainAddr:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!t||!r){ze&&console.log(`${e} no senderIdentity/fnSenderSecret \u2014 skipping establish (I: f29348a77d1542326d14043ea4b69126)`);return}if(!n)throw new Error("(UNEXPECTED) senderDomainAddr falsy but senderIdentity/fnSenderSecret truthy? if identity is used, senderDomainAddr must be provided. (E: c288fa8e9d3d82fc)");let c=I({ibGib:t}),l=ye({ibGib:t});if(!l)throw new Error("(UNEXPECTED) senderIdentityTjpAddr falsy? (E: d5d8c3ab25a83a2c127904fe96de1526)");if(!a)throw new Error("(UNEXPECTED) sagaId falsy? Must be set in initializeOpts before calling establishSessionIdentity. (E: c6ba389d51b8af07d82458f875cf9826)");let d=await r();if(!d)throw new Error("senderSecret falsy. senderSecret required. (E: 1a8b0298bf78cbdf284b7988983b9826)");let f=await _n({senderSecret:d,sagaId:a}),b=new Mt;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:c,senderIdentityTjpAddr:l};this.opts.targetAddrs&&(p.targetAddrs=this.opts.targetAddrs);let u=await b.genesis({masterSecret:f,configs:[this.opts.sessionConnectPoolConfig,this.opts.sessionSyncPoolConfig],frameDetails:p,metaspace:s,space:i}),m=I({ibGib:u}),g=await b.sign({latestKeystone:t,masterSecret:d,claim:{verb:ut,target:m},metaspace:s,space:i});await this.postEstablishToReceiver({newSenderIdentity:g,sessionIdentity:u}),this.currentSessionIdentity=u}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ze&&console.log(`${e} complete.`)}}async initializeOpts(e){let t=`${this.lc}[${this.initializeOpts.name}]`;try{ze&&console.log(`${t} starting... (I: 31bd5fda37c89fa37fbaf14daf5fe726)`),this.opts=e}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ze&&console.log(`${t} complete.`)}}setOptionalOpts(e){let t=`${this.lc}[${this.setOptionalOpts.name}]`;try{if(ze&&console.log(`${t} starting... (I: ae5ddbd3577db267f84743175a736626)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0dd4d6080a6e2f31d86cf4d86e11b826)");ze&&console.log(`${t} updating opts. arg keys: ${Object.keys(e)} (I: 452d78a558f8fc3468c8e2e68c70b226)`),this.opts={...this.opts,...e}}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ze&&console.log(`${t} complete.`)}}async authenticateAndValidate({context:e}){let t=`${this.lc}[${this.authenticateAndValidate.name}]`;try{if(ze&&console.log(`${t} starting... (I: add238055cd84a222c5b8c89913af526)`),!this.opts)throw new Error("(UNEXPECTED) opts falsy in authenticateValidateAuthorize (E: b7e5a8ad99d84e1ba8d8f7facd288826)");let{localSpace:r}=this.opts,n=await Gc({context:e,space:r});if(n.length>0)throw new Error(`invalid context authentication. authenticationErrors: ${n} (E: da89da5ee1269aeb78952d475d607526)`);let a=await Go({context:e});if(a.length>0)throw new Error(`invalid context received. validationErrors: ${a} (E: 8b34c875c968af29bc433138e57a7826)`)}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ze&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{if(ze&&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 r=await this.sendContextRequest(e);if(r){let n=await _o({sagaIbGib:e.sagaFrame,space:this.opts.localSpace});return r}else{ze&&console.log(`${t} No response from peer. this may be normal if we just sent the very last commit frame. (I: 1855b7728c8898e1f9c001f8170ba826)`);return}}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ze&&console.log(`${t} complete.`)}}async getLocalIbGib(e){let t=`${this.lc}[${this.getLocalIbGib.name}]`;try{if(ze&&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 r=await z({space:this.opts.localSpace,addr:e});if(r.success&&r.ibGibs&&r.ibGibs.length===1)return r.ibGibs[0];throw new Error(`couldn't get addr (${e}) from local space ${this.opts.localSpace}. reason: ${r.errorMsg??"unknown error (E: 926ef8bf4fcc299ab89dba34ea691a26)"} (E: d8a89807e471d3f8b938ab21df44cb26)`)}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{ze&&console.log(`${t} complete.`)}}};var Re=!1,Gr=class o extends _s{static{h(this,"SyncPeerInnerspace_V1")}lc=`[${o.name}]`;get classname(){return o.name}constructor(e,t){super(e,t)}async preConnectCheck(e){let t=`${this.lc}[${this.preConnectCheck.name}]`;try{if(Re&&console.log(`${t} starting... (I: af5dc1a0bf980848b84e50515614be26)`),!e.sagaId)throw new Error(`${t} sagaId required for connect (E: 8a4c0a9b8f1d4f2b1c3b5d6e8a4c0a9b)`);if(!this.opts)throw new Error("this.opts falsy. required to connect (E: 4c24fd577f9cd695a8bf0dc8ddea6826)")}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Re&&console.log(`${t} complete.`)}}async connectImpl(e){let t=`${this.lc}[${this.connectImpl.name}]`;try{if(Re&&console.log(`${t} starting... (I: 2b8f8040d9b4c48a735c021c33f2a826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: d617e80d8e082bc76853dba8bb87cc26)")}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Re&&console.log(`${t} complete.`)}}async postEstablishToReceiver({newSenderIdentity:e,sessionIdentity:t}){let r=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if(Re&&console.log(`${r} starting... (I: 6ca5e81a59a861c1f327df0885198a26)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 1bb4b875bdb8e88bedff5ab80d1d5826)");let{receiverMetaspace:n,receiverSpace:a}=this.opts;await n.put({ibGib:e,space:a}),await n.registerNewIbGib({ibGib:e,space:a}),await n.put({ibGib:t,space:a}),await n.registerNewIbGib({ibGib:t,space:a})}catch(n){throw console.error(`${r} ${E(n)}`),n}finally{Re&&console.log(`${r} complete.`)}}async ensureReceiverTempSpace(){let e=`${this.lc}[${this.ensureReceiverTempSpace.name}]`;try{if(Re&&console.log(`${e} starting... (I: bab87f15dea77cd4892bd8a8d2e65826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0f85bd4c3efdbee2a829aca860c48926)");if(!this.opts.receiverTempSpace){let{receiverMetaspace:t}=this.opts,n=`tmp_sync_recv_${(crypto.randomUUID?crypto.randomUUID():Math.random().toString(36)).substring(0,8)}`,a=await t.createNewLocalSpace({opts:{allowCancel:!1,spaceName:n,getFnPrompt:t.getFnPrompt,logalot:Re}});if(!a)throw new Error("(UNEXPECTED) receiverTempSpace falsy? couldn't create a temp space? (E: a6b8f86b0f58384b884a33b82924b826)");await a.initialized,this.opts.receiverTempSpace=a}return this.opts.receiverTempSpace}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Re&&console.log(`${e} complete.`)}}async sendContextRequest(e){let t=`${this.lc}[${this.sendContextRequest.name}]`;try{if(Re&&console.log(`${t} starting... (I: bab87f15dea77cd4892bd8a8d2e65826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: d8b1348e3233810128999596b1fa5826)");await this.ensureReceiverTempSpace();let{localSpace:r,localTempSpace:n,receiverSpace:a,receiverCoordinator:s,receiverMetaspace:i,receiverTempSpace:c}=this.opts;Re&&console.log(`${t} starting...Context: ${I({ibGib:e})}`);let{sagaFrame:l}=e;if(!e.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 1d2ac8a9b991d451e8900588057fe626)");if(!e.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 3508786f0d8880bcadd346282a807826)");if(!e.rel8ns.sagaFrame)throw new Error("(UNEXPECTED) context.rel8ns.sagaFrame falsy? (E: ac06782ad538be406882605f0a83aa26)");if(!e.sagaFrame)throw new Error("(UNEXPECTED) context.sagaFrame falsy? (E: 79cd98a6d9b88a591f4596c8bc58ff26)");if(!l.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: f30e290a8b770e1b387377420ea73a26)");if(!l.rel8ns)throw new Error("(UNEXPECTED) sagaFrame.rel8ns falsy? (E: f888caa698b8cf6b4893b7fd6df09726)");if(!c)throw new Error("(UNEXPECTED) receiverTempSpace falsy? (E: 3b46d838f6fc645c58b29215bfddb826)");if(!n)throw new Error("(UNEXPECTED) localTempSpace falsy? (E: b187a8f913c2295ae90d7ae2b47b6a26)");let{sagaIbGib:d,msgStones:f}=await Kr({sagaIbGib:l,localSpace:r});if(f.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1? we're only geared for a single msg stone that is always present (not 0, not greater than 1) (E: 2d3138ed130f1aca116551889483e826)");let b=f[0];if(!b.data)throw new Error("(UNEXPECTED) sync saga message ibgib.data falsy? (E: 61ec18743988ad3cbab2072d1dd69826)");let p=[b,l,e].map(A=>Fe({ibGib:A}));e.signedSessionIdentity&&p.push(Fe({ibGib:e.signedSessionIdentity})),Re&&console.log(`${t} putting into receiverSpace: ${a.ib} (I: 1ba18b14a26bdd0e7800da4812898826)`),await ce({ibGibs:p,space:a});for(let A of p)await J({ibGib:A,space:a,fnBroadcast:void 0});e.payloadIbGibsDomain&&e.payloadIbGibsDomain.length>0&&(Re&&console.log(`${t} putting into receiverTempSpace: ${c.ib} (I: d0cea920b818393d68118bc8a1515526)`),await wr({ibGibs:e.payloadIbGibsDomain,space:c}));let u=await s.continueSync({sagaContext:e,metaspace:i,mySpace:a,myTempSpace:c,peer:this});if(Re&&console.log(`${t} receiverCoordinator.continueSync responseCtx: ${u?X(u):"undefined"} (I: fb2831decde1f2b3589021f85ab19126)`),!u){Re&&console.log(`${t} receiver produced undefined response context. (I: 2e1888ffc9e836689d5b171887c36d26)`);return}let{msgStones:m}=await Kr({sagaIbGib:u.sagaFrame,localSpace:a});if(m.length!==1)throw new Error("(UNEXPECTED) msgStonesResponse.length !== 1? we're only geared for a single msg stone that is always present (not 0, not greater than 1) (E: 2d3138ed130f1aca116551889483e826)");let g=m[0];if(!g.data)throw new Error("(UNEXPECTED) sync saga message ibgib.data falsy? (E: 61ec18743988ad3cbab2072d1dd69826)");let y=[g,u.sagaFrame,u].map(A=>Fe({ibGib:A}));await ce({ibGibs:y,space:r});for(let A of y)await J({ibGib:A,space:r,fnBroadcast:void 0});let w=u.payloadIbGibsDomain;return w&&(new Promise(async(A,G)=>{let T=`${t}[putPayloadsPromise]`;try{if(Re&&console.log(`${T} starting... (I: 4133e736b4c80d2cf94448b87b206826)`),Re)for(let _=0;_<10;_++)console.warn(`${t} ARTIFICIALLY DELAYING PAYLOADS TO MIMIC TRANSFER LATENCY. REMOVE THIS DELAY!! (W: 5e7b28f1daa82d955897e9d8cdb16f26)`),await De(16);await wr({ibGibs:w,space:n});for(let $ of w)await this.payloadIbGibsDomainReceived$.next($);Re&&console.log(`${T} complete.`),A()}catch($){let _=`${T} ${E($)}`;console.error(_),Re&&console.log(`${T} complete. (errored)`),G(_)}}),delete u.payloadIbGibsDomain),u}catch(r){throw console.error(`${t} ${E(r)}`),r}finally{Re&&console.log(`${t} complete.`)}}};var Ts={classname:Gr.name};var Tu="[branch-graph-helpers]",Gs=!1;async function kc({sourceSpace:o,targetBranchSpace:e,rootItemIbGib:t,branchName:r,metaspace:n}){let a=`${Tu}[${kc.name}]`;try{if(Gs&&console.log(`${a} starting... (I: bc5303fbf9f80cbce8423bc174313826)`),!o||!e||!t||!n)throw new Error("sourceSpace, targetBranchSpace, rootItemIbGib, and metaspace are required (E: d97b285b899e7b427840008e6ff69826)");let s=new Tr,i=new Tr,c=new Gr(B(Ts));await c.initialized,await c.initializeOpts({localMetaspace:n,localSpace:o,receiverSpace:e,receiverCoordinator:i,receiverMetaspace:n}),await(await s.sync({peer:c,localSpace:o,metaspace:n,domainIbGibs:[t]})).done,Gs&&console.log(`${a} SyncSagaCoordinator sync initiated for ${t.ib} (I: f0a798bee4ae2b73f8e7e5ac921bc826)`);let d=1,f;return r&&n&&(f=await Xr({branchName:r,rootItem:t,space:e,metaspace:n})),Gs&&console.log(`${a} Populated target branch space via SyncSagaCoordinator (I: c0ec8e54539765f6fe250bc820dee826)`),{syncedCount:d,branchIbGib:f}}catch(s){throw console.error(`${a} ${E(s)} (E: 353e4f45b478d33e48f898a65893b826)`),s}finally{Gs&&console.log(`${a} complete. (I: 4036b819429e2a63add97a8843bbc826)`)}}h(kc,"populateBranchSpaceFromGraph");var Gu="[branch-cmd]",Sr=!1;async function Su(o){let e=`${Gu}[${Su.name}]`;try{return Sr&&console.log(`${e} starting... (I: cf8e88cca798e6cb48267f950007e826)`),o.branchName?.trim()?await Ob(o):await qc(o)}catch(t){throw console.error(`${e} ${E(t)} (E: ae6e9841d2283328f891f3f6b1a25226)`),t}finally{Sr&&console.log(`${e} complete. (I: 3376f633d188c591816c9058ab659426)`)}}h(Su,"executeVcsBranch");async function Ob(o){let e=`[${Ob.name}]`;try{Sr&&console.log(`${e} starting... (I: 672388ad93a52955c8147b4f76b8cb26)`);let{metaspace:t,localSpace:r,activeBranchSpace:n,sourceBranchSpace:a,galaxyIbGib:s,branchName:i,sourceBranchName:c,itemPath:l}=o,d=Wf(i);if(!d.isValid||!i)throw new Error(`Invalid branch name "${i??""}": ${d.error} (E: 5d1208912ba80526aaf32bf3dd6b5c26)`);let f=i.trim(),b=c?.trim()||s.data.policy?.defaultBranch||Te;if((await ka({galaxyIbGib:s,metaspace:t})).some(F=>F.branchName.toLowerCase()===f.toLowerCase()))throw new Error(`branch with branchName "${f}" already exists. (E: 507808912ba80526aaf32bf3dd6b5c26)`);let{branchIbGib:u,branchSpace:m,rootItemAddr_latest:g,rootItemIbGib_latest:y}=await Xe({galaxyIbGib:s,branchName:b,metaspace:t}),w=a||n||m;if(!w)throw new Error(`(UNEXPECTED) effectiveSourceSpace falsy for branch "${b}". (E: 792bcf7429188d67a502efc2e426)`);let A=y,G;if(l&&l.trim().length>0){G=l.trim().replace(/\\/g,"/").replace(/^\.\//,"");let F=new Map;await jc({item:y,space:w,metaspace:t,currentRelPath:"",outMap:F});let k=F.get(G);if(!k)throw new Error(`Item '${l}' not found in source branch '${b}' (E: ca1617c6476aaecbe8cc78db2c3ca826)`);A=k}let{space:T,spaceId:$}=await un({metaspace:t,branchName:f});await kc({sourceSpace:w,targetBranchSpace:T,rootItemIbGib:A,metaspace:t});let _=I({ibGib:u}),S=qe(w.ib),D=ot({spaceId:S,ibGibAddr:_}),C=await Xr({branchName:f,rootItem:A,space:T,metaspace:t,parentBranchSqAddr:D,parentBranchName:u.data.name,scopedItemPath:G}),N=I({ibGib:C}),x=ot({spaceId:$,ibGibAddr:N}),L=await tc({parentBranchIbGib:u,childBranchSqAddr:x,space:w,metaspace:t}),U=s,O=(s.data.policy?.defaultBranch||Te).toLowerCase();if(b.toLowerCase()===O){let F=I({ibGib:L}),k=ot({spaceId:S,ibGibAddr:F});U=await mt({space:r,metaspace:t,galaxyIbGib:s,dataToUpdate:{trunkBranchSqAddr:k,"$@branch":[k]}})}let{branches:M}=await qc({...o,branchName:void 0,galaxyIbGib:U});return{branches:M,createdBranchName:f,createdBranchAddr:N,updatedGalaxy:U}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Sr&&console.log(`${e} complete.`)}}h(Ob,"executeVcsBranch_createNewBranch");async function qc(o){let e=`[${qc.name}]`;try{Sr&&console.log(`${e} starting... (I: 265118f9fc182b4e0802b926eb83c826)`);let{metaspace:t,galaxyIbGib:r,currentBranchName:n}=o,a=n||r.data.policy?.defaultBranch||Te,s=await nc({galaxyIbGib:r,metaspace:t}),i=[];for(let c of s){let{name:l}=c.data,d=I({ibGib:c});if(!c.rel8ns)throw new Error(`(UNEXPECTED) branchIbGib.rel8ns falsy? branchAddr: ${d} (E: 3a0f47a46fb858e6f5ddfb684ceb7826)`);if(!c.rel8ns.b2tfs_item)throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item falsy? branchAddr: ${d} (E: aaa7583adf555e9218a5cfae47540126)`);if(c.rel8ns.b2tfs_item.length===0)throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item empty? branchAddr: ${d} (E: 4823e871cc889a90e86bbf85f5a00826)`);let f=c.rel8ns.b2tfs_item[0];i.push({name:l,isActive:l===a,branchAddr:d,rootItemAddr:f})}return{branches:i}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Sr&&console.log(`${e} complete.`)}}h(qc,"executeVcsBranch_listBranches");async function jc({item:o,space:e,metaspace:t,currentRelPath:r,outMap:n}){let a=`[${jc.name}]`;try{Sr&&console.log(`${a} starting... (I: c82a58edda64ffbb550b93cfdbad6826)`);let{fsType:s}=o.data;if(r&&n.set(r,o),s==="folder")if(o.rel8ns){let i=o.rel8ns?.[be]||[];for(let c of i){let l=await ae({addr:c,space:e,metaspace:t});if(l){let d=r?Ge(r,l.data.name):l.data.name;await jc({item:l,space:e,metaspace:t,currentRelPath:d,outMap:n})}else console.warn(`${a} (UNEXPECTED) childAddr (${c}) not found in space (${e.ib})? Is this an error? What's up here? We need to investigate this. (W: 732698e07198dd17b9927c089c820826)`)}}else console.warn(`${a} (UNEXPECTED) item.rel8ns falsy? item addr (${I({ibGib:o})}). Not sure when this would happen, so investigate this and update this warning if it comes up. (W: 59f9587f0118e0ce371ef1a8dbf7e626)`)}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{Sr&&console.log(`${a} complete.`)}}h(jc,"branchCmd_walkBranchGraphForItems");var xu="[init-cmd]",Xc=!0;async function Cu({metaspace:o,localSpace:e,galaxyName:t="code-1",rootFolderName:r="root",branchName:n=Te}){let a=`${xu}[${Cu.name}]`;try{Xc&&console.log(`${a} starting... (I: 8a9b10c11d12e13f14a15b16c17d18e1)`);let{space:s,spaceId:i,spaceName:c}=await un({metaspace:o,branchName:n,galaxyName:t}),l=await er({fsType:"folder",name:r}),d=l.newIbGib;await V({resTransform:l,space:s}),await o.registerNewIbGib({ibGib:d,space:s});let f=await Xr({branchName:n,rootItem:d,space:s,metaspace:o}),b=I({ibGib:f}),p=ot({spaceId:i,ibGibAddr:b}),u=await cc({galaxyName:t,space:e,metaspace:o,defaultBranch:n,sqBranchAddr:p});return Xc&&console.log(`${a} Successfully initialized repository (spaceId: ${i}, branchName: ${n}) (I: 9a10b11c12d13e14f15a16b17c18d19e)`),{spaceId:i,branchName:n,rootItem:d,branchIbGib:f,branchSpace:s,galaxyIbGib:u}}catch(s){throw console.error(`${a} ${E(s)} (E: 470bd27dfb68abaa38827ca83fa39826)`),s}finally{Xc&&console.log(`${a} complete. (I: ff39f8a7a9e8407087efd1e844e84626)`)}}h(Cu,"executeVcsInit");var s_="Space witness for projecting and observing workspace hierarchies.";var xr="workspace_scan";var Cn=!1,Zr="[status-helper]";async function Hc({item:o,space:e,metaspace:t,currentRelPath:r,outMap:n}){let a=`[${Hc.name}]`;try{if(Cn&&console.log(`${a} starting... (I: 2bcc48c4fdd884784497bee826fbe126)`),!o||!o.data)return;let{fsType:s,fileHash:i}=o.data;if(r&&n.set(r,{relPath:r,fileHash:i,fsType:s}),s==="folder"){if(!o.rel8ns)throw new Error("(UNEXPECTED) item.rel8ns falsy? item.data.fsType === 'folder', so we should at least have rel8ns.tjp (E: a1271821cef893c375f390755fc89626)");let c=o.rel8ns?.[be]||[];for(let l of c){let d=await ae({addr:l,space:e});if(d&&d.data){let f=r?Ge(r,d.data.name):d.data.name;await Hc({item:d,space:e,metaspace:t,currentRelPath:f,outMap:n})}}}}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{Cn&&console.log(`${a} complete.`)}}h(Hc,"walkBranchGraph");async function Vc({galaxyIbGib:o,workspaceSpace:e,localSpace:t,activeBranchSpace:r,metaspace:n,repoRoot:a,targetDir:s,vcsFolderName:i=".vcsgib",filterFilePatterns:c=[]}){let l=`${Zr}[${Vc.name}]`;if(o??=await yn({space:t,metaspace:n}),!o)throw new Error(`galaxyIbGib falsy and couldn't get any index ibgib in the localSpace (${t.ib}) via metaspace (E: 8aaf983c3166024dead6ad7922161426)`);let d=It({targetDir:s??"",repoRoot:a??"",galaxyIbGib:o}),f=d===Te?a||"":a?Ge(a,"b",d):Ge("b",d),b,p=r;try{let S=await Xe({galaxyIbGib:o,branchName:d,metaspace:n});p=p||S.branchSpace,b=S.rootItemIbGib_latest||S.rootItemIbGib}catch(S){Cn&&console.log(`${l} (SUPPRESSED) error: ${E(S)} (E: a88ab80c909d4307d8e68b5241935826)`)}let u=new Map,m=o.data.stagedPaths||{};for(let[S,D]of Object.entries(m))u.set(S,D);let g=new Map;b&&p&&await Hc({item:b,space:p,metaspace:n,currentRelPath:"",outMap:g});let y=new Map,w=[],A=e;if(!A&&n&&(A=(await n.getLocalUserSpaces({lock:!1})||[]).find(D=>D.data?.classname?.includes("WorkspaceProjectionSpace")&&(!f||D.data?.workspaceRoot===f))),A){let D=(await A.witness({data:{cmd:"get",cmdModifiers:[xr]}}))?.data?.scanResult;D?.files&&(y=D.files),D?.pendingComments&&(w=D.pendingComments)}if(Cn){let S=b?I({ibGib:b}):void 0;console.log(`${Zr}[getRepoStatus] branch: ${d}, branchSpace: ${p?.data?.name||p?.ib}, branchAddrs: ${JSON.stringify(o?.data?.["$@branch"])}, rootItemAddr: ${S}`),console.log(`${Zr}[getRepoStatus] branchItemsMap keys: ${JSON.stringify(Array.from(g.keys()))}`);for(let[D,C]of g.entries())console.log(`${Zr}[getRepoStatus] branch item '${D}': fileHash=${C.fileHash}`);console.log(`${Zr}[getRepoStatus] physicalItemsMap keys: ${JSON.stringify(Array.from(y.keys()))}`);for(let[D,C]of y.entries())console.log(`${Zr}[getRepoStatus] physical item '${D}': fileHash=${C.fileHash}`)}let G=[],T=[],$=[],_=[];for(let[S,D]of u.entries()){let C=g.has(S),N=D.isDeleted?"deleted":C?"modified":"new";G.push({path:S,fsType:D.fsType||"file",status:"staged",stagedType:N})}for(let[S,D]of y.entries()){let C=u.get(S);if(C){C.isDeleted&&_.push({path:S,fsType:D.isDirectory?"folder":"file",status:"untracked"});continue}let N=g.get(S);N?!D.isDirectory&&D.fileHash&&N.fileHash&&D.fileHash!==N.fileHash&&(Cn&&console.log(`${Zr}[getRepoStatus] MODIFIED: '${S}' phys=${D.fileHash} vs branch=${N.fileHash}`),T.push({path:S,fsType:"file",status:"modified"})):_.push({path:S,fsType:D.isDirectory?"folder":"file",status:"untracked"})}for(let[S,D]of g.entries())!S||S==="."||S===""||!y.has(S)&&!u.has(S)&&$.push({path:S,fsType:D.fsType,status:"deleted"});return{branchName:d,activeWorktreeDir:f,staged:G,modified:T,deleted:$,untracked:_,pendingComments:w}}h(Vc,"getRepoStatus");async function Lb(o){return await Vc(o)}h(Lb,"executeVcsStatus");var Nu="[glob-helper]",Du=!1,Rb=[".vcsgib","b","ibgib","node_modules",".git"];function Wc(o){let e=o.replace(/\\/g,"/"),t=e.replace(/\./g,"\\.").replace(/\?/g,"[^/]").replace(/\/\*\*\//g,"(?:/|/.+/)").replace(/\/\*\*/g,"(?:/.*)?").replace(/\*\*\//g,"(?:.*/)?").replace(/\*/g,"[^/]*");return e.endsWith("/")||(t+="(?:/.*)?"),new RegExp(`^${t}$`)}h(Wc,"globToRegExp");function T_(o){return o?o.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("#")):[]}h(T_,"parseFilterFileContent");function vu({relativePath:o,isDirectory:e=!1,filterPatterns:t=[]}){let r=`${Nu}[${vu.name}]`;if(!o)return!1;let n=o.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),a=n.split("/")[0]||n;if(Rb.includes(a)||Rb.includes(n))return!0;if(t.length===0)return!1;let s=!1;for(let i of t){if(!i||i.trim()==="")continue;let c=i.trim();if(c.startsWith("regexp js ")){let u=c.substring(10);try{let m=new RegExp(u);(m.test(n)||m.test(a))&&(s=!0)}catch(m){console.error(`${r} Error evaluating regex pattern (${c}):`,m)}continue}let l=!1,d=c;d.startsWith("!")?(l=!0,d=d.substring(1).trim()):d.startsWith("include ")&&(l=!0,d=d.substring(8).trim());let f=d.endsWith("/");if(f&&!e)continue;let b=f?d.slice(0,-1):d,p=!1;if(b===a||n===b)p=!0;else if(b.includes("*")||b.includes("?")){let u=Wc(b);p=u.test(n)||u.test(a)}else p=n.split("/").includes(b)||n.endsWith("/"+b);p&&(s=!l)}return Du&&console.log(`${r} relativePath: ${o}, isIgnored: ${s}`),s}h(vu,"isPathFiltered");var Mb="[add-cmd]",Ub=!1;async function Pu({metaspace:o,localSpace:e,branchName:t,activeBranchSpace:r,branchSpace:n,workspaceSpace:a,galaxyIbGib:s,paths:i=[],all:c=!1,repoRoot:l,targetDir:d=l,vcsFolderName:f=".vcsgib"}){let b=`${Mb}[${Pu.name}]`;try{Ub&&console.log(`${b} starting... (I: d6173882c2b3e92748569c165050a826)`);let p=new Map,m=(await a.witness({data:{cmd:"get",cmdModifiers:[xr]}}))?.data?.scanResult;if(m?.files&&(p=m.files),!l)throw new Error("repoRoot required for executeVcsAdd (E: e934e81561a84f3c9217646a78248826)");let g=t||It({targetDir:d||l,repoRoot:l,galaxyIbGib:s}),{branchSpace:y,rootItemIbGib_latest:w}=await Xe({galaxyIbGib:s,branchName:g,metaspace:o}),A=n||r||y;if(!A)throw new Error(`(UNEXPECTED) branchSpace falsy for branch "${g}" (E: 73a812b3ca794f92)`);let G=new Map;w&&await Yc({item:w,space:A,metaspace:o,currentRelPath:"",outMap:G});let T=[],$=g===Te?l:`${l}/b/${g}`;if(c||i.length===0||i.length===1&&(i[0]==="."||i[0]==="")){for(let[N,x]of p.entries())x.isDirectory||T.push(N);for(let[N,x]of G.entries())x.fsType==="file"&&!p.has(N)&&(T.includes(N)||T.push(N))}else for(let N of i){let x=yo(N,d,$);if(x.includes("*")||x.includes("?")){let L=Wc(x),U=0;for(let[O,M]of p.entries())if(!M.isDirectory){let F=O.split("/").pop()||O;(L.test(O)||L.test(F))&&(T.includes(O)||T.push(O),U++)}for(let[O,M]of G.entries())if(M.fsType==="file"&&!p.has(O)){let F=O.split("/").pop()||O;(L.test(O)||L.test(F))&&(T.includes(O)||T.push(O),U++)}if(U===0)throw new Error(`No files matched glob pattern: ${N} (E: b4f9586075918649820246a804c8be26)`)}else{let L=p.get(x),U=G.get(x);if(L)if(L.isDirectory){for(let[O,M]of p.entries())!M.isDirectory&&(O===x||O.startsWith(x+"/"))&&(T.includes(O)||T.push(O));for(let[O,M]of G.entries())M.fsType==="file"&&!p.has(O)&&(O===x||O.startsWith(x+"/"))&&(T.includes(O)||T.push(O))}else T.includes(x)||T.push(x);else if(U)if(U.fsType==="folder")for(let[O,M]of G.entries())M.fsType==="file"&&!p.has(O)&&(O===x||O.startsWith(x+"/"))&&(T.includes(O)||T.push(O));else T.includes(x)||T.push(x);else{let O=0;for(let[M,F]of p.entries())!F.isDirectory&&M.startsWith(x+"/")&&(T.includes(M)||T.push(M),O++);for(let[M,F]of G.entries())F.fsType==="file"&&!p.has(M)&&M.startsWith(x+"/")&&(T.includes(M)||T.push(M),O++);if(O===0)throw new Error(`Path does not exist: ${N} (E: 10c11d12e13f14a15b16c17d18e19f20)`)}}}let _=[...s.data?.staged_item||[]],S={...s.data?.stagedPaths||{}},D=[];for(let N of T){let x=p.get(N),L=G.get(N);if(!x&&L){let Y=L.item?I({ibGib:L.item}):void 0;S[N]={previousItemAddr:Y,fsType:L.fsType,stagedAt:new Date().toISOString(),isDeleted:!0},D.push(N);continue}let U=x?.fileHash,O,F=(await a.witness({data:{cmd:"get",ibGibAddrs:[N]}}))?.ibGibs?.find(Y=>!!Y);if(!F||!F.data)throw new Error(`Failed to load file data for '${N}' from workspace space (E: 8a67b120f2694b6ca5610ec1f2e34567)`);if(O=F.data instanceof Uint8Array?F.data:new Uint8Array(F.data),!U){let Y=await crypto.subtle.digest("SHA-256",O.buffer);U=Array.from(new Uint8Array(Y)).map(j=>j.toString(16).padStart(2,"0")).join("")}if(L&&L.fileHash&&L.fileHash===U)continue;let k=`bin ${U}`,Ee=await ee({ibGib:{ib:k,data:O}}),pe={ib:k,gib:Ee,data:O},oe=I({ibGib:pe});await ce({ibGib:pe,space:A}),await o.registerNewIbGib({ibGib:pe,space:A});let re=N.split("/").pop()||N,fe=await te({s:re}),W;L&&L.item?W=await Ft({existingItem:L.item,dataToUpdate:{fileHash:U},rel8nsToUpdate:{bin:[oe]}}):W=await er({fsType:"file",name:re,data:{nameHash:fe,fileHash:U,fileEncoding:"utf8"},rel8ns:{bin:[oe]}});let Z=W.newIbGib,se=I({ibGib:Z});await V({resTransform:W,space:A}),await o.registerNewIbGib({ibGib:Z,space:A}),_.includes(se)||_.push(se),S[N]={itemAddr:se,binAddr:oe,fileHash:U,fsType:"file",stagedAt:new Date().toISOString()},D.push(N)}if(!e)throw new Error("localSpace is required to update repository galaxy (E: 99ea3cac6d28432c4fa9dbf84e680826)");let C=await mt({space:e,metaspace:o,galaxyIbGib:s,dataToUpdate:{stagedPaths:S,staged_item:_}});return{stagedPaths:D,stagedCount:D.length,updatedGalaxy:C}}catch(p){throw console.error(`${b} ${E(p)} (E: 82708be03354a87ad499f6536eb55a26)`),p}finally{Ub&&console.log(`${b} complete. (I: f5cfeba2cbe8e5a76e617348895bd326)`)}}h(Pu,"executeVcsAdd");async function Yc({item:o,space:e,metaspace:t,currentRelPath:r,outMap:n}){if(!o||!o.data)return;let{fsType:a,fileHash:s}=o.data;if(r&&n.set(r,{relPath:r,fileHash:s,fsType:a,item:o}),a==="folder"){let i=o.rel8ns?.[be]||[];for(let c of i){let l=await ae({addr:c,space:e,metaspace:t});if(l&&l.data){let d=r?Ge(r,l.data.name):l.data.name;await Yc({item:l,space:e,metaspace:t,currentRelPath:d,outMap:n})}else console.warn(`${Mb}[${Yc.name}] child item '${c}' could not be loaded from space during add branch graph walk (W: 4f7c19a024ef11eebe560242ac120002)`)}}}h(Yc,"addCmd_walkBranchGraph");var Fb="___whitespace___";var xt=!1;function Bb({commentText:o,addlMetadataText:e}){let t=`[${Bb.name}]`;try{if(!o)throw new Error("commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)");let r=bt({text:o,length:20,replaceMap:{"?":"__qm__"}});if(e){e.length>128&&console.warn(`${t} addlMetadataText (${e.length}) is too long. Max length: ${128}`);let n=bt({text:e,length:128});if(!n)throw new Error("(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)");return`comment ${r} ${n}`}else return`comment ${r}`}catch(r){throw console.error(`${t} ${r.message}`),r}}h(Bb,"getCommentIb");function Lu({ib:o}){let e=`${Lu.name}]`;try{if(xt&&console.log(`${e} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`),!o)throw new Error("ib required (E: d89f8c4df46b970585c82bc89c1c6322)");let[t,r,n]=o.split(" ");for(;r.includes("__qm__");)r=r.replace("__qm__","?");return{safeIbCommentText:r,safeIbCommentMetadataText:n}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{xt&&console.log(`${e} complete.`)}}h(Lu,"parseCommentIb");async function Ss({text:o,addlMetadataText:e,saveInSpace:t,space:r,dontTrimText:n}){let a=`[${Ss.name}]`;xt&&console.log(`${a} starting...`);try{if(!o)throw new Error("text required (E: 3e3d0f555e1a83771a6548eb10943522)");if(n||(o=o.trim()),!o)throw new Error("text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)");let s={text:o,textTimestamp:rt()},i={parentIbGib:H.primitive({ib:"comment"}),ib:Bb({commentText:o.trim()||Fb,addlMetadataText:e}),data:s,dna:!0,tjp:{uuid:!0,timestamp:!0},nCounter:!0};xt&&console.log(`${a} opts: ${X(i)}`);let c=await H.firstGen(i);if(t){if(!r)throw new Error("space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)");await V({resTransform:c,space:r})}return c}catch(s){throw console.error(`${a} ${s.message}`),s}}h(Ss,"createCommentIbGib");function Ru({ibGib:o}){let e=`[${Ru.name}]`;try{if(xt&&console.log(`${e} starting...`),!o)throw new Error("ibGib required (E: f204dac30ae548b0a049f1c4d8048502)");let{ib:t,data:r,rel8ns:n}=o;if(!n)return xt&&console.log(`${e} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`),!1;let a=n.ancestor||[];return a&&a.includes("comment^gib")?(xt&&console.log(`${e} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`),!0):r?r.text&&t?.includes("comment")?(xt&&console.log(`${e} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`),!0):(xt&&console.log(`${e} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`),!1):(xt&&console.log(`${e} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`),!1)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{xt&&console.log(`${e} complete.`)}}h(Ru,"isComment");var Uu="[commit-cmd]",Do=!1;async function Mu({metaspace:o,localSpace:e,branchName:t,activeBranchSpace:r,branchSpace:n,workspaceSpace:a,galaxyIbGib:s,message:i,author:c="vcs-user",repoRoot:l="",targetDir:d=l,vcsFolderName:f=".vcsgib",keepEmptyFolders:b=!1}){let p=`${Uu}[${Mu.name}]`;try{if(Do&&console.log(`${p} starting... (I: b8615dc6ad884198a85729aa3900d726)`),!l)throw new Error("repoRoot required for executeVcsCommit (E: f490281b6a184e92a83850cb39480826)");let u=t||It({targetDir:d||l,repoRoot:l,galaxyIbGib:s});if(!u)throw new Error("(UNEXPECTED) activeBranchName falsy? (E: 61e786846d989a15ad6c9b68068c0a26)");let m=s.data.stagedPaths||{};if(Object.keys(m).length===0)throw new Error("Nothing to commit (no staged items found in galaxy) (E: b1b825a7a47f020c6978d64a70f12c26)");let{branchInfo:y,branchIbGib:w,branchSpace:A,rootItemAddr_latest:G,rootItemIbGib_latest:T}=await Xe({galaxyIbGib:s,branchName:u,metaspace:o}),$=n||r||A;if(!$)throw new Error(`(UNEXPECTED) branchSpace falsy for branch "${u}" (E: d288e4092b7c4da9bb42ad910c)`);let _=[];if(a){let j=(await a.witness({data:{cmd:"get",cmdModifiers:[xr]}}))?.data?.scanResult;j?.pendingComments&&(_=j.pendingComments)}let S=new Map,D=[];for(let Y of _){let we=(await Ss({text:Y.content,saveInSpace:!0,space:$})).newIbGib,ke=I({ibGib:we});await o.registerNewIbGib({ibGib:we,space:$});let Ct=S.get(Y.targetRelPath)||[];Ct.push(ke),S.set(Y.targetRelPath,Ct),D.push(Y.commentRelPath)}let C=_.length;if((!i||i.trim().length===0)&&C===0)throw new Error('Commit message is required (-m "message" or companion comment files) (E: fb4714c7171820cdc491ff48aa89a626)');let{newRootItem:N,newRootAddr:x,committedPaths:L,deletedPaths:U}=await kb({existingRootItem:T,stagedPaths:m,itemCommentsMap:S,activeBranchSpace:$,metaspace:o,keepEmptyFolders:b}),O;if(i&&i.trim().length>0){let j=(await Ss({text:i.trim(),saveInSpace:!0,space:$})).newIbGib;O=I({ibGib:j}),await o.registerNewIbGib({ibGib:j,space:$});let we=N.rel8ns?.comment||[],ke=await Ft({existingItem:N,rel8nsToUpdate:{comment:[...we,O]}});await V({resTransform:ke,space:$}),await o.registerNewIbGib({ibGib:ke.newIbGib,space:$}),N=ke.newIbGib,x=I({ibGib:N}),Do&&console.log(`[DIAG-COMMIT] branch: '${u}', message: "${i}", commentAddr: ${O}, rootItem comments: ${JSON.stringify(N.rel8ns?.comment||[])}`)}else Do&&console.log(`${p} no commit msg? do we require a commit msg? (I: 71203833c29513061814948650bd8226)`);let M={committedAt:new Date().toISOString(),committedPaths:L};U&&U.length>0&&(M.deletedPaths=U);let F=await Ae({src:w,dataToAddOrPatch:M,dna:!0,nCounter:!0}),k=F.newIbGib;await V({resTransform:F,space:$});let oe=await ie({src:k,rel8nsToAddByAddr:O?{comment:[O]}:void 0,rel8nsToReplaceByAddr:{b2tfs_item:[{oldAddr:G,newAddr:x}]},dna:!0,nCounter:!0});k=oe.newIbGib;let re=I({ibGib:k});await V({resTransform:oe,space:$}),await J({ibGib:k,space:$}),await o.registerNewIbGib({ibGib:k,space:$});let fe=ot({spaceId:qe($.ib),ibGibAddr:re}),W=u.toLowerCase()===(s.data.policy?.defaultBranch||Te).toLowerCase(),Z={stagedPaths:{},staged_item:[]};W&&(Z.trunkBranchSqAddr=fe,Z["$@branch"]=[fe]);let se=await mt({space:e,metaspace:o,galaxyIbGib:s,dataToUpdate:Z});if(a&&D.length>0)for(let Y of D)try{await a.witness({data:{cmd:"delete",relPath:Y,ibGibAddrs:[Y]}})}catch{}return{branchName:u,commitAddr:re,commentAddr:O,rootItemAddr:x,committedPaths:L,deletedPaths:U,ingestedCommentsCount:C,updatedGalaxy:se,branchIbGib:k}}catch(u){debugger;throw console.error(`${p} ${E(u)} (E: 7afb5867182883e4f8433198d4197f26)`),u}finally{Do&&console.log(`${p} complete. (I: 8d7c6286dec864a1a3b6349880e09626)`)}}h(Mu,"executeVcsCommit");async function kb({existingRootItem:o,stagedPaths:e,itemCommentsMap:t,activeBranchSpace:r,metaspace:n,keepEmptyFolders:a=!1}){let s=`[${kb.name}]`;try{Do&&console.log(`${s} starting... (I: dfcd220de3b81323c8e1bf4ff9615926)`);let i=new Map;if(await qb({item:o,space:r,metaspace:n,currentRelPath:"",outMap:i}),!o.data.name)throw new Error("(UNEXPECTED) existingRootItem.data.name falsy? (E: 8af4e81f199479b12861c861f2482826)");let c={name:o.data.name,fsType:"folder",itemAddr:I({ibGib:o}),children:new Map};for(let[u,m]of i.entries()){let g=u.split("/").filter(Boolean),y=c;for(let w=0;w<g.length;w++){let A=g[w],G=w===g.length-1;y.children.has(A)||y.children.set(A,{name:A,fsType:G?m.fsType:"folder",itemAddr:G?I({ibGib:m.item}):void 0,children:new Map}),y=y.children.get(A)}}let l=[],d=[];for(let[u,m]of Object.entries(e)){l.push(u);let g=u.split("/").filter(Boolean),y=c;if(m.isDeleted){d.push(u);for(let w=0;w<g.length-1;w++){let A=g[w];if(y=y.children.get(A),!y)break}if(y){let w=g[g.length-1];y.children.delete(w)}}else for(let w=0;w<g.length;w++){let A=g[w],G=w===g.length-1;y.children.has(A)||y.children.set(A,{name:A,fsType:G?m.fsType:"folder",itemAddr:G?m.itemAddr:void 0,children:new Map});let T=y.children.get(A);G&&(T.itemAddr=m.itemAddr,T.fsType=m.fsType),y=T}}let f=await jb({node:c,isRoot:!0,itemCommentsMap:t,activeBranchSpace:r,metaspace:n,keepEmptyFolders:a});if(!f)throw new Error("(UNEXPECTED) root Merkle folder returned null (E: e36a5b28d09e4f25b29c9e81f7281026)");let b=f.item,p=I({ibGib:b});return{newRootItem:b,newRootAddr:p,committedPaths:l,deletedPaths:d}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{Do&&console.log(`${s} complete.`)}}h(kb,"commitCmd_buildFolderTree");async function jb({node:o,parentRelPath:e,isRoot:t=!1,itemCommentsMap:r,activeBranchSpace:n,metaspace:a,keepEmptyFolders:s=!1}){let i=t?"":e?Ge(e,o.name):o.name,c=[];for(let[b,p]of o.children.entries())if(p.fsType==="folder"){if(!s&&p.children.size===0)continue;let u=await jb({node:p,parentRelPath:i,isRoot:!1,itemCommentsMap:r,activeBranchSpace:n,metaspace:a,keepEmptyFolders:s});u&&c.push(u.itemAddr)}else{let u=p.itemAddr,m=i?Ge(i,b):b,g=r.get(m)||[];if(g.length>0&&u){let y=await ae({addr:u,space:n,metaspace:a});if(!y)throw new Error(`could not get fileItemAddr (${u}) from activeBranchSpace (${n.ib}) (E: 316865814791f792f7814d04c6af7826)`);let w=await Ft({existingItem:y,rel8nsToUpdate:{comment:[...g]}});await V({resTransform:w,space:n}),await a.registerNewIbGib({ibGib:w.newIbGib,space:n}),u=I({ibGib:w.newIbGib})}u&&c.push(u)}if(!t&&!s&&c.length===0)return null;let l=r.get(i)||[],d;if(o.itemAddr){let b=await ae({addr:o.itemAddr,space:n});if(!b)throw new Error(`could not get node.itemAddr (${o.itemAddr}) from activeBranchSpace (${n.ib}) (E: a1d53d1d920878c718cd4349b204e926)`);let p=b.rel8ns?.[be]||[],u=new Map;for(let T of p){let $=Ne({ibGibAddr:T}).tjpGib||T;u.set($,T)}let m=new Map;for(let T of c){let $=Ne({ibGibAddr:T}).tjpGib||T;m.set($,T)}let g=[],y=[];for(let[T,$]of u.entries()){let _=m.get(T);(!_||_!==$)&&g.push($)}for(let[T,$]of m.entries()){let _=u.get(T);(!_||_!==$)&&y.push($)}let w=b.rel8ns?.comment||[],A=l&&l.length>0;if(g.length===0&&y.length===0&&!A)return{item:b,itemAddr:o.itemAddr};let G=await Ft({existingItem:b,rel8nsToUpdate:{...y.length>0?{[be]:y}:{},...A?{comment:[...w,...l]}:{}},rel8nsToRemove:g.length>0?{[be]:g}:void 0});await V({resTransform:G,space:n}),await a.registerNewIbGib({ibGib:G.newIbGib,space:n}),d=G.newIbGib}else{let b=await te({s:o.name}),p=await er({fsType:"folder",name:o.name,data:{nameHash:b,diffTransactionId:await q()},rel8ns:{[be]:c,...l.length>0?{comment:l}:{}}});await V({resTransform:p,space:n}),await a.registerNewIbGib({ibGib:p.newIbGib,space:n}),d=p.newIbGib}let f=I({ibGib:d});return{item:d,itemAddr:f}}h(jb,"commitCmd_buildMerkleFolder");async function qb({item:o,space:e,metaspace:t,currentRelPath:r,outMap:n}){if(!o||!o.data)return;let{fsType:a}=o.data;if(r&&n.set(r,{relPath:r,fsType:a,item:o}),a==="folder"){let s=o.rel8ns?.[be]||[],i=await st({addrs:s,space:e});for(let c of i){let l=r?Ge(r,c.data.name):c.data.name;await qb({item:c,space:e,metaspace:t,currentRelPath:l,outMap:n})}}}h(qb,"commitCmd_walkBranchGraph");var Fu="[checkout-cmd]",Xb=!1;async function Bu({metaspace:o,localSpace:e,targetBranchSpace:t,workspaceSpace:r,galaxyIbGib:n,branchName:a,force:s=!1,repoRoot:i=""}){let c=`${Fu}[${Bu.name}]`;try{Xb&&console.log(`${c} starting... (I: 28b508922ce8249958263628c96e2726)`);let l=a?.trim();if(!l)throw new Error("Branch name is required for checkout (E: c896086f2d6917f73831f4d8676ff826)");let d=n.data.policy?.defaultBranch||Te,{branchIbGib:f,branchInfo:b,branchSpace:p,rootItemAddr_latest:u,rootItemIbGib_latest:m}=await Xe({galaxyIbGib:n,branchName:l,metaspace:o}),g=t||p;if(!m)throw new Error(`Root item not found for address '${u}' (E: ec0a28ab5a2e13f1889e3f016e64ca26)`);if(r){let A=!0;if(!s)try{let T=(await r.witness({data:{cmd:"get",cmdModifiers:[xr]}}))?.data?.scanResult;(T?.files?T.files instanceof Map?T.files.size:Object.keys(T.files).length:0)>0&&(A=!1)}catch{A=!0}A&&await r.witness({data:{cmd:"put",ibGibAddrs:[u]},ibGibs:[m]})}let y=l===Te?i:i?Ge(i,"b",l):Ge("b",l);return{previousBranch:d,currentBranch:l,worktreePath:y,updatedGalaxy:n}}catch(l){throw console.error(`${c} ${E(l)} (E: bfd24a20afeb3d0ee15bf52f427ba826)`),l}finally{Xb&&console.log(`${c} complete. (I: 0b4068603a0fba6058e8ca7a080df826)`)}}h(Bu,"executeVcsCheckout");var ku="[reset-cmd]",Hb=!1;async function ju({metaspace:o,localSpace:e,activeBranchSpace:t,galaxyIbGib:r,paths:n=[],all:a=!1,targetDir:s="",activeWorktreeDir:i}){let c=`${ku}[${ju.name}]`;try{Hb&&console.log(`${c} starting... (I: 9c70a86e0b28bd8a9862230e17379126)`);let d=await $n({galaxyIbGib:r,paths:n,targetDir:s,activeWorktreeDir:i,space:e||t,metaspace:o,all:a}),f=Object.keys(d.updatedGalaxy.data?.stagedPaths||{}).length;return{unstagedPaths:d.unstagedPaths,stagedCount:f,updatedGalaxy:d.updatedGalaxy}}catch(l){throw console.error(`${c} ${E(l)} (E: aade98ceb7b3677f68ef666822ce7826)`),l}finally{Hb&&console.log(`${c} complete. (I: 8f0b1890b1380b24184544b89a12d126)`)}}h(ju,"executeVcsReset");var qu="[restore-cmd]",Vb=!1;async function Xu({metaspace:o,localSpace:e,workspaceSpace:t,branchName:r,paths:n=[],staged:a=!1,all:s=!1,targetDir:i="",activeWorktreeDir:c=""}){let l=`${qu}[${Xu.name}]`;try{Vb&&console.log(`${l} starting... (I: cee216893bed53ec4459e1eb5dacf326)`);let d=await yn({metaspace:o,space:e});if(!d)throw new Error(`couldn't get galaxyIbGib from space (${e.ib}) via metaspace. (E: b18aa4c434cad43bc828c5641e298d26)`);let f=r||It({targetDir:c||i,repoRoot:i,galaxyIbGib:d});if(a){let b=await $n({galaxyIbGib:d,paths:n,targetDir:i,activeWorktreeDir:c,space:e,metaspace:o,all:s});return{restoredPaths:[],unstagedPaths:b.unstagedPaths,updatedGalaxy:b.updatedGalaxy}}else return{restoredPaths:(await lc({paths:n,targetDir:i,activeWorktreeDir:c,branchName:f,workspaceSpace:t,metaspace:o,galaxyIbGib:d})).restoredPaths,unstagedPaths:[],updatedGalaxy:d}}catch(d){throw console.error(`${l} ${E(d)} (E: e9378836e2e8d5068b0b02c873ae6626)`),d}finally{Vb&&console.log(`${l} complete. (I: 6e00780e0d9a8c91280df4051e660826)`)}}h(Xu,"executeVcsRestore");function xs(o){let e=Math.min(o.length,1024);for(let t=0;t<e;t++)if(o[t]===0)return!0;return!1}h(xs,"isBinaryBuffer");function Cs(o,e="utf8"){if(!o||o.length===0)return[];try{return new TextDecoder(e||"utf8",{fatal:!1}).decode(o).split(/\r?\n/)}catch{return[]}}h(Cs,"decodeToLines");function zc(o,e){let t=o.length,r=e.length;if(t===r&&o.every((f,b)=>f===e[b]))return[];let n=Array.from({length:t+1},()=>new Array(r+1).fill(0));for(let f=1;f<=t;f++)for(let b=1;b<=r;b++)o[f-1]===e[b-1]?n[f][b]=n[f-1][b-1]+1:n[f][b]=Math.max(n[f-1][b],n[f][b-1]);let a=t,s=r,i=[];for(;a>0||s>0;)a>0&&s>0&&o[a-1]===e[s-1]?(i.push({type:"equal",oldIdx:a-1,line:o[a-1]}),a--,s--):s>0&&(a===0||n[a][s-1]>=n[a-1][s])?(i.push({type:"insert",line:e[s-1]}),s--):a>0&&(s===0||n[a][s-1]<n[a-1][s])&&(i.push({type:"delete",oldIdx:a-1,line:o[a-1]}),a--);i.reverse();let c=[],l=null,d=0;for(let f of i)f.type==="equal"?(l&&(c.push(l),l=null),d++):(l||(l={old_i:d,oldLines:[],newLines:[]}),f.type==="delete"?(l.oldLines.push(f.line),d++):f.type==="insert"&&l.newLines.push(f.line));return l&&c.push(l),c}h(zc,"computeLineLcsDiff");var Hu="[b2tfs-3way-graft-strategy]",rr=!1,vo="[MERGE DIAGNOSTIC]";function Vu({textLCA:o,textBase:e,textOrphan:t}){if(e===t)return{mergedText:e,hasConflict:!1};if(e===o)return{mergedText:t,hasConflict:!1};if(t===o)return{mergedText:e,hasConflict:!1};let r=o.split(/\r?\n/),n=e.split(/\r?\n/),a=t.split(/\r?\n/),s=zc(r,n),i=zc(r,a);if(s.length===0)return{mergedText:t,hasConflict:!1};if(i.length===0)return{mergedText:e,hasConflict:!1};let c=!1,l=[],d=0,f=0,b=0;for(;d<r.length||f<s.length||b<i.length;){let p=s[f],u=i[b],m=p&&p.old_i===d,g=u&&u.old_i===d;if(m&&g){let y=p.newLines,w=u.newLines,A=p.oldLines.length,G=u.oldLines.length;y.join(`
|
|
37
|
+
`)===w.join(`
|
|
38
|
+
`)&&A===G?l.push(...y):(c=!0,l.push("<<<<<<< HEAD"),l.push(...y),l.push("======="),l.push(...w),l.push(">>>>>>>"));let T=Math.max(A,G,1);d+=T,f++,b++}else if(m){l.push(...p.newLines);let y=Math.max(p.oldLines.length,1);d+=y,f++}else if(g){l.push(...u.newLines);let y=Math.max(u.oldLines.length,1);d+=y,b++}else d<r.length?(l.push(r[d]),d++):(p&&f<s.length&&(l.push(...p.newLines),f++),u&&b<i.length&&(l.push(...u.newLines),b++))}return{mergedText:l.join(`
|
|
39
|
+
`),hasConflict:c}}h(Vu,"perform3WayTextLineMerge");var Ns=class extends xo{static{h(this,"B2tFS3WayGraftStrategy")}strategyId="B2tFS3WayGraftStrategy";lc="[B2tFS3WayGraftStrategy]";async canGraft(e){let t=`${this.lc}[${this.canGraft.name}]`;try{let{conflictStrategy:r,timelineAddrsA:n,timelineAddrsB:a,ibGibReadCache:s,space:i}=e;if(!(r===gt.optimisticWithLCS||r==="b2tfs3WayMerge"))return!1;let l=n.at(-1),d=a.at(-1);if(!l||!d)return rr&&console.log(`${t} we don't have two tip addrs? (I: b20b6de462c35e0e74360cc8d317f126)`),!1;let[f,b]=await Ve({addrs:[l,d],readCache_graph:s,space:i});if(!f)throw new Error("(UNEXPECTED) tipA falsy? (E: 752101026888140f074614e893531826)");if(!b)throw new Error("(UNEXPECTED) tipB falsy? (E: d4d4a876cad8c7869830d33832bfde26)");if(!($o(f)&&$o(b)))return($o(f)||$o(b))&&console.error(`${t}${vo} (UNEXPECTED)(NOT THROWN) only tipA or tipB but not both are b2tfs items? (E: cacb38796da881268898e9d1af245826)`),!1;if(f.data.fsType!==b.data.fsType)throw new Error(`(UNEXPECTED) tipA.data.fsType (${f.data.fsType}) !== tipB.data.fsType (${b.data.fsType})? (E: c01c1885ac738f679813117852c48426)`);return f.data.fsType===mn.file}catch(r){return console.error(`${t} ${E(r)} (E: 463df8afd9a8c42008856f3737b71826)`),!1}}async graft(e){let t=`${Hu}[${this.strategyId}][${this.graft.name}]`;try{rr&&console.log(`${t} starting 3-way B2tFS snapshot graft... (I: 88cf3a0e67b3da14bfea241159296e26)`);let{conflictStrategy:r,timelineAddrsA:n,timelineAddrsB:a,latestCommonFrameAddr:s,ibGibReadCache:i,space:c,graftPreference:l}=e,d=n.lastIndexOf(s),f=n.slice(d+1),b=await Ve({readCache_graph:i,addrs:f,space:c}),p=b.at(-1),u=a.lastIndexOf(s),m=a.slice(u+1),g=await Ve({readCache_graph:i,addrs:m,space:c}),y=g.at(-1),{baseTip:w,baseBranch:A,orphanTip:G,orphanBranch:T}=this.resolveBaseAndOrphan({graftPreference:l,tipA_sender:p,branchA_sender_sinceLCA:b,tipB_receiver:y,branchB_receiver_sinceLCA:g}),$=I({ibGib:w}),_=A.map(He=>I({ibGib:He})),S=I({ibGib:G}),D=T.map(He=>I({ibGib:He}));rr&&(console.log(`${t} baseBranchAddrs:
|
|
40
|
+
${_.join(`
|
|
41
|
+
`)} (I: 2cad420d7bc822f798b8a8785f1f8c26)`),console.log(`${t} orphanBranchAddrs:
|
|
42
|
+
${D.join(`
|
|
43
|
+
`)} (I: cc86489d6737e2aced42b585cba13526)`));let C=await this.fetchIbGib({addr:s,space:c,readCache_graph:i});if(!C)throw new Error("(UNEXPECTED) lcaNode falsy? (E: a8b2d80dc4f8ba1448fa280d89dfb626)");let N=await this.resolveRootItemNode({nodeOrAddr:C,space:c,readCache_graph:i});if(!N)throw new Error("(UNEXPECTED) lcaItem falsy? (E: 0944f88dde58cbabf82342b814955826)");let x=await this.resolveRootItemNode({nodeOrAddr:w,space:c,readCache_graph:i});if(!x)throw new Error("(UNEXPECTED) baseItem falsy? (E: fac3087884cbebc7083e580514002826)");let L=await this.resolveRootItemNode({nodeOrAddr:G,space:c,readCache_graph:i});if(!L)throw new Error("(UNEXPECTED) orphanItem falsy? (E: 8e7e383753a8814f283280ee82156826)");if(N.data.fsType!==x.data.fsType)throw new Error("(UNEXPECTED) lcaItem.data.fsType !== baseItem.data.fsType? (E: 794608f3e678a399ed670388629a6826)");if(N.data.fsType!==L.data.fsType)throw new Error("(UNEXPECTED) lcaItem.data.fsType !== orphanItem.data.fsType? (E: 2813981c8c422b41f85a02fd8aa88226)");let U=N.data.fsType;if(U===mn.folder)throw new Error("(UNEXPECTED) fsType === B2tFSType.folder? Folders fall back to DefaultDnaReplayGraftStrategy and reification. (E: b282b8f77b18575378edb902bd80a826)");if(U!==mn.file)throw new Error(`(UNEXPECTED) fsType (${U}) is not a file? (E: 272418fe2067ea3e16dac028e86d1a26)`);let O=await this.getFilePayloadBuffer({fileItem:N,space:c,readCache_graph:i}),M=await this.getFilePayloadBuffer({fileItem:x,space:c,readCache_graph:i}),F=await this.getFilePayloadBuffer({fileItem:L,space:c,readCache_graph:i}),k=M?xs(M.buffer):!1,Ee=F?xs(F.buffer):!1,pe=O?xs(O.buffer):!1;if(k||Ee||pe){rr&&console.log(`${t} Non-text binary file detected (${x.data?.name}). Skipping 3-way line diff and falling through. (I: 8ff3a887d3ea1f162317b77feb7ec326)`);return}if(!O)throw new Error("(UNEXPECTED) lcaPayload falsy? (E: 0b82892204482f5538a430b8915b7826)");if(!M)throw new Error("(UNEXPECTED) basePayload falsy? (E: af1f68a020280b3a5d6ed4a812acd426)");if(!F)throw new Error("(UNEXPECTED) orphanPayload falsy? (E: 6a521b684763862c3a2e0ca315d62826)");let oe=Cs(O.buffer).join(`
|
|
44
|
+
`),re=Cs(M.buffer).join(`
|
|
45
|
+
`),fe=Cs(F.buffer).join(`
|
|
46
|
+
`);rr&&(console.log(`${t}${vo} file: ${x.data.name}`),console.log(`${t}${vo} textLCA:
|
|
47
|
+
${oe}`),console.log(`${t}${vo} textBase:
|
|
48
|
+
${re}`),console.log(`${t}${vo} textOrphan:
|
|
49
|
+
${fe}`));let{mergedText:W}=Vu({textLCA:oe,textBase:re,textOrphan:fe});rr&&console.log(`${t}${vo} mergedText:
|
|
50
|
+
${W}`);let Z=Buffer.from(W,"utf8"),se=await te({s:W});x.data.fileExt!==L.data.fileExt&&console.warn(`${t} baseItem.data.fileExt (${x.data.fileExt}) !== orphanItem.data.fileExt (${L.data.fileExt})? Using baseItem.data.fileExt for merged fileExt (W: a999b54235bb231fa49224842e212326)`);let Y=x.data.fileExt,we={ib:pa({binHash:se,binExt:Y,binEncoding:"utf8"}),data:Z};we.gib=await ee({ibGib:we,hasTjp:!1});let ke=I({ibGib:we});await ce({ibGib:we,space:c}),await J({ibGib:we,space:c});let Ct=h(He=>{if(He.data.n||He.data.n===0)return He.data.n;throw new Error("(UNEXPECTED) item.data.n not a number? (E: 896ceae089c83ca67817fff826be5826)")},"fnGetN"),$e=Ct(x),tt=Ct(L),Nt=Math.max($e,tt),eo=N.rel8ns?.comment||[],vs=new Set(eo),Oo=(x.rel8ns?.comment||[]).filter(He=>!vs.has(He)),Ps=(L.rel8ns?.comment||[]).filter(He=>!vs.has(He)),kt=Array.from(new Set([...Oo,...Ps])),Qc=Array.from(new Set([...eo,...kt])),Lo=[];if(kt.length>0){for(let Nr of kt){let Ro=await this.fetchIbGib({addr:Nr,space:c,readCache_graph:i});if(!Ro)throw new Error(`(UNEXPECTED) Comment ibgib for address '${Nr}' not found in cache or space (E: eb6798734f68e8f578fe1da3a2698826)`);Lo.push(Ro);let Pn=await it({ibGib:Ro,space:c,ibGibs:i?Object.values(i):void 0});for(let tl of Object.values(Pn)){let eh=I({ibGib:tl});Lo.some(th=>I({ibGib:th})===eh)||Lo.push(tl)}}let{mapWithTjp_YesDna:He,mapWithoutTjps:Qb}=nt({ibGibs:Lo});for(let Nr of Object.values(Qb))c&&await ce({ibGib:Nr,space:c,isDna:ko({ibGib:Nr})});let el=at({ibGibs:Object.values(He)});for(let Nr of Object.keys(el)){let Ro=el[Nr];for(let Pn of Ro)c&&(await ce({ibGib:Pn,space:c}),await J({ibGib:Pn,space:c}))}}let nr=await Ft({existingItem:x,dataToUpdate:{fileHash:se,n:Nt+1},rel8nsToUpdate:{[Hr]:[ke],...Qc.length>0?{comment:Qc}:{}}});if(!nr.dnas)throw new Error("(UNEXPECTED) evolveRes.dnas falsy? (E: e640e892cc76c77f98f3881301035826)");if(!nr.newIbGib)throw new Error("(UNEXPECTED) evolveRes.newIbGib falsy? (E: 9e488d07772827b66a2aff4801905426)");let Os=nr.newIbGib,Kb=I({ibGib:Os});rr&&console.log(`${t} newItemAddr: ${Kb} (I: d23eef651b88be1248ee29ca179eff26)`);let Ls=[],Rs=[];Ls.push(...nr.dnas),nr.intermediateIbGibs&&nr.intermediateIbGibs.forEach(He=>Rs.push(He)),await V({resTransform:nr,space:c}),await J({ibGib:nr.newIbGib,space:c});let zb={baseTextB2tFSItemAddr:$,baseTextBinAddr:M.binIbGib?I({ibGib:M.binIbGib}):void 0,orphanTextB2tFSItemAddr:S,orphanTextBinAddr:F.binIbGib?I({ibGib:F.binIbGib}):void 0},Dn=await An({conflictStrategy:r,details:"Merged orphan tip text with the baseTip as a starting point.",addlGraftDetails:[zb],latestCommonFrameAddr:s,baseAddrsSinceLCA:_,orphanAddrsSinceLCA:D,dnaAddrsApplied:[]});await ce({ibGib:Dn,space:c}),await J({ibGib:Dn,space:c});let Jb=I({ibGib:Dn}),vn=await ie({src:Os,rel8nsToAddByAddr:{[Yr]:[Jb]},dna:!0,nCounter:!0});if(!vn.dnas)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas falsy? (E: f3f4a83d3a08bd8de84250c389aed826)");let Us=vn.newIbGib,Zb=I({ibGib:Us});rr&&console.log(`${t} finalGraftTipAddr: ${Zb} (I: 583ac81fb0a84827b85c3076ffeeaf26)`),Rs.push(Os);for(let He of vn.dnas)Ls.push(He);return await V({resTransform:vn,space:c}),await J({ibGib:Us,space:c}),{dnasReplayed:[],dnasCreatedInGraft:Ls,intermediateIbGibsCreatedInGraft:Rs,ancillaryIbGibsCreated:[we,...Lo],newGraftTip:Us,graftInfoCreated:Dn}}catch(r){throw console.error(`${t} ${E(r)} (E: 8acdfd6742487fe88836989dbef30826)`),r}finally{rr&&console.log(`${t} complete. (I: daceba1747880a2d1837eec8129d7726)`)}}async fetchIbGib({addr:e,space:t,readCache_graph:r}){if(e){if(r){if(r[e])return r[e];let n=e.includes("^")?e.substring(e.lastIndexOf("^")+1):e,a=Object.keys(r).find(s=>s===e||n&&s.endsWith("^"+n));if(a)return r[a]}try{let n=await z({space:t,addrs:[e]});if(n){let a=n.ibGibs?.find(s=>!!s)||n.rawResultIbGib?.ibGibs?.find(s=>!!s);if(a)return a}}catch{}}}async resolveRootItemNode({nodeOrAddr:e,space:t,readCache_graph:r}){if(!e)throw new Error("(UNEXPECTED) nodeOrAddr falsy? (E: 524108327b9caa00586207ea399f7226)");let n;if(typeof e=="string"?n=await this.fetchIbGib({addr:e,space:t,readCache_graph:r}):n=e,!n)throw new Error("(UNEXPECTED) node falsy? couldn't get node? (E: bd7d1c3b4a3881ff882746281869d826)");if($o(n))return n;throw new Error("(UNEXPECTED) node is not a B2tFSItemIbGib_V1? (E: ddabb281ccb2fb1a181109a82046b826)")}async getFilePayloadBuffer({fileItem:e,space:t,readCache_graph:r}){if(!e||!e.rel8ns)return;let a=(e.rel8ns[Hr]||[]).at(-1);if(!a)return;let s=await this.fetchIbGib({addr:a,space:t,readCache_graph:r});if(!s)throw new Error(`(UNEXPECTED) couldn't fetch binIbGib? latestBinAddr: ${a}. space.ib: ${t.ib} (E: 3d1238b3a348924038a79f88264d8226)`);if(s.data===void 0)return;let i,c=s.data;if(c&&typeof c=="object"&&c._dataType==="Uint8Array_Base64"&&typeof c.value=="string")i=Buffer.from(c.value,"base64");else if(typeof c=="string")i=Buffer.from(c,"utf8");else if(c instanceof Uint8Array||Buffer.isBuffer(c))i=c;else if(typeof c=="object"&&c!==null)if(typeof c.text=="string")i=Buffer.from(c.text,"utf8");else if(typeof c.data=="string")i=Buffer.from(c.data,"utf8");else{let l=Object.values(c);i=new Uint8Array(l)}else i=new Uint8Array(0);return{buffer:i,binIbGib:s}}};var Po="[TRACE_VCS]";function or(o){if(!o)return"(none)";let e=o.lastIndexOf("^");if(e===-1)return o.slice(0,40);let t=o.slice(0,e),r=o.slice(e+1),n=r.indexOf("."),a=n===-1?r.slice(0,8):`${r.slice(0,8)}.${r.slice(n+1,n+9)}`;return`${t}^${a}`}h(or,"shortAddr");async function Nn({label:o,rootItemAddr:e,space:t,metaspace:r}){let n=`${Po}[logTree][${o}]`,a=t?.data?.name||t?.data?.spaceSubPath||t?.ib||"unknown";if(console.log(`${n} === Hierarchy for root: ${or(e)} in space: ${a} ===`),!e){console.log(`${n} rootItemAddr is falsy`);return}async function s(i,c,l){let d=" ".repeat(c),f=await ae({addr:i,space:t,metaspace:r});if(!f){console.log(`${n}${d} ? MISSING item at ${or(i)} (path: ${l})`);return}let b=f.data?.name||"(root)",p=f.data?.fsType||"unknown",u=f.rel8ns?.comment||[],m=f.rel8ns?.[be]||[];console.log(`${n}${d} ?? ${b} (${p}) addr: ${or(i)} comments: ${u.length} children: ${m.length}`);for(let g of u){let y=await ae({addr:g,space:t,metaspace:r});console.log(`${n}${d} ?? comment: "${y?.data?.text?.slice(0,50)}"`)}for(let g of m)await s(g,c+1,l?Ge(l,b):b)}h(s,"walk"),await s(e,1,"")}h(Nn,"logTreeHierarchyDiagnostic");var Wu="[merge-cmd]",Qr=!1;async function Yu({metaspace:o,localSpace:e,baseBranchSpace:t,incomingBranchSpace:r,workspaceSpace:n,galaxyIbGib:a,baseBranchName:s,incomingBranchName:i,message:c,targetDir:l="",repoRoot:d=""}){let f=`${Wu}[${Yu.name}]`;try{Qr&&console.log(`${f} starting... (I: 798888825c2c7ec3c8b0e0b815a6e826)`);let b=i?.trim();if(!b)throw new Error("Branch name is required for merge (E: 4ac298f0b33f3d5a38131778bf302c26)");let p=s?.trim()||It({targetDir:l||d,repoRoot:d,galaxyIbGib:a});if(!p)throw new Error("(UNEXPECTED) baseBranchName falsy? (E: e120d81b52d2210265d89c5cae5d8826)");if(p===b)throw new Error(`Cannot merge branch '${b}' into itself (E: b849951c15e8768a9150a91b8f314926)`);let{branchIbGib:u,branchSpace:m,rootItemAddr_latest:g}=await Xe({galaxyIbGib:a,branchName:p,metaspace:o}),y=t||m,{branchIbGib:w,branchSpace:A,rootItemAddr_latest:G,rootItemIbGib_latest:T}=await Xe({galaxyIbGib:a,branchName:b,metaspace:o}),$=r||A;No.instance.registerStrategy(new Ns);let _=new Gr(B(Ts));await _.initialized,await _.initializeOpts({localMetaspace:o,localSpace:$,receiverSpace:y,receiverCoordinator:new Tr,receiverMetaspace:o}),await(await new Tr().sync({peer:_,localSpace:$,metaspace:o,domainIbGibs:[T],conflictStrategy:gt.optimisticWithLCS,graftPreference:Bt.receiver})).done,Qr&&(console.log(`[DIAG-MERGE] syncSaga complete. baseBranch: '${p}', incomingBranch: '${b}'`),console.log(`[DIAG-MERGE] incomingRootItem (${G}) comments: ${JSON.stringify(T.rel8ns?.comment||[])}`),console.log(`[DIAG-MERGE] currentBaseRootItem (${u.rel8ns?.b2tfs_item?.at(-1)}) comments: ${JSON.stringify(u.rel8ns?.comment||[])}`)),Qr&&await Nn({label:`executeVcsMerge: BEFORE reify (baseBranch: ${p})`,rootItemAddr:g,space:y,metaspace:o});let C=await dc({rootItemAddr:g,space:y,metaspace:o}),N=C.reifiedRootItem,x=I({ibGib:N});Qr&&(console.log(`[DIAG-MERGE] reifiedRootItem (${x}) comments: ${JSON.stringify(N.rel8ns?.comment||[])}`),Qr&&console.log(`${Po}[merge-cmd] reifyRes hasChanges: ${C.hasChanges}, currentBaseRoot: ${or(g)} -> reifiedRoot: ${or(x)}`),await Nn({label:`executeVcsMerge: AFTER reify (baseBranch: ${p})`,rootItemAddr:x,space:y,metaspace:o}));let L=I({ibGib:u});if(C.hasChanges&&x!==g){let k=await ie({src:u,rel8nsToReplaceByAddr:{b2tfs_item:[{oldAddr:g,newAddr:x}]},dna:!0,nCounter:!0}),Ee=k.newIbGib;await V({resTransform:k,space:y}),await J({ibGib:Ee,space:y}),L=I({ibGib:Ee})}Qr&&console.log(`${Po}[merge-cmd] mergedBranchAddr: ${or(L)}`);let U=qe(y.ib),O=ot({spaceId:U,ibGibAddr:L}),M=a,F=(a.data.policy?.defaultBranch||Te).toLowerCase();if(p.toLowerCase()===F&&C.hasChanges&&x!==g){if(!e)throw new Error("localSpace is required to update repository galaxy (E: 9514b8da1f483877a8f665eac3e4d826)");M=await mt({space:e,metaspace:o,galaxyIbGib:a,dataToUpdate:{trunkBranchSqAddr:O,"$@branch":[O]}})}return n&&N&&await n.witness({data:{cmd:"put",ibGibAddrs:[x]},ibGibs:[N]}),{baseBranch:p,incomingBranch:b,mergeCommitAddr:L,mergeRootAddr:x,stats:{totalFiles:0,identical:0,cleanResolved:0,conflicted:0},updatedGalaxy:M}}catch(b){throw console.error(`${f} ${E(b)} (E: 02f9688abff8e143d8fb8f78843d5326)`),b}finally{Qr&&console.log(`${f} complete. (I: 5a00080e92e65c11283ced174ab25826)`)}}h(Yu,"executeVcsMerge");var Ku="[log-cmd]",Jc=!1;async function zu({metaspace:o,galaxyIbGib:e,filePath:t,branchName:r,allComments:n=!1,repoRoot:a="",targetDir:s=a}){let i=`${Ku}[${zu.name}]`;try{Jc&&console.log(`${i} starting... (I: 4f79a8c2c76b572e081d6e58a0338826)`);let c=r||It({targetDir:s||a,repoRoot:a,galaxyIbGib:e});if(!c)throw new Error("(UNEXPECTED) branchName falsy? (E: 3f236889705ddb4de8f88d080e6cc826)");let{branchIbGib:l,branchSpace:d,rootItemAddr:f,rootItemAddr_latest:b,rootItemIbGib:p,rootItemIbGib_latest:u}=await Xe({galaxyIbGib:e,branchName:c,metaspace:o});if(!l)throw new Error(`(UNEXPECTED) branchIbGib falsy for branch ${c}? (E: 4a2f8b9195ce40bb8e9c1db166a01826)`);if(!d)throw new Error(`(UNEXPECTED) branchSpace falsy for branch ${c}? (E: 9c28e9f50db84e6db582a87d0c3d9a26)`);return t?await Ju({filePath:t,targetDir:s,repoRoot:a,branchName:c,branchSpace:d,rootItemIbGib:p,rootItemAddr:f,metaspace:o}):await Zu({branchIbGib:l,branchSpace:d,branchName:c,allComments:n,metaspace:o})}catch(c){throw console.error(`${i} ${E(c)} (E: 70db81a942bc4e5781a74d49cf308b26)`),c}finally{Jc&&console.log(`${i} complete. (I: e5cf48c58e1c3018949e0d38e47ebc26)`)}}h(zu,"executeVcsLog");async function Ju({filePath:o,targetDir:e,repoRoot:t,branchName:r,branchSpace:n,rootItemIbGib:a,rootItemAddr:s,metaspace:i}){let c=yo(o,e,t);if(!a&&s&&(a=await ae({addr:s,space:n,metaspace:i})),!a)throw new Error(`No root item found on branch ${r} (E: 8a1b6e4d9c7f4e28b8a531d04cb54a26)`);Jc&&(console.log(`${Po}[executeVcsLog] branchName: '${r}', rootItemAddr: ${or(s)}, space: ${n?.data?.name||n?.ib}`),await Nn({label:`executeVcsLog for '${c}' on branch '${r}'`,rootItemAddr:s||I({ibGib:a}),space:n,metaspace:i}));let l=await Qu({rootItem:a,targetRelPath:c,space:n,metaspace:i});if(!l)throw new Error(`Path '${c}' not found in active branch snapshot (E: 67b84a9e2d1f463c9b7e51c88d32a026)`);let d=I({ibGib:l}),b=[...l.rel8ns?.past||[],d].reverse(),p=await st({addrs:b,space:n}),u=jt(p.flatMap(y=>y.rel8ns?.comment||[])),m=new Map;if(u.length>0){let y=await st({addrs:u,space:n}),w=await ma({ibGibs:y,space:n});for(let A=0;A<y.length;A++){let G=y[A],T=I({ibGib:G}),$=w[A]||G,_=I({ibGib:$});m.set(T,{tip:$,tipAddr:_})}}let g=[];for(let y of p){let w=I({ibGib:y}),A=y.rel8ns?.comment||[];for(let G of A){let T=m.get(G);if(T){let{tip:$,tipAddr:_}=T;g.push({commitAddr:w,commentAddr:_,message:$.data?.text||"",timestamp:$.data?.textTimestamp||$.data?.timestamp||"",author:"vcs-user"})}}}return{branchName:r,targetPath:c,commits:g}}h(Ju,"executeVcsLogFile");async function Zu({branchIbGib:o,branchSpace:e,branchName:t,allComments:r,metaspace:n}){let a=I({ibGib:o}),i=[...o.rel8ns?.past||[],a].reverse(),c=await st({addrs:i,space:e}),l=jt(c.map(g=>g.rel8ns?.b2tfs_item?.at(-1)||g.rel8ns?.b2tFS_item?.at(-1)).filter(Boolean)),d=l.length>0?await st({addrs:l,space:e}):[],f=new Map;for(let g of d)f.set(I({ibGib:g}),g);let b=jt(c.flatMap(g=>{let y=g.rel8ns?.b2tfs_item?.at(-1)||g.rel8ns?.b2tFS_item?.at(-1),w=y?f.get(y):void 0;return[...g.rel8ns?.comment||[],...w?.rel8ns?.comment||[]]}).filter(Boolean)),p=new Map;if(b.length>0){let g=await st({addrs:b,space:e}),y=await ma({ibGibs:g,space:e});for(let w=0;w<g.length;w++){let A=g[w],G=I({ibGib:A}),T=y[w]||A,$=I({ibGib:T});p.set(G,{tip:T,tipAddr:$})}}let u=[],m=new Set;for(let g of c){let y=I({ibGib:g}),w=g.rel8ns?.b2tfs_item?.at(-1)||g.rel8ns?.b2tFS_item?.at(-1),A=w?f.get(w):void 0,G=[...g.rel8ns?.comment||[],...A?.rel8ns?.comment||[]].reverse();for(let T of G){let $=p.get(T);if(!$)continue;let{tip:_,tipAddr:S}=$;if(m.has(S))continue;m.add(S);let D=_.data?.text||"(no commit message)",C=_.data?.textTimestamp||_.data?.timestamp||g.data?.committedAt||"",N=g.data?.committedPaths||[],x=[];r&&A&&await Wb({item:A,space:e,metaspace:n,currentRelPath:"",outComments:x}),u.push({branchAddr:y,commitAddr:y,commentAddr:S,message:D,timestamp:C,author:"vcs-user",rootItemAddr:w,committedPaths:N,itemComments:x.length>0?x:void 0})}}return{branchName:t,commits:u}}h(Zu,"executeVcsLogBranch");async function Qu({rootItem:o,targetRelPath:e,space:t,metaspace:r}){if(!o)return;if(!e||e==="."||e==="")return o;let n=e.split("/").filter(Boolean),a=o;for(let s of n){if(a.data?.fsType!=="folder")return;let i=a.rel8ns?.[be]||[];if(i.length===0)return;let l=(await st({addrs:i,space:t})).find(d=>d?.data?.name===s);if(!l)return;a=l}return a}h(Qu,"logCmd_findItemByPath");async function Wb({item:o,space:e,metaspace:t,currentRelPath:r,outComments:n}){if(!o||!o.data)return;let a=o.rel8ns?.comment||[];for(let s of a){let i=await ae({addr:s,space:e,metaspace:t});i&&i.data?.text&&n.push({path:r||"(root)",name:i.data?.name,message:i.data.text})}if(o.data.fsType==="folder"){let s=o.rel8ns?.[be]||[];if(s.length>0){let i=await st({addrs:s,space:e});for(let c of i){let l=r?Ge(r,c.data.name):c.data.name;await Wb({item:c,space:e,metaspace:t,currentRelPath:l,outComments:n})}}}}h(Wb,"logCmd_collectAllItemComments");var em="[generate-comment-cmd]",Yb=!1;async function tm({metaspace:o,localSpace:e,workspaceSpace:t,activeBranchSpace:r,galaxyIbGib:n,paths:a=[],folderTopic:s="notes",repoRoot:i,targetDir:c,vcsFolderName:l}){let d=`${em}[${tm.name}]`;try{if(Yb&&console.log(`${d} starting... (I: 2e8b09f7a6344adca26e846174d81226)`),!t)throw new Error("workspaceSpace is required to generate companion comments (E: e3f0980a31244e439bb4c1a851d7c326)");let f=[];if(a.length>0)for(let u of a){if(!u||typeof u!="string"||!u.trim())continue;let m=/[/\\]+$/.test(u),g=qa(u).replace(/^\.?\//,"").replace(/\/+$/,"");if(!g){f.push({relPath:"",fsType:"folder"});continue}let y;m&&(y="folder"),f.some(w=>w.relPath===g)||f.push({relPath:g,fsType:y})}else{let u=await Lb({metaspace:o,localSpace:e,activeBranchSpace:r,workspaceSpace:t,galaxyIbGib:n,repoRoot:i,targetDir:c,vcsFolderName:l}),m=h(g=>{let y=qa(g.path).replace(/^\.?\//,"").replace(/\/+$/,"");f.some(w=>w.relPath===y)||f.push({relPath:y,fsType:g.fsType})},"addStatusItem");for(let g of u.staged)m(g);for(let g of u.modified)m(g);for(let g of u.untracked)m(g)}let b=[],p=[];for(let u of f){let m=u.relPath,g;if(u.fsType==="folder")g=!0;else if(u.fsType==="file")g=!1;else{let $=await t.witness({data:{cmd:"get",relPath:m}});$?.ibGibs&&$.ibGibs.length>0?g=!1:g=!Qf(m)}let y,w;g?(w=m,y=`.ib.${s}.md`):(w=Jf(m),y=`.ib.${Zf(m)}.md`);let A=w&&w!=="."?qa(Ge(w,y)):y,G=await t.witness({data:{cmd:"get",relPath:A}});if(G?.ibGibs&&G.ibGibs.length>0)p.push(A);else{let _=`# ${m?`\`${m}\``:"root"}
|
|
51
|
+
|
|
52
|
+
(Enter contemporaneous notes/comments here)
|
|
53
|
+
`,S=await sb({name:A,content:_});await t.witness({data:{cmd:"put"},ibGibs:[S]}),b.push(A)}}return{createdFiles:b,skippedFiles:p}}catch(f){throw console.error(`${d} ${E(f)} (E: d23e082728cb489e830e9d6d5a1b3c4f)`),f}finally{Yb&&console.log(`${d} complete. (I: a3b71946358e469d80fc4ef2b281c726)`)}}h(tm,"executeVcsGenerateComment");var Cr=!1,Zc=class o{static{h(this,"IbGibApiBridge")}lc=`[${o.name}]`;async parseResponseJson(e,t){let r=e.headers.get("content-type")||"";if(!r.includes("application/json")){let n=await e.text();if(n.trim().toLowerCase().startsWith("<!doctype html")||n.includes("<html"))throw new Error(`API request to '${t}' failed (${e.status} ${e.statusText}): Received HTML fallback instead of JSON. Check API route matching and parameters.`);if(!e.ok)return{message:n.trim()||`API request failed with status ${e.status} (${e.statusText})`};throw new Error(`API request to '${t}' failed (${e.status} ${e.statusText}): Returned non-JSON content type '${r}': ${n.slice(0,150)}`)}return await e.json()}async postGenesisKeystone(e,t){let r=`${this.lc}[${this.postGenesisKeystone.name}]`;try{Cr&&console.log(`${r} starting... (I: eecd082fc4a4381c8857928e8b090826)`);let n="/api/keystone/genesis",a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e,siteUsername:t?.siteUsername,siteUsernameExceptionKey:t?.siteUsernameExceptionKey})}),s=await this.parseResponseJson(a,n);if(!a.ok){let i=s.message||s.error||"Unknown error";return console.error(`${r} server rejected genesis keystone: ${i}`),{success:!1,message:i,addr:s.addr,statusCode:a.status}}return Cr&&console.log(`${r} genesis keystone posted successfully. pending: ${s.pending}`),{success:!0,pending:!!s.pending,statusCode:a.status,addr:s.addr,siteUsername:s.siteUsername,message:s.message}}catch(n){let a=E(n);return console.error(`${r} error: ${a}`),{success:!1,message:a}}}async putEvolveKeystone({domainAddr:e,keystoneIbGib:t,relatedKeystoneIbGibs:r=[],revokeTokens:n}){let a=`${this.lc}[${this.putEvolveKeystone.name}]`;try{Cr&&console.log(`${a} posting evolved keystone...`);let s=`/api/keystone/evolve/${encodeURIComponent(e)}`,i=await fetch(s,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t,relatedKeystoneIbGibs:r,revokeTokens:n})}),c=await this.parseResponseJson(i,s);if(!i.ok){let l=c.message||c.error||"Unknown error";return console.error(`${a} server rejected keystone evolution: ${l}`),{success:!1,message:l}}return Cr&&console.log(`${a} keystone evolution accepted by server.`),{success:!0}}catch(s){let i=E(s);return console.error(`${a} fetch error: ${i}`),{success:!1,message:i}}}async lookupPrimaryKeystone({identifier:e}){let t=`${this.lc}[${this.lookupPrimaryKeystone.name}]`;try{let r="/api/keystone/lookup",n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:e})}),a=await this.parseResponseJson(n,r);if(!n.ok){let s=a.message||a.error||"Identity not found";return console.error(`${t} server lookup failed: ${s}`),{success:!1,message:s}}return{success:!0,tjpAddr:a.tjpAddr,siteUsername:a.siteUsername,primaryKeystoneIbGib:a.primaryKeystoneIbGib}}catch(r){let n=E(r);return console.error(`${t} lookup fetch error: ${n}`),{success:!1,message:n}}}async checkEmailAvailability({email:e}){let t=`${this.lc}[${this.checkEmailAvailability.name}]`;try{let r=`/api/keystone/check-email?email=${encodeURIComponent(e)}`,n=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"}}),a=await this.parseResponseJson(n,r);if(!n.ok){let s=a.message||a.error||"Server check failed";return console.error(`${t} email check failed: ${s}`),{available:!1,message:s}}return{available:a.available??!0,message:a.message}}catch(r){let n=E(r);return console.error(`${t} check email error: ${n}`),{available:!0}}}async checkSiteUsernameAvailability({siteUsername:e}){let t=`${this.lc}[${this.checkSiteUsernameAvailability.name}]`;try{let r=`/api/keystone/check-site-username/${encodeURIComponent(e.trim())}`,n=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"}}),a=await this.parseResponseJson(n,r);if(!n.ok){let s=a.message||a.error||"Server check failed";return console.error(`${t} site username check failed: ${s}`),{available:!1,message:s}}return{available:a.available??!0,requiresExceptionKey:!!a.requiresExceptionKey,reason:a.reason,message:a.message,retryAfterMs:a.retryAfterMs}}catch(r){let n=E(r);return console.error(`${t} check site username error: ${n}`),{available:!1,message:n}}}async requestSiteUsernameException({siteUsername:e,email:t,applicantName:r,projectTitle:n,reason:a,profileUrl:s}){let i=`${this.lc}[${this.requestSiteUsernameException.name}]`;try{let c="/api/keystone/request-site-username-exception",l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteUsername:e,email:t,applicantName:r,projectTitle:n,reason:a,profileUrl:s})}),d=await this.parseResponseJson(l,c);if(!l.ok){let f=d.message||d.error||"Server rejected exception request";return console.error(`${i} exception request failed: ${f}`),{success:!1,message:f}}return{success:!0,requestId:d.requestId,message:d.message}}catch(c){let l=E(c);return console.error(`${i} request exception error: ${l}`),{success:!1,message:l}}}async getKeystoneGraph(e){let t=`${this.lc}[${this.getKeystoneGraph.name}]`;try{Cr&&console.log(`${t} fetching keystone graph...`);let r=`/api/keystone/${encodeURIComponent(e)}?getLatest=true&getGraph=true`,n=await fetch(r,{method:"GET",headers:{Accept:"application/json"}}),a=await this.parseResponseJson(n,r);if(!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(r){let n=E(r);return console.error(`${t} fetch error: ${n}`),{success:!1,message:n}}}async getIbGib(e,t,r=!1){let n=`${this.lc}[${this.getIbGib.name}]`;try{Cr&&console.log(`${n} fetching single ibGib frame...`);let a=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${r}&getGraph=false`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await this.parseResponseJson(s,a);if(!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=E(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async getIbGibGraph(e,t,r=!1){let n=`${this.lc}[${this.getIbGibGraph.name}]`;try{Cr&&console.log(`${n} fetching ibGib graph...`);let a=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${r}&getGraph=true`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(!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=E(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async postVerificationCode({email:e,primaryTjpAddr:t}){let r=`${this.lc}[${this.postVerificationCode.name}]`;try{let n="/api/email/verification-code",a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,primaryTjpAddr:t})}),s=await this.parseResponseJson(a,n);if(!a.ok){let i=s.message||s.error||"Verification code request failed";return console.error(`${r} server verification code post failed: ${i}`),{success:!1,message:i}}return{success:!0,message:s.message}}catch(n){let a=E(n);return console.error(`${r} post verification code error: ${a}`),{success:!1,message:a}}}async postMagicLink(e){return this.postVerificationCode(e)}async postVerifyCode({email:e,primaryTjpAddr:t,code:r}){let n=`${this.lc}[${this.postVerifyCode.name}]`;try{let a="/api/email/verify-code",s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,primaryTjpAddr:t,code:r})}),i=await this.parseResponseJson(s,a);if(!s.ok){let c=i.message||i.error||"Code verification failed";return console.error(`${n} server verify-code failed: ${c}`),{success:!1,message:c}}return Cr&&console.log(`${n} verification code accepted.`),{success:!0,message:i.message}}catch(a){let s=E(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async postCustodianGenesis({email:e,code:t,username:r,siteUsername:n,siteUsernameExceptionKey:a}){let s=`${this.lc}[${this.postCustodianGenesis.name}]`;try{let i="/api/identity/custodian/genesis",c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,code:t,username:r,siteUsername:n,siteUsernameExceptionKey:a})}),l=await this.parseResponseJson(c,i);if(!c.ok){let d=l.message||l.error||"Custodian genesis failed";return console.error(`${s} custodian genesis failed: ${d}`),{success:!1,message:d}}return{success:!0,isNewIdentity:!!l.isNewIdentity,primaryTjpAddr:l.primaryTjpAddr,primaryKeystone:l.primaryKeystone,primaryGraph:l.primaryGraph,custodianReqs:l.custodianReqs,message:l.message}}catch(i){let c=E(i);return console.error(`${s} post custodian genesis error: ${c}`),{success:!1,message:c}}}async postCustodianRegisterDelegate({delegateKeystone:e}){let t=`${this.lc}[${this.postCustodianRegisterDelegate.name}]`;try{let r="/api/identity/custodian/register-delegate",n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({delegateKeystone:e})}),a=await this.parseResponseJson(n,r);if(!n.ok){let s=a.message||a.error||"Custodian delegate registration failed";return console.error(`${t} custodian delegate registration failed: ${s}`),{success:!1,message:s}}return{success:!0,primaryTjpAddr:a.primaryTjpAddr,evolvedPrimaryKeystone:a.evolvedPrimaryKeystone,primaryGraph:a.primaryGraph,message:a.message}}catch(r){let n=E(r);return console.error(`${t} post custodian register delegate error: ${n}`),{success:!1,message:n}}}async getSsoConfig(){let e=`${this.lc}[${this.getSsoConfig.name}]`;try{let t="/api/identity/sso/config",r=await fetch(t,{method:"GET"}),n=await this.parseResponseJson(r,t);return r.ok?{success:!0,providers:n.providers}:{success:!1,message:n.message||n.error||"Failed to fetch SSO config"}}catch(t){let r=E(t);return console.error(`${e} fetch SSO config error: ${r}`),{success:!1,message:r}}}async postSsoLogin({code:e,providerId:t,redirectUri:r,username:n,siteUsername:a,siteUsernameExceptionKey:s}){let i=`${this.lc}[${this.postSsoLogin.name}]`;try{let c="/api/identity/sso/login",l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,providerId:t,redirectUri:r,username:n,siteUsername:a,siteUsernameExceptionKey:s})}),d=await this.parseResponseJson(l,c);if(!l.ok){let f=d.message||d.error||"SSO login code exchange failed";return console.error(`${i} SSO login code exchange failed: ${f}`),{success:!1,message:f}}return{success:!0,isNewIdentity:!!d.isNewIdentity,primaryTjpAddr:d.primaryTjpAddr,primaryKeystone:d.primaryKeystone,primaryGraph:d.primaryGraph,custodianReqs:d.custodianReqs,userInfo:d.userInfo,message:d.message}}catch(c){let l=E(c);return console.error(`${i} post SSO login error: ${l}`),{success:!1,message:l}}}},Ds;function dS(){return Ds||(Ds=new Zc),Ds}h(dS,"getApiBridge");function fS(o){Ds=o}h(fS,"setApiBridge");export{h as a,Ie as b,dt as c,B as d,rt as e,te as f,q as g,X as h,De as i,E as j,Uo as k,ft as l,jt as m,bt as n,il as o,I as p,K as q,no as r,Q as s,ue as t,Ue as u,vt as v,hl as w,Se as x,ko as y,Ce as z,ee as A,Ne as B,Ae as C,ie as D,ne as E,qt as F,H as G,bg as H,hg as I,pg as J,jo as K,fh as L,Fn as M,Bn as N,Ng as O,Dg as P,vg as Q,El as R,kn as S,qn as T,zs as U,bh as V,kg as W,Vn as X,lr as Y,Wn as Z,Ol as _,Yn as $,uh as aa,mh as ba,aE as ca,sE as da,iE as ea,cE as fa,lE as ga,dE as ha,Lt as ia,Fl as ja,si as ka,Ah as la,_h as ma,so as na,Pr as oa,Wl as pa,Ph as qa,oa as ra,fi as sa,QE as ta,z as ua,ce as va,pi as wa,V as xa,zl as ya,ia as za,ca as Aa,Je as Ba,ui as Ca,Zl as Da,J as Ea,ao as Fa,Ko as Ga,td as Ha,pt as Ia,zo as Ja,Lh as Ka,bd as La,hd as Ma,Rh as Na,Uh as Oa,Mh as Pa,Tt as Qa,Ei as Ra,Fh as Sa,da as Ta,ve as Ua,Bh as Va,kh as Wa,fa as Xa,ot as Ya,ha as Za,_t as _a,Bw as $a,ud as ab,Wo as bb,nt as cb,at as db,md as eb,ye as fb,Fe as gb,ae as hb,pr as ib,zw as jb,Wh as kb,Jw as lb,Zw as mb,Qw as nb,e2 as ob,g2 as pb,E2 as qb,w2 as rb,y2 as sb,$2 as tb,I2 as ub,A2 as vb,_2 as wb,T2 as xb,G2 as yb,S2 as zb,Kh as Ab,zh as Bb,Jh as Cb,Rr as Db,Nd as Eb,Zh as Fb,Ut as Gb,Ze as Hb,tn as Ib,Di as Jb,vi as Kb,Be as Lb,ut as Mb,bo as Nb,Ld as Ob,Rd as Pb,rn as Qb,on as Rb,Li as Sb,cy as Tb,ly as Ub,gy as Vb,Jd as Wb,an as Xb,Mr as Yb,it as Zb,Ip as _b,_$ as $b,Ca as ac,Mt as bc,mr as cc,kr as dc,If as ec,Gp as fc,Af as gc,H$ as hc,po as ic,Cf as jc,fn as kc,qi as lc,t6 as mc,r6 as nc,o6 as oc,Xi as pc,Oa as qc,d6 as rc,Hi as sc,f6 as tc,Pf as uc,vf as vc,xp as wc,Cp as xc,Np as yc,Dp as zc,vp as Ac,Pp as Bc,Op as Cc,S6 as Dc,va as Ec,Pa as Fc,Lp as Gc,Wi as Hc,Qo as Ic,io as Jc,Rp as Kc,Up as Lc,ur as Mc,pc as Nc,uc as Oc,gu as Pc,Zc as Qc,dS as Rc,fS as Sc,zr as Tc,_u as Uc,Fc as Vc,Ua as Wc,Bb as Xc,Lu as Yc,Ss as Zc,Ru as _c,Bp as $c,Zt as ad,Qt as bd,zi as cd,Ar as dd,ws as ed,Ma as fd,$t as gd,jp as hd,Hf as id,hn as jd,qe as kd,Vf as ld,T1 as md,qp as nd,G1 as od,Ed as pd,Vw as qd,wd as rd,Mp as sd,Uf as td,j6 as ud,Fp as vd,St as wd,rb as xd,su as yd,Ge as zd,Te as Ad,Wf as Bd,Hp as Cd,It as Dd,un as Ed,rc as Fd,ka as Gd,yn as Hd,mt as Id,Xe as Jd,iu as Kd,Wa as Ld,cu as Md,lu as Nd,Cu as Od,s_ as Pd,xr as Qd,Lb as Rd,T_ as Sd,vu as Td,Pu as Ud,Mu as Vd,gt as Wd,Yr as Xd,cb as Yd,za as Zd,_n as _d,Go as $d,Tr as ae,_s as be,Su as ce,Bu as de,ju as ee,Xu as fe,Yu as ge,zu as he,tm as ie};
|