@rizom/ops 0.2.0-alpha.674 → 0.2.0-alpha.675
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/brains-ops.js +7 -7
- package/dist/deploy.js +1 -1
- package/dist/index.js +8 -8
- package/package.json +1 -1
package/dist/brains-ops.js
CHANGED
|
@@ -357,8 +357,8 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
357
357
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
358
358
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Ag(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",n=[];if(o&&t.sep&&!t.value){let i=[];for(let s=0;s<t.sep.length;++s){let a=t.sep[s];switch(a.type){case"newline":i.push(s);break;case"space":break;case"comment":if(a.indent>e.indent)i.length=0;break;default:i.length=0}}if(i.length>=2)n=t.sep.splice(i[1])}switch(this.type){case"anchor":case"tag":if(o||t.value)n.push(this.sourceToken),e.items.push({start:n}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(o||t.value)n.push(this.sourceToken),e.items.push({start:n,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(Oi(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=Bc(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Oi(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]});else if(XZ(t.key)&&!Oi(t.sep,"newline")){let i=Bc(t.start),s=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:s,sep:a}]})}else if(n.length>0)t.sep=t.sep.concat(n,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||o)e.items.push({start:n,key:null,sep:[this.sourceToken]});else if(Oi(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);if(o||t.value)e.items.push({start:n,key:i,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(i);else Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0;return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Oi(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)e.items.push({start:n});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Ag(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||Oi(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:o,sep:[]});else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=kg(r),n=Bc(o);YZ(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
359
359
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
360
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=kg(e),r=Bc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=kg(e),r=Bc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}mae.Parser=eU});var iU=ge(function(_ae){var tU=fA(),gae=Td(),zd=$d(),yae=xk(),bae=Me(),Sae=xA(),rU=_A();function nU(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Sae.LineCounter||null,prettyErrors:t}}function vae(e,t={}){let{lineCounter:r,prettyErrors:o}=nU(t),n=new rU.Parser(r?.addNewLine),i=new tU.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(zd.prettifyError(e,r)),a.warnings.forEach(zd.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function oU(e,t={}){let{lineCounter:r,prettyErrors:o}=nU(t),n=new rU.Parser(r?.addNewLine),i=new tU.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new zd.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(zd.prettifyError(e,r)),s.warnings.forEach(zd.prettifyError(e,r));return s}function wae(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=oU(e,r);if(!n)return null;if(n.warnings.forEach((i)=>yae.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function xae(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(bae.isDocument(e)&&!o)return e.toString(r);return new gae.Document(e,o,r).toString(r)}_ae.parse=wae;_ae.parseAllDocuments=vae;_ae.parseDocument=oU;_ae.stringify=xae});var Tae,$ae,Rae,EA,Oae,Ci,Cae,Pae,zae,Nae,
|
|
361
|
-
`)}function fU(e,t,r,o){if(!Io(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>jc(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];aU(s?.key,i.key),aU(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function pU(e){let t=dU(e),r=dce(t.toJS()),o=kA(t,"schemaVersion"),n=kA(t,"model");cU(o,kA(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",js);let i=fU(t,"preset","bundles",r.bundles);if(cU(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return Zs.parse(t.toJS()),t.toString({lineWidth:0})}function mU(e){let t=dU(e),r=fce(t.toJS());if(r.bundlesOverride)fU(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return dn.parse(t.toJS()),t.toString({lineWidth:0})}var lU,Dd,cce,lce,uce;var hU=w(()=>{vo();he();Nd();wo();lU=l.enum(["core","default","pro"]),Dd=l.string().min(1),cce=l.strictObject({schemaVersion:l.literal(1),brainVersion:Ot,model:l.literal("rover"),githubOrg:l.string().min(1),contentRepoPrefix:l.string().min(1),domainSuffix:l.string().min(1),preset:lU,aiApiKey:Dd,gitSyncToken:Dd,contentRepoAdminToken:Dd,agePublicKey:l.string().startsWith("age1").min(1)}),lce=l.strictObject({members:l.array(yr).min(1),brainVersionOverride:Ot.optional(),presetOverride:lU.optional(),aiApiKeyOverride:Dd.optional(),gitSyncTokenOverride:Dd.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:l.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),uce=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function yU(e,t){let r=Jn(e,{keepSourceTokens:!0});if(r.errors.length>0||!Io(r.contents))throw Error(`Invalid ${t} YAML`);return r}function yce(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function bU(e,t,r){if(!yce(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function SU(e){let t=un(e,gce);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function vU(e,t){let r=yU(e,"pilot desired-state"),o=mce.parse(r.toJS());return bU("pilot.yaml",o.bundles,t),r.set("bundleContract",js),r.set("bundles",t.targetBundles),Zs.parse(r.toJS()),r.toString({lineWidth:0})}function wU(e,t,r){let o=yU(e,`cohort ${t}`),n=hce.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);bU(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return dn.parse(o.toJS()),o.toString({lineWidth:0})}var pce,AA,$g,mce,hce,gU,gce;var xU=w(()=>{vo();he();Nd();wo();pce=l.enum(["core","site","publishing","team"]),AA=l.array(pce).min(1),$g=l.array(l.string().min(1)),mce=l.strictObject({brainVersion:Ot,bundles:AA,add:$g.optional(),remove:$g.optional(),githubOrg:l.string().min(1),contentRepoPrefix:l.string().min(1),domainSuffix:l.string().min(1),aiApiKey:l.string().min(1),gitSyncToken:l.string().min(1),contentRepoAdminToken:l.string().min(1),agePublicKey:l.string().startsWith("age1").min(1)}),hce=l.strictObject({members:l.array(yr).min(1),brainVersionOverride:Ot.optional(),bundlesOverride:AA.optional(),addOverride:$g.optional(),removeOverride:$g.optional(),aiApiKeyOverride:l.string().min(1).optional(),gitSyncTokenOverride:l.string().min(1).optional()}),gU=l.strictObject({sourceBundles:AA,targetBundles:l.array(KI).min(1)}),gce=l.strictObject({bundleContract:l.literal(js),pilot:gU,cohorts:l.record(yr,gU)})});var AU={};Zt(AU,{loadCapabilityBundleReview:()=>kce,loadReviewedSitePins:()=>Ice,parseReviewedSitePins:()=>kU,stageLegacyCrossover:()=>Tce});import{access as bce,cp as Sce,mkdir as _U,readFile as Uc,readdir as IU,writeFile as Zc}from"fs/promises";import{basename as vce,join as Kn,relative as Rg,resolve as EU}from"path";import{fileURLToPath as wce}from"url";function kU(e){let t=un(e,xce);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Ice(e){return kU(await Uc(e,"utf8"))}async function kce(e){return SU(await Uc(e,"utf8"))}async function Ace(e,t){let r=Kn(e,"users"),o=(await IU(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Kn(r,s),c=await Uc(a,"utf8"),u=Jn(c,{keepSourceTokens:!0});if(u.errors.length>0||!Io(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=_ce.parse(u.toJS());if(!d.siteOverride)continue;let f=t?.[d.handle];if(!f)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),f.package!==d.siteOverride.package||f.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==f.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==f.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],f.version),f.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],f.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);$h.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==c)await Zc(a,m),i.push(Rg(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Tce(e,t,r={}){let o=EU(e),n=EU(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Sce(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=vce(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Kn(n,"docs","canonical-crossover-record.md");try{await bce(s)}catch{await _U(Kn(n,"docs"),{recursive:!0}),await Zc(s,await Uc(Ece,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Kn(n,"pilot.yaml"),c=await Uc(a,"utf8"),d=Jn(c).toJS();if(!cd(d))throw Error(`${a} is not a YAML mapping`);let f=Array.isArray(d.bundles),m=r.bundleReview,h;if(f){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=vU(c,m.pilot)}else h=pU(c);await Zc(a,h),i.push("pilot.yaml");let b=Kn(n,"cohorts"),y=(await IU(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Kn(b,A),L=await Uc(O,"utf8"),z=A.replace(/\.ya?ml$/,""),K=m?.cohorts[z];if(K)S.delete(z);await Zc(O,f?wU(L,z,K):mU(L)),i.push(Rg(n,O))}if(f&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Ace(n,r.sitePins));let x=await wt(n),_=Ph(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Kn(n,"users",A.handle);if(await _U(L,{recursive:!0}),O.brainYaml){let z=Kn(L,"brain.yaml");await Zc(z,O.brainYaml),i.push(Rg(n,z))}if(O.envFile){let z=Kn(L,".env");await Zc(z,O.envFile),i.push(Rg(n,z))}}return await _i(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var xce,_ce,Ece;var TU=w(()=>{vo();ld();he();Nd();ak();hU();xU();fn();ad();wo();xce=l.strictObject({sites:l.record(yr,HI)}),_ce=l.object({handle:yr,siteOverride:l.object({package:l.string().min(1),version:Ot.optional(),theme:l.string().min(1).optional(),themeVersion:Ot.optional()}).optional()}).passthrough(),Ece=wce(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var RU,$ce,Rce,Oce,Ao,Ld,Cce,TA,Pce,$U,zce,Nce,OU,kRe,CU;var Og=w(()=>{tI();RU=["primary","secondary"],$ce=l.custom((e)=>typeof e==="function","Expected a React component"),Rce=l.strictObject({show:l.boolean().optional(),label:l.string().min(1).optional(),slot:l.enum(RU).optional(),priority:l.number().optional()}),Oce=l.strictObject({id:l.string().min(1),template:l.string().min(1),content:l.unknown().optional(),dataQuery:l.looseObject({entityType:l.string().optional(),template:l.string().optional(),query:l.record(l.string(),l.unknown()).optional()}).optional(),order:l.number().optional()}),Ao=l.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),Ld=l.strictObject({title:l.string().optional(),description:l.string().optional(),navigationLabel:l.string().optional()}),Cce=l.strictObject({id:l.string().min(1),path:l.string().startsWith("/"),title:l.string().optional(),pageLabel:l.string().optional(),description:l.string().optional(),sections:l.array(Oce).optional(),layout:l.string().min(1).optional(),fullscreen:l.boolean().optional(),pluginId:l.string().optional(),sourceEntityType:l.string().optional(),external:l.boolean().optional(),navigation:Rce.optional(),translations:l.record(Ao,Ld).optional()}),TA=l.strictObject({label:l.string().min(1),pluralName:l.string().min(1).optional(),layout:l.string().min(1).optional(),detailTemplate:l.string().min(1).optional(),paginate:l.boolean().optional(),pageSize:l.number().int().positive().optional(),citable:l.boolean().optional(),navigation:l.strictObject({show:l.boolean().optional(),slot:l.enum(RU).optional(),priority:l.number().optional()}).optional()}),Pce=l.strictObject({schema:l.custom((e)=>e instanceof l.ZodType,"Expected a Zod schema"),component:l.custom((e)=>typeof e==="function","Expected a React component"),title:l.string().min(1),description:l.string(),requiredPermission:l.enum(["admin","trusted","public"]).optional(),fullscreen:l.boolean().optional()}),$U=l.strictObject({namespace:l.string().min(1),sections:l.record(l.string(),Pce)}),zce=l.record(l.string(),l.json()),Nce=l.record(l.string(),l.record(l.string(),zce)),OU={layouts:l.record(l.string(),$ce).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:l.array(Cce),content:Nce.optional(),sections:l.union([$U,l.array($U)]).optional(),themeOverride:l.string().optional(),headScripts:l.array(l.string()).optional(),entityDisplay:l.record(l.string(),TA),staticAssets:l.record(l.string(),l.string()).optional(),languages:l.array(Ao).min(1).optional()},kRe=l.strictObject(OU).partial(),CU=l.strictObject(OU).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[c,u]of r.entries()){let d=u.toLowerCase();if(o.has(d))t.addIssue({code:"custom",path:["languages",c],message:`Language "${u}" is declared twice`});o.add(d)}let n=r.slice(1).map((c)=>`/${c.toLowerCase()}`),i=new Set;for(let[c,u]of e.routes.entries()){if(i.has(u.id))t.addIssue({code:"custom",path:["routes",c,"id"],message:`Duplicate route id "${u.id}"`});i.add(u.id);let d=u.path.toLowerCase(),f=n.find((h)=>d===h||d.startsWith(`${h}/`));if(f)t.addIssue({code:"custom",path:["routes",c,"path"],message:`Route path "${u.path}" is under ${f}, where another language's pages are built`});let m=u.layout??"default";if(!e.layouts[m])t.addIssue({code:"custom",path:["routes",c,"layout"],message:`Unknown layout "${m}"`});for(let[h,b]of(u.sections??[]).entries()){let y=/^([^:.\s]+)\.([^:.\s]+)$/.exec(b.template);if(y)t.addIssue({code:"custom",path:["routes",c,"sections",h,"template"],message:`Section template "${b.template}" is written "${y[1]}:${y[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((c)=>[c.namespace,c]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});for(let[c,u]of Object.entries(e.content??{})){let d=a.get(c);if(!d){t.addIssue({code:"custom",path:["content",c],message:`Content namespace "${c}" has no section group`});continue}for(let[f,m]of Object.entries(u)){let h=d.sections[f];if(!h){t.addIssue({code:"custom",path:["content",c,f],message:`Content section "${c}:${f}" is not defined`});continue}let b=h.schema.safeParse(m);if(!b.success)t.addIssue({code:"custom",path:["content",c,f],message:`Content does not satisfy the "${c}:${f}" schema: ${l.prettifyError(b.error)}`})}}})});var PU,zU,NU,Cg,DU,Lce,LU,BU,Bce,jU,ZU,jce,Pg;var $A=w(()=>{Vt();he();Og();Og();PU=l.object({id:l.string(),template:l.string(),content:l.unknown().optional(),dataQuery:l.looseObject({entityType:l.string().optional(),template:l.string().optional(),query:l.looseObject({id:l.string().optional(),limit:l.number().optional(),offset:l.number().optional()}).optional()}).optional(),order:l.number().optional()}),zU=["primary","secondary"],NU=l.object({show:l.boolean().default(!1),label:l.string().optional(),slot:l.enum(zU).default("primary"),priority:l.number().min(0).max(100).default(50)}).optional(),Cg=l.object({id:l.string(),path:l.string(),title:l.string().default(""),pageLabel:l.string().optional(),description:l.string().default(""),sections:l.array(PU).default([]),layout:l.string().default("default"),fullscreen:l.boolean().optional(),pluginId:l.string().optional(),sourceEntityType:l.string().optional(),external:l.boolean().optional(),navigation:NU,translations:l.record(Ao,Ld).optional(),languages:l.array(Ao).optional()}),DU=l.object({routes:l.array(Cg),pluginId:l.string()}),Lce=_e({channel:"plugin:site-builder:route:register",request:DU,response:l.void(),delivery:"command"}),LU=l.strictObject({}),BU=l.array(Cg),Bce=_e({channel:"site-builder:routes:list",request:LU,response:BU,delivery:"request"}),jU=l.strictObject({}),ZU=l.array(Cg),jce=_e({channel:"plugin:site-builder:pages",request:jU,response:ZU,delivery:"collect"}),Pg=l.object({label:l.string(),href:l.string(),priority:l.number()})});var UU,qU,MU,Zce;var FU=w(()=>{Vt();he();UU=l.object({pluginId:l.string(),slotName:l.string(),render:l.custom((e)=>typeof e==="function"),priority:l.number().optional()}),qU=l.strictObject({}),MU=l.array(UU),Zce=_e({channel:"plugin:site-builder:slots",request:qU,response:MU,delivery:"collect"})});var JU="site:metadata:updated",zg,KU,HU,qc,VU,Uce,qce,Mce;var RA=w(()=>{Vt();he();$A();zg=l.object({heading:l.string().describe("Main CTA heading text"),buttonText:l.string().describe("Call-to-action button text"),buttonLink:l.string().describe("URL or anchor for the CTA button")}),KU=l.object({title:l.string().optional(),description:l.string().optional(),copyright:l.string().optional(),cta:zg.optional()}),HU=l.object({blurb:l.string().optional().describe("Short italic subtitle under the section title")}),qc=l.object({represents:l.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:l.string().describe("The site's title"),description:l.string().describe("The site's description"),url:l.string().optional().describe("Canonical site URL"),copyright:l.string().optional().describe("Copyright notice text"),logo:l.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:l.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:l.string().optional().describe("Analytics script HTML"),cta:zg.optional().describe("Call-to-action configuration"),sections:l.record(l.string(),HU).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:l.record(Ao,KU).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),VU=l.strictObject({}),Uce=_e({channel:"site:metadata:get",request:VU,response:qc,delivery:"request"}),qce=xi(JU,qc),Mce=qc.extend({copyright:l.string(),navigation:l.object({primary:l.array(Pg),secondary:l.array(Pg)}),socialLinks:l.array(JI).optional().describe("Social media links from profile metadata"),photo:l.string().optional().describe("The anchor's photo, as ")})});var URe;var OA=w(()=>{he();URe=l.record(l.string(),l.unknown())});var Bd=w(()=>{OA()});var WU=w(()=>{Vt();Bd()});var GU=w(()=>{Bd();Vt()});var QU=w(()=>{Bd();Vt()});var nOe;var YU=w(()=>{he();nOe=l.record(l.string(),l.unknown())});var sOe;var XU=w(()=>{he();Sc();sOe=l.record(l.string(),l.unknown())});var e6=w(()=>{Sc()});var t6=w(()=>{Bd();WU();GU();QU();YU();XU();e6();OA()});var Xce;var r6=w(()=>{he();Xce=l.object({slug:l.string(),title:l.string(),type:l.string(),entityId:l.string(),contentHash:l.string()})});var PA=w(()=>{t6();r6()});var n6=w(()=>{PA();he()});var ele,tle,rle;var Dg=w(()=>{he();Vt();ele={url:l.string(),typeLabel:l.string(),listUrl:l.string(),listLabel:l.string()},tle={url:l.string().nullable().default(null),typeLabel:l.string().nullable().default(null),listUrl:l.string().nullable().default(null),listLabel:l.string().nullable().default(null)},rle=l.object({name:l.string(),description:l.string(),schema:l.unknown(),basePrompt:l.string().optional(),useKnowledgeContext:l.boolean().optional(),requiredPermission:l.enum(["admin","trusted","public"]),formatter:l.unknown().optional(),overlayFormatter:l.unknown().optional(),layout:l.object({component:l.unknown().optional(),fullscreen:l.boolean().optional(),formats:l.unknown().optional()}).optional(),dataSourceId:l.string().optional()})});var Lg=w(()=>{Dg()});var s6=w(()=>{Lg()});var zA=()=>{};var ole,ile,Mc,a6,sle;var c6=w(()=>{Vt();he();zA();ole=l.enum(["admin","trusted","public"]),ile=l.enum(["create","update","delete","extract","publish"]),Mc=l.enum(["never","admin","trusted","public"]),a6=l.strictObject({create:Mc.optional(),update:Mc.optional(),delete:Mc.optional(),extract:Mc.optional(),publish:Mc.optional()}),sle=l.record(l.string(),a6)});var l6=w(()=>{Lg();Dg()});var ale,cle,Bg,lle,ule,dle;var u6=w(()=>{he();ale=l.enum(["site-content-preview","site-content-production"]),cle=l.enum(["web","image","pdf","epub"]),Bg=l.custom((e)=>typeof e==="function"),lle=l.object({name:l.string(),schema:l.unknown(),description:l.string().optional(),pluginId:l.string(),renderers:l.object({web:l.union([Bg,l.string()]).optional(),image:l.union([Bg,l.string()]).optional(),pdf:l.union([Bg,l.string()]).optional(),epub:l.union([Bg,l.string()]).optional()})}),ule=l.object({enableContentGeneration:l.boolean().default(!1),outputDir:l.string(),workingDir:l.string().optional(),environment:l.enum(["preview","production"]).default("preview"),siteConfig:l.object({title:l.string(),description:l.string(),url:l.string().optional()}).optional()}),dle=l.object({success:l.boolean(),routesBuilt:l.number(),errors:l.array(l.string()).optional(),warnings:l.array(l.string()).optional()})});var d6=w(()=>{Dg();s6();Lg();c6();zA();l6();u6()});var NA=ge(function(ple,jg){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Nt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Nt,this.updater=D||bt}function s(){}function a(g){return""+g}function c(g){try{a(g);var E=!1}catch(q){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===In?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case ve:return"Suspense";case ke:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case pe:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case Ie:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case we:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===we)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function f(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(to.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){Yi||(Yi=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return Xi[g]||(Xi[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,q,te){var se=D.ref;return g={$$typeof:M,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:q}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===we&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===M}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(c(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,q){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case M:case N:se=!0;break;case we:return se=g._init,K(se(g._payload),E,D,J,q)}}if(se){se=g,q=q(se);var ye=J===""?"."+L(se,0):J;return $r(q)?(D="",ye!=null&&(D=ye.replace(fa,"$&/")+"/"),K(q,E,D,"",function($e){return $e})):q!=null&&(A(q)&&(q.key!=null&&(se&&se.key===q.key||c(q.key)),D=x(q,D+(q.key==null||se&&se.key===q.key?"":(""+q.key).replace(fa,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),q=D),E.push(q)),1}if(se=0,ye=J===""?".":J+":",$r(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,q);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Mo||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Mo=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,q);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,q);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],q=0;return K(g,J,"","",function(te){return E.call(D,te,q++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(q){if(g._status===0||g._status===-1){g._status=1,g._result=q;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=q)}},function(q){if(g._status===0||g._status===-1){g._status=2,g._result=q;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=q)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
360
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=kg(e),r=Bc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=kg(e),r=Bc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}mae.Parser=eU});var iU=ge(function(_ae){var tU=fA(),gae=Td(),zd=$d(),yae=xk(),bae=Me(),Sae=xA(),rU=_A();function nU(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Sae.LineCounter||null,prettyErrors:t}}function vae(e,t={}){let{lineCounter:r,prettyErrors:o}=nU(t),n=new rU.Parser(r?.addNewLine),i=new tU.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(zd.prettifyError(e,r)),a.warnings.forEach(zd.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function oU(e,t={}){let{lineCounter:r,prettyErrors:o}=nU(t),n=new rU.Parser(r?.addNewLine),i=new tU.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new zd.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(zd.prettifyError(e,r)),s.warnings.forEach(zd.prettifyError(e,r));return s}function wae(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=oU(e,r);if(!n)return null;if(n.warnings.forEach((i)=>yae.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function xae(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(bae.isDocument(e)&&!o)return e.toString(r);return new gae.Document(e,o,r).toString(r)}_ae.parse=wae;_ae.parseAllDocuments=vae;_ae.parseDocument=oU;_ae.stringify=xae});var Tae,$ae,Rae,EA,Oae,Ci,Cae,Pae,zae,Nae,X$e,Dae,Lae,Bae,Tg,sU,jae,Zae,Uae,qae,Mae,Fae,Jae,Kae,Hae,Vae,Io,ko,Wae,jc,IA,Gae,Qae,Yae,Xae,ece,tce,rce,nce,oce,Jn,ice,sce,ace;var Nd=w(()=>{Tae=fA(),$ae=Td(),Rae=Gk(),EA=$d(),Oae=md(),Ci=Me(),Cae=Ai(),Pae=It(),zae=$i(),Nae=Ri(),X$e=Eg(),Dae=wA(),Lae=xA(),Bae=_A(),Tg=iU(),sU=fd();jae=Tae.Composer,Zae=$ae.Document,Uae=Rae.Schema,qae=EA.YAMLError,Mae=EA.YAMLParseError,Fae=EA.YAMLWarning,Jae=Oae.Alias,Kae=Ci.isAlias,Hae=Ci.isCollection,Vae=Ci.isDocument,Io=Ci.isMap,ko=Ci.isNode,Wae=Ci.isPair,jc=Ci.isScalar,IA=Ci.isSeq,Gae=Cae.Pair,Qae=Pae.Scalar,Yae=zae.YAMLMap,Xae=Nae.YAMLSeq,ece=Dae.Lexer,tce=Lae.LineCounter,rce=Bae.Parser,nce=Tg.parse,oce=Tg.parseAllDocuments,Jn=Tg.parseDocument,ice=Tg.stringify,sce=sU.visit,ace=sU.visitAsync});function uU(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"],remove:[...uce]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function dce(e){let t=cce.parse(e);return Zs.parse({brainVersion:t.brainVersion,bundleContract:js,...uU(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,aiApiKey:t.aiApiKey,gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function fce(e){let t=lce.parse(e),r=t.presetOverride?uU(t.presetOverride):void 0;return dn.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{aiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function dU(e){let t=Jn(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!Io(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function kA(e,t){if(!Io(e.contents))return;return e.contents.items.find((r)=>jc(r.key)&&r.key.value===t)}function aU(e,t){if(!ko(e)||!ko(t))return;if(e.commentBefore!==void 0)t.commentBefore=e.commentBefore;if(e.comment!==void 0)t.comment=e.comment;if(e.spaceBefore!==void 0)t.spaceBefore=e.spaceBefore}function cU(e,t){if(!e||!ko(t))return;let r=[ko(e.key)?e.key.commentBefore:void 0,ko(e.key)?e.key.comment:void 0,ko(e.value)?e.value.commentBefore:void 0,ko(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
|
|
361
|
+
`)}function fU(e,t,r,o){if(!Io(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>jc(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];aU(s?.key,i.key),aU(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function pU(e){let t=dU(e),r=dce(t.toJS()),o=kA(t,"schemaVersion"),n=kA(t,"model");cU(o,kA(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",js);let i=fU(t,"preset","bundles",r.bundles);if(cU(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return Zs.parse(t.toJS()),t.toString({lineWidth:0})}function mU(e){let t=dU(e),r=fce(t.toJS());if(r.bundlesOverride)fU(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return dn.parse(t.toJS()),t.toString({lineWidth:0})}var lU,Dd,cce,lce,uce;var hU=w(()=>{vo();he();Nd();wo();lU=l.enum(["core","default","pro"]),Dd=l.string().min(1),cce=l.strictObject({schemaVersion:l.literal(1),brainVersion:Ot,model:l.literal("rover"),githubOrg:l.string().min(1),contentRepoPrefix:l.string().min(1),domainSuffix:l.string().min(1),preset:lU,aiApiKey:Dd,gitSyncToken:Dd,contentRepoAdminToken:Dd,agePublicKey:l.string().startsWith("age1").min(1)}),lce=l.strictObject({members:l.array(yr).min(1),brainVersionOverride:Ot.optional(),presetOverride:lU.optional(),aiApiKeyOverride:Dd.optional(),gitSyncTokenOverride:Dd.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:l.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),uce=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function yU(e,t){let r=Jn(e,{keepSourceTokens:!0});if(r.errors.length>0||!Io(r.contents))throw Error(`Invalid ${t} YAML`);return r}function yce(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function bU(e,t,r){if(!yce(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function SU(e){let t=un(e,gce);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function vU(e,t){let r=yU(e,"pilot desired-state"),o=mce.parse(r.toJS());return bU("pilot.yaml",o.bundles,t),r.set("bundleContract",js),r.set("bundles",t.targetBundles),Zs.parse(r.toJS()),r.toString({lineWidth:0})}function wU(e,t,r){let o=yU(e,`cohort ${t}`),n=hce.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);bU(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return dn.parse(o.toJS()),o.toString({lineWidth:0})}var pce,AA,$g,mce,hce,gU,gce;var xU=w(()=>{vo();he();Nd();wo();pce=l.enum(["core","site","publishing","team"]),AA=l.array(pce).min(1),$g=l.array(l.string().min(1)),mce=l.strictObject({brainVersion:Ot,bundles:AA,add:$g.optional(),remove:$g.optional(),githubOrg:l.string().min(1),contentRepoPrefix:l.string().min(1),domainSuffix:l.string().min(1),aiApiKey:l.string().min(1),gitSyncToken:l.string().min(1),contentRepoAdminToken:l.string().min(1),agePublicKey:l.string().startsWith("age1").min(1)}),hce=l.strictObject({members:l.array(yr).min(1),brainVersionOverride:Ot.optional(),bundlesOverride:AA.optional(),addOverride:$g.optional(),removeOverride:$g.optional(),aiApiKeyOverride:l.string().min(1).optional(),gitSyncTokenOverride:l.string().min(1).optional()}),gU=l.strictObject({sourceBundles:AA,targetBundles:l.array(KI).min(1)}),gce=l.strictObject({bundleContract:l.literal(js),pilot:gU,cohorts:l.record(yr,gU)})});var AU={};Zt(AU,{loadCapabilityBundleReview:()=>kce,loadReviewedSitePins:()=>Ice,parseReviewedSitePins:()=>kU,stageLegacyCrossover:()=>Tce});import{access as bce,cp as Sce,mkdir as _U,readFile as Uc,readdir as IU,writeFile as Zc}from"fs/promises";import{basename as vce,join as Kn,relative as Rg,resolve as EU}from"path";import{fileURLToPath as wce}from"url";function kU(e){let t=un(e,xce);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Ice(e){return kU(await Uc(e,"utf8"))}async function kce(e){return SU(await Uc(e,"utf8"))}async function Ace(e,t){let r=Kn(e,"users"),o=(await IU(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Kn(r,s),c=await Uc(a,"utf8"),u=Jn(c,{keepSourceTokens:!0});if(u.errors.length>0||!Io(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=_ce.parse(u.toJS());if(!d.siteOverride)continue;let f=t?.[d.handle];if(!f)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),f.package!==d.siteOverride.package||f.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==f.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==f.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],f.version),f.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],f.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);$h.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==c)await Zc(a,m),i.push(Rg(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Tce(e,t,r={}){let o=EU(e),n=EU(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Sce(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=vce(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Kn(n,"docs","canonical-crossover-record.md");try{await bce(s)}catch{await _U(Kn(n,"docs"),{recursive:!0}),await Zc(s,await Uc(Ece,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Kn(n,"pilot.yaml"),c=await Uc(a,"utf8"),d=Jn(c).toJS();if(!cd(d))throw Error(`${a} is not a YAML mapping`);let f=Array.isArray(d.bundles),m=r.bundleReview,h;if(f){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=vU(c,m.pilot)}else h=pU(c);await Zc(a,h),i.push("pilot.yaml");let b=Kn(n,"cohorts"),y=(await IU(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Kn(b,A),L=await Uc(O,"utf8"),z=A.replace(/\.ya?ml$/,""),K=m?.cohorts[z];if(K)S.delete(z);await Zc(O,f?wU(L,z,K):mU(L)),i.push(Rg(n,O))}if(f&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Ace(n,r.sitePins));let x=await wt(n),_=Ph(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Kn(n,"users",A.handle);if(await _U(L,{recursive:!0}),O.brainYaml){let z=Kn(L,"brain.yaml");await Zc(z,O.brainYaml),i.push(Rg(n,z))}if(O.envFile){let z=Kn(L,".env");await Zc(z,O.envFile),i.push(Rg(n,z))}}return await _i(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var xce,_ce,Ece;var TU=w(()=>{vo();ld();he();Nd();ak();hU();xU();fn();ad();wo();xce=l.strictObject({sites:l.record(yr,HI)}),_ce=l.object({handle:yr,siteOverride:l.object({package:l.string().min(1),version:Ot.optional(),theme:l.string().min(1).optional(),themeVersion:Ot.optional()}).optional()}).passthrough(),Ece=wce(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var RU,$ce,Rce,Oce,Ao,Ld,Cce,TA,Pce,$U,zce,Nce,OU,IRe,CU;var Og=w(()=>{tI();RU=["primary","secondary"],$ce=l.custom((e)=>typeof e==="function","Expected a React component"),Rce=l.strictObject({show:l.boolean().optional(),label:l.string().min(1).optional(),slot:l.enum(RU).optional(),priority:l.number().optional()}),Oce=l.strictObject({id:l.string().min(1),template:l.string().min(1),content:l.unknown().optional(),dataQuery:l.looseObject({entityType:l.string().optional(),template:l.string().optional(),query:l.record(l.string(),l.unknown()).optional()}).optional(),order:l.number().optional()}),Ao=l.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),Ld=l.strictObject({title:l.string().optional(),description:l.string().optional(),navigationLabel:l.string().optional()}),Cce=l.strictObject({id:l.string().min(1),path:l.string().startsWith("/"),title:l.string().optional(),pageLabel:l.string().optional(),description:l.string().optional(),sections:l.array(Oce).optional(),layout:l.string().min(1).optional(),fullscreen:l.boolean().optional(),pluginId:l.string().optional(),sourceEntityType:l.string().optional(),external:l.boolean().optional(),navigation:Rce.optional(),translations:l.record(Ao,Ld).optional()}),TA=l.strictObject({label:l.string().min(1),pluralName:l.string().min(1).optional(),layout:l.string().min(1).optional(),detailTemplate:l.string().min(1).optional(),paginate:l.boolean().optional(),pageSize:l.number().int().positive().optional(),citable:l.boolean().optional(),navigation:l.strictObject({show:l.boolean().optional(),slot:l.enum(RU).optional(),priority:l.number().optional()}).optional()}),Pce=l.strictObject({schema:l.custom((e)=>e instanceof l.ZodType,"Expected a Zod schema"),component:l.custom((e)=>typeof e==="function","Expected a React component"),title:l.string().min(1),description:l.string(),requiredPermission:l.enum(["admin","trusted","public"]).optional(),fullscreen:l.boolean().optional()}),$U=l.strictObject({namespace:l.string().min(1),sections:l.record(l.string(),Pce)}),zce=l.record(l.string(),l.json()),Nce=l.record(l.string(),l.record(l.string(),zce)),OU={layouts:l.record(l.string(),$ce).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:l.array(Cce),content:Nce.optional(),sections:l.union([$U,l.array($U)]).optional(),themeOverride:l.string().optional(),headScripts:l.array(l.string()).optional(),entityDisplay:l.record(l.string(),TA),staticAssets:l.record(l.string(),l.string()).optional(),languages:l.array(Ao).min(1).optional()},IRe=l.strictObject(OU).partial(),CU=l.strictObject(OU).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[c,u]of r.entries()){let d=u.toLowerCase();if(o.has(d))t.addIssue({code:"custom",path:["languages",c],message:`Language "${u}" is declared twice`});o.add(d)}let n=r.slice(1).map((c)=>`/${c.toLowerCase()}`),i=new Set;for(let[c,u]of e.routes.entries()){if(i.has(u.id))t.addIssue({code:"custom",path:["routes",c,"id"],message:`Duplicate route id "${u.id}"`});i.add(u.id);let d=u.path.toLowerCase(),f=n.find((h)=>d===h||d.startsWith(`${h}/`));if(f)t.addIssue({code:"custom",path:["routes",c,"path"],message:`Route path "${u.path}" is under ${f}, where another language's pages are built`});let m=u.layout??"default";if(!e.layouts[m])t.addIssue({code:"custom",path:["routes",c,"layout"],message:`Unknown layout "${m}"`});for(let[h,b]of(u.sections??[]).entries()){let y=/^([^:.\s]+)\.([^:.\s]+)$/.exec(b.template);if(y)t.addIssue({code:"custom",path:["routes",c,"sections",h,"template"],message:`Section template "${b.template}" is written "${y[1]}:${y[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((c)=>[c.namespace,c]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});for(let[c,u]of Object.entries(e.content??{})){let d=a.get(c);if(!d){t.addIssue({code:"custom",path:["content",c],message:`Content namespace "${c}" has no section group`});continue}for(let[f,m]of Object.entries(u)){let h=d.sections[f];if(!h){t.addIssue({code:"custom",path:["content",c,f],message:`Content section "${c}:${f}" is not defined`});continue}let b=h.schema.safeParse(m);if(!b.success)t.addIssue({code:"custom",path:["content",c,f],message:`Content does not satisfy the "${c}:${f}" schema: ${l.prettifyError(b.error)}`})}}})});var PU,zU,NU,Cg,DU,Lce,LU,BU,Bce,jU,ZU,jce,Pg;var $A=w(()=>{Vt();he();Og();Og();PU=l.object({id:l.string(),template:l.string(),content:l.unknown().optional(),dataQuery:l.looseObject({entityType:l.string().optional(),template:l.string().optional(),query:l.looseObject({id:l.string().optional(),limit:l.number().optional(),offset:l.number().optional()}).optional()}).optional(),order:l.number().optional()}),zU=["primary","secondary"],NU=l.object({show:l.boolean().default(!1),label:l.string().optional(),slot:l.enum(zU).default("primary"),priority:l.number().min(0).max(100).default(50)}).optional(),Cg=l.object({id:l.string(),path:l.string(),title:l.string().default(""),pageLabel:l.string().optional(),description:l.string().default(""),sections:l.array(PU).default([]),layout:l.string().default("default"),fullscreen:l.boolean().optional(),pluginId:l.string().optional(),sourceEntityType:l.string().optional(),external:l.boolean().optional(),navigation:NU,translations:l.record(Ao,Ld).optional(),languages:l.array(Ao).optional()}),DU=l.object({routes:l.array(Cg),pluginId:l.string()}),Lce=_e({channel:"plugin:site-builder:route:register",request:DU,response:l.void(),delivery:"command"}),LU=l.strictObject({}),BU=l.array(Cg),Bce=_e({channel:"site-builder:routes:list",request:LU,response:BU,delivery:"request"}),jU=l.strictObject({}),ZU=l.array(Cg),jce=_e({channel:"plugin:site-builder:pages",request:jU,response:ZU,delivery:"collect"}),Pg=l.object({label:l.string(),href:l.string(),priority:l.number()})});var UU,qU,MU,Zce;var FU=w(()=>{Vt();he();UU=l.object({pluginId:l.string(),slotName:l.string(),render:l.custom((e)=>typeof e==="function"),priority:l.number().optional()}),qU=l.strictObject({}),MU=l.array(UU),Zce=_e({channel:"plugin:site-builder:slots",request:qU,response:MU,delivery:"collect"})});var JU="site:metadata:updated",zg,KU,HU,qc,VU,Uce,qce,Mce;var RA=w(()=>{Vt();he();$A();zg=l.object({heading:l.string().describe("Main CTA heading text"),buttonText:l.string().describe("Call-to-action button text"),buttonLink:l.string().describe("URL or anchor for the CTA button")}),KU=l.object({title:l.string().optional(),description:l.string().optional(),copyright:l.string().optional(),cta:zg.optional()}),HU=l.object({blurb:l.string().optional().describe("Short italic subtitle under the section title")}),qc=l.object({represents:l.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:l.string().describe("The site's title"),description:l.string().describe("The site's description"),url:l.string().optional().describe("Canonical site URL"),copyright:l.string().optional().describe("Copyright notice text"),logo:l.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:l.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:l.string().optional().describe("Analytics script HTML"),cta:zg.optional().describe("Call-to-action configuration"),sections:l.record(l.string(),HU).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:l.record(Ao,KU).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),VU=l.strictObject({}),Uce=_e({channel:"site:metadata:get",request:VU,response:qc,delivery:"request"}),qce=xi(JU,qc),Mce=qc.extend({copyright:l.string(),navigation:l.object({primary:l.array(Pg),secondary:l.array(Pg)}),socialLinks:l.array(JI).optional().describe("Social media links from profile metadata"),photo:l.string().optional().describe("The anchor's photo, as ")})});var ZRe;var OA=w(()=>{he();ZRe=l.record(l.string(),l.unknown())});var Bd=w(()=>{OA()});var WU=w(()=>{Vt();Bd()});var GU=w(()=>{Bd();Vt()});var QU=w(()=>{Bd();Vt()});var rOe;var YU=w(()=>{he();rOe=l.record(l.string(),l.unknown())});var iOe;var XU=w(()=>{he();Sc();iOe=l.record(l.string(),l.unknown())});var e6=w(()=>{Sc()});var t6=w(()=>{Bd();WU();GU();QU();YU();XU();e6();OA()});var Xce;var r6=w(()=>{he();Xce=l.object({slug:l.string(),title:l.string(),type:l.string(),entityId:l.string(),contentHash:l.string()})});var PA=w(()=>{t6();r6()});var n6=w(()=>{PA();he()});var ele,tle,rle;var Dg=w(()=>{he();Vt();ele={url:l.string(),typeLabel:l.string(),listUrl:l.string(),listLabel:l.string()},tle={url:l.string().nullable().default(null),typeLabel:l.string().nullable().default(null),listUrl:l.string().nullable().default(null),listLabel:l.string().nullable().default(null)},rle=l.object({name:l.string(),description:l.string(),schema:l.unknown(),basePrompt:l.string().optional(),useKnowledgeContext:l.boolean().optional(),requiredPermission:l.enum(["admin","trusted","public"]),formatter:l.unknown().optional(),overlayFormatter:l.unknown().optional(),layout:l.object({component:l.unknown().optional(),fullscreen:l.boolean().optional(),formats:l.unknown().optional()}).optional(),dataSourceId:l.string().optional()})});var Lg=w(()=>{Dg()});var s6=w(()=>{Lg()});var zA=()=>{};var ole,ile,Mc,a6,sle;var c6=w(()=>{Vt();he();zA();ole=l.enum(["admin","trusted","public"]),ile=l.enum(["create","update","delete","extract","publish"]),Mc=l.enum(["never","admin","trusted","public"]),a6=l.strictObject({create:Mc.optional(),update:Mc.optional(),delete:Mc.optional(),extract:Mc.optional(),publish:Mc.optional()}),sle=l.record(l.string(),a6)});var l6=w(()=>{Lg();Dg()});var ale,cle,Bg,lle,ule,dle;var u6=w(()=>{he();ale=l.enum(["site-content-preview","site-content-production"]),cle=l.enum(["web","image","pdf","epub"]),Bg=l.custom((e)=>typeof e==="function"),lle=l.object({name:l.string(),schema:l.unknown(),description:l.string().optional(),pluginId:l.string(),renderers:l.object({web:l.union([Bg,l.string()]).optional(),image:l.union([Bg,l.string()]).optional(),pdf:l.union([Bg,l.string()]).optional(),epub:l.union([Bg,l.string()]).optional()})}),ule=l.object({enableContentGeneration:l.boolean().default(!1),outputDir:l.string(),workingDir:l.string().optional(),environment:l.enum(["preview","production"]).default("preview"),siteConfig:l.object({title:l.string(),description:l.string(),url:l.string().optional()}).optional()}),dle=l.object({success:l.boolean(),routesBuilt:l.number(),errors:l.array(l.string()).optional(),warnings:l.array(l.string()).optional()})});var d6=w(()=>{Dg();s6();Lg();c6();zA();l6();u6()});var NA=ge(function(ple,jg){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Nt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Nt,this.updater=D||bt}function s(){}function a(g){return""+g}function c(g){try{a(g);var E=!1}catch(q){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===In?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case ve:return"Suspense";case ke:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case pe:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case Ie:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case we:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===we)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function f(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(to.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){Yi||(Yi=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return Xi[g]||(Xi[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,q,te){var se=D.ref;return g={$$typeof:M,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:q}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===we&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===M}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(c(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,q){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case M:case N:se=!0;break;case we:return se=g._init,K(se(g._payload),E,D,J,q)}}if(se){se=g,q=q(se);var ye=J===""?"."+L(se,0):J;return $r(q)?(D="",ye!=null&&(D=ye.replace(fa,"$&/")+"/"),K(q,E,D,"",function($e){return $e})):q!=null&&(A(q)&&(q.key!=null&&(se&&se.key===q.key||c(q.key)),D=x(q,D+(q.key==null||se&&se.key===q.key?"":(""+q.key).replace(fa,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),q=D),E.push(q)),1}if(se=0,ye=J===""?".":J+":",$r(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,q);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Mo||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Mo=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,q);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,q);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],q=0;return K(g,J,"","",function(te){return E.call(D,te,q++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(q){if(g._status===0||g._status===-1){g._status=1,g._result=q;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=q)}},function(q){if(g._status===0||g._status===-1){g._status=2,g._result=q;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=q)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
362
362
|
|
|
363
363
|
Your code should look like:
|
|
364
364
|
const MyComponent = lazy(() => import('./MyComponent'))
|
|
@@ -371,7 +371,7 @@ Your code should look like:
|
|
|
371
371
|
2. You might be breaking the Rules of Hooks
|
|
372
372
|
3. You might have more than one copy of React in the same app
|
|
373
373
|
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),g}function j(){Le.asyncTransitions--}function R(g){if(U===null)try{var E=("require"+Math.random()).slice(0,7);U=(jg&&jg[E]).call(jg,"timers").setImmediate}catch(D){U=function(J){p===!1&&(p=!0,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var q=new MessageChannel;q.port1.onmessage=J,q.port2.postMessage(void 0)}}return U(g)}function B(g){return 1<g.length&&typeof AggregateError==="function"?AggregateError(g):g[0]}function I(g,E){E!==ne-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),ne=E}function T(g,E,D){var J=Le.actQueue;if(J!==null)if(J.length!==0)try{k(J),R(function(){return T(g,E,D)});return}catch(q){Le.thrownErrors.push(q)}else Le.actQueue=null;0<Le.thrownErrors.length?(J=B(Le.thrownErrors),Le.thrownErrors.length=0,D(J)):E(g)}function k(g){if(!X){X=!0;var E=0;try{for(;E<g.length;E++){var D=g[E];do{Le.didUsePromise=!1;var J=D(!1);if(J!==null){if(Le.didUsePromise){g[E]=D,g.splice(0,E);return}D=J}else break}while(1)}g.length=0}catch(q){g.splice(0,E+1),Le.thrownErrors.push(q)}finally{X=!1}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var M=Symbol.for("react.transitional.element"),N=Symbol.for("react.portal"),H=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ae=Symbol.for("react.consumer"),pe=Symbol.for("react.context"),be=Symbol.for("react.forward_ref"),ve=Symbol.for("react.suspense"),ke=Symbol.for("react.suspense_list"),Ie=Symbol.for("react.memo"),we=Symbol.for("react.lazy"),Ue=Symbol.for("react.activity"),De=Symbol.iterator,Qe={},bt={isMounted:function(){return!1},enqueueForceUpdate:function(g){r(g,"forceUpdate")},enqueueReplaceState:function(g){r(g,"replaceState")},enqueueSetState:function(g){r(g,"setState")}},Tt=Object.assign,Nt={};Object.freeze(Nt),o.prototype.isReactComponent={},o.prototype.setState=function(g,E){if(typeof g!=="object"&&typeof g!=="function"&&g!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,g,E,"setState")},o.prototype.forceUpdate=function(g){this.updater.enqueueForceUpdate(this,g,"forceUpdate")};var lt={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(V in lt)lt.hasOwnProperty(V)&&e(V,lt[V]);n.prototype=o.prototype,lt=i.prototype=new n,lt.constructor=i,Tt(lt,o.prototype),lt.isPureReactComponent=!0;var $r=Array.isArray,In=Symbol.for("react.client.reference"),Le={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},to=Object.prototype.hasOwnProperty,Qi=console.createTask?console.createTask:function(){return null};lt={react_stack_bottom_frame:function(g){return g()}};var Yi,da,Xi={},kn=lt.react_stack_bottom_frame.bind(lt,m)(),Al=Qi(d(m)),Mo=!1,fa=/\/+/g,pa=typeof reportError==="function"?reportError:function(g){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof g==="object"&&g!==null&&typeof g.message==="string"?String(g.message):String(g),error:g});if(!window.dispatchEvent(E))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",g);return}console.error(g)},p=!1,U=null,ne=0,ie=!1,X=!1,v=typeof queueMicrotask==="function"?function(g){queueMicrotask(function(){return queueMicrotask(g)})}:R;lt=Object.freeze({__proto__:null,c:function(g){return ee().useMemoCache(g)}});var V={map:P,forEach:function(g,E,D){P(g,function(){E.apply(this,arguments)},D)},count:function(g){var E=0;return P(g,function(){E++}),E},toArray:function(g){return P(g,function(E){return E})||[]},only:function(g){if(!A(g))throw Error("React.Children.only expected to receive a single React element child.");return g}};ple.Activity=Ue,ple.Children=V,ple.Component=o,ple.Fragment=H,ple.Profiler=re,ple.PureComponent=i,ple.StrictMode=G,ple.Suspense=ve,ple.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Le,ple.__COMPILER_RUNTIME=lt,ple.act=function(g){var E=Le.actQueue,D=ne;ne++;var J=Le.actQueue=E!==null?E:[],q=!1;try{var te=g()}catch(fe){Le.thrownErrors.push(fe)}if(0<Le.thrownErrors.length)throw I(E,D),g=B(Le.thrownErrors),Le.thrownErrors.length=0,g;if(te!==null&&typeof te==="object"&&typeof te.then==="function"){var se=te;return v(function(){q||ie||(ie=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),{then:function(fe,$e){q=!0,se.then(function(ze){if(I(E,D),D===0){try{k(J),R(function(){return T(ze,fe,$e)})}catch(es){Le.thrownErrors.push(es)}if(0<Le.thrownErrors.length){var An=B(Le.thrownErrors);Le.thrownErrors.length=0,$e(An)}}else fe(ze)},function(ze){I(E,D),0<Le.thrownErrors.length?(ze=B(Le.thrownErrors),Le.thrownErrors.length=0,$e(ze)):$e(ze)})}}}var ye=te;if(I(E,D),D===0&&(k(J),J.length!==0&&v(function(){q||ie||(ie=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))}),Le.actQueue=null),0<Le.thrownErrors.length)throw g=B(Le.thrownErrors),Le.thrownErrors.length=0,g;return{then:function(fe,$e){q=!0,D===0?(Le.actQueue=J,R(function(){return T(ye,fe,$e)})):fe(ye)}}},ple.cache=function(g){return function(){return g.apply(null,arguments)}},ple.cacheSignal=function(){return null},ple.captureOwnerStack=function(){var g=Le.getCurrentStack;return g===null?null:g()},ple.cloneElement=function(g,E,D){if(g===null||g===void 0)throw Error("The argument must be a React element, but you passed "+g+".");var J=Tt({},g.props),q=g.key,te=g._owner;if(E!=null){var se;e:{if(to.call(E,"ref")&&(se=Object.getOwnPropertyDescriptor(E,"ref").get)&&se.isReactWarning){se=!1;break e}se=E.ref!==void 0}se&&(te=f()),h(E)&&(c(E.key),q=""+E.key);for(ye in E)!to.call(E,ye)||ye==="key"||ye==="__self"||ye==="__source"||ye==="ref"&&E.ref===void 0||(J[ye]=E[ye])}var ye=arguments.length-2;if(ye===1)J.children=D;else if(1<ye){se=Array(ye);for(var fe=0;fe<ye;fe++)se[fe]=arguments[fe+2];J.children=se}J=S(g.type,q,J,te,g._debugStack,g._debugTask);for(q=2;q<arguments.length;q++)_(arguments[q]);return J},ple.createContext=function(g){return g={$$typeof:pe,_currentValue:g,_currentValue2:g,_threadCount:0,Provider:null,Consumer:null},g.Provider=g,g.Consumer={$$typeof:ae,_context:g},g._currentRenderer=null,g._currentRenderer2=null,g},ple.createElement=function(g,E,D){for(var J=2;J<arguments.length;J++)_(arguments[J]);J={};var q=null;if(E!=null)for(fe in da||!("__self"in E)||"key"in E||(da=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),h(E)&&(c(E.key),q=""+E.key),E)to.call(E,fe)&&fe!=="key"&&fe!=="__self"&&fe!=="__source"&&(J[fe]=E[fe]);var te=arguments.length-2;if(te===1)J.children=D;else if(1<te){for(var se=Array(te),ye=0;ye<te;ye++)se[ye]=arguments[ye+2];Object.freeze&&Object.freeze(se),J.children=se}if(g&&g.defaultProps)for(fe in te=g.defaultProps,te)J[fe]===void 0&&(J[fe]=te[fe]);q&&b(J,typeof g==="function"?g.displayName||g.name||"Unknown":g);var fe=1e4>Le.recentlyCreatedOwnerStacks++;return S(g,q,J,f(),fe?Error("react-stack-top-frame"):kn,fe?Qi(d(g)):Al)},ple.createRef=function(){var g={current:null};return Object.seal(g),g},ple.forwardRef=function(g){g!=null&&g.$$typeof===Ie?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof g!=="function"?console.error("forwardRef requires a render function but was given %s.",g===null?"null":typeof g):g.length!==0&&g.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",g.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),g!=null&&g.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var E={$$typeof:be,render:g},D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},ple.isValidElement=A,ple.lazy=function(g){g={_status:-1,_result:g};var E={$$typeof:we,_payload:g,_init:W},D={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return g._ioInfo=D,E._debugInfo=[{awaited:D}],E},ple.memo=function(g,E){g==null&&console.error("memo: The first argument must be a component. Instead received: %s",g===null?"null":typeof g),E={$$typeof:Ie,type:g,compare:E===void 0?null:E};var D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},ple.startTransition=function(g){var E=Le.T,D={};D._updatedFibers=new Set,Le.T=D;try{var J=g(),q=Le.S;q!==null&&q(D,J),typeof J==="object"&&J!==null&&typeof J.then==="function"&&(Le.asyncTransitions++,J.then(j,j),J.then(s,pa))}catch(te){pa(te)}finally{E===null&&D._updatedFibers&&(g=D._updatedFibers.size,D._updatedFibers.clear(),10<g&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),E!==null&&D.types!==null&&(E.types!==null&&E.types!==D.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),E.types=D.types),Le.T=E}},ple.unstable_useCacheRefresh=function(){return ee().useCacheRefresh()},ple.use=function(g){return ee().use(g)},ple.useActionState=function(g,E,D){return ee().useActionState(g,E,D)},ple.useCallback=function(g,E){return ee().useCallback(g,E)},ple.useContext=function(g){var E=ee();return g.$$typeof===ae&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),E.useContext(g)},ple.useDebugValue=function(g,E){return ee().useDebugValue(g,E)},ple.useDeferredValue=function(g,E){return ee().useDeferredValue(g,E)},ple.useEffect=function(g,E){return g==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useEffect(g,E)},ple.useEffectEvent=function(g){return ee().useEffectEvent(g)},ple.useId=function(){return ee().useId()},ple.useImperativeHandle=function(g,E,D){return ee().useImperativeHandle(g,E,D)},ple.useInsertionEffect=function(g,E){return g==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useInsertionEffect(g,E)},ple.useLayoutEffect=function(g,E){return g==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useLayoutEffect(g,E)},ple.useMemo=function(g,E){return ee().useMemo(g,E)},ple.useOptimistic=function(g,E){return ee().useOptimistic(g,E)},ple.useReducer=function(g,E,D){return ee().useReducer(g,E,D)},ple.useRef=function(g){return ee().useRef(g)},ple.useState=function(g){return ee().useState(g)},ple.useSyncExternalStore=function(g,E,D){return ee().useSyncExternalStore(g,E,D)},ple.useTransition=function(){return ee().useTransition()},ple.version="19.2.7",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()});var f6,p6;var DA=w(()=>{f6=$l(NA(),1),p6=f6.createContext(void 0)});var mle;var m6=w(()=>{PA();d6();DA();he();mle=$l(NA(),1)});var hle,gle;var h6=w(()=>{Vt();he();RA();hle=qc.omit({url:!0,analyticsScript:!0}),gle=hle.extend({title:l.string().optional().describe("Optional site title override"),description:l.string().optional().describe("Optional site description override")})});function LA(e,t={}){let r=g6(e),o=g6(t.sharedDomain??"rizom.ai").replace(/^\./,""),n=`.${o}`;if(r.endsWith(n)){let i=r.slice(0,-n.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${o}`}return`preview.${r}`}function g6(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}var y6=w(()=>{Bh()});var yle,ble;var b6=w(()=>{he();Og();yle=l.string(),ble=l.custom((e)=>{if(!Ls(e))return!1;let{plugin:t,...r}=e;if(t!==void 0&&typeof t!=="function")return!1;return CU.safeParse(r).success})});var Sle;var S6=w(()=>{Bh();he();Sle=l.object({title:l.string().min(1),slug:l.string().min(1),description:l.string(),content:l.string(),author:l.string(),publishedAt:l.iso.datetime({offset:!0}),category:l.string().min(1).optional()})});var v6=w(()=>{$A();FU();RA();n6();m6();h6();y6();b6();DA();S6()});function w6(e,t={}){return LA(e,t)}var x6=w(()=>{v6()});var T6={};Zt(T6,{assertPilotUsersRemoved:()=>A6,createPilotOffboardDriver:()=>E6,offboardPilotUsers:()=>Ile});import{access as vle,readdir as wle,readFile as xle,rm as jd,writeFile as _le}from"fs/promises";import{basename as Ele,join as To}from"path";async function Ile(e,t){let r=[...new Set(t.handles.map((f)=>yr.parse(f)))].sort((f,m)=>f.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await wt(e),c=r.map((f)=>kle(a,f,i)),u=t.driver??E6({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(c.map(async(f)=>({target:f,inspection:await u.inspect(f)})));if(Tle(d),$le(d,o,s),!o){for(let f of d)if(!f.inspection.contentRepoArchived)await u.archiveContentRepo(f.target),s(`[${f.target.handle}] archived ${f.target.contentRepo}`);for(let f of d)for(let m of f.inspection.dnsRecords)await u.deleteDnsRecord(f.target,m),s(`[${f.target.handle}] deleted DNS ${m.name}`);for(let f of d)if(f.inspection.server)await u.deleteServer(f.target,f.inspection.server),s(`[${f.target.handle}] deleted ${f.target.instanceName}`);await Ale(c,u,t.sleep??((f)=>new Promise((m)=>setTimeout(m,f)))),await Rle(e,r),await _i(e),await A6(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function kle(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=w6(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??Zg(r,"CF_ZONE_ID"),c=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=c.includes("/")?c:`${e.pilot.githubOrg}/${c}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function Ale(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function Tle(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function $le(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((c)=>`${c.type} ${c.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function Rle(e,t){let r=new Set(t),o=To(e,"cohorts");for(let n of(await wle(o)).filter((i)=>i.endsWith(".yaml"))){let i=To(o,n),s=await xle(i,"utf8"),a=Jn(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let c=a.get("members",!0);if(!IA(c))throw Error(`${n}: members must be a sequence`);let u=c.items.filter((d)=>!jc(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===c.items.length)continue;if(u.length===0){await jd(i);continue}c.items=u,dn.parse(a.toJS()),await _le(i,a.toString())}for(let n of t)await Promise.all([jd(To(e,"users",`${n}.yaml`),{force:!0}),jd(To(e,"users",`${n}.secrets.yaml`),{force:!0}),jd(To(e,"users",`${n}.secrets.yaml.age`),{force:!0}),jd(To(e,"users",n),{recursive:!0,force:!0})])}function E6(e){let t=e.fetchImpl??fetch,r=Zg(e.env,"HCLOUD_TOKEN"),o=Zg(e.env,"CF_API_TOKEN"),n=Zg(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,c]=await Promise.all([Ole(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>Cle(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),Ple(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:c.archived}},async archiveContentRepo(i){await Fc(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:I6(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(Jc(await Fc(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:k6(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await Fc(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function Ole(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=Jc(await Fc(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=Jc(s),c=_6(a.public_net),u=_6(c?.ipv4);return{id:zle(a.id,"Hetzner server id"),name:Zd(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function Cle(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=Jc(await Fc(e,n.toString(),{headers:k6(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let c=Jc(a),u=Zd(c.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:Zd(c.id,"Cloudflare record id"),name:Zd(c.name,"Cloudflare record name"),type:u,content:Zd(c.content,"Cloudflare record content")}})}async function Ple(e,t,r){let o=Jc(await Fc(e,`https://api.github.com/repos/${r}`,{headers:I6(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function Fc(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function I6(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function k6(e){return{Authorization:`Bearer ${e}`}}function Zg(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function Jc(e){if(!Ls(e))throw Error("Provider returned an unexpected payload");return e}function _6(e){return Ls(e)?e:void 0}function Zd(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function zle(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Nle(e){try{return await vle(e),!0}catch{return!1}}async function A6(e,t){for(let r of t)for(let o of[To(e,"users",`${r}.yaml`),To(e,"users",`${r}.secrets.yaml.age`),To(e,"users",r)])if(await Nle(o))throw Error(`Offboarded user state remains: ${Ele(o)}`)}var $6=w(()=>{Nd();fn();x6();ad();wo()});var R6="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as O6}from"crypto";function Lle(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Pi||Pi.length<e)Pi=Buffer.allocUnsafe(e*Dle),O6.getRandomValues(Pi),Kc=0;else if(Kc+e>Pi.length)O6.getRandomValues(Pi),Kc=0}catch(t){throw Pi=void 0,t}Kc+=e}function C6(e=21){Lle(e|=0);let t="";for(let r=Kc-e;r<Kc;r++)t+=R6[Pi[r]&63];return t}var Dle=128,Pi,Kc;var P6=()=>{};function $o(e=12){return C6(e)}var Ud=w(()=>{P6()});import{openSync as Ble,writeSync as jle}from"fs";class kr{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??Ws.INFO,this.context=e.context??void 0,this.useStderr=e.useStderr??!1,this.format=e.format??"text",this.logFile=e.logFile,t!==void 0)this.fileHandle=t;else if(this.logFile)try{this.fileHandle=Ble(this.logFile,"a")}catch{}}static getInstance(e){if(!kr.instance)kr.instance=new kr(e);else{if(e?.useStderr!==void 0)kr.instance.useStderr=e.useStderr;if(e?.level!==void 0)kr.instance.level=e.level}return kr.instance}static resetInstance(){kr.instance=null}static createFresh(e){return new kr(e)}formatEntry(e,t,r){let o=new Date().toISOString();if(this.format==="json"){let n={ts:o,level:e,msg:t};if(this.context)n.ctx=this.context;if(r.length>0)n.data=r;return JSON.stringify(n)}return this.context?`[${o}] [${this.context}] ${t}`:`[${o}] ${t}`}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{jle(this.fileHandle,n+`
|
|
374
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}silly(e,...t){if(this.level<=Ws.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=Ws.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=Ws.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=Ws.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=Ws.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=Ws.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new kr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var Ws,gPe;var BA=w(()=>{Ws={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};gPe=kr.getInstance()});var jA,Zle,Hc,vPe;var qd=w(()=>{Vt();he();jA=l.enum(["file_operations","content_operations","data_processing","batch_processing"]),Zle=l.looseObject({pluginId:l.string().optional(),progressToken:l.union([l.string(),l.number()]).optional(),operationType:jA,operationTarget:l.string().optional(),interfaceType:l.string().optional(),conversationId:l.string().optional(),channelId:l.string().optional(),requestedByActor:vi.optional(),requestedByUserId:l.string().optional(),requestedByInterface:l.string().optional(),silent:l.boolean().optional(),provenance:wi.optional()}),Hc=l.looseObject({pluginId:l.string().optional(),progressToken:l.union([l.string(),l.number()]).optional(),operationType:jA,operationTarget:l.string().optional(),interfaceType:l.string().optional(),conversationId:l.string().optional(),channelId:l.string().optional(),requestedByActor:vi.optional(),requestedByUserId:l.string().optional(),requestedByInterface:l.string().optional(),silent:l.boolean().optional(),provenance:wi.optional(),rootJobId:l.string()}),vPe=l.enum(["none","skip","replace","coalesce"])});var Ule,zi=15000;var Md=w(()=>{qd();he();Ule=l.object({id:l.string(),type:l.string(),data:l.string(),status:l.enum(["pending","processing","completed","failed"]),source:l.string().nullable(),priority:l.number(),retryCount:l.number(),maxRetries:l.number(),lastError:l.string().nullable(),lastErrorPublic:l.unknown(),createdAt:l.number(),scheduledFor:l.number(),startedAt:l.number().nullable(),completedAt:l.number().nullable(),attemptId:l.string().nullable(),workerSlotId:l.string().nullable(),workerSessionId:l.string().nullable(),leaseExpiresAt:l.number().nullable(),attemptHeartbeatAt:l.number().nullable(),runtimeUpdatedAt:l.number().nullable(),metadata:Hc,progress:l.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:l.unknown().nullable().optional()})});var ZA,z6,Oe,qle,Mle,N6,D6,L6;var Ro=w(()=>{Vt();he();qd();ZA=l.enum(["pending","processing","completed","failed"]),z6=l.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},qle=l.object({id:l.string(),type:l.string(),status:ZA,data:l.unknown(),result:l.unknown().optional(),lastError:l.string().optional().nullable(),attempts:l.number(),maxRetries:l.number(),priority:l.number(),createdAt:l.date(),updatedAt:l.date(),processedAt:l.date().optional().nullable(),completedAt:l.date().optional().nullable(),failedAt:l.date().optional().nullable()}),Mle=l.object({jobId:l.string(),type:l.string(),status:z6,result:l.unknown().optional(),error:l.string().optional()}),N6=l.object({success:l.literal(!1),error:l.string().optional()}),D6=l.object({id:l.string(),type:l.enum(["job","batch"]),status:ZA,message:l.string().optional(),progress:l.object({current:l.number(),total:l.number(),percentage:l.number()}).optional(),aggregationKey:l.string().optional(),batchDetails:l.object({totalOperations:l.number(),completedOperations:l.number(),failedOperations:l.number(),currentOperation:l.string().optional(),errors:l.array(l.string()).optional()}).optional(),jobDetails:l.object({jobType:l.string(),priority:l.number(),retryCount:l.number()}).optional(),metadata:Hc}),L6=xi(qI.progress,D6)});var Ce,Wt;var gn=w(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function B6(e){let t=Fle.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Jle(r.authority):void 0,i=Gs(r.path),s=r.query!==void 0?Hle(r.query):void 0,a=r.fragment!==void 0?Gs(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Jle(e){let t=Kle.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=Gs(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:Gs(r.username),password:r.password!==void 0?Gs(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function Hle(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:Gs(n.replaceAll("+"," ")),value:Gs(i.replaceAll("+"," "))})}return{pairs:r}}function Gs(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function Fd(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=Vle(t.host),i=Wle(t.port),a=`//${Gle(t.userinfo)}${n}${i}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${o}${a}${c}`)}function Vle(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function Wle(e){return e!==void 0?`:${e}`:""}function Gle(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Fle,Kle;var Ug=w(()=>{gn();Fle=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Kle=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Wc,j6,Z6,Jd,qg,Qle,Gt,U6,F6=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),J6=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),K6=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Jd[t>>18&63]+Jd[t>>12&63]+Jd[t>>6&63]+Jd[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},MA,UA,Mg=(e,t=!1)=>t?F6(UA(e)):UA(e),Yle=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},Xle,H6=(e)=>e.replace(Xle,Yle),q6,Vc=(e,t=!1)=>t?F6(q6(e)):q6(e),M6=(e)=>Vc(e,!0),eue,tue=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},V6=(e)=>e.replace(eue,tue),W6=(e)=>{if(e=e.replace(/\s+/g,""),!Qle.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=qg[e.charAt(i++)]<<18|qg[e.charAt(i++)]<<12|(r=qg[e.charAt(i++)])<<6|(o=qg[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},FA,G6,Q6=(e)=>G6(Y6(e)),rue,Y6=(e)=>J6(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),qA=(e)=>rue(Y6(e)),nue=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},X6=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),e4=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,X6(r));e("fromBase64",function(){return qA(this)}),e("toBase64",function(t){return Vc(this,t)}),e("toBase64URI",function(){return Vc(this,!0)}),e("toBase64URL",function(){return Vc(this,!0)}),e("toUint8Array",function(){return Q6(this)})},t4=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,X6(r));e("toBase64",function(t){return Mg(this,t)}),e("toBase64URI",function(){return Mg(this,!0)}),e("toBase64URL",function(){return Mg(this,!0)})},oue=()=>{e4(),t4()},Gc;var Fg=w(()=>{Wc=typeof Buffer==="function",j6=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,Z6=typeof TextEncoder==="function"?new TextEncoder:void 0,Jd=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),qg=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Jd),Qle=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),U6=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),MA=typeof btoa==="function"?(e)=>btoa(e):Wc?(e)=>Buffer.from(e,"binary").toString("base64"):K6,UA=Wc?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return MA(r.join(""))},Xle=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,q6=Wc?(e)=>Buffer.from(e,"utf8").toString("base64"):Z6?(e)=>UA(Z6.encode(e)):(e)=>MA(H6(e)),eue=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,FA=typeof atob==="function"?(e)=>atob(J6(e)):Wc?(e)=>Buffer.from(e,"base64").toString("binary"):W6,G6=Wc?(e)=>U6(Buffer.from(e,"base64")):(e)=>U6(FA(e).split("").map((t)=>t.charCodeAt(0))),rue=Wc?(e)=>Buffer.from(e,"base64").toString("utf8"):j6?(e)=>j6.decode(G6(e)):(e)=>V6(FA(e)),Gc={version:"3.8.0",VERSION:"3.8.0",atob:FA,atobPolyfill:W6,btoa:MA,btoaPolyfill:K6,fromBase64:qA,toBase64:Vc,encode:Vc,encodeURI:M6,encodeURL:M6,utob:H6,btou:V6,decode:qA,isValid:nue,fromUint8Array:Mg,toUint8Array:Q6,extendString:e4,extendUint8Array:t4,extendBuiltins:oue}});function Ni(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class Qc{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(iue),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function iue(e){return Array.prototype.map.call(e,sue)}function sue(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Gc.fromUint8Array(new Uint8Array(e));else return e}var Hn="https://github.com/libsql/libsql-client-ts#supported-urls";var Yc=w(()=>{Fg()});function n4(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function Kd(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===r4)r="file::memory:";let c=B6(r),u=c.scheme.toLowerCase(),d=u==="file"&&c.path===r4&&c.authority===void 0,f;if(d)f={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else f={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of c.query?.pairs??[]){if(!Object.hasOwn(f,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=f[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=c.path+m,b;if(u==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(c.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:c.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var r4=":memory:";var Hd=w(()=>{gn();Ug();Yc()});var i4=ge(function(Gr){var aue=Gr&&Gr.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),cue=Gr&&Gr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o4=Gr&&Gr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))aue(t,e,r)}return cue(t,e),t};Object.defineProperty(Gr,"__esModule",{value:!0});Gr.load=Gr.currentTarget=void 0;var lue=o4(Zr("path")),uue=o4(Zr("fs"));function due(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return fue()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}Gr.currentTarget=due;function fue(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function pue(e){let t=lue.join(e,"index.node");return uue.existsSync(t)?Zr(t):null}Gr.load=pue});var c4=ge(function(UPe,a4){var s4=()=>process.platform==="linux",JA=null,mue=()=>{if(!JA)JA=s4()&&process.report?process.report.getReport():{};return JA};a4.exports={isLinux:s4,getReport:mue}});var d4=ge(function(qPe,u4){var l4=Zr("fs"),hue=(e)=>l4.readFileSync(e,"utf-8"),gue=(e)=>new Promise((t,r)=>{l4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});u4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:hue,readFile:gue}});var T4=ge(function(MPe,A4){var p4=Zr("child_process"),{isLinux:Xc,getReport:m4}=c4(),{LDD_PATH:Jg,readFile:h4,readFileSync:g4}=d4(),Vn,Wn,Di="",y4=()=>{if(!Di)return new Promise((e)=>{p4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Di=t?" ":r,e(Di)})});return Di},b4=()=>{if(!Di)try{Di=p4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Di=" "}return Di},Oo="glibc",S4=/GLIBC\s(\d+\.\d+)/,Qs="musl",yue=Oo.toUpperCase(),bue=Qs.toLowerCase(),Sue=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),v4=()=>{let e=m4();if(e.header&&e.header.glibcVersionRuntime)return Oo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Sue))return Qs}return null},w4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Oo))return Oo;if(r&&r.includes(Qs))return Qs;return null},x4=(e)=>{if(e.includes(bue))return Qs;if(e.includes(yue))return Oo;return null},vue=async()=>{if(Vn!==void 0)return Vn;Vn=null;try{let e=await h4(Jg);Vn=x4(e)}catch(e){}return Vn},wue=()=>{if(Vn!==void 0)return Vn;Vn=null;try{let e=g4(Jg);Vn=x4(e)}catch(e){}return Vn},_4=async()=>{let e=null;if(Xc()){if(e=await vue(),!e)e=v4();if(!e){let t=await y4();e=w4(t)}}return e},E4=()=>{let e=null;if(Xc()){if(e=wue(),!e)e=v4();if(!e){let t=b4();e=w4(t)}}return e},xue=async()=>Xc()&&await _4()!==Oo,_ue=()=>Xc()&&E4()!==Oo,Eue=async()=>{if(Wn!==void 0)return Wn;Wn=null;try{let t=(await h4(Jg)).match(S4);if(t)Wn=t[1]}catch(e){}return Wn},Iue=()=>{if(Wn!==void 0)return Wn;Wn=null;try{let t=g4(Jg).match(S4);if(t)Wn=t[1]}catch(e){}return Wn},I4=()=>{let e=m4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},f4=(e)=>e.trim().split(/\s+/)[1],k4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Oo))return f4(t);if(r&&o&&r.includes(Qs))return f4(o);return null},kue=async()=>{let e=null;if(Xc()){if(e=await Eue(),!e)e=I4();if(!e){let t=await y4();e=k4(t)}}return e},Aue=()=>{let e=null;if(Xc()){if(e=Iue(),!e)e=I4();if(!e){let t=b4();e=k4(t)}}return e};A4.exports={GLIBC:Oo,MUSL:Qs,family:_4,familySync:E4,isNonGlibcLinux:xue,isNonGlibcLinuxSync:_ue,version:kue,versionSync:Aue}});var R4=ge(function(FPe,$4){var Tue={ALLOW:0,DENY:1};$4.exports=Tue});var C4=ge(function(JPe,O4){var KA={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ys(e,t,r){if(new.target!==Ys)return new Ys(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),KA.value=""+e,Object.defineProperty(this,"message",KA),Error.captureStackTrace(this,Ys),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ys,Error);Object.setPrototypeOf(Ys.prototype,Error.prototype);Object.defineProperty(Ys.prototype,"name",KA);O4.exports=Ys});var Z4=ge(function(KPe,Kg){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:$ue,currentTarget:Rue}=i4(),{familySync:P4,GLIBC:Oue,MUSL:Cue}=T4();function Pue(){if(process.env.LIBSQL_JS_DEV)return $ue(__dirname);let e=Rue();if(P4()==Oue)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&P4()==Cue)e="linux-arm-musleabihf";return Zr(`@libsql/${e}`)}var{databaseOpen:zue,databaseOpenWithSync:Nue,databaseInTransaction:Due,databaseInterrupt:Lue,databaseClose:Bue,databaseSyncSync:jue,databaseSyncUntilSync:Zue,databaseExecSync:Uue,databasePrepareSync:que,databaseDefaultSafeIntegers:Mue,databaseAuthorizer:Fue,databaseLoadExtension:Jue,databaseMaxWriteReplicationIndex:Kue,statementRaw:Hue,statementIsReader:Vue,statementGet:z4,statementRun:N4,statementInterrupt:Wue,statementRowsSync:D4,statementColumns:Gue,statementSafeIntegers:Que,rowsNext:Yue}=Pue(),Xue=R4(),L4=C4();function el(e){if(e.libsqlError)return new L4(e.message,e.code,e.rawCode);return e}class B4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Nue(e,t.syncUrl,o,r,i,s,a,c,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=zue(e,i,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Due(n)}}})}sync(){return jue.call(this.db)}syncUntil(e){return Zue.call(this.db,e)}prepare(e){try{let t=que.call(this.db,e);return new j4(t)}catch(t){throw el(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){Fue.call(this.db,e)}loadExtension(...e){Jue.call(this.db,...e)}maxWriteReplicationIndex(){return Kue.call(this.db)}exec(e){try{Uue.call(this.db,e)}catch(t){throw el(t)}}interrupt(){Lue.call(this.db)}close(){Bue.call(this.db),this.open=!1}defaultSafeIntegers(e){return Mue.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class j4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return Hue.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return Vue.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return N4.call(this.stmt,e[0]);else return N4.call(this.stmt,e.flat())}catch(t){throw el(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return z4.call(this.stmt,e[0]);else return z4.call(this.stmt,e.flat())}catch(t){throw el(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=D4.call(this.stmt,e[0]);else t=D4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)Yue.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw el(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw el(t)}}interrupt(){Wue.call(this.stmt)}columns(){return Gue.call(this.stmt)}safeIntegers(e){return Que.call(this.stmt,e??!0),this}}Kg.exports=B4;Kg.exports.Authorization=Xue;Kg.exports.SqliteError=L4});import{Buffer as q4}from"buffer";function M4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Hn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=n4(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new Vd.default(o,n);return Pt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new F4(o,n,i,e.intMode)}class F4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),Pt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{Pt(r,Ni(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(Pt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return Pt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)Pt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{Pt(t,"PRAGMA foreign_keys=off",this.#n),Pt(t,Ni("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(Pt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Pt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n);Pt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return Pt(t,Ni(e),this.#n),this.#r=null,new J4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return K4(t,e)}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new Vd.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new Vd.default(this.#e,this.#t);return this.#r}}class J4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),Pt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(Pt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),K4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Pt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Pt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Pt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function Pt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>U4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=U4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),c=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>ede(m,a,r)),d=0,f=void 0;return new Qc(a,c,u,0,void 0)}else{let a=i.run(n),c=a.changes,u=BigInt(a.lastInsertRowid);return new Qc([],[],[],c,u)}}catch(i){throw H4(i)}}function ede(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=tde(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function tde(e,t){if(typeof e==="bigint")if(t==="number"){if(e<rde||e>nde)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof q4)return e.buffer;return e}function U4(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<ode||e>ide)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return q4.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function K4(e,t){try{e.exec(t)}catch(r){throw H4(r)}}function H4(e){if(e instanceof Vd.default.SqliteError){let t=e.code,r=sde(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function sde(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return ade[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Vd,rde,nde=9007199254740991n,ode,ide=9223372036854775807n,ade;var V4=w(()=>{gn();Hd();Yc();Vd=$l(Z4(),1);gn();rde=-9007199254740991n;ode=-9223372036854775808n;ade={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Li;var HA=w(()=>{if(typeof WebSocket<"u")Li=WebSocket;else if(typeof global<"u")Li=global.WebSocket;else if(typeof window<"u")Li=window.WebSocket;else if(typeof self<"u")Li=self.WebSocket});class tl{constructor(){this.intMode="number"}intMode}var We,Pe,Wd,xt,Gd,rl,Xs,yn,or,Gn;var _t=w(()=>{We=class We extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends We{constructor(e){super(e);this.name="ProtoError"}};Wd=class Wd extends We{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends We{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Gd=class Gd extends We{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};rl=class rl extends We{constructor(e){super(e);this.name="WebSocketError"}};Xs=class Xs extends We{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};yn=class yn extends We{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends We{constructor(e){super(e);this.name="InternalError"}};Gn=class Gn extends We{constructor(e){super(e);this.name="MisuseError"}}});function Ar(e){if(typeof e==="string")return e;throw nl(e,"string")}function Lr(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw nl(e,"string or null")}function Co(e){if(typeof e==="number")return e;throw nl(e,"number")}function Bi(e){if(typeof e==="boolean")return e;throw nl(e,"boolean")}function Qd(e){if(Array.isArray(e))return e;throw nl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw nl(e,"object")}function bn(e,t){return Qd(e).map((r)=>t(kt(r)))}function nl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function ea(e,t){return t(kt(e))}var ol=w(()=>{_t()});class W4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Yd(e,t){let r=[],o=new W4(r);return o.begin(),t(o,e),o.end(),r.join("")}var ta=0,Xd=1,ef=2,G4=5;class Q4{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class Y4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(ef);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return ji(this.bytes(),e)}int32(){return this.#r(ta),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(ta),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Xd),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===ta)this.#e.skipVarint();else if(this.#t===Xd)this.#e.skip(8);else if(this.#t===ef){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===G4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function ji(e,t){let r=new Q4(e),o=new Y4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let c=t[s];if(c!==void 0){let u=c(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var VA=w(()=>{_t()});class WA{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,ef),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new WA;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,ta),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,ta),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Xd),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function tf(e,t){let r=new WA;return t(r,e),r.data()}var X4=()=>{};var GA=w(()=>{ol();VA();X4()});class Zi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var QA=w(()=>{_t()});function Ke(e,t){throw new or(t)}var Qr=w(()=>{_t()});function il(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<lde||e>ude)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function YA(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new Gn("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var lde,ude=9223372036854775807n;var XA=w(()=>{_t();Qr();lde=-9223372036854775808n});function ra(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Vg(e,t){let r=ra(e),o=e.rows.map((n)=>eq(r.columnNames,n,t));return{...r,rows:o}}function Wg(e,t){let r=ra(e),o;if(e.rows.length>0)o=eq(r.columnNames,e.rows[0],t);return{...r,row:o}}function Gg(e,t){let r=ra(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=YA(e.rows[0][0],t);return{...r,value:o}}function eq(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=YA(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Po(e){return new Wd(e.message,e)}var rf=w(()=>{_t();XA()});class na{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new Gn("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new We("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function nf(e,t){if(t instanceof na)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var sl=w(()=>{_t()});class Ui{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class of{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(il(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=il(t),this}bindName(e,t){return this._namedArgs.set(e,il(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Qg(e,t,r){let o,n=[],i=[];if(t instanceof of){o=t.sql,n=t._args;for(let[c,u]of t._namedArgs.entries())i.push({name:c,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((c)=>il(c));else i=Object.entries(t[1]).map(([c,u])=>({name:c,value:il(u)}));else o=t;let{sql:s,sqlId:a}=nf(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Yg=w(()=>{sl();XA()});class Xg{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new eT(this)}execute(){if(this.#t)throw new Gn("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return fde(this._stream,this._steps,e);else return dde(this._stream,this._steps,e)}}function dde(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function fde(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let c={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(c,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Po(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class eT{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,Vg)}queryRow(e){return this.#t(e,!0,Wg)}queryValue(e){return this.#t(e,!0,Gg)}run(e){return this.#t(e,!1,ra)}#t(e,t,r){if(this._index!==void 0)throw new Gn("This BatchStep has already been added to the batch");let o=Qg(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let c=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Po(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:c})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:tq(e)})}static error(e){return new ut(e._batch,{type:"error",step:tq(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)rq(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)rq(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function tq(e){if(e._index===void 0)throw new Gn("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function rq(e,t){if(t._batch!==e)throw new Gn("Cannot mix BatchCond objects for different Batch objects")}var tT=w(()=>{_t();rf();Yg();Qr()});function nq(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class al{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Vg)}queryRow(e){return this.#e(e,!0,Wg)}queryValue(e){return this.#e(e,!0,Gg)}run(e){return this.#e(e,!1,ra)}#e(e,t,r){let o=Qg(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Xg(this,e)}describe(e){let t=nf(this._sqlOwner(),e);return this._describe(t).then(nq)}sequence(e){let t=nf(this._sqlOwner(),e);return this._sequence(t)}intMode}var ey=w(()=>{tT();rf();sl();Yg()});class sf{}var pde=1000,mde=10,rT;var oq=w(()=>{_t();rT=class rT extends sf{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Ui,this.#o=new Ui,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<mde)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:pde}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new We("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var af;var nT=w(()=>{_t();ey();oq();af=class af extends al{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new af(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Ui,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new We("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new rT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new We("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function cf(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,iq),e.arrayObjects("named_args",t.namedArgs,hde),e.boolean("want_rows",t.wantRows)}function hde(e,t){e.string("name",t.name),e.object("value",t.value,iq)}function cl(e,t){e.arrayObjects("steps",t.steps,gde)}function gde(e,t){if(t.condition!==void 0)e.object("condition",t.condition,oT);e.object("stmt",t.stmt,cf)}function oT(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,oT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,oT);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function iq(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",Gc.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var iT=w(()=>{Fg();Qr()});function sq(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,yde);else throw Ke(t,"Impossible type of ClientMsg")}function yde(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,cf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,cl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,cl);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var aq=w(()=>{iT();Qr()});function lf(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,lq);for(let r of t.namedArgs)e.message(4,r,bde);e.bool(5,t.wantRows)}function bde(e,t){e.string(1,t.name),e.message(2,t.value,lq)}function ll(e,t){for(let r of t.steps)e.message(1,r,Sde)}function Sde(e,t){if(t.condition!==void 0)e.message(1,t.condition,sT);e.message(2,t.stmt,lf)}function sT(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,sT);else if(t.type==="and")e.message(4,t.conds,cq);else if(t.type==="or")e.message(5,t.conds,cq);else if(t.type==="is_autocommit")e.message(6,void 0,uq);else throw Ke(t,"Impossible type of BatchCond")}function cq(e,t){for(let r of t)e.message(1,r,sT)}function lq(e,t){if(t===null)e.message(1,void 0,uq);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function uq(e,t){}var aT=w(()=>{Qr()});function dq(e,t){if(t.type==="hello")e.message(1,t,vde);else if(t.type==="request")e.message(2,t,wde);else throw Ke(t,"Impossible type of ClientMsg")}function vde(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function wde(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,xde);else if(r.type==="close_stream")e.message(3,r,_de);else if(r.type==="execute")e.message(4,r,Ede);else if(r.type==="batch")e.message(5,r,Ide);else if(r.type==="open_cursor")e.message(6,r,kde);else if(r.type==="close_cursor")e.message(7,r,Ade);else if(r.type==="fetch_cursor")e.message(8,r,Tde);else if(r.type==="sequence")e.message(9,r,$de);else if(r.type==="describe")e.message(10,r,Rde);else if(r.type==="store_sql")e.message(11,r,Ode);else if(r.type==="close_sql")e.message(12,r,Cde);else if(r.type==="get_autocommit")e.message(13,r,Pde);else throw Ke(r,"Impossible type of Request")}function xde(e,t){e.int32(1,t.streamId)}function _de(e,t){e.int32(1,t.streamId)}function Ede(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,lf)}function Ide(e,t){e.int32(1,t.streamId),e.message(2,t.batch,ll)}function kde(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,ll)}function Ade(e,t){e.int32(1,t.cursorId)}function Tde(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function $de(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Rde(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Ode(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Cde(e,t){e.int32(1,t.sqlId)}function Pde(e,t){e.int32(1,t.streamId)}var fq=w(()=>{aT();Qr()});function qi(e){let t=Ar(e.message),r=Lr(e.code);return{message:t,code:r}}function uf(e){let t=bn(e.cols,pq),r=Qd(e.rows).map((s)=>bn(s,mq)),o=Co(e.affected_row_count),n=Lr(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function pq(e){let t=Lr(e.name),r=Lr(e.decltype);return{name:t,decltype:r}}function ty(e){let t=new Map;Qd(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,uf(kt(o)))});let r=new Map;return Qd(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,qi(kt(o)))}),{stepResults:t,stepErrors:r}}function ry(e){let t=Ar(e.type);if(t==="step_begin"){let r=Co(e.step),o=bn(e.cols,pq);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Co(e.affected_row_count),o=Lr(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Co(e.step),o=qi(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:bn(e.row,mq)};else if(t==="error")return{type:"error",error:qi(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function ny(e){let t=bn(e.params,zde),r=bn(e.cols,Nde),o=Bi(e.is_explain),n=Bi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function zde(e){return{name:Lr(e.name)}}function Nde(e){let t=Ar(e.name),r=Lr(e.decltype);return{name:t,decltype:r}}function mq(e){let t=Ar(e.type);if(t==="null")return null;else if(t==="integer"){let r=Ar(e.value);return BigInt(r)}else if(t==="float")return Co(e.value);else if(t==="text")return Ar(e.value);else if(t==="blob")return Gc.toUint8Array(Ar(e.base64));else throw new Pe("Unexpected type of Value")}var oy=w(()=>{Fg();_t();ol()});function hq(e){let t=Ar(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:qi(kt(e.error))};else if(t==="response_ok"){let r=Co(e.request_id),o=Dde(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Co(e.request_id),o=qi(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function Dde(e){let t=Ar(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:uf(kt(e.result))};else if(t==="batch")return{type:"batch",result:ty(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=bn(e.entries,ry),o=Bi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:ny(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Bi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var gq=w(()=>{_t();ol();oy()});var Yr,Mi,yq,bq,ul,Lde,Bde,iy,jde,Zde,Ude,dl,qde,Mde,Fde;var sy=w(()=>{Yr={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},Mi={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(yq))},2(e,t){t.rows.push(e.message(bq))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},yq={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},bq={default(){return[]},1(e,t){t.push(e.message(Fde))}},ul={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Lde);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Bde);t.stepErrors.set(r,o)}},Lde={default(){return[0,Mi.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Mi)}},Bde={default(){return[0,Yr.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Yr)}},iy={default(){return{type:"none"}},1(e){return e.message(jde)},2(e){return e.message(Zde)},3(e){return e.message(Ude)},4(e){return{type:"row",row:e.message(bq)}},5(e){return{type:"error",error:e.message(Yr)}}},jde={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(yq))}},Zde={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Ude={default(){return{type:"step_error",step:0,error:Yr.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(Yr)}},dl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(qde))},2(e,t){t.cols.push(e.message(Mde))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},qde={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Mde={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Fde={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var Sq,Jde,Kde,Hde,Vde,Wde,Gde,Qde,Yde;var vq=w(()=>{sy();Sq={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Jde)},3(e){return e.message(Hde)},4(e){return e.message(Kde)}},Jde={default(){return{type:"hello_error",error:Yr.default()}},1(e,t){t.error=e.message(Yr)}},Kde={default(){return{type:"response_error",requestId:0,error:Yr.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(Yr)}},Hde={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(Vde)},5(e,t){t.response=e.message(Wde)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Gde)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Qde)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Yde)}},Vde={default(){return{type:"execute",result:Mi.default()}},1(e,t){t.result=e.message(Mi)}},Wde={default(){return{type:"batch",result:ul.default()}},1(e,t){t.result=e.message(ul)}},Gde={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(iy))},2(e,t){t.done=e.bool()}},Qde={default(){return{type:"describe",result:dl.default()}},1(e,t){t.result=e.message(dl)}},Yde={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var wq,cT,ay;var cy=w(()=>{GA();_t();QA();rf();sl();Qr();nT();aq();fq();gq();vq();wq=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),cT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);ay=class ay extends tl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Zi,this._streamIdAlloc=new Zi,this._cursorIdAlloc=new Zi,this.#l=new Zi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new We("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=cT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Yd(e,sq);this.#e.send(r)}else if(t==="protobuf"){let r=tf(e,dq);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new yn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new yn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new rl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new rl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=ea(JSON.parse(e.data),hq)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=ji(new Uint8Array(e.data),Sq)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Po(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Po(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return af.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new na(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new We("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var oa;var xq=w(()=>{if(typeof queueMicrotask<"u")oa=queueMicrotask;else{let e=Promise.resolve();oa=(t)=>{e.then(t)}}});class lT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function _q(e){let t=Lr(e.baton),r=Lr(e.base_url),o=bn(e.results,Xde);return{baton:t,baseUrl:r,results:o}}function Xde(e){let t=Ar(e.type);if(t==="ok")return{type:"ok",response:efe(kt(e.response))};else if(t==="error")return{type:"error",error:qi(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function efe(e){let t=Ar(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:uf(kt(e.result))};else if(t==="batch")return{type:"batch",result:ty(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:ny(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Bi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function Eq(e){let t=Lr(e.baton),r=Lr(e.base_url);return{baton:t,baseUrl:r}}var uT=w(()=>{_t();ol();oy()});var Iq,tfe,rfe,nfe,ofe,ife,sfe,kq;var dT=w(()=>{sy();Iq={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(tfe))}},tfe={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(rfe)}},2(e){return{type:"error",error:e.message(Yr)}}},rfe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(nfe)},3(e){return e.message(ofe)},4(e){return{type:"sequence"}},5(e){return e.message(ife)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(sfe)}},nfe={default(){return{type:"execute",result:Mi.default()}},1(e,t){t.result=e.message(Mi)}},ofe={default(){return{type:"batch",result:ul.default()}},1(e,t){t.result=e.message(ul)}},ife={default(){return{type:"describe",result:dl.default()}},1(e,t){t.result=e.message(dl)}},sfe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},kq={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var fT;var Aq=w(()=>{ol();VA();_t();Qr();uT();dT();oy();sy();fT=class fT extends sf{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new lT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(Eq,kq);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(ry,iy)}close(){this._setClosed(new We("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return ea(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return ji(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function Tq(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,afe)}function afe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,cf);else if(t.type==="batch")e.object("batch",t.batch,cl);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function $q(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,cl)}var pT=w(()=>{iT();Qr()});function Rq(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,cfe)}function cfe(e,t){if(t.type==="close")e.message(1,t,lfe);else if(t.type==="execute")e.message(2,t,ufe);else if(t.type==="batch")e.message(3,t,dfe);else if(t.type==="sequence")e.message(4,t,ffe);else if(t.type==="describe")e.message(5,t,pfe);else if(t.type==="store_sql")e.message(6,t,mfe);else if(t.type==="close_sql")e.message(7,t,hfe);else if(t.type==="get_autocommit")e.message(8,t,gfe);else throw Ke(t,"Impossible type of StreamRequest")}function lfe(e,t){}function ufe(e,t){e.message(1,t.stmt,lf)}function dfe(e,t){e.message(1,t.batch,ll)}function ffe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function pfe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function mfe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function hfe(e,t){e.int32(1,t.sqlId)}function gfe(e,t){}function Oq(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,ll)}var mT=w(()=>{aT();Qr()});function yfe(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Po(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function bfe(e,t){if(t==="json"){let r=await e.json();return ea(r,_q)}if(t==="protobuf"){let r=await e.arrayBuffer();return ji(new Uint8Array(r),Iq)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Sfe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Po(o);return new Xs(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new Xs(r,e.status)}return await e.body?.cancel(),new Xs(r,e.status)}var ly;var hT=w(()=>{_t();GA();QA();xq();rf();sl();ey();Qr();Aq();pT();mT();pT();mT();uT();dT();ly=class ly extends al{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Ui,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new Zi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new na(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,oa(()=>this.#u())}close(){this._setClosed(new We("Stream was manually closed"))}closeGracefully(){this.#l=!0,oa(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,oa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new xt("Stream is closed",this.#f);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),oa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new We("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>bfe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>yfe(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new fT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Sfe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,Tq,Rq)}#v(e,t){if(t.cursorPath===void 0)throw new yn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,$q,Oq)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Yd(t,o),s="application/json";else if(r==="protobuf")i=tf(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function wfe(e,t){let r=e;for(let o of vfe){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return gT}var vfe,gT,uy;var yT=w(()=>{_t();hT();vfe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],gT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};uy=class uy extends tl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=wfe(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(gT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=gT.version)return;else if(this._endpoint===void 0)throw new yn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new yn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new ly(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new We("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var Cq=w(()=>{_t()});function bT(e,t,r=2){if(typeof Li>"u")throw new Gd("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(cT.keys());else o=Array.from(wq.keys());let n=new Li(e,o);return new ay(n,t)}function ST(e,t,r,o,n=2){return new uy(e instanceof URL?e:new URL(e),t,r,o,n)}var dy=w(()=>{HA();cy();_t();yT();cy();HA();tT();Cq();sl();Yg();ey();yT();hT();cy();nT();_t()});class df{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(zo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Ni(this.#e)),c=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(c));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let f=d.query(u);return f.catch(()=>{return}),c=d,f}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let c=i.step();if(s!==void 0)c.condition(ut.ok(s));if(this.#t>=3)c.condition(ut.not(ut.isAutocommit(i)));let u=c.query(a);return u.catch(()=>{return}),s=c,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(pl(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Ni(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function fl(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Ni(e)),a=i,c=o.map((h)=>{let b=r.step().condition(ut.ok(a));if(t>=3)b.condition(ut.not(ut.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<c.length;h++)try{let b=await c[h];if(b===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(pl(b))}catch(b){if(b instanceof Wt)throw b;let y=st(b);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function zo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new of(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function pl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new Qc(t,r,o,n,i)}function st(e){if(e instanceof We){let t=Pq(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function Pq(e){if(e instanceof Wd&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof We?Pq(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof rl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Xs)return"SERVER_ERROR";else if(e instanceof yn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var wT=w(()=>{dy();gn();Yc()});class ml{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new zq,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class zq{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var xT=ge(function(K2e,Dq){function xfe(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function i(c){return new Promise(function(u,d){r.push({fn:c,resolve:u,reject:d}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(c){if(t>=e)return i(c);else return s(c)};return a}function _fe(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function Nq(e){return e.queue=0,e.map=_fe,e}Dq.exports=function(e){if(e)return Nq(xfe(e));else return Nq(function(t){return t()})}});function jq(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Fd(e.scheme,e.authority,e.path),r;try{r=bT(t,e.authToken)}catch(o){if(o instanceof Gd){let n=e.scheme==="wss"?"https":"http",i=Fd(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Hn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new Zq(r,t,e.authToken,e.intMode,e.concurrency)}class Zq{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=Bq.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=zo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return pl(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(zo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await fl(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(zo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await fl("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new Uq(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Efe&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=Lq}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=bT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new ml(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=Lq;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var Bq,Efe=60000,Lq=100,Uq;var qq=w(()=>{dy();gn();Hd();wT();Ug();Yc();Bq=$l(xT(),1);gn();Uq=class Uq extends df{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function Fq(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Fd(e.scheme,e.authority,e.path);return new Kq(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class Kq{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=ST(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=Mq.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=zo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return pl(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(zo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new ml(s,Jq).apply(o);let u=s.batch(!1);i=fl(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(zo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=fl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new Hq(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=ST(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var Mq,Jq=30,Hq;var Vq=w(()=>{dy();gn();Hd();wT();Ug();Yc();Mq=$l(xT(),1);gn();Hq=class Hq extends df{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new ml(e,Jq)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function hl(e){return Ife(Kd(e,!0))}function Ife(e){if(e.scheme==="wss"||e.scheme==="ws")return jq(e);else if(e.scheme==="https"||e.scheme==="http")return Fq(e);else return M4(e)}var _T=w(()=>{Hd();V4();qq();Vq();gn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var Re=w(()=>{F=Symbol.for("drizzle:entityKind")});var He;var Sn=w(()=>{Re();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var ff;var fy=w(()=>{Re();ff=class ff{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var gl=w(()=>{ir=Symbol.for("drizzle:Name")});var ET,Wq;var Gq=w(()=>{Re();gl();ET=class ET{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new Wq(e,this)}};Wq=class Wq{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function py(e,...t){return e(...t)}var IT=()=>{};function kT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var Qq,kfe,Yq;var Xq=w(()=>{Re();gl();Qq=class Qq{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new Yq(e,this.columns,this.nullsNotDistinctConfig,this.name)}};kfe=class kfe{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Qq(e,this.name)}};Yq=class Yq{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??kT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function eM(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function tM(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[c,u]=eM(e,o+1,!0);r.push(c),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[c,u]=tM(e,o+1);r.push(c),o=u;continue}let[s,a]=eM(e,o,!1);r.push(s),o=a}return[r,o]}function rM(e){let[t]=tM(e,1);return t}function AT(e){return`{${e.map((t)=>{if(Array.isArray(t))return AT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var nM=()=>{};var pf,yl,oM,Afe,iM,TT;var sM=w(()=>{fy();Sn();Re();Gq();IT();Xq();nM();pf=class pf extends ff{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new iM(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>py((n,i)=>{let s=new ET(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new oM(e,this.config)}};yl=class yl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=kT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};oM=class oM extends yl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Afe=class Afe{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};iM=class iM extends pf{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new TT(e,this.config,t)}};TT=class TT extends yl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=rM(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,TT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return AT(r)}}});function lM(e){return!!e&&typeof e==="function"&&aM in e&&e[aM]===!0}var Tfe,cM,aM,$fe,uM;var dM=w(()=>{Re();sM();Tfe=class Tfe extends pf{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new cM(e,this.config)}};cM=class cM extends yl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};aM=Symbol.for("drizzle:isPgEnum");$fe=class $fe extends pf{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new uM(e,this.config)}};uM=class uM extends yl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,mf;var vn=w(()=>{Re();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};mf=class mf extends dt{static[F]="WithSubquery"}});var fM="0.45.2";var pM=()=>{};var $T,RT,mM;var hM=w(()=>{IT();pM();mM={startActiveSpan(e,t){if(!$T)return t();if(!RT)RT=$T.trace.getTracer("drizzle-orm",fM);return py((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),$T,RT)}}});var ft;var No=w(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function Fi(e){return e[ir]}function ia(e){return`${e[my]??"public"}.${e[ir]}`}var my,hy,gM,OT,CT,hf,yM,Rfe,me;var sr=w(()=>{Re();gl();my=Symbol.for("drizzle:Schema"),hy=Symbol.for("drizzle:Columns"),gM=Symbol.for("drizzle:ExtraConfigColumns"),OT=Symbol.for("drizzle:OriginalName"),CT=Symbol.for("drizzle:BaseName"),hf=Symbol.for("drizzle:IsAlias"),yM=Symbol.for("drizzle:ExtraConfigBuilder"),Rfe=Symbol.for("drizzle:IsDrizzleTable");me=class me{static[F]="Table";static Symbol={Name:ir,Schema:my,OriginalName:OT,Columns:hy,ExtraConfigColumns:gM,BaseName:CT,IsAlias:hf,ExtraConfigBuilder:yM};[ir];[OT];[my];[hy];[gM];[CT];[hf]=!1;[Rfe]=!0;[yM]=void 0;constructor(e,t,r){this[ir]=this[OT]=e,this[my]=t,this[CT]=r}}});function PT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Cfe(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function bM(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new zt(e[0]));for(let[o,n]of t.entries())r.push(n,new zt(e[o+1]));return new xe(r)}function gf(e,t){return e.map((r)=>{if(oe(r,Ji)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Br)&&oe(r.value,Ji)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var Ofe,zt,xe,gy,SM,vM,nLe,Br,Ji,Pfe,Xr;var Qt=w(()=>{Re();dM();vn();hM();No();Sn();sr();Ofe=class Ofe{static[F]="FakePrimitiveParam"};zt=class zt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new xe([this])}};xe=class xe{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,me)){let r=t[me.Symbol.Schema];this.usedTables.push(r===void 0?t[me.Symbol.Name]:r+"."+t[me.Symbol.Name])}}static[F]="SQL";decoder=SM;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return mM.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return Cfe(e.map((u)=>{if(oe(u,zt))return{sql:u.value.join(""),params:[]};if(oe(u,gy))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new zt("(")];for(let[f,m]of u.entries())if(d.push(m),f<u.length-1)d.push(new zt(", "));return d.push(new zt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,xe))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,me)){let d=u[me.Symbol.Schema],f=u[me.Symbol.Name];return{sql:d===void 0||u[hf]?n(f):n(d)+"."+n(f),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let f=u.table[me.Symbol.Schema];return{sql:u.table[hf]||f===void 0?n(u.table[me.Symbol.Name])+"."+n(d):n(f)+"."+n(u.table[me.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,Xr)){let d=u[ft].schema,f=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(f):n(d)+"."+n(f),params:[]}}if(oe(u,Br)){if(oe(u.value,Ji))return{sql:i(c.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,xe))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let f=["none"];if(s)f=[s(u.encoder)];return{sql:i(c.value++,d),params:[d],typings:f}}if(oe(u,Ji))return{sql:i(c.value++,u),params:[u],typings:["none"]};if(oe(u,xe.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new zt("("),u._.sql,new zt(") "),new gy(u._.alias)],r)}if(lM(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(PT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new zt("("),u.getSQL(),new zt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(c.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new xe.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};gy=class gy{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new xe([this])}};SM={mapFromDriverValue:(e)=>e},vM={mapToDriverValue:(e)=>e},nLe={...SM,...vM};Br=class Br{constructor(e,t=vM){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new xe([this])}};((e)=>{function t(){return new xe([])}e.empty=t;function r(c){return new xe(c)}e.fromList=r;function o(c){return new xe([new zt(c)])}e.raw=o;function n(c,u){let d=[];for(let[f,m]of c.entries()){if(f>0&&u!==void 0)d.push(u);d.push(m)}return new xe(d)}e.join=n;function i(c){return new gy(c)}e.identifier=i;function s(c){return new Ji(c)}e.placeholder=s;function a(c,u){return new Br(c,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(xe||(xe={}));Ji=class Ji{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new xe([this])}};Pfe=Symbol.for("drizzle:IsDrizzleView");Xr=class Xr{static[F]="View";[ft];[Pfe]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new xe([this])}};He.prototype.getSQL=function(){return new xe([this])};me.prototype.getSQL=function(){return new xe([this])};dt.prototype.getSQL=function(){return new xe([this])}});function zT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},c)=>{let u;if(oe(a,He))u=a;else if(oe(a,xe))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[f,m]of s.entries())if(f<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[c],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?Fi(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==Fi(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function en(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,xe)||oe(n,xe.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,me))r.push(...en(n[me.Symbol.Columns],i));else r.push(...en(n,i));return r},[])}function yf(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function yy(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,xe)||oe(n,He))return[o,n];else return[o,new Br(n,e[me.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function wM(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function by(e){return e[me.Symbol.Columns]}function bf(e){return oe(e,dt)?e._.alias:oe(e,Xr)?e[ft].name:oe(e,xe)?void 0:e[me.Symbol.IsAlias]?e[me.Symbol.Name]:e[me.Symbol.BaseName]}function Qn(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function xM(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var NT;var br=w(()=>{Sn();Re();Qt();vn();sr();No();NT=typeof TextDecoder>"u"?null:new TextDecoder});var _M,DT,LT;var Sy=w(()=>{Re();_M=class _M{static[F]="ConsoleLogWriter";write(e){console.log(e)}};DT=class DT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new _M}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};LT=class LT{static[F]="NoopLogger";logQuery(){}}});var EM,IM,BT;var kM=w(()=>{Re();sr();EM=Symbol.for("drizzle:PgInlineForeignKeys"),IM=Symbol.for("drizzle:EnableRLS");BT=class BT extends me{static[F]="PgTable";static Symbol=Object.assign({},me.Symbol,{InlineForeignKeys:EM,EnableRLS:IM});[EM]=[];[IM]=!1;[me.Symbol.ExtraConfigBuilder]=void 0;[me.Symbol.ExtraConfigColumns]={}}});var jT,AM;var TM=w(()=>{Re();kM();jT=class jT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new AM(e,this.columns,this.name)}};AM=class AM{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[BT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Tr(e,t){if(bM(t)&&!PT(e)&&!oe(e,Br)&&!oe(e,Ji)&&!oe(e,He)&&!oe(e,me)&&!oe(e,Xr))return new Br(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new xe(t);return new xe([new zt("("),C.join(t,new zt(" and ")),new zt(")")])}function tn(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new xe(t);return new xe([new zt("("),C.join(t,new zt(" or ")),new zt(")")])}function RM(e){return C`not ${e}`}function Hi(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>Tr(r,e))}`}return C`${e} in ${Tr(t,e)}`}function vy(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>Tr(r,e))}`}return C`${e} not in ${Tr(t,e)}`}function jr(e){return C`${e} is null`}function PM(e){return C`${e} is not null`}function wy(e){return C`exists ${e}`}function Vi(e){return C`not exists ${e}`}function zM(e,t,r){return C`${e} between ${Tr(t,e)} and ${Tr(r,e)}`}function NM(e,t,r){return C`${e} not between ${Tr(t,e)} and ${Tr(r,e)}`}function DM(e,t){return C`${e} like ${t}`}function LM(e,t){return C`${e} not like ${t}`}function BM(e,t){return C`${e} ilike ${t}`}function jM(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${Tr(t,e)}`,$M=(e,t)=>C`${e} <> ${Tr(t,e)}`,wn=(e,t)=>C`${e} > ${Tr(t,e)}`,OM=(e,t)=>C`${e} >= ${Tr(t,e)}`,CM=(e,t)=>C`${e} < ${Tr(t,e)}`,Ki=(e,t)=>C`${e} <= ${Tr(t,e)}`;var ZM=w(()=>{Sn();Re();sr();Qt()});function Do(e){return C`${e} asc`}function sa(e){return C`${e} desc`}var UM=w(()=>{Qt()});var ZT=w(()=>{ZM();UM()});function MM(){return{and:tt,between:zM,eq:je,exists:wy,gt:wn,gte:OM,ilike:BM,inArray:Hi,isNull:jr,isNotNull:PM,like:DM,lt:CM,lte:Ki,ne:$M,not:RM,notBetween:NM,notExists:Vi,notLike:LM,notIlike:jM,notInArray:vy,or:tn,sql:C}}function FM(){return{sql:C,asc:Do,desc:sa}}function JM(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,me))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,me)){let a=ia(s),c=o[a];r[a]=i,n[i]={tsName:i,dbName:s[me.Symbol.Name],schema:s[me.Symbol.Schema],columns:s[me.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let d of Object.values(s[me.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[me.Symbol.ExtraConfigBuilder]?.(s[me.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,jT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,qM)){let a=ia(s.table),c=r[a],u=s.config(t(s.table)),d;for(let[f,m]of Object.entries(u))if(c){let h=n[c];if(h.relations[f]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[f]=m}}return{tables:n,tableNamesMap:r}}function zfe(e){return function(r,o){return new Wi(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Nfe(e){return function(r,o){return new Sf(e,r,o)}}function KM(e,t,r){if(oe(r,Wi)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ia(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[me.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ia(i)];if(!s)throw Error(`Table "${i[me.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[me.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],Wi)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function HM(e){return{one:zfe(e),many:Nfe(e)}}function xy(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let c=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(c,Wi)?d&&xy(e,e[a.relationTableTsKey],d,a.selection,n):d.map((f)=>xy(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,xe))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=c===null?null:d.mapFromDriverValue(c)}return i}var UT,qM,Wi,Sf;var vf=w(()=>{sr();Sn();Re();TM();ZT();Qt();UT=class UT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[me.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};qM=class qM{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};Wi=class Wi extends UT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new Wi(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Sf=class Sf extends UT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Sf(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function wf(e,t){return new Proxy(e,new aa(t,!1))}function Yn(e,t){return new Proxy(e,new bl(new Proxy(e.table,new aa(t,!1))))}function qT(e,t){return new xe.Aliased(xf(e.sql,t),e.fieldAlias)}function xf(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return Yn(r,t);if(oe(r,xe))return xf(r,t);if(oe(r,xe.Aliased))return qT(r,t);return r}))}var bl,aa,Dfe;var _f=w(()=>{Sn();Re();Qt();sr();No();bl=class bl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};aa=class aa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===me.Symbol.IsAlias)return!0;if(t===me.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===me.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===me.Symbol.Columns){let o=e[me.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new bl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new bl(new Proxy(e,this)));return r}};Dfe=class Dfe{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return wf(e.sourceTable,this.alias);return e[t]}}});var at;var ca=w(()=>{_f();Sn();Re();Qt();vn();No();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,Xr)?e[ft].selectedFields:e)[t];if(oe(o,xe.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,xe)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new bl(new Proxy(o.table,new aa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var Sr;var Lo=w(()=>{Re();Sr=class Sr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var MT,VM;var FT=w(()=>{Re();gl();MT=class MT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new VM(e,this)}};VM=class VM{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var WM,Lfe,GM;var KT=w(()=>{Re();gl();WM=class WM{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new GM(e,this.columns,this.name)}};Lfe=class Lfe{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new WM(e,this.name)}};GM=class GM{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??JT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Bt,gt;var Gi=w(()=>{fy();Sn();Re();FT();KT();Bt=class Bt extends ff{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new MT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};gt=class gt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function nF(e,t){let{name:r,config:o}=Qn(e,t);if(o?.mode==="json")return new XM(r);if(o?.mode==="bigint")return new QM(r);return new tF(r)}var QM,YM,XM,eF,tF,rF;var HT=w(()=>{Re();br();Gi();QM=class QM extends Bt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new YM(e,this.config)}};YM=class YM extends gt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(NT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};XM=class XM extends Bt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new eF(e,this.config)}};eF=class eF extends gt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(NT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};tF=class tF extends Bt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new rF(e,this.config)}};rF=class rF extends gt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function sF(e){return(t,r)=>{let{name:o,config:n}=Qn(t,r);return new oF(o,n,e)}}var oF,iF;var VT=w(()=>{Re();br();Gi();oF=class oF extends Bt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new iF(e,this.config)}};iF=class iF extends gt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=Qn(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new lF(r,o.mode);if(o?.mode==="boolean")return new dF(r,o.mode);return new aF(r)}var _y,Ey,aF,cF,lF,uF,dF,fF;var WT=w(()=>{Re();Qt();br();Gi();_y=class _y extends Bt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};Ey=class Ey extends gt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};aF=class aF extends _y{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new cF(e,this.config)}};cF=class cF extends Ey{static[F]="SQLiteInteger"};lF=class lF extends _y{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new uF(e,this.config)}};uF=class uF extends Ey{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};dF=class dF extends _y{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new fF(e,this.config)}};fF=class fF extends Ey{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function SF(e,t){let{name:r,config:o}=Qn(e,t),n=o?.mode;return n==="number"?new hF(r):n==="bigint"?new yF(r):new pF(r)}var pF,mF,hF,gF,yF,bF;var GT=w(()=>{Re();br();Gi();pF=class pF extends Bt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new mF(e,this.config)}};mF=class mF extends gt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};hF=class hF extends Bt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new gF(e,this.config)}};gF=class gF extends gt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};yF=class yF extends Bt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new bF(e,this.config)}};bF=class bF extends gt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function xF(e){return new vF(e??"")}var vF,wF;var QT=w(()=>{Re();Gi();vF=class vF extends Bt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new wF(e,this.config)}};wF=class wF extends gt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function pt(e,t={}){let{name:r,config:o}=Qn(e,t);if(o.mode==="json")return new IF(r);return new _F(r,o)}var _F,EF,IF,kF;var YT=w(()=>{Re();br();Gi();_F=class _F extends Bt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new EF(e,this.config)}};EF=class EF extends gt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};IF=class IF extends Bt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new kF(e,this.config)}};kF=class kF extends gt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function AF(){return{blob:nF,customType:sF,integer:ar,numeric:SF,real:xF,text:pt}}var TF=w(()=>{HT();VT();WT();GT();QT();YT()});function Bfe(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(AF()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let f=d;f.setName(u);let m=f.build(i);return i[XT].push(...f.buildForeignKeys(m,i)),[u,m]})),c=Object.assign(i,a);if(c[me.Symbol.Columns]=a,c[me.Symbol.ExtraConfigColumns]=a,r)c[At.Symbol.ExtraConfigBuilder]=r;return c}var XT,At,Ef=(e,t,r)=>Bfe(e,t,r);var Bo=w(()=>{Re();sr();TF();XT=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends me{static[F]="SQLiteTable";static Symbol=Object.assign({},me.Symbol,{InlineForeignKeys:XT});[me.Symbol.Columns];[XT]=[];[me.Symbol.ExtraConfigBuilder]=void 0}});var jfe,$F;var RF=w(()=>{Re();jfe=class jfe{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new $F(e,this)}};$F=class $F{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function jo(e){return new OF(e,!1)}var OF,CF,PF;var zF=w(()=>{Re();OF=class OF{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new CF(this.name,e,this.unique)}};CF=class CF{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new PF(this.config,e)}};PF=class PF{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Zfe,NF;var DF=w(()=>{Re();Bo();Zfe=class Zfe{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new NF(e,this.columns,this.name)}};NF=class NF{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function xn(e){if(oe(e,At))return[`${e[me.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,xe))return e.usedTables??[];return[]}var Sl=w(()=>{Re();Qt();vn();sr();Bo()});var Iy;var LF=w(()=>{Re();Lo();ca();Bo();sr();br();Sl();Iy=class Iy extends Sr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[me.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=en(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:xn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function Ufe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function qfe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Mfe(e){return e}var e$;var BF=w(()=>{Re();sr();e$=class e${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Ufe:e==="camelCase"?qfe:Mfe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[me.Symbol.Schema]??"public",r=e.table[me.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[me.Symbol.Schema]??"public",r=e[me.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[me.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var vl,Zo,t$;var ky=w(()=>{Re();vl=class vl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Zo=class Zo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
374
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}silly(e,...t){if(this.level<=Ws.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=Ws.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=Ws.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=Ws.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=Ws.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=Ws.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new kr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var Ws,hPe;var BA=w(()=>{Ws={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};hPe=kr.getInstance()});var jA,Zle,Hc,SPe;var qd=w(()=>{Vt();he();jA=l.enum(["file_operations","content_operations","data_processing","batch_processing"]),Zle=l.looseObject({pluginId:l.string().optional(),progressToken:l.union([l.string(),l.number()]).optional(),operationType:jA,operationTarget:l.string().optional(),interfaceType:l.string().optional(),conversationId:l.string().optional(),channelId:l.string().optional(),requestedByActor:vi.optional(),requestedByUserId:l.string().optional(),requestedByInterface:l.string().optional(),silent:l.boolean().optional(),provenance:wi.optional()}),Hc=l.looseObject({pluginId:l.string().optional(),progressToken:l.union([l.string(),l.number()]).optional(),operationType:jA,operationTarget:l.string().optional(),interfaceType:l.string().optional(),conversationId:l.string().optional(),channelId:l.string().optional(),requestedByActor:vi.optional(),requestedByUserId:l.string().optional(),requestedByInterface:l.string().optional(),silent:l.boolean().optional(),provenance:wi.optional(),rootJobId:l.string()}),SPe=l.enum(["none","skip","replace","coalesce"])});var Ule,zi=15000;var Md=w(()=>{qd();he();Ule=l.object({id:l.string(),type:l.string(),data:l.string(),status:l.enum(["pending","processing","completed","failed"]),source:l.string().nullable(),priority:l.number(),retryCount:l.number(),maxRetries:l.number(),lastError:l.string().nullable(),lastErrorPublic:l.unknown(),createdAt:l.number(),scheduledFor:l.number(),startedAt:l.number().nullable(),completedAt:l.number().nullable(),attemptId:l.string().nullable(),workerSlotId:l.string().nullable(),workerSessionId:l.string().nullable(),leaseExpiresAt:l.number().nullable(),attemptHeartbeatAt:l.number().nullable(),runtimeUpdatedAt:l.number().nullable(),metadata:Hc,progress:l.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:l.unknown().nullable().optional()})});var ZA,z6,Oe,qle,Mle,N6,D6,L6;var Ro=w(()=>{Vt();he();qd();ZA=l.enum(["pending","processing","completed","failed"]),z6=l.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},qle=l.object({id:l.string(),type:l.string(),status:ZA,data:l.unknown(),result:l.unknown().optional(),lastError:l.string().optional().nullable(),attempts:l.number(),maxRetries:l.number(),priority:l.number(),createdAt:l.date(),updatedAt:l.date(),processedAt:l.date().optional().nullable(),completedAt:l.date().optional().nullable(),failedAt:l.date().optional().nullable()}),Mle=l.object({jobId:l.string(),type:l.string(),status:z6,result:l.unknown().optional(),error:l.string().optional()}),N6=l.object({success:l.literal(!1),error:l.string().optional()}),D6=l.object({id:l.string(),type:l.enum(["job","batch"]),status:ZA,message:l.string().optional(),progress:l.object({current:l.number(),total:l.number(),percentage:l.number()}).optional(),aggregationKey:l.string().optional(),batchDetails:l.object({totalOperations:l.number(),completedOperations:l.number(),failedOperations:l.number(),currentOperation:l.string().optional(),errors:l.array(l.string()).optional()}).optional(),jobDetails:l.object({jobType:l.string(),priority:l.number(),retryCount:l.number()}).optional(),metadata:Hc}),L6=xi(qI.progress,D6)});var Ce,Wt;var gn=w(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function B6(e){let t=Fle.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Jle(r.authority):void 0,i=Gs(r.path),s=r.query!==void 0?Hle(r.query):void 0,a=r.fragment!==void 0?Gs(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Jle(e){let t=Kle.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=Gs(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:Gs(r.username),password:r.password!==void 0?Gs(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function Hle(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:Gs(n.replaceAll("+"," ")),value:Gs(i.replaceAll("+"," "))})}return{pairs:r}}function Gs(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function Fd(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=Vle(t.host),i=Wle(t.port),a=`//${Gle(t.userinfo)}${n}${i}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${o}${a}${c}`)}function Vle(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function Wle(e){return e!==void 0?`:${e}`:""}function Gle(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Fle,Kle;var Ug=w(()=>{gn();Fle=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Kle=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Wc,j6,Z6,Jd,qg,Qle,Gt,U6,F6=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),J6=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),K6=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Jd[t>>18&63]+Jd[t>>12&63]+Jd[t>>6&63]+Jd[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},MA,UA,Mg=(e,t=!1)=>t?F6(UA(e)):UA(e),Yle=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},Xle,H6=(e)=>e.replace(Xle,Yle),q6,Vc=(e,t=!1)=>t?F6(q6(e)):q6(e),M6=(e)=>Vc(e,!0),eue,tue=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},V6=(e)=>e.replace(eue,tue),W6=(e)=>{if(e=e.replace(/\s+/g,""),!Qle.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=qg[e.charAt(i++)]<<18|qg[e.charAt(i++)]<<12|(r=qg[e.charAt(i++)])<<6|(o=qg[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},FA,G6,Q6=(e)=>G6(Y6(e)),rue,Y6=(e)=>J6(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),qA=(e)=>rue(Y6(e)),nue=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},X6=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),e4=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,X6(r));e("fromBase64",function(){return qA(this)}),e("toBase64",function(t){return Vc(this,t)}),e("toBase64URI",function(){return Vc(this,!0)}),e("toBase64URL",function(){return Vc(this,!0)}),e("toUint8Array",function(){return Q6(this)})},t4=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,X6(r));e("toBase64",function(t){return Mg(this,t)}),e("toBase64URI",function(){return Mg(this,!0)}),e("toBase64URL",function(){return Mg(this,!0)})},oue=()=>{e4(),t4()},Gc;var Fg=w(()=>{Wc=typeof Buffer==="function",j6=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,Z6=typeof TextEncoder==="function"?new TextEncoder:void 0,Jd=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),qg=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Jd),Qle=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),U6=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),MA=typeof btoa==="function"?(e)=>btoa(e):Wc?(e)=>Buffer.from(e,"binary").toString("base64"):K6,UA=Wc?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return MA(r.join(""))},Xle=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,q6=Wc?(e)=>Buffer.from(e,"utf8").toString("base64"):Z6?(e)=>UA(Z6.encode(e)):(e)=>MA(H6(e)),eue=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,FA=typeof atob==="function"?(e)=>atob(J6(e)):Wc?(e)=>Buffer.from(e,"base64").toString("binary"):W6,G6=Wc?(e)=>U6(Buffer.from(e,"base64")):(e)=>U6(FA(e).split("").map((t)=>t.charCodeAt(0))),rue=Wc?(e)=>Buffer.from(e,"base64").toString("utf8"):j6?(e)=>j6.decode(G6(e)):(e)=>V6(FA(e)),Gc={version:"3.8.0",VERSION:"3.8.0",atob:FA,atobPolyfill:W6,btoa:MA,btoaPolyfill:K6,fromBase64:qA,toBase64:Vc,encode:Vc,encodeURI:M6,encodeURL:M6,utob:H6,btou:V6,decode:qA,isValid:nue,fromUint8Array:Mg,toUint8Array:Q6,extendString:e4,extendUint8Array:t4,extendBuiltins:oue}});function Ni(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class Qc{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(iue),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function iue(e){return Array.prototype.map.call(e,sue)}function sue(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Gc.fromUint8Array(new Uint8Array(e));else return e}var Hn="https://github.com/libsql/libsql-client-ts#supported-urls";var Yc=w(()=>{Fg()});function n4(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function Kd(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===r4)r="file::memory:";let c=B6(r),u=c.scheme.toLowerCase(),d=u==="file"&&c.path===r4&&c.authority===void 0,f;if(d)f={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else f={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of c.query?.pairs??[]){if(!Object.hasOwn(f,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=f[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=c.path+m,b;if(u==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(c.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:c.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var r4=":memory:";var Hd=w(()=>{gn();Ug();Yc()});var i4=ge(function(Gr){var aue=Gr&&Gr.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),cue=Gr&&Gr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o4=Gr&&Gr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))aue(t,e,r)}return cue(t,e),t};Object.defineProperty(Gr,"__esModule",{value:!0});Gr.load=Gr.currentTarget=void 0;var lue=o4(Zr("path")),uue=o4(Zr("fs"));function due(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return fue()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}Gr.currentTarget=due;function fue(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function pue(e){let t=lue.join(e,"index.node");return uue.existsSync(t)?Zr(t):null}Gr.load=pue});var c4=ge(function(ZPe,a4){var s4=()=>process.platform==="linux",JA=null,mue=()=>{if(!JA)JA=s4()&&process.report?process.report.getReport():{};return JA};a4.exports={isLinux:s4,getReport:mue}});var d4=ge(function(UPe,u4){var l4=Zr("fs"),hue=(e)=>l4.readFileSync(e,"utf-8"),gue=(e)=>new Promise((t,r)=>{l4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});u4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:hue,readFile:gue}});var T4=ge(function(qPe,A4){var p4=Zr("child_process"),{isLinux:Xc,getReport:m4}=c4(),{LDD_PATH:Jg,readFile:h4,readFileSync:g4}=d4(),Vn,Wn,Di="",y4=()=>{if(!Di)return new Promise((e)=>{p4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Di=t?" ":r,e(Di)})});return Di},b4=()=>{if(!Di)try{Di=p4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Di=" "}return Di},Oo="glibc",S4=/GLIBC\s(\d+\.\d+)/,Qs="musl",yue=Oo.toUpperCase(),bue=Qs.toLowerCase(),Sue=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),v4=()=>{let e=m4();if(e.header&&e.header.glibcVersionRuntime)return Oo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Sue))return Qs}return null},w4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Oo))return Oo;if(r&&r.includes(Qs))return Qs;return null},x4=(e)=>{if(e.includes(bue))return Qs;if(e.includes(yue))return Oo;return null},vue=async()=>{if(Vn!==void 0)return Vn;Vn=null;try{let e=await h4(Jg);Vn=x4(e)}catch(e){}return Vn},wue=()=>{if(Vn!==void 0)return Vn;Vn=null;try{let e=g4(Jg);Vn=x4(e)}catch(e){}return Vn},_4=async()=>{let e=null;if(Xc()){if(e=await vue(),!e)e=v4();if(!e){let t=await y4();e=w4(t)}}return e},E4=()=>{let e=null;if(Xc()){if(e=wue(),!e)e=v4();if(!e){let t=b4();e=w4(t)}}return e},xue=async()=>Xc()&&await _4()!==Oo,_ue=()=>Xc()&&E4()!==Oo,Eue=async()=>{if(Wn!==void 0)return Wn;Wn=null;try{let t=(await h4(Jg)).match(S4);if(t)Wn=t[1]}catch(e){}return Wn},Iue=()=>{if(Wn!==void 0)return Wn;Wn=null;try{let t=g4(Jg).match(S4);if(t)Wn=t[1]}catch(e){}return Wn},I4=()=>{let e=m4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},f4=(e)=>e.trim().split(/\s+/)[1],k4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Oo))return f4(t);if(r&&o&&r.includes(Qs))return f4(o);return null},kue=async()=>{let e=null;if(Xc()){if(e=await Eue(),!e)e=I4();if(!e){let t=await y4();e=k4(t)}}return e},Aue=()=>{let e=null;if(Xc()){if(e=Iue(),!e)e=I4();if(!e){let t=b4();e=k4(t)}}return e};A4.exports={GLIBC:Oo,MUSL:Qs,family:_4,familySync:E4,isNonGlibcLinux:xue,isNonGlibcLinuxSync:_ue,version:kue,versionSync:Aue}});var R4=ge(function(MPe,$4){var Tue={ALLOW:0,DENY:1};$4.exports=Tue});var C4=ge(function(FPe,O4){var KA={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ys(e,t,r){if(new.target!==Ys)return new Ys(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),KA.value=""+e,Object.defineProperty(this,"message",KA),Error.captureStackTrace(this,Ys),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ys,Error);Object.setPrototypeOf(Ys.prototype,Error.prototype);Object.defineProperty(Ys.prototype,"name",KA);O4.exports=Ys});var Z4=ge(function(JPe,Kg){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:$ue,currentTarget:Rue}=i4(),{familySync:P4,GLIBC:Oue,MUSL:Cue}=T4();function Pue(){if(process.env.LIBSQL_JS_DEV)return $ue(__dirname);let e=Rue();if(P4()==Oue)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&P4()==Cue)e="linux-arm-musleabihf";return Zr(`@libsql/${e}`)}var{databaseOpen:zue,databaseOpenWithSync:Nue,databaseInTransaction:Due,databaseInterrupt:Lue,databaseClose:Bue,databaseSyncSync:jue,databaseSyncUntilSync:Zue,databaseExecSync:Uue,databasePrepareSync:que,databaseDefaultSafeIntegers:Mue,databaseAuthorizer:Fue,databaseLoadExtension:Jue,databaseMaxWriteReplicationIndex:Kue,statementRaw:Hue,statementIsReader:Vue,statementGet:z4,statementRun:N4,statementInterrupt:Wue,statementRowsSync:D4,statementColumns:Gue,statementSafeIntegers:Que,rowsNext:Yue}=Pue(),Xue=R4(),L4=C4();function el(e){if(e.libsqlError)return new L4(e.message,e.code,e.rawCode);return e}class B4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Nue(e,t.syncUrl,o,r,i,s,a,c,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=zue(e,i,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Due(n)}}})}sync(){return jue.call(this.db)}syncUntil(e){return Zue.call(this.db,e)}prepare(e){try{let t=que.call(this.db,e);return new j4(t)}catch(t){throw el(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){Fue.call(this.db,e)}loadExtension(...e){Jue.call(this.db,...e)}maxWriteReplicationIndex(){return Kue.call(this.db)}exec(e){try{Uue.call(this.db,e)}catch(t){throw el(t)}}interrupt(){Lue.call(this.db)}close(){Bue.call(this.db),this.open=!1}defaultSafeIntegers(e){return Mue.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class j4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return Hue.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return Vue.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return N4.call(this.stmt,e[0]);else return N4.call(this.stmt,e.flat())}catch(t){throw el(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return z4.call(this.stmt,e[0]);else return z4.call(this.stmt,e.flat())}catch(t){throw el(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=D4.call(this.stmt,e[0]);else t=D4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)Yue.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw el(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw el(t)}}interrupt(){Wue.call(this.stmt)}columns(){return Gue.call(this.stmt)}safeIntegers(e){return Que.call(this.stmt,e??!0),this}}Kg.exports=B4;Kg.exports.Authorization=Xue;Kg.exports.SqliteError=L4});import{Buffer as q4}from"buffer";function M4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Hn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=n4(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new Vd.default(o,n);return Pt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new F4(o,n,i,e.intMode)}class F4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),Pt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{Pt(r,Ni(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(Pt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return Pt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)Pt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{Pt(t,"PRAGMA foreign_keys=off",this.#n),Pt(t,Ni("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(Pt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Pt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n);Pt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return Pt(t,Ni(e),this.#n),this.#r=null,new J4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return K4(t,e)}finally{if(t.inTransaction)Pt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new Vd.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new Vd.default(this.#e,this.#t);return this.#r}}class J4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),Pt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(Pt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),K4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Pt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Pt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Pt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function Pt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>U4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=U4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),c=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>ede(m,a,r)),d=0,f=void 0;return new Qc(a,c,u,0,void 0)}else{let a=i.run(n),c=a.changes,u=BigInt(a.lastInsertRowid);return new Qc([],[],[],c,u)}}catch(i){throw H4(i)}}function ede(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=tde(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function tde(e,t){if(typeof e==="bigint")if(t==="number"){if(e<rde||e>nde)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof q4)return e.buffer;return e}function U4(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<ode||e>ide)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return q4.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function K4(e,t){try{e.exec(t)}catch(r){throw H4(r)}}function H4(e){if(e instanceof Vd.default.SqliteError){let t=e.code,r=sde(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function sde(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return ade[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Vd,rde,nde=9007199254740991n,ode,ide=9223372036854775807n,ade;var V4=w(()=>{gn();Hd();Yc();Vd=$l(Z4(),1);gn();rde=-9007199254740991n;ode=-9223372036854775808n;ade={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Li;var HA=w(()=>{if(typeof WebSocket<"u")Li=WebSocket;else if(typeof global<"u")Li=global.WebSocket;else if(typeof window<"u")Li=window.WebSocket;else if(typeof self<"u")Li=self.WebSocket});class tl{constructor(){this.intMode="number"}intMode}var We,Pe,Wd,xt,Gd,rl,Xs,yn,or,Gn;var _t=w(()=>{We=class We extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends We{constructor(e){super(e);this.name="ProtoError"}};Wd=class Wd extends We{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends We{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Gd=class Gd extends We{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};rl=class rl extends We{constructor(e){super(e);this.name="WebSocketError"}};Xs=class Xs extends We{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};yn=class yn extends We{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends We{constructor(e){super(e);this.name="InternalError"}};Gn=class Gn extends We{constructor(e){super(e);this.name="MisuseError"}}});function Ar(e){if(typeof e==="string")return e;throw nl(e,"string")}function Lr(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw nl(e,"string or null")}function Co(e){if(typeof e==="number")return e;throw nl(e,"number")}function Bi(e){if(typeof e==="boolean")return e;throw nl(e,"boolean")}function Qd(e){if(Array.isArray(e))return e;throw nl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw nl(e,"object")}function bn(e,t){return Qd(e).map((r)=>t(kt(r)))}function nl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function ea(e,t){return t(kt(e))}var ol=w(()=>{_t()});class W4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Yd(e,t){let r=[],o=new W4(r);return o.begin(),t(o,e),o.end(),r.join("")}var ta=0,Xd=1,ef=2,G4=5;class Q4{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class Y4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(ef);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return ji(this.bytes(),e)}int32(){return this.#r(ta),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(ta),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Xd),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===ta)this.#e.skipVarint();else if(this.#t===Xd)this.#e.skip(8);else if(this.#t===ef){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===G4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function ji(e,t){let r=new Q4(e),o=new Y4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let c=t[s];if(c!==void 0){let u=c(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var VA=w(()=>{_t()});class WA{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,ef),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new WA;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,ta),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,ta),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Xd),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function tf(e,t){let r=new WA;return t(r,e),r.data()}var X4=()=>{};var GA=w(()=>{ol();VA();X4()});class Zi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var QA=w(()=>{_t()});function Ke(e,t){throw new or(t)}var Qr=w(()=>{_t()});function il(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<lde||e>ude)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function YA(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new Gn("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var lde,ude=9223372036854775807n;var XA=w(()=>{_t();Qr();lde=-9223372036854775808n});function ra(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Vg(e,t){let r=ra(e),o=e.rows.map((n)=>eq(r.columnNames,n,t));return{...r,rows:o}}function Wg(e,t){let r=ra(e),o;if(e.rows.length>0)o=eq(r.columnNames,e.rows[0],t);return{...r,row:o}}function Gg(e,t){let r=ra(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=YA(e.rows[0][0],t);return{...r,value:o}}function eq(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=YA(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Po(e){return new Wd(e.message,e)}var rf=w(()=>{_t();XA()});class na{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new Gn("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new We("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function nf(e,t){if(t instanceof na)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var sl=w(()=>{_t()});class Ui{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class of{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(il(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=il(t),this}bindName(e,t){return this._namedArgs.set(e,il(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Qg(e,t,r){let o,n=[],i=[];if(t instanceof of){o=t.sql,n=t._args;for(let[c,u]of t._namedArgs.entries())i.push({name:c,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((c)=>il(c));else i=Object.entries(t[1]).map(([c,u])=>({name:c,value:il(u)}));else o=t;let{sql:s,sqlId:a}=nf(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Yg=w(()=>{sl();XA()});class Xg{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new eT(this)}execute(){if(this.#t)throw new Gn("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return fde(this._stream,this._steps,e);else return dde(this._stream,this._steps,e)}}function dde(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function fde(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let c={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(c,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Po(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class eT{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,Vg)}queryRow(e){return this.#t(e,!0,Wg)}queryValue(e){return this.#t(e,!0,Gg)}run(e){return this.#t(e,!1,ra)}#t(e,t,r){if(this._index!==void 0)throw new Gn("This BatchStep has already been added to the batch");let o=Qg(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let c=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Po(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:c})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:tq(e)})}static error(e){return new ut(e._batch,{type:"error",step:tq(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)rq(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)rq(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function tq(e){if(e._index===void 0)throw new Gn("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function rq(e,t){if(t._batch!==e)throw new Gn("Cannot mix BatchCond objects for different Batch objects")}var tT=w(()=>{_t();rf();Yg();Qr()});function nq(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class al{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Vg)}queryRow(e){return this.#e(e,!0,Wg)}queryValue(e){return this.#e(e,!0,Gg)}run(e){return this.#e(e,!1,ra)}#e(e,t,r){let o=Qg(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Xg(this,e)}describe(e){let t=nf(this._sqlOwner(),e);return this._describe(t).then(nq)}sequence(e){let t=nf(this._sqlOwner(),e);return this._sequence(t)}intMode}var ey=w(()=>{tT();rf();sl();Yg()});class sf{}var pde=1000,mde=10,rT;var oq=w(()=>{_t();rT=class rT extends sf{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Ui,this.#o=new Ui,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<mde)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:pde}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new We("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var af;var nT=w(()=>{_t();ey();oq();af=class af extends al{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new af(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Ui,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new We("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new rT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new We("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function cf(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,iq),e.arrayObjects("named_args",t.namedArgs,hde),e.boolean("want_rows",t.wantRows)}function hde(e,t){e.string("name",t.name),e.object("value",t.value,iq)}function cl(e,t){e.arrayObjects("steps",t.steps,gde)}function gde(e,t){if(t.condition!==void 0)e.object("condition",t.condition,oT);e.object("stmt",t.stmt,cf)}function oT(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,oT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,oT);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function iq(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",Gc.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var iT=w(()=>{Fg();Qr()});function sq(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,yde);else throw Ke(t,"Impossible type of ClientMsg")}function yde(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,cf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,cl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,cl);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var aq=w(()=>{iT();Qr()});function lf(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,lq);for(let r of t.namedArgs)e.message(4,r,bde);e.bool(5,t.wantRows)}function bde(e,t){e.string(1,t.name),e.message(2,t.value,lq)}function ll(e,t){for(let r of t.steps)e.message(1,r,Sde)}function Sde(e,t){if(t.condition!==void 0)e.message(1,t.condition,sT);e.message(2,t.stmt,lf)}function sT(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,sT);else if(t.type==="and")e.message(4,t.conds,cq);else if(t.type==="or")e.message(5,t.conds,cq);else if(t.type==="is_autocommit")e.message(6,void 0,uq);else throw Ke(t,"Impossible type of BatchCond")}function cq(e,t){for(let r of t)e.message(1,r,sT)}function lq(e,t){if(t===null)e.message(1,void 0,uq);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function uq(e,t){}var aT=w(()=>{Qr()});function dq(e,t){if(t.type==="hello")e.message(1,t,vde);else if(t.type==="request")e.message(2,t,wde);else throw Ke(t,"Impossible type of ClientMsg")}function vde(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function wde(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,xde);else if(r.type==="close_stream")e.message(3,r,_de);else if(r.type==="execute")e.message(4,r,Ede);else if(r.type==="batch")e.message(5,r,Ide);else if(r.type==="open_cursor")e.message(6,r,kde);else if(r.type==="close_cursor")e.message(7,r,Ade);else if(r.type==="fetch_cursor")e.message(8,r,Tde);else if(r.type==="sequence")e.message(9,r,$de);else if(r.type==="describe")e.message(10,r,Rde);else if(r.type==="store_sql")e.message(11,r,Ode);else if(r.type==="close_sql")e.message(12,r,Cde);else if(r.type==="get_autocommit")e.message(13,r,Pde);else throw Ke(r,"Impossible type of Request")}function xde(e,t){e.int32(1,t.streamId)}function _de(e,t){e.int32(1,t.streamId)}function Ede(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,lf)}function Ide(e,t){e.int32(1,t.streamId),e.message(2,t.batch,ll)}function kde(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,ll)}function Ade(e,t){e.int32(1,t.cursorId)}function Tde(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function $de(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Rde(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Ode(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Cde(e,t){e.int32(1,t.sqlId)}function Pde(e,t){e.int32(1,t.streamId)}var fq=w(()=>{aT();Qr()});function qi(e){let t=Ar(e.message),r=Lr(e.code);return{message:t,code:r}}function uf(e){let t=bn(e.cols,pq),r=Qd(e.rows).map((s)=>bn(s,mq)),o=Co(e.affected_row_count),n=Lr(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function pq(e){let t=Lr(e.name),r=Lr(e.decltype);return{name:t,decltype:r}}function ty(e){let t=new Map;Qd(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,uf(kt(o)))});let r=new Map;return Qd(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,qi(kt(o)))}),{stepResults:t,stepErrors:r}}function ry(e){let t=Ar(e.type);if(t==="step_begin"){let r=Co(e.step),o=bn(e.cols,pq);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Co(e.affected_row_count),o=Lr(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Co(e.step),o=qi(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:bn(e.row,mq)};else if(t==="error")return{type:"error",error:qi(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function ny(e){let t=bn(e.params,zde),r=bn(e.cols,Nde),o=Bi(e.is_explain),n=Bi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function zde(e){return{name:Lr(e.name)}}function Nde(e){let t=Ar(e.name),r=Lr(e.decltype);return{name:t,decltype:r}}function mq(e){let t=Ar(e.type);if(t==="null")return null;else if(t==="integer"){let r=Ar(e.value);return BigInt(r)}else if(t==="float")return Co(e.value);else if(t==="text")return Ar(e.value);else if(t==="blob")return Gc.toUint8Array(Ar(e.base64));else throw new Pe("Unexpected type of Value")}var oy=w(()=>{Fg();_t();ol()});function hq(e){let t=Ar(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:qi(kt(e.error))};else if(t==="response_ok"){let r=Co(e.request_id),o=Dde(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Co(e.request_id),o=qi(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function Dde(e){let t=Ar(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:uf(kt(e.result))};else if(t==="batch")return{type:"batch",result:ty(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=bn(e.entries,ry),o=Bi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:ny(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Bi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var gq=w(()=>{_t();ol();oy()});var Yr,Mi,yq,bq,ul,Lde,Bde,iy,jde,Zde,Ude,dl,qde,Mde,Fde;var sy=w(()=>{Yr={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},Mi={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(yq))},2(e,t){t.rows.push(e.message(bq))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},yq={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},bq={default(){return[]},1(e,t){t.push(e.message(Fde))}},ul={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Lde);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Bde);t.stepErrors.set(r,o)}},Lde={default(){return[0,Mi.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Mi)}},Bde={default(){return[0,Yr.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Yr)}},iy={default(){return{type:"none"}},1(e){return e.message(jde)},2(e){return e.message(Zde)},3(e){return e.message(Ude)},4(e){return{type:"row",row:e.message(bq)}},5(e){return{type:"error",error:e.message(Yr)}}},jde={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(yq))}},Zde={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Ude={default(){return{type:"step_error",step:0,error:Yr.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(Yr)}},dl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(qde))},2(e,t){t.cols.push(e.message(Mde))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},qde={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Mde={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Fde={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var Sq,Jde,Kde,Hde,Vde,Wde,Gde,Qde,Yde;var vq=w(()=>{sy();Sq={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Jde)},3(e){return e.message(Hde)},4(e){return e.message(Kde)}},Jde={default(){return{type:"hello_error",error:Yr.default()}},1(e,t){t.error=e.message(Yr)}},Kde={default(){return{type:"response_error",requestId:0,error:Yr.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(Yr)}},Hde={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(Vde)},5(e,t){t.response=e.message(Wde)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Gde)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Qde)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Yde)}},Vde={default(){return{type:"execute",result:Mi.default()}},1(e,t){t.result=e.message(Mi)}},Wde={default(){return{type:"batch",result:ul.default()}},1(e,t){t.result=e.message(ul)}},Gde={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(iy))},2(e,t){t.done=e.bool()}},Qde={default(){return{type:"describe",result:dl.default()}},1(e,t){t.result=e.message(dl)}},Yde={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var wq,cT,ay;var cy=w(()=>{GA();_t();QA();rf();sl();Qr();nT();aq();fq();gq();vq();wq=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),cT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);ay=class ay extends tl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Zi,this._streamIdAlloc=new Zi,this._cursorIdAlloc=new Zi,this.#l=new Zi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new We("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=cT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Yd(e,sq);this.#e.send(r)}else if(t==="protobuf"){let r=tf(e,dq);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new yn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new yn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new rl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new rl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=ea(JSON.parse(e.data),hq)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=ji(new Uint8Array(e.data),Sq)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Po(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Po(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return af.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new na(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new We("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var oa;var xq=w(()=>{if(typeof queueMicrotask<"u")oa=queueMicrotask;else{let e=Promise.resolve();oa=(t)=>{e.then(t)}}});class lT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function _q(e){let t=Lr(e.baton),r=Lr(e.base_url),o=bn(e.results,Xde);return{baton:t,baseUrl:r,results:o}}function Xde(e){let t=Ar(e.type);if(t==="ok")return{type:"ok",response:efe(kt(e.response))};else if(t==="error")return{type:"error",error:qi(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function efe(e){let t=Ar(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:uf(kt(e.result))};else if(t==="batch")return{type:"batch",result:ty(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:ny(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Bi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function Eq(e){let t=Lr(e.baton),r=Lr(e.base_url);return{baton:t,baseUrl:r}}var uT=w(()=>{_t();ol();oy()});var Iq,tfe,rfe,nfe,ofe,ife,sfe,kq;var dT=w(()=>{sy();Iq={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(tfe))}},tfe={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(rfe)}},2(e){return{type:"error",error:e.message(Yr)}}},rfe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(nfe)},3(e){return e.message(ofe)},4(e){return{type:"sequence"}},5(e){return e.message(ife)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(sfe)}},nfe={default(){return{type:"execute",result:Mi.default()}},1(e,t){t.result=e.message(Mi)}},ofe={default(){return{type:"batch",result:ul.default()}},1(e,t){t.result=e.message(ul)}},ife={default(){return{type:"describe",result:dl.default()}},1(e,t){t.result=e.message(dl)}},sfe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},kq={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var fT;var Aq=w(()=>{ol();VA();_t();Qr();uT();dT();oy();sy();fT=class fT extends sf{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new lT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(Eq,kq);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(ry,iy)}close(){this._setClosed(new We("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return ea(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return ji(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function Tq(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,afe)}function afe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,cf);else if(t.type==="batch")e.object("batch",t.batch,cl);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function $q(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,cl)}var pT=w(()=>{iT();Qr()});function Rq(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,cfe)}function cfe(e,t){if(t.type==="close")e.message(1,t,lfe);else if(t.type==="execute")e.message(2,t,ufe);else if(t.type==="batch")e.message(3,t,dfe);else if(t.type==="sequence")e.message(4,t,ffe);else if(t.type==="describe")e.message(5,t,pfe);else if(t.type==="store_sql")e.message(6,t,mfe);else if(t.type==="close_sql")e.message(7,t,hfe);else if(t.type==="get_autocommit")e.message(8,t,gfe);else throw Ke(t,"Impossible type of StreamRequest")}function lfe(e,t){}function ufe(e,t){e.message(1,t.stmt,lf)}function dfe(e,t){e.message(1,t.batch,ll)}function ffe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function pfe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function mfe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function hfe(e,t){e.int32(1,t.sqlId)}function gfe(e,t){}function Oq(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,ll)}var mT=w(()=>{aT();Qr()});function yfe(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Po(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function bfe(e,t){if(t==="json"){let r=await e.json();return ea(r,_q)}if(t==="protobuf"){let r=await e.arrayBuffer();return ji(new Uint8Array(r),Iq)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Sfe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Po(o);return new Xs(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new Xs(r,e.status)}return await e.body?.cancel(),new Xs(r,e.status)}var ly;var hT=w(()=>{_t();GA();QA();xq();rf();sl();ey();Qr();Aq();pT();mT();pT();mT();uT();dT();ly=class ly extends al{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Ui,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new Zi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new na(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,oa(()=>this.#u())}close(){this._setClosed(new We("Stream was manually closed"))}closeGracefully(){this.#l=!0,oa(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,oa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new xt("Stream is closed",this.#f);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),oa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new We("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>bfe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>yfe(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new fT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Sfe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,Tq,Rq)}#v(e,t){if(t.cursorPath===void 0)throw new yn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,$q,Oq)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Yd(t,o),s="application/json";else if(r==="protobuf")i=tf(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function wfe(e,t){let r=e;for(let o of vfe){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return gT}var vfe,gT,uy;var yT=w(()=>{_t();hT();vfe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],gT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};uy=class uy extends tl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=wfe(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(gT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=gT.version)return;else if(this._endpoint===void 0)throw new yn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new yn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new ly(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new We("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var Cq=w(()=>{_t()});function bT(e,t,r=2){if(typeof Li>"u")throw new Gd("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(cT.keys());else o=Array.from(wq.keys());let n=new Li(e,o);return new ay(n,t)}function ST(e,t,r,o,n=2){return new uy(e instanceof URL?e:new URL(e),t,r,o,n)}var dy=w(()=>{HA();cy();_t();yT();cy();HA();tT();Cq();sl();Yg();ey();yT();hT();cy();nT();_t()});class df{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(zo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Ni(this.#e)),c=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(c));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let f=d.query(u);return f.catch(()=>{return}),c=d,f}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let c=i.step();if(s!==void 0)c.condition(ut.ok(s));if(this.#t>=3)c.condition(ut.not(ut.isAutocommit(i)));let u=c.query(a);return u.catch(()=>{return}),s=c,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(pl(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Ni(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function fl(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Ni(e)),a=i,c=o.map((h)=>{let b=r.step().condition(ut.ok(a));if(t>=3)b.condition(ut.not(ut.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<c.length;h++)try{let b=await c[h];if(b===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(pl(b))}catch(b){if(b instanceof Wt)throw b;let y=st(b);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function zo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new of(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function pl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new Qc(t,r,o,n,i)}function st(e){if(e instanceof We){let t=Pq(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function Pq(e){if(e instanceof Wd&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof We?Pq(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof rl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Xs)return"SERVER_ERROR";else if(e instanceof yn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var wT=w(()=>{dy();gn();Yc()});class ml{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new zq,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class zq{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var xT=ge(function(J2e,Dq){function xfe(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function i(c){return new Promise(function(u,d){r.push({fn:c,resolve:u,reject:d}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(c){if(t>=e)return i(c);else return s(c)};return a}function _fe(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function Nq(e){return e.queue=0,e.map=_fe,e}Dq.exports=function(e){if(e)return Nq(xfe(e));else return Nq(function(t){return t()})}});function jq(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Fd(e.scheme,e.authority,e.path),r;try{r=bT(t,e.authToken)}catch(o){if(o instanceof Gd){let n=e.scheme==="wss"?"https":"http",i=Fd(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Hn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new Zq(r,t,e.authToken,e.intMode,e.concurrency)}class Zq{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=Bq.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=zo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return pl(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(zo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await fl(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(zo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await fl("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new Uq(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Efe&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=Lq}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=bT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new ml(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=Lq;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var Bq,Efe=60000,Lq=100,Uq;var qq=w(()=>{dy();gn();Hd();wT();Ug();Yc();Bq=$l(xT(),1);gn();Uq=class Uq extends df{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function Fq(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Hn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Fd(e.scheme,e.authority,e.path);return new Kq(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class Kq{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=ST(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=Mq.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=zo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return pl(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(zo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new ml(s,Jq).apply(o);let u=s.batch(!1);i=fl(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(zo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=fl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new Hq(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=ST(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var Mq,Jq=30,Hq;var Vq=w(()=>{dy();gn();Hd();wT();Ug();Yc();Mq=$l(xT(),1);gn();Hq=class Hq extends df{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new ml(e,Jq)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function hl(e){return Ife(Kd(e,!0))}function Ife(e){if(e.scheme==="wss"||e.scheme==="ws")return jq(e);else if(e.scheme==="https"||e.scheme==="http")return Fq(e);else return M4(e)}var _T=w(()=>{Hd();V4();qq();Vq();gn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var Re=w(()=>{F=Symbol.for("drizzle:entityKind")});var He;var Sn=w(()=>{Re();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var ff;var fy=w(()=>{Re();ff=class ff{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var gl=w(()=>{ir=Symbol.for("drizzle:Name")});var ET,Wq;var Gq=w(()=>{Re();gl();ET=class ET{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new Wq(e,this)}};Wq=class Wq{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function py(e,...t){return e(...t)}var IT=()=>{};function kT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var Qq,kfe,Yq;var Xq=w(()=>{Re();gl();Qq=class Qq{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new Yq(e,this.columns,this.nullsNotDistinctConfig,this.name)}};kfe=class kfe{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Qq(e,this.name)}};Yq=class Yq{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??kT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function eM(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function tM(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[c,u]=eM(e,o+1,!0);r.push(c),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[c,u]=tM(e,o+1);r.push(c),o=u;continue}let[s,a]=eM(e,o,!1);r.push(s),o=a}return[r,o]}function rM(e){let[t]=tM(e,1);return t}function AT(e){return`{${e.map((t)=>{if(Array.isArray(t))return AT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var nM=()=>{};var pf,yl,oM,Afe,iM,TT;var sM=w(()=>{fy();Sn();Re();Gq();IT();Xq();nM();pf=class pf extends ff{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new iM(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>py((n,i)=>{let s=new ET(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new oM(e,this.config)}};yl=class yl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=kT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};oM=class oM extends yl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Afe=class Afe{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};iM=class iM extends pf{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new TT(e,this.config,t)}};TT=class TT extends yl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=rM(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,TT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return AT(r)}}});function lM(e){return!!e&&typeof e==="function"&&aM in e&&e[aM]===!0}var Tfe,cM,aM,$fe,uM;var dM=w(()=>{Re();sM();Tfe=class Tfe extends pf{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new cM(e,this.config)}};cM=class cM extends yl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};aM=Symbol.for("drizzle:isPgEnum");$fe=class $fe extends pf{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new uM(e,this.config)}};uM=class uM extends yl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,mf;var vn=w(()=>{Re();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};mf=class mf extends dt{static[F]="WithSubquery"}});var fM="0.45.2";var pM=()=>{};var $T,RT,mM;var hM=w(()=>{IT();pM();mM={startActiveSpan(e,t){if(!$T)return t();if(!RT)RT=$T.trace.getTracer("drizzle-orm",fM);return py((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),$T,RT)}}});var ft;var No=w(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function Fi(e){return e[ir]}function ia(e){return`${e[my]??"public"}.${e[ir]}`}var my,hy,gM,OT,CT,hf,yM,Rfe,me;var sr=w(()=>{Re();gl();my=Symbol.for("drizzle:Schema"),hy=Symbol.for("drizzle:Columns"),gM=Symbol.for("drizzle:ExtraConfigColumns"),OT=Symbol.for("drizzle:OriginalName"),CT=Symbol.for("drizzle:BaseName"),hf=Symbol.for("drizzle:IsAlias"),yM=Symbol.for("drizzle:ExtraConfigBuilder"),Rfe=Symbol.for("drizzle:IsDrizzleTable");me=class me{static[F]="Table";static Symbol={Name:ir,Schema:my,OriginalName:OT,Columns:hy,ExtraConfigColumns:gM,BaseName:CT,IsAlias:hf,ExtraConfigBuilder:yM};[ir];[OT];[my];[hy];[gM];[CT];[hf]=!1;[Rfe]=!0;[yM]=void 0;constructor(e,t,r){this[ir]=this[OT]=e,this[my]=t,this[CT]=r}}});function PT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Cfe(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function bM(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new zt(e[0]));for(let[o,n]of t.entries())r.push(n,new zt(e[o+1]));return new xe(r)}function gf(e,t){return e.map((r)=>{if(oe(r,Ji)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Br)&&oe(r.value,Ji)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var Ofe,zt,xe,gy,SM,vM,rLe,Br,Ji,Pfe,Xr;var Qt=w(()=>{Re();dM();vn();hM();No();Sn();sr();Ofe=class Ofe{static[F]="FakePrimitiveParam"};zt=class zt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new xe([this])}};xe=class xe{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,me)){let r=t[me.Symbol.Schema];this.usedTables.push(r===void 0?t[me.Symbol.Name]:r+"."+t[me.Symbol.Name])}}static[F]="SQL";decoder=SM;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return mM.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return Cfe(e.map((u)=>{if(oe(u,zt))return{sql:u.value.join(""),params:[]};if(oe(u,gy))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new zt("(")];for(let[f,m]of u.entries())if(d.push(m),f<u.length-1)d.push(new zt(", "));return d.push(new zt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,xe))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,me)){let d=u[me.Symbol.Schema],f=u[me.Symbol.Name];return{sql:d===void 0||u[hf]?n(f):n(d)+"."+n(f),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let f=u.table[me.Symbol.Schema];return{sql:u.table[hf]||f===void 0?n(u.table[me.Symbol.Name])+"."+n(d):n(f)+"."+n(u.table[me.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,Xr)){let d=u[ft].schema,f=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(f):n(d)+"."+n(f),params:[]}}if(oe(u,Br)){if(oe(u.value,Ji))return{sql:i(c.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,xe))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let f=["none"];if(s)f=[s(u.encoder)];return{sql:i(c.value++,d),params:[d],typings:f}}if(oe(u,Ji))return{sql:i(c.value++,u),params:[u],typings:["none"]};if(oe(u,xe.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new zt("("),u._.sql,new zt(") "),new gy(u._.alias)],r)}if(lM(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(PT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new zt("("),u.getSQL(),new zt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(c.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new xe.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};gy=class gy{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new xe([this])}};SM={mapFromDriverValue:(e)=>e},vM={mapToDriverValue:(e)=>e},rLe={...SM,...vM};Br=class Br{constructor(e,t=vM){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new xe([this])}};((e)=>{function t(){return new xe([])}e.empty=t;function r(c){return new xe(c)}e.fromList=r;function o(c){return new xe([new zt(c)])}e.raw=o;function n(c,u){let d=[];for(let[f,m]of c.entries()){if(f>0&&u!==void 0)d.push(u);d.push(m)}return new xe(d)}e.join=n;function i(c){return new gy(c)}e.identifier=i;function s(c){return new Ji(c)}e.placeholder=s;function a(c,u){return new Br(c,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(xe||(xe={}));Ji=class Ji{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new xe([this])}};Pfe=Symbol.for("drizzle:IsDrizzleView");Xr=class Xr{static[F]="View";[ft];[Pfe]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new xe([this])}};He.prototype.getSQL=function(){return new xe([this])};me.prototype.getSQL=function(){return new xe([this])};dt.prototype.getSQL=function(){return new xe([this])}});function zT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},c)=>{let u;if(oe(a,He))u=a;else if(oe(a,xe))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[f,m]of s.entries())if(f<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[c],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?Fi(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==Fi(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function en(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,xe)||oe(n,xe.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,me))r.push(...en(n[me.Symbol.Columns],i));else r.push(...en(n,i));return r},[])}function yf(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function yy(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,xe)||oe(n,He))return[o,n];else return[o,new Br(n,e[me.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function wM(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function by(e){return e[me.Symbol.Columns]}function bf(e){return oe(e,dt)?e._.alias:oe(e,Xr)?e[ft].name:oe(e,xe)?void 0:e[me.Symbol.IsAlias]?e[me.Symbol.Name]:e[me.Symbol.BaseName]}function Qn(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function xM(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var NT;var br=w(()=>{Sn();Re();Qt();vn();sr();No();NT=typeof TextDecoder>"u"?null:new TextDecoder});var _M,DT,LT;var Sy=w(()=>{Re();_M=class _M{static[F]="ConsoleLogWriter";write(e){console.log(e)}};DT=class DT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new _M}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};LT=class LT{static[F]="NoopLogger";logQuery(){}}});var EM,IM,BT;var kM=w(()=>{Re();sr();EM=Symbol.for("drizzle:PgInlineForeignKeys"),IM=Symbol.for("drizzle:EnableRLS");BT=class BT extends me{static[F]="PgTable";static Symbol=Object.assign({},me.Symbol,{InlineForeignKeys:EM,EnableRLS:IM});[EM]=[];[IM]=!1;[me.Symbol.ExtraConfigBuilder]=void 0;[me.Symbol.ExtraConfigColumns]={}}});var jT,AM;var TM=w(()=>{Re();kM();jT=class jT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new AM(e,this.columns,this.name)}};AM=class AM{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[BT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Tr(e,t){if(bM(t)&&!PT(e)&&!oe(e,Br)&&!oe(e,Ji)&&!oe(e,He)&&!oe(e,me)&&!oe(e,Xr))return new Br(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new xe(t);return new xe([new zt("("),C.join(t,new zt(" and ")),new zt(")")])}function tn(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new xe(t);return new xe([new zt("("),C.join(t,new zt(" or ")),new zt(")")])}function RM(e){return C`not ${e}`}function Hi(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>Tr(r,e))}`}return C`${e} in ${Tr(t,e)}`}function vy(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>Tr(r,e))}`}return C`${e} not in ${Tr(t,e)}`}function jr(e){return C`${e} is null`}function PM(e){return C`${e} is not null`}function wy(e){return C`exists ${e}`}function Vi(e){return C`not exists ${e}`}function zM(e,t,r){return C`${e} between ${Tr(t,e)} and ${Tr(r,e)}`}function NM(e,t,r){return C`${e} not between ${Tr(t,e)} and ${Tr(r,e)}`}function DM(e,t){return C`${e} like ${t}`}function LM(e,t){return C`${e} not like ${t}`}function BM(e,t){return C`${e} ilike ${t}`}function jM(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${Tr(t,e)}`,$M=(e,t)=>C`${e} <> ${Tr(t,e)}`,wn=(e,t)=>C`${e} > ${Tr(t,e)}`,OM=(e,t)=>C`${e} >= ${Tr(t,e)}`,CM=(e,t)=>C`${e} < ${Tr(t,e)}`,Ki=(e,t)=>C`${e} <= ${Tr(t,e)}`;var ZM=w(()=>{Sn();Re();sr();Qt()});function Do(e){return C`${e} asc`}function sa(e){return C`${e} desc`}var UM=w(()=>{Qt()});var ZT=w(()=>{ZM();UM()});function MM(){return{and:tt,between:zM,eq:je,exists:wy,gt:wn,gte:OM,ilike:BM,inArray:Hi,isNull:jr,isNotNull:PM,like:DM,lt:CM,lte:Ki,ne:$M,not:RM,notBetween:NM,notExists:Vi,notLike:LM,notIlike:jM,notInArray:vy,or:tn,sql:C}}function FM(){return{sql:C,asc:Do,desc:sa}}function JM(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,me))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,me)){let a=ia(s),c=o[a];r[a]=i,n[i]={tsName:i,dbName:s[me.Symbol.Name],schema:s[me.Symbol.Schema],columns:s[me.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let d of Object.values(s[me.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[me.Symbol.ExtraConfigBuilder]?.(s[me.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,jT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,qM)){let a=ia(s.table),c=r[a],u=s.config(t(s.table)),d;for(let[f,m]of Object.entries(u))if(c){let h=n[c];if(h.relations[f]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[f]=m}}return{tables:n,tableNamesMap:r}}function zfe(e){return function(r,o){return new Wi(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Nfe(e){return function(r,o){return new Sf(e,r,o)}}function KM(e,t,r){if(oe(r,Wi)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ia(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[me.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ia(i)];if(!s)throw Error(`Table "${i[me.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[me.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],Wi)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function HM(e){return{one:zfe(e),many:Nfe(e)}}function xy(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let c=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(c,Wi)?d&&xy(e,e[a.relationTableTsKey],d,a.selection,n):d.map((f)=>xy(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,xe))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=c===null?null:d.mapFromDriverValue(c)}return i}var UT,qM,Wi,Sf;var vf=w(()=>{sr();Sn();Re();TM();ZT();Qt();UT=class UT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[me.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};qM=class qM{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};Wi=class Wi extends UT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new Wi(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Sf=class Sf extends UT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Sf(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function wf(e,t){return new Proxy(e,new aa(t,!1))}function Yn(e,t){return new Proxy(e,new bl(new Proxy(e.table,new aa(t,!1))))}function qT(e,t){return new xe.Aliased(xf(e.sql,t),e.fieldAlias)}function xf(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return Yn(r,t);if(oe(r,xe))return xf(r,t);if(oe(r,xe.Aliased))return qT(r,t);return r}))}var bl,aa,Dfe;var _f=w(()=>{Sn();Re();Qt();sr();No();bl=class bl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};aa=class aa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===me.Symbol.IsAlias)return!0;if(t===me.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===me.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===me.Symbol.Columns){let o=e[me.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new bl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new bl(new Proxy(e,this)));return r}};Dfe=class Dfe{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return wf(e.sourceTable,this.alias);return e[t]}}});var at;var ca=w(()=>{_f();Sn();Re();Qt();vn();No();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,Xr)?e[ft].selectedFields:e)[t];if(oe(o,xe.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,xe)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new bl(new Proxy(o.table,new aa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var Sr;var Lo=w(()=>{Re();Sr=class Sr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var MT,VM;var FT=w(()=>{Re();gl();MT=class MT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new VM(e,this)}};VM=class VM{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var WM,Lfe,GM;var KT=w(()=>{Re();gl();WM=class WM{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new GM(e,this.columns,this.name)}};Lfe=class Lfe{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new WM(e,this.name)}};GM=class GM{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??JT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Bt,gt;var Gi=w(()=>{fy();Sn();Re();FT();KT();Bt=class Bt extends ff{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new MT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};gt=class gt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function nF(e,t){let{name:r,config:o}=Qn(e,t);if(o?.mode==="json")return new XM(r);if(o?.mode==="bigint")return new QM(r);return new tF(r)}var QM,YM,XM,eF,tF,rF;var HT=w(()=>{Re();br();Gi();QM=class QM extends Bt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new YM(e,this.config)}};YM=class YM extends gt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(NT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};XM=class XM extends Bt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new eF(e,this.config)}};eF=class eF extends gt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(NT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};tF=class tF extends Bt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new rF(e,this.config)}};rF=class rF extends gt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function sF(e){return(t,r)=>{let{name:o,config:n}=Qn(t,r);return new oF(o,n,e)}}var oF,iF;var VT=w(()=>{Re();br();Gi();oF=class oF extends Bt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new iF(e,this.config)}};iF=class iF extends gt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=Qn(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new lF(r,o.mode);if(o?.mode==="boolean")return new dF(r,o.mode);return new aF(r)}var _y,Ey,aF,cF,lF,uF,dF,fF;var WT=w(()=>{Re();Qt();br();Gi();_y=class _y extends Bt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};Ey=class Ey extends gt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};aF=class aF extends _y{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new cF(e,this.config)}};cF=class cF extends Ey{static[F]="SQLiteInteger"};lF=class lF extends _y{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new uF(e,this.config)}};uF=class uF extends Ey{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};dF=class dF extends _y{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new fF(e,this.config)}};fF=class fF extends Ey{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function SF(e,t){let{name:r,config:o}=Qn(e,t),n=o?.mode;return n==="number"?new hF(r):n==="bigint"?new yF(r):new pF(r)}var pF,mF,hF,gF,yF,bF;var GT=w(()=>{Re();br();Gi();pF=class pF extends Bt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new mF(e,this.config)}};mF=class mF extends gt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};hF=class hF extends Bt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new gF(e,this.config)}};gF=class gF extends gt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};yF=class yF extends Bt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new bF(e,this.config)}};bF=class bF extends gt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function xF(e){return new vF(e??"")}var vF,wF;var QT=w(()=>{Re();Gi();vF=class vF extends Bt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new wF(e,this.config)}};wF=class wF extends gt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function pt(e,t={}){let{name:r,config:o}=Qn(e,t);if(o.mode==="json")return new IF(r);return new _F(r,o)}var _F,EF,IF,kF;var YT=w(()=>{Re();br();Gi();_F=class _F extends Bt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new EF(e,this.config)}};EF=class EF extends gt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};IF=class IF extends Bt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new kF(e,this.config)}};kF=class kF extends gt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function AF(){return{blob:nF,customType:sF,integer:ar,numeric:SF,real:xF,text:pt}}var TF=w(()=>{HT();VT();WT();GT();QT();YT()});function Bfe(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(AF()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let f=d;f.setName(u);let m=f.build(i);return i[XT].push(...f.buildForeignKeys(m,i)),[u,m]})),c=Object.assign(i,a);if(c[me.Symbol.Columns]=a,c[me.Symbol.ExtraConfigColumns]=a,r)c[At.Symbol.ExtraConfigBuilder]=r;return c}var XT,At,Ef=(e,t,r)=>Bfe(e,t,r);var Bo=w(()=>{Re();sr();TF();XT=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends me{static[F]="SQLiteTable";static Symbol=Object.assign({},me.Symbol,{InlineForeignKeys:XT});[me.Symbol.Columns];[XT]=[];[me.Symbol.ExtraConfigBuilder]=void 0}});var jfe,$F;var RF=w(()=>{Re();jfe=class jfe{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new $F(e,this)}};$F=class $F{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function jo(e){return new OF(e,!1)}var OF,CF,PF;var zF=w(()=>{Re();OF=class OF{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new CF(this.name,e,this.unique)}};CF=class CF{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new PF(this.config,e)}};PF=class PF{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Zfe,NF;var DF=w(()=>{Re();Bo();Zfe=class Zfe{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new NF(e,this.columns,this.name)}};NF=class NF{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function xn(e){if(oe(e,At))return[`${e[me.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,xe))return e.usedTables??[];return[]}var Sl=w(()=>{Re();Qt();vn();sr();Bo()});var Iy;var LF=w(()=>{Re();Lo();ca();Bo();sr();br();Sl();Iy=class Iy extends Sr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[me.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=en(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:xn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function Ufe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function qfe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Mfe(e){return e}var e$;var BF=w(()=>{Re();sr();e$=class e${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Ufe:e==="camelCase"?qfe:Mfe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[me.Symbol.Schema]??"public",r=e.table[me.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[me.Symbol.Schema]??"public",r=e[me.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[me.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var vl,Zo,t$;var ky=w(()=>{Re();vl=class vl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Zo=class Zo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
375
375
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Zo),r)this.cause=r}};t$=class t$ extends vl{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var jF=()=>{};var ZF=()=>{};var UF=w(()=>{jF();ZF()});var r$=w(()=>{ZT();UF();Qt()});var n$=w(()=>{HT();Gi();VT();WT();GT();QT();YT()});var Uo;var If=w(()=>{Re();Qt();Uo=class Uo extends Xr{static[F]="SQLiteViewBase"}});var wl,o$,i$;var Ay=w(()=>{_f();BF();Sn();Re();ky();vf();r$();Qt();n$();Bo();vn();sr();br();No();If();wl=class wl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new e$(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${c}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[me.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],c=a.onUpdateFn?.(),u=t[i]??(oe(c,xe)?c:C.param(c,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:c}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),f=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=r?C` where ${r}`:void 0,y=this.buildOrderBy(c),S=this.buildLimit(a);return C`${u}update ${e} set ${d}${f}${m}${b}${h}${y}${S}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,xe.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,xe.Aliased)||oe(n,xe)){let a=oe(n,xe.Aliased)?n.sql:n;if(t)s.push(new xe(a.queryChunks.map((c)=>{if(oe(c,He))return C.identifier(this.casing.getColumnCasing(c));return c})));else s.push(a);if(oe(n,xe.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,He)){let a=n.table[me.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,dt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let c=a[0][1],u=oe(c,xe)?c.decoder:oe(c,He)?{mapFromDriverValue:(d)=>c.mapFromDriverValue(d)}:c.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,At)){let s=n[At.Symbol.Name],a=n[At.Symbol.Schema],c=n[At.Symbol.OriginalName],u=s===c?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(c)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,me)&&e[me.Symbol.IsAlias])return C`${C`${C.identifier(e[me.Symbol.Schema]??"")}.`.if(e[me.Symbol.Schema])}${C.identifier(e[me.Symbol.OriginalName])} ${C.identifier(e[me.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:c,limit:u,offset:d,distinct:f,setOperators:m}){let h=r??en(t);for(let R of h)if(oe(R.field,He)&&Fi(R.field.table)!==(oe(i,dt)?i._.alias:oe(i,Uo)?i[ft].name:oe(i,xe)?void 0:Fi(i))&&!((B)=>s?.some(({alias:I})=>I===(B[me.Symbol.IsAlias]?Fi(B):B[me.Symbol.BaseName])))(R.field.table)){let B=Fi(R.field.table);throw Error(`Your "${R.path.join("->")}" field references a column "${B}"."${R.field.name}", but the table "${B}" is not part of the query! Did you forget to join it?`)}let b=!s||s.length===0,y=this.buildWithCTE(e),S=f?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:b}),_=this.buildFromTable(i),A=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,z=[];if(c){for(let[R,B]of c.entries())if(z.push(B),R<c.length-1)z.push(C`, `)}let K=z.length>0?C` group by ${C.join(z)}`:void 0,P=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${S} ${x} from ${_}${A}${O}${K}${L}${P}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,c=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let b of i)if(oe(b,gt))h.push(C.identifier(b.name));else if(oe(b,xe)){for(let y=0;y<b.queryChunks.length;y++){let S=b.queryChunks[y];if(oe(S,gt))b.queryChunks[y]=C.identifier(this.casing.getColumnCasing(S))}h.push(C`${b}`)}else h.push(C`${b}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,f=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${f}${c}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[me.Symbol.Columns],c=Object.entries(a).filter(([b,y])=>!y.shouldDisableInsert()),u=c.map(([,b])=>C.identifier(this.casing.getColumnCasing(b)));if(i){let b=t;if(oe(b,xe))s.push(b);else s.push(b.getSQL())}else{let b=t;s.push(C.raw("values "));for(let[y,S]of b.entries()){let x=[];for(let[_,A]of c){let O=S[_];if(O===void 0||oe(O,Br)&&O.value===void 0){let L;if(A.default!==null&&A.default!==void 0)L=oe(A.default,xe)?A.default:C.param(A.default,A);else if(A.defaultFn!==void 0){let z=A.defaultFn();L=oe(z,xe)?z:C.param(z,A)}else if(!A.default&&A.onUpdateFn!==void 0){let z=A.onUpdateFn();L=oe(z,xe)?z:C.param(z,A)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<b.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),f=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${f}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let u=[],d,f,m=[],h,b=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:Yn(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(n.columns).map(([z,K])=>[z,Yn(K,s)]));if(i.where){let z=typeof i.where==="function"?i.where(S,MM()):i.where;h=z&&xf(z,s)}let x=[],_=[];if(i.columns){let z=!1;for(let[K,P]of Object.entries(i.columns)){if(P===void 0)continue;if(K in n.columns){if(!z&&P===!0)z=!0;_.push(K)}}if(_.length>0)_=z?_.filter((K)=>i.columns?.[K]===!0):Object.keys(n.columns).filter((K)=>!_.includes(K))}else _=Object.keys(n.columns);for(let z of _){let K=n.columns[z];x.push({tsKey:z,value:K})}let A=[];if(i.with)A=Object.entries(i.with).filter((z)=>!!z[1]).map(([z,K])=>({tsKey:z,queryConfig:K,relation:n.relations[z]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(S,{sql:C}):i.extras;for(let[z,K]of Object.entries(O))x.push({tsKey:z,value:qT(K,s)})}for(let{tsKey:z,value:K}of x)u.push({dbKey:oe(K,xe.Aliased)?K.fieldAlias:n.columns[z].name,tsKey:z,field:oe(K,He)?Yn(K,s):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(S,FM()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((z)=>{if(oe(z,He))return Yn(z,s);return xf(z,s)}),d=i.limit,f=i.offset;for(let{tsKey:z,queryConfig:K,relation:P}of A){let W=KM(t,r,P),ee=ia(P.referencedTable),j=r[ee],R=`${s}_${z}`,B=tt(...W.fields.map((k,M)=>je(Yn(W.references[M],R),Yn(k,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(P,Wi)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:R,joinOn:B,nestedQueryRelation:P}),T=C`(${I.sql})`.as(z);u.push({dbKey:z,tsKey:z,field:T,relationTableTsKey:j,isJson:!0,selection:I.selection})}}if(u.length===0)throw new vl({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(c,h),a){let S=C`json_array(${C.join(u.map(({field:A})=>oe(A,gt)?C.identifier(this.casing.getColumnCasing(A)):oe(A,xe.Aliased)?A.sql:A),C`, `)})`;if(oe(a,Sf))S=C`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||f!==void 0||m.length>0)y=this.buildSelectQuery({table:wf(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:f,orderBy:m,setOperators:[]}),h=void 0,d=void 0,f=void 0,m=void 0;else y=wf(o,s);y=this.buildSelectQuery({table:oe(y,At)?y:new dt(y,{},s),fields:{},fieldsFlat:x.map(({field:A})=>({path:[],field:oe(A,He)?Yn(A,s):A})),joins:b,where:h,limit:d,offset:f,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:wf(o,s),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:oe(S,He)?Yn(S,s):S})),joins:b,where:h,limit:d,offset:f,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};o$=class o$ extends wl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
|
|
376
376
|
CREATE TABLE IF NOT EXISTS ${C.identifier(o)} (
|
|
377
377
|
id SERIAL PRIMARY KEY,
|
|
@@ -384,7 +384,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
384
384
|
hash text NOT NULL,
|
|
385
385
|
created_at numeric
|
|
386
386
|
)
|
|
387
|
-
`;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let u of c.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var s$;var qF=w(()=>{Re();s$=class s${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ty(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!yf(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var _n,MF,a$,Ffe=()=>({union:Jfe,unionAll:Kfe,intersect:Hfe,except:Vfe}),Jfe,Kfe,Hfe,Vfe;var c$=w(()=>{Re();qF();Lo();ca();Qt();vn();sr();br();No();Sl();If();_n=class _n{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,dt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Uo))r=e[ft].selectedFields;else if(oe(e,xe))r={};else r=by(e);return new a$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};MF=class MF extends s${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=bf(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of xn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=bf(t);for(let i of xn(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,xe)){let i=oe(t,dt)?t._.selectedFields:oe(t,Xr)?t[ft].selectedFields:t[me.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(Ffe()):r;if(!yf(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...xn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...xn(r.table));return new Proxy(new dt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};a$=class a$ extends MF{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=en(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};wM(a$,[Sr]);Jfe=Ty("union",!1),Kfe=Ty("union",!0),Hfe=Ty("intersect",!1),Vfe=Ty("except",!1)});var la;var $y=w(()=>{Re();ca();Ay();vn();c$();la=class la{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,wl)?e:void 0,this.dialectConfig=oe(e,wl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new mf(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new _n({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new _n({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new _n({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new _n({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new o$(this.dialectConfig);return this.dialect}}});var Ry,l$;var FF=w(()=>{Re();Lo();Qt();Bo();sr();br();Sl();$y();Ry=class Ry{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[me.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,xe)?s:new Br(s,n[i])}return o});return new l$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new la):e;if(!oe(t,xe)&&!yf(this.table[hy],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new l$(this.table,t,this.session,this.dialect,this.withList,!0)}};l$=class l$ extends Sr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=en(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,yy(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:xn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Oy,JF;var KF=w(()=>{Re();Lo();ca();Bo();vn();sr();br();No();Sl();If();Oy=class Oy{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new JF(this.table,yy(this.table,e),this.session,this.dialect,this.withList)}};JF=class JF extends Sr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=bf(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,At)?t[me.Symbol.Columns]:oe(t,dt)?t._.selectedFields:oe(t,Uo)?t[ft].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[me.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[me.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=en(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:xn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var u$=w(()=>{LF();FF();$y();c$();KF()});var kf;var HF=w(()=>{Re();Qt();kf=class kf extends xe{constructor(e){super(kf.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=kf.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var f$,Cy,d$;var VF=w(()=>{Re();Lo();vf();f$=class f${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Cy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Cy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Cy=class Cy extends Sr{constructor(e,t,r,o,n,i,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=c}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>xy(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};d$=class d$ extends Cy{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var xl;var WF=w(()=>{Re();Lo();xl=class xl extends Sr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Af;var Py=w(()=>{Re();ca();Qt();u$();vn();HF();VF();WF();Af=class Af{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new f$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new la(r.dialect));return new Proxy(new mf(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new kf({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new _n({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new _n({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Oy(a,t.session,t.dialect,e)}function i(a){return new Ry(a,t.session,t.dialect,e)}function s(a){return new Iy(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new _n({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new _n({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Oy(e,this.session,this.dialect)}$cache;insert(e){return new Ry(e,this.session,this.dialect)}delete(e){return new Iy(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function p$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var GF,Tf;var m$=w(()=>{Re();GF=class GF{static[F]="Cache"};Tf=class Tf extends GF{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var QF=w(()=>{m$()});function zy(e,t){return new Proxy(e,new aa(t,!1))}var YF=w(()=>{_f()});var XF,h$,g$,y$;var b$=w(()=>{m$();Re();ky();Lo();Py();XF=class XF extends Sr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};h$=class h${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,Tf)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Zo(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Zo(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Zo(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Zo(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await p$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Zo(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await p$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Zo(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new XF(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};g$=class g${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new vl({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};y$=class y$ extends Af{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new t$}}});var S$,Wfe,Gfe,Ny;var e3=w(()=>{Re();ca();br();$y();Bo();If();S$=class S${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};Wfe=class Wfe extends S${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new la);let t=new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Ny({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};Gfe=class Gfe extends S${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=by(Ef(e,t))}existing(){return new Proxy(new Ny({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Ny({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Ny=class Ny extends Uo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var Dy=w(()=>{YF();RF();n$();Py();Ay();FT();zF();DF();u$();b$();Bo();KT();Sl();e3()});function t3(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Ly(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var By,v$,r3;var w$=w(()=>{QF();Re();Sy();Qt();Dy();b$();br();By=class By extends g${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new LT,this.cache=o.cache??new Tf}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new r3(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new By(this.client,this.dialect,this.schema,this.options,r),n=new v$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};v$=class v$ extends y${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new v$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};r3=class r3 extends h${constructor(e,t,r,o,n,i,s,a,c,u,d){super("async",c,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=gf(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let c=gf(o.params,e??{});return r.logQuery(o.sql,c),await this.queryWithCache(o.sql,c,async()=>{let u={sql:o.sql,args:c};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>t3(r));if(this.customResultMapper)return this.customResultMapper(e,Ly);return e.map((r)=>zT(this.fields,Array.prototype.slice.call(r).map((o)=>Ly(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let c=gf(o.params,e??{});return r.logQuery(o.sql,c),await this.queryWithCache(o.sql,c,async()=>{let u={sql:o.sql,args:c};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return t3(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Ly);return zT(this.fields,Array.prototype.slice.call(r).map((o)=>Ly(o)),this.joinsNotNullableMap)}async values(e){let t=gf(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function _l(e,t={}){let r=new i$({casing:t.casing}),o;if(t.logger===!0)o=new DT;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=JM(t.schema,HM);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new By(e,r,n,{logger:o,cache:t.cache},void 0),s=new n3("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var n3;var o3=w(()=>{Re();Sy();vf();Py();Ay();w$();n3=class n3 extends Af{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function jy(...e){if(typeof e[0]==="string"){let t=hl({url:e[0]});return _l(t,e[1])}if(xM(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return _l(r,o);let n=typeof t==="string"?hl({url:t}):hl(t);return _l(n,o)}return _l(e[0],e[1])}var i3=w(()=>{_T();br();o3();((e)=>{function t(r){return _l({},r)}e.mock=t})(jy||(jy={}))});var s3=w(()=>{i3();w$()});function Qfe(){return new Promise((e)=>setTimeout(e,0))}function Xfe(){if(x$)return;x$=!0,setTimeout(()=>{x$=!1,_$=performance.now()},0)}async function $f(e=Yfe){if(Xfe(),performance.now()-_$<e)return;await Qfe(),_$=performance.now()}var Yfe=50,_$,x$=!1;var a3=w(()=>{_$=performance.now()});function c3(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function npe(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Zy(e,t){let r=Date.now()+(t.budgetMs??epe),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!npe(i))throw i;await t.afterRefusal?.();let s=Math.min(tpe*2**(n-1),rpe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function E$(e,t={}){let r=hl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(f,m){return await $f(),Zy(()=>typeof f==="string"?s(f,m):s(f),u)}r.execute=d,r.batch=async(f,m)=>(await $f(),Zy(()=>a(f,m),u)),r.migrate=async(f)=>(await $f(),Zy(()=>c(f),u)),r.transaction=async(f)=>(await $f(),Zy(()=>o(f),u))}return r}function Uy(e){let{url:t,schema:r}=e,o=c3(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?E$({url:t,authToken:o},n):E$({url:t},n);return{db:jy(i,{schema:r}),client:i,url:t}}async function qy(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var epe=5000,tpe=5,rpe=40;var I$=w(()=>{_T();s3();a3()});var l3=w(()=>{BA();I$()});var k$=w(()=>{I$();l3()});var A$=w(()=>{_f();fy();Sn();Re();ky();Sy();Lo();vf();r$();vn();sr();br();No()});var Y,qe;var T$=w(()=>{Dy();A$();Ud();Y=Ef("job_queue",{id:pt("id").primaryKey().$defaultFn(()=>$o()),type:pt("type").notNull(),data:pt("data").notNull(),result:pt("result",{mode:"json"}),progress:pt("progress",{mode:"json"}).$type(),source:pt("source"),metadata:pt("metadata",{mode:"json"}).$type().notNull(),status:pt("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:pt("lastError"),lastErrorPublic:pt("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:pt("attemptId"),workerSlotId:pt("workerSlotId"),workerSessionId:pt("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:pt("brainVersion"),brainVersionSortKey:pt("brainVersionSortKey")},(e)=>({queueReadyIdx:jo("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:jo("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:jo("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:jo("idx_job_queue_source").on(e.source),rootJobIdx:jo("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:jo("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),qe=Ef("job_worker_sessions",{slotId:pt("slotId").primaryKey(),sessionId:pt("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:pt("brainVersion"),brainVersionSortKey:pt("brainVersionSortKey"),stableSlotId:pt("stableSlotId")},(e)=>({heartbeatIdx:jo("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:jo("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function u3(e){return Uy({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:qe},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var d3=w(()=>{k$();T$()});class $${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class R${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class O${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=ope.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var ope;var f3=w(()=>{he();Ro();ope=l.looseObject({deduplicationKey:l.string().optional()})});function h3(e){return`${String(e.length).padStart(2,"0")}${e}`}function spe(e){return ipe.test(e)?`0${h3(e)}`:`1${e}`}function Rf(e){let t=p3.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(h3).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(spe).join("!")}`}var p3,ipe,m3;var C$=w(()=>{he();p3=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,ipe=/^\d+$/u,m3=l.string().regex(p3,"Brain version must be a semver version")});function g3(e){return JSON.stringify(new _c(e).toJSON())}class P${db;transactionClient;databaseUrl;logger;deduplicator=new O$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??ape}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return dpe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,c=!0;if(!o.closed)try{await o.rollback()}catch(u){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},u=async()=>{await c(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),f=this.deduplicator.findDuplicate(d,a,i);if(!f)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,f.id,o),{kind:"skipped",jobId:f.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,f.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.id}}await c();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",g3("cancelled"),m,m,f.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=Rf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?Rf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(cpe*2**(o-1),lpe),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ge(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=zi,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?Rf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(qe).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:qe.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=zi){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(qe).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(qe.slotId,e),je(qe.sessionId,t))).returning({slotId:qe.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,qe.slotId),je(Y.workerSessionId,qe.sessionId),je(Y.status,Oe.PROCESSING),wn(Y.leaseExpiresAt,e)));await this.db.delete(qe).where(tt(Ki(qe.expiresAt,e-t),Vi(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(qe).where(tt(je(qe.slotId,e),je(qe.sessionId,t))).returning({slotId:qe.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,c=Math.min(1000*2**i.retryCount,60000),u=s?o+c:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:LI(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new _c("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),tn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),jr(Y.attemptId),jr(Y.workerSlotId),jr(Y.workerSessionId),jr(Y.leaseExpiresAt),jr(Y.attemptHeartbeatAt),jr(Y.progress),jr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(Do(Y.createdAt),Do(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(sa(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${qe.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${qe.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${qe.heartbeatAt})`}).from(qe)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],c=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=upe.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(Do(Y.runtimeUpdatedAt),Do(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(tn(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),Ki(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=tn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,Hi(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(sa(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Hi(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(sa(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,Hi(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(sa(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:c}=e,u=c?this.brainVersionGate(c,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:qe.slotId}).from(qe).where(tt(je(qe.slotId,o),je(qe.sessionId,n),wn(qe.expiresAt,t))),f=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:qe.slotId}).from(qe).where(tt(je(qe.slotId,Y.workerSlotId),je(qe.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),tn(jr(Y.attemptId),Vi(m),Ki(Y.leaseExpiresAt,t))),b=zy(Y,"running"),y=this.db.select({id:b.id}).from(b).where(tt(je(b.type,Y.type),je(b.status,Oe.PROCESSING),wn(b.leaseExpiresAt,t),C`${b.id} <> ${Y.id}`)),S=a.length===0?void 0:tn(vy(Y.type,[...a]),Vi(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(Hi(Y.type,s),S,u.admissible,tn(tt(je(Y.status,Oe.PENDING),Ki(Y.scheduledFor,t)),h))).orderBy(Do(Y.priority),Do(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${g3("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(Hi(Y.id,_),wy(d),f,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=zy(qe,"claimer"),n=zy(qe,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),wn(n.expiresAt,r),tn(wn(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),wn(n.slotId,o.slotId)))));return Vi(i)}brainVersionGate(e,t){let r=Rf(e),o=this.db.select({slotId:qe.slotId}).from(qe).where(tt(wn(qe.expiresAt,t),wn(qe.brainVersionSortKey,r)));return{admissible:tn(jr(Y.brainVersionSortKey),Ki(Y.brainVersionSortKey,r)),noNewerWorker:Vi(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),jr(Y.attemptId),tn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var ape=2000,cpe=5,lpe=40,upe,dpe;var y3=w(()=>{A$();Dy();T$();Vt();he();Ro();Md();f3();C$();upe=l.number().int().min(0).max(1000),dpe=new R$});import{AsyncLocalStorage as fpe}from"async_hooks";class Of{storage=new fpe;static createFresh(){return new Of}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=wi.parse(e),n=ppe(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function ppe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var z$=w(()=>{Vt()});class Cf{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${$o()}`;directWorkerSessionId=$o();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Cf(e,t??kr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:m3.parse(e.brainVersion);let{db:o,client:n,url:i}=u3(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Of.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new $$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new P$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await qy(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=$o(),c=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,c,o),d=o?.metadata??{operationType:"data_processing"},{provenance:f,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:c,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},b,y=()=>{b?.rollback(),b=void 0};try{let S=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{b=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(b?.commit(),b=void 0,S.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:S.jobId});else if(S.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:S.jobId});else{if(S.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:S.replacedJobId});this.logger.debug("Job enqueued",{id:S.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return S.jobId}catch(S){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ge(S)}),S}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,c=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return wi.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:$o(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=zi){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=zi){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?i??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var b3=w(()=>{Ud();BA();Md();Ro();k$();d3();y3();Vt();z$();C$()});var N$=()=>{};var S3=w(()=>{Ud();Ro();Md();Ro();N$();z$()});var v3=w(()=>{Ro();N$()});var rqe;var w3=w(()=>{he();qd();Ro();rqe=l.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},l.record(l.string(),l.unknown()))});var iqe;var x3=w(()=>{he();iqe=l.record(l.string(),l.unknown())});var _3=w(()=>{Vt();Ud()});var E3=w(()=>{b3();S3();v3();w3();x3();Md();Ro();qd();_3()});var D$={};Zt(D$,{LEGACY_PROJECTION_JOB_TYPES:()=>k3,LEGACY_PROJECTION_RETIREMENT_REASON:()=>T3,legacyProjectionJobTypeSchema:()=>A3,retireLegacyProjectionJob:()=>_pe});import{existsSync as vpe}from"fs";import{resolve as wpe}from"path";function I3(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function xpe(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function _pe(e){let t=wpe(e.databasePath);if(!vpe(t))throw Error(`Job database does not exist: ${t}`);let r=A3.parse(e.jobType),o=Cf.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(xpe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:I3(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:T3,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:I3(s),retired:!0}}finally{o.close()}}var k3,A3,T3="Retired legacy projection job superseded by scheduler-owned projections";var L$=w(()=>{E3();he();k3=["conversation-memory:project","skill:project","swot:derive","topic:project"],A3=l.enum(k3)});function jt(e,t,r,o,n){return R3.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function z3(e){return Jy.parse(structuredClone(Tpe[e]))}function Ky(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function j$(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),B$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:c.ok})}catch(c){return B$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:Rpe(c)})}finally{clearTimeout(a)}}async function N3(e,t){let r=Jy.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${My(c)}`}if(!n)for(let c of r.phases)try{let u=O3.parse(await t.executePhase(c,i));if(o.push(u),!u.success){n=`${c.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=My(u);o.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:d}),n=`${c.id}: ${d}`;break}}finally{try{if(s=C3.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let u=My(c);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=P3.parse(await t.stopMonitoring())}catch(c){let u=My(c);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=$pe(a,r.maximumExternalAiCalls??0),Ape.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function $pe(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Rpe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function My(e){return Ge(e)}var Fy,$3,R3,Jy,Epe,B$,Ipe,O3,C3,kpe,P3,Ape,Tpe;var Z$=w(()=>{he();Fy=l.enum(["regression","load","stress"]),$3=l.enum(["add","update","rename","delete"]),R3=l.object({id:l.string().min(1),operation:$3,count:l.number().int().positive().max(700),targetProbeCount:l.number().int().min(0).max(700),settleMs:l.number().int().nonnegative().max(300000)}),Jy=l.object({profile:Fy,maximumProbeCount:l.number().int().positive().max(700),maximumExternalAiCalls:l.number().int().nonnegative().max(1e4).optional(),phases:l.array(R3).min(1)}),Epe=l.object({entities:l.number().int().nonnegative(),notes:l.number().int().nonnegative(),version:l.string().min(1)}),B$=l.object({timestamp:l.iso.datetime(),endpoint:l.string().startsWith("/"),status:l.number().int().nonnegative(),durationMs:l.number().nonnegative(),ok:l.boolean(),error:l.string().optional()}),Ipe=l.object({timestamp:l.iso.datetime(),cpuPercent:l.number().nonnegative(),memoryPercent:l.number().nonnegative(),pids:l.number().int().nonnegative()}),O3=l.object({id:l.string().min(1),operation:$3,count:l.number().int().positive(),success:l.boolean(),commitLatencyMs:l.number().nonnegative().optional(),persistenceLatencyMs:l.number().nonnegative().optional(),error:l.string().optional()}),C3=l.object({success:l.boolean(),probesRemaining:l.number().int().nonnegative(),finalEntities:l.number().int().nonnegative().optional(),finalNotes:l.number().int().nonnegative().optional(),contentTreeRestored:l.boolean().optional(),error:l.string().optional()}),kpe=l.object({status:l.string(),restartCount:l.number().int().nonnegative(),oomKilled:l.boolean()}),P3=l.object({health:l.array(B$),runtime:l.array(Ipe),externalAiCalls:l.number().int().nonnegative().optional(),container:kpe.optional()}),Ape=l.object({profile:Fy,success:l.boolean(),baseline:Epe,phases:l.array(O3),cleanup:C3,metrics:P3,failure:l.string().optional()}),Tpe={regression:{profile:"regression",maximumProbeCount:20,phases:[jt("add20","add",20,20,0),jt("update20","update",20,20,30000),jt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[jt("add50","add",50,50,0),jt("add150","add",100,150,0),jt("add350","add",200,350,0),jt("update350a","update",350,350,45000),jt("rename100","rename",100,350,45000),jt("update350b","update",350,350,45000),jt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[jt("add50","add",50,50,0),jt("add150","add",100,150,0),jt("add350","add",200,350,0),jt("add700","add",350,700,0),jt("update700a","update",700,700,45000),jt("rename200","rename",200,700,45000),jt("update700b","update",700,700,45000),jt("delete700","delete",700,0,150000)]}}});import{spawn as Ope}from"child_process";async function D3(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw Xn(t,r,n);return n}function Xn(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var qo=async(e,t,r={})=>new Promise((o,n)=>{let i=Ope(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(c)=>{s+=c}),i.stderr.on("data",(c)=>{a+=c}),i.on("error",n),i.on("close",(c)=>{o({exitCode:c??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var Pf=()=>{};class El{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new El(e,r,o);return await D3(e,"git",["-c","credential.helper=","-c",`credential.helper=${L3}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",L3]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw Xn("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var L3='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var B3=w(()=>{Pf()});function zf(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class U${#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await j$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#p()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#f(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#f(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return Cpe.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#f(e,t,r){return e!==void 0&&(t===void 0||zf(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await j$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#p(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var j3,Cpe;var Z3=w(()=>{he();Z$();j3=l.array(l.object({entityType:l.string(),count:l.number().int().nonnegative()})),Cpe=l.object({status:l.literal("ready"),operationalStatus:l.literal("operational"),app:l.object({version:l.string()})})});var Hy={};Zt(Hy,{applyDirectorySyncStressPhase:()=>F3,cleanupDirectorySyncStress:()=>Mpe,listProbeFiles:()=>ua,parseStressRuntimeSample:()=>J3,removeProbeFiles:()=>V$,runDeployedDirectorySyncStress:()=>Upe,runStressCommand:()=>qo,verifyDirectorySyncStressAccess:()=>qpe});import{chmod as Ppe,mkdir as M$,mkdtemp as F$,readFile as zpe,readdir as Npe,rename as Dpe,rm as Df,writeFile as En}from"fs/promises";import{tmpdir as J$}from"os";import{join as ct,resolve as K$}from"path";async function Upe(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=W$(r),n=K$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await M$(n,{recursive:!0});let{pilot:i,user:s}=await H$(e.rootDir,e.handle);Ky({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Fy.parse(e.profile),c=e.plan?Jy.parse(e.plan):z3(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)M3(s);let u=Lpe.parse(e.env??process.env),d=new q3({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??qo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await N3(c,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await Kpe(m),m}async function qpe(e){let r=(e.now??(()=>new Date))().toISOString(),o=W$(r),n=K$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await M$(n,{recursive:!0});let{pilot:i,user:s}=await H$(e.rootDir,e.handle);Ky({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),M3(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await F$(ct(J$(),"brains-ops-directory-sync-access-check-"));try{let u=await El.clone(e.commandRunner??qo,`${i.githubOrg}/${s.contentRepo}`,ct(c,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await En(ct(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
387
|
+
`;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let u of c.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var s$;var qF=w(()=>{Re();s$=class s${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ty(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!yf(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var _n,MF,a$,Ffe=()=>({union:Jfe,unionAll:Kfe,intersect:Hfe,except:Vfe}),Jfe,Kfe,Hfe,Vfe;var c$=w(()=>{Re();qF();Lo();ca();Qt();vn();sr();br();No();Sl();If();_n=class _n{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,dt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Uo))r=e[ft].selectedFields;else if(oe(e,xe))r={};else r=by(e);return new a$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};MF=class MF extends s${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=bf(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of xn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=bf(t);for(let i of xn(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,xe)){let i=oe(t,dt)?t._.selectedFields:oe(t,Xr)?t[ft].selectedFields:t[me.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(Ffe()):r;if(!yf(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...xn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...xn(r.table));return new Proxy(new dt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};a$=class a$ extends MF{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=en(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};wM(a$,[Sr]);Jfe=Ty("union",!1),Kfe=Ty("union",!0),Hfe=Ty("intersect",!1),Vfe=Ty("except",!1)});var la;var $y=w(()=>{Re();ca();Ay();vn();c$();la=class la{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,wl)?e:void 0,this.dialectConfig=oe(e,wl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new mf(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new _n({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new _n({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new _n({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new _n({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new o$(this.dialectConfig);return this.dialect}}});var Ry,l$;var FF=w(()=>{Re();Lo();Qt();Bo();sr();br();Sl();$y();Ry=class Ry{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[me.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,xe)?s:new Br(s,n[i])}return o});return new l$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new la):e;if(!oe(t,xe)&&!yf(this.table[hy],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new l$(this.table,t,this.session,this.dialect,this.withList,!0)}};l$=class l$ extends Sr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=en(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,yy(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:xn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Oy,JF;var KF=w(()=>{Re();Lo();ca();Bo();vn();sr();br();No();Sl();If();Oy=class Oy{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new JF(this.table,yy(this.table,e),this.session,this.dialect,this.withList)}};JF=class JF extends Sr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=bf(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,At)?t[me.Symbol.Columns]:oe(t,dt)?t._.selectedFields:oe(t,Uo)?t[ft].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[me.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[me.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=en(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:xn(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var u$=w(()=>{LF();FF();$y();c$();KF()});var kf;var HF=w(()=>{Re();Qt();kf=class kf extends xe{constructor(e){super(kf.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=kf.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var f$,Cy,d$;var VF=w(()=>{Re();Lo();vf();f$=class f${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Cy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Cy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Cy=class Cy extends Sr{constructor(e,t,r,o,n,i,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=c}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>xy(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};d$=class d$ extends Cy{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var xl;var WF=w(()=>{Re();Lo();xl=class xl extends Sr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Af;var Py=w(()=>{Re();ca();Qt();u$();vn();HF();VF();WF();Af=class Af{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new f$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new la(r.dialect));return new Proxy(new mf(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new kf({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new _n({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new _n({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Oy(a,t.session,t.dialect,e)}function i(a){return new Ry(a,t.session,t.dialect,e)}function s(a){return new Iy(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new _n({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new _n({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Oy(e,this.session,this.dialect)}$cache;insert(e){return new Ry(e,this.session,this.dialect)}delete(e){return new Iy(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new xl(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function p$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var GF,Tf;var m$=w(()=>{Re();GF=class GF{static[F]="Cache"};Tf=class Tf extends GF{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var QF=w(()=>{m$()});function zy(e,t){return new Proxy(e,new aa(t,!1))}var YF=w(()=>{_f()});var XF,h$,g$,y$;var b$=w(()=>{m$();Re();ky();Lo();Py();XF=class XF extends Sr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};h$=class h${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,Tf)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Zo(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Zo(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Zo(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Zo(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await p$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Zo(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await p$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Zo(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new XF(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};g$=class g${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new vl({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};y$=class y$ extends Af{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new t$}}});var S$,Wfe,Gfe,Ny;var e3=w(()=>{Re();ca();br();$y();Bo();If();S$=class S${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};Wfe=class Wfe extends S${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new la);let t=new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Ny({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};Gfe=class Gfe extends S${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=by(Ef(e,t))}existing(){return new Proxy(new Ny({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Ny({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Ny=class Ny extends Uo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var Dy=w(()=>{YF();RF();n$();Py();Ay();FT();zF();DF();u$();b$();Bo();KT();Sl();e3()});function t3(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Ly(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var By,v$,r3;var w$=w(()=>{QF();Re();Sy();Qt();Dy();b$();br();By=class By extends g${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new LT,this.cache=o.cache??new Tf}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new r3(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new By(this.client,this.dialect,this.schema,this.options,r),n=new v$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};v$=class v$ extends y${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new v$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};r3=class r3 extends h${constructor(e,t,r,o,n,i,s,a,c,u,d){super("async",c,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=gf(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let c=gf(o.params,e??{});return r.logQuery(o.sql,c),await this.queryWithCache(o.sql,c,async()=>{let u={sql:o.sql,args:c};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>t3(r));if(this.customResultMapper)return this.customResultMapper(e,Ly);return e.map((r)=>zT(this.fields,Array.prototype.slice.call(r).map((o)=>Ly(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let c=gf(o.params,e??{});return r.logQuery(o.sql,c),await this.queryWithCache(o.sql,c,async()=>{let u={sql:o.sql,args:c};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return t3(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Ly);return zT(this.fields,Array.prototype.slice.call(r).map((o)=>Ly(o)),this.joinsNotNullableMap)}async values(e){let t=gf(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function _l(e,t={}){let r=new i$({casing:t.casing}),o;if(t.logger===!0)o=new DT;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=JM(t.schema,HM);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new By(e,r,n,{logger:o,cache:t.cache},void 0),s=new n3("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var n3;var o3=w(()=>{Re();Sy();vf();Py();Ay();w$();n3=class n3 extends Af{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function jy(...e){if(typeof e[0]==="string"){let t=hl({url:e[0]});return _l(t,e[1])}if(xM(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return _l(r,o);let n=typeof t==="string"?hl({url:t}):hl(t);return _l(n,o)}return _l(e[0],e[1])}var i3=w(()=>{_T();br();o3();((e)=>{function t(r){return _l({},r)}e.mock=t})(jy||(jy={}))});var s3=w(()=>{i3();w$()});function Qfe(){return new Promise((e)=>setTimeout(e,0))}function Xfe(){if(x$)return;x$=!0,setTimeout(()=>{x$=!1,_$=performance.now()},0)}async function $f(e=Yfe){if(Xfe(),performance.now()-_$<e)return;await Qfe(),_$=performance.now()}var Yfe=50,_$,x$=!1;var a3=w(()=>{_$=performance.now()});function c3(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function npe(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Zy(e,t){let r=Date.now()+(t.budgetMs??epe),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!npe(i))throw i;await t.afterRefusal?.();let s=Math.min(tpe*2**(n-1),rpe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function E$(e,t={}){let r=hl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(f,m){return await $f(),Zy(()=>typeof f==="string"?s(f,m):s(f),u)}r.execute=d,r.batch=async(f,m)=>(await $f(),Zy(()=>a(f,m),u)),r.migrate=async(f)=>(await $f(),Zy(()=>c(f),u)),r.transaction=async(f)=>(await $f(),Zy(()=>o(f),u))}return r}function Uy(e){let{url:t,schema:r}=e,o=c3(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?E$({url:t,authToken:o},n):E$({url:t},n);return{db:jy(i,{schema:r}),client:i,url:t}}async function qy(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var epe=5000,tpe=5,rpe=40;var I$=w(()=>{_T();s3();a3()});var l3=w(()=>{BA();I$()});var k$=w(()=>{I$();l3()});var A$=w(()=>{_f();fy();Sn();Re();ky();Sy();Lo();vf();r$();vn();sr();br();No()});var Y,qe;var T$=w(()=>{Dy();A$();Ud();Y=Ef("job_queue",{id:pt("id").primaryKey().$defaultFn(()=>$o()),type:pt("type").notNull(),data:pt("data").notNull(),result:pt("result",{mode:"json"}),progress:pt("progress",{mode:"json"}).$type(),source:pt("source"),metadata:pt("metadata",{mode:"json"}).$type().notNull(),status:pt("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:pt("lastError"),lastErrorPublic:pt("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:pt("attemptId"),workerSlotId:pt("workerSlotId"),workerSessionId:pt("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:pt("brainVersion"),brainVersionSortKey:pt("brainVersionSortKey")},(e)=>({queueReadyIdx:jo("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:jo("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:jo("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:jo("idx_job_queue_source").on(e.source),rootJobIdx:jo("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:jo("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),qe=Ef("job_worker_sessions",{slotId:pt("slotId").primaryKey(),sessionId:pt("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:pt("brainVersion"),brainVersionSortKey:pt("brainVersionSortKey"),stableSlotId:pt("stableSlotId")},(e)=>({heartbeatIdx:jo("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:jo("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function u3(e){return Uy({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:qe},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var d3=w(()=>{k$();T$()});class $${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class R${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class O${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=ope.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var ope;var f3=w(()=>{he();Ro();ope=l.looseObject({deduplicationKey:l.string().optional()})});function h3(e){return`${String(e.length).padStart(2,"0")}${e}`}function spe(e){return ipe.test(e)?`0${h3(e)}`:`1${e}`}function Rf(e){let t=p3.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(h3).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(spe).join("!")}`}var p3,ipe,m3;var C$=w(()=>{he();p3=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,ipe=/^\d+$/u,m3=l.string().regex(p3,"Brain version must be a semver version")});function g3(e){return JSON.stringify(new _c(e).toJSON())}class P${db;transactionClient;databaseUrl;logger;deduplicator=new O$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??ape}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return dpe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,c=!0;if(!o.closed)try{await o.rollback()}catch(u){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},u=async()=>{await c(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),f=this.deduplicator.findDuplicate(d,a,i);if(!f)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,f.id,o),{kind:"skipped",jobId:f.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,f.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.id}}await c();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",g3("cancelled"),m,m,f.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=Rf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?Rf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(cpe*2**(o-1),lpe),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ge(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=zi,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?Rf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(qe).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:qe.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=zi){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(qe).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(qe.slotId,e),je(qe.sessionId,t))).returning({slotId:qe.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,qe.slotId),je(Y.workerSessionId,qe.sessionId),je(Y.status,Oe.PROCESSING),wn(Y.leaseExpiresAt,e)));await this.db.delete(qe).where(tt(Ki(qe.expiresAt,e-t),Vi(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(qe).where(tt(je(qe.slotId,e),je(qe.sessionId,t))).returning({slotId:qe.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,c=Math.min(1000*2**i.retryCount,60000),u=s?o+c:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:LI(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new _c("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),tn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),jr(Y.attemptId),jr(Y.workerSlotId),jr(Y.workerSessionId),jr(Y.leaseExpiresAt),jr(Y.attemptHeartbeatAt),jr(Y.progress),jr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(Do(Y.createdAt),Do(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(sa(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${qe.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${qe.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${qe.heartbeatAt})`}).from(qe)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],c=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=upe.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(Do(Y.runtimeUpdatedAt),Do(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(tn(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),Ki(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=tn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,Hi(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(sa(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Hi(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(sa(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,Hi(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(sa(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:c}=e,u=c?this.brainVersionGate(c,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:qe.slotId}).from(qe).where(tt(je(qe.slotId,o),je(qe.sessionId,n),wn(qe.expiresAt,t))),f=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:qe.slotId}).from(qe).where(tt(je(qe.slotId,Y.workerSlotId),je(qe.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),tn(jr(Y.attemptId),Vi(m),Ki(Y.leaseExpiresAt,t))),b=zy(Y,"running"),y=this.db.select({id:b.id}).from(b).where(tt(je(b.type,Y.type),je(b.status,Oe.PROCESSING),wn(b.leaseExpiresAt,t),C`${b.id} <> ${Y.id}`)),S=a.length===0?void 0:tn(vy(Y.type,[...a]),Vi(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(Hi(Y.type,s),S,u.admissible,tn(tt(je(Y.status,Oe.PENDING),Ki(Y.scheduledFor,t)),h))).orderBy(Do(Y.priority),Do(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${g3("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(Hi(Y.id,_),wy(d),f,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=zy(qe,"claimer"),n=zy(qe,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),wn(n.expiresAt,r),tn(wn(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),wn(n.slotId,o.slotId)))));return Vi(i)}brainVersionGate(e,t){let r=Rf(e),o=this.db.select({slotId:qe.slotId}).from(qe).where(tt(wn(qe.expiresAt,t),wn(qe.brainVersionSortKey,r)));return{admissible:tn(jr(Y.brainVersionSortKey),Ki(Y.brainVersionSortKey,r)),noNewerWorker:Vi(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),jr(Y.attemptId),tn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var ape=2000,cpe=5,lpe=40,upe,dpe;var y3=w(()=>{A$();Dy();T$();Vt();he();Ro();Md();f3();C$();upe=l.number().int().min(0).max(1000),dpe=new R$});import{AsyncLocalStorage as fpe}from"async_hooks";class Of{storage=new fpe;static createFresh(){return new Of}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=wi.parse(e),n=ppe(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function ppe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var z$=w(()=>{Vt()});class Cf{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${$o()}`;directWorkerSessionId=$o();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Cf(e,t??kr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:m3.parse(e.brainVersion);let{db:o,client:n,url:i}=u3(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Of.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new $$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new P$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await qy(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=$o(),c=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,c,o),d=o?.metadata??{operationType:"data_processing"},{provenance:f,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:c,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},b,y=()=>{b?.rollback(),b=void 0};try{let S=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{b=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(b?.commit(),b=void 0,S.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:S.jobId});else if(S.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:S.jobId});else{if(S.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:S.replacedJobId});this.logger.debug("Job enqueued",{id:S.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return S.jobId}catch(S){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ge(S)}),S}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,c=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return wi.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:$o(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=zi){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=zi){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?i??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var b3=w(()=>{Ud();BA();Md();Ro();k$();d3();y3();Vt();z$();C$()});var N$=()=>{};var S3=w(()=>{Ud();Ro();Md();Ro();N$();z$()});var v3=w(()=>{Ro();N$()});var tqe;var w3=w(()=>{he();qd();Ro();tqe=l.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},l.record(l.string(),l.unknown()))});var oqe;var x3=w(()=>{he();oqe=l.record(l.string(),l.unknown())});var _3=w(()=>{Vt();Ud()});var E3=w(()=>{b3();S3();v3();w3();x3();Md();Ro();qd();_3()});var D$={};Zt(D$,{LEGACY_PROJECTION_JOB_TYPES:()=>k3,LEGACY_PROJECTION_RETIREMENT_REASON:()=>T3,legacyProjectionJobTypeSchema:()=>A3,retireLegacyProjectionJob:()=>_pe});import{existsSync as vpe}from"fs";import{resolve as wpe}from"path";function I3(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function xpe(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function _pe(e){let t=wpe(e.databasePath);if(!vpe(t))throw Error(`Job database does not exist: ${t}`);let r=A3.parse(e.jobType),o=Cf.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(xpe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:I3(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:T3,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:I3(s),retired:!0}}finally{o.close()}}var k3,A3,T3="Retired legacy projection job superseded by scheduler-owned projections";var L$=w(()=>{E3();he();k3=["conversation-memory:project","skill:project","swot:derive","topic:project"],A3=l.enum(k3)});function jt(e,t,r,o,n){return R3.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function z3(e){return Jy.parse(structuredClone(Tpe[e]))}function Ky(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function j$(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),B$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:c.ok})}catch(c){return B$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:Rpe(c)})}finally{clearTimeout(a)}}async function N3(e,t){let r=Jy.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${My(c)}`}if(!n)for(let c of r.phases)try{let u=O3.parse(await t.executePhase(c,i));if(o.push(u),!u.success){n=`${c.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=My(u);o.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:d}),n=`${c.id}: ${d}`;break}}finally{try{if(s=C3.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let u=My(c);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=P3.parse(await t.stopMonitoring())}catch(c){let u=My(c);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=$pe(a,r.maximumExternalAiCalls??0),Ape.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function $pe(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Rpe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function My(e){return Ge(e)}var Fy,$3,R3,Jy,Epe,B$,Ipe,O3,C3,kpe,P3,Ape,Tpe;var Z$=w(()=>{he();Fy=l.enum(["regression","load","stress"]),$3=l.enum(["add","update","rename","delete"]),R3=l.object({id:l.string().min(1),operation:$3,count:l.number().int().positive().max(700),targetProbeCount:l.number().int().min(0).max(700),settleMs:l.number().int().nonnegative().max(300000)}),Jy=l.object({profile:Fy,maximumProbeCount:l.number().int().positive().max(700),maximumExternalAiCalls:l.number().int().nonnegative().max(1e4).optional(),phases:l.array(R3).min(1)}),Epe=l.object({entities:l.number().int().nonnegative(),notes:l.number().int().nonnegative(),version:l.string().min(1)}),B$=l.object({timestamp:l.iso.datetime(),endpoint:l.string().startsWith("/"),status:l.number().int().nonnegative(),durationMs:l.number().nonnegative(),ok:l.boolean(),error:l.string().optional()}),Ipe=l.object({timestamp:l.iso.datetime(),cpuPercent:l.number().nonnegative(),memoryPercent:l.number().nonnegative(),pids:l.number().int().nonnegative()}),O3=l.object({id:l.string().min(1),operation:$3,count:l.number().int().positive(),success:l.boolean(),commitLatencyMs:l.number().nonnegative().optional(),persistenceLatencyMs:l.number().nonnegative().optional(),error:l.string().optional()}),C3=l.object({success:l.boolean(),probesRemaining:l.number().int().nonnegative(),finalEntities:l.number().int().nonnegative().optional(),finalNotes:l.number().int().nonnegative().optional(),contentTreeRestored:l.boolean().optional(),error:l.string().optional()}),kpe=l.object({status:l.string(),restartCount:l.number().int().nonnegative(),oomKilled:l.boolean()}),P3=l.object({health:l.array(B$),runtime:l.array(Ipe),externalAiCalls:l.number().int().nonnegative().optional(),container:kpe.optional()}),Ape=l.object({profile:Fy,success:l.boolean(),baseline:Epe,phases:l.array(O3),cleanup:C3,metrics:P3,failure:l.string().optional()}),Tpe={regression:{profile:"regression",maximumProbeCount:20,phases:[jt("add20","add",20,20,0),jt("update20","update",20,20,30000),jt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[jt("add50","add",50,50,0),jt("add150","add",100,150,0),jt("add350","add",200,350,0),jt("update350a","update",350,350,45000),jt("rename100","rename",100,350,45000),jt("update350b","update",350,350,45000),jt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[jt("add50","add",50,50,0),jt("add150","add",100,150,0),jt("add350","add",200,350,0),jt("add700","add",350,700,0),jt("update700a","update",700,700,45000),jt("rename200","rename",200,700,45000),jt("update700b","update",700,700,45000),jt("delete700","delete",700,0,150000)]}}});import{spawn as Ope}from"child_process";async function D3(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw Xn(t,r,n);return n}function Xn(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var qo=async(e,t,r={})=>new Promise((o,n)=>{let i=Ope(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(c)=>{s+=c}),i.stderr.on("data",(c)=>{a+=c}),i.on("error",n),i.on("close",(c)=>{o({exitCode:c??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var Pf=()=>{};class El{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new El(e,r,o);return await D3(e,"git",["-c","credential.helper=","-c",`credential.helper=${L3}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",L3]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw Xn("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var L3='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var B3=w(()=>{Pf()});function zf(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class U${#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await j$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#p()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#f(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#f(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return Cpe.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#f(e,t,r){return e!==void 0&&(t===void 0||zf(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await j$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#p(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var j3,Cpe;var Z3=w(()=>{he();Z$();j3=l.array(l.object({entityType:l.string(),count:l.number().int().nonnegative()})),Cpe=l.object({status:l.literal("ready"),operationalStatus:l.literal("operational"),app:l.object({version:l.string()})})});var Hy={};Zt(Hy,{applyDirectorySyncStressPhase:()=>F3,cleanupDirectorySyncStress:()=>Mpe,listProbeFiles:()=>ua,parseStressRuntimeSample:()=>J3,removeProbeFiles:()=>V$,runDeployedDirectorySyncStress:()=>Upe,runStressCommand:()=>qo,verifyDirectorySyncStressAccess:()=>qpe});import{chmod as Ppe,mkdir as M$,mkdtemp as F$,readFile as zpe,readdir as Npe,rename as Dpe,rm as Df,writeFile as En}from"fs/promises";import{tmpdir as J$}from"os";import{join as ct,resolve as K$}from"path";async function Upe(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=W$(r),n=K$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await M$(n,{recursive:!0});let{pilot:i,user:s}=await H$(e.rootDir,e.handle);Ky({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Fy.parse(e.profile),c=e.plan?Jy.parse(e.plan):z3(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)M3(s);let u=Lpe.parse(e.env??process.env),d=new q3({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??qo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await N3(c,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await Kpe(m),m}async function qpe(e){let r=(e.now??(()=>new Date))().toISOString(),o=W$(r),n=K$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await M$(n,{recursive:!0});let{pilot:i,user:s}=await H$(e.rootDir,e.handle);Ky({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),M3(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await F$(ct(J$(),"brains-ops-directory-sync-access-check-"));try{let u=await El.clone(e.commandRunner??qo,`${i.githubOrg}/${s.contentRepo}`,ct(c,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await En(ct(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
388
388
|
`),f}finally{await Df(c,{recursive:!0,force:!0})}}async function Mpe(e){let t=e.now??(()=>new Date),r=K$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`cleanup-${W$(t().toISOString())}`));await M$(r,{recursive:!0});let{pilot:o,user:n}=await H$(e.rootDir,e.handle);Ky({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let i=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!i)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??qo,a=e.logger??console.info,c=await F$(ct(J$(),"brains-ops-directory-sync-cleanup-")),u=ct(c,"content");try{let d=await El.clone(s,`${o.githubOrg}/${n.contentRepo}`,u,i),f=await V$(d.dir),m;if(f>0)await d.commitAll("test(directory-sync): clean residual stress probes"),await d.pushMainWithRebase(),m=await d.output(["rev-parse","HEAD"]),a(`Removed ${f} directory-sync stress probes`);let h=(await ua(d.dir)).length,b=h===0?await d.pruneStressBackupBranches():[],y={success:h===0,artifactsDir:r,probesRemoved:f,probesRemaining:h,backupBranchesDeleted:b,...m?{cleanupCommit:m}:{}};return await En(ct(r,"cleanup.json"),`${JSON.stringify(y,null,2)}
|
|
389
389
|
`),y}finally{await Df(c,{recursive:!0,force:!0})}}class q3{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new U$({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#b(),readEntityCounts:()=>this.#y()})}async prepare(e){this.#r=await F$(ct(J$(),"brains-ops-directory-sync-stress-"));let t=ct(this.#r,"content");this.#o=ct(this.#r,"id_ed25519"),this.#i=ct(this.#r,"known_hosts"),this.#a=await this.#m(),await En(this.#o,Jpe(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await Ppe(this.#o,384);let r=await this.#S("ssh-keyscan",["-T","10","-t","ed25519",this.#a]);if(r.exitCode!==0||!r.stdout.trim())throw Error("Unable to resolve smoke SSH host key");await En(this.#i,r.stdout,{mode:384});let o=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=o.stdout.trim().split(/\r?\n/)[0],!this.#s||!/^[A-Za-z0-9_.-]+$/.test(this.#s))throw Error("Unable to resolve a running smoke container");let n=await El.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await ua(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let i=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#f();let s=await this.#t.waitForHealthSnapshot(60000);if(!s)throw Error("Smoke health was unavailable before stress testing");return this.#c=`ops/directory-sync-stress-backup-${this.#e.runId}`,await n.run(["push","origin",`HEAD:refs/heads/${this.#c}`]),await this.#t.discoverEndpoints(),await En(ct(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:i,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:zf(s),version:s.version}},null,2)}
|
|
390
390
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:zf(s),version:s.version}}async startMonitoring(){this.#v(),this.#t.start()}async executePhase(e,t){this.#v();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let o=this.#t.healthSamples.length,n=this.#e.now().getTime(),i=await this.#g();if(i?.pending!==0||i.processing!==0)return Il(e,"health did not provide a drained queue before the phase");await F3(r.dir,e),await r.commitAll(`test(directory-sync): stress ${e.id}`),await r.pushMainWithRebase();let s=this.#e.now().getTime(),a=await r.output(["rev-parse","HEAD"]),c=await this.#p(a,900000);if(c===void 0)return Il(e,"runtime did not pull the phase commit");let u;if(e.operation==="rename"){let h=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let b=await this.#t.waitForStableEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-s,!b)return Il(e,`health did not stabilize at ${h} notes`,c,u)}else if(e.operation==="add"||e.operation==="delete"){let h=t.notes+e.targetProbeCount,b=this.#e.now().getTime(),y=await this.#t.waitForEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-b,!y)return Il(e,`health did not reach ${h} notes`,c,u)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let d=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(i.completedImports+d,1200000))return Il(e,`health did not observe ${d} completed import job(s) with a drained queue`,c,u);let m=this.#t.healthSamples.slice(o).find((h)=>!h.ok);if(m)return Il(e,`${m.endpoint} unavailable (${m.status===0?m.error??"unknown":m.status})`,c,u);return this.#e.logger(`Completed ${e.id} in ${this.#e.now().getTime()-n}ms`),{id:e.id,operation:e.operation,count:e.count,success:!0,commitLatencyMs:c,...u===void 0?{}:{persistenceLatencyMs:u}}}async cleanup(e){let t=this.#n;if(!t)return{success:!1,probesRemaining:0,error:"stress checkout was not prepared"};try{if(await t.sync(!0),await V$(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let o=(await ua(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=o===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:o,...n?{finalEntities:n.entities,finalNotes:zf(n)}:{},contentTreeRestored:s,...!a?{error:!n?"entity baseline was not restored before cleanup timeout":!s?"content tree differs from the pre-stress baseline":"stress probes remain after cleanup"}:{}}}catch(r){return{success:!1,probesRemaining:(await ua(t.dir)).length,error:Ge(r)}}}async stopMonitoring(){await this.#t.stop(),await En(ct(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
@@ -398,7 +398,7 @@ Update marker: ${t.id}.
|
|
|
398
398
|
`}function W$(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function Kpe(e){await En(ct(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
|
|
399
399
|
`),await En(ct(e.artifactsDir,"report.md"),Hpe(e))}function Hpe(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,o=t.map((a)=>a.cpuPercent).sort((a,c)=>a-c),n=t.map((a)=>a.memoryPercent),i=r.filter((a)=>!a.ok),s=["# Directory-sync stress report","",`- Run: \`${e.runId}\``,`- Target: \`${e.target.handle}\` (${e.target.domain})`,`- Profile: \`${e.report.profile}\``,`- Version: \`${e.report.baseline.version}\``,`- Result: **${e.report.success?"PASS":"FAIL"}**`,`- Started: ${e.startedAt}`,`- Completed: ${e.completedAt}`,"","## Phases","","| Phase | Operation | Count | Result | Pull latency | Persistence latency |","| --- | --- | ---: | --- | ---: | ---: |",...e.report.phases.map((a)=>`| ${a.id} | ${a.operation} | ${a.count} | ${a.success?"pass":`fail: ${a.error??"unknown"}`} | ${U3(a.commitLatencyMs)} | ${U3(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${Nf(q$(o,0.5))} / ${Nf(q$(o,0.95))} / ${Nf(q$(o,0.99))} / ${Nf(o.at(-1))}`,`- Memory max: ${Nf(n.length?Math.max(...n):void 0)}`,`- PIDs max: ${t.length?Math.max(...t.map((a)=>a.pids)):"n/a"}`,`- Container status/restarts/OOM: ${e.report.metrics.container?`${e.report.metrics.container.status} / ${e.report.metrics.container.restartCount} / ${e.report.metrics.container.oomKilled}`:"unknown"}`,`- External AI calls: ${e.report.metrics.externalAiCalls??0}`,`- Health samples: ${r.length}`,`- Health failures: ${i.length}`,"","## Cleanup","",`- Result: ${e.report.cleanup.success?"pass":"fail"}`,`- Remaining probes: ${e.report.cleanup.probesRemaining}`,`- Final entities: ${e.report.cleanup.finalEntities??"unknown"}`,`- Final notes: ${e.report.cleanup.finalNotes??"unknown"}`,`- Content tree restored: ${e.report.cleanup.contentTreeRestored??"unknown"}`,""];if(e.report.failure)s.push("## Failure","",e.report.failure,"");return`${s.join(`
|
|
400
400
|
`)}
|
|
401
|
-
`}function q$(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function Nf(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function U3(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var Lpe,Bpe,jpe,Zpe;var Vy=w(()=>{he();Z$();fn();Pf();B3();Z3();Pf();Lpe=l.object({HCLOUD_TOKEN:l.string().min(1),KAMAL_SSH_PRIVATE_KEY:l.string().min(1),CONTENT_REPO_ADMIN_TOKEN:l.string().min(1)}),Bpe=l.object({servers:l.array(l.object({id:l.number().int(),status:l.string(),public_net:l.object({ipv4:l.object({ip:l.string().min(1)})})}))}),jpe=l.object({status:l.literal("ready"),operationalStatus:l.literal("operational"),resources:l.object({queue:l.object({totals:l.object({pending:l.number().int().nonnegative(),processing:l.number().int().nonnegative()}),byType:l.array(l.object({type:l.string(),status:l.string(),count:l.number().int().nonnegative()}))})})}),Zpe=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var K3=w(()=>{Es()});var Vpe="/usr/local/sbin/brains-health-watchdog",Wpe="ai.rizom.brain.watchdog",Gpe="true",G$,H3,
|
|
401
|
+
`}function q$(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function Nf(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function U3(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var Lpe,Bpe,jpe,Zpe;var Vy=w(()=>{he();Z$();fn();Pf();B3();Z3();Pf();Lpe=l.object({HCLOUD_TOKEN:l.string().min(1),KAMAL_SSH_PRIVATE_KEY:l.string().min(1),CONTENT_REPO_ADMIN_TOKEN:l.string().min(1)}),Bpe=l.object({servers:l.array(l.object({id:l.number().int(),status:l.string(),public_net:l.object({ipv4:l.object({ip:l.string().min(1)})})}))}),jpe=l.object({status:l.literal("ready"),operationalStatus:l.literal("operational"),resources:l.object({queue:l.object({totals:l.object({pending:l.number().int().nonnegative(),processing:l.number().int().nonnegative()}),byType:l.array(l.object({type:l.string(),status:l.string(),count:l.number().int().nonnegative()}))})})}),Zpe=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var K3=w(()=>{Es()});var Vpe="/usr/local/sbin/brains-health-watchdog",Wpe="ai.rizom.brain.watchdog",Gpe="true",G$,H3,tMe;var V3=w(async()=>{K3();G$=`${Wpe}=${Gpe}`,H3=`#!/usr/bin/env bash
|
|
402
402
|
set -euo pipefail
|
|
403
403
|
umask 077
|
|
404
404
|
|
|
@@ -457,7 +457,7 @@ while read -r container_id; do
|
|
|
457
457
|
logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
|
|
458
458
|
docker restart "$container_id"
|
|
459
459
|
done < <(docker ps --filter health=unhealthy --filter label=${G$} --format '{{.ID}}')
|
|
460
|
-
`,
|
|
460
|
+
`,tMe=`[Unit]
|
|
461
461
|
Description=Restart persistently unhealthy Brain containers
|
|
462
462
|
After=docker.service
|
|
463
463
|
Requires=docker.service
|
|
@@ -698,7 +698,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
698
698
|
`).replace(/\\n/g,`
|
|
699
699
|
`).trimEnd()}
|
|
700
700
|
`}var X3,rme;var tR=w(async()=>{he();W3();fn();Pf();await V3();X3=l.object({HCLOUD_TOKEN:l.string().min(1),KAMAL_SSH_PRIVATE_KEY:l.string().min(1)}),rme=l.object({servers:l.array(l.object({status:l.string(),public_net:l.object({ipv4:l.object({ip:l.string().min(1)})})}))})});import{parseArgs as Z5}from"util";function ot(e){return e}class Bf extends Error{constructor(e){super(e);this.name="CliUsageError"}}function U5(e,t){let r={...t};for(let o of e)for(let[n,i]of Object.entries(o.flags??{})){let s=r[n];if(s===void 0){r[n]=i;continue}if(s.type!==i.type||s.short!==i.short||s.default!==i.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function q5(e){let t={};for(let[r,o]of Object.entries(e))t[r]={type:o.type,...o.short!==void 0?{short:o.short}:{},...o.default!==void 0?{default:o.default}:{}};return t}function M5(e){if(!(e instanceof Error)||!("code"in e))return!1;return e.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"||e.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"}function oR(e,t){let r=U5(t.commands,t.globalFlags??{}),o,n;try{({values:o,positionals:n}=Z5({args:e,options:q5(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(M5(s))throw new Bf(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&o.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&o.version===!0)return{command:"version",args:[],flags:{version:!0}};let i={};for(let[s,a]of Object.entries(r)){let c=o[s];if(typeof c==="string"&&a.type==="string")i[s]=c;else if(typeof c==="boolean"&&a.type==="boolean")i[s]=c}return{command:n[0]??"help",args:n.slice(1),flags:i}}function iR(e){let t=e.reduce((r,o)=>Math.max(r,o.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function F5(e){return iR(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function J5(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",o=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${o}`}function sR(e){return iR(Object.entries(e).map(([t,r])=>({label:J5(t,r),description:r.description})))}function aR(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function K5(e){return JSON.stringify(Object.entries(e).map(([t,r])=>[t,r.type,r.short??"",r.description,r.placeholder??"",r.default??""]).sort((t,r)=>String(t[0]).localeCompare(String(r[0]))))}function H5(e){let t=[],r=new Map;for(let n of e){let i=n.flags??{};if(Object.keys(i).length===0)continue;let s=K5(i),a=r.get(s);if(a){a.names.push(n.name);continue}let c={names:[n.name],flags:i};r.set(s,c),t.push(c)}let o=[];for(let n of t)o.push("",`${n.names.join(" / ")} options:`),o.push(...sR(n.flags));return o}function cR(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...F5(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...sR(e.globalFlags));return t.push(...H5(e.commands)),t.join(`
|
|
701
|
-
`)}function lR(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function nt(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ts(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var jf={name:"@rizom/ops",version:"0.2.0-alpha.674",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};import{existsSync as xK,mkdirSync as _K,readFileSync as jS,writeFileSync as ZS}from"fs";import{dirname as EK,join as bC}from"path";function Xy(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function St(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function Ut(e,t,r=""){let o=Xy(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;if(!o)throw TypeError(u);throw RangeError(u)}return e}function no(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(St(e.outputLen),St(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function ma(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Zf(e,t){Ut(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function Uf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function cr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ha(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rn(e,t){return e<<32-t|e>>>t}function Fe(e,t){return e<<t|e>>>32-t>>>0}var W5=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function G5(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Q5(e){for(let t=0;t<e.length;t++)e[t]=G5(e[t]);return e}var eb=W5?(e)=>e:Q5,dR=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Y5=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function qf(e){if(Ut(e),dR)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Y5[e[r]];return t}var ro={_0:48,_9:57,A:65,F:70,a:97,f:102};function uR(e){if(e>=ro._0&&e<=ro._9)return e-ro._0;if(e>=ro.A&&e<=ro.F)return e-(ro.A-10);if(e>=ro.a&&e<=ro.f)return e-(ro.a-10);return}function Rl(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(dR)try{return Uint8Array.fromHex(e)}catch(n){if(n instanceof SyntaxError)throw RangeError(n.message);throw n}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=uR(e.charCodeAt(i)),a=uR(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}o[n]=s*16+a}return o}function X5(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function tb(e,t=""){if(typeof e==="string")return X5(e);return Ut(e,void 0,t)}function rb(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Ut(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function Mf(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw TypeError("options must be object or undefined");return Object.assign(e,t)}function nb(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.canXOF=o.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function oo(e=32){St(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var ob=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});class ib{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(no(e),Ut(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),cr(o)}update(e){return ma(this),this.iHash.update(e),this}digestInto(e){ma(this),Zf(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Tn=(()=>{let e=(t,r,o)=>new ib(t,r).update(o).digest();return e.create=(t,r)=>new ib(t,r),e})();function Ol(e,t,r){if(no(e),r===void 0)r=new Uint8Array(e.outputLen);return Tn(e,r,t)}var sb=Uint8Array.of(0),fR=Uint8Array.of();function ab(e,t,r,o=32){no(e),St(o,"length"),Ut(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=fR;else Ut(r,void 0,"info");let s=new Uint8Array(i*n),a=Tn.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)sb[0]=d+1,c.update(d===0?fR:u).update(r).update(sb).digestInto(u),s.set(u,n*d),a._cloneInto(c);return a.destroy(),c.destroy(),cr(u,sb),s.slice(0,o)}var Fo=(e,t,r,o,n)=>ab(e,Ol(e,t,r),o,n);function pR(e,t,r){return e&t^~e&r}function mR(e,t,r){return e&t^e&r^t&r}class Ff{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ha(this.buffer)}update(e){ma(this),Ut(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=ha(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){ma(this),Zf(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,cr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=ha(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var io=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Jf=BigInt(4294967295),hR=BigInt(32);function e8(e,t=!1){if(t)return{h:Number(e&Jf),l:Number(e>>hR&Jf)};return{h:Number(e>>hR&Jf)|0,l:Number(e&Jf)|0}}function gR(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=e8(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}var cb=(e,t,r)=>e>>>r,lb=(e,t,r)=>e<<32-r|t>>>r,rs=(e,t,r)=>e>>>r|t<<32-r,ns=(e,t,r)=>e<<32-r|t>>>r,Cl=(e,t,r)=>e<<64-r|t>>>r-32,Pl=(e,t,r)=>e>>>r-32|t<<64-r;function $n(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var yR=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),bR=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,SR=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),vR=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,wR=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),xR=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var r8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jo=new Uint32Array(64);class _R extends Ff{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Jo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Jo[d-15],m=Jo[d-2],h=rn(f,7)^rn(f,18)^f>>>3,b=rn(m,17)^rn(m,19)^m>>>10;Jo[d]=b+Jo[d-7]+h+Jo[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let f=rn(s,6)^rn(s,11)^rn(s,25),m=u+f+pR(s,a,c)+r8[d]+Jo[d]|0,b=(rn(r,2)^rn(r,13)^rn(r,22))+mR(r,o,n)|0;u=c,c=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,c,u)}roundClean(){cr(Jo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}}class ER extends _R{A=io[0]|0;B=io[1]|0;C=io[2]|0;D=io[3]|0;E=io[4]|0;F=io[5]|0;G=io[6]|0;H=io[7]|0;constructor(){super(32)}}var IR=(()=>gR(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),n8=(()=>IR[0])(),o8=(()=>IR[1])(),Ko=new Uint32Array(80),Ho=new Uint32Array(80);class kR extends Ff{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y]}set(e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ko[_]=e.getUint32(t),Ho[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Ko[_-15]|0,O=Ho[_-15]|0,L=rs(A,O,1)^rs(A,O,8)^cb(A,O,7),z=ns(A,O,1)^ns(A,O,8)^lb(A,O,7),K=Ko[_-2]|0,P=Ho[_-2]|0,W=rs(K,P,19)^Cl(K,P,61)^cb(K,P,6),ee=ns(K,P,19)^Pl(K,P,61)^lb(K,P,6),j=SR(z,ee,Ho[_-7],Ho[_-16]),R=vR(j,L,W,Ko[_-7],Ko[_-16]);Ko[_]=R|0,Ho[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:f,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=rs(d,f,14)^rs(d,f,18)^Cl(d,f,41),O=ns(d,f,14)^ns(d,f,18)^Pl(d,f,41),L=d&m^~d&b,z=f&h^~f&y,K=wR(x,O,z,o8[_],Ho[_]),P=xR(K,S,A,L,n8[_],Ko[_]),W=K|0,ee=rs(r,o,28)^Cl(r,o,34)^Cl(r,o,39),j=ns(r,o,28)^Pl(r,o,34)^Pl(r,o,39),R=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=f|0,{h:d,l:f}=$n(c|0,u|0,P|0,W|0),c=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=yR(W,j,B);r=bR(I,P,ee,R),o=I|0}({h:r,l:o}=$n(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=$n(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=$n(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$n(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:f}=$n(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=$n(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=$n(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=$n(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,c,u,d,f,m,h,b,y,S,x)}roundClean(){cr(Ko,Ho)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class AR extends kR{Ah=qt[0]|0;Al=qt[1]|0;Bh=qt[2]|0;Bl=qt[3]|0;Ch=qt[4]|0;Cl=qt[5]|0;Dh=qt[6]|0;Dl=qt[7]|0;Eh=qt[8]|0;El=qt[9]|0;Fh=qt[10]|0;Fl=qt[11]|0;Gh=qt[12]|0;Gl=qt[13]|0;Hh=qt[14]|0;Hl=qt[15]|0;constructor(){super(64)}}var vt=nb(()=>new ER,ob(1));var Kf=nb(()=>new AR,ob(3));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Qf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function fb(e){if(!Qf(e))throw TypeError("Uint8Array expected")}function CR(e,t){if(!Array.isArray(t))return!1;if(t.length===0)return!0;if(e)return t.every((r)=>typeof r==="string");else return t.every((r)=>Number.isSafeInteger(r))}function PR(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function Vo(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function Nl(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function Vf(e){if(!Array.isArray(e))throw TypeError("array expected")}function Wf(e,t){if(!CR(!0,t))throw TypeError(`${e}: array of strings expected`)}function pb(e,t){if(!CR(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Rr(...e){let t=(i)=>i,r=(i,s)=>(a)=>i(s(a)),o=e.map((i)=>i.encode).reduceRight(r,t),n=e.map((i)=>i.decode).reduce(r,t);return{encode:o,decode:n}}function Or(e){let t=typeof e==="string"?e.split(""):e,r=t.length;Wf("alphabet",t);let o=new Map(t.map((n,i)=>[n,i]));return{encode:(n)=>(Vf(n),n.map((i)=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:(n)=>(Vf(n),n.map((i)=>{Vo("alphabet.decode",i);let s=o.get(i);if(s===void 0)throw Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Cr(e=""){return Vo("join",e),{encode:(t)=>(Wf("join.decode",t),t.join(e)),decode:(t)=>(Vo("join.decode",t),t.split(e))}}function Yf(e,t="="){return Nl(e),Vo("padding",t),{encode(r){Wf("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){Wf("padding.decode",r);let o=r.length;if(o*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;o>0&&r[o-1]===t;o--)if((o-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,o)}}}function zR(e){return PR(e),{encode:(t)=>t,decode:(t)=>e(t)}}function TR(e,t,r){if(t<2)throw RangeError(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw RangeError(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Vf(e),!e.length)return[];let o=0,n=[],i=Array.from(e,(a)=>{if(Nl(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=i.length;while(!0){let a=0,c=!0;for(let u=o;u<s;u++){let d=i[u],f=t*a,m=f+d;if(!Number.isSafeInteger(m)||f/t!==a||m-d!==f)throw Error("convertRadix: carry overflow");let h=m/r;a=m%r;let b=Math.floor(h);if(i[u]=b,!Number.isSafeInteger(b)||b*r+a!==m)throw Error("convertRadix: carry overflow");if(!c)continue;else if(!b)o=u;else c=!1}if(n.push(a),c)break}for(let a=0;a<e.length-1&&e[a]===0;a++)n.push(0);return n.reverse()}var NR=(e,t)=>t===0?e:NR(t,e%t),Gf=(e,t)=>e+(t-NR(e,t)),Hf=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function ub(e,t,r,o){if(Vf(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if(Gf(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${Gf(t,r)}`);let n=0,i=0,s=Hf[t],a=Hf[r]-1,c=[];for(let u of e){if(Nl(u),u>=s)throw Error(`convertRadix2: invalid data word=${u} from=${t}`);if(n=n<<t|u,i+t>32)throw Error(`convertRadix2: carry overflow pos=${i} from=${t}`);i+=t;for(;i>=r;i-=r)c.push((n>>i-r&a)>>>0);let d=Hf[i];if(d===void 0)throw Error("invalid carry");n&=d-1}if(n=n<<r-i&a,!o&&i>=t)throw Error("Excess padding");if(!o&&n>0)throw Error(`Non-zero padding: ${n}`);if(o&&i>0)c.push(n>>>0);return c}function i8(e){Nl(e);let t=256;return{encode:(r)=>{if(!Qf(r))throw TypeError("radix.encode input should be Uint8Array");return TR(Array.from(r),t,e)},decode:(r)=>(pb("radix.decode",r),Uint8Array.from(TR(r,e,t)))}}function Ur(e,t=!1){if(Nl(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if(Gf(8,e)>32||Gf(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!Qf(r))throw TypeError("radix2.encode input should be Uint8Array");return ub(Array.from(r),8,e,!t)},decode:(r)=>(pb("radix2.decode",r),Uint8Array.from(ub(r,e,8,t)))}}function $R(e){return PR(e),function(...t){try{return e.apply(null,t)}catch(r){}}}var $me=Object.freeze(Rr(Ur(4),Or("0123456789ABCDEF"),Cr(""))),Rme=Object.freeze(Rr(Ur(5),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Yf(5),Cr(""))),Ome=Object.freeze(Rr(Ur(5),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Cr(""))),Cme=Object.freeze(Rr(Ur(5),Or("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Yf(5),Cr(""))),Pme=Object.freeze(Rr(Ur(5),Or("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Cr(""))),zme=Object.freeze(Rr(Ur(5),Or("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Cr(""),zR((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),DR=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),s8=/[\t\n\f\r ]/,LR=(e,t)=>{Vo("base64",e);let r=t?"base64url":"base64";if(e.length>0&&s8.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},mb=Object.freeze(DR?{encode(e){return fb(e),e.toBase64()},decode(e){return LR(e,!1)}}:Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Yf(6),Cr(""))),Yt=Object.freeze(Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Cr(""))),Nme=Object.freeze(DR?{encode(e){return fb(e),e.toBase64({alphabet:"base64url"})},decode(e){return LR(e,!0)}}:Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Yf(6),Cr(""))),Dme=Object.freeze(Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Cr(""))),hb=(e)=>Rr(i8(58),Or(e),Cr("")),Lme=Object.freeze(hb("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Bme=Object.freeze(hb("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),jme=Object.freeze(hb("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"));var db=Rr(Or("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Cr("")),RR=[996825010,642813549,513874426,1027748829,705979059];function zl(e){let t=e>>25,r=(e&33554431)<<5;for(let o=0;o<RR.length;o++)if((t>>o&1)===1)r^=RR[o];return r}function OR(e,t,r=1){let o=e.length,n=1;for(let i=0;i<o;i++){let s=e.charCodeAt(i);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=zl(n)^s>>5}n=zl(n);for(let i=0;i<o;i++)n=zl(n)^e.charCodeAt(i)&31;for(let i of t)n=zl(n)^i;for(let i=0;i<6;i++)n=zl(n);return n^=r,db.encode(ub([n%Hf[30]],30,5,!1))}function BR(e){let t=e==="bech32"?1:734539939,r=Ur(5),o=r.decode,n=r.encode,i=$R(o);function s(f,m,h=90){if(Vo("bech32.encode prefix",f),Qf(m))m=Array.from(m);pb("bech32.encode",m);let b=f.length;if(b===0)throw TypeError(`Invalid prefix length ${b}`);let y=b+7+m.length;if(h!==!1&&y>h)throw TypeError(`Length ${y} exceeds limit ${h}`);let S=f.toLowerCase(),x=OR(S,m,t);return`${S}1${db.encode(m)}${x}`}function a(f,m=90){Vo("bech32.decode input",f);let h=f.length;if(h<8||m!==!1&&h>m)throw TypeError(`invalid string length: ${h} (${f}). Expected (8..${m})`);let b=f.toLowerCase();if(f!==b&&f!==f.toUpperCase())throw Error("String must be lowercase or uppercase");let y=b.lastIndexOf("1");if(y===0||y===-1)throw Error('Letter "1" must be present between prefix and data only');let S=b.slice(0,y),x=b.slice(y+1);if(x.length<6)throw Error("Data must be at least 6 characters long");let _=db.decode(x).slice(0,-6),A=OR(S,_,t);if(!x.endsWith(A))throw Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:S,words:_}}let c=$R(a);function u(f){let{prefix:m,words:h}=a(f,!1);return{prefix:m,words:h,bytes:o(h)}}function d(f,m){return s(f,n(m))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:c,fromWords:o,fromWordsUnsafe:i,toWords:n}}var Pr=Object.freeze(BR("bech32")),Zme=Object.freeze(BR("bech32m"));var a8=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),c8={encode(e){return fb(e),e.toHex()},decode(e){return Vo("hex",e),Uint8Array.fromHex(e)}},Ume=Object.freeze(a8?c8:Rr(Ur(4),Or("0123456789abcdef"),Cr(""),zR((e)=>{if(typeof e!=="string"||e.length%2!==0)throw TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));function u8(e,t,r,o){no(e);let n=Mf({dkLen:32,asyncTick:10},o),{c:i,dkLen:s,asyncTick:a}=n;if(St(i,"c"),St(s,"dkLen"),St(a,"asyncTick"),i<1)throw Error("iterations (c) must be >= 1");if(s<1)throw Error('"dkLen" must be >= 1');if(s>4294967295*e.outputLen)throw Error("derived key too long");let c=tb(t,"password"),u=tb(r,"salt"),d=new Uint8Array(s),f=Tn.create(e,c),m=f._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:f,PRFSalt:m}}function d8(e,t,r,o,n){if(e.destroy(),t.destroy(),o)o.destroy();return cr(n),r}function gb(e,t,r,o){let{c:n,dkLen:i,DK:s,PRF:a,PRFSalt:c}=u8(e,t,r,o),u,d=new Uint8Array(4),f=ha(d),m=new Uint8Array(a.outputLen);for(let h=1,b=0;b<i;h++,b+=a.outputLen){let y=s.subarray(b,b+a.outputLen);f.setInt32(0,h,!1),(u=c._cloneInto(u)).update(d).digestInto(m),y.set(m.subarray(0,y.length));for(let S=1;S<n;S++){a._cloneInto(u).update(m).digestInto(m);for(let x=0;x<y.length;x++)y[x]^=m[x]}}return d8(a,c,s,u,m)}function jR(e,t,r,o,n,i){let s=e[t++]^r[o++],a=e[t++]^r[o++],c=e[t++]^r[o++],u=e[t++]^r[o++],d=e[t++]^r[o++],f=e[t++]^r[o++],m=e[t++]^r[o++],h=e[t++]^r[o++],b=e[t++]^r[o++],y=e[t++]^r[o++],S=e[t++]^r[o++],x=e[t++]^r[o++],_=e[t++]^r[o++],A=e[t++]^r[o++],O=e[t++]^r[o++],L=e[t++]^r[o++],z=s,K=a,P=c,W=u,ee=d,j=f,R=m,B=h,I=b,T=y,k=S,M=x,N=_,H=A,G=O,re=L;for(let ae=0;ae<8;ae+=2)ee^=Fe(z+N|0,7),I^=Fe(ee+z|0,9),N^=Fe(I+ee|0,13),z^=Fe(N+I|0,18),T^=Fe(j+K|0,7),H^=Fe(T+j|0,9),K^=Fe(H+T|0,13),j^=Fe(K+H|0,18),G^=Fe(k+R|0,7),P^=Fe(G+k|0,9),R^=Fe(P+G|0,13),k^=Fe(R+P|0,18),W^=Fe(re+M|0,7),B^=Fe(W+re|0,9),M^=Fe(B+W|0,13),re^=Fe(M+B|0,18),K^=Fe(z+W|0,7),P^=Fe(K+z|0,9),W^=Fe(P+K|0,13),z^=Fe(W+P|0,18),R^=Fe(j+ee|0,7),B^=Fe(R+j|0,9),ee^=Fe(B+R|0,13),j^=Fe(ee+B|0,18),M^=Fe(k+T|0,7),I^=Fe(M+k|0,9),T^=Fe(I+M|0,13),k^=Fe(T+I|0,18),N^=Fe(re+G|0,7),H^=Fe(N+re|0,9),G^=Fe(H+N|0,13),re^=Fe(G+H|0,18);n[i++]=s+z|0,n[i++]=a+K|0,n[i++]=c+P|0,n[i++]=u+W|0,n[i++]=d+ee|0,n[i++]=f+j|0,n[i++]=m+R|0,n[i++]=h+B|0,n[i++]=b+I|0,n[i++]=y+T|0,n[i++]=S+k|0,n[i++]=x+M|0,n[i++]=_+N|0,n[i++]=A+H|0,n[i++]=O+G|0,n[i++]=L+re|0}function yb(e,t,r,o,n){let i=o+0,s=o+16*n;for(let a=0;a<16;a++)r[s+a]=e[t+(2*n-1)*16+a];for(let a=0;a<n;a++,i+=16,t+=16){if(jR(r,s,e,t,r,i),a>0)s+=16;jR(r,i,e,t+=16,r,s)}}function f8(e,t,r){let o=Mf({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:i,p:s,dkLen:a,asyncTick:c,maxmem:u,onProgress:d}=o;if(St(n,"N"),St(i,"r"),St(s,"p"),St(a,"dkLen"),St(c,"asyncTick"),St(u,"maxmem"),d!==void 0&&typeof d!=="function")throw Error("progressCb must be a function");let f=128*i,m=f/4,h=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>h)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(h-1)*32/f)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(h-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let b=f*(n+s+1);if(b>u)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+b+", maxmem="+u);let y=gb(vt,e,t,{c:1,dkLen:f*s}),S=Uf(y),x=Uf(new Uint8Array(f*n)),_=Uf(new Uint8Array(f)),A=()=>{};if(d){let O=2*n*s,L=Math.max(Math.floor(O/1e4),1),z=0;A=()=>{if(z++,d&&(!(z%L)||z===O))d(z/O)}}return{N:n,r:i,p:s,dkLen:a,blockSize32:m,V:x,B32:S,B:y,tmp:_,blockMixCb:A,asyncTick:c}}function p8(e,t,r,o,n){let i=gb(vt,e,r,{c:1,dkLen:t});return cr(r,o,n),i}function bb(e,t,r){let{N:o,r:n,p:i,dkLen:s,blockSize32:a,V:c,B32:u,B:d,tmp:f,blockMixCb:m}=f8(e,t,r);eb(u);for(let h=0;h<i;h++){let b=a*h;for(let y=0;y<a;y++)c[y]=u[b+y];for(let y=0,S=0;y<o-1;y++)yb(c,S,c,S+=a,n),m();yb(c,(o-1)*a,u,b,n),m();for(let y=0;y<o;y++){let S=(u[b+a-16]&o-1)>>>0;for(let x=0;x<a;x++)f[x]=u[b+x]^c[S*a+x];yb(f,0,u,b,n),m()}}return eb(u),p8(e,s,d,c,f)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function m8(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Xf(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function ga(e){if(typeof e!=="number")throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function $t(e,t,r=""){let o=m8(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;if(!o)throw TypeError(u);throw RangeError(u)}return e}function Sb(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ZR(e,t,r=!1){$t(e,void 0,"output");let o=t.outputLen;if(e.length<o)throw RangeError("digestInto() expects output buffer of length at least "+o);if(r&&!ya(e))throw Error("invalid output, must be aligned")}function Rn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function nn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function h8(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var os=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),g8=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;var y8=(e)=>{for(let t=0;t<e.length;t++)e[t]=g8(e[t]);return e},so=os?(e)=>e:y8;function UR(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function qR(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function MR(e,t,r){let o=t,n=r||(()=>[]),i=(a,c)=>o(c,...n(a)).update(a).digest(),s=o(new Uint8Array(e),...n(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...c)=>o(a,...c),i}var FR=(e,t)=>{function r(o,...n){if($t(o,void 0,"key"),e.nonceLength!==void 0){let d=n[0];$t(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;if(i&&n[1]!==void 0)$t(n[1],void 0,"AAD");let s=t(o,...n),a=(d,f)=>{if(f!==void 0){if(d!==2)throw Error("cipher output not supported");$t(f,void 0,"output")}},c=!1;return{encrypt(d,f){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,$t(d),a(s.encrypt.length,f),s.encrypt(d,f)},decrypt(d,f){if($t(d),i&&d.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,f),s.decrypt(d,f)}}}return Object.assign(r,e),r};function Dl(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if($t(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!ya(t))throw Error("invalid output, must be aligned");return t}function JR(e,t,r){ga(e),ga(t),Xf(r);let o=new Uint8Array(16),n=h8(o);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),o}function ya(e){return e.byteOffset%4===0}function ba(e){return Uint8Array.from($t(e))}var HR=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),b8=(()=>so(Rn(HR("expand 16-byte k"))))(),S8=(()=>so(Rn(HR("expand 32-byte k"))))();function Je(e,t){return e<<t|e>>>32-t}var Ll=64,v8=16,vb=(()=>4294967295)(),KR=Uint32Array.of();function w8(e,t,r,o,n,i,s,a){let c=n.length,u=new Uint8Array(Ll),d=Rn(u),f=os&&ya(n)&&ya(i),m=f?Rn(n):KR,h=f?Rn(i):KR;if(!os){for(let b=0;b<c;s++){if(e(t,r,o,d,s,a),so(d),s>=vb)throw Error("arx: counter overflow");let y=Math.min(Ll,c-b);for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}return}for(let b=0;b<c;s++){if(e(t,r,o,d,s,a),s>=vb)throw Error("arx: counter overflow");let y=Math.min(Ll,c-b);if(f&&y===Ll){let S=b/4;if(b%4!==0)throw Error("arx: invalid block position");for(let x=0,_;x<v8;x++)_=S+x,h[_]=m[_]^d[x];b+=Ll;continue}for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}}function VR(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=UR({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return ga(n),ga(s),Xf(i),Xf(r),(a,c,u,d,f=0)=>{$t(a,void 0,"key"),$t(c,void 0,"nonce"),$t(u,void 0,"data");let m=u.length;if(d=Dl(m,d,!1),ga(f),f<0||f>=vb)throw Error("arx: counter overflow");let h=[],b=a.length,y,S;if(b===32)h.push(y=ba(a)),S=S8;else if(b===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),S=b8,h.push(y);else throw $t(a,32,"arx key"),Error("invalid key size");if(!os||!ya(c))h.push(c=ba(c));let x=Rn(y);if(o){if(c.length!==24)throw Error("arx: extended nonce must be 24 bytes");let O=c.subarray(0,16);if(os)o(S,x,Rn(O),x);else{let L=so(Uint32Array.from(S));o(L,x,Rn(O),x),nn(L),so(x)}c=c.subarray(16)}else if(!os)so(x);let _=16-n;if(_!==c.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let O=new Uint8Array(12);O.set(c,i?0:12-c.length),c=O,h.push(c)}let A=so(Rn(c));try{return w8(e,S,x,A,u,d,f,s),d}finally{nn(...h)}}}function Mt(e,t){return e[t++]&255|(e[t++]&255)<<8}class WR{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=ba($t(e,32,"key"));let t=Mt(e,0),r=Mt(e,2),o=Mt(e,4),n=Mt(e,6),i=Mt(e,8),s=Mt(e,10),a=Mt(e,12),c=Mt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Mt(e,16+2*u)}process(e,t,r=!1){let o=r?0:2048,{h:n,r:i}=this,s=i[0],a=i[1],c=i[2],u=i[3],d=i[4],f=i[5],m=i[6],h=i[7],b=i[8],y=i[9],S=Mt(e,t+0),x=Mt(e,t+2),_=Mt(e,t+4),A=Mt(e,t+6),O=Mt(e,t+8),L=Mt(e,t+10),z=Mt(e,t+12),K=Mt(e,t+14),P=n[0]+(S&8191),W=n[1]+((S>>>13|x<<3)&8191),ee=n[2]+((x>>>10|_<<6)&8191),j=n[3]+((_>>>7|A<<9)&8191),R=n[4]+((A>>>4|O<<12)&8191),B=n[5]+(O>>>1&8191),I=n[6]+((O>>>14|L<<2)&8191),T=n[7]+((L>>>11|z<<5)&8191),k=n[8]+((z>>>8|K<<8)&8191),M=n[9]+(K>>>5|o),N=0,H=N+P*s+W*(5*y)+ee*(5*b)+j*(5*h)+R*(5*m);N=H>>>13,H&=8191,H+=B*(5*f)+I*(5*d)+T*(5*u)+k*(5*c)+M*(5*a),N+=H>>>13,H&=8191;let G=N+P*a+W*s+ee*(5*y)+j*(5*b)+R*(5*h);N=G>>>13,G&=8191,G+=B*(5*m)+I*(5*f)+T*(5*d)+k*(5*u)+M*(5*c),N+=G>>>13,G&=8191;let re=N+P*c+W*a+ee*s+j*(5*y)+R*(5*b);N=re>>>13,re&=8191,re+=B*(5*h)+I*(5*m)+T*(5*f)+k*(5*d)+M*(5*u),N+=re>>>13,re&=8191;let ae=N+P*u+W*c+ee*a+j*s+R*(5*y);N=ae>>>13,ae&=8191,ae+=B*(5*b)+I*(5*h)+T*(5*m)+k*(5*f)+M*(5*d),N+=ae>>>13,ae&=8191;let pe=N+P*d+W*u+ee*c+j*a+R*s;N=pe>>>13,pe&=8191,pe+=B*(5*y)+I*(5*b)+T*(5*h)+k*(5*m)+M*(5*f),N+=pe>>>13,pe&=8191;let be=N+P*f+W*d+ee*u+j*c+R*a;N=be>>>13,be&=8191,be+=B*s+I*(5*y)+T*(5*b)+k*(5*h)+M*(5*m),N+=be>>>13,be&=8191;let ve=N+P*m+W*f+ee*d+j*u+R*c;N=ve>>>13,ve&=8191,ve+=B*a+I*s+T*(5*y)+k*(5*b)+M*(5*h),N+=ve>>>13,ve&=8191;let ke=N+P*h+W*m+ee*f+j*d+R*u;N=ke>>>13,ke&=8191,ke+=B*c+I*a+T*s+k*(5*y)+M*(5*b),N+=ke>>>13,ke&=8191;let Ie=N+P*b+W*h+ee*m+j*f+R*d;N=Ie>>>13,Ie&=8191,Ie+=B*u+I*c+T*a+k*s+M*(5*y),N+=Ie>>>13,Ie&=8191;let we=N+P*y+W*b+ee*h+j*m+R*f;N=we>>>13,we&=8191,we+=B*d+I*u+T*c+k*a+M*s,N+=we>>>13,we&=8191,N=(N<<2)+N|0,N=N+H|0,H=N&8191,N=N>>>13,G+=N,n[0]=H,n[1]=G,n[2]=re,n[3]=ae,n[4]=pe,n[5]=be,n[6]=ve,n[7]=ke,n[8]=Ie,n[9]=we}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=o,o=e[s]>>>13,e[s]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+o,o=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(o^1)-1;for(let s=0;s<10;s++)r[s]&=n;n=~n;for(let s=0;s<10;s++)e[s]=e[s]&n|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=i&65535;nn(r)}update(e){Sb(this),$t(e),e=ba(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,nn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Sb(this),ZR(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:o}=this;if(o){t[o++]=1;for(;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let i=0;i<8;i++)e[n++]=r[i]>>>0,e[n++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var GR=MR(32,(e)=>new WR(e));function x8(e,t,r,o,n,i=20){let s=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],m=t[2],h=t[3],b=t[4],y=t[5],S=t[6],x=t[7],_=n,A=r[0],O=r[1],L=r[2],z=s,K=a,P=c,W=u,ee=d,j=f,R=m,B=h,I=b,T=y,k=S,M=x,N=_,H=A,G=O,re=L;for(let pe=0;pe<i;pe+=2)z=z+ee|0,N=Je(N^z,16),I=I+N|0,ee=Je(ee^I,12),z=z+ee|0,N=Je(N^z,8),I=I+N|0,ee=Je(ee^I,7),K=K+j|0,H=Je(H^K,16),T=T+H|0,j=Je(j^T,12),K=K+j|0,H=Je(H^K,8),T=T+H|0,j=Je(j^T,7),P=P+R|0,G=Je(G^P,16),k=k+G|0,R=Je(R^k,12),P=P+R|0,G=Je(G^P,8),k=k+G|0,R=Je(R^k,7),W=W+B|0,re=Je(re^W,16),M=M+re|0,B=Je(B^M,12),W=W+B|0,re=Je(re^W,8),M=M+re|0,B=Je(B^M,7),z=z+j|0,re=Je(re^z,16),k=k+re|0,j=Je(j^k,12),z=z+j|0,re=Je(re^z,8),k=k+re|0,j=Je(j^k,7),K=K+R|0,N=Je(N^K,16),M=M+N|0,R=Je(R^M,12),K=K+R|0,N=Je(N^K,8),M=M+N|0,R=Je(R^M,7),P=P+B|0,H=Je(H^P,16),I=I+H|0,B=Je(B^I,12),P=P+B|0,H=Je(H^P,8),I=I+H|0,B=Je(B^I,7),W=W+ee|0,G=Je(G^W,16),T=T+G|0,ee=Je(ee^T,12),W=W+ee|0,G=Je(G^W,8),T=T+G|0,ee=Je(ee^T,7);let ae=0;o[ae++]=s+z|0,o[ae++]=a+K|0,o[ae++]=c+P|0,o[ae++]=u+W|0,o[ae++]=d+ee|0,o[ae++]=f+j|0,o[ae++]=m+R|0,o[ae++]=h+B|0,o[ae++]=b+I|0,o[ae++]=y+T|0,o[ae++]=S+k|0,o[ae++]=x+M|0,o[ae++]=_+N|0,o[ae++]=A+H|0,o[ae++]=O+G|0,o[ae++]=L+re|0}var _8=VR(x8,{counterRight:!1,counterLength:4,allowShortKeys:!1});var E8=new Uint8Array(16),QR=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(E8.subarray(r))},I8=new Uint8Array(32);function YR(e,t,r,o,n){if(n!==void 0)$t(n,void 0,"AAD");let i=e(t,r,I8),s=JR(o.length,n?n.length:0,!0),a=GR.create(i);if(n)QR(a,n);QR(a,o),a.update(s);let c=a.digest();return nn(i,s),c}var k8=(e)=>(t,r,o)=>({encrypt(i,s){let a=i.length;s=Dl(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);e(t,r,c,c,1);let u=YR(e,t,r,c,o);return s.set(u,a),nn(u),s},decrypt(i,s){s=Dl(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),u=YR(e,t,r,a,o);if(!qR(c,u))throw nn(u),Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,r,s,s,1),nn(u),s}}),qr=FR({blockSize:64,nonceLength:12,tagLength:16},k8(_8));/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Sa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Dt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Te(e,t,r=""){let o=Sa(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=o?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+c)}return e}function Mr(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Dt(e.outputLen),Dt(e.blockLen)}function co(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ep(e,t){Te(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function tp(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function vr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function rp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function on(e,t){return e<<32-t|e>>>t}var A8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function T8(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function $8(e){for(let t=0;t<e.length;t++)e[t]=T8(e[t]);return e}var wb=A8?(e)=>e:$8,eO=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),R8=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function is(e){if(Te(e),eO)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=R8[e[r]];return t}var ao={_0:48,_9:57,A:65,F:70,a:97,f:102};function XR(e){if(e>=ao._0&&e<=ao._9)return e-ao._0;if(e>=ao.A&&e<=ao.F)return e-(ao.A-10);if(e>=ao.a&&e<=ao.f)return e-(ao.a-10);return}function ss(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(eO)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=XR(e.charCodeAt(i)),a=XR(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+c+'" at index '+i)}o[n]=s*16+a}return o}function Et(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Te(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function va(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Wo(e=32){let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var Go=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _b=BigInt(0),xb=BigInt(1);function Bl(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function tO(e){if(typeof e==="bigint"){if(!np(e))throw Error("positive bigint expected, got "+e)}else Dt(e);return e}function jl(e){let t=tO(e).toString(16);return t.length&1?"0"+t:t}function rO(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?_b:BigInt("0x"+e)}function Qo(e){return rO(is(e))}function Yo(e){return rO(is(op(Te(e)).reverse()))}function wa(e,t){Dt(t),e=tO(e);let r=ss(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function Zl(e,t){return wa(e,t).reverse()}function op(e){return Uint8Array.from(e)}function Xo(e){return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}var np=(e)=>typeof e==="bigint"&&_b<=e;function O8(e,t,r){return np(e)&&np(t)&&np(r)&&t<=e&&e<r}function Ul(e,t,r,o){if(!O8(t,r,o))throw Error("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Eb(e){let t;for(t=0;e>_b;e>>=xb,t+=1);return t}var ql=(e)=>(xb<<BigInt(e))-xb;function nO(e,t,r){if(Dt(e,"hashLen"),Dt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=o(e),u=o(e),d=0,f=()=>{c.fill(1),u.fill(0),d=0},m=(...S)=>r(u,Et(c,...S)),h=(S=n)=>{if(u=m(i,S),c=m(),S.length===0)return;u=m(s,S),c=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){c=m();let _=c.slice();x.push(_),S+=c.length}return Et(...x)};return(S,x)=>{f(),h(S);let _=void 0;while(!(_=x(b())))h();return f(),_}}function as(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function o(i,s,a){let c=e[i];if(a&&c===void 0)return;let u=typeof c;if(u!==s||c===null)throw Error(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,c])=>o(a,c,s));n(t,!1),n(r,!0)}function Ib(e){let t=new WeakMap;return(r,...o)=>{let n=t.get(r);if(n!==void 0)return n;let i=e(r,...o);return t.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ur=BigInt(0),Xt=BigInt(1),cs=BigInt(2),sO=BigInt(3),aO=BigInt(4),cO=BigInt(5),C8=BigInt(7),lO=BigInt(8),P8=BigInt(9),uO=BigInt(16);function lr(e,t){let r=e%t;return r>=ur?r:t+r}function Fr(e,t,r){let o=e;while(t-- >ur)o*=o,o%=r;return o}function oO(e,t){if(e===ur)throw Error("invert: expected non-zero number");if(t<=ur)throw Error("invert: expected positive modulus, got "+t);let r=lr(e,t),o=t,n=ur,i=Xt,s=Xt,a=ur;while(r!==ur){let u=o/r,d=o%r,f=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=f,a=m}if(o!==Xt)throw Error("invert: does not exist");return lr(n,t)}function kb(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function dO(e,t){let r=(e.ORDER+Xt)/aO,o=e.pow(t,r);return kb(e,o,t),o}function z8(e,t){let r=(e.ORDER-cO)/lO,o=e.mul(t,cs),n=e.pow(o,r),i=e.mul(t,n),s=e.mul(e.mul(i,cs),n),a=e.mul(i,e.sub(s,e.ONE));return kb(e,a,t),a}function N8(e){let t=ip(e),r=fO(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+C8)/uO;return(a,c)=>{let u=a.pow(c,s),d=a.mul(u,o),f=a.mul(u,n),m=a.mul(u,i),h=a.eql(a.sqr(d),c),b=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(m,f,b);let y=a.eql(a.sqr(d),c),S=a.cmov(u,d,y);return kb(a,S,c),S}}function fO(e){if(e<sO)throw Error("sqrt is not defined for small field");let t=e-Xt,r=0;while(t%cs===ur)t/=cs,r++;let o=cs,n=ip(e);while(iO(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return dO;let i=n.pow(o,t),s=(t+Xt)/cs;return function(c,u){if(c.is0(u))return u;if(iO(c,u)!==1)throw Error("Cannot find square root");let d=r,f=c.mul(c.ONE,i),m=c.pow(u,t),h=c.pow(u,s);while(!c.eql(m,c.ONE)){if(c.is0(m))return c.ZERO;let b=1,y=c.sqr(m);while(!c.eql(y,c.ONE))if(b++,y=c.sqr(y),b===d)throw Error("Cannot find square root");let S=Xt<<BigInt(d-b-1),x=c.pow(f,S);d=b,f=c.sqr(x),m=c.mul(m,f),h=c.mul(h,x)}return h}}function D8(e){if(e%aO===sO)return dO;if(e%lO===cO)return z8;if(e%uO===P8)return N8(e);return fO(e)}var L8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ab(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=L8.reduce((o,n)=>(o[n]="function",o),t);return as(e,r),e}function B8(e,t,r){if(r<ur)throw Error("invalid exponent, negatives unsupported");if(r===ur)return e.ONE;if(r===Xt)return t;let o=e.ONE,n=t;while(r>ur){if(r&Xt)o=e.mul(o,n);n=e.sqr(n),r>>=Xt}return o}function Ml(e,t,r=!1){let o=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,c)=>{if(e.is0(a))return s;return o[c]=s,e.mul(s,a)},e.ONE),i=e.inv(n);return t.reduceRight((s,a,c)=>{if(e.is0(a))return s;return o[c]=e.mul(s,o[c]),e.mul(s,a)},i),o}function iO(e,t){let r=(e.ORDER-Xt)/cs,o=e.pow(t,r),n=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),s=e.eql(o,e.neg(e.ONE));if(!n&&!i&&!s)throw Error("invalid Legendre symbol result");return n?1:i?0:-1}function j8(e,t){if(t!==void 0)Dt(t);let r=t!==void 0?t:e.toString(2).length,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}class pO{ORDER;BITS;BYTES;isLE;ZERO=ur;ONE=Xt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=ur)throw Error("invalid field: expected ORDER > 0, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")this.sqrt=t.sqrt;if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=t.allowedLengths?.slice();if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=j8(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return lr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Xt)===Xt}neg(e){return lr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return lr(e*e,this.ORDER)}add(e,t){return lr(e+t,this.ORDER)}sub(e,t){return lr(e-t,this.ORDER)}mul(e,t){return lr(e*t,this.ORDER)}pow(e,t){return B8(this,e,t)}div(e,t){return lr(e*oO(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return oO(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=D8(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?Zl(e,this.BYTES):wa(e,this.BYTES)}fromBytes(e,t=!1){Te(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(o);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?Yo(e):Qo(e);if(s)a=lr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Ml(this,e)}cmov(e,t,r){return r?t:e}}function ip(e,t={}){return new pO(e,t)}function mO(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Tb(e){let t=mO(e);return t+Math.ceil(t/2)}function hO(e,t,r=!1){Te(e);let o=e.length,n=mO(t),i=Tb(t);if(o<16||o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?Yo(e):Qo(e),a=lr(s,t-Xt)+Xt;return r?Zl(a,n):wa(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var xa=BigInt(0),ls=BigInt(1);function Fl(e,t){let r=t.negate();return e?r:t}function Cb(e,t){let r=Ml(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function SO(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function $b(e,t){SO(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=ql(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function gO(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>o)a-=i,c+=ls;let u=t*o,d=u+Math.abs(a)-1,f=a===0,m=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:m,isNegF:h,offsetF:u}}var Rb=new WeakMap,vO=new WeakMap;function Ob(e){return vO.get(e)||1}function yO(e){if(e!==xa)throw Error("invalid wNAF")}class Pb{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>xa){if(t&ls)r=r.add(o);o=o.double(),t>>=ls}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=$b(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let c=1;c<o;c++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=$b(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:c,isZero:u,isNeg:d,isNegF:f,offsetF:m}=gO(r,s,i);if(r=a,u)n=n.add(Fl(f,t[m]));else o=o.add(Fl(d,t[c]))}return yO(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=$b(e,this.bits);for(let i=0;i<n.windows;i++){if(r===xa)break;let{nextN:s,offset:a,isZero:c,isNeg:u}=gO(r,i,n);if(r=s,c)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return yO(r),o}getPrecomputes(e,t,r){let o=Rb.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);Rb.set(t,o)}}return o}cached(e,t,r){let o=Ob(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=Ob(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){SO(t,this.bits),vO.set(e,t),Rb.delete(e)}hasCache(e){return Ob(e)!==1}}function wO(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>xa||o>xa){if(r&ls)i=i.add(n);if(o&ls)s=s.add(n);n=n.double(),r>>=ls,o>>=ls}return{p1:i,p2:s}}function bO(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return Ab(t),t}else return ip(e,{isLE:r})}function xO(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u==="bigint"&&u>xa))throw Error(`CURVE.${c} must be positive bigint`)}let n=bO(t.p,r.Fp,o),i=bO(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function sp(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jl=BigInt(0),_a=BigInt(1),ap=BigInt(2);function Z8(e){return as(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function _O(e){let t=Z8(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let c=s||Wo,u=a?255:448,d=a?32:56,f=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?ap**BigInt(254):ap**BigInt(447),b=a?BigInt(8)*ap**BigInt(251)-_a:BigInt(4)*ap**BigInt(445)-_a,y=h+b+_a,S=(I)=>lr(I,r),x=_(f);function _(I){return Zl(S(I),d)}function A(I){let T=op(Te(I,d,"uCoordinate"));if(a)T[31]&=127;return S(Yo(T))}function O(I){return Yo(n(op(Te(I,d,"scalar"))))}function L(I,T){let k=ee(A(T),O(I));if(k===Jl)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,T,k){let M=S(I*(T-k));return T=S(T-M),k=S(k+M),{x_2:T,x_3:k}}function ee(I,T){Ul("u",I,Jl,r),Ul("scalar",T,h,y);let k=T,M=I,N=_a,H=Jl,G=I,re=_a,ae=Jl;for(let be=BigInt(u-1);be>=Jl;be--){let ve=k>>be&_a;ae^=ve,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=ve;let ke=N+H,Ie=S(ke*ke),we=N-H,Ue=S(we*we),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=S(bt*ke),Nt=S(Qe*we),lt=Tt+Nt,$r=Tt-Nt;G=S(lt*lt),re=S(M*S($r*$r)),N=S(Ie*Ue),H=S(De*(Ie+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let pe=i(H);return S(N*pe)}let j={secretKey:d,publicKey:d,seed:d},R=(I=c(d))=>(Te(I,j.seed,"seed"),I),B={randomSecretKey:R};return Object.freeze({keygen:sp(R,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}class zb{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Mr(e),Te(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),vr(o)}update(e){return co(this),this.iHash.update(e),this}digestInto(e){co(this),Te(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Ea=(e,t,r)=>new zb(e,t).update(r).digest();Ea.create=(e,t)=>new zb(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var EO=(e,t)=>(e+(e>=0?t:-t)/kO)/t;function U8(e,t,r){let[[o,n],[i,s]]=t,a=EO(s*e,r),c=EO(-n*e,r),u=e-a*o-c*i,d=-a*n-c*s,f=u<lo,m=d<lo;if(f)u=-u;if(m)d=-d;let h=ql(Math.ceil(Eb(r)/2))+Ia;if(u<lo||u>=h||d<lo||d>=h)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:m,k2:d}}function Db(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function Nb(e,t){let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(Bl(r.lowS,"lowS"),Bl(r.prehash,"prehash"),r.format!==void 0)Db(r.format);return r}class IO extends Error{constructor(e=""){super(e)}}var ei={Err:IO,_tlv:{encode:(e,t)=>{let{Err:r}=ei;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=jl(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?jl(n.length/2|128):"";return jl(e)+i+n+t},decode(e,t){let{Err:r}=ei,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=ei;if(e<lo)throw new t("integer: negative integers are not allowed");let r=jl(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ei;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Qo(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=ei,n=Te(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=o.decode(2,i),{v:u,l:d}=o.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=ei,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}},lo=BigInt(0),Ia=BigInt(1),kO=BigInt(2),cp=BigInt(3),q8=BigInt(4);function Lb(e,t={}){let r=xO("weierstrass",e,t),{Fp:o,Fn:n}=r,i=r.CURVE,{h:s,n:a}=i;as(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c){if(!o.is0(i.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=TO(o,n);function d(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function f(R,B,I){let{x:T,y:k}=B.toAffine(),M=o.toBytes(T);if(Bl(I,"isCompressed"),I){d();let N=!o.isOdd(k);return Et(AO(N),M)}else return Et(Uint8Array.of(4),M,o.toBytes(k))}function m(R){Te(R,void 0,"Point");let{publicKey:B,publicKeyUncompressed:I}=u,T=R.length,k=R[0],M=R.subarray(1);if(T===B&&(k===2||k===3)){let N=o.fromBytes(M);if(!o.isValid(N))throw Error("bad point: is not on curve, wrong x");let H=y(N),G;try{G=o.sqrt(H)}catch(pe){let be=pe instanceof Error?": "+pe.message:"";throw Error("bad point: is not on curve, sqrt error"+be)}d();let re=o.isOdd(G);if((k&1)===1!==re)G=o.neg(G);return{x:N,y:G}}else if(T===I&&k===4){let N=o.BYTES,H=o.fromBytes(M.subarray(0,N)),G=o.fromBytes(M.subarray(N,N*2));if(!S(H,G))throw Error("bad point: is not on curve");return{x:H,y:G}}else throw Error(`bad point: got length ${T}, expected compressed=${B} or uncompressed=${I}`)}let h=t.toBytes||f,b=t.fromBytes||m;function y(R){let B=o.sqr(R),I=o.mul(B,R);return o.add(o.add(I,o.mul(R,i.a)),i.b)}function S(R,B){let I=o.sqr(B),T=y(R);return o.eql(I,T)}if(!S(i.Gx,i.Gy))throw Error("bad curve params: generator point");let x=o.mul(o.pow(i.a,cp),q8),_=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(x,_)))throw Error("bad curve params: a or b");function A(R,B,I=!1){if(!o.isValid(B)||I&&o.is0(B))throw Error(`bad point coordinate ${R}`);return B}function O(R){if(!(R instanceof W))throw Error("Weierstrass Point expected")}function L(R){if(!c||!c.basises)throw Error("no endo");return U8(R,c.basises,n.ORDER)}let z=Ib((R,B)=>{let{X:I,Y:T,Z:k}=R;if(o.eql(k,o.ONE))return{x:I,y:T};let M=R.is0();if(B==null)B=M?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(T,B),G=o.mul(k,B);if(M)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}),K=Ib((R)=>{if(R.is0()){if(t.allowInfinityPoint&&!o.is0(R.Y))return;throw Error("bad point: ZERO")}let{x:B,y:I}=R.toAffine();if(!o.isValid(B)||!o.isValid(I))throw Error("bad point: x or y not field elements");if(!S(B,I))throw Error("bad point: equation left != right");if(!R.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function P(R,B,I,T,k){return I=new W(o.mul(I.X,R),I.Y,I.Z),B=Fl(T,B),I=Fl(k,I),B.add(I)}class W{static BASE=new W(i.Gx,i.Gy,o.ONE);static ZERO=new W(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(R,B,I){this.X=A("x",R),this.Y=A("y",B,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(R){let{x:B,y:I}=R||{};if(!R||!o.isValid(B)||!o.isValid(I))throw Error("invalid affine point");if(R instanceof W)throw Error("projective point not allowed");if(o.is0(B)&&o.is0(I))return W.ZERO;return new W(B,I,o.ONE)}static fromBytes(R){let B=W.fromAffine(b(Te(R,void 0,"point")));return B.assertValidity(),B}static fromHex(R){return W.fromBytes(ss(R))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(R=8,B=!0){if(j.createCache(this,R),!B)this.multiply(cp);return this}assertValidity(){K(this)}hasEvenY(){let{y:R}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(R)}equals(R){O(R);let{X:B,Y:I,Z:T}=this,{X:k,Y:M,Z:N}=R,H=o.eql(o.mul(B,N),o.mul(k,T)),G=o.eql(o.mul(I,N),o.mul(M,T));return H&&G}negate(){return new W(this.X,o.neg(this.Y),this.Z)}double(){let{a:R,b:B}=i,I=o.mul(B,cp),{X:T,Y:k,Z:M}=this,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=o.mul(T,T),ae=o.mul(k,k),pe=o.mul(M,M),be=o.mul(T,k);return be=o.add(be,be),G=o.mul(T,M),G=o.add(G,G),N=o.mul(R,G),H=o.mul(I,pe),H=o.add(N,H),N=o.sub(ae,H),H=o.add(ae,H),H=o.mul(N,H),N=o.mul(be,N),G=o.mul(I,G),pe=o.mul(R,pe),be=o.sub(re,pe),be=o.mul(R,be),be=o.add(be,G),G=o.add(re,re),re=o.add(G,re),re=o.add(re,pe),re=o.mul(re,be),H=o.add(H,re),pe=o.mul(k,M),pe=o.add(pe,pe),re=o.mul(pe,be),N=o.sub(N,re),G=o.mul(pe,ae),G=o.add(G,G),G=o.add(G,G),new W(N,H,G)}add(R){O(R);let{X:B,Y:I,Z:T}=this,{X:k,Y:M,Z:N}=R,H=o.ZERO,G=o.ZERO,re=o.ZERO,ae=i.a,pe=o.mul(i.b,cp),be=o.mul(B,k),ve=o.mul(I,M),ke=o.mul(T,N),Ie=o.add(B,I),we=o.add(k,M);Ie=o.mul(Ie,we),we=o.add(be,ve),Ie=o.sub(Ie,we),we=o.add(B,T);let Ue=o.add(k,N);return we=o.mul(we,Ue),Ue=o.add(be,ke),we=o.sub(we,Ue),Ue=o.add(I,T),H=o.add(M,N),Ue=o.mul(Ue,H),H=o.add(ve,ke),Ue=o.sub(Ue,H),re=o.mul(ae,we),H=o.mul(pe,ke),re=o.add(H,re),H=o.sub(ve,re),re=o.add(ve,re),G=o.mul(H,re),ve=o.add(be,be),ve=o.add(ve,be),ke=o.mul(ae,ke),we=o.mul(pe,we),ve=o.add(ve,ke),ke=o.sub(be,ke),ke=o.mul(ae,ke),we=o.add(we,ke),be=o.mul(ve,we),G=o.add(G,be),be=o.mul(Ue,we),H=o.mul(Ie,H),H=o.sub(H,be),be=o.mul(Ie,ve),re=o.mul(Ue,re),re=o.add(re,be),new W(H,G,re)}subtract(R){return this.add(R.negate())}is0(){return this.equals(W.ZERO)}multiply(R){let{endo:B}=t;if(!n.isValidNot0(R))throw Error("invalid scalar: out of range");let I,T,k=(M)=>j.cached(this,M,(N)=>Cb(W,N));if(B){let{k1neg:M,k1:N,k2neg:H,k2:G}=L(R),{p:re,f:ae}=k(N),{p:pe,f:be}=k(G);T=ae.add(be),I=P(B.beta,re,pe,M,H)}else{let{p:M,f:N}=k(R);I=M,T=N}return Cb(W,[I,T])[0]}multiplyUnsafe(R){let{endo:B}=t,I=this;if(!n.isValid(R))throw Error("invalid scalar: out of range");if(R===lo||I.is0())return W.ZERO;if(R===Ia)return I;if(j.hasCache(this))return this.multiply(R);if(B){let{k1neg:T,k1:k,k2neg:M,k2:N}=L(R),{p1:H,p2:G}=wO(W,I,k,N);return P(B.beta,H,G,T,M)}else return j.unsafe(I,R)}toAffine(R){return z(this,R)}isTorsionFree(){let{isTorsionFree:R}=t;if(s===Ia)return!0;if(R)return R(W,this);return j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:R}=t;if(s===Ia)return this;if(R)return R(W,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(R=!0){return Bl(R,"isCompressed"),this.assertValidity(),h(W,this,R)}toHex(R=!0){return is(this.toBytes(R))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ee=n.BITS,j=new Pb(W,t.endo?Math.ceil(ee/2):ee);return W.BASE.precompute(8),W}function AO(e){return Uint8Array.of(e?2:3)}function TO(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function M8(e,t={}){let{Fn:r}=e,o=t.randomBytes||Wo,n=Object.assign(TO(e.Fp,r),{seed:Tb(r.ORDER)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h=o(n.seed)){return hO(Te(h,n.seed,"seed"),r.ORDER)}function c(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n;if(!Sa(h))return;if("_lengths"in r&&r._lengths||b===y)return;let x=Te(h,void 0,"key").length;return x===y||x===S}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let f={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=sp(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:e,utils:f,lengths:n})}function Bb(e,t,r={}){Mr(t),as(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes||Wo,n=r.hmac||((I,T)=>Ea(t,I,T)),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:m,lengths:h}=M8(e,r),b={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*kO<i.ORDER;function S(I){let T=a>>Ia;return I>T}function x(I,T){if(!s.isValidNot0(T))throw Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return T}function _(){if(y)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(I,T){Db(T);let k=h.signature,M=T==="compact"?k:T==="recovered"?k+1:void 0;return Te(I,M)}class O{r;s;recovery;constructor(I,T,k){if(this.r=x("r",I),this.s=x("s",T),k!=null){if(_(),![0,1,2,3].includes(k))throw Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(I,T=b.format){A(I,T);let k;if(T==="der"){let{r:G,s:re}=ei.toSig(Te(I));return new O(G,re)}if(T==="recovered")k=I[0],T="compact",I=I.subarray(1);let M=h.signature/2,N=I.subarray(0,M),H=I.subarray(M,M*2);return new O(s.fromBytes(N),s.fromBytes(H),k)}static fromHex(I,T){return this.fromBytes(ss(I),T)}assertRecovery(){let{recovery:I}=this;if(I==null)throw Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new O(this.r,this.s,I)}recoverPublicKey(I){let{r:T,s:k}=this,M=this.assertRecovery(),N=M===2||M===3?T+a:T;if(!i.isValid(N))throw Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(N),G=e.fromBytes(Et(AO((M&1)===0),H)),re=s.inv(N),ae=z(Te(I,void 0,"msgHash")),pe=s.create(-ae*re),be=s.create(k*re),ve=e.BASE.multiplyUnsafe(pe).add(G.multiplyUnsafe(be));if(ve.is0())throw Error("invalid recovery: point at infinify");return ve.assertValidity(),ve}hasHighS(){return S(this.s)}toBytes(I=b.format){if(Db(I),I==="der")return ss(ei.hexFromSig(this));let{r:T,s:k}=this,M=s.toBytes(T),N=s.toBytes(k);if(I==="recovered")return _(),Et(Uint8Array.of(this.assertRecovery()),M,N);return Et(M,N)}toHex(I){return is(this.toBytes(I))}}let L=r.bits2int||function(T){if(T.length>8192)throw Error("input is too large");let k=Qo(T),M=T.length*8-c;return M>0?k>>BigInt(M):k},z=r.bits2int_modN||function(T){return s.create(L(T))},K=ql(c);function P(I){return Ul("num < 2^"+c,I,lo,K),s.toBytes(I)}function W(I,T){return Te(I,void 0,"message"),T?Te(t(I),void 0,"prehashed message"):I}function ee(I,T,k){let{lowS:M,prehash:N,extraEntropy:H}=Nb(k,b);I=W(I,N);let G=z(I),re=s.fromBytes(T);if(!s.isValidNot0(re))throw Error("invalid private key");let ae=[P(re),P(G)];if(H!=null&&H!==!1){let ke=H===!0?o(h.secretKey):H;ae.push(Te(ke,void 0,"extraEntropy"))}let pe=Et(...ae),be=G;function ve(ke){let Ie=L(ke);if(!s.isValidNot0(Ie))return;let we=s.inv(Ie),Ue=e.BASE.multiply(Ie).toAffine(),De=s.create(Ue.x);if(De===lo)return;let Qe=s.create(we*s.create(be+De*re));if(Qe===lo)return;let bt=(Ue.x===De?0:2)|Number(Ue.y&Ia),Tt=Qe;if(M&&S(Qe))Tt=s.neg(Qe),bt^=1;return new O(De,Tt,y?void 0:bt)}return{seed:pe,k2sig:ve}}function j(I,T,k={}){let{seed:M,k2sig:N}=ee(I,T,k);return nO(t.outputLen,s.BYTES,n)(M,N).toBytes(k.format)}function R(I,T,k,M={}){let{lowS:N,prehash:H,format:G}=Nb(M,b);if(k=Te(k,void 0,"publicKey"),T=W(T,H),!Sa(I)){let re=I instanceof O?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+re)}A(I,G);try{let re=O.fromBytes(I,G),ae=e.fromBytes(k);if(N&&re.hasHighS())return!1;let{r:pe,s:be}=re,ve=z(T),ke=s.inv(be),Ie=s.create(ve*ke),we=s.create(pe*ke),Ue=e.BASE.multiplyUnsafe(Ie).add(ae.multiplyUnsafe(we));if(Ue.is0())return!1;return s.create(Ue.x)===pe}catch(re){return!1}}function B(I,T,k={}){let{prehash:M}=Nb(k,b);return T=W(T,M),O.fromBytes(I,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:m,lengths:h,Point:e,sign:j,verify:R,recoverPublicKey:B,Signature:O,hash:t})}function $O(e,t,r){return e&t^~e&r}function RO(e,t,r){return e&t^e&r^t&r}class lp{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=rp(this.buffer)}update(e){co(this),Te(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=rp(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){co(this),ep(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,vr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=rp(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var uo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ft=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);var up=BigInt(4294967295),OO=BigInt(32);function F8(e,t=!1){if(t)return{h:Number(e&up),l:Number(e>>OO&up)};return{h:Number(e>>OO&up)|0,l:Number(e&up)|0}}function dp(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=F8(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}var jb=(e,t,r)=>e>>>r,Zb=(e,t,r)=>e<<32-r|t>>>r,us=(e,t,r)=>e>>>r|t<<32-r,ds=(e,t,r)=>e<<32-r|t>>>r,Kl=(e,t,r)=>e<<64-r|t>>>r-32,Hl=(e,t,r)=>e>>>r-32|t<<64-r;var CO=(e,t,r)=>e<<r|t>>>32-r,PO=(e,t,r)=>t<<r|e>>>32-r,zO=(e,t,r)=>t<<r-32|e>>>64-r,NO=(e,t,r)=>e<<r-32|t>>>64-r;function On(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var DO=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),LO=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,BO=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),jO=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,ZO=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),UO=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var K8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ti=new Uint32Array(64);class qO extends lp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)ti[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=ti[d-15],m=ti[d-2],h=on(f,7)^on(f,18)^f>>>3,b=on(m,17)^on(m,19)^m>>>10;ti[d]=b+ti[d-7]+h+ti[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let f=on(s,6)^on(s,11)^on(s,25),m=u+f+$O(s,a,c)+K8[d]+ti[d]|0,b=(on(r,2)^on(r,13)^on(r,22))+RO(r,o,n)|0;u=c,c=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,c,u)}roundClean(){vr(ti)}destroy(){this.set(0,0,0,0,0,0,0,0),vr(this.buffer)}}class MO extends qO{A=uo[0]|0;B=uo[1]|0;C=uo[2]|0;D=uo[3]|0;E=uo[4]|0;F=uo[5]|0;G=uo[6]|0;H=uo[7]|0;constructor(){super(32)}}var FO=(()=>dp(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),H8=(()=>FO[0])(),V8=(()=>FO[1])(),ri=new Uint32Array(80),ni=new Uint32Array(80);class JO extends lp{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y]}set(e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)ri[_]=e.getUint32(t),ni[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=ri[_-15]|0,O=ni[_-15]|0,L=us(A,O,1)^us(A,O,8)^jb(A,O,7),z=ds(A,O,1)^ds(A,O,8)^Zb(A,O,7),K=ri[_-2]|0,P=ni[_-2]|0,W=us(K,P,19)^Kl(K,P,61)^jb(K,P,6),ee=ds(K,P,19)^Hl(K,P,61)^Zb(K,P,6),j=BO(z,ee,ni[_-7],ni[_-16]),R=jO(j,L,W,ri[_-7],ri[_-16]);ri[_]=R|0,ni[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:f,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=us(d,f,14)^us(d,f,18)^Kl(d,f,41),O=ds(d,f,14)^ds(d,f,18)^Hl(d,f,41),L=d&m^~d&b,z=f&h^~f&y,K=ZO(x,O,z,V8[_],ni[_]),P=UO(K,S,A,L,H8[_],ri[_]),W=K|0,ee=us(r,o,28)^Kl(r,o,34)^Kl(r,o,39),j=ds(r,o,28)^Hl(r,o,34)^Hl(r,o,39),R=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=f|0,{h:d,l:f}=On(c|0,u|0,P|0,W|0),c=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=DO(W,j,B);r=LO(I,P,ee,R),o=I|0}({h:r,l:o}=On(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=On(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=On(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=On(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:f}=On(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=On(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=On(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=On(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,c,u,d,f,m,h,b,y,S,x)}roundClean(){vr(ri,ni)}destroy(){vr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class KO extends JO{Ah=Ft[0]|0;Al=Ft[1]|0;Bh=Ft[2]|0;Bl=Ft[3]|0;Ch=Ft[4]|0;Cl=Ft[5]|0;Dh=Ft[6]|0;Dl=Ft[7]|0;Eh=Ft[8]|0;El=Ft[9]|0;Fh=Ft[10]|0;Fl=Ft[11]|0;Gh=Ft[12]|0;Gl=Ft[13]|0;Hh=Ft[14]|0;Hl=Ft[15]|0;constructor(){super(48)}}var fp=va(()=>new MO,Go(1));var HO=va(()=>new KO,Go(2));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var W8=BigInt(1),VO=BigInt(2),G8=BigInt(3),Q8=BigInt(5),Fhe=BigInt(8),WO=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function Y8(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=WO,a=e*e%i*e%i,c=Fr(a,VO,i)*a%i,u=Fr(c,W8,i)*e%i,d=Fr(u,Q8,i)*u%i,f=Fr(d,t,i)*d%i,m=Fr(f,r,i)*f%i,h=Fr(m,o,i)*m%i,b=Fr(h,n,i)*h%i,y=Fr(b,n,i)*h%i,S=Fr(y,t,i)*d%i;return{pow_p_5_8:Fr(S,VO,i)*e%i,b2:a}}function X8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var GO=(()=>{let e=WO;return _O({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=Y8(t);return lr(Fr(r,G8,e)*o,e)},adjustScalarBytes:X8})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var eJ=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),tJ=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))();var rJ=Lb(eJ),Ub=Bb(rJ,fp);var nJ=Lb(tJ),QO=Bb(nJ,HO);function XO(e,t,r){if(Mr(e),r===void 0)r=new Uint8Array(e.outputLen);return Ea(e,r,t)}var qb=Uint8Array.of(0),YO=Uint8Array.of();function e1(e,t,r,o=32){Mr(e),Dt(o,"length");let n=e.outputLen;if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=YO;else Te(r,void 0,"info");let s=new Uint8Array(i*n),a=Ea.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)qb[0]=d+1,c.update(d===0?YO:u).update(r).update(qb).digestInto(u),s.set(u,n*d),a._cloneInto(c);return a.destroy(),c.destroy(),vr(u,qb),s.slice(0,o)}var oJ=BigInt(0),Vl=BigInt(1),iJ=BigInt(2),sJ=BigInt(7),aJ=BigInt(256),cJ=BigInt(113),n1=[],o1=[],i1=[];for(let e=0,t=Vl,r=1,o=0;e<24;e++){[r,o]=[o,(2*r+3*o)%5],n1.push(2*(5*o+r)),o1.push((e+1)*(e+2)/2%64);let n=oJ;for(let i=0;i<7;i++)if(t=(t<<Vl^(t>>sJ)*cJ)%aJ,t&iJ)n^=Vl<<(Vl<<BigInt(i))-Vl;i1.push(n)}var s1=dp(i1,!0),lJ=s1[0],uJ=s1[1],t1=(e,t,r)=>r>32?zO(e,t,r):CO(e,t,r),r1=(e,t,r)=>r>32?NO(e,t,r):PO(e,t,r);function dJ(e,t=24){let r=new Uint32Array(10);for(let o=24-t;o<24;o++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,u=r[c],d=r[c+1],f=t1(u,d,1)^r[a],m=r1(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=f,e[s+h+1]^=m}let n=e[2],i=e[3];for(let s=0;s<24;s++){let a=o1[s],c=t1(n,i,a),u=r1(n,i,a),d=n1[s];n=e[d],i=e[d+1],e[d]=c,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=lJ[o],e[1]^=uJ[o]}vr(r)}class pp{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=n,Dt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=tp(this.state)}clone(){return this._cloneInto()}keccak(){wb(this.state32),dJ(this.state32,this.rounds),wb(this.state32),this.posOut=0,this.pos=0}update(e){co(this),Te(e);let{blockLen:t,state:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(t-this.pos,o-n);for(let s=0;s<i;s++)r[this.pos++]^=e[n++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:o}=this;if(e[r]^=t,(t&128)!==0&&r===o-1)this.keccak();e[o-1]^=128,this.keccak()}writeInto(e){co(this,!1),Te(e),this.finish();let t=this.state,{blockLen:r}=this;for(let o=0,n=e.length;o<n;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,n-o);e.set(t.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Dt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ep(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,vr(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:o,rounds:n,enableXOF:i}=this;return e||=new pp(t,r,o,i,n),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}var a1=(e,t,r,o={})=>va(()=>new pp(t,e,r),o);var fs=a1(6,136,32,Go(8));var c1=a1(6,72,64,Go(10));var l1=(e,t,r,o={})=>va((n={})=>new pp(t,e,n.dkLen===void 0?r:n.dkLen,!0),o),u1=l1(31,168,16,Go(11)),Cn=l1(31,136,32,Go(12));function Mb(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function f1(e){return Mb(e),(e&e-1)===0&&e!==0}function Fb(e,t){Mb(e);let r=0;for(let o=0;o<t;o++,e>>>=1)r=r<<1|e&1;return r}function p1(e){return Mb(e),31-Math.clz32(e)}function d1(e){let t=e.length;if(t<2||!f1(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=p1(t);for(let o=0;o<t;o++){let n=Fb(o,r);if(o<n){let i=e[o];e[o]=e[n],e[n]=i}}return e}var Jb=(e,t)=>{let{N:r,roots:o,dit:n,invertButterflies:i=!1,skipStages:s=0,brp:a=!0}=t,c=p1(r);if(!f1(r))throw Error("FFT: Polynomial size should be power of two");let u=n!==i;return(d)=>{if(d.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)d1(d);for(let f=0,m=1;f<c-s;f++){let h=n?f+1+s:c-f,b=1<<h,y=b>>1,S=r>>h;for(let x=0;x<r;x+=b)for(let _=0,A=m++;_<y;_++){let O=i?n?r-A:A:_*S,L=x+_,z=x+_+y,K=o[O],P=d[z],W=d[L];if(u){let ee=e.mul(P,K);d[L]=e.add(W,ee),d[z]=e.sub(W,ee)}else if(i)d[L]=e.add(P,W),d[z]=e.mul(e.sub(P,W),K);else d[L]=e.add(W,P),d[z]=e.mul(e.sub(W,P),K)}}if(!n&&a)d1(d);return d}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var Pn=Wo;function mp(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function m1(e){return Uint8Array.from(e)}function ps(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,o=t.reduce((n,i)=>n+r(i),0);return{bytesLen:o,encode:(n)=>{let i=new Uint8Array(o);for(let s=0,a=0;s<t.length;s++){let c=t[s],u=r(c),d=typeof c==="number"?n[s]:c.encode(n[s]);if(Te(d,u,e),i.set(d,a),typeof c!=="number")d.fill(0);a+=u}return i},decode:(n)=>{Te(n,o,e);let i=[];for(let s of t){let a=r(s),c=n.subarray(0,a);i.push(typeof s==="number"?c:s.decode(c)),n=n.subarray(a)}return i}}}function hp(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(o)=>{if(o.length!==t)throw Error(`vecCoder.encode: wrong length=${o.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let i=0,s=0;i<o.length;i++){let a=e.encode(o[i]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(o)=>{Te(o,r);let n=[];for(let i=0;i<o.length;i+=e.bytesLen)n.push(e.decode(o.subarray(i,i+e.bytesLen)));return n}}}function Rt(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function Kb(e){return(1<<e)-1}var ige=Uint8Array.of();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var h1=(e)=>{let{newPoly:t,N:r,Q:o,F:n,ROOT_OF_UNITY:i,brvBits:s,isKyber:a}=e,c=(_,A=o)=>{let O=_%A|0;return(O>=0?O|0:A+O|0)|0},u=(_,A=o)=>{let O=c(_,A)|0;return(O>A>>1?O-A|0:O)|0};function d(){let _=t(r);for(let A=0;A<r;A++){let O=Fb(A,s),L=BigInt(i)**BigInt(O)%BigInt(o);_[A]=Number(L)|0}return _}let f=d(),m={add:(_,A)=>c((_|0)+(A|0))|0,sub:(_,A)=>c((_|0)-(A|0))|0,mul:(_,A)=>c((_|0)*(A|0))|0,inv:(_)=>{throw Error("not implemented")}},h={N:r,roots:f,invertButterflies:!0,skipStages:a?1:0,brp:!1},b=Jb(m,{dit:!1,...h}),y=Jb(m,{dit:!0,...h});return{mod:c,smod:u,nttZetas:f,NTT:{encode:(_)=>b(_),decode:(_)=>{y(_);for(let A=0;A<_.length;A++)_[A]=c(n*_[A]);return _}},bitsCoder:(_,A)=>{let O=Kb(_),L=_*(r/8);return{bytesLen:L,encode:(z)=>{let K=new Uint8Array(L);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=(A.encode(z[P])&O)<<ee,ee+=_;for(;ee>=8;ee-=8,W>>=8)K[j++]=W&Kb(ee)}return K},decode:(z)=>{let K=t(r);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=z[P]<<ee,ee+=8;for(;ee>=_;ee-=_,W>>=_)K[j++]=A.decode(W&O)}return K}}}}},fJ=(e)=>(t,r)=>{if(!r)r=e.blockLen;let o=new Uint8Array(t.length+2);o.set(t);let n=t.length,i=new Uint8Array(r),s=e.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(u,d)=>(o[n+0]=u,o[n+1]=d,s.destroy(),s=e.create({}).update(o),a++,()=>(c++,s.xofInto(i))),clean:()=>{s.destroy(),Rt(i,o)}}},g1=fJ(u1);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var er=256,fo=3329,pJ=3303,mJ=17,{mod:Ql,nttZetas:hJ,NTT:ms,bitsCoder:gJ}=h1({N:er,Q:fo,F:pJ,ROOT_OF_UNITY:mJ,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0}),Hb={512:{N:er,Q:fo,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:er,Q:fo,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:er,Q:fo,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}},yJ=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+fo/2)/fo,decode:(r)=>r*fo+t>>>e}},Wl=(e)=>gJ(e,yJ(e));function hs(e,t){for(let r=0;r<er;r++)e[r]=Ql(e[r]+t[r])}function bJ(e,t){for(let r=0;r<er;r++)e[r]=Ql(e[r]-t[r])}function SJ(e,t,r,o,n){let i=Ql(t*o*n+e*r),s=Ql(e*o+t*r);return{c0:i,c1:s}}function gp(e,t){for(let r=0;r<er/2;r++){let o=hJ[64+(r>>1)];if(r&1)o=-o;let{c0:n,c1:i}=SJ(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],o);e[2*r+0]=n,e[2*r+1]=i}return e}function y1(e){let t=new Uint16Array(er);for(let r=0;r<er;){let o=e();if(o.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<er&&n+3<=o.length;n+=3){let i=(o[n+0]>>0|o[n+1]<<8)&4095,s=(o[n+1]>>4|o[n+2]<<4)&4095;if(i<fo)t[r++]=i;if(r<er&&s<fo)t[r++]=s}}return t}function Gl(e,t,r,o){let n=e(o*er/4,t,r),i=new Uint16Array(er),s=tp(n),a=0;for(let c=0,u=0,d=0,f=0;c<s.length;c++){let m=s[c];for(let h=0;h<32;h++)if(d+=m&1,m>>=1,a+=1,a===o)f=d,d=0;else if(a===2*o)i[u++]=Ql(f-d),d=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return i}var vJ=(e)=>{let{K:t,PRF:r,XOF:o,HASH512:n,ETA1:i,ETA2:s,du:a,dv:c}=e,u=Wl(1),d=Wl(c),f=Wl(a),m=ps("publicKey",hp(Wl(12),t),32),h=hp(Wl(12),t),b=ps("ciphertext",hp(f,t),d),y=ps("seed",32,32);return{secretCoder:h,lengths:{secretKey:h.bytesLen,publicKey:m.bytesLen,cipherText:b.bytesLen},keygen:(S)=>{Te(S,32,"seed");let x=new Uint8Array(33);x.set(S),x[32]=t;let _=n(x),[A,O]=y.decode(_),L=[],z=[];for(let W=0;W<t;W++)L.push(ms.encode(Gl(r,O,W,i)));let K=o(A);for(let W=0;W<t;W++){let ee=ms.encode(Gl(r,O,t+W,i));for(let j=0;j<t;j++){let R=y1(K.get(j,W));hs(ee,gp(R,L[j]))}z.push(ee)}K.clean();let P={publicKey:m.encode([z,A]),secretKey:h.encode(L)};return Rt(A,O,L,z,x,_),P},encrypt:(S,x,_)=>{let[A,O]=m.decode(S),L=[];for(let j=0;j<t;j++)L.push(ms.encode(Gl(r,_,j,i)));let z=o(O),K=new Uint16Array(er),P=[];for(let j=0;j<t;j++){let R=Gl(r,_,t+j,s),B=new Uint16Array(er);for(let I=0;I<t;I++){let T=y1(z.get(j,I));hs(B,gp(T,L[I]))}hs(R,ms.decode(B)),P.push(R),hs(K,gp(A[j],L[j])),Rt(B)}z.clean();let W=Gl(r,_,2*t,s);hs(W,ms.decode(K));let ee=u.decode(x);return hs(ee,W),Rt(A,L,K,W),b.encode([P,ee])},decrypt:(S,x)=>{let[_,A]=b.decode(S),O=h.decode(x),L=new Uint16Array(er);for(let z=0;z<t;z++)hs(L,gp(O[z],ms.encode(_[z])));return bJ(A,ms.decode(L)),Rt(L,O,_),u.encode(A)}}};function Vb(e){let t=vJ(e),{HASH256:r,HASH512:o,KDF:n}=e,{secretCoder:i,lengths:s}=t,a=ps("secretKey",s.secretKey,s.publicKey,32,32),c=32,u=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(d=Pn(64))=>{Te(d,64,"seed");let{publicKey:f,secretKey:m}=t.keygen(d.subarray(0,32)),h=r(f),b=a.encode([m,f,h,d.subarray(32)]);return Rt(m,h),{publicKey:f,secretKey:b}},getPublicKey:(d)=>{let[f,m,h,b]=a.decode(d);return Uint8Array.from(m)},encapsulate:(d,f=Pn(32))=>{Te(d,s.publicKey,"publicKey"),Te(f,32,"message");let m=d.subarray(0,384*e.K),h=i.encode(i.decode(m1(m)));if(!mp(h,m))throw Rt(h),Error("ML-KEM.encapsulate: wrong publicKey modulus");Rt(h);let b=o.create().update(f).update(r(d)).digest(),y=t.encrypt(d,f,b.subarray(32,64));return Rt(b.subarray(32)),{cipherText:y,sharedSecret:b.subarray(0,32)}},decapsulate:(d,f)=>{Te(f,a.bytesLen,"secretKey"),Te(d,s.cipherText,"cipherText");let m=a.bytesLen-96,h=m+32,b=r(f.subarray(m/2,h));if(!mp(b,f.subarray(h,h+32)))throw Error("invalid secretKey: hash check failed");let[y,S,x,_]=a.decode(f),A=t.decrypt(d,y),O=o.create().update(A).update(x).digest(),L=O.subarray(0,32),z=t.encrypt(S,A,O.subarray(32,64)),K=mp(d,z),P=n.create({dkLen:32}).update(_).update(d).digest();return Rt(A,z,!K?L:P),K?L:P}}}function wJ(e,t,r){return Cn.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var Wb={HASH256:fs,HASH512:c1,KDF:Cn,XOF:g1,PRF:wJ},gge=Vb({...Wb,...Hb[512]}),Yl=Vb({...Wb,...Hb[768]}),b1=Vb({...Wb,...Hb[1024]});/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */function xJ(e,t=!1){let{lengths:r,keygen:o}=e;if(t){let i=e.Point.Fn;if(!i)throw Error("No Point.Fn");o=(s=Pn(r.seed))=>{Te(s,r.seed,"seed");let a=i.isLE?Yo(s):Qo(s),c=i.toBytes(i.create(a));return{secretKey:c,publicKey:e.getPublicKey(c)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:o,getPublicKey:(n)=>e.getPublicKey(n)}}function Gb(e,t=!1){let r=xJ(e,t);if(!e.getSharedSecret)throw Error("wrong curve");return{lengths:{...r.lengths,msg:r.lengths.seed,cipherText:r.lengths.publicKey},keygen:r.keygen,getPublicKey:r.getPublicKey,encapsulate(o,n=Pn(e.lengths.seed)){let i=this.keygen(n).secretKey,s=this.decapsulate(o,i),a=e.getPublicKey(i);return Rt(i),{sharedSecret:s,cipherText:a}},decapsulate(o,n){let i=e.getSharedSecret(n,o);return e.lengths.publicKeyHasPrefix?i.subarray(1):i}}}function Xl(e,t){return ps(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function Qb(e){return(t,r)=>e(t,{dkLen:r})}function _J(e,t,...r){let o=Xl(r,"seed"),n=Xl(r,"publicKey");if(e===void 0)e=o.bytesLen;Dt(e);function i(s){Te(s,e);let a=o.decode(t(s,o.bytesLen)),c=r.map((f,m)=>f.keygen(a[m])),u=c.map((f)=>f.secretKey),d=c.map((f)=>f.publicKey);return{secretKey:u,publicKey:d}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Pn(e)){let{publicKey:a,secretKey:c}=i(s),u=n.encode(a);return Rt(a),Rt(c),{secretKey:s,publicKey:u}},expandDecapsulationKey:i,realSeedLen:e}}function yp(e,t,r,o,...n){let i=_J(e,r,...n),s=Xl(n,"cipherText"),a=Xl(n,"publicKey"),c=Xl(n,"msg");if(t===void 0)t=c.bytesLen;return Dt(t),{lengths:{...i.info.lengths,msg:t,msgRand:c.bytesLen,cipherText:s.bytesLen},getPublicKey:i.getPublicKey,keygen:i.keygen,encapsulate(u,d=Pn(c.bytesLen)){let f=a.decode(u),m=c.decode(d),h=n.map((x,_)=>x.encapsulate(f[_],m[_])),b=h.map((x)=>x.sharedSecret),y=h.map((x)=>x.cipherText),S={sharedSecret:o(f,y,b),cipherText:s.encode(y)};return Rt(b,y),S},decapsulate(u,d){let f=s.decode(u),{publicKey:m,secretKey:h}=i.expandDecapsulationKey(d),b=n.map((y,S)=>y.decapsulate(f[S],h[S]));return o(m,f,b)}}}function S1(e,t,r,o,n){return Mr(o),Mr(n),yp(32,32,Qb(o),(i,s,a)=>n(Et(a[0],a[1],s[1],i[1],Xo(e))),t,r)}var Age=S1("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",Yl,Gb(Ub,!0),Cn,fs),Tge=S1("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",b1,Gb(QO,!0),Cn,fs);function EJ(e,t,r,o,n){return Mr(o),Mr(n),yp(32,32,Qb(o),(i,s,a)=>{let c=Et(a[0],a[1],s[0],i[0],s[1],i[1],Xo(e)),u=32,d=Et(Xo("hybrid_prk"),c),f=XO(n,d),m=Et(wa(32,2),Xo("shared_secret"),Xo("")),h=e1(n,f,m,32);return Rt(f,m,d,c),h},t,r)}var v1=Gb(GO),$ge=EJ("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",Yl,v1,Cn,fp),IJ=(()=>yp(32,32,Qb(Cn),(e,t,r)=>fs(Et(r[0],r[1],t[1],e[1],Xo("\\.//^\\"))),Yl,v1))();function kJ(e,t,r,o){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function i(s){let a;for(let d=0,f=t;;d=f,f+=t){if(f>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(d,f),!0),n.isValidNot0(a))break}let c=n.toBytes(n.create(a)),u=e.getPublicKey(c,!1);return{secretKey:c,publicKey:u}}return{lengths:{secretKey:t,publicKey:r,seed:o,msg:o,cipherText:r},keygen(s=Pn(o)){return Te(s,o,"seed"),i(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Pn(o)){Te(a,o,"rand");let{secretKey:c}=i(a),u=this.decapsulate(s,c),d=e.getPublicKey(c,!1);return Rt(c),{sharedSecret:u,cipherText:d}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function AJ(e,t,r,o){let{secretKey:n,publicKeyUncompressed:i}=r.lengths;if(!n||!i)throw Error("wrong curve");let s=kJ(r,n,i,o),a=64,c=a+o;return yp(32,32,(u)=>{Te(u,32);let d=Cn(u,{dkLen:c}),f=d.subarray(0,a),m=d.subarray(a,c);return Et(f,m)},(u,d,f)=>fs(Et(f[0],f[1],d[1],u[1],Xo(e))),t,s)}var TJ=(()=>AJ("MLKEM768-P256",Yl,Ub,128))();var bp=IJ,w1=TJ;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ye=(e,t,r)=>Ut(e,t,r),Xb=St,ka=qf,Jt=(...e)=>rb(...e),Aa=(e)=>Rl(e),Ta=Xy,$a=(e)=>oo(e),vp=BigInt(0),Yb=BigInt(1);function po(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function wp(e){if(typeof e==="bigint"){if(!Sp(e))throw RangeError("positive bigint expected, got "+e)}else Xb(e);return e}function zn(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function eu(e){let t=wp(e).toString(16);return t.length&1?"0"+t:t}function x1(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?vp:BigInt("0x"+e)}function gs(e){return x1(qf(e))}function sn(e){return x1(qf(oi(Ut(e)).reverse()))}function xp(e,t){if(St(t),t===0)throw RangeError("zero length");e=wp(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return Rl(r.padStart(t*2,"0"))}function tu(e,t){return xp(e,t).reverse()}function _1(e,t){if(e=Ye(e),t=Ye(t),e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function oi(e){return Uint8Array.from(Ye(e))}function _p(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}var Sp=(e)=>typeof e==="bigint"&&vp<=e;function $J(e,t,r){return Sp(e)&&Sp(t)&&Sp(r)&&t<=e&&e<r}function mo(e,t,r,o){if(!$J(t,r,o))throw RangeError("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Ra(e){if(e<vp)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>vp;e>>=Yb,t+=1);return t}var ru=(e)=>(Yb<<BigInt(e))-Yb;function E1(e,t,r){if(St(e,"hashLen"),St(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=o(e),u=o(e),d=0,f=()=>{c.fill(1),u.fill(0),d=0},m=(...S)=>r(u,Jt(c,...S)),h=(S=n)=>{if(u=m(i,S),c=m(),S.length===0)return;u=m(s,S),c=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){c=m();let _=c.slice();x.push(_),S+=c.length}return Jt(...x)};return(S,x)=>{f(),h(S);let _=void 0;while((_=x(b()))===void 0)h();return f(),_}}function Jr(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw TypeError(`param "${i}" is invalid: expected own property`);let c=e[i];if(a&&c===void 0)return;let u=typeof c;if(u!==s||c===null)throw TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,c])=>o(a,c,s));n(t,!1),n(r,!0)}var eS=()=>{throw Error("not implemented")};/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Kt=BigInt(0),mt=BigInt(1),ys=BigInt(2),T1=BigInt(3),$1=BigInt(4),R1=BigInt(5),RJ=BigInt(7),O1=BigInt(8),OJ=BigInt(9),C1=BigInt(16);function it(e,t){if(t<=Kt)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Kt?r:t+r}function Kr(e,t,r){if(t<Kt)throw Error("pow2: expected non-negative exponent, got "+t);let o=e;while(t-- >Kt)o*=o,o%=r;return o}function I1(e,t){if(e===Kt)throw Error("invert: expected non-zero number");if(t<=Kt)throw Error("invert: expected positive modulus, got "+t);let r=it(e,t),o=t,n=Kt,i=mt,s=mt,a=Kt;while(r!==Kt){let u=o/r,d=o-r*u,f=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=f,a=m}if(o!==mt)throw Error("invert: does not exist");return it(n,t)}function tS(e,t,r){let o=e;if(!o.eql(o.sqr(t),r))throw Error("Cannot find square root")}function P1(e,t){let r=e,o=(r.ORDER+mt)/$1,n=r.pow(t,o);return tS(r,n,t),n}function CJ(e,t){let r=e,o=(r.ORDER-R1)/O1,n=r.mul(t,ys),i=r.pow(n,o),s=r.mul(t,i),a=r.mul(r.mul(s,ys),i),c=r.mul(s,r.sub(a,r.ONE));return tS(r,c,t),c}function PJ(e){let t=Ep(e),r=z1(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+RJ)/C1;return(a,c)=>{let u=a,d=u.pow(c,s),f=u.mul(d,o),m=u.mul(d,n),h=u.mul(d,i),b=u.eql(u.sqr(f),c),y=u.eql(u.sqr(m),c);d=u.cmov(d,f,b),f=u.cmov(h,m,y);let S=u.eql(u.sqr(f),c),x=u.cmov(d,f,S);return tS(u,x,c),x}}function z1(e){if(e<T1)throw Error("sqrt is not defined for small field");let t=e-mt,r=0;while(t%ys===Kt)t/=ys,r++;let o=ys,n=Ep(e);while(k1(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return P1;let i=n.pow(o,t),s=(t+mt)/ys;return function(c,u){let d=c;if(d.is0(u))return u;if(k1(d,u)!==1)throw Error("Cannot find square root");let f=r,m=d.mul(d.ONE,i),h=d.pow(u,t),b=d.pow(u,s);while(!d.eql(h,d.ONE)){if(d.is0(h))return d.ZERO;let y=1,S=d.sqr(h);while(!d.eql(S,d.ONE))if(y++,S=d.sqr(S),y===f)throw Error("Cannot find square root");let x=mt<<BigInt(f-y-1),_=d.pow(m,x);f=y,m=d.sqr(_),h=d.mul(h,m),b=d.mul(b,_)}return b}}function zJ(e){if(e%$1===T1)return P1;if(e%O1===R1)return CJ;if(e%C1===OJ)return PJ(e);return z1(e)}var ho=(e,t)=>(it(e,t)&mt)===mt,NJ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=NJ.reduce((o,n)=>(o[n]="function",o),t);if(Jr(e,r),zn(e.BYTES,"BYTES"),zn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=mt)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function DJ(e,t,r){let o=e;if(r<Kt)throw Error("invalid exponent, negatives unsupported");if(r===Kt)return o.ONE;if(r===mt)return t;let n=o.ONE,i=t;while(r>Kt){if(r&mt)n=o.mul(n,i);i=o.sqr(i),r>>=mt}return n}function nu(e,t,r=!1){let o=e,n=Array(t.length).fill(r?o.ZERO:void 0),i=t.reduce((a,c,u)=>{if(o.is0(c))return a;return n[u]=a,o.mul(a,c)},o.ONE),s=o.inv(i);return t.reduceRight((a,c,u)=>{if(o.is0(c))return a;return n[u]=o.mul(a,n[u]),o.mul(a,c)},s),n}function k1(e,t){let r=e,o=(r.ORDER-mt)/ys,n=r.pow(t,o),i=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function LJ(e,t){if(t!==void 0)Xb(t);if(e<=Kt)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=Ra(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let o=t!==void 0?t:r,n=Math.ceil(o/8);return{nBitLength:o,nByteLength:n}}var A1=new WeakMap;class nS{ORDER;BITS;BYTES;isLE;ZERO=Kt;ONE=mt;_lengths;_mod;constructor(e,t={}){if(e<=mt)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=LJ(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,Object.freeze(this)}create(e){return it(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Kt<=e&&e<this.ORDER}is0(e){return e===Kt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&mt)===mt}neg(e){return it(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return it(e*e,this.ORDER)}add(e,t){return it(e+t,this.ORDER)}sub(e,t){return it(e-t,this.ORDER)}mul(e,t){return it(e*t,this.ORDER)}pow(e,t){return DJ(this,e,t)}div(e,t){return it(e*I1(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return I1(e,this.ORDER)}sqrt(e){let t=A1.get(this);if(!t)A1.set(this,t=zJ(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?tu(e,this.BYTES):xp(e,this.BYTES)}fromBytes(e,t=!1){Ye(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(o);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?sn(e):gs(e);if(s)a=it(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return nu(this,e)}cmov(e,t,r){return po(r,"condition"),r?t:e}}Object.freeze(nS.prototype);function Ep(e,t={}){return new nS(e,t)}function N1(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=mt)throw Error("field order must be greater than 1");let t=Ra(e-mt);return Math.ceil(t/8)}function oS(e){let t=N1(e);return t+Math.ceil(t/2)}function D1(e,t,r=!1){Ye(e);let o=e.length,n=N1(t),i=Math.max(oS(t),16);if(o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?sn(e):gs(e),a=it(s,t-mt)+mt;return r?tu(a,n):xp(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Oa=BigInt(0),bs=BigInt(1);function ou(e,t){let r=t.negate();return e?r:t}function Ss(e,t){let r=nu(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function Z1(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function iS(e,t){Z1(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=ru(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function L1(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>o)a-=i,c+=bs;let u=t*o,d=u+Math.abs(a)-1,f=a===0,m=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:m,isNegF:h,offsetF:u}}var sS=new WeakMap,U1=new WeakMap;function aS(e){return U1.get(e)||1}function B1(e){if(e!==Oa)throw Error("invalid wNAF")}class iu{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>Oa){if(t&bs)r=r.add(o);o=o.double(),t>>=bs}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=iS(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let c=1;c<o;c++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=iS(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:c,isZero:u,isNeg:d,isNegF:f,offsetF:m}=L1(r,s,i);if(r=a,u)n=n.add(ou(f,t[m]));else o=o.add(ou(d,t[c]))}return B1(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=iS(e,this.bits);for(let i=0;i<n.windows;i++){if(r===Oa)break;let{nextN:s,offset:a,isZero:c,isNeg:u}=L1(r,i,n);if(r=s,c)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return B1(r),o}getPrecomputes(e,t,r){let o=sS.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);sS.set(t,o)}}return o}cached(e,t,r){let o=aS(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=aS(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){Z1(t,this.bits),U1.set(e,t),sS.delete(e)}hasCache(e){return aS(e)!==1}}function q1(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>Oa||o>Oa){if(r&bs)i=i.add(n);if(o&bs)s=s.add(n);n=n.double(),r>>=bs,o>>=bs}return{p1:i,p2:s}}function j1(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return rS(t),t}else return Ep(e,{isLE:r})}function Ip(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u==="bigint"&&u>Oa))throw Error(`CURVE.${c} must be positive bigint`)}let n=j1(t.p,r.Fp,o),i=j1(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function su(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}function au(e,t){if(zn(e),zn(t),t<0||t>4)throw Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let o=t-1;o>=0;o--)r[o]=e&255,e>>>=8;return new Uint8Array(r)}function BJ(e,t){let r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e[o]^t[o];return r}function jJ(e){if(!Ta(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?_p(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function cS(e,t,r,o){if(Ye(e),zn(r),t=jJ(t),t.length>255)t=o(Jt(_p("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:i}=o,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=Jt(t,au(t.length,1)),c=new Uint8Array(i),u=au(r,2),d=Array(s),f=o(Jt(c,e,u,au(0,1),a));d[0]=o(Jt(f,au(1,1),a));for(let h=1;h<s;h++){let b=[BJ(f,d[h-1]),au(h+1,1),a];d[h]=o(Jt(...b))}return Jt(...d).slice(0,r)}var M1="HashToScalar-";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var F1=(e,t)=>(e+(e>=0?t:-t)/K1)/t;function ZJ(e,t,r){mo("scalar",e,Nn,r);let[[o,n],[i,s]]=t,a=F1(s*e,r),c=F1(-n*e,r),u=e-a*o-c*i,d=-a*n-c*s,f=u<Nn,m=d<Nn;if(f)u=-u;if(m)d=-d;let h=ru(Math.ceil(Ra(r)/2))+ii;if(u<Nn||u>=h||d<Nn||d>=h)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:m,k2:d}}function uS(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function lS(e,t){Jr(e);let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(po(r.lowS,"lowS"),po(r.prehash,"prehash"),r.format!==void 0)uS(r.format);return r}class J1 extends Error{constructor(e=""){super(e)}}var an={Err:J1,_tlv:{encode:(e,t)=>{let{Err:r}=an;if(zn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!=="string")throw TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=eu(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?eu(n.length/2|128):"";return eu(e)+i+n+t},decode(e,t){let{Err:r}=an;t=Ye(t,void 0,"DER data");let o=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=an;if(wp(e),e<Nn)throw new t("integer: negative integers are not allowed");let r=eu(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=an;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return gs(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=an,n=Ye(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=o.decode(2,i),{v:u,l:d}=o.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=an,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};Object.freeze(an._tlv);Object.freeze(an._int);Object.freeze(an);var Nn=BigInt(0),ii=BigInt(1),K1=BigInt(2),kp=BigInt(3),UJ=BigInt(4);function H1(e,t={}){let r=Ip("weierstrass",e,t),o=r.Fp,n=r.Fn,i=r.CURVE,{h:s,n:a}=i;Jr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=t;if(c){if(!o.is0(i.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let d=W1(o,n);function f(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function m(j,R,B){if(u&&R.is0())return Uint8Array.of(0);let{x:I,y:T}=R.toAffine(),k=o.toBytes(I);if(po(B,"isCompressed"),B){f();let M=!o.isOdd(T);return Jt(V1(M),k)}else return Jt(Uint8Array.of(4),k,o.toBytes(T))}function h(j){Ye(j,void 0,"Point");let{publicKey:R,publicKeyUncompressed:B}=d,I=j.length,T=j[0],k=j.subarray(1);if(u&&I===1&&T===0)return{x:o.ZERO,y:o.ZERO};if(I===R&&(T===2||T===3)){let M=o.fromBytes(k);if(!o.isValid(M))throw Error("bad point: is not on curve, wrong x");let N=S(M),H;try{H=o.sqrt(N)}catch(ae){let pe=ae instanceof Error?": "+ae.message:"";throw Error("bad point: is not on curve, sqrt error"+pe)}f();let G=o.isOdd(H);if((T&1)===1!==G)H=o.neg(H);return{x:M,y:H}}else if(I===B&&T===4){let M=o.BYTES,N=o.fromBytes(k.subarray(0,M)),H=o.fromBytes(k.subarray(M,M*2));if(!x(N,H))throw Error("bad point: is not on curve");return{x:N,y:H}}else throw Error(`bad point: got length ${I}, expected compressed=${R} or uncompressed=${B}`)}let b=t.toBytes===void 0?m:t.toBytes,y=t.fromBytes===void 0?h:t.fromBytes;function S(j){let R=o.sqr(j),B=o.mul(R,j);return o.add(o.add(B,o.mul(j,i.a)),i.b)}function x(j,R){let B=o.sqr(R),I=S(j);return o.eql(B,I)}if(!x(i.Gx,i.Gy))throw Error("bad curve params: generator point");let _=o.mul(o.pow(i.a,kp),UJ),A=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(_,A)))throw Error("bad curve params: a or b");function O(j,R,B=!1){if(!o.isValid(R)||B&&o.is0(R))throw Error(`bad point coordinate ${j}`);return R}function L(j){if(!(j instanceof P))throw Error("Weierstrass Point expected")}function z(j){if(!c||!c.basises)throw Error("no endo");return ZJ(j,c.basises,n.ORDER)}function K(j,R,B,I,T){return B=new P(o.mul(B.X,j),B.Y,B.Z),R=ou(I,R),B=ou(T,B),R.add(B)}class P{static BASE=new P(i.Gx,i.Gy,o.ONE);static ZERO=new P(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(j,R,B){this.X=O("x",j),this.Y=O("y",R,!0),this.Z=O("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(j){let{x:R,y:B}=j||{};if(!j||!o.isValid(R)||!o.isValid(B))throw Error("invalid affine point");if(j instanceof P)throw Error("projective point not allowed");if(o.is0(R)&&o.is0(B))return P.ZERO;return new P(R,B,o.ONE)}static fromBytes(j){let R=P.fromAffine(y(Ye(j,void 0,"point")));return R.assertValidity(),R}static fromHex(j){return P.fromBytes(Aa(j))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,R=!0){if(ee.createCache(this,j),!R)this.multiply(kp);return this}assertValidity(){let j=this;if(j.is0()){if(t.allowInfinityPoint&&o.is0(j.X)&&o.eql(j.Y,o.ONE)&&o.is0(j.Z))return;throw Error("bad point: ZERO")}let{x:R,y:B}=j.toAffine();if(!o.isValid(R)||!o.isValid(B))throw Error("bad point: x or y not field elements");if(!x(R,B))throw Error("bad point: equation left != right");if(!j.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:j}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(j)}equals(j){L(j);let{X:R,Y:B,Z:I}=this,{X:T,Y:k,Z:M}=j,N=o.eql(o.mul(R,M),o.mul(T,I)),H=o.eql(o.mul(B,M),o.mul(k,I));return N&&H}negate(){return new P(this.X,o.neg(this.Y),this.Z)}double(){let{a:j,b:R}=i,B=o.mul(R,kp),{X:I,Y:T,Z:k}=this,M=o.ZERO,N=o.ZERO,H=o.ZERO,G=o.mul(I,I),re=o.mul(T,T),ae=o.mul(k,k),pe=o.mul(I,T);return pe=o.add(pe,pe),H=o.mul(I,k),H=o.add(H,H),M=o.mul(j,H),N=o.mul(B,ae),N=o.add(M,N),M=o.sub(re,N),N=o.add(re,N),N=o.mul(M,N),M=o.mul(pe,M),H=o.mul(B,H),ae=o.mul(j,ae),pe=o.sub(G,ae),pe=o.mul(j,pe),pe=o.add(pe,H),H=o.add(G,G),G=o.add(H,G),G=o.add(G,ae),G=o.mul(G,pe),N=o.add(N,G),ae=o.mul(T,k),ae=o.add(ae,ae),G=o.mul(ae,pe),M=o.sub(M,G),H=o.mul(ae,re),H=o.add(H,H),H=o.add(H,H),new P(M,N,H)}add(j){L(j);let{X:R,Y:B,Z:I}=this,{X:T,Y:k,Z:M}=j,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=i.a,ae=o.mul(i.b,kp),pe=o.mul(R,T),be=o.mul(B,k),ve=o.mul(I,M),ke=o.add(R,B),Ie=o.add(T,k);ke=o.mul(ke,Ie),Ie=o.add(pe,be),ke=o.sub(ke,Ie),Ie=o.add(R,I);let we=o.add(T,M);return Ie=o.mul(Ie,we),we=o.add(pe,ve),Ie=o.sub(Ie,we),we=o.add(B,I),N=o.add(k,M),we=o.mul(we,N),N=o.add(be,ve),we=o.sub(we,N),G=o.mul(re,Ie),N=o.mul(ae,ve),G=o.add(N,G),N=o.sub(be,G),G=o.add(be,G),H=o.mul(N,G),be=o.add(pe,pe),be=o.add(be,pe),ve=o.mul(re,ve),Ie=o.mul(ae,Ie),be=o.add(be,ve),ve=o.sub(pe,ve),ve=o.mul(re,ve),Ie=o.add(Ie,ve),pe=o.mul(be,Ie),H=o.add(H,pe),pe=o.mul(we,Ie),N=o.mul(ke,N),N=o.sub(N,pe),pe=o.mul(ke,be),G=o.mul(we,G),G=o.add(G,pe),new P(N,H,G)}subtract(j){return L(j),this.add(j.negate())}is0(){return this.equals(P.ZERO)}multiply(j){let{endo:R}=t;if(!n.isValidNot0(j))throw RangeError("invalid scalar: out of range");let B,I,T=(k)=>ee.cached(this,k,(M)=>Ss(P,M));if(R){let{k1neg:k,k1:M,k2neg:N,k2:H}=z(j),{p:G,f:re}=T(M),{p:ae,f:pe}=T(H);I=re.add(pe),B=K(R.beta,G,ae,k,N)}else{let{p:k,f:M}=T(j);B=k,I=M}return Ss(P,[B,I])[0]}multiplyUnsafe(j){let{endo:R}=t,B=this,I=j;if(!n.isValid(I))throw RangeError("invalid scalar: out of range");if(I===Nn||B.is0())return P.ZERO;if(I===ii)return B;if(ee.hasCache(this))return this.multiply(I);if(R){let{k1neg:T,k1:k,k2neg:M,k2:N}=z(I),{p1:H,p2:G}=q1(P,B,k,N);return K(R.beta,H,G,T,M)}else return ee.unsafe(B,I)}toAffine(j){let R=this,B=j,{X:I,Y:T,Z:k}=R;if(o.eql(k,o.ONE))return{x:I,y:T};let M=R.is0();if(B==null)B=M?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(T,B),G=o.mul(k,B);if(M)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){let{isTorsionFree:j}=t;if(s===ii)return!0;if(j)return j(P,this);return ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:j}=t;if(s===ii)return this;if(j)return j(P,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===ii)return this.is0();return this.clearCofactor().is0()}toBytes(j=!0){return po(j,"isCompressed"),this.assertValidity(),b(P,this,j)}toHex(j=!0){return ka(this.toBytes(j))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=n.BITS,ee=new iu(P,t.endo?Math.ceil(W/2):W);if(W>=8)P.BASE.precompute(8);return Object.freeze(P.prototype),Object.freeze(P),P}function V1(e){return Uint8Array.of(e?2:3)}function W1(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function qJ(e,t={}){let{Fn:r}=e,o=t.randomBytes===void 0?$a:t.randomBytes,n=Object.assign(W1(e.Fp,r),{seed:Math.max(oS(r.ORDER),16)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h){return h=h===void 0?o(n.seed):h,D1(Ye(h,n.seed,"seed"),r.ORDER)}function c(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n,x=r._lengths;if(!Ta(h))return;let _=Ye(h,void 0,"key").length,A=_===y||_===S,O=_===b||!!x?.includes(_);if(A&&O)return;return A}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let f={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=su(a,c);return Object.freeze(f),Object.freeze(n),Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:e,utils:f,lengths:n})}function G1(e,t,r={}){let o=t;no(o),Jr(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?$a:r.randomBytes,i=r.hmac===void 0?(T,k)=>Tn(o,T,k):r.hmac,{Fp:s,Fn:a}=e,{ORDER:c,BITS:u}=a,{keygen:d,getPublicKey:f,getSharedSecret:m,utils:h,lengths:b}=qJ(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},S=c*K1+ii<s.ORDER;function x(T){let k=c>>ii;return T>k}function _(T,k){if(!a.isValidNot0(k))throw Error(`invalid signature ${T}: out of range 1..Point.Fn.ORDER`);return k}function A(){if(S)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(T,k){uS(k);let M=b.signature,N=k==="compact"?M:k==="recovered"?M+1:void 0;return Ye(T,N)}class L{r;s;recovery;constructor(T,k,M){if(this.r=_("r",T),this.s=_("s",k),M!=null){if(A(),![0,1,2,3].includes(M))throw Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(T,k=y.format){O(T,k);let M;if(k==="der"){let{r:re,s:ae}=an.toSig(Ye(T));return new L(re,ae)}if(k==="recovered")M=T[0],k="compact",T=T.subarray(1);let N=b.signature/2,H=T.subarray(0,N),G=T.subarray(N,N*2);return new L(a.fromBytes(H),a.fromBytes(G),M)}static fromHex(T,k){return this.fromBytes(Aa(T),k)}assertRecovery(){let{recovery:T}=this;if(T==null)throw Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new L(this.r,this.s,T)}recoverPublicKey(T){let{r:k,s:M}=this,N=this.assertRecovery(),H=N===2||N===3?k+c:k;if(!s.isValid(H))throw Error("invalid recovery id: sig.r+curve.n != R.x");let G=s.toBytes(H),re=e.fromBytes(Jt(V1((N&1)===0),G)),ae=a.inv(H),pe=K(Ye(T,void 0,"msgHash")),be=a.create(-pe*ae),ve=a.create(M*ae),ke=e.BASE.multiplyUnsafe(be).add(re.multiplyUnsafe(ve));if(ke.is0())throw Error("invalid recovery: point at infinify");return ke.assertValidity(),ke}hasHighS(){return x(this.s)}toBytes(T=y.format){if(uS(T),T==="der")return Aa(an.hexFromSig(this));let{r:k,s:M}=this,N=a.toBytes(k),H=a.toBytes(M);if(T==="recovered")return A(),Jt(Uint8Array.of(this.assertRecovery()),N,H);return Jt(N,H)}toHex(T){return ka(this.toBytes(T))}}Object.freeze(L.prototype),Object.freeze(L);let z=r.bits2int===void 0?function(k){if(k.length>8192)throw Error("input is too large");let M=gs(k),N=k.length*8-u;return N>0?M>>BigInt(N):M}:r.bits2int,K=r.bits2int_modN===void 0?function(k){return a.create(z(k))}:r.bits2int_modN,P=ru(u);function W(T){return mo("num < 2^"+u,T,Nn,P),a.toBytes(T)}function ee(T,k){return Ye(T,void 0,"message"),k?Ye(o(T),void 0,"prehashed message"):T}function j(T,k,M){let{lowS:N,prehash:H,extraEntropy:G}=lS(M,y);T=ee(T,H);let re=K(T),ae=a.fromBytes(k);if(!a.isValidNot0(ae))throw Error("invalid private key");let pe=[W(ae),W(re)];if(G!=null&&G!==!1){let Ie=G===!0?n(b.secretKey):G;pe.push(Ye(Ie,void 0,"extraEntropy"))}let be=Jt(...pe),ve=re;function ke(Ie){let we=z(Ie);if(!a.isValidNot0(we))return;let Ue=a.inv(we),De=e.BASE.multiply(we).toAffine(),Qe=a.create(De.x);if(Qe===Nn)return;let bt=a.create(Ue*a.create(ve+Qe*ae));if(bt===Nn)return;let Tt=(De.x===Qe?0:2)|Number(De.y&ii),Nt=bt;if(N&&x(bt))Nt=a.neg(bt),Tt^=1;return new L(Qe,Nt,S?void 0:Tt)}return{seed:be,k2sig:ke}}function R(T,k,M={}){let{seed:N,k2sig:H}=j(T,k,M);return E1(o.outputLen,a.BYTES,i)(N,H).toBytes(M.format)}function B(T,k,M,N={}){let{lowS:H,prehash:G,format:re}=lS(N,y);if(M=Ye(M,void 0,"publicKey"),k=ee(k,G),!Ta(T)){let ae=T instanceof L?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ae)}O(T,re);try{let ae=L.fromBytes(T,re),pe=e.fromBytes(M);if(H&&ae.hasHighS())return!1;let{r:be,s:ve}=ae,ke=K(k),Ie=a.inv(ve),we=a.create(ke*Ie),Ue=a.create(be*Ie),De=e.BASE.multiplyUnsafe(we).add(pe.multiplyUnsafe(Ue));if(De.is0())return!1;return a.create(De.x)===be}catch(ae){return!1}}function I(T,k,M={}){let{prehash:N}=lS(M,y);return k=ee(k,N),L.fromBytes(T,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:d,getPublicKey:f,getSharedSecret:m,utils:h,lengths:b,Point:e,sign:R,verify:B,recoverPublicKey:I,Signature:L,hash:o})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var MJ=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))();var FJ=H1(MJ),Ca=G1(FJ,vt);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var si=BigInt(0),wr=BigInt(1),dS=BigInt(2),JJ=BigInt(8);function KJ(e,t,r,o){let n=e.sqr(r),i=e.sqr(o),s=e.add(e.mul(t.a,n),i),a=e.add(e.ONE,e.mul(t.d,e.mul(n,i)));return e.eql(s,a)}function Q1(e,t={}){let r=t,o=Ip("edwards",e,r,r.FpFnLE),{Fp:n,Fn:i}=o,s=o.CURVE,{h:a}=s;Jr(r,{},{uvRatio:"function"});let c=dS<<BigInt(i.BYTES*8)-wr,u=(y)=>n.create(y),d=r.uvRatio===void 0?(y,S)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,S))}}catch(x){return{isValid:!1,value:si}}}:r.uvRatio;if(!KJ(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function f(y,S,x=!1){let _=x?wr:si;return mo("coordinate "+y,S,_,c),S}function m(y){if(!(y instanceof h))throw Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,wr,u(s.Gx*s.Gy));static ZERO=new h(si,wr,wr,si);static Fp=n;static Fn=i;X;Y;Z;T;constructor(y,S,x,_){this.X=f("x",y),this.Y=f("y",S),this.Z=f("z",x,!0),this.T=f("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw Error("extended point not allowed");let{x:S,y:x}=y||{};return f("x",S),f("y",x),new h(S,x,wr,u(S*x))}static fromBytes(y,S=!1){let x=n.BYTES,{a:_,d:A}=s;y=oi(Ye(y,x,"point")),po(S,"zip215");let O=oi(y),L=y[x-1];O[x-1]=L&-129;let z=sn(O),K=S?c:n.ORDER;mo("point.y",z,si,K);let P=u(z*z),W=u(P-wr),ee=u(A*P-_),{isValid:j,value:R}=d(W,ee);if(!j)throw Error("bad point: invalid y coordinate");let B=(R&wr)===wr,I=(L&128)!==0;if(!S&&R===si&&I)throw Error("bad point: x=0 and x_0=1");if(I!==B)R=u(-R);return h.fromAffine({x:R,y:z})}static fromHex(y,S=!1){return h.fromBytes(Aa(y),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,S=!0){if(b.createCache(this,y),!S)this.multiply(dS);return this}assertValidity(){let y=this,{a:S,d:x}=s;if(y.is0())throw Error("bad point: ZERO");let{X:_,Y:A,Z:O,T:L}=y,z=u(_*_),K=u(A*A),P=u(O*O),W=u(P*P),ee=u(z*S),j=u(P*u(ee+K)),R=u(W+u(x*u(z*K)));if(j!==R)throw Error("bad point: equation left != right (1)");let B=u(_*A),I=u(O*L);if(B!==I)throw Error("bad point: equation left != right (2)")}equals(y){m(y);let{X:S,Y:x,Z:_}=this,{X:A,Y:O,Z:L}=y,z=u(S*L),K=u(A*_),P=u(x*L),W=u(O*_);return z===K&&P===W}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:y}=s,{X:S,Y:x,Z:_}=this,A=u(S*S),O=u(x*x),L=u(dS*u(_*_)),z=u(y*A),K=S+x,P=u(u(K*K)-A-O),W=z+O,ee=W-L,j=z-O,R=u(P*ee),B=u(W*j),I=u(P*j),T=u(ee*W);return new h(R,B,T,I)}add(y){m(y);let{a:S,d:x}=s,{X:_,Y:A,Z:O,T:L}=this,{X:z,Y:K,Z:P,T:W}=y,ee=u(_*z),j=u(A*K),R=u(L*x*W),B=u(O*P),I=u((_+A)*(z+K)-ee-j),T=B-R,k=B+R,M=u(j-S*ee),N=u(I*T),H=u(k*M),G=u(I*M),re=u(T*k);return new h(N,H,re,G)}subtract(y){return m(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:x}=b.cached(this,y,(_)=>Ss(h,_));return Ss(h,[S,x])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(y===si)return h.ZERO;if(this.is0()||y===wr)return this;return b.unsafe(this,y,(S)=>Ss(h,S))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(y){let S=this,x=y,{X:_,Y:A,Z:O}=S,L=S.is0();if(x==null)x=L?JJ:n.inv(O);let z=u(_*x),K=u(A*x),P=n.mul(O,x);if(L)return{x:si,y:wr};if(P!==wr)throw Error("invZ was invalid");return{x:z,y:K}}clearCofactor(){if(a===wr)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:y,y:S}=this.toAffine(),x=n.toBytes(S);return x[x.length-1]|=y&wr?128:0,x}toHex(){return ka(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new iu(h,i.BITS);if(i.BITS>=8)h.BASE.precompute(8);return Object.freeze(h.prototype),Object.freeze(h),h}class fS{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){eS()}static fromHex(e){eS()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return ka(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var cu=BigInt(0),Pa=BigInt(1),Ap=BigInt(2);function HJ(e){return Jr(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function Y1(e){let t=HJ(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let c=s===void 0?$a:s,u=a?255:448,d=a?32:56,f=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?Ap**BigInt(254):Ap**BigInt(447),b=a?BigInt(8)*Ap**BigInt(251)-Pa:BigInt(4)*Ap**BigInt(445)-Pa,y=h+b+Pa,S=(I)=>it(I,r),x=_(f);function _(I){return tu(S(I),d)}function A(I){let T=oi(Ye(I,d,"uCoordinate"));if(a)T[31]&=127;return S(sn(T))}function O(I){return sn(n(oi(Ye(I,d,"scalar"))))}function L(I,T){let k=ee(A(T),O(I));if(k===cu)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,T,k){let M=S(I*(T-k));return T=S(T-M),k=S(k+M),{x_2:T,x_3:k}}function ee(I,T){mo("u",I,cu,r),mo("scalar",T,h,y);let k=T,M=I,N=Pa,H=cu,G=I,re=Pa,ae=cu;for(let be=BigInt(u-1);be>=cu;be--){let ve=k>>be&Pa;ae^=ve,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=ve;let ke=N+H,Ie=S(ke*ke),we=N-H,Ue=S(we*we),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=S(bt*ke),Nt=S(Qe*we),lt=Tt+Nt,$r=Tt-Nt;G=S(lt*lt),re=S(M*S($r*$r)),N=S(Ie*Ue),H=S(De*(Ie+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let pe=i(H);return S(N*pe)}let j={secretKey:d,publicKey:d,seed:d},R=(I)=>(I=I===void 0?c(d):I,Ye(I,j.seed,"seed"),I),B={randomSecretKey:R};return Object.freeze(j),Object.freeze(B),Object.freeze({keygen:su(R,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var VJ=BigInt(0),go=BigInt(1),X1=BigInt(2),WJ=BigInt(3),GJ=BigInt(5),QJ=BigInt(8),ws=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gS=(()=>({p:ws,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:QJ,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function rC(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=ws,a=e*e%i*e%i,c=Kr(a,X1,i)*a%i,u=Kr(c,go,i)*e%i,d=Kr(u,GJ,i)*u%i,f=Kr(d,t,i)*d%i,m=Kr(f,r,i)*f%i,h=Kr(m,o,i)*m%i,b=Kr(h,n,i)*h%i,y=Kr(b,n,i)*h%i,S=Kr(y,t,i)*d%i;return{pow_p_5_8:Kr(S,X1,i)*e%i,b2:a}}function YJ(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var pS=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function yS(e,t){let r=ws,o=it(t*t*t,r),n=it(o*o*t,r),i=rC(e*n).pow_p_5_8,s=it(e*o*i,r),a=it(t*s*s,r),c=s,u=it(s*pS,r),d=a===e,f=a===it(-e,r),m=a===it(-e*pS,r);if(d)s=c;if(f||m)s=u;if(ho(s,r))s=it(-s,r);return{isValid:d||f,value:s}}var vs=Q1(gS,{uvRatio:yS}),ai=(()=>vs.Fp)(),nC=(()=>vs.Fn)();var Tp=(()=>{let e=ws;return Y1({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=rC(t);return it(Kr(r,WJ,e)*o,e)},adjustScalarBytes:YJ})})();var mS=pS,XJ=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),eK=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),tK=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rK=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),eC=(e)=>yS(go,e),nK=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),hS=(e)=>ai.create(sn(e)&nK);function tC(e){let{d:t}=gS,r=ws,o=(x)=>ai.create(x),n=o(mS*e*e),i=o((n+go)*tK),s=BigInt(-1),a=o((s-t*n)*o(n+t)),{isValid:c,value:u}=yS(i,a),d=o(u*e);if(!ho(d,r))d=o(-d);if(!c)u=d;if(!c)s=n;let f=o(s*(n-go)*rK-a),m=u*u,h=o((u+u)*a),b=o(f*XJ),y=o(go-m),S=o(go+m);return new vs(o(h*S),o(y*b),o(b*S),o(h*y))}class dr extends fS{static BASE=(()=>new dr(vs.BASE))();static ZERO=(()=>new dr(vs.ZERO))();static Fp=(()=>ai)();static Fn=(()=>nC)();constructor(e){super(e)}static fromAffine(e){return new dr(vs.fromAffine(e))}assertSame(e){if(!(e instanceof dr))throw Error("RistrettoPoint expected")}init(e){return new dr(e)}static fromBytes(e){Ut(e,32);let{a:t,d:r}=gS,o=ws,n=(A)=>ai.create(A),i=hS(e);if(!_1(ai.toBytes(i),e)||ho(i,o))throw Error("invalid ristretto255 encoding 1");let s=n(i*i),a=n(go+t*s),c=n(go-t*s),u=n(a*a),d=n(c*c),f=n(t*r*u-d),{isValid:m,value:h}=eC(n(f*d)),b=n(h*c),y=n(h*b*f),S=n((i+i)*b);if(ho(S,o))S=n(-S);let x=n(a*y),_=n(S*x);if(!m||ho(_,o)||x===VJ)throw Error("invalid ristretto255 encoding 2");return new dr(new vs(S,x,go,_))}static fromHex(e){return dr.fromBytes(Rl(e))}toBytes(){let{X:e,Y:t,Z:r,T:o}=this.ep,n=ws,i=(y)=>ai.create(y),s=i(i(r+t)*i(r-t)),a=i(e*t),c=i(a*a),{value:u}=eC(i(s*c)),d=i(u*s),f=i(u*a),m=i(d*f*o),h;if(ho(o*m,n)){let y=i(t*mS),S=i(e*mS);e=y,t=S,h=i(d*eK)}else h=f;if(ho(e*m,n))t=i(-t);let b=i((r-t)*h);if(ho(b,n))b=i(-b);return ai.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:o,Y:n}=e.ep,i=(c)=>ai.create(c),s=i(t*n)===i(r*o),a=i(r*n)===i(t*o);return s||a}is0(){return this.equals(dr.ZERO)}}Object.freeze(dr.BASE);Object.freeze(dr.ZERO);Object.freeze(dr.prototype);Object.freeze(dr);var oK=Object.freeze({Point:dr,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,o=cS(e,r,64,Kf);return oK.deriveToCurve(o)},hashToScalar(e,t={DST:M1}){let r=cS(e,t.DST,64,Kf);return nC.create(sn(r))},deriveToCurve(e){Ut(e,64);let t=hS(e.subarray(0,32)),r=tC(t),o=hS(e.subarray(32,64)),n=tC(o);return new dr(r.add(n))}});var oC=!1,iK=!1;async function iC(e,t){if(iK)return await t();try{return await e()}catch(r){if(r instanceof ReferenceError||r instanceof DOMException&&r.name==="NotSupportedError")return await t();else throw r}}async function $p(e,t){return await iC(async()=>{let r=bS(e)?e:await aK(e),o=await crypto.subtle.importKey("raw",cK(t),{name:"X25519"},oC,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:o},r,256))},()=>{if(bS(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return Tp.scalarMult(e,t)})}async function lu(e){return await iC(async()=>$p(e,Tp.GuBytes),()=>{if(bS(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return Tp.scalarMultBase(e)})}var sK=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function aK(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...sK,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},oC,["deriveBits"])}function bS(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function cK(e){return e}class SS{s;transcript=[];buf=new Uint8Array(0);constructor(e){this.s=e.getReader()}async readLine(){let e=[];while(!0){let t=this.buf.indexOf(10);if(t>=0)return e.push(this.buf.subarray(0,t)),this.transcript.push(this.buf.subarray(0,t+1)),this.buf=this.buf.subarray(t+1),uK(xs(e));if(this.buf.length>0)e.push(this.buf),this.transcript.push(this.buf);let r=await this.s.read();if(r.done)return this.buf=xs(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:xs(this.transcript)}}}function uK(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function xs(e){let t=e.reduce((n,i)=>n+i.length,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function za(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let o of t)r.enqueue(o)}}))}function Rp(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function vS(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function sC(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function aC(e,t){let r=e.getReader(),o=[],n=0;while(n<t){let{done:c,value:u}=await r.read();if(c)throw Error("stream ended before reading "+t.toString()+" bytes");o.push(u),n+=u.length}r.releaseLock();let i=xs(o),s=i.subarray(0,t),a=za(e,i.subarray(t));return{data:s,rest:a}}class Dn{args;body;constructor(e,t){this.args=e,this.body=t}}async function dK(e){let t=await e.readLine();if(t===null)throw Error("invalid stanza");let r=t.split(" ");if(r.length<2||r.shift()!=="->")return{next:t};for(let i of r)if(i.length===0)throw Error("invalid stanza");let o=[];for(;;){let i=await e.readLine();if(i===null)throw Error("invalid stanza");let s=Yt.decode(i);if(s.length>48)throw Error("invalid stanza");if(o.push(s),s.length<48)break}let n=xs(o);return{s:new Dn(r,n)}}async function cC(e){let t=new SS(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let o=[];for(;;){let{s:n,next:i}=await dK(t);if(n!==void 0){o.push(n);continue}if(!i.startsWith("--- "))throw Error("invalid header");let s=Yt.decode(i.slice(4)),{rest:a,transcript:c}=t.close(),u=c.slice(0,c.length-1-i.length+3);return{stanzas:o,headerNoMAC:u,MAC:s,headerSize:c.length,rest:za(e,a)}}}function wS(e){let t=[];t.push(`age-encryption.org/v1
|
|
701
|
+
`)}function lR(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function nt(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ts(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var jf={name:"@rizom/ops",version:"0.2.0-alpha.675",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};import{existsSync as xK,mkdirSync as _K,readFileSync as jS,writeFileSync as ZS}from"fs";import{dirname as EK,join as bC}from"path";function Xy(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function St(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function Ut(e,t,r=""){let o=Xy(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;if(!o)throw TypeError(u);throw RangeError(u)}return e}function no(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(St(e.outputLen),St(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function ma(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Zf(e,t){Ut(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function Uf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function cr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ha(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rn(e,t){return e<<32-t|e>>>t}function Fe(e,t){return e<<t|e>>>32-t>>>0}var W5=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function G5(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Q5(e){for(let t=0;t<e.length;t++)e[t]=G5(e[t]);return e}var eb=W5?(e)=>e:Q5,dR=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Y5=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function qf(e){if(Ut(e),dR)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Y5[e[r]];return t}var ro={_0:48,_9:57,A:65,F:70,a:97,f:102};function uR(e){if(e>=ro._0&&e<=ro._9)return e-ro._0;if(e>=ro.A&&e<=ro.F)return e-(ro.A-10);if(e>=ro.a&&e<=ro.f)return e-(ro.a-10);return}function Rl(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(dR)try{return Uint8Array.fromHex(e)}catch(n){if(n instanceof SyntaxError)throw RangeError(n.message);throw n}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=uR(e.charCodeAt(i)),a=uR(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}o[n]=s*16+a}return o}function X5(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function tb(e,t=""){if(typeof e==="string")return X5(e);return Ut(e,void 0,t)}function rb(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Ut(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function Mf(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw TypeError("options must be object or undefined");return Object.assign(e,t)}function nb(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.canXOF=o.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function oo(e=32){St(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var ob=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});class ib{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(no(e),Ut(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),cr(o)}update(e){return ma(this),this.iHash.update(e),this}digestInto(e){ma(this),Zf(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Tn=(()=>{let e=(t,r,o)=>new ib(t,r).update(o).digest();return e.create=(t,r)=>new ib(t,r),e})();function Ol(e,t,r){if(no(e),r===void 0)r=new Uint8Array(e.outputLen);return Tn(e,r,t)}var sb=Uint8Array.of(0),fR=Uint8Array.of();function ab(e,t,r,o=32){no(e),St(o,"length"),Ut(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=fR;else Ut(r,void 0,"info");let s=new Uint8Array(i*n),a=Tn.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)sb[0]=d+1,c.update(d===0?fR:u).update(r).update(sb).digestInto(u),s.set(u,n*d),a._cloneInto(c);return a.destroy(),c.destroy(),cr(u,sb),s.slice(0,o)}var Fo=(e,t,r,o,n)=>ab(e,Ol(e,t,r),o,n);function pR(e,t,r){return e&t^~e&r}function mR(e,t,r){return e&t^e&r^t&r}class Ff{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ha(this.buffer)}update(e){ma(this),Ut(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=ha(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){ma(this),Zf(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,cr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=ha(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var io=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Jf=BigInt(4294967295),hR=BigInt(32);function e8(e,t=!1){if(t)return{h:Number(e&Jf),l:Number(e>>hR&Jf)};return{h:Number(e>>hR&Jf)|0,l:Number(e&Jf)|0}}function gR(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=e8(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}var cb=(e,t,r)=>e>>>r,lb=(e,t,r)=>e<<32-r|t>>>r,rs=(e,t,r)=>e>>>r|t<<32-r,ns=(e,t,r)=>e<<32-r|t>>>r,Cl=(e,t,r)=>e<<64-r|t>>>r-32,Pl=(e,t,r)=>e>>>r-32|t<<64-r;function $n(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var yR=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),bR=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,SR=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),vR=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,wR=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),xR=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var r8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jo=new Uint32Array(64);class _R extends Ff{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Jo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Jo[d-15],m=Jo[d-2],h=rn(f,7)^rn(f,18)^f>>>3,b=rn(m,17)^rn(m,19)^m>>>10;Jo[d]=b+Jo[d-7]+h+Jo[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let f=rn(s,6)^rn(s,11)^rn(s,25),m=u+f+pR(s,a,c)+r8[d]+Jo[d]|0,b=(rn(r,2)^rn(r,13)^rn(r,22))+mR(r,o,n)|0;u=c,c=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,c,u)}roundClean(){cr(Jo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}}class ER extends _R{A=io[0]|0;B=io[1]|0;C=io[2]|0;D=io[3]|0;E=io[4]|0;F=io[5]|0;G=io[6]|0;H=io[7]|0;constructor(){super(32)}}var IR=(()=>gR(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),n8=(()=>IR[0])(),o8=(()=>IR[1])(),Ko=new Uint32Array(80),Ho=new Uint32Array(80);class kR extends Ff{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y]}set(e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ko[_]=e.getUint32(t),Ho[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Ko[_-15]|0,O=Ho[_-15]|0,L=rs(A,O,1)^rs(A,O,8)^cb(A,O,7),z=ns(A,O,1)^ns(A,O,8)^lb(A,O,7),K=Ko[_-2]|0,P=Ho[_-2]|0,W=rs(K,P,19)^Cl(K,P,61)^cb(K,P,6),ee=ns(K,P,19)^Pl(K,P,61)^lb(K,P,6),j=SR(z,ee,Ho[_-7],Ho[_-16]),R=vR(j,L,W,Ko[_-7],Ko[_-16]);Ko[_]=R|0,Ho[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:f,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=rs(d,f,14)^rs(d,f,18)^Cl(d,f,41),O=ns(d,f,14)^ns(d,f,18)^Pl(d,f,41),L=d&m^~d&b,z=f&h^~f&y,K=wR(x,O,z,o8[_],Ho[_]),P=xR(K,S,A,L,n8[_],Ko[_]),W=K|0,ee=rs(r,o,28)^Cl(r,o,34)^Cl(r,o,39),j=ns(r,o,28)^Pl(r,o,34)^Pl(r,o,39),R=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=f|0,{h:d,l:f}=$n(c|0,u|0,P|0,W|0),c=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=yR(W,j,B);r=bR(I,P,ee,R),o=I|0}({h:r,l:o}=$n(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=$n(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=$n(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$n(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:f}=$n(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=$n(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=$n(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=$n(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,c,u,d,f,m,h,b,y,S,x)}roundClean(){cr(Ko,Ho)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class AR extends kR{Ah=qt[0]|0;Al=qt[1]|0;Bh=qt[2]|0;Bl=qt[3]|0;Ch=qt[4]|0;Cl=qt[5]|0;Dh=qt[6]|0;Dl=qt[7]|0;Eh=qt[8]|0;El=qt[9]|0;Fh=qt[10]|0;Fl=qt[11]|0;Gh=qt[12]|0;Gl=qt[13]|0;Hh=qt[14]|0;Hl=qt[15]|0;constructor(){super(64)}}var vt=nb(()=>new ER,ob(1));var Kf=nb(()=>new AR,ob(3));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Qf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function fb(e){if(!Qf(e))throw TypeError("Uint8Array expected")}function CR(e,t){if(!Array.isArray(t))return!1;if(t.length===0)return!0;if(e)return t.every((r)=>typeof r==="string");else return t.every((r)=>Number.isSafeInteger(r))}function PR(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function Vo(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function Nl(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function Vf(e){if(!Array.isArray(e))throw TypeError("array expected")}function Wf(e,t){if(!CR(!0,t))throw TypeError(`${e}: array of strings expected`)}function pb(e,t){if(!CR(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Rr(...e){let t=(i)=>i,r=(i,s)=>(a)=>i(s(a)),o=e.map((i)=>i.encode).reduceRight(r,t),n=e.map((i)=>i.decode).reduce(r,t);return{encode:o,decode:n}}function Or(e){let t=typeof e==="string"?e.split(""):e,r=t.length;Wf("alphabet",t);let o=new Map(t.map((n,i)=>[n,i]));return{encode:(n)=>(Vf(n),n.map((i)=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:(n)=>(Vf(n),n.map((i)=>{Vo("alphabet.decode",i);let s=o.get(i);if(s===void 0)throw Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Cr(e=""){return Vo("join",e),{encode:(t)=>(Wf("join.decode",t),t.join(e)),decode:(t)=>(Vo("join.decode",t),t.split(e))}}function Yf(e,t="="){return Nl(e),Vo("padding",t),{encode(r){Wf("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){Wf("padding.decode",r);let o=r.length;if(o*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;o>0&&r[o-1]===t;o--)if((o-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,o)}}}function zR(e){return PR(e),{encode:(t)=>t,decode:(t)=>e(t)}}function TR(e,t,r){if(t<2)throw RangeError(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw RangeError(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Vf(e),!e.length)return[];let o=0,n=[],i=Array.from(e,(a)=>{if(Nl(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=i.length;while(!0){let a=0,c=!0;for(let u=o;u<s;u++){let d=i[u],f=t*a,m=f+d;if(!Number.isSafeInteger(m)||f/t!==a||m-d!==f)throw Error("convertRadix: carry overflow");let h=m/r;a=m%r;let b=Math.floor(h);if(i[u]=b,!Number.isSafeInteger(b)||b*r+a!==m)throw Error("convertRadix: carry overflow");if(!c)continue;else if(!b)o=u;else c=!1}if(n.push(a),c)break}for(let a=0;a<e.length-1&&e[a]===0;a++)n.push(0);return n.reverse()}var NR=(e,t)=>t===0?e:NR(t,e%t),Gf=(e,t)=>e+(t-NR(e,t)),Hf=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function ub(e,t,r,o){if(Vf(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if(Gf(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${Gf(t,r)}`);let n=0,i=0,s=Hf[t],a=Hf[r]-1,c=[];for(let u of e){if(Nl(u),u>=s)throw Error(`convertRadix2: invalid data word=${u} from=${t}`);if(n=n<<t|u,i+t>32)throw Error(`convertRadix2: carry overflow pos=${i} from=${t}`);i+=t;for(;i>=r;i-=r)c.push((n>>i-r&a)>>>0);let d=Hf[i];if(d===void 0)throw Error("invalid carry");n&=d-1}if(n=n<<r-i&a,!o&&i>=t)throw Error("Excess padding");if(!o&&n>0)throw Error(`Non-zero padding: ${n}`);if(o&&i>0)c.push(n>>>0);return c}function i8(e){Nl(e);let t=256;return{encode:(r)=>{if(!Qf(r))throw TypeError("radix.encode input should be Uint8Array");return TR(Array.from(r),t,e)},decode:(r)=>(pb("radix.decode",r),Uint8Array.from(TR(r,e,t)))}}function Ur(e,t=!1){if(Nl(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if(Gf(8,e)>32||Gf(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!Qf(r))throw TypeError("radix2.encode input should be Uint8Array");return ub(Array.from(r),8,e,!t)},decode:(r)=>(pb("radix2.decode",r),Uint8Array.from(ub(r,e,8,t)))}}function $R(e){return PR(e),function(...t){try{return e.apply(null,t)}catch(r){}}}var $me=Object.freeze(Rr(Ur(4),Or("0123456789ABCDEF"),Cr(""))),Rme=Object.freeze(Rr(Ur(5),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Yf(5),Cr(""))),Ome=Object.freeze(Rr(Ur(5),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Cr(""))),Cme=Object.freeze(Rr(Ur(5),Or("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Yf(5),Cr(""))),Pme=Object.freeze(Rr(Ur(5),Or("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Cr(""))),zme=Object.freeze(Rr(Ur(5),Or("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Cr(""),zR((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),DR=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),s8=/[\t\n\f\r ]/,LR=(e,t)=>{Vo("base64",e);let r=t?"base64url":"base64";if(e.length>0&&s8.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},mb=Object.freeze(DR?{encode(e){return fb(e),e.toBase64()},decode(e){return LR(e,!1)}}:Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Yf(6),Cr(""))),Yt=Object.freeze(Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Cr(""))),Nme=Object.freeze(DR?{encode(e){return fb(e),e.toBase64({alphabet:"base64url"})},decode(e){return LR(e,!0)}}:Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Yf(6),Cr(""))),Dme=Object.freeze(Rr(Ur(6),Or("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Cr(""))),hb=(e)=>Rr(i8(58),Or(e),Cr("")),Lme=Object.freeze(hb("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Bme=Object.freeze(hb("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),jme=Object.freeze(hb("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"));var db=Rr(Or("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Cr("")),RR=[996825010,642813549,513874426,1027748829,705979059];function zl(e){let t=e>>25,r=(e&33554431)<<5;for(let o=0;o<RR.length;o++)if((t>>o&1)===1)r^=RR[o];return r}function OR(e,t,r=1){let o=e.length,n=1;for(let i=0;i<o;i++){let s=e.charCodeAt(i);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=zl(n)^s>>5}n=zl(n);for(let i=0;i<o;i++)n=zl(n)^e.charCodeAt(i)&31;for(let i of t)n=zl(n)^i;for(let i=0;i<6;i++)n=zl(n);return n^=r,db.encode(ub([n%Hf[30]],30,5,!1))}function BR(e){let t=e==="bech32"?1:734539939,r=Ur(5),o=r.decode,n=r.encode,i=$R(o);function s(f,m,h=90){if(Vo("bech32.encode prefix",f),Qf(m))m=Array.from(m);pb("bech32.encode",m);let b=f.length;if(b===0)throw TypeError(`Invalid prefix length ${b}`);let y=b+7+m.length;if(h!==!1&&y>h)throw TypeError(`Length ${y} exceeds limit ${h}`);let S=f.toLowerCase(),x=OR(S,m,t);return`${S}1${db.encode(m)}${x}`}function a(f,m=90){Vo("bech32.decode input",f);let h=f.length;if(h<8||m!==!1&&h>m)throw TypeError(`invalid string length: ${h} (${f}). Expected (8..${m})`);let b=f.toLowerCase();if(f!==b&&f!==f.toUpperCase())throw Error("String must be lowercase or uppercase");let y=b.lastIndexOf("1");if(y===0||y===-1)throw Error('Letter "1" must be present between prefix and data only');let S=b.slice(0,y),x=b.slice(y+1);if(x.length<6)throw Error("Data must be at least 6 characters long");let _=db.decode(x).slice(0,-6),A=OR(S,_,t);if(!x.endsWith(A))throw Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:S,words:_}}let c=$R(a);function u(f){let{prefix:m,words:h}=a(f,!1);return{prefix:m,words:h,bytes:o(h)}}function d(f,m){return s(f,n(m))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:c,fromWords:o,fromWordsUnsafe:i,toWords:n}}var Pr=Object.freeze(BR("bech32")),Zme=Object.freeze(BR("bech32m"));var a8=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),c8={encode(e){return fb(e),e.toHex()},decode(e){return Vo("hex",e),Uint8Array.fromHex(e)}},Ume=Object.freeze(a8?c8:Rr(Ur(4),Or("0123456789abcdef"),Cr(""),zR((e)=>{if(typeof e!=="string"||e.length%2!==0)throw TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));function u8(e,t,r,o){no(e);let n=Mf({dkLen:32,asyncTick:10},o),{c:i,dkLen:s,asyncTick:a}=n;if(St(i,"c"),St(s,"dkLen"),St(a,"asyncTick"),i<1)throw Error("iterations (c) must be >= 1");if(s<1)throw Error('"dkLen" must be >= 1');if(s>4294967295*e.outputLen)throw Error("derived key too long");let c=tb(t,"password"),u=tb(r,"salt"),d=new Uint8Array(s),f=Tn.create(e,c),m=f._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:f,PRFSalt:m}}function d8(e,t,r,o,n){if(e.destroy(),t.destroy(),o)o.destroy();return cr(n),r}function gb(e,t,r,o){let{c:n,dkLen:i,DK:s,PRF:a,PRFSalt:c}=u8(e,t,r,o),u,d=new Uint8Array(4),f=ha(d),m=new Uint8Array(a.outputLen);for(let h=1,b=0;b<i;h++,b+=a.outputLen){let y=s.subarray(b,b+a.outputLen);f.setInt32(0,h,!1),(u=c._cloneInto(u)).update(d).digestInto(m),y.set(m.subarray(0,y.length));for(let S=1;S<n;S++){a._cloneInto(u).update(m).digestInto(m);for(let x=0;x<y.length;x++)y[x]^=m[x]}}return d8(a,c,s,u,m)}function jR(e,t,r,o,n,i){let s=e[t++]^r[o++],a=e[t++]^r[o++],c=e[t++]^r[o++],u=e[t++]^r[o++],d=e[t++]^r[o++],f=e[t++]^r[o++],m=e[t++]^r[o++],h=e[t++]^r[o++],b=e[t++]^r[o++],y=e[t++]^r[o++],S=e[t++]^r[o++],x=e[t++]^r[o++],_=e[t++]^r[o++],A=e[t++]^r[o++],O=e[t++]^r[o++],L=e[t++]^r[o++],z=s,K=a,P=c,W=u,ee=d,j=f,R=m,B=h,I=b,T=y,k=S,M=x,N=_,H=A,G=O,re=L;for(let ae=0;ae<8;ae+=2)ee^=Fe(z+N|0,7),I^=Fe(ee+z|0,9),N^=Fe(I+ee|0,13),z^=Fe(N+I|0,18),T^=Fe(j+K|0,7),H^=Fe(T+j|0,9),K^=Fe(H+T|0,13),j^=Fe(K+H|0,18),G^=Fe(k+R|0,7),P^=Fe(G+k|0,9),R^=Fe(P+G|0,13),k^=Fe(R+P|0,18),W^=Fe(re+M|0,7),B^=Fe(W+re|0,9),M^=Fe(B+W|0,13),re^=Fe(M+B|0,18),K^=Fe(z+W|0,7),P^=Fe(K+z|0,9),W^=Fe(P+K|0,13),z^=Fe(W+P|0,18),R^=Fe(j+ee|0,7),B^=Fe(R+j|0,9),ee^=Fe(B+R|0,13),j^=Fe(ee+B|0,18),M^=Fe(k+T|0,7),I^=Fe(M+k|0,9),T^=Fe(I+M|0,13),k^=Fe(T+I|0,18),N^=Fe(re+G|0,7),H^=Fe(N+re|0,9),G^=Fe(H+N|0,13),re^=Fe(G+H|0,18);n[i++]=s+z|0,n[i++]=a+K|0,n[i++]=c+P|0,n[i++]=u+W|0,n[i++]=d+ee|0,n[i++]=f+j|0,n[i++]=m+R|0,n[i++]=h+B|0,n[i++]=b+I|0,n[i++]=y+T|0,n[i++]=S+k|0,n[i++]=x+M|0,n[i++]=_+N|0,n[i++]=A+H|0,n[i++]=O+G|0,n[i++]=L+re|0}function yb(e,t,r,o,n){let i=o+0,s=o+16*n;for(let a=0;a<16;a++)r[s+a]=e[t+(2*n-1)*16+a];for(let a=0;a<n;a++,i+=16,t+=16){if(jR(r,s,e,t,r,i),a>0)s+=16;jR(r,i,e,t+=16,r,s)}}function f8(e,t,r){let o=Mf({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:i,p:s,dkLen:a,asyncTick:c,maxmem:u,onProgress:d}=o;if(St(n,"N"),St(i,"r"),St(s,"p"),St(a,"dkLen"),St(c,"asyncTick"),St(u,"maxmem"),d!==void 0&&typeof d!=="function")throw Error("progressCb must be a function");let f=128*i,m=f/4,h=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>h)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(h-1)*32/f)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(h-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let b=f*(n+s+1);if(b>u)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+b+", maxmem="+u);let y=gb(vt,e,t,{c:1,dkLen:f*s}),S=Uf(y),x=Uf(new Uint8Array(f*n)),_=Uf(new Uint8Array(f)),A=()=>{};if(d){let O=2*n*s,L=Math.max(Math.floor(O/1e4),1),z=0;A=()=>{if(z++,d&&(!(z%L)||z===O))d(z/O)}}return{N:n,r:i,p:s,dkLen:a,blockSize32:m,V:x,B32:S,B:y,tmp:_,blockMixCb:A,asyncTick:c}}function p8(e,t,r,o,n){let i=gb(vt,e,r,{c:1,dkLen:t});return cr(r,o,n),i}function bb(e,t,r){let{N:o,r:n,p:i,dkLen:s,blockSize32:a,V:c,B32:u,B:d,tmp:f,blockMixCb:m}=f8(e,t,r);eb(u);for(let h=0;h<i;h++){let b=a*h;for(let y=0;y<a;y++)c[y]=u[b+y];for(let y=0,S=0;y<o-1;y++)yb(c,S,c,S+=a,n),m();yb(c,(o-1)*a,u,b,n),m();for(let y=0;y<o;y++){let S=(u[b+a-16]&o-1)>>>0;for(let x=0;x<a;x++)f[x]=u[b+x]^c[S*a+x];yb(f,0,u,b,n),m()}}return eb(u),p8(e,s,d,c,f)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function m8(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Xf(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function ga(e){if(typeof e!=="number")throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function $t(e,t,r=""){let o=m8(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;if(!o)throw TypeError(u);throw RangeError(u)}return e}function Sb(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ZR(e,t,r=!1){$t(e,void 0,"output");let o=t.outputLen;if(e.length<o)throw RangeError("digestInto() expects output buffer of length at least "+o);if(r&&!ya(e))throw Error("invalid output, must be aligned")}function Rn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function nn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function h8(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var os=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),g8=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;var y8=(e)=>{for(let t=0;t<e.length;t++)e[t]=g8(e[t]);return e},so=os?(e)=>e:y8;function UR(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function qR(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function MR(e,t,r){let o=t,n=r||(()=>[]),i=(a,c)=>o(c,...n(a)).update(a).digest(),s=o(new Uint8Array(e),...n(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...c)=>o(a,...c),i}var FR=(e,t)=>{function r(o,...n){if($t(o,void 0,"key"),e.nonceLength!==void 0){let d=n[0];$t(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;if(i&&n[1]!==void 0)$t(n[1],void 0,"AAD");let s=t(o,...n),a=(d,f)=>{if(f!==void 0){if(d!==2)throw Error("cipher output not supported");$t(f,void 0,"output")}},c=!1;return{encrypt(d,f){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,$t(d),a(s.encrypt.length,f),s.encrypt(d,f)},decrypt(d,f){if($t(d),i&&d.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,f),s.decrypt(d,f)}}}return Object.assign(r,e),r};function Dl(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if($t(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!ya(t))throw Error("invalid output, must be aligned");return t}function JR(e,t,r){ga(e),ga(t),Xf(r);let o=new Uint8Array(16),n=h8(o);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),o}function ya(e){return e.byteOffset%4===0}function ba(e){return Uint8Array.from($t(e))}var HR=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),b8=(()=>so(Rn(HR("expand 16-byte k"))))(),S8=(()=>so(Rn(HR("expand 32-byte k"))))();function Je(e,t){return e<<t|e>>>32-t}var Ll=64,v8=16,vb=(()=>4294967295)(),KR=Uint32Array.of();function w8(e,t,r,o,n,i,s,a){let c=n.length,u=new Uint8Array(Ll),d=Rn(u),f=os&&ya(n)&&ya(i),m=f?Rn(n):KR,h=f?Rn(i):KR;if(!os){for(let b=0;b<c;s++){if(e(t,r,o,d,s,a),so(d),s>=vb)throw Error("arx: counter overflow");let y=Math.min(Ll,c-b);for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}return}for(let b=0;b<c;s++){if(e(t,r,o,d,s,a),s>=vb)throw Error("arx: counter overflow");let y=Math.min(Ll,c-b);if(f&&y===Ll){let S=b/4;if(b%4!==0)throw Error("arx: invalid block position");for(let x=0,_;x<v8;x++)_=S+x,h[_]=m[_]^d[x];b+=Ll;continue}for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}}function VR(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=UR({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return ga(n),ga(s),Xf(i),Xf(r),(a,c,u,d,f=0)=>{$t(a,void 0,"key"),$t(c,void 0,"nonce"),$t(u,void 0,"data");let m=u.length;if(d=Dl(m,d,!1),ga(f),f<0||f>=vb)throw Error("arx: counter overflow");let h=[],b=a.length,y,S;if(b===32)h.push(y=ba(a)),S=S8;else if(b===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),S=b8,h.push(y);else throw $t(a,32,"arx key"),Error("invalid key size");if(!os||!ya(c))h.push(c=ba(c));let x=Rn(y);if(o){if(c.length!==24)throw Error("arx: extended nonce must be 24 bytes");let O=c.subarray(0,16);if(os)o(S,x,Rn(O),x);else{let L=so(Uint32Array.from(S));o(L,x,Rn(O),x),nn(L),so(x)}c=c.subarray(16)}else if(!os)so(x);let _=16-n;if(_!==c.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let O=new Uint8Array(12);O.set(c,i?0:12-c.length),c=O,h.push(c)}let A=so(Rn(c));try{return w8(e,S,x,A,u,d,f,s),d}finally{nn(...h)}}}function Mt(e,t){return e[t++]&255|(e[t++]&255)<<8}class WR{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=ba($t(e,32,"key"));let t=Mt(e,0),r=Mt(e,2),o=Mt(e,4),n=Mt(e,6),i=Mt(e,8),s=Mt(e,10),a=Mt(e,12),c=Mt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Mt(e,16+2*u)}process(e,t,r=!1){let o=r?0:2048,{h:n,r:i}=this,s=i[0],a=i[1],c=i[2],u=i[3],d=i[4],f=i[5],m=i[6],h=i[7],b=i[8],y=i[9],S=Mt(e,t+0),x=Mt(e,t+2),_=Mt(e,t+4),A=Mt(e,t+6),O=Mt(e,t+8),L=Mt(e,t+10),z=Mt(e,t+12),K=Mt(e,t+14),P=n[0]+(S&8191),W=n[1]+((S>>>13|x<<3)&8191),ee=n[2]+((x>>>10|_<<6)&8191),j=n[3]+((_>>>7|A<<9)&8191),R=n[4]+((A>>>4|O<<12)&8191),B=n[5]+(O>>>1&8191),I=n[6]+((O>>>14|L<<2)&8191),T=n[7]+((L>>>11|z<<5)&8191),k=n[8]+((z>>>8|K<<8)&8191),M=n[9]+(K>>>5|o),N=0,H=N+P*s+W*(5*y)+ee*(5*b)+j*(5*h)+R*(5*m);N=H>>>13,H&=8191,H+=B*(5*f)+I*(5*d)+T*(5*u)+k*(5*c)+M*(5*a),N+=H>>>13,H&=8191;let G=N+P*a+W*s+ee*(5*y)+j*(5*b)+R*(5*h);N=G>>>13,G&=8191,G+=B*(5*m)+I*(5*f)+T*(5*d)+k*(5*u)+M*(5*c),N+=G>>>13,G&=8191;let re=N+P*c+W*a+ee*s+j*(5*y)+R*(5*b);N=re>>>13,re&=8191,re+=B*(5*h)+I*(5*m)+T*(5*f)+k*(5*d)+M*(5*u),N+=re>>>13,re&=8191;let ae=N+P*u+W*c+ee*a+j*s+R*(5*y);N=ae>>>13,ae&=8191,ae+=B*(5*b)+I*(5*h)+T*(5*m)+k*(5*f)+M*(5*d),N+=ae>>>13,ae&=8191;let pe=N+P*d+W*u+ee*c+j*a+R*s;N=pe>>>13,pe&=8191,pe+=B*(5*y)+I*(5*b)+T*(5*h)+k*(5*m)+M*(5*f),N+=pe>>>13,pe&=8191;let be=N+P*f+W*d+ee*u+j*c+R*a;N=be>>>13,be&=8191,be+=B*s+I*(5*y)+T*(5*b)+k*(5*h)+M*(5*m),N+=be>>>13,be&=8191;let ve=N+P*m+W*f+ee*d+j*u+R*c;N=ve>>>13,ve&=8191,ve+=B*a+I*s+T*(5*y)+k*(5*b)+M*(5*h),N+=ve>>>13,ve&=8191;let ke=N+P*h+W*m+ee*f+j*d+R*u;N=ke>>>13,ke&=8191,ke+=B*c+I*a+T*s+k*(5*y)+M*(5*b),N+=ke>>>13,ke&=8191;let Ie=N+P*b+W*h+ee*m+j*f+R*d;N=Ie>>>13,Ie&=8191,Ie+=B*u+I*c+T*a+k*s+M*(5*y),N+=Ie>>>13,Ie&=8191;let we=N+P*y+W*b+ee*h+j*m+R*f;N=we>>>13,we&=8191,we+=B*d+I*u+T*c+k*a+M*s,N+=we>>>13,we&=8191,N=(N<<2)+N|0,N=N+H|0,H=N&8191,N=N>>>13,G+=N,n[0]=H,n[1]=G,n[2]=re,n[3]=ae,n[4]=pe,n[5]=be,n[6]=ve,n[7]=ke,n[8]=Ie,n[9]=we}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=o,o=e[s]>>>13,e[s]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+o,o=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(o^1)-1;for(let s=0;s<10;s++)r[s]&=n;n=~n;for(let s=0;s<10;s++)e[s]=e[s]&n|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=i&65535;nn(r)}update(e){Sb(this),$t(e),e=ba(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,nn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Sb(this),ZR(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:o}=this;if(o){t[o++]=1;for(;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let i=0;i<8;i++)e[n++]=r[i]>>>0,e[n++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var GR=MR(32,(e)=>new WR(e));function x8(e,t,r,o,n,i=20){let s=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],m=t[2],h=t[3],b=t[4],y=t[5],S=t[6],x=t[7],_=n,A=r[0],O=r[1],L=r[2],z=s,K=a,P=c,W=u,ee=d,j=f,R=m,B=h,I=b,T=y,k=S,M=x,N=_,H=A,G=O,re=L;for(let pe=0;pe<i;pe+=2)z=z+ee|0,N=Je(N^z,16),I=I+N|0,ee=Je(ee^I,12),z=z+ee|0,N=Je(N^z,8),I=I+N|0,ee=Je(ee^I,7),K=K+j|0,H=Je(H^K,16),T=T+H|0,j=Je(j^T,12),K=K+j|0,H=Je(H^K,8),T=T+H|0,j=Je(j^T,7),P=P+R|0,G=Je(G^P,16),k=k+G|0,R=Je(R^k,12),P=P+R|0,G=Je(G^P,8),k=k+G|0,R=Je(R^k,7),W=W+B|0,re=Je(re^W,16),M=M+re|0,B=Je(B^M,12),W=W+B|0,re=Je(re^W,8),M=M+re|0,B=Je(B^M,7),z=z+j|0,re=Je(re^z,16),k=k+re|0,j=Je(j^k,12),z=z+j|0,re=Je(re^z,8),k=k+re|0,j=Je(j^k,7),K=K+R|0,N=Je(N^K,16),M=M+N|0,R=Je(R^M,12),K=K+R|0,N=Je(N^K,8),M=M+N|0,R=Je(R^M,7),P=P+B|0,H=Je(H^P,16),I=I+H|0,B=Je(B^I,12),P=P+B|0,H=Je(H^P,8),I=I+H|0,B=Je(B^I,7),W=W+ee|0,G=Je(G^W,16),T=T+G|0,ee=Je(ee^T,12),W=W+ee|0,G=Je(G^W,8),T=T+G|0,ee=Je(ee^T,7);let ae=0;o[ae++]=s+z|0,o[ae++]=a+K|0,o[ae++]=c+P|0,o[ae++]=u+W|0,o[ae++]=d+ee|0,o[ae++]=f+j|0,o[ae++]=m+R|0,o[ae++]=h+B|0,o[ae++]=b+I|0,o[ae++]=y+T|0,o[ae++]=S+k|0,o[ae++]=x+M|0,o[ae++]=_+N|0,o[ae++]=A+H|0,o[ae++]=O+G|0,o[ae++]=L+re|0}var _8=VR(x8,{counterRight:!1,counterLength:4,allowShortKeys:!1});var E8=new Uint8Array(16),QR=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(E8.subarray(r))},I8=new Uint8Array(32);function YR(e,t,r,o,n){if(n!==void 0)$t(n,void 0,"AAD");let i=e(t,r,I8),s=JR(o.length,n?n.length:0,!0),a=GR.create(i);if(n)QR(a,n);QR(a,o),a.update(s);let c=a.digest();return nn(i,s),c}var k8=(e)=>(t,r,o)=>({encrypt(i,s){let a=i.length;s=Dl(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);e(t,r,c,c,1);let u=YR(e,t,r,c,o);return s.set(u,a),nn(u),s},decrypt(i,s){s=Dl(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),u=YR(e,t,r,a,o);if(!qR(c,u))throw nn(u),Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,r,s,s,1),nn(u),s}}),qr=FR({blockSize:64,nonceLength:12,tagLength:16},k8(_8));/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Sa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Dt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Te(e,t,r=""){let o=Sa(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=o?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+c)}return e}function Mr(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Dt(e.outputLen),Dt(e.blockLen)}function co(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ep(e,t){Te(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function tp(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function vr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function rp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function on(e,t){return e<<32-t|e>>>t}var A8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function T8(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function $8(e){for(let t=0;t<e.length;t++)e[t]=T8(e[t]);return e}var wb=A8?(e)=>e:$8,eO=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),R8=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function is(e){if(Te(e),eO)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=R8[e[r]];return t}var ao={_0:48,_9:57,A:65,F:70,a:97,f:102};function XR(e){if(e>=ao._0&&e<=ao._9)return e-ao._0;if(e>=ao.A&&e<=ao.F)return e-(ao.A-10);if(e>=ao.a&&e<=ao.f)return e-(ao.a-10);return}function ss(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(eO)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=XR(e.charCodeAt(i)),a=XR(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+c+'" at index '+i)}o[n]=s*16+a}return o}function Et(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Te(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function va(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Wo(e=32){let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var Go=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _b=BigInt(0),xb=BigInt(1);function Bl(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function tO(e){if(typeof e==="bigint"){if(!np(e))throw Error("positive bigint expected, got "+e)}else Dt(e);return e}function jl(e){let t=tO(e).toString(16);return t.length&1?"0"+t:t}function rO(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?_b:BigInt("0x"+e)}function Qo(e){return rO(is(e))}function Yo(e){return rO(is(op(Te(e)).reverse()))}function wa(e,t){Dt(t),e=tO(e);let r=ss(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function Zl(e,t){return wa(e,t).reverse()}function op(e){return Uint8Array.from(e)}function Xo(e){return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}var np=(e)=>typeof e==="bigint"&&_b<=e;function O8(e,t,r){return np(e)&&np(t)&&np(r)&&t<=e&&e<r}function Ul(e,t,r,o){if(!O8(t,r,o))throw Error("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Eb(e){let t;for(t=0;e>_b;e>>=xb,t+=1);return t}var ql=(e)=>(xb<<BigInt(e))-xb;function nO(e,t,r){if(Dt(e,"hashLen"),Dt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=o(e),u=o(e),d=0,f=()=>{c.fill(1),u.fill(0),d=0},m=(...S)=>r(u,Et(c,...S)),h=(S=n)=>{if(u=m(i,S),c=m(),S.length===0)return;u=m(s,S),c=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){c=m();let _=c.slice();x.push(_),S+=c.length}return Et(...x)};return(S,x)=>{f(),h(S);let _=void 0;while(!(_=x(b())))h();return f(),_}}function as(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function o(i,s,a){let c=e[i];if(a&&c===void 0)return;let u=typeof c;if(u!==s||c===null)throw Error(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,c])=>o(a,c,s));n(t,!1),n(r,!0)}function Ib(e){let t=new WeakMap;return(r,...o)=>{let n=t.get(r);if(n!==void 0)return n;let i=e(r,...o);return t.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ur=BigInt(0),Xt=BigInt(1),cs=BigInt(2),sO=BigInt(3),aO=BigInt(4),cO=BigInt(5),C8=BigInt(7),lO=BigInt(8),P8=BigInt(9),uO=BigInt(16);function lr(e,t){let r=e%t;return r>=ur?r:t+r}function Fr(e,t,r){let o=e;while(t-- >ur)o*=o,o%=r;return o}function oO(e,t){if(e===ur)throw Error("invert: expected non-zero number");if(t<=ur)throw Error("invert: expected positive modulus, got "+t);let r=lr(e,t),o=t,n=ur,i=Xt,s=Xt,a=ur;while(r!==ur){let u=o/r,d=o%r,f=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=f,a=m}if(o!==Xt)throw Error("invert: does not exist");return lr(n,t)}function kb(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function dO(e,t){let r=(e.ORDER+Xt)/aO,o=e.pow(t,r);return kb(e,o,t),o}function z8(e,t){let r=(e.ORDER-cO)/lO,o=e.mul(t,cs),n=e.pow(o,r),i=e.mul(t,n),s=e.mul(e.mul(i,cs),n),a=e.mul(i,e.sub(s,e.ONE));return kb(e,a,t),a}function N8(e){let t=ip(e),r=fO(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+C8)/uO;return(a,c)=>{let u=a.pow(c,s),d=a.mul(u,o),f=a.mul(u,n),m=a.mul(u,i),h=a.eql(a.sqr(d),c),b=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(m,f,b);let y=a.eql(a.sqr(d),c),S=a.cmov(u,d,y);return kb(a,S,c),S}}function fO(e){if(e<sO)throw Error("sqrt is not defined for small field");let t=e-Xt,r=0;while(t%cs===ur)t/=cs,r++;let o=cs,n=ip(e);while(iO(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return dO;let i=n.pow(o,t),s=(t+Xt)/cs;return function(c,u){if(c.is0(u))return u;if(iO(c,u)!==1)throw Error("Cannot find square root");let d=r,f=c.mul(c.ONE,i),m=c.pow(u,t),h=c.pow(u,s);while(!c.eql(m,c.ONE)){if(c.is0(m))return c.ZERO;let b=1,y=c.sqr(m);while(!c.eql(y,c.ONE))if(b++,y=c.sqr(y),b===d)throw Error("Cannot find square root");let S=Xt<<BigInt(d-b-1),x=c.pow(f,S);d=b,f=c.sqr(x),m=c.mul(m,f),h=c.mul(h,x)}return h}}function D8(e){if(e%aO===sO)return dO;if(e%lO===cO)return z8;if(e%uO===P8)return N8(e);return fO(e)}var L8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ab(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=L8.reduce((o,n)=>(o[n]="function",o),t);return as(e,r),e}function B8(e,t,r){if(r<ur)throw Error("invalid exponent, negatives unsupported");if(r===ur)return e.ONE;if(r===Xt)return t;let o=e.ONE,n=t;while(r>ur){if(r&Xt)o=e.mul(o,n);n=e.sqr(n),r>>=Xt}return o}function Ml(e,t,r=!1){let o=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,c)=>{if(e.is0(a))return s;return o[c]=s,e.mul(s,a)},e.ONE),i=e.inv(n);return t.reduceRight((s,a,c)=>{if(e.is0(a))return s;return o[c]=e.mul(s,o[c]),e.mul(s,a)},i),o}function iO(e,t){let r=(e.ORDER-Xt)/cs,o=e.pow(t,r),n=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),s=e.eql(o,e.neg(e.ONE));if(!n&&!i&&!s)throw Error("invalid Legendre symbol result");return n?1:i?0:-1}function j8(e,t){if(t!==void 0)Dt(t);let r=t!==void 0?t:e.toString(2).length,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}class pO{ORDER;BITS;BYTES;isLE;ZERO=ur;ONE=Xt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=ur)throw Error("invalid field: expected ORDER > 0, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")this.sqrt=t.sqrt;if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=t.allowedLengths?.slice();if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=j8(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return lr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Xt)===Xt}neg(e){return lr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return lr(e*e,this.ORDER)}add(e,t){return lr(e+t,this.ORDER)}sub(e,t){return lr(e-t,this.ORDER)}mul(e,t){return lr(e*t,this.ORDER)}pow(e,t){return B8(this,e,t)}div(e,t){return lr(e*oO(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return oO(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=D8(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?Zl(e,this.BYTES):wa(e,this.BYTES)}fromBytes(e,t=!1){Te(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(o);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?Yo(e):Qo(e);if(s)a=lr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Ml(this,e)}cmov(e,t,r){return r?t:e}}function ip(e,t={}){return new pO(e,t)}function mO(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Tb(e){let t=mO(e);return t+Math.ceil(t/2)}function hO(e,t,r=!1){Te(e);let o=e.length,n=mO(t),i=Tb(t);if(o<16||o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?Yo(e):Qo(e),a=lr(s,t-Xt)+Xt;return r?Zl(a,n):wa(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var xa=BigInt(0),ls=BigInt(1);function Fl(e,t){let r=t.negate();return e?r:t}function Cb(e,t){let r=Ml(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function SO(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function $b(e,t){SO(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=ql(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function gO(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>o)a-=i,c+=ls;let u=t*o,d=u+Math.abs(a)-1,f=a===0,m=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:m,isNegF:h,offsetF:u}}var Rb=new WeakMap,vO=new WeakMap;function Ob(e){return vO.get(e)||1}function yO(e){if(e!==xa)throw Error("invalid wNAF")}class Pb{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>xa){if(t&ls)r=r.add(o);o=o.double(),t>>=ls}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=$b(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let c=1;c<o;c++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=$b(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:c,isZero:u,isNeg:d,isNegF:f,offsetF:m}=gO(r,s,i);if(r=a,u)n=n.add(Fl(f,t[m]));else o=o.add(Fl(d,t[c]))}return yO(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=$b(e,this.bits);for(let i=0;i<n.windows;i++){if(r===xa)break;let{nextN:s,offset:a,isZero:c,isNeg:u}=gO(r,i,n);if(r=s,c)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return yO(r),o}getPrecomputes(e,t,r){let o=Rb.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);Rb.set(t,o)}}return o}cached(e,t,r){let o=Ob(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=Ob(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){SO(t,this.bits),vO.set(e,t),Rb.delete(e)}hasCache(e){return Ob(e)!==1}}function wO(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>xa||o>xa){if(r&ls)i=i.add(n);if(o&ls)s=s.add(n);n=n.double(),r>>=ls,o>>=ls}return{p1:i,p2:s}}function bO(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return Ab(t),t}else return ip(e,{isLE:r})}function xO(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u==="bigint"&&u>xa))throw Error(`CURVE.${c} must be positive bigint`)}let n=bO(t.p,r.Fp,o),i=bO(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function sp(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jl=BigInt(0),_a=BigInt(1),ap=BigInt(2);function Z8(e){return as(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function _O(e){let t=Z8(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let c=s||Wo,u=a?255:448,d=a?32:56,f=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?ap**BigInt(254):ap**BigInt(447),b=a?BigInt(8)*ap**BigInt(251)-_a:BigInt(4)*ap**BigInt(445)-_a,y=h+b+_a,S=(I)=>lr(I,r),x=_(f);function _(I){return Zl(S(I),d)}function A(I){let T=op(Te(I,d,"uCoordinate"));if(a)T[31]&=127;return S(Yo(T))}function O(I){return Yo(n(op(Te(I,d,"scalar"))))}function L(I,T){let k=ee(A(T),O(I));if(k===Jl)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,T,k){let M=S(I*(T-k));return T=S(T-M),k=S(k+M),{x_2:T,x_3:k}}function ee(I,T){Ul("u",I,Jl,r),Ul("scalar",T,h,y);let k=T,M=I,N=_a,H=Jl,G=I,re=_a,ae=Jl;for(let be=BigInt(u-1);be>=Jl;be--){let ve=k>>be&_a;ae^=ve,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=ve;let ke=N+H,Ie=S(ke*ke),we=N-H,Ue=S(we*we),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=S(bt*ke),Nt=S(Qe*we),lt=Tt+Nt,$r=Tt-Nt;G=S(lt*lt),re=S(M*S($r*$r)),N=S(Ie*Ue),H=S(De*(Ie+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let pe=i(H);return S(N*pe)}let j={secretKey:d,publicKey:d,seed:d},R=(I=c(d))=>(Te(I,j.seed,"seed"),I),B={randomSecretKey:R};return Object.freeze({keygen:sp(R,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}class zb{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Mr(e),Te(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),vr(o)}update(e){return co(this),this.iHash.update(e),this}digestInto(e){co(this),Te(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Ea=(e,t,r)=>new zb(e,t).update(r).digest();Ea.create=(e,t)=>new zb(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var EO=(e,t)=>(e+(e>=0?t:-t)/kO)/t;function U8(e,t,r){let[[o,n],[i,s]]=t,a=EO(s*e,r),c=EO(-n*e,r),u=e-a*o-c*i,d=-a*n-c*s,f=u<lo,m=d<lo;if(f)u=-u;if(m)d=-d;let h=ql(Math.ceil(Eb(r)/2))+Ia;if(u<lo||u>=h||d<lo||d>=h)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:m,k2:d}}function Db(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function Nb(e,t){let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(Bl(r.lowS,"lowS"),Bl(r.prehash,"prehash"),r.format!==void 0)Db(r.format);return r}class IO extends Error{constructor(e=""){super(e)}}var ei={Err:IO,_tlv:{encode:(e,t)=>{let{Err:r}=ei;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=jl(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?jl(n.length/2|128):"";return jl(e)+i+n+t},decode(e,t){let{Err:r}=ei,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=ei;if(e<lo)throw new t("integer: negative integers are not allowed");let r=jl(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ei;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Qo(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=ei,n=Te(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=o.decode(2,i),{v:u,l:d}=o.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=ei,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}},lo=BigInt(0),Ia=BigInt(1),kO=BigInt(2),cp=BigInt(3),q8=BigInt(4);function Lb(e,t={}){let r=xO("weierstrass",e,t),{Fp:o,Fn:n}=r,i=r.CURVE,{h:s,n:a}=i;as(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c){if(!o.is0(i.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=TO(o,n);function d(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function f(R,B,I){let{x:T,y:k}=B.toAffine(),M=o.toBytes(T);if(Bl(I,"isCompressed"),I){d();let N=!o.isOdd(k);return Et(AO(N),M)}else return Et(Uint8Array.of(4),M,o.toBytes(k))}function m(R){Te(R,void 0,"Point");let{publicKey:B,publicKeyUncompressed:I}=u,T=R.length,k=R[0],M=R.subarray(1);if(T===B&&(k===2||k===3)){let N=o.fromBytes(M);if(!o.isValid(N))throw Error("bad point: is not on curve, wrong x");let H=y(N),G;try{G=o.sqrt(H)}catch(pe){let be=pe instanceof Error?": "+pe.message:"";throw Error("bad point: is not on curve, sqrt error"+be)}d();let re=o.isOdd(G);if((k&1)===1!==re)G=o.neg(G);return{x:N,y:G}}else if(T===I&&k===4){let N=o.BYTES,H=o.fromBytes(M.subarray(0,N)),G=o.fromBytes(M.subarray(N,N*2));if(!S(H,G))throw Error("bad point: is not on curve");return{x:H,y:G}}else throw Error(`bad point: got length ${T}, expected compressed=${B} or uncompressed=${I}`)}let h=t.toBytes||f,b=t.fromBytes||m;function y(R){let B=o.sqr(R),I=o.mul(B,R);return o.add(o.add(I,o.mul(R,i.a)),i.b)}function S(R,B){let I=o.sqr(B),T=y(R);return o.eql(I,T)}if(!S(i.Gx,i.Gy))throw Error("bad curve params: generator point");let x=o.mul(o.pow(i.a,cp),q8),_=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(x,_)))throw Error("bad curve params: a or b");function A(R,B,I=!1){if(!o.isValid(B)||I&&o.is0(B))throw Error(`bad point coordinate ${R}`);return B}function O(R){if(!(R instanceof W))throw Error("Weierstrass Point expected")}function L(R){if(!c||!c.basises)throw Error("no endo");return U8(R,c.basises,n.ORDER)}let z=Ib((R,B)=>{let{X:I,Y:T,Z:k}=R;if(o.eql(k,o.ONE))return{x:I,y:T};let M=R.is0();if(B==null)B=M?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(T,B),G=o.mul(k,B);if(M)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}),K=Ib((R)=>{if(R.is0()){if(t.allowInfinityPoint&&!o.is0(R.Y))return;throw Error("bad point: ZERO")}let{x:B,y:I}=R.toAffine();if(!o.isValid(B)||!o.isValid(I))throw Error("bad point: x or y not field elements");if(!S(B,I))throw Error("bad point: equation left != right");if(!R.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function P(R,B,I,T,k){return I=new W(o.mul(I.X,R),I.Y,I.Z),B=Fl(T,B),I=Fl(k,I),B.add(I)}class W{static BASE=new W(i.Gx,i.Gy,o.ONE);static ZERO=new W(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(R,B,I){this.X=A("x",R),this.Y=A("y",B,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(R){let{x:B,y:I}=R||{};if(!R||!o.isValid(B)||!o.isValid(I))throw Error("invalid affine point");if(R instanceof W)throw Error("projective point not allowed");if(o.is0(B)&&o.is0(I))return W.ZERO;return new W(B,I,o.ONE)}static fromBytes(R){let B=W.fromAffine(b(Te(R,void 0,"point")));return B.assertValidity(),B}static fromHex(R){return W.fromBytes(ss(R))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(R=8,B=!0){if(j.createCache(this,R),!B)this.multiply(cp);return this}assertValidity(){K(this)}hasEvenY(){let{y:R}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(R)}equals(R){O(R);let{X:B,Y:I,Z:T}=this,{X:k,Y:M,Z:N}=R,H=o.eql(o.mul(B,N),o.mul(k,T)),G=o.eql(o.mul(I,N),o.mul(M,T));return H&&G}negate(){return new W(this.X,o.neg(this.Y),this.Z)}double(){let{a:R,b:B}=i,I=o.mul(B,cp),{X:T,Y:k,Z:M}=this,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=o.mul(T,T),ae=o.mul(k,k),pe=o.mul(M,M),be=o.mul(T,k);return be=o.add(be,be),G=o.mul(T,M),G=o.add(G,G),N=o.mul(R,G),H=o.mul(I,pe),H=o.add(N,H),N=o.sub(ae,H),H=o.add(ae,H),H=o.mul(N,H),N=o.mul(be,N),G=o.mul(I,G),pe=o.mul(R,pe),be=o.sub(re,pe),be=o.mul(R,be),be=o.add(be,G),G=o.add(re,re),re=o.add(G,re),re=o.add(re,pe),re=o.mul(re,be),H=o.add(H,re),pe=o.mul(k,M),pe=o.add(pe,pe),re=o.mul(pe,be),N=o.sub(N,re),G=o.mul(pe,ae),G=o.add(G,G),G=o.add(G,G),new W(N,H,G)}add(R){O(R);let{X:B,Y:I,Z:T}=this,{X:k,Y:M,Z:N}=R,H=o.ZERO,G=o.ZERO,re=o.ZERO,ae=i.a,pe=o.mul(i.b,cp),be=o.mul(B,k),ve=o.mul(I,M),ke=o.mul(T,N),Ie=o.add(B,I),we=o.add(k,M);Ie=o.mul(Ie,we),we=o.add(be,ve),Ie=o.sub(Ie,we),we=o.add(B,T);let Ue=o.add(k,N);return we=o.mul(we,Ue),Ue=o.add(be,ke),we=o.sub(we,Ue),Ue=o.add(I,T),H=o.add(M,N),Ue=o.mul(Ue,H),H=o.add(ve,ke),Ue=o.sub(Ue,H),re=o.mul(ae,we),H=o.mul(pe,ke),re=o.add(H,re),H=o.sub(ve,re),re=o.add(ve,re),G=o.mul(H,re),ve=o.add(be,be),ve=o.add(ve,be),ke=o.mul(ae,ke),we=o.mul(pe,we),ve=o.add(ve,ke),ke=o.sub(be,ke),ke=o.mul(ae,ke),we=o.add(we,ke),be=o.mul(ve,we),G=o.add(G,be),be=o.mul(Ue,we),H=o.mul(Ie,H),H=o.sub(H,be),be=o.mul(Ie,ve),re=o.mul(Ue,re),re=o.add(re,be),new W(H,G,re)}subtract(R){return this.add(R.negate())}is0(){return this.equals(W.ZERO)}multiply(R){let{endo:B}=t;if(!n.isValidNot0(R))throw Error("invalid scalar: out of range");let I,T,k=(M)=>j.cached(this,M,(N)=>Cb(W,N));if(B){let{k1neg:M,k1:N,k2neg:H,k2:G}=L(R),{p:re,f:ae}=k(N),{p:pe,f:be}=k(G);T=ae.add(be),I=P(B.beta,re,pe,M,H)}else{let{p:M,f:N}=k(R);I=M,T=N}return Cb(W,[I,T])[0]}multiplyUnsafe(R){let{endo:B}=t,I=this;if(!n.isValid(R))throw Error("invalid scalar: out of range");if(R===lo||I.is0())return W.ZERO;if(R===Ia)return I;if(j.hasCache(this))return this.multiply(R);if(B){let{k1neg:T,k1:k,k2neg:M,k2:N}=L(R),{p1:H,p2:G}=wO(W,I,k,N);return P(B.beta,H,G,T,M)}else return j.unsafe(I,R)}toAffine(R){return z(this,R)}isTorsionFree(){let{isTorsionFree:R}=t;if(s===Ia)return!0;if(R)return R(W,this);return j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:R}=t;if(s===Ia)return this;if(R)return R(W,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(R=!0){return Bl(R,"isCompressed"),this.assertValidity(),h(W,this,R)}toHex(R=!0){return is(this.toBytes(R))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ee=n.BITS,j=new Pb(W,t.endo?Math.ceil(ee/2):ee);return W.BASE.precompute(8),W}function AO(e){return Uint8Array.of(e?2:3)}function TO(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function M8(e,t={}){let{Fn:r}=e,o=t.randomBytes||Wo,n=Object.assign(TO(e.Fp,r),{seed:Tb(r.ORDER)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h=o(n.seed)){return hO(Te(h,n.seed,"seed"),r.ORDER)}function c(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n;if(!Sa(h))return;if("_lengths"in r&&r._lengths||b===y)return;let x=Te(h,void 0,"key").length;return x===y||x===S}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let f={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=sp(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:e,utils:f,lengths:n})}function Bb(e,t,r={}){Mr(t),as(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes||Wo,n=r.hmac||((I,T)=>Ea(t,I,T)),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:m,lengths:h}=M8(e,r),b={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*kO<i.ORDER;function S(I){let T=a>>Ia;return I>T}function x(I,T){if(!s.isValidNot0(T))throw Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return T}function _(){if(y)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(I,T){Db(T);let k=h.signature,M=T==="compact"?k:T==="recovered"?k+1:void 0;return Te(I,M)}class O{r;s;recovery;constructor(I,T,k){if(this.r=x("r",I),this.s=x("s",T),k!=null){if(_(),![0,1,2,3].includes(k))throw Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(I,T=b.format){A(I,T);let k;if(T==="der"){let{r:G,s:re}=ei.toSig(Te(I));return new O(G,re)}if(T==="recovered")k=I[0],T="compact",I=I.subarray(1);let M=h.signature/2,N=I.subarray(0,M),H=I.subarray(M,M*2);return new O(s.fromBytes(N),s.fromBytes(H),k)}static fromHex(I,T){return this.fromBytes(ss(I),T)}assertRecovery(){let{recovery:I}=this;if(I==null)throw Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new O(this.r,this.s,I)}recoverPublicKey(I){let{r:T,s:k}=this,M=this.assertRecovery(),N=M===2||M===3?T+a:T;if(!i.isValid(N))throw Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(N),G=e.fromBytes(Et(AO((M&1)===0),H)),re=s.inv(N),ae=z(Te(I,void 0,"msgHash")),pe=s.create(-ae*re),be=s.create(k*re),ve=e.BASE.multiplyUnsafe(pe).add(G.multiplyUnsafe(be));if(ve.is0())throw Error("invalid recovery: point at infinify");return ve.assertValidity(),ve}hasHighS(){return S(this.s)}toBytes(I=b.format){if(Db(I),I==="der")return ss(ei.hexFromSig(this));let{r:T,s:k}=this,M=s.toBytes(T),N=s.toBytes(k);if(I==="recovered")return _(),Et(Uint8Array.of(this.assertRecovery()),M,N);return Et(M,N)}toHex(I){return is(this.toBytes(I))}}let L=r.bits2int||function(T){if(T.length>8192)throw Error("input is too large");let k=Qo(T),M=T.length*8-c;return M>0?k>>BigInt(M):k},z=r.bits2int_modN||function(T){return s.create(L(T))},K=ql(c);function P(I){return Ul("num < 2^"+c,I,lo,K),s.toBytes(I)}function W(I,T){return Te(I,void 0,"message"),T?Te(t(I),void 0,"prehashed message"):I}function ee(I,T,k){let{lowS:M,prehash:N,extraEntropy:H}=Nb(k,b);I=W(I,N);let G=z(I),re=s.fromBytes(T);if(!s.isValidNot0(re))throw Error("invalid private key");let ae=[P(re),P(G)];if(H!=null&&H!==!1){let ke=H===!0?o(h.secretKey):H;ae.push(Te(ke,void 0,"extraEntropy"))}let pe=Et(...ae),be=G;function ve(ke){let Ie=L(ke);if(!s.isValidNot0(Ie))return;let we=s.inv(Ie),Ue=e.BASE.multiply(Ie).toAffine(),De=s.create(Ue.x);if(De===lo)return;let Qe=s.create(we*s.create(be+De*re));if(Qe===lo)return;let bt=(Ue.x===De?0:2)|Number(Ue.y&Ia),Tt=Qe;if(M&&S(Qe))Tt=s.neg(Qe),bt^=1;return new O(De,Tt,y?void 0:bt)}return{seed:pe,k2sig:ve}}function j(I,T,k={}){let{seed:M,k2sig:N}=ee(I,T,k);return nO(t.outputLen,s.BYTES,n)(M,N).toBytes(k.format)}function R(I,T,k,M={}){let{lowS:N,prehash:H,format:G}=Nb(M,b);if(k=Te(k,void 0,"publicKey"),T=W(T,H),!Sa(I)){let re=I instanceof O?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+re)}A(I,G);try{let re=O.fromBytes(I,G),ae=e.fromBytes(k);if(N&&re.hasHighS())return!1;let{r:pe,s:be}=re,ve=z(T),ke=s.inv(be),Ie=s.create(ve*ke),we=s.create(pe*ke),Ue=e.BASE.multiplyUnsafe(Ie).add(ae.multiplyUnsafe(we));if(Ue.is0())return!1;return s.create(Ue.x)===pe}catch(re){return!1}}function B(I,T,k={}){let{prehash:M}=Nb(k,b);return T=W(T,M),O.fromBytes(I,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:m,lengths:h,Point:e,sign:j,verify:R,recoverPublicKey:B,Signature:O,hash:t})}function $O(e,t,r){return e&t^~e&r}function RO(e,t,r){return e&t^e&r^t&r}class lp{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=rp(this.buffer)}update(e){co(this),Te(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=rp(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){co(this),ep(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,vr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=rp(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var uo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ft=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);var up=BigInt(4294967295),OO=BigInt(32);function F8(e,t=!1){if(t)return{h:Number(e&up),l:Number(e>>OO&up)};return{h:Number(e>>OO&up)|0,l:Number(e&up)|0}}function dp(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=F8(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}var jb=(e,t,r)=>e>>>r,Zb=(e,t,r)=>e<<32-r|t>>>r,us=(e,t,r)=>e>>>r|t<<32-r,ds=(e,t,r)=>e<<32-r|t>>>r,Kl=(e,t,r)=>e<<64-r|t>>>r-32,Hl=(e,t,r)=>e>>>r-32|t<<64-r;var CO=(e,t,r)=>e<<r|t>>>32-r,PO=(e,t,r)=>t<<r|e>>>32-r,zO=(e,t,r)=>t<<r-32|e>>>64-r,NO=(e,t,r)=>e<<r-32|t>>>64-r;function On(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var DO=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),LO=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,BO=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),jO=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,ZO=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),UO=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var K8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ti=new Uint32Array(64);class qO extends lp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)ti[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=ti[d-15],m=ti[d-2],h=on(f,7)^on(f,18)^f>>>3,b=on(m,17)^on(m,19)^m>>>10;ti[d]=b+ti[d-7]+h+ti[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let f=on(s,6)^on(s,11)^on(s,25),m=u+f+$O(s,a,c)+K8[d]+ti[d]|0,b=(on(r,2)^on(r,13)^on(r,22))+RO(r,o,n)|0;u=c,c=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,c,u)}roundClean(){vr(ti)}destroy(){this.set(0,0,0,0,0,0,0,0),vr(this.buffer)}}class MO extends qO{A=uo[0]|0;B=uo[1]|0;C=uo[2]|0;D=uo[3]|0;E=uo[4]|0;F=uo[5]|0;G=uo[6]|0;H=uo[7]|0;constructor(){super(32)}}var FO=(()=>dp(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),H8=(()=>FO[0])(),V8=(()=>FO[1])(),ri=new Uint32Array(80),ni=new Uint32Array(80);class JO extends lp{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y]}set(e,t,r,o,n,i,s,a,c,u,d,f,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)ri[_]=e.getUint32(t),ni[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=ri[_-15]|0,O=ni[_-15]|0,L=us(A,O,1)^us(A,O,8)^jb(A,O,7),z=ds(A,O,1)^ds(A,O,8)^Zb(A,O,7),K=ri[_-2]|0,P=ni[_-2]|0,W=us(K,P,19)^Kl(K,P,61)^jb(K,P,6),ee=ds(K,P,19)^Hl(K,P,61)^Zb(K,P,6),j=BO(z,ee,ni[_-7],ni[_-16]),R=jO(j,L,W,ri[_-7],ri[_-16]);ri[_]=R|0,ni[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:f,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=us(d,f,14)^us(d,f,18)^Kl(d,f,41),O=ds(d,f,14)^ds(d,f,18)^Hl(d,f,41),L=d&m^~d&b,z=f&h^~f&y,K=ZO(x,O,z,V8[_],ni[_]),P=UO(K,S,A,L,H8[_],ri[_]),W=K|0,ee=us(r,o,28)^Kl(r,o,34)^Kl(r,o,39),j=ds(r,o,28)^Hl(r,o,34)^Hl(r,o,39),R=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=f|0,{h:d,l:f}=On(c|0,u|0,P|0,W|0),c=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=DO(W,j,B);r=LO(I,P,ee,R),o=I|0}({h:r,l:o}=On(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=On(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=On(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=On(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:f}=On(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=On(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=On(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=On(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,c,u,d,f,m,h,b,y,S,x)}roundClean(){vr(ri,ni)}destroy(){vr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class KO extends JO{Ah=Ft[0]|0;Al=Ft[1]|0;Bh=Ft[2]|0;Bl=Ft[3]|0;Ch=Ft[4]|0;Cl=Ft[5]|0;Dh=Ft[6]|0;Dl=Ft[7]|0;Eh=Ft[8]|0;El=Ft[9]|0;Fh=Ft[10]|0;Fl=Ft[11]|0;Gh=Ft[12]|0;Gl=Ft[13]|0;Hh=Ft[14]|0;Hl=Ft[15]|0;constructor(){super(48)}}var fp=va(()=>new MO,Go(1));var HO=va(()=>new KO,Go(2));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var W8=BigInt(1),VO=BigInt(2),G8=BigInt(3),Q8=BigInt(5),Fhe=BigInt(8),WO=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function Y8(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=WO,a=e*e%i*e%i,c=Fr(a,VO,i)*a%i,u=Fr(c,W8,i)*e%i,d=Fr(u,Q8,i)*u%i,f=Fr(d,t,i)*d%i,m=Fr(f,r,i)*f%i,h=Fr(m,o,i)*m%i,b=Fr(h,n,i)*h%i,y=Fr(b,n,i)*h%i,S=Fr(y,t,i)*d%i;return{pow_p_5_8:Fr(S,VO,i)*e%i,b2:a}}function X8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var GO=(()=>{let e=WO;return _O({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=Y8(t);return lr(Fr(r,G8,e)*o,e)},adjustScalarBytes:X8})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var eJ=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),tJ=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))();var rJ=Lb(eJ),Ub=Bb(rJ,fp);var nJ=Lb(tJ),QO=Bb(nJ,HO);function XO(e,t,r){if(Mr(e),r===void 0)r=new Uint8Array(e.outputLen);return Ea(e,r,t)}var qb=Uint8Array.of(0),YO=Uint8Array.of();function e1(e,t,r,o=32){Mr(e),Dt(o,"length");let n=e.outputLen;if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=YO;else Te(r,void 0,"info");let s=new Uint8Array(i*n),a=Ea.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)qb[0]=d+1,c.update(d===0?YO:u).update(r).update(qb).digestInto(u),s.set(u,n*d),a._cloneInto(c);return a.destroy(),c.destroy(),vr(u,qb),s.slice(0,o)}var oJ=BigInt(0),Vl=BigInt(1),iJ=BigInt(2),sJ=BigInt(7),aJ=BigInt(256),cJ=BigInt(113),n1=[],o1=[],i1=[];for(let e=0,t=Vl,r=1,o=0;e<24;e++){[r,o]=[o,(2*r+3*o)%5],n1.push(2*(5*o+r)),o1.push((e+1)*(e+2)/2%64);let n=oJ;for(let i=0;i<7;i++)if(t=(t<<Vl^(t>>sJ)*cJ)%aJ,t&iJ)n^=Vl<<(Vl<<BigInt(i))-Vl;i1.push(n)}var s1=dp(i1,!0),lJ=s1[0],uJ=s1[1],t1=(e,t,r)=>r>32?zO(e,t,r):CO(e,t,r),r1=(e,t,r)=>r>32?NO(e,t,r):PO(e,t,r);function dJ(e,t=24){let r=new Uint32Array(10);for(let o=24-t;o<24;o++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,u=r[c],d=r[c+1],f=t1(u,d,1)^r[a],m=r1(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=f,e[s+h+1]^=m}let n=e[2],i=e[3];for(let s=0;s<24;s++){let a=o1[s],c=t1(n,i,a),u=r1(n,i,a),d=n1[s];n=e[d],i=e[d+1],e[d]=c,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=lJ[o],e[1]^=uJ[o]}vr(r)}class pp{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=n,Dt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=tp(this.state)}clone(){return this._cloneInto()}keccak(){wb(this.state32),dJ(this.state32,this.rounds),wb(this.state32),this.posOut=0,this.pos=0}update(e){co(this),Te(e);let{blockLen:t,state:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(t-this.pos,o-n);for(let s=0;s<i;s++)r[this.pos++]^=e[n++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:o}=this;if(e[r]^=t,(t&128)!==0&&r===o-1)this.keccak();e[o-1]^=128,this.keccak()}writeInto(e){co(this,!1),Te(e),this.finish();let t=this.state,{blockLen:r}=this;for(let o=0,n=e.length;o<n;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,n-o);e.set(t.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Dt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ep(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,vr(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:o,rounds:n,enableXOF:i}=this;return e||=new pp(t,r,o,i,n),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}var a1=(e,t,r,o={})=>va(()=>new pp(t,e,r),o);var fs=a1(6,136,32,Go(8));var c1=a1(6,72,64,Go(10));var l1=(e,t,r,o={})=>va((n={})=>new pp(t,e,n.dkLen===void 0?r:n.dkLen,!0),o),u1=l1(31,168,16,Go(11)),Cn=l1(31,136,32,Go(12));function Mb(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function f1(e){return Mb(e),(e&e-1)===0&&e!==0}function Fb(e,t){Mb(e);let r=0;for(let o=0;o<t;o++,e>>>=1)r=r<<1|e&1;return r}function p1(e){return Mb(e),31-Math.clz32(e)}function d1(e){let t=e.length;if(t<2||!f1(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=p1(t);for(let o=0;o<t;o++){let n=Fb(o,r);if(o<n){let i=e[o];e[o]=e[n],e[n]=i}}return e}var Jb=(e,t)=>{let{N:r,roots:o,dit:n,invertButterflies:i=!1,skipStages:s=0,brp:a=!0}=t,c=p1(r);if(!f1(r))throw Error("FFT: Polynomial size should be power of two");let u=n!==i;return(d)=>{if(d.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)d1(d);for(let f=0,m=1;f<c-s;f++){let h=n?f+1+s:c-f,b=1<<h,y=b>>1,S=r>>h;for(let x=0;x<r;x+=b)for(let _=0,A=m++;_<y;_++){let O=i?n?r-A:A:_*S,L=x+_,z=x+_+y,K=o[O],P=d[z],W=d[L];if(u){let ee=e.mul(P,K);d[L]=e.add(W,ee),d[z]=e.sub(W,ee)}else if(i)d[L]=e.add(P,W),d[z]=e.mul(e.sub(P,W),K);else d[L]=e.add(W,P),d[z]=e.mul(e.sub(W,P),K)}}if(!n&&a)d1(d);return d}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var Pn=Wo;function mp(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function m1(e){return Uint8Array.from(e)}function ps(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,o=t.reduce((n,i)=>n+r(i),0);return{bytesLen:o,encode:(n)=>{let i=new Uint8Array(o);for(let s=0,a=0;s<t.length;s++){let c=t[s],u=r(c),d=typeof c==="number"?n[s]:c.encode(n[s]);if(Te(d,u,e),i.set(d,a),typeof c!=="number")d.fill(0);a+=u}return i},decode:(n)=>{Te(n,o,e);let i=[];for(let s of t){let a=r(s),c=n.subarray(0,a);i.push(typeof s==="number"?c:s.decode(c)),n=n.subarray(a)}return i}}}function hp(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(o)=>{if(o.length!==t)throw Error(`vecCoder.encode: wrong length=${o.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let i=0,s=0;i<o.length;i++){let a=e.encode(o[i]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(o)=>{Te(o,r);let n=[];for(let i=0;i<o.length;i+=e.bytesLen)n.push(e.decode(o.subarray(i,i+e.bytesLen)));return n}}}function Rt(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function Kb(e){return(1<<e)-1}var ige=Uint8Array.of();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var h1=(e)=>{let{newPoly:t,N:r,Q:o,F:n,ROOT_OF_UNITY:i,brvBits:s,isKyber:a}=e,c=(_,A=o)=>{let O=_%A|0;return(O>=0?O|0:A+O|0)|0},u=(_,A=o)=>{let O=c(_,A)|0;return(O>A>>1?O-A|0:O)|0};function d(){let _=t(r);for(let A=0;A<r;A++){let O=Fb(A,s),L=BigInt(i)**BigInt(O)%BigInt(o);_[A]=Number(L)|0}return _}let f=d(),m={add:(_,A)=>c((_|0)+(A|0))|0,sub:(_,A)=>c((_|0)-(A|0))|0,mul:(_,A)=>c((_|0)*(A|0))|0,inv:(_)=>{throw Error("not implemented")}},h={N:r,roots:f,invertButterflies:!0,skipStages:a?1:0,brp:!1},b=Jb(m,{dit:!1,...h}),y=Jb(m,{dit:!0,...h});return{mod:c,smod:u,nttZetas:f,NTT:{encode:(_)=>b(_),decode:(_)=>{y(_);for(let A=0;A<_.length;A++)_[A]=c(n*_[A]);return _}},bitsCoder:(_,A)=>{let O=Kb(_),L=_*(r/8);return{bytesLen:L,encode:(z)=>{let K=new Uint8Array(L);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=(A.encode(z[P])&O)<<ee,ee+=_;for(;ee>=8;ee-=8,W>>=8)K[j++]=W&Kb(ee)}return K},decode:(z)=>{let K=t(r);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=z[P]<<ee,ee+=8;for(;ee>=_;ee-=_,W>>=_)K[j++]=A.decode(W&O)}return K}}}}},fJ=(e)=>(t,r)=>{if(!r)r=e.blockLen;let o=new Uint8Array(t.length+2);o.set(t);let n=t.length,i=new Uint8Array(r),s=e.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(u,d)=>(o[n+0]=u,o[n+1]=d,s.destroy(),s=e.create({}).update(o),a++,()=>(c++,s.xofInto(i))),clean:()=>{s.destroy(),Rt(i,o)}}},g1=fJ(u1);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var er=256,fo=3329,pJ=3303,mJ=17,{mod:Ql,nttZetas:hJ,NTT:ms,bitsCoder:gJ}=h1({N:er,Q:fo,F:pJ,ROOT_OF_UNITY:mJ,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0}),Hb={512:{N:er,Q:fo,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:er,Q:fo,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:er,Q:fo,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}},yJ=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+fo/2)/fo,decode:(r)=>r*fo+t>>>e}},Wl=(e)=>gJ(e,yJ(e));function hs(e,t){for(let r=0;r<er;r++)e[r]=Ql(e[r]+t[r])}function bJ(e,t){for(let r=0;r<er;r++)e[r]=Ql(e[r]-t[r])}function SJ(e,t,r,o,n){let i=Ql(t*o*n+e*r),s=Ql(e*o+t*r);return{c0:i,c1:s}}function gp(e,t){for(let r=0;r<er/2;r++){let o=hJ[64+(r>>1)];if(r&1)o=-o;let{c0:n,c1:i}=SJ(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],o);e[2*r+0]=n,e[2*r+1]=i}return e}function y1(e){let t=new Uint16Array(er);for(let r=0;r<er;){let o=e();if(o.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<er&&n+3<=o.length;n+=3){let i=(o[n+0]>>0|o[n+1]<<8)&4095,s=(o[n+1]>>4|o[n+2]<<4)&4095;if(i<fo)t[r++]=i;if(r<er&&s<fo)t[r++]=s}}return t}function Gl(e,t,r,o){let n=e(o*er/4,t,r),i=new Uint16Array(er),s=tp(n),a=0;for(let c=0,u=0,d=0,f=0;c<s.length;c++){let m=s[c];for(let h=0;h<32;h++)if(d+=m&1,m>>=1,a+=1,a===o)f=d,d=0;else if(a===2*o)i[u++]=Ql(f-d),d=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return i}var vJ=(e)=>{let{K:t,PRF:r,XOF:o,HASH512:n,ETA1:i,ETA2:s,du:a,dv:c}=e,u=Wl(1),d=Wl(c),f=Wl(a),m=ps("publicKey",hp(Wl(12),t),32),h=hp(Wl(12),t),b=ps("ciphertext",hp(f,t),d),y=ps("seed",32,32);return{secretCoder:h,lengths:{secretKey:h.bytesLen,publicKey:m.bytesLen,cipherText:b.bytesLen},keygen:(S)=>{Te(S,32,"seed");let x=new Uint8Array(33);x.set(S),x[32]=t;let _=n(x),[A,O]=y.decode(_),L=[],z=[];for(let W=0;W<t;W++)L.push(ms.encode(Gl(r,O,W,i)));let K=o(A);for(let W=0;W<t;W++){let ee=ms.encode(Gl(r,O,t+W,i));for(let j=0;j<t;j++){let R=y1(K.get(j,W));hs(ee,gp(R,L[j]))}z.push(ee)}K.clean();let P={publicKey:m.encode([z,A]),secretKey:h.encode(L)};return Rt(A,O,L,z,x,_),P},encrypt:(S,x,_)=>{let[A,O]=m.decode(S),L=[];for(let j=0;j<t;j++)L.push(ms.encode(Gl(r,_,j,i)));let z=o(O),K=new Uint16Array(er),P=[];for(let j=0;j<t;j++){let R=Gl(r,_,t+j,s),B=new Uint16Array(er);for(let I=0;I<t;I++){let T=y1(z.get(j,I));hs(B,gp(T,L[I]))}hs(R,ms.decode(B)),P.push(R),hs(K,gp(A[j],L[j])),Rt(B)}z.clean();let W=Gl(r,_,2*t,s);hs(W,ms.decode(K));let ee=u.decode(x);return hs(ee,W),Rt(A,L,K,W),b.encode([P,ee])},decrypt:(S,x)=>{let[_,A]=b.decode(S),O=h.decode(x),L=new Uint16Array(er);for(let z=0;z<t;z++)hs(L,gp(O[z],ms.encode(_[z])));return bJ(A,ms.decode(L)),Rt(L,O,_),u.encode(A)}}};function Vb(e){let t=vJ(e),{HASH256:r,HASH512:o,KDF:n}=e,{secretCoder:i,lengths:s}=t,a=ps("secretKey",s.secretKey,s.publicKey,32,32),c=32,u=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(d=Pn(64))=>{Te(d,64,"seed");let{publicKey:f,secretKey:m}=t.keygen(d.subarray(0,32)),h=r(f),b=a.encode([m,f,h,d.subarray(32)]);return Rt(m,h),{publicKey:f,secretKey:b}},getPublicKey:(d)=>{let[f,m,h,b]=a.decode(d);return Uint8Array.from(m)},encapsulate:(d,f=Pn(32))=>{Te(d,s.publicKey,"publicKey"),Te(f,32,"message");let m=d.subarray(0,384*e.K),h=i.encode(i.decode(m1(m)));if(!mp(h,m))throw Rt(h),Error("ML-KEM.encapsulate: wrong publicKey modulus");Rt(h);let b=o.create().update(f).update(r(d)).digest(),y=t.encrypt(d,f,b.subarray(32,64));return Rt(b.subarray(32)),{cipherText:y,sharedSecret:b.subarray(0,32)}},decapsulate:(d,f)=>{Te(f,a.bytesLen,"secretKey"),Te(d,s.cipherText,"cipherText");let m=a.bytesLen-96,h=m+32,b=r(f.subarray(m/2,h));if(!mp(b,f.subarray(h,h+32)))throw Error("invalid secretKey: hash check failed");let[y,S,x,_]=a.decode(f),A=t.decrypt(d,y),O=o.create().update(A).update(x).digest(),L=O.subarray(0,32),z=t.encrypt(S,A,O.subarray(32,64)),K=mp(d,z),P=n.create({dkLen:32}).update(_).update(d).digest();return Rt(A,z,!K?L:P),K?L:P}}}function wJ(e,t,r){return Cn.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var Wb={HASH256:fs,HASH512:c1,KDF:Cn,XOF:g1,PRF:wJ},gge=Vb({...Wb,...Hb[512]}),Yl=Vb({...Wb,...Hb[768]}),b1=Vb({...Wb,...Hb[1024]});/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */function xJ(e,t=!1){let{lengths:r,keygen:o}=e;if(t){let i=e.Point.Fn;if(!i)throw Error("No Point.Fn");o=(s=Pn(r.seed))=>{Te(s,r.seed,"seed");let a=i.isLE?Yo(s):Qo(s),c=i.toBytes(i.create(a));return{secretKey:c,publicKey:e.getPublicKey(c)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:o,getPublicKey:(n)=>e.getPublicKey(n)}}function Gb(e,t=!1){let r=xJ(e,t);if(!e.getSharedSecret)throw Error("wrong curve");return{lengths:{...r.lengths,msg:r.lengths.seed,cipherText:r.lengths.publicKey},keygen:r.keygen,getPublicKey:r.getPublicKey,encapsulate(o,n=Pn(e.lengths.seed)){let i=this.keygen(n).secretKey,s=this.decapsulate(o,i),a=e.getPublicKey(i);return Rt(i),{sharedSecret:s,cipherText:a}},decapsulate(o,n){let i=e.getSharedSecret(n,o);return e.lengths.publicKeyHasPrefix?i.subarray(1):i}}}function Xl(e,t){return ps(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function Qb(e){return(t,r)=>e(t,{dkLen:r})}function _J(e,t,...r){let o=Xl(r,"seed"),n=Xl(r,"publicKey");if(e===void 0)e=o.bytesLen;Dt(e);function i(s){Te(s,e);let a=o.decode(t(s,o.bytesLen)),c=r.map((f,m)=>f.keygen(a[m])),u=c.map((f)=>f.secretKey),d=c.map((f)=>f.publicKey);return{secretKey:u,publicKey:d}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Pn(e)){let{publicKey:a,secretKey:c}=i(s),u=n.encode(a);return Rt(a),Rt(c),{secretKey:s,publicKey:u}},expandDecapsulationKey:i,realSeedLen:e}}function yp(e,t,r,o,...n){let i=_J(e,r,...n),s=Xl(n,"cipherText"),a=Xl(n,"publicKey"),c=Xl(n,"msg");if(t===void 0)t=c.bytesLen;return Dt(t),{lengths:{...i.info.lengths,msg:t,msgRand:c.bytesLen,cipherText:s.bytesLen},getPublicKey:i.getPublicKey,keygen:i.keygen,encapsulate(u,d=Pn(c.bytesLen)){let f=a.decode(u),m=c.decode(d),h=n.map((x,_)=>x.encapsulate(f[_],m[_])),b=h.map((x)=>x.sharedSecret),y=h.map((x)=>x.cipherText),S={sharedSecret:o(f,y,b),cipherText:s.encode(y)};return Rt(b,y),S},decapsulate(u,d){let f=s.decode(u),{publicKey:m,secretKey:h}=i.expandDecapsulationKey(d),b=n.map((y,S)=>y.decapsulate(f[S],h[S]));return o(m,f,b)}}}function S1(e,t,r,o,n){return Mr(o),Mr(n),yp(32,32,Qb(o),(i,s,a)=>n(Et(a[0],a[1],s[1],i[1],Xo(e))),t,r)}var Age=S1("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",Yl,Gb(Ub,!0),Cn,fs),Tge=S1("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",b1,Gb(QO,!0),Cn,fs);function EJ(e,t,r,o,n){return Mr(o),Mr(n),yp(32,32,Qb(o),(i,s,a)=>{let c=Et(a[0],a[1],s[0],i[0],s[1],i[1],Xo(e)),u=32,d=Et(Xo("hybrid_prk"),c),f=XO(n,d),m=Et(wa(32,2),Xo("shared_secret"),Xo("")),h=e1(n,f,m,32);return Rt(f,m,d,c),h},t,r)}var v1=Gb(GO),$ge=EJ("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",Yl,v1,Cn,fp),IJ=(()=>yp(32,32,Qb(Cn),(e,t,r)=>fs(Et(r[0],r[1],t[1],e[1],Xo("\\.//^\\"))),Yl,v1))();function kJ(e,t,r,o){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function i(s){let a;for(let d=0,f=t;;d=f,f+=t){if(f>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(d,f),!0),n.isValidNot0(a))break}let c=n.toBytes(n.create(a)),u=e.getPublicKey(c,!1);return{secretKey:c,publicKey:u}}return{lengths:{secretKey:t,publicKey:r,seed:o,msg:o,cipherText:r},keygen(s=Pn(o)){return Te(s,o,"seed"),i(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Pn(o)){Te(a,o,"rand");let{secretKey:c}=i(a),u=this.decapsulate(s,c),d=e.getPublicKey(c,!1);return Rt(c),{sharedSecret:u,cipherText:d}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function AJ(e,t,r,o){let{secretKey:n,publicKeyUncompressed:i}=r.lengths;if(!n||!i)throw Error("wrong curve");let s=kJ(r,n,i,o),a=64,c=a+o;return yp(32,32,(u)=>{Te(u,32);let d=Cn(u,{dkLen:c}),f=d.subarray(0,a),m=d.subarray(a,c);return Et(f,m)},(u,d,f)=>fs(Et(f[0],f[1],d[1],u[1],Xo(e))),t,s)}var TJ=(()=>AJ("MLKEM768-P256",Yl,Ub,128))();var bp=IJ,w1=TJ;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ye=(e,t,r)=>Ut(e,t,r),Xb=St,ka=qf,Jt=(...e)=>rb(...e),Aa=(e)=>Rl(e),Ta=Xy,$a=(e)=>oo(e),vp=BigInt(0),Yb=BigInt(1);function po(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function wp(e){if(typeof e==="bigint"){if(!Sp(e))throw RangeError("positive bigint expected, got "+e)}else Xb(e);return e}function zn(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function eu(e){let t=wp(e).toString(16);return t.length&1?"0"+t:t}function x1(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?vp:BigInt("0x"+e)}function gs(e){return x1(qf(e))}function sn(e){return x1(qf(oi(Ut(e)).reverse()))}function xp(e,t){if(St(t),t===0)throw RangeError("zero length");e=wp(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return Rl(r.padStart(t*2,"0"))}function tu(e,t){return xp(e,t).reverse()}function _1(e,t){if(e=Ye(e),t=Ye(t),e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function oi(e){return Uint8Array.from(Ye(e))}function _p(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}var Sp=(e)=>typeof e==="bigint"&&vp<=e;function $J(e,t,r){return Sp(e)&&Sp(t)&&Sp(r)&&t<=e&&e<r}function mo(e,t,r,o){if(!$J(t,r,o))throw RangeError("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Ra(e){if(e<vp)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>vp;e>>=Yb,t+=1);return t}var ru=(e)=>(Yb<<BigInt(e))-Yb;function E1(e,t,r){if(St(e,"hashLen"),St(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=o(e),u=o(e),d=0,f=()=>{c.fill(1),u.fill(0),d=0},m=(...S)=>r(u,Jt(c,...S)),h=(S=n)=>{if(u=m(i,S),c=m(),S.length===0)return;u=m(s,S),c=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){c=m();let _=c.slice();x.push(_),S+=c.length}return Jt(...x)};return(S,x)=>{f(),h(S);let _=void 0;while((_=x(b()))===void 0)h();return f(),_}}function Jr(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw TypeError(`param "${i}" is invalid: expected own property`);let c=e[i];if(a&&c===void 0)return;let u=typeof c;if(u!==s||c===null)throw TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,c])=>o(a,c,s));n(t,!1),n(r,!0)}var eS=()=>{throw Error("not implemented")};/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Kt=BigInt(0),mt=BigInt(1),ys=BigInt(2),T1=BigInt(3),$1=BigInt(4),R1=BigInt(5),RJ=BigInt(7),O1=BigInt(8),OJ=BigInt(9),C1=BigInt(16);function it(e,t){if(t<=Kt)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Kt?r:t+r}function Kr(e,t,r){if(t<Kt)throw Error("pow2: expected non-negative exponent, got "+t);let o=e;while(t-- >Kt)o*=o,o%=r;return o}function I1(e,t){if(e===Kt)throw Error("invert: expected non-zero number");if(t<=Kt)throw Error("invert: expected positive modulus, got "+t);let r=it(e,t),o=t,n=Kt,i=mt,s=mt,a=Kt;while(r!==Kt){let u=o/r,d=o-r*u,f=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=f,a=m}if(o!==mt)throw Error("invert: does not exist");return it(n,t)}function tS(e,t,r){let o=e;if(!o.eql(o.sqr(t),r))throw Error("Cannot find square root")}function P1(e,t){let r=e,o=(r.ORDER+mt)/$1,n=r.pow(t,o);return tS(r,n,t),n}function CJ(e,t){let r=e,o=(r.ORDER-R1)/O1,n=r.mul(t,ys),i=r.pow(n,o),s=r.mul(t,i),a=r.mul(r.mul(s,ys),i),c=r.mul(s,r.sub(a,r.ONE));return tS(r,c,t),c}function PJ(e){let t=Ep(e),r=z1(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+RJ)/C1;return(a,c)=>{let u=a,d=u.pow(c,s),f=u.mul(d,o),m=u.mul(d,n),h=u.mul(d,i),b=u.eql(u.sqr(f),c),y=u.eql(u.sqr(m),c);d=u.cmov(d,f,b),f=u.cmov(h,m,y);let S=u.eql(u.sqr(f),c),x=u.cmov(d,f,S);return tS(u,x,c),x}}function z1(e){if(e<T1)throw Error("sqrt is not defined for small field");let t=e-mt,r=0;while(t%ys===Kt)t/=ys,r++;let o=ys,n=Ep(e);while(k1(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return P1;let i=n.pow(o,t),s=(t+mt)/ys;return function(c,u){let d=c;if(d.is0(u))return u;if(k1(d,u)!==1)throw Error("Cannot find square root");let f=r,m=d.mul(d.ONE,i),h=d.pow(u,t),b=d.pow(u,s);while(!d.eql(h,d.ONE)){if(d.is0(h))return d.ZERO;let y=1,S=d.sqr(h);while(!d.eql(S,d.ONE))if(y++,S=d.sqr(S),y===f)throw Error("Cannot find square root");let x=mt<<BigInt(f-y-1),_=d.pow(m,x);f=y,m=d.sqr(_),h=d.mul(h,m),b=d.mul(b,_)}return b}}function zJ(e){if(e%$1===T1)return P1;if(e%O1===R1)return CJ;if(e%C1===OJ)return PJ(e);return z1(e)}var ho=(e,t)=>(it(e,t)&mt)===mt,NJ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=NJ.reduce((o,n)=>(o[n]="function",o),t);if(Jr(e,r),zn(e.BYTES,"BYTES"),zn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=mt)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function DJ(e,t,r){let o=e;if(r<Kt)throw Error("invalid exponent, negatives unsupported");if(r===Kt)return o.ONE;if(r===mt)return t;let n=o.ONE,i=t;while(r>Kt){if(r&mt)n=o.mul(n,i);i=o.sqr(i),r>>=mt}return n}function nu(e,t,r=!1){let o=e,n=Array(t.length).fill(r?o.ZERO:void 0),i=t.reduce((a,c,u)=>{if(o.is0(c))return a;return n[u]=a,o.mul(a,c)},o.ONE),s=o.inv(i);return t.reduceRight((a,c,u)=>{if(o.is0(c))return a;return n[u]=o.mul(a,n[u]),o.mul(a,c)},s),n}function k1(e,t){let r=e,o=(r.ORDER-mt)/ys,n=r.pow(t,o),i=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function LJ(e,t){if(t!==void 0)Xb(t);if(e<=Kt)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=Ra(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let o=t!==void 0?t:r,n=Math.ceil(o/8);return{nBitLength:o,nByteLength:n}}var A1=new WeakMap;class nS{ORDER;BITS;BYTES;isLE;ZERO=Kt;ONE=mt;_lengths;_mod;constructor(e,t={}){if(e<=mt)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=LJ(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,Object.freeze(this)}create(e){return it(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Kt<=e&&e<this.ORDER}is0(e){return e===Kt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&mt)===mt}neg(e){return it(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return it(e*e,this.ORDER)}add(e,t){return it(e+t,this.ORDER)}sub(e,t){return it(e-t,this.ORDER)}mul(e,t){return it(e*t,this.ORDER)}pow(e,t){return DJ(this,e,t)}div(e,t){return it(e*I1(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return I1(e,this.ORDER)}sqrt(e){let t=A1.get(this);if(!t)A1.set(this,t=zJ(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?tu(e,this.BYTES):xp(e,this.BYTES)}fromBytes(e,t=!1){Ye(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(o);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?sn(e):gs(e);if(s)a=it(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return nu(this,e)}cmov(e,t,r){return po(r,"condition"),r?t:e}}Object.freeze(nS.prototype);function Ep(e,t={}){return new nS(e,t)}function N1(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=mt)throw Error("field order must be greater than 1");let t=Ra(e-mt);return Math.ceil(t/8)}function oS(e){let t=N1(e);return t+Math.ceil(t/2)}function D1(e,t,r=!1){Ye(e);let o=e.length,n=N1(t),i=Math.max(oS(t),16);if(o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?sn(e):gs(e),a=it(s,t-mt)+mt;return r?tu(a,n):xp(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Oa=BigInt(0),bs=BigInt(1);function ou(e,t){let r=t.negate();return e?r:t}function Ss(e,t){let r=nu(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function Z1(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function iS(e,t){Z1(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=ru(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function L1(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>o)a-=i,c+=bs;let u=t*o,d=u+Math.abs(a)-1,f=a===0,m=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:m,isNegF:h,offsetF:u}}var sS=new WeakMap,U1=new WeakMap;function aS(e){return U1.get(e)||1}function B1(e){if(e!==Oa)throw Error("invalid wNAF")}class iu{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>Oa){if(t&bs)r=r.add(o);o=o.double(),t>>=bs}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=iS(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let c=1;c<o;c++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=iS(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:c,isZero:u,isNeg:d,isNegF:f,offsetF:m}=L1(r,s,i);if(r=a,u)n=n.add(ou(f,t[m]));else o=o.add(ou(d,t[c]))}return B1(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=iS(e,this.bits);for(let i=0;i<n.windows;i++){if(r===Oa)break;let{nextN:s,offset:a,isZero:c,isNeg:u}=L1(r,i,n);if(r=s,c)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return B1(r),o}getPrecomputes(e,t,r){let o=sS.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);sS.set(t,o)}}return o}cached(e,t,r){let o=aS(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=aS(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){Z1(t,this.bits),U1.set(e,t),sS.delete(e)}hasCache(e){return aS(e)!==1}}function q1(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>Oa||o>Oa){if(r&bs)i=i.add(n);if(o&bs)s=s.add(n);n=n.double(),r>>=bs,o>>=bs}return{p1:i,p2:s}}function j1(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return rS(t),t}else return Ep(e,{isLE:r})}function Ip(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u==="bigint"&&u>Oa))throw Error(`CURVE.${c} must be positive bigint`)}let n=j1(t.p,r.Fp,o),i=j1(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function su(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}function au(e,t){if(zn(e),zn(t),t<0||t>4)throw Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let o=t-1;o>=0;o--)r[o]=e&255,e>>>=8;return new Uint8Array(r)}function BJ(e,t){let r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e[o]^t[o];return r}function jJ(e){if(!Ta(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?_p(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function cS(e,t,r,o){if(Ye(e),zn(r),t=jJ(t),t.length>255)t=o(Jt(_p("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:i}=o,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=Jt(t,au(t.length,1)),c=new Uint8Array(i),u=au(r,2),d=Array(s),f=o(Jt(c,e,u,au(0,1),a));d[0]=o(Jt(f,au(1,1),a));for(let h=1;h<s;h++){let b=[BJ(f,d[h-1]),au(h+1,1),a];d[h]=o(Jt(...b))}return Jt(...d).slice(0,r)}var M1="HashToScalar-";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var F1=(e,t)=>(e+(e>=0?t:-t)/K1)/t;function ZJ(e,t,r){mo("scalar",e,Nn,r);let[[o,n],[i,s]]=t,a=F1(s*e,r),c=F1(-n*e,r),u=e-a*o-c*i,d=-a*n-c*s,f=u<Nn,m=d<Nn;if(f)u=-u;if(m)d=-d;let h=ru(Math.ceil(Ra(r)/2))+ii;if(u<Nn||u>=h||d<Nn||d>=h)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:m,k2:d}}function uS(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function lS(e,t){Jr(e);let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(po(r.lowS,"lowS"),po(r.prehash,"prehash"),r.format!==void 0)uS(r.format);return r}class J1 extends Error{constructor(e=""){super(e)}}var an={Err:J1,_tlv:{encode:(e,t)=>{let{Err:r}=an;if(zn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!=="string")throw TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=eu(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?eu(n.length/2|128):"";return eu(e)+i+n+t},decode(e,t){let{Err:r}=an;t=Ye(t,void 0,"DER data");let o=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=an;if(wp(e),e<Nn)throw new t("integer: negative integers are not allowed");let r=eu(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=an;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return gs(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=an,n=Ye(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=o.decode(2,i),{v:u,l:d}=o.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=an,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};Object.freeze(an._tlv);Object.freeze(an._int);Object.freeze(an);var Nn=BigInt(0),ii=BigInt(1),K1=BigInt(2),kp=BigInt(3),UJ=BigInt(4);function H1(e,t={}){let r=Ip("weierstrass",e,t),o=r.Fp,n=r.Fn,i=r.CURVE,{h:s,n:a}=i;Jr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=t;if(c){if(!o.is0(i.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let d=W1(o,n);function f(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function m(j,R,B){if(u&&R.is0())return Uint8Array.of(0);let{x:I,y:T}=R.toAffine(),k=o.toBytes(I);if(po(B,"isCompressed"),B){f();let M=!o.isOdd(T);return Jt(V1(M),k)}else return Jt(Uint8Array.of(4),k,o.toBytes(T))}function h(j){Ye(j,void 0,"Point");let{publicKey:R,publicKeyUncompressed:B}=d,I=j.length,T=j[0],k=j.subarray(1);if(u&&I===1&&T===0)return{x:o.ZERO,y:o.ZERO};if(I===R&&(T===2||T===3)){let M=o.fromBytes(k);if(!o.isValid(M))throw Error("bad point: is not on curve, wrong x");let N=S(M),H;try{H=o.sqrt(N)}catch(ae){let pe=ae instanceof Error?": "+ae.message:"";throw Error("bad point: is not on curve, sqrt error"+pe)}f();let G=o.isOdd(H);if((T&1)===1!==G)H=o.neg(H);return{x:M,y:H}}else if(I===B&&T===4){let M=o.BYTES,N=o.fromBytes(k.subarray(0,M)),H=o.fromBytes(k.subarray(M,M*2));if(!x(N,H))throw Error("bad point: is not on curve");return{x:N,y:H}}else throw Error(`bad point: got length ${I}, expected compressed=${R} or uncompressed=${B}`)}let b=t.toBytes===void 0?m:t.toBytes,y=t.fromBytes===void 0?h:t.fromBytes;function S(j){let R=o.sqr(j),B=o.mul(R,j);return o.add(o.add(B,o.mul(j,i.a)),i.b)}function x(j,R){let B=o.sqr(R),I=S(j);return o.eql(B,I)}if(!x(i.Gx,i.Gy))throw Error("bad curve params: generator point");let _=o.mul(o.pow(i.a,kp),UJ),A=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(_,A)))throw Error("bad curve params: a or b");function O(j,R,B=!1){if(!o.isValid(R)||B&&o.is0(R))throw Error(`bad point coordinate ${j}`);return R}function L(j){if(!(j instanceof P))throw Error("Weierstrass Point expected")}function z(j){if(!c||!c.basises)throw Error("no endo");return ZJ(j,c.basises,n.ORDER)}function K(j,R,B,I,T){return B=new P(o.mul(B.X,j),B.Y,B.Z),R=ou(I,R),B=ou(T,B),R.add(B)}class P{static BASE=new P(i.Gx,i.Gy,o.ONE);static ZERO=new P(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(j,R,B){this.X=O("x",j),this.Y=O("y",R,!0),this.Z=O("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(j){let{x:R,y:B}=j||{};if(!j||!o.isValid(R)||!o.isValid(B))throw Error("invalid affine point");if(j instanceof P)throw Error("projective point not allowed");if(o.is0(R)&&o.is0(B))return P.ZERO;return new P(R,B,o.ONE)}static fromBytes(j){let R=P.fromAffine(y(Ye(j,void 0,"point")));return R.assertValidity(),R}static fromHex(j){return P.fromBytes(Aa(j))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,R=!0){if(ee.createCache(this,j),!R)this.multiply(kp);return this}assertValidity(){let j=this;if(j.is0()){if(t.allowInfinityPoint&&o.is0(j.X)&&o.eql(j.Y,o.ONE)&&o.is0(j.Z))return;throw Error("bad point: ZERO")}let{x:R,y:B}=j.toAffine();if(!o.isValid(R)||!o.isValid(B))throw Error("bad point: x or y not field elements");if(!x(R,B))throw Error("bad point: equation left != right");if(!j.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:j}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(j)}equals(j){L(j);let{X:R,Y:B,Z:I}=this,{X:T,Y:k,Z:M}=j,N=o.eql(o.mul(R,M),o.mul(T,I)),H=o.eql(o.mul(B,M),o.mul(k,I));return N&&H}negate(){return new P(this.X,o.neg(this.Y),this.Z)}double(){let{a:j,b:R}=i,B=o.mul(R,kp),{X:I,Y:T,Z:k}=this,M=o.ZERO,N=o.ZERO,H=o.ZERO,G=o.mul(I,I),re=o.mul(T,T),ae=o.mul(k,k),pe=o.mul(I,T);return pe=o.add(pe,pe),H=o.mul(I,k),H=o.add(H,H),M=o.mul(j,H),N=o.mul(B,ae),N=o.add(M,N),M=o.sub(re,N),N=o.add(re,N),N=o.mul(M,N),M=o.mul(pe,M),H=o.mul(B,H),ae=o.mul(j,ae),pe=o.sub(G,ae),pe=o.mul(j,pe),pe=o.add(pe,H),H=o.add(G,G),G=o.add(H,G),G=o.add(G,ae),G=o.mul(G,pe),N=o.add(N,G),ae=o.mul(T,k),ae=o.add(ae,ae),G=o.mul(ae,pe),M=o.sub(M,G),H=o.mul(ae,re),H=o.add(H,H),H=o.add(H,H),new P(M,N,H)}add(j){L(j);let{X:R,Y:B,Z:I}=this,{X:T,Y:k,Z:M}=j,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=i.a,ae=o.mul(i.b,kp),pe=o.mul(R,T),be=o.mul(B,k),ve=o.mul(I,M),ke=o.add(R,B),Ie=o.add(T,k);ke=o.mul(ke,Ie),Ie=o.add(pe,be),ke=o.sub(ke,Ie),Ie=o.add(R,I);let we=o.add(T,M);return Ie=o.mul(Ie,we),we=o.add(pe,ve),Ie=o.sub(Ie,we),we=o.add(B,I),N=o.add(k,M),we=o.mul(we,N),N=o.add(be,ve),we=o.sub(we,N),G=o.mul(re,Ie),N=o.mul(ae,ve),G=o.add(N,G),N=o.sub(be,G),G=o.add(be,G),H=o.mul(N,G),be=o.add(pe,pe),be=o.add(be,pe),ve=o.mul(re,ve),Ie=o.mul(ae,Ie),be=o.add(be,ve),ve=o.sub(pe,ve),ve=o.mul(re,ve),Ie=o.add(Ie,ve),pe=o.mul(be,Ie),H=o.add(H,pe),pe=o.mul(we,Ie),N=o.mul(ke,N),N=o.sub(N,pe),pe=o.mul(ke,be),G=o.mul(we,G),G=o.add(G,pe),new P(N,H,G)}subtract(j){return L(j),this.add(j.negate())}is0(){return this.equals(P.ZERO)}multiply(j){let{endo:R}=t;if(!n.isValidNot0(j))throw RangeError("invalid scalar: out of range");let B,I,T=(k)=>ee.cached(this,k,(M)=>Ss(P,M));if(R){let{k1neg:k,k1:M,k2neg:N,k2:H}=z(j),{p:G,f:re}=T(M),{p:ae,f:pe}=T(H);I=re.add(pe),B=K(R.beta,G,ae,k,N)}else{let{p:k,f:M}=T(j);B=k,I=M}return Ss(P,[B,I])[0]}multiplyUnsafe(j){let{endo:R}=t,B=this,I=j;if(!n.isValid(I))throw RangeError("invalid scalar: out of range");if(I===Nn||B.is0())return P.ZERO;if(I===ii)return B;if(ee.hasCache(this))return this.multiply(I);if(R){let{k1neg:T,k1:k,k2neg:M,k2:N}=z(I),{p1:H,p2:G}=q1(P,B,k,N);return K(R.beta,H,G,T,M)}else return ee.unsafe(B,I)}toAffine(j){let R=this,B=j,{X:I,Y:T,Z:k}=R;if(o.eql(k,o.ONE))return{x:I,y:T};let M=R.is0();if(B==null)B=M?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(T,B),G=o.mul(k,B);if(M)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){let{isTorsionFree:j}=t;if(s===ii)return!0;if(j)return j(P,this);return ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:j}=t;if(s===ii)return this;if(j)return j(P,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===ii)return this.is0();return this.clearCofactor().is0()}toBytes(j=!0){return po(j,"isCompressed"),this.assertValidity(),b(P,this,j)}toHex(j=!0){return ka(this.toBytes(j))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=n.BITS,ee=new iu(P,t.endo?Math.ceil(W/2):W);if(W>=8)P.BASE.precompute(8);return Object.freeze(P.prototype),Object.freeze(P),P}function V1(e){return Uint8Array.of(e?2:3)}function W1(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function qJ(e,t={}){let{Fn:r}=e,o=t.randomBytes===void 0?$a:t.randomBytes,n=Object.assign(W1(e.Fp,r),{seed:Math.max(oS(r.ORDER),16)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h){return h=h===void 0?o(n.seed):h,D1(Ye(h,n.seed,"seed"),r.ORDER)}function c(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n,x=r._lengths;if(!Ta(h))return;let _=Ye(h,void 0,"key").length,A=_===y||_===S,O=_===b||!!x?.includes(_);if(A&&O)return;return A}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let f={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=su(a,c);return Object.freeze(f),Object.freeze(n),Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:e,utils:f,lengths:n})}function G1(e,t,r={}){let o=t;no(o),Jr(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?$a:r.randomBytes,i=r.hmac===void 0?(T,k)=>Tn(o,T,k):r.hmac,{Fp:s,Fn:a}=e,{ORDER:c,BITS:u}=a,{keygen:d,getPublicKey:f,getSharedSecret:m,utils:h,lengths:b}=qJ(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},S=c*K1+ii<s.ORDER;function x(T){let k=c>>ii;return T>k}function _(T,k){if(!a.isValidNot0(k))throw Error(`invalid signature ${T}: out of range 1..Point.Fn.ORDER`);return k}function A(){if(S)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(T,k){uS(k);let M=b.signature,N=k==="compact"?M:k==="recovered"?M+1:void 0;return Ye(T,N)}class L{r;s;recovery;constructor(T,k,M){if(this.r=_("r",T),this.s=_("s",k),M!=null){if(A(),![0,1,2,3].includes(M))throw Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(T,k=y.format){O(T,k);let M;if(k==="der"){let{r:re,s:ae}=an.toSig(Ye(T));return new L(re,ae)}if(k==="recovered")M=T[0],k="compact",T=T.subarray(1);let N=b.signature/2,H=T.subarray(0,N),G=T.subarray(N,N*2);return new L(a.fromBytes(H),a.fromBytes(G),M)}static fromHex(T,k){return this.fromBytes(Aa(T),k)}assertRecovery(){let{recovery:T}=this;if(T==null)throw Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new L(this.r,this.s,T)}recoverPublicKey(T){let{r:k,s:M}=this,N=this.assertRecovery(),H=N===2||N===3?k+c:k;if(!s.isValid(H))throw Error("invalid recovery id: sig.r+curve.n != R.x");let G=s.toBytes(H),re=e.fromBytes(Jt(V1((N&1)===0),G)),ae=a.inv(H),pe=K(Ye(T,void 0,"msgHash")),be=a.create(-pe*ae),ve=a.create(M*ae),ke=e.BASE.multiplyUnsafe(be).add(re.multiplyUnsafe(ve));if(ke.is0())throw Error("invalid recovery: point at infinify");return ke.assertValidity(),ke}hasHighS(){return x(this.s)}toBytes(T=y.format){if(uS(T),T==="der")return Aa(an.hexFromSig(this));let{r:k,s:M}=this,N=a.toBytes(k),H=a.toBytes(M);if(T==="recovered")return A(),Jt(Uint8Array.of(this.assertRecovery()),N,H);return Jt(N,H)}toHex(T){return ka(this.toBytes(T))}}Object.freeze(L.prototype),Object.freeze(L);let z=r.bits2int===void 0?function(k){if(k.length>8192)throw Error("input is too large");let M=gs(k),N=k.length*8-u;return N>0?M>>BigInt(N):M}:r.bits2int,K=r.bits2int_modN===void 0?function(k){return a.create(z(k))}:r.bits2int_modN,P=ru(u);function W(T){return mo("num < 2^"+u,T,Nn,P),a.toBytes(T)}function ee(T,k){return Ye(T,void 0,"message"),k?Ye(o(T),void 0,"prehashed message"):T}function j(T,k,M){let{lowS:N,prehash:H,extraEntropy:G}=lS(M,y);T=ee(T,H);let re=K(T),ae=a.fromBytes(k);if(!a.isValidNot0(ae))throw Error("invalid private key");let pe=[W(ae),W(re)];if(G!=null&&G!==!1){let Ie=G===!0?n(b.secretKey):G;pe.push(Ye(Ie,void 0,"extraEntropy"))}let be=Jt(...pe),ve=re;function ke(Ie){let we=z(Ie);if(!a.isValidNot0(we))return;let Ue=a.inv(we),De=e.BASE.multiply(we).toAffine(),Qe=a.create(De.x);if(Qe===Nn)return;let bt=a.create(Ue*a.create(ve+Qe*ae));if(bt===Nn)return;let Tt=(De.x===Qe?0:2)|Number(De.y&ii),Nt=bt;if(N&&x(bt))Nt=a.neg(bt),Tt^=1;return new L(Qe,Nt,S?void 0:Tt)}return{seed:be,k2sig:ke}}function R(T,k,M={}){let{seed:N,k2sig:H}=j(T,k,M);return E1(o.outputLen,a.BYTES,i)(N,H).toBytes(M.format)}function B(T,k,M,N={}){let{lowS:H,prehash:G,format:re}=lS(N,y);if(M=Ye(M,void 0,"publicKey"),k=ee(k,G),!Ta(T)){let ae=T instanceof L?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ae)}O(T,re);try{let ae=L.fromBytes(T,re),pe=e.fromBytes(M);if(H&&ae.hasHighS())return!1;let{r:be,s:ve}=ae,ke=K(k),Ie=a.inv(ve),we=a.create(ke*Ie),Ue=a.create(be*Ie),De=e.BASE.multiplyUnsafe(we).add(pe.multiplyUnsafe(Ue));if(De.is0())return!1;return a.create(De.x)===be}catch(ae){return!1}}function I(T,k,M={}){let{prehash:N}=lS(M,y);return k=ee(k,N),L.fromBytes(T,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:d,getPublicKey:f,getSharedSecret:m,utils:h,lengths:b,Point:e,sign:R,verify:B,recoverPublicKey:I,Signature:L,hash:o})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var MJ=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))();var FJ=H1(MJ),Ca=G1(FJ,vt);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var si=BigInt(0),wr=BigInt(1),dS=BigInt(2),JJ=BigInt(8);function KJ(e,t,r,o){let n=e.sqr(r),i=e.sqr(o),s=e.add(e.mul(t.a,n),i),a=e.add(e.ONE,e.mul(t.d,e.mul(n,i)));return e.eql(s,a)}function Q1(e,t={}){let r=t,o=Ip("edwards",e,r,r.FpFnLE),{Fp:n,Fn:i}=o,s=o.CURVE,{h:a}=s;Jr(r,{},{uvRatio:"function"});let c=dS<<BigInt(i.BYTES*8)-wr,u=(y)=>n.create(y),d=r.uvRatio===void 0?(y,S)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,S))}}catch(x){return{isValid:!1,value:si}}}:r.uvRatio;if(!KJ(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function f(y,S,x=!1){let _=x?wr:si;return mo("coordinate "+y,S,_,c),S}function m(y){if(!(y instanceof h))throw Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,wr,u(s.Gx*s.Gy));static ZERO=new h(si,wr,wr,si);static Fp=n;static Fn=i;X;Y;Z;T;constructor(y,S,x,_){this.X=f("x",y),this.Y=f("y",S),this.Z=f("z",x,!0),this.T=f("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw Error("extended point not allowed");let{x:S,y:x}=y||{};return f("x",S),f("y",x),new h(S,x,wr,u(S*x))}static fromBytes(y,S=!1){let x=n.BYTES,{a:_,d:A}=s;y=oi(Ye(y,x,"point")),po(S,"zip215");let O=oi(y),L=y[x-1];O[x-1]=L&-129;let z=sn(O),K=S?c:n.ORDER;mo("point.y",z,si,K);let P=u(z*z),W=u(P-wr),ee=u(A*P-_),{isValid:j,value:R}=d(W,ee);if(!j)throw Error("bad point: invalid y coordinate");let B=(R&wr)===wr,I=(L&128)!==0;if(!S&&R===si&&I)throw Error("bad point: x=0 and x_0=1");if(I!==B)R=u(-R);return h.fromAffine({x:R,y:z})}static fromHex(y,S=!1){return h.fromBytes(Aa(y),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,S=!0){if(b.createCache(this,y),!S)this.multiply(dS);return this}assertValidity(){let y=this,{a:S,d:x}=s;if(y.is0())throw Error("bad point: ZERO");let{X:_,Y:A,Z:O,T:L}=y,z=u(_*_),K=u(A*A),P=u(O*O),W=u(P*P),ee=u(z*S),j=u(P*u(ee+K)),R=u(W+u(x*u(z*K)));if(j!==R)throw Error("bad point: equation left != right (1)");let B=u(_*A),I=u(O*L);if(B!==I)throw Error("bad point: equation left != right (2)")}equals(y){m(y);let{X:S,Y:x,Z:_}=this,{X:A,Y:O,Z:L}=y,z=u(S*L),K=u(A*_),P=u(x*L),W=u(O*_);return z===K&&P===W}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:y}=s,{X:S,Y:x,Z:_}=this,A=u(S*S),O=u(x*x),L=u(dS*u(_*_)),z=u(y*A),K=S+x,P=u(u(K*K)-A-O),W=z+O,ee=W-L,j=z-O,R=u(P*ee),B=u(W*j),I=u(P*j),T=u(ee*W);return new h(R,B,T,I)}add(y){m(y);let{a:S,d:x}=s,{X:_,Y:A,Z:O,T:L}=this,{X:z,Y:K,Z:P,T:W}=y,ee=u(_*z),j=u(A*K),R=u(L*x*W),B=u(O*P),I=u((_+A)*(z+K)-ee-j),T=B-R,k=B+R,M=u(j-S*ee),N=u(I*T),H=u(k*M),G=u(I*M),re=u(T*k);return new h(N,H,re,G)}subtract(y){return m(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:x}=b.cached(this,y,(_)=>Ss(h,_));return Ss(h,[S,x])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(y===si)return h.ZERO;if(this.is0()||y===wr)return this;return b.unsafe(this,y,(S)=>Ss(h,S))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(y){let S=this,x=y,{X:_,Y:A,Z:O}=S,L=S.is0();if(x==null)x=L?JJ:n.inv(O);let z=u(_*x),K=u(A*x),P=n.mul(O,x);if(L)return{x:si,y:wr};if(P!==wr)throw Error("invZ was invalid");return{x:z,y:K}}clearCofactor(){if(a===wr)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:y,y:S}=this.toAffine(),x=n.toBytes(S);return x[x.length-1]|=y&wr?128:0,x}toHex(){return ka(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new iu(h,i.BITS);if(i.BITS>=8)h.BASE.precompute(8);return Object.freeze(h.prototype),Object.freeze(h),h}class fS{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){eS()}static fromHex(e){eS()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return ka(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var cu=BigInt(0),Pa=BigInt(1),Ap=BigInt(2);function HJ(e){return Jr(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function Y1(e){let t=HJ(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let c=s===void 0?$a:s,u=a?255:448,d=a?32:56,f=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?Ap**BigInt(254):Ap**BigInt(447),b=a?BigInt(8)*Ap**BigInt(251)-Pa:BigInt(4)*Ap**BigInt(445)-Pa,y=h+b+Pa,S=(I)=>it(I,r),x=_(f);function _(I){return tu(S(I),d)}function A(I){let T=oi(Ye(I,d,"uCoordinate"));if(a)T[31]&=127;return S(sn(T))}function O(I){return sn(n(oi(Ye(I,d,"scalar"))))}function L(I,T){let k=ee(A(T),O(I));if(k===cu)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,T,k){let M=S(I*(T-k));return T=S(T-M),k=S(k+M),{x_2:T,x_3:k}}function ee(I,T){mo("u",I,cu,r),mo("scalar",T,h,y);let k=T,M=I,N=Pa,H=cu,G=I,re=Pa,ae=cu;for(let be=BigInt(u-1);be>=cu;be--){let ve=k>>be&Pa;ae^=ve,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=ve;let ke=N+H,Ie=S(ke*ke),we=N-H,Ue=S(we*we),De=Ie-Ue,Qe=G+re,bt=G-re,Tt=S(bt*ke),Nt=S(Qe*we),lt=Tt+Nt,$r=Tt-Nt;G=S(lt*lt),re=S(M*S($r*$r)),N=S(Ie*Ue),H=S(De*(Ie+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let pe=i(H);return S(N*pe)}let j={secretKey:d,publicKey:d,seed:d},R=(I)=>(I=I===void 0?c(d):I,Ye(I,j.seed,"seed"),I),B={randomSecretKey:R};return Object.freeze(j),Object.freeze(B),Object.freeze({keygen:su(R,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var VJ=BigInt(0),go=BigInt(1),X1=BigInt(2),WJ=BigInt(3),GJ=BigInt(5),QJ=BigInt(8),ws=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gS=(()=>({p:ws,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:QJ,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function rC(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=ws,a=e*e%i*e%i,c=Kr(a,X1,i)*a%i,u=Kr(c,go,i)*e%i,d=Kr(u,GJ,i)*u%i,f=Kr(d,t,i)*d%i,m=Kr(f,r,i)*f%i,h=Kr(m,o,i)*m%i,b=Kr(h,n,i)*h%i,y=Kr(b,n,i)*h%i,S=Kr(y,t,i)*d%i;return{pow_p_5_8:Kr(S,X1,i)*e%i,b2:a}}function YJ(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var pS=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function yS(e,t){let r=ws,o=it(t*t*t,r),n=it(o*o*t,r),i=rC(e*n).pow_p_5_8,s=it(e*o*i,r),a=it(t*s*s,r),c=s,u=it(s*pS,r),d=a===e,f=a===it(-e,r),m=a===it(-e*pS,r);if(d)s=c;if(f||m)s=u;if(ho(s,r))s=it(-s,r);return{isValid:d||f,value:s}}var vs=Q1(gS,{uvRatio:yS}),ai=(()=>vs.Fp)(),nC=(()=>vs.Fn)();var Tp=(()=>{let e=ws;return Y1({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=rC(t);return it(Kr(r,WJ,e)*o,e)},adjustScalarBytes:YJ})})();var mS=pS,XJ=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),eK=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),tK=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rK=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),eC=(e)=>yS(go,e),nK=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),hS=(e)=>ai.create(sn(e)&nK);function tC(e){let{d:t}=gS,r=ws,o=(x)=>ai.create(x),n=o(mS*e*e),i=o((n+go)*tK),s=BigInt(-1),a=o((s-t*n)*o(n+t)),{isValid:c,value:u}=yS(i,a),d=o(u*e);if(!ho(d,r))d=o(-d);if(!c)u=d;if(!c)s=n;let f=o(s*(n-go)*rK-a),m=u*u,h=o((u+u)*a),b=o(f*XJ),y=o(go-m),S=o(go+m);return new vs(o(h*S),o(y*b),o(b*S),o(h*y))}class dr extends fS{static BASE=(()=>new dr(vs.BASE))();static ZERO=(()=>new dr(vs.ZERO))();static Fp=(()=>ai)();static Fn=(()=>nC)();constructor(e){super(e)}static fromAffine(e){return new dr(vs.fromAffine(e))}assertSame(e){if(!(e instanceof dr))throw Error("RistrettoPoint expected")}init(e){return new dr(e)}static fromBytes(e){Ut(e,32);let{a:t,d:r}=gS,o=ws,n=(A)=>ai.create(A),i=hS(e);if(!_1(ai.toBytes(i),e)||ho(i,o))throw Error("invalid ristretto255 encoding 1");let s=n(i*i),a=n(go+t*s),c=n(go-t*s),u=n(a*a),d=n(c*c),f=n(t*r*u-d),{isValid:m,value:h}=eC(n(f*d)),b=n(h*c),y=n(h*b*f),S=n((i+i)*b);if(ho(S,o))S=n(-S);let x=n(a*y),_=n(S*x);if(!m||ho(_,o)||x===VJ)throw Error("invalid ristretto255 encoding 2");return new dr(new vs(S,x,go,_))}static fromHex(e){return dr.fromBytes(Rl(e))}toBytes(){let{X:e,Y:t,Z:r,T:o}=this.ep,n=ws,i=(y)=>ai.create(y),s=i(i(r+t)*i(r-t)),a=i(e*t),c=i(a*a),{value:u}=eC(i(s*c)),d=i(u*s),f=i(u*a),m=i(d*f*o),h;if(ho(o*m,n)){let y=i(t*mS),S=i(e*mS);e=y,t=S,h=i(d*eK)}else h=f;if(ho(e*m,n))t=i(-t);let b=i((r-t)*h);if(ho(b,n))b=i(-b);return ai.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:o,Y:n}=e.ep,i=(c)=>ai.create(c),s=i(t*n)===i(r*o),a=i(r*n)===i(t*o);return s||a}is0(){return this.equals(dr.ZERO)}}Object.freeze(dr.BASE);Object.freeze(dr.ZERO);Object.freeze(dr.prototype);Object.freeze(dr);var oK=Object.freeze({Point:dr,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,o=cS(e,r,64,Kf);return oK.deriveToCurve(o)},hashToScalar(e,t={DST:M1}){let r=cS(e,t.DST,64,Kf);return nC.create(sn(r))},deriveToCurve(e){Ut(e,64);let t=hS(e.subarray(0,32)),r=tC(t),o=hS(e.subarray(32,64)),n=tC(o);return new dr(r.add(n))}});var oC=!1,iK=!1;async function iC(e,t){if(iK)return await t();try{return await e()}catch(r){if(r instanceof ReferenceError||r instanceof DOMException&&r.name==="NotSupportedError")return await t();else throw r}}async function $p(e,t){return await iC(async()=>{let r=bS(e)?e:await aK(e),o=await crypto.subtle.importKey("raw",cK(t),{name:"X25519"},oC,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:o},r,256))},()=>{if(bS(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return Tp.scalarMult(e,t)})}async function lu(e){return await iC(async()=>$p(e,Tp.GuBytes),()=>{if(bS(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return Tp.scalarMultBase(e)})}var sK=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function aK(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...sK,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},oC,["deriveBits"])}function bS(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function cK(e){return e}class SS{s;transcript=[];buf=new Uint8Array(0);constructor(e){this.s=e.getReader()}async readLine(){let e=[];while(!0){let t=this.buf.indexOf(10);if(t>=0)return e.push(this.buf.subarray(0,t)),this.transcript.push(this.buf.subarray(0,t+1)),this.buf=this.buf.subarray(t+1),uK(xs(e));if(this.buf.length>0)e.push(this.buf),this.transcript.push(this.buf);let r=await this.s.read();if(r.done)return this.buf=xs(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:xs(this.transcript)}}}function uK(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function xs(e){let t=e.reduce((n,i)=>n+i.length,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function za(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let o of t)r.enqueue(o)}}))}function Rp(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function vS(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function sC(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function aC(e,t){let r=e.getReader(),o=[],n=0;while(n<t){let{done:c,value:u}=await r.read();if(c)throw Error("stream ended before reading "+t.toString()+" bytes");o.push(u),n+=u.length}r.releaseLock();let i=xs(o),s=i.subarray(0,t),a=za(e,i.subarray(t));return{data:s,rest:a}}class Dn{args;body;constructor(e,t){this.args=e,this.body=t}}async function dK(e){let t=await e.readLine();if(t===null)throw Error("invalid stanza");let r=t.split(" ");if(r.length<2||r.shift()!=="->")return{next:t};for(let i of r)if(i.length===0)throw Error("invalid stanza");let o=[];for(;;){let i=await e.readLine();if(i===null)throw Error("invalid stanza");let s=Yt.decode(i);if(s.length>48)throw Error("invalid stanza");if(o.push(s),s.length<48)break}let n=xs(o);return{s:new Dn(r,n)}}async function cC(e){let t=new SS(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let o=[];for(;;){let{s:n,next:i}=await dK(t);if(n!==void 0){o.push(n);continue}if(!i.startsWith("--- "))throw Error("invalid header");let s=Yt.decode(i.slice(4)),{rest:a,transcript:c}=t.close(),u=c.slice(0,c.length-1-i.length+3);return{stanzas:o,headerNoMAC:u,MAC:s,headerSize:c.length,rest:za(e,a)}}}function wS(e){let t=[];t.push(`age-encryption.org/v1
|
|
702
702
|
`);for(let r of e){t.push("-> "+r.args.join(" ")+`
|
|
703
703
|
`);for(let o=0;o<r.body.length;o+=48){let n=o+48;if(n>r.body.length)n=r.body.length;t.push(Yt.encode(r.body.subarray(o,n))+`
|
|
704
704
|
`)}if(r.body.length%48===0)t.push(`
|